]> git.proxmox.com Git - mirror_qemu.git/blob - ui/cocoa.m
ui/cocoa.m: add Speed menu
[mirror_qemu.git] / ui / cocoa.m
1 /*
2 * QEMU Cocoa CG display driver
3 *
4 * Copyright (c) 2008 Mike Kronenberg
5 *
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:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
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
22 * THE SOFTWARE.
23 */
24
25 #include "qemu/osdep.h"
26
27 #import <Cocoa/Cocoa.h>
28 #include <crt_externs.h>
29
30 #include "qemu-common.h"
31 #include "ui/console.h"
32 #include "ui/input.h"
33 #include "sysemu/sysemu.h"
34 #include "qmp-commands.h"
35 #include "sysemu/blockdev.h"
36 #include "qemu-version.h"
37 #include <Carbon/Carbon.h>
38 #include "qom/cpu.h"
39
40 #ifndef MAC_OS_X_VERSION_10_5
41 #define MAC_OS_X_VERSION_10_5 1050
42 #endif
43 #ifndef MAC_OS_X_VERSION_10_6
44 #define MAC_OS_X_VERSION_10_6 1060
45 #endif
46 #ifndef MAC_OS_X_VERSION_10_10
47 #define MAC_OS_X_VERSION_10_10 101000
48 #endif
49 #ifndef MAC_OS_X_VERSION_10_12
50 #define MAC_OS_X_VERSION_10_12 101200
51 #endif
52
53 /* macOS 10.12 deprecated many constants, #define the new names for older SDKs */
54 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_12
55 #define NSEventMaskAny NSAnyEventMask
56 #define NSEventModifierFlagCapsLock NSAlphaShiftKeyMask
57 #define NSEventModifierFlagShift NSShiftKeyMask
58 #define NSEventModifierFlagCommand NSCommandKeyMask
59 #define NSEventModifierFlagControl NSControlKeyMask
60 #define NSEventModifierFlagOption NSAlternateKeyMask
61 #define NSEventTypeFlagsChanged NSFlagsChanged
62 #define NSEventTypeKeyUp NSKeyUp
63 #define NSEventTypeKeyDown NSKeyDown
64 #define NSEventTypeMouseMoved NSMouseMoved
65 #define NSEventTypeLeftMouseDown NSLeftMouseDown
66 #define NSEventTypeRightMouseDown NSRightMouseDown
67 #define NSEventTypeOtherMouseDown NSOtherMouseDown
68 #define NSEventTypeLeftMouseDragged NSLeftMouseDragged
69 #define NSEventTypeRightMouseDragged NSRightMouseDragged
70 #define NSEventTypeOtherMouseDragged NSOtherMouseDragged
71 #define NSEventTypeLeftMouseUp NSLeftMouseUp
72 #define NSEventTypeRightMouseUp NSRightMouseUp
73 #define NSEventTypeOtherMouseUp NSOtherMouseUp
74 #define NSEventTypeScrollWheel NSScrollWheel
75 #define NSTextAlignmentCenter NSCenterTextAlignment
76 #define NSWindowStyleMaskBorderless NSBorderlessWindowMask
77 #define NSWindowStyleMaskClosable NSClosableWindowMask
78 #define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask
79 #define NSWindowStyleMaskTitled NSTitledWindowMask
80 #endif
81
82 //#define DEBUG
83
84 #ifdef DEBUG
85 #define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
86 #else
87 #define COCOA_DEBUG(...) ((void) 0)
88 #endif
89
90 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
91
92 typedef struct {
93 int width;
94 int height;
95 int bitsPerComponent;
96 int bitsPerPixel;
97 } QEMUScreen;
98
99 NSWindow *normalWindow, *about_window;
100 static DisplayChangeListener *dcl;
101 static int last_buttons;
102
103 int gArgc;
104 char **gArgv;
105 bool stretch_video;
106 NSTextField *pauseLabel;
107 NSArray * supportedImageFileTypes;
108
109 // Mac to QKeyCode conversion
110 const int mac_to_qkeycode_map[] = {
111 [kVK_ANSI_A] = Q_KEY_CODE_A,
112 [kVK_ANSI_B] = Q_KEY_CODE_B,
113 [kVK_ANSI_C] = Q_KEY_CODE_C,
114 [kVK_ANSI_D] = Q_KEY_CODE_D,
115 [kVK_ANSI_E] = Q_KEY_CODE_E,
116 [kVK_ANSI_F] = Q_KEY_CODE_F,
117 [kVK_ANSI_G] = Q_KEY_CODE_G,
118 [kVK_ANSI_H] = Q_KEY_CODE_H,
119 [kVK_ANSI_I] = Q_KEY_CODE_I,
120 [kVK_ANSI_J] = Q_KEY_CODE_J,
121 [kVK_ANSI_K] = Q_KEY_CODE_K,
122 [kVK_ANSI_L] = Q_KEY_CODE_L,
123 [kVK_ANSI_M] = Q_KEY_CODE_M,
124 [kVK_ANSI_N] = Q_KEY_CODE_N,
125 [kVK_ANSI_O] = Q_KEY_CODE_O,
126 [kVK_ANSI_P] = Q_KEY_CODE_P,
127 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
128 [kVK_ANSI_R] = Q_KEY_CODE_R,
129 [kVK_ANSI_S] = Q_KEY_CODE_S,
130 [kVK_ANSI_T] = Q_KEY_CODE_T,
131 [kVK_ANSI_U] = Q_KEY_CODE_U,
132 [kVK_ANSI_V] = Q_KEY_CODE_V,
133 [kVK_ANSI_W] = Q_KEY_CODE_W,
134 [kVK_ANSI_X] = Q_KEY_CODE_X,
135 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
136 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
137
138 [kVK_ANSI_0] = Q_KEY_CODE_0,
139 [kVK_ANSI_1] = Q_KEY_CODE_1,
140 [kVK_ANSI_2] = Q_KEY_CODE_2,
141 [kVK_ANSI_3] = Q_KEY_CODE_3,
142 [kVK_ANSI_4] = Q_KEY_CODE_4,
143 [kVK_ANSI_5] = Q_KEY_CODE_5,
144 [kVK_ANSI_6] = Q_KEY_CODE_6,
145 [kVK_ANSI_7] = Q_KEY_CODE_7,
146 [kVK_ANSI_8] = Q_KEY_CODE_8,
147 [kVK_ANSI_9] = Q_KEY_CODE_9,
148
149 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
150 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
151 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
152 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
153 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
154 [kVK_Tab] = Q_KEY_CODE_TAB,
155 [kVK_Return] = Q_KEY_CODE_RET,
156 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
157 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
158 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
159 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
160 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
161 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
162 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
163 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
164 [kVK_Shift] = Q_KEY_CODE_SHIFT,
165 [kVK_RightShift] = Q_KEY_CODE_SHIFT_R,
166 [kVK_Control] = Q_KEY_CODE_CTRL,
167 [kVK_RightControl] = Q_KEY_CODE_CTRL_R,
168 [kVK_Option] = Q_KEY_CODE_ALT,
169 [kVK_RightOption] = Q_KEY_CODE_ALT_R,
170 [kVK_Command] = Q_KEY_CODE_META_L,
171 [0x36] = Q_KEY_CODE_META_R, /* There is no kVK_RightCommand */
172 [kVK_Space] = Q_KEY_CODE_SPC,
173
174 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
175 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
176 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
177 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
178 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
179 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
180 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
181 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
182 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
183 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
184 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
185 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
186 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
187 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
188 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
189 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
190 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
191 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
192
193 [kVK_UpArrow] = Q_KEY_CODE_UP,
194 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
195 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
196 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
197
198 [kVK_Help] = Q_KEY_CODE_INSERT,
199 [kVK_Home] = Q_KEY_CODE_HOME,
200 [kVK_PageUp] = Q_KEY_CODE_PGUP,
201 [kVK_PageDown] = Q_KEY_CODE_PGDN,
202 [kVK_End] = Q_KEY_CODE_END,
203 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
204
205 [kVK_Escape] = Q_KEY_CODE_ESC,
206
207 /* The Power key can't be used directly because the operating system uses
208 * it. This key can be emulated by using it in place of another key such as
209 * F1. Don't forget to disable the real key binding.
210 */
211 /* [kVK_F1] = Q_KEY_CODE_POWER, */
212
213 [kVK_F1] = Q_KEY_CODE_F1,
214 [kVK_F2] = Q_KEY_CODE_F2,
215 [kVK_F3] = Q_KEY_CODE_F3,
216 [kVK_F4] = Q_KEY_CODE_F4,
217 [kVK_F5] = Q_KEY_CODE_F5,
218 [kVK_F6] = Q_KEY_CODE_F6,
219 [kVK_F7] = Q_KEY_CODE_F7,
220 [kVK_F8] = Q_KEY_CODE_F8,
221 [kVK_F9] = Q_KEY_CODE_F9,
222 [kVK_F10] = Q_KEY_CODE_F10,
223 [kVK_F11] = Q_KEY_CODE_F11,
224 [kVK_F12] = Q_KEY_CODE_F12,
225 [kVK_F13] = Q_KEY_CODE_PRINT,
226 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
227 [kVK_F15] = Q_KEY_CODE_PAUSE,
228
229 /*
230 * The eject and volume keys can't be used here because they are handled at
231 * a lower level than what an Application can see.
232 */
233 };
234
235 static int cocoa_keycode_to_qemu(int keycode)
236 {
237 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
238 fprintf(stderr, "(cocoa) warning unknown keycode 0x%x\n", keycode);
239 return 0;
240 }
241 return mac_to_qkeycode_map[keycode];
242 }
243
244 /* Displays an alert dialog box with the specified message */
245 static void QEMU_Alert(NSString *message)
246 {
247 NSAlert *alert;
248 alert = [NSAlert new];
249 [alert setMessageText: message];
250 [alert runModal];
251 }
252
253 /* Handles any errors that happen with a device transaction */
254 static void handleAnyDeviceErrors(Error * err)
255 {
256 if (err) {
257 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
258 encoding: NSASCIIStringEncoding]);
259 error_free(err);
260 }
261 }
262
263 /*
264 ------------------------------------------------------
265 QemuCocoaView
266 ------------------------------------------------------
267 */
268 @interface QemuCocoaView : NSView
269 {
270 QEMUScreen screen;
271 NSWindow *fullScreenWindow;
272 float cx,cy,cw,ch,cdx,cdy;
273 CGDataProviderRef dataProviderRef;
274 BOOL modifiers_state[256];
275 BOOL isMouseGrabbed;
276 BOOL isFullscreen;
277 BOOL isAbsoluteEnabled;
278 BOOL isMouseDeassociated;
279 }
280 - (void) switchSurface:(DisplaySurface *)surface;
281 - (void) grabMouse;
282 - (void) ungrabMouse;
283 - (void) toggleFullScreen:(id)sender;
284 - (void) handleEvent:(NSEvent *)event;
285 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
286 /* The state surrounding mouse grabbing is potentially confusing.
287 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
288 * pointing device an absolute-position one?"], but is only updated on
289 * next refresh.
290 * isMouseGrabbed tracks whether GUI events are directed to the guest;
291 * it controls whether special keys like Cmd get sent to the guest,
292 * and whether we capture the mouse when in non-absolute mode.
293 * isMouseDeassociated tracks whether we've told MacOSX to disassociate
294 * the mouse and mouse cursor position by calling
295 * CGAssociateMouseAndMouseCursorPosition(FALSE)
296 * (which basically happens if we grab in non-absolute mode).
297 */
298 - (BOOL) isMouseGrabbed;
299 - (BOOL) isAbsoluteEnabled;
300 - (BOOL) isMouseDeassociated;
301 - (float) cdx;
302 - (float) cdy;
303 - (QEMUScreen) gscreen;
304 - (void) raiseAllKeys;
305 @end
306
307 QemuCocoaView *cocoaView;
308
309 @implementation QemuCocoaView
310 - (id)initWithFrame:(NSRect)frameRect
311 {
312 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
313
314 self = [super initWithFrame:frameRect];
315 if (self) {
316
317 screen.bitsPerComponent = 8;
318 screen.bitsPerPixel = 32;
319 screen.width = frameRect.size.width;
320 screen.height = frameRect.size.height;
321
322 }
323 return self;
324 }
325
326 - (void) dealloc
327 {
328 COCOA_DEBUG("QemuCocoaView: dealloc\n");
329
330 if (dataProviderRef)
331 CGDataProviderRelease(dataProviderRef);
332
333 [super dealloc];
334 }
335
336 - (BOOL) isOpaque
337 {
338 return YES;
339 }
340
341 - (BOOL) screenContainsPoint:(NSPoint) p
342 {
343 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
344 }
345
346 - (void) hideCursor
347 {
348 if (!cursor_hide) {
349 return;
350 }
351 [NSCursor hide];
352 }
353
354 - (void) unhideCursor
355 {
356 if (!cursor_hide) {
357 return;
358 }
359 [NSCursor unhide];
360 }
361
362 - (void) drawRect:(NSRect) rect
363 {
364 COCOA_DEBUG("QemuCocoaView: drawRect\n");
365
366 // get CoreGraphic context
367 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] graphicsPort];
368 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
369 CGContextSetShouldAntialias (viewContextRef, NO);
370
371 // draw screen bitmap directly to Core Graphics context
372 if (!dataProviderRef) {
373 // Draw request before any guest device has set up a framebuffer:
374 // just draw an opaque black rectangle
375 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
376 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
377 } else {
378 CGImageRef imageRef = CGImageCreate(
379 screen.width, //width
380 screen.height, //height
381 screen.bitsPerComponent, //bitsPerComponent
382 screen.bitsPerPixel, //bitsPerPixel
383 (screen.width * (screen.bitsPerComponent/2)), //bytesPerRow
384 #ifdef __LITTLE_ENDIAN__
385 CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
386 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
387 #else
388 CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
389 kCGImageAlphaNoneSkipFirst, //bitmapInfo
390 #endif
391 dataProviderRef, //provider
392 NULL, //decode
393 0, //interpolate
394 kCGRenderingIntentDefault //intent
395 );
396 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
397 const NSRect *rectList;
398 NSInteger rectCount;
399 int i;
400 CGImageRef clipImageRef;
401 CGRect clipRect;
402
403 [self getRectsBeingDrawn:&rectList count:&rectCount];
404 for (i = 0; i < rectCount; i++) {
405 clipRect.origin.x = rectList[i].origin.x / cdx;
406 clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
407 clipRect.size.width = rectList[i].size.width / cdx;
408 clipRect.size.height = rectList[i].size.height / cdy;
409 clipImageRef = CGImageCreateWithImageInRect(
410 imageRef,
411 clipRect
412 );
413 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
414 CGImageRelease (clipImageRef);
415 }
416 CGImageRelease (imageRef);
417 }
418 }
419
420 - (void) setContentDimensions
421 {
422 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
423
424 if (isFullscreen) {
425 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
426 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
427
428 /* stretches video, but keeps same aspect ratio */
429 if (stretch_video == true) {
430 /* use smallest stretch value - prevents clipping on sides */
431 if (MIN(cdx, cdy) == cdx) {
432 cdy = cdx;
433 } else {
434 cdx = cdy;
435 }
436 } else { /* No stretching */
437 cdx = cdy = 1;
438 }
439 cw = screen.width * cdx;
440 ch = screen.height * cdy;
441 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
442 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
443 } else {
444 cx = 0;
445 cy = 0;
446 cw = screen.width;
447 ch = screen.height;
448 cdx = 1.0;
449 cdy = 1.0;
450 }
451 }
452
453 - (void) switchSurface:(DisplaySurface *)surface
454 {
455 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
456
457 int w = surface_width(surface);
458 int h = surface_height(surface);
459 /* cdx == 0 means this is our very first surface, in which case we need
460 * to recalculate the content dimensions even if it happens to be the size
461 * of the initial empty window.
462 */
463 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
464
465 int oldh = screen.height;
466 if (isResize) {
467 // Resize before we trigger the redraw, or we'll redraw at the wrong size
468 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
469 screen.width = w;
470 screen.height = h;
471 [self setContentDimensions];
472 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
473 }
474
475 // update screenBuffer
476 if (dataProviderRef)
477 CGDataProviderRelease(dataProviderRef);
478
479 //sync host window color space with guests
480 screen.bitsPerPixel = surface_bits_per_pixel(surface);
481 screen.bitsPerComponent = surface_bytes_per_pixel(surface) * 2;
482
483 dataProviderRef = CGDataProviderCreateWithData(NULL, surface_data(surface), w * 4 * h, NULL);
484
485 // update windows
486 if (isFullscreen) {
487 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
488 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
489 } else {
490 if (qemu_name)
491 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
492 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
493 }
494
495 if (isResize) {
496 [normalWindow center];
497 }
498 }
499
500 - (void) toggleFullScreen:(id)sender
501 {
502 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
503
504 if (isFullscreen) { // switch from fullscreen to desktop
505 isFullscreen = FALSE;
506 [self ungrabMouse];
507 [self setContentDimensions];
508 if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
509 [self exitFullScreenModeWithOptions:nil];
510 } else {
511 [fullScreenWindow close];
512 [normalWindow setContentView: self];
513 [normalWindow makeKeyAndOrderFront: self];
514 [NSMenu setMenuBarVisible:YES];
515 }
516 } else { // switch from desktop to fullscreen
517 isFullscreen = TRUE;
518 [normalWindow orderOut: nil]; /* Hide the window */
519 [self grabMouse];
520 [self setContentDimensions];
521 if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
522 [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
523 [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
524 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
525 nil]];
526 } else {
527 [NSMenu setMenuBarVisible:NO];
528 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
529 styleMask:NSWindowStyleMaskBorderless
530 backing:NSBackingStoreBuffered
531 defer:NO];
532 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
533 [fullScreenWindow setHasShadow:NO];
534 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
535 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
536 [[fullScreenWindow contentView] addSubview: self];
537 [fullScreenWindow makeKeyAndOrderFront:self];
538 }
539 }
540 }
541
542 - (void) toggleModifier: (int)keycode {
543 // Toggle the stored state.
544 modifiers_state[keycode] = !modifiers_state[keycode];
545 // Send a keyup or keydown depending on the state.
546 qemu_input_event_send_key_qcode(dcl->con, keycode, modifiers_state[keycode]);
547 }
548
549 - (void) toggleStatefulModifier: (int)keycode {
550 // Toggle the stored state.
551 modifiers_state[keycode] = !modifiers_state[keycode];
552 // Generate keydown and keyup.
553 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
554 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
555 }
556
557 - (void) handleEvent:(NSEvent *)event
558 {
559 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
560
561 int buttons = 0;
562 int keycode = 0;
563 bool mouse_event = false;
564 NSPoint p = [event locationInWindow];
565
566 switch ([event type]) {
567 case NSEventTypeFlagsChanged:
568 if ([event keyCode] == 0) {
569 // When the Cocoa keyCode is zero that means keys should be
570 // synthesized based on the values in in the eventModifiers
571 // bitmask.
572
573 if (qemu_console_is_graphic(NULL)) {
574 NSEventModifierFlags modifiers = [event modifierFlags];
575
576 if (!!(modifiers & NSEventModifierFlagCapsLock) != !!modifiers_state[Q_KEY_CODE_CAPS_LOCK]) {
577 [self toggleStatefulModifier:Q_KEY_CODE_CAPS_LOCK];
578 }
579 if (!!(modifiers & NSEventModifierFlagShift) != !!modifiers_state[Q_KEY_CODE_SHIFT]) {
580 [self toggleModifier:Q_KEY_CODE_SHIFT];
581 }
582 if (!!(modifiers & NSEventModifierFlagControl) != !!modifiers_state[Q_KEY_CODE_CTRL]) {
583 [self toggleModifier:Q_KEY_CODE_CTRL];
584 }
585 if (!!(modifiers & NSEventModifierFlagOption) != !!modifiers_state[Q_KEY_CODE_ALT]) {
586 [self toggleModifier:Q_KEY_CODE_ALT];
587 }
588 if (!!(modifiers & NSEventModifierFlagCommand) != !!modifiers_state[Q_KEY_CODE_META_L]) {
589 [self toggleModifier:Q_KEY_CODE_META_L];
590 }
591 }
592 } else {
593 keycode = cocoa_keycode_to_qemu([event keyCode]);
594 }
595
596 if ((keycode == Q_KEY_CODE_META_L || keycode == Q_KEY_CODE_META_R)
597 && !isMouseGrabbed) {
598 /* Don't pass command key changes to guest unless mouse is grabbed */
599 keycode = 0;
600 }
601
602 if (keycode) {
603 // emulate caps lock and num lock keydown and keyup
604 if (keycode == Q_KEY_CODE_CAPS_LOCK ||
605 keycode == Q_KEY_CODE_NUM_LOCK) {
606 [self toggleStatefulModifier:keycode];
607 } else if (qemu_console_is_graphic(NULL)) {
608 [self toggleModifier:keycode];
609 }
610 }
611
612 // release Mouse grab when pressing ctrl+alt
613 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
614 [self ungrabMouse];
615 }
616 break;
617 case NSEventTypeKeyDown:
618 keycode = cocoa_keycode_to_qemu([event keyCode]);
619
620 // forward command key combos to the host UI unless the mouse is grabbed
621 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
622 [NSApp sendEvent:event];
623 return;
624 }
625
626 // default
627
628 // handle control + alt Key Combos (ctrl+alt is reserved for QEMU)
629 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
630 switch (keycode) {
631
632 // enable graphic console
633 case Q_KEY_CODE_1 ... Q_KEY_CODE_9: // '1' to '9' keys
634 console_select(keycode - 11);
635 break;
636 }
637
638 // handle keys for graphic console
639 } else if (qemu_console_is_graphic(NULL)) {
640 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
641
642 // handlekeys for Monitor
643 } else {
644 int keysym = 0;
645 switch([event keyCode]) {
646 case 115:
647 keysym = QEMU_KEY_HOME;
648 break;
649 case 117:
650 keysym = QEMU_KEY_DELETE;
651 break;
652 case 119:
653 keysym = QEMU_KEY_END;
654 break;
655 case 123:
656 keysym = QEMU_KEY_LEFT;
657 break;
658 case 124:
659 keysym = QEMU_KEY_RIGHT;
660 break;
661 case 125:
662 keysym = QEMU_KEY_DOWN;
663 break;
664 case 126:
665 keysym = QEMU_KEY_UP;
666 break;
667 default:
668 {
669 NSString *ks = [event characters];
670 if ([ks length] > 0)
671 keysym = [ks characterAtIndex:0];
672 }
673 }
674 if (keysym)
675 kbd_put_keysym(keysym);
676 }
677 break;
678 case NSEventTypeKeyUp:
679 keycode = cocoa_keycode_to_qemu([event keyCode]);
680
681 // don't pass the guest a spurious key-up if we treated this
682 // command-key combo as a host UI action
683 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
684 return;
685 }
686
687 if (qemu_console_is_graphic(NULL)) {
688 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
689 }
690 break;
691 case NSEventTypeMouseMoved:
692 if (isAbsoluteEnabled) {
693 if (![self screenContainsPoint:p] || ![[self window] isKeyWindow]) {
694 if (isMouseGrabbed) {
695 [self ungrabMouse];
696 }
697 } else {
698 if (!isMouseGrabbed) {
699 [self grabMouse];
700 }
701 }
702 }
703 mouse_event = true;
704 break;
705 case NSEventTypeLeftMouseDown:
706 if ([event modifierFlags] & NSEventModifierFlagCommand) {
707 buttons |= MOUSE_EVENT_RBUTTON;
708 } else {
709 buttons |= MOUSE_EVENT_LBUTTON;
710 }
711 mouse_event = true;
712 break;
713 case NSEventTypeRightMouseDown:
714 buttons |= MOUSE_EVENT_RBUTTON;
715 mouse_event = true;
716 break;
717 case NSEventTypeOtherMouseDown:
718 buttons |= MOUSE_EVENT_MBUTTON;
719 mouse_event = true;
720 break;
721 case NSEventTypeLeftMouseDragged:
722 if ([event modifierFlags] & NSEventModifierFlagCommand) {
723 buttons |= MOUSE_EVENT_RBUTTON;
724 } else {
725 buttons |= MOUSE_EVENT_LBUTTON;
726 }
727 mouse_event = true;
728 break;
729 case NSEventTypeRightMouseDragged:
730 buttons |= MOUSE_EVENT_RBUTTON;
731 mouse_event = true;
732 break;
733 case NSEventTypeOtherMouseDragged:
734 buttons |= MOUSE_EVENT_MBUTTON;
735 mouse_event = true;
736 break;
737 case NSEventTypeLeftMouseUp:
738 mouse_event = true;
739 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
740 if([[self window] isKeyWindow]) {
741 [self grabMouse];
742 }
743 }
744 break;
745 case NSEventTypeRightMouseUp:
746 mouse_event = true;
747 break;
748 case NSEventTypeOtherMouseUp:
749 mouse_event = true;
750 break;
751 case NSEventTypeScrollWheel:
752 if (isMouseGrabbed) {
753 buttons |= ([event deltaY] < 0) ?
754 MOUSE_EVENT_WHEELUP : MOUSE_EVENT_WHEELDN;
755 }
756 mouse_event = true;
757 break;
758 default:
759 [NSApp sendEvent:event];
760 }
761
762 if (mouse_event) {
763 /* Don't send button events to the guest unless we've got a
764 * mouse grab or window focus. If we have neither then this event
765 * is the user clicking on the background window to activate and
766 * bring us to the front, which will be done by the sendEvent
767 * call below. We definitely don't want to pass that click through
768 * to the guest.
769 */
770 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
771 (last_buttons != buttons)) {
772 static uint32_t bmap[INPUT_BUTTON__MAX] = {
773 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
774 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
775 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
776 [INPUT_BUTTON_WHEEL_UP] = MOUSE_EVENT_WHEELUP,
777 [INPUT_BUTTON_WHEEL_DOWN] = MOUSE_EVENT_WHEELDN,
778 };
779 qemu_input_update_buttons(dcl->con, bmap, last_buttons, buttons);
780 last_buttons = buttons;
781 }
782 if (isMouseGrabbed) {
783 if (isAbsoluteEnabled) {
784 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
785 * The check on screenContainsPoint is to avoid sending out of range values for
786 * clicks in the titlebar.
787 */
788 if ([self screenContainsPoint:p]) {
789 qemu_input_queue_abs(dcl->con, INPUT_AXIS_X, p.x, 0, screen.width);
790 qemu_input_queue_abs(dcl->con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
791 }
792 } else {
793 qemu_input_queue_rel(dcl->con, INPUT_AXIS_X, (int)[event deltaX]);
794 qemu_input_queue_rel(dcl->con, INPUT_AXIS_Y, (int)[event deltaY]);
795 }
796 } else {
797 [NSApp sendEvent:event];
798 }
799 qemu_input_event_sync();
800 }
801 }
802
803 - (void) grabMouse
804 {
805 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
806
807 if (!isFullscreen) {
808 if (qemu_name)
809 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt to release Mouse)", qemu_name]];
810 else
811 [normalWindow setTitle:@"QEMU - (Press ctrl + alt to release Mouse)"];
812 }
813 [self hideCursor];
814 if (!isAbsoluteEnabled) {
815 isMouseDeassociated = TRUE;
816 CGAssociateMouseAndMouseCursorPosition(FALSE);
817 }
818 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
819 }
820
821 - (void) ungrabMouse
822 {
823 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
824
825 if (!isFullscreen) {
826 if (qemu_name)
827 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
828 else
829 [normalWindow setTitle:@"QEMU"];
830 }
831 [self unhideCursor];
832 if (isMouseDeassociated) {
833 CGAssociateMouseAndMouseCursorPosition(TRUE);
834 isMouseDeassociated = FALSE;
835 }
836 isMouseGrabbed = FALSE;
837 }
838
839 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
840 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
841 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
842 - (BOOL) isMouseDeassociated {return isMouseDeassociated;}
843 - (float) cdx {return cdx;}
844 - (float) cdy {return cdy;}
845 - (QEMUScreen) gscreen {return screen;}
846
847 /*
848 * Makes the target think all down keys are being released.
849 * This prevents a stuck key problem, since we will not see
850 * key up events for those keys after we have lost focus.
851 */
852 - (void) raiseAllKeys
853 {
854 int index;
855 const int max_index = ARRAY_SIZE(modifiers_state);
856
857 for (index = 0; index < max_index; index++) {
858 if (modifiers_state[index]) {
859 modifiers_state[index] = 0;
860 qemu_input_event_send_key_qcode(dcl->con, index, false);
861 }
862 }
863 }
864 @end
865
866
867
868 /*
869 ------------------------------------------------------
870 QemuCocoaAppController
871 ------------------------------------------------------
872 */
873 @interface QemuCocoaAppController : NSObject
874 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
875 <NSWindowDelegate, NSApplicationDelegate>
876 #endif
877 {
878 }
879 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv;
880 - (void)doToggleFullScreen:(id)sender;
881 - (void)toggleFullScreen:(id)sender;
882 - (void)showQEMUDoc:(id)sender;
883 - (void)zoomToFit:(id) sender;
884 - (void)displayConsole:(id)sender;
885 - (void)pauseQEMU:(id)sender;
886 - (void)resumeQEMU:(id)sender;
887 - (void)displayPause;
888 - (void)removePause;
889 - (void)restartQEMU:(id)sender;
890 - (void)powerDownQEMU:(id)sender;
891 - (void)ejectDeviceMedia:(id)sender;
892 - (void)changeDeviceMedia:(id)sender;
893 - (BOOL)verifyQuit;
894 - (void)openDocumentation:(NSString *)filename;
895 - (IBAction) do_about_menu_item: (id) sender;
896 - (void)make_about_window;
897 - (void)adjustSpeed:(id)sender;
898 @end
899
900 @implementation QemuCocoaAppController
901 - (id) init
902 {
903 COCOA_DEBUG("QemuCocoaAppController: init\n");
904
905 self = [super init];
906 if (self) {
907
908 // create a view and add it to the window
909 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
910 if(!cocoaView) {
911 fprintf(stderr, "(cocoa) can't create a view\n");
912 exit(1);
913 }
914
915 // create a window
916 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
917 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
918 backing:NSBackingStoreBuffered defer:NO];
919 if(!normalWindow) {
920 fprintf(stderr, "(cocoa) can't create window\n");
921 exit(1);
922 }
923 [normalWindow setAcceptsMouseMovedEvents:YES];
924 [normalWindow setTitle:@"QEMU"];
925 [normalWindow setContentView:cocoaView];
926 #if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10)
927 [normalWindow useOptimizedDrawing:YES];
928 #endif
929 [normalWindow makeKeyAndOrderFront:self];
930 [normalWindow center];
931 [normalWindow setDelegate: self];
932 stretch_video = false;
933
934 /* Used for displaying pause on the screen */
935 pauseLabel = [NSTextField new];
936 [pauseLabel setBezeled:YES];
937 [pauseLabel setDrawsBackground:YES];
938 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
939 [pauseLabel setEditable:NO];
940 [pauseLabel setSelectable:NO];
941 [pauseLabel setStringValue: @"Paused"];
942 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
943 [pauseLabel setTextColor: [NSColor blackColor]];
944 [pauseLabel sizeToFit];
945
946 // set the supported image file types that can be opened
947 supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
948 @"qcow", @"qcow2", @"cloop", @"vmdk", @"cdr",
949 @"toast", nil];
950 [self make_about_window];
951 }
952 return self;
953 }
954
955 - (void) dealloc
956 {
957 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
958
959 if (cocoaView)
960 [cocoaView release];
961 [super dealloc];
962 }
963
964 - (void)applicationDidFinishLaunching: (NSNotification *) note
965 {
966 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
967 // launch QEMU, with the global args
968 [self startEmulationWithArgc:gArgc argv:(char **)gArgv];
969 }
970
971 - (void)applicationWillTerminate:(NSNotification *)aNotification
972 {
973 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
974
975 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
976 exit(0);
977 }
978
979 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
980 {
981 return YES;
982 }
983
984 - (NSApplicationTerminateReply)applicationShouldTerminate:
985 (NSApplication *)sender
986 {
987 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
988 return [self verifyQuit];
989 }
990
991 /* Called when the user clicks on a window's close button */
992 - (BOOL)windowShouldClose:(id)sender
993 {
994 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
995 [NSApp terminate: sender];
996 /* If the user allows the application to quit then the call to
997 * NSApp terminate will never return. If we get here then the user
998 * cancelled the quit, so we should return NO to not permit the
999 * closing of this window.
1000 */
1001 return NO;
1002 }
1003
1004 /* Called when QEMU goes into the background */
1005 - (void) applicationWillResignActive: (NSNotification *)aNotification
1006 {
1007 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1008 [cocoaView raiseAllKeys];
1009 }
1010
1011 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv
1012 {
1013 COCOA_DEBUG("QemuCocoaAppController: startEmulationWithArgc\n");
1014
1015 int status;
1016 status = qemu_main(argc, argv, *_NSGetEnviron());
1017 exit(status);
1018 }
1019
1020 /* We abstract the method called by the Enter Fullscreen menu item
1021 * because Mac OS 10.7 and higher disables it. This is because of the
1022 * menu item's old selector's name toggleFullScreen:
1023 */
1024 - (void) doToggleFullScreen:(id)sender
1025 {
1026 [self toggleFullScreen:(id)sender];
1027 }
1028
1029 - (void)toggleFullScreen:(id)sender
1030 {
1031 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1032
1033 [cocoaView toggleFullScreen:sender];
1034 }
1035
1036 /* Tries to find then open the specified filename */
1037 - (void) openDocumentation: (NSString *) filename
1038 {
1039 /* Where to look for local files */
1040 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"../"};
1041 NSString *full_file_path;
1042
1043 /* iterate thru the possible paths until the file is found */
1044 int index;
1045 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1046 full_file_path = [[NSBundle mainBundle] executablePath];
1047 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1048 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1049 path_array[index], filename];
1050 if ([[NSWorkspace sharedWorkspace] openFile: full_file_path] == YES) {
1051 return;
1052 }
1053 }
1054
1055 /* If none of the paths opened a file */
1056 NSBeep();
1057 QEMU_Alert(@"Failed to open file");
1058 }
1059
1060 - (void)showQEMUDoc:(id)sender
1061 {
1062 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1063
1064 [self openDocumentation: @"qemu-doc.html"];
1065 }
1066
1067 /* Stretches video to fit host monitor size */
1068 - (void)zoomToFit:(id) sender
1069 {
1070 stretch_video = !stretch_video;
1071 if (stretch_video == true) {
1072 [sender setState: NSOnState];
1073 } else {
1074 [sender setState: NSOffState];
1075 }
1076 }
1077
1078 /* Displays the console on the screen */
1079 - (void)displayConsole:(id)sender
1080 {
1081 console_select([sender tag]);
1082 }
1083
1084 /* Pause the guest */
1085 - (void)pauseQEMU:(id)sender
1086 {
1087 qmp_stop(NULL);
1088 [sender setEnabled: NO];
1089 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1090 [self displayPause];
1091 }
1092
1093 /* Resume running the guest operating system */
1094 - (void)resumeQEMU:(id) sender
1095 {
1096 qmp_cont(NULL);
1097 [sender setEnabled: NO];
1098 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1099 [self removePause];
1100 }
1101
1102 /* Displays the word pause on the screen */
1103 - (void)displayPause
1104 {
1105 /* Coordinates have to be calculated each time because the window can change its size */
1106 int xCoord, yCoord, width, height;
1107 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1108 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1109 width = [pauseLabel frame].size.width;
1110 height = [pauseLabel frame].size.height;
1111 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1112 [cocoaView addSubview: pauseLabel];
1113 }
1114
1115 /* Removes the word pause from the screen */
1116 - (void)removePause
1117 {
1118 [pauseLabel removeFromSuperview];
1119 }
1120
1121 /* Restarts QEMU */
1122 - (void)restartQEMU:(id)sender
1123 {
1124 qmp_system_reset(NULL);
1125 }
1126
1127 /* Powers down QEMU */
1128 - (void)powerDownQEMU:(id)sender
1129 {
1130 qmp_system_powerdown(NULL);
1131 }
1132
1133 /* Ejects the media.
1134 * Uses sender's tag to figure out the device to eject.
1135 */
1136 - (void)ejectDeviceMedia:(id)sender
1137 {
1138 NSString * drive;
1139 drive = [sender representedObject];
1140 if(drive == nil) {
1141 NSBeep();
1142 QEMU_Alert(@"Failed to find drive to eject!");
1143 return;
1144 }
1145
1146 Error *err = NULL;
1147 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1148 false, NULL, false, false, &err);
1149 handleAnyDeviceErrors(err);
1150 }
1151
1152 /* Displays a dialog box asking the user to select an image file to load.
1153 * Uses sender's represented object value to figure out which drive to use.
1154 */
1155 - (void)changeDeviceMedia:(id)sender
1156 {
1157 /* Find the drive name */
1158 NSString * drive;
1159 drive = [sender representedObject];
1160 if(drive == nil) {
1161 NSBeep();
1162 QEMU_Alert(@"Could not find drive!");
1163 return;
1164 }
1165
1166 /* Display the file open dialog */
1167 NSOpenPanel * openPanel;
1168 openPanel = [NSOpenPanel openPanel];
1169 [openPanel setCanChooseFiles: YES];
1170 [openPanel setAllowsMultipleSelection: NO];
1171 [openPanel setAllowedFileTypes: supportedImageFileTypes];
1172 if([openPanel runModal] == NSFileHandlingPanelOKButton) {
1173 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1174 if(file == nil) {
1175 NSBeep();
1176 QEMU_Alert(@"Failed to convert URL to file path!");
1177 return;
1178 }
1179
1180 Error *err = NULL;
1181 qmp_blockdev_change_medium(true,
1182 [drive cStringUsingEncoding:
1183 NSASCIIStringEncoding],
1184 false, NULL,
1185 [file cStringUsingEncoding:
1186 NSASCIIStringEncoding],
1187 true, "raw",
1188 false, 0,
1189 &err);
1190 handleAnyDeviceErrors(err);
1191 }
1192 }
1193
1194 /* Verifies if the user really wants to quit */
1195 - (BOOL)verifyQuit
1196 {
1197 NSAlert *alert = [NSAlert new];
1198 [alert autorelease];
1199 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1200 [alert addButtonWithTitle: @"Cancel"];
1201 [alert addButtonWithTitle: @"Quit"];
1202 if([alert runModal] == NSAlertSecondButtonReturn) {
1203 return YES;
1204 } else {
1205 return NO;
1206 }
1207 }
1208
1209 /* The action method for the About menu item */
1210 - (IBAction) do_about_menu_item: (id) sender
1211 {
1212 [about_window makeKeyAndOrderFront: nil];
1213 }
1214
1215 /* Create and display the about dialog */
1216 - (void)make_about_window
1217 {
1218 /* Make the window */
1219 int x = 0, y = 0, about_width = 400, about_height = 200;
1220 NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1221 about_window = [[NSWindow alloc] initWithContentRect:window_rect
1222 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1223 NSWindowStyleMaskMiniaturizable
1224 backing:NSBackingStoreBuffered
1225 defer:NO];
1226 [about_window setTitle: @"About"];
1227 [about_window setReleasedWhenClosed: NO];
1228 [about_window center];
1229 NSView *superView = [about_window contentView];
1230
1231 /* Create the dimensions of the picture */
1232 int picture_width = 80, picture_height = 80;
1233 x = (about_width - picture_width)/2;
1234 y = about_height - picture_height - 10;
1235 NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1236
1237 /* Get the path to the QEMU binary */
1238 NSString *binary_name = [NSString stringWithCString: gArgv[0]
1239 encoding: NSASCIIStringEncoding];
1240 binary_name = [binary_name lastPathComponent];
1241 NSString *program_path = [[NSString alloc] initWithFormat: @"%@/%@",
1242 [[NSBundle mainBundle] bundlePath], binary_name];
1243
1244 /* Make the picture of QEMU */
1245 NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1246 picture_rect];
1247 NSImage *qemu_image = [[NSWorkspace sharedWorkspace] iconForFile:
1248 program_path];
1249 [picture_view setImage: qemu_image];
1250 [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1251 [superView addSubview: picture_view];
1252
1253 /* Make the name label */
1254 x = 0;
1255 y = y - 25;
1256 int name_width = about_width, name_height = 20;
1257 NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1258 NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1259 [name_label setEditable: NO];
1260 [name_label setBezeled: NO];
1261 [name_label setDrawsBackground: NO];
1262 [name_label setAlignment: NSTextAlignmentCenter];
1263 NSString *qemu_name = [[NSString alloc] initWithCString: gArgv[0]
1264 encoding: NSASCIIStringEncoding];
1265 qemu_name = [qemu_name lastPathComponent];
1266 [name_label setStringValue: qemu_name];
1267 [superView addSubview: name_label];
1268
1269 /* Set the version label's attributes */
1270 x = 0;
1271 y = 50;
1272 int version_width = about_width, version_height = 20;
1273 NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1274 NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1275 version_rect];
1276 [version_label setEditable: NO];
1277 [version_label setBezeled: NO];
1278 [version_label setAlignment: NSTextAlignmentCenter];
1279 [version_label setDrawsBackground: NO];
1280
1281 /* Create the version string*/
1282 NSString *version_string;
1283 version_string = [[NSString alloc] initWithFormat:
1284 @"QEMU emulator version %s%s", QEMU_VERSION, QEMU_PKGVERSION];
1285 [version_label setStringValue: version_string];
1286 [superView addSubview: version_label];
1287
1288 /* Make copyright label */
1289 x = 0;
1290 y = 35;
1291 int copyright_width = about_width, copyright_height = 20;
1292 NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1293 NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1294 copyright_rect];
1295 [copyright_label setEditable: NO];
1296 [copyright_label setBezeled: NO];
1297 [copyright_label setDrawsBackground: NO];
1298 [copyright_label setAlignment: NSTextAlignmentCenter];
1299 [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1300 QEMU_COPYRIGHT]];
1301 [superView addSubview: copyright_label];
1302 }
1303
1304 /* Used by the Speed menu items */
1305 - (void)adjustSpeed:(id)sender
1306 {
1307 int throttle_pct; /* throttle percentage */
1308 NSMenu *menu;
1309
1310 menu = [sender menu];
1311 if (menu != nil)
1312 {
1313 /* Unselect the currently selected item */
1314 for (NSMenuItem *item in [menu itemArray]) {
1315 if (item.state == NSOnState) {
1316 [item setState: NSOffState];
1317 break;
1318 }
1319 }
1320 }
1321
1322 // check the menu item
1323 [sender setState: NSOnState];
1324
1325 // get the throttle percentage
1326 throttle_pct = [sender tag];
1327
1328 cpu_throttle_set(throttle_pct);
1329 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1330 }
1331
1332 @end
1333
1334
1335 int main (int argc, const char * argv[]) {
1336
1337 gArgc = argc;
1338 gArgv = (char **)argv;
1339 int i;
1340
1341 /* In case we don't need to display a window, let's not do that */
1342 for (i = 1; i < argc; i++) {
1343 const char *opt = argv[i];
1344
1345 if (opt[0] == '-') {
1346 /* Treat --foo the same as -foo. */
1347 if (opt[1] == '-') {
1348 opt++;
1349 }
1350 if (!strcmp(opt, "-h") || !strcmp(opt, "-help") ||
1351 !strcmp(opt, "-vnc") ||
1352 !strcmp(opt, "-nographic") ||
1353 !strcmp(opt, "-version") ||
1354 !strcmp(opt, "-curses") ||
1355 !strcmp(opt, "-display") ||
1356 !strcmp(opt, "-qtest")) {
1357 return qemu_main(gArgc, gArgv, *_NSGetEnviron());
1358 }
1359 }
1360 }
1361
1362 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1363
1364 // Pull this console process up to being a fully-fledged graphical
1365 // app with a menubar and Dock icon
1366 ProcessSerialNumber psn = { 0, kCurrentProcess };
1367 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1368
1369 [NSApplication sharedApplication];
1370
1371 // Add menus
1372 NSMenu *menu;
1373 NSMenuItem *menuItem;
1374
1375 [NSApp setMainMenu:[[NSMenu alloc] init]];
1376
1377 // Application menu
1378 menu = [[NSMenu alloc] initWithTitle:@""];
1379 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1380 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1381 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1382 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1383 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1384 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1385 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1386 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1387 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1388 [menuItem setSubmenu:menu];
1389 [[NSApp mainMenu] addItem:menuItem];
1390 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1391
1392 // Machine menu
1393 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1394 [menu setAutoenablesItems: NO];
1395 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1396 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1397 [menu addItem: menuItem];
1398 [menuItem setEnabled: NO];
1399 [menu addItem: [NSMenuItem separatorItem]];
1400 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1401 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1402 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1403 [menuItem setSubmenu:menu];
1404 [[NSApp mainMenu] addItem:menuItem];
1405
1406 // View menu
1407 menu = [[NSMenu alloc] initWithTitle:@"View"];
1408 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1409 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1410 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1411 [menuItem setSubmenu:menu];
1412 [[NSApp mainMenu] addItem:menuItem];
1413
1414 // Speed menu
1415 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1416
1417 // Add the rest of the Speed menu items
1418 int p, percentage, throttle_pct;
1419 for (p = 10; p >= 0; p--)
1420 {
1421 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1422
1423 menuItem = [[[NSMenuItem alloc]
1424 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1425
1426 if (percentage == 100) {
1427 [menuItem setState: NSOnState];
1428 }
1429
1430 /* Calculate the throttle percentage */
1431 throttle_pct = -1 * percentage + 100;
1432
1433 [menuItem setTag: throttle_pct];
1434 [menu addItem: menuItem];
1435 }
1436 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1437 [menuItem setSubmenu:menu];
1438 [[NSApp mainMenu] addItem:menuItem];
1439
1440 // Window menu
1441 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1442 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1443 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1444 [menuItem setSubmenu:menu];
1445 [[NSApp mainMenu] addItem:menuItem];
1446 [NSApp setWindowsMenu:menu];
1447
1448 // Help menu
1449 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1450 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1451 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1452 [menuItem setSubmenu:menu];
1453 [[NSApp mainMenu] addItem:menuItem];
1454
1455 // Create an Application controller
1456 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1457 [NSApp setDelegate:appController];
1458
1459 // Start the main event loop
1460 [NSApp run];
1461
1462 [appController release];
1463 [pool release];
1464
1465 return 0;
1466 }
1467
1468
1469
1470 #pragma mark qemu
1471 static void cocoa_update(DisplayChangeListener *dcl,
1472 int x, int y, int w, int h)
1473 {
1474 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1475
1476 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1477
1478 NSRect rect;
1479 if ([cocoaView cdx] == 1.0) {
1480 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1481 } else {
1482 rect = NSMakeRect(
1483 x * [cocoaView cdx],
1484 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1485 w * [cocoaView cdx],
1486 h * [cocoaView cdy]);
1487 }
1488 [cocoaView setNeedsDisplayInRect:rect];
1489
1490 [pool release];
1491 }
1492
1493 static void cocoa_switch(DisplayChangeListener *dcl,
1494 DisplaySurface *surface)
1495 {
1496 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1497
1498 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1499 [cocoaView switchSurface:surface];
1500 [pool release];
1501 }
1502
1503 static void cocoa_refresh(DisplayChangeListener *dcl)
1504 {
1505 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1506
1507 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
1508 graphic_hw_update(NULL);
1509
1510 if (qemu_input_is_absolute()) {
1511 if (![cocoaView isAbsoluteEnabled]) {
1512 if ([cocoaView isMouseGrabbed]) {
1513 [cocoaView ungrabMouse];
1514 }
1515 }
1516 [cocoaView setAbsoluteEnabled:YES];
1517 }
1518
1519 NSDate *distantPast;
1520 NSEvent *event;
1521 distantPast = [NSDate distantPast];
1522 do {
1523 event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:distantPast
1524 inMode: NSDefaultRunLoopMode dequeue:YES];
1525 if (event != nil) {
1526 [cocoaView handleEvent:event];
1527 }
1528 } while(event != nil);
1529 [pool release];
1530 }
1531
1532 static void cocoa_cleanup(void)
1533 {
1534 COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
1535 g_free(dcl);
1536 }
1537
1538 static const DisplayChangeListenerOps dcl_ops = {
1539 .dpy_name = "cocoa",
1540 .dpy_gfx_update = cocoa_update,
1541 .dpy_gfx_switch = cocoa_switch,
1542 .dpy_refresh = cocoa_refresh,
1543 };
1544
1545 /* Returns a name for a given console */
1546 static NSString * getConsoleName(QemuConsole * console)
1547 {
1548 return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1549 }
1550
1551 /* Add an entry to the View menu for each console */
1552 static void add_console_menu_entries(void)
1553 {
1554 NSMenu *menu;
1555 NSMenuItem *menuItem;
1556 int index = 0;
1557
1558 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1559
1560 [menu addItem:[NSMenuItem separatorItem]];
1561
1562 while (qemu_console_lookup_by_index(index) != NULL) {
1563 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1564 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1565 [menuItem setTag: index];
1566 [menu addItem: menuItem];
1567 index++;
1568 }
1569 }
1570
1571 /* Make menu items for all removable devices.
1572 * Each device is given an 'Eject' and 'Change' menu item.
1573 */
1574 static void addRemovableDevicesMenuItems(void)
1575 {
1576 NSMenu *menu;
1577 NSMenuItem *menuItem;
1578 BlockInfoList *currentDevice, *pointerToFree;
1579 NSString *deviceName;
1580
1581 currentDevice = qmp_query_block(NULL);
1582 pointerToFree = currentDevice;
1583 if(currentDevice == NULL) {
1584 NSBeep();
1585 QEMU_Alert(@"Failed to query for block devices!");
1586 return;
1587 }
1588
1589 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1590
1591 // Add a separator between related groups of menu items
1592 [menu addItem:[NSMenuItem separatorItem]];
1593
1594 // Set the attributes to the "Removable Media" menu item
1595 NSString *titleString = @"Removable Media";
1596 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1597 NSColor *newColor = [NSColor blackColor];
1598 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1599 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1600 traits:NSBoldFontMask|NSItalicFontMask
1601 weight:0
1602 size:14];
1603 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1604 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1605 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1606
1607 // Add the "Removable Media" menu item
1608 menuItem = [NSMenuItem new];
1609 [menuItem setAttributedTitle: attString];
1610 [menuItem setEnabled: NO];
1611 [menu addItem: menuItem];
1612
1613 /* Loop through all the block devices in the emulator */
1614 while (currentDevice) {
1615 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1616
1617 if(currentDevice->value->removable) {
1618 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1619 action: @selector(changeDeviceMedia:)
1620 keyEquivalent: @""];
1621 [menu addItem: menuItem];
1622 [menuItem setRepresentedObject: deviceName];
1623 [menuItem autorelease];
1624
1625 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1626 action: @selector(ejectDeviceMedia:)
1627 keyEquivalent: @""];
1628 [menu addItem: menuItem];
1629 [menuItem setRepresentedObject: deviceName];
1630 [menuItem autorelease];
1631 }
1632 currentDevice = currentDevice->next;
1633 }
1634 qapi_free_BlockInfoList(pointerToFree);
1635 }
1636
1637 void cocoa_display_init(DisplayState *ds, int full_screen)
1638 {
1639 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1640
1641 /* if fullscreen mode is to be used */
1642 if (full_screen == true) {
1643 [NSApp activateIgnoringOtherApps: YES];
1644 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1645 }
1646
1647 dcl = g_malloc0(sizeof(DisplayChangeListener));
1648
1649 // register vga output callbacks
1650 dcl->ops = &dcl_ops;
1651 register_displaychangelistener(dcl);
1652
1653 // register cleanup function
1654 atexit(cocoa_cleanup);
1655
1656 /* At this point QEMU has created all the consoles, so we can add View
1657 * menu entries for them.
1658 */
1659 add_console_menu_entries();
1660
1661 /* Give all removable devices a menu item.
1662 * Has to be called after QEMU has started to
1663 * find out what removable devices it has.
1664 */
1665 addRemovableDevicesMenuItems();
1666 }