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 "qmp-commands.h"
36 #include "sysemu/blockdev.h"
37 #include "qemu-version.h"
38 #include <Carbon/Carbon.h>
41 #ifndef MAC_OS_X_VERSION_10_5
42 #define MAC_OS_X_VERSION_10_5 1050
44 #ifndef MAC_OS_X_VERSION_10_6
45 #define MAC_OS_X_VERSION_10_6 1060
47 #ifndef MAC_OS_X_VERSION_10_10
48 #define MAC_OS_X_VERSION_10_10 101000
50 #ifndef MAC_OS_X_VERSION_10_12
51 #define MAC_OS_X_VERSION_10_12 101200
54 /* macOS 10.12 deprecated many constants, #define the new names for older SDKs */
55 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_12
56 #define NSEventMaskAny NSAnyEventMask
57 #define NSEventModifierFlagCapsLock NSAlphaShiftKeyMask
58 #define NSEventModifierFlagShift NSShiftKeyMask
59 #define NSEventModifierFlagCommand NSCommandKeyMask
60 #define NSEventModifierFlagControl NSControlKeyMask
61 #define NSEventModifierFlagOption NSAlternateKeyMask
62 #define NSEventTypeFlagsChanged NSFlagsChanged
63 #define NSEventTypeKeyUp NSKeyUp
64 #define NSEventTypeKeyDown NSKeyDown
65 #define NSEventTypeMouseMoved NSMouseMoved
66 #define NSEventTypeLeftMouseDown NSLeftMouseDown
67 #define NSEventTypeRightMouseDown NSRightMouseDown
68 #define NSEventTypeOtherMouseDown NSOtherMouseDown
69 #define NSEventTypeLeftMouseDragged NSLeftMouseDragged
70 #define NSEventTypeRightMouseDragged NSRightMouseDragged
71 #define NSEventTypeOtherMouseDragged NSOtherMouseDragged
72 #define NSEventTypeLeftMouseUp NSLeftMouseUp
73 #define NSEventTypeRightMouseUp NSRightMouseUp
74 #define NSEventTypeOtherMouseUp NSOtherMouseUp
75 #define NSEventTypeScrollWheel NSScrollWheel
76 #define NSTextAlignmentCenter NSCenterTextAlignment
77 #define NSWindowStyleMaskBorderless NSBorderlessWindowMask
78 #define NSWindowStyleMaskClosable NSClosableWindowMask
79 #define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask
80 #define NSWindowStyleMaskTitled NSTitledWindowMask
86 #define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
88 #define COCOA_DEBUG(...) ((void) 0)
91 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
100 NSWindow *normalWindow, *about_window;
101 static DisplayChangeListener *dcl;
102 static int last_buttons;
107 NSTextField *pauseLabel;
108 NSArray * supportedImageFileTypes;
110 // Mac to QKeyCode conversion
111 const int mac_to_qkeycode_map[] = {
112 [kVK_ANSI_A] = Q_KEY_CODE_A,
113 [kVK_ANSI_B] = Q_KEY_CODE_B,
114 [kVK_ANSI_C] = Q_KEY_CODE_C,
115 [kVK_ANSI_D] = Q_KEY_CODE_D,
116 [kVK_ANSI_E] = Q_KEY_CODE_E,
117 [kVK_ANSI_F] = Q_KEY_CODE_F,
118 [kVK_ANSI_G] = Q_KEY_CODE_G,
119 [kVK_ANSI_H] = Q_KEY_CODE_H,
120 [kVK_ANSI_I] = Q_KEY_CODE_I,
121 [kVK_ANSI_J] = Q_KEY_CODE_J,
122 [kVK_ANSI_K] = Q_KEY_CODE_K,
123 [kVK_ANSI_L] = Q_KEY_CODE_L,
124 [kVK_ANSI_M] = Q_KEY_CODE_M,
125 [kVK_ANSI_N] = Q_KEY_CODE_N,
126 [kVK_ANSI_O] = Q_KEY_CODE_O,
127 [kVK_ANSI_P] = Q_KEY_CODE_P,
128 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
129 [kVK_ANSI_R] = Q_KEY_CODE_R,
130 [kVK_ANSI_S] = Q_KEY_CODE_S,
131 [kVK_ANSI_T] = Q_KEY_CODE_T,
132 [kVK_ANSI_U] = Q_KEY_CODE_U,
133 [kVK_ANSI_V] = Q_KEY_CODE_V,
134 [kVK_ANSI_W] = Q_KEY_CODE_W,
135 [kVK_ANSI_X] = Q_KEY_CODE_X,
136 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
137 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
139 [kVK_ANSI_0] = Q_KEY_CODE_0,
140 [kVK_ANSI_1] = Q_KEY_CODE_1,
141 [kVK_ANSI_2] = Q_KEY_CODE_2,
142 [kVK_ANSI_3] = Q_KEY_CODE_3,
143 [kVK_ANSI_4] = Q_KEY_CODE_4,
144 [kVK_ANSI_5] = Q_KEY_CODE_5,
145 [kVK_ANSI_6] = Q_KEY_CODE_6,
146 [kVK_ANSI_7] = Q_KEY_CODE_7,
147 [kVK_ANSI_8] = Q_KEY_CODE_8,
148 [kVK_ANSI_9] = Q_KEY_CODE_9,
150 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
151 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
152 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
153 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
154 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
155 [kVK_Tab] = Q_KEY_CODE_TAB,
156 [kVK_Return] = Q_KEY_CODE_RET,
157 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
158 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
159 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
160 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
161 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
162 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
163 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
164 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
165 [kVK_Shift] = Q_KEY_CODE_SHIFT,
166 [kVK_RightShift] = Q_KEY_CODE_SHIFT_R,
167 [kVK_Control] = Q_KEY_CODE_CTRL,
168 [kVK_RightControl] = Q_KEY_CODE_CTRL_R,
169 [kVK_Option] = Q_KEY_CODE_ALT,
170 [kVK_RightOption] = Q_KEY_CODE_ALT_R,
171 [kVK_Command] = Q_KEY_CODE_META_L,
172 [0x36] = Q_KEY_CODE_META_R, /* There is no kVK_RightCommand */
173 [kVK_Space] = Q_KEY_CODE_SPC,
175 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
176 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
177 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
178 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
179 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
180 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
181 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
182 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
183 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
184 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
185 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
186 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
187 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
188 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
189 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
190 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
191 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
192 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
194 [kVK_UpArrow] = Q_KEY_CODE_UP,
195 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
196 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
197 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
199 [kVK_Help] = Q_KEY_CODE_INSERT,
200 [kVK_Home] = Q_KEY_CODE_HOME,
201 [kVK_PageUp] = Q_KEY_CODE_PGUP,
202 [kVK_PageDown] = Q_KEY_CODE_PGDN,
203 [kVK_End] = Q_KEY_CODE_END,
204 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
206 [kVK_Escape] = Q_KEY_CODE_ESC,
208 /* The Power key can't be used directly because the operating system uses
209 * it. This key can be emulated by using it in place of another key such as
210 * F1. Don't forget to disable the real key binding.
212 /* [kVK_F1] = Q_KEY_CODE_POWER, */
214 [kVK_F1] = Q_KEY_CODE_F1,
215 [kVK_F2] = Q_KEY_CODE_F2,
216 [kVK_F3] = Q_KEY_CODE_F3,
217 [kVK_F4] = Q_KEY_CODE_F4,
218 [kVK_F5] = Q_KEY_CODE_F5,
219 [kVK_F6] = Q_KEY_CODE_F6,
220 [kVK_F7] = Q_KEY_CODE_F7,
221 [kVK_F8] = Q_KEY_CODE_F8,
222 [kVK_F9] = Q_KEY_CODE_F9,
223 [kVK_F10] = Q_KEY_CODE_F10,
224 [kVK_F11] = Q_KEY_CODE_F11,
225 [kVK_F12] = Q_KEY_CODE_F12,
226 [kVK_F13] = Q_KEY_CODE_PRINT,
227 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
228 [kVK_F15] = Q_KEY_CODE_PAUSE,
231 * The eject and volume keys can't be used here because they are handled at
232 * a lower level than what an Application can see.
236 static int cocoa_keycode_to_qemu(int keycode)
238 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
239 fprintf(stderr, "(cocoa) warning unknown keycode 0x%x\n", keycode);
242 return mac_to_qkeycode_map[keycode];
245 /* Displays an alert dialog box with the specified message */
246 static void QEMU_Alert(NSString *message)
249 alert = [NSAlert new];
250 [alert setMessageText: message];
254 /* Handles any errors that happen with a device transaction */
255 static void handleAnyDeviceErrors(Error * err)
258 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
259 encoding: NSASCIIStringEncoding]);
265 ------------------------------------------------------
267 ------------------------------------------------------
269 @interface QemuCocoaView : NSView
272 NSWindow *fullScreenWindow;
273 float cx,cy,cw,ch,cdx,cdy;
274 CGDataProviderRef dataProviderRef;
275 BOOL modifiers_state[256];
278 BOOL isAbsoluteEnabled;
279 BOOL isMouseDeassociated;
281 - (void) switchSurface:(DisplaySurface *)surface;
283 - (void) ungrabMouse;
284 - (void) toggleFullScreen:(id)sender;
285 - (void) handleMonitorInput:(NSEvent *)event;
286 - (void) handleEvent:(NSEvent *)event;
287 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
288 /* The state surrounding mouse grabbing is potentially confusing.
289 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
290 * pointing device an absolute-position one?"], but is only updated on
292 * isMouseGrabbed tracks whether GUI events are directed to the guest;
293 * it controls whether special keys like Cmd get sent to the guest,
294 * and whether we capture the mouse when in non-absolute mode.
295 * isMouseDeassociated tracks whether we've told MacOSX to disassociate
296 * the mouse and mouse cursor position by calling
297 * CGAssociateMouseAndMouseCursorPosition(FALSE)
298 * (which basically happens if we grab in non-absolute mode).
300 - (BOOL) isMouseGrabbed;
301 - (BOOL) isAbsoluteEnabled;
302 - (BOOL) isMouseDeassociated;
305 - (QEMUScreen) gscreen;
306 - (void) raiseAllKeys;
309 QemuCocoaView *cocoaView;
311 @implementation QemuCocoaView
312 - (id)initWithFrame:(NSRect)frameRect
314 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
316 self = [super initWithFrame:frameRect];
319 screen.bitsPerComponent = 8;
320 screen.bitsPerPixel = 32;
321 screen.width = frameRect.size.width;
322 screen.height = frameRect.size.height;
330 COCOA_DEBUG("QemuCocoaView: dealloc\n");
333 CGDataProviderRelease(dataProviderRef);
343 - (BOOL) screenContainsPoint:(NSPoint) p
345 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
356 - (void) unhideCursor
364 - (void) drawRect:(NSRect) rect
366 COCOA_DEBUG("QemuCocoaView: drawRect\n");
368 // get CoreGraphic context
369 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] graphicsPort];
370 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
371 CGContextSetShouldAntialias (viewContextRef, NO);
373 // draw screen bitmap directly to Core Graphics context
374 if (!dataProviderRef) {
375 // Draw request before any guest device has set up a framebuffer:
376 // just draw an opaque black rectangle
377 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
378 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
380 CGImageRef imageRef = CGImageCreate(
381 screen.width, //width
382 screen.height, //height
383 screen.bitsPerComponent, //bitsPerComponent
384 screen.bitsPerPixel, //bitsPerPixel
385 (screen.width * (screen.bitsPerComponent/2)), //bytesPerRow
386 #ifdef __LITTLE_ENDIAN__
387 CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
388 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
390 CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
391 kCGImageAlphaNoneSkipFirst, //bitmapInfo
393 dataProviderRef, //provider
396 kCGRenderingIntentDefault //intent
398 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
399 const NSRect *rectList;
402 CGImageRef clipImageRef;
405 [self getRectsBeingDrawn:&rectList count:&rectCount];
406 for (i = 0; i < rectCount; i++) {
407 clipRect.origin.x = rectList[i].origin.x / cdx;
408 clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
409 clipRect.size.width = rectList[i].size.width / cdx;
410 clipRect.size.height = rectList[i].size.height / cdy;
411 clipImageRef = CGImageCreateWithImageInRect(
415 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
416 CGImageRelease (clipImageRef);
418 CGImageRelease (imageRef);
422 - (void) setContentDimensions
424 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
427 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
428 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
430 /* stretches video, but keeps same aspect ratio */
431 if (stretch_video == true) {
432 /* use smallest stretch value - prevents clipping on sides */
433 if (MIN(cdx, cdy) == cdx) {
438 } else { /* No stretching */
441 cw = screen.width * cdx;
442 ch = screen.height * cdy;
443 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
444 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
455 - (void) switchSurface:(DisplaySurface *)surface
457 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
459 int w = surface_width(surface);
460 int h = surface_height(surface);
461 /* cdx == 0 means this is our very first surface, in which case we need
462 * to recalculate the content dimensions even if it happens to be the size
463 * of the initial empty window.
465 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
467 int oldh = screen.height;
469 // Resize before we trigger the redraw, or we'll redraw at the wrong size
470 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
473 [self setContentDimensions];
474 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
477 // update screenBuffer
479 CGDataProviderRelease(dataProviderRef);
481 //sync host window color space with guests
482 screen.bitsPerPixel = surface_bits_per_pixel(surface);
483 screen.bitsPerComponent = surface_bytes_per_pixel(surface) * 2;
485 dataProviderRef = CGDataProviderCreateWithData(NULL, surface_data(surface), w * 4 * h, NULL);
489 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
490 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
493 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
494 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
498 [normalWindow center];
502 - (void) toggleFullScreen:(id)sender
504 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
506 if (isFullscreen) { // switch from fullscreen to desktop
507 isFullscreen = FALSE;
509 [self setContentDimensions];
510 if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
511 [self exitFullScreenModeWithOptions:nil];
513 [fullScreenWindow close];
514 [normalWindow setContentView: self];
515 [normalWindow makeKeyAndOrderFront: self];
516 [NSMenu setMenuBarVisible:YES];
518 } else { // switch from desktop to fullscreen
520 [normalWindow orderOut: nil]; /* Hide the window */
522 [self setContentDimensions];
523 if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
524 [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
525 [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
526 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
529 [NSMenu setMenuBarVisible:NO];
530 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
531 styleMask:NSWindowStyleMaskBorderless
532 backing:NSBackingStoreBuffered
534 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
535 [fullScreenWindow setHasShadow:NO];
536 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
537 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
538 [[fullScreenWindow contentView] addSubview: self];
539 [fullScreenWindow makeKeyAndOrderFront:self];
544 - (void) toggleModifier: (int)keycode {
545 // Toggle the stored state.
546 modifiers_state[keycode] = !modifiers_state[keycode];
547 // Send a keyup or keydown depending on the state.
548 qemu_input_event_send_key_qcode(dcl->con, keycode, modifiers_state[keycode]);
551 - (void) toggleStatefulModifier: (int)keycode {
552 // Toggle the stored state.
553 modifiers_state[keycode] = !modifiers_state[keycode];
554 // Generate keydown and keyup.
555 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
556 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
559 // Does the work of sending input to the monitor
560 - (void) handleMonitorInput:(NSEvent *)event
565 // if the control key is down
566 if ([event modifierFlags] & NSEventModifierFlagControl) {
570 /* translates Macintosh keycodes to QEMU's keysym */
572 int without_control_translation[] = {
573 [0 ... 0xff] = 0, // invalid key
575 [kVK_UpArrow] = QEMU_KEY_UP,
576 [kVK_DownArrow] = QEMU_KEY_DOWN,
577 [kVK_RightArrow] = QEMU_KEY_RIGHT,
578 [kVK_LeftArrow] = QEMU_KEY_LEFT,
579 [kVK_Home] = QEMU_KEY_HOME,
580 [kVK_End] = QEMU_KEY_END,
581 [kVK_PageUp] = QEMU_KEY_PAGEUP,
582 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
583 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
584 [kVK_Delete] = QEMU_KEY_BACKSPACE,
587 int with_control_translation[] = {
588 [0 ... 0xff] = 0, // invalid key
590 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
591 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
592 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
593 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
594 [kVK_Home] = QEMU_KEY_CTRL_HOME,
595 [kVK_End] = QEMU_KEY_CTRL_END,
596 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
597 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
600 if (control_key != 0) { /* If the control key is being used */
601 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
602 keysym = with_control_translation[[event keyCode]];
605 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
606 keysym = without_control_translation[[event keyCode]];
610 // if not a key that needs translating
612 NSString *ks = [event characters];
613 if ([ks length] > 0) {
614 keysym = [ks characterAtIndex:0];
619 kbd_put_keysym(keysym);
623 - (void) handleEvent:(NSEvent *)event
625 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
629 bool mouse_event = false;
630 NSPoint p = [event locationInWindow];
632 switch ([event type]) {
633 case NSEventTypeFlagsChanged:
634 if ([event keyCode] == 0) {
635 // When the Cocoa keyCode is zero that means keys should be
636 // synthesized based on the values in in the eventModifiers
639 if (qemu_console_is_graphic(NULL)) {
640 NSUInteger modifiers = [event modifierFlags];
642 if (!!(modifiers & NSEventModifierFlagCapsLock) != !!modifiers_state[Q_KEY_CODE_CAPS_LOCK]) {
643 [self toggleStatefulModifier:Q_KEY_CODE_CAPS_LOCK];
645 if (!!(modifiers & NSEventModifierFlagShift) != !!modifiers_state[Q_KEY_CODE_SHIFT]) {
646 [self toggleModifier:Q_KEY_CODE_SHIFT];
648 if (!!(modifiers & NSEventModifierFlagControl) != !!modifiers_state[Q_KEY_CODE_CTRL]) {
649 [self toggleModifier:Q_KEY_CODE_CTRL];
651 if (!!(modifiers & NSEventModifierFlagOption) != !!modifiers_state[Q_KEY_CODE_ALT]) {
652 [self toggleModifier:Q_KEY_CODE_ALT];
654 if (!!(modifiers & NSEventModifierFlagCommand) != !!modifiers_state[Q_KEY_CODE_META_L]) {
655 [self toggleModifier:Q_KEY_CODE_META_L];
659 keycode = cocoa_keycode_to_qemu([event keyCode]);
662 if ((keycode == Q_KEY_CODE_META_L || keycode == Q_KEY_CODE_META_R)
663 && !isMouseGrabbed) {
664 /* Don't pass command key changes to guest unless mouse is grabbed */
669 // emulate caps lock and num lock keydown and keyup
670 if (keycode == Q_KEY_CODE_CAPS_LOCK ||
671 keycode == Q_KEY_CODE_NUM_LOCK) {
672 [self toggleStatefulModifier:keycode];
673 } else if (qemu_console_is_graphic(NULL)) {
674 [self toggleModifier:keycode];
679 case NSEventTypeKeyDown:
680 keycode = cocoa_keycode_to_qemu([event keyCode]);
682 // forward command key combos to the host UI unless the mouse is grabbed
683 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
684 [NSApp sendEvent:event];
690 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
691 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
692 NSString *keychar = [event charactersIgnoringModifiers];
693 if ([keychar length] == 1) {
694 char key = [keychar characterAtIndex:0];
697 // enable graphic console
699 console_select(key - '0' - 1); /* ascii math */
702 // release the mouse grab
710 if (qemu_console_is_graphic(NULL)) {
711 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
713 [self handleMonitorInput: event];
716 case NSEventTypeKeyUp:
717 keycode = cocoa_keycode_to_qemu([event keyCode]);
719 // don't pass the guest a spurious key-up if we treated this
720 // command-key combo as a host UI action
721 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
725 if (qemu_console_is_graphic(NULL)) {
726 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
729 case NSEventTypeMouseMoved:
730 if (isAbsoluteEnabled) {
731 if (![self screenContainsPoint:p] || ![[self window] isKeyWindow]) {
732 if (isMouseGrabbed) {
736 if (!isMouseGrabbed) {
743 case NSEventTypeLeftMouseDown:
744 if ([event modifierFlags] & NSEventModifierFlagCommand) {
745 buttons |= MOUSE_EVENT_RBUTTON;
747 buttons |= MOUSE_EVENT_LBUTTON;
751 case NSEventTypeRightMouseDown:
752 buttons |= MOUSE_EVENT_RBUTTON;
755 case NSEventTypeOtherMouseDown:
756 buttons |= MOUSE_EVENT_MBUTTON;
759 case NSEventTypeLeftMouseDragged:
760 if ([event modifierFlags] & NSEventModifierFlagCommand) {
761 buttons |= MOUSE_EVENT_RBUTTON;
763 buttons |= MOUSE_EVENT_LBUTTON;
767 case NSEventTypeRightMouseDragged:
768 buttons |= MOUSE_EVENT_RBUTTON;
771 case NSEventTypeOtherMouseDragged:
772 buttons |= MOUSE_EVENT_MBUTTON;
775 case NSEventTypeLeftMouseUp:
777 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
778 if([[self window] isKeyWindow]) {
783 case NSEventTypeRightMouseUp:
786 case NSEventTypeOtherMouseUp:
789 case NSEventTypeScrollWheel:
791 * Send wheel events to the guest regardless of window focus.
792 * This is in-line with standard Mac OS X UI behaviour.
795 /* Determine if this is a scroll up or scroll down event */
796 buttons = ([event scrollingDeltaY] > 0) ?
797 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
798 qemu_input_queue_btn(dcl->con, buttons, true);
799 qemu_input_event_sync();
800 qemu_input_queue_btn(dcl->con, buttons, false);
801 qemu_input_event_sync();
804 * Since deltaY also reports scroll wheel events we prevent mouse
805 * movement code from executing.
810 [NSApp sendEvent:event];
814 /* Don't send button events to the guest unless we've got a
815 * mouse grab or window focus. If we have neither then this event
816 * is the user clicking on the background window to activate and
817 * bring us to the front, which will be done by the sendEvent
818 * call below. We definitely don't want to pass that click through
821 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
822 (last_buttons != buttons)) {
823 static uint32_t bmap[INPUT_BUTTON__MAX] = {
824 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
825 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
826 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
828 qemu_input_update_buttons(dcl->con, bmap, last_buttons, buttons);
829 last_buttons = buttons;
831 if (isMouseGrabbed) {
832 if (isAbsoluteEnabled) {
833 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
834 * The check on screenContainsPoint is to avoid sending out of range values for
835 * clicks in the titlebar.
837 if ([self screenContainsPoint:p]) {
838 qemu_input_queue_abs(dcl->con, INPUT_AXIS_X, p.x, 0, screen.width);
839 qemu_input_queue_abs(dcl->con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
842 qemu_input_queue_rel(dcl->con, INPUT_AXIS_X, (int)[event deltaX]);
843 qemu_input_queue_rel(dcl->con, INPUT_AXIS_Y, (int)[event deltaY]);
846 [NSApp sendEvent:event];
848 qemu_input_event_sync();
854 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
858 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
860 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
863 if (!isAbsoluteEnabled) {
864 isMouseDeassociated = TRUE;
865 CGAssociateMouseAndMouseCursorPosition(FALSE);
867 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
872 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
876 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
878 [normalWindow setTitle:@"QEMU"];
881 if (isMouseDeassociated) {
882 CGAssociateMouseAndMouseCursorPosition(TRUE);
883 isMouseDeassociated = FALSE;
885 isMouseGrabbed = FALSE;
888 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
889 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
890 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
891 - (BOOL) isMouseDeassociated {return isMouseDeassociated;}
892 - (float) cdx {return cdx;}
893 - (float) cdy {return cdy;}
894 - (QEMUScreen) gscreen {return screen;}
897 * Makes the target think all down keys are being released.
898 * This prevents a stuck key problem, since we will not see
899 * key up events for those keys after we have lost focus.
901 - (void) raiseAllKeys
904 const int max_index = ARRAY_SIZE(modifiers_state);
906 for (index = 0; index < max_index; index++) {
907 if (modifiers_state[index]) {
908 modifiers_state[index] = 0;
909 qemu_input_event_send_key_qcode(dcl->con, index, false);
918 ------------------------------------------------------
919 QemuCocoaAppController
920 ------------------------------------------------------
922 @interface QemuCocoaAppController : NSObject
923 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
924 <NSWindowDelegate, NSApplicationDelegate>
928 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv;
929 - (void)doToggleFullScreen:(id)sender;
930 - (void)toggleFullScreen:(id)sender;
931 - (void)showQEMUDoc:(id)sender;
932 - (void)zoomToFit:(id) sender;
933 - (void)displayConsole:(id)sender;
934 - (void)pauseQEMU:(id)sender;
935 - (void)resumeQEMU:(id)sender;
936 - (void)displayPause;
938 - (void)restartQEMU:(id)sender;
939 - (void)powerDownQEMU:(id)sender;
940 - (void)ejectDeviceMedia:(id)sender;
941 - (void)changeDeviceMedia:(id)sender;
943 - (void)openDocumentation:(NSString *)filename;
944 - (IBAction) do_about_menu_item: (id) sender;
945 - (void)make_about_window;
946 - (void)adjustSpeed:(id)sender;
949 @implementation QemuCocoaAppController
952 COCOA_DEBUG("QemuCocoaAppController: init\n");
957 // create a view and add it to the window
958 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
960 fprintf(stderr, "(cocoa) can't create a view\n");
965 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
966 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
967 backing:NSBackingStoreBuffered defer:NO];
969 fprintf(stderr, "(cocoa) can't create window\n");
972 [normalWindow setAcceptsMouseMovedEvents:YES];
973 [normalWindow setTitle:@"QEMU"];
974 [normalWindow setContentView:cocoaView];
975 #if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10)
976 [normalWindow useOptimizedDrawing:YES];
978 [normalWindow makeKeyAndOrderFront:self];
979 [normalWindow center];
980 [normalWindow setDelegate: self];
981 stretch_video = false;
983 /* Used for displaying pause on the screen */
984 pauseLabel = [NSTextField new];
985 [pauseLabel setBezeled:YES];
986 [pauseLabel setDrawsBackground:YES];
987 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
988 [pauseLabel setEditable:NO];
989 [pauseLabel setSelectable:NO];
990 [pauseLabel setStringValue: @"Paused"];
991 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
992 [pauseLabel setTextColor: [NSColor blackColor]];
993 [pauseLabel sizeToFit];
995 // set the supported image file types that can be opened
996 supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
997 @"qcow", @"qcow2", @"cloop", @"vmdk", @"cdr",
999 [self make_about_window];
1006 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1009 [cocoaView release];
1013 - (void)applicationDidFinishLaunching: (NSNotification *) note
1015 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1016 // launch QEMU, with the global args
1017 [self startEmulationWithArgc:gArgc argv:(char **)gArgv];
1020 - (void)applicationWillTerminate:(NSNotification *)aNotification
1022 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1024 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1028 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1033 - (NSApplicationTerminateReply)applicationShouldTerminate:
1034 (NSApplication *)sender
1036 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1037 return [self verifyQuit];
1040 /* Called when the user clicks on a window's close button */
1041 - (BOOL)windowShouldClose:(id)sender
1043 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1044 [NSApp terminate: sender];
1045 /* If the user allows the application to quit then the call to
1046 * NSApp terminate will never return. If we get here then the user
1047 * cancelled the quit, so we should return NO to not permit the
1048 * closing of this window.
1053 /* Called when QEMU goes into the background */
1054 - (void) applicationWillResignActive: (NSNotification *)aNotification
1056 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1057 [cocoaView raiseAllKeys];
1060 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv
1062 COCOA_DEBUG("QemuCocoaAppController: startEmulationWithArgc\n");
1065 status = qemu_main(argc, argv, *_NSGetEnviron());
1069 /* We abstract the method called by the Enter Fullscreen menu item
1070 * because Mac OS 10.7 and higher disables it. This is because of the
1071 * menu item's old selector's name toggleFullScreen:
1073 - (void) doToggleFullScreen:(id)sender
1075 [self toggleFullScreen:(id)sender];
1078 - (void)toggleFullScreen:(id)sender
1080 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1082 [cocoaView toggleFullScreen:sender];
1085 /* Tries to find then open the specified filename */
1086 - (void) openDocumentation: (NSString *) filename
1088 /* Where to look for local files */
1089 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"../"};
1090 NSString *full_file_path;
1092 /* iterate thru the possible paths until the file is found */
1094 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1095 full_file_path = [[NSBundle mainBundle] executablePath];
1096 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1097 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1098 path_array[index], filename];
1099 if ([[NSWorkspace sharedWorkspace] openFile: full_file_path] == YES) {
1104 /* If none of the paths opened a file */
1106 QEMU_Alert(@"Failed to open file");
1109 - (void)showQEMUDoc:(id)sender
1111 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1113 [self openDocumentation: @"qemu-doc.html"];
1116 /* Stretches video to fit host monitor size */
1117 - (void)zoomToFit:(id) sender
1119 stretch_video = !stretch_video;
1120 if (stretch_video == true) {
1121 [sender setState: NSOnState];
1123 [sender setState: NSOffState];
1127 /* Displays the console on the screen */
1128 - (void)displayConsole:(id)sender
1130 console_select([sender tag]);
1133 /* Pause the guest */
1134 - (void)pauseQEMU:(id)sender
1137 [sender setEnabled: NO];
1138 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1139 [self displayPause];
1142 /* Resume running the guest operating system */
1143 - (void)resumeQEMU:(id) sender
1146 [sender setEnabled: NO];
1147 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1151 /* Displays the word pause on the screen */
1152 - (void)displayPause
1154 /* Coordinates have to be calculated each time because the window can change its size */
1155 int xCoord, yCoord, width, height;
1156 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1157 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1158 width = [pauseLabel frame].size.width;
1159 height = [pauseLabel frame].size.height;
1160 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1161 [cocoaView addSubview: pauseLabel];
1164 /* Removes the word pause from the screen */
1167 [pauseLabel removeFromSuperview];
1171 - (void)restartQEMU:(id)sender
1173 qmp_system_reset(NULL);
1176 /* Powers down QEMU */
1177 - (void)powerDownQEMU:(id)sender
1179 qmp_system_powerdown(NULL);
1182 /* Ejects the media.
1183 * Uses sender's tag to figure out the device to eject.
1185 - (void)ejectDeviceMedia:(id)sender
1188 drive = [sender representedObject];
1191 QEMU_Alert(@"Failed to find drive to eject!");
1196 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1197 false, NULL, false, false, &err);
1198 handleAnyDeviceErrors(err);
1201 /* Displays a dialog box asking the user to select an image file to load.
1202 * Uses sender's represented object value to figure out which drive to use.
1204 - (void)changeDeviceMedia:(id)sender
1206 /* Find the drive name */
1208 drive = [sender representedObject];
1211 QEMU_Alert(@"Could not find drive!");
1215 /* Display the file open dialog */
1216 NSOpenPanel * openPanel;
1217 openPanel = [NSOpenPanel openPanel];
1218 [openPanel setCanChooseFiles: YES];
1219 [openPanel setAllowsMultipleSelection: NO];
1220 [openPanel setAllowedFileTypes: supportedImageFileTypes];
1221 if([openPanel runModal] == NSFileHandlingPanelOKButton) {
1222 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1225 QEMU_Alert(@"Failed to convert URL to file path!");
1230 qmp_blockdev_change_medium(true,
1231 [drive cStringUsingEncoding:
1232 NSASCIIStringEncoding],
1234 [file cStringUsingEncoding:
1235 NSASCIIStringEncoding],
1239 handleAnyDeviceErrors(err);
1243 /* Verifies if the user really wants to quit */
1246 NSAlert *alert = [NSAlert new];
1247 [alert autorelease];
1248 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1249 [alert addButtonWithTitle: @"Cancel"];
1250 [alert addButtonWithTitle: @"Quit"];
1251 if([alert runModal] == NSAlertSecondButtonReturn) {
1258 /* The action method for the About menu item */
1259 - (IBAction) do_about_menu_item: (id) sender
1261 [about_window makeKeyAndOrderFront: nil];
1264 /* Create and display the about dialog */
1265 - (void)make_about_window
1267 /* Make the window */
1268 int x = 0, y = 0, about_width = 400, about_height = 200;
1269 NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1270 about_window = [[NSWindow alloc] initWithContentRect:window_rect
1271 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1272 NSWindowStyleMaskMiniaturizable
1273 backing:NSBackingStoreBuffered
1275 [about_window setTitle: @"About"];
1276 [about_window setReleasedWhenClosed: NO];
1277 [about_window center];
1278 NSView *superView = [about_window contentView];
1280 /* Create the dimensions of the picture */
1281 int picture_width = 80, picture_height = 80;
1282 x = (about_width - picture_width)/2;
1283 y = about_height - picture_height - 10;
1284 NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1286 /* Get the path to the QEMU binary */
1287 NSString *binary_name = [NSString stringWithCString: gArgv[0]
1288 encoding: NSASCIIStringEncoding];
1289 binary_name = [binary_name lastPathComponent];
1290 NSString *program_path = [[NSString alloc] initWithFormat: @"%@/%@",
1291 [[NSBundle mainBundle] bundlePath], binary_name];
1293 /* Make the picture of QEMU */
1294 NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1296 NSImage *qemu_image = [[NSWorkspace sharedWorkspace] iconForFile:
1298 [picture_view setImage: qemu_image];
1299 [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1300 [superView addSubview: picture_view];
1302 /* Make the name label */
1305 int name_width = about_width, name_height = 20;
1306 NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1307 NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1308 [name_label setEditable: NO];
1309 [name_label setBezeled: NO];
1310 [name_label setDrawsBackground: NO];
1311 [name_label setAlignment: NSTextAlignmentCenter];
1312 NSString *qemu_name = [[NSString alloc] initWithCString: gArgv[0]
1313 encoding: NSASCIIStringEncoding];
1314 qemu_name = [qemu_name lastPathComponent];
1315 [name_label setStringValue: qemu_name];
1316 [superView addSubview: name_label];
1318 /* Set the version label's attributes */
1321 int version_width = about_width, version_height = 20;
1322 NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1323 NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1325 [version_label setEditable: NO];
1326 [version_label setBezeled: NO];
1327 [version_label setAlignment: NSTextAlignmentCenter];
1328 [version_label setDrawsBackground: NO];
1330 /* Create the version string*/
1331 NSString *version_string;
1332 version_string = [[NSString alloc] initWithFormat:
1333 @"QEMU emulator version %s%s", QEMU_VERSION, QEMU_PKGVERSION];
1334 [version_label setStringValue: version_string];
1335 [superView addSubview: version_label];
1337 /* Make copyright label */
1340 int copyright_width = about_width, copyright_height = 20;
1341 NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1342 NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1344 [copyright_label setEditable: NO];
1345 [copyright_label setBezeled: NO];
1346 [copyright_label setDrawsBackground: NO];
1347 [copyright_label setAlignment: NSTextAlignmentCenter];
1348 [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1350 [superView addSubview: copyright_label];
1353 /* Used by the Speed menu items */
1354 - (void)adjustSpeed:(id)sender
1356 int throttle_pct; /* throttle percentage */
1359 menu = [sender menu];
1362 /* Unselect the currently selected item */
1363 for (NSMenuItem *item in [menu itemArray]) {
1364 if (item.state == NSOnState) {
1365 [item setState: NSOffState];
1371 // check the menu item
1372 [sender setState: NSOnState];
1374 // get the throttle percentage
1375 throttle_pct = [sender tag];
1377 cpu_throttle_set(throttle_pct);
1378 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1384 int main (int argc, const char * argv[]) {
1387 gArgv = (char **)argv;
1390 /* In case we don't need to display a window, let's not do that */
1391 for (i = 1; i < argc; i++) {
1392 const char *opt = argv[i];
1394 if (opt[0] == '-') {
1395 /* Treat --foo the same as -foo. */
1396 if (opt[1] == '-') {
1399 if (!strcmp(opt, "-h") || !strcmp(opt, "-help") ||
1400 !strcmp(opt, "-vnc") ||
1401 !strcmp(opt, "-nographic") ||
1402 !strcmp(opt, "-version") ||
1403 !strcmp(opt, "-curses") ||
1404 !strcmp(opt, "-display") ||
1405 !strcmp(opt, "-qtest")) {
1406 return qemu_main(gArgc, gArgv, *_NSGetEnviron());
1411 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1413 // Pull this console process up to being a fully-fledged graphical
1414 // app with a menubar and Dock icon
1415 ProcessSerialNumber psn = { 0, kCurrentProcess };
1416 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1418 [NSApplication sharedApplication];
1422 NSMenuItem *menuItem;
1424 [NSApp setMainMenu:[[NSMenu alloc] init]];
1427 menu = [[NSMenu alloc] initWithTitle:@""];
1428 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1429 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1430 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1431 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1432 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1433 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1434 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1435 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1436 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1437 [menuItem setSubmenu:menu];
1438 [[NSApp mainMenu] addItem:menuItem];
1439 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1442 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1443 [menu setAutoenablesItems: NO];
1444 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1445 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1446 [menu addItem: menuItem];
1447 [menuItem setEnabled: NO];
1448 [menu addItem: [NSMenuItem separatorItem]];
1449 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1450 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1451 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1452 [menuItem setSubmenu:menu];
1453 [[NSApp mainMenu] addItem:menuItem];
1456 menu = [[NSMenu alloc] initWithTitle:@"View"];
1457 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1458 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1459 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1460 [menuItem setSubmenu:menu];
1461 [[NSApp mainMenu] addItem:menuItem];
1464 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1466 // Add the rest of the Speed menu items
1467 int p, percentage, throttle_pct;
1468 for (p = 10; p >= 0; p--)
1470 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1472 menuItem = [[[NSMenuItem alloc]
1473 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1475 if (percentage == 100) {
1476 [menuItem setState: NSOnState];
1479 /* Calculate the throttle percentage */
1480 throttle_pct = -1 * percentage + 100;
1482 [menuItem setTag: throttle_pct];
1483 [menu addItem: menuItem];
1485 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1486 [menuItem setSubmenu:menu];
1487 [[NSApp mainMenu] addItem:menuItem];
1490 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1491 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1492 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1493 [menuItem setSubmenu:menu];
1494 [[NSApp mainMenu] addItem:menuItem];
1495 [NSApp setWindowsMenu:menu];
1498 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1499 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1500 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1501 [menuItem setSubmenu:menu];
1502 [[NSApp mainMenu] addItem:menuItem];
1504 // Create an Application controller
1505 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1506 [NSApp setDelegate:appController];
1508 // Start the main event loop
1511 [appController release];
1520 static void cocoa_update(DisplayChangeListener *dcl,
1521 int x, int y, int w, int h)
1523 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1525 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1528 if ([cocoaView cdx] == 1.0) {
1529 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1532 x * [cocoaView cdx],
1533 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1534 w * [cocoaView cdx],
1535 h * [cocoaView cdy]);
1537 [cocoaView setNeedsDisplayInRect:rect];
1542 static void cocoa_switch(DisplayChangeListener *dcl,
1543 DisplaySurface *surface)
1545 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1547 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1548 [cocoaView switchSurface:surface];
1552 static void cocoa_refresh(DisplayChangeListener *dcl)
1554 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1556 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
1557 graphic_hw_update(NULL);
1559 if (qemu_input_is_absolute()) {
1560 if (![cocoaView isAbsoluteEnabled]) {
1561 if ([cocoaView isMouseGrabbed]) {
1562 [cocoaView ungrabMouse];
1565 [cocoaView setAbsoluteEnabled:YES];
1568 NSDate *distantPast;
1570 distantPast = [NSDate distantPast];
1572 event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:distantPast
1573 inMode: NSDefaultRunLoopMode dequeue:YES];
1575 [cocoaView handleEvent:event];
1577 } while(event != nil);
1581 static void cocoa_cleanup(void)
1583 COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
1587 static const DisplayChangeListenerOps dcl_ops = {
1588 .dpy_name = "cocoa",
1589 .dpy_gfx_update = cocoa_update,
1590 .dpy_gfx_switch = cocoa_switch,
1591 .dpy_refresh = cocoa_refresh,
1594 /* Returns a name for a given console */
1595 static NSString * getConsoleName(QemuConsole * console)
1597 return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1600 /* Add an entry to the View menu for each console */
1601 static void add_console_menu_entries(void)
1604 NSMenuItem *menuItem;
1607 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1609 [menu addItem:[NSMenuItem separatorItem]];
1611 while (qemu_console_lookup_by_index(index) != NULL) {
1612 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1613 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1614 [menuItem setTag: index];
1615 [menu addItem: menuItem];
1620 /* Make menu items for all removable devices.
1621 * Each device is given an 'Eject' and 'Change' menu item.
1623 static void addRemovableDevicesMenuItems(void)
1626 NSMenuItem *menuItem;
1627 BlockInfoList *currentDevice, *pointerToFree;
1628 NSString *deviceName;
1630 currentDevice = qmp_query_block(NULL);
1631 pointerToFree = currentDevice;
1632 if(currentDevice == NULL) {
1634 QEMU_Alert(@"Failed to query for block devices!");
1638 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1640 // Add a separator between related groups of menu items
1641 [menu addItem:[NSMenuItem separatorItem]];
1643 // Set the attributes to the "Removable Media" menu item
1644 NSString *titleString = @"Removable Media";
1645 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1646 NSColor *newColor = [NSColor blackColor];
1647 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1648 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1649 traits:NSBoldFontMask|NSItalicFontMask
1652 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1653 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1654 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1656 // Add the "Removable Media" menu item
1657 menuItem = [NSMenuItem new];
1658 [menuItem setAttributedTitle: attString];
1659 [menuItem setEnabled: NO];
1660 [menu addItem: menuItem];
1662 /* Loop through all the block devices in the emulator */
1663 while (currentDevice) {
1664 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1666 if(currentDevice->value->removable) {
1667 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1668 action: @selector(changeDeviceMedia:)
1669 keyEquivalent: @""];
1670 [menu addItem: menuItem];
1671 [menuItem setRepresentedObject: deviceName];
1672 [menuItem autorelease];
1674 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1675 action: @selector(ejectDeviceMedia:)
1676 keyEquivalent: @""];
1677 [menu addItem: menuItem];
1678 [menuItem setRepresentedObject: deviceName];
1679 [menuItem autorelease];
1681 currentDevice = currentDevice->next;
1683 qapi_free_BlockInfoList(pointerToFree);
1686 void cocoa_display_init(DisplayState *ds, int full_screen)
1688 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1690 /* if fullscreen mode is to be used */
1691 if (full_screen == true) {
1692 [NSApp activateIgnoringOtherApps: YES];
1693 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1696 dcl = g_malloc0(sizeof(DisplayChangeListener));
1698 // register vga output callbacks
1699 dcl->ops = &dcl_ops;
1700 register_displaychangelistener(dcl);
1702 // register cleanup function
1703 atexit(cocoa_cleanup);
1705 /* At this point QEMU has created all the consoles, so we can add View
1706 * menu entries for them.
1708 add_console_menu_entries();
1710 /* Give all removable devices a menu item.
1711 * Has to be called after QEMU has started to
1712 * find out what removable devices it has.
1714 addRemovableDevicesMenuItems();