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