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, *about_window;
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;
101 static bool stretch_video;
102 static NSTextField *pauseLabel;
104 static QemuSemaphore display_init_sem;
105 static QemuSemaphore app_started_sem;
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;
312 - (void) switchSurface:(pixman_image_t *)image;
314 - (void) ungrabMouse;
315 - (void) toggleFullScreen:(id)sender;
316 - (void) handleMonitorInput:(NSEvent *)event;
317 - (bool) handleEvent:(NSEvent *)event;
318 - (bool) handleEventLocked:(NSEvent *)event;
319 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
320 /* The state surrounding mouse grabbing is potentially confusing.
321 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
322 * pointing device an absolute-position one?"], but is only updated on
324 * isMouseGrabbed tracks whether GUI events are directed to the guest;
325 * it controls whether special keys like Cmd get sent to the guest,
326 * and whether we capture the mouse when in non-absolute mode.
328 - (BOOL) isMouseGrabbed;
329 - (BOOL) isAbsoluteEnabled;
332 - (QEMUScreen) gscreen;
333 - (void) raiseAllKeys;
336 QemuCocoaView *cocoaView;
338 @implementation QemuCocoaView
339 - (id)initWithFrame:(NSRect)frameRect
341 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
343 self = [super initWithFrame:frameRect];
346 screen.width = frameRect.size.width;
347 screen.height = frameRect.size.height;
348 kbd = qkbd_state_init(dcl.con);
356 COCOA_DEBUG("QemuCocoaView: dealloc\n");
359 pixman_image_unref(pixman_image);
362 qkbd_state_free(kbd);
371 - (BOOL) screenContainsPoint:(NSPoint) p
373 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
376 /* Get location of event and convert to virtual screen coordinate */
377 - (CGPoint) screenLocationOfEvent:(NSEvent *)ev
379 NSWindow *eventWindow = [ev window];
380 // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
381 CGRect r = CGRectZero;
382 r.origin = [ev locationInWindow];
385 return [[self window] convertRectFromScreen:r].origin;
387 CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
388 CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
395 } else if ([[self window] isEqual:eventWindow]) {
399 CGPoint loc = [self convertPoint:r.origin fromView:nil];
407 return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
419 - (void) unhideCursor
427 - (void) drawRect:(NSRect) rect
429 COCOA_DEBUG("QemuCocoaView: drawRect\n");
431 // get CoreGraphic context
432 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
434 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
435 CGContextSetShouldAntialias (viewContextRef, NO);
437 // draw screen bitmap directly to Core Graphics context
439 // Draw request before any guest device has set up a framebuffer:
440 // just draw an opaque black rectangle
441 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
442 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
444 int w = pixman_image_get_width(pixman_image);
445 int h = pixman_image_get_height(pixman_image);
446 int bitsPerPixel = PIXMAN_FORMAT_BPP(pixman_image_get_format(pixman_image));
447 int stride = pixman_image_get_stride(pixman_image);
448 CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(
450 pixman_image_get_data(pixman_image),
454 CGImageRef imageRef = CGImageCreate(
457 DIV_ROUND_UP(bitsPerPixel, 8) * 2, //bitsPerComponent
458 bitsPerPixel, //bitsPerPixel
459 stride, //bytesPerRow
460 CGColorSpaceCreateWithName(kCGColorSpaceSRGB), //colorspace
461 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst, //bitmapInfo
462 dataProviderRef, //provider
465 kCGRenderingIntentDefault //intent
467 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
468 const NSRect *rectList;
471 CGImageRef clipImageRef;
474 [self getRectsBeingDrawn:&rectList count:&rectCount];
475 for (i = 0; i < rectCount; i++) {
476 clipRect.origin.x = rectList[i].origin.x / cdx;
477 clipRect.origin.y = (float)h - (rectList[i].origin.y + rectList[i].size.height) / cdy;
478 clipRect.size.width = rectList[i].size.width / cdx;
479 clipRect.size.height = rectList[i].size.height / cdy;
480 clipImageRef = CGImageCreateWithImageInRect(
484 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
485 CGImageRelease (clipImageRef);
487 CGImageRelease (imageRef);
488 CGDataProviderRelease(dataProviderRef);
492 - (void) setContentDimensions
494 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
497 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
498 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
500 /* stretches video, but keeps same aspect ratio */
501 if (stretch_video == true) {
502 /* use smallest stretch value - prevents clipping on sides */
503 if (MIN(cdx, cdy) == cdx) {
508 } else { /* No stretching */
511 cw = screen.width * cdx;
512 ch = screen.height * cdy;
513 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
514 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
525 - (void) updateUIInfoLocked
527 /* Must be called with the iothread lock, i.e. via updateUIInfo */
531 if (!qemu_console_is_graphic(dcl.con)) {
536 NSDictionary *description = [[[self window] screen] deviceDescription];
537 CGDirectDisplayID display = [[description objectForKey:@"NSScreenNumber"] unsignedIntValue];
538 NSSize screenSize = [[[self window] screen] frame].size;
539 CGSize screenPhysicalSize = CGDisplayScreenSize(display);
541 frameSize = isFullscreen ? screenSize : [self frame].size;
542 info.width_mm = frameSize.width / screenSize.width * screenPhysicalSize.width;
543 info.height_mm = frameSize.height / screenSize.height * screenPhysicalSize.height;
545 frameSize = [self frame].size;
552 info.width = frameSize.width;
553 info.height = frameSize.height;
555 dpy_set_ui_info(dcl.con, &info, TRUE);
558 - (void) updateUIInfo
562 * Don't try to tell QEMU about UI information in the application
563 * startup phase -- we haven't yet registered dcl with the QEMU UI
564 * layer, and also trying to take the iothread lock would deadlock.
565 * When cocoa_display_init() does register the dcl, the UI layer
566 * will call cocoa_switch(), which will call updateUIInfo, so
567 * we don't lose any information here.
572 with_iothread_lock(^{
573 [self updateUIInfoLocked];
577 - (void)viewDidMoveToWindow
582 - (void) switchSurface:(pixman_image_t *)image
584 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
586 int w = pixman_image_get_width(image);
587 int h = pixman_image_get_height(image);
588 /* cdx == 0 means this is our very first surface, in which case we need
589 * to recalculate the content dimensions even if it happens to be the size
590 * of the initial empty window.
592 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
594 int oldh = screen.height;
596 // Resize before we trigger the redraw, or we'll redraw at the wrong size
597 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
600 [self setContentDimensions];
601 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
604 // update screenBuffer
606 pixman_image_unref(pixman_image);
609 pixman_image = image;
613 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
614 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
617 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
618 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
622 [normalWindow center];
626 - (void) toggleFullScreen:(id)sender
628 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
630 if (isFullscreen) { // switch from fullscreen to desktop
631 isFullscreen = FALSE;
633 [self setContentDimensions];
634 [fullScreenWindow close];
635 [normalWindow setContentView: self];
636 [normalWindow makeKeyAndOrderFront: self];
637 [NSMenu setMenuBarVisible:YES];
638 } else { // switch from desktop to fullscreen
640 [normalWindow orderOut: nil]; /* Hide the window */
642 [self setContentDimensions];
643 [NSMenu setMenuBarVisible:NO];
644 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
645 styleMask:NSWindowStyleMaskBorderless
646 backing:NSBackingStoreBuffered
648 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
649 [fullScreenWindow setHasShadow:NO];
650 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
651 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
652 [[fullScreenWindow contentView] addSubview: self];
653 [fullScreenWindow makeKeyAndOrderFront:self];
657 - (void) toggleKey: (int)keycode {
658 qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode));
661 // Does the work of sending input to the monitor
662 - (void) handleMonitorInput:(NSEvent *)event
667 // if the control key is down
668 if ([event modifierFlags] & NSEventModifierFlagControl) {
672 /* translates Macintosh keycodes to QEMU's keysym */
674 int without_control_translation[] = {
675 [0 ... 0xff] = 0, // invalid key
677 [kVK_UpArrow] = QEMU_KEY_UP,
678 [kVK_DownArrow] = QEMU_KEY_DOWN,
679 [kVK_RightArrow] = QEMU_KEY_RIGHT,
680 [kVK_LeftArrow] = QEMU_KEY_LEFT,
681 [kVK_Home] = QEMU_KEY_HOME,
682 [kVK_End] = QEMU_KEY_END,
683 [kVK_PageUp] = QEMU_KEY_PAGEUP,
684 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
685 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
686 [kVK_Delete] = QEMU_KEY_BACKSPACE,
689 int with_control_translation[] = {
690 [0 ... 0xff] = 0, // invalid key
692 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
693 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
694 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
695 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
696 [kVK_Home] = QEMU_KEY_CTRL_HOME,
697 [kVK_End] = QEMU_KEY_CTRL_END,
698 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
699 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
702 if (control_key != 0) { /* If the control key is being used */
703 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
704 keysym = with_control_translation[[event keyCode]];
707 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
708 keysym = without_control_translation[[event keyCode]];
712 // if not a key that needs translating
714 NSString *ks = [event characters];
715 if ([ks length] > 0) {
716 keysym = [ks characterAtIndex:0];
721 kbd_put_keysym(keysym);
725 - (bool) handleEvent:(NSEvent *)event
729 * Just let OSX have all events that arrive before
730 * applicationDidFinishLaunching.
731 * This avoids a deadlock on the iothread lock, which cocoa_display_init()
732 * will not drop until after the app_started_sem is posted. (In theory
733 * there should not be any such events, but OSX Catalina now emits some.)
737 return bool_with_iothread_lock(^{
738 return [self handleEventLocked:event];
742 - (bool) handleEventLocked:(NSEvent *)event
744 /* Return true if we handled the event, false if it should be given to OSX */
745 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
748 bool mouse_event = false;
749 static bool switched_to_fullscreen = false;
750 // Location of event in virtual screen coordinates
751 NSPoint p = [self screenLocationOfEvent:event];
752 NSUInteger modifiers = [event modifierFlags];
755 * Check -[NSEvent modifierFlags] here.
757 * There is a NSEventType for an event notifying the change of
758 * -[NSEvent modifierFlags], NSEventTypeFlagsChanged but these operations
759 * are performed for any events because a modifier state may change while
760 * the application is inactive (i.e. no events fire) and we don't want to
761 * wait for another modifier state change to detect such a change.
763 * NSEventModifierFlagCapsLock requires a special treatment. The other flags
764 * are handled in similar manners.
766 * NSEventModifierFlagCapsLock
767 * ---------------------------
769 * If CapsLock state is changed, "up" and "down" events will be fired in
770 * sequence, effectively updates CapsLock state on the guest.
775 * If a flag is not set, fire "up" events for all keys which correspond to
776 * the flag. Note that "down" events are not fired here because the flags
777 * checked here do not tell what exact keys are down.
779 * If one of the keys corresponding to a flag is down, we rely on
780 * -[NSEvent keyCode] of an event whose -[NSEvent type] is
781 * NSEventTypeFlagsChanged to know the exact key which is down, which has
782 * the following two downsides:
783 * - It does not work when the application is inactive as described above.
784 * - It malfactions *after* the modifier state is changed while the
785 * application is inactive. It is because -[NSEvent keyCode] does not tell
786 * if the key is up or down, and requires to infer the current state from
787 * the previous state. It is still possible to fix such a malfanction by
788 * completely leaving your hands from the keyboard, which hopefully makes
789 * this implementation usable enough.
791 if (!!(modifiers & NSEventModifierFlagCapsLock) !=
792 qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) {
793 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true);
794 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false);
797 if (!(modifiers & NSEventModifierFlagShift)) {
798 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false);
799 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false);
801 if (!(modifiers & NSEventModifierFlagControl)) {
802 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false);
803 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false);
805 if (!(modifiers & NSEventModifierFlagOption)) {
806 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
807 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
809 if (!(modifiers & NSEventModifierFlagCommand)) {
810 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
811 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
814 switch ([event type]) {
815 case NSEventTypeFlagsChanged:
816 switch ([event keyCode]) {
818 if (!!(modifiers & NSEventModifierFlagShift)) {
819 [self toggleKey:Q_KEY_CODE_SHIFT];
824 if (!!(modifiers & NSEventModifierFlagShift)) {
825 [self toggleKey:Q_KEY_CODE_SHIFT_R];
830 if (!!(modifiers & NSEventModifierFlagControl)) {
831 [self toggleKey:Q_KEY_CODE_CTRL];
835 case kVK_RightControl:
836 if (!!(modifiers & NSEventModifierFlagControl)) {
837 [self toggleKey:Q_KEY_CODE_CTRL_R];
842 if (!!(modifiers & NSEventModifierFlagOption)) {
843 [self toggleKey:Q_KEY_CODE_ALT];
847 case kVK_RightOption:
848 if (!!(modifiers & NSEventModifierFlagOption)) {
849 [self toggleKey:Q_KEY_CODE_ALT_R];
853 /* Don't pass command key changes to guest unless mouse is grabbed */
855 if (isMouseGrabbed &&
856 !!(modifiers & NSEventModifierFlagCommand)) {
857 [self toggleKey:Q_KEY_CODE_META_L];
861 case kVK_RightCommand:
862 if (isMouseGrabbed &&
863 !!(modifiers & NSEventModifierFlagCommand)) {
864 [self toggleKey:Q_KEY_CODE_META_R];
869 case NSEventTypeKeyDown:
870 keycode = cocoa_keycode_to_qemu([event keyCode]);
872 // forward command key combos to the host UI unless the mouse is grabbed
873 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
875 * Prevent the command key from being stuck down in the guest
876 * when using Command-F to switch to full screen mode.
878 if (keycode == Q_KEY_CODE_F) {
879 switched_to_fullscreen = true;
886 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
887 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
888 NSString *keychar = [event charactersIgnoringModifiers];
889 if ([keychar length] == 1) {
890 char key = [keychar characterAtIndex:0];
893 // enable graphic console
895 console_select(key - '0' - 1); /* ascii math */
898 // release the mouse grab
906 if (qemu_console_is_graphic(NULL)) {
907 qkbd_state_key_event(kbd, keycode, true);
909 [self handleMonitorInput: event];
912 case NSEventTypeKeyUp:
913 keycode = cocoa_keycode_to_qemu([event keyCode]);
915 // don't pass the guest a spurious key-up if we treated this
916 // command-key combo as a host UI action
917 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
921 if (qemu_console_is_graphic(NULL)) {
922 qkbd_state_key_event(kbd, keycode, false);
925 case NSEventTypeMouseMoved:
926 if (isAbsoluteEnabled) {
927 // Cursor re-entered into a window might generate events bound to screen coordinates
928 // and `nil` window property, and in full screen mode, current window might not be
929 // key window, where event location alone should suffice.
930 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
931 if (isMouseGrabbed) {
935 if (!isMouseGrabbed) {
942 case NSEventTypeLeftMouseDown:
943 buttons |= MOUSE_EVENT_LBUTTON;
946 case NSEventTypeRightMouseDown:
947 buttons |= MOUSE_EVENT_RBUTTON;
950 case NSEventTypeOtherMouseDown:
951 buttons |= MOUSE_EVENT_MBUTTON;
954 case NSEventTypeLeftMouseDragged:
955 buttons |= MOUSE_EVENT_LBUTTON;
958 case NSEventTypeRightMouseDragged:
959 buttons |= MOUSE_EVENT_RBUTTON;
962 case NSEventTypeOtherMouseDragged:
963 buttons |= MOUSE_EVENT_MBUTTON;
966 case NSEventTypeLeftMouseUp:
968 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
970 * In fullscreen mode, the window of cocoaView may not be the
971 * key window, therefore the position relative to the virtual
972 * screen alone will be sufficient.
974 if(isFullscreen || [[self window] isKeyWindow]) {
979 case NSEventTypeRightMouseUp:
982 case NSEventTypeOtherMouseUp:
985 case NSEventTypeScrollWheel:
987 * Send wheel events to the guest regardless of window focus.
988 * This is in-line with standard Mac OS X UI behaviour.
992 * We shouldn't have got a scroll event when deltaY and delta Y
993 * are zero, hence no harm in dropping the event
995 if ([event deltaY] != 0 || [event deltaX] != 0) {
996 /* Determine if this is a scroll up or scroll down event */
997 if ([event deltaY] != 0) {
998 buttons = ([event deltaY] > 0) ?
999 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1000 } else if ([event deltaX] != 0) {
1001 buttons = ([event deltaX] > 0) ?
1002 INPUT_BUTTON_WHEEL_LEFT : INPUT_BUTTON_WHEEL_RIGHT;
1005 qemu_input_queue_btn(dcl.con, buttons, true);
1006 qemu_input_event_sync();
1007 qemu_input_queue_btn(dcl.con, buttons, false);
1008 qemu_input_event_sync();
1012 * Since deltaX/deltaY also report scroll wheel events we prevent mouse
1013 * movement code from executing.
1015 mouse_event = false;
1022 /* Don't send button events to the guest unless we've got a
1023 * mouse grab or window focus. If we have neither then this event
1024 * is the user clicking on the background window to activate and
1025 * bring us to the front, which will be done by the sendEvent
1026 * call below. We definitely don't want to pass that click through
1029 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
1030 (last_buttons != buttons)) {
1031 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1032 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1033 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1034 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
1036 qemu_input_update_buttons(dcl.con, bmap, last_buttons, buttons);
1037 last_buttons = buttons;
1039 if (isMouseGrabbed) {
1040 if (isAbsoluteEnabled) {
1041 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
1042 * The check on screenContainsPoint is to avoid sending out of range values for
1043 * clicks in the titlebar.
1045 if ([self screenContainsPoint:p]) {
1046 qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x, 0, screen.width);
1047 qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
1050 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, (int)[event deltaX]);
1051 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, (int)[event deltaY]);
1056 qemu_input_event_sync();
1063 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
1065 if (!isFullscreen) {
1067 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
1069 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
1072 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1073 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
1076 - (void) ungrabMouse
1078 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
1080 if (!isFullscreen) {
1082 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
1084 [normalWindow setTitle:@"QEMU"];
1086 [self unhideCursor];
1087 CGAssociateMouseAndMouseCursorPosition(TRUE);
1088 isMouseGrabbed = FALSE;
1091 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {
1092 isAbsoluteEnabled = tIsAbsoluteEnabled;
1093 if (isMouseGrabbed) {
1094 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1097 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
1098 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
1099 - (float) cdx {return cdx;}
1100 - (float) cdy {return cdy;}
1101 - (QEMUScreen) gscreen {return screen;}
1104 * Makes the target think all down keys are being released.
1105 * This prevents a stuck key problem, since we will not see
1106 * key up events for those keys after we have lost focus.
1108 - (void) raiseAllKeys
1110 with_iothread_lock(^{
1111 qkbd_state_lift_all_keys(kbd);
1119 ------------------------------------------------------
1120 QemuCocoaAppController
1121 ------------------------------------------------------
1123 @interface QemuCocoaAppController : NSObject
1124 <NSWindowDelegate, NSApplicationDelegate>
1127 - (void)doToggleFullScreen:(id)sender;
1128 - (void)toggleFullScreen:(id)sender;
1129 - (void)showQEMUDoc:(id)sender;
1130 - (void)zoomToFit:(id) sender;
1131 - (void)displayConsole:(id)sender;
1132 - (void)pauseQEMU:(id)sender;
1133 - (void)resumeQEMU:(id)sender;
1134 - (void)displayPause;
1135 - (void)removePause;
1136 - (void)restartQEMU:(id)sender;
1137 - (void)powerDownQEMU:(id)sender;
1138 - (void)ejectDeviceMedia:(id)sender;
1139 - (void)changeDeviceMedia:(id)sender;
1141 - (void)openDocumentation:(NSString *)filename;
1142 - (IBAction) do_about_menu_item: (id) sender;
1143 - (void)make_about_window;
1144 - (void)adjustSpeed:(id)sender;
1147 @implementation QemuCocoaAppController
1150 COCOA_DEBUG("QemuCocoaAppController: init\n");
1152 self = [super init];
1155 // create a view and add it to the window
1156 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1158 error_report("(cocoa) can't create a view");
1163 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
1164 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
1165 backing:NSBackingStoreBuffered defer:NO];
1167 error_report("(cocoa) can't create window");
1170 [normalWindow setAcceptsMouseMovedEvents:YES];
1171 [normalWindow setTitle:@"QEMU"];
1172 [normalWindow setContentView:cocoaView];
1173 [normalWindow makeKeyAndOrderFront:self];
1174 [normalWindow center];
1175 [normalWindow setDelegate: self];
1176 stretch_video = false;
1178 /* Used for displaying pause on the screen */
1179 pauseLabel = [NSTextField new];
1180 [pauseLabel setBezeled:YES];
1181 [pauseLabel setDrawsBackground:YES];
1182 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1183 [pauseLabel setEditable:NO];
1184 [pauseLabel setSelectable:NO];
1185 [pauseLabel setStringValue: @"Paused"];
1186 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1187 [pauseLabel setTextColor: [NSColor blackColor]];
1188 [pauseLabel sizeToFit];
1190 [self make_about_window];
1197 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1200 [cocoaView release];
1204 - (void)applicationDidFinishLaunching: (NSNotification *) note
1206 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1207 allow_events = true;
1208 /* Tell cocoa_display_init to proceed */
1209 qemu_sem_post(&app_started_sem);
1212 - (void)applicationWillTerminate:(NSNotification *)aNotification
1214 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1216 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1219 * Sleep here, because returning will cause OSX to kill us
1220 * immediately; the QEMU main loop will handle the shutdown
1221 * request and terminate the process.
1223 [NSThread sleepForTimeInterval:INFINITY];
1226 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1231 - (NSApplicationTerminateReply)applicationShouldTerminate:
1232 (NSApplication *)sender
1234 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1235 return [self verifyQuit];
1238 - (void)windowDidChangeScreen:(NSNotification *)notification
1240 [cocoaView updateUIInfo];
1243 - (void)windowDidResize:(NSNotification *)notification
1245 [cocoaView updateUIInfo];
1248 /* Called when the user clicks on a window's close button */
1249 - (BOOL)windowShouldClose:(id)sender
1251 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1252 [NSApp terminate: sender];
1253 /* If the user allows the application to quit then the call to
1254 * NSApp terminate will never return. If we get here then the user
1255 * cancelled the quit, so we should return NO to not permit the
1256 * closing of this window.
1261 /* Called when QEMU goes into the background */
1262 - (void) applicationWillResignActive: (NSNotification *)aNotification
1264 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1265 [cocoaView raiseAllKeys];
1268 /* We abstract the method called by the Enter Fullscreen menu item
1269 * because Mac OS 10.7 and higher disables it. This is because of the
1270 * menu item's old selector's name toggleFullScreen:
1272 - (void) doToggleFullScreen:(id)sender
1274 [self toggleFullScreen:(id)sender];
1277 - (void)toggleFullScreen:(id)sender
1279 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1281 [cocoaView toggleFullScreen:sender];
1284 /* Tries to find then open the specified filename */
1285 - (void) openDocumentation: (NSString *) filename
1287 /* Where to look for local files */
1288 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
1289 NSString *full_file_path;
1290 NSURL *full_file_url;
1292 /* iterate thru the possible paths until the file is found */
1294 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1295 full_file_path = [[NSBundle mainBundle] executablePath];
1296 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1297 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1298 path_array[index], filename];
1299 full_file_url = [NSURL fileURLWithPath: full_file_path
1300 isDirectory: false];
1301 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
1306 /* If none of the paths opened a file */
1308 QEMU_Alert(@"Failed to open file");
1311 - (void)showQEMUDoc:(id)sender
1313 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1315 [self openDocumentation: @"index.html"];
1318 /* Stretches video to fit host monitor size */
1319 - (void)zoomToFit:(id) sender
1321 stretch_video = !stretch_video;
1322 if (stretch_video == true) {
1323 [sender setState: NSControlStateValueOn];
1325 [sender setState: NSControlStateValueOff];
1329 /* Displays the console on the screen */
1330 - (void)displayConsole:(id)sender
1332 console_select([sender tag]);
1335 /* Pause the guest */
1336 - (void)pauseQEMU:(id)sender
1338 with_iothread_lock(^{
1341 [sender setEnabled: NO];
1342 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1343 [self displayPause];
1346 /* Resume running the guest operating system */
1347 - (void)resumeQEMU:(id) sender
1349 with_iothread_lock(^{
1352 [sender setEnabled: NO];
1353 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1357 /* Displays the word pause on the screen */
1358 - (void)displayPause
1360 /* Coordinates have to be calculated each time because the window can change its size */
1361 int xCoord, yCoord, width, height;
1362 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1363 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1364 width = [pauseLabel frame].size.width;
1365 height = [pauseLabel frame].size.height;
1366 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1367 [cocoaView addSubview: pauseLabel];
1370 /* Removes the word pause from the screen */
1373 [pauseLabel removeFromSuperview];
1377 - (void)restartQEMU:(id)sender
1379 with_iothread_lock(^{
1380 qmp_system_reset(NULL);
1384 /* Powers down QEMU */
1385 - (void)powerDownQEMU:(id)sender
1387 with_iothread_lock(^{
1388 qmp_system_powerdown(NULL);
1392 /* Ejects the media.
1393 * Uses sender's tag to figure out the device to eject.
1395 - (void)ejectDeviceMedia:(id)sender
1398 drive = [sender representedObject];
1401 QEMU_Alert(@"Failed to find drive to eject!");
1405 __block Error *err = NULL;
1406 with_iothread_lock(^{
1407 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1408 false, NULL, false, false, &err);
1410 handleAnyDeviceErrors(err);
1413 /* Displays a dialog box asking the user to select an image file to load.
1414 * Uses sender's represented object value to figure out which drive to use.
1416 - (void)changeDeviceMedia:(id)sender
1418 /* Find the drive name */
1420 drive = [sender representedObject];
1423 QEMU_Alert(@"Could not find drive!");
1427 /* Display the file open dialog */
1428 NSOpenPanel * openPanel;
1429 openPanel = [NSOpenPanel openPanel];
1430 [openPanel setCanChooseFiles: YES];
1431 [openPanel setAllowsMultipleSelection: NO];
1432 if([openPanel runModal] == NSModalResponseOK) {
1433 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1436 QEMU_Alert(@"Failed to convert URL to file path!");
1440 __block Error *err = NULL;
1441 with_iothread_lock(^{
1442 qmp_blockdev_change_medium(true,
1443 [drive cStringUsingEncoding:
1444 NSASCIIStringEncoding],
1446 [file cStringUsingEncoding:
1447 NSASCIIStringEncoding],
1452 handleAnyDeviceErrors(err);
1456 /* Verifies if the user really wants to quit */
1459 NSAlert *alert = [NSAlert new];
1460 [alert autorelease];
1461 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1462 [alert addButtonWithTitle: @"Cancel"];
1463 [alert addButtonWithTitle: @"Quit"];
1464 if([alert runModal] == NSAlertSecondButtonReturn) {
1471 /* The action method for the About menu item */
1472 - (IBAction) do_about_menu_item: (id) sender
1474 [about_window makeKeyAndOrderFront: nil];
1477 /* Create and display the about dialog */
1478 - (void)make_about_window
1480 /* Make the window */
1481 int x = 0, y = 0, about_width = 400, about_height = 200;
1482 NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1483 about_window = [[NSWindow alloc] initWithContentRect:window_rect
1484 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1485 NSWindowStyleMaskMiniaturizable
1486 backing:NSBackingStoreBuffered
1488 [about_window setTitle: @"About"];
1489 [about_window setReleasedWhenClosed: NO];
1490 [about_window center];
1491 NSView *superView = [about_window contentView];
1493 /* Create the dimensions of the picture */
1494 int picture_width = 80, picture_height = 80;
1495 x = (about_width - picture_width)/2;
1496 y = about_height - picture_height - 10;
1497 NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1499 /* Make the picture of QEMU */
1500 NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1502 char *qemu_image_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1503 NSString *qemu_image_path = [NSString stringWithUTF8String:qemu_image_path_c];
1504 g_free(qemu_image_path_c);
1505 NSImage *qemu_image = [[NSImage alloc] initWithContentsOfFile:qemu_image_path];
1506 [picture_view setImage: qemu_image];
1507 [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1508 [superView addSubview: picture_view];
1510 /* Make the name label */
1511 NSBundle *bundle = [NSBundle mainBundle];
1515 int name_width = about_width, name_height = 20;
1516 NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1517 NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1518 [name_label setEditable: NO];
1519 [name_label setBezeled: NO];
1520 [name_label setDrawsBackground: NO];
1521 [name_label setAlignment: NSTextAlignmentCenter];
1522 NSString *qemu_name = [[bundle executablePath] lastPathComponent];
1523 [name_label setStringValue: qemu_name];
1524 [superView addSubview: name_label];
1527 /* Set the version label's attributes */
1530 int version_width = about_width, version_height = 20;
1531 NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1532 NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1534 [version_label setEditable: NO];
1535 [version_label setBezeled: NO];
1536 [version_label setAlignment: NSTextAlignmentCenter];
1537 [version_label setDrawsBackground: NO];
1539 /* Create the version string*/
1540 NSString *version_string;
1541 version_string = [[NSString alloc] initWithFormat:
1542 @"QEMU emulator version %s", QEMU_FULL_VERSION];
1543 [version_label setStringValue: version_string];
1544 [superView addSubview: version_label];
1546 /* Make copyright label */
1549 int copyright_width = about_width, copyright_height = 20;
1550 NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1551 NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1553 [copyright_label setEditable: NO];
1554 [copyright_label setBezeled: NO];
1555 [copyright_label setDrawsBackground: NO];
1556 [copyright_label setAlignment: NSTextAlignmentCenter];
1557 [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1559 [superView addSubview: copyright_label];
1562 /* Used by the Speed menu items */
1563 - (void)adjustSpeed:(id)sender
1565 int throttle_pct; /* throttle percentage */
1568 menu = [sender menu];
1571 /* Unselect the currently selected item */
1572 for (NSMenuItem *item in [menu itemArray]) {
1573 if (item.state == NSControlStateValueOn) {
1574 [item setState: NSControlStateValueOff];
1580 // check the menu item
1581 [sender setState: NSControlStateValueOn];
1583 // get the throttle percentage
1584 throttle_pct = [sender tag];
1586 with_iothread_lock(^{
1587 cpu_throttle_set(throttle_pct);
1589 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1594 @interface QemuApplication : NSApplication
1597 @implementation QemuApplication
1598 - (void)sendEvent:(NSEvent *)event
1600 COCOA_DEBUG("QemuApplication: sendEvent\n");
1601 if (![cocoaView handleEvent:event]) {
1602 [super sendEvent: event];
1607 static void create_initial_menus(void)
1611 NSMenuItem *menuItem;
1613 [NSApp setMainMenu:[[NSMenu alloc] init]];
1614 [NSApp setServicesMenu:[[NSMenu alloc] initWithTitle:@"Services"]];
1617 menu = [[NSMenu alloc] initWithTitle:@""];
1618 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1619 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1620 menuItem = [menu addItemWithTitle:@"Services" action:nil keyEquivalent:@""];
1621 [menuItem setSubmenu:[NSApp servicesMenu]];
1622 [menu addItem:[NSMenuItem separatorItem]];
1623 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1624 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1625 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1626 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1627 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1628 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1629 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1630 [menuItem setSubmenu:menu];
1631 [[NSApp mainMenu] addItem:menuItem];
1632 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1635 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1636 [menu setAutoenablesItems: NO];
1637 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1638 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1639 [menu addItem: menuItem];
1640 [menuItem setEnabled: NO];
1641 [menu addItem: [NSMenuItem separatorItem]];
1642 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1643 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1644 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1645 [menuItem setSubmenu:menu];
1646 [[NSApp mainMenu] addItem:menuItem];
1649 menu = [[NSMenu alloc] initWithTitle:@"View"];
1650 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1651 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1652 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1653 [menuItem setSubmenu:menu];
1654 [[NSApp mainMenu] addItem:menuItem];
1657 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1659 // Add the rest of the Speed menu items
1660 int p, percentage, throttle_pct;
1661 for (p = 10; p >= 0; p--)
1663 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1665 menuItem = [[[NSMenuItem alloc]
1666 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1668 if (percentage == 100) {
1669 [menuItem setState: NSControlStateValueOn];
1672 /* Calculate the throttle percentage */
1673 throttle_pct = -1 * percentage + 100;
1675 [menuItem setTag: throttle_pct];
1676 [menu addItem: menuItem];
1678 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1679 [menuItem setSubmenu:menu];
1680 [[NSApp mainMenu] addItem:menuItem];
1683 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1684 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1685 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1686 [menuItem setSubmenu:menu];
1687 [[NSApp mainMenu] addItem:menuItem];
1688 [NSApp setWindowsMenu:menu];
1691 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1692 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1693 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1694 [menuItem setSubmenu:menu];
1695 [[NSApp mainMenu] addItem:menuItem];
1698 /* Returns a name for a given console */
1699 static NSString * getConsoleName(QemuConsole * console)
1701 g_autofree char *label = qemu_console_get_label(console);
1703 return [NSString stringWithUTF8String:label];
1706 /* Add an entry to the View menu for each console */
1707 static void add_console_menu_entries(void)
1710 NSMenuItem *menuItem;
1713 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1715 [menu addItem:[NSMenuItem separatorItem]];
1717 while (qemu_console_lookup_by_index(index) != NULL) {
1718 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1719 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1720 [menuItem setTag: index];
1721 [menu addItem: menuItem];
1726 /* Make menu items for all removable devices.
1727 * Each device is given an 'Eject' and 'Change' menu item.
1729 static void addRemovableDevicesMenuItems(void)
1732 NSMenuItem *menuItem;
1733 BlockInfoList *currentDevice, *pointerToFree;
1734 NSString *deviceName;
1736 currentDevice = qmp_query_block(NULL);
1737 pointerToFree = currentDevice;
1739 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1741 // Add a separator between related groups of menu items
1742 [menu addItem:[NSMenuItem separatorItem]];
1744 // Set the attributes to the "Removable Media" menu item
1745 NSString *titleString = @"Removable Media";
1746 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1747 NSColor *newColor = [NSColor blackColor];
1748 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1749 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1750 traits:NSBoldFontMask|NSItalicFontMask
1753 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1754 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1755 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1757 // Add the "Removable Media" menu item
1758 menuItem = [NSMenuItem new];
1759 [menuItem setAttributedTitle: attString];
1760 [menuItem setEnabled: NO];
1761 [menu addItem: menuItem];
1763 /* Loop through all the block devices in the emulator */
1764 while (currentDevice) {
1765 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1767 if(currentDevice->value->removable) {
1768 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1769 action: @selector(changeDeviceMedia:)
1770 keyEquivalent: @""];
1771 [menu addItem: menuItem];
1772 [menuItem setRepresentedObject: deviceName];
1773 [menuItem autorelease];
1775 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1776 action: @selector(ejectDeviceMedia:)
1777 keyEquivalent: @""];
1778 [menu addItem: menuItem];
1779 [menuItem setRepresentedObject: deviceName];
1780 [menuItem autorelease];
1782 currentDevice = currentDevice->next;
1784 qapi_free_BlockInfoList(pointerToFree);
1787 @interface QemuCocoaPasteboardTypeOwner : NSObject<NSPasteboardTypeOwner>
1790 @implementation QemuCocoaPasteboardTypeOwner
1792 - (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)type
1794 if (type != NSPasteboardTypeString) {
1798 with_iothread_lock(^{
1799 QemuClipboardInfo *info = qemu_clipboard_info_ref(cbinfo);
1800 qemu_event_reset(&cbevent);
1801 qemu_clipboard_request(info, QEMU_CLIPBOARD_TYPE_TEXT);
1803 while (info == cbinfo &&
1804 info->types[QEMU_CLIPBOARD_TYPE_TEXT].available &&
1805 info->types[QEMU_CLIPBOARD_TYPE_TEXT].data == NULL) {
1806 qemu_mutex_unlock_iothread();
1807 qemu_event_wait(&cbevent);
1808 qemu_mutex_lock_iothread();
1811 if (info == cbinfo) {
1812 NSData *data = [[NSData alloc] initWithBytes:info->types[QEMU_CLIPBOARD_TYPE_TEXT].data
1813 length:info->types[QEMU_CLIPBOARD_TYPE_TEXT].size];
1814 [sender setData:data forType:NSPasteboardTypeString];
1818 qemu_clipboard_info_unref(info);
1824 static QemuCocoaPasteboardTypeOwner *cbowner;
1826 static void cocoa_clipboard_notify(Notifier *notifier, void *data);
1827 static void cocoa_clipboard_request(QemuClipboardInfo *info,
1828 QemuClipboardType type);
1830 static QemuClipboardPeer cbpeer = {
1832 .notifier = { .notify = cocoa_clipboard_notify },
1833 .request = cocoa_clipboard_request
1836 static void cocoa_clipboard_update_info(QemuClipboardInfo *info)
1838 if (info->owner == &cbpeer || info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
1842 if (info != cbinfo) {
1843 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1844 qemu_clipboard_info_unref(cbinfo);
1845 cbinfo = qemu_clipboard_info_ref(info);
1846 cbchangecount = [[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:cbowner];
1850 qemu_event_set(&cbevent);
1853 static void cocoa_clipboard_notify(Notifier *notifier, void *data)
1855 QemuClipboardNotify *notify = data;
1857 switch (notify->type) {
1858 case QEMU_CLIPBOARD_UPDATE_INFO:
1859 cocoa_clipboard_update_info(notify->info);
1861 case QEMU_CLIPBOARD_RESET_SERIAL:
1867 static void cocoa_clipboard_request(QemuClipboardInfo *info,
1868 QemuClipboardType type)
1873 case QEMU_CLIPBOARD_TYPE_TEXT:
1874 text = [[NSPasteboard generalPasteboard] dataForType:NSPasteboardTypeString];
1876 qemu_clipboard_set_data(&cbpeer, info, type,
1877 [text length], [text bytes], true);
1887 * The startup process for the OSX/Cocoa UI is complicated, because
1888 * OSX insists that the UI runs on the initial main thread, and so we
1889 * need to start a second thread which runs the vl.c qemu_main():
1891 * Initial thread: 2nd thread:
1893 * create qemu-main thread
1894 * wait on display_init semaphore
1897 * in cocoa_display_init():
1898 * post the display_init semaphore
1899 * wait on app_started semaphore
1900 * create application, menus, etc
1901 * enter OSX run loop
1902 * in applicationDidFinishLaunching:
1903 * post app_started semaphore
1904 * tell main thread to fullscreen if needed
1906 * run qemu main-loop
1908 * We do this in two stages so that we don't do the creation of the
1909 * GUI application menus and so on for command line options like --help
1910 * where we want to just print text to stdout and exit immediately.
1913 static void *call_qemu_main(void *opaque)
1917 COCOA_DEBUG("Second thread: calling qemu_main()\n");
1918 status = qemu_main(gArgc, gArgv, *_NSGetEnviron());
1919 COCOA_DEBUG("Second thread: qemu_main() returned, exiting\n");
1924 int main (int argc, char **argv) {
1927 COCOA_DEBUG("Entered main()\n");
1931 qemu_sem_init(&display_init_sem, 0);
1932 qemu_sem_init(&app_started_sem, 0);
1934 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1935 NULL, QEMU_THREAD_DETACHED);
1937 COCOA_DEBUG("Main thread: waiting for display_init_sem\n");
1938 qemu_sem_wait(&display_init_sem);
1939 COCOA_DEBUG("Main thread: initializing app\n");
1941 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1943 // Pull this console process up to being a fully-fledged graphical
1944 // app with a menubar and Dock icon
1945 ProcessSerialNumber psn = { 0, kCurrentProcess };
1946 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1948 [QemuApplication sharedApplication];
1950 create_initial_menus();
1953 * Create the menu entries which depend on QEMU state (for consoles
1954 * and removeable devices). These make calls back into QEMU functions,
1955 * which is OK because at this point we know that the second thread
1956 * holds the iothread lock and is synchronously waiting for us to
1959 add_console_menu_entries();
1960 addRemovableDevicesMenuItems();
1962 // Create an Application controller
1963 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1964 [NSApp setDelegate:appController];
1966 // Start the main event loop
1967 COCOA_DEBUG("Main thread: entering OSX run loop\n");
1969 COCOA_DEBUG("Main thread: left OSX run loop, exiting\n");
1971 [appController release];
1980 static void cocoa_update(DisplayChangeListener *dcl,
1981 int x, int y, int w, int h)
1983 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1985 dispatch_async(dispatch_get_main_queue(), ^{
1987 if ([cocoaView cdx] == 1.0) {
1988 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1991 x * [cocoaView cdx],
1992 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1993 w * [cocoaView cdx],
1994 h * [cocoaView cdy]);
1996 [cocoaView setNeedsDisplayInRect:rect];
2000 static void cocoa_switch(DisplayChangeListener *dcl,
2001 DisplaySurface *surface)
2003 pixman_image_t *image = surface->image;
2005 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
2007 // The DisplaySurface will be freed as soon as this callback returns.
2008 // We take a reference to the underlying pixman image here so it does
2009 // not disappear from under our feet; the switchSurface method will
2010 // deref the old image when it is done with it.
2011 pixman_image_ref(image);
2013 dispatch_async(dispatch_get_main_queue(), ^{
2014 [cocoaView updateUIInfo];
2015 [cocoaView switchSurface:image];
2019 static void cocoa_refresh(DisplayChangeListener *dcl)
2021 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2023 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
2024 graphic_hw_update(NULL);
2026 if (qemu_input_is_absolute()) {
2027 dispatch_async(dispatch_get_main_queue(), ^{
2028 if (![cocoaView isAbsoluteEnabled]) {
2029 if ([cocoaView isMouseGrabbed]) {
2030 [cocoaView ungrabMouse];
2033 [cocoaView setAbsoluteEnabled:YES];
2037 if (cbchangecount != [[NSPasteboard generalPasteboard] changeCount]) {
2038 qemu_clipboard_info_unref(cbinfo);
2039 cbinfo = qemu_clipboard_info_new(&cbpeer, QEMU_CLIPBOARD_SELECTION_CLIPBOARD);
2040 if ([[NSPasteboard generalPasteboard] availableTypeFromArray:@[NSPasteboardTypeString]]) {
2041 cbinfo->types[QEMU_CLIPBOARD_TYPE_TEXT].available = true;
2043 qemu_clipboard_update(cbinfo);
2044 cbchangecount = [[NSPasteboard generalPasteboard] changeCount];
2045 qemu_event_set(&cbevent);
2051 static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
2053 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
2055 /* Tell main thread to go ahead and create the app and enter the run loop */
2056 qemu_sem_post(&display_init_sem);
2057 qemu_sem_wait(&app_started_sem);
2058 COCOA_DEBUG("cocoa_display_init: app start completed\n");
2060 /* if fullscreen mode is to be used */
2061 if (opts->has_full_screen && opts->full_screen) {
2062 dispatch_async(dispatch_get_main_queue(), ^{
2063 [NSApp activateIgnoringOtherApps: YES];
2064 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
2067 if (opts->has_show_cursor && opts->show_cursor) {
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);
2079 static QemuDisplay qemu_display_cocoa = {
2080 .type = DISPLAY_TYPE_COCOA,
2081 .init = cocoa_display_init,
2084 static void register_cocoa(void)
2086 qemu_display_register(&qemu_display_cocoa);
2089 type_init(register_cocoa);