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