2 * QEMU Cocoa CG display driver
4 * Copyright (c) 2008 Mike Kronenberg
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "qemu/osdep.h"
27 #import <Cocoa/Cocoa.h>
28 #include <crt_externs.h>
30 #include "qemu/help-texts.h"
31 #include "qemu-main.h"
32 #include "ui/clipboard.h"
33 #include "ui/console.h"
35 #include "ui/kbd-state.h"
36 #include "sysemu/sysemu.h"
37 #include "sysemu/runstate.h"
38 #include "sysemu/runstate-action.h"
39 #include "sysemu/cpu-throttle.h"
40 #include "qapi/error.h"
41 #include "qapi/qapi-commands-block.h"
42 #include "qapi/qapi-commands-machine.h"
43 #include "qapi/qapi-commands-misc.h"
44 #include "sysemu/blockdev.h"
45 #include "qemu-version.h"
46 #include "qemu/cutils.h"
47 #include "qemu/main-loop.h"
48 #include "qemu/module.h"
49 #include "qemu/error-report.h"
50 #include <Carbon/Carbon.h>
51 #include "hw/core/cpu.h"
53 #ifndef MAC_OS_X_VERSION_10_13
54 #define MAC_OS_X_VERSION_10_13 101300
57 #ifndef MAC_OS_VERSION_14_0
58 #define MAC_OS_VERSION_14_0 140000
61 /* 10.14 deprecates NSOnState and NSOffState in favor of
62 * NSControlStateValueOn/Off, which were introduced in 10.13.
63 * Define for older versions
65 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
66 #define NSControlStateValueOn NSOnState
67 #define NSControlStateValueOff NSOffState
73 #define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
75 #define COCOA_DEBUG(...) ((void) 0)
78 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
80 #define UC_CTRL_KEY "\xe2\x8c\x83"
81 #define UC_ALT_KEY "\xe2\x8c\xa5"
88 static void cocoa_update(DisplayChangeListener *dcl,
89 int x, int y, int w, int h);
91 static void cocoa_switch(DisplayChangeListener *dcl,
92 DisplaySurface *surface);
94 static void cocoa_refresh(DisplayChangeListener *dcl);
96 static NSWindow *normalWindow;
97 static const DisplayChangeListenerOps dcl_ops = {
99 .dpy_gfx_update = cocoa_update,
100 .dpy_gfx_switch = cocoa_switch,
101 .dpy_refresh = cocoa_refresh,
103 static DisplayChangeListener dcl = {
106 static int cursor_hide = 1;
107 static int left_command_key_enabled = 1;
108 static bool swap_opt_cmd;
110 static bool stretch_video;
111 static CGInterpolationQuality zoom_interpolation = kCGInterpolationNone;
112 static NSTextField *pauseLabel;
114 static bool allow_events;
116 static NSInteger cbchangecount = -1;
117 static QemuClipboardInfo *cbinfo;
118 static QemuEvent cbevent;
120 // Utility functions to run specified code block with the BQL held
121 typedef void (^CodeBlock)(void);
122 typedef bool (^BoolCodeBlock)(void);
124 static void with_bql(CodeBlock block)
126 bool locked = bql_locked();
136 static bool bool_with_bql(BoolCodeBlock block)
138 bool locked = bql_locked();
151 // Mac to QKeyCode conversion
152 static const int mac_to_qkeycode_map[] = {
153 [kVK_ANSI_A] = Q_KEY_CODE_A,
154 [kVK_ANSI_B] = Q_KEY_CODE_B,
155 [kVK_ANSI_C] = Q_KEY_CODE_C,
156 [kVK_ANSI_D] = Q_KEY_CODE_D,
157 [kVK_ANSI_E] = Q_KEY_CODE_E,
158 [kVK_ANSI_F] = Q_KEY_CODE_F,
159 [kVK_ANSI_G] = Q_KEY_CODE_G,
160 [kVK_ANSI_H] = Q_KEY_CODE_H,
161 [kVK_ANSI_I] = Q_KEY_CODE_I,
162 [kVK_ANSI_J] = Q_KEY_CODE_J,
163 [kVK_ANSI_K] = Q_KEY_CODE_K,
164 [kVK_ANSI_L] = Q_KEY_CODE_L,
165 [kVK_ANSI_M] = Q_KEY_CODE_M,
166 [kVK_ANSI_N] = Q_KEY_CODE_N,
167 [kVK_ANSI_O] = Q_KEY_CODE_O,
168 [kVK_ANSI_P] = Q_KEY_CODE_P,
169 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
170 [kVK_ANSI_R] = Q_KEY_CODE_R,
171 [kVK_ANSI_S] = Q_KEY_CODE_S,
172 [kVK_ANSI_T] = Q_KEY_CODE_T,
173 [kVK_ANSI_U] = Q_KEY_CODE_U,
174 [kVK_ANSI_V] = Q_KEY_CODE_V,
175 [kVK_ANSI_W] = Q_KEY_CODE_W,
176 [kVK_ANSI_X] = Q_KEY_CODE_X,
177 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
178 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
180 [kVK_ANSI_0] = Q_KEY_CODE_0,
181 [kVK_ANSI_1] = Q_KEY_CODE_1,
182 [kVK_ANSI_2] = Q_KEY_CODE_2,
183 [kVK_ANSI_3] = Q_KEY_CODE_3,
184 [kVK_ANSI_4] = Q_KEY_CODE_4,
185 [kVK_ANSI_5] = Q_KEY_CODE_5,
186 [kVK_ANSI_6] = Q_KEY_CODE_6,
187 [kVK_ANSI_7] = Q_KEY_CODE_7,
188 [kVK_ANSI_8] = Q_KEY_CODE_8,
189 [kVK_ANSI_9] = Q_KEY_CODE_9,
191 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
192 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
193 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
194 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
195 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
196 [kVK_Tab] = Q_KEY_CODE_TAB,
197 [kVK_Return] = Q_KEY_CODE_RET,
198 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
199 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
200 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
201 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
202 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
203 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
204 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
205 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
206 [kVK_Space] = Q_KEY_CODE_SPC,
208 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
209 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
210 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
211 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
212 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
213 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
214 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
215 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
216 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
217 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
218 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
219 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
220 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
221 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
222 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
223 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
224 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
225 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
227 [kVK_UpArrow] = Q_KEY_CODE_UP,
228 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
229 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
230 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
232 [kVK_Help] = Q_KEY_CODE_INSERT,
233 [kVK_Home] = Q_KEY_CODE_HOME,
234 [kVK_PageUp] = Q_KEY_CODE_PGUP,
235 [kVK_PageDown] = Q_KEY_CODE_PGDN,
236 [kVK_End] = Q_KEY_CODE_END,
237 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
239 [kVK_Escape] = Q_KEY_CODE_ESC,
241 /* The Power key can't be used directly because the operating system uses
242 * it. This key can be emulated by using it in place of another key such as
243 * F1. Don't forget to disable the real key binding.
245 /* [kVK_F1] = Q_KEY_CODE_POWER, */
247 [kVK_F1] = Q_KEY_CODE_F1,
248 [kVK_F2] = Q_KEY_CODE_F2,
249 [kVK_F3] = Q_KEY_CODE_F3,
250 [kVK_F4] = Q_KEY_CODE_F4,
251 [kVK_F5] = Q_KEY_CODE_F5,
252 [kVK_F6] = Q_KEY_CODE_F6,
253 [kVK_F7] = Q_KEY_CODE_F7,
254 [kVK_F8] = Q_KEY_CODE_F8,
255 [kVK_F9] = Q_KEY_CODE_F9,
256 [kVK_F10] = Q_KEY_CODE_F10,
257 [kVK_F11] = Q_KEY_CODE_F11,
258 [kVK_F12] = Q_KEY_CODE_F12,
259 [kVK_F13] = Q_KEY_CODE_PRINT,
260 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
261 [kVK_F15] = Q_KEY_CODE_PAUSE,
263 // JIS keyboards only
264 [kVK_JIS_Yen] = Q_KEY_CODE_YEN,
265 [kVK_JIS_Underscore] = Q_KEY_CODE_RO,
266 [kVK_JIS_KeypadComma] = Q_KEY_CODE_KP_COMMA,
267 [kVK_JIS_Eisu] = Q_KEY_CODE_MUHENKAN,
268 [kVK_JIS_Kana] = Q_KEY_CODE_HENKAN,
271 * The eject and volume keys can't be used here because they are handled at
272 * a lower level than what an Application can see.
276 static int cocoa_keycode_to_qemu(int keycode)
278 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
279 error_report("(cocoa) warning unknown keycode 0x%x", keycode);
282 return mac_to_qkeycode_map[keycode];
285 /* Displays an alert dialog box with the specified message */
286 static void QEMU_Alert(NSString *message)
289 alert = [NSAlert new];
290 [alert setMessageText: message];
294 /* Handles any errors that happen with a device transaction */
295 static void handleAnyDeviceErrors(Error * err)
298 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
299 encoding: NSASCIIStringEncoding]);
305 ------------------------------------------------------
307 ------------------------------------------------------
309 @interface QemuCocoaView : NSView
312 NSWindow *fullScreenWindow;
313 float cx,cy,cw,ch,cdx,cdy;
314 pixman_image_t *pixman_image;
318 BOOL isAbsoluteEnabled;
319 CFMachPortRef eventsTap;
321 - (void) switchSurface:(pixman_image_t *)image;
323 - (void) ungrabMouse;
324 - (void) toggleFullScreen:(id)sender;
325 - (void) setFullGrab:(id)sender;
326 - (void) handleMonitorInput:(NSEvent *)event;
327 - (bool) handleEvent:(NSEvent *)event;
328 - (bool) handleEventLocked:(NSEvent *)event;
329 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
330 /* The state surrounding mouse grabbing is potentially confusing.
331 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
332 * pointing device an absolute-position one?"], but is only updated on
334 * isMouseGrabbed tracks whether GUI events are directed to the guest;
335 * it controls whether special keys like Cmd get sent to the guest,
336 * and whether we capture the mouse when in non-absolute mode.
338 - (BOOL) isMouseGrabbed;
339 - (BOOL) isAbsoluteEnabled;
342 - (QEMUScreen) gscreen;
343 - (void) raiseAllKeys;
346 QemuCocoaView *cocoaView;
348 static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEventRef cgEvent, void *userInfo)
350 QemuCocoaView *view = userInfo;
351 NSEvent *event = [NSEvent eventWithCGEvent:cgEvent];
352 if ([view isMouseGrabbed] && [view handleEvent:event]) {
353 COCOA_DEBUG("Global events tap: qemu handled the event, capturing!\n");
356 COCOA_DEBUG("Global events tap: qemu did not handle the event, letting it through...\n");
361 @implementation QemuCocoaView
362 - (id)initWithFrame:(NSRect)frameRect
364 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
366 self = [super initWithFrame:frameRect];
369 screen.width = frameRect.size.width;
370 screen.height = frameRect.size.height;
371 kbd = qkbd_state_init(dcl.con);
372 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_14_0
373 [self setClipsToBounds:YES];
382 COCOA_DEBUG("QemuCocoaView: dealloc\n");
385 pixman_image_unref(pixman_image);
388 qkbd_state_free(kbd);
391 CFRelease(eventsTap);
402 - (BOOL) screenContainsPoint:(NSPoint) p
404 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
407 /* Get location of event and convert to virtual screen coordinate */
408 - (CGPoint) screenLocationOfEvent:(NSEvent *)ev
410 NSWindow *eventWindow = [ev window];
411 // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
412 CGRect r = CGRectZero;
413 r.origin = [ev locationInWindow];
416 return [[self window] convertRectFromScreen:r].origin;
418 CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
419 CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
426 } else if ([[self window] isEqual:eventWindow]) {
430 CGPoint loc = [self convertPoint:r.origin fromView:nil];
438 return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
450 - (void) unhideCursor
458 - (void) drawRect:(NSRect) rect
460 COCOA_DEBUG("QemuCocoaView: drawRect\n");
462 // get CoreGraphic context
463 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
465 CGContextSetInterpolationQuality (viewContextRef, zoom_interpolation);
466 CGContextSetShouldAntialias (viewContextRef, NO);
468 // draw screen bitmap directly to Core Graphics context
470 // Draw request before any guest device has set up a framebuffer:
471 // just draw an opaque black rectangle
472 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
473 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
475 int w = pixman_image_get_width(pixman_image);
476 int h = pixman_image_get_height(pixman_image);
477 int bitsPerPixel = PIXMAN_FORMAT_BPP(pixman_image_get_format(pixman_image));
478 int stride = pixman_image_get_stride(pixman_image);
479 CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(
481 pixman_image_get_data(pixman_image),
485 CGImageRef imageRef = CGImageCreate(
488 DIV_ROUND_UP(bitsPerPixel, 8) * 2, //bitsPerComponent
489 bitsPerPixel, //bitsPerPixel
490 stride, //bytesPerRow
491 CGColorSpaceCreateWithName(kCGColorSpaceSRGB), //colorspace
492 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst, //bitmapInfo
493 dataProviderRef, //provider
496 kCGRenderingIntentDefault //intent
498 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
499 const NSRect *rectList;
502 CGImageRef clipImageRef;
505 [self getRectsBeingDrawn:&rectList count:&rectCount];
506 for (i = 0; i < rectCount; i++) {
507 clipRect = rectList[i];
508 clipRect.origin.y = (float)h - (clipRect.origin.y + clipRect.size.height);
509 clipImageRef = CGImageCreateWithImageInRect(
513 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
514 CGImageRelease (clipImageRef);
516 CGImageRelease (imageRef);
517 CGDataProviderRelease(dataProviderRef);
521 - (void) setContentDimensions
523 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
526 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
527 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
529 /* stretches video, but keeps same aspect ratio */
530 if (stretch_video == true) {
531 /* use smallest stretch value - prevents clipping on sides */
532 if (MIN(cdx, cdy) == cdx) {
537 } else { /* No stretching */
540 cw = screen.width * cdx;
541 ch = screen.height * cdy;
542 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
543 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
554 - (void) updateBounds
556 [self setBoundsSize:NSMakeSize(screen.width, screen.height)];
559 - (void) updateUIInfoLocked
561 /* Must be called with the BQL, i.e. via updateUIInfo */
565 if (!qemu_console_is_graphic(dcl.con)) {
570 NSDictionary *description = [[[self window] screen] deviceDescription];
571 CGDirectDisplayID display = [[description objectForKey:@"NSScreenNumber"] unsignedIntValue];
572 NSSize screenSize = [[[self window] screen] frame].size;
573 CGSize screenPhysicalSize = CGDisplayScreenSize(display);
574 CVDisplayLinkRef displayLink;
576 frameSize = isFullscreen ? screenSize : [self frame].size;
578 if (!CVDisplayLinkCreateWithCGDisplay(display, &displayLink)) {
579 CVTime period = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLink);
580 CVDisplayLinkRelease(displayLink);
581 if (!(period.flags & kCVTimeIsIndefinite)) {
582 update_displaychangelistener(&dcl,
583 1000 * period.timeValue / period.timeScale);
584 info.refresh_rate = (int64_t)1000 * period.timeScale / period.timeValue;
588 info.width_mm = frameSize.width / screenSize.width * screenPhysicalSize.width;
589 info.height_mm = frameSize.height / screenSize.height * screenPhysicalSize.height;
591 frameSize = [self frame].size;
598 info.width = frameSize.width;
599 info.height = frameSize.height;
601 dpy_set_ui_info(dcl.con, &info, TRUE);
604 - (void) updateUIInfo
608 * Don't try to tell QEMU about UI information in the application
609 * startup phase -- we haven't yet registered dcl with the QEMU UI
611 * When cocoa_display_init() does register the dcl, the UI layer
612 * will call cocoa_switch(), which will call updateUIInfo, so
613 * we don't lose any information here.
619 [self updateUIInfoLocked];
623 - (void)viewDidMoveToWindow
628 - (void) switchSurface:(pixman_image_t *)image
630 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
632 int w = pixman_image_get_width(image);
633 int h = pixman_image_get_height(image);
634 /* cdx == 0 means this is our very first surface, in which case we need
635 * to recalculate the content dimensions even if it happens to be the size
636 * of the initial empty window.
638 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
640 int oldh = screen.height;
642 // Resize before we trigger the redraw, or we'll redraw at the wrong size
643 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
646 [self setContentDimensions];
647 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
651 // update screenBuffer
653 pixman_image_unref(pixman_image);
656 pixman_image = image;
660 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
661 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
664 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
665 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
669 [normalWindow center];
673 - (void) toggleFullScreen:(id)sender
675 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
677 if (isFullscreen) { // switch from fullscreen to desktop
678 isFullscreen = FALSE;
680 [self setContentDimensions];
681 [fullScreenWindow close];
682 [normalWindow setContentView: self];
683 [normalWindow makeKeyAndOrderFront: self];
684 [NSMenu setMenuBarVisible:YES];
685 } else { // switch from desktop to fullscreen
687 [normalWindow orderOut: nil]; /* Hide the window */
689 [self setContentDimensions];
690 [NSMenu setMenuBarVisible:NO];
691 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
692 styleMask:NSWindowStyleMaskBorderless
693 backing:NSBackingStoreBuffered
695 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
696 [fullScreenWindow setHasShadow:NO];
697 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
698 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
699 [[fullScreenWindow contentView] addSubview: self];
700 [fullScreenWindow makeKeyAndOrderFront:self];
704 - (void) setFullGrab:(id)sender
706 COCOA_DEBUG("QemuCocoaView: setFullGrab\n");
708 CGEventMask mask = CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp) | CGEventMaskBit(kCGEventFlagsChanged);
709 eventsTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault,
710 mask, handleTapEvent, self);
712 warn_report("Could not create event tap, system key combos will not be captured.\n");
715 COCOA_DEBUG("Global events tap created! Will capture system key combos.\n");
718 CFRunLoopRef runLoop = CFRunLoopGetCurrent();
720 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
724 CFRunLoopSourceRef tapEventsSrc = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventsTap, 0);
725 if (!tapEventsSrc ) {
726 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
730 CFRunLoopAddSource(runLoop, tapEventsSrc, kCFRunLoopDefaultMode);
731 CFRelease(tapEventsSrc);
734 - (void) toggleKey: (int)keycode {
735 qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode));
738 // Does the work of sending input to the monitor
739 - (void) handleMonitorInput:(NSEvent *)event
744 // if the control key is down
745 if ([event modifierFlags] & NSEventModifierFlagControl) {
749 /* translates Macintosh keycodes to QEMU's keysym */
751 static const int without_control_translation[] = {
752 [0 ... 0xff] = 0, // invalid key
754 [kVK_UpArrow] = QEMU_KEY_UP,
755 [kVK_DownArrow] = QEMU_KEY_DOWN,
756 [kVK_RightArrow] = QEMU_KEY_RIGHT,
757 [kVK_LeftArrow] = QEMU_KEY_LEFT,
758 [kVK_Home] = QEMU_KEY_HOME,
759 [kVK_End] = QEMU_KEY_END,
760 [kVK_PageUp] = QEMU_KEY_PAGEUP,
761 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
762 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
763 [kVK_Delete] = QEMU_KEY_BACKSPACE,
766 static const int with_control_translation[] = {
767 [0 ... 0xff] = 0, // invalid key
769 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
770 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
771 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
772 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
773 [kVK_Home] = QEMU_KEY_CTRL_HOME,
774 [kVK_End] = QEMU_KEY_CTRL_END,
775 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
776 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
779 if (control_key != 0) { /* If the control key is being used */
780 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
781 keysym = with_control_translation[[event keyCode]];
784 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
785 keysym = without_control_translation[[event keyCode]];
789 // if not a key that needs translating
791 NSString *ks = [event characters];
792 if ([ks length] > 0) {
793 keysym = [ks characterAtIndex:0];
798 qemu_text_console_put_keysym(NULL, keysym);
802 - (bool) handleEvent:(NSEvent *)event
804 return bool_with_bql(^{
805 return [self handleEventLocked:event];
809 - (bool) handleEventLocked:(NSEvent *)event
811 /* Return true if we handled the event, false if it should be given to OSX */
812 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
815 // Location of event in virtual screen coordinates
816 NSPoint p = [self screenLocationOfEvent:event];
817 NSUInteger modifiers = [event modifierFlags];
820 * Check -[NSEvent modifierFlags] here.
822 * There is a NSEventType for an event notifying the change of
823 * -[NSEvent modifierFlags], NSEventTypeFlagsChanged but these operations
824 * are performed for any events because a modifier state may change while
825 * the application is inactive (i.e. no events fire) and we don't want to
826 * wait for another modifier state change to detect such a change.
828 * NSEventModifierFlagCapsLock requires a special treatment. The other flags
829 * are handled in similar manners.
831 * NSEventModifierFlagCapsLock
832 * ---------------------------
834 * If CapsLock state is changed, "up" and "down" events will be fired in
835 * sequence, effectively updates CapsLock state on the guest.
840 * If a flag is not set, fire "up" events for all keys which correspond to
841 * the flag. Note that "down" events are not fired here because the flags
842 * checked here do not tell what exact keys are down.
844 * If one of the keys corresponding to a flag is down, we rely on
845 * -[NSEvent keyCode] of an event whose -[NSEvent type] is
846 * NSEventTypeFlagsChanged to know the exact key which is down, which has
847 * the following two downsides:
848 * - It does not work when the application is inactive as described above.
849 * - It malfactions *after* the modifier state is changed while the
850 * application is inactive. It is because -[NSEvent keyCode] does not tell
851 * if the key is up or down, and requires to infer the current state from
852 * the previous state. It is still possible to fix such a malfanction by
853 * completely leaving your hands from the keyboard, which hopefully makes
854 * this implementation usable enough.
856 if (!!(modifiers & NSEventModifierFlagCapsLock) !=
857 qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) {
858 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true);
859 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false);
862 if (!(modifiers & NSEventModifierFlagShift)) {
863 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false);
864 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false);
866 if (!(modifiers & NSEventModifierFlagControl)) {
867 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false);
868 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false);
870 if (!(modifiers & NSEventModifierFlagOption)) {
872 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
873 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
875 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
876 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
879 if (!(modifiers & NSEventModifierFlagCommand)) {
881 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
882 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
884 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
885 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
889 switch ([event type]) {
890 case NSEventTypeFlagsChanged:
891 switch ([event keyCode]) {
893 if (!!(modifiers & NSEventModifierFlagShift)) {
894 [self toggleKey:Q_KEY_CODE_SHIFT];
899 if (!!(modifiers & NSEventModifierFlagShift)) {
900 [self toggleKey:Q_KEY_CODE_SHIFT_R];
905 if (!!(modifiers & NSEventModifierFlagControl)) {
906 [self toggleKey:Q_KEY_CODE_CTRL];
910 case kVK_RightControl:
911 if (!!(modifiers & NSEventModifierFlagControl)) {
912 [self toggleKey:Q_KEY_CODE_CTRL_R];
917 if (!!(modifiers & NSEventModifierFlagOption)) {
919 [self toggleKey:Q_KEY_CODE_META_L];
921 [self toggleKey:Q_KEY_CODE_ALT];
926 case kVK_RightOption:
927 if (!!(modifiers & NSEventModifierFlagOption)) {
929 [self toggleKey:Q_KEY_CODE_META_R];
931 [self toggleKey:Q_KEY_CODE_ALT_R];
936 /* Don't pass command key changes to guest unless mouse is grabbed */
938 if (isMouseGrabbed &&
939 !!(modifiers & NSEventModifierFlagCommand) &&
940 left_command_key_enabled) {
942 [self toggleKey:Q_KEY_CODE_ALT];
944 [self toggleKey:Q_KEY_CODE_META_L];
949 case kVK_RightCommand:
950 if (isMouseGrabbed &&
951 !!(modifiers & NSEventModifierFlagCommand)) {
953 [self toggleKey:Q_KEY_CODE_ALT_R];
955 [self toggleKey:Q_KEY_CODE_META_R];
961 case NSEventTypeKeyDown:
962 keycode = cocoa_keycode_to_qemu([event keyCode]);
964 // forward command key combos to the host UI unless the mouse is grabbed
965 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
971 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
972 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
973 NSString *keychar = [event charactersIgnoringModifiers];
974 if ([keychar length] == 1) {
975 char key = [keychar characterAtIndex:0];
978 // enable graphic console
980 console_select(key - '0' - 1); /* ascii math */
983 // release the mouse grab
991 if (qemu_console_is_graphic(NULL)) {
992 qkbd_state_key_event(kbd, keycode, true);
994 [self handleMonitorInput: event];
997 case NSEventTypeKeyUp:
998 keycode = cocoa_keycode_to_qemu([event keyCode]);
1000 // don't pass the guest a spurious key-up if we treated this
1001 // command-key combo as a host UI action
1002 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
1006 if (qemu_console_is_graphic(NULL)) {
1007 qkbd_state_key_event(kbd, keycode, false);
1010 case NSEventTypeMouseMoved:
1011 if (isAbsoluteEnabled) {
1012 // Cursor re-entered into a window might generate events bound to screen coordinates
1013 // and `nil` window property, and in full screen mode, current window might not be
1014 // key window, where event location alone should suffice.
1015 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
1016 if (isMouseGrabbed) {
1020 if (!isMouseGrabbed) {
1025 return [self handleMouseEvent:event];
1026 case NSEventTypeLeftMouseDown:
1027 return [self handleMouseEvent:event button:INPUT_BUTTON_LEFT down:true];
1028 case NSEventTypeRightMouseDown:
1029 return [self handleMouseEvent:event button:INPUT_BUTTON_RIGHT down:true];
1030 case NSEventTypeOtherMouseDown:
1031 return [self handleMouseEvent:event button:INPUT_BUTTON_MIDDLE down:true];
1032 case NSEventTypeLeftMouseDragged:
1033 return [self handleMouseEvent:event button:INPUT_BUTTON_LEFT down:true];
1034 case NSEventTypeRightMouseDragged:
1035 return [self handleMouseEvent:event button:INPUT_BUTTON_RIGHT down:true];
1036 case NSEventTypeOtherMouseDragged:
1037 return [self handleMouseEvent:event button:INPUT_BUTTON_MIDDLE down:true];
1038 case NSEventTypeLeftMouseUp:
1039 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
1041 * In fullscreen mode, the window of cocoaView may not be the
1042 * key window, therefore the position relative to the virtual
1043 * screen alone will be sufficient.
1045 if(isFullscreen || [[self window] isKeyWindow]) {
1049 return [self handleMouseEvent:event button:INPUT_BUTTON_LEFT down:false];
1050 case NSEventTypeRightMouseUp:
1051 return [self handleMouseEvent:event button:INPUT_BUTTON_RIGHT down:false];
1052 case NSEventTypeOtherMouseUp:
1053 return [self handleMouseEvent:event button:INPUT_BUTTON_MIDDLE down:false];
1054 case NSEventTypeScrollWheel:
1056 * Send wheel events to the guest regardless of window focus.
1057 * This is in-line with standard Mac OS X UI behaviour.
1060 /* Determine if this is a scroll up or scroll down event */
1061 if ([event deltaY] != 0) {
1062 button = ([event deltaY] > 0) ?
1063 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1064 } else if ([event deltaX] != 0) {
1065 button = ([event deltaX] > 0) ?
1066 INPUT_BUTTON_WHEEL_LEFT : INPUT_BUTTON_WHEEL_RIGHT;
1069 * We shouldn't have got a scroll event when deltaY and delta Y
1070 * are zero, hence no harm in dropping the event
1075 qemu_input_queue_btn(dcl.con, button, true);
1076 qemu_input_event_sync();
1077 qemu_input_queue_btn(dcl.con, button, false);
1078 qemu_input_event_sync();
1086 - (bool) handleMouseEvent:(NSEvent *)event button:(InputButton)button down:(bool)down
1088 /* Don't send button events to the guest unless we've got a
1089 * mouse grab or window focus. If we have neither then this event
1090 * is the user clicking on the background window to activate and
1091 * bring us to the front, which will be done by the sendEvent
1092 * call below. We definitely don't want to pass that click through
1095 if (!isMouseGrabbed && ![[self window] isKeyWindow]) {
1099 qemu_input_queue_btn(dcl.con, button, down);
1101 return [self handleMouseEvent:event];
1104 - (bool) handleMouseEvent:(NSEvent *)event
1106 if (!isMouseGrabbed) {
1110 if (isAbsoluteEnabled) {
1111 NSPoint p = [self screenLocationOfEvent:event];
1113 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
1114 * The check on screenContainsPoint is to avoid sending out of range values for
1115 * clicks in the titlebar.
1117 if ([self screenContainsPoint:p]) {
1118 qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x, 0, screen.width);
1119 qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
1122 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, (int)[event deltaX]);
1123 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, (int)[event deltaY]);
1126 qemu_input_event_sync();
1133 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
1135 if (!isFullscreen) {
1137 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press " UC_CTRL_KEY " " UC_ALT_KEY " G to release Mouse)", qemu_name]];
1139 [normalWindow setTitle:@"QEMU - (Press " UC_CTRL_KEY " " UC_ALT_KEY " G to release Mouse)"];
1142 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1143 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
1146 - (void) ungrabMouse
1148 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
1150 if (!isFullscreen) {
1152 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
1154 [normalWindow setTitle:@"QEMU"];
1156 [self unhideCursor];
1157 CGAssociateMouseAndMouseCursorPosition(TRUE);
1158 isMouseGrabbed = FALSE;
1161 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {
1162 isAbsoluteEnabled = tIsAbsoluteEnabled;
1163 if (isMouseGrabbed) {
1164 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1167 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
1168 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
1169 - (float) cdx {return cdx;}
1170 - (float) cdy {return cdy;}
1171 - (QEMUScreen) gscreen {return screen;}
1174 * Makes the target think all down keys are being released.
1175 * This prevents a stuck key problem, since we will not see
1176 * key up events for those keys after we have lost focus.
1178 - (void) raiseAllKeys
1181 qkbd_state_lift_all_keys(kbd);
1189 ------------------------------------------------------
1190 QemuCocoaAppController
1191 ------------------------------------------------------
1193 @interface QemuCocoaAppController : NSObject
1194 <NSWindowDelegate, NSApplicationDelegate>
1197 - (void)doToggleFullScreen:(id)sender;
1198 - (void)toggleFullScreen:(id)sender;
1199 - (void)showQEMUDoc:(id)sender;
1200 - (void)zoomToFit:(id) sender;
1201 - (void)displayConsole:(id)sender;
1202 - (void)pauseQEMU:(id)sender;
1203 - (void)resumeQEMU:(id)sender;
1204 - (void)displayPause;
1205 - (void)removePause;
1206 - (void)restartQEMU:(id)sender;
1207 - (void)powerDownQEMU:(id)sender;
1208 - (void)ejectDeviceMedia:(id)sender;
1209 - (void)changeDeviceMedia:(id)sender;
1211 - (void)openDocumentation:(NSString *)filename;
1212 - (IBAction) do_about_menu_item: (id) sender;
1213 - (void)adjustSpeed:(id)sender;
1216 @implementation QemuCocoaAppController
1219 COCOA_DEBUG("QemuCocoaAppController: init\n");
1221 self = [super init];
1224 // create a view and add it to the window
1225 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1227 error_report("(cocoa) can't create a view");
1232 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
1233 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
1234 backing:NSBackingStoreBuffered defer:NO];
1236 error_report("(cocoa) can't create window");
1239 [normalWindow setAcceptsMouseMovedEvents:YES];
1240 [normalWindow setTitle:@"QEMU"];
1241 [normalWindow setContentView:cocoaView];
1242 [normalWindow makeKeyAndOrderFront:self];
1243 [normalWindow center];
1244 [normalWindow setDelegate: self];
1246 /* Used for displaying pause on the screen */
1247 pauseLabel = [NSTextField new];
1248 [pauseLabel setBezeled:YES];
1249 [pauseLabel setDrawsBackground:YES];
1250 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1251 [pauseLabel setEditable:NO];
1252 [pauseLabel setSelectable:NO];
1253 [pauseLabel setStringValue: @"Paused"];
1254 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1255 [pauseLabel setTextColor: [NSColor blackColor]];
1256 [pauseLabel sizeToFit];
1263 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1266 [cocoaView release];
1270 - (void)applicationDidFinishLaunching: (NSNotification *) note
1272 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1273 allow_events = true;
1276 - (void)applicationWillTerminate:(NSNotification *)aNotification
1278 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1281 shutdown_action = SHUTDOWN_ACTION_POWEROFF;
1282 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1286 * Sleep here, because returning will cause OSX to kill us
1287 * immediately; the QEMU main loop will handle the shutdown
1288 * request and terminate the process.
1290 [NSThread sleepForTimeInterval:INFINITY];
1293 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1298 - (NSApplicationTerminateReply)applicationShouldTerminate:
1299 (NSApplication *)sender
1301 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1302 return [self verifyQuit];
1305 - (void)windowDidChangeScreen:(NSNotification *)notification
1307 [cocoaView updateUIInfo];
1310 - (void)windowDidResize:(NSNotification *)notification
1312 [cocoaView updateBounds];
1313 [cocoaView updateUIInfo];
1316 /* Called when the user clicks on a window's close button */
1317 - (BOOL)windowShouldClose:(id)sender
1319 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1320 [NSApp terminate: sender];
1321 /* If the user allows the application to quit then the call to
1322 * NSApp terminate will never return. If we get here then the user
1323 * cancelled the quit, so we should return NO to not permit the
1324 * closing of this window.
1330 * Called when QEMU goes into the background. Note that
1331 * [-NSWindowDelegate windowDidResignKey:] is used here instead of
1332 * [-NSApplicationDelegate applicationWillResignActive:] because it cannot
1333 * detect that the window loses focus when the deck is clicked on macOS 13.2.1.
1335 - (void) windowDidResignKey: (NSNotification *)aNotification
1337 COCOA_DEBUG("%s\n", __func__);
1338 [cocoaView ungrabMouse];
1339 [cocoaView raiseAllKeys];
1342 /* We abstract the method called by the Enter Fullscreen menu item
1343 * because Mac OS 10.7 and higher disables it. This is because of the
1344 * menu item's old selector's name toggleFullScreen:
1346 - (void) doToggleFullScreen:(id)sender
1348 [self toggleFullScreen:(id)sender];
1351 - (void)toggleFullScreen:(id)sender
1353 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1355 [cocoaView toggleFullScreen:sender];
1358 - (void) setFullGrab:(id)sender
1360 COCOA_DEBUG("QemuCocoaAppController: setFullGrab\n");
1362 [cocoaView setFullGrab:sender];
1365 /* Tries to find then open the specified filename */
1366 - (void) openDocumentation: (NSString *) filename
1368 /* Where to look for local files */
1369 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
1370 NSString *full_file_path;
1371 NSURL *full_file_url;
1373 /* iterate thru the possible paths until the file is found */
1375 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1376 full_file_path = [[NSBundle mainBundle] executablePath];
1377 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1378 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1379 path_array[index], filename];
1380 full_file_url = [NSURL fileURLWithPath: full_file_path
1381 isDirectory: false];
1382 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
1387 /* If none of the paths opened a file */
1389 QEMU_Alert(@"Failed to open file");
1392 - (void)showQEMUDoc:(id)sender
1394 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1396 [self openDocumentation: @"index.html"];
1399 /* Stretches video to fit host monitor size */
1400 - (void)zoomToFit:(id) sender
1402 stretch_video = !stretch_video;
1403 if (stretch_video == true) {
1404 [sender setState: NSControlStateValueOn];
1406 [sender setState: NSControlStateValueOff];
1410 - (void)toggleZoomInterpolation:(id) sender
1412 if (zoom_interpolation == kCGInterpolationNone) {
1413 zoom_interpolation = kCGInterpolationLow;
1414 [sender setState: NSControlStateValueOn];
1416 zoom_interpolation = kCGInterpolationNone;
1417 [sender setState: NSControlStateValueOff];
1421 /* Displays the console on the screen */
1422 - (void)displayConsole:(id)sender
1424 console_select([sender tag]);
1427 /* Pause the guest */
1428 - (void)pauseQEMU:(id)sender
1433 [sender setEnabled: NO];
1434 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1435 [self displayPause];
1438 /* Resume running the guest operating system */
1439 - (void)resumeQEMU:(id) sender
1444 [sender setEnabled: NO];
1445 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1449 /* Displays the word pause on the screen */
1450 - (void)displayPause
1452 /* Coordinates have to be calculated each time because the window can change its size */
1453 int xCoord, yCoord, width, height;
1454 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1455 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1456 width = [pauseLabel frame].size.width;
1457 height = [pauseLabel frame].size.height;
1458 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1459 [cocoaView addSubview: pauseLabel];
1462 /* Removes the word pause from the screen */
1465 [pauseLabel removeFromSuperview];
1469 - (void)restartQEMU:(id)sender
1472 qmp_system_reset(NULL);
1476 /* Powers down QEMU */
1477 - (void)powerDownQEMU:(id)sender
1480 qmp_system_powerdown(NULL);
1484 /* Ejects the media.
1485 * Uses sender's tag to figure out the device to eject.
1487 - (void)ejectDeviceMedia:(id)sender
1490 drive = [sender representedObject];
1493 QEMU_Alert(@"Failed to find drive to eject!");
1497 __block Error *err = NULL;
1499 qmp_eject([drive cStringUsingEncoding: NSASCIIStringEncoding],
1500 NULL, false, false, &err);
1502 handleAnyDeviceErrors(err);
1505 /* Displays a dialog box asking the user to select an image file to load.
1506 * Uses sender's represented object value to figure out which drive to use.
1508 - (void)changeDeviceMedia:(id)sender
1510 /* Find the drive name */
1512 drive = [sender representedObject];
1515 QEMU_Alert(@"Could not find drive!");
1519 /* Display the file open dialog */
1520 NSOpenPanel * openPanel;
1521 openPanel = [NSOpenPanel openPanel];
1522 [openPanel setCanChooseFiles: YES];
1523 [openPanel setAllowsMultipleSelection: NO];
1524 if([openPanel runModal] == NSModalResponseOK) {
1525 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1528 QEMU_Alert(@"Failed to convert URL to file path!");
1532 __block Error *err = NULL;
1534 qmp_blockdev_change_medium([drive cStringUsingEncoding:
1535 NSASCIIStringEncoding],
1537 [file cStringUsingEncoding:
1538 NSASCIIStringEncoding],
1544 handleAnyDeviceErrors(err);
1548 /* Verifies if the user really wants to quit */
1551 NSAlert *alert = [NSAlert new];
1552 [alert autorelease];
1553 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1554 [alert addButtonWithTitle: @"Cancel"];
1555 [alert addButtonWithTitle: @"Quit"];
1556 if([alert runModal] == NSAlertSecondButtonReturn) {
1563 /* The action method for the About menu item */
1564 - (IBAction) do_about_menu_item: (id) sender
1566 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1567 char *icon_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1568 NSString *icon_path = [NSString stringWithUTF8String:icon_path_c];
1569 g_free(icon_path_c);
1570 NSImage *icon = [[NSImage alloc] initWithContentsOfFile:icon_path];
1571 NSString *version = @"QEMU emulator version " QEMU_FULL_VERSION;
1572 NSString *copyright = @QEMU_COPYRIGHT;
1573 NSDictionary *options;
1576 NSAboutPanelOptionApplicationIcon : icon,
1577 NSAboutPanelOptionApplicationVersion : version,
1578 @"Copyright" : copyright,
1583 NSAboutPanelOptionApplicationVersion : version,
1584 @"Copyright" : copyright,
1587 [NSApp orderFrontStandardAboutPanelWithOptions:options];
1591 /* Used by the Speed menu items */
1592 - (void)adjustSpeed:(id)sender
1594 int throttle_pct; /* throttle percentage */
1597 menu = [sender menu];
1600 /* Unselect the currently selected item */
1601 for (NSMenuItem *item in [menu itemArray]) {
1602 if (item.state == NSControlStateValueOn) {
1603 [item setState: NSControlStateValueOff];
1609 // check the menu item
1610 [sender setState: NSControlStateValueOn];
1612 // get the throttle percentage
1613 throttle_pct = [sender tag];
1616 cpu_throttle_set(throttle_pct);
1618 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1623 @interface QemuApplication : NSApplication
1626 @implementation QemuApplication
1627 - (void)sendEvent:(NSEvent *)event
1629 COCOA_DEBUG("QemuApplication: sendEvent\n");
1630 if (![cocoaView handleEvent:event]) {
1631 [super sendEvent: event];
1636 static void create_initial_menus(void)
1640 NSMenuItem *menuItem;
1642 [NSApp setMainMenu:[[NSMenu alloc] init]];
1643 [NSApp setServicesMenu:[[NSMenu alloc] initWithTitle:@"Services"]];
1646 menu = [[NSMenu alloc] initWithTitle:@""];
1647 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1648 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1649 menuItem = [menu addItemWithTitle:@"Services" action:nil keyEquivalent:@""];
1650 [menuItem setSubmenu:[NSApp servicesMenu]];
1651 [menu addItem:[NSMenuItem separatorItem]];
1652 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1653 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1654 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1655 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1656 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1657 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1658 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1659 [menuItem setSubmenu:menu];
1660 [[NSApp mainMenu] addItem:menuItem];
1661 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1664 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1665 [menu setAutoenablesItems: NO];
1666 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1667 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1668 [menu addItem: menuItem];
1669 [menuItem setEnabled: NO];
1670 [menu addItem: [NSMenuItem separatorItem]];
1671 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1672 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1673 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1674 [menuItem setSubmenu:menu];
1675 [[NSApp mainMenu] addItem:menuItem];
1678 menu = [[NSMenu alloc] initWithTitle:@"View"];
1679 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1680 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease];
1681 [menuItem setState: stretch_video ? NSControlStateValueOn : NSControlStateValueOff];
1682 [menu addItem: menuItem];
1683 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Zoom Interpolation" action:@selector(toggleZoomInterpolation:) keyEquivalent:@""] autorelease];
1684 [menuItem setState: zoom_interpolation == kCGInterpolationLow ? NSControlStateValueOn : NSControlStateValueOff];
1685 [menu addItem: menuItem];
1686 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1687 [menuItem setSubmenu:menu];
1688 [[NSApp mainMenu] addItem:menuItem];
1691 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1693 // Add the rest of the Speed menu items
1694 int p, percentage, throttle_pct;
1695 for (p = 10; p >= 0; p--)
1697 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1699 menuItem = [[[NSMenuItem alloc]
1700 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1702 if (percentage == 100) {
1703 [menuItem setState: NSControlStateValueOn];
1706 /* Calculate the throttle percentage */
1707 throttle_pct = -1 * percentage + 100;
1709 [menuItem setTag: throttle_pct];
1710 [menu addItem: menuItem];
1712 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1713 [menuItem setSubmenu:menu];
1714 [[NSApp mainMenu] addItem:menuItem];
1717 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1718 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1719 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1720 [menuItem setSubmenu:menu];
1721 [[NSApp mainMenu] addItem:menuItem];
1722 [NSApp setWindowsMenu:menu];
1725 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1726 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1727 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1728 [menuItem setSubmenu:menu];
1729 [[NSApp mainMenu] addItem:menuItem];
1732 /* Returns a name for a given console */
1733 static NSString * getConsoleName(QemuConsole * console)
1735 g_autofree char *label = qemu_console_get_label(console);
1737 return [NSString stringWithUTF8String:label];
1740 /* Add an entry to the View menu for each console */
1741 static void add_console_menu_entries(void)
1744 NSMenuItem *menuItem;
1747 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1749 [menu addItem:[NSMenuItem separatorItem]];
1751 while (qemu_console_lookup_by_index(index) != NULL) {
1752 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1753 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1754 [menuItem setTag: index];
1755 [menu addItem: menuItem];
1760 /* Make menu items for all removable devices.
1761 * Each device is given an 'Eject' and 'Change' menu item.
1763 static void addRemovableDevicesMenuItems(void)
1766 NSMenuItem *menuItem;
1767 BlockInfoList *currentDevice, *pointerToFree;
1768 NSString *deviceName;
1770 currentDevice = qmp_query_block(NULL);
1771 pointerToFree = currentDevice;
1773 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1775 // Add a separator between related groups of menu items
1776 [menu addItem:[NSMenuItem separatorItem]];
1778 // Set the attributes to the "Removable Media" menu item
1779 NSString *titleString = @"Removable Media";
1780 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1781 NSColor *newColor = [NSColor blackColor];
1782 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1783 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1784 traits:NSBoldFontMask|NSItalicFontMask
1787 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1788 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1789 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1791 // Add the "Removable Media" menu item
1792 menuItem = [NSMenuItem new];
1793 [menuItem setAttributedTitle: attString];
1794 [menuItem setEnabled: NO];
1795 [menu addItem: menuItem];
1797 /* Loop through all the block devices in the emulator */
1798 while (currentDevice) {
1799 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1801 if(currentDevice->value->removable) {
1802 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1803 action: @selector(changeDeviceMedia:)
1804 keyEquivalent: @""];
1805 [menu addItem: menuItem];
1806 [menuItem setRepresentedObject: deviceName];
1807 [menuItem autorelease];
1809 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1810 action: @selector(ejectDeviceMedia:)
1811 keyEquivalent: @""];
1812 [menu addItem: menuItem];
1813 [menuItem setRepresentedObject: deviceName];
1814 [menuItem autorelease];
1816 currentDevice = currentDevice->next;
1818 qapi_free_BlockInfoList(pointerToFree);
1821 @interface QemuCocoaPasteboardTypeOwner : NSObject<NSPasteboardTypeOwner>
1824 @implementation QemuCocoaPasteboardTypeOwner
1826 - (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)type
1828 if (type != NSPasteboardTypeString) {
1833 QemuClipboardInfo *info = qemu_clipboard_info_ref(cbinfo);
1834 qemu_event_reset(&cbevent);
1835 qemu_clipboard_request(info, QEMU_CLIPBOARD_TYPE_TEXT);
1837 while (info == cbinfo &&
1838 info->types[QEMU_CLIPBOARD_TYPE_TEXT].available &&
1839 info->types[QEMU_CLIPBOARD_TYPE_TEXT].data == NULL) {
1841 qemu_event_wait(&cbevent);
1845 if (info == cbinfo) {
1846 NSData *data = [[NSData alloc] initWithBytes:info->types[QEMU_CLIPBOARD_TYPE_TEXT].data
1847 length:info->types[QEMU_CLIPBOARD_TYPE_TEXT].size];
1848 [sender setData:data forType:NSPasteboardTypeString];
1852 qemu_clipboard_info_unref(info);
1858 static QemuCocoaPasteboardTypeOwner *cbowner;
1860 static void cocoa_clipboard_notify(Notifier *notifier, void *data);
1861 static void cocoa_clipboard_request(QemuClipboardInfo *info,
1862 QemuClipboardType type);
1864 static QemuClipboardPeer cbpeer = {
1866 .notifier = { .notify = cocoa_clipboard_notify },
1867 .request = cocoa_clipboard_request
1870 static void cocoa_clipboard_update_info(QemuClipboardInfo *info)
1872 if (info->owner == &cbpeer || info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
1876 if (info != cbinfo) {
1877 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1878 qemu_clipboard_info_unref(cbinfo);
1879 cbinfo = qemu_clipboard_info_ref(info);
1880 cbchangecount = [[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:cbowner];
1884 qemu_event_set(&cbevent);
1887 static void cocoa_clipboard_notify(Notifier *notifier, void *data)
1889 QemuClipboardNotify *notify = data;
1891 switch (notify->type) {
1892 case QEMU_CLIPBOARD_UPDATE_INFO:
1893 cocoa_clipboard_update_info(notify->info);
1895 case QEMU_CLIPBOARD_RESET_SERIAL:
1901 static void cocoa_clipboard_request(QemuClipboardInfo *info,
1902 QemuClipboardType type)
1904 NSAutoreleasePool *pool;
1908 case QEMU_CLIPBOARD_TYPE_TEXT:
1909 pool = [[NSAutoreleasePool alloc] init];
1910 text = [[NSPasteboard generalPasteboard] dataForType:NSPasteboardTypeString];
1912 qemu_clipboard_set_data(&cbpeer, info, type,
1913 [text length], [text bytes], true);
1923 * The startup process for the OSX/Cocoa UI is complicated, because
1924 * OSX insists that the UI runs on the initial main thread, and so we
1925 * need to start a second thread which runs the qemu_default_main():
1927 * in cocoa_display_init():
1928 * assign cocoa_main to qemu_main
1929 * create application, menus, etc
1931 * create qemu-main thread
1932 * enter OSX run loop
1935 static void *call_qemu_main(void *opaque)
1939 COCOA_DEBUG("Second thread: calling qemu_default_main()\n");
1941 status = qemu_default_main();
1943 COCOA_DEBUG("Second thread: qemu_default_main() returned, exiting\n");
1948 static int cocoa_main(void)
1952 COCOA_DEBUG("Entered %s()\n", __func__);
1955 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1956 NULL, QEMU_THREAD_DETACHED);
1958 // Start the main event loop
1959 COCOA_DEBUG("Main thread: entering OSX run loop\n");
1961 COCOA_DEBUG("Main thread: left OSX run loop, which should never happen\n");
1969 static void cocoa_update(DisplayChangeListener *dcl,
1970 int x, int y, int w, int h)
1972 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1974 dispatch_async(dispatch_get_main_queue(), ^{
1975 NSRect rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1976 [cocoaView setNeedsDisplayInRect:rect];
1980 static void cocoa_switch(DisplayChangeListener *dcl,
1981 DisplaySurface *surface)
1983 pixman_image_t *image = surface->image;
1985 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1987 // The DisplaySurface will be freed as soon as this callback returns.
1988 // We take a reference to the underlying pixman image here so it does
1989 // not disappear from under our feet; the switchSurface method will
1990 // deref the old image when it is done with it.
1991 pixman_image_ref(image);
1993 dispatch_async(dispatch_get_main_queue(), ^{
1994 [cocoaView updateUIInfo];
1995 [cocoaView switchSurface:image];
1999 static void cocoa_refresh(DisplayChangeListener *dcl)
2001 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2003 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
2004 graphic_hw_update(NULL);
2006 if (qemu_input_is_absolute(dcl->con)) {
2007 dispatch_async(dispatch_get_main_queue(), ^{
2008 if (![cocoaView isAbsoluteEnabled]) {
2009 if ([cocoaView isMouseGrabbed]) {
2010 [cocoaView ungrabMouse];
2013 [cocoaView setAbsoluteEnabled:YES];
2017 if (cbchangecount != [[NSPasteboard generalPasteboard] changeCount]) {
2018 qemu_clipboard_info_unref(cbinfo);
2019 cbinfo = qemu_clipboard_info_new(&cbpeer, QEMU_CLIPBOARD_SELECTION_CLIPBOARD);
2020 if ([[NSPasteboard generalPasteboard] availableTypeFromArray:@[NSPasteboardTypeString]]) {
2021 cbinfo->types[QEMU_CLIPBOARD_TYPE_TEXT].available = true;
2023 qemu_clipboard_update(cbinfo);
2024 cbchangecount = [[NSPasteboard generalPasteboard] changeCount];
2025 qemu_event_set(&cbevent);
2031 static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
2033 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2035 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
2037 qemu_main = cocoa_main;
2039 // Pull this console process up to being a fully-fledged graphical
2040 // app with a menubar and Dock icon
2041 ProcessSerialNumber psn = { 0, kCurrentProcess };
2042 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
2044 [QemuApplication sharedApplication];
2046 // Create an Application controller
2047 QemuCocoaAppController *controller = [[QemuCocoaAppController alloc] init];
2048 [NSApp setDelegate:controller];
2050 /* if fullscreen mode is to be used */
2051 if (opts->has_full_screen && opts->full_screen) {
2052 [NSApp activateIgnoringOtherApps: YES];
2053 [controller toggleFullScreen: nil];
2055 if (opts->u.cocoa.has_full_grab && opts->u.cocoa.full_grab) {
2056 [controller setFullGrab: nil];
2059 if (opts->has_show_cursor && opts->show_cursor) {
2062 if (opts->u.cocoa.has_swap_opt_cmd) {
2063 swap_opt_cmd = opts->u.cocoa.swap_opt_cmd;
2066 if (opts->u.cocoa.has_left_command_key && !opts->u.cocoa.left_command_key) {
2067 left_command_key_enabled = 0;
2070 if (opts->u.cocoa.has_zoom_to_fit && opts->u.cocoa.zoom_to_fit) {
2071 stretch_video = true;
2074 if (opts->u.cocoa.has_zoom_interpolation && opts->u.cocoa.zoom_interpolation) {
2075 zoom_interpolation = kCGInterpolationLow;
2078 create_initial_menus();
2080 * Create the menu entries which depend on QEMU state (for consoles
2081 * and removable devices). These make calls back into QEMU functions,
2082 * which is OK because at this point we know that the second thread
2083 * holds the BQL and is synchronously waiting for us to
2086 add_console_menu_entries();
2087 addRemovableDevicesMenuItems();
2089 // register vga output callbacks
2090 register_displaychangelistener(&dcl);
2092 qemu_event_init(&cbevent, false);
2093 cbowner = [[QemuCocoaPasteboardTypeOwner alloc] init];
2094 qemu_clipboard_peer_register(&cbpeer);
2099 static QemuDisplay qemu_display_cocoa = {
2100 .type = DISPLAY_TYPE_COCOA,
2101 .init = cocoa_display_init,
2104 static void register_cocoa(void)
2106 qemu_display_register(&qemu_display_cocoa);
2109 type_init(register_cocoa);