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