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