blob: 530c506489b281d0aa4866a96a5154cc4a76c4be [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
Akihiko Odaki15280e82021-06-16 23:19:10 +0900521- (void) updateUIInfo
522{
523 NSSize frameSize;
524 QemuUIInfo info;
525
526 if (!qemu_console_is_graphic(dcl.con)) {
527 return;
528 }
529
530 if ([self window]) {
531 NSDictionary *description = [[[self window] screen] deviceDescription];
532 CGDirectDisplayID display = [[description objectForKey:@"NSScreenNumber"] unsignedIntValue];
533 NSSize screenSize = [[[self window] screen] frame].size;
534 CGSize screenPhysicalSize = CGDisplayScreenSize(display);
535
536 frameSize = isFullscreen ? screenSize : [self frame].size;
537 info.width_mm = frameSize.width / screenSize.width * screenPhysicalSize.width;
538 info.height_mm = frameSize.height / screenSize.height * screenPhysicalSize.height;
539 } else {
540 frameSize = [self frame].size;
541 info.width_mm = 0;
542 info.height_mm = 0;
543 }
544
545 info.xoff = 0;
546 info.yoff = 0;
547 info.width = frameSize.width;
548 info.height = frameSize.height;
549
550 dpy_set_ui_info(dcl.con, &info);
551}
552
553- (void)viewDidMoveToWindow
554{
555 [self updateUIInfo];
556}
557
Peter Maydell72a3e312019-02-25 10:24:28 +0000558- (void) switchSurface:(pixman_image_t *)image
thsc304f7e2008-01-22 23:25:15 +0000559{
Gerd Hoffmann5e00d3a2013-03-01 12:52:06 +0100560 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
thsc304f7e2008-01-22 23:25:15 +0000561
Peter Maydell72a3e312019-02-25 10:24:28 +0000562 int w = pixman_image_get_width(image);
563 int h = pixman_image_get_height(image);
Peter Maydell381600d2014-06-23 10:35:22 +0100564 /* cdx == 0 means this is our very first surface, in which case we need
565 * to recalculate the content dimensions even if it happens to be the size
566 * of the initial empty window.
567 */
568 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
Peter Maydelld3345a02013-12-24 02:51:46 +0000569
570 int oldh = screen.height;
571 if (isResize) {
572 // Resize before we trigger the redraw, or we'll redraw at the wrong size
573 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
574 screen.width = w;
575 screen.height = h;
576 [self setContentDimensions];
577 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
578 }
Peter Maydell8510d912013-03-18 20:28:21 +0000579
thsc304f7e2008-01-22 23:25:15 +0000580 // update screenBuffer
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900581 if (pixman_image) {
Peter Maydell55888402019-02-25 10:24:33 +0000582 pixman_image_unref(pixman_image);
583 }
thsc304f7e2008-01-22 23:25:15 +0000584
Peter Maydell55888402019-02-25 10:24:33 +0000585 pixman_image = image;
thsc304f7e2008-01-22 23:25:15 +0000586
587 // update windows
588 if (isFullscreen) {
589 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
Peter Maydelld3345a02013-12-24 02:51:46 +0000590 [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 +0000591 } else {
592 if (qemu_name)
593 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
Peter Maydelld3345a02013-12-24 02:51:46 +0000594 [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 +0000595 }
Peter Maydelld3345a02013-12-24 02:51:46 +0000596
597 if (isResize) {
598 [normalWindow center];
599 }
thsc304f7e2008-01-22 23:25:15 +0000600}
601
602- (void) toggleFullScreen:(id)sender
603{
604 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
605
606 if (isFullscreen) { // switch from fullscreen to desktop
607 isFullscreen = FALSE;
608 [self ungrabMouse];
609 [self setContentDimensions];
Akihiko Odaki1e8b6f22021-02-20 10:31:38 +0900610 [fullScreenWindow close];
611 [normalWindow setContentView: self];
612 [normalWindow makeKeyAndOrderFront: self];
613 [NSMenu setMenuBarVisible:YES];
thsc304f7e2008-01-22 23:25:15 +0000614 } else { // switch from desktop to fullscreen
615 isFullscreen = TRUE;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100616 [normalWindow orderOut: nil]; /* Hide the window */
thsc304f7e2008-01-22 23:25:15 +0000617 [self grabMouse];
618 [self setContentDimensions];
Akihiko Odaki1e8b6f22021-02-20 10:31:38 +0900619 [NSMenu setMenuBarVisible:NO];
620 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
621 styleMask:NSWindowStyleMaskBorderless
622 backing:NSBackingStoreBuffered
623 defer:NO];
624 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
625 [fullScreenWindow setHasShadow:NO];
626 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
627 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
628 [[fullScreenWindow contentView] addSubview: self];
629 [fullScreenWindow makeKeyAndOrderFront:self];
thsc304f7e2008-01-22 23:25:15 +0000630 }
631}
632
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900633- (void) toggleKey: (int)keycode {
634 qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode));
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700635}
636
John Arbuckle9c3a4182017-11-07 10:14:14 +0000637// Does the work of sending input to the monitor
638- (void) handleMonitorInput:(NSEvent *)event
639{
640 int keysym = 0;
641 int control_key = 0;
642
643 // if the control key is down
644 if ([event modifierFlags] & NSEventModifierFlagControl) {
645 control_key = 1;
646 }
647
648 /* translates Macintosh keycodes to QEMU's keysym */
649
650 int without_control_translation[] = {
651 [0 ... 0xff] = 0, // invalid key
652
653 [kVK_UpArrow] = QEMU_KEY_UP,
654 [kVK_DownArrow] = QEMU_KEY_DOWN,
655 [kVK_RightArrow] = QEMU_KEY_RIGHT,
656 [kVK_LeftArrow] = QEMU_KEY_LEFT,
657 [kVK_Home] = QEMU_KEY_HOME,
658 [kVK_End] = QEMU_KEY_END,
659 [kVK_PageUp] = QEMU_KEY_PAGEUP,
660 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
661 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
662 [kVK_Delete] = QEMU_KEY_BACKSPACE,
663 };
664
665 int with_control_translation[] = {
666 [0 ... 0xff] = 0, // invalid key
667
668 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
669 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
670 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
671 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
672 [kVK_Home] = QEMU_KEY_CTRL_HOME,
673 [kVK_End] = QEMU_KEY_CTRL_END,
674 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
675 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
676 };
677
678 if (control_key != 0) { /* If the control key is being used */
679 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
680 keysym = with_control_translation[[event keyCode]];
681 }
682 } else {
683 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
684 keysym = without_control_translation[[event keyCode]];
685 }
686 }
687
688 // if not a key that needs translating
689 if (keysym == 0) {
690 NSString *ks = [event characters];
691 if ([ks length] > 0) {
692 keysym = [ks characterAtIndex:0];
693 }
694 }
695
696 if (keysym) {
697 kbd_put_keysym(keysym);
698 }
699}
700
Peter Maydell60105d72019-02-25 10:24:31 +0000701- (bool) handleEvent:(NSEvent *)event
thsc304f7e2008-01-22 23:25:15 +0000702{
Hikaru Nishidadff742a2019-10-15 10:07:34 +0900703 if(!allow_events) {
704 /*
705 * Just let OSX have all events that arrive before
706 * applicationDidFinishLaunching.
707 * This avoids a deadlock on the iothread lock, which cocoa_display_init()
708 * will not drop until after the app_started_sem is posted. (In theory
709 * there should not be any such events, but OSX Catalina now emits some.)
710 */
711 return false;
712 }
Peter Maydell60105d72019-02-25 10:24:31 +0000713 return bool_with_iothread_lock(^{
714 return [self handleEventLocked:event];
Peter Maydell31819e92019-02-25 10:24:27 +0000715 });
716}
thsc304f7e2008-01-22 23:25:15 +0000717
Peter Maydell60105d72019-02-25 10:24:31 +0000718- (bool) handleEventLocked:(NSEvent *)event
Peter Maydell31819e92019-02-25 10:24:27 +0000719{
Peter Maydell60105d72019-02-25 10:24:31 +0000720 /* Return true if we handled the event, false if it should be given to OSX */
Peter Maydell31819e92019-02-25 10:24:27 +0000721 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
thsc304f7e2008-01-22 23:25:15 +0000722 int buttons = 0;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700723 int keycode = 0;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100724 bool mouse_event = false;
John Arbuckle0c6c4392018-07-02 22:00:17 -0400725 static bool switched_to_fullscreen = false;
Chen Zhang2044dff2019-06-04 17:36:00 +0800726 // Location of event in virtual screen coordinates
727 NSPoint p = [self screenLocationOfEvent:event];
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900728 NSUInteger modifiers = [event modifierFlags];
729
Akihiko Odakiad7f2f82021-03-12 22:32:12 +0900730 /*
731 * Check -[NSEvent modifierFlags] here.
732 *
733 * There is a NSEventType for an event notifying the change of
734 * -[NSEvent modifierFlags], NSEventTypeFlagsChanged but these operations
735 * are performed for any events because a modifier state may change while
736 * the application is inactive (i.e. no events fire) and we don't want to
737 * wait for another modifier state change to detect such a change.
738 *
739 * NSEventModifierFlagCapsLock requires a special treatment. The other flags
740 * are handled in similar manners.
741 *
742 * NSEventModifierFlagCapsLock
743 * ---------------------------
744 *
745 * If CapsLock state is changed, "up" and "down" events will be fired in
746 * sequence, effectively updates CapsLock state on the guest.
747 *
748 * The other flags
749 * ---------------
750 *
751 * If a flag is not set, fire "up" events for all keys which correspond to
752 * the flag. Note that "down" events are not fired here because the flags
753 * checked here do not tell what exact keys are down.
754 *
755 * If one of the keys corresponding to a flag is down, we rely on
756 * -[NSEvent keyCode] of an event whose -[NSEvent type] is
757 * NSEventTypeFlagsChanged to know the exact key which is down, which has
758 * the following two downsides:
759 * - It does not work when the application is inactive as described above.
760 * - It malfactions *after* the modifier state is changed while the
761 * application is inactive. It is because -[NSEvent keyCode] does not tell
762 * if the key is up or down, and requires to infer the current state from
763 * the previous state. It is still possible to fix such a malfanction by
764 * completely leaving your hands from the keyboard, which hopefully makes
765 * this implementation usable enough.
766 */
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900767 if (!!(modifiers & NSEventModifierFlagCapsLock) !=
768 qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) {
769 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true);
770 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false);
771 }
772
773 if (!(modifiers & NSEventModifierFlagShift)) {
774 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false);
775 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false);
776 }
777 if (!(modifiers & NSEventModifierFlagControl)) {
778 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false);
779 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false);
780 }
781 if (!(modifiers & NSEventModifierFlagOption)) {
782 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
783 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
784 }
785 if (!(modifiers & NSEventModifierFlagCommand)) {
786 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
787 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
788 }
thsc304f7e2008-01-22 23:25:15 +0000789
790 switch ([event type]) {
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700791 case NSEventTypeFlagsChanged:
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900792 switch ([event keyCode]) {
793 case kVK_Shift:
794 if (!!(modifiers & NSEventModifierFlagShift)) {
795 [self toggleKey:Q_KEY_CODE_SHIFT];
796 }
797 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700798
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900799 case kVK_RightShift:
800 if (!!(modifiers & NSEventModifierFlagShift)) {
801 [self toggleKey:Q_KEY_CODE_SHIFT_R];
802 }
803 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700804
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900805 case kVK_Control:
806 if (!!(modifiers & NSEventModifierFlagControl)) {
807 [self toggleKey:Q_KEY_CODE_CTRL];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700808 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900809 break;
810
811 case kVK_RightControl:
812 if (!!(modifiers & NSEventModifierFlagControl)) {
813 [self toggleKey:Q_KEY_CODE_CTRL_R];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700814 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900815 break;
816
817 case kVK_Option:
818 if (!!(modifiers & NSEventModifierFlagOption)) {
819 [self toggleKey:Q_KEY_CODE_ALT];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700820 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900821 break;
822
823 case kVK_RightOption:
824 if (!!(modifiers & NSEventModifierFlagOption)) {
825 [self toggleKey:Q_KEY_CODE_ALT_R];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700826 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900827 break;
828
829 /* Don't pass command key changes to guest unless mouse is grabbed */
830 case kVK_Command:
831 if (isMouseGrabbed &&
832 !!(modifiers & NSEventModifierFlagCommand)) {
833 [self toggleKey:Q_KEY_CODE_META_L];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700834 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900835 break;
836
837 case kVK_RightCommand:
838 if (isMouseGrabbed &&
839 !!(modifiers & NSEventModifierFlagCommand)) {
840 [self toggleKey:Q_KEY_CODE_META_R];
841 }
842 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700843 }
thsc304f7e2008-01-22 23:25:15 +0000844 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700845 case NSEventTypeKeyDown:
Peter Maydell88959192013-12-08 22:59:02 +0000846 keycode = cocoa_keycode_to_qemu([event keyCode]);
thsc304f7e2008-01-22 23:25:15 +0000847
Peter Maydell88959192013-12-08 22:59:02 +0000848 // forward command key combos to the host UI unless the mouse is grabbed
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700849 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
John Arbuckle0c6c4392018-07-02 22:00:17 -0400850 /*
851 * Prevent the command key from being stuck down in the guest
852 * when using Command-F to switch to full screen mode.
853 */
854 if (keycode == Q_KEY_CODE_F) {
855 switched_to_fullscreen = true;
856 }
Peter Maydell60105d72019-02-25 10:24:31 +0000857 return false;
thsc304f7e2008-01-22 23:25:15 +0000858 }
859
860 // default
thsc304f7e2008-01-22 23:25:15 +0000861
John Arbuckle5929e362017-11-07 10:14:14 +0000862 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700863 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
John Arbuckle5929e362017-11-07 10:14:14 +0000864 NSString *keychar = [event charactersIgnoringModifiers];
865 if ([keychar length] == 1) {
866 char key = [keychar characterAtIndex:0];
867 switch (key) {
thsc304f7e2008-01-22 23:25:15 +0000868
John Arbuckle5929e362017-11-07 10:14:14 +0000869 // enable graphic console
870 case '1' ... '9':
871 console_select(key - '0' - 1); /* ascii math */
Peter Maydell60105d72019-02-25 10:24:31 +0000872 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000873
874 // release the mouse grab
875 case 'g':
876 [self ungrabMouse];
Peter Maydell60105d72019-02-25 10:24:31 +0000877 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000878 }
thsc304f7e2008-01-22 23:25:15 +0000879 }
Peter Maydellef2088f2017-11-07 10:14:14 +0000880 }
thsc304f7e2008-01-22 23:25:15 +0000881
Peter Maydellef2088f2017-11-07 10:14:14 +0000882 if (qemu_console_is_graphic(NULL)) {
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900883 qkbd_state_key_event(kbd, keycode, true);
thsc304f7e2008-01-22 23:25:15 +0000884 } else {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000885 [self handleMonitorInput: event];
thsc304f7e2008-01-22 23:25:15 +0000886 }
887 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700888 case NSEventTypeKeyUp:
thsc304f7e2008-01-22 23:25:15 +0000889 keycode = cocoa_keycode_to_qemu([event keyCode]);
Peter Maydell88959192013-12-08 22:59:02 +0000890
891 // don't pass the guest a spurious key-up if we treated this
892 // command-key combo as a host UI action
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700893 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
Peter Maydell60105d72019-02-25 10:24:31 +0000894 return true;
Peter Maydell88959192013-12-08 22:59:02 +0000895 }
896
Peter Maydell68c0aa62013-04-17 09:16:35 +0000897 if (qemu_console_is_graphic(NULL)) {
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900898 qkbd_state_key_event(kbd, keycode, false);
thsc304f7e2008-01-22 23:25:15 +0000899 }
900 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700901 case NSEventTypeMouseMoved:
thsc304f7e2008-01-22 23:25:15 +0000902 if (isAbsoluteEnabled) {
Chen Zhang2044dff2019-06-04 17:36:00 +0800903 // Cursor re-entered into a window might generate events bound to screen coordinates
904 // and `nil` window property, and in full screen mode, current window might not be
905 // key window, where event location alone should suffice.
906 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
Peter Maydellf61c3872014-06-23 10:35:24 +0100907 if (isMouseGrabbed) {
908 [self ungrabMouse];
thsc304f7e2008-01-22 23:25:15 +0000909 }
910 } else {
Peter Maydellf61c3872014-06-23 10:35:24 +0100911 if (!isMouseGrabbed) {
912 [self grabMouse];
thsc304f7e2008-01-22 23:25:15 +0000913 }
914 }
915 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100916 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000917 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700918 case NSEventTypeLeftMouseDown:
Akihiko Odaki4295f832021-02-12 09:07:06 +0900919 buttons |= MOUSE_EVENT_LBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100920 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000921 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700922 case NSEventTypeRightMouseDown:
thsc304f7e2008-01-22 23:25:15 +0000923 buttons |= MOUSE_EVENT_RBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100924 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000925 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700926 case NSEventTypeOtherMouseDown:
thsc304f7e2008-01-22 23:25:15 +0000927 buttons |= MOUSE_EVENT_MBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100928 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000929 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700930 case NSEventTypeLeftMouseDragged:
Akihiko Odaki4295f832021-02-12 09:07:06 +0900931 buttons |= MOUSE_EVENT_LBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100932 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000933 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700934 case NSEventTypeRightMouseDragged:
thsc304f7e2008-01-22 23:25:15 +0000935 buttons |= MOUSE_EVENT_RBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100936 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000937 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700938 case NSEventTypeOtherMouseDragged:
thsc304f7e2008-01-22 23:25:15 +0000939 buttons |= MOUSE_EVENT_MBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100940 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000941 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700942 case NSEventTypeLeftMouseUp:
Peter Maydellf61c3872014-06-23 10:35:24 +0100943 mouse_event = true;
944 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
Chen Zhang8e23e342019-06-04 17:36:48 +0800945 /*
946 * In fullscreen mode, the window of cocoaView may not be the
947 * key window, therefore the position relative to the virtual
948 * screen alone will be sufficient.
949 */
950 if(isFullscreen || [[self window] isKeyWindow]) {
Programmingkid9e8204b2016-08-15 22:11:06 -0400951 [self grabMouse];
952 }
thsc304f7e2008-01-22 23:25:15 +0000953 }
954 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700955 case NSEventTypeRightMouseUp:
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100956 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000957 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700958 case NSEventTypeOtherMouseUp:
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100959 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000960 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700961 case NSEventTypeScrollWheel:
John Arbuckleae7313e2018-01-08 13:07:07 -0500962 /*
963 * Send wheel events to the guest regardless of window focus.
964 * This is in-line with standard Mac OS X UI behaviour.
965 */
966
John Arbuckledc3c89d2018-07-09 11:02:35 -0400967 /*
968 * When deltaY is zero, it means that this scrolling event was
969 * either horizontal, or so fine that it only appears in
970 * scrollingDeltaY. So we drop the event.
971 */
972 if ([event deltaY] != 0) {
John Arbuckleae7313e2018-01-08 13:07:07 -0500973 /* Determine if this is a scroll up or scroll down event */
John Arbuckledc3c89d2018-07-09 11:02:35 -0400974 buttons = ([event deltaY] > 0) ?
975 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
Akihiko Odakicc7859c2021-02-19 17:44:19 +0900976 qemu_input_queue_btn(dcl.con, buttons, true);
John Arbuckledc3c89d2018-07-09 11:02:35 -0400977 qemu_input_event_sync();
Akihiko Odakicc7859c2021-02-19 17:44:19 +0900978 qemu_input_queue_btn(dcl.con, buttons, false);
John Arbuckledc3c89d2018-07-09 11:02:35 -0400979 qemu_input_event_sync();
980 }
John Arbuckleae7313e2018-01-08 13:07:07 -0500981 /*
982 * Since deltaY also reports scroll wheel events we prevent mouse
983 * movement code from executing.
984 */
985 mouse_event = false;
thsc304f7e2008-01-22 23:25:15 +0000986 break;
987 default:
Peter Maydell60105d72019-02-25 10:24:31 +0000988 return false;
thsc304f7e2008-01-22 23:25:15 +0000989 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100990
991 if (mouse_event) {
Peter Maydell8d3a5d92015-11-26 15:19:28 +0000992 /* Don't send button events to the guest unless we've got a
993 * mouse grab or window focus. If we have neither then this event
994 * is the user clicking on the background window to activate and
995 * bring us to the front, which will be done by the sendEvent
996 * call below. We definitely don't want to pass that click through
997 * to the guest.
998 */
999 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
1000 (last_buttons != buttons)) {
Eric Blake7fb1cf12015-11-18 01:52:57 -07001001 static uint32_t bmap[INPUT_BUTTON__MAX] = {
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001002 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1003 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
John Arbuckleae7313e2018-01-08 13:07:07 -05001004 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001005 };
Akihiko Odakicc7859c2021-02-19 17:44:19 +09001006 qemu_input_update_buttons(dcl.con, bmap, last_buttons, buttons);
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001007 last_buttons = buttons;
1008 }
Peter Maydellf61c3872014-06-23 10:35:24 +01001009 if (isMouseGrabbed) {
1010 if (isAbsoluteEnabled) {
1011 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
1012 * The check on screenContainsPoint is to avoid sending out of range values for
1013 * clicks in the titlebar.
1014 */
1015 if ([self screenContainsPoint:p]) {
Akihiko Odakicc7859c2021-02-19 17:44:19 +09001016 qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x, 0, screen.width);
1017 qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
Peter Maydellf61c3872014-06-23 10:35:24 +01001018 }
1019 } else {
Akihiko Odakicc7859c2021-02-19 17:44:19 +09001020 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, (int)[event deltaX]);
1021 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, (int)[event deltaY]);
Peter Maydellf61c3872014-06-23 10:35:24 +01001022 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001023 } else {
Peter Maydell60105d72019-02-25 10:24:31 +00001024 return false;
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001025 }
1026 qemu_input_event_sync();
1027 }
Peter Maydell60105d72019-02-25 10:24:31 +00001028 return true;
thsc304f7e2008-01-22 23:25:15 +00001029}
1030
1031- (void) grabMouse
1032{
1033 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
1034
1035 if (!isFullscreen) {
1036 if (qemu_name)
John Arbuckle5929e362017-11-07 10:14:14 +00001037 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
thsc304f7e2008-01-22 23:25:15 +00001038 else
John Arbuckle5929e362017-11-07 10:14:14 +00001039 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
thsc304f7e2008-01-22 23:25:15 +00001040 }
Peter Maydell13aefd32014-06-23 10:35:25 +01001041 [self hideCursor];
Akihiko Odakid1929062021-02-23 00:07:14 +09001042 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
Peter Maydell49b9bd42013-12-08 22:59:03 +00001043 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
thsc304f7e2008-01-22 23:25:15 +00001044}
1045
1046- (void) ungrabMouse
1047{
1048 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
1049
1050 if (!isFullscreen) {
1051 if (qemu_name)
1052 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
1053 else
1054 [normalWindow setTitle:@"QEMU"];
1055 }
Peter Maydell13aefd32014-06-23 10:35:25 +01001056 [self unhideCursor];
Akihiko Odakid1929062021-02-23 00:07:14 +09001057 CGAssociateMouseAndMouseCursorPosition(TRUE);
Peter Maydell49b9bd42013-12-08 22:59:03 +00001058 isMouseGrabbed = FALSE;
thsc304f7e2008-01-22 23:25:15 +00001059}
1060
Akihiko Odakid1929062021-02-23 00:07:14 +09001061- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {
1062 isAbsoluteEnabled = tIsAbsoluteEnabled;
1063 if (isMouseGrabbed) {
1064 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1065 }
1066}
Peter Maydell49b9bd42013-12-08 22:59:03 +00001067- (BOOL) isMouseGrabbed {return isMouseGrabbed;}
thsc304f7e2008-01-22 23:25:15 +00001068- (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
1069- (float) cdx {return cdx;}
1070- (float) cdy {return cdy;}
1071- (QEMUScreen) gscreen {return screen;}
John Arbuckle3b178b72015-09-25 23:14:00 +01001072
1073/*
1074 * Makes the target think all down keys are being released.
1075 * This prevents a stuck key problem, since we will not see
1076 * key up events for those keys after we have lost focus.
1077 */
1078- (void) raiseAllKeys
1079{
Peter Maydell31819e92019-02-25 10:24:27 +00001080 with_iothread_lock(^{
Akihiko Odaki6d73bb62021-03-10 23:46:02 +09001081 qkbd_state_lift_all_keys(kbd);
Peter Maydell31819e92019-02-25 10:24:27 +00001082 });
John Arbuckle3b178b72015-09-25 23:14:00 +01001083}
bellard5b0753e2005-03-01 21:37:28 +00001084@end
1085
1086
thsc304f7e2008-01-22 23:25:15 +00001087
bellard5b0753e2005-03-01 21:37:28 +00001088/*
1089 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +00001090 QemuCocoaAppController
bellard5b0753e2005-03-01 21:37:28 +00001091 ------------------------------------------------------
1092*/
thsc304f7e2008-01-22 23:25:15 +00001093@interface QemuCocoaAppController : NSObject
John Arbuckled9bc14f2015-09-25 23:13:59 +01001094 <NSWindowDelegate, NSApplicationDelegate>
bellard5b0753e2005-03-01 21:37:28 +00001095{
1096}
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001097- (void)doToggleFullScreen:(id)sender;
thsc304f7e2008-01-22 23:25:15 +00001098- (void)toggleFullScreen:(id)sender;
1099- (void)showQEMUDoc:(id)sender;
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001100- (void)zoomToFit:(id) sender;
Programmingkidb4c6a112015-05-19 09:11:18 +01001101- (void)displayConsole:(id)sender;
John Arbuckle8524f1c2015-06-19 10:53:27 +01001102- (void)pauseQEMU:(id)sender;
1103- (void)resumeQEMU:(id)sender;
1104- (void)displayPause;
1105- (void)removePause;
John Arbuckle27074612015-06-19 10:53:27 +01001106- (void)restartQEMU:(id)sender;
1107- (void)powerDownQEMU:(id)sender;
John Arbuckle693a3e02015-06-19 10:53:27 +01001108- (void)ejectDeviceMedia:(id)sender;
1109- (void)changeDeviceMedia:(id)sender;
John Arbuckled9bc14f2015-09-25 23:13:59 +01001110- (BOOL)verifyQuit;
John Arbucklef4747902016-03-23 14:26:17 +00001111- (void)openDocumentation:(NSString *)filename;
Programmingkid9e8204b2016-08-15 22:11:06 -04001112- (IBAction) do_about_menu_item: (id) sender;
1113- (void)make_about_window;
John Arbucklee47ec1a2017-06-13 23:17:38 -04001114- (void)adjustSpeed:(id)sender;
bellard5b0753e2005-03-01 21:37:28 +00001115@end
1116
thsc304f7e2008-01-22 23:25:15 +00001117@implementation QemuCocoaAppController
1118- (id) init
1119{
1120 COCOA_DEBUG("QemuCocoaAppController: init\n");
1121
1122 self = [super init];
1123 if (self) {
1124
1125 // create a view and add it to the window
1126 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1127 if(!cocoaView) {
Akihiko Odaki43137392021-02-23 22:11:06 +09001128 error_report("(cocoa) can't create a view");
thsc304f7e2008-01-22 23:25:15 +00001129 exit(1);
1130 }
1131
1132 // create a window
1133 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001134 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
thsc304f7e2008-01-22 23:25:15 +00001135 backing:NSBackingStoreBuffered defer:NO];
1136 if(!normalWindow) {
Akihiko Odaki43137392021-02-23 22:11:06 +09001137 error_report("(cocoa) can't create window");
thsc304f7e2008-01-22 23:25:15 +00001138 exit(1);
1139 }
1140 [normalWindow setAcceptsMouseMovedEvents:YES];
John Arbucklea1dbc052015-10-13 21:51:18 +01001141 [normalWindow setTitle:@"QEMU"];
thsc304f7e2008-01-22 23:25:15 +00001142 [normalWindow setContentView:cocoaView];
1143 [normalWindow makeKeyAndOrderFront:self];
Peter Maydell49060c22013-12-24 11:54:12 +00001144 [normalWindow center];
John Arbuckled9bc14f2015-09-25 23:13:59 +01001145 [normalWindow setDelegate: self];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001146 stretch_video = false;
John Arbuckle8524f1c2015-06-19 10:53:27 +01001147
1148 /* Used for displaying pause on the screen */
1149 pauseLabel = [NSTextField new];
1150 [pauseLabel setBezeled:YES];
1151 [pauseLabel setDrawsBackground:YES];
1152 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1153 [pauseLabel setEditable:NO];
1154 [pauseLabel setSelectable:NO];
1155 [pauseLabel setStringValue: @"Paused"];
1156 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1157 [pauseLabel setTextColor: [NSColor blackColor]];
1158 [pauseLabel sizeToFit];
John Arbuckle693a3e02015-06-19 10:53:27 +01001159
1160 // set the supported image file types that can be opened
1161 supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
John Arbuckle9d227f12016-03-30 12:37:11 -04001162 @"qcow", @"qcow2", @"cloop", @"vmdk", @"cdr",
Programmingkid5f26fcf2016-12-30 15:42:21 -05001163 @"toast", nil];
Programmingkid9e8204b2016-08-15 22:11:06 -04001164 [self make_about_window];
thsc304f7e2008-01-22 23:25:15 +00001165 }
1166 return self;
1167}
1168
1169- (void) dealloc
1170{
1171 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1172
1173 if (cocoaView)
1174 [cocoaView release];
1175 [super dealloc];
1176}
1177
bellard5b0753e2005-03-01 21:37:28 +00001178- (void)applicationDidFinishLaunching: (NSNotification *) note
1179{
thsc304f7e2008-01-22 23:25:15 +00001180 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
Hikaru Nishidadff742a2019-10-15 10:07:34 +09001181 allow_events = true;
Peter Maydell55888402019-02-25 10:24:33 +00001182 /* Tell cocoa_display_init to proceed */
1183 qemu_sem_post(&app_started_sem);
bellard5b0753e2005-03-01 21:37:28 +00001184}
1185
1186- (void)applicationWillTerminate:(NSNotification *)aNotification
1187{
thsc304f7e2008-01-22 23:25:15 +00001188 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1189
Eric Blakecf83f142017-05-15 16:41:13 -05001190 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
Akihiko Odaki40c01932021-02-19 20:16:52 +09001191
1192 /*
1193 * Sleep here, because returning will cause OSX to kill us
1194 * immediately; the QEMU main loop will handle the shutdown
1195 * request and terminate the process.
1196 */
1197 [NSThread sleepForTimeInterval:INFINITY];
bellard5b0753e2005-03-01 21:37:28 +00001198}
1199
Andreas Färber41ea49b2009-12-14 22:13:27 +01001200- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1201{
1202 return YES;
1203}
1204
John Arbuckled9bc14f2015-09-25 23:13:59 +01001205- (NSApplicationTerminateReply)applicationShouldTerminate:
1206 (NSApplication *)sender
1207{
1208 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1209 return [self verifyQuit];
1210}
1211
Akihiko Odaki15280e82021-06-16 23:19:10 +09001212- (void)windowDidChangeScreen:(NSNotification *)notification
1213{
1214 [cocoaView updateUIInfo];
1215}
1216
1217- (void)windowDidResize:(NSNotification *)notification
1218{
1219 [cocoaView updateUIInfo];
1220}
1221
John Arbuckled9bc14f2015-09-25 23:13:59 +01001222/* Called when the user clicks on a window's close button */
1223- (BOOL)windowShouldClose:(id)sender
1224{
1225 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1226 [NSApp terminate: sender];
1227 /* If the user allows the application to quit then the call to
1228 * NSApp terminate will never return. If we get here then the user
1229 * cancelled the quit, so we should return NO to not permit the
1230 * closing of this window.
1231 */
1232 return NO;
1233}
1234
John Arbuckle3b178b72015-09-25 23:14:00 +01001235/* Called when QEMU goes into the background */
1236- (void) applicationWillResignActive: (NSNotification *)aNotification
1237{
1238 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1239 [cocoaView raiseAllKeys];
1240}
1241
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001242/* We abstract the method called by the Enter Fullscreen menu item
1243 * because Mac OS 10.7 and higher disables it. This is because of the
1244 * menu item's old selector's name toggleFullScreen:
1245 */
1246- (void) doToggleFullScreen:(id)sender
1247{
1248 [self toggleFullScreen:(id)sender];
1249}
1250
thsc304f7e2008-01-22 23:25:15 +00001251- (void)toggleFullScreen:(id)sender
bellard5b0753e2005-03-01 21:37:28 +00001252{
thsc304f7e2008-01-22 23:25:15 +00001253 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1254
1255 [cocoaView toggleFullScreen:sender];
1256}
1257
John Arbucklef4747902016-03-23 14:26:17 +00001258/* Tries to find then open the specified filename */
1259- (void) openDocumentation: (NSString *) filename
1260{
1261 /* Where to look for local files */
Roman Bolshakov8d6fda82021-01-09 00:38:15 +03001262 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
John Arbucklef4747902016-03-23 14:26:17 +00001263 NSString *full_file_path;
Roman Bolshakov1ff5a062021-01-02 18:07:21 +03001264 NSURL *full_file_url;
John Arbucklef4747902016-03-23 14:26:17 +00001265
1266 /* iterate thru the possible paths until the file is found */
1267 int index;
1268 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1269 full_file_path = [[NSBundle mainBundle] executablePath];
1270 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1271 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1272 path_array[index], filename];
Roman Bolshakov1ff5a062021-01-02 18:07:21 +03001273 full_file_url = [NSURL fileURLWithPath: full_file_path
1274 isDirectory: false];
1275 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
John Arbucklef4747902016-03-23 14:26:17 +00001276 return;
1277 }
1278 }
1279
1280 /* If none of the paths opened a file */
1281 NSBeep();
1282 QEMU_Alert(@"Failed to open file");
1283}
1284
thsc304f7e2008-01-22 23:25:15 +00001285- (void)showQEMUDoc:(id)sender
1286{
1287 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1288
Peter Maydell1879f242020-02-28 15:36:16 +00001289 [self openDocumentation: @"index.html"];
thsc304f7e2008-01-22 23:25:15 +00001290}
1291
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001292/* Stretches video to fit host monitor size */
1293- (void)zoomToFit:(id) sender
1294{
1295 stretch_video = !stretch_video;
1296 if (stretch_video == true) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001297 [sender setState: NSControlStateValueOn];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001298 } else {
Brendan Shanks5e246002019-01-31 23:12:25 -08001299 [sender setState: NSControlStateValueOff];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001300 }
1301}
bellard5b0753e2005-03-01 21:37:28 +00001302
Programmingkidb4c6a112015-05-19 09:11:18 +01001303/* Displays the console on the screen */
1304- (void)displayConsole:(id)sender
1305{
1306 console_select([sender tag]);
1307}
John Arbuckle8524f1c2015-06-19 10:53:27 +01001308
1309/* Pause the guest */
1310- (void)pauseQEMU:(id)sender
1311{
Peter Maydell31819e92019-02-25 10:24:27 +00001312 with_iothread_lock(^{
1313 qmp_stop(NULL);
1314 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001315 [sender setEnabled: NO];
1316 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1317 [self displayPause];
1318}
1319
1320/* Resume running the guest operating system */
1321- (void)resumeQEMU:(id) sender
1322{
Peter Maydell31819e92019-02-25 10:24:27 +00001323 with_iothread_lock(^{
1324 qmp_cont(NULL);
1325 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001326 [sender setEnabled: NO];
1327 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1328 [self removePause];
1329}
1330
1331/* Displays the word pause on the screen */
1332- (void)displayPause
1333{
1334 /* Coordinates have to be calculated each time because the window can change its size */
1335 int xCoord, yCoord, width, height;
1336 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1337 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1338 width = [pauseLabel frame].size.width;
1339 height = [pauseLabel frame].size.height;
1340 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1341 [cocoaView addSubview: pauseLabel];
1342}
1343
1344/* Removes the word pause from the screen */
1345- (void)removePause
1346{
1347 [pauseLabel removeFromSuperview];
1348}
1349
John Arbuckle27074612015-06-19 10:53:27 +01001350/* Restarts QEMU */
1351- (void)restartQEMU:(id)sender
1352{
Peter Maydell31819e92019-02-25 10:24:27 +00001353 with_iothread_lock(^{
1354 qmp_system_reset(NULL);
1355 });
John Arbuckle27074612015-06-19 10:53:27 +01001356}
1357
1358/* Powers down QEMU */
1359- (void)powerDownQEMU:(id)sender
1360{
Peter Maydell31819e92019-02-25 10:24:27 +00001361 with_iothread_lock(^{
1362 qmp_system_powerdown(NULL);
1363 });
John Arbuckle27074612015-06-19 10:53:27 +01001364}
1365
John Arbuckle693a3e02015-06-19 10:53:27 +01001366/* Ejects the media.
1367 * Uses sender's tag to figure out the device to eject.
1368 */
1369- (void)ejectDeviceMedia:(id)sender
1370{
1371 NSString * drive;
1372 drive = [sender representedObject];
1373 if(drive == nil) {
1374 NSBeep();
1375 QEMU_Alert(@"Failed to find drive to eject!");
1376 return;
1377 }
1378
Peter Maydell31819e92019-02-25 10:24:27 +00001379 __block Error *err = NULL;
1380 with_iothread_lock(^{
1381 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1382 false, NULL, false, false, &err);
1383 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001384 handleAnyDeviceErrors(err);
1385}
1386
1387/* Displays a dialog box asking the user to select an image file to load.
1388 * Uses sender's represented object value to figure out which drive to use.
1389 */
1390- (void)changeDeviceMedia:(id)sender
1391{
1392 /* Find the drive name */
1393 NSString * drive;
1394 drive = [sender representedObject];
1395 if(drive == nil) {
1396 NSBeep();
1397 QEMU_Alert(@"Could not find drive!");
1398 return;
1399 }
1400
1401 /* Display the file open dialog */
1402 NSOpenPanel * openPanel;
1403 openPanel = [NSOpenPanel openPanel];
1404 [openPanel setCanChooseFiles: YES];
1405 [openPanel setAllowsMultipleSelection: NO];
1406 [openPanel setAllowedFileTypes: supportedImageFileTypes];
Peter Maydellb5725382018-05-29 19:15:23 +01001407 if([openPanel runModal] == NSModalResponseOK) {
John Arbuckle693a3e02015-06-19 10:53:27 +01001408 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1409 if(file == nil) {
1410 NSBeep();
1411 QEMU_Alert(@"Failed to convert URL to file path!");
1412 return;
1413 }
1414
Peter Maydell31819e92019-02-25 10:24:27 +00001415 __block Error *err = NULL;
1416 with_iothread_lock(^{
1417 qmp_blockdev_change_medium(true,
1418 [drive cStringUsingEncoding:
1419 NSASCIIStringEncoding],
1420 false, NULL,
1421 [file cStringUsingEncoding:
1422 NSASCIIStringEncoding],
1423 true, "raw",
1424 false, 0,
1425 &err);
1426 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001427 handleAnyDeviceErrors(err);
1428 }
1429}
1430
John Arbuckled9bc14f2015-09-25 23:13:59 +01001431/* Verifies if the user really wants to quit */
1432- (BOOL)verifyQuit
1433{
1434 NSAlert *alert = [NSAlert new];
1435 [alert autorelease];
1436 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1437 [alert addButtonWithTitle: @"Cancel"];
1438 [alert addButtonWithTitle: @"Quit"];
1439 if([alert runModal] == NSAlertSecondButtonReturn) {
1440 return YES;
1441 } else {
1442 return NO;
1443 }
1444}
1445
Programmingkid9e8204b2016-08-15 22:11:06 -04001446/* The action method for the About menu item */
1447- (IBAction) do_about_menu_item: (id) sender
1448{
1449 [about_window makeKeyAndOrderFront: nil];
1450}
1451
1452/* Create and display the about dialog */
1453- (void)make_about_window
1454{
1455 /* Make the window */
1456 int x = 0, y = 0, about_width = 400, about_height = 200;
1457 NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1458 about_window = [[NSWindow alloc] initWithContentRect:window_rect
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001459 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1460 NSWindowStyleMaskMiniaturizable
Programmingkid9e8204b2016-08-15 22:11:06 -04001461 backing:NSBackingStoreBuffered
1462 defer:NO];
1463 [about_window setTitle: @"About"];
1464 [about_window setReleasedWhenClosed: NO];
1465 [about_window center];
1466 NSView *superView = [about_window contentView];
1467
1468 /* Create the dimensions of the picture */
1469 int picture_width = 80, picture_height = 80;
1470 x = (about_width - picture_width)/2;
1471 y = about_height - picture_height - 10;
1472 NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1473
Programmingkid9e8204b2016-08-15 22:11:06 -04001474 /* Make the picture of QEMU */
1475 NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1476 picture_rect];
Akihiko Odakie31746e2021-03-09 21:22:25 +09001477 char *qemu_image_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1478 NSString *qemu_image_path = [NSString stringWithUTF8String:qemu_image_path_c];
1479 g_free(qemu_image_path_c);
1480 NSImage *qemu_image = [[NSImage alloc] initWithContentsOfFile:qemu_image_path];
Programmingkid9e8204b2016-08-15 22:11:06 -04001481 [picture_view setImage: qemu_image];
1482 [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1483 [superView addSubview: picture_view];
1484
1485 /* Make the name label */
Akihiko Odakia0f973f2021-03-09 21:22:26 +09001486 NSBundle *bundle = [NSBundle mainBundle];
1487 if (bundle) {
1488 x = 0;
1489 y = y - 25;
1490 int name_width = about_width, name_height = 20;
1491 NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1492 NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1493 [name_label setEditable: NO];
1494 [name_label setBezeled: NO];
1495 [name_label setDrawsBackground: NO];
1496 [name_label setAlignment: NSTextAlignmentCenter];
1497 NSString *qemu_name = [[bundle executablePath] lastPathComponent];
1498 [name_label setStringValue: qemu_name];
1499 [superView addSubview: name_label];
1500 }
Programmingkid9e8204b2016-08-15 22:11:06 -04001501
1502 /* Set the version label's attributes */
1503 x = 0;
1504 y = 50;
1505 int version_width = about_width, version_height = 20;
1506 NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1507 NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1508 version_rect];
1509 [version_label setEditable: NO];
1510 [version_label setBezeled: NO];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001511 [version_label setAlignment: NSTextAlignmentCenter];
Programmingkid9e8204b2016-08-15 22:11:06 -04001512 [version_label setDrawsBackground: NO];
1513
1514 /* Create the version string*/
1515 NSString *version_string;
1516 version_string = [[NSString alloc] initWithFormat:
Thomas Huth7e563bf2018-02-15 12:06:47 +01001517 @"QEMU emulator version %s", QEMU_FULL_VERSION];
Programmingkid9e8204b2016-08-15 22:11:06 -04001518 [version_label setStringValue: version_string];
1519 [superView addSubview: version_label];
1520
1521 /* Make copyright label */
1522 x = 0;
1523 y = 35;
1524 int copyright_width = about_width, copyright_height = 20;
1525 NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1526 NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1527 copyright_rect];
1528 [copyright_label setEditable: NO];
1529 [copyright_label setBezeled: NO];
1530 [copyright_label setDrawsBackground: NO];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001531 [copyright_label setAlignment: NSTextAlignmentCenter];
Programmingkid9e8204b2016-08-15 22:11:06 -04001532 [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1533 QEMU_COPYRIGHT]];
1534 [superView addSubview: copyright_label];
1535}
1536
John Arbucklee47ec1a2017-06-13 23:17:38 -04001537/* Used by the Speed menu items */
1538- (void)adjustSpeed:(id)sender
1539{
1540 int throttle_pct; /* throttle percentage */
1541 NSMenu *menu;
1542
1543 menu = [sender menu];
1544 if (menu != nil)
1545 {
1546 /* Unselect the currently selected item */
1547 for (NSMenuItem *item in [menu itemArray]) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001548 if (item.state == NSControlStateValueOn) {
1549 [item setState: NSControlStateValueOff];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001550 break;
1551 }
1552 }
1553 }
1554
1555 // check the menu item
Brendan Shanks5e246002019-01-31 23:12:25 -08001556 [sender setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001557
1558 // get the throttle percentage
1559 throttle_pct = [sender tag];
1560
Peter Maydell31819e92019-02-25 10:24:27 +00001561 with_iothread_lock(^{
1562 cpu_throttle_set(throttle_pct);
1563 });
John Arbucklee47ec1a2017-06-13 23:17:38 -04001564 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1565}
1566
Programmingkidb4c6a112015-05-19 09:11:18 +01001567@end
bellard5b0753e2005-03-01 21:37:28 +00001568
Peter Maydell61a2ed42019-02-25 10:24:32 +00001569@interface QemuApplication : NSApplication
1570@end
1571
1572@implementation QemuApplication
1573- (void)sendEvent:(NSEvent *)event
1574{
1575 COCOA_DEBUG("QemuApplication: sendEvent\n");
Peter Maydell55888402019-02-25 10:24:33 +00001576 if (![cocoaView handleEvent:event]) {
1577 [super sendEvent: event];
1578 }
Peter Maydell61a2ed42019-02-25 10:24:32 +00001579}
1580@end
1581
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001582static void create_initial_menus(void)
1583{
thsc304f7e2008-01-22 23:25:15 +00001584 // Add menus
1585 NSMenu *menu;
1586 NSMenuItem *menuItem;
1587
bellard5b0753e2005-03-01 21:37:28 +00001588 [NSApp setMainMenu:[[NSMenu alloc] init]];
bellard5b0753e2005-03-01 21:37:28 +00001589
thsc304f7e2008-01-22 23:25:15 +00001590 // Application menu
1591 menu = [[NSMenu alloc] initWithTitle:@""];
Programmingkid9e8204b2016-08-15 22:11:06 -04001592 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
thsc304f7e2008-01-22 23:25:15 +00001593 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1594 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1595 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001596 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
thsc304f7e2008-01-22 23:25:15 +00001597 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1598 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1599 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1600 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1601 [menuItem setSubmenu:menu];
1602 [[NSApp mainMenu] addItem:menuItem];
1603 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
ths3b46e622007-09-17 08:09:54 +00001604
John Arbuckle8524f1c2015-06-19 10:53:27 +01001605 // Machine menu
1606 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1607 [menu setAutoenablesItems: NO];
1608 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1609 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1610 [menu addItem: menuItem];
1611 [menuItem setEnabled: NO];
John Arbuckle27074612015-06-19 10:53:27 +01001612 [menu addItem: [NSMenuItem separatorItem]];
1613 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1614 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
John Arbuckle8524f1c2015-06-19 10:53:27 +01001615 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1616 [menuItem setSubmenu:menu];
1617 [[NSApp mainMenu] addItem:menuItem];
1618
thsc304f7e2008-01-22 23:25:15 +00001619 // View menu
1620 menu = [[NSMenu alloc] initWithTitle:@"View"];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001621 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1622 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
thsc304f7e2008-01-22 23:25:15 +00001623 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1624 [menuItem setSubmenu:menu];
1625 [[NSApp mainMenu] addItem:menuItem];
1626
John Arbucklee47ec1a2017-06-13 23:17:38 -04001627 // Speed menu
1628 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1629
1630 // Add the rest of the Speed menu items
1631 int p, percentage, throttle_pct;
1632 for (p = 10; p >= 0; p--)
1633 {
1634 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1635
1636 menuItem = [[[NSMenuItem alloc]
1637 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1638
1639 if (percentage == 100) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001640 [menuItem setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001641 }
1642
1643 /* Calculate the throttle percentage */
1644 throttle_pct = -1 * percentage + 100;
1645
1646 [menuItem setTag: throttle_pct];
1647 [menu addItem: menuItem];
1648 }
1649 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1650 [menuItem setSubmenu:menu];
1651 [[NSApp mainMenu] addItem:menuItem];
1652
thsc304f7e2008-01-22 23:25:15 +00001653 // Window menu
1654 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1655 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1656 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1657 [menuItem setSubmenu:menu];
1658 [[NSApp mainMenu] addItem:menuItem];
1659 [NSApp setWindowsMenu:menu];
1660
1661 // Help menu
1662 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1663 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
thsc304f7e2008-01-22 23:25:15 +00001664 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1665 [menuItem setSubmenu:menu];
1666 [[NSApp mainMenu] addItem:menuItem];
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001667}
1668
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001669/* Returns a name for a given console */
1670static NSString * getConsoleName(QemuConsole * console)
1671{
1672 return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1673}
1674
1675/* Add an entry to the View menu for each console */
1676static void add_console_menu_entries(void)
1677{
1678 NSMenu *menu;
1679 NSMenuItem *menuItem;
1680 int index = 0;
1681
1682 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1683
1684 [menu addItem:[NSMenuItem separatorItem]];
1685
1686 while (qemu_console_lookup_by_index(index) != NULL) {
1687 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1688 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1689 [menuItem setTag: index];
1690 [menu addItem: menuItem];
1691 index++;
1692 }
1693}
1694
1695/* Make menu items for all removable devices.
1696 * Each device is given an 'Eject' and 'Change' menu item.
1697 */
1698static void addRemovableDevicesMenuItems(void)
1699{
1700 NSMenu *menu;
1701 NSMenuItem *menuItem;
1702 BlockInfoList *currentDevice, *pointerToFree;
1703 NSString *deviceName;
1704
1705 currentDevice = qmp_query_block(NULL);
1706 pointerToFree = currentDevice;
1707 if(currentDevice == NULL) {
1708 NSBeep();
1709 QEMU_Alert(@"Failed to query for block devices!");
1710 return;
1711 }
1712
1713 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1714
1715 // Add a separator between related groups of menu items
1716 [menu addItem:[NSMenuItem separatorItem]];
1717
1718 // Set the attributes to the "Removable Media" menu item
1719 NSString *titleString = @"Removable Media";
1720 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1721 NSColor *newColor = [NSColor blackColor];
1722 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1723 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1724 traits:NSBoldFontMask|NSItalicFontMask
1725 weight:0
1726 size:14];
1727 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1728 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1729 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1730
1731 // Add the "Removable Media" menu item
1732 menuItem = [NSMenuItem new];
1733 [menuItem setAttributedTitle: attString];
1734 [menuItem setEnabled: NO];
1735 [menu addItem: menuItem];
1736
1737 /* Loop through all the block devices in the emulator */
1738 while (currentDevice) {
1739 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1740
1741 if(currentDevice->value->removable) {
1742 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1743 action: @selector(changeDeviceMedia:)
1744 keyEquivalent: @""];
1745 [menu addItem: menuItem];
1746 [menuItem setRepresentedObject: deviceName];
1747 [menuItem autorelease];
1748
1749 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1750 action: @selector(ejectDeviceMedia:)
1751 keyEquivalent: @""];
1752 [menu addItem: menuItem];
1753 [menuItem setRepresentedObject: deviceName];
1754 [menuItem autorelease];
1755 }
1756 currentDevice = currentDevice->next;
1757 }
1758 qapi_free_BlockInfoList(pointerToFree);
1759}
1760
Peter Maydell55888402019-02-25 10:24:33 +00001761/*
1762 * The startup process for the OSX/Cocoa UI is complicated, because
1763 * OSX insists that the UI runs on the initial main thread, and so we
1764 * need to start a second thread which runs the vl.c qemu_main():
1765 *
1766 * Initial thread: 2nd thread:
1767 * in main():
1768 * create qemu-main thread
1769 * wait on display_init semaphore
1770 * call qemu_main()
1771 * ...
1772 * in cocoa_display_init():
1773 * post the display_init semaphore
1774 * wait on app_started semaphore
1775 * create application, menus, etc
1776 * enter OSX run loop
1777 * in applicationDidFinishLaunching:
1778 * post app_started semaphore
1779 * tell main thread to fullscreen if needed
1780 * [...]
1781 * run qemu main-loop
1782 *
1783 * We do this in two stages so that we don't do the creation of the
1784 * GUI application menus and so on for command line options like --help
1785 * where we want to just print text to stdout and exit immediately.
1786 */
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001787
Peter Maydell55888402019-02-25 10:24:33 +00001788static void *call_qemu_main(void *opaque)
1789{
1790 int status;
1791
1792 COCOA_DEBUG("Second thread: calling qemu_main()\n");
1793 status = qemu_main(gArgc, gArgv, *_NSGetEnviron());
1794 COCOA_DEBUG("Second thread: qemu_main() returned, exiting\n");
1795 exit(status);
1796}
1797
1798int main (int argc, const char * argv[]) {
1799 QemuThread thread;
1800
1801 COCOA_DEBUG("Entered main()\n");
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001802 gArgc = argc;
1803 gArgv = (char **)argv;
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001804
Peter Maydell55888402019-02-25 10:24:33 +00001805 qemu_sem_init(&display_init_sem, 0);
1806 qemu_sem_init(&app_started_sem, 0);
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001807
Peter Maydell55888402019-02-25 10:24:33 +00001808 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1809 NULL, QEMU_THREAD_DETACHED);
1810
1811 COCOA_DEBUG("Main thread: waiting for display_init_sem\n");
1812 qemu_sem_wait(&display_init_sem);
1813 COCOA_DEBUG("Main thread: initializing app\n");
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001814
1815 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1816
1817 // Pull this console process up to being a fully-fledged graphical
1818 // app with a menubar and Dock icon
1819 ProcessSerialNumber psn = { 0, kCurrentProcess };
1820 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1821
Peter Maydell61a2ed42019-02-25 10:24:32 +00001822 [QemuApplication sharedApplication];
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001823
1824 create_initial_menus();
thsc304f7e2008-01-22 23:25:15 +00001825
Peter Maydell55888402019-02-25 10:24:33 +00001826 /*
1827 * Create the menu entries which depend on QEMU state (for consoles
1828 * and removeable devices). These make calls back into QEMU functions,
1829 * which is OK because at this point we know that the second thread
1830 * holds the iothread lock and is synchronously waiting for us to
1831 * finish.
1832 */
1833 add_console_menu_entries();
1834 addRemovableDevicesMenuItems();
1835
thsc304f7e2008-01-22 23:25:15 +00001836 // Create an Application controller
1837 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1838 [NSApp setDelegate:appController];
1839
1840 // Start the main event loop
Peter Maydell55888402019-02-25 10:24:33 +00001841 COCOA_DEBUG("Main thread: entering OSX run loop\n");
bellard5b0753e2005-03-01 21:37:28 +00001842 [NSApp run];
Peter Maydell55888402019-02-25 10:24:33 +00001843 COCOA_DEBUG("Main thread: left OSX run loop, exiting\n");
ths3b46e622007-09-17 08:09:54 +00001844
thsc304f7e2008-01-22 23:25:15 +00001845 [appController release];
bellard5b0753e2005-03-01 21:37:28 +00001846 [pool release];
bellardcae41b12006-05-22 21:25:04 +00001847
bellard5b0753e2005-03-01 21:37:28 +00001848 return 0;
1849}
thsc304f7e2008-01-22 23:25:15 +00001850
1851
1852
1853#pragma mark qemu
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001854static void cocoa_update(DisplayChangeListener *dcl,
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001855 int x, int y, int w, int h)
thsc304f7e2008-01-22 23:25:15 +00001856{
Peter Maydell6e657e62013-04-22 10:29:46 +00001857 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1858
thsc304f7e2008-01-22 23:25:15 +00001859 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1860
Peter Maydell55888402019-02-25 10:24:33 +00001861 dispatch_async(dispatch_get_main_queue(), ^{
1862 NSRect rect;
1863 if ([cocoaView cdx] == 1.0) {
1864 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1865 } else {
1866 rect = NSMakeRect(
1867 x * [cocoaView cdx],
1868 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1869 w * [cocoaView cdx],
1870 h * [cocoaView cdy]);
1871 }
1872 [cocoaView setNeedsDisplayInRect:rect];
1873 });
Peter Maydell6e657e62013-04-22 10:29:46 +00001874
1875 [pool release];
thsc304f7e2008-01-22 23:25:15 +00001876}
1877
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01001878static void cocoa_switch(DisplayChangeListener *dcl,
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01001879 DisplaySurface *surface)
thsc304f7e2008-01-22 23:25:15 +00001880{
Peter Maydell6e657e62013-04-22 10:29:46 +00001881 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Peter Maydell55888402019-02-25 10:24:33 +00001882 pixman_image_t *image = surface->image;
thsc304f7e2008-01-22 23:25:15 +00001883
Peter Maydell6e657e62013-04-22 10:29:46 +00001884 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
Peter Maydell55888402019-02-25 10:24:33 +00001885
Akihiko Odaki15280e82021-06-16 23:19:10 +09001886 [cocoaView updateUIInfo];
1887
Peter Maydell55888402019-02-25 10:24:33 +00001888 // The DisplaySurface will be freed as soon as this callback returns.
1889 // We take a reference to the underlying pixman image here so it does
1890 // not disappear from under our feet; the switchSurface method will
1891 // deref the old image when it is done with it.
1892 pixman_image_ref(image);
1893
1894 dispatch_async(dispatch_get_main_queue(), ^{
1895 [cocoaView switchSurface:image];
1896 });
Peter Maydell6e657e62013-04-22 10:29:46 +00001897 [pool release];
thsc304f7e2008-01-22 23:25:15 +00001898}
1899
Gerd Hoffmannbc2ed972013-03-01 13:03:04 +01001900static void cocoa_refresh(DisplayChangeListener *dcl)
thsc304f7e2008-01-22 23:25:15 +00001901{
Peter Maydell6e657e62013-04-22 10:29:46 +00001902 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1903
thsc304f7e2008-01-22 23:25:15 +00001904 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
John Arbuckle468a8952015-10-13 21:51:18 +01001905 graphic_hw_update(NULL);
thsc304f7e2008-01-22 23:25:15 +00001906
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001907 if (qemu_input_is_absolute()) {
Peter Maydell55888402019-02-25 10:24:33 +00001908 dispatch_async(dispatch_get_main_queue(), ^{
1909 if (![cocoaView isAbsoluteEnabled]) {
1910 if ([cocoaView isMouseGrabbed]) {
1911 [cocoaView ungrabMouse];
1912 }
thsc304f7e2008-01-22 23:25:15 +00001913 }
Peter Maydell55888402019-02-25 10:24:33 +00001914 [cocoaView setAbsoluteEnabled:YES];
1915 });
thsc304f7e2008-01-22 23:25:15 +00001916 }
Peter Maydell6e657e62013-04-22 10:29:46 +00001917 [pool release];
thsc304f7e2008-01-22 23:25:15 +00001918}
1919
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01001920static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
thsc304f7e2008-01-22 23:25:15 +00001921{
1922 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1923
Peter Maydell55888402019-02-25 10:24:33 +00001924 /* Tell main thread to go ahead and create the app and enter the run loop */
1925 qemu_sem_post(&display_init_sem);
1926 qemu_sem_wait(&app_started_sem);
1927 COCOA_DEBUG("cocoa_display_init: app start completed\n");
1928
Programmingkid43227af2015-05-19 09:11:17 +01001929 /* if fullscreen mode is to be used */
Gerd Hoffmann767f9bf2018-02-02 12:10:19 +01001930 if (opts->has_full_screen && opts->full_screen) {
Peter Maydell55888402019-02-25 10:24:33 +00001931 dispatch_async(dispatch_get_main_queue(), ^{
1932 [NSApp activateIgnoringOtherApps: YES];
1933 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1934 });
Programmingkid43227af2015-05-19 09:11:17 +01001935 }
Gerd Hoffmann3487da62020-02-06 12:27:50 +01001936 if (opts->has_show_cursor && opts->show_cursor) {
1937 cursor_hide = 0;
1938 }
Programmingkid43227af2015-05-19 09:11:17 +01001939
aliguori9794f742009-03-04 19:25:22 +00001940 // register vga output callbacks
Akihiko Odakicc7859c2021-02-19 17:44:19 +09001941 register_displaychangelistener(&dcl);
thsc304f7e2008-01-22 23:25:15 +00001942}
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01001943
1944static QemuDisplay qemu_display_cocoa = {
1945 .type = DISPLAY_TYPE_COCOA,
1946 .init = cocoa_display_init,
1947};
1948
1949static void register_cocoa(void)
1950{
1951 qemu_display_register(&qemu_display_cocoa);
1952}
1953
1954type_init(register_cocoa);