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) updateUIInfo
530 if (!qemu_console_is_graphic(dcl.con)) {
535 NSDictionary *description = [[[self window] screen] deviceDescription];
536 CGDirectDisplayID display = [[description objectForKey:@"NSScreenNumber"] unsignedIntValue];
537 NSSize screenSize = [[[self window] screen] frame].size;
538 CGSize screenPhysicalSize = CGDisplayScreenSize(display);
540 frameSize = isFullscreen ? screenSize : [self frame].size;
541 info.width_mm = frameSize.width / screenSize.width * screenPhysicalSize.width;
542 info.height_mm = frameSize.height / screenSize.height * screenPhysicalSize.height;
544 frameSize = [self frame].size;
551 info.width = frameSize.width;
552 info.height = frameSize.height;
554 dpy_set_ui_info(dcl.con, &info, TRUE);
557 - (void)viewDidMoveToWindow
562 - (void) switchSurface:(pixman_image_t *)image
564 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
566 int w = pixman_image_get_width(image);
567 int h = pixman_image_get_height(image);
568 /* cdx == 0 means this is our very first surface, in which case we need
569 * to recalculate the content dimensions even if it happens to be the size
570 * of the initial empty window.
572 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
574 int oldh = screen.height;
576 // Resize before we trigger the redraw, or we'll redraw at the wrong size
577 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
580 [self setContentDimensions];
581 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
584 // update screenBuffer
586 pixman_image_unref(pixman_image);
589 pixman_image = image;
593 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
594 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
597 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
598 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
602 [normalWindow center];
606 - (void) toggleFullScreen:(id)sender
608 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
610 if (isFullscreen) { // switch from fullscreen to desktop
611 isFullscreen = FALSE;
613 [self setContentDimensions];
614 [fullScreenWindow close];
615 [normalWindow setContentView: self];
616 [normalWindow makeKeyAndOrderFront: self];
617 [NSMenu setMenuBarVisible:YES];
618 } else { // switch from desktop to fullscreen
620 [normalWindow orderOut: nil]; /* Hide the window */
622 [self setContentDimensions];
623 [NSMenu setMenuBarVisible:NO];
624 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
625 styleMask:NSWindowStyleMaskBorderless
626 backing:NSBackingStoreBuffered
628 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
629 [fullScreenWindow setHasShadow:NO];
630 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
631 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
632 [[fullScreenWindow contentView] addSubview: self];
633 [fullScreenWindow makeKeyAndOrderFront:self];
637 - (void) toggleKey: (int)keycode {
638 qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode));
641 // Does the work of sending input to the monitor
642 - (void) handleMonitorInput:(NSEvent *)event
647 // if the control key is down
648 if ([event modifierFlags] & NSEventModifierFlagControl) {
652 /* translates Macintosh keycodes to QEMU's keysym */
654 int without_control_translation[] = {
655 [0 ... 0xff] = 0, // invalid key
657 [kVK_UpArrow] = QEMU_KEY_UP,
658 [kVK_DownArrow] = QEMU_KEY_DOWN,
659 [kVK_RightArrow] = QEMU_KEY_RIGHT,
660 [kVK_LeftArrow] = QEMU_KEY_LEFT,
661 [kVK_Home] = QEMU_KEY_HOME,
662 [kVK_End] = QEMU_KEY_END,
663 [kVK_PageUp] = QEMU_KEY_PAGEUP,
664 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
665 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
666 [kVK_Delete] = QEMU_KEY_BACKSPACE,
669 int with_control_translation[] = {
670 [0 ... 0xff] = 0, // invalid key
672 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
673 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
674 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
675 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
676 [kVK_Home] = QEMU_KEY_CTRL_HOME,
677 [kVK_End] = QEMU_KEY_CTRL_END,
678 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
679 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
682 if (control_key != 0) { /* If the control key is being used */
683 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
684 keysym = with_control_translation[[event keyCode]];
687 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
688 keysym = without_control_translation[[event keyCode]];
692 // if not a key that needs translating
694 NSString *ks = [event characters];
695 if ([ks length] > 0) {
696 keysym = [ks characterAtIndex:0];
701 kbd_put_keysym(keysym);
705 - (bool) handleEvent:(NSEvent *)event
709 * Just let OSX have all events that arrive before
710 * applicationDidFinishLaunching.
711 * This avoids a deadlock on the iothread lock, which cocoa_display_init()
712 * will not drop until after the app_started_sem is posted. (In theory
713 * there should not be any such events, but OSX Catalina now emits some.)
717 return bool_with_iothread_lock(^{
718 return [self handleEventLocked:event];
722 - (bool) handleEventLocked:(NSEvent *)event
724 /* Return true if we handled the event, false if it should be given to OSX */
725 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
728 bool mouse_event = false;
729 static bool switched_to_fullscreen = false;
730 // Location of event in virtual screen coordinates
731 NSPoint p = [self screenLocationOfEvent:event];
732 NSUInteger modifiers = [event modifierFlags];
735 * Check -[NSEvent modifierFlags] here.
737 * There is a NSEventType for an event notifying the change of
738 * -[NSEvent modifierFlags], NSEventTypeFlagsChanged but these operations
739 * are performed for any events because a modifier state may change while
740 * the application is inactive (i.e. no events fire) and we don't want to
741 * wait for another modifier state change to detect such a change.
743 * NSEventModifierFlagCapsLock requires a special treatment. The other flags
744 * are handled in similar manners.
746 * NSEventModifierFlagCapsLock
747 * ---------------------------
749 * If CapsLock state is changed, "up" and "down" events will be fired in
750 * sequence, effectively updates CapsLock state on the guest.
755 * If a flag is not set, fire "up" events for all keys which correspond to
756 * the flag. Note that "down" events are not fired here because the flags
757 * checked here do not tell what exact keys are down.
759 * If one of the keys corresponding to a flag is down, we rely on
760 * -[NSEvent keyCode] of an event whose -[NSEvent type] is
761 * NSEventTypeFlagsChanged to know the exact key which is down, which has
762 * the following two downsides:
763 * - It does not work when the application is inactive as described above.
764 * - It malfactions *after* the modifier state is changed while the
765 * application is inactive. It is because -[NSEvent keyCode] does not tell
766 * if the key is up or down, and requires to infer the current state from
767 * the previous state. It is still possible to fix such a malfanction by
768 * completely leaving your hands from the keyboard, which hopefully makes
769 * this implementation usable enough.
771 if (!!(modifiers & NSEventModifierFlagCapsLock) !=
772 qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) {
773 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true);
774 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false);
777 if (!(modifiers & NSEventModifierFlagShift)) {
778 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false);
779 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false);
781 if (!(modifiers & NSEventModifierFlagControl)) {
782 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false);
783 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false);
785 if (!(modifiers & NSEventModifierFlagOption)) {
786 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
787 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
789 if (!(modifiers & NSEventModifierFlagCommand)) {
790 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
791 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
794 switch ([event type]) {
795 case NSEventTypeFlagsChanged:
796 switch ([event keyCode]) {
798 if (!!(modifiers & NSEventModifierFlagShift)) {
799 [self toggleKey:Q_KEY_CODE_SHIFT];
804 if (!!(modifiers & NSEventModifierFlagShift)) {
805 [self toggleKey:Q_KEY_CODE_SHIFT_R];
810 if (!!(modifiers & NSEventModifierFlagControl)) {
811 [self toggleKey:Q_KEY_CODE_CTRL];
815 case kVK_RightControl:
816 if (!!(modifiers & NSEventModifierFlagControl)) {
817 [self toggleKey:Q_KEY_CODE_CTRL_R];
822 if (!!(modifiers & NSEventModifierFlagOption)) {
823 [self toggleKey:Q_KEY_CODE_ALT];
827 case kVK_RightOption:
828 if (!!(modifiers & NSEventModifierFlagOption)) {
829 [self toggleKey:Q_KEY_CODE_ALT_R];
833 /* Don't pass command key changes to guest unless mouse is grabbed */
835 if (isMouseGrabbed &&
836 !!(modifiers & NSEventModifierFlagCommand)) {
837 [self toggleKey:Q_KEY_CODE_META_L];
841 case kVK_RightCommand:
842 if (isMouseGrabbed &&
843 !!(modifiers & NSEventModifierFlagCommand)) {
844 [self toggleKey:Q_KEY_CODE_META_R];
849 case NSEventTypeKeyDown:
850 keycode = cocoa_keycode_to_qemu([event keyCode]);
852 // forward command key combos to the host UI unless the mouse is grabbed
853 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
855 * Prevent the command key from being stuck down in the guest
856 * when using Command-F to switch to full screen mode.
858 if (keycode == Q_KEY_CODE_F) {
859 switched_to_fullscreen = true;
866 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
867 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
868 NSString *keychar = [event charactersIgnoringModifiers];
869 if ([keychar length] == 1) {
870 char key = [keychar characterAtIndex:0];
873 // enable graphic console
875 console_select(key - '0' - 1); /* ascii math */
878 // release the mouse grab
886 if (qemu_console_is_graphic(NULL)) {
887 qkbd_state_key_event(kbd, keycode, true);
889 [self handleMonitorInput: event];
892 case NSEventTypeKeyUp:
893 keycode = cocoa_keycode_to_qemu([event keyCode]);
895 // don't pass the guest a spurious key-up if we treated this
896 // command-key combo as a host UI action
897 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
901 if (qemu_console_is_graphic(NULL)) {
902 qkbd_state_key_event(kbd, keycode, false);
905 case NSEventTypeMouseMoved:
906 if (isAbsoluteEnabled) {
907 // Cursor re-entered into a window might generate events bound to screen coordinates
908 // and `nil` window property, and in full screen mode, current window might not be
909 // key window, where event location alone should suffice.
910 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
911 if (isMouseGrabbed) {
915 if (!isMouseGrabbed) {
922 case NSEventTypeLeftMouseDown:
923 buttons |= MOUSE_EVENT_LBUTTON;
926 case NSEventTypeRightMouseDown:
927 buttons |= MOUSE_EVENT_RBUTTON;
930 case NSEventTypeOtherMouseDown:
931 buttons |= MOUSE_EVENT_MBUTTON;
934 case NSEventTypeLeftMouseDragged:
935 buttons |= MOUSE_EVENT_LBUTTON;
938 case NSEventTypeRightMouseDragged:
939 buttons |= MOUSE_EVENT_RBUTTON;
942 case NSEventTypeOtherMouseDragged:
943 buttons |= MOUSE_EVENT_MBUTTON;
946 case NSEventTypeLeftMouseUp:
948 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
950 * In fullscreen mode, the window of cocoaView may not be the
951 * key window, therefore the position relative to the virtual
952 * screen alone will be sufficient.
954 if(isFullscreen || [[self window] isKeyWindow]) {
959 case NSEventTypeRightMouseUp:
962 case NSEventTypeOtherMouseUp:
965 case NSEventTypeScrollWheel:
967 * Send wheel events to the guest regardless of window focus.
968 * This is in-line with standard Mac OS X UI behaviour.
972 * We shouldn't have got a scroll event when deltaY and delta Y
973 * are zero, hence no harm in dropping the event
975 if ([event deltaY] != 0 || [event deltaX] != 0) {
976 /* Determine if this is a scroll up or scroll down event */
977 if ([event deltaY] != 0) {
978 buttons = ([event deltaY] > 0) ?
979 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
980 } else if ([event deltaX] != 0) {
981 buttons = ([event deltaX] > 0) ?
982 INPUT_BUTTON_WHEEL_LEFT : INPUT_BUTTON_WHEEL_RIGHT;
985 qemu_input_queue_btn(dcl.con, buttons, true);
986 qemu_input_event_sync();
987 qemu_input_queue_btn(dcl.con, buttons, false);
988 qemu_input_event_sync();
992 * Since deltaX/deltaY also report scroll wheel events we prevent mouse
993 * movement code from executing.
1002 /* Don't send button events to the guest unless we've got a
1003 * mouse grab or window focus. If we have neither then this event
1004 * is the user clicking on the background window to activate and
1005 * bring us to the front, which will be done by the sendEvent
1006 * call below. We definitely don't want to pass that click through
1009 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
1010 (last_buttons != buttons)) {
1011 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1012 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1013 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1014 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
1016 qemu_input_update_buttons(dcl.con, bmap, last_buttons, buttons);
1017 last_buttons = buttons;
1019 if (isMouseGrabbed) {
1020 if (isAbsoluteEnabled) {
1021 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
1022 * The check on screenContainsPoint is to avoid sending out of range values for
1023 * clicks in the titlebar.
1025 if ([self screenContainsPoint:p]) {
1026 qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x, 0, screen.width);
1027 qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
1030 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, (int)[event deltaX]);
1031 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, (int)[event deltaY]);
1036 qemu_input_event_sync();
1043 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
1045 if (!isFullscreen) {
1047 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
1049 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
1052 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1053 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
1056 - (void) ungrabMouse
1058 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
1060 if (!isFullscreen) {
1062 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
1064 [normalWindow setTitle:@"QEMU"];
1066 [self unhideCursor];
1067 CGAssociateMouseAndMouseCursorPosition(TRUE);
1068 isMouseGrabbed = FALSE;
1071 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {
1072 isAbsoluteEnabled = tIsAbsoluteEnabled;
1073 if (isMouseGrabbed) {
1074 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1077 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
1078 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
1079 - (float) cdx {return cdx;}
1080 - (float) cdy {return cdy;}
1081 - (QEMUScreen) gscreen {return screen;}
1084 * Makes the target think all down keys are being released.
1085 * This prevents a stuck key problem, since we will not see
1086 * key up events for those keys after we have lost focus.
1088 - (void) raiseAllKeys
1090 with_iothread_lock(^{
1091 qkbd_state_lift_all_keys(kbd);
1099 ------------------------------------------------------
1100 QemuCocoaAppController
1101 ------------------------------------------------------
1103 @interface QemuCocoaAppController : NSObject
1104 <NSWindowDelegate, NSApplicationDelegate>
1107 - (void)doToggleFullScreen:(id)sender;
1108 - (void)toggleFullScreen:(id)sender;
1109 - (void)showQEMUDoc:(id)sender;
1110 - (void)zoomToFit:(id) sender;
1111 - (void)displayConsole:(id)sender;
1112 - (void)pauseQEMU:(id)sender;
1113 - (void)resumeQEMU:(id)sender;
1114 - (void)displayPause;
1115 - (void)removePause;
1116 - (void)restartQEMU:(id)sender;
1117 - (void)powerDownQEMU:(id)sender;
1118 - (void)ejectDeviceMedia:(id)sender;
1119 - (void)changeDeviceMedia:(id)sender;
1121 - (void)openDocumentation:(NSString *)filename;
1122 - (IBAction) do_about_menu_item: (id) sender;
1123 - (void)make_about_window;
1124 - (void)adjustSpeed:(id)sender;
1127 @implementation QemuCocoaAppController
1130 COCOA_DEBUG("QemuCocoaAppController: init\n");
1132 self = [super init];
1135 // create a view and add it to the window
1136 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1138 error_report("(cocoa) can't create a view");
1143 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
1144 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
1145 backing:NSBackingStoreBuffered defer:NO];
1147 error_report("(cocoa) can't create window");
1150 [normalWindow setAcceptsMouseMovedEvents:YES];
1151 [normalWindow setTitle:@"QEMU"];
1152 [normalWindow setContentView:cocoaView];
1153 [normalWindow makeKeyAndOrderFront:self];
1154 [normalWindow center];
1155 [normalWindow setDelegate: self];
1156 stretch_video = false;
1158 /* Used for displaying pause on the screen */
1159 pauseLabel = [NSTextField new];
1160 [pauseLabel setBezeled:YES];
1161 [pauseLabel setDrawsBackground:YES];
1162 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1163 [pauseLabel setEditable:NO];
1164 [pauseLabel setSelectable:NO];
1165 [pauseLabel setStringValue: @"Paused"];
1166 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1167 [pauseLabel setTextColor: [NSColor blackColor]];
1168 [pauseLabel sizeToFit];
1170 [self make_about_window];
1177 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1180 [cocoaView release];
1184 - (void)applicationDidFinishLaunching: (NSNotification *) note
1186 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1187 allow_events = true;
1188 /* Tell cocoa_display_init to proceed */
1189 qemu_sem_post(&app_started_sem);
1192 - (void)applicationWillTerminate:(NSNotification *)aNotification
1194 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1196 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1199 * Sleep here, because returning will cause OSX to kill us
1200 * immediately; the QEMU main loop will handle the shutdown
1201 * request and terminate the process.
1203 [NSThread sleepForTimeInterval:INFINITY];
1206 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1211 - (NSApplicationTerminateReply)applicationShouldTerminate:
1212 (NSApplication *)sender
1214 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1215 return [self verifyQuit];
1218 - (void)windowDidChangeScreen:(NSNotification *)notification
1220 [cocoaView updateUIInfo];
1223 - (void)windowDidResize:(NSNotification *)notification
1225 [cocoaView updateUIInfo];
1228 /* Called when the user clicks on a window's close button */
1229 - (BOOL)windowShouldClose:(id)sender
1231 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1232 [NSApp terminate: sender];
1233 /* If the user allows the application to quit then the call to
1234 * NSApp terminate will never return. If we get here then the user
1235 * cancelled the quit, so we should return NO to not permit the
1236 * closing of this window.
1241 /* Called when QEMU goes into the background */
1242 - (void) applicationWillResignActive: (NSNotification *)aNotification
1244 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1245 [cocoaView raiseAllKeys];
1248 /* We abstract the method called by the Enter Fullscreen menu item
1249 * because Mac OS 10.7 and higher disables it. This is because of the
1250 * menu item's old selector's name toggleFullScreen:
1252 - (void) doToggleFullScreen:(id)sender
1254 [self toggleFullScreen:(id)sender];
1257 - (void)toggleFullScreen:(id)sender
1259 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1261 [cocoaView toggleFullScreen:sender];
1264 /* Tries to find then open the specified filename */
1265 - (void) openDocumentation: (NSString *) filename
1267 /* Where to look for local files */
1268 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
1269 NSString *full_file_path;
1270 NSURL *full_file_url;
1272 /* iterate thru the possible paths until the file is found */
1274 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1275 full_file_path = [[NSBundle mainBundle] executablePath];
1276 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1277 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1278 path_array[index], filename];
1279 full_file_url = [NSURL fileURLWithPath: full_file_path
1280 isDirectory: false];
1281 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
1286 /* If none of the paths opened a file */
1288 QEMU_Alert(@"Failed to open file");
1291 - (void)showQEMUDoc:(id)sender
1293 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1295 [self openDocumentation: @"index.html"];
1298 /* Stretches video to fit host monitor size */
1299 - (void)zoomToFit:(id) sender
1301 stretch_video = !stretch_video;
1302 if (stretch_video == true) {
1303 [sender setState: NSControlStateValueOn];
1305 [sender setState: NSControlStateValueOff];
1309 /* Displays the console on the screen */
1310 - (void)displayConsole:(id)sender
1312 console_select([sender tag]);
1315 /* Pause the guest */
1316 - (void)pauseQEMU:(id)sender
1318 with_iothread_lock(^{
1321 [sender setEnabled: NO];
1322 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1323 [self displayPause];
1326 /* Resume running the guest operating system */
1327 - (void)resumeQEMU:(id) sender
1329 with_iothread_lock(^{
1332 [sender setEnabled: NO];
1333 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1337 /* Displays the word pause on the screen */
1338 - (void)displayPause
1340 /* Coordinates have to be calculated each time because the window can change its size */
1341 int xCoord, yCoord, width, height;
1342 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1343 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1344 width = [pauseLabel frame].size.width;
1345 height = [pauseLabel frame].size.height;
1346 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1347 [cocoaView addSubview: pauseLabel];
1350 /* Removes the word pause from the screen */
1353 [pauseLabel removeFromSuperview];
1357 - (void)restartQEMU:(id)sender
1359 with_iothread_lock(^{
1360 qmp_system_reset(NULL);
1364 /* Powers down QEMU */
1365 - (void)powerDownQEMU:(id)sender
1367 with_iothread_lock(^{
1368 qmp_system_powerdown(NULL);
1372 /* Ejects the media.
1373 * Uses sender's tag to figure out the device to eject.
1375 - (void)ejectDeviceMedia:(id)sender
1378 drive = [sender representedObject];
1381 QEMU_Alert(@"Failed to find drive to eject!");
1385 __block Error *err = NULL;
1386 with_iothread_lock(^{
1387 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1388 false, NULL, false, false, &err);
1390 handleAnyDeviceErrors(err);
1393 /* Displays a dialog box asking the user to select an image file to load.
1394 * Uses sender's represented object value to figure out which drive to use.
1396 - (void)changeDeviceMedia:(id)sender
1398 /* Find the drive name */
1400 drive = [sender representedObject];
1403 QEMU_Alert(@"Could not find drive!");
1407 /* Display the file open dialog */
1408 NSOpenPanel * openPanel;
1409 openPanel = [NSOpenPanel openPanel];
1410 [openPanel setCanChooseFiles: YES];
1411 [openPanel setAllowsMultipleSelection: NO];
1412 if([openPanel runModal] == NSModalResponseOK) {
1413 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1416 QEMU_Alert(@"Failed to convert URL to file path!");
1420 __block Error *err = NULL;
1421 with_iothread_lock(^{
1422 qmp_blockdev_change_medium(true,
1423 [drive cStringUsingEncoding:
1424 NSASCIIStringEncoding],
1426 [file cStringUsingEncoding:
1427 NSASCIIStringEncoding],
1432 handleAnyDeviceErrors(err);
1436 /* Verifies if the user really wants to quit */
1439 NSAlert *alert = [NSAlert new];
1440 [alert autorelease];
1441 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1442 [alert addButtonWithTitle: @"Cancel"];
1443 [alert addButtonWithTitle: @"Quit"];
1444 if([alert runModal] == NSAlertSecondButtonReturn) {
1451 /* The action method for the About menu item */
1452 - (IBAction) do_about_menu_item: (id) sender
1454 [about_window makeKeyAndOrderFront: nil];
1457 /* Create and display the about dialog */
1458 - (void)make_about_window
1460 /* Make the window */
1461 int x = 0, y = 0, about_width = 400, about_height = 200;
1462 NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1463 about_window = [[NSWindow alloc] initWithContentRect:window_rect
1464 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1465 NSWindowStyleMaskMiniaturizable
1466 backing:NSBackingStoreBuffered
1468 [about_window setTitle: @"About"];
1469 [about_window setReleasedWhenClosed: NO];
1470 [about_window center];
1471 NSView *superView = [about_window contentView];
1473 /* Create the dimensions of the picture */
1474 int picture_width = 80, picture_height = 80;
1475 x = (about_width - picture_width)/2;
1476 y = about_height - picture_height - 10;
1477 NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1479 /* Make the picture of QEMU */
1480 NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1482 char *qemu_image_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1483 NSString *qemu_image_path = [NSString stringWithUTF8String:qemu_image_path_c];
1484 g_free(qemu_image_path_c);
1485 NSImage *qemu_image = [[NSImage alloc] initWithContentsOfFile:qemu_image_path];
1486 [picture_view setImage: qemu_image];
1487 [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1488 [superView addSubview: picture_view];
1490 /* Make the name label */
1491 NSBundle *bundle = [NSBundle mainBundle];
1495 int name_width = about_width, name_height = 20;
1496 NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1497 NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1498 [name_label setEditable: NO];
1499 [name_label setBezeled: NO];
1500 [name_label setDrawsBackground: NO];
1501 [name_label setAlignment: NSTextAlignmentCenter];
1502 NSString *qemu_name = [[bundle executablePath] lastPathComponent];
1503 [name_label setStringValue: qemu_name];
1504 [superView addSubview: name_label];
1507 /* Set the version label's attributes */
1510 int version_width = about_width, version_height = 20;
1511 NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1512 NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1514 [version_label setEditable: NO];
1515 [version_label setBezeled: NO];
1516 [version_label setAlignment: NSTextAlignmentCenter];
1517 [version_label setDrawsBackground: NO];
1519 /* Create the version string*/
1520 NSString *version_string;
1521 version_string = [[NSString alloc] initWithFormat:
1522 @"QEMU emulator version %s", QEMU_FULL_VERSION];
1523 [version_label setStringValue: version_string];
1524 [superView addSubview: version_label];
1526 /* Make copyright label */
1529 int copyright_width = about_width, copyright_height = 20;
1530 NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1531 NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1533 [copyright_label setEditable: NO];
1534 [copyright_label setBezeled: NO];
1535 [copyright_label setDrawsBackground: NO];
1536 [copyright_label setAlignment: NSTextAlignmentCenter];
1537 [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1539 [superView addSubview: copyright_label];
1542 /* Used by the Speed menu items */
1543 - (void)adjustSpeed:(id)sender
1545 int throttle_pct; /* throttle percentage */
1548 menu = [sender menu];
1551 /* Unselect the currently selected item */
1552 for (NSMenuItem *item in [menu itemArray]) {
1553 if (item.state == NSControlStateValueOn) {
1554 [item setState: NSControlStateValueOff];
1560 // check the menu item
1561 [sender setState: NSControlStateValueOn];
1563 // get the throttle percentage
1564 throttle_pct = [sender tag];
1566 with_iothread_lock(^{
1567 cpu_throttle_set(throttle_pct);
1569 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1574 @interface QemuApplication : NSApplication
1577 @implementation QemuApplication
1578 - (void)sendEvent:(NSEvent *)event
1580 COCOA_DEBUG("QemuApplication: sendEvent\n");
1581 if (![cocoaView handleEvent:event]) {
1582 [super sendEvent: event];
1587 static void create_initial_menus(void)
1591 NSMenuItem *menuItem;
1593 [NSApp setMainMenu:[[NSMenu alloc] init]];
1596 menu = [[NSMenu alloc] initWithTitle:@""];
1597 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1598 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1599 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1600 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1601 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1602 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1603 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1604 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1605 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1606 [menuItem setSubmenu:menu];
1607 [[NSApp mainMenu] addItem:menuItem];
1608 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1611 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1612 [menu setAutoenablesItems: NO];
1613 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1614 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1615 [menu addItem: menuItem];
1616 [menuItem setEnabled: NO];
1617 [menu addItem: [NSMenuItem separatorItem]];
1618 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1619 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1620 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1621 [menuItem setSubmenu:menu];
1622 [[NSApp mainMenu] addItem:menuItem];
1625 menu = [[NSMenu alloc] initWithTitle:@"View"];
1626 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1627 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1628 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1629 [menuItem setSubmenu:menu];
1630 [[NSApp mainMenu] addItem:menuItem];
1633 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1635 // Add the rest of the Speed menu items
1636 int p, percentage, throttle_pct;
1637 for (p = 10; p >= 0; p--)
1639 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1641 menuItem = [[[NSMenuItem alloc]
1642 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1644 if (percentage == 100) {
1645 [menuItem setState: NSControlStateValueOn];
1648 /* Calculate the throttle percentage */
1649 throttle_pct = -1 * percentage + 100;
1651 [menuItem setTag: throttle_pct];
1652 [menu addItem: menuItem];
1654 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1655 [menuItem setSubmenu:menu];
1656 [[NSApp mainMenu] addItem:menuItem];
1659 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1660 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1661 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1662 [menuItem setSubmenu:menu];
1663 [[NSApp mainMenu] addItem:menuItem];
1664 [NSApp setWindowsMenu:menu];
1667 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1668 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1669 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1670 [menuItem setSubmenu:menu];
1671 [[NSApp mainMenu] addItem:menuItem];
1674 /* Returns a name for a given console */
1675 static NSString * getConsoleName(QemuConsole * console)
1677 g_autofree char *label = qemu_console_get_label(console);
1679 return [NSString stringWithUTF8String:label];
1682 /* Add an entry to the View menu for each console */
1683 static void add_console_menu_entries(void)
1686 NSMenuItem *menuItem;
1689 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1691 [menu addItem:[NSMenuItem separatorItem]];
1693 while (qemu_console_lookup_by_index(index) != NULL) {
1694 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1695 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1696 [menuItem setTag: index];
1697 [menu addItem: menuItem];
1702 /* Make menu items for all removable devices.
1703 * Each device is given an 'Eject' and 'Change' menu item.
1705 static void addRemovableDevicesMenuItems(void)
1708 NSMenuItem *menuItem;
1709 BlockInfoList *currentDevice, *pointerToFree;
1710 NSString *deviceName;
1712 currentDevice = qmp_query_block(NULL);
1713 pointerToFree = currentDevice;
1715 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1717 // Add a separator between related groups of menu items
1718 [menu addItem:[NSMenuItem separatorItem]];
1720 // Set the attributes to the "Removable Media" menu item
1721 NSString *titleString = @"Removable Media";
1722 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1723 NSColor *newColor = [NSColor blackColor];
1724 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1725 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1726 traits:NSBoldFontMask|NSItalicFontMask
1729 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1730 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1731 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1733 // Add the "Removable Media" menu item
1734 menuItem = [NSMenuItem new];
1735 [menuItem setAttributedTitle: attString];
1736 [menuItem setEnabled: NO];
1737 [menu addItem: menuItem];
1739 /* Loop through all the block devices in the emulator */
1740 while (currentDevice) {
1741 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1743 if(currentDevice->value->removable) {
1744 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1745 action: @selector(changeDeviceMedia:)
1746 keyEquivalent: @""];
1747 [menu addItem: menuItem];
1748 [menuItem setRepresentedObject: deviceName];
1749 [menuItem autorelease];
1751 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1752 action: @selector(ejectDeviceMedia:)
1753 keyEquivalent: @""];
1754 [menu addItem: menuItem];
1755 [menuItem setRepresentedObject: deviceName];
1756 [menuItem autorelease];
1758 currentDevice = currentDevice->next;
1760 qapi_free_BlockInfoList(pointerToFree);
1763 @interface QemuCocoaPasteboardTypeOwner : NSObject<NSPasteboardTypeOwner>
1766 @implementation QemuCocoaPasteboardTypeOwner
1768 - (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)type
1770 if (type != NSPasteboardTypeString) {
1774 with_iothread_lock(^{
1775 QemuClipboardInfo *info = qemu_clipboard_info_ref(cbinfo);
1776 qemu_event_reset(&cbevent);
1777 qemu_clipboard_request(info, QEMU_CLIPBOARD_TYPE_TEXT);
1779 while (info == cbinfo &&
1780 info->types[QEMU_CLIPBOARD_TYPE_TEXT].available &&
1781 info->types[QEMU_CLIPBOARD_TYPE_TEXT].data == NULL) {
1782 qemu_mutex_unlock_iothread();
1783 qemu_event_wait(&cbevent);
1784 qemu_mutex_lock_iothread();
1787 if (info == cbinfo) {
1788 NSData *data = [[NSData alloc] initWithBytes:info->types[QEMU_CLIPBOARD_TYPE_TEXT].data
1789 length:info->types[QEMU_CLIPBOARD_TYPE_TEXT].size];
1790 [sender setData:data forType:NSPasteboardTypeString];
1794 qemu_clipboard_info_unref(info);
1800 static QemuCocoaPasteboardTypeOwner *cbowner;
1802 static void cocoa_clipboard_notify(Notifier *notifier, void *data);
1803 static void cocoa_clipboard_request(QemuClipboardInfo *info,
1804 QemuClipboardType type);
1806 static QemuClipboardPeer cbpeer = {
1808 .notifier = { .notify = cocoa_clipboard_notify },
1809 .request = cocoa_clipboard_request
1812 static void cocoa_clipboard_update_info(QemuClipboardInfo *info)
1814 if (info->owner == &cbpeer || info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
1818 if (info != cbinfo) {
1819 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1820 qemu_clipboard_info_unref(cbinfo);
1821 cbinfo = qemu_clipboard_info_ref(info);
1822 cbchangecount = [[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:cbowner];
1826 qemu_event_set(&cbevent);
1829 static void cocoa_clipboard_notify(Notifier *notifier, void *data)
1831 QemuClipboardNotify *notify = data;
1833 switch (notify->type) {
1834 case QEMU_CLIPBOARD_UPDATE_INFO:
1835 cocoa_clipboard_update_info(notify->info);
1837 case QEMU_CLIPBOARD_RESET_SERIAL:
1843 static void cocoa_clipboard_request(QemuClipboardInfo *info,
1844 QemuClipboardType type)
1849 case QEMU_CLIPBOARD_TYPE_TEXT:
1850 text = [[NSPasteboard generalPasteboard] dataForType:NSPasteboardTypeString];
1852 qemu_clipboard_set_data(&cbpeer, info, type,
1853 [text length], [text bytes], true);
1863 * The startup process for the OSX/Cocoa UI is complicated, because
1864 * OSX insists that the UI runs on the initial main thread, and so we
1865 * need to start a second thread which runs the vl.c qemu_main():
1867 * Initial thread: 2nd thread:
1869 * create qemu-main thread
1870 * wait on display_init semaphore
1873 * in cocoa_display_init():
1874 * post the display_init semaphore
1875 * wait on app_started semaphore
1876 * create application, menus, etc
1877 * enter OSX run loop
1878 * in applicationDidFinishLaunching:
1879 * post app_started semaphore
1880 * tell main thread to fullscreen if needed
1882 * run qemu main-loop
1884 * We do this in two stages so that we don't do the creation of the
1885 * GUI application menus and so on for command line options like --help
1886 * where we want to just print text to stdout and exit immediately.
1889 static void *call_qemu_main(void *opaque)
1893 COCOA_DEBUG("Second thread: calling qemu_main()\n");
1894 status = qemu_main(gArgc, gArgv, *_NSGetEnviron());
1895 COCOA_DEBUG("Second thread: qemu_main() returned, exiting\n");
1900 int main (int argc, char **argv) {
1903 COCOA_DEBUG("Entered main()\n");
1907 qemu_sem_init(&display_init_sem, 0);
1908 qemu_sem_init(&app_started_sem, 0);
1910 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1911 NULL, QEMU_THREAD_DETACHED);
1913 COCOA_DEBUG("Main thread: waiting for display_init_sem\n");
1914 qemu_sem_wait(&display_init_sem);
1915 COCOA_DEBUG("Main thread: initializing app\n");
1917 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1919 // Pull this console process up to being a fully-fledged graphical
1920 // app with a menubar and Dock icon
1921 ProcessSerialNumber psn = { 0, kCurrentProcess };
1922 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1924 [QemuApplication sharedApplication];
1926 create_initial_menus();
1929 * Create the menu entries which depend on QEMU state (for consoles
1930 * and removeable devices). These make calls back into QEMU functions,
1931 * which is OK because at this point we know that the second thread
1932 * holds the iothread lock and is synchronously waiting for us to
1935 add_console_menu_entries();
1936 addRemovableDevicesMenuItems();
1938 // Create an Application controller
1939 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1940 [NSApp setDelegate:appController];
1942 // Start the main event loop
1943 COCOA_DEBUG("Main thread: entering OSX run loop\n");
1945 COCOA_DEBUG("Main thread: left OSX run loop, exiting\n");
1947 [appController release];
1956 static void cocoa_update(DisplayChangeListener *dcl,
1957 int x, int y, int w, int h)
1959 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1961 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1963 dispatch_async(dispatch_get_main_queue(), ^{
1965 if ([cocoaView cdx] == 1.0) {
1966 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1969 x * [cocoaView cdx],
1970 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1971 w * [cocoaView cdx],
1972 h * [cocoaView cdy]);
1974 [cocoaView setNeedsDisplayInRect:rect];
1980 static void cocoa_switch(DisplayChangeListener *dcl,
1981 DisplaySurface *surface)
1983 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1984 pixman_image_t *image = surface->image;
1986 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1988 [cocoaView updateUIInfo];
1990 // The DisplaySurface will be freed as soon as this callback returns.
1991 // We take a reference to the underlying pixman image here so it does
1992 // not disappear from under our feet; the switchSurface method will
1993 // deref the old image when it is done with it.
1994 pixman_image_ref(image);
1996 dispatch_async(dispatch_get_main_queue(), ^{
1997 [cocoaView switchSurface:image];
2002 static void cocoa_refresh(DisplayChangeListener *dcl)
2004 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2006 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
2007 graphic_hw_update(NULL);
2009 if (qemu_input_is_absolute()) {
2010 dispatch_async(dispatch_get_main_queue(), ^{
2011 if (![cocoaView isAbsoluteEnabled]) {
2012 if ([cocoaView isMouseGrabbed]) {
2013 [cocoaView ungrabMouse];
2016 [cocoaView setAbsoluteEnabled:YES];
2020 if (cbchangecount != [[NSPasteboard generalPasteboard] changeCount]) {
2021 qemu_clipboard_info_unref(cbinfo);
2022 cbinfo = qemu_clipboard_info_new(&cbpeer, QEMU_CLIPBOARD_SELECTION_CLIPBOARD);
2023 if ([[NSPasteboard generalPasteboard] availableTypeFromArray:@[NSPasteboardTypeString]]) {
2024 cbinfo->types[QEMU_CLIPBOARD_TYPE_TEXT].available = true;
2026 qemu_clipboard_update(cbinfo);
2027 cbchangecount = [[NSPasteboard generalPasteboard] changeCount];
2028 qemu_event_set(&cbevent);
2034 static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
2036 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
2038 /* Tell main thread to go ahead and create the app and enter the run loop */
2039 qemu_sem_post(&display_init_sem);
2040 qemu_sem_wait(&app_started_sem);
2041 COCOA_DEBUG("cocoa_display_init: app start completed\n");
2043 /* if fullscreen mode is to be used */
2044 if (opts->has_full_screen && opts->full_screen) {
2045 dispatch_async(dispatch_get_main_queue(), ^{
2046 [NSApp activateIgnoringOtherApps: YES];
2047 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
2050 if (opts->has_show_cursor && opts->show_cursor) {
2054 // register vga output callbacks
2055 register_displaychangelistener(&dcl);
2057 qemu_event_init(&cbevent, false);
2058 cbowner = [[QemuCocoaPasteboardTypeOwner alloc] init];
2059 qemu_clipboard_peer_register(&cbpeer);
2062 static QemuDisplay qemu_display_cocoa = {
2063 .type = DISPLAY_TYPE_COCOA,
2064 .init = cocoa_display_init,
2067 static void register_cocoa(void)
2069 qemu_display_register(&qemu_display_cocoa);
2072 type_init(register_cocoa);