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/console.h"
33 #include "sysemu/sysemu.h"
34 #include "qapi/error.h"
35 #include "qapi/qapi-commands-block.h"
36 #include "qapi/qapi-commands-misc.h"
37 #include "sysemu/blockdev.h"
38 #include "qemu-version.h"
39 #include <Carbon/Carbon.h>
42 #ifndef MAC_OS_X_VERSION_10_5
43 #define MAC_OS_X_VERSION_10_5 1050
45 #ifndef MAC_OS_X_VERSION_10_6
46 #define MAC_OS_X_VERSION_10_6 1060
48 #ifndef MAC_OS_X_VERSION_10_9
49 #define MAC_OS_X_VERSION_10_9 1090
51 #ifndef MAC_OS_X_VERSION_10_10
52 #define MAC_OS_X_VERSION_10_10 101000
54 #ifndef MAC_OS_X_VERSION_10_12
55 #define MAC_OS_X_VERSION_10_12 101200
57 #ifndef MAC_OS_X_VERSION_10_13
58 #define MAC_OS_X_VERSION_10_13 101300
61 /* macOS 10.12 deprecated many constants, #define the new names for older SDKs */
62 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_12
63 #define NSEventMaskAny NSAnyEventMask
64 #define NSEventModifierFlagCapsLock NSAlphaShiftKeyMask
65 #define NSEventModifierFlagShift NSShiftKeyMask
66 #define NSEventModifierFlagCommand NSCommandKeyMask
67 #define NSEventModifierFlagControl NSControlKeyMask
68 #define NSEventModifierFlagOption NSAlternateKeyMask
69 #define NSEventTypeFlagsChanged NSFlagsChanged
70 #define NSEventTypeKeyUp NSKeyUp
71 #define NSEventTypeKeyDown NSKeyDown
72 #define NSEventTypeMouseMoved NSMouseMoved
73 #define NSEventTypeLeftMouseDown NSLeftMouseDown
74 #define NSEventTypeRightMouseDown NSRightMouseDown
75 #define NSEventTypeOtherMouseDown NSOtherMouseDown
76 #define NSEventTypeLeftMouseDragged NSLeftMouseDragged
77 #define NSEventTypeRightMouseDragged NSRightMouseDragged
78 #define NSEventTypeOtherMouseDragged NSOtherMouseDragged
79 #define NSEventTypeLeftMouseUp NSLeftMouseUp
80 #define NSEventTypeRightMouseUp NSRightMouseUp
81 #define NSEventTypeOtherMouseUp NSOtherMouseUp
82 #define NSEventTypeScrollWheel NSScrollWheel
83 #define NSTextAlignmentCenter NSCenterTextAlignment
84 #define NSWindowStyleMaskBorderless NSBorderlessWindowMask
85 #define NSWindowStyleMaskClosable NSClosableWindowMask
86 #define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask
87 #define NSWindowStyleMaskTitled NSTitledWindowMask
89 /* 10.13 deprecates NSFileHandlingPanelOKButton in favour of
90 * NSModalResponseOK, which was introduced in 10.9. Define
91 * it for older versions.
93 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_9
94 #define NSModalResponseOK NSFileHandlingPanelOKButton
96 /* 10.14 deprecates NSOnState and NSOffState in favor of
97 * NSControlStateValueOn/Off, which were introduced in 10.13.
98 * Define for older versions
100 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
101 #define NSControlStateValueOn NSOnState
102 #define NSControlStateValueOff NSOffState
108 #define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
110 #define COCOA_DEBUG(...) ((void) 0)
113 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
118 int bitsPerComponent;
122 NSWindow *normalWindow, *about_window;
123 static DisplayChangeListener *dcl;
124 static int last_buttons;
129 NSTextField *pauseLabel;
130 NSArray * supportedImageFileTypes;
132 // Utility function to run specified code block with iothread lock held
133 typedef void (^CodeBlock)(void);
135 static void with_iothread_lock(CodeBlock block)
137 bool locked = qemu_mutex_iothread_locked();
139 qemu_mutex_lock_iothread();
143 qemu_mutex_unlock_iothread();
147 // Mac to QKeyCode conversion
148 const int mac_to_qkeycode_map[] = {
149 [kVK_ANSI_A] = Q_KEY_CODE_A,
150 [kVK_ANSI_B] = Q_KEY_CODE_B,
151 [kVK_ANSI_C] = Q_KEY_CODE_C,
152 [kVK_ANSI_D] = Q_KEY_CODE_D,
153 [kVK_ANSI_E] = Q_KEY_CODE_E,
154 [kVK_ANSI_F] = Q_KEY_CODE_F,
155 [kVK_ANSI_G] = Q_KEY_CODE_G,
156 [kVK_ANSI_H] = Q_KEY_CODE_H,
157 [kVK_ANSI_I] = Q_KEY_CODE_I,
158 [kVK_ANSI_J] = Q_KEY_CODE_J,
159 [kVK_ANSI_K] = Q_KEY_CODE_K,
160 [kVK_ANSI_L] = Q_KEY_CODE_L,
161 [kVK_ANSI_M] = Q_KEY_CODE_M,
162 [kVK_ANSI_N] = Q_KEY_CODE_N,
163 [kVK_ANSI_O] = Q_KEY_CODE_O,
164 [kVK_ANSI_P] = Q_KEY_CODE_P,
165 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
166 [kVK_ANSI_R] = Q_KEY_CODE_R,
167 [kVK_ANSI_S] = Q_KEY_CODE_S,
168 [kVK_ANSI_T] = Q_KEY_CODE_T,
169 [kVK_ANSI_U] = Q_KEY_CODE_U,
170 [kVK_ANSI_V] = Q_KEY_CODE_V,
171 [kVK_ANSI_W] = Q_KEY_CODE_W,
172 [kVK_ANSI_X] = Q_KEY_CODE_X,
173 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
174 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
176 [kVK_ANSI_0] = Q_KEY_CODE_0,
177 [kVK_ANSI_1] = Q_KEY_CODE_1,
178 [kVK_ANSI_2] = Q_KEY_CODE_2,
179 [kVK_ANSI_3] = Q_KEY_CODE_3,
180 [kVK_ANSI_4] = Q_KEY_CODE_4,
181 [kVK_ANSI_5] = Q_KEY_CODE_5,
182 [kVK_ANSI_6] = Q_KEY_CODE_6,
183 [kVK_ANSI_7] = Q_KEY_CODE_7,
184 [kVK_ANSI_8] = Q_KEY_CODE_8,
185 [kVK_ANSI_9] = Q_KEY_CODE_9,
187 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
188 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
189 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
190 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
191 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
192 [kVK_Tab] = Q_KEY_CODE_TAB,
193 [kVK_Return] = Q_KEY_CODE_RET,
194 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
195 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
196 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
197 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
198 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
199 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
200 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
201 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
202 [kVK_Shift] = Q_KEY_CODE_SHIFT,
203 [kVK_RightShift] = Q_KEY_CODE_SHIFT_R,
204 [kVK_Control] = Q_KEY_CODE_CTRL,
205 [kVK_RightControl] = Q_KEY_CODE_CTRL_R,
206 [kVK_Option] = Q_KEY_CODE_ALT,
207 [kVK_RightOption] = Q_KEY_CODE_ALT_R,
208 [kVK_Command] = Q_KEY_CODE_META_L,
209 [0x36] = Q_KEY_CODE_META_R, /* There is no kVK_RightCommand */
210 [kVK_Space] = Q_KEY_CODE_SPC,
212 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
213 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
214 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
215 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
216 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
217 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
218 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
219 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
220 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
221 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
222 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
223 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
224 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
225 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
226 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
227 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
228 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
229 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
231 [kVK_UpArrow] = Q_KEY_CODE_UP,
232 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
233 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
234 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
236 [kVK_Help] = Q_KEY_CODE_INSERT,
237 [kVK_Home] = Q_KEY_CODE_HOME,
238 [kVK_PageUp] = Q_KEY_CODE_PGUP,
239 [kVK_PageDown] = Q_KEY_CODE_PGDN,
240 [kVK_End] = Q_KEY_CODE_END,
241 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
243 [kVK_Escape] = Q_KEY_CODE_ESC,
245 /* The Power key can't be used directly because the operating system uses
246 * it. This key can be emulated by using it in place of another key such as
247 * F1. Don't forget to disable the real key binding.
249 /* [kVK_F1] = Q_KEY_CODE_POWER, */
251 [kVK_F1] = Q_KEY_CODE_F1,
252 [kVK_F2] = Q_KEY_CODE_F2,
253 [kVK_F3] = Q_KEY_CODE_F3,
254 [kVK_F4] = Q_KEY_CODE_F4,
255 [kVK_F5] = Q_KEY_CODE_F5,
256 [kVK_F6] = Q_KEY_CODE_F6,
257 [kVK_F7] = Q_KEY_CODE_F7,
258 [kVK_F8] = Q_KEY_CODE_F8,
259 [kVK_F9] = Q_KEY_CODE_F9,
260 [kVK_F10] = Q_KEY_CODE_F10,
261 [kVK_F11] = Q_KEY_CODE_F11,
262 [kVK_F12] = Q_KEY_CODE_F12,
263 [kVK_F13] = Q_KEY_CODE_PRINT,
264 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
265 [kVK_F15] = Q_KEY_CODE_PAUSE,
268 * The eject and volume keys can't be used here because they are handled at
269 * a lower level than what an Application can see.
273 static int cocoa_keycode_to_qemu(int keycode)
275 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
276 fprintf(stderr, "(cocoa) warning unknown keycode 0x%x\n", keycode);
279 return mac_to_qkeycode_map[keycode];
282 /* Displays an alert dialog box with the specified message */
283 static void QEMU_Alert(NSString *message)
286 alert = [NSAlert new];
287 [alert setMessageText: message];
291 /* Handles any errors that happen with a device transaction */
292 static void handleAnyDeviceErrors(Error * err)
295 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
296 encoding: NSASCIIStringEncoding]);
302 ------------------------------------------------------
304 ------------------------------------------------------
306 @interface QemuCocoaView : NSView
309 NSWindow *fullScreenWindow;
310 float cx,cy,cw,ch,cdx,cdy;
311 CGDataProviderRef dataProviderRef;
312 BOOL modifiers_state[256];
315 BOOL isAbsoluteEnabled;
316 BOOL isMouseDeassociated;
318 - (void) switchSurface:(pixman_image_t *)image;
320 - (void) ungrabMouse;
321 - (void) toggleFullScreen:(id)sender;
322 - (void) handleMonitorInput:(NSEvent *)event;
323 - (void) handleEvent:(NSEvent *)event;
324 - (void) handleEventLocked:(NSEvent *)event;
325 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
326 /* The state surrounding mouse grabbing is potentially confusing.
327 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
328 * pointing device an absolute-position one?"], but is only updated on
330 * isMouseGrabbed tracks whether GUI events are directed to the guest;
331 * it controls whether special keys like Cmd get sent to the guest,
332 * and whether we capture the mouse when in non-absolute mode.
333 * isMouseDeassociated tracks whether we've told MacOSX to disassociate
334 * the mouse and mouse cursor position by calling
335 * CGAssociateMouseAndMouseCursorPosition(FALSE)
336 * (which basically happens if we grab in non-absolute mode).
338 - (BOOL) isMouseGrabbed;
339 - (BOOL) isAbsoluteEnabled;
340 - (BOOL) isMouseDeassociated;
343 - (QEMUScreen) gscreen;
344 - (void) raiseAllKeys;
347 QemuCocoaView *cocoaView;
349 @implementation QemuCocoaView
350 - (id)initWithFrame:(NSRect)frameRect
352 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
354 self = [super initWithFrame:frameRect];
357 screen.bitsPerComponent = 8;
358 screen.bitsPerPixel = 32;
359 screen.width = frameRect.size.width;
360 screen.height = frameRect.size.height;
368 COCOA_DEBUG("QemuCocoaView: dealloc\n");
371 CGDataProviderRelease(dataProviderRef);
381 - (BOOL) screenContainsPoint:(NSPoint) p
383 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
394 - (void) unhideCursor
402 - (void) drawRect:(NSRect) rect
404 COCOA_DEBUG("QemuCocoaView: drawRect\n");
406 // get CoreGraphic context
407 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10
408 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] graphicsPort];
410 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
413 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
414 CGContextSetShouldAntialias (viewContextRef, NO);
416 // draw screen bitmap directly to Core Graphics context
417 if (!dataProviderRef) {
418 // Draw request before any guest device has set up a framebuffer:
419 // just draw an opaque black rectangle
420 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
421 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
423 CGImageRef imageRef = CGImageCreate(
424 screen.width, //width
425 screen.height, //height
426 screen.bitsPerComponent, //bitsPerComponent
427 screen.bitsPerPixel, //bitsPerPixel
428 (screen.width * (screen.bitsPerComponent/2)), //bytesPerRow
429 #ifdef __LITTLE_ENDIAN__
430 CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
431 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
433 CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
434 kCGImageAlphaNoneSkipFirst, //bitmapInfo
436 dataProviderRef, //provider
439 kCGRenderingIntentDefault //intent
441 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
442 const NSRect *rectList;
445 CGImageRef clipImageRef;
448 [self getRectsBeingDrawn:&rectList count:&rectCount];
449 for (i = 0; i < rectCount; i++) {
450 clipRect.origin.x = rectList[i].origin.x / cdx;
451 clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
452 clipRect.size.width = rectList[i].size.width / cdx;
453 clipRect.size.height = rectList[i].size.height / cdy;
454 clipImageRef = CGImageCreateWithImageInRect(
458 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
459 CGImageRelease (clipImageRef);
461 CGImageRelease (imageRef);
465 - (void) setContentDimensions
467 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
470 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
471 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
473 /* stretches video, but keeps same aspect ratio */
474 if (stretch_video == true) {
475 /* use smallest stretch value - prevents clipping on sides */
476 if (MIN(cdx, cdy) == cdx) {
481 } else { /* No stretching */
484 cw = screen.width * cdx;
485 ch = screen.height * cdy;
486 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
487 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
498 - (void) switchSurface:(pixman_image_t *)image
500 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
502 int w = pixman_image_get_width(image);
503 int h = pixman_image_get_height(image);
504 pixman_format_code_t image_format = pixman_image_get_format(image);
505 /* cdx == 0 means this is our very first surface, in which case we need
506 * to recalculate the content dimensions even if it happens to be the size
507 * of the initial empty window.
509 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
511 int oldh = screen.height;
513 // Resize before we trigger the redraw, or we'll redraw at the wrong size
514 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
517 [self setContentDimensions];
518 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
521 // update screenBuffer
523 CGDataProviderRelease(dataProviderRef);
525 //sync host window color space with guests
526 screen.bitsPerPixel = PIXMAN_FORMAT_BPP(image_format);
527 screen.bitsPerComponent = DIV_ROUND_UP(screen.bitsPerPixel, 8) * 2;
529 dataProviderRef = CGDataProviderCreateWithData(NULL, pixman_image_get_data(image), w * 4 * h, NULL);
533 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
534 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
537 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
538 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
542 [normalWindow center];
546 - (void) toggleFullScreen:(id)sender
548 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
550 if (isFullscreen) { // switch from fullscreen to desktop
551 isFullscreen = FALSE;
553 [self setContentDimensions];
554 if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
555 [self exitFullScreenModeWithOptions:nil];
557 [fullScreenWindow close];
558 [normalWindow setContentView: self];
559 [normalWindow makeKeyAndOrderFront: self];
560 [NSMenu setMenuBarVisible:YES];
562 } else { // switch from desktop to fullscreen
564 [normalWindow orderOut: nil]; /* Hide the window */
566 [self setContentDimensions];
567 if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
568 [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
569 [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
570 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
573 [NSMenu setMenuBarVisible:NO];
574 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
575 styleMask:NSWindowStyleMaskBorderless
576 backing:NSBackingStoreBuffered
578 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
579 [fullScreenWindow setHasShadow:NO];
580 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
581 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
582 [[fullScreenWindow contentView] addSubview: self];
583 [fullScreenWindow makeKeyAndOrderFront:self];
588 - (void) toggleModifier: (int)keycode {
589 // Toggle the stored state.
590 modifiers_state[keycode] = !modifiers_state[keycode];
591 // Send a keyup or keydown depending on the state.
592 qemu_input_event_send_key_qcode(dcl->con, keycode, modifiers_state[keycode]);
595 - (void) toggleStatefulModifier: (int)keycode {
596 // Toggle the stored state.
597 modifiers_state[keycode] = !modifiers_state[keycode];
598 // Generate keydown and keyup.
599 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
600 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
603 // Does the work of sending input to the monitor
604 - (void) handleMonitorInput:(NSEvent *)event
609 // if the control key is down
610 if ([event modifierFlags] & NSEventModifierFlagControl) {
614 /* translates Macintosh keycodes to QEMU's keysym */
616 int without_control_translation[] = {
617 [0 ... 0xff] = 0, // invalid key
619 [kVK_UpArrow] = QEMU_KEY_UP,
620 [kVK_DownArrow] = QEMU_KEY_DOWN,
621 [kVK_RightArrow] = QEMU_KEY_RIGHT,
622 [kVK_LeftArrow] = QEMU_KEY_LEFT,
623 [kVK_Home] = QEMU_KEY_HOME,
624 [kVK_End] = QEMU_KEY_END,
625 [kVK_PageUp] = QEMU_KEY_PAGEUP,
626 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
627 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
628 [kVK_Delete] = QEMU_KEY_BACKSPACE,
631 int with_control_translation[] = {
632 [0 ... 0xff] = 0, // invalid key
634 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
635 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
636 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
637 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
638 [kVK_Home] = QEMU_KEY_CTRL_HOME,
639 [kVK_End] = QEMU_KEY_CTRL_END,
640 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
641 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
644 if (control_key != 0) { /* If the control key is being used */
645 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
646 keysym = with_control_translation[[event keyCode]];
649 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
650 keysym = without_control_translation[[event keyCode]];
654 // if not a key that needs translating
656 NSString *ks = [event characters];
657 if ([ks length] > 0) {
658 keysym = [ks characterAtIndex:0];
663 kbd_put_keysym(keysym);
667 - (void) handleEvent:(NSEvent *)event
669 with_iothread_lock(^{
670 [self handleEventLocked:event];
674 - (void) handleEventLocked:(NSEvent *)event
676 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
679 bool mouse_event = false;
680 static bool switched_to_fullscreen = false;
681 NSPoint p = [event locationInWindow];
683 switch ([event type]) {
684 case NSEventTypeFlagsChanged:
685 if ([event keyCode] == 0) {
686 // When the Cocoa keyCode is zero that means keys should be
687 // synthesized based on the values in in the eventModifiers
690 if (qemu_console_is_graphic(NULL)) {
691 NSUInteger modifiers = [event modifierFlags];
693 if (!!(modifiers & NSEventModifierFlagCapsLock) != !!modifiers_state[Q_KEY_CODE_CAPS_LOCK]) {
694 [self toggleStatefulModifier:Q_KEY_CODE_CAPS_LOCK];
696 if (!!(modifiers & NSEventModifierFlagShift) != !!modifiers_state[Q_KEY_CODE_SHIFT]) {
697 [self toggleModifier:Q_KEY_CODE_SHIFT];
699 if (!!(modifiers & NSEventModifierFlagControl) != !!modifiers_state[Q_KEY_CODE_CTRL]) {
700 [self toggleModifier:Q_KEY_CODE_CTRL];
702 if (!!(modifiers & NSEventModifierFlagOption) != !!modifiers_state[Q_KEY_CODE_ALT]) {
703 [self toggleModifier:Q_KEY_CODE_ALT];
705 if (!!(modifiers & NSEventModifierFlagCommand) != !!modifiers_state[Q_KEY_CODE_META_L]) {
706 [self toggleModifier:Q_KEY_CODE_META_L];
710 keycode = cocoa_keycode_to_qemu([event keyCode]);
713 if ((keycode == Q_KEY_CODE_META_L || keycode == Q_KEY_CODE_META_R)
714 && !isMouseGrabbed) {
715 /* Don't pass command key changes to guest unless mouse is grabbed */
720 // emulate caps lock and num lock keydown and keyup
721 if (keycode == Q_KEY_CODE_CAPS_LOCK ||
722 keycode == Q_KEY_CODE_NUM_LOCK) {
723 [self toggleStatefulModifier:keycode];
724 } else if (qemu_console_is_graphic(NULL)) {
725 if (switched_to_fullscreen) {
726 switched_to_fullscreen = false;
728 [self toggleModifier:keycode];
734 case NSEventTypeKeyDown:
735 keycode = cocoa_keycode_to_qemu([event keyCode]);
737 // forward command key combos to the host UI unless the mouse is grabbed
738 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
740 * Prevent the command key from being stuck down in the guest
741 * when using Command-F to switch to full screen mode.
743 if (keycode == Q_KEY_CODE_F) {
744 switched_to_fullscreen = true;
746 [NSApp sendEvent:event];
752 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
753 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
754 NSString *keychar = [event charactersIgnoringModifiers];
755 if ([keychar length] == 1) {
756 char key = [keychar characterAtIndex:0];
759 // enable graphic console
761 console_select(key - '0' - 1); /* ascii math */
764 // release the mouse grab
772 if (qemu_console_is_graphic(NULL)) {
773 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
775 [self handleMonitorInput: event];
778 case NSEventTypeKeyUp:
779 keycode = cocoa_keycode_to_qemu([event keyCode]);
781 // don't pass the guest a spurious key-up if we treated this
782 // command-key combo as a host UI action
783 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
787 if (qemu_console_is_graphic(NULL)) {
788 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
791 case NSEventTypeMouseMoved:
792 if (isAbsoluteEnabled) {
793 if (![self screenContainsPoint:p] || ![[self window] isKeyWindow]) {
794 if (isMouseGrabbed) {
798 if (!isMouseGrabbed) {
805 case NSEventTypeLeftMouseDown:
806 if ([event modifierFlags] & NSEventModifierFlagCommand) {
807 buttons |= MOUSE_EVENT_RBUTTON;
809 buttons |= MOUSE_EVENT_LBUTTON;
813 case NSEventTypeRightMouseDown:
814 buttons |= MOUSE_EVENT_RBUTTON;
817 case NSEventTypeOtherMouseDown:
818 buttons |= MOUSE_EVENT_MBUTTON;
821 case NSEventTypeLeftMouseDragged:
822 if ([event modifierFlags] & NSEventModifierFlagCommand) {
823 buttons |= MOUSE_EVENT_RBUTTON;
825 buttons |= MOUSE_EVENT_LBUTTON;
829 case NSEventTypeRightMouseDragged:
830 buttons |= MOUSE_EVENT_RBUTTON;
833 case NSEventTypeOtherMouseDragged:
834 buttons |= MOUSE_EVENT_MBUTTON;
837 case NSEventTypeLeftMouseUp:
839 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
840 if([[self window] isKeyWindow]) {
845 case NSEventTypeRightMouseUp:
848 case NSEventTypeOtherMouseUp:
851 case NSEventTypeScrollWheel:
853 * Send wheel events to the guest regardless of window focus.
854 * This is in-line with standard Mac OS X UI behaviour.
858 * When deltaY is zero, it means that this scrolling event was
859 * either horizontal, or so fine that it only appears in
860 * scrollingDeltaY. So we drop the event.
862 if ([event deltaY] != 0) {
863 /* Determine if this is a scroll up or scroll down event */
864 buttons = ([event deltaY] > 0) ?
865 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
866 qemu_input_queue_btn(dcl->con, buttons, true);
867 qemu_input_event_sync();
868 qemu_input_queue_btn(dcl->con, buttons, false);
869 qemu_input_event_sync();
872 * Since deltaY also reports scroll wheel events we prevent mouse
873 * movement code from executing.
878 [NSApp sendEvent:event];
882 /* Don't send button events to the guest unless we've got a
883 * mouse grab or window focus. If we have neither then this event
884 * is the user clicking on the background window to activate and
885 * bring us to the front, which will be done by the sendEvent
886 * call below. We definitely don't want to pass that click through
889 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
890 (last_buttons != buttons)) {
891 static uint32_t bmap[INPUT_BUTTON__MAX] = {
892 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
893 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
894 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
896 qemu_input_update_buttons(dcl->con, bmap, last_buttons, buttons);
897 last_buttons = buttons;
899 if (isMouseGrabbed) {
900 if (isAbsoluteEnabled) {
901 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
902 * The check on screenContainsPoint is to avoid sending out of range values for
903 * clicks in the titlebar.
905 if ([self screenContainsPoint:p]) {
906 qemu_input_queue_abs(dcl->con, INPUT_AXIS_X, p.x, 0, screen.width);
907 qemu_input_queue_abs(dcl->con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
910 qemu_input_queue_rel(dcl->con, INPUT_AXIS_X, (int)[event deltaX]);
911 qemu_input_queue_rel(dcl->con, INPUT_AXIS_Y, (int)[event deltaY]);
914 [NSApp sendEvent:event];
916 qemu_input_event_sync();
922 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
926 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
928 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
931 if (!isAbsoluteEnabled) {
932 isMouseDeassociated = TRUE;
933 CGAssociateMouseAndMouseCursorPosition(FALSE);
935 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
940 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
944 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
946 [normalWindow setTitle:@"QEMU"];
949 if (isMouseDeassociated) {
950 CGAssociateMouseAndMouseCursorPosition(TRUE);
951 isMouseDeassociated = FALSE;
953 isMouseGrabbed = FALSE;
956 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
957 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
958 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
959 - (BOOL) isMouseDeassociated {return isMouseDeassociated;}
960 - (float) cdx {return cdx;}
961 - (float) cdy {return cdy;}
962 - (QEMUScreen) gscreen {return screen;}
965 * Makes the target think all down keys are being released.
966 * This prevents a stuck key problem, since we will not see
967 * key up events for those keys after we have lost focus.
969 - (void) raiseAllKeys
971 const int max_index = ARRAY_SIZE(modifiers_state);
973 with_iothread_lock(^{
976 for (index = 0; index < max_index; index++) {
977 if (modifiers_state[index]) {
978 modifiers_state[index] = 0;
979 qemu_input_event_send_key_qcode(dcl->con, index, false);
989 ------------------------------------------------------
990 QemuCocoaAppController
991 ------------------------------------------------------
993 @interface QemuCocoaAppController : NSObject
994 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
995 <NSWindowDelegate, NSApplicationDelegate>
999 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv;
1000 - (void)doToggleFullScreen:(id)sender;
1001 - (void)toggleFullScreen:(id)sender;
1002 - (void)showQEMUDoc:(id)sender;
1003 - (void)zoomToFit:(id) sender;
1004 - (void)displayConsole:(id)sender;
1005 - (void)pauseQEMU:(id)sender;
1006 - (void)resumeQEMU:(id)sender;
1007 - (void)displayPause;
1008 - (void)removePause;
1009 - (void)restartQEMU:(id)sender;
1010 - (void)powerDownQEMU:(id)sender;
1011 - (void)ejectDeviceMedia:(id)sender;
1012 - (void)changeDeviceMedia:(id)sender;
1014 - (void)openDocumentation:(NSString *)filename;
1015 - (IBAction) do_about_menu_item: (id) sender;
1016 - (void)make_about_window;
1017 - (void)adjustSpeed:(id)sender;
1020 @implementation QemuCocoaAppController
1023 COCOA_DEBUG("QemuCocoaAppController: init\n");
1025 self = [super init];
1028 // create a view and add it to the window
1029 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1031 fprintf(stderr, "(cocoa) can't create a view\n");
1036 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
1037 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
1038 backing:NSBackingStoreBuffered defer:NO];
1040 fprintf(stderr, "(cocoa) can't create window\n");
1043 [normalWindow setAcceptsMouseMovedEvents:YES];
1044 [normalWindow setTitle:@"QEMU"];
1045 [normalWindow setContentView:cocoaView];
1046 #if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10)
1047 [normalWindow useOptimizedDrawing:YES];
1049 [normalWindow makeKeyAndOrderFront:self];
1050 [normalWindow center];
1051 [normalWindow setDelegate: self];
1052 stretch_video = false;
1054 /* Used for displaying pause on the screen */
1055 pauseLabel = [NSTextField new];
1056 [pauseLabel setBezeled:YES];
1057 [pauseLabel setDrawsBackground:YES];
1058 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1059 [pauseLabel setEditable:NO];
1060 [pauseLabel setSelectable:NO];
1061 [pauseLabel setStringValue: @"Paused"];
1062 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1063 [pauseLabel setTextColor: [NSColor blackColor]];
1064 [pauseLabel sizeToFit];
1066 // set the supported image file types that can be opened
1067 supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
1068 @"qcow", @"qcow2", @"cloop", @"vmdk", @"cdr",
1070 [self make_about_window];
1077 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1080 [cocoaView release];
1084 - (void)applicationDidFinishLaunching: (NSNotification *) note
1086 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1087 // launch QEMU, with the global args
1088 [self startEmulationWithArgc:gArgc argv:(char **)gArgv];
1091 - (void)applicationWillTerminate:(NSNotification *)aNotification
1093 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1095 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1099 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1104 - (NSApplicationTerminateReply)applicationShouldTerminate:
1105 (NSApplication *)sender
1107 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1108 return [self verifyQuit];
1111 /* Called when the user clicks on a window's close button */
1112 - (BOOL)windowShouldClose:(id)sender
1114 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1115 [NSApp terminate: sender];
1116 /* If the user allows the application to quit then the call to
1117 * NSApp terminate will never return. If we get here then the user
1118 * cancelled the quit, so we should return NO to not permit the
1119 * closing of this window.
1124 /* Called when QEMU goes into the background */
1125 - (void) applicationWillResignActive: (NSNotification *)aNotification
1127 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1128 [cocoaView raiseAllKeys];
1131 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv
1133 COCOA_DEBUG("QemuCocoaAppController: startEmulationWithArgc\n");
1136 status = qemu_main(argc, argv, *_NSGetEnviron());
1140 /* We abstract the method called by the Enter Fullscreen menu item
1141 * because Mac OS 10.7 and higher disables it. This is because of the
1142 * menu item's old selector's name toggleFullScreen:
1144 - (void) doToggleFullScreen:(id)sender
1146 [self toggleFullScreen:(id)sender];
1149 - (void)toggleFullScreen:(id)sender
1151 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1153 [cocoaView toggleFullScreen:sender];
1156 /* Tries to find then open the specified filename */
1157 - (void) openDocumentation: (NSString *) filename
1159 /* Where to look for local files */
1160 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"../"};
1161 NSString *full_file_path;
1163 /* iterate thru the possible paths until the file is found */
1165 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1166 full_file_path = [[NSBundle mainBundle] executablePath];
1167 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1168 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1169 path_array[index], filename];
1170 if ([[NSWorkspace sharedWorkspace] openFile: full_file_path] == YES) {
1175 /* If none of the paths opened a file */
1177 QEMU_Alert(@"Failed to open file");
1180 - (void)showQEMUDoc:(id)sender
1182 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1184 [self openDocumentation: @"qemu-doc.html"];
1187 /* Stretches video to fit host monitor size */
1188 - (void)zoomToFit:(id) sender
1190 stretch_video = !stretch_video;
1191 if (stretch_video == true) {
1192 [sender setState: NSControlStateValueOn];
1194 [sender setState: NSControlStateValueOff];
1198 /* Displays the console on the screen */
1199 - (void)displayConsole:(id)sender
1201 console_select([sender tag]);
1204 /* Pause the guest */
1205 - (void)pauseQEMU:(id)sender
1207 with_iothread_lock(^{
1210 [sender setEnabled: NO];
1211 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1212 [self displayPause];
1215 /* Resume running the guest operating system */
1216 - (void)resumeQEMU:(id) sender
1218 with_iothread_lock(^{
1221 [sender setEnabled: NO];
1222 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1226 /* Displays the word pause on the screen */
1227 - (void)displayPause
1229 /* Coordinates have to be calculated each time because the window can change its size */
1230 int xCoord, yCoord, width, height;
1231 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1232 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1233 width = [pauseLabel frame].size.width;
1234 height = [pauseLabel frame].size.height;
1235 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1236 [cocoaView addSubview: pauseLabel];
1239 /* Removes the word pause from the screen */
1242 [pauseLabel removeFromSuperview];
1246 - (void)restartQEMU:(id)sender
1248 with_iothread_lock(^{
1249 qmp_system_reset(NULL);
1253 /* Powers down QEMU */
1254 - (void)powerDownQEMU:(id)sender
1256 with_iothread_lock(^{
1257 qmp_system_powerdown(NULL);
1261 /* Ejects the media.
1262 * Uses sender's tag to figure out the device to eject.
1264 - (void)ejectDeviceMedia:(id)sender
1267 drive = [sender representedObject];
1270 QEMU_Alert(@"Failed to find drive to eject!");
1274 __block Error *err = NULL;
1275 with_iothread_lock(^{
1276 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1277 false, NULL, false, false, &err);
1279 handleAnyDeviceErrors(err);
1282 /* Displays a dialog box asking the user to select an image file to load.
1283 * Uses sender's represented object value to figure out which drive to use.
1285 - (void)changeDeviceMedia:(id)sender
1287 /* Find the drive name */
1289 drive = [sender representedObject];
1292 QEMU_Alert(@"Could not find drive!");
1296 /* Display the file open dialog */
1297 NSOpenPanel * openPanel;
1298 openPanel = [NSOpenPanel openPanel];
1299 [openPanel setCanChooseFiles: YES];
1300 [openPanel setAllowsMultipleSelection: NO];
1301 [openPanel setAllowedFileTypes: supportedImageFileTypes];
1302 if([openPanel runModal] == NSModalResponseOK) {
1303 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1306 QEMU_Alert(@"Failed to convert URL to file path!");
1310 __block Error *err = NULL;
1311 with_iothread_lock(^{
1312 qmp_blockdev_change_medium(true,
1313 [drive cStringUsingEncoding:
1314 NSASCIIStringEncoding],
1316 [file cStringUsingEncoding:
1317 NSASCIIStringEncoding],
1322 handleAnyDeviceErrors(err);
1326 /* Verifies if the user really wants to quit */
1329 NSAlert *alert = [NSAlert new];
1330 [alert autorelease];
1331 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1332 [alert addButtonWithTitle: @"Cancel"];
1333 [alert addButtonWithTitle: @"Quit"];
1334 if([alert runModal] == NSAlertSecondButtonReturn) {
1341 /* The action method for the About menu item */
1342 - (IBAction) do_about_menu_item: (id) sender
1344 [about_window makeKeyAndOrderFront: nil];
1347 /* Create and display the about dialog */
1348 - (void)make_about_window
1350 /* Make the window */
1351 int x = 0, y = 0, about_width = 400, about_height = 200;
1352 NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1353 about_window = [[NSWindow alloc] initWithContentRect:window_rect
1354 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1355 NSWindowStyleMaskMiniaturizable
1356 backing:NSBackingStoreBuffered
1358 [about_window setTitle: @"About"];
1359 [about_window setReleasedWhenClosed: NO];
1360 [about_window center];
1361 NSView *superView = [about_window contentView];
1363 /* Create the dimensions of the picture */
1364 int picture_width = 80, picture_height = 80;
1365 x = (about_width - picture_width)/2;
1366 y = about_height - picture_height - 10;
1367 NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1369 /* Get the path to the QEMU binary */
1370 NSString *binary_name = [NSString stringWithCString: gArgv[0]
1371 encoding: NSASCIIStringEncoding];
1372 binary_name = [binary_name lastPathComponent];
1373 NSString *program_path = [[NSString alloc] initWithFormat: @"%@/%@",
1374 [[NSBundle mainBundle] bundlePath], binary_name];
1376 /* Make the picture of QEMU */
1377 NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1379 NSImage *qemu_image = [[NSWorkspace sharedWorkspace] iconForFile:
1381 [picture_view setImage: qemu_image];
1382 [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1383 [superView addSubview: picture_view];
1385 /* Make the name label */
1388 int name_width = about_width, name_height = 20;
1389 NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1390 NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1391 [name_label setEditable: NO];
1392 [name_label setBezeled: NO];
1393 [name_label setDrawsBackground: NO];
1394 [name_label setAlignment: NSTextAlignmentCenter];
1395 NSString *qemu_name = [[NSString alloc] initWithCString: gArgv[0]
1396 encoding: NSASCIIStringEncoding];
1397 qemu_name = [qemu_name lastPathComponent];
1398 [name_label setStringValue: qemu_name];
1399 [superView addSubview: name_label];
1401 /* Set the version label's attributes */
1404 int version_width = about_width, version_height = 20;
1405 NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1406 NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1408 [version_label setEditable: NO];
1409 [version_label setBezeled: NO];
1410 [version_label setAlignment: NSTextAlignmentCenter];
1411 [version_label setDrawsBackground: NO];
1413 /* Create the version string*/
1414 NSString *version_string;
1415 version_string = [[NSString alloc] initWithFormat:
1416 @"QEMU emulator version %s", QEMU_FULL_VERSION];
1417 [version_label setStringValue: version_string];
1418 [superView addSubview: version_label];
1420 /* Make copyright label */
1423 int copyright_width = about_width, copyright_height = 20;
1424 NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1425 NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1427 [copyright_label setEditable: NO];
1428 [copyright_label setBezeled: NO];
1429 [copyright_label setDrawsBackground: NO];
1430 [copyright_label setAlignment: NSTextAlignmentCenter];
1431 [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1433 [superView addSubview: copyright_label];
1436 /* Used by the Speed menu items */
1437 - (void)adjustSpeed:(id)sender
1439 int throttle_pct; /* throttle percentage */
1442 menu = [sender menu];
1445 /* Unselect the currently selected item */
1446 for (NSMenuItem *item in [menu itemArray]) {
1447 if (item.state == NSControlStateValueOn) {
1448 [item setState: NSControlStateValueOff];
1454 // check the menu item
1455 [sender setState: NSControlStateValueOn];
1457 // get the throttle percentage
1458 throttle_pct = [sender tag];
1460 with_iothread_lock(^{
1461 cpu_throttle_set(throttle_pct);
1463 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1469 int main (int argc, const char * argv[]) {
1472 gArgv = (char **)argv;
1475 /* In case we don't need to display a window, let's not do that */
1476 for (i = 1; i < argc; i++) {
1477 const char *opt = argv[i];
1479 if (opt[0] == '-') {
1480 /* Treat --foo the same as -foo. */
1481 if (opt[1] == '-') {
1484 if (!strcmp(opt, "-h") || !strcmp(opt, "-help") ||
1485 !strcmp(opt, "-vnc") ||
1486 !strcmp(opt, "-nographic") ||
1487 !strcmp(opt, "-version") ||
1488 !strcmp(opt, "-curses") ||
1489 !strcmp(opt, "-display") ||
1490 !strcmp(opt, "-qtest")) {
1491 return qemu_main(gArgc, gArgv, *_NSGetEnviron());
1496 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1498 // Pull this console process up to being a fully-fledged graphical
1499 // app with a menubar and Dock icon
1500 ProcessSerialNumber psn = { 0, kCurrentProcess };
1501 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1503 [NSApplication sharedApplication];
1507 NSMenuItem *menuItem;
1509 [NSApp setMainMenu:[[NSMenu alloc] init]];
1512 menu = [[NSMenu alloc] initWithTitle:@""];
1513 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1514 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1515 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1516 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1517 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1518 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1519 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1520 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1521 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1522 [menuItem setSubmenu:menu];
1523 [[NSApp mainMenu] addItem:menuItem];
1524 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1527 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1528 [menu setAutoenablesItems: NO];
1529 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1530 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1531 [menu addItem: menuItem];
1532 [menuItem setEnabled: NO];
1533 [menu addItem: [NSMenuItem separatorItem]];
1534 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1535 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1536 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1537 [menuItem setSubmenu:menu];
1538 [[NSApp mainMenu] addItem:menuItem];
1541 menu = [[NSMenu alloc] initWithTitle:@"View"];
1542 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1543 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1544 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1545 [menuItem setSubmenu:menu];
1546 [[NSApp mainMenu] addItem:menuItem];
1549 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1551 // Add the rest of the Speed menu items
1552 int p, percentage, throttle_pct;
1553 for (p = 10; p >= 0; p--)
1555 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1557 menuItem = [[[NSMenuItem alloc]
1558 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1560 if (percentage == 100) {
1561 [menuItem setState: NSControlStateValueOn];
1564 /* Calculate the throttle percentage */
1565 throttle_pct = -1 * percentage + 100;
1567 [menuItem setTag: throttle_pct];
1568 [menu addItem: menuItem];
1570 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1571 [menuItem setSubmenu:menu];
1572 [[NSApp mainMenu] addItem:menuItem];
1575 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1576 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1577 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1578 [menuItem setSubmenu:menu];
1579 [[NSApp mainMenu] addItem:menuItem];
1580 [NSApp setWindowsMenu:menu];
1583 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1584 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1585 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1586 [menuItem setSubmenu:menu];
1587 [[NSApp mainMenu] addItem:menuItem];
1589 // Create an Application controller
1590 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1591 [NSApp setDelegate:appController];
1593 // Start the main event loop
1596 [appController release];
1605 static void cocoa_update(DisplayChangeListener *dcl,
1606 int x, int y, int w, int h)
1608 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1610 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1613 if ([cocoaView cdx] == 1.0) {
1614 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1617 x * [cocoaView cdx],
1618 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1619 w * [cocoaView cdx],
1620 h * [cocoaView cdy]);
1622 [cocoaView setNeedsDisplayInRect:rect];
1627 static void cocoa_switch(DisplayChangeListener *dcl,
1628 DisplaySurface *surface)
1630 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1632 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1633 [cocoaView switchSurface:surface->image];
1637 static void cocoa_refresh(DisplayChangeListener *dcl)
1639 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1641 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
1642 graphic_hw_update(NULL);
1644 if (qemu_input_is_absolute()) {
1645 if (![cocoaView isAbsoluteEnabled]) {
1646 if ([cocoaView isMouseGrabbed]) {
1647 [cocoaView ungrabMouse];
1650 [cocoaView setAbsoluteEnabled:YES];
1653 NSDate *distantPast;
1655 distantPast = [NSDate distantPast];
1657 event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:distantPast
1658 inMode: NSDefaultRunLoopMode dequeue:YES];
1660 [cocoaView handleEvent:event];
1662 } while(event != nil);
1666 static void cocoa_cleanup(void)
1668 COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
1672 static const DisplayChangeListenerOps dcl_ops = {
1673 .dpy_name = "cocoa",
1674 .dpy_gfx_update = cocoa_update,
1675 .dpy_gfx_switch = cocoa_switch,
1676 .dpy_refresh = cocoa_refresh,
1679 /* Returns a name for a given console */
1680 static NSString * getConsoleName(QemuConsole * console)
1682 return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1685 /* Add an entry to the View menu for each console */
1686 static void add_console_menu_entries(void)
1689 NSMenuItem *menuItem;
1692 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1694 [menu addItem:[NSMenuItem separatorItem]];
1696 while (qemu_console_lookup_by_index(index) != NULL) {
1697 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1698 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1699 [menuItem setTag: index];
1700 [menu addItem: menuItem];
1705 /* Make menu items for all removable devices.
1706 * Each device is given an 'Eject' and 'Change' menu item.
1708 static void addRemovableDevicesMenuItems(void)
1711 NSMenuItem *menuItem;
1712 BlockInfoList *currentDevice, *pointerToFree;
1713 NSString *deviceName;
1715 currentDevice = qmp_query_block(NULL);
1716 pointerToFree = currentDevice;
1717 if(currentDevice == NULL) {
1719 QEMU_Alert(@"Failed to query for block devices!");
1723 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1725 // Add a separator between related groups of menu items
1726 [menu addItem:[NSMenuItem separatorItem]];
1728 // Set the attributes to the "Removable Media" menu item
1729 NSString *titleString = @"Removable Media";
1730 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1731 NSColor *newColor = [NSColor blackColor];
1732 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1733 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1734 traits:NSBoldFontMask|NSItalicFontMask
1737 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1738 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1739 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1741 // Add the "Removable Media" menu item
1742 menuItem = [NSMenuItem new];
1743 [menuItem setAttributedTitle: attString];
1744 [menuItem setEnabled: NO];
1745 [menu addItem: menuItem];
1747 /* Loop through all the block devices in the emulator */
1748 while (currentDevice) {
1749 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1751 if(currentDevice->value->removable) {
1752 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1753 action: @selector(changeDeviceMedia:)
1754 keyEquivalent: @""];
1755 [menu addItem: menuItem];
1756 [menuItem setRepresentedObject: deviceName];
1757 [menuItem autorelease];
1759 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1760 action: @selector(ejectDeviceMedia:)
1761 keyEquivalent: @""];
1762 [menu addItem: menuItem];
1763 [menuItem setRepresentedObject: deviceName];
1764 [menuItem autorelease];
1766 currentDevice = currentDevice->next;
1768 qapi_free_BlockInfoList(pointerToFree);
1771 static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
1773 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1775 /* if fullscreen mode is to be used */
1776 if (opts->has_full_screen && opts->full_screen) {
1777 [NSApp activateIgnoringOtherApps: YES];
1778 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1781 dcl = g_malloc0(sizeof(DisplayChangeListener));
1783 // register vga output callbacks
1784 dcl->ops = &dcl_ops;
1785 register_displaychangelistener(dcl);
1787 // register cleanup function
1788 atexit(cocoa_cleanup);
1790 /* At this point QEMU has created all the consoles, so we can add View
1791 * menu entries for them.
1793 add_console_menu_entries();
1795 /* Give all removable devices a menu item.
1796 * Has to be called after QEMU has started to
1797 * find out what removable devices it has.
1799 addRemovableDevicesMenuItems();
1802 static QemuDisplay qemu_display_cocoa = {
1803 .type = DISPLAY_TYPE_COCOA,
1804 .init = cocoa_display_init,
1807 static void register_cocoa(void)
1809 qemu_display_register(&qemu_display_cocoa);
1812 type_init(register_cocoa);