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