]> git.proxmox.com Git - mirror_qemu.git/blob - ui/cocoa.m
ui/cocoa: Use the pixman image directly in switchSurface
[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:(pixman_image_t *)image;
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:(pixman_image_t *)image
499 {
500 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
501
502 int w = pixman_image_get_width(image);
503 int h = pixman_image_get_height(image);
504 pixman_format_code_t image_format = pixman_image_get_format(image);
505 /* cdx == 0 means this is our very first surface, in which case we need
506 * to recalculate the content dimensions even if it happens to be the size
507 * of the initial empty window.
508 */
509 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
510
511 int oldh = screen.height;
512 if (isResize) {
513 // Resize before we trigger the redraw, or we'll redraw at the wrong size
514 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
515 screen.width = w;
516 screen.height = h;
517 [self setContentDimensions];
518 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
519 }
520
521 // update screenBuffer
522 if (dataProviderRef)
523 CGDataProviderRelease(dataProviderRef);
524
525 //sync host window color space with guests
526 screen.bitsPerPixel = PIXMAN_FORMAT_BPP(image_format);
527 screen.bitsPerComponent = DIV_ROUND_UP(screen.bitsPerPixel, 8) * 2;
528
529 dataProviderRef = CGDataProviderCreateWithData(NULL, pixman_image_get_data(image), w * 4 * h, NULL);
530
531 // update windows
532 if (isFullscreen) {
533 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
534 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
535 } else {
536 if (qemu_name)
537 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
538 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
539 }
540
541 if (isResize) {
542 [normalWindow center];
543 }
544 }
545
546 - (void) toggleFullScreen:(id)sender
547 {
548 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
549
550 if (isFullscreen) { // switch from fullscreen to desktop
551 isFullscreen = FALSE;
552 [self ungrabMouse];
553 [self setContentDimensions];
554 if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
555 [self exitFullScreenModeWithOptions:nil];
556 } else {
557 [fullScreenWindow close];
558 [normalWindow setContentView: self];
559 [normalWindow makeKeyAndOrderFront: self];
560 [NSMenu setMenuBarVisible:YES];
561 }
562 } else { // switch from desktop to fullscreen
563 isFullscreen = TRUE;
564 [normalWindow orderOut: nil]; /* Hide the window */
565 [self grabMouse];
566 [self setContentDimensions];
567 if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
568 [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
569 [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
570 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
571 nil]];
572 } else {
573 [NSMenu setMenuBarVisible:NO];
574 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
575 styleMask:NSWindowStyleMaskBorderless
576 backing:NSBackingStoreBuffered
577 defer:NO];
578 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
579 [fullScreenWindow setHasShadow:NO];
580 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
581 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
582 [[fullScreenWindow contentView] addSubview: self];
583 [fullScreenWindow makeKeyAndOrderFront:self];
584 }
585 }
586 }
587
588 - (void) toggleModifier: (int)keycode {
589 // Toggle the stored state.
590 modifiers_state[keycode] = !modifiers_state[keycode];
591 // Send a keyup or keydown depending on the state.
592 qemu_input_event_send_key_qcode(dcl->con, keycode, modifiers_state[keycode]);
593 }
594
595 - (void) toggleStatefulModifier: (int)keycode {
596 // Toggle the stored state.
597 modifiers_state[keycode] = !modifiers_state[keycode];
598 // Generate keydown and keyup.
599 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
600 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
601 }
602
603 // Does the work of sending input to the monitor
604 - (void) handleMonitorInput:(NSEvent *)event
605 {
606 int keysym = 0;
607 int control_key = 0;
608
609 // if the control key is down
610 if ([event modifierFlags] & NSEventModifierFlagControl) {
611 control_key = 1;
612 }
613
614 /* translates Macintosh keycodes to QEMU's keysym */
615
616 int without_control_translation[] = {
617 [0 ... 0xff] = 0, // invalid key
618
619 [kVK_UpArrow] = QEMU_KEY_UP,
620 [kVK_DownArrow] = QEMU_KEY_DOWN,
621 [kVK_RightArrow] = QEMU_KEY_RIGHT,
622 [kVK_LeftArrow] = QEMU_KEY_LEFT,
623 [kVK_Home] = QEMU_KEY_HOME,
624 [kVK_End] = QEMU_KEY_END,
625 [kVK_PageUp] = QEMU_KEY_PAGEUP,
626 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
627 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
628 [kVK_Delete] = QEMU_KEY_BACKSPACE,
629 };
630
631 int with_control_translation[] = {
632 [0 ... 0xff] = 0, // invalid key
633
634 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
635 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
636 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
637 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
638 [kVK_Home] = QEMU_KEY_CTRL_HOME,
639 [kVK_End] = QEMU_KEY_CTRL_END,
640 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
641 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
642 };
643
644 if (control_key != 0) { /* If the control key is being used */
645 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
646 keysym = with_control_translation[[event keyCode]];
647 }
648 } else {
649 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
650 keysym = without_control_translation[[event keyCode]];
651 }
652 }
653
654 // if not a key that needs translating
655 if (keysym == 0) {
656 NSString *ks = [event characters];
657 if ([ks length] > 0) {
658 keysym = [ks characterAtIndex:0];
659 }
660 }
661
662 if (keysym) {
663 kbd_put_keysym(keysym);
664 }
665 }
666
667 - (void) handleEvent:(NSEvent *)event
668 {
669 with_iothread_lock(^{
670 [self handleEventLocked:event];
671 });
672 }
673
674 - (void) handleEventLocked:(NSEvent *)event
675 {
676 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
677 int buttons = 0;
678 int keycode = 0;
679 bool mouse_event = false;
680 static bool switched_to_fullscreen = false;
681 NSPoint p = [event locationInWindow];
682
683 switch ([event type]) {
684 case NSEventTypeFlagsChanged:
685 if ([event keyCode] == 0) {
686 // When the Cocoa keyCode is zero that means keys should be
687 // synthesized based on the values in in the eventModifiers
688 // bitmask.
689
690 if (qemu_console_is_graphic(NULL)) {
691 NSUInteger modifiers = [event modifierFlags];
692
693 if (!!(modifiers & NSEventModifierFlagCapsLock) != !!modifiers_state[Q_KEY_CODE_CAPS_LOCK]) {
694 [self toggleStatefulModifier:Q_KEY_CODE_CAPS_LOCK];
695 }
696 if (!!(modifiers & NSEventModifierFlagShift) != !!modifiers_state[Q_KEY_CODE_SHIFT]) {
697 [self toggleModifier:Q_KEY_CODE_SHIFT];
698 }
699 if (!!(modifiers & NSEventModifierFlagControl) != !!modifiers_state[Q_KEY_CODE_CTRL]) {
700 [self toggleModifier:Q_KEY_CODE_CTRL];
701 }
702 if (!!(modifiers & NSEventModifierFlagOption) != !!modifiers_state[Q_KEY_CODE_ALT]) {
703 [self toggleModifier:Q_KEY_CODE_ALT];
704 }
705 if (!!(modifiers & NSEventModifierFlagCommand) != !!modifiers_state[Q_KEY_CODE_META_L]) {
706 [self toggleModifier:Q_KEY_CODE_META_L];
707 }
708 }
709 } else {
710 keycode = cocoa_keycode_to_qemu([event keyCode]);
711 }
712
713 if ((keycode == Q_KEY_CODE_META_L || keycode == Q_KEY_CODE_META_R)
714 && !isMouseGrabbed) {
715 /* Don't pass command key changes to guest unless mouse is grabbed */
716 keycode = 0;
717 }
718
719 if (keycode) {
720 // emulate caps lock and num lock keydown and keyup
721 if (keycode == Q_KEY_CODE_CAPS_LOCK ||
722 keycode == Q_KEY_CODE_NUM_LOCK) {
723 [self toggleStatefulModifier:keycode];
724 } else if (qemu_console_is_graphic(NULL)) {
725 if (switched_to_fullscreen) {
726 switched_to_fullscreen = false;
727 } else {
728 [self toggleModifier:keycode];
729 }
730 }
731 }
732
733 break;
734 case NSEventTypeKeyDown:
735 keycode = cocoa_keycode_to_qemu([event keyCode]);
736
737 // forward command key combos to the host UI unless the mouse is grabbed
738 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
739 /*
740 * Prevent the command key from being stuck down in the guest
741 * when using Command-F to switch to full screen mode.
742 */
743 if (keycode == Q_KEY_CODE_F) {
744 switched_to_fullscreen = true;
745 }
746 [NSApp sendEvent:event];
747 return;
748 }
749
750 // default
751
752 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
753 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
754 NSString *keychar = [event charactersIgnoringModifiers];
755 if ([keychar length] == 1) {
756 char key = [keychar characterAtIndex:0];
757 switch (key) {
758
759 // enable graphic console
760 case '1' ... '9':
761 console_select(key - '0' - 1); /* ascii math */
762 return;
763
764 // release the mouse grab
765 case 'g':
766 [self ungrabMouse];
767 return;
768 }
769 }
770 }
771
772 if (qemu_console_is_graphic(NULL)) {
773 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
774 } else {
775 [self handleMonitorInput: event];
776 }
777 break;
778 case NSEventTypeKeyUp:
779 keycode = cocoa_keycode_to_qemu([event keyCode]);
780
781 // don't pass the guest a spurious key-up if we treated this
782 // command-key combo as a host UI action
783 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
784 return;
785 }
786
787 if (qemu_console_is_graphic(NULL)) {
788 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
789 }
790 break;
791 case NSEventTypeMouseMoved:
792 if (isAbsoluteEnabled) {
793 if (![self screenContainsPoint:p] || ![[self window] isKeyWindow]) {
794 if (isMouseGrabbed) {
795 [self ungrabMouse];
796 }
797 } else {
798 if (!isMouseGrabbed) {
799 [self grabMouse];
800 }
801 }
802 }
803 mouse_event = true;
804 break;
805 case NSEventTypeLeftMouseDown:
806 if ([event modifierFlags] & NSEventModifierFlagCommand) {
807 buttons |= MOUSE_EVENT_RBUTTON;
808 } else {
809 buttons |= MOUSE_EVENT_LBUTTON;
810 }
811 mouse_event = true;
812 break;
813 case NSEventTypeRightMouseDown:
814 buttons |= MOUSE_EVENT_RBUTTON;
815 mouse_event = true;
816 break;
817 case NSEventTypeOtherMouseDown:
818 buttons |= MOUSE_EVENT_MBUTTON;
819 mouse_event = true;
820 break;
821 case NSEventTypeLeftMouseDragged:
822 if ([event modifierFlags] & NSEventModifierFlagCommand) {
823 buttons |= MOUSE_EVENT_RBUTTON;
824 } else {
825 buttons |= MOUSE_EVENT_LBUTTON;
826 }
827 mouse_event = true;
828 break;
829 case NSEventTypeRightMouseDragged:
830 buttons |= MOUSE_EVENT_RBUTTON;
831 mouse_event = true;
832 break;
833 case NSEventTypeOtherMouseDragged:
834 buttons |= MOUSE_EVENT_MBUTTON;
835 mouse_event = true;
836 break;
837 case NSEventTypeLeftMouseUp:
838 mouse_event = true;
839 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
840 if([[self window] isKeyWindow]) {
841 [self grabMouse];
842 }
843 }
844 break;
845 case NSEventTypeRightMouseUp:
846 mouse_event = true;
847 break;
848 case NSEventTypeOtherMouseUp:
849 mouse_event = true;
850 break;
851 case NSEventTypeScrollWheel:
852 /*
853 * Send wheel events to the guest regardless of window focus.
854 * This is in-line with standard Mac OS X UI behaviour.
855 */
856
857 /*
858 * When deltaY is zero, it means that this scrolling event was
859 * either horizontal, or so fine that it only appears in
860 * scrollingDeltaY. So we drop the event.
861 */
862 if ([event deltaY] != 0) {
863 /* Determine if this is a scroll up or scroll down event */
864 buttons = ([event deltaY] > 0) ?
865 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
866 qemu_input_queue_btn(dcl->con, buttons, true);
867 qemu_input_event_sync();
868 qemu_input_queue_btn(dcl->con, buttons, false);
869 qemu_input_event_sync();
870 }
871 /*
872 * Since deltaY also reports scroll wheel events we prevent mouse
873 * movement code from executing.
874 */
875 mouse_event = false;
876 break;
877 default:
878 [NSApp sendEvent:event];
879 }
880
881 if (mouse_event) {
882 /* Don't send button events to the guest unless we've got a
883 * mouse grab or window focus. If we have neither then this event
884 * is the user clicking on the background window to activate and
885 * bring us to the front, which will be done by the sendEvent
886 * call below. We definitely don't want to pass that click through
887 * to the guest.
888 */
889 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
890 (last_buttons != buttons)) {
891 static uint32_t bmap[INPUT_BUTTON__MAX] = {
892 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
893 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
894 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
895 };
896 qemu_input_update_buttons(dcl->con, bmap, last_buttons, buttons);
897 last_buttons = buttons;
898 }
899 if (isMouseGrabbed) {
900 if (isAbsoluteEnabled) {
901 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
902 * The check on screenContainsPoint is to avoid sending out of range values for
903 * clicks in the titlebar.
904 */
905 if ([self screenContainsPoint:p]) {
906 qemu_input_queue_abs(dcl->con, INPUT_AXIS_X, p.x, 0, screen.width);
907 qemu_input_queue_abs(dcl->con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
908 }
909 } else {
910 qemu_input_queue_rel(dcl->con, INPUT_AXIS_X, (int)[event deltaX]);
911 qemu_input_queue_rel(dcl->con, INPUT_AXIS_Y, (int)[event deltaY]);
912 }
913 } else {
914 [NSApp sendEvent:event];
915 }
916 qemu_input_event_sync();
917 }
918 }
919
920 - (void) grabMouse
921 {
922 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
923
924 if (!isFullscreen) {
925 if (qemu_name)
926 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
927 else
928 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
929 }
930 [self hideCursor];
931 if (!isAbsoluteEnabled) {
932 isMouseDeassociated = TRUE;
933 CGAssociateMouseAndMouseCursorPosition(FALSE);
934 }
935 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
936 }
937
938 - (void) ungrabMouse
939 {
940 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
941
942 if (!isFullscreen) {
943 if (qemu_name)
944 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
945 else
946 [normalWindow setTitle:@"QEMU"];
947 }
948 [self unhideCursor];
949 if (isMouseDeassociated) {
950 CGAssociateMouseAndMouseCursorPosition(TRUE);
951 isMouseDeassociated = FALSE;
952 }
953 isMouseGrabbed = FALSE;
954 }
955
956 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
957 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
958 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
959 - (BOOL) isMouseDeassociated {return isMouseDeassociated;}
960 - (float) cdx {return cdx;}
961 - (float) cdy {return cdy;}
962 - (QEMUScreen) gscreen {return screen;}
963
964 /*
965 * Makes the target think all down keys are being released.
966 * This prevents a stuck key problem, since we will not see
967 * key up events for those keys after we have lost focus.
968 */
969 - (void) raiseAllKeys
970 {
971 const int max_index = ARRAY_SIZE(modifiers_state);
972
973 with_iothread_lock(^{
974 int index;
975
976 for (index = 0; index < max_index; index++) {
977 if (modifiers_state[index]) {
978 modifiers_state[index] = 0;
979 qemu_input_event_send_key_qcode(dcl->con, index, false);
980 }
981 }
982 });
983 }
984 @end
985
986
987
988 /*
989 ------------------------------------------------------
990 QemuCocoaAppController
991 ------------------------------------------------------
992 */
993 @interface QemuCocoaAppController : NSObject
994 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
995 <NSWindowDelegate, NSApplicationDelegate>
996 #endif
997 {
998 }
999 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv;
1000 - (void)doToggleFullScreen:(id)sender;
1001 - (void)toggleFullScreen:(id)sender;
1002 - (void)showQEMUDoc:(id)sender;
1003 - (void)zoomToFit:(id) sender;
1004 - (void)displayConsole:(id)sender;
1005 - (void)pauseQEMU:(id)sender;
1006 - (void)resumeQEMU:(id)sender;
1007 - (void)displayPause;
1008 - (void)removePause;
1009 - (void)restartQEMU:(id)sender;
1010 - (void)powerDownQEMU:(id)sender;
1011 - (void)ejectDeviceMedia:(id)sender;
1012 - (void)changeDeviceMedia:(id)sender;
1013 - (BOOL)verifyQuit;
1014 - (void)openDocumentation:(NSString *)filename;
1015 - (IBAction) do_about_menu_item: (id) sender;
1016 - (void)make_about_window;
1017 - (void)adjustSpeed:(id)sender;
1018 @end
1019
1020 @implementation QemuCocoaAppController
1021 - (id) init
1022 {
1023 COCOA_DEBUG("QemuCocoaAppController: init\n");
1024
1025 self = [super init];
1026 if (self) {
1027
1028 // create a view and add it to the window
1029 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1030 if(!cocoaView) {
1031 fprintf(stderr, "(cocoa) can't create a view\n");
1032 exit(1);
1033 }
1034
1035 // create a window
1036 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
1037 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
1038 backing:NSBackingStoreBuffered defer:NO];
1039 if(!normalWindow) {
1040 fprintf(stderr, "(cocoa) can't create window\n");
1041 exit(1);
1042 }
1043 [normalWindow setAcceptsMouseMovedEvents:YES];
1044 [normalWindow setTitle:@"QEMU"];
1045 [normalWindow setContentView:cocoaView];
1046 #if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10)
1047 [normalWindow useOptimizedDrawing:YES];
1048 #endif
1049 [normalWindow makeKeyAndOrderFront:self];
1050 [normalWindow center];
1051 [normalWindow setDelegate: self];
1052 stretch_video = false;
1053
1054 /* Used for displaying pause on the screen */
1055 pauseLabel = [NSTextField new];
1056 [pauseLabel setBezeled:YES];
1057 [pauseLabel setDrawsBackground:YES];
1058 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1059 [pauseLabel setEditable:NO];
1060 [pauseLabel setSelectable:NO];
1061 [pauseLabel setStringValue: @"Paused"];
1062 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1063 [pauseLabel setTextColor: [NSColor blackColor]];
1064 [pauseLabel sizeToFit];
1065
1066 // set the supported image file types that can be opened
1067 supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
1068 @"qcow", @"qcow2", @"cloop", @"vmdk", @"cdr",
1069 @"toast", nil];
1070 [self make_about_window];
1071 }
1072 return self;
1073 }
1074
1075 - (void) dealloc
1076 {
1077 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1078
1079 if (cocoaView)
1080 [cocoaView release];
1081 [super dealloc];
1082 }
1083
1084 - (void)applicationDidFinishLaunching: (NSNotification *) note
1085 {
1086 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1087 // launch QEMU, with the global args
1088 [self startEmulationWithArgc:gArgc argv:(char **)gArgv];
1089 }
1090
1091 - (void)applicationWillTerminate:(NSNotification *)aNotification
1092 {
1093 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1094
1095 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1096 exit(0);
1097 }
1098
1099 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1100 {
1101 return YES;
1102 }
1103
1104 - (NSApplicationTerminateReply)applicationShouldTerminate:
1105 (NSApplication *)sender
1106 {
1107 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1108 return [self verifyQuit];
1109 }
1110
1111 /* Called when the user clicks on a window's close button */
1112 - (BOOL)windowShouldClose:(id)sender
1113 {
1114 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1115 [NSApp terminate: sender];
1116 /* If the user allows the application to quit then the call to
1117 * NSApp terminate will never return. If we get here then the user
1118 * cancelled the quit, so we should return NO to not permit the
1119 * closing of this window.
1120 */
1121 return NO;
1122 }
1123
1124 /* Called when QEMU goes into the background */
1125 - (void) applicationWillResignActive: (NSNotification *)aNotification
1126 {
1127 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1128 [cocoaView raiseAllKeys];
1129 }
1130
1131 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv
1132 {
1133 COCOA_DEBUG("QemuCocoaAppController: startEmulationWithArgc\n");
1134
1135 int status;
1136 status = qemu_main(argc, argv, *_NSGetEnviron());
1137 exit(status);
1138 }
1139
1140 /* We abstract the method called by the Enter Fullscreen menu item
1141 * because Mac OS 10.7 and higher disables it. This is because of the
1142 * menu item's old selector's name toggleFullScreen:
1143 */
1144 - (void) doToggleFullScreen:(id)sender
1145 {
1146 [self toggleFullScreen:(id)sender];
1147 }
1148
1149 - (void)toggleFullScreen:(id)sender
1150 {
1151 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1152
1153 [cocoaView toggleFullScreen:sender];
1154 }
1155
1156 /* Tries to find then open the specified filename */
1157 - (void) openDocumentation: (NSString *) filename
1158 {
1159 /* Where to look for local files */
1160 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"../"};
1161 NSString *full_file_path;
1162
1163 /* iterate thru the possible paths until the file is found */
1164 int index;
1165 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1166 full_file_path = [[NSBundle mainBundle] executablePath];
1167 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1168 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1169 path_array[index], filename];
1170 if ([[NSWorkspace sharedWorkspace] openFile: full_file_path] == YES) {
1171 return;
1172 }
1173 }
1174
1175 /* If none of the paths opened a file */
1176 NSBeep();
1177 QEMU_Alert(@"Failed to open file");
1178 }
1179
1180 - (void)showQEMUDoc:(id)sender
1181 {
1182 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1183
1184 [self openDocumentation: @"qemu-doc.html"];
1185 }
1186
1187 /* Stretches video to fit host monitor size */
1188 - (void)zoomToFit:(id) sender
1189 {
1190 stretch_video = !stretch_video;
1191 if (stretch_video == true) {
1192 [sender setState: NSControlStateValueOn];
1193 } else {
1194 [sender setState: NSControlStateValueOff];
1195 }
1196 }
1197
1198 /* Displays the console on the screen */
1199 - (void)displayConsole:(id)sender
1200 {
1201 console_select([sender tag]);
1202 }
1203
1204 /* Pause the guest */
1205 - (void)pauseQEMU:(id)sender
1206 {
1207 with_iothread_lock(^{
1208 qmp_stop(NULL);
1209 });
1210 [sender setEnabled: NO];
1211 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1212 [self displayPause];
1213 }
1214
1215 /* Resume running the guest operating system */
1216 - (void)resumeQEMU:(id) sender
1217 {
1218 with_iothread_lock(^{
1219 qmp_cont(NULL);
1220 });
1221 [sender setEnabled: NO];
1222 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1223 [self removePause];
1224 }
1225
1226 /* Displays the word pause on the screen */
1227 - (void)displayPause
1228 {
1229 /* Coordinates have to be calculated each time because the window can change its size */
1230 int xCoord, yCoord, width, height;
1231 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1232 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1233 width = [pauseLabel frame].size.width;
1234 height = [pauseLabel frame].size.height;
1235 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1236 [cocoaView addSubview: pauseLabel];
1237 }
1238
1239 /* Removes the word pause from the screen */
1240 - (void)removePause
1241 {
1242 [pauseLabel removeFromSuperview];
1243 }
1244
1245 /* Restarts QEMU */
1246 - (void)restartQEMU:(id)sender
1247 {
1248 with_iothread_lock(^{
1249 qmp_system_reset(NULL);
1250 });
1251 }
1252
1253 /* Powers down QEMU */
1254 - (void)powerDownQEMU:(id)sender
1255 {
1256 with_iothread_lock(^{
1257 qmp_system_powerdown(NULL);
1258 });
1259 }
1260
1261 /* Ejects the media.
1262 * Uses sender's tag to figure out the device to eject.
1263 */
1264 - (void)ejectDeviceMedia:(id)sender
1265 {
1266 NSString * drive;
1267 drive = [sender representedObject];
1268 if(drive == nil) {
1269 NSBeep();
1270 QEMU_Alert(@"Failed to find drive to eject!");
1271 return;
1272 }
1273
1274 __block Error *err = NULL;
1275 with_iothread_lock(^{
1276 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1277 false, NULL, false, false, &err);
1278 });
1279 handleAnyDeviceErrors(err);
1280 }
1281
1282 /* Displays a dialog box asking the user to select an image file to load.
1283 * Uses sender's represented object value to figure out which drive to use.
1284 */
1285 - (void)changeDeviceMedia:(id)sender
1286 {
1287 /* Find the drive name */
1288 NSString * drive;
1289 drive = [sender representedObject];
1290 if(drive == nil) {
1291 NSBeep();
1292 QEMU_Alert(@"Could not find drive!");
1293 return;
1294 }
1295
1296 /* Display the file open dialog */
1297 NSOpenPanel * openPanel;
1298 openPanel = [NSOpenPanel openPanel];
1299 [openPanel setCanChooseFiles: YES];
1300 [openPanel setAllowsMultipleSelection: NO];
1301 [openPanel setAllowedFileTypes: supportedImageFileTypes];
1302 if([openPanel runModal] == NSModalResponseOK) {
1303 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1304 if(file == nil) {
1305 NSBeep();
1306 QEMU_Alert(@"Failed to convert URL to file path!");
1307 return;
1308 }
1309
1310 __block Error *err = NULL;
1311 with_iothread_lock(^{
1312 qmp_blockdev_change_medium(true,
1313 [drive cStringUsingEncoding:
1314 NSASCIIStringEncoding],
1315 false, NULL,
1316 [file cStringUsingEncoding:
1317 NSASCIIStringEncoding],
1318 true, "raw",
1319 false, 0,
1320 &err);
1321 });
1322 handleAnyDeviceErrors(err);
1323 }
1324 }
1325
1326 /* Verifies if the user really wants to quit */
1327 - (BOOL)verifyQuit
1328 {
1329 NSAlert *alert = [NSAlert new];
1330 [alert autorelease];
1331 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1332 [alert addButtonWithTitle: @"Cancel"];
1333 [alert addButtonWithTitle: @"Quit"];
1334 if([alert runModal] == NSAlertSecondButtonReturn) {
1335 return YES;
1336 } else {
1337 return NO;
1338 }
1339 }
1340
1341 /* The action method for the About menu item */
1342 - (IBAction) do_about_menu_item: (id) sender
1343 {
1344 [about_window makeKeyAndOrderFront: nil];
1345 }
1346
1347 /* Create and display the about dialog */
1348 - (void)make_about_window
1349 {
1350 /* Make the window */
1351 int x = 0, y = 0, about_width = 400, about_height = 200;
1352 NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1353 about_window = [[NSWindow alloc] initWithContentRect:window_rect
1354 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1355 NSWindowStyleMaskMiniaturizable
1356 backing:NSBackingStoreBuffered
1357 defer:NO];
1358 [about_window setTitle: @"About"];
1359 [about_window setReleasedWhenClosed: NO];
1360 [about_window center];
1361 NSView *superView = [about_window contentView];
1362
1363 /* Create the dimensions of the picture */
1364 int picture_width = 80, picture_height = 80;
1365 x = (about_width - picture_width)/2;
1366 y = about_height - picture_height - 10;
1367 NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1368
1369 /* Get the path to the QEMU binary */
1370 NSString *binary_name = [NSString stringWithCString: gArgv[0]
1371 encoding: NSASCIIStringEncoding];
1372 binary_name = [binary_name lastPathComponent];
1373 NSString *program_path = [[NSString alloc] initWithFormat: @"%@/%@",
1374 [[NSBundle mainBundle] bundlePath], binary_name];
1375
1376 /* Make the picture of QEMU */
1377 NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1378 picture_rect];
1379 NSImage *qemu_image = [[NSWorkspace sharedWorkspace] iconForFile:
1380 program_path];
1381 [picture_view setImage: qemu_image];
1382 [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1383 [superView addSubview: picture_view];
1384
1385 /* Make the name label */
1386 x = 0;
1387 y = y - 25;
1388 int name_width = about_width, name_height = 20;
1389 NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1390 NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1391 [name_label setEditable: NO];
1392 [name_label setBezeled: NO];
1393 [name_label setDrawsBackground: NO];
1394 [name_label setAlignment: NSTextAlignmentCenter];
1395 NSString *qemu_name = [[NSString alloc] initWithCString: gArgv[0]
1396 encoding: NSASCIIStringEncoding];
1397 qemu_name = [qemu_name lastPathComponent];
1398 [name_label setStringValue: qemu_name];
1399 [superView addSubview: name_label];
1400
1401 /* Set the version label's attributes */
1402 x = 0;
1403 y = 50;
1404 int version_width = about_width, version_height = 20;
1405 NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1406 NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1407 version_rect];
1408 [version_label setEditable: NO];
1409 [version_label setBezeled: NO];
1410 [version_label setAlignment: NSTextAlignmentCenter];
1411 [version_label setDrawsBackground: NO];
1412
1413 /* Create the version string*/
1414 NSString *version_string;
1415 version_string = [[NSString alloc] initWithFormat:
1416 @"QEMU emulator version %s", QEMU_FULL_VERSION];
1417 [version_label setStringValue: version_string];
1418 [superView addSubview: version_label];
1419
1420 /* Make copyright label */
1421 x = 0;
1422 y = 35;
1423 int copyright_width = about_width, copyright_height = 20;
1424 NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1425 NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1426 copyright_rect];
1427 [copyright_label setEditable: NO];
1428 [copyright_label setBezeled: NO];
1429 [copyright_label setDrawsBackground: NO];
1430 [copyright_label setAlignment: NSTextAlignmentCenter];
1431 [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1432 QEMU_COPYRIGHT]];
1433 [superView addSubview: copyright_label];
1434 }
1435
1436 /* Used by the Speed menu items */
1437 - (void)adjustSpeed:(id)sender
1438 {
1439 int throttle_pct; /* throttle percentage */
1440 NSMenu *menu;
1441
1442 menu = [sender menu];
1443 if (menu != nil)
1444 {
1445 /* Unselect the currently selected item */
1446 for (NSMenuItem *item in [menu itemArray]) {
1447 if (item.state == NSControlStateValueOn) {
1448 [item setState: NSControlStateValueOff];
1449 break;
1450 }
1451 }
1452 }
1453
1454 // check the menu item
1455 [sender setState: NSControlStateValueOn];
1456
1457 // get the throttle percentage
1458 throttle_pct = [sender tag];
1459
1460 with_iothread_lock(^{
1461 cpu_throttle_set(throttle_pct);
1462 });
1463 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1464 }
1465
1466 @end
1467
1468
1469 int main (int argc, const char * argv[]) {
1470
1471 gArgc = argc;
1472 gArgv = (char **)argv;
1473 int i;
1474
1475 /* In case we don't need to display a window, let's not do that */
1476 for (i = 1; i < argc; i++) {
1477 const char *opt = argv[i];
1478
1479 if (opt[0] == '-') {
1480 /* Treat --foo the same as -foo. */
1481 if (opt[1] == '-') {
1482 opt++;
1483 }
1484 if (!strcmp(opt, "-h") || !strcmp(opt, "-help") ||
1485 !strcmp(opt, "-vnc") ||
1486 !strcmp(opt, "-nographic") ||
1487 !strcmp(opt, "-version") ||
1488 !strcmp(opt, "-curses") ||
1489 !strcmp(opt, "-display") ||
1490 !strcmp(opt, "-qtest")) {
1491 return qemu_main(gArgc, gArgv, *_NSGetEnviron());
1492 }
1493 }
1494 }
1495
1496 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1497
1498 // Pull this console process up to being a fully-fledged graphical
1499 // app with a menubar and Dock icon
1500 ProcessSerialNumber psn = { 0, kCurrentProcess };
1501 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1502
1503 [NSApplication sharedApplication];
1504
1505 // Add menus
1506 NSMenu *menu;
1507 NSMenuItem *menuItem;
1508
1509 [NSApp setMainMenu:[[NSMenu alloc] init]];
1510
1511 // Application menu
1512 menu = [[NSMenu alloc] initWithTitle:@""];
1513 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1514 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1515 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1516 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1517 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1518 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1519 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1520 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1521 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1522 [menuItem setSubmenu:menu];
1523 [[NSApp mainMenu] addItem:menuItem];
1524 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1525
1526 // Machine menu
1527 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1528 [menu setAutoenablesItems: NO];
1529 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1530 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1531 [menu addItem: menuItem];
1532 [menuItem setEnabled: NO];
1533 [menu addItem: [NSMenuItem separatorItem]];
1534 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1535 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1536 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1537 [menuItem setSubmenu:menu];
1538 [[NSApp mainMenu] addItem:menuItem];
1539
1540 // View menu
1541 menu = [[NSMenu alloc] initWithTitle:@"View"];
1542 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1543 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1544 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1545 [menuItem setSubmenu:menu];
1546 [[NSApp mainMenu] addItem:menuItem];
1547
1548 // Speed menu
1549 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1550
1551 // Add the rest of the Speed menu items
1552 int p, percentage, throttle_pct;
1553 for (p = 10; p >= 0; p--)
1554 {
1555 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1556
1557 menuItem = [[[NSMenuItem alloc]
1558 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1559
1560 if (percentage == 100) {
1561 [menuItem setState: NSControlStateValueOn];
1562 }
1563
1564 /* Calculate the throttle percentage */
1565 throttle_pct = -1 * percentage + 100;
1566
1567 [menuItem setTag: throttle_pct];
1568 [menu addItem: menuItem];
1569 }
1570 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1571 [menuItem setSubmenu:menu];
1572 [[NSApp mainMenu] addItem:menuItem];
1573
1574 // Window menu
1575 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1576 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1577 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1578 [menuItem setSubmenu:menu];
1579 [[NSApp mainMenu] addItem:menuItem];
1580 [NSApp setWindowsMenu:menu];
1581
1582 // Help menu
1583 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1584 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1585 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1586 [menuItem setSubmenu:menu];
1587 [[NSApp mainMenu] addItem:menuItem];
1588
1589 // Create an Application controller
1590 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1591 [NSApp setDelegate:appController];
1592
1593 // Start the main event loop
1594 [NSApp run];
1595
1596 [appController release];
1597 [pool release];
1598
1599 return 0;
1600 }
1601
1602
1603
1604 #pragma mark qemu
1605 static void cocoa_update(DisplayChangeListener *dcl,
1606 int x, int y, int w, int h)
1607 {
1608 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1609
1610 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1611
1612 NSRect rect;
1613 if ([cocoaView cdx] == 1.0) {
1614 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1615 } else {
1616 rect = NSMakeRect(
1617 x * [cocoaView cdx],
1618 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1619 w * [cocoaView cdx],
1620 h * [cocoaView cdy]);
1621 }
1622 [cocoaView setNeedsDisplayInRect:rect];
1623
1624 [pool release];
1625 }
1626
1627 static void cocoa_switch(DisplayChangeListener *dcl,
1628 DisplaySurface *surface)
1629 {
1630 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1631
1632 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
1633 [cocoaView switchSurface:surface->image];
1634 [pool release];
1635 }
1636
1637 static void cocoa_refresh(DisplayChangeListener *dcl)
1638 {
1639 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1640
1641 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
1642 graphic_hw_update(NULL);
1643
1644 if (qemu_input_is_absolute()) {
1645 if (![cocoaView isAbsoluteEnabled]) {
1646 if ([cocoaView isMouseGrabbed]) {
1647 [cocoaView ungrabMouse];
1648 }
1649 }
1650 [cocoaView setAbsoluteEnabled:YES];
1651 }
1652
1653 NSDate *distantPast;
1654 NSEvent *event;
1655 distantPast = [NSDate distantPast];
1656 do {
1657 event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:distantPast
1658 inMode: NSDefaultRunLoopMode dequeue:YES];
1659 if (event != nil) {
1660 [cocoaView handleEvent:event];
1661 }
1662 } while(event != nil);
1663 [pool release];
1664 }
1665
1666 static void cocoa_cleanup(void)
1667 {
1668 COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
1669 g_free(dcl);
1670 }
1671
1672 static const DisplayChangeListenerOps dcl_ops = {
1673 .dpy_name = "cocoa",
1674 .dpy_gfx_update = cocoa_update,
1675 .dpy_gfx_switch = cocoa_switch,
1676 .dpy_refresh = cocoa_refresh,
1677 };
1678
1679 /* Returns a name for a given console */
1680 static NSString * getConsoleName(QemuConsole * console)
1681 {
1682 return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1683 }
1684
1685 /* Add an entry to the View menu for each console */
1686 static void add_console_menu_entries(void)
1687 {
1688 NSMenu *menu;
1689 NSMenuItem *menuItem;
1690 int index = 0;
1691
1692 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1693
1694 [menu addItem:[NSMenuItem separatorItem]];
1695
1696 while (qemu_console_lookup_by_index(index) != NULL) {
1697 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1698 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1699 [menuItem setTag: index];
1700 [menu addItem: menuItem];
1701 index++;
1702 }
1703 }
1704
1705 /* Make menu items for all removable devices.
1706 * Each device is given an 'Eject' and 'Change' menu item.
1707 */
1708 static void addRemovableDevicesMenuItems(void)
1709 {
1710 NSMenu *menu;
1711 NSMenuItem *menuItem;
1712 BlockInfoList *currentDevice, *pointerToFree;
1713 NSString *deviceName;
1714
1715 currentDevice = qmp_query_block(NULL);
1716 pointerToFree = currentDevice;
1717 if(currentDevice == NULL) {
1718 NSBeep();
1719 QEMU_Alert(@"Failed to query for block devices!");
1720 return;
1721 }
1722
1723 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1724
1725 // Add a separator between related groups of menu items
1726 [menu addItem:[NSMenuItem separatorItem]];
1727
1728 // Set the attributes to the "Removable Media" menu item
1729 NSString *titleString = @"Removable Media";
1730 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1731 NSColor *newColor = [NSColor blackColor];
1732 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1733 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1734 traits:NSBoldFontMask|NSItalicFontMask
1735 weight:0
1736 size:14];
1737 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1738 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1739 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1740
1741 // Add the "Removable Media" menu item
1742 menuItem = [NSMenuItem new];
1743 [menuItem setAttributedTitle: attString];
1744 [menuItem setEnabled: NO];
1745 [menu addItem: menuItem];
1746
1747 /* Loop through all the block devices in the emulator */
1748 while (currentDevice) {
1749 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1750
1751 if(currentDevice->value->removable) {
1752 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1753 action: @selector(changeDeviceMedia:)
1754 keyEquivalent: @""];
1755 [menu addItem: menuItem];
1756 [menuItem setRepresentedObject: deviceName];
1757 [menuItem autorelease];
1758
1759 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1760 action: @selector(ejectDeviceMedia:)
1761 keyEquivalent: @""];
1762 [menu addItem: menuItem];
1763 [menuItem setRepresentedObject: deviceName];
1764 [menuItem autorelease];
1765 }
1766 currentDevice = currentDevice->next;
1767 }
1768 qapi_free_BlockInfoList(pointerToFree);
1769 }
1770
1771 static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
1772 {
1773 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1774
1775 /* if fullscreen mode is to be used */
1776 if (opts->has_full_screen && opts->full_screen) {
1777 [NSApp activateIgnoringOtherApps: YES];
1778 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1779 }
1780
1781 dcl = g_malloc0(sizeof(DisplayChangeListener));
1782
1783 // register vga output callbacks
1784 dcl->ops = &dcl_ops;
1785 register_displaychangelistener(dcl);
1786
1787 // register cleanup function
1788 atexit(cocoa_cleanup);
1789
1790 /* At this point QEMU has created all the consoles, so we can add View
1791 * menu entries for them.
1792 */
1793 add_console_menu_entries();
1794
1795 /* Give all removable devices a menu item.
1796 * Has to be called after QEMU has started to
1797 * find out what removable devices it has.
1798 */
1799 addRemovableDevicesMenuItems();
1800 }
1801
1802 static QemuDisplay qemu_display_cocoa = {
1803 .type = DISPLAY_TYPE_COCOA,
1804 .init = cocoa_display_init,
1805 };
1806
1807 static void register_cocoa(void)
1808 {
1809 qemu_display_register(&qemu_display_cocoa);
1810 }
1811
1812 type_init(register_cocoa);