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 // Mac to QKeyCode conversion
133 const int mac_to_qkeycode_map[] = {
134 [kVK_ANSI_A] = Q_KEY_CODE_A,
135 [kVK_ANSI_B] = Q_KEY_CODE_B,
136 [kVK_ANSI_C] = Q_KEY_CODE_C,
137 [kVK_ANSI_D] = Q_KEY_CODE_D,
138 [kVK_ANSI_E] = Q_KEY_CODE_E,
139 [kVK_ANSI_F] = Q_KEY_CODE_F,
140 [kVK_ANSI_G] = Q_KEY_CODE_G,
141 [kVK_ANSI_H] = Q_KEY_CODE_H,
142 [kVK_ANSI_I] = Q_KEY_CODE_I,
143 [kVK_ANSI_J] = Q_KEY_CODE_J,
144 [kVK_ANSI_K] = Q_KEY_CODE_K,
145 [kVK_ANSI_L] = Q_KEY_CODE_L,
146 [kVK_ANSI_M] = Q_KEY_CODE_M,
147 [kVK_ANSI_N] = Q_KEY_CODE_N,
148 [kVK_ANSI_O] = Q_KEY_CODE_O,
149 [kVK_ANSI_P] = Q_KEY_CODE_P,
150 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
151 [kVK_ANSI_R] = Q_KEY_CODE_R,
152 [kVK_ANSI_S] = Q_KEY_CODE_S,
153 [kVK_ANSI_T] = Q_KEY_CODE_T,
154 [kVK_ANSI_U] = Q_KEY_CODE_U,
155 [kVK_ANSI_V] = Q_KEY_CODE_V,
156 [kVK_ANSI_W] = Q_KEY_CODE_W,
157 [kVK_ANSI_X] = Q_KEY_CODE_X,
158 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
159 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
161 [kVK_ANSI_0] = Q_KEY_CODE_0,
162 [kVK_ANSI_1] = Q_KEY_CODE_1,
163 [kVK_ANSI_2] = Q_KEY_CODE_2,
164 [kVK_ANSI_3] = Q_KEY_CODE_3,
165 [kVK_ANSI_4] = Q_KEY_CODE_4,
166 [kVK_ANSI_5] = Q_KEY_CODE_5,
167 [kVK_ANSI_6] = Q_KEY_CODE_6,
168 [kVK_ANSI_7] = Q_KEY_CODE_7,
169 [kVK_ANSI_8] = Q_KEY_CODE_8,
170 [kVK_ANSI_9] = Q_KEY_CODE_9,
172 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
173 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
174 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
175 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
176 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
177 [kVK_Tab] = Q_KEY_CODE_TAB,
178 [kVK_Return] = Q_KEY_CODE_RET,
179 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
180 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
181 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
182 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
183 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
184 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
185 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
186 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
187 [kVK_Shift] = Q_KEY_CODE_SHIFT,
188 [kVK_RightShift] = Q_KEY_CODE_SHIFT_R,
189 [kVK_Control] = Q_KEY_CODE_CTRL,
190 [kVK_RightControl] = Q_KEY_CODE_CTRL_R,
191 [kVK_Option] = Q_KEY_CODE_ALT,
192 [kVK_RightOption] = Q_KEY_CODE_ALT_R,
193 [kVK_Command] = Q_KEY_CODE_META_L,
194 [0x36] = Q_KEY_CODE_META_R, /* There is no kVK_RightCommand */
195 [kVK_Space] = Q_KEY_CODE_SPC,
197 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
198 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
199 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
200 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
201 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
202 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
203 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
204 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
205 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
206 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
207 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
208 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
209 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
210 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
211 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
212 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
213 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
214 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
216 [kVK_UpArrow] = Q_KEY_CODE_UP,
217 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
218 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
219 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
221 [kVK_Help] = Q_KEY_CODE_INSERT,
222 [kVK_Home] = Q_KEY_CODE_HOME,
223 [kVK_PageUp] = Q_KEY_CODE_PGUP,
224 [kVK_PageDown] = Q_KEY_CODE_PGDN,
225 [kVK_End] = Q_KEY_CODE_END,
226 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
228 [kVK_Escape] = Q_KEY_CODE_ESC,
230 /* The Power key can't be used directly because the operating system uses
231 * it. This key can be emulated by using it in place of another key such as
232 * F1. Don't forget to disable the real key binding.
234 /* [kVK_F1] = Q_KEY_CODE_POWER, */
236 [kVK_F1] = Q_KEY_CODE_F1,
237 [kVK_F2] = Q_KEY_CODE_F2,
238 [kVK_F3] = Q_KEY_CODE_F3,
239 [kVK_F4] = Q_KEY_CODE_F4,
240 [kVK_F5] = Q_KEY_CODE_F5,
241 [kVK_F6] = Q_KEY_CODE_F6,
242 [kVK_F7] = Q_KEY_CODE_F7,
243 [kVK_F8] = Q_KEY_CODE_F8,
244 [kVK_F9] = Q_KEY_CODE_F9,
245 [kVK_F10] = Q_KEY_CODE_F10,
246 [kVK_F11] = Q_KEY_CODE_F11,
247 [kVK_F12] = Q_KEY_CODE_F12,
248 [kVK_F13] = Q_KEY_CODE_PRINT,
249 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
250 [kVK_F15] = Q_KEY_CODE_PAUSE,
253 * The eject and volume keys can't be used here because they are handled at
254 * a lower level than what an Application can see.
258 static int cocoa_keycode_to_qemu(int keycode)
260 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
261 fprintf(stderr, "(cocoa) warning unknown keycode 0x%x\n", keycode);
264 return mac_to_qkeycode_map[keycode];
267 /* Displays an alert dialog box with the specified message */
268 static void QEMU_Alert(NSString *message)
271 alert = [NSAlert new];
272 [alert setMessageText: message];
276 /* Handles any errors that happen with a device transaction */
277 static void handleAnyDeviceErrors(Error * err)
280 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
281 encoding: NSASCIIStringEncoding]);
287 ------------------------------------------------------
289 ------------------------------------------------------
291 @interface QemuCocoaView : NSView
294 NSWindow *fullScreenWindow;
295 float cx,cy,cw,ch,cdx,cdy;
296 CGDataProviderRef dataProviderRef;
297 BOOL modifiers_state[256];
300 BOOL isAbsoluteEnabled;
301 BOOL isMouseDeassociated;
303 - (void) switchSurface:(DisplaySurface *)surface;
305 - (void) ungrabMouse;
306 - (void) toggleFullScreen:(id)sender;
307 - (void) handleMonitorInput:(NSEvent *)event;
308 - (void) handleEvent:(NSEvent *)event;
309 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
310 /* The state surrounding mouse grabbing is potentially confusing.
311 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
312 * pointing device an absolute-position one?"], but is only updated on
314 * isMouseGrabbed tracks whether GUI events are directed to the guest;
315 * it controls whether special keys like Cmd get sent to the guest,
316 * and whether we capture the mouse when in non-absolute mode.
317 * isMouseDeassociated tracks whether we've told MacOSX to disassociate
318 * the mouse and mouse cursor position by calling
319 * CGAssociateMouseAndMouseCursorPosition(FALSE)
320 * (which basically happens if we grab in non-absolute mode).
322 - (BOOL) isMouseGrabbed;
323 - (BOOL) isAbsoluteEnabled;
324 - (BOOL) isMouseDeassociated;
327 - (QEMUScreen) gscreen;
328 - (void) raiseAllKeys;
331 QemuCocoaView *cocoaView;
333 @implementation QemuCocoaView
334 - (id)initWithFrame:(NSRect)frameRect
336 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
338 self = [super initWithFrame:frameRect];
341 screen.bitsPerComponent = 8;
342 screen.bitsPerPixel = 32;
343 screen.width = frameRect.size.width;
344 screen.height = frameRect.size.height;
352 COCOA_DEBUG("QemuCocoaView: dealloc\n");
355 CGDataProviderRelease(dataProviderRef);
365 - (BOOL) screenContainsPoint:(NSPoint) p
367 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
378 - (void) unhideCursor
386 - (void) drawRect:(NSRect) rect
388 COCOA_DEBUG("QemuCocoaView: drawRect\n");
390 // get CoreGraphic context
391 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10
392 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] graphicsPort];
394 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
397 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
398 CGContextSetShouldAntialias (viewContextRef, NO);
400 // draw screen bitmap directly to Core Graphics context
401 if (!dataProviderRef) {
402 // Draw request before any guest device has set up a framebuffer:
403 // just draw an opaque black rectangle
404 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
405 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
407 CGImageRef imageRef = CGImageCreate(
408 screen.width, //width
409 screen.height, //height
410 screen.bitsPerComponent, //bitsPerComponent
411 screen.bitsPerPixel, //bitsPerPixel
412 (screen.width * (screen.bitsPerComponent/2)), //bytesPerRow
413 #ifdef __LITTLE_ENDIAN__
414 CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
415 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
417 CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
418 kCGImageAlphaNoneSkipFirst, //bitmapInfo
420 dataProviderRef, //provider
423 kCGRenderingIntentDefault //intent
425 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
426 const NSRect *rectList;
429 CGImageRef clipImageRef;
432 [self getRectsBeingDrawn:&rectList count:&rectCount];
433 for (i = 0; i < rectCount; i++) {
434 clipRect.origin.x = rectList[i].origin.x / cdx;
435 clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
436 clipRect.size.width = rectList[i].size.width / cdx;
437 clipRect.size.height = rectList[i].size.height / cdy;
438 clipImageRef = CGImageCreateWithImageInRect(
442 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
443 CGImageRelease (clipImageRef);
445 CGImageRelease (imageRef);
449 - (void) setContentDimensions
451 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
454 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
455 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
457 /* stretches video, but keeps same aspect ratio */
458 if (stretch_video == true) {
459 /* use smallest stretch value - prevents clipping on sides */
460 if (MIN(cdx, cdy) == cdx) {
465 } else { /* No stretching */
468 cw = screen.width * cdx;
469 ch = screen.height * cdy;
470 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
471 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
482 - (void) switchSurface:(DisplaySurface *)surface
484 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
486 int w = surface_width(surface);
487 int h = surface_height(surface);
488 /* cdx == 0 means this is our very first surface, in which case we need
489 * to recalculate the content dimensions even if it happens to be the size
490 * of the initial empty window.
492 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
494 int oldh = screen.height;
496 // Resize before we trigger the redraw, or we'll redraw at the wrong size
497 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
500 [self setContentDimensions];
501 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
504 // update screenBuffer
506 CGDataProviderRelease(dataProviderRef);
508 //sync host window color space with guests
509 screen.bitsPerPixel = surface_bits_per_pixel(surface);
510 screen.bitsPerComponent = surface_bytes_per_pixel(surface) * 2;
512 dataProviderRef = CGDataProviderCreateWithData(NULL, surface_data(surface), w * 4 * h, NULL);
516 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
517 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
520 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
521 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
525 [normalWindow center];
529 - (void) toggleFullScreen:(id)sender
531 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
533 if (isFullscreen) { // switch from fullscreen to desktop
534 isFullscreen = FALSE;
536 [self setContentDimensions];
537 if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
538 [self exitFullScreenModeWithOptions:nil];
540 [fullScreenWindow close];
541 [normalWindow setContentView: self];
542 [normalWindow makeKeyAndOrderFront: self];
543 [NSMenu setMenuBarVisible:YES];
545 } else { // switch from desktop to fullscreen
547 [normalWindow orderOut: nil]; /* Hide the window */
549 [self setContentDimensions];
550 if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
551 [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
552 [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
553 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
556 [NSMenu setMenuBarVisible:NO];
557 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
558 styleMask:NSWindowStyleMaskBorderless
559 backing:NSBackingStoreBuffered
561 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
562 [fullScreenWindow setHasShadow:NO];
563 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
564 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
565 [[fullScreenWindow contentView] addSubview: self];
566 [fullScreenWindow makeKeyAndOrderFront:self];
571 - (void) toggleModifier: (int)keycode {
572 // Toggle the stored state.
573 modifiers_state[keycode] = !modifiers_state[keycode];
574 // Send a keyup or keydown depending on the state.
575 qemu_input_event_send_key_qcode(dcl->con, keycode, modifiers_state[keycode]);
578 - (void) toggleStatefulModifier: (int)keycode {
579 // Toggle the stored state.
580 modifiers_state[keycode] = !modifiers_state[keycode];
581 // Generate keydown and keyup.
582 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
583 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
586 // Does the work of sending input to the monitor
587 - (void) handleMonitorInput:(NSEvent *)event
592 // if the control key is down
593 if ([event modifierFlags] & NSEventModifierFlagControl) {
597 /* translates Macintosh keycodes to QEMU's keysym */
599 int without_control_translation[] = {
600 [0 ... 0xff] = 0, // invalid key
602 [kVK_UpArrow] = QEMU_KEY_UP,
603 [kVK_DownArrow] = QEMU_KEY_DOWN,
604 [kVK_RightArrow] = QEMU_KEY_RIGHT,
605 [kVK_LeftArrow] = QEMU_KEY_LEFT,
606 [kVK_Home] = QEMU_KEY_HOME,
607 [kVK_End] = QEMU_KEY_END,
608 [kVK_PageUp] = QEMU_KEY_PAGEUP,
609 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
610 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
611 [kVK_Delete] = QEMU_KEY_BACKSPACE,
614 int with_control_translation[] = {
615 [0 ... 0xff] = 0, // invalid key
617 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
618 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
619 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
620 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
621 [kVK_Home] = QEMU_KEY_CTRL_HOME,
622 [kVK_End] = QEMU_KEY_CTRL_END,
623 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
624 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
627 if (control_key != 0) { /* If the control key is being used */
628 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
629 keysym = with_control_translation[[event keyCode]];
632 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
633 keysym = without_control_translation[[event keyCode]];
637 // if not a key that needs translating
639 NSString *ks = [event characters];
640 if ([ks length] > 0) {
641 keysym = [ks characterAtIndex:0];
646 kbd_put_keysym(keysym);
650 - (void) handleEvent:(NSEvent *)event
652 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
656 bool mouse_event = false;
657 static bool switched_to_fullscreen = false;
658 NSPoint p = [event locationInWindow];
660 switch ([event type]) {
661 case NSEventTypeFlagsChanged:
662 if ([event keyCode] == 0) {
663 // When the Cocoa keyCode is zero that means keys should be
664 // synthesized based on the values in in the eventModifiers
667 if (qemu_console_is_graphic(NULL)) {
668 NSUInteger modifiers = [event modifierFlags];
670 if (!!(modifiers & NSEventModifierFlagCapsLock) != !!modifiers_state[Q_KEY_CODE_CAPS_LOCK]) {
671 [self toggleStatefulModifier:Q_KEY_CODE_CAPS_LOCK];
673 if (!!(modifiers & NSEventModifierFlagShift) != !!modifiers_state[Q_KEY_CODE_SHIFT]) {
674 [self toggleModifier:Q_KEY_CODE_SHIFT];
676 if (!!(modifiers & NSEventModifierFlagControl) != !!modifiers_state[Q_KEY_CODE_CTRL]) {
677 [self toggleModifier:Q_KEY_CODE_CTRL];
679 if (!!(modifiers & NSEventModifierFlagOption) != !!modifiers_state[Q_KEY_CODE_ALT]) {
680 [self toggleModifier:Q_KEY_CODE_ALT];
682 if (!!(modifiers & NSEventModifierFlagCommand) != !!modifiers_state[Q_KEY_CODE_META_L]) {
683 [self toggleModifier:Q_KEY_CODE_META_L];
687 keycode = cocoa_keycode_to_qemu([event keyCode]);
690 if ((keycode == Q_KEY_CODE_META_L || keycode == Q_KEY_CODE_META_R)
691 && !isMouseGrabbed) {
692 /* Don't pass command key changes to guest unless mouse is grabbed */
697 // emulate caps lock and num lock keydown and keyup
698 if (keycode == Q_KEY_CODE_CAPS_LOCK ||
699 keycode == Q_KEY_CODE_NUM_LOCK) {
700 [self toggleStatefulModifier:keycode];
701 } else if (qemu_console_is_graphic(NULL)) {
702 if (switched_to_fullscreen) {
703 switched_to_fullscreen = false;
705 [self toggleModifier:keycode];
711 case NSEventTypeKeyDown:
712 keycode = cocoa_keycode_to_qemu([event keyCode]);
714 // forward command key combos to the host UI unless the mouse is grabbed
715 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
717 * Prevent the command key from being stuck down in the guest
718 * when using Command-F to switch to full screen mode.
720 if (keycode == Q_KEY_CODE_F) {
721 switched_to_fullscreen = true;
723 [NSApp sendEvent:event];
729 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
730 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
731 NSString *keychar = [event charactersIgnoringModifiers];
732 if ([keychar length] == 1) {
733 char key = [keychar characterAtIndex:0];
736 // enable graphic console
738 console_select(key - '0' - 1); /* ascii math */
741 // release the mouse grab
749 if (qemu_console_is_graphic(NULL)) {
750 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
752 [self handleMonitorInput: event];
755 case NSEventTypeKeyUp:
756 keycode = cocoa_keycode_to_qemu([event keyCode]);
758 // don't pass the guest a spurious key-up if we treated this
759 // command-key combo as a host UI action
760 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
764 if (qemu_console_is_graphic(NULL)) {
765 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
768 case NSEventTypeMouseMoved:
769 if (isAbsoluteEnabled) {
770 if (![self screenContainsPoint:p] || ![[self window] isKeyWindow]) {
771 if (isMouseGrabbed) {
775 if (!isMouseGrabbed) {
782 case NSEventTypeLeftMouseDown:
783 if ([event modifierFlags] & NSEventModifierFlagCommand) {
784 buttons |= MOUSE_EVENT_RBUTTON;
786 buttons |= MOUSE_EVENT_LBUTTON;
790 case NSEventTypeRightMouseDown:
791 buttons |= MOUSE_EVENT_RBUTTON;
794 case NSEventTypeOtherMouseDown:
795 buttons |= MOUSE_EVENT_MBUTTON;
798 case NSEventTypeLeftMouseDragged:
799 if ([event modifierFlags] & NSEventModifierFlagCommand) {
800 buttons |= MOUSE_EVENT_RBUTTON;
802 buttons |= MOUSE_EVENT_LBUTTON;
806 case NSEventTypeRightMouseDragged:
807 buttons |= MOUSE_EVENT_RBUTTON;
810 case NSEventTypeOtherMouseDragged:
811 buttons |= MOUSE_EVENT_MBUTTON;
814 case NSEventTypeLeftMouseUp:
816 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
817 if([[self window] isKeyWindow]) {
822 case NSEventTypeRightMouseUp:
825 case NSEventTypeOtherMouseUp:
828 case NSEventTypeScrollWheel:
830 * Send wheel events to the guest regardless of window focus.
831 * This is in-line with standard Mac OS X UI behaviour.
835 * When deltaY is zero, it means that this scrolling event was
836 * either horizontal, or so fine that it only appears in
837 * scrollingDeltaY. So we drop the event.
839 if ([event deltaY] != 0) {
840 /* Determine if this is a scroll up or scroll down event */
841 buttons = ([event deltaY] > 0) ?
842 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
843 qemu_input_queue_btn(dcl->con, buttons, true);
844 qemu_input_event_sync();
845 qemu_input_queue_btn(dcl->con, buttons, false);
846 qemu_input_event_sync();
849 * Since deltaY also reports scroll wheel events we prevent mouse
850 * movement code from executing.
855 [NSApp sendEvent:event];
859 /* Don't send button events to the guest unless we've got a
860 * mouse grab or window focus. If we have neither then this event
861 * is the user clicking on the background window to activate and
862 * bring us to the front, which will be done by the sendEvent
863 * call below. We definitely don't want to pass that click through
866 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
867 (last_buttons != buttons)) {
868 static uint32_t bmap[INPUT_BUTTON__MAX] = {
869 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
870 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
871 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
873 qemu_input_update_buttons(dcl->con, bmap, last_buttons, buttons);
874 last_buttons = buttons;
876 if (isMouseGrabbed) {
877 if (isAbsoluteEnabled) {
878 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
879 * The check on screenContainsPoint is to avoid sending out of range values for
880 * clicks in the titlebar.
882 if ([self screenContainsPoint:p]) {
883 qemu_input_queue_abs(dcl->con, INPUT_AXIS_X, p.x, 0, screen.width);
884 qemu_input_queue_abs(dcl->con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
887 qemu_input_queue_rel(dcl->con, INPUT_AXIS_X, (int)[event deltaX]);
888 qemu_input_queue_rel(dcl->con, INPUT_AXIS_Y, (int)[event deltaY]);
891 [NSApp sendEvent:event];
893 qemu_input_event_sync();
899 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
903 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
905 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
908 if (!isAbsoluteEnabled) {
909 isMouseDeassociated = TRUE;
910 CGAssociateMouseAndMouseCursorPosition(FALSE);
912 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
917 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
921 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
923 [normalWindow setTitle:@"QEMU"];
926 if (isMouseDeassociated) {
927 CGAssociateMouseAndMouseCursorPosition(TRUE);
928 isMouseDeassociated = FALSE;
930 isMouseGrabbed = FALSE;
933 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
934 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
935 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
936 - (BOOL) isMouseDeassociated {return isMouseDeassociated;}
937 - (float) cdx {return cdx;}
938 - (float) cdy {return cdy;}
939 - (QEMUScreen) gscreen {return screen;}
942 * Makes the target think all down keys are being released.
943 * This prevents a stuck key problem, since we will not see
944 * key up events for those keys after we have lost focus.
946 - (void) raiseAllKeys
949 const int max_index = ARRAY_SIZE(modifiers_state);
951 for (index = 0; index < max_index; index++) {
952 if (modifiers_state[index]) {
953 modifiers_state[index] = 0;
954 qemu_input_event_send_key_qcode(dcl->con, index, false);
963 ------------------------------------------------------
964 QemuCocoaAppController
965 ------------------------------------------------------
967 @interface QemuCocoaAppController : NSObject
968 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
969 <NSWindowDelegate, NSApplicationDelegate>
973 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv;
974 - (void)doToggleFullScreen:(id)sender;
975 - (void)toggleFullScreen:(id)sender;
976 - (void)showQEMUDoc:(id)sender;
977 - (void)zoomToFit:(id) sender;
978 - (void)displayConsole:(id)sender;
979 - (void)pauseQEMU:(id)sender;
980 - (void)resumeQEMU:(id)sender;
981 - (void)displayPause;
983 - (void)restartQEMU:(id)sender;
984 - (void)powerDownQEMU:(id)sender;
985 - (void)ejectDeviceMedia:(id)sender;
986 - (void)changeDeviceMedia:(id)sender;
988 - (void)openDocumentation:(NSString *)filename;
989 - (IBAction) do_about_menu_item: (id) sender;
990 - (void)make_about_window;
991 - (void)adjustSpeed:(id)sender;
994 @implementation QemuCocoaAppController
997 COCOA_DEBUG("QemuCocoaAppController: init\n");
1002 // create a view and add it to the window
1003 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1005 fprintf(stderr, "(cocoa) can't create a view\n");
1010 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
1011 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
1012 backing:NSBackingStoreBuffered defer:NO];
1014 fprintf(stderr, "(cocoa) can't create window\n");
1017 [normalWindow setAcceptsMouseMovedEvents:YES];
1018 [normalWindow setTitle:@"QEMU"];
1019 [normalWindow setContentView:cocoaView];
1020 #if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10)
1021 [normalWindow useOptimizedDrawing:YES];
1023 [normalWindow makeKeyAndOrderFront:self];
1024 [normalWindow center];
1025 [normalWindow setDelegate: self];
1026 stretch_video = false;
1028 /* Used for displaying pause on the screen */
1029 pauseLabel = [NSTextField new];
1030 [pauseLabel setBezeled:YES];
1031 [pauseLabel setDrawsBackground:YES];
1032 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1033 [pauseLabel setEditable:NO];
1034 [pauseLabel setSelectable:NO];
1035 [pauseLabel setStringValue: @"Paused"];
1036 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1037 [pauseLabel setTextColor: [NSColor blackColor]];
1038 [pauseLabel sizeToFit];
1040 // set the supported image file types that can be opened
1041 supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
1042 @"qcow", @"qcow2", @"cloop", @"vmdk", @"cdr",
1044 [self make_about_window];
1051 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1054 [cocoaView release];
1058 - (void)applicationDidFinishLaunching: (NSNotification *) note
1060 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1061 // launch QEMU, with the global args
1062 [self startEmulationWithArgc:gArgc argv:(char **)gArgv];
1065 - (void)applicationWillTerminate:(NSNotification *)aNotification
1067 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1069 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1073 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1078 - (NSApplicationTerminateReply)applicationShouldTerminate:
1079 (NSApplication *)sender
1081 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1082 return [self verifyQuit];
1085 /* Called when the user clicks on a window's close button */
1086 - (BOOL)windowShouldClose:(id)sender
1088 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1089 [NSApp terminate: sender];
1090 /* If the user allows the application to quit then the call to
1091 * NSApp terminate will never return. If we get here then the user
1092 * cancelled the quit, so we should return NO to not permit the
1093 * closing of this window.
1098 /* Called when QEMU goes into the background */
1099 - (void) applicationWillResignActive: (NSNotification *)aNotification
1101 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1102 [cocoaView raiseAllKeys];
1105 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv
1107 COCOA_DEBUG("QemuCocoaAppController: startEmulationWithArgc\n");
1110 status = qemu_main(argc, argv, *_NSGetEnviron());
1114 /* We abstract the method called by the Enter Fullscreen menu item
1115 * because Mac OS 10.7 and higher disables it. This is because of the
1116 * menu item's old selector's name toggleFullScreen:
1118 - (void) doToggleFullScreen:(id)sender
1120 [self toggleFullScreen:(id)sender];
1123 - (void)toggleFullScreen:(id)sender
1125 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1127 [cocoaView toggleFullScreen:sender];
1130 /* Tries to find then open the specified filename */
1131 - (void) openDocumentation: (NSString *) filename
1133 /* Where to look for local files */
1134 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"../"};
1135 NSString *full_file_path;
1137 /* iterate thru the possible paths until the file is found */
1139 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1140 full_file_path = [[NSBundle mainBundle] executablePath];
1141 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1142 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1143 path_array[index], filename];
1144 if ([[NSWorkspace sharedWorkspace] openFile: full_file_path] == YES) {
1149 /* If none of the paths opened a file */
1151 QEMU_Alert(@"Failed to open file");
1154 - (void)showQEMUDoc:(id)sender
1156 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1158 [self openDocumentation: @"qemu-doc.html"];
1161 /* Stretches video to fit host monitor size */
1162 - (void)zoomToFit:(id) sender
1164 stretch_video = !stretch_video;
1165 if (stretch_video == true) {
1166 [sender setState: NSControlStateValueOn];
1168 [sender setState: NSControlStateValueOff];
1172 /* Displays the console on the screen */
1173 - (void)displayConsole:(id)sender
1175 console_select([sender tag]);
1178 /* Pause the guest */
1179 - (void)pauseQEMU:(id)sender
1182 [sender setEnabled: NO];
1183 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1184 [self displayPause];
1187 /* Resume running the guest operating system */
1188 - (void)resumeQEMU:(id) sender
1191 [sender setEnabled: NO];
1192 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1196 /* Displays the word pause on the screen */
1197 - (void)displayPause
1199 /* Coordinates have to be calculated each time because the window can change its size */
1200 int xCoord, yCoord, width, height;
1201 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1202 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1203 width = [pauseLabel frame].size.width;
1204 height = [pauseLabel frame].size.height;
1205 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1206 [cocoaView addSubview: pauseLabel];
1209 /* Removes the word pause from the screen */
1212 [pauseLabel removeFromSuperview];
1216 - (void)restartQEMU:(id)sender
1218 qmp_system_reset(NULL);
1221 /* Powers down QEMU */
1222 - (void)powerDownQEMU:(id)sender
1224 qmp_system_powerdown(NULL);
1227 /* Ejects the media.
1228 * Uses sender's tag to figure out the device to eject.
1230 - (void)ejectDeviceMedia:(id)sender
1233 drive = [sender representedObject];
1236 QEMU_Alert(@"Failed to find drive to eject!");
1241 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1242 false, NULL, false, false, &err);
1243 handleAnyDeviceErrors(err);
1246 /* Displays a dialog box asking the user to select an image file to load.
1247 * Uses sender's represented object value to figure out which drive to use.
1249 - (void)changeDeviceMedia:(id)sender
1251 /* Find the drive name */
1253 drive = [sender representedObject];
1256 QEMU_Alert(@"Could not find drive!");
1260 /* Display the file open dialog */
1261 NSOpenPanel * openPanel;
1262 openPanel = [NSOpenPanel openPanel];
1263 [openPanel setCanChooseFiles: YES];
1264 [openPanel setAllowsMultipleSelection: NO];
1265 [openPanel setAllowedFileTypes: supportedImageFileTypes];
1266 if([openPanel runModal] == NSModalResponseOK) {
1267 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1270 QEMU_Alert(@"Failed to convert URL to file path!");
1275 qmp_blockdev_change_medium(true,
1276 [drive cStringUsingEncoding:
1277 NSASCIIStringEncoding],
1279 [file cStringUsingEncoding:
1280 NSASCIIStringEncoding],
1284 handleAnyDeviceErrors(err);
1288 /* Verifies if the user really wants to quit */
1291 NSAlert *alert = [NSAlert new];
1292 [alert autorelease];
1293 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1294 [alert addButtonWithTitle: @"Cancel"];
1295 [alert addButtonWithTitle: @"Quit"];
1296 if([alert runModal] == NSAlertSecondButtonReturn) {
1303 /* The action method for the About menu item */
1304 - (IBAction) do_about_menu_item: (id) sender
1306 [about_window makeKeyAndOrderFront: nil];
1309 /* Create and display the about dialog */
1310 - (void)make_about_window
1312 /* Make the window */
1313 int x = 0, y = 0, about_width = 400, about_height = 200;
1314 NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1315 about_window = [[NSWindow alloc] initWithContentRect:window_rect
1316 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1317 NSWindowStyleMaskMiniaturizable
1318 backing:NSBackingStoreBuffered
1320 [about_window setTitle: @"About"];
1321 [about_window setReleasedWhenClosed: NO];
1322 [about_window center];
1323 NSView *superView = [about_window contentView];
1325 /* Create the dimensions of the picture */
1326 int picture_width = 80, picture_height = 80;
1327 x = (about_width - picture_width)/2;
1328 y = about_height - picture_height - 10;
1329 NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1331 /* Get the path to the QEMU binary */
1332 NSString *binary_name = [NSString stringWithCString: gArgv[0]
1333 encoding: NSASCIIStringEncoding];
1334 binary_name = [binary_name lastPathComponent];
1335 NSString *program_path = [[NSString alloc] initWithFormat: @"%@/%@",
1336 [[NSBundle mainBundle] bundlePath], binary_name];
1338 /* Make the picture of QEMU */
1339 NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1341 NSImage *qemu_image = [[NSWorkspace sharedWorkspace] iconForFile:
1343 [picture_view setImage: qemu_image];
1344 [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1345 [superView addSubview: picture_view];
1347 /* Make the name label */
1350 int name_width = about_width, name_height = 20;
1351 NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1352 NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1353 [name_label setEditable: NO];
1354 [name_label setBezeled: NO];
1355 [name_label setDrawsBackground: NO];
1356 [name_label setAlignment: NSTextAlignmentCenter];
1357 NSString *qemu_name = [[NSString alloc] initWithCString: gArgv[0]
1358 encoding: NSASCIIStringEncoding];
1359 qemu_name = [qemu_name lastPathComponent];
1360 [name_label setStringValue: qemu_name];
1361 [superView addSubview: name_label];
1363 /* Set the version label's attributes */
1366 int version_width = about_width, version_height = 20;
1367 NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1368 NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1370 [version_label setEditable: NO];
1371 [version_label setBezeled: NO];
1372 [version_label setAlignment: NSTextAlignmentCenter];
1373 [version_label setDrawsBackground: NO];
1375 /* Create the version string*/
1376 NSString *version_string;
1377 version_string = [[NSString alloc] initWithFormat:
1378 @"QEMU emulator version %s", QEMU_FULL_VERSION];
1379 [version_label setStringValue: version_string];
1380 [superView addSubview: version_label];
1382 /* Make copyright label */
1385 int copyright_width = about_width, copyright_height = 20;
1386 NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1387 NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1389 [copyright_label setEditable: NO];
1390 [copyright_label setBezeled: NO];
1391 [copyright_label setDrawsBackground: NO];
1392 [copyright_label setAlignment: NSTextAlignmentCenter];
1393 [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1395 [superView addSubview: copyright_label];
1398 /* Used by the Speed menu items */
1399 - (void)adjustSpeed:(id)sender
1401 int throttle_pct; /* throttle percentage */
1404 menu = [sender menu];
1407 /* Unselect the currently selected item */
1408 for (NSMenuItem *item in [menu itemArray]) {
1409 if (item.state == NSControlStateValueOn) {
1410 [item setState: NSControlStateValueOff];
1416 // check the menu item
1417 [sender setState: NSControlStateValueOn];
1419 // get the throttle percentage
1420 throttle_pct = [sender tag];
1422 cpu_throttle_set(throttle_pct);
1423 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1429 int main (int argc, const char * argv[]) {
1432 gArgv = (char **)argv;
1435 /* In case we don't need to display a window, let's not do that */
1436 for (i = 1; i < argc; i++) {
1437 const char *opt = argv[i];
1439 if (opt[0] == '-') {
1440 /* Treat --foo the same as -foo. */
1441 if (opt[1] == '-') {
1444 if (!strcmp(opt, "-h") || !strcmp(opt, "-help") ||
1445 !strcmp(opt, "-vnc") ||
1446 !strcmp(opt, "-nographic") ||
1447 !strcmp(opt, "-version") ||
1448 !strcmp(opt, "-curses") ||
1449 !strcmp(opt, "-display") ||
1450 !strcmp(opt, "-qtest")) {
1451 return qemu_main(gArgc, gArgv, *_NSGetEnviron());
1456 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1458 // Pull this console process up to being a fully-fledged graphical
1459 // app with a menubar and Dock icon
1460 ProcessSerialNumber psn = { 0, kCurrentProcess };
1461 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1463 [NSApplication sharedApplication];
1467 NSMenuItem *menuItem;
1469 [NSApp setMainMenu:[[NSMenu alloc] init]];
1472 menu = [[NSMenu alloc] initWithTitle:@""];
1473 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1474 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1475 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1476 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1477 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1478 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1479 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1480 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1481 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1482 [menuItem setSubmenu:menu];
1483 [[NSApp mainMenu] addItem:menuItem];
1484 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1487 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1488 [menu setAutoenablesItems: NO];
1489 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1490 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1491 [menu addItem: menuItem];
1492 [menuItem setEnabled: NO];
1493 [menu addItem: [NSMenuItem separatorItem]];
1494 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1495 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1496 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1497 [menuItem setSubmenu:menu];
1498 [[NSApp mainMenu] addItem:menuItem];
1501 menu = [[NSMenu alloc] initWithTitle:@"View"];
1502 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1503 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1504 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1505 [menuItem setSubmenu:menu];
1506 [[NSApp mainMenu] addItem:menuItem];
1509 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1511 // Add the rest of the Speed menu items
1512 int p, percentage, throttle_pct;
1513 for (p = 10; p >= 0; p--)
1515 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1517 menuItem = [[[NSMenuItem alloc]
1518 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1520 if (percentage == 100) {
1521 [menuItem setState: NSControlStateValueOn];
1524 /* Calculate the throttle percentage */
1525 throttle_pct = -1 * percentage + 100;
1527 [menuItem setTag: throttle_pct];
1528 [menu addItem: menuItem];
1530 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1531 [menuItem setSubmenu:menu];
1532 [[NSApp mainMenu] addItem:menuItem];
1535 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1536 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1537 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1538 [menuItem setSubmenu:menu];
1539 [[NSApp mainMenu] addItem:menuItem];
1540 [NSApp setWindowsMenu:menu];
1543 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1544 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1545 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1546 [menuItem setSubmenu:menu];
1547 [[NSApp mainMenu] addItem:menuItem];
1549 // Create an Application controller
1550 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1551 [NSApp setDelegate:appController];
1553 // Start the main event loop
1556 [appController release];
1565 static void cocoa_update(DisplayChangeListener *dcl,
1566 int x, int y, int w, int h)
1568 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1570 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1573 if ([cocoaView cdx] == 1.0) {
1574 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1577 x * [cocoaView cdx],
1578 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1579 w * [cocoaView cdx],
1580 h * [cocoaView cdy]);
1582 [cocoaView setNeedsDisplayInRect:rect];
1587 static void cocoa_switch(DisplayChangeListener *dcl,
1588 DisplaySurface *surface)
1590 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1592 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1593 [cocoaView switchSurface:surface];
1597 static void cocoa_refresh(DisplayChangeListener *dcl)
1599 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1601 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
1602 graphic_hw_update(NULL);
1604 if (qemu_input_is_absolute()) {
1605 if (![cocoaView isAbsoluteEnabled]) {
1606 if ([cocoaView isMouseGrabbed]) {
1607 [cocoaView ungrabMouse];
1610 [cocoaView setAbsoluteEnabled:YES];
1613 NSDate *distantPast;
1615 distantPast = [NSDate distantPast];
1617 event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:distantPast
1618 inMode: NSDefaultRunLoopMode dequeue:YES];
1620 [cocoaView handleEvent:event];
1622 } while(event != nil);
1626 static void cocoa_cleanup(void)
1628 COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
1632 static const DisplayChangeListenerOps dcl_ops = {
1633 .dpy_name = "cocoa",
1634 .dpy_gfx_update = cocoa_update,
1635 .dpy_gfx_switch = cocoa_switch,
1636 .dpy_refresh = cocoa_refresh,
1639 /* Returns a name for a given console */
1640 static NSString * getConsoleName(QemuConsole * console)
1642 return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1645 /* Add an entry to the View menu for each console */
1646 static void add_console_menu_entries(void)
1649 NSMenuItem *menuItem;
1652 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1654 [menu addItem:[NSMenuItem separatorItem]];
1656 while (qemu_console_lookup_by_index(index) != NULL) {
1657 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1658 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1659 [menuItem setTag: index];
1660 [menu addItem: menuItem];
1665 /* Make menu items for all removable devices.
1666 * Each device is given an 'Eject' and 'Change' menu item.
1668 static void addRemovableDevicesMenuItems(void)
1671 NSMenuItem *menuItem;
1672 BlockInfoList *currentDevice, *pointerToFree;
1673 NSString *deviceName;
1675 currentDevice = qmp_query_block(NULL);
1676 pointerToFree = currentDevice;
1677 if(currentDevice == NULL) {
1679 QEMU_Alert(@"Failed to query for block devices!");
1683 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1685 // Add a separator between related groups of menu items
1686 [menu addItem:[NSMenuItem separatorItem]];
1688 // Set the attributes to the "Removable Media" menu item
1689 NSString *titleString = @"Removable Media";
1690 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1691 NSColor *newColor = [NSColor blackColor];
1692 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1693 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1694 traits:NSBoldFontMask|NSItalicFontMask
1697 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1698 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1699 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1701 // Add the "Removable Media" menu item
1702 menuItem = [NSMenuItem new];
1703 [menuItem setAttributedTitle: attString];
1704 [menuItem setEnabled: NO];
1705 [menu addItem: menuItem];
1707 /* Loop through all the block devices in the emulator */
1708 while (currentDevice) {
1709 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1711 if(currentDevice->value->removable) {
1712 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1713 action: @selector(changeDeviceMedia:)
1714 keyEquivalent: @""];
1715 [menu addItem: menuItem];
1716 [menuItem setRepresentedObject: deviceName];
1717 [menuItem autorelease];
1719 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1720 action: @selector(ejectDeviceMedia:)
1721 keyEquivalent: @""];
1722 [menu addItem: menuItem];
1723 [menuItem setRepresentedObject: deviceName];
1724 [menuItem autorelease];
1726 currentDevice = currentDevice->next;
1728 qapi_free_BlockInfoList(pointerToFree);
1731 static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
1733 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1735 /* if fullscreen mode is to be used */
1736 if (opts->has_full_screen && opts->full_screen) {
1737 [NSApp activateIgnoringOtherApps: YES];
1738 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1741 dcl = g_malloc0(sizeof(DisplayChangeListener));
1743 // register vga output callbacks
1744 dcl->ops = &dcl_ops;
1745 register_displaychangelistener(dcl);
1747 // register cleanup function
1748 atexit(cocoa_cleanup);
1750 /* At this point QEMU has created all the consoles, so we can add View
1751 * menu entries for them.
1753 add_console_menu_entries();
1755 /* Give all removable devices a menu item.
1756 * Has to be called after QEMU has started to
1757 * find out what removable devices it has.
1759 addRemovableDevicesMenuItems();
1762 static QemuDisplay qemu_display_cocoa = {
1763 .type = DISPLAY_TYPE_COCOA,
1764 .init = cocoa_display_init,
1767 static void register_cocoa(void)
1769 qemu_display_register(&qemu_display_cocoa);
1772 type_init(register_cocoa);