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
58 /* macOS 10.12 deprecated many constants, #define the new names for older SDKs */
59 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_12
60 #define NSEventMaskAny NSAnyEventMask
61 #define NSEventModifierFlagCapsLock NSAlphaShiftKeyMask
62 #define NSEventModifierFlagShift NSShiftKeyMask
63 #define NSEventModifierFlagCommand NSCommandKeyMask
64 #define NSEventModifierFlagControl NSControlKeyMask
65 #define NSEventModifierFlagOption NSAlternateKeyMask
66 #define NSEventTypeFlagsChanged NSFlagsChanged
67 #define NSEventTypeKeyUp NSKeyUp
68 #define NSEventTypeKeyDown NSKeyDown
69 #define NSEventTypeMouseMoved NSMouseMoved
70 #define NSEventTypeLeftMouseDown NSLeftMouseDown
71 #define NSEventTypeRightMouseDown NSRightMouseDown
72 #define NSEventTypeOtherMouseDown NSOtherMouseDown
73 #define NSEventTypeLeftMouseDragged NSLeftMouseDragged
74 #define NSEventTypeRightMouseDragged NSRightMouseDragged
75 #define NSEventTypeOtherMouseDragged NSOtherMouseDragged
76 #define NSEventTypeLeftMouseUp NSLeftMouseUp
77 #define NSEventTypeRightMouseUp NSRightMouseUp
78 #define NSEventTypeOtherMouseUp NSOtherMouseUp
79 #define NSEventTypeScrollWheel NSScrollWheel
80 #define NSTextAlignmentCenter NSCenterTextAlignment
81 #define NSWindowStyleMaskBorderless NSBorderlessWindowMask
82 #define NSWindowStyleMaskClosable NSClosableWindowMask
83 #define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask
84 #define NSWindowStyleMaskTitled NSTitledWindowMask
86 /* 10.13 deprecates NSFileHandlingPanelOKButton in favour of
87 * NSModalResponseOK, which was introduced in 10.9. Define
88 * it for older versions.
90 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_9
91 #define NSModalResponseOK NSFileHandlingPanelOKButton
97 #define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
99 #define COCOA_DEBUG(...) ((void) 0)
102 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
107 int bitsPerComponent;
111 NSWindow *normalWindow, *about_window;
112 static DisplayChangeListener *dcl;
113 static int last_buttons;
118 NSTextField *pauseLabel;
119 NSArray * supportedImageFileTypes;
121 // Mac to QKeyCode conversion
122 const int mac_to_qkeycode_map[] = {
123 [kVK_ANSI_A] = Q_KEY_CODE_A,
124 [kVK_ANSI_B] = Q_KEY_CODE_B,
125 [kVK_ANSI_C] = Q_KEY_CODE_C,
126 [kVK_ANSI_D] = Q_KEY_CODE_D,
127 [kVK_ANSI_E] = Q_KEY_CODE_E,
128 [kVK_ANSI_F] = Q_KEY_CODE_F,
129 [kVK_ANSI_G] = Q_KEY_CODE_G,
130 [kVK_ANSI_H] = Q_KEY_CODE_H,
131 [kVK_ANSI_I] = Q_KEY_CODE_I,
132 [kVK_ANSI_J] = Q_KEY_CODE_J,
133 [kVK_ANSI_K] = Q_KEY_CODE_K,
134 [kVK_ANSI_L] = Q_KEY_CODE_L,
135 [kVK_ANSI_M] = Q_KEY_CODE_M,
136 [kVK_ANSI_N] = Q_KEY_CODE_N,
137 [kVK_ANSI_O] = Q_KEY_CODE_O,
138 [kVK_ANSI_P] = Q_KEY_CODE_P,
139 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
140 [kVK_ANSI_R] = Q_KEY_CODE_R,
141 [kVK_ANSI_S] = Q_KEY_CODE_S,
142 [kVK_ANSI_T] = Q_KEY_CODE_T,
143 [kVK_ANSI_U] = Q_KEY_CODE_U,
144 [kVK_ANSI_V] = Q_KEY_CODE_V,
145 [kVK_ANSI_W] = Q_KEY_CODE_W,
146 [kVK_ANSI_X] = Q_KEY_CODE_X,
147 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
148 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
150 [kVK_ANSI_0] = Q_KEY_CODE_0,
151 [kVK_ANSI_1] = Q_KEY_CODE_1,
152 [kVK_ANSI_2] = Q_KEY_CODE_2,
153 [kVK_ANSI_3] = Q_KEY_CODE_3,
154 [kVK_ANSI_4] = Q_KEY_CODE_4,
155 [kVK_ANSI_5] = Q_KEY_CODE_5,
156 [kVK_ANSI_6] = Q_KEY_CODE_6,
157 [kVK_ANSI_7] = Q_KEY_CODE_7,
158 [kVK_ANSI_8] = Q_KEY_CODE_8,
159 [kVK_ANSI_9] = Q_KEY_CODE_9,
161 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
162 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
163 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
164 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
165 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
166 [kVK_Tab] = Q_KEY_CODE_TAB,
167 [kVK_Return] = Q_KEY_CODE_RET,
168 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
169 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
170 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
171 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
172 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
173 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
174 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
175 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
176 [kVK_Shift] = Q_KEY_CODE_SHIFT,
177 [kVK_RightShift] = Q_KEY_CODE_SHIFT_R,
178 [kVK_Control] = Q_KEY_CODE_CTRL,
179 [kVK_RightControl] = Q_KEY_CODE_CTRL_R,
180 [kVK_Option] = Q_KEY_CODE_ALT,
181 [kVK_RightOption] = Q_KEY_CODE_ALT_R,
182 [kVK_Command] = Q_KEY_CODE_META_L,
183 [0x36] = Q_KEY_CODE_META_R, /* There is no kVK_RightCommand */
184 [kVK_Space] = Q_KEY_CODE_SPC,
186 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
187 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
188 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
189 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
190 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
191 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
192 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
193 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
194 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
195 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
196 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
197 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
198 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
199 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
200 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
201 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
202 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
203 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
205 [kVK_UpArrow] = Q_KEY_CODE_UP,
206 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
207 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
208 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
210 [kVK_Help] = Q_KEY_CODE_INSERT,
211 [kVK_Home] = Q_KEY_CODE_HOME,
212 [kVK_PageUp] = Q_KEY_CODE_PGUP,
213 [kVK_PageDown] = Q_KEY_CODE_PGDN,
214 [kVK_End] = Q_KEY_CODE_END,
215 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
217 [kVK_Escape] = Q_KEY_CODE_ESC,
219 /* The Power key can't be used directly because the operating system uses
220 * it. This key can be emulated by using it in place of another key such as
221 * F1. Don't forget to disable the real key binding.
223 /* [kVK_F1] = Q_KEY_CODE_POWER, */
225 [kVK_F1] = Q_KEY_CODE_F1,
226 [kVK_F2] = Q_KEY_CODE_F2,
227 [kVK_F3] = Q_KEY_CODE_F3,
228 [kVK_F4] = Q_KEY_CODE_F4,
229 [kVK_F5] = Q_KEY_CODE_F5,
230 [kVK_F6] = Q_KEY_CODE_F6,
231 [kVK_F7] = Q_KEY_CODE_F7,
232 [kVK_F8] = Q_KEY_CODE_F8,
233 [kVK_F9] = Q_KEY_CODE_F9,
234 [kVK_F10] = Q_KEY_CODE_F10,
235 [kVK_F11] = Q_KEY_CODE_F11,
236 [kVK_F12] = Q_KEY_CODE_F12,
237 [kVK_F13] = Q_KEY_CODE_PRINT,
238 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
239 [kVK_F15] = Q_KEY_CODE_PAUSE,
242 * The eject and volume keys can't be used here because they are handled at
243 * a lower level than what an Application can see.
247 static int cocoa_keycode_to_qemu(int keycode)
249 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
250 fprintf(stderr, "(cocoa) warning unknown keycode 0x%x\n", keycode);
253 return mac_to_qkeycode_map[keycode];
256 /* Displays an alert dialog box with the specified message */
257 static void QEMU_Alert(NSString *message)
260 alert = [NSAlert new];
261 [alert setMessageText: message];
265 /* Handles any errors that happen with a device transaction */
266 static void handleAnyDeviceErrors(Error * err)
269 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
270 encoding: NSASCIIStringEncoding]);
276 ------------------------------------------------------
278 ------------------------------------------------------
280 @interface QemuCocoaView : NSView
283 NSWindow *fullScreenWindow;
284 float cx,cy,cw,ch,cdx,cdy;
285 CGDataProviderRef dataProviderRef;
286 BOOL modifiers_state[256];
289 BOOL isAbsoluteEnabled;
290 BOOL isMouseDeassociated;
292 - (void) switchSurface:(DisplaySurface *)surface;
294 - (void) ungrabMouse;
295 - (void) toggleFullScreen:(id)sender;
296 - (void) handleMonitorInput:(NSEvent *)event;
297 - (void) handleEvent:(NSEvent *)event;
298 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
299 /* The state surrounding mouse grabbing is potentially confusing.
300 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
301 * pointing device an absolute-position one?"], but is only updated on
303 * isMouseGrabbed tracks whether GUI events are directed to the guest;
304 * it controls whether special keys like Cmd get sent to the guest,
305 * and whether we capture the mouse when in non-absolute mode.
306 * isMouseDeassociated tracks whether we've told MacOSX to disassociate
307 * the mouse and mouse cursor position by calling
308 * CGAssociateMouseAndMouseCursorPosition(FALSE)
309 * (which basically happens if we grab in non-absolute mode).
311 - (BOOL) isMouseGrabbed;
312 - (BOOL) isAbsoluteEnabled;
313 - (BOOL) isMouseDeassociated;
316 - (QEMUScreen) gscreen;
317 - (void) raiseAllKeys;
320 QemuCocoaView *cocoaView;
322 @implementation QemuCocoaView
323 - (id)initWithFrame:(NSRect)frameRect
325 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
327 self = [super initWithFrame:frameRect];
330 screen.bitsPerComponent = 8;
331 screen.bitsPerPixel = 32;
332 screen.width = frameRect.size.width;
333 screen.height = frameRect.size.height;
341 COCOA_DEBUG("QemuCocoaView: dealloc\n");
344 CGDataProviderRelease(dataProviderRef);
354 - (BOOL) screenContainsPoint:(NSPoint) p
356 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
367 - (void) unhideCursor
375 - (void) drawRect:(NSRect) rect
377 COCOA_DEBUG("QemuCocoaView: drawRect\n");
379 // get CoreGraphic context
380 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] graphicsPort];
381 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
382 CGContextSetShouldAntialias (viewContextRef, NO);
384 // draw screen bitmap directly to Core Graphics context
385 if (!dataProviderRef) {
386 // Draw request before any guest device has set up a framebuffer:
387 // just draw an opaque black rectangle
388 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
389 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
391 CGImageRef imageRef = CGImageCreate(
392 screen.width, //width
393 screen.height, //height
394 screen.bitsPerComponent, //bitsPerComponent
395 screen.bitsPerPixel, //bitsPerPixel
396 (screen.width * (screen.bitsPerComponent/2)), //bytesPerRow
397 #ifdef __LITTLE_ENDIAN__
398 CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
399 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
401 CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
402 kCGImageAlphaNoneSkipFirst, //bitmapInfo
404 dataProviderRef, //provider
407 kCGRenderingIntentDefault //intent
409 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
410 const NSRect *rectList;
413 CGImageRef clipImageRef;
416 [self getRectsBeingDrawn:&rectList count:&rectCount];
417 for (i = 0; i < rectCount; i++) {
418 clipRect.origin.x = rectList[i].origin.x / cdx;
419 clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
420 clipRect.size.width = rectList[i].size.width / cdx;
421 clipRect.size.height = rectList[i].size.height / cdy;
422 clipImageRef = CGImageCreateWithImageInRect(
426 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
427 CGImageRelease (clipImageRef);
429 CGImageRelease (imageRef);
433 - (void) setContentDimensions
435 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
438 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
439 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
441 /* stretches video, but keeps same aspect ratio */
442 if (stretch_video == true) {
443 /* use smallest stretch value - prevents clipping on sides */
444 if (MIN(cdx, cdy) == cdx) {
449 } else { /* No stretching */
452 cw = screen.width * cdx;
453 ch = screen.height * cdy;
454 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
455 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
466 - (void) switchSurface:(DisplaySurface *)surface
468 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
470 int w = surface_width(surface);
471 int h = surface_height(surface);
472 /* cdx == 0 means this is our very first surface, in which case we need
473 * to recalculate the content dimensions even if it happens to be the size
474 * of the initial empty window.
476 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
478 int oldh = screen.height;
480 // Resize before we trigger the redraw, or we'll redraw at the wrong size
481 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
484 [self setContentDimensions];
485 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
488 // update screenBuffer
490 CGDataProviderRelease(dataProviderRef);
492 //sync host window color space with guests
493 screen.bitsPerPixel = surface_bits_per_pixel(surface);
494 screen.bitsPerComponent = surface_bytes_per_pixel(surface) * 2;
496 dataProviderRef = CGDataProviderCreateWithData(NULL, surface_data(surface), w * 4 * h, NULL);
500 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
501 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
504 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
505 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
509 [normalWindow center];
513 - (void) toggleFullScreen:(id)sender
515 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
517 if (isFullscreen) { // switch from fullscreen to desktop
518 isFullscreen = FALSE;
520 [self setContentDimensions];
521 if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
522 [self exitFullScreenModeWithOptions:nil];
524 [fullScreenWindow close];
525 [normalWindow setContentView: self];
526 [normalWindow makeKeyAndOrderFront: self];
527 [NSMenu setMenuBarVisible:YES];
529 } else { // switch from desktop to fullscreen
531 [normalWindow orderOut: nil]; /* Hide the window */
533 [self setContentDimensions];
534 if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
535 [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
536 [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
537 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
540 [NSMenu setMenuBarVisible:NO];
541 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
542 styleMask:NSWindowStyleMaskBorderless
543 backing:NSBackingStoreBuffered
545 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
546 [fullScreenWindow setHasShadow:NO];
547 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
548 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
549 [[fullScreenWindow contentView] addSubview: self];
550 [fullScreenWindow makeKeyAndOrderFront:self];
555 - (void) toggleModifier: (int)keycode {
556 // Toggle the stored state.
557 modifiers_state[keycode] = !modifiers_state[keycode];
558 // Send a keyup or keydown depending on the state.
559 qemu_input_event_send_key_qcode(dcl->con, keycode, modifiers_state[keycode]);
562 - (void) toggleStatefulModifier: (int)keycode {
563 // Toggle the stored state.
564 modifiers_state[keycode] = !modifiers_state[keycode];
565 // Generate keydown and keyup.
566 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
567 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
570 // Does the work of sending input to the monitor
571 - (void) handleMonitorInput:(NSEvent *)event
576 // if the control key is down
577 if ([event modifierFlags] & NSEventModifierFlagControl) {
581 /* translates Macintosh keycodes to QEMU's keysym */
583 int without_control_translation[] = {
584 [0 ... 0xff] = 0, // invalid key
586 [kVK_UpArrow] = QEMU_KEY_UP,
587 [kVK_DownArrow] = QEMU_KEY_DOWN,
588 [kVK_RightArrow] = QEMU_KEY_RIGHT,
589 [kVK_LeftArrow] = QEMU_KEY_LEFT,
590 [kVK_Home] = QEMU_KEY_HOME,
591 [kVK_End] = QEMU_KEY_END,
592 [kVK_PageUp] = QEMU_KEY_PAGEUP,
593 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
594 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
595 [kVK_Delete] = QEMU_KEY_BACKSPACE,
598 int with_control_translation[] = {
599 [0 ... 0xff] = 0, // invalid key
601 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
602 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
603 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
604 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
605 [kVK_Home] = QEMU_KEY_CTRL_HOME,
606 [kVK_End] = QEMU_KEY_CTRL_END,
607 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
608 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
611 if (control_key != 0) { /* If the control key is being used */
612 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
613 keysym = with_control_translation[[event keyCode]];
616 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
617 keysym = without_control_translation[[event keyCode]];
621 // if not a key that needs translating
623 NSString *ks = [event characters];
624 if ([ks length] > 0) {
625 keysym = [ks characterAtIndex:0];
630 kbd_put_keysym(keysym);
634 - (void) handleEvent:(NSEvent *)event
636 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
640 bool mouse_event = false;
641 static bool switched_to_fullscreen = false;
642 NSPoint p = [event locationInWindow];
644 switch ([event type]) {
645 case NSEventTypeFlagsChanged:
646 if ([event keyCode] == 0) {
647 // When the Cocoa keyCode is zero that means keys should be
648 // synthesized based on the values in in the eventModifiers
651 if (qemu_console_is_graphic(NULL)) {
652 NSUInteger modifiers = [event modifierFlags];
654 if (!!(modifiers & NSEventModifierFlagCapsLock) != !!modifiers_state[Q_KEY_CODE_CAPS_LOCK]) {
655 [self toggleStatefulModifier:Q_KEY_CODE_CAPS_LOCK];
657 if (!!(modifiers & NSEventModifierFlagShift) != !!modifiers_state[Q_KEY_CODE_SHIFT]) {
658 [self toggleModifier:Q_KEY_CODE_SHIFT];
660 if (!!(modifiers & NSEventModifierFlagControl) != !!modifiers_state[Q_KEY_CODE_CTRL]) {
661 [self toggleModifier:Q_KEY_CODE_CTRL];
663 if (!!(modifiers & NSEventModifierFlagOption) != !!modifiers_state[Q_KEY_CODE_ALT]) {
664 [self toggleModifier:Q_KEY_CODE_ALT];
666 if (!!(modifiers & NSEventModifierFlagCommand) != !!modifiers_state[Q_KEY_CODE_META_L]) {
667 [self toggleModifier:Q_KEY_CODE_META_L];
671 keycode = cocoa_keycode_to_qemu([event keyCode]);
674 if ((keycode == Q_KEY_CODE_META_L || keycode == Q_KEY_CODE_META_R)
675 && !isMouseGrabbed) {
676 /* Don't pass command key changes to guest unless mouse is grabbed */
681 // emulate caps lock and num lock keydown and keyup
682 if (keycode == Q_KEY_CODE_CAPS_LOCK ||
683 keycode == Q_KEY_CODE_NUM_LOCK) {
684 [self toggleStatefulModifier:keycode];
685 } else if (qemu_console_is_graphic(NULL)) {
686 if (switched_to_fullscreen) {
687 switched_to_fullscreen = false;
689 [self toggleModifier:keycode];
695 case NSEventTypeKeyDown:
696 keycode = cocoa_keycode_to_qemu([event keyCode]);
698 // forward command key combos to the host UI unless the mouse is grabbed
699 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
701 * Prevent the command key from being stuck down in the guest
702 * when using Command-F to switch to full screen mode.
704 if (keycode == Q_KEY_CODE_F) {
705 switched_to_fullscreen = true;
707 [NSApp sendEvent:event];
713 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
714 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
715 NSString *keychar = [event charactersIgnoringModifiers];
716 if ([keychar length] == 1) {
717 char key = [keychar characterAtIndex:0];
720 // enable graphic console
722 console_select(key - '0' - 1); /* ascii math */
725 // release the mouse grab
733 if (qemu_console_is_graphic(NULL)) {
734 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
736 [self handleMonitorInput: event];
739 case NSEventTypeKeyUp:
740 keycode = cocoa_keycode_to_qemu([event keyCode]);
742 // don't pass the guest a spurious key-up if we treated this
743 // command-key combo as a host UI action
744 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
748 if (qemu_console_is_graphic(NULL)) {
749 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
752 case NSEventTypeMouseMoved:
753 if (isAbsoluteEnabled) {
754 if (![self screenContainsPoint:p] || ![[self window] isKeyWindow]) {
755 if (isMouseGrabbed) {
759 if (!isMouseGrabbed) {
766 case NSEventTypeLeftMouseDown:
767 if ([event modifierFlags] & NSEventModifierFlagCommand) {
768 buttons |= MOUSE_EVENT_RBUTTON;
770 buttons |= MOUSE_EVENT_LBUTTON;
774 case NSEventTypeRightMouseDown:
775 buttons |= MOUSE_EVENT_RBUTTON;
778 case NSEventTypeOtherMouseDown:
779 buttons |= MOUSE_EVENT_MBUTTON;
782 case NSEventTypeLeftMouseDragged:
783 if ([event modifierFlags] & NSEventModifierFlagCommand) {
784 buttons |= MOUSE_EVENT_RBUTTON;
786 buttons |= MOUSE_EVENT_LBUTTON;
790 case NSEventTypeRightMouseDragged:
791 buttons |= MOUSE_EVENT_RBUTTON;
794 case NSEventTypeOtherMouseDragged:
795 buttons |= MOUSE_EVENT_MBUTTON;
798 case NSEventTypeLeftMouseUp:
800 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
801 if([[self window] isKeyWindow]) {
806 case NSEventTypeRightMouseUp:
809 case NSEventTypeOtherMouseUp:
812 case NSEventTypeScrollWheel:
814 * Send wheel events to the guest regardless of window focus.
815 * This is in-line with standard Mac OS X UI behaviour.
819 * When deltaY is zero, it means that this scrolling event was
820 * either horizontal, or so fine that it only appears in
821 * scrollingDeltaY. So we drop the event.
823 if ([event deltaY] != 0) {
824 /* Determine if this is a scroll up or scroll down event */
825 buttons = ([event deltaY] > 0) ?
826 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
827 qemu_input_queue_btn(dcl->con, buttons, true);
828 qemu_input_event_sync();
829 qemu_input_queue_btn(dcl->con, buttons, false);
830 qemu_input_event_sync();
833 * Since deltaY also reports scroll wheel events we prevent mouse
834 * movement code from executing.
839 [NSApp sendEvent:event];
843 /* Don't send button events to the guest unless we've got a
844 * mouse grab or window focus. If we have neither then this event
845 * is the user clicking on the background window to activate and
846 * bring us to the front, which will be done by the sendEvent
847 * call below. We definitely don't want to pass that click through
850 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
851 (last_buttons != buttons)) {
852 static uint32_t bmap[INPUT_BUTTON__MAX] = {
853 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
854 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
855 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
857 qemu_input_update_buttons(dcl->con, bmap, last_buttons, buttons);
858 last_buttons = buttons;
860 if (isMouseGrabbed) {
861 if (isAbsoluteEnabled) {
862 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
863 * The check on screenContainsPoint is to avoid sending out of range values for
864 * clicks in the titlebar.
866 if ([self screenContainsPoint:p]) {
867 qemu_input_queue_abs(dcl->con, INPUT_AXIS_X, p.x, 0, screen.width);
868 qemu_input_queue_abs(dcl->con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
871 qemu_input_queue_rel(dcl->con, INPUT_AXIS_X, (int)[event deltaX]);
872 qemu_input_queue_rel(dcl->con, INPUT_AXIS_Y, (int)[event deltaY]);
875 [NSApp sendEvent:event];
877 qemu_input_event_sync();
883 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
887 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
889 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
892 if (!isAbsoluteEnabled) {
893 isMouseDeassociated = TRUE;
894 CGAssociateMouseAndMouseCursorPosition(FALSE);
896 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
901 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
905 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
907 [normalWindow setTitle:@"QEMU"];
910 if (isMouseDeassociated) {
911 CGAssociateMouseAndMouseCursorPosition(TRUE);
912 isMouseDeassociated = FALSE;
914 isMouseGrabbed = FALSE;
917 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
918 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
919 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
920 - (BOOL) isMouseDeassociated {return isMouseDeassociated;}
921 - (float) cdx {return cdx;}
922 - (float) cdy {return cdy;}
923 - (QEMUScreen) gscreen {return screen;}
926 * Makes the target think all down keys are being released.
927 * This prevents a stuck key problem, since we will not see
928 * key up events for those keys after we have lost focus.
930 - (void) raiseAllKeys
933 const int max_index = ARRAY_SIZE(modifiers_state);
935 for (index = 0; index < max_index; index++) {
936 if (modifiers_state[index]) {
937 modifiers_state[index] = 0;
938 qemu_input_event_send_key_qcode(dcl->con, index, false);
947 ------------------------------------------------------
948 QemuCocoaAppController
949 ------------------------------------------------------
951 @interface QemuCocoaAppController : NSObject
952 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
953 <NSWindowDelegate, NSApplicationDelegate>
957 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv;
958 - (void)doToggleFullScreen:(id)sender;
959 - (void)toggleFullScreen:(id)sender;
960 - (void)showQEMUDoc:(id)sender;
961 - (void)zoomToFit:(id) sender;
962 - (void)displayConsole:(id)sender;
963 - (void)pauseQEMU:(id)sender;
964 - (void)resumeQEMU:(id)sender;
965 - (void)displayPause;
967 - (void)restartQEMU:(id)sender;
968 - (void)powerDownQEMU:(id)sender;
969 - (void)ejectDeviceMedia:(id)sender;
970 - (void)changeDeviceMedia:(id)sender;
972 - (void)openDocumentation:(NSString *)filename;
973 - (IBAction) do_about_menu_item: (id) sender;
974 - (void)make_about_window;
975 - (void)adjustSpeed:(id)sender;
978 @implementation QemuCocoaAppController
981 COCOA_DEBUG("QemuCocoaAppController: init\n");
986 // create a view and add it to the window
987 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
989 fprintf(stderr, "(cocoa) can't create a view\n");
994 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
995 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
996 backing:NSBackingStoreBuffered defer:NO];
998 fprintf(stderr, "(cocoa) can't create window\n");
1001 [normalWindow setAcceptsMouseMovedEvents:YES];
1002 [normalWindow setTitle:@"QEMU"];
1003 [normalWindow setContentView:cocoaView];
1004 #if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10)
1005 [normalWindow useOptimizedDrawing:YES];
1007 [normalWindow makeKeyAndOrderFront:self];
1008 [normalWindow center];
1009 [normalWindow setDelegate: self];
1010 stretch_video = false;
1012 /* Used for displaying pause on the screen */
1013 pauseLabel = [NSTextField new];
1014 [pauseLabel setBezeled:YES];
1015 [pauseLabel setDrawsBackground:YES];
1016 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1017 [pauseLabel setEditable:NO];
1018 [pauseLabel setSelectable:NO];
1019 [pauseLabel setStringValue: @"Paused"];
1020 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1021 [pauseLabel setTextColor: [NSColor blackColor]];
1022 [pauseLabel sizeToFit];
1024 // set the supported image file types that can be opened
1025 supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
1026 @"qcow", @"qcow2", @"cloop", @"vmdk", @"cdr",
1028 [self make_about_window];
1035 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1038 [cocoaView release];
1042 - (void)applicationDidFinishLaunching: (NSNotification *) note
1044 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1045 // launch QEMU, with the global args
1046 [self startEmulationWithArgc:gArgc argv:(char **)gArgv];
1049 - (void)applicationWillTerminate:(NSNotification *)aNotification
1051 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1053 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1057 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1062 - (NSApplicationTerminateReply)applicationShouldTerminate:
1063 (NSApplication *)sender
1065 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1066 return [self verifyQuit];
1069 /* Called when the user clicks on a window's close button */
1070 - (BOOL)windowShouldClose:(id)sender
1072 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1073 [NSApp terminate: sender];
1074 /* If the user allows the application to quit then the call to
1075 * NSApp terminate will never return. If we get here then the user
1076 * cancelled the quit, so we should return NO to not permit the
1077 * closing of this window.
1082 /* Called when QEMU goes into the background */
1083 - (void) applicationWillResignActive: (NSNotification *)aNotification
1085 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1086 [cocoaView raiseAllKeys];
1089 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv
1091 COCOA_DEBUG("QemuCocoaAppController: startEmulationWithArgc\n");
1094 status = qemu_main(argc, argv, *_NSGetEnviron());
1098 /* We abstract the method called by the Enter Fullscreen menu item
1099 * because Mac OS 10.7 and higher disables it. This is because of the
1100 * menu item's old selector's name toggleFullScreen:
1102 - (void) doToggleFullScreen:(id)sender
1104 [self toggleFullScreen:(id)sender];
1107 - (void)toggleFullScreen:(id)sender
1109 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1111 [cocoaView toggleFullScreen:sender];
1114 /* Tries to find then open the specified filename */
1115 - (void) openDocumentation: (NSString *) filename
1117 /* Where to look for local files */
1118 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"../"};
1119 NSString *full_file_path;
1121 /* iterate thru the possible paths until the file is found */
1123 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1124 full_file_path = [[NSBundle mainBundle] executablePath];
1125 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1126 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1127 path_array[index], filename];
1128 if ([[NSWorkspace sharedWorkspace] openFile: full_file_path] == YES) {
1133 /* If none of the paths opened a file */
1135 QEMU_Alert(@"Failed to open file");
1138 - (void)showQEMUDoc:(id)sender
1140 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1142 [self openDocumentation: @"qemu-doc.html"];
1145 /* Stretches video to fit host monitor size */
1146 - (void)zoomToFit:(id) sender
1148 stretch_video = !stretch_video;
1149 if (stretch_video == true) {
1150 [sender setState: NSOnState];
1152 [sender setState: NSOffState];
1156 /* Displays the console on the screen */
1157 - (void)displayConsole:(id)sender
1159 console_select([sender tag]);
1162 /* Pause the guest */
1163 - (void)pauseQEMU:(id)sender
1166 [sender setEnabled: NO];
1167 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1168 [self displayPause];
1171 /* Resume running the guest operating system */
1172 - (void)resumeQEMU:(id) sender
1175 [sender setEnabled: NO];
1176 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1180 /* Displays the word pause on the screen */
1181 - (void)displayPause
1183 /* Coordinates have to be calculated each time because the window can change its size */
1184 int xCoord, yCoord, width, height;
1185 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1186 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1187 width = [pauseLabel frame].size.width;
1188 height = [pauseLabel frame].size.height;
1189 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1190 [cocoaView addSubview: pauseLabel];
1193 /* Removes the word pause from the screen */
1196 [pauseLabel removeFromSuperview];
1200 - (void)restartQEMU:(id)sender
1202 qmp_system_reset(NULL);
1205 /* Powers down QEMU */
1206 - (void)powerDownQEMU:(id)sender
1208 qmp_system_powerdown(NULL);
1211 /* Ejects the media.
1212 * Uses sender's tag to figure out the device to eject.
1214 - (void)ejectDeviceMedia:(id)sender
1217 drive = [sender representedObject];
1220 QEMU_Alert(@"Failed to find drive to eject!");
1225 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1226 false, NULL, false, false, &err);
1227 handleAnyDeviceErrors(err);
1230 /* Displays a dialog box asking the user to select an image file to load.
1231 * Uses sender's represented object value to figure out which drive to use.
1233 - (void)changeDeviceMedia:(id)sender
1235 /* Find the drive name */
1237 drive = [sender representedObject];
1240 QEMU_Alert(@"Could not find drive!");
1244 /* Display the file open dialog */
1245 NSOpenPanel * openPanel;
1246 openPanel = [NSOpenPanel openPanel];
1247 [openPanel setCanChooseFiles: YES];
1248 [openPanel setAllowsMultipleSelection: NO];
1249 [openPanel setAllowedFileTypes: supportedImageFileTypes];
1250 if([openPanel runModal] == NSModalResponseOK) {
1251 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1254 QEMU_Alert(@"Failed to convert URL to file path!");
1259 qmp_blockdev_change_medium(true,
1260 [drive cStringUsingEncoding:
1261 NSASCIIStringEncoding],
1263 [file cStringUsingEncoding:
1264 NSASCIIStringEncoding],
1268 handleAnyDeviceErrors(err);
1272 /* Verifies if the user really wants to quit */
1275 NSAlert *alert = [NSAlert new];
1276 [alert autorelease];
1277 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1278 [alert addButtonWithTitle: @"Cancel"];
1279 [alert addButtonWithTitle: @"Quit"];
1280 if([alert runModal] == NSAlertSecondButtonReturn) {
1287 /* The action method for the About menu item */
1288 - (IBAction) do_about_menu_item: (id) sender
1290 [about_window makeKeyAndOrderFront: nil];
1293 /* Create and display the about dialog */
1294 - (void)make_about_window
1296 /* Make the window */
1297 int x = 0, y = 0, about_width = 400, about_height = 200;
1298 NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1299 about_window = [[NSWindow alloc] initWithContentRect:window_rect
1300 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1301 NSWindowStyleMaskMiniaturizable
1302 backing:NSBackingStoreBuffered
1304 [about_window setTitle: @"About"];
1305 [about_window setReleasedWhenClosed: NO];
1306 [about_window center];
1307 NSView *superView = [about_window contentView];
1309 /* Create the dimensions of the picture */
1310 int picture_width = 80, picture_height = 80;
1311 x = (about_width - picture_width)/2;
1312 y = about_height - picture_height - 10;
1313 NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1315 /* Get the path to the QEMU binary */
1316 NSString *binary_name = [NSString stringWithCString: gArgv[0]
1317 encoding: NSASCIIStringEncoding];
1318 binary_name = [binary_name lastPathComponent];
1319 NSString *program_path = [[NSString alloc] initWithFormat: @"%@/%@",
1320 [[NSBundle mainBundle] bundlePath], binary_name];
1322 /* Make the picture of QEMU */
1323 NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1325 NSImage *qemu_image = [[NSWorkspace sharedWorkspace] iconForFile:
1327 [picture_view setImage: qemu_image];
1328 [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1329 [superView addSubview: picture_view];
1331 /* Make the name label */
1334 int name_width = about_width, name_height = 20;
1335 NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1336 NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1337 [name_label setEditable: NO];
1338 [name_label setBezeled: NO];
1339 [name_label setDrawsBackground: NO];
1340 [name_label setAlignment: NSTextAlignmentCenter];
1341 NSString *qemu_name = [[NSString alloc] initWithCString: gArgv[0]
1342 encoding: NSASCIIStringEncoding];
1343 qemu_name = [qemu_name lastPathComponent];
1344 [name_label setStringValue: qemu_name];
1345 [superView addSubview: name_label];
1347 /* Set the version label's attributes */
1350 int version_width = about_width, version_height = 20;
1351 NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1352 NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1354 [version_label setEditable: NO];
1355 [version_label setBezeled: NO];
1356 [version_label setAlignment: NSTextAlignmentCenter];
1357 [version_label setDrawsBackground: NO];
1359 /* Create the version string*/
1360 NSString *version_string;
1361 version_string = [[NSString alloc] initWithFormat:
1362 @"QEMU emulator version %s", QEMU_FULL_VERSION];
1363 [version_label setStringValue: version_string];
1364 [superView addSubview: version_label];
1366 /* Make copyright label */
1369 int copyright_width = about_width, copyright_height = 20;
1370 NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1371 NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1373 [copyright_label setEditable: NO];
1374 [copyright_label setBezeled: NO];
1375 [copyright_label setDrawsBackground: NO];
1376 [copyright_label setAlignment: NSTextAlignmentCenter];
1377 [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1379 [superView addSubview: copyright_label];
1382 /* Used by the Speed menu items */
1383 - (void)adjustSpeed:(id)sender
1385 int throttle_pct; /* throttle percentage */
1388 menu = [sender menu];
1391 /* Unselect the currently selected item */
1392 for (NSMenuItem *item in [menu itemArray]) {
1393 if (item.state == NSOnState) {
1394 [item setState: NSOffState];
1400 // check the menu item
1401 [sender setState: NSOnState];
1403 // get the throttle percentage
1404 throttle_pct = [sender tag];
1406 cpu_throttle_set(throttle_pct);
1407 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1413 int main (int argc, const char * argv[]) {
1416 gArgv = (char **)argv;
1419 /* In case we don't need to display a window, let's not do that */
1420 for (i = 1; i < argc; i++) {
1421 const char *opt = argv[i];
1423 if (opt[0] == '-') {
1424 /* Treat --foo the same as -foo. */
1425 if (opt[1] == '-') {
1428 if (!strcmp(opt, "-h") || !strcmp(opt, "-help") ||
1429 !strcmp(opt, "-vnc") ||
1430 !strcmp(opt, "-nographic") ||
1431 !strcmp(opt, "-version") ||
1432 !strcmp(opt, "-curses") ||
1433 !strcmp(opt, "-display") ||
1434 !strcmp(opt, "-qtest")) {
1435 return qemu_main(gArgc, gArgv, *_NSGetEnviron());
1440 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1442 // Pull this console process up to being a fully-fledged graphical
1443 // app with a menubar and Dock icon
1444 ProcessSerialNumber psn = { 0, kCurrentProcess };
1445 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1447 [NSApplication sharedApplication];
1451 NSMenuItem *menuItem;
1453 [NSApp setMainMenu:[[NSMenu alloc] init]];
1456 menu = [[NSMenu alloc] initWithTitle:@""];
1457 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1458 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1459 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1460 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1461 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1462 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1463 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1464 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1465 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1466 [menuItem setSubmenu:menu];
1467 [[NSApp mainMenu] addItem:menuItem];
1468 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1471 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1472 [menu setAutoenablesItems: NO];
1473 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1474 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1475 [menu addItem: menuItem];
1476 [menuItem setEnabled: NO];
1477 [menu addItem: [NSMenuItem separatorItem]];
1478 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1479 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1480 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1481 [menuItem setSubmenu:menu];
1482 [[NSApp mainMenu] addItem:menuItem];
1485 menu = [[NSMenu alloc] initWithTitle:@"View"];
1486 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1487 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1488 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1489 [menuItem setSubmenu:menu];
1490 [[NSApp mainMenu] addItem:menuItem];
1493 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1495 // Add the rest of the Speed menu items
1496 int p, percentage, throttle_pct;
1497 for (p = 10; p >= 0; p--)
1499 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1501 menuItem = [[[NSMenuItem alloc]
1502 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1504 if (percentage == 100) {
1505 [menuItem setState: NSOnState];
1508 /* Calculate the throttle percentage */
1509 throttle_pct = -1 * percentage + 100;
1511 [menuItem setTag: throttle_pct];
1512 [menu addItem: menuItem];
1514 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1515 [menuItem setSubmenu:menu];
1516 [[NSApp mainMenu] addItem:menuItem];
1519 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1520 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1521 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1522 [menuItem setSubmenu:menu];
1523 [[NSApp mainMenu] addItem:menuItem];
1524 [NSApp setWindowsMenu:menu];
1527 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1528 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1529 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1530 [menuItem setSubmenu:menu];
1531 [[NSApp mainMenu] addItem:menuItem];
1533 // Create an Application controller
1534 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1535 [NSApp setDelegate:appController];
1537 // Start the main event loop
1540 [appController release];
1549 static void cocoa_update(DisplayChangeListener *dcl,
1550 int x, int y, int w, int h)
1552 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1554 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1557 if ([cocoaView cdx] == 1.0) {
1558 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1561 x * [cocoaView cdx],
1562 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1563 w * [cocoaView cdx],
1564 h * [cocoaView cdy]);
1566 [cocoaView setNeedsDisplayInRect:rect];
1571 static void cocoa_switch(DisplayChangeListener *dcl,
1572 DisplaySurface *surface)
1574 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1576 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1577 [cocoaView switchSurface:surface];
1581 static void cocoa_refresh(DisplayChangeListener *dcl)
1583 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1585 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
1586 graphic_hw_update(NULL);
1588 if (qemu_input_is_absolute()) {
1589 if (![cocoaView isAbsoluteEnabled]) {
1590 if ([cocoaView isMouseGrabbed]) {
1591 [cocoaView ungrabMouse];
1594 [cocoaView setAbsoluteEnabled:YES];
1597 NSDate *distantPast;
1599 distantPast = [NSDate distantPast];
1601 event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:distantPast
1602 inMode: NSDefaultRunLoopMode dequeue:YES];
1604 [cocoaView handleEvent:event];
1606 } while(event != nil);
1610 static void cocoa_cleanup(void)
1612 COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
1616 static const DisplayChangeListenerOps dcl_ops = {
1617 .dpy_name = "cocoa",
1618 .dpy_gfx_update = cocoa_update,
1619 .dpy_gfx_switch = cocoa_switch,
1620 .dpy_refresh = cocoa_refresh,
1623 /* Returns a name for a given console */
1624 static NSString * getConsoleName(QemuConsole * console)
1626 return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1629 /* Add an entry to the View menu for each console */
1630 static void add_console_menu_entries(void)
1633 NSMenuItem *menuItem;
1636 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1638 [menu addItem:[NSMenuItem separatorItem]];
1640 while (qemu_console_lookup_by_index(index) != NULL) {
1641 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1642 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1643 [menuItem setTag: index];
1644 [menu addItem: menuItem];
1649 /* Make menu items for all removable devices.
1650 * Each device is given an 'Eject' and 'Change' menu item.
1652 static void addRemovableDevicesMenuItems(void)
1655 NSMenuItem *menuItem;
1656 BlockInfoList *currentDevice, *pointerToFree;
1657 NSString *deviceName;
1659 currentDevice = qmp_query_block(NULL);
1660 pointerToFree = currentDevice;
1661 if(currentDevice == NULL) {
1663 QEMU_Alert(@"Failed to query for block devices!");
1667 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1669 // Add a separator between related groups of menu items
1670 [menu addItem:[NSMenuItem separatorItem]];
1672 // Set the attributes to the "Removable Media" menu item
1673 NSString *titleString = @"Removable Media";
1674 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1675 NSColor *newColor = [NSColor blackColor];
1676 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1677 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1678 traits:NSBoldFontMask|NSItalicFontMask
1681 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1682 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1683 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1685 // Add the "Removable Media" menu item
1686 menuItem = [NSMenuItem new];
1687 [menuItem setAttributedTitle: attString];
1688 [menuItem setEnabled: NO];
1689 [menu addItem: menuItem];
1691 /* Loop through all the block devices in the emulator */
1692 while (currentDevice) {
1693 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1695 if(currentDevice->value->removable) {
1696 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1697 action: @selector(changeDeviceMedia:)
1698 keyEquivalent: @""];
1699 [menu addItem: menuItem];
1700 [menuItem setRepresentedObject: deviceName];
1701 [menuItem autorelease];
1703 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1704 action: @selector(ejectDeviceMedia:)
1705 keyEquivalent: @""];
1706 [menu addItem: menuItem];
1707 [menuItem setRepresentedObject: deviceName];
1708 [menuItem autorelease];
1710 currentDevice = currentDevice->next;
1712 qapi_free_BlockInfoList(pointerToFree);
1715 static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
1717 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1719 /* if fullscreen mode is to be used */
1720 if (opts->has_full_screen && opts->full_screen) {
1721 [NSApp activateIgnoringOtherApps: YES];
1722 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1725 dcl = g_malloc0(sizeof(DisplayChangeListener));
1727 // register vga output callbacks
1728 dcl->ops = &dcl_ops;
1729 register_displaychangelistener(dcl);
1731 // register cleanup function
1732 atexit(cocoa_cleanup);
1734 /* At this point QEMU has created all the consoles, so we can add View
1735 * menu entries for them.
1737 add_console_menu_entries();
1739 /* Give all removable devices a menu item.
1740 * Has to be called after QEMU has started to
1741 * find out what removable devices it has.
1743 addRemovableDevicesMenuItems();
1746 static QemuDisplay qemu_display_cocoa = {
1747 .type = DISPLAY_TYPE_COCOA,
1748 .init = cocoa_display_init,
1751 static void register_cocoa(void)
1753 qemu_display_register(&qemu_display_cocoa);
1756 type_init(register_cocoa);