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