blob: 13fba8103e1a50334a31d936669c5a2a39c4f71c [file] [log] [blame]
bellard5b0753e2005-03-01 21:37:28 +00001/*
thsc304f7e2008-01-22 23:25:15 +00002 * QEMU Cocoa CG display driver
ths5fafdf22007-09-16 21:08:06 +00003 *
thsc304f7e2008-01-22 23:25:15 +00004 * Copyright (c) 2008 Mike Kronenberg
ths5fafdf22007-09-16 21:08:06 +00005 *
bellard5b0753e2005-03-01 21:37:28 +00006 * 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 */
bellardda4dbf72005-03-02 22:22:43 +000024
Peter Maydelle4a096b2016-01-29 16:23:34 +000025#include "qemu/osdep.h"
26
bellard5b0753e2005-03-01 21:37:28 +000027#import <Cocoa/Cocoa.h>
Andreas Färber3bbbee12011-05-29 19:42:51 +020028#include <crt_externs.h>
bellard5b0753e2005-03-01 21:37:28 +000029
pbrook87ecb682007-11-17 17:14:51 +000030#include "qemu-common.h"
Paolo Bonzini28ecbae2012-11-28 12:06:30 +010031#include "ui/console.h"
Gerd Hoffmann21bae112013-12-04 14:08:04 +010032#include "ui/input.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010033#include "sysemu/sysemu.h"
Markus Armbruster54d31232019-08-12 07:23:59 +020034#include "sysemu/runstate.h"
Claudio Fontanab0c3cf92020-06-29 11:35:03 +020035#include "sysemu/cpu-throttle.h"
Markus Armbrustere688df62018-02-01 12:18:31 +010036#include "qapi/error.h"
Markus Armbruster16bf5232018-12-20 09:45:59 +010037#include "qapi/qapi-commands-block.h"
Philippe Mathieu-Daudé90f8c0f2020-10-12 14:15:33 +020038#include "qapi/qapi-commands-machine.h"
Markus Armbruster16bf5232018-12-20 09:45:59 +010039#include "qapi/qapi-commands-misc.h"
John Arbuckle693a3e02015-06-19 10:53:27 +010040#include "sysemu/blockdev.h"
Programmingkid9e8204b2016-08-15 22:11:06 -040041#include "qemu-version.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020042#include "qemu/main-loop.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020043#include "qemu/module.h"
John Arbuckleaaac7142016-03-23 14:26:18 +000044#include <Carbon/Carbon.h>
Markus Armbruster2e5b09f2019-07-09 17:20:52 +020045#include "hw/core/cpu.h"
bellardda4dbf72005-03-02 22:22:43 +000046
Brendan Shanks5e246002019-01-31 23:12:25 -080047#ifndef MAC_OS_X_VERSION_10_13
48#define MAC_OS_X_VERSION_10_13 101300
49#endif
Andreas Färber44e4c0b2009-12-13 00:45:40 +010050
Brendan Shanks5e246002019-01-31 23:12:25 -080051/* 10.14 deprecates NSOnState and NSOffState in favor of
52 * NSControlStateValueOn/Off, which were introduced in 10.13.
53 * Define for older versions
54 */
55#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
56#define NSControlStateValueOn NSOnState
57#define NSControlStateValueOff NSOffState
58#endif
bellard5b0753e2005-03-01 21:37:28 +000059
thsc304f7e2008-01-22 23:25:15 +000060//#define DEBUG
61
62#ifdef DEBUG
63#define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
64#else
65#define COCOA_DEBUG(...) ((void) 0)
66#endif
67
68#define cgrect(nsrect) (*(CGRect *)&(nsrect))
thsc304f7e2008-01-22 23:25:15 +000069
70typedef struct {
71 int width;
72 int height;
73 int bitsPerComponent;
74 int bitsPerPixel;
75} QEMUScreen;
76
Programmingkid9e8204b2016-08-15 22:11:06 -040077NSWindow *normalWindow, *about_window;
aliguori9794f742009-03-04 19:25:22 +000078static DisplayChangeListener *dcl;
Gerd Hoffmann21bae112013-12-04 14:08:04 +010079static int last_buttons;
Gerd Hoffmann3487da62020-02-06 12:27:50 +010080static int cursor_hide = 1;
bellard5b0753e2005-03-01 21:37:28 +000081
82int gArgc;
83char **gArgv;
Programmingkid5d1b2ee2015-05-19 09:11:17 +010084bool stretch_video;
John Arbuckle8524f1c2015-06-19 10:53:27 +010085NSTextField *pauseLabel;
John Arbuckle693a3e02015-06-19 10:53:27 +010086NSArray * supportedImageFileTypes;
bellard5b0753e2005-03-01 21:37:28 +000087
Peter Maydell55888402019-02-25 10:24:33 +000088static QemuSemaphore display_init_sem;
89static QemuSemaphore app_started_sem;
Hikaru Nishidadff742a2019-10-15 10:07:34 +090090static bool allow_events;
Peter Maydell55888402019-02-25 10:24:33 +000091
Peter Maydell60105d72019-02-25 10:24:31 +000092// Utility functions to run specified code block with iothread lock held
Peter Maydell31819e92019-02-25 10:24:27 +000093typedef void (^CodeBlock)(void);
Peter Maydell60105d72019-02-25 10:24:31 +000094typedef bool (^BoolCodeBlock)(void);
Peter Maydell31819e92019-02-25 10:24:27 +000095
96static void with_iothread_lock(CodeBlock block)
97{
98 bool locked = qemu_mutex_iothread_locked();
99 if (!locked) {
100 qemu_mutex_lock_iothread();
101 }
102 block();
103 if (!locked) {
104 qemu_mutex_unlock_iothread();
105 }
106}
107
Peter Maydell60105d72019-02-25 10:24:31 +0000108static bool bool_with_iothread_lock(BoolCodeBlock block)
109{
110 bool locked = qemu_mutex_iothread_locked();
111 bool val;
112
113 if (!locked) {
114 qemu_mutex_lock_iothread();
115 }
116 val = block();
117 if (!locked) {
118 qemu_mutex_unlock_iothread();
119 }
120 return val;
121}
122
John Arbuckleaaac7142016-03-23 14:26:18 +0000123// Mac to QKeyCode conversion
124const int mac_to_qkeycode_map[] = {
125 [kVK_ANSI_A] = Q_KEY_CODE_A,
126 [kVK_ANSI_B] = Q_KEY_CODE_B,
127 [kVK_ANSI_C] = Q_KEY_CODE_C,
128 [kVK_ANSI_D] = Q_KEY_CODE_D,
129 [kVK_ANSI_E] = Q_KEY_CODE_E,
130 [kVK_ANSI_F] = Q_KEY_CODE_F,
131 [kVK_ANSI_G] = Q_KEY_CODE_G,
132 [kVK_ANSI_H] = Q_KEY_CODE_H,
133 [kVK_ANSI_I] = Q_KEY_CODE_I,
134 [kVK_ANSI_J] = Q_KEY_CODE_J,
135 [kVK_ANSI_K] = Q_KEY_CODE_K,
136 [kVK_ANSI_L] = Q_KEY_CODE_L,
137 [kVK_ANSI_M] = Q_KEY_CODE_M,
138 [kVK_ANSI_N] = Q_KEY_CODE_N,
139 [kVK_ANSI_O] = Q_KEY_CODE_O,
140 [kVK_ANSI_P] = Q_KEY_CODE_P,
141 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
142 [kVK_ANSI_R] = Q_KEY_CODE_R,
143 [kVK_ANSI_S] = Q_KEY_CODE_S,
144 [kVK_ANSI_T] = Q_KEY_CODE_T,
145 [kVK_ANSI_U] = Q_KEY_CODE_U,
146 [kVK_ANSI_V] = Q_KEY_CODE_V,
147 [kVK_ANSI_W] = Q_KEY_CODE_W,
148 [kVK_ANSI_X] = Q_KEY_CODE_X,
149 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
150 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
ths3b46e622007-09-17 08:09:54 +0000151
John Arbuckleaaac7142016-03-23 14:26:18 +0000152 [kVK_ANSI_0] = Q_KEY_CODE_0,
153 [kVK_ANSI_1] = Q_KEY_CODE_1,
154 [kVK_ANSI_2] = Q_KEY_CODE_2,
155 [kVK_ANSI_3] = Q_KEY_CODE_3,
156 [kVK_ANSI_4] = Q_KEY_CODE_4,
157 [kVK_ANSI_5] = Q_KEY_CODE_5,
158 [kVK_ANSI_6] = Q_KEY_CODE_6,
159 [kVK_ANSI_7] = Q_KEY_CODE_7,
160 [kVK_ANSI_8] = Q_KEY_CODE_8,
161 [kVK_ANSI_9] = Q_KEY_CODE_9,
162
163 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
164 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
165 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
166 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
167 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
168 [kVK_Tab] = Q_KEY_CODE_TAB,
169 [kVK_Return] = Q_KEY_CODE_RET,
170 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
171 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
172 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
173 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
174 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
175 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
176 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
177 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
178 [kVK_Shift] = Q_KEY_CODE_SHIFT,
179 [kVK_RightShift] = Q_KEY_CODE_SHIFT_R,
180 [kVK_Control] = Q_KEY_CODE_CTRL,
181 [kVK_RightControl] = Q_KEY_CODE_CTRL_R,
182 [kVK_Option] = Q_KEY_CODE_ALT,
183 [kVK_RightOption] = Q_KEY_CODE_ALT_R,
184 [kVK_Command] = Q_KEY_CODE_META_L,
185 [0x36] = Q_KEY_CODE_META_R, /* There is no kVK_RightCommand */
186 [kVK_Space] = Q_KEY_CODE_SPC,
187
188 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
189 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
190 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
191 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
192 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
193 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
194 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
195 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
196 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
197 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
198 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
199 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
200 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
201 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
202 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
203 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
204 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
205 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
206
207 [kVK_UpArrow] = Q_KEY_CODE_UP,
208 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
209 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
210 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
211
212 [kVK_Help] = Q_KEY_CODE_INSERT,
213 [kVK_Home] = Q_KEY_CODE_HOME,
214 [kVK_PageUp] = Q_KEY_CODE_PGUP,
215 [kVK_PageDown] = Q_KEY_CODE_PGDN,
216 [kVK_End] = Q_KEY_CODE_END,
217 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
218
219 [kVK_Escape] = Q_KEY_CODE_ESC,
220
221 /* The Power key can't be used directly because the operating system uses
222 * it. This key can be emulated by using it in place of another key such as
223 * F1. Don't forget to disable the real key binding.
224 */
225 /* [kVK_F1] = Q_KEY_CODE_POWER, */
226
227 [kVK_F1] = Q_KEY_CODE_F1,
228 [kVK_F2] = Q_KEY_CODE_F2,
229 [kVK_F3] = Q_KEY_CODE_F3,
230 [kVK_F4] = Q_KEY_CODE_F4,
231 [kVK_F5] = Q_KEY_CODE_F5,
232 [kVK_F6] = Q_KEY_CODE_F6,
233 [kVK_F7] = Q_KEY_CODE_F7,
234 [kVK_F8] = Q_KEY_CODE_F8,
235 [kVK_F9] = Q_KEY_CODE_F9,
236 [kVK_F10] = Q_KEY_CODE_F10,
237 [kVK_F11] = Q_KEY_CODE_F11,
238 [kVK_F12] = Q_KEY_CODE_F12,
239 [kVK_F13] = Q_KEY_CODE_PRINT,
240 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
241 [kVK_F15] = Q_KEY_CODE_PAUSE,
242
243 /*
244 * The eject and volume keys can't be used here because they are handled at
245 * a lower level than what an Application can see.
246 */
bellard5b0753e2005-03-01 21:37:28 +0000247};
248
Andreas Färber77047bb2009-12-13 00:55:53 +0100249static int cocoa_keycode_to_qemu(int keycode)
bellard5b0753e2005-03-01 21:37:28 +0000250{
John Arbuckleaaac7142016-03-23 14:26:18 +0000251 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
Peter Maydell01cc4e62013-12-08 22:59:04 +0000252 fprintf(stderr, "(cocoa) warning unknown keycode 0x%x\n", keycode);
bellard5b0753e2005-03-01 21:37:28 +0000253 return 0;
254 }
John Arbuckleaaac7142016-03-23 14:26:18 +0000255 return mac_to_qkeycode_map[keycode];
bellard5b0753e2005-03-01 21:37:28 +0000256}
257
John Arbuckle693a3e02015-06-19 10:53:27 +0100258/* Displays an alert dialog box with the specified message */
259static void QEMU_Alert(NSString *message)
260{
261 NSAlert *alert;
262 alert = [NSAlert new];
263 [alert setMessageText: message];
264 [alert runModal];
265}
thsc304f7e2008-01-22 23:25:15 +0000266
John Arbuckle693a3e02015-06-19 10:53:27 +0100267/* Handles any errors that happen with a device transaction */
268static void handleAnyDeviceErrors(Error * err)
269{
270 if (err) {
271 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
272 encoding: NSASCIIStringEncoding]);
273 error_free(err);
274 }
275}
thsc304f7e2008-01-22 23:25:15 +0000276
bellard5b0753e2005-03-01 21:37:28 +0000277/*
278 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +0000279 QemuCocoaView
bellard5b0753e2005-03-01 21:37:28 +0000280 ------------------------------------------------------
281*/
thsc304f7e2008-01-22 23:25:15 +0000282@interface QemuCocoaView : NSView
bellard5b0753e2005-03-01 21:37:28 +0000283{
thsc304f7e2008-01-22 23:25:15 +0000284 QEMUScreen screen;
285 NSWindow *fullScreenWindow;
286 float cx,cy,cw,ch,cdx,cdy;
287 CGDataProviderRef dataProviderRef;
Peter Maydell55888402019-02-25 10:24:33 +0000288 pixman_image_t *pixman_image;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700289 BOOL modifiers_state[256];
Peter Maydell49b9bd42013-12-08 22:59:03 +0000290 BOOL isMouseGrabbed;
thsc304f7e2008-01-22 23:25:15 +0000291 BOOL isFullscreen;
292 BOOL isAbsoluteEnabled;
Peter Maydellf61c3872014-06-23 10:35:24 +0100293 BOOL isMouseDeassociated;
thsc304f7e2008-01-22 23:25:15 +0000294}
Peter Maydell72a3e312019-02-25 10:24:28 +0000295- (void) switchSurface:(pixman_image_t *)image;
thsc304f7e2008-01-22 23:25:15 +0000296- (void) grabMouse;
297- (void) ungrabMouse;
298- (void) toggleFullScreen:(id)sender;
John Arbuckle9c3a4182017-11-07 10:14:14 +0000299- (void) handleMonitorInput:(NSEvent *)event;
Peter Maydell60105d72019-02-25 10:24:31 +0000300- (bool) handleEvent:(NSEvent *)event;
301- (bool) handleEventLocked:(NSEvent *)event;
thsc304f7e2008-01-22 23:25:15 +0000302- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
Peter Maydellf61c3872014-06-23 10:35:24 +0100303/* The state surrounding mouse grabbing is potentially confusing.
304 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
305 * pointing device an absolute-position one?"], but is only updated on
306 * next refresh.
307 * isMouseGrabbed tracks whether GUI events are directed to the guest;
308 * it controls whether special keys like Cmd get sent to the guest,
309 * and whether we capture the mouse when in non-absolute mode.
310 * isMouseDeassociated tracks whether we've told MacOSX to disassociate
311 * the mouse and mouse cursor position by calling
312 * CGAssociateMouseAndMouseCursorPosition(FALSE)
313 * (which basically happens if we grab in non-absolute mode).
314 */
Peter Maydell49b9bd42013-12-08 22:59:03 +0000315- (BOOL) isMouseGrabbed;
thsc304f7e2008-01-22 23:25:15 +0000316- (BOOL) isAbsoluteEnabled;
Peter Maydellf61c3872014-06-23 10:35:24 +0100317- (BOOL) isMouseDeassociated;
thsc304f7e2008-01-22 23:25:15 +0000318- (float) cdx;
319- (float) cdy;
320- (QEMUScreen) gscreen;
John Arbuckle3b178b72015-09-25 23:14:00 +0100321- (void) raiseAllKeys;
thsc304f7e2008-01-22 23:25:15 +0000322@end
ths3b46e622007-09-17 08:09:54 +0000323
Andreas Färber7fee1992011-06-09 20:53:32 +0200324QemuCocoaView *cocoaView;
325
thsc304f7e2008-01-22 23:25:15 +0000326@implementation QemuCocoaView
327- (id)initWithFrame:(NSRect)frameRect
328{
329 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
ths3b46e622007-09-17 08:09:54 +0000330
thsc304f7e2008-01-22 23:25:15 +0000331 self = [super initWithFrame:frameRect];
332 if (self) {
pbrook95219892006-04-09 01:06:34 +0000333
thsc304f7e2008-01-22 23:25:15 +0000334 screen.bitsPerComponent = 8;
335 screen.bitsPerPixel = 32;
336 screen.width = frameRect.size.width;
337 screen.height = frameRect.size.height;
bellard7c206a72005-12-18 19:18:45 +0000338
thsc304f7e2008-01-22 23:25:15 +0000339 }
340 return self;
341}
bellard7c206a72005-12-18 19:18:45 +0000342
thsc304f7e2008-01-22 23:25:15 +0000343- (void) dealloc
344{
345 COCOA_DEBUG("QemuCocoaView: dealloc\n");
bellard7c206a72005-12-18 19:18:45 +0000346
Peter Maydell55888402019-02-25 10:24:33 +0000347 if (dataProviderRef) {
thsc304f7e2008-01-22 23:25:15 +0000348 CGDataProviderRelease(dataProviderRef);
Peter Maydell55888402019-02-25 10:24:33 +0000349 pixman_image_unref(pixman_image);
350 }
ths3b46e622007-09-17 08:09:54 +0000351
thsc304f7e2008-01-22 23:25:15 +0000352 [super dealloc];
353}
bellard5cbfcd02006-06-14 15:53:24 +0000354
Andreas Färberd50f71d2009-12-13 02:03:33 +0100355- (BOOL) isOpaque
356{
357 return YES;
358}
359
Peter Maydell5dd45be2014-06-23 10:35:23 +0100360- (BOOL) screenContainsPoint:(NSPoint) p
361{
362 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
363}
364
Chen Zhang2044dff2019-06-04 17:36:00 +0800365/* Get location of event and convert to virtual screen coordinate */
366- (CGPoint) screenLocationOfEvent:(NSEvent *)ev
367{
368 NSWindow *eventWindow = [ev window];
369 // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
370 CGRect r = CGRectZero;
371 r.origin = [ev locationInWindow];
372 if (!eventWindow) {
373 if (!isFullscreen) {
374 return [[self window] convertRectFromScreen:r].origin;
375 } else {
376 CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
377 CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
378 if (stretch_video) {
379 loc.x /= cdx;
380 loc.y /= cdy;
381 }
382 return loc;
383 }
384 } else if ([[self window] isEqual:eventWindow]) {
385 if (!isFullscreen) {
386 return r.origin;
387 } else {
388 CGPoint loc = [self convertPoint:r.origin fromView:nil];
389 if (stretch_video) {
390 loc.x /= cdx;
391 loc.y /= cdy;
392 }
393 return loc;
394 }
395 } else {
396 return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
397 }
398}
399
Peter Maydell13aefd32014-06-23 10:35:25 +0100400- (void) hideCursor
401{
402 if (!cursor_hide) {
403 return;
404 }
405 [NSCursor hide];
406}
407
408- (void) unhideCursor
409{
410 if (!cursor_hide) {
411 return;
412 }
413 [NSCursor unhide];
414}
415
thsc304f7e2008-01-22 23:25:15 +0000416- (void) drawRect:(NSRect) rect
417{
418 COCOA_DEBUG("QemuCocoaView: drawRect\n");
bellard5cbfcd02006-06-14 15:53:24 +0000419
thsc304f7e2008-01-22 23:25:15 +0000420 // get CoreGraphic context
Brendan Shanks5e246002019-01-31 23:12:25 -0800421 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
Brendan Shanks5e246002019-01-31 23:12:25 -0800422
thsc304f7e2008-01-22 23:25:15 +0000423 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
424 CGContextSetShouldAntialias (viewContextRef, NO);
ths3b46e622007-09-17 08:09:54 +0000425
thsc304f7e2008-01-22 23:25:15 +0000426 // draw screen bitmap directly to Core Graphics context
Peter Maydell7d270b12013-12-24 02:51:47 +0000427 if (!dataProviderRef) {
428 // Draw request before any guest device has set up a framebuffer:
429 // just draw an opaque black rectangle
430 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
431 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
432 } else {
thsc304f7e2008-01-22 23:25:15 +0000433 CGImageRef imageRef = CGImageCreate(
434 screen.width, //width
435 screen.height, //height
436 screen.bitsPerComponent, //bitsPerComponent
437 screen.bitsPerPixel, //bitsPerPixel
aliguori9794f742009-03-04 19:25:22 +0000438 (screen.width * (screen.bitsPerComponent/2)), //bytesPerRow
Andreas Färber04afa4a2009-12-13 00:58:21 +0100439#ifdef __LITTLE_ENDIAN__
thsc304f7e2008-01-22 23:25:15 +0000440 CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
aliguori9794f742009-03-04 19:25:22 +0000441 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
thsc304f7e2008-01-22 23:25:15 +0000442#else
443 CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
444 kCGImageAlphaNoneSkipFirst, //bitmapInfo
445#endif
446 dataProviderRef, //provider
447 NULL, //decode
448 0, //interpolate
449 kCGRenderingIntentDefault //intent
450 );
Peter Maydellb63901d2015-05-19 09:11:17 +0100451 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
452 const NSRect *rectList;
Peter Maydellb63901d2015-05-19 09:11:17 +0100453 NSInteger rectCount;
Peter Maydellb63901d2015-05-19 09:11:17 +0100454 int i;
455 CGImageRef clipImageRef;
456 CGRect clipRect;
ths3b46e622007-09-17 08:09:54 +0000457
Peter Maydellb63901d2015-05-19 09:11:17 +0100458 [self getRectsBeingDrawn:&rectList count:&rectCount];
459 for (i = 0; i < rectCount; i++) {
460 clipRect.origin.x = rectList[i].origin.x / cdx;
461 clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
462 clipRect.size.width = rectList[i].size.width / cdx;
463 clipRect.size.height = rectList[i].size.height / cdy;
464 clipImageRef = CGImageCreateWithImageInRect(
465 imageRef,
466 clipRect
467 );
468 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
469 CGImageRelease (clipImageRef);
bellard5b0753e2005-03-01 21:37:28 +0000470 }
thsc304f7e2008-01-22 23:25:15 +0000471 CGImageRelease (imageRef);
bellard5b0753e2005-03-01 21:37:28 +0000472 }
473}
474
thsc304f7e2008-01-22 23:25:15 +0000475- (void) setContentDimensions
bellard5b0753e2005-03-01 21:37:28 +0000476{
thsc304f7e2008-01-22 23:25:15 +0000477 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
ths3b46e622007-09-17 08:09:54 +0000478
thsc304f7e2008-01-22 23:25:15 +0000479 if (isFullscreen) {
480 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
481 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100482
483 /* stretches video, but keeps same aspect ratio */
484 if (stretch_video == true) {
485 /* use smallest stretch value - prevents clipping on sides */
486 if (MIN(cdx, cdy) == cdx) {
487 cdy = cdx;
488 } else {
489 cdx = cdy;
490 }
491 } else { /* No stretching */
492 cdx = cdy = 1;
493 }
thsc304f7e2008-01-22 23:25:15 +0000494 cw = screen.width * cdx;
495 ch = screen.height * cdy;
496 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
497 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
498 } else {
499 cx = 0;
500 cy = 0;
501 cw = screen.width;
502 ch = screen.height;
503 cdx = 1.0;
504 cdy = 1.0;
505 }
bellard5b0753e2005-03-01 21:37:28 +0000506}
507
Peter Maydell72a3e312019-02-25 10:24:28 +0000508- (void) switchSurface:(pixman_image_t *)image
thsc304f7e2008-01-22 23:25:15 +0000509{
Gerd Hoffmann5e00d3a2013-03-01 12:52:06 +0100510 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
thsc304f7e2008-01-22 23:25:15 +0000511
Peter Maydell72a3e312019-02-25 10:24:28 +0000512 int w = pixman_image_get_width(image);
513 int h = pixman_image_get_height(image);
514 pixman_format_code_t image_format = pixman_image_get_format(image);
Peter Maydell381600d2014-06-23 10:35:22 +0100515 /* cdx == 0 means this is our very first surface, in which case we need
516 * to recalculate the content dimensions even if it happens to be the size
517 * of the initial empty window.
518 */
519 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
Peter Maydelld3345a02013-12-24 02:51:46 +0000520
521 int oldh = screen.height;
522 if (isResize) {
523 // Resize before we trigger the redraw, or we'll redraw at the wrong size
524 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
525 screen.width = w;
526 screen.height = h;
527 [self setContentDimensions];
528 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
529 }
Peter Maydell8510d912013-03-18 20:28:21 +0000530
thsc304f7e2008-01-22 23:25:15 +0000531 // update screenBuffer
Peter Maydell55888402019-02-25 10:24:33 +0000532 if (dataProviderRef) {
thsc304f7e2008-01-22 23:25:15 +0000533 CGDataProviderRelease(dataProviderRef);
Peter Maydell55888402019-02-25 10:24:33 +0000534 pixman_image_unref(pixman_image);
535 }
thsc304f7e2008-01-22 23:25:15 +0000536
aliguori9794f742009-03-04 19:25:22 +0000537 //sync host window color space with guests
Peter Maydell72a3e312019-02-25 10:24:28 +0000538 screen.bitsPerPixel = PIXMAN_FORMAT_BPP(image_format);
539 screen.bitsPerComponent = DIV_ROUND_UP(screen.bitsPerPixel, 8) * 2;
thsc304f7e2008-01-22 23:25:15 +0000540
Peter Maydell55888402019-02-25 10:24:33 +0000541 pixman_image = image;
Peter Maydell72a3e312019-02-25 10:24:28 +0000542 dataProviderRef = CGDataProviderCreateWithData(NULL, pixman_image_get_data(image), w * 4 * h, NULL);
thsc304f7e2008-01-22 23:25:15 +0000543
544 // update windows
545 if (isFullscreen) {
546 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
Peter Maydelld3345a02013-12-24 02:51:46 +0000547 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
thsc304f7e2008-01-22 23:25:15 +0000548 } else {
549 if (qemu_name)
550 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
Peter Maydelld3345a02013-12-24 02:51:46 +0000551 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
thsc304f7e2008-01-22 23:25:15 +0000552 }
Peter Maydelld3345a02013-12-24 02:51:46 +0000553
554 if (isResize) {
555 [normalWindow center];
556 }
thsc304f7e2008-01-22 23:25:15 +0000557}
558
559- (void) toggleFullScreen:(id)sender
560{
561 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
562
563 if (isFullscreen) { // switch from fullscreen to desktop
564 isFullscreen = FALSE;
565 [self ungrabMouse];
566 [self setContentDimensions];
thsc304f7e2008-01-22 23:25:15 +0000567 if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
568 [self exitFullScreenModeWithOptions:nil];
569 } else {
thsc304f7e2008-01-22 23:25:15 +0000570 [fullScreenWindow close];
571 [normalWindow setContentView: self];
572 [normalWindow makeKeyAndOrderFront: self];
573 [NSMenu setMenuBarVisible:YES];
thsc304f7e2008-01-22 23:25:15 +0000574 }
thsc304f7e2008-01-22 23:25:15 +0000575 } else { // switch from desktop to fullscreen
576 isFullscreen = TRUE;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100577 [normalWindow orderOut: nil]; /* Hide the window */
thsc304f7e2008-01-22 23:25:15 +0000578 [self grabMouse];
579 [self setContentDimensions];
thsc304f7e2008-01-22 23:25:15 +0000580 if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
581 [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
582 [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
583 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
584 nil]];
585 } else {
thsc304f7e2008-01-22 23:25:15 +0000586 [NSMenu setMenuBarVisible:NO];
587 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700588 styleMask:NSWindowStyleMaskBorderless
thsc304f7e2008-01-22 23:25:15 +0000589 backing:NSBackingStoreBuffered
590 defer:NO];
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100591 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
thsc304f7e2008-01-22 23:25:15 +0000592 [fullScreenWindow setHasShadow:NO];
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100593 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
594 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
595 [[fullScreenWindow contentView] addSubview: self];
thsc304f7e2008-01-22 23:25:15 +0000596 [fullScreenWindow makeKeyAndOrderFront:self];
thsc304f7e2008-01-22 23:25:15 +0000597 }
thsc304f7e2008-01-22 23:25:15 +0000598 }
599}
600
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700601- (void) toggleModifier: (int)keycode {
602 // Toggle the stored state.
603 modifiers_state[keycode] = !modifiers_state[keycode];
604 // Send a keyup or keydown depending on the state.
605 qemu_input_event_send_key_qcode(dcl->con, keycode, modifiers_state[keycode]);
606}
607
608- (void) toggleStatefulModifier: (int)keycode {
609 // Toggle the stored state.
610 modifiers_state[keycode] = !modifiers_state[keycode];
611 // Generate keydown and keyup.
612 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
613 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
614}
615
John Arbuckle9c3a4182017-11-07 10:14:14 +0000616// Does the work of sending input to the monitor
617- (void) handleMonitorInput:(NSEvent *)event
618{
619 int keysym = 0;
620 int control_key = 0;
621
622 // if the control key is down
623 if ([event modifierFlags] & NSEventModifierFlagControl) {
624 control_key = 1;
625 }
626
627 /* translates Macintosh keycodes to QEMU's keysym */
628
629 int without_control_translation[] = {
630 [0 ... 0xff] = 0, // invalid key
631
632 [kVK_UpArrow] = QEMU_KEY_UP,
633 [kVK_DownArrow] = QEMU_KEY_DOWN,
634 [kVK_RightArrow] = QEMU_KEY_RIGHT,
635 [kVK_LeftArrow] = QEMU_KEY_LEFT,
636 [kVK_Home] = QEMU_KEY_HOME,
637 [kVK_End] = QEMU_KEY_END,
638 [kVK_PageUp] = QEMU_KEY_PAGEUP,
639 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
640 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
641 [kVK_Delete] = QEMU_KEY_BACKSPACE,
642 };
643
644 int with_control_translation[] = {
645 [0 ... 0xff] = 0, // invalid key
646
647 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
648 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
649 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
650 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
651 [kVK_Home] = QEMU_KEY_CTRL_HOME,
652 [kVK_End] = QEMU_KEY_CTRL_END,
653 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
654 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
655 };
656
657 if (control_key != 0) { /* If the control key is being used */
658 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
659 keysym = with_control_translation[[event keyCode]];
660 }
661 } else {
662 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
663 keysym = without_control_translation[[event keyCode]];
664 }
665 }
666
667 // if not a key that needs translating
668 if (keysym == 0) {
669 NSString *ks = [event characters];
670 if ([ks length] > 0) {
671 keysym = [ks characterAtIndex:0];
672 }
673 }
674
675 if (keysym) {
676 kbd_put_keysym(keysym);
677 }
678}
679
Peter Maydell60105d72019-02-25 10:24:31 +0000680- (bool) handleEvent:(NSEvent *)event
thsc304f7e2008-01-22 23:25:15 +0000681{
Hikaru Nishidadff742a2019-10-15 10:07:34 +0900682 if(!allow_events) {
683 /*
684 * Just let OSX have all events that arrive before
685 * applicationDidFinishLaunching.
686 * This avoids a deadlock on the iothread lock, which cocoa_display_init()
687 * will not drop until after the app_started_sem is posted. (In theory
688 * there should not be any such events, but OSX Catalina now emits some.)
689 */
690 return false;
691 }
Peter Maydell60105d72019-02-25 10:24:31 +0000692 return bool_with_iothread_lock(^{
693 return [self handleEventLocked:event];
Peter Maydell31819e92019-02-25 10:24:27 +0000694 });
695}
thsc304f7e2008-01-22 23:25:15 +0000696
Peter Maydell60105d72019-02-25 10:24:31 +0000697- (bool) handleEventLocked:(NSEvent *)event
Peter Maydell31819e92019-02-25 10:24:27 +0000698{
Peter Maydell60105d72019-02-25 10:24:31 +0000699 /* Return true if we handled the event, false if it should be given to OSX */
Peter Maydell31819e92019-02-25 10:24:27 +0000700 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
thsc304f7e2008-01-22 23:25:15 +0000701 int buttons = 0;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700702 int keycode = 0;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100703 bool mouse_event = false;
John Arbuckle0c6c4392018-07-02 22:00:17 -0400704 static bool switched_to_fullscreen = false;
Chen Zhang2044dff2019-06-04 17:36:00 +0800705 // Location of event in virtual screen coordinates
706 NSPoint p = [self screenLocationOfEvent:event];
thsc304f7e2008-01-22 23:25:15 +0000707
708 switch ([event type]) {
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700709 case NSEventTypeFlagsChanged:
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700710 if ([event keyCode] == 0) {
711 // When the Cocoa keyCode is zero that means keys should be
712 // synthesized based on the values in in the eventModifiers
713 // bitmask.
714
715 if (qemu_console_is_graphic(NULL)) {
John Arbucklee7206242017-06-28 15:37:16 -0400716 NSUInteger modifiers = [event modifierFlags];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700717
718 if (!!(modifiers & NSEventModifierFlagCapsLock) != !!modifiers_state[Q_KEY_CODE_CAPS_LOCK]) {
719 [self toggleStatefulModifier:Q_KEY_CODE_CAPS_LOCK];
720 }
721 if (!!(modifiers & NSEventModifierFlagShift) != !!modifiers_state[Q_KEY_CODE_SHIFT]) {
722 [self toggleModifier:Q_KEY_CODE_SHIFT];
723 }
724 if (!!(modifiers & NSEventModifierFlagControl) != !!modifiers_state[Q_KEY_CODE_CTRL]) {
725 [self toggleModifier:Q_KEY_CODE_CTRL];
726 }
727 if (!!(modifiers & NSEventModifierFlagOption) != !!modifiers_state[Q_KEY_CODE_ALT]) {
728 [self toggleModifier:Q_KEY_CODE_ALT];
729 }
730 if (!!(modifiers & NSEventModifierFlagCommand) != !!modifiers_state[Q_KEY_CODE_META_L]) {
731 [self toggleModifier:Q_KEY_CODE_META_L];
732 }
733 }
734 } else {
735 keycode = cocoa_keycode_to_qemu([event keyCode]);
736 }
Peter Maydell88959192013-12-08 22:59:02 +0000737
John Arbuckleaaac7142016-03-23 14:26:18 +0000738 if ((keycode == Q_KEY_CODE_META_L || keycode == Q_KEY_CODE_META_R)
739 && !isMouseGrabbed) {
Peter Maydell88959192013-12-08 22:59:02 +0000740 /* Don't pass command key changes to guest unless mouse is grabbed */
741 keycode = 0;
742 }
743
thsc304f7e2008-01-22 23:25:15 +0000744 if (keycode) {
John Arbuckleaaac7142016-03-23 14:26:18 +0000745 // emulate caps lock and num lock keydown and keyup
746 if (keycode == Q_KEY_CODE_CAPS_LOCK ||
747 keycode == Q_KEY_CODE_NUM_LOCK) {
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700748 [self toggleStatefulModifier:keycode];
Peter Maydell68c0aa62013-04-17 09:16:35 +0000749 } else if (qemu_console_is_graphic(NULL)) {
John Arbuckle0c6c4392018-07-02 22:00:17 -0400750 if (switched_to_fullscreen) {
751 switched_to_fullscreen = false;
752 } else {
753 [self toggleModifier:keycode];
754 }
thsc304f7e2008-01-22 23:25:15 +0000755 }
756 }
757
thsc304f7e2008-01-22 23:25:15 +0000758 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700759 case NSEventTypeKeyDown:
Peter Maydell88959192013-12-08 22:59:02 +0000760 keycode = cocoa_keycode_to_qemu([event keyCode]);
thsc304f7e2008-01-22 23:25:15 +0000761
Peter Maydell88959192013-12-08 22:59:02 +0000762 // forward command key combos to the host UI unless the mouse is grabbed
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700763 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
John Arbuckle0c6c4392018-07-02 22:00:17 -0400764 /*
765 * Prevent the command key from being stuck down in the guest
766 * when using Command-F to switch to full screen mode.
767 */
768 if (keycode == Q_KEY_CODE_F) {
769 switched_to_fullscreen = true;
770 }
Peter Maydell60105d72019-02-25 10:24:31 +0000771 return false;
thsc304f7e2008-01-22 23:25:15 +0000772 }
773
774 // default
thsc304f7e2008-01-22 23:25:15 +0000775
John Arbuckle5929e362017-11-07 10:14:14 +0000776 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700777 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
John Arbuckle5929e362017-11-07 10:14:14 +0000778 NSString *keychar = [event charactersIgnoringModifiers];
779 if ([keychar length] == 1) {
780 char key = [keychar characterAtIndex:0];
781 switch (key) {
thsc304f7e2008-01-22 23:25:15 +0000782
John Arbuckle5929e362017-11-07 10:14:14 +0000783 // enable graphic console
784 case '1' ... '9':
785 console_select(key - '0' - 1); /* ascii math */
Peter Maydell60105d72019-02-25 10:24:31 +0000786 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000787
788 // release the mouse grab
789 case 'g':
790 [self ungrabMouse];
Peter Maydell60105d72019-02-25 10:24:31 +0000791 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000792 }
thsc304f7e2008-01-22 23:25:15 +0000793 }
Peter Maydellef2088f2017-11-07 10:14:14 +0000794 }
thsc304f7e2008-01-22 23:25:15 +0000795
Peter Maydellef2088f2017-11-07 10:14:14 +0000796 if (qemu_console_is_graphic(NULL)) {
John Arbuckleaaac7142016-03-23 14:26:18 +0000797 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
thsc304f7e2008-01-22 23:25:15 +0000798 } else {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000799 [self handleMonitorInput: event];
thsc304f7e2008-01-22 23:25:15 +0000800 }
801 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700802 case NSEventTypeKeyUp:
thsc304f7e2008-01-22 23:25:15 +0000803 keycode = cocoa_keycode_to_qemu([event keyCode]);
Peter Maydell88959192013-12-08 22:59:02 +0000804
805 // don't pass the guest a spurious key-up if we treated this
806 // command-key combo as a host UI action
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700807 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
Peter Maydell60105d72019-02-25 10:24:31 +0000808 return true;
Peter Maydell88959192013-12-08 22:59:02 +0000809 }
810
Peter Maydell68c0aa62013-04-17 09:16:35 +0000811 if (qemu_console_is_graphic(NULL)) {
John Arbuckleaaac7142016-03-23 14:26:18 +0000812 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
thsc304f7e2008-01-22 23:25:15 +0000813 }
814 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700815 case NSEventTypeMouseMoved:
thsc304f7e2008-01-22 23:25:15 +0000816 if (isAbsoluteEnabled) {
Chen Zhang2044dff2019-06-04 17:36:00 +0800817 // Cursor re-entered into a window might generate events bound to screen coordinates
818 // and `nil` window property, and in full screen mode, current window might not be
819 // key window, where event location alone should suffice.
820 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
Peter Maydellf61c3872014-06-23 10:35:24 +0100821 if (isMouseGrabbed) {
822 [self ungrabMouse];
thsc304f7e2008-01-22 23:25:15 +0000823 }
824 } else {
Peter Maydellf61c3872014-06-23 10:35:24 +0100825 if (!isMouseGrabbed) {
826 [self grabMouse];
thsc304f7e2008-01-22 23:25:15 +0000827 }
828 }
829 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100830 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000831 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700832 case NSEventTypeLeftMouseDown:
833 if ([event modifierFlags] & NSEventModifierFlagCommand) {
thsc304f7e2008-01-22 23:25:15 +0000834 buttons |= MOUSE_EVENT_RBUTTON;
835 } else {
836 buttons |= MOUSE_EVENT_LBUTTON;
837 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100838 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000839 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700840 case NSEventTypeRightMouseDown:
thsc304f7e2008-01-22 23:25:15 +0000841 buttons |= MOUSE_EVENT_RBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100842 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000843 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700844 case NSEventTypeOtherMouseDown:
thsc304f7e2008-01-22 23:25:15 +0000845 buttons |= MOUSE_EVENT_MBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100846 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000847 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700848 case NSEventTypeLeftMouseDragged:
849 if ([event modifierFlags] & NSEventModifierFlagCommand) {
thsc304f7e2008-01-22 23:25:15 +0000850 buttons |= MOUSE_EVENT_RBUTTON;
851 } else {
852 buttons |= MOUSE_EVENT_LBUTTON;
853 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100854 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000855 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700856 case NSEventTypeRightMouseDragged:
thsc304f7e2008-01-22 23:25:15 +0000857 buttons |= MOUSE_EVENT_RBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100858 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000859 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700860 case NSEventTypeOtherMouseDragged:
thsc304f7e2008-01-22 23:25:15 +0000861 buttons |= MOUSE_EVENT_MBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100862 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000863 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700864 case NSEventTypeLeftMouseUp:
Peter Maydellf61c3872014-06-23 10:35:24 +0100865 mouse_event = true;
866 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
Chen Zhang8e23e342019-06-04 17:36:48 +0800867 /*
868 * In fullscreen mode, the window of cocoaView may not be the
869 * key window, therefore the position relative to the virtual
870 * screen alone will be sufficient.
871 */
872 if(isFullscreen || [[self window] isKeyWindow]) {
Programmingkid9e8204b2016-08-15 22:11:06 -0400873 [self grabMouse];
874 }
thsc304f7e2008-01-22 23:25:15 +0000875 }
876 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700877 case NSEventTypeRightMouseUp:
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100878 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000879 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700880 case NSEventTypeOtherMouseUp:
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100881 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000882 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700883 case NSEventTypeScrollWheel:
John Arbuckleae7313e2018-01-08 13:07:07 -0500884 /*
885 * Send wheel events to the guest regardless of window focus.
886 * This is in-line with standard Mac OS X UI behaviour.
887 */
888
John Arbuckledc3c89d2018-07-09 11:02:35 -0400889 /*
890 * When deltaY is zero, it means that this scrolling event was
891 * either horizontal, or so fine that it only appears in
892 * scrollingDeltaY. So we drop the event.
893 */
894 if ([event deltaY] != 0) {
John Arbuckleae7313e2018-01-08 13:07:07 -0500895 /* Determine if this is a scroll up or scroll down event */
John Arbuckledc3c89d2018-07-09 11:02:35 -0400896 buttons = ([event deltaY] > 0) ?
897 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
898 qemu_input_queue_btn(dcl->con, buttons, true);
899 qemu_input_event_sync();
900 qemu_input_queue_btn(dcl->con, buttons, false);
901 qemu_input_event_sync();
902 }
John Arbuckleae7313e2018-01-08 13:07:07 -0500903 /*
904 * Since deltaY also reports scroll wheel events we prevent mouse
905 * movement code from executing.
906 */
907 mouse_event = false;
thsc304f7e2008-01-22 23:25:15 +0000908 break;
909 default:
Peter Maydell60105d72019-02-25 10:24:31 +0000910 return false;
thsc304f7e2008-01-22 23:25:15 +0000911 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100912
913 if (mouse_event) {
Peter Maydell8d3a5d92015-11-26 15:19:28 +0000914 /* Don't send button events to the guest unless we've got a
915 * mouse grab or window focus. If we have neither then this event
916 * is the user clicking on the background window to activate and
917 * bring us to the front, which will be done by the sendEvent
918 * call below. We definitely don't want to pass that click through
919 * to the guest.
920 */
921 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
922 (last_buttons != buttons)) {
Eric Blake7fb1cf12015-11-18 01:52:57 -0700923 static uint32_t bmap[INPUT_BUTTON__MAX] = {
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100924 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
925 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
John Arbuckleae7313e2018-01-08 13:07:07 -0500926 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100927 };
928 qemu_input_update_buttons(dcl->con, bmap, last_buttons, buttons);
929 last_buttons = buttons;
930 }
Peter Maydellf61c3872014-06-23 10:35:24 +0100931 if (isMouseGrabbed) {
932 if (isAbsoluteEnabled) {
933 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
934 * The check on screenContainsPoint is to avoid sending out of range values for
935 * clicks in the titlebar.
936 */
937 if ([self screenContainsPoint:p]) {
Philippe Voinov9cfa7ab2017-05-05 15:39:52 +0200938 qemu_input_queue_abs(dcl->con, INPUT_AXIS_X, p.x, 0, screen.width);
939 qemu_input_queue_abs(dcl->con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
Peter Maydellf61c3872014-06-23 10:35:24 +0100940 }
941 } else {
942 qemu_input_queue_rel(dcl->con, INPUT_AXIS_X, (int)[event deltaX]);
943 qemu_input_queue_rel(dcl->con, INPUT_AXIS_Y, (int)[event deltaY]);
944 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100945 } else {
Peter Maydell60105d72019-02-25 10:24:31 +0000946 return false;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100947 }
948 qemu_input_event_sync();
949 }
Peter Maydell60105d72019-02-25 10:24:31 +0000950 return true;
thsc304f7e2008-01-22 23:25:15 +0000951}
952
953- (void) grabMouse
954{
955 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
956
957 if (!isFullscreen) {
958 if (qemu_name)
John Arbuckle5929e362017-11-07 10:14:14 +0000959 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
thsc304f7e2008-01-22 23:25:15 +0000960 else
John Arbuckle5929e362017-11-07 10:14:14 +0000961 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
thsc304f7e2008-01-22 23:25:15 +0000962 }
Peter Maydell13aefd32014-06-23 10:35:25 +0100963 [self hideCursor];
Peter Maydellf61c3872014-06-23 10:35:24 +0100964 if (!isAbsoluteEnabled) {
965 isMouseDeassociated = TRUE;
966 CGAssociateMouseAndMouseCursorPosition(FALSE);
967 }
Peter Maydell49b9bd42013-12-08 22:59:03 +0000968 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
thsc304f7e2008-01-22 23:25:15 +0000969}
970
971- (void) ungrabMouse
972{
973 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
974
975 if (!isFullscreen) {
976 if (qemu_name)
977 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
978 else
979 [normalWindow setTitle:@"QEMU"];
980 }
Peter Maydell13aefd32014-06-23 10:35:25 +0100981 [self unhideCursor];
Peter Maydellf61c3872014-06-23 10:35:24 +0100982 if (isMouseDeassociated) {
983 CGAssociateMouseAndMouseCursorPosition(TRUE);
984 isMouseDeassociated = FALSE;
985 }
Peter Maydell49b9bd42013-12-08 22:59:03 +0000986 isMouseGrabbed = FALSE;
thsc304f7e2008-01-22 23:25:15 +0000987}
988
989- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
Peter Maydell49b9bd42013-12-08 22:59:03 +0000990- (BOOL) isMouseGrabbed {return isMouseGrabbed;}
thsc304f7e2008-01-22 23:25:15 +0000991- (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
Peter Maydellf61c3872014-06-23 10:35:24 +0100992- (BOOL) isMouseDeassociated {return isMouseDeassociated;}
thsc304f7e2008-01-22 23:25:15 +0000993- (float) cdx {return cdx;}
994- (float) cdy {return cdy;}
995- (QEMUScreen) gscreen {return screen;}
John Arbuckle3b178b72015-09-25 23:14:00 +0100996
997/*
998 * Makes the target think all down keys are being released.
999 * This prevents a stuck key problem, since we will not see
1000 * key up events for those keys after we have lost focus.
1001 */
1002- (void) raiseAllKeys
1003{
John Arbuckle3b178b72015-09-25 23:14:00 +01001004 const int max_index = ARRAY_SIZE(modifiers_state);
1005
Peter Maydell31819e92019-02-25 10:24:27 +00001006 with_iothread_lock(^{
1007 int index;
1008
1009 for (index = 0; index < max_index; index++) {
1010 if (modifiers_state[index]) {
1011 modifiers_state[index] = 0;
1012 qemu_input_event_send_key_qcode(dcl->con, index, false);
1013 }
1014 }
1015 });
John Arbuckle3b178b72015-09-25 23:14:00 +01001016}
bellard5b0753e2005-03-01 21:37:28 +00001017@end
1018
1019
thsc304f7e2008-01-22 23:25:15 +00001020
bellard5b0753e2005-03-01 21:37:28 +00001021/*
1022 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +00001023 QemuCocoaAppController
bellard5b0753e2005-03-01 21:37:28 +00001024 ------------------------------------------------------
1025*/
thsc304f7e2008-01-22 23:25:15 +00001026@interface QemuCocoaAppController : NSObject
John Arbuckled9bc14f2015-09-25 23:13:59 +01001027 <NSWindowDelegate, NSApplicationDelegate>
bellard5b0753e2005-03-01 21:37:28 +00001028{
1029}
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001030- (void)doToggleFullScreen:(id)sender;
thsc304f7e2008-01-22 23:25:15 +00001031- (void)toggleFullScreen:(id)sender;
1032- (void)showQEMUDoc:(id)sender;
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001033- (void)zoomToFit:(id) sender;
Programmingkidb4c6a112015-05-19 09:11:18 +01001034- (void)displayConsole:(id)sender;
John Arbuckle8524f1c2015-06-19 10:53:27 +01001035- (void)pauseQEMU:(id)sender;
1036- (void)resumeQEMU:(id)sender;
1037- (void)displayPause;
1038- (void)removePause;
John Arbuckle27074612015-06-19 10:53:27 +01001039- (void)restartQEMU:(id)sender;
1040- (void)powerDownQEMU:(id)sender;
John Arbuckle693a3e02015-06-19 10:53:27 +01001041- (void)ejectDeviceMedia:(id)sender;
1042- (void)changeDeviceMedia:(id)sender;
John Arbuckled9bc14f2015-09-25 23:13:59 +01001043- (BOOL)verifyQuit;
John Arbucklef4747902016-03-23 14:26:17 +00001044- (void)openDocumentation:(NSString *)filename;
Programmingkid9e8204b2016-08-15 22:11:06 -04001045- (IBAction) do_about_menu_item: (id) sender;
1046- (void)make_about_window;
John Arbucklee47ec1a2017-06-13 23:17:38 -04001047- (void)adjustSpeed:(id)sender;
bellard5b0753e2005-03-01 21:37:28 +00001048@end
1049
thsc304f7e2008-01-22 23:25:15 +00001050@implementation QemuCocoaAppController
1051- (id) init
1052{
1053 COCOA_DEBUG("QemuCocoaAppController: init\n");
1054
1055 self = [super init];
1056 if (self) {
1057
1058 // create a view and add it to the window
1059 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1060 if(!cocoaView) {
1061 fprintf(stderr, "(cocoa) can't create a view\n");
1062 exit(1);
1063 }
1064
1065 // create a window
1066 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001067 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
thsc304f7e2008-01-22 23:25:15 +00001068 backing:NSBackingStoreBuffered defer:NO];
1069 if(!normalWindow) {
1070 fprintf(stderr, "(cocoa) can't create window\n");
1071 exit(1);
1072 }
1073 [normalWindow setAcceptsMouseMovedEvents:YES];
John Arbucklea1dbc052015-10-13 21:51:18 +01001074 [normalWindow setTitle:@"QEMU"];
thsc304f7e2008-01-22 23:25:15 +00001075 [normalWindow setContentView:cocoaView];
1076 [normalWindow makeKeyAndOrderFront:self];
Peter Maydell49060c22013-12-24 11:54:12 +00001077 [normalWindow center];
John Arbuckled9bc14f2015-09-25 23:13:59 +01001078 [normalWindow setDelegate: self];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001079 stretch_video = false;
John Arbuckle8524f1c2015-06-19 10:53:27 +01001080
1081 /* Used for displaying pause on the screen */
1082 pauseLabel = [NSTextField new];
1083 [pauseLabel setBezeled:YES];
1084 [pauseLabel setDrawsBackground:YES];
1085 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1086 [pauseLabel setEditable:NO];
1087 [pauseLabel setSelectable:NO];
1088 [pauseLabel setStringValue: @"Paused"];
1089 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1090 [pauseLabel setTextColor: [NSColor blackColor]];
1091 [pauseLabel sizeToFit];
John Arbuckle693a3e02015-06-19 10:53:27 +01001092
1093 // set the supported image file types that can be opened
1094 supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
John Arbuckle9d227f12016-03-30 12:37:11 -04001095 @"qcow", @"qcow2", @"cloop", @"vmdk", @"cdr",
Programmingkid5f26fcf2016-12-30 15:42:21 -05001096 @"toast", nil];
Programmingkid9e8204b2016-08-15 22:11:06 -04001097 [self make_about_window];
thsc304f7e2008-01-22 23:25:15 +00001098 }
1099 return self;
1100}
1101
1102- (void) dealloc
1103{
1104 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1105
1106 if (cocoaView)
1107 [cocoaView release];
1108 [super dealloc];
1109}
1110
bellard5b0753e2005-03-01 21:37:28 +00001111- (void)applicationDidFinishLaunching: (NSNotification *) note
1112{
thsc304f7e2008-01-22 23:25:15 +00001113 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
Hikaru Nishidadff742a2019-10-15 10:07:34 +09001114 allow_events = true;
Peter Maydell55888402019-02-25 10:24:33 +00001115 /* Tell cocoa_display_init to proceed */
1116 qemu_sem_post(&app_started_sem);
bellard5b0753e2005-03-01 21:37:28 +00001117}
1118
1119- (void)applicationWillTerminate:(NSNotification *)aNotification
1120{
thsc304f7e2008-01-22 23:25:15 +00001121 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1122
Eric Blakecf83f142017-05-15 16:41:13 -05001123 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
bellard5b0753e2005-03-01 21:37:28 +00001124 exit(0);
1125}
1126
Andreas Färber41ea49b2009-12-14 22:13:27 +01001127- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1128{
1129 return YES;
1130}
1131
John Arbuckled9bc14f2015-09-25 23:13:59 +01001132- (NSApplicationTerminateReply)applicationShouldTerminate:
1133 (NSApplication *)sender
1134{
1135 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1136 return [self verifyQuit];
1137}
1138
1139/* Called when the user clicks on a window's close button */
1140- (BOOL)windowShouldClose:(id)sender
1141{
1142 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1143 [NSApp terminate: sender];
1144 /* If the user allows the application to quit then the call to
1145 * NSApp terminate will never return. If we get here then the user
1146 * cancelled the quit, so we should return NO to not permit the
1147 * closing of this window.
1148 */
1149 return NO;
1150}
1151
John Arbuckle3b178b72015-09-25 23:14:00 +01001152/* Called when QEMU goes into the background */
1153- (void) applicationWillResignActive: (NSNotification *)aNotification
1154{
1155 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1156 [cocoaView raiseAllKeys];
1157}
1158
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001159/* We abstract the method called by the Enter Fullscreen menu item
1160 * because Mac OS 10.7 and higher disables it. This is because of the
1161 * menu item's old selector's name toggleFullScreen:
1162 */
1163- (void) doToggleFullScreen:(id)sender
1164{
1165 [self toggleFullScreen:(id)sender];
1166}
1167
thsc304f7e2008-01-22 23:25:15 +00001168- (void)toggleFullScreen:(id)sender
bellard5b0753e2005-03-01 21:37:28 +00001169{
thsc304f7e2008-01-22 23:25:15 +00001170 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1171
1172 [cocoaView toggleFullScreen:sender];
1173}
1174
John Arbucklef4747902016-03-23 14:26:17 +00001175/* Tries to find then open the specified filename */
1176- (void) openDocumentation: (NSString *) filename
1177{
1178 /* Where to look for local files */
Roman Bolshakov8d6fda82021-01-09 00:38:15 +03001179 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
John Arbucklef4747902016-03-23 14:26:17 +00001180 NSString *full_file_path;
Roman Bolshakov1ff5a062021-01-02 18:07:21 +03001181 NSURL *full_file_url;
John Arbucklef4747902016-03-23 14:26:17 +00001182
1183 /* iterate thru the possible paths until the file is found */
1184 int index;
1185 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1186 full_file_path = [[NSBundle mainBundle] executablePath];
1187 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1188 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1189 path_array[index], filename];
Roman Bolshakov1ff5a062021-01-02 18:07:21 +03001190 full_file_url = [NSURL fileURLWithPath: full_file_path
1191 isDirectory: false];
1192 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
John Arbucklef4747902016-03-23 14:26:17 +00001193 return;
1194 }
1195 }
1196
1197 /* If none of the paths opened a file */
1198 NSBeep();
1199 QEMU_Alert(@"Failed to open file");
1200}
1201
thsc304f7e2008-01-22 23:25:15 +00001202- (void)showQEMUDoc:(id)sender
1203{
1204 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1205
Peter Maydell1879f242020-02-28 15:36:16 +00001206 [self openDocumentation: @"index.html"];
thsc304f7e2008-01-22 23:25:15 +00001207}
1208
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001209/* Stretches video to fit host monitor size */
1210- (void)zoomToFit:(id) sender
1211{
1212 stretch_video = !stretch_video;
1213 if (stretch_video == true) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001214 [sender setState: NSControlStateValueOn];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001215 } else {
Brendan Shanks5e246002019-01-31 23:12:25 -08001216 [sender setState: NSControlStateValueOff];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001217 }
1218}
bellard5b0753e2005-03-01 21:37:28 +00001219
Programmingkidb4c6a112015-05-19 09:11:18 +01001220/* Displays the console on the screen */
1221- (void)displayConsole:(id)sender
1222{
1223 console_select([sender tag]);
1224}
John Arbuckle8524f1c2015-06-19 10:53:27 +01001225
1226/* Pause the guest */
1227- (void)pauseQEMU:(id)sender
1228{
Peter Maydell31819e92019-02-25 10:24:27 +00001229 with_iothread_lock(^{
1230 qmp_stop(NULL);
1231 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001232 [sender setEnabled: NO];
1233 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1234 [self displayPause];
1235}
1236
1237/* Resume running the guest operating system */
1238- (void)resumeQEMU:(id) sender
1239{
Peter Maydell31819e92019-02-25 10:24:27 +00001240 with_iothread_lock(^{
1241 qmp_cont(NULL);
1242 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001243 [sender setEnabled: NO];
1244 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1245 [self removePause];
1246}
1247
1248/* Displays the word pause on the screen */
1249- (void)displayPause
1250{
1251 /* Coordinates have to be calculated each time because the window can change its size */
1252 int xCoord, yCoord, width, height;
1253 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1254 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1255 width = [pauseLabel frame].size.width;
1256 height = [pauseLabel frame].size.height;
1257 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1258 [cocoaView addSubview: pauseLabel];
1259}
1260
1261/* Removes the word pause from the screen */
1262- (void)removePause
1263{
1264 [pauseLabel removeFromSuperview];
1265}
1266
John Arbuckle27074612015-06-19 10:53:27 +01001267/* Restarts QEMU */
1268- (void)restartQEMU:(id)sender
1269{
Peter Maydell31819e92019-02-25 10:24:27 +00001270 with_iothread_lock(^{
1271 qmp_system_reset(NULL);
1272 });
John Arbuckle27074612015-06-19 10:53:27 +01001273}
1274
1275/* Powers down QEMU */
1276- (void)powerDownQEMU:(id)sender
1277{
Peter Maydell31819e92019-02-25 10:24:27 +00001278 with_iothread_lock(^{
1279 qmp_system_powerdown(NULL);
1280 });
John Arbuckle27074612015-06-19 10:53:27 +01001281}
1282
John Arbuckle693a3e02015-06-19 10:53:27 +01001283/* Ejects the media.
1284 * Uses sender's tag to figure out the device to eject.
1285 */
1286- (void)ejectDeviceMedia:(id)sender
1287{
1288 NSString * drive;
1289 drive = [sender representedObject];
1290 if(drive == nil) {
1291 NSBeep();
1292 QEMU_Alert(@"Failed to find drive to eject!");
1293 return;
1294 }
1295
Peter Maydell31819e92019-02-25 10:24:27 +00001296 __block Error *err = NULL;
1297 with_iothread_lock(^{
1298 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1299 false, NULL, false, false, &err);
1300 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001301 handleAnyDeviceErrors(err);
1302}
1303
1304/* Displays a dialog box asking the user to select an image file to load.
1305 * Uses sender's represented object value to figure out which drive to use.
1306 */
1307- (void)changeDeviceMedia:(id)sender
1308{
1309 /* Find the drive name */
1310 NSString * drive;
1311 drive = [sender representedObject];
1312 if(drive == nil) {
1313 NSBeep();
1314 QEMU_Alert(@"Could not find drive!");
1315 return;
1316 }
1317
1318 /* Display the file open dialog */
1319 NSOpenPanel * openPanel;
1320 openPanel = [NSOpenPanel openPanel];
1321 [openPanel setCanChooseFiles: YES];
1322 [openPanel setAllowsMultipleSelection: NO];
1323 [openPanel setAllowedFileTypes: supportedImageFileTypes];
Peter Maydellb5725382018-05-29 19:15:23 +01001324 if([openPanel runModal] == NSModalResponseOK) {
John Arbuckle693a3e02015-06-19 10:53:27 +01001325 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1326 if(file == nil) {
1327 NSBeep();
1328 QEMU_Alert(@"Failed to convert URL to file path!");
1329 return;
1330 }
1331
Peter Maydell31819e92019-02-25 10:24:27 +00001332 __block Error *err = NULL;
1333 with_iothread_lock(^{
1334 qmp_blockdev_change_medium(true,
1335 [drive cStringUsingEncoding:
1336 NSASCIIStringEncoding],
1337 false, NULL,
1338 [file cStringUsingEncoding:
1339 NSASCIIStringEncoding],
1340 true, "raw",
1341 false, 0,
1342 &err);
1343 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001344 handleAnyDeviceErrors(err);
1345 }
1346}
1347
John Arbuckled9bc14f2015-09-25 23:13:59 +01001348/* Verifies if the user really wants to quit */
1349- (BOOL)verifyQuit
1350{
1351 NSAlert *alert = [NSAlert new];
1352 [alert autorelease];
1353 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1354 [alert addButtonWithTitle: @"Cancel"];
1355 [alert addButtonWithTitle: @"Quit"];
1356 if([alert runModal] == NSAlertSecondButtonReturn) {
1357 return YES;
1358 } else {
1359 return NO;
1360 }
1361}
1362
Programmingkid9e8204b2016-08-15 22:11:06 -04001363/* The action method for the About menu item */
1364- (IBAction) do_about_menu_item: (id) sender
1365{
1366 [about_window makeKeyAndOrderFront: nil];
1367}
1368
1369/* Create and display the about dialog */
1370- (void)make_about_window
1371{
1372 /* Make the window */
1373 int x = 0, y = 0, about_width = 400, about_height = 200;
1374 NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1375 about_window = [[NSWindow alloc] initWithContentRect:window_rect
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001376 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1377 NSWindowStyleMaskMiniaturizable
Programmingkid9e8204b2016-08-15 22:11:06 -04001378 backing:NSBackingStoreBuffered
1379 defer:NO];
1380 [about_window setTitle: @"About"];
1381 [about_window setReleasedWhenClosed: NO];
1382 [about_window center];
1383 NSView *superView = [about_window contentView];
1384
1385 /* Create the dimensions of the picture */
1386 int picture_width = 80, picture_height = 80;
1387 x = (about_width - picture_width)/2;
1388 y = about_height - picture_height - 10;
1389 NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1390
1391 /* Get the path to the QEMU binary */
1392 NSString *binary_name = [NSString stringWithCString: gArgv[0]
1393 encoding: NSASCIIStringEncoding];
1394 binary_name = [binary_name lastPathComponent];
1395 NSString *program_path = [[NSString alloc] initWithFormat: @"%@/%@",
1396 [[NSBundle mainBundle] bundlePath], binary_name];
1397
1398 /* Make the picture of QEMU */
1399 NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1400 picture_rect];
1401 NSImage *qemu_image = [[NSWorkspace sharedWorkspace] iconForFile:
1402 program_path];
1403 [picture_view setImage: qemu_image];
1404 [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1405 [superView addSubview: picture_view];
1406
1407 /* Make the name label */
1408 x = 0;
1409 y = y - 25;
1410 int name_width = about_width, name_height = 20;
1411 NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1412 NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1413 [name_label setEditable: NO];
1414 [name_label setBezeled: NO];
1415 [name_label setDrawsBackground: NO];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001416 [name_label setAlignment: NSTextAlignmentCenter];
Programmingkid9e8204b2016-08-15 22:11:06 -04001417 NSString *qemu_name = [[NSString alloc] initWithCString: gArgv[0]
1418 encoding: NSASCIIStringEncoding];
1419 qemu_name = [qemu_name lastPathComponent];
1420 [name_label setStringValue: qemu_name];
1421 [superView addSubview: name_label];
1422
1423 /* Set the version label's attributes */
1424 x = 0;
1425 y = 50;
1426 int version_width = about_width, version_height = 20;
1427 NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1428 NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1429 version_rect];
1430 [version_label setEditable: NO];
1431 [version_label setBezeled: NO];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001432 [version_label setAlignment: NSTextAlignmentCenter];
Programmingkid9e8204b2016-08-15 22:11:06 -04001433 [version_label setDrawsBackground: NO];
1434
1435 /* Create the version string*/
1436 NSString *version_string;
1437 version_string = [[NSString alloc] initWithFormat:
Thomas Huth7e563bf2018-02-15 12:06:47 +01001438 @"QEMU emulator version %s", QEMU_FULL_VERSION];
Programmingkid9e8204b2016-08-15 22:11:06 -04001439 [version_label setStringValue: version_string];
1440 [superView addSubview: version_label];
1441
1442 /* Make copyright label */
1443 x = 0;
1444 y = 35;
1445 int copyright_width = about_width, copyright_height = 20;
1446 NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1447 NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1448 copyright_rect];
1449 [copyright_label setEditable: NO];
1450 [copyright_label setBezeled: NO];
1451 [copyright_label setDrawsBackground: NO];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001452 [copyright_label setAlignment: NSTextAlignmentCenter];
Programmingkid9e8204b2016-08-15 22:11:06 -04001453 [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1454 QEMU_COPYRIGHT]];
1455 [superView addSubview: copyright_label];
1456}
1457
John Arbucklee47ec1a2017-06-13 23:17:38 -04001458/* Used by the Speed menu items */
1459- (void)adjustSpeed:(id)sender
1460{
1461 int throttle_pct; /* throttle percentage */
1462 NSMenu *menu;
1463
1464 menu = [sender menu];
1465 if (menu != nil)
1466 {
1467 /* Unselect the currently selected item */
1468 for (NSMenuItem *item in [menu itemArray]) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001469 if (item.state == NSControlStateValueOn) {
1470 [item setState: NSControlStateValueOff];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001471 break;
1472 }
1473 }
1474 }
1475
1476 // check the menu item
Brendan Shanks5e246002019-01-31 23:12:25 -08001477 [sender setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001478
1479 // get the throttle percentage
1480 throttle_pct = [sender tag];
1481
Peter Maydell31819e92019-02-25 10:24:27 +00001482 with_iothread_lock(^{
1483 cpu_throttle_set(throttle_pct);
1484 });
John Arbucklee47ec1a2017-06-13 23:17:38 -04001485 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1486}
1487
Programmingkidb4c6a112015-05-19 09:11:18 +01001488@end
bellard5b0753e2005-03-01 21:37:28 +00001489
Peter Maydell61a2ed42019-02-25 10:24:32 +00001490@interface QemuApplication : NSApplication
1491@end
1492
1493@implementation QemuApplication
1494- (void)sendEvent:(NSEvent *)event
1495{
1496 COCOA_DEBUG("QemuApplication: sendEvent\n");
Peter Maydell55888402019-02-25 10:24:33 +00001497 if (![cocoaView handleEvent:event]) {
1498 [super sendEvent: event];
1499 }
Peter Maydell61a2ed42019-02-25 10:24:32 +00001500}
1501@end
1502
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001503static void create_initial_menus(void)
1504{
thsc304f7e2008-01-22 23:25:15 +00001505 // Add menus
1506 NSMenu *menu;
1507 NSMenuItem *menuItem;
1508
bellard5b0753e2005-03-01 21:37:28 +00001509 [NSApp setMainMenu:[[NSMenu alloc] init]];
bellard5b0753e2005-03-01 21:37:28 +00001510
thsc304f7e2008-01-22 23:25:15 +00001511 // Application menu
1512 menu = [[NSMenu alloc] initWithTitle:@""];
Programmingkid9e8204b2016-08-15 22:11:06 -04001513 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
thsc304f7e2008-01-22 23:25:15 +00001514 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1515 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1516 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001517 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
thsc304f7e2008-01-22 23:25:15 +00001518 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1519 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1520 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1521 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1522 [menuItem setSubmenu:menu];
1523 [[NSApp mainMenu] addItem:menuItem];
1524 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
ths3b46e622007-09-17 08:09:54 +00001525
John Arbuckle8524f1c2015-06-19 10:53:27 +01001526 // Machine menu
1527 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1528 [menu setAutoenablesItems: NO];
1529 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1530 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1531 [menu addItem: menuItem];
1532 [menuItem setEnabled: NO];
John Arbuckle27074612015-06-19 10:53:27 +01001533 [menu addItem: [NSMenuItem separatorItem]];
1534 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1535 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
John Arbuckle8524f1c2015-06-19 10:53:27 +01001536 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1537 [menuItem setSubmenu:menu];
1538 [[NSApp mainMenu] addItem:menuItem];
1539
thsc304f7e2008-01-22 23:25:15 +00001540 // View menu
1541 menu = [[NSMenu alloc] initWithTitle:@"View"];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001542 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1543 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
thsc304f7e2008-01-22 23:25:15 +00001544 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1545 [menuItem setSubmenu:menu];
1546 [[NSApp mainMenu] addItem:menuItem];
1547
John Arbucklee47ec1a2017-06-13 23:17:38 -04001548 // Speed menu
1549 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1550
1551 // Add the rest of the Speed menu items
1552 int p, percentage, throttle_pct;
1553 for (p = 10; p >= 0; p--)
1554 {
1555 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1556
1557 menuItem = [[[NSMenuItem alloc]
1558 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1559
1560 if (percentage == 100) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001561 [menuItem setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001562 }
1563
1564 /* Calculate the throttle percentage */
1565 throttle_pct = -1 * percentage + 100;
1566
1567 [menuItem setTag: throttle_pct];
1568 [menu addItem: menuItem];
1569 }
1570 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1571 [menuItem setSubmenu:menu];
1572 [[NSApp mainMenu] addItem:menuItem];
1573
thsc304f7e2008-01-22 23:25:15 +00001574 // Window menu
1575 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1576 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1577 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1578 [menuItem setSubmenu:menu];
1579 [[NSApp mainMenu] addItem:menuItem];
1580 [NSApp setWindowsMenu:menu];
1581
1582 // Help menu
1583 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1584 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
thsc304f7e2008-01-22 23:25:15 +00001585 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1586 [menuItem setSubmenu:menu];
1587 [[NSApp mainMenu] addItem:menuItem];
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001588}
1589
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001590/* Returns a name for a given console */
1591static NSString * getConsoleName(QemuConsole * console)
1592{
1593 return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1594}
1595
1596/* Add an entry to the View menu for each console */
1597static void add_console_menu_entries(void)
1598{
1599 NSMenu *menu;
1600 NSMenuItem *menuItem;
1601 int index = 0;
1602
1603 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1604
1605 [menu addItem:[NSMenuItem separatorItem]];
1606
1607 while (qemu_console_lookup_by_index(index) != NULL) {
1608 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1609 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1610 [menuItem setTag: index];
1611 [menu addItem: menuItem];
1612 index++;
1613 }
1614}
1615
1616/* Make menu items for all removable devices.
1617 * Each device is given an 'Eject' and 'Change' menu item.
1618 */
1619static void addRemovableDevicesMenuItems(void)
1620{
1621 NSMenu *menu;
1622 NSMenuItem *menuItem;
1623 BlockInfoList *currentDevice, *pointerToFree;
1624 NSString *deviceName;
1625
1626 currentDevice = qmp_query_block(NULL);
1627 pointerToFree = currentDevice;
1628 if(currentDevice == NULL) {
1629 NSBeep();
1630 QEMU_Alert(@"Failed to query for block devices!");
1631 return;
1632 }
1633
1634 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1635
1636 // Add a separator between related groups of menu items
1637 [menu addItem:[NSMenuItem separatorItem]];
1638
1639 // Set the attributes to the "Removable Media" menu item
1640 NSString *titleString = @"Removable Media";
1641 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1642 NSColor *newColor = [NSColor blackColor];
1643 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1644 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1645 traits:NSBoldFontMask|NSItalicFontMask
1646 weight:0
1647 size:14];
1648 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1649 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1650 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1651
1652 // Add the "Removable Media" menu item
1653 menuItem = [NSMenuItem new];
1654 [menuItem setAttributedTitle: attString];
1655 [menuItem setEnabled: NO];
1656 [menu addItem: menuItem];
1657
1658 /* Loop through all the block devices in the emulator */
1659 while (currentDevice) {
1660 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1661
1662 if(currentDevice->value->removable) {
1663 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1664 action: @selector(changeDeviceMedia:)
1665 keyEquivalent: @""];
1666 [menu addItem: menuItem];
1667 [menuItem setRepresentedObject: deviceName];
1668 [menuItem autorelease];
1669
1670 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1671 action: @selector(ejectDeviceMedia:)
1672 keyEquivalent: @""];
1673 [menu addItem: menuItem];
1674 [menuItem setRepresentedObject: deviceName];
1675 [menuItem autorelease];
1676 }
1677 currentDevice = currentDevice->next;
1678 }
1679 qapi_free_BlockInfoList(pointerToFree);
1680}
1681
Peter Maydell55888402019-02-25 10:24:33 +00001682/*
1683 * The startup process for the OSX/Cocoa UI is complicated, because
1684 * OSX insists that the UI runs on the initial main thread, and so we
1685 * need to start a second thread which runs the vl.c qemu_main():
1686 *
1687 * Initial thread: 2nd thread:
1688 * in main():
1689 * create qemu-main thread
1690 * wait on display_init semaphore
1691 * call qemu_main()
1692 * ...
1693 * in cocoa_display_init():
1694 * post the display_init semaphore
1695 * wait on app_started semaphore
1696 * create application, menus, etc
1697 * enter OSX run loop
1698 * in applicationDidFinishLaunching:
1699 * post app_started semaphore
1700 * tell main thread to fullscreen if needed
1701 * [...]
1702 * run qemu main-loop
1703 *
1704 * We do this in two stages so that we don't do the creation of the
1705 * GUI application menus and so on for command line options like --help
1706 * where we want to just print text to stdout and exit immediately.
1707 */
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001708
Peter Maydell55888402019-02-25 10:24:33 +00001709static void *call_qemu_main(void *opaque)
1710{
1711 int status;
1712
1713 COCOA_DEBUG("Second thread: calling qemu_main()\n");
1714 status = qemu_main(gArgc, gArgv, *_NSGetEnviron());
1715 COCOA_DEBUG("Second thread: qemu_main() returned, exiting\n");
1716 exit(status);
1717}
1718
1719int main (int argc, const char * argv[]) {
1720 QemuThread thread;
1721
1722 COCOA_DEBUG("Entered main()\n");
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001723 gArgc = argc;
1724 gArgv = (char **)argv;
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001725
Peter Maydell55888402019-02-25 10:24:33 +00001726 qemu_sem_init(&display_init_sem, 0);
1727 qemu_sem_init(&app_started_sem, 0);
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001728
Peter Maydell55888402019-02-25 10:24:33 +00001729 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1730 NULL, QEMU_THREAD_DETACHED);
1731
1732 COCOA_DEBUG("Main thread: waiting for display_init_sem\n");
1733 qemu_sem_wait(&display_init_sem);
1734 COCOA_DEBUG("Main thread: initializing app\n");
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001735
1736 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1737
1738 // Pull this console process up to being a fully-fledged graphical
1739 // app with a menubar and Dock icon
1740 ProcessSerialNumber psn = { 0, kCurrentProcess };
1741 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1742
Peter Maydell61a2ed42019-02-25 10:24:32 +00001743 [QemuApplication sharedApplication];
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001744
1745 create_initial_menus();
thsc304f7e2008-01-22 23:25:15 +00001746
Peter Maydell55888402019-02-25 10:24:33 +00001747 /*
1748 * Create the menu entries which depend on QEMU state (for consoles
1749 * and removeable devices). These make calls back into QEMU functions,
1750 * which is OK because at this point we know that the second thread
1751 * holds the iothread lock and is synchronously waiting for us to
1752 * finish.
1753 */
1754 add_console_menu_entries();
1755 addRemovableDevicesMenuItems();
1756
thsc304f7e2008-01-22 23:25:15 +00001757 // Create an Application controller
1758 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1759 [NSApp setDelegate:appController];
1760
1761 // Start the main event loop
Peter Maydell55888402019-02-25 10:24:33 +00001762 COCOA_DEBUG("Main thread: entering OSX run loop\n");
bellard5b0753e2005-03-01 21:37:28 +00001763 [NSApp run];
Peter Maydell55888402019-02-25 10:24:33 +00001764 COCOA_DEBUG("Main thread: left OSX run loop, exiting\n");
ths3b46e622007-09-17 08:09:54 +00001765
thsc304f7e2008-01-22 23:25:15 +00001766 [appController release];
bellard5b0753e2005-03-01 21:37:28 +00001767 [pool release];
bellardcae41b12006-05-22 21:25:04 +00001768
bellard5b0753e2005-03-01 21:37:28 +00001769 return 0;
1770}
thsc304f7e2008-01-22 23:25:15 +00001771
1772
1773
1774#pragma mark qemu
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001775static void cocoa_update(DisplayChangeListener *dcl,
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001776 int x, int y, int w, int h)
thsc304f7e2008-01-22 23:25:15 +00001777{
Peter Maydell6e657e62013-04-22 10:29:46 +00001778 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1779
thsc304f7e2008-01-22 23:25:15 +00001780 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1781
Peter Maydell55888402019-02-25 10:24:33 +00001782 dispatch_async(dispatch_get_main_queue(), ^{
1783 NSRect rect;
1784 if ([cocoaView cdx] == 1.0) {
1785 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1786 } else {
1787 rect = NSMakeRect(
1788 x * [cocoaView cdx],
1789 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1790 w * [cocoaView cdx],
1791 h * [cocoaView cdy]);
1792 }
1793 [cocoaView setNeedsDisplayInRect:rect];
1794 });
Peter Maydell6e657e62013-04-22 10:29:46 +00001795
1796 [pool release];
thsc304f7e2008-01-22 23:25:15 +00001797}
1798
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01001799static void cocoa_switch(DisplayChangeListener *dcl,
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01001800 DisplaySurface *surface)
thsc304f7e2008-01-22 23:25:15 +00001801{
Peter Maydell6e657e62013-04-22 10:29:46 +00001802 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Peter Maydell55888402019-02-25 10:24:33 +00001803 pixman_image_t *image = surface->image;
thsc304f7e2008-01-22 23:25:15 +00001804
Peter Maydell6e657e62013-04-22 10:29:46 +00001805 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
Peter Maydell55888402019-02-25 10:24:33 +00001806
1807 // The DisplaySurface will be freed as soon as this callback returns.
1808 // We take a reference to the underlying pixman image here so it does
1809 // not disappear from under our feet; the switchSurface method will
1810 // deref the old image when it is done with it.
1811 pixman_image_ref(image);
1812
1813 dispatch_async(dispatch_get_main_queue(), ^{
1814 [cocoaView switchSurface:image];
1815 });
Peter Maydell6e657e62013-04-22 10:29:46 +00001816 [pool release];
thsc304f7e2008-01-22 23:25:15 +00001817}
1818
Gerd Hoffmannbc2ed972013-03-01 13:03:04 +01001819static void cocoa_refresh(DisplayChangeListener *dcl)
thsc304f7e2008-01-22 23:25:15 +00001820{
Peter Maydell6e657e62013-04-22 10:29:46 +00001821 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1822
thsc304f7e2008-01-22 23:25:15 +00001823 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
John Arbuckle468a8952015-10-13 21:51:18 +01001824 graphic_hw_update(NULL);
thsc304f7e2008-01-22 23:25:15 +00001825
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001826 if (qemu_input_is_absolute()) {
Peter Maydell55888402019-02-25 10:24:33 +00001827 dispatch_async(dispatch_get_main_queue(), ^{
1828 if (![cocoaView isAbsoluteEnabled]) {
1829 if ([cocoaView isMouseGrabbed]) {
1830 [cocoaView ungrabMouse];
1831 }
thsc304f7e2008-01-22 23:25:15 +00001832 }
Peter Maydell55888402019-02-25 10:24:33 +00001833 [cocoaView setAbsoluteEnabled:YES];
1834 });
thsc304f7e2008-01-22 23:25:15 +00001835 }
Peter Maydell6e657e62013-04-22 10:29:46 +00001836 [pool release];
thsc304f7e2008-01-22 23:25:15 +00001837}
1838
1839static void cocoa_cleanup(void)
1840{
1841 COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
Blue Swirl58a06672011-08-21 18:42:08 +00001842 g_free(dcl);
thsc304f7e2008-01-22 23:25:15 +00001843}
1844
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001845static const DisplayChangeListenerOps dcl_ops = {
1846 .dpy_name = "cocoa",
Peter Maydell8510d912013-03-18 20:28:21 +00001847 .dpy_gfx_update = cocoa_update,
1848 .dpy_gfx_switch = cocoa_switch,
1849 .dpy_refresh = cocoa_refresh,
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001850};
1851
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01001852static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
thsc304f7e2008-01-22 23:25:15 +00001853{
1854 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1855
Peter Maydell55888402019-02-25 10:24:33 +00001856 /* Tell main thread to go ahead and create the app and enter the run loop */
1857 qemu_sem_post(&display_init_sem);
1858 qemu_sem_wait(&app_started_sem);
1859 COCOA_DEBUG("cocoa_display_init: app start completed\n");
1860
Programmingkid43227af2015-05-19 09:11:17 +01001861 /* if fullscreen mode is to be used */
Gerd Hoffmann767f9bf2018-02-02 12:10:19 +01001862 if (opts->has_full_screen && opts->full_screen) {
Peter Maydell55888402019-02-25 10:24:33 +00001863 dispatch_async(dispatch_get_main_queue(), ^{
1864 [NSApp activateIgnoringOtherApps: YES];
1865 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1866 });
Programmingkid43227af2015-05-19 09:11:17 +01001867 }
Gerd Hoffmann3487da62020-02-06 12:27:50 +01001868 if (opts->has_show_cursor && opts->show_cursor) {
1869 cursor_hide = 0;
1870 }
Programmingkid43227af2015-05-19 09:11:17 +01001871
Blue Swirl58a06672011-08-21 18:42:08 +00001872 dcl = g_malloc0(sizeof(DisplayChangeListener));
1873
aliguori9794f742009-03-04 19:25:22 +00001874 // register vga output callbacks
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001875 dcl->ops = &dcl_ops;
Gerd Hoffmann52090892013-04-23 15:44:31 +02001876 register_displaychangelistener(dcl);
thsc304f7e2008-01-22 23:25:15 +00001877
1878 // register cleanup function
1879 atexit(cocoa_cleanup);
1880}
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01001881
1882static QemuDisplay qemu_display_cocoa = {
1883 .type = DISPLAY_TYPE_COCOA,
1884 .init = cocoa_display_init,
1885};
1886
1887static void register_cocoa(void)
1888{
1889 qemu_display_register(&qemu_display_cocoa);
1890}
1891
1892type_init(register_cocoa);