blob: 37e1fb52eb4d403441a646ac4180541bdf8dfb3a [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"
Akihiko Odaki6d73bb62021-03-10 23:46:02 +090033#include "ui/kbd-state.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010034#include "sysemu/sysemu.h"
Markus Armbruster54d31232019-08-12 07:23:59 +020035#include "sysemu/runstate.h"
Claudio Fontanab0c3cf92020-06-29 11:35:03 +020036#include "sysemu/cpu-throttle.h"
Markus Armbrustere688df62018-02-01 12:18:31 +010037#include "qapi/error.h"
Markus Armbruster16bf5232018-12-20 09:45:59 +010038#include "qapi/qapi-commands-block.h"
Philippe Mathieu-Daudé90f8c0f2020-10-12 14:15:33 +020039#include "qapi/qapi-commands-machine.h"
Markus Armbruster16bf5232018-12-20 09:45:59 +010040#include "qapi/qapi-commands-misc.h"
John Arbuckle693a3e02015-06-19 10:53:27 +010041#include "sysemu/blockdev.h"
Programmingkid9e8204b2016-08-15 22:11:06 -040042#include "qemu-version.h"
Akihiko Odakie31746e2021-03-09 21:22:25 +090043#include "qemu/cutils.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020044#include "qemu/main-loop.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020045#include "qemu/module.h"
John Arbuckleaaac7142016-03-23 14:26:18 +000046#include <Carbon/Carbon.h>
Markus Armbruster2e5b09f2019-07-09 17:20:52 +020047#include "hw/core/cpu.h"
bellardda4dbf72005-03-02 22:22:43 +000048
Brendan Shanks5e246002019-01-31 23:12:25 -080049#ifndef MAC_OS_X_VERSION_10_13
50#define MAC_OS_X_VERSION_10_13 101300
51#endif
Andreas Färber44e4c0b2009-12-13 00:45:40 +010052
Brendan Shanks5e246002019-01-31 23:12:25 -080053/* 10.14 deprecates NSOnState and NSOffState in favor of
54 * NSControlStateValueOn/Off, which were introduced in 10.13.
55 * Define for older versions
56 */
57#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
58#define NSControlStateValueOn NSOnState
59#define NSControlStateValueOff NSOffState
60#endif
bellard5b0753e2005-03-01 21:37:28 +000061
thsc304f7e2008-01-22 23:25:15 +000062//#define DEBUG
63
64#ifdef DEBUG
65#define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
66#else
67#define COCOA_DEBUG(...) ((void) 0)
68#endif
69
70#define cgrect(nsrect) (*(CGRect *)&(nsrect))
thsc304f7e2008-01-22 23:25:15 +000071
72typedef struct {
73 int width;
74 int height;
thsc304f7e2008-01-22 23:25:15 +000075} QEMUScreen;
76
Akihiko Odakicc7859c2021-02-19 17:44:19 +090077static void cocoa_update(DisplayChangeListener *dcl,
78 int x, int y, int w, int h);
79
80static void cocoa_switch(DisplayChangeListener *dcl,
81 DisplaySurface *surface);
82
83static void cocoa_refresh(DisplayChangeListener *dcl);
84
Akihiko Odakicb823402021-02-25 17:42:02 +090085static NSWindow *normalWindow, *about_window;
Akihiko Odakicc7859c2021-02-19 17:44:19 +090086static const DisplayChangeListenerOps dcl_ops = {
87 .dpy_name = "cocoa",
88 .dpy_gfx_update = cocoa_update,
89 .dpy_gfx_switch = cocoa_switch,
90 .dpy_refresh = cocoa_refresh,
91};
92static DisplayChangeListener dcl = {
93 .ops = &dcl_ops,
94};
Gerd Hoffmann21bae112013-12-04 14:08:04 +010095static int last_buttons;
Gerd Hoffmann3487da62020-02-06 12:27:50 +010096static int cursor_hide = 1;
bellard5b0753e2005-03-01 21:37:28 +000097
Akihiko Odakicb823402021-02-25 17:42:02 +090098static int gArgc;
99static char **gArgv;
100static bool stretch_video;
101static NSTextField *pauseLabel;
102static NSArray * supportedImageFileTypes;
bellard5b0753e2005-03-01 21:37:28 +0000103
Peter Maydell55888402019-02-25 10:24:33 +0000104static QemuSemaphore display_init_sem;
105static QemuSemaphore app_started_sem;
Hikaru Nishidadff742a2019-10-15 10:07:34 +0900106static bool allow_events;
Peter Maydell55888402019-02-25 10:24:33 +0000107
Peter Maydell60105d72019-02-25 10:24:31 +0000108// Utility functions to run specified code block with iothread lock held
Peter Maydell31819e92019-02-25 10:24:27 +0000109typedef void (^CodeBlock)(void);
Peter Maydell60105d72019-02-25 10:24:31 +0000110typedef bool (^BoolCodeBlock)(void);
Peter Maydell31819e92019-02-25 10:24:27 +0000111
112static void with_iothread_lock(CodeBlock block)
113{
114 bool locked = qemu_mutex_iothread_locked();
115 if (!locked) {
116 qemu_mutex_lock_iothread();
117 }
118 block();
119 if (!locked) {
120 qemu_mutex_unlock_iothread();
121 }
122}
123
Peter Maydell60105d72019-02-25 10:24:31 +0000124static bool bool_with_iothread_lock(BoolCodeBlock block)
125{
126 bool locked = qemu_mutex_iothread_locked();
127 bool val;
128
129 if (!locked) {
130 qemu_mutex_lock_iothread();
131 }
132 val = block();
133 if (!locked) {
134 qemu_mutex_unlock_iothread();
135 }
136 return val;
137}
138
John Arbuckleaaac7142016-03-23 14:26:18 +0000139// Mac to QKeyCode conversion
Akihiko Odakicb823402021-02-25 17:42:02 +0900140static const int mac_to_qkeycode_map[] = {
John Arbuckleaaac7142016-03-23 14:26:18 +0000141 [kVK_ANSI_A] = Q_KEY_CODE_A,
142 [kVK_ANSI_B] = Q_KEY_CODE_B,
143 [kVK_ANSI_C] = Q_KEY_CODE_C,
144 [kVK_ANSI_D] = Q_KEY_CODE_D,
145 [kVK_ANSI_E] = Q_KEY_CODE_E,
146 [kVK_ANSI_F] = Q_KEY_CODE_F,
147 [kVK_ANSI_G] = Q_KEY_CODE_G,
148 [kVK_ANSI_H] = Q_KEY_CODE_H,
149 [kVK_ANSI_I] = Q_KEY_CODE_I,
150 [kVK_ANSI_J] = Q_KEY_CODE_J,
151 [kVK_ANSI_K] = Q_KEY_CODE_K,
152 [kVK_ANSI_L] = Q_KEY_CODE_L,
153 [kVK_ANSI_M] = Q_KEY_CODE_M,
154 [kVK_ANSI_N] = Q_KEY_CODE_N,
155 [kVK_ANSI_O] = Q_KEY_CODE_O,
156 [kVK_ANSI_P] = Q_KEY_CODE_P,
157 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
158 [kVK_ANSI_R] = Q_KEY_CODE_R,
159 [kVK_ANSI_S] = Q_KEY_CODE_S,
160 [kVK_ANSI_T] = Q_KEY_CODE_T,
161 [kVK_ANSI_U] = Q_KEY_CODE_U,
162 [kVK_ANSI_V] = Q_KEY_CODE_V,
163 [kVK_ANSI_W] = Q_KEY_CODE_W,
164 [kVK_ANSI_X] = Q_KEY_CODE_X,
165 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
166 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
ths3b46e622007-09-17 08:09:54 +0000167
John Arbuckleaaac7142016-03-23 14:26:18 +0000168 [kVK_ANSI_0] = Q_KEY_CODE_0,
169 [kVK_ANSI_1] = Q_KEY_CODE_1,
170 [kVK_ANSI_2] = Q_KEY_CODE_2,
171 [kVK_ANSI_3] = Q_KEY_CODE_3,
172 [kVK_ANSI_4] = Q_KEY_CODE_4,
173 [kVK_ANSI_5] = Q_KEY_CODE_5,
174 [kVK_ANSI_6] = Q_KEY_CODE_6,
175 [kVK_ANSI_7] = Q_KEY_CODE_7,
176 [kVK_ANSI_8] = Q_KEY_CODE_8,
177 [kVK_ANSI_9] = Q_KEY_CODE_9,
178
179 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
180 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
181 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
182 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
183 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
184 [kVK_Tab] = Q_KEY_CODE_TAB,
185 [kVK_Return] = Q_KEY_CODE_RET,
186 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
187 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
188 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
189 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
190 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
191 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
192 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
193 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
John Arbuckleaaac7142016-03-23 14:26:18 +0000194 [kVK_Space] = Q_KEY_CODE_SPC,
195
196 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
197 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
198 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
199 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
200 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
201 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
202 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
203 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
204 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
205 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
206 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
207 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
208 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
209 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
210 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
211 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
212 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
213 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
214
215 [kVK_UpArrow] = Q_KEY_CODE_UP,
216 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
217 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
218 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
219
220 [kVK_Help] = Q_KEY_CODE_INSERT,
221 [kVK_Home] = Q_KEY_CODE_HOME,
222 [kVK_PageUp] = Q_KEY_CODE_PGUP,
223 [kVK_PageDown] = Q_KEY_CODE_PGDN,
224 [kVK_End] = Q_KEY_CODE_END,
225 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
226
227 [kVK_Escape] = Q_KEY_CODE_ESC,
228
229 /* The Power key can't be used directly because the operating system uses
230 * it. This key can be emulated by using it in place of another key such as
231 * F1. Don't forget to disable the real key binding.
232 */
233 /* [kVK_F1] = Q_KEY_CODE_POWER, */
234
235 [kVK_F1] = Q_KEY_CODE_F1,
236 [kVK_F2] = Q_KEY_CODE_F2,
237 [kVK_F3] = Q_KEY_CODE_F3,
238 [kVK_F4] = Q_KEY_CODE_F4,
239 [kVK_F5] = Q_KEY_CODE_F5,
240 [kVK_F6] = Q_KEY_CODE_F6,
241 [kVK_F7] = Q_KEY_CODE_F7,
242 [kVK_F8] = Q_KEY_CODE_F8,
243 [kVK_F9] = Q_KEY_CODE_F9,
244 [kVK_F10] = Q_KEY_CODE_F10,
245 [kVK_F11] = Q_KEY_CODE_F11,
246 [kVK_F12] = Q_KEY_CODE_F12,
247 [kVK_F13] = Q_KEY_CODE_PRINT,
248 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
249 [kVK_F15] = Q_KEY_CODE_PAUSE,
250
Akihiko Odaki708b7252021-02-12 09:04:04 +0900251 // JIS keyboards only
252 [kVK_JIS_Yen] = Q_KEY_CODE_YEN,
253 [kVK_JIS_Underscore] = Q_KEY_CODE_RO,
254 [kVK_JIS_KeypadComma] = Q_KEY_CODE_KP_COMMA,
255 [kVK_JIS_Eisu] = Q_KEY_CODE_MUHENKAN,
256 [kVK_JIS_Kana] = Q_KEY_CODE_HENKAN,
257
John Arbuckleaaac7142016-03-23 14:26:18 +0000258 /*
259 * The eject and volume keys can't be used here because they are handled at
260 * a lower level than what an Application can see.
261 */
bellard5b0753e2005-03-01 21:37:28 +0000262};
263
Andreas Färber77047bb2009-12-13 00:55:53 +0100264static int cocoa_keycode_to_qemu(int keycode)
bellard5b0753e2005-03-01 21:37:28 +0000265{
John Arbuckleaaac7142016-03-23 14:26:18 +0000266 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
Akihiko Odaki43137392021-02-23 22:11:06 +0900267 error_report("(cocoa) warning unknown keycode 0x%x", keycode);
bellard5b0753e2005-03-01 21:37:28 +0000268 return 0;
269 }
John Arbuckleaaac7142016-03-23 14:26:18 +0000270 return mac_to_qkeycode_map[keycode];
bellard5b0753e2005-03-01 21:37:28 +0000271}
272
John Arbuckle693a3e02015-06-19 10:53:27 +0100273/* Displays an alert dialog box with the specified message */
274static void QEMU_Alert(NSString *message)
275{
276 NSAlert *alert;
277 alert = [NSAlert new];
278 [alert setMessageText: message];
279 [alert runModal];
280}
thsc304f7e2008-01-22 23:25:15 +0000281
John Arbuckle693a3e02015-06-19 10:53:27 +0100282/* Handles any errors that happen with a device transaction */
283static void handleAnyDeviceErrors(Error * err)
284{
285 if (err) {
286 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
287 encoding: NSASCIIStringEncoding]);
288 error_free(err);
289 }
290}
thsc304f7e2008-01-22 23:25:15 +0000291
bellard5b0753e2005-03-01 21:37:28 +0000292/*
293 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +0000294 QemuCocoaView
bellard5b0753e2005-03-01 21:37:28 +0000295 ------------------------------------------------------
296*/
thsc304f7e2008-01-22 23:25:15 +0000297@interface QemuCocoaView : NSView
bellard5b0753e2005-03-01 21:37:28 +0000298{
thsc304f7e2008-01-22 23:25:15 +0000299 QEMUScreen screen;
300 NSWindow *fullScreenWindow;
301 float cx,cy,cw,ch,cdx,cdy;
Peter Maydell55888402019-02-25 10:24:33 +0000302 pixman_image_t *pixman_image;
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900303 QKbdState *kbd;
Peter Maydell49b9bd42013-12-08 22:59:03 +0000304 BOOL isMouseGrabbed;
thsc304f7e2008-01-22 23:25:15 +0000305 BOOL isFullscreen;
306 BOOL isAbsoluteEnabled;
thsc304f7e2008-01-22 23:25:15 +0000307}
Peter Maydell72a3e312019-02-25 10:24:28 +0000308- (void) switchSurface:(pixman_image_t *)image;
thsc304f7e2008-01-22 23:25:15 +0000309- (void) grabMouse;
310- (void) ungrabMouse;
311- (void) toggleFullScreen:(id)sender;
John Arbuckle9c3a4182017-11-07 10:14:14 +0000312- (void) handleMonitorInput:(NSEvent *)event;
Peter Maydell60105d72019-02-25 10:24:31 +0000313- (bool) handleEvent:(NSEvent *)event;
314- (bool) handleEventLocked:(NSEvent *)event;
thsc304f7e2008-01-22 23:25:15 +0000315- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
Peter Maydellf61c3872014-06-23 10:35:24 +0100316/* The state surrounding mouse grabbing is potentially confusing.
317 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
318 * pointing device an absolute-position one?"], but is only updated on
319 * next refresh.
320 * isMouseGrabbed tracks whether GUI events are directed to the guest;
321 * it controls whether special keys like Cmd get sent to the guest,
322 * and whether we capture the mouse when in non-absolute mode.
Peter Maydellf61c3872014-06-23 10:35:24 +0100323 */
Peter Maydell49b9bd42013-12-08 22:59:03 +0000324- (BOOL) isMouseGrabbed;
thsc304f7e2008-01-22 23:25:15 +0000325- (BOOL) isAbsoluteEnabled;
326- (float) cdx;
327- (float) cdy;
328- (QEMUScreen) gscreen;
John Arbuckle3b178b72015-09-25 23:14:00 +0100329- (void) raiseAllKeys;
thsc304f7e2008-01-22 23:25:15 +0000330@end
ths3b46e622007-09-17 08:09:54 +0000331
Andreas Färber7fee1992011-06-09 20:53:32 +0200332QemuCocoaView *cocoaView;
333
thsc304f7e2008-01-22 23:25:15 +0000334@implementation QemuCocoaView
335- (id)initWithFrame:(NSRect)frameRect
336{
337 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
ths3b46e622007-09-17 08:09:54 +0000338
thsc304f7e2008-01-22 23:25:15 +0000339 self = [super initWithFrame:frameRect];
340 if (self) {
pbrook95219892006-04-09 01:06:34 +0000341
thsc304f7e2008-01-22 23:25:15 +0000342 screen.width = frameRect.size.width;
343 screen.height = frameRect.size.height;
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900344 kbd = qkbd_state_init(dcl.con);
bellard7c206a72005-12-18 19:18:45 +0000345
thsc304f7e2008-01-22 23:25:15 +0000346 }
347 return self;
348}
bellard7c206a72005-12-18 19:18:45 +0000349
thsc304f7e2008-01-22 23:25:15 +0000350- (void) dealloc
351{
352 COCOA_DEBUG("QemuCocoaView: dealloc\n");
bellard7c206a72005-12-18 19:18:45 +0000353
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900354 if (pixman_image) {
Peter Maydell55888402019-02-25 10:24:33 +0000355 pixman_image_unref(pixman_image);
356 }
ths3b46e622007-09-17 08:09:54 +0000357
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900358 qkbd_state_free(kbd);
thsc304f7e2008-01-22 23:25:15 +0000359 [super dealloc];
360}
bellard5cbfcd02006-06-14 15:53:24 +0000361
Andreas Färberd50f71d2009-12-13 02:03:33 +0100362- (BOOL) isOpaque
363{
364 return YES;
365}
366
Peter Maydell5dd45be2014-06-23 10:35:23 +0100367- (BOOL) screenContainsPoint:(NSPoint) p
368{
369 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
370}
371
Chen Zhang2044dff2019-06-04 17:36:00 +0800372/* Get location of event and convert to virtual screen coordinate */
373- (CGPoint) screenLocationOfEvent:(NSEvent *)ev
374{
375 NSWindow *eventWindow = [ev window];
376 // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
377 CGRect r = CGRectZero;
378 r.origin = [ev locationInWindow];
379 if (!eventWindow) {
380 if (!isFullscreen) {
381 return [[self window] convertRectFromScreen:r].origin;
382 } else {
383 CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
384 CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
385 if (stretch_video) {
386 loc.x /= cdx;
387 loc.y /= cdy;
388 }
389 return loc;
390 }
391 } else if ([[self window] isEqual:eventWindow]) {
392 if (!isFullscreen) {
393 return r.origin;
394 } else {
395 CGPoint loc = [self convertPoint:r.origin fromView:nil];
396 if (stretch_video) {
397 loc.x /= cdx;
398 loc.y /= cdy;
399 }
400 return loc;
401 }
402 } else {
403 return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
404 }
405}
406
Peter Maydell13aefd32014-06-23 10:35:25 +0100407- (void) hideCursor
408{
409 if (!cursor_hide) {
410 return;
411 }
412 [NSCursor hide];
413}
414
415- (void) unhideCursor
416{
417 if (!cursor_hide) {
418 return;
419 }
420 [NSCursor unhide];
421}
422
thsc304f7e2008-01-22 23:25:15 +0000423- (void) drawRect:(NSRect) rect
424{
425 COCOA_DEBUG("QemuCocoaView: drawRect\n");
bellard5cbfcd02006-06-14 15:53:24 +0000426
thsc304f7e2008-01-22 23:25:15 +0000427 // get CoreGraphic context
Brendan Shanks5e246002019-01-31 23:12:25 -0800428 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
Brendan Shanks5e246002019-01-31 23:12:25 -0800429
thsc304f7e2008-01-22 23:25:15 +0000430 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
431 CGContextSetShouldAntialias (viewContextRef, NO);
ths3b46e622007-09-17 08:09:54 +0000432
thsc304f7e2008-01-22 23:25:15 +0000433 // draw screen bitmap directly to Core Graphics context
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900434 if (!pixman_image) {
Peter Maydell7d270b12013-12-24 02:51:47 +0000435 // Draw request before any guest device has set up a framebuffer:
436 // just draw an opaque black rectangle
437 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
438 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
439 } else {
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900440 int w = pixman_image_get_width(pixman_image);
441 int h = pixman_image_get_height(pixman_image);
442 int bitsPerPixel = PIXMAN_FORMAT_BPP(pixman_image_get_format(pixman_image));
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900443 int stride = pixman_image_get_stride(pixman_image);
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900444 CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(
445 NULL,
446 pixman_image_get_data(pixman_image),
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900447 stride * h,
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900448 NULL
449 );
thsc304f7e2008-01-22 23:25:15 +0000450 CGImageRef imageRef = CGImageCreate(
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900451 w, //width
452 h, //height
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900453 DIV_ROUND_UP(bitsPerPixel, 8) * 2, //bitsPerComponent
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900454 bitsPerPixel, //bitsPerPixel
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900455 stride, //bytesPerRow
Akihiko Odakiae57d352021-03-05 21:13:04 +0900456 CGColorSpaceCreateWithName(kCGColorSpaceSRGB), //colorspace
457 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst, //bitmapInfo
thsc304f7e2008-01-22 23:25:15 +0000458 dataProviderRef, //provider
459 NULL, //decode
460 0, //interpolate
461 kCGRenderingIntentDefault //intent
462 );
Peter Maydellb63901d2015-05-19 09:11:17 +0100463 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
464 const NSRect *rectList;
Peter Maydellb63901d2015-05-19 09:11:17 +0100465 NSInteger rectCount;
Peter Maydellb63901d2015-05-19 09:11:17 +0100466 int i;
467 CGImageRef clipImageRef;
468 CGRect clipRect;
ths3b46e622007-09-17 08:09:54 +0000469
Peter Maydellb63901d2015-05-19 09:11:17 +0100470 [self getRectsBeingDrawn:&rectList count:&rectCount];
471 for (i = 0; i < rectCount; i++) {
472 clipRect.origin.x = rectList[i].origin.x / cdx;
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900473 clipRect.origin.y = (float)h - (rectList[i].origin.y + rectList[i].size.height) / cdy;
Peter Maydellb63901d2015-05-19 09:11:17 +0100474 clipRect.size.width = rectList[i].size.width / cdx;
475 clipRect.size.height = rectList[i].size.height / cdy;
476 clipImageRef = CGImageCreateWithImageInRect(
477 imageRef,
478 clipRect
479 );
480 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
481 CGImageRelease (clipImageRef);
bellard5b0753e2005-03-01 21:37:28 +0000482 }
thsc304f7e2008-01-22 23:25:15 +0000483 CGImageRelease (imageRef);
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900484 CGDataProviderRelease(dataProviderRef);
bellard5b0753e2005-03-01 21:37:28 +0000485 }
486}
487
thsc304f7e2008-01-22 23:25:15 +0000488- (void) setContentDimensions
bellard5b0753e2005-03-01 21:37:28 +0000489{
thsc304f7e2008-01-22 23:25:15 +0000490 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
ths3b46e622007-09-17 08:09:54 +0000491
thsc304f7e2008-01-22 23:25:15 +0000492 if (isFullscreen) {
493 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
494 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100495
496 /* stretches video, but keeps same aspect ratio */
497 if (stretch_video == true) {
498 /* use smallest stretch value - prevents clipping on sides */
499 if (MIN(cdx, cdy) == cdx) {
500 cdy = cdx;
501 } else {
502 cdx = cdy;
503 }
504 } else { /* No stretching */
505 cdx = cdy = 1;
506 }
thsc304f7e2008-01-22 23:25:15 +0000507 cw = screen.width * cdx;
508 ch = screen.height * cdy;
509 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
510 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
511 } else {
512 cx = 0;
513 cy = 0;
514 cw = screen.width;
515 ch = screen.height;
516 cdx = 1.0;
517 cdy = 1.0;
518 }
bellard5b0753e2005-03-01 21:37:28 +0000519}
520
Peter Maydell72a3e312019-02-25 10:24:28 +0000521- (void) switchSurface:(pixman_image_t *)image
thsc304f7e2008-01-22 23:25:15 +0000522{
Gerd Hoffmann5e00d3a2013-03-01 12:52:06 +0100523 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
thsc304f7e2008-01-22 23:25:15 +0000524
Peter Maydell72a3e312019-02-25 10:24:28 +0000525 int w = pixman_image_get_width(image);
526 int h = pixman_image_get_height(image);
Peter Maydell381600d2014-06-23 10:35:22 +0100527 /* cdx == 0 means this is our very first surface, in which case we need
528 * to recalculate the content dimensions even if it happens to be the size
529 * of the initial empty window.
530 */
531 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
Peter Maydelld3345a02013-12-24 02:51:46 +0000532
533 int oldh = screen.height;
534 if (isResize) {
535 // Resize before we trigger the redraw, or we'll redraw at the wrong size
536 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
537 screen.width = w;
538 screen.height = h;
539 [self setContentDimensions];
540 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
541 }
Peter Maydell8510d912013-03-18 20:28:21 +0000542
thsc304f7e2008-01-22 23:25:15 +0000543 // update screenBuffer
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900544 if (pixman_image) {
Peter Maydell55888402019-02-25 10:24:33 +0000545 pixman_image_unref(pixman_image);
546 }
thsc304f7e2008-01-22 23:25:15 +0000547
Peter Maydell55888402019-02-25 10:24:33 +0000548 pixman_image = image;
thsc304f7e2008-01-22 23:25:15 +0000549
550 // update windows
551 if (isFullscreen) {
552 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
Peter Maydelld3345a02013-12-24 02:51:46 +0000553 [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 +0000554 } else {
555 if (qemu_name)
556 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
Peter Maydelld3345a02013-12-24 02:51:46 +0000557 [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 +0000558 }
Peter Maydelld3345a02013-12-24 02:51:46 +0000559
560 if (isResize) {
561 [normalWindow center];
562 }
thsc304f7e2008-01-22 23:25:15 +0000563}
564
565- (void) toggleFullScreen:(id)sender
566{
567 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
568
569 if (isFullscreen) { // switch from fullscreen to desktop
570 isFullscreen = FALSE;
571 [self ungrabMouse];
572 [self setContentDimensions];
Akihiko Odaki1e8b6f22021-02-20 10:31:38 +0900573 [fullScreenWindow close];
574 [normalWindow setContentView: self];
575 [normalWindow makeKeyAndOrderFront: self];
576 [NSMenu setMenuBarVisible:YES];
thsc304f7e2008-01-22 23:25:15 +0000577 } else { // switch from desktop to fullscreen
578 isFullscreen = TRUE;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100579 [normalWindow orderOut: nil]; /* Hide the window */
thsc304f7e2008-01-22 23:25:15 +0000580 [self grabMouse];
581 [self setContentDimensions];
Akihiko Odaki1e8b6f22021-02-20 10:31:38 +0900582 [NSMenu setMenuBarVisible:NO];
583 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
584 styleMask:NSWindowStyleMaskBorderless
585 backing:NSBackingStoreBuffered
586 defer:NO];
587 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
588 [fullScreenWindow setHasShadow:NO];
589 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
590 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
591 [[fullScreenWindow contentView] addSubview: self];
592 [fullScreenWindow makeKeyAndOrderFront:self];
thsc304f7e2008-01-22 23:25:15 +0000593 }
594}
595
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900596- (void) toggleKey: (int)keycode {
597 qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode));
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700598}
599
John Arbuckle9c3a4182017-11-07 10:14:14 +0000600// Does the work of sending input to the monitor
601- (void) handleMonitorInput:(NSEvent *)event
602{
603 int keysym = 0;
604 int control_key = 0;
605
606 // if the control key is down
607 if ([event modifierFlags] & NSEventModifierFlagControl) {
608 control_key = 1;
609 }
610
611 /* translates Macintosh keycodes to QEMU's keysym */
612
613 int without_control_translation[] = {
614 [0 ... 0xff] = 0, // invalid key
615
616 [kVK_UpArrow] = QEMU_KEY_UP,
617 [kVK_DownArrow] = QEMU_KEY_DOWN,
618 [kVK_RightArrow] = QEMU_KEY_RIGHT,
619 [kVK_LeftArrow] = QEMU_KEY_LEFT,
620 [kVK_Home] = QEMU_KEY_HOME,
621 [kVK_End] = QEMU_KEY_END,
622 [kVK_PageUp] = QEMU_KEY_PAGEUP,
623 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
624 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
625 [kVK_Delete] = QEMU_KEY_BACKSPACE,
626 };
627
628 int with_control_translation[] = {
629 [0 ... 0xff] = 0, // invalid key
630
631 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
632 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
633 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
634 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
635 [kVK_Home] = QEMU_KEY_CTRL_HOME,
636 [kVK_End] = QEMU_KEY_CTRL_END,
637 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
638 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
639 };
640
641 if (control_key != 0) { /* If the control key is being used */
642 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
643 keysym = with_control_translation[[event keyCode]];
644 }
645 } else {
646 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
647 keysym = without_control_translation[[event keyCode]];
648 }
649 }
650
651 // if not a key that needs translating
652 if (keysym == 0) {
653 NSString *ks = [event characters];
654 if ([ks length] > 0) {
655 keysym = [ks characterAtIndex:0];
656 }
657 }
658
659 if (keysym) {
660 kbd_put_keysym(keysym);
661 }
662}
663
Peter Maydell60105d72019-02-25 10:24:31 +0000664- (bool) handleEvent:(NSEvent *)event
thsc304f7e2008-01-22 23:25:15 +0000665{
Hikaru Nishidadff742a2019-10-15 10:07:34 +0900666 if(!allow_events) {
667 /*
668 * Just let OSX have all events that arrive before
669 * applicationDidFinishLaunching.
670 * This avoids a deadlock on the iothread lock, which cocoa_display_init()
671 * will not drop until after the app_started_sem is posted. (In theory
672 * there should not be any such events, but OSX Catalina now emits some.)
673 */
674 return false;
675 }
Peter Maydell60105d72019-02-25 10:24:31 +0000676 return bool_with_iothread_lock(^{
677 return [self handleEventLocked:event];
Peter Maydell31819e92019-02-25 10:24:27 +0000678 });
679}
thsc304f7e2008-01-22 23:25:15 +0000680
Peter Maydell60105d72019-02-25 10:24:31 +0000681- (bool) handleEventLocked:(NSEvent *)event
Peter Maydell31819e92019-02-25 10:24:27 +0000682{
Peter Maydell60105d72019-02-25 10:24:31 +0000683 /* Return true if we handled the event, false if it should be given to OSX */
Peter Maydell31819e92019-02-25 10:24:27 +0000684 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
thsc304f7e2008-01-22 23:25:15 +0000685 int buttons = 0;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700686 int keycode = 0;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100687 bool mouse_event = false;
John Arbuckle0c6c4392018-07-02 22:00:17 -0400688 static bool switched_to_fullscreen = false;
Chen Zhang2044dff2019-06-04 17:36:00 +0800689 // Location of event in virtual screen coordinates
690 NSPoint p = [self screenLocationOfEvent:event];
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900691 NSUInteger modifiers = [event modifierFlags];
692
Akihiko Odakiad7f2f82021-03-12 22:32:12 +0900693 /*
694 * Check -[NSEvent modifierFlags] here.
695 *
696 * There is a NSEventType for an event notifying the change of
697 * -[NSEvent modifierFlags], NSEventTypeFlagsChanged but these operations
698 * are performed for any events because a modifier state may change while
699 * the application is inactive (i.e. no events fire) and we don't want to
700 * wait for another modifier state change to detect such a change.
701 *
702 * NSEventModifierFlagCapsLock requires a special treatment. The other flags
703 * are handled in similar manners.
704 *
705 * NSEventModifierFlagCapsLock
706 * ---------------------------
707 *
708 * If CapsLock state is changed, "up" and "down" events will be fired in
709 * sequence, effectively updates CapsLock state on the guest.
710 *
711 * The other flags
712 * ---------------
713 *
714 * If a flag is not set, fire "up" events for all keys which correspond to
715 * the flag. Note that "down" events are not fired here because the flags
716 * checked here do not tell what exact keys are down.
717 *
718 * If one of the keys corresponding to a flag is down, we rely on
719 * -[NSEvent keyCode] of an event whose -[NSEvent type] is
720 * NSEventTypeFlagsChanged to know the exact key which is down, which has
721 * the following two downsides:
722 * - It does not work when the application is inactive as described above.
723 * - It malfactions *after* the modifier state is changed while the
724 * application is inactive. It is because -[NSEvent keyCode] does not tell
725 * if the key is up or down, and requires to infer the current state from
726 * the previous state. It is still possible to fix such a malfanction by
727 * completely leaving your hands from the keyboard, which hopefully makes
728 * this implementation usable enough.
729 */
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900730 if (!!(modifiers & NSEventModifierFlagCapsLock) !=
731 qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) {
732 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true);
733 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false);
734 }
735
736 if (!(modifiers & NSEventModifierFlagShift)) {
737 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false);
738 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false);
739 }
740 if (!(modifiers & NSEventModifierFlagControl)) {
741 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false);
742 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false);
743 }
744 if (!(modifiers & NSEventModifierFlagOption)) {
745 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
746 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
747 }
748 if (!(modifiers & NSEventModifierFlagCommand)) {
749 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
750 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
751 }
thsc304f7e2008-01-22 23:25:15 +0000752
753 switch ([event type]) {
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700754 case NSEventTypeFlagsChanged:
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900755 switch ([event keyCode]) {
756 case kVK_Shift:
757 if (!!(modifiers & NSEventModifierFlagShift)) {
758 [self toggleKey:Q_KEY_CODE_SHIFT];
759 }
760 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700761
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900762 case kVK_RightShift:
763 if (!!(modifiers & NSEventModifierFlagShift)) {
764 [self toggleKey:Q_KEY_CODE_SHIFT_R];
765 }
766 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700767
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900768 case kVK_Control:
769 if (!!(modifiers & NSEventModifierFlagControl)) {
770 [self toggleKey:Q_KEY_CODE_CTRL];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700771 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900772 break;
773
774 case kVK_RightControl:
775 if (!!(modifiers & NSEventModifierFlagControl)) {
776 [self toggleKey:Q_KEY_CODE_CTRL_R];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700777 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900778 break;
779
780 case kVK_Option:
781 if (!!(modifiers & NSEventModifierFlagOption)) {
782 [self toggleKey:Q_KEY_CODE_ALT];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700783 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900784 break;
785
786 case kVK_RightOption:
787 if (!!(modifiers & NSEventModifierFlagOption)) {
788 [self toggleKey:Q_KEY_CODE_ALT_R];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700789 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900790 break;
791
792 /* Don't pass command key changes to guest unless mouse is grabbed */
793 case kVK_Command:
794 if (isMouseGrabbed &&
795 !!(modifiers & NSEventModifierFlagCommand)) {
796 [self toggleKey:Q_KEY_CODE_META_L];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700797 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900798 break;
799
800 case kVK_RightCommand:
801 if (isMouseGrabbed &&
802 !!(modifiers & NSEventModifierFlagCommand)) {
803 [self toggleKey:Q_KEY_CODE_META_R];
804 }
805 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700806 }
thsc304f7e2008-01-22 23:25:15 +0000807 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700808 case NSEventTypeKeyDown:
Peter Maydell88959192013-12-08 22:59:02 +0000809 keycode = cocoa_keycode_to_qemu([event keyCode]);
thsc304f7e2008-01-22 23:25:15 +0000810
Peter Maydell88959192013-12-08 22:59:02 +0000811 // forward command key combos to the host UI unless the mouse is grabbed
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700812 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
John Arbuckle0c6c4392018-07-02 22:00:17 -0400813 /*
814 * Prevent the command key from being stuck down in the guest
815 * when using Command-F to switch to full screen mode.
816 */
817 if (keycode == Q_KEY_CODE_F) {
818 switched_to_fullscreen = true;
819 }
Peter Maydell60105d72019-02-25 10:24:31 +0000820 return false;
thsc304f7e2008-01-22 23:25:15 +0000821 }
822
823 // default
thsc304f7e2008-01-22 23:25:15 +0000824
John Arbuckle5929e362017-11-07 10:14:14 +0000825 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700826 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
John Arbuckle5929e362017-11-07 10:14:14 +0000827 NSString *keychar = [event charactersIgnoringModifiers];
828 if ([keychar length] == 1) {
829 char key = [keychar characterAtIndex:0];
830 switch (key) {
thsc304f7e2008-01-22 23:25:15 +0000831
John Arbuckle5929e362017-11-07 10:14:14 +0000832 // enable graphic console
833 case '1' ... '9':
834 console_select(key - '0' - 1); /* ascii math */
Peter Maydell60105d72019-02-25 10:24:31 +0000835 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000836
837 // release the mouse grab
838 case 'g':
839 [self ungrabMouse];
Peter Maydell60105d72019-02-25 10:24:31 +0000840 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000841 }
thsc304f7e2008-01-22 23:25:15 +0000842 }
Peter Maydellef2088f2017-11-07 10:14:14 +0000843 }
thsc304f7e2008-01-22 23:25:15 +0000844
Peter Maydellef2088f2017-11-07 10:14:14 +0000845 if (qemu_console_is_graphic(NULL)) {
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900846 qkbd_state_key_event(kbd, keycode, true);
thsc304f7e2008-01-22 23:25:15 +0000847 } else {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000848 [self handleMonitorInput: event];
thsc304f7e2008-01-22 23:25:15 +0000849 }
850 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700851 case NSEventTypeKeyUp:
thsc304f7e2008-01-22 23:25:15 +0000852 keycode = cocoa_keycode_to_qemu([event keyCode]);
Peter Maydell88959192013-12-08 22:59:02 +0000853
854 // don't pass the guest a spurious key-up if we treated this
855 // command-key combo as a host UI action
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700856 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
Peter Maydell60105d72019-02-25 10:24:31 +0000857 return true;
Peter Maydell88959192013-12-08 22:59:02 +0000858 }
859
Peter Maydell68c0aa62013-04-17 09:16:35 +0000860 if (qemu_console_is_graphic(NULL)) {
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900861 qkbd_state_key_event(kbd, keycode, false);
thsc304f7e2008-01-22 23:25:15 +0000862 }
863 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700864 case NSEventTypeMouseMoved:
thsc304f7e2008-01-22 23:25:15 +0000865 if (isAbsoluteEnabled) {
Chen Zhang2044dff2019-06-04 17:36:00 +0800866 // Cursor re-entered into a window might generate events bound to screen coordinates
867 // and `nil` window property, and in full screen mode, current window might not be
868 // key window, where event location alone should suffice.
869 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
Peter Maydellf61c3872014-06-23 10:35:24 +0100870 if (isMouseGrabbed) {
871 [self ungrabMouse];
thsc304f7e2008-01-22 23:25:15 +0000872 }
873 } else {
Peter Maydellf61c3872014-06-23 10:35:24 +0100874 if (!isMouseGrabbed) {
875 [self grabMouse];
thsc304f7e2008-01-22 23:25:15 +0000876 }
877 }
878 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100879 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000880 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700881 case NSEventTypeLeftMouseDown:
Akihiko Odaki4295f832021-02-12 09:07:06 +0900882 buttons |= MOUSE_EVENT_LBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100883 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000884 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700885 case NSEventTypeRightMouseDown:
thsc304f7e2008-01-22 23:25:15 +0000886 buttons |= MOUSE_EVENT_RBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100887 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000888 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700889 case NSEventTypeOtherMouseDown:
thsc304f7e2008-01-22 23:25:15 +0000890 buttons |= MOUSE_EVENT_MBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100891 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000892 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700893 case NSEventTypeLeftMouseDragged:
Akihiko Odaki4295f832021-02-12 09:07:06 +0900894 buttons |= MOUSE_EVENT_LBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100895 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000896 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700897 case NSEventTypeRightMouseDragged:
thsc304f7e2008-01-22 23:25:15 +0000898 buttons |= MOUSE_EVENT_RBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100899 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000900 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700901 case NSEventTypeOtherMouseDragged:
thsc304f7e2008-01-22 23:25:15 +0000902 buttons |= MOUSE_EVENT_MBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100903 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000904 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700905 case NSEventTypeLeftMouseUp:
Peter Maydellf61c3872014-06-23 10:35:24 +0100906 mouse_event = true;
907 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
Chen Zhang8e23e342019-06-04 17:36:48 +0800908 /*
909 * In fullscreen mode, the window of cocoaView may not be the
910 * key window, therefore the position relative to the virtual
911 * screen alone will be sufficient.
912 */
913 if(isFullscreen || [[self window] isKeyWindow]) {
Programmingkid9e8204b2016-08-15 22:11:06 -0400914 [self grabMouse];
915 }
thsc304f7e2008-01-22 23:25:15 +0000916 }
917 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700918 case NSEventTypeRightMouseUp:
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100919 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000920 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700921 case NSEventTypeOtherMouseUp:
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100922 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000923 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700924 case NSEventTypeScrollWheel:
John Arbuckleae7313e2018-01-08 13:07:07 -0500925 /*
926 * Send wheel events to the guest regardless of window focus.
927 * This is in-line with standard Mac OS X UI behaviour.
928 */
929
John Arbuckledc3c89d2018-07-09 11:02:35 -0400930 /*
931 * When deltaY is zero, it means that this scrolling event was
932 * either horizontal, or so fine that it only appears in
933 * scrollingDeltaY. So we drop the event.
934 */
935 if ([event deltaY] != 0) {
John Arbuckleae7313e2018-01-08 13:07:07 -0500936 /* Determine if this is a scroll up or scroll down event */
John Arbuckledc3c89d2018-07-09 11:02:35 -0400937 buttons = ([event deltaY] > 0) ?
938 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
Akihiko Odakicc7859c2021-02-19 17:44:19 +0900939 qemu_input_queue_btn(dcl.con, buttons, true);
John Arbuckledc3c89d2018-07-09 11:02:35 -0400940 qemu_input_event_sync();
Akihiko Odakicc7859c2021-02-19 17:44:19 +0900941 qemu_input_queue_btn(dcl.con, buttons, false);
John Arbuckledc3c89d2018-07-09 11:02:35 -0400942 qemu_input_event_sync();
943 }
John Arbuckleae7313e2018-01-08 13:07:07 -0500944 /*
945 * Since deltaY also reports scroll wheel events we prevent mouse
946 * movement code from executing.
947 */
948 mouse_event = false;
thsc304f7e2008-01-22 23:25:15 +0000949 break;
950 default:
Peter Maydell60105d72019-02-25 10:24:31 +0000951 return false;
thsc304f7e2008-01-22 23:25:15 +0000952 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100953
954 if (mouse_event) {
Peter Maydell8d3a5d92015-11-26 15:19:28 +0000955 /* Don't send button events to the guest unless we've got a
956 * mouse grab or window focus. If we have neither then this event
957 * is the user clicking on the background window to activate and
958 * bring us to the front, which will be done by the sendEvent
959 * call below. We definitely don't want to pass that click through
960 * to the guest.
961 */
962 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
963 (last_buttons != buttons)) {
Eric Blake7fb1cf12015-11-18 01:52:57 -0700964 static uint32_t bmap[INPUT_BUTTON__MAX] = {
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100965 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
966 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
John Arbuckleae7313e2018-01-08 13:07:07 -0500967 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100968 };
Akihiko Odakicc7859c2021-02-19 17:44:19 +0900969 qemu_input_update_buttons(dcl.con, bmap, last_buttons, buttons);
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100970 last_buttons = buttons;
971 }
Peter Maydellf61c3872014-06-23 10:35:24 +0100972 if (isMouseGrabbed) {
973 if (isAbsoluteEnabled) {
974 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
975 * The check on screenContainsPoint is to avoid sending out of range values for
976 * clicks in the titlebar.
977 */
978 if ([self screenContainsPoint:p]) {
Akihiko Odakicc7859c2021-02-19 17:44:19 +0900979 qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x, 0, screen.width);
980 qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
Peter Maydellf61c3872014-06-23 10:35:24 +0100981 }
982 } else {
Akihiko Odakicc7859c2021-02-19 17:44:19 +0900983 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, (int)[event deltaX]);
984 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, (int)[event deltaY]);
Peter Maydellf61c3872014-06-23 10:35:24 +0100985 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100986 } else {
Peter Maydell60105d72019-02-25 10:24:31 +0000987 return false;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100988 }
989 qemu_input_event_sync();
990 }
Peter Maydell60105d72019-02-25 10:24:31 +0000991 return true;
thsc304f7e2008-01-22 23:25:15 +0000992}
993
994- (void) grabMouse
995{
996 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
997
998 if (!isFullscreen) {
999 if (qemu_name)
John Arbuckle5929e362017-11-07 10:14:14 +00001000 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
thsc304f7e2008-01-22 23:25:15 +00001001 else
John Arbuckle5929e362017-11-07 10:14:14 +00001002 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
thsc304f7e2008-01-22 23:25:15 +00001003 }
Peter Maydell13aefd32014-06-23 10:35:25 +01001004 [self hideCursor];
Akihiko Odakid1929062021-02-23 00:07:14 +09001005 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
Peter Maydell49b9bd42013-12-08 22:59:03 +00001006 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
thsc304f7e2008-01-22 23:25:15 +00001007}
1008
1009- (void) ungrabMouse
1010{
1011 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
1012
1013 if (!isFullscreen) {
1014 if (qemu_name)
1015 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
1016 else
1017 [normalWindow setTitle:@"QEMU"];
1018 }
Peter Maydell13aefd32014-06-23 10:35:25 +01001019 [self unhideCursor];
Akihiko Odakid1929062021-02-23 00:07:14 +09001020 CGAssociateMouseAndMouseCursorPosition(TRUE);
Peter Maydell49b9bd42013-12-08 22:59:03 +00001021 isMouseGrabbed = FALSE;
thsc304f7e2008-01-22 23:25:15 +00001022}
1023
Akihiko Odakid1929062021-02-23 00:07:14 +09001024- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {
1025 isAbsoluteEnabled = tIsAbsoluteEnabled;
1026 if (isMouseGrabbed) {
1027 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1028 }
1029}
Peter Maydell49b9bd42013-12-08 22:59:03 +00001030- (BOOL) isMouseGrabbed {return isMouseGrabbed;}
thsc304f7e2008-01-22 23:25:15 +00001031- (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
1032- (float) cdx {return cdx;}
1033- (float) cdy {return cdy;}
1034- (QEMUScreen) gscreen {return screen;}
John Arbuckle3b178b72015-09-25 23:14:00 +01001035
1036/*
1037 * Makes the target think all down keys are being released.
1038 * This prevents a stuck key problem, since we will not see
1039 * key up events for those keys after we have lost focus.
1040 */
1041- (void) raiseAllKeys
1042{
Peter Maydell31819e92019-02-25 10:24:27 +00001043 with_iothread_lock(^{
Akihiko Odaki6d73bb62021-03-10 23:46:02 +09001044 qkbd_state_lift_all_keys(kbd);
Peter Maydell31819e92019-02-25 10:24:27 +00001045 });
John Arbuckle3b178b72015-09-25 23:14:00 +01001046}
bellard5b0753e2005-03-01 21:37:28 +00001047@end
1048
1049
thsc304f7e2008-01-22 23:25:15 +00001050
bellard5b0753e2005-03-01 21:37:28 +00001051/*
1052 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +00001053 QemuCocoaAppController
bellard5b0753e2005-03-01 21:37:28 +00001054 ------------------------------------------------------
1055*/
thsc304f7e2008-01-22 23:25:15 +00001056@interface QemuCocoaAppController : NSObject
John Arbuckled9bc14f2015-09-25 23:13:59 +01001057 <NSWindowDelegate, NSApplicationDelegate>
bellard5b0753e2005-03-01 21:37:28 +00001058{
1059}
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001060- (void)doToggleFullScreen:(id)sender;
thsc304f7e2008-01-22 23:25:15 +00001061- (void)toggleFullScreen:(id)sender;
1062- (void)showQEMUDoc:(id)sender;
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001063- (void)zoomToFit:(id) sender;
Programmingkidb4c6a112015-05-19 09:11:18 +01001064- (void)displayConsole:(id)sender;
John Arbuckle8524f1c2015-06-19 10:53:27 +01001065- (void)pauseQEMU:(id)sender;
1066- (void)resumeQEMU:(id)sender;
1067- (void)displayPause;
1068- (void)removePause;
John Arbuckle27074612015-06-19 10:53:27 +01001069- (void)restartQEMU:(id)sender;
1070- (void)powerDownQEMU:(id)sender;
John Arbuckle693a3e02015-06-19 10:53:27 +01001071- (void)ejectDeviceMedia:(id)sender;
1072- (void)changeDeviceMedia:(id)sender;
John Arbuckled9bc14f2015-09-25 23:13:59 +01001073- (BOOL)verifyQuit;
John Arbucklef4747902016-03-23 14:26:17 +00001074- (void)openDocumentation:(NSString *)filename;
Programmingkid9e8204b2016-08-15 22:11:06 -04001075- (IBAction) do_about_menu_item: (id) sender;
1076- (void)make_about_window;
John Arbucklee47ec1a2017-06-13 23:17:38 -04001077- (void)adjustSpeed:(id)sender;
bellard5b0753e2005-03-01 21:37:28 +00001078@end
1079
thsc304f7e2008-01-22 23:25:15 +00001080@implementation QemuCocoaAppController
1081- (id) init
1082{
1083 COCOA_DEBUG("QemuCocoaAppController: init\n");
1084
1085 self = [super init];
1086 if (self) {
1087
1088 // create a view and add it to the window
1089 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1090 if(!cocoaView) {
Akihiko Odaki43137392021-02-23 22:11:06 +09001091 error_report("(cocoa) can't create a view");
thsc304f7e2008-01-22 23:25:15 +00001092 exit(1);
1093 }
1094
1095 // create a window
1096 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001097 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
thsc304f7e2008-01-22 23:25:15 +00001098 backing:NSBackingStoreBuffered defer:NO];
1099 if(!normalWindow) {
Akihiko Odaki43137392021-02-23 22:11:06 +09001100 error_report("(cocoa) can't create window");
thsc304f7e2008-01-22 23:25:15 +00001101 exit(1);
1102 }
1103 [normalWindow setAcceptsMouseMovedEvents:YES];
John Arbucklea1dbc052015-10-13 21:51:18 +01001104 [normalWindow setTitle:@"QEMU"];
thsc304f7e2008-01-22 23:25:15 +00001105 [normalWindow setContentView:cocoaView];
1106 [normalWindow makeKeyAndOrderFront:self];
Peter Maydell49060c22013-12-24 11:54:12 +00001107 [normalWindow center];
John Arbuckled9bc14f2015-09-25 23:13:59 +01001108 [normalWindow setDelegate: self];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001109 stretch_video = false;
John Arbuckle8524f1c2015-06-19 10:53:27 +01001110
1111 /* Used for displaying pause on the screen */
1112 pauseLabel = [NSTextField new];
1113 [pauseLabel setBezeled:YES];
1114 [pauseLabel setDrawsBackground:YES];
1115 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1116 [pauseLabel setEditable:NO];
1117 [pauseLabel setSelectable:NO];
1118 [pauseLabel setStringValue: @"Paused"];
1119 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1120 [pauseLabel setTextColor: [NSColor blackColor]];
1121 [pauseLabel sizeToFit];
John Arbuckle693a3e02015-06-19 10:53:27 +01001122
1123 // set the supported image file types that can be opened
1124 supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
John Arbuckle9d227f12016-03-30 12:37:11 -04001125 @"qcow", @"qcow2", @"cloop", @"vmdk", @"cdr",
Programmingkid5f26fcf2016-12-30 15:42:21 -05001126 @"toast", nil];
Programmingkid9e8204b2016-08-15 22:11:06 -04001127 [self make_about_window];
thsc304f7e2008-01-22 23:25:15 +00001128 }
1129 return self;
1130}
1131
1132- (void) dealloc
1133{
1134 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1135
1136 if (cocoaView)
1137 [cocoaView release];
1138 [super dealloc];
1139}
1140
bellard5b0753e2005-03-01 21:37:28 +00001141- (void)applicationDidFinishLaunching: (NSNotification *) note
1142{
thsc304f7e2008-01-22 23:25:15 +00001143 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
Hikaru Nishidadff742a2019-10-15 10:07:34 +09001144 allow_events = true;
Peter Maydell55888402019-02-25 10:24:33 +00001145 /* Tell cocoa_display_init to proceed */
1146 qemu_sem_post(&app_started_sem);
bellard5b0753e2005-03-01 21:37:28 +00001147}
1148
1149- (void)applicationWillTerminate:(NSNotification *)aNotification
1150{
thsc304f7e2008-01-22 23:25:15 +00001151 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1152
Eric Blakecf83f142017-05-15 16:41:13 -05001153 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
Akihiko Odaki40c01932021-02-19 20:16:52 +09001154
1155 /*
1156 * Sleep here, because returning will cause OSX to kill us
1157 * immediately; the QEMU main loop will handle the shutdown
1158 * request and terminate the process.
1159 */
1160 [NSThread sleepForTimeInterval:INFINITY];
bellard5b0753e2005-03-01 21:37:28 +00001161}
1162
Andreas Färber41ea49b2009-12-14 22:13:27 +01001163- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1164{
1165 return YES;
1166}
1167
John Arbuckled9bc14f2015-09-25 23:13:59 +01001168- (NSApplicationTerminateReply)applicationShouldTerminate:
1169 (NSApplication *)sender
1170{
1171 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1172 return [self verifyQuit];
1173}
1174
1175/* Called when the user clicks on a window's close button */
1176- (BOOL)windowShouldClose:(id)sender
1177{
1178 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1179 [NSApp terminate: sender];
1180 /* If the user allows the application to quit then the call to
1181 * NSApp terminate will never return. If we get here then the user
1182 * cancelled the quit, so we should return NO to not permit the
1183 * closing of this window.
1184 */
1185 return NO;
1186}
1187
John Arbuckle3b178b72015-09-25 23:14:00 +01001188/* Called when QEMU goes into the background */
1189- (void) applicationWillResignActive: (NSNotification *)aNotification
1190{
1191 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1192 [cocoaView raiseAllKeys];
1193}
1194
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001195/* We abstract the method called by the Enter Fullscreen menu item
1196 * because Mac OS 10.7 and higher disables it. This is because of the
1197 * menu item's old selector's name toggleFullScreen:
1198 */
1199- (void) doToggleFullScreen:(id)sender
1200{
1201 [self toggleFullScreen:(id)sender];
1202}
1203
thsc304f7e2008-01-22 23:25:15 +00001204- (void)toggleFullScreen:(id)sender
bellard5b0753e2005-03-01 21:37:28 +00001205{
thsc304f7e2008-01-22 23:25:15 +00001206 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1207
1208 [cocoaView toggleFullScreen:sender];
1209}
1210
John Arbucklef4747902016-03-23 14:26:17 +00001211/* Tries to find then open the specified filename */
1212- (void) openDocumentation: (NSString *) filename
1213{
1214 /* Where to look for local files */
Roman Bolshakov8d6fda82021-01-09 00:38:15 +03001215 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
John Arbucklef4747902016-03-23 14:26:17 +00001216 NSString *full_file_path;
Roman Bolshakov1ff5a062021-01-02 18:07:21 +03001217 NSURL *full_file_url;
John Arbucklef4747902016-03-23 14:26:17 +00001218
1219 /* iterate thru the possible paths until the file is found */
1220 int index;
1221 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1222 full_file_path = [[NSBundle mainBundle] executablePath];
1223 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1224 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1225 path_array[index], filename];
Roman Bolshakov1ff5a062021-01-02 18:07:21 +03001226 full_file_url = [NSURL fileURLWithPath: full_file_path
1227 isDirectory: false];
1228 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
John Arbucklef4747902016-03-23 14:26:17 +00001229 return;
1230 }
1231 }
1232
1233 /* If none of the paths opened a file */
1234 NSBeep();
1235 QEMU_Alert(@"Failed to open file");
1236}
1237
thsc304f7e2008-01-22 23:25:15 +00001238- (void)showQEMUDoc:(id)sender
1239{
1240 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1241
Peter Maydell1879f242020-02-28 15:36:16 +00001242 [self openDocumentation: @"index.html"];
thsc304f7e2008-01-22 23:25:15 +00001243}
1244
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001245/* Stretches video to fit host monitor size */
1246- (void)zoomToFit:(id) sender
1247{
1248 stretch_video = !stretch_video;
1249 if (stretch_video == true) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001250 [sender setState: NSControlStateValueOn];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001251 } else {
Brendan Shanks5e246002019-01-31 23:12:25 -08001252 [sender setState: NSControlStateValueOff];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001253 }
1254}
bellard5b0753e2005-03-01 21:37:28 +00001255
Programmingkidb4c6a112015-05-19 09:11:18 +01001256/* Displays the console on the screen */
1257- (void)displayConsole:(id)sender
1258{
1259 console_select([sender tag]);
1260}
John Arbuckle8524f1c2015-06-19 10:53:27 +01001261
1262/* Pause the guest */
1263- (void)pauseQEMU:(id)sender
1264{
Peter Maydell31819e92019-02-25 10:24:27 +00001265 with_iothread_lock(^{
1266 qmp_stop(NULL);
1267 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001268 [sender setEnabled: NO];
1269 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1270 [self displayPause];
1271}
1272
1273/* Resume running the guest operating system */
1274- (void)resumeQEMU:(id) sender
1275{
Peter Maydell31819e92019-02-25 10:24:27 +00001276 with_iothread_lock(^{
1277 qmp_cont(NULL);
1278 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001279 [sender setEnabled: NO];
1280 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1281 [self removePause];
1282}
1283
1284/* Displays the word pause on the screen */
1285- (void)displayPause
1286{
1287 /* Coordinates have to be calculated each time because the window can change its size */
1288 int xCoord, yCoord, width, height;
1289 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1290 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1291 width = [pauseLabel frame].size.width;
1292 height = [pauseLabel frame].size.height;
1293 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1294 [cocoaView addSubview: pauseLabel];
1295}
1296
1297/* Removes the word pause from the screen */
1298- (void)removePause
1299{
1300 [pauseLabel removeFromSuperview];
1301}
1302
John Arbuckle27074612015-06-19 10:53:27 +01001303/* Restarts QEMU */
1304- (void)restartQEMU:(id)sender
1305{
Peter Maydell31819e92019-02-25 10:24:27 +00001306 with_iothread_lock(^{
1307 qmp_system_reset(NULL);
1308 });
John Arbuckle27074612015-06-19 10:53:27 +01001309}
1310
1311/* Powers down QEMU */
1312- (void)powerDownQEMU:(id)sender
1313{
Peter Maydell31819e92019-02-25 10:24:27 +00001314 with_iothread_lock(^{
1315 qmp_system_powerdown(NULL);
1316 });
John Arbuckle27074612015-06-19 10:53:27 +01001317}
1318
John Arbuckle693a3e02015-06-19 10:53:27 +01001319/* Ejects the media.
1320 * Uses sender's tag to figure out the device to eject.
1321 */
1322- (void)ejectDeviceMedia:(id)sender
1323{
1324 NSString * drive;
1325 drive = [sender representedObject];
1326 if(drive == nil) {
1327 NSBeep();
1328 QEMU_Alert(@"Failed to find drive to eject!");
1329 return;
1330 }
1331
Peter Maydell31819e92019-02-25 10:24:27 +00001332 __block Error *err = NULL;
1333 with_iothread_lock(^{
1334 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1335 false, NULL, false, false, &err);
1336 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001337 handleAnyDeviceErrors(err);
1338}
1339
1340/* Displays a dialog box asking the user to select an image file to load.
1341 * Uses sender's represented object value to figure out which drive to use.
1342 */
1343- (void)changeDeviceMedia:(id)sender
1344{
1345 /* Find the drive name */
1346 NSString * drive;
1347 drive = [sender representedObject];
1348 if(drive == nil) {
1349 NSBeep();
1350 QEMU_Alert(@"Could not find drive!");
1351 return;
1352 }
1353
1354 /* Display the file open dialog */
1355 NSOpenPanel * openPanel;
1356 openPanel = [NSOpenPanel openPanel];
1357 [openPanel setCanChooseFiles: YES];
1358 [openPanel setAllowsMultipleSelection: NO];
1359 [openPanel setAllowedFileTypes: supportedImageFileTypes];
Peter Maydellb5725382018-05-29 19:15:23 +01001360 if([openPanel runModal] == NSModalResponseOK) {
John Arbuckle693a3e02015-06-19 10:53:27 +01001361 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1362 if(file == nil) {
1363 NSBeep();
1364 QEMU_Alert(@"Failed to convert URL to file path!");
1365 return;
1366 }
1367
Peter Maydell31819e92019-02-25 10:24:27 +00001368 __block Error *err = NULL;
1369 with_iothread_lock(^{
1370 qmp_blockdev_change_medium(true,
1371 [drive cStringUsingEncoding:
1372 NSASCIIStringEncoding],
1373 false, NULL,
1374 [file cStringUsingEncoding:
1375 NSASCIIStringEncoding],
1376 true, "raw",
1377 false, 0,
1378 &err);
1379 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001380 handleAnyDeviceErrors(err);
1381 }
1382}
1383
John Arbuckled9bc14f2015-09-25 23:13:59 +01001384/* Verifies if the user really wants to quit */
1385- (BOOL)verifyQuit
1386{
1387 NSAlert *alert = [NSAlert new];
1388 [alert autorelease];
1389 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1390 [alert addButtonWithTitle: @"Cancel"];
1391 [alert addButtonWithTitle: @"Quit"];
1392 if([alert runModal] == NSAlertSecondButtonReturn) {
1393 return YES;
1394 } else {
1395 return NO;
1396 }
1397}
1398
Programmingkid9e8204b2016-08-15 22:11:06 -04001399/* The action method for the About menu item */
1400- (IBAction) do_about_menu_item: (id) sender
1401{
1402 [about_window makeKeyAndOrderFront: nil];
1403}
1404
1405/* Create and display the about dialog */
1406- (void)make_about_window
1407{
1408 /* Make the window */
1409 int x = 0, y = 0, about_width = 400, about_height = 200;
1410 NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1411 about_window = [[NSWindow alloc] initWithContentRect:window_rect
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001412 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1413 NSWindowStyleMaskMiniaturizable
Programmingkid9e8204b2016-08-15 22:11:06 -04001414 backing:NSBackingStoreBuffered
1415 defer:NO];
1416 [about_window setTitle: @"About"];
1417 [about_window setReleasedWhenClosed: NO];
1418 [about_window center];
1419 NSView *superView = [about_window contentView];
1420
1421 /* Create the dimensions of the picture */
1422 int picture_width = 80, picture_height = 80;
1423 x = (about_width - picture_width)/2;
1424 y = about_height - picture_height - 10;
1425 NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1426
Programmingkid9e8204b2016-08-15 22:11:06 -04001427 /* Make the picture of QEMU */
1428 NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1429 picture_rect];
Akihiko Odakie31746e2021-03-09 21:22:25 +09001430 char *qemu_image_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1431 NSString *qemu_image_path = [NSString stringWithUTF8String:qemu_image_path_c];
1432 g_free(qemu_image_path_c);
1433 NSImage *qemu_image = [[NSImage alloc] initWithContentsOfFile:qemu_image_path];
Programmingkid9e8204b2016-08-15 22:11:06 -04001434 [picture_view setImage: qemu_image];
1435 [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1436 [superView addSubview: picture_view];
1437
1438 /* Make the name label */
Akihiko Odakia0f973f2021-03-09 21:22:26 +09001439 NSBundle *bundle = [NSBundle mainBundle];
1440 if (bundle) {
1441 x = 0;
1442 y = y - 25;
1443 int name_width = about_width, name_height = 20;
1444 NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1445 NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1446 [name_label setEditable: NO];
1447 [name_label setBezeled: NO];
1448 [name_label setDrawsBackground: NO];
1449 [name_label setAlignment: NSTextAlignmentCenter];
1450 NSString *qemu_name = [[bundle executablePath] lastPathComponent];
1451 [name_label setStringValue: qemu_name];
1452 [superView addSubview: name_label];
1453 }
Programmingkid9e8204b2016-08-15 22:11:06 -04001454
1455 /* Set the version label's attributes */
1456 x = 0;
1457 y = 50;
1458 int version_width = about_width, version_height = 20;
1459 NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1460 NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1461 version_rect];
1462 [version_label setEditable: NO];
1463 [version_label setBezeled: NO];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001464 [version_label setAlignment: NSTextAlignmentCenter];
Programmingkid9e8204b2016-08-15 22:11:06 -04001465 [version_label setDrawsBackground: NO];
1466
1467 /* Create the version string*/
1468 NSString *version_string;
1469 version_string = [[NSString alloc] initWithFormat:
Thomas Huth7e563bf2018-02-15 12:06:47 +01001470 @"QEMU emulator version %s", QEMU_FULL_VERSION];
Programmingkid9e8204b2016-08-15 22:11:06 -04001471 [version_label setStringValue: version_string];
1472 [superView addSubview: version_label];
1473
1474 /* Make copyright label */
1475 x = 0;
1476 y = 35;
1477 int copyright_width = about_width, copyright_height = 20;
1478 NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1479 NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1480 copyright_rect];
1481 [copyright_label setEditable: NO];
1482 [copyright_label setBezeled: NO];
1483 [copyright_label setDrawsBackground: NO];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001484 [copyright_label setAlignment: NSTextAlignmentCenter];
Programmingkid9e8204b2016-08-15 22:11:06 -04001485 [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1486 QEMU_COPYRIGHT]];
1487 [superView addSubview: copyright_label];
1488}
1489
John Arbucklee47ec1a2017-06-13 23:17:38 -04001490/* Used by the Speed menu items */
1491- (void)adjustSpeed:(id)sender
1492{
1493 int throttle_pct; /* throttle percentage */
1494 NSMenu *menu;
1495
1496 menu = [sender menu];
1497 if (menu != nil)
1498 {
1499 /* Unselect the currently selected item */
1500 for (NSMenuItem *item in [menu itemArray]) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001501 if (item.state == NSControlStateValueOn) {
1502 [item setState: NSControlStateValueOff];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001503 break;
1504 }
1505 }
1506 }
1507
1508 // check the menu item
Brendan Shanks5e246002019-01-31 23:12:25 -08001509 [sender setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001510
1511 // get the throttle percentage
1512 throttle_pct = [sender tag];
1513
Peter Maydell31819e92019-02-25 10:24:27 +00001514 with_iothread_lock(^{
1515 cpu_throttle_set(throttle_pct);
1516 });
John Arbucklee47ec1a2017-06-13 23:17:38 -04001517 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1518}
1519
Programmingkidb4c6a112015-05-19 09:11:18 +01001520@end
bellard5b0753e2005-03-01 21:37:28 +00001521
Peter Maydell61a2ed42019-02-25 10:24:32 +00001522@interface QemuApplication : NSApplication
1523@end
1524
1525@implementation QemuApplication
1526- (void)sendEvent:(NSEvent *)event
1527{
1528 COCOA_DEBUG("QemuApplication: sendEvent\n");
Peter Maydell55888402019-02-25 10:24:33 +00001529 if (![cocoaView handleEvent:event]) {
1530 [super sendEvent: event];
1531 }
Peter Maydell61a2ed42019-02-25 10:24:32 +00001532}
1533@end
1534
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001535static void create_initial_menus(void)
1536{
thsc304f7e2008-01-22 23:25:15 +00001537 // Add menus
1538 NSMenu *menu;
1539 NSMenuItem *menuItem;
1540
bellard5b0753e2005-03-01 21:37:28 +00001541 [NSApp setMainMenu:[[NSMenu alloc] init]];
bellard5b0753e2005-03-01 21:37:28 +00001542
thsc304f7e2008-01-22 23:25:15 +00001543 // Application menu
1544 menu = [[NSMenu alloc] initWithTitle:@""];
Programmingkid9e8204b2016-08-15 22:11:06 -04001545 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
thsc304f7e2008-01-22 23:25:15 +00001546 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1547 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1548 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001549 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
thsc304f7e2008-01-22 23:25:15 +00001550 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1551 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1552 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1553 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1554 [menuItem setSubmenu:menu];
1555 [[NSApp mainMenu] addItem:menuItem];
1556 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
ths3b46e622007-09-17 08:09:54 +00001557
John Arbuckle8524f1c2015-06-19 10:53:27 +01001558 // Machine menu
1559 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1560 [menu setAutoenablesItems: NO];
1561 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1562 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1563 [menu addItem: menuItem];
1564 [menuItem setEnabled: NO];
John Arbuckle27074612015-06-19 10:53:27 +01001565 [menu addItem: [NSMenuItem separatorItem]];
1566 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1567 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
John Arbuckle8524f1c2015-06-19 10:53:27 +01001568 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1569 [menuItem setSubmenu:menu];
1570 [[NSApp mainMenu] addItem:menuItem];
1571
thsc304f7e2008-01-22 23:25:15 +00001572 // View menu
1573 menu = [[NSMenu alloc] initWithTitle:@"View"];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001574 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1575 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
thsc304f7e2008-01-22 23:25:15 +00001576 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1577 [menuItem setSubmenu:menu];
1578 [[NSApp mainMenu] addItem:menuItem];
1579
John Arbucklee47ec1a2017-06-13 23:17:38 -04001580 // Speed menu
1581 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1582
1583 // Add the rest of the Speed menu items
1584 int p, percentage, throttle_pct;
1585 for (p = 10; p >= 0; p--)
1586 {
1587 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1588
1589 menuItem = [[[NSMenuItem alloc]
1590 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1591
1592 if (percentage == 100) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001593 [menuItem setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001594 }
1595
1596 /* Calculate the throttle percentage */
1597 throttle_pct = -1 * percentage + 100;
1598
1599 [menuItem setTag: throttle_pct];
1600 [menu addItem: menuItem];
1601 }
1602 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1603 [menuItem setSubmenu:menu];
1604 [[NSApp mainMenu] addItem:menuItem];
1605
thsc304f7e2008-01-22 23:25:15 +00001606 // Window menu
1607 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1608 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1609 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1610 [menuItem setSubmenu:menu];
1611 [[NSApp mainMenu] addItem:menuItem];
1612 [NSApp setWindowsMenu:menu];
1613
1614 // Help menu
1615 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1616 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
thsc304f7e2008-01-22 23:25:15 +00001617 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1618 [menuItem setSubmenu:menu];
1619 [[NSApp mainMenu] addItem:menuItem];
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001620}
1621
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001622/* Returns a name for a given console */
1623static NSString * getConsoleName(QemuConsole * console)
1624{
1625 return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1626}
1627
1628/* Add an entry to the View menu for each console */
1629static void add_console_menu_entries(void)
1630{
1631 NSMenu *menu;
1632 NSMenuItem *menuItem;
1633 int index = 0;
1634
1635 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1636
1637 [menu addItem:[NSMenuItem separatorItem]];
1638
1639 while (qemu_console_lookup_by_index(index) != NULL) {
1640 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1641 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1642 [menuItem setTag: index];
1643 [menu addItem: menuItem];
1644 index++;
1645 }
1646}
1647
1648/* Make menu items for all removable devices.
1649 * Each device is given an 'Eject' and 'Change' menu item.
1650 */
1651static void addRemovableDevicesMenuItems(void)
1652{
1653 NSMenu *menu;
1654 NSMenuItem *menuItem;
1655 BlockInfoList *currentDevice, *pointerToFree;
1656 NSString *deviceName;
1657
1658 currentDevice = qmp_query_block(NULL);
1659 pointerToFree = currentDevice;
1660 if(currentDevice == NULL) {
1661 NSBeep();
1662 QEMU_Alert(@"Failed to query for block devices!");
1663 return;
1664 }
1665
1666 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1667
1668 // Add a separator between related groups of menu items
1669 [menu addItem:[NSMenuItem separatorItem]];
1670
1671 // Set the attributes to the "Removable Media" menu item
1672 NSString *titleString = @"Removable Media";
1673 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1674 NSColor *newColor = [NSColor blackColor];
1675 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1676 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1677 traits:NSBoldFontMask|NSItalicFontMask
1678 weight:0
1679 size:14];
1680 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1681 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1682 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1683
1684 // Add the "Removable Media" menu item
1685 menuItem = [NSMenuItem new];
1686 [menuItem setAttributedTitle: attString];
1687 [menuItem setEnabled: NO];
1688 [menu addItem: menuItem];
1689
1690 /* Loop through all the block devices in the emulator */
1691 while (currentDevice) {
1692 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1693
1694 if(currentDevice->value->removable) {
1695 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1696 action: @selector(changeDeviceMedia:)
1697 keyEquivalent: @""];
1698 [menu addItem: menuItem];
1699 [menuItem setRepresentedObject: deviceName];
1700 [menuItem autorelease];
1701
1702 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1703 action: @selector(ejectDeviceMedia:)
1704 keyEquivalent: @""];
1705 [menu addItem: menuItem];
1706 [menuItem setRepresentedObject: deviceName];
1707 [menuItem autorelease];
1708 }
1709 currentDevice = currentDevice->next;
1710 }
1711 qapi_free_BlockInfoList(pointerToFree);
1712}
1713
Peter Maydell55888402019-02-25 10:24:33 +00001714/*
1715 * The startup process for the OSX/Cocoa UI is complicated, because
1716 * OSX insists that the UI runs on the initial main thread, and so we
1717 * need to start a second thread which runs the vl.c qemu_main():
1718 *
1719 * Initial thread: 2nd thread:
1720 * in main():
1721 * create qemu-main thread
1722 * wait on display_init semaphore
1723 * call qemu_main()
1724 * ...
1725 * in cocoa_display_init():
1726 * post the display_init semaphore
1727 * wait on app_started semaphore
1728 * create application, menus, etc
1729 * enter OSX run loop
1730 * in applicationDidFinishLaunching:
1731 * post app_started semaphore
1732 * tell main thread to fullscreen if needed
1733 * [...]
1734 * run qemu main-loop
1735 *
1736 * We do this in two stages so that we don't do the creation of the
1737 * GUI application menus and so on for command line options like --help
1738 * where we want to just print text to stdout and exit immediately.
1739 */
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001740
Peter Maydell55888402019-02-25 10:24:33 +00001741static void *call_qemu_main(void *opaque)
1742{
1743 int status;
1744
1745 COCOA_DEBUG("Second thread: calling qemu_main()\n");
1746 status = qemu_main(gArgc, gArgv, *_NSGetEnviron());
1747 COCOA_DEBUG("Second thread: qemu_main() returned, exiting\n");
1748 exit(status);
1749}
1750
1751int main (int argc, const char * argv[]) {
1752 QemuThread thread;
1753
1754 COCOA_DEBUG("Entered main()\n");
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001755 gArgc = argc;
1756 gArgv = (char **)argv;
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001757
Peter Maydell55888402019-02-25 10:24:33 +00001758 qemu_sem_init(&display_init_sem, 0);
1759 qemu_sem_init(&app_started_sem, 0);
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001760
Peter Maydell55888402019-02-25 10:24:33 +00001761 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1762 NULL, QEMU_THREAD_DETACHED);
1763
1764 COCOA_DEBUG("Main thread: waiting for display_init_sem\n");
1765 qemu_sem_wait(&display_init_sem);
1766 COCOA_DEBUG("Main thread: initializing app\n");
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001767
1768 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1769
1770 // Pull this console process up to being a fully-fledged graphical
1771 // app with a menubar and Dock icon
1772 ProcessSerialNumber psn = { 0, kCurrentProcess };
1773 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1774
Peter Maydell61a2ed42019-02-25 10:24:32 +00001775 [QemuApplication sharedApplication];
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001776
1777 create_initial_menus();
thsc304f7e2008-01-22 23:25:15 +00001778
Peter Maydell55888402019-02-25 10:24:33 +00001779 /*
1780 * Create the menu entries which depend on QEMU state (for consoles
1781 * and removeable devices). These make calls back into QEMU functions,
1782 * which is OK because at this point we know that the second thread
1783 * holds the iothread lock and is synchronously waiting for us to
1784 * finish.
1785 */
1786 add_console_menu_entries();
1787 addRemovableDevicesMenuItems();
1788
thsc304f7e2008-01-22 23:25:15 +00001789 // Create an Application controller
1790 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1791 [NSApp setDelegate:appController];
1792
1793 // Start the main event loop
Peter Maydell55888402019-02-25 10:24:33 +00001794 COCOA_DEBUG("Main thread: entering OSX run loop\n");
bellard5b0753e2005-03-01 21:37:28 +00001795 [NSApp run];
Peter Maydell55888402019-02-25 10:24:33 +00001796 COCOA_DEBUG("Main thread: left OSX run loop, exiting\n");
ths3b46e622007-09-17 08:09:54 +00001797
thsc304f7e2008-01-22 23:25:15 +00001798 [appController release];
bellard5b0753e2005-03-01 21:37:28 +00001799 [pool release];
bellardcae41b12006-05-22 21:25:04 +00001800
bellard5b0753e2005-03-01 21:37:28 +00001801 return 0;
1802}
thsc304f7e2008-01-22 23:25:15 +00001803
1804
1805
1806#pragma mark qemu
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001807static void cocoa_update(DisplayChangeListener *dcl,
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001808 int x, int y, int w, int h)
thsc304f7e2008-01-22 23:25:15 +00001809{
Peter Maydell6e657e62013-04-22 10:29:46 +00001810 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1811
thsc304f7e2008-01-22 23:25:15 +00001812 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1813
Peter Maydell55888402019-02-25 10:24:33 +00001814 dispatch_async(dispatch_get_main_queue(), ^{
1815 NSRect rect;
1816 if ([cocoaView cdx] == 1.0) {
1817 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1818 } else {
1819 rect = NSMakeRect(
1820 x * [cocoaView cdx],
1821 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1822 w * [cocoaView cdx],
1823 h * [cocoaView cdy]);
1824 }
1825 [cocoaView setNeedsDisplayInRect:rect];
1826 });
Peter Maydell6e657e62013-04-22 10:29:46 +00001827
1828 [pool release];
thsc304f7e2008-01-22 23:25:15 +00001829}
1830
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01001831static void cocoa_switch(DisplayChangeListener *dcl,
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01001832 DisplaySurface *surface)
thsc304f7e2008-01-22 23:25:15 +00001833{
Peter Maydell6e657e62013-04-22 10:29:46 +00001834 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Peter Maydell55888402019-02-25 10:24:33 +00001835 pixman_image_t *image = surface->image;
thsc304f7e2008-01-22 23:25:15 +00001836
Peter Maydell6e657e62013-04-22 10:29:46 +00001837 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
Peter Maydell55888402019-02-25 10:24:33 +00001838
1839 // The DisplaySurface will be freed as soon as this callback returns.
1840 // We take a reference to the underlying pixman image here so it does
1841 // not disappear from under our feet; the switchSurface method will
1842 // deref the old image when it is done with it.
1843 pixman_image_ref(image);
1844
1845 dispatch_async(dispatch_get_main_queue(), ^{
1846 [cocoaView switchSurface:image];
1847 });
Peter Maydell6e657e62013-04-22 10:29:46 +00001848 [pool release];
thsc304f7e2008-01-22 23:25:15 +00001849}
1850
Gerd Hoffmannbc2ed972013-03-01 13:03:04 +01001851static void cocoa_refresh(DisplayChangeListener *dcl)
thsc304f7e2008-01-22 23:25:15 +00001852{
Peter Maydell6e657e62013-04-22 10:29:46 +00001853 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1854
thsc304f7e2008-01-22 23:25:15 +00001855 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
John Arbuckle468a8952015-10-13 21:51:18 +01001856 graphic_hw_update(NULL);
thsc304f7e2008-01-22 23:25:15 +00001857
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001858 if (qemu_input_is_absolute()) {
Peter Maydell55888402019-02-25 10:24:33 +00001859 dispatch_async(dispatch_get_main_queue(), ^{
1860 if (![cocoaView isAbsoluteEnabled]) {
1861 if ([cocoaView isMouseGrabbed]) {
1862 [cocoaView ungrabMouse];
1863 }
thsc304f7e2008-01-22 23:25:15 +00001864 }
Peter Maydell55888402019-02-25 10:24:33 +00001865 [cocoaView setAbsoluteEnabled:YES];
1866 });
thsc304f7e2008-01-22 23:25:15 +00001867 }
Peter Maydell6e657e62013-04-22 10:29:46 +00001868 [pool release];
thsc304f7e2008-01-22 23:25:15 +00001869}
1870
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01001871static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
thsc304f7e2008-01-22 23:25:15 +00001872{
1873 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1874
Peter Maydell55888402019-02-25 10:24:33 +00001875 /* Tell main thread to go ahead and create the app and enter the run loop */
1876 qemu_sem_post(&display_init_sem);
1877 qemu_sem_wait(&app_started_sem);
1878 COCOA_DEBUG("cocoa_display_init: app start completed\n");
1879
Programmingkid43227af2015-05-19 09:11:17 +01001880 /* if fullscreen mode is to be used */
Gerd Hoffmann767f9bf2018-02-02 12:10:19 +01001881 if (opts->has_full_screen && opts->full_screen) {
Peter Maydell55888402019-02-25 10:24:33 +00001882 dispatch_async(dispatch_get_main_queue(), ^{
1883 [NSApp activateIgnoringOtherApps: YES];
1884 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1885 });
Programmingkid43227af2015-05-19 09:11:17 +01001886 }
Gerd Hoffmann3487da62020-02-06 12:27:50 +01001887 if (opts->has_show_cursor && opts->show_cursor) {
1888 cursor_hide = 0;
1889 }
Programmingkid43227af2015-05-19 09:11:17 +01001890
aliguori9794f742009-03-04 19:25:22 +00001891 // register vga output callbacks
Akihiko Odakicc7859c2021-02-19 17:44:19 +09001892 register_displaychangelistener(&dcl);
thsc304f7e2008-01-22 23:25:15 +00001893}
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01001894
1895static QemuDisplay qemu_display_cocoa = {
1896 .type = DISPLAY_TYPE_COCOA,
1897 .init = cocoa_display_init,
1898};
1899
1900static void register_cocoa(void)
1901{
1902 qemu_display_register(&qemu_display_cocoa);
1903}
1904
1905type_init(register_cocoa);