blob: 3efa8ac1a9f171c4d0803bfe63742c860877ca24 [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
Marc-André Lureau49f95222022-04-20 17:25:49 +040030#include "qemu/help-texts.h"
Marc-André Lureau88c39c82022-04-20 17:25:47 +040031#include "qemu-main.h"
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +090032#include "ui/clipboard.h"
Paolo Bonzini28ecbae2012-11-28 12:06:30 +010033#include "ui/console.h"
Gerd Hoffmann21bae112013-12-04 14:08:04 +010034#include "ui/input.h"
Akihiko Odaki6d73bb62021-03-10 23:46:02 +090035#include "ui/kbd-state.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010036#include "sysemu/sysemu.h"
Markus Armbruster54d31232019-08-12 07:23:59 +020037#include "sysemu/runstate.h"
Akihiko Odaki2910abd2022-05-29 17:25:08 +090038#include "sysemu/runstate-action.h"
Claudio Fontanab0c3cf92020-06-29 11:35:03 +020039#include "sysemu/cpu-throttle.h"
Markus Armbrustere688df62018-02-01 12:18:31 +010040#include "qapi/error.h"
Markus Armbruster16bf5232018-12-20 09:45:59 +010041#include "qapi/qapi-commands-block.h"
Philippe Mathieu-Daudé90f8c0f2020-10-12 14:15:33 +020042#include "qapi/qapi-commands-machine.h"
Markus Armbruster16bf5232018-12-20 09:45:59 +010043#include "qapi/qapi-commands-misc.h"
John Arbuckle693a3e02015-06-19 10:53:27 +010044#include "sysemu/blockdev.h"
Programmingkid9e8204b2016-08-15 22:11:06 -040045#include "qemu-version.h"
Akihiko Odakie31746e2021-03-09 21:22:25 +090046#include "qemu/cutils.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020047#include "qemu/main-loop.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020048#include "qemu/module.h"
Richard Hendersoncc37d982023-03-15 17:43:13 +000049#include "qemu/error-report.h"
John Arbuckleaaac7142016-03-23 14:26:18 +000050#include <Carbon/Carbon.h>
Markus Armbruster2e5b09f2019-07-09 17:20:52 +020051#include "hw/core/cpu.h"
bellardda4dbf72005-03-02 22:22:43 +000052
Brendan Shanks5e246002019-01-31 23:12:25 -080053#ifndef MAC_OS_X_VERSION_10_13
54#define MAC_OS_X_VERSION_10_13 101300
55#endif
Andreas Färber44e4c0b2009-12-13 00:45:40 +010056
David Parsonsf5af8022024-02-24 14:06:20 +000057#ifndef MAC_OS_VERSION_14_0
58#define MAC_OS_VERSION_14_0 140000
59#endif
60
Brendan Shanks5e246002019-01-31 23:12:25 -080061/* 10.14 deprecates NSOnState and NSOffState in favor of
62 * NSControlStateValueOn/Off, which were introduced in 10.13.
63 * Define for older versions
64 */
65#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
66#define NSControlStateValueOn NSOnState
67#define NSControlStateValueOff NSOffState
68#endif
bellard5b0753e2005-03-01 21:37:28 +000069
thsc304f7e2008-01-22 23:25:15 +000070//#define DEBUG
71
72#ifdef DEBUG
73#define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
74#else
75#define COCOA_DEBUG(...) ((void) 0)
76#endif
77
78#define cgrect(nsrect) (*(CGRect *)&(nsrect))
thsc304f7e2008-01-22 23:25:15 +000079
Christian Schoenebeck23bdd0d2022-12-27 17:15:31 +010080#define UC_CTRL_KEY "\xe2\x8c\x83"
81#define UC_ALT_KEY "\xe2\x8c\xa5"
82
thsc304f7e2008-01-22 23:25:15 +000083typedef struct {
84 int width;
85 int height;
thsc304f7e2008-01-22 23:25:15 +000086} QEMUScreen;
87
Akihiko Odakicc7859c2021-02-19 17:44:19 +090088static void cocoa_update(DisplayChangeListener *dcl,
89 int x, int y, int w, int h);
90
91static void cocoa_switch(DisplayChangeListener *dcl,
92 DisplaySurface *surface);
93
94static void cocoa_refresh(DisplayChangeListener *dcl);
95
Akihiko Odakicc7859c2021-02-19 17:44:19 +090096static const DisplayChangeListenerOps dcl_ops = {
97 .dpy_name = "cocoa",
98 .dpy_gfx_update = cocoa_update,
99 .dpy_gfx_switch = cocoa_switch,
100 .dpy_refresh = cocoa_refresh,
101};
102static DisplayChangeListener dcl = {
103 .ops = &dcl_ops,
104};
Akihiko Odakica3de7b2024-03-19 12:08:41 +0900105static QKbdState *kbd;
Gerd Hoffmann3487da62020-02-06 12:27:50 +0100106static int cursor_hide = 1;
Carwyn Ellis48941a52022-01-02 17:41:52 +0000107static int left_command_key_enabled = 1;
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900108static bool swap_opt_cmd;
bellard5b0753e2005-03-01 21:37:28 +0000109
Carwyn Ellise28a9092023-11-10 16:17:29 +0000110static CGInterpolationQuality zoom_interpolation = kCGInterpolationNone;
Akihiko Odakicb823402021-02-25 17:42:02 +0900111static NSTextField *pauseLabel;
bellard5b0753e2005-03-01 21:37:28 +0000112
Hikaru Nishidadff742a2019-10-15 10:07:34 +0900113static bool allow_events;
Peter Maydell55888402019-02-25 10:24:33 +0000114
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +0900115static NSInteger cbchangecount = -1;
116static QemuClipboardInfo *cbinfo;
117static QemuEvent cbevent;
118
Stefan Hajnoczia4a411f2024-01-02 10:35:28 -0500119// Utility functions to run specified code block with the BQL held
Peter Maydell31819e92019-02-25 10:24:27 +0000120typedef void (^CodeBlock)(void);
Peter Maydell60105d72019-02-25 10:24:31 +0000121typedef bool (^BoolCodeBlock)(void);
Peter Maydell31819e92019-02-25 10:24:27 +0000122
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500123static void with_bql(CodeBlock block)
Peter Maydell31819e92019-02-25 10:24:27 +0000124{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500125 bool locked = bql_locked();
Peter Maydell31819e92019-02-25 10:24:27 +0000126 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500127 bql_lock();
Peter Maydell31819e92019-02-25 10:24:27 +0000128 }
129 block();
130 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500131 bql_unlock();
Peter Maydell31819e92019-02-25 10:24:27 +0000132 }
133}
134
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500135static bool bool_with_bql(BoolCodeBlock block)
Peter Maydell60105d72019-02-25 10:24:31 +0000136{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500137 bool locked = bql_locked();
Peter Maydell60105d72019-02-25 10:24:31 +0000138 bool val;
139
140 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500141 bql_lock();
Peter Maydell60105d72019-02-25 10:24:31 +0000142 }
143 val = block();
144 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500145 bql_unlock();
Peter Maydell60105d72019-02-25 10:24:31 +0000146 }
147 return val;
148}
149
John Arbuckleaaac7142016-03-23 14:26:18 +0000150// Mac to QKeyCode conversion
Akihiko Odakicb823402021-02-25 17:42:02 +0900151static const int mac_to_qkeycode_map[] = {
John Arbuckleaaac7142016-03-23 14:26:18 +0000152 [kVK_ANSI_A] = Q_KEY_CODE_A,
153 [kVK_ANSI_B] = Q_KEY_CODE_B,
154 [kVK_ANSI_C] = Q_KEY_CODE_C,
155 [kVK_ANSI_D] = Q_KEY_CODE_D,
156 [kVK_ANSI_E] = Q_KEY_CODE_E,
157 [kVK_ANSI_F] = Q_KEY_CODE_F,
158 [kVK_ANSI_G] = Q_KEY_CODE_G,
159 [kVK_ANSI_H] = Q_KEY_CODE_H,
160 [kVK_ANSI_I] = Q_KEY_CODE_I,
161 [kVK_ANSI_J] = Q_KEY_CODE_J,
162 [kVK_ANSI_K] = Q_KEY_CODE_K,
163 [kVK_ANSI_L] = Q_KEY_CODE_L,
164 [kVK_ANSI_M] = Q_KEY_CODE_M,
165 [kVK_ANSI_N] = Q_KEY_CODE_N,
166 [kVK_ANSI_O] = Q_KEY_CODE_O,
167 [kVK_ANSI_P] = Q_KEY_CODE_P,
168 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
169 [kVK_ANSI_R] = Q_KEY_CODE_R,
170 [kVK_ANSI_S] = Q_KEY_CODE_S,
171 [kVK_ANSI_T] = Q_KEY_CODE_T,
172 [kVK_ANSI_U] = Q_KEY_CODE_U,
173 [kVK_ANSI_V] = Q_KEY_CODE_V,
174 [kVK_ANSI_W] = Q_KEY_CODE_W,
175 [kVK_ANSI_X] = Q_KEY_CODE_X,
176 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
177 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
ths3b46e622007-09-17 08:09:54 +0000178
John Arbuckleaaac7142016-03-23 14:26:18 +0000179 [kVK_ANSI_0] = Q_KEY_CODE_0,
180 [kVK_ANSI_1] = Q_KEY_CODE_1,
181 [kVK_ANSI_2] = Q_KEY_CODE_2,
182 [kVK_ANSI_3] = Q_KEY_CODE_3,
183 [kVK_ANSI_4] = Q_KEY_CODE_4,
184 [kVK_ANSI_5] = Q_KEY_CODE_5,
185 [kVK_ANSI_6] = Q_KEY_CODE_6,
186 [kVK_ANSI_7] = Q_KEY_CODE_7,
187 [kVK_ANSI_8] = Q_KEY_CODE_8,
188 [kVK_ANSI_9] = Q_KEY_CODE_9,
189
190 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
191 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
192 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
193 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
194 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
195 [kVK_Tab] = Q_KEY_CODE_TAB,
196 [kVK_Return] = Q_KEY_CODE_RET,
197 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
198 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
199 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
200 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
201 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
202 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
203 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
204 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
John Arbuckleaaac7142016-03-23 14:26:18 +0000205 [kVK_Space] = Q_KEY_CODE_SPC,
206
207 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
208 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
209 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
210 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
211 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
212 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
213 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
214 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
215 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
216 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
217 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
218 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
219 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
220 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
221 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
222 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
223 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
224 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
225
226 [kVK_UpArrow] = Q_KEY_CODE_UP,
227 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
228 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
229 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
230
231 [kVK_Help] = Q_KEY_CODE_INSERT,
232 [kVK_Home] = Q_KEY_CODE_HOME,
233 [kVK_PageUp] = Q_KEY_CODE_PGUP,
234 [kVK_PageDown] = Q_KEY_CODE_PGDN,
235 [kVK_End] = Q_KEY_CODE_END,
236 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
237
238 [kVK_Escape] = Q_KEY_CODE_ESC,
239
240 /* The Power key can't be used directly because the operating system uses
241 * it. This key can be emulated by using it in place of another key such as
242 * F1. Don't forget to disable the real key binding.
243 */
244 /* [kVK_F1] = Q_KEY_CODE_POWER, */
245
246 [kVK_F1] = Q_KEY_CODE_F1,
247 [kVK_F2] = Q_KEY_CODE_F2,
248 [kVK_F3] = Q_KEY_CODE_F3,
249 [kVK_F4] = Q_KEY_CODE_F4,
250 [kVK_F5] = Q_KEY_CODE_F5,
251 [kVK_F6] = Q_KEY_CODE_F6,
252 [kVK_F7] = Q_KEY_CODE_F7,
253 [kVK_F8] = Q_KEY_CODE_F8,
254 [kVK_F9] = Q_KEY_CODE_F9,
255 [kVK_F10] = Q_KEY_CODE_F10,
256 [kVK_F11] = Q_KEY_CODE_F11,
257 [kVK_F12] = Q_KEY_CODE_F12,
258 [kVK_F13] = Q_KEY_CODE_PRINT,
259 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
260 [kVK_F15] = Q_KEY_CODE_PAUSE,
261
Akihiko Odaki708b7252021-02-12 09:04:04 +0900262 // JIS keyboards only
263 [kVK_JIS_Yen] = Q_KEY_CODE_YEN,
264 [kVK_JIS_Underscore] = Q_KEY_CODE_RO,
265 [kVK_JIS_KeypadComma] = Q_KEY_CODE_KP_COMMA,
266 [kVK_JIS_Eisu] = Q_KEY_CODE_MUHENKAN,
267 [kVK_JIS_Kana] = Q_KEY_CODE_HENKAN,
268
John Arbuckleaaac7142016-03-23 14:26:18 +0000269 /*
270 * The eject and volume keys can't be used here because they are handled at
271 * a lower level than what an Application can see.
272 */
bellard5b0753e2005-03-01 21:37:28 +0000273};
274
Andreas Färber77047bb2009-12-13 00:55:53 +0100275static int cocoa_keycode_to_qemu(int keycode)
bellard5b0753e2005-03-01 21:37:28 +0000276{
John Arbuckleaaac7142016-03-23 14:26:18 +0000277 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
Akihiko Odaki43137392021-02-23 22:11:06 +0900278 error_report("(cocoa) warning unknown keycode 0x%x", keycode);
bellard5b0753e2005-03-01 21:37:28 +0000279 return 0;
280 }
John Arbuckleaaac7142016-03-23 14:26:18 +0000281 return mac_to_qkeycode_map[keycode];
bellard5b0753e2005-03-01 21:37:28 +0000282}
283
John Arbuckle693a3e02015-06-19 10:53:27 +0100284/* Displays an alert dialog box with the specified message */
285static void QEMU_Alert(NSString *message)
286{
287 NSAlert *alert;
288 alert = [NSAlert new];
289 [alert setMessageText: message];
290 [alert runModal];
291}
thsc304f7e2008-01-22 23:25:15 +0000292
John Arbuckle693a3e02015-06-19 10:53:27 +0100293/* Handles any errors that happen with a device transaction */
294static void handleAnyDeviceErrors(Error * err)
295{
296 if (err) {
297 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
298 encoding: NSASCIIStringEncoding]);
299 error_free(err);
300 }
301}
thsc304f7e2008-01-22 23:25:15 +0000302
bellard5b0753e2005-03-01 21:37:28 +0000303/*
304 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +0000305 QemuCocoaView
bellard5b0753e2005-03-01 21:37:28 +0000306 ------------------------------------------------------
307*/
thsc304f7e2008-01-22 23:25:15 +0000308@interface QemuCocoaView : NSView
bellard5b0753e2005-03-01 21:37:28 +0000309{
Akihiko Odaki91aa5082024-02-24 21:43:37 +0900310 NSTrackingArea *trackingArea;
thsc304f7e2008-01-22 23:25:15 +0000311 QEMUScreen screen;
Peter Maydell55888402019-02-25 10:24:33 +0000312 pixman_image_t *pixman_image;
Peter Maydell49b9bd42013-12-08 22:59:03 +0000313 BOOL isMouseGrabbed;
thsc304f7e2008-01-22 23:25:15 +0000314 BOOL isAbsoluteEnabled;
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900315 CFMachPortRef eventsTap;
thsc304f7e2008-01-22 23:25:15 +0000316}
Peter Maydell72a3e312019-02-25 10:24:28 +0000317- (void) switchSurface:(pixman_image_t *)image;
thsc304f7e2008-01-22 23:25:15 +0000318- (void) grabMouse;
319- (void) ungrabMouse;
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900320- (void) setFullGrab:(id)sender;
John Arbuckle9c3a4182017-11-07 10:14:14 +0000321- (void) handleMonitorInput:(NSEvent *)event;
Peter Maydell60105d72019-02-25 10:24:31 +0000322- (bool) handleEvent:(NSEvent *)event;
323- (bool) handleEventLocked:(NSEvent *)event;
thsc304f7e2008-01-22 23:25:15 +0000324- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
Peter Maydellf61c3872014-06-23 10:35:24 +0100325/* The state surrounding mouse grabbing is potentially confusing.
326 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
327 * pointing device an absolute-position one?"], but is only updated on
328 * next refresh.
329 * isMouseGrabbed tracks whether GUI events are directed to the guest;
330 * it controls whether special keys like Cmd get sent to the guest,
331 * and whether we capture the mouse when in non-absolute mode.
Peter Maydellf61c3872014-06-23 10:35:24 +0100332 */
Peter Maydell49b9bd42013-12-08 22:59:03 +0000333- (BOOL) isMouseGrabbed;
thsc304f7e2008-01-22 23:25:15 +0000334- (BOOL) isAbsoluteEnabled;
thsc304f7e2008-01-22 23:25:15 +0000335- (QEMUScreen) gscreen;
John Arbuckle3b178b72015-09-25 23:14:00 +0100336- (void) raiseAllKeys;
thsc304f7e2008-01-22 23:25:15 +0000337@end
ths3b46e622007-09-17 08:09:54 +0000338
Andreas Färber7fee1992011-06-09 20:53:32 +0200339QemuCocoaView *cocoaView;
340
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900341static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEventRef cgEvent, void *userInfo)
342{
Philippe Mathieu-Daudé21eb7522023-10-04 14:00:13 +0200343 QemuCocoaView *view = userInfo;
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900344 NSEvent *event = [NSEvent eventWithCGEvent:cgEvent];
Philippe Mathieu-Daudé21eb7522023-10-04 14:00:13 +0200345 if ([view isMouseGrabbed] && [view handleEvent:event]) {
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900346 COCOA_DEBUG("Global events tap: qemu handled the event, capturing!\n");
347 return NULL;
348 }
349 COCOA_DEBUG("Global events tap: qemu did not handle the event, letting it through...\n");
350
351 return cgEvent;
352}
353
thsc304f7e2008-01-22 23:25:15 +0000354@implementation QemuCocoaView
355- (id)initWithFrame:(NSRect)frameRect
356{
357 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
ths3b46e622007-09-17 08:09:54 +0000358
thsc304f7e2008-01-22 23:25:15 +0000359 self = [super initWithFrame:frameRect];
360 if (self) {
pbrook95219892006-04-09 01:06:34 +0000361
thsc304f7e2008-01-22 23:25:15 +0000362 screen.width = frameRect.size.width;
363 screen.height = frameRect.size.height;
David Parsonsf5af8022024-02-24 14:06:20 +0000364#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_14_0
365 [self setClipsToBounds:YES];
366#endif
bellard7c206a72005-12-18 19:18:45 +0000367
thsc304f7e2008-01-22 23:25:15 +0000368 }
369 return self;
370}
bellard7c206a72005-12-18 19:18:45 +0000371
thsc304f7e2008-01-22 23:25:15 +0000372- (void) dealloc
373{
374 COCOA_DEBUG("QemuCocoaView: dealloc\n");
bellard7c206a72005-12-18 19:18:45 +0000375
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900376 if (pixman_image) {
Peter Maydell55888402019-02-25 10:24:33 +0000377 pixman_image_unref(pixman_image);
378 }
ths3b46e622007-09-17 08:09:54 +0000379
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900380 if (eventsTap) {
381 CFRelease(eventsTap);
382 }
383
thsc304f7e2008-01-22 23:25:15 +0000384 [super dealloc];
385}
bellard5cbfcd02006-06-14 15:53:24 +0000386
Andreas Färberd50f71d2009-12-13 02:03:33 +0100387- (BOOL) isOpaque
388{
389 return YES;
390}
391
Akihiko Odaki91aa5082024-02-24 21:43:37 +0900392- (void) removeTrackingRect
Peter Maydell5dd45be2014-06-23 10:35:23 +0100393{
Akihiko Odaki91aa5082024-02-24 21:43:37 +0900394 if (trackingArea) {
395 [self removeTrackingArea:trackingArea];
396 [trackingArea release];
397 trackingArea = nil;
398 }
Peter Maydell5dd45be2014-06-23 10:35:23 +0100399}
400
Akihiko Odaki91aa5082024-02-24 21:43:37 +0900401- (void) frameUpdated
Chen Zhang2044dff2019-06-04 17:36:00 +0800402{
Akihiko Odaki91aa5082024-02-24 21:43:37 +0900403 [self removeTrackingRect];
404
405 if ([self window]) {
406 NSTrackingAreaOptions options = NSTrackingActiveInKeyWindow |
407 NSTrackingMouseEnteredAndExited |
408 NSTrackingMouseMoved;
409 trackingArea = [[NSTrackingArea alloc] initWithRect:[self frame]
410 options:options
411 owner:self
412 userInfo:nil];
413 [self addTrackingArea:trackingArea];
414 [self updateUIInfo];
Chen Zhang2044dff2019-06-04 17:36:00 +0800415 }
416}
417
Akihiko Odaki91aa5082024-02-24 21:43:37 +0900418- (void) viewDidMoveToWindow
419{
420 [self resizeWindow];
421 [self frameUpdated];
422}
423
424- (void) viewWillMoveToWindow:(NSWindow *)newWindow
425{
426 [self removeTrackingRect];
427}
428
Akihiko Odakica3de7b2024-03-19 12:08:41 +0900429- (void) selectConsoleLocked:(unsigned int)index
430{
431 QemuConsole *con = qemu_console_lookup_by_index(index);
432 if (!con) {
433 return;
434 }
435
436 unregister_displaychangelistener(&dcl);
437 qkbd_state_switch_console(kbd, con);
438 dcl.con = con;
439 register_displaychangelistener(&dcl);
440 [self updateUIInfo];
441}
442
Peter Maydell13aefd32014-06-23 10:35:25 +0100443- (void) hideCursor
444{
445 if (!cursor_hide) {
446 return;
447 }
448 [NSCursor hide];
449}
450
451- (void) unhideCursor
452{
453 if (!cursor_hide) {
454 return;
455 }
456 [NSCursor unhide];
457}
458
thsc304f7e2008-01-22 23:25:15 +0000459- (void) drawRect:(NSRect) rect
460{
461 COCOA_DEBUG("QemuCocoaView: drawRect\n");
bellard5cbfcd02006-06-14 15:53:24 +0000462
thsc304f7e2008-01-22 23:25:15 +0000463 // get CoreGraphic context
Brendan Shanks5e246002019-01-31 23:12:25 -0800464 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
Brendan Shanks5e246002019-01-31 23:12:25 -0800465
Carwyn Ellise28a9092023-11-10 16:17:29 +0000466 CGContextSetInterpolationQuality (viewContextRef, zoom_interpolation);
thsc304f7e2008-01-22 23:25:15 +0000467 CGContextSetShouldAntialias (viewContextRef, NO);
ths3b46e622007-09-17 08:09:54 +0000468
thsc304f7e2008-01-22 23:25:15 +0000469 // draw screen bitmap directly to Core Graphics context
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900470 if (!pixman_image) {
Peter Maydell7d270b12013-12-24 02:51:47 +0000471 // Draw request before any guest device has set up a framebuffer:
472 // just draw an opaque black rectangle
473 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
474 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
475 } else {
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900476 int w = pixman_image_get_width(pixman_image);
477 int h = pixman_image_get_height(pixman_image);
478 int bitsPerPixel = PIXMAN_FORMAT_BPP(pixman_image_get_format(pixman_image));
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900479 int stride = pixman_image_get_stride(pixman_image);
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900480 CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(
481 NULL,
482 pixman_image_get_data(pixman_image),
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900483 stride * h,
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900484 NULL
485 );
thsc304f7e2008-01-22 23:25:15 +0000486 CGImageRef imageRef = CGImageCreate(
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900487 w, //width
488 h, //height
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900489 DIV_ROUND_UP(bitsPerPixel, 8) * 2, //bitsPerComponent
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900490 bitsPerPixel, //bitsPerPixel
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900491 stride, //bytesPerRow
Akihiko Odakiae57d352021-03-05 21:13:04 +0900492 CGColorSpaceCreateWithName(kCGColorSpaceSRGB), //colorspace
493 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst, //bitmapInfo
thsc304f7e2008-01-22 23:25:15 +0000494 dataProviderRef, //provider
495 NULL, //decode
496 0, //interpolate
497 kCGRenderingIntentDefault //intent
498 );
Peter Maydellb63901d2015-05-19 09:11:17 +0100499 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
500 const NSRect *rectList;
Peter Maydellb63901d2015-05-19 09:11:17 +0100501 NSInteger rectCount;
Peter Maydellb63901d2015-05-19 09:11:17 +0100502 int i;
503 CGImageRef clipImageRef;
504 CGRect clipRect;
ths3b46e622007-09-17 08:09:54 +0000505
Peter Maydellb63901d2015-05-19 09:11:17 +0100506 [self getRectsBeingDrawn:&rectList count:&rectCount];
507 for (i = 0; i < rectCount; i++) {
Akihiko Odakifcb03de2024-02-24 21:43:35 +0900508 clipRect = rectList[i];
509 clipRect.origin.y = (float)h - (clipRect.origin.y + clipRect.size.height);
Peter Maydellb63901d2015-05-19 09:11:17 +0100510 clipImageRef = CGImageCreateWithImageInRect(
511 imageRef,
512 clipRect
513 );
514 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
515 CGImageRelease (clipImageRef);
bellard5b0753e2005-03-01 21:37:28 +0000516 }
thsc304f7e2008-01-22 23:25:15 +0000517 CGImageRelease (imageRef);
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900518 CGDataProviderRelease(dataProviderRef);
bellard5b0753e2005-03-01 21:37:28 +0000519 }
520}
521
Akihiko Odakid2ee0422024-03-23 15:20:01 +0900522- (NSSize)fixAspectRatio:(NSSize)max
523{
524 NSSize scaled;
525 NSSize fixed;
526
527 scaled.width = screen.width * max.height;
528 scaled.height = screen.height * max.width;
529
530 /*
531 * Here screen is our guest's output size, and max is the size of the
532 * largest possible area of the screen we can display on.
533 * We want to scale up (screen.width x screen.height) by either:
534 * 1) max.height / screen.height
535 * 2) max.width / screen.width
536 * With the first scale factor the scale will result in an output height of
537 * max.height (i.e. we will fill the whole height of the available screen
538 * space and have black bars left and right) and with the second scale
539 * factor the scaling will result in an output width of max.width (i.e. we
540 * fill the whole width of the available screen space and have black bars
541 * top and bottom). We need to pick whichever keeps the whole of the guest
542 * output on the screen, which is to say the smaller of the two scale
543 * factors.
544 * To avoid doing more division than strictly necessary, instead of directly
545 * comparing scale factors 1 and 2 we instead calculate and compare those
546 * two scale factors multiplied by (screen.height * screen.width).
547 */
548 if (scaled.width < scaled.height) {
549 fixed.width = scaled.width / screen.height;
550 fixed.height = max.height;
551 } else {
552 fixed.width = max.width;
553 fixed.height = scaled.height / screen.width;
554 }
555
556 return fixed;
557}
558
Akihiko Odaki91aa5082024-02-24 21:43:37 +0900559- (NSSize) screenSafeAreaSize
bellard5b0753e2005-03-01 21:37:28 +0000560{
Akihiko Odaki91aa5082024-02-24 21:43:37 +0900561 NSSize size = [[[self window] screen] frame].size;
562 NSEdgeInsets insets = [[[self window] screen] safeAreaInsets];
563 size.width -= insets.left + insets.right;
564 size.height -= insets.top + insets.bottom;
565 return size;
566}
ths3b46e622007-09-17 08:09:54 +0000567
Akihiko Odaki91aa5082024-02-24 21:43:37 +0900568- (void) resizeWindow
569{
570 [[self window] setContentAspectRatio:NSMakeSize(screen.width, screen.height)];
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100571
Akihiko Odaki55766632024-02-24 21:43:41 +0900572 if (!([[self window] styleMask] & NSWindowStyleMaskResizable)) {
Akihiko Odaki91aa5082024-02-24 21:43:37 +0900573 [[self window] setContentSize:NSMakeSize(screen.width, screen.height)];
574 [[self window] center];
575 } else if ([[self window] styleMask] & NSWindowStyleMaskFullScreen) {
Akihiko Odakid2ee0422024-03-23 15:20:01 +0900576 [[self window] setContentSize:[self fixAspectRatio:[self screenSafeAreaSize]]];
Akihiko Odaki91aa5082024-02-24 21:43:37 +0900577 [[self window] center];
Akihiko Odakid2ee0422024-03-23 15:20:01 +0900578 } else {
579 [[self window] setContentSize:[self fixAspectRatio:[self frame].size]];
thsc304f7e2008-01-22 23:25:15 +0000580 }
bellard5b0753e2005-03-01 21:37:28 +0000581}
582
Akihiko Odakifcb03de2024-02-24 21:43:35 +0900583- (void) updateBounds
584{
585 [self setBoundsSize:NSMakeSize(screen.width, screen.height)];
586}
587
Peter Maydell8d65dee2022-02-24 10:13:29 +0000588- (void) updateUIInfoLocked
Akihiko Odaki15280e82021-06-16 23:19:10 +0900589{
Stefan Hajnoczia4a411f2024-01-02 10:35:28 -0500590 /* Must be called with the BQL, i.e. via updateUIInfo */
Akihiko Odaki15280e82021-06-16 23:19:10 +0900591 NSSize frameSize;
592 QemuUIInfo info;
593
594 if (!qemu_console_is_graphic(dcl.con)) {
595 return;
596 }
597
598 if ([self window]) {
599 NSDictionary *description = [[[self window] screen] deviceDescription];
600 CGDirectDisplayID display = [[description objectForKey:@"NSScreenNumber"] unsignedIntValue];
601 NSSize screenSize = [[[self window] screen] frame].size;
602 CGSize screenPhysicalSize = CGDisplayScreenSize(display);
Akihiko Odaki91aa5082024-02-24 21:43:37 +0900603 bool isFullscreen = ([[self window] styleMask] & NSWindowStyleMaskFullScreen) != 0;
Akihiko Odaki52eaefd2022-07-02 23:25:19 +0900604 CVDisplayLinkRef displayLink;
Akihiko Odaki15280e82021-06-16 23:19:10 +0900605
Akihiko Odaki91aa5082024-02-24 21:43:37 +0900606 frameSize = isFullscreen ? [self screenSafeAreaSize] : [self frame].size;
Akihiko Odaki52eaefd2022-07-02 23:25:19 +0900607
608 if (!CVDisplayLinkCreateWithCGDisplay(display, &displayLink)) {
609 CVTime period = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLink);
610 CVDisplayLinkRelease(displayLink);
611 if (!(period.flags & kCVTimeIsIndefinite)) {
612 update_displaychangelistener(&dcl,
613 1000 * period.timeValue / period.timeScale);
614 info.refresh_rate = (int64_t)1000 * period.timeScale / period.timeValue;
615 }
616 }
617
Akihiko Odaki15280e82021-06-16 23:19:10 +0900618 info.width_mm = frameSize.width / screenSize.width * screenPhysicalSize.width;
619 info.height_mm = frameSize.height / screenSize.height * screenPhysicalSize.height;
620 } else {
621 frameSize = [self frame].size;
622 info.width_mm = 0;
623 info.height_mm = 0;
624 }
625
626 info.xoff = 0;
627 info.yoff = 0;
628 info.width = frameSize.width;
629 info.height = frameSize.height;
630
Marc-André Lureauca19ef52021-04-13 20:39:11 +0400631 dpy_set_ui_info(dcl.con, &info, TRUE);
Akihiko Odaki15280e82021-06-16 23:19:10 +0900632}
633
Peter Maydell8d65dee2022-02-24 10:13:29 +0000634- (void) updateUIInfo
635{
636 if (!allow_events) {
637 /*
638 * Don't try to tell QEMU about UI information in the application
639 * startup phase -- we haven't yet registered dcl with the QEMU UI
Akihiko Odakibab6a302022-08-19 22:27:54 +0900640 * layer.
Peter Maydell8d65dee2022-02-24 10:13:29 +0000641 * When cocoa_display_init() does register the dcl, the UI layer
642 * will call cocoa_switch(), which will call updateUIInfo, so
643 * we don't lose any information here.
644 */
645 return;
646 }
647
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500648 with_bql(^{
Peter Maydell8d65dee2022-02-24 10:13:29 +0000649 [self updateUIInfoLocked];
650 });
651}
652
Peter Maydell72a3e312019-02-25 10:24:28 +0000653- (void) switchSurface:(pixman_image_t *)image
thsc304f7e2008-01-22 23:25:15 +0000654{
Gerd Hoffmann5e00d3a2013-03-01 12:52:06 +0100655 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
thsc304f7e2008-01-22 23:25:15 +0000656
Peter Maydell72a3e312019-02-25 10:24:28 +0000657 int w = pixman_image_get_width(image);
658 int h = pixman_image_get_height(image);
Peter Maydelld3345a02013-12-24 02:51:46 +0000659
Akihiko Odaki91aa5082024-02-24 21:43:37 +0900660 if (w != screen.width || h != screen.height) {
Peter Maydelld3345a02013-12-24 02:51:46 +0000661 // Resize before we trigger the redraw, or we'll redraw at the wrong size
662 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
663 screen.width = w;
664 screen.height = h;
Akihiko Odaki91aa5082024-02-24 21:43:37 +0900665 [self resizeWindow];
Akihiko Odakifcb03de2024-02-24 21:43:35 +0900666 [self updateBounds];
Peter Maydelld3345a02013-12-24 02:51:46 +0000667 }
Peter Maydell8510d912013-03-18 20:28:21 +0000668
thsc304f7e2008-01-22 23:25:15 +0000669 // update screenBuffer
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900670 if (pixman_image) {
Peter Maydell55888402019-02-25 10:24:33 +0000671 pixman_image_unref(pixman_image);
672 }
thsc304f7e2008-01-22 23:25:15 +0000673
Peter Maydell55888402019-02-25 10:24:33 +0000674 pixman_image = image;
thsc304f7e2008-01-22 23:25:15 +0000675}
676
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900677- (void) setFullGrab:(id)sender
678{
679 COCOA_DEBUG("QemuCocoaView: setFullGrab\n");
680
681 CGEventMask mask = CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp) | CGEventMaskBit(kCGEventFlagsChanged);
682 eventsTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault,
683 mask, handleTapEvent, self);
684 if (!eventsTap) {
685 warn_report("Could not create event tap, system key combos will not be captured.\n");
686 return;
687 } else {
688 COCOA_DEBUG("Global events tap created! Will capture system key combos.\n");
689 }
690
691 CFRunLoopRef runLoop = CFRunLoopGetCurrent();
692 if (!runLoop) {
693 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
694 return;
695 }
696
697 CFRunLoopSourceRef tapEventsSrc = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventsTap, 0);
698 if (!tapEventsSrc ) {
699 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
700 return;
701 }
702
703 CFRunLoopAddSource(runLoop, tapEventsSrc, kCFRunLoopDefaultMode);
704 CFRelease(tapEventsSrc);
705}
706
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900707- (void) toggleKey: (int)keycode {
708 qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode));
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700709}
710
John Arbuckle9c3a4182017-11-07 10:14:14 +0000711// Does the work of sending input to the monitor
712- (void) handleMonitorInput:(NSEvent *)event
713{
714 int keysym = 0;
715 int control_key = 0;
716
717 // if the control key is down
718 if ([event modifierFlags] & NSEventModifierFlagControl) {
719 control_key = 1;
720 }
721
722 /* translates Macintosh keycodes to QEMU's keysym */
723
Philippe Mathieu-Daudé94592622022-02-15 16:21:14 +0100724 static const int without_control_translation[] = {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000725 [0 ... 0xff] = 0, // invalid key
726
727 [kVK_UpArrow] = QEMU_KEY_UP,
728 [kVK_DownArrow] = QEMU_KEY_DOWN,
729 [kVK_RightArrow] = QEMU_KEY_RIGHT,
730 [kVK_LeftArrow] = QEMU_KEY_LEFT,
731 [kVK_Home] = QEMU_KEY_HOME,
732 [kVK_End] = QEMU_KEY_END,
733 [kVK_PageUp] = QEMU_KEY_PAGEUP,
734 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
735 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
736 [kVK_Delete] = QEMU_KEY_BACKSPACE,
737 };
738
Philippe Mathieu-Daudé94592622022-02-15 16:21:14 +0100739 static const int with_control_translation[] = {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000740 [0 ... 0xff] = 0, // invalid key
741
742 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
743 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
744 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
745 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
746 [kVK_Home] = QEMU_KEY_CTRL_HOME,
747 [kVK_End] = QEMU_KEY_CTRL_END,
748 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
749 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
750 };
751
752 if (control_key != 0) { /* If the control key is being used */
753 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
754 keysym = with_control_translation[[event keyCode]];
755 }
756 } else {
757 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
758 keysym = without_control_translation[[event keyCode]];
759 }
760 }
761
762 // if not a key that needs translating
763 if (keysym == 0) {
764 NSString *ks = [event characters];
765 if ([ks length] > 0) {
766 keysym = [ks characterAtIndex:0];
767 }
768 }
769
770 if (keysym) {
Akihiko Odakica3de7b2024-03-19 12:08:41 +0900771 QemuTextConsole *con = QEMU_TEXT_CONSOLE(dcl.con);
772 qemu_text_console_put_keysym(con, keysym);
John Arbuckle9c3a4182017-11-07 10:14:14 +0000773 }
774}
775
Peter Maydell60105d72019-02-25 10:24:31 +0000776- (bool) handleEvent:(NSEvent *)event
thsc304f7e2008-01-22 23:25:15 +0000777{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500778 return bool_with_bql(^{
Peter Maydell60105d72019-02-25 10:24:31 +0000779 return [self handleEventLocked:event];
Peter Maydell31819e92019-02-25 10:24:27 +0000780 });
781}
thsc304f7e2008-01-22 23:25:15 +0000782
Peter Maydell60105d72019-02-25 10:24:31 +0000783- (bool) handleEventLocked:(NSEvent *)event
Peter Maydell31819e92019-02-25 10:24:27 +0000784{
Peter Maydell60105d72019-02-25 10:24:31 +0000785 /* Return true if we handled the event, false if it should be given to OSX */
Peter Maydell31819e92019-02-25 10:24:27 +0000786 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
Akihiko Odaki0f7be472024-02-24 21:43:33 +0900787 InputButton button;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700788 int keycode = 0;
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900789 NSUInteger modifiers = [event modifierFlags];
790
Akihiko Odakiad7f2f82021-03-12 22:32:12 +0900791 /*
792 * Check -[NSEvent modifierFlags] here.
793 *
794 * There is a NSEventType for an event notifying the change of
795 * -[NSEvent modifierFlags], NSEventTypeFlagsChanged but these operations
796 * are performed for any events because a modifier state may change while
797 * the application is inactive (i.e. no events fire) and we don't want to
798 * wait for another modifier state change to detect such a change.
799 *
800 * NSEventModifierFlagCapsLock requires a special treatment. The other flags
801 * are handled in similar manners.
802 *
803 * NSEventModifierFlagCapsLock
804 * ---------------------------
805 *
806 * If CapsLock state is changed, "up" and "down" events will be fired in
807 * sequence, effectively updates CapsLock state on the guest.
808 *
809 * The other flags
810 * ---------------
811 *
812 * If a flag is not set, fire "up" events for all keys which correspond to
813 * the flag. Note that "down" events are not fired here because the flags
814 * checked here do not tell what exact keys are down.
815 *
816 * If one of the keys corresponding to a flag is down, we rely on
817 * -[NSEvent keyCode] of an event whose -[NSEvent type] is
818 * NSEventTypeFlagsChanged to know the exact key which is down, which has
819 * the following two downsides:
820 * - It does not work when the application is inactive as described above.
821 * - It malfactions *after* the modifier state is changed while the
822 * application is inactive. It is because -[NSEvent keyCode] does not tell
823 * if the key is up or down, and requires to infer the current state from
824 * the previous state. It is still possible to fix such a malfanction by
825 * completely leaving your hands from the keyboard, which hopefully makes
826 * this implementation usable enough.
827 */
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900828 if (!!(modifiers & NSEventModifierFlagCapsLock) !=
829 qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) {
830 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true);
831 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false);
832 }
833
834 if (!(modifiers & NSEventModifierFlagShift)) {
835 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false);
836 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false);
837 }
838 if (!(modifiers & NSEventModifierFlagControl)) {
839 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false);
840 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false);
841 }
842 if (!(modifiers & NSEventModifierFlagOption)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900843 if (swap_opt_cmd) {
844 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
845 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
846 } else {
847 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
848 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
849 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900850 }
851 if (!(modifiers & NSEventModifierFlagCommand)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900852 if (swap_opt_cmd) {
853 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
854 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
855 } else {
856 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
857 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
858 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900859 }
thsc304f7e2008-01-22 23:25:15 +0000860
861 switch ([event type]) {
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700862 case NSEventTypeFlagsChanged:
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900863 switch ([event keyCode]) {
864 case kVK_Shift:
865 if (!!(modifiers & NSEventModifierFlagShift)) {
866 [self toggleKey:Q_KEY_CODE_SHIFT];
867 }
868 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700869
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900870 case kVK_RightShift:
871 if (!!(modifiers & NSEventModifierFlagShift)) {
872 [self toggleKey:Q_KEY_CODE_SHIFT_R];
873 }
874 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700875
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900876 case kVK_Control:
877 if (!!(modifiers & NSEventModifierFlagControl)) {
878 [self toggleKey:Q_KEY_CODE_CTRL];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700879 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900880 break;
881
882 case kVK_RightControl:
883 if (!!(modifiers & NSEventModifierFlagControl)) {
884 [self toggleKey:Q_KEY_CODE_CTRL_R];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700885 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900886 break;
887
888 case kVK_Option:
889 if (!!(modifiers & NSEventModifierFlagOption)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900890 if (swap_opt_cmd) {
891 [self toggleKey:Q_KEY_CODE_META_L];
892 } else {
893 [self toggleKey:Q_KEY_CODE_ALT];
894 }
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700895 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900896 break;
897
898 case kVK_RightOption:
899 if (!!(modifiers & NSEventModifierFlagOption)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900900 if (swap_opt_cmd) {
901 [self toggleKey:Q_KEY_CODE_META_R];
902 } else {
903 [self toggleKey:Q_KEY_CODE_ALT_R];
904 }
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700905 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900906 break;
907
908 /* Don't pass command key changes to guest unless mouse is grabbed */
909 case kVK_Command:
910 if (isMouseGrabbed &&
Akihiko Odakid6b6dea2022-03-18 00:29:49 +0900911 !!(modifiers & NSEventModifierFlagCommand) &&
912 left_command_key_enabled) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900913 if (swap_opt_cmd) {
914 [self toggleKey:Q_KEY_CODE_ALT];
915 } else {
916 [self toggleKey:Q_KEY_CODE_META_L];
917 }
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700918 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900919 break;
920
921 case kVK_RightCommand:
922 if (isMouseGrabbed &&
923 !!(modifiers & NSEventModifierFlagCommand)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900924 if (swap_opt_cmd) {
925 [self toggleKey:Q_KEY_CODE_ALT_R];
926 } else {
927 [self toggleKey:Q_KEY_CODE_META_R];
928 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900929 }
930 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700931 }
Akihiko Odaki0f7be472024-02-24 21:43:33 +0900932 return true;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700933 case NSEventTypeKeyDown:
Peter Maydell88959192013-12-08 22:59:02 +0000934 keycode = cocoa_keycode_to_qemu([event keyCode]);
thsc304f7e2008-01-22 23:25:15 +0000935
Peter Maydell88959192013-12-08 22:59:02 +0000936 // forward command key combos to the host UI unless the mouse is grabbed
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700937 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
Peter Maydell60105d72019-02-25 10:24:31 +0000938 return false;
thsc304f7e2008-01-22 23:25:15 +0000939 }
940
941 // default
thsc304f7e2008-01-22 23:25:15 +0000942
John Arbuckle5929e362017-11-07 10:14:14 +0000943 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700944 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
John Arbuckle5929e362017-11-07 10:14:14 +0000945 NSString *keychar = [event charactersIgnoringModifiers];
946 if ([keychar length] == 1) {
947 char key = [keychar characterAtIndex:0];
948 switch (key) {
thsc304f7e2008-01-22 23:25:15 +0000949
John Arbuckle5929e362017-11-07 10:14:14 +0000950 // enable graphic console
951 case '1' ... '9':
Akihiko Odakica3de7b2024-03-19 12:08:41 +0900952 [self selectConsoleLocked:key - '0' - 1]; /* ascii math */
Peter Maydell60105d72019-02-25 10:24:31 +0000953 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000954
955 // release the mouse grab
956 case 'g':
957 [self ungrabMouse];
Peter Maydell60105d72019-02-25 10:24:31 +0000958 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000959 }
thsc304f7e2008-01-22 23:25:15 +0000960 }
Peter Maydellef2088f2017-11-07 10:14:14 +0000961 }
thsc304f7e2008-01-22 23:25:15 +0000962
Akihiko Odakica3de7b2024-03-19 12:08:41 +0900963 if (qemu_console_is_graphic(dcl.con)) {
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900964 qkbd_state_key_event(kbd, keycode, true);
thsc304f7e2008-01-22 23:25:15 +0000965 } else {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000966 [self handleMonitorInput: event];
thsc304f7e2008-01-22 23:25:15 +0000967 }
Akihiko Odaki0f7be472024-02-24 21:43:33 +0900968 return true;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700969 case NSEventTypeKeyUp:
thsc304f7e2008-01-22 23:25:15 +0000970 keycode = cocoa_keycode_to_qemu([event keyCode]);
Peter Maydell88959192013-12-08 22:59:02 +0000971
972 // don't pass the guest a spurious key-up if we treated this
973 // command-key combo as a host UI action
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700974 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
Peter Maydell60105d72019-02-25 10:24:31 +0000975 return true;
Peter Maydell88959192013-12-08 22:59:02 +0000976 }
977
Akihiko Odakica3de7b2024-03-19 12:08:41 +0900978 if (qemu_console_is_graphic(dcl.con)) {
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900979 qkbd_state_key_event(kbd, keycode, false);
thsc304f7e2008-01-22 23:25:15 +0000980 }
Akihiko Odaki0f7be472024-02-24 21:43:33 +0900981 return true;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700982 case NSEventTypeScrollWheel:
John Arbuckleae7313e2018-01-08 13:07:07 -0500983 /*
984 * Send wheel events to the guest regardless of window focus.
985 * This is in-line with standard Mac OS X UI behaviour.
986 */
987
988 /* Determine if this is a scroll up or scroll down event */
Akihiko Odaki0f7be472024-02-24 21:43:33 +0900989 if ([event deltaY] != 0) {
990 button = ([event deltaY] > 0) ?
John Arbuckledc3c89d2018-07-09 11:02:35 -0400991 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
Akihiko Odaki0f7be472024-02-24 21:43:33 +0900992 } else if ([event deltaX] != 0) {
993 button = ([event deltaX] > 0) ?
Dmitry Petrovd70a5de2022-01-08 16:39:44 +0100994 INPUT_BUTTON_WHEEL_LEFT : INPUT_BUTTON_WHEEL_RIGHT;
Akihiko Odaki0f7be472024-02-24 21:43:33 +0900995 } else {
996 /*
997 * We shouldn't have got a scroll event when deltaY and delta Y
998 * are zero, hence no harm in dropping the event
999 */
1000 return true;
John Arbuckledc3c89d2018-07-09 11:02:35 -04001001 }
Dmitry Petrovd70a5de2022-01-08 16:39:44 +01001002
Akihiko Odaki0f7be472024-02-24 21:43:33 +09001003 qemu_input_queue_btn(dcl.con, button, true);
1004 qemu_input_event_sync();
1005 qemu_input_queue_btn(dcl.con, button, false);
1006 qemu_input_event_sync();
1007
1008 return true;
thsc304f7e2008-01-22 23:25:15 +00001009 default:
Peter Maydell60105d72019-02-25 10:24:31 +00001010 return false;
thsc304f7e2008-01-22 23:25:15 +00001011 }
1012}
1013
Akihiko Odaki91aa5082024-02-24 21:43:37 +09001014- (void) handleMouseEvent:(NSEvent *)event button:(InputButton)button down:(bool)down
Akihiko Odakiaf4efbc2024-02-24 21:43:32 +09001015{
1016 if (!isMouseGrabbed) {
Akihiko Odaki91aa5082024-02-24 21:43:37 +09001017 return;
Akihiko Odakiaf4efbc2024-02-24 21:43:32 +09001018 }
1019
Akihiko Odaki91aa5082024-02-24 21:43:37 +09001020 with_bql(^{
1021 qemu_input_queue_btn(dcl.con, button, down);
1022 });
Akihiko Odakiaf4efbc2024-02-24 21:43:32 +09001023
Akihiko Odaki91aa5082024-02-24 21:43:37 +09001024 [self handleMouseEvent:event];
1025}
1026
1027- (void) handleMouseEvent:(NSEvent *)event
1028{
1029 if (!isMouseGrabbed) {
1030 return;
1031 }
1032
1033 with_bql(^{
1034 if (isAbsoluteEnabled) {
1035 CGFloat d = (CGFloat)screen.height / [self frame].size.height;
1036 NSPoint p = [event locationInWindow];
1037
1038 /* Note that the origin for Cocoa mouse coords is bottom left, not top left. */
1039 qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x * d, 0, screen.width);
1040 qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y * d, 0, screen.height);
1041 } else {
1042 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, [event deltaX]);
1043 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, [event deltaY]);
Akihiko Odakiaf4efbc2024-02-24 21:43:32 +09001044 }
Akihiko Odaki91aa5082024-02-24 21:43:37 +09001045
1046 qemu_input_event_sync();
1047 });
1048}
1049
1050- (void) mouseExited:(NSEvent *)event
1051{
1052 if (isAbsoluteEnabled && isMouseGrabbed) {
1053 [self ungrabMouse];
1054 }
1055}
1056
1057- (void) mouseEntered:(NSEvent *)event
1058{
1059 if (isAbsoluteEnabled && !isMouseGrabbed) {
1060 [self grabMouse];
1061 }
1062}
1063
1064- (void) mouseMoved:(NSEvent *)event
1065{
1066 [self handleMouseEvent:event];
1067}
1068
1069- (void) mouseDown:(NSEvent *)event
1070{
1071 [self handleMouseEvent:event button:INPUT_BUTTON_LEFT down:true];
1072}
1073
1074- (void) rightMouseDown:(NSEvent *)event
1075{
1076 [self handleMouseEvent:event button:INPUT_BUTTON_RIGHT down:true];
1077}
1078
1079- (void) otherMouseDown:(NSEvent *)event
1080{
1081 [self handleMouseEvent:event button:INPUT_BUTTON_MIDDLE down:true];
1082}
1083
1084- (void) mouseDragged:(NSEvent *)event
1085{
1086 [self handleMouseEvent:event];
1087}
1088
1089- (void) rightMouseDragged:(NSEvent *)event
1090{
1091 [self handleMouseEvent:event];
1092}
1093
1094- (void) otherMouseDragged:(NSEvent *)event
1095{
1096 [self handleMouseEvent:event];
1097}
1098
1099- (void) mouseUp:(NSEvent *)event
1100{
1101 if (!isMouseGrabbed) {
1102 [self grabMouse];
Akihiko Odakiaf4efbc2024-02-24 21:43:32 +09001103 }
1104
Akihiko Odaki91aa5082024-02-24 21:43:37 +09001105 [self handleMouseEvent:event button:INPUT_BUTTON_LEFT down:false];
1106}
Akihiko Odakiaf4efbc2024-02-24 21:43:32 +09001107
Akihiko Odaki91aa5082024-02-24 21:43:37 +09001108- (void) rightMouseUp:(NSEvent *)event
1109{
1110 [self handleMouseEvent:event button:INPUT_BUTTON_RIGHT down:false];
1111}
1112
1113- (void) otherMouseUp:(NSEvent *)event
1114{
1115 [self handleMouseEvent:event button:INPUT_BUTTON_MIDDLE down:false];
Akihiko Odakiaf4efbc2024-02-24 21:43:32 +09001116}
1117
thsc304f7e2008-01-22 23:25:15 +00001118- (void) grabMouse
1119{
1120 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
1121
Akihiko Odaki91aa5082024-02-24 21:43:37 +09001122 if (qemu_name)
Akihiko Odaki0c358862024-02-24 21:43:38 +09001123 [[self window] setTitle:[NSString stringWithFormat:@"QEMU %s - (Press " UC_CTRL_KEY " " UC_ALT_KEY " G to release Mouse)", qemu_name]];
Akihiko Odaki91aa5082024-02-24 21:43:37 +09001124 else
Akihiko Odaki0c358862024-02-24 21:43:38 +09001125 [[self window] setTitle:@"QEMU - (Press " UC_CTRL_KEY " " UC_ALT_KEY " G to release Mouse)"];
Peter Maydell13aefd32014-06-23 10:35:25 +01001126 [self hideCursor];
Akihiko Odakid1929062021-02-23 00:07:14 +09001127 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
Peter Maydell49b9bd42013-12-08 22:59:03 +00001128 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
thsc304f7e2008-01-22 23:25:15 +00001129}
1130
1131- (void) ungrabMouse
1132{
1133 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
1134
Akihiko Odaki91aa5082024-02-24 21:43:37 +09001135 if (qemu_name)
Akihiko Odaki0c358862024-02-24 21:43:38 +09001136 [[self window] setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
Akihiko Odaki91aa5082024-02-24 21:43:37 +09001137 else
Akihiko Odaki0c358862024-02-24 21:43:38 +09001138 [[self window] setTitle:@"QEMU"];
Peter Maydell13aefd32014-06-23 10:35:25 +01001139 [self unhideCursor];
Akihiko Odakid1929062021-02-23 00:07:14 +09001140 CGAssociateMouseAndMouseCursorPosition(TRUE);
Peter Maydell49b9bd42013-12-08 22:59:03 +00001141 isMouseGrabbed = FALSE;
Akihiko Odaki91aa5082024-02-24 21:43:37 +09001142 [self raiseAllButtons];
thsc304f7e2008-01-22 23:25:15 +00001143}
1144
Akihiko Odakid1929062021-02-23 00:07:14 +09001145- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {
1146 isAbsoluteEnabled = tIsAbsoluteEnabled;
1147 if (isMouseGrabbed) {
1148 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1149 }
1150}
Peter Maydell49b9bd42013-12-08 22:59:03 +00001151- (BOOL) isMouseGrabbed {return isMouseGrabbed;}
thsc304f7e2008-01-22 23:25:15 +00001152- (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
thsc304f7e2008-01-22 23:25:15 +00001153- (QEMUScreen) gscreen {return screen;}
John Arbuckle3b178b72015-09-25 23:14:00 +01001154
1155/*
1156 * Makes the target think all down keys are being released.
1157 * This prevents a stuck key problem, since we will not see
1158 * key up events for those keys after we have lost focus.
1159 */
1160- (void) raiseAllKeys
1161{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001162 with_bql(^{
Akihiko Odaki6d73bb62021-03-10 23:46:02 +09001163 qkbd_state_lift_all_keys(kbd);
Peter Maydell31819e92019-02-25 10:24:27 +00001164 });
John Arbuckle3b178b72015-09-25 23:14:00 +01001165}
Akihiko Odaki91aa5082024-02-24 21:43:37 +09001166
1167- (void) raiseAllButtons
1168{
1169 with_bql(^{
1170 qemu_input_queue_btn(dcl.con, INPUT_BUTTON_LEFT, false);
1171 qemu_input_queue_btn(dcl.con, INPUT_BUTTON_RIGHT, false);
1172 qemu_input_queue_btn(dcl.con, INPUT_BUTTON_MIDDLE, false);
1173 });
1174}
bellard5b0753e2005-03-01 21:37:28 +00001175@end
1176
1177
thsc304f7e2008-01-22 23:25:15 +00001178
bellard5b0753e2005-03-01 21:37:28 +00001179/*
1180 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +00001181 QemuCocoaAppController
bellard5b0753e2005-03-01 21:37:28 +00001182 ------------------------------------------------------
1183*/
thsc304f7e2008-01-22 23:25:15 +00001184@interface QemuCocoaAppController : NSObject
John Arbuckled9bc14f2015-09-25 23:13:59 +01001185 <NSWindowDelegate, NSApplicationDelegate>
bellard5b0753e2005-03-01 21:37:28 +00001186{
1187}
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001188- (void)doToggleFullScreen:(id)sender;
thsc304f7e2008-01-22 23:25:15 +00001189- (void)showQEMUDoc:(id)sender;
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001190- (void)zoomToFit:(id) sender;
Programmingkidb4c6a112015-05-19 09:11:18 +01001191- (void)displayConsole:(id)sender;
John Arbuckle8524f1c2015-06-19 10:53:27 +01001192- (void)pauseQEMU:(id)sender;
1193- (void)resumeQEMU:(id)sender;
1194- (void)displayPause;
1195- (void)removePause;
John Arbuckle27074612015-06-19 10:53:27 +01001196- (void)restartQEMU:(id)sender;
1197- (void)powerDownQEMU:(id)sender;
John Arbuckle693a3e02015-06-19 10:53:27 +01001198- (void)ejectDeviceMedia:(id)sender;
1199- (void)changeDeviceMedia:(id)sender;
John Arbuckled9bc14f2015-09-25 23:13:59 +01001200- (BOOL)verifyQuit;
John Arbucklef4747902016-03-23 14:26:17 +00001201- (void)openDocumentation:(NSString *)filename;
Programmingkid9e8204b2016-08-15 22:11:06 -04001202- (IBAction) do_about_menu_item: (id) sender;
John Arbucklee47ec1a2017-06-13 23:17:38 -04001203- (void)adjustSpeed:(id)sender;
bellard5b0753e2005-03-01 21:37:28 +00001204@end
1205
thsc304f7e2008-01-22 23:25:15 +00001206@implementation QemuCocoaAppController
1207- (id) init
1208{
Akihiko Odaki0c358862024-02-24 21:43:38 +09001209 NSWindow *window;
1210
thsc304f7e2008-01-22 23:25:15 +00001211 COCOA_DEBUG("QemuCocoaAppController: init\n");
1212
1213 self = [super init];
1214 if (self) {
1215
1216 // create a view and add it to the window
1217 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1218 if(!cocoaView) {
Akihiko Odaki43137392021-02-23 22:11:06 +09001219 error_report("(cocoa) can't create a view");
thsc304f7e2008-01-22 23:25:15 +00001220 exit(1);
1221 }
1222
1223 // create a window
Akihiko Odaki0c358862024-02-24 21:43:38 +09001224 window = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001225 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
thsc304f7e2008-01-22 23:25:15 +00001226 backing:NSBackingStoreBuffered defer:NO];
Akihiko Odaki0c358862024-02-24 21:43:38 +09001227 if(!window) {
Akihiko Odaki43137392021-02-23 22:11:06 +09001228 error_report("(cocoa) can't create window");
thsc304f7e2008-01-22 23:25:15 +00001229 exit(1);
1230 }
Akihiko Odaki0c358862024-02-24 21:43:38 +09001231 [window setAcceptsMouseMovedEvents:YES];
1232 [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
1233 [window setTitle:qemu_name ? [NSString stringWithFormat:@"QEMU %s", qemu_name] : @"QEMU"];
1234 [window setContentView:cocoaView];
1235 [window makeKeyAndOrderFront:self];
1236 [window center];
1237 [window setDelegate: self];
John Arbuckle8524f1c2015-06-19 10:53:27 +01001238
1239 /* Used for displaying pause on the screen */
1240 pauseLabel = [NSTextField new];
1241 [pauseLabel setBezeled:YES];
1242 [pauseLabel setDrawsBackground:YES];
1243 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1244 [pauseLabel setEditable:NO];
1245 [pauseLabel setSelectable:NO];
1246 [pauseLabel setStringValue: @"Paused"];
1247 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1248 [pauseLabel setTextColor: [NSColor blackColor]];
1249 [pauseLabel sizeToFit];
thsc304f7e2008-01-22 23:25:15 +00001250 }
1251 return self;
1252}
1253
1254- (void) dealloc
1255{
1256 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1257
1258 if (cocoaView)
1259 [cocoaView release];
1260 [super dealloc];
1261}
1262
bellard5b0753e2005-03-01 21:37:28 +00001263- (void)applicationDidFinishLaunching: (NSNotification *) note
1264{
thsc304f7e2008-01-22 23:25:15 +00001265 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
Hikaru Nishidadff742a2019-10-15 10:07:34 +09001266 allow_events = true;
bellard5b0753e2005-03-01 21:37:28 +00001267}
1268
1269- (void)applicationWillTerminate:(NSNotification *)aNotification
1270{
thsc304f7e2008-01-22 23:25:15 +00001271 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1272
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001273 with_bql(^{
Akihiko Odaki2910abd2022-05-29 17:25:08 +09001274 shutdown_action = SHUTDOWN_ACTION_POWEROFF;
1275 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1276 });
Akihiko Odaki40c01932021-02-19 20:16:52 +09001277
1278 /*
1279 * Sleep here, because returning will cause OSX to kill us
1280 * immediately; the QEMU main loop will handle the shutdown
1281 * request and terminate the process.
1282 */
1283 [NSThread sleepForTimeInterval:INFINITY];
bellard5b0753e2005-03-01 21:37:28 +00001284}
1285
Andreas Färber41ea49b2009-12-14 22:13:27 +01001286- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1287{
1288 return YES;
1289}
1290
John Arbuckled9bc14f2015-09-25 23:13:59 +01001291- (NSApplicationTerminateReply)applicationShouldTerminate:
1292 (NSApplication *)sender
1293{
1294 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1295 return [self verifyQuit];
1296}
1297
Akihiko Odaki15280e82021-06-16 23:19:10 +09001298- (void)windowDidChangeScreen:(NSNotification *)notification
1299{
1300 [cocoaView updateUIInfo];
1301}
1302
Akihiko Odaki91aa5082024-02-24 21:43:37 +09001303- (void)windowDidEnterFullScreen:(NSNotification *)notification
1304{
1305 [cocoaView grabMouse];
1306}
1307
1308- (void)windowDidExitFullScreen:(NSNotification *)notification
1309{
1310 [cocoaView resizeWindow];
1311 [cocoaView ungrabMouse];
1312}
1313
Akihiko Odaki15280e82021-06-16 23:19:10 +09001314- (void)windowDidResize:(NSNotification *)notification
1315{
Akihiko Odakifcb03de2024-02-24 21:43:35 +09001316 [cocoaView updateBounds];
Akihiko Odaki91aa5082024-02-24 21:43:37 +09001317 [cocoaView frameUpdated];
Akihiko Odaki15280e82021-06-16 23:19:10 +09001318}
1319
John Arbuckled9bc14f2015-09-25 23:13:59 +01001320/* Called when the user clicks on a window's close button */
1321- (BOOL)windowShouldClose:(id)sender
1322{
1323 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1324 [NSApp terminate: sender];
1325 /* If the user allows the application to quit then the call to
1326 * NSApp terminate will never return. If we get here then the user
1327 * cancelled the quit, so we should return NO to not permit the
1328 * closing of this window.
1329 */
1330 return NO;
1331}
1332
Akihiko Odaki91aa5082024-02-24 21:43:37 +09001333- (NSApplicationPresentationOptions) window:(NSWindow *)window
1334 willUseFullScreenPresentationOptions:(NSApplicationPresentationOptions)proposedOptions;
1335
1336{
1337 return (proposedOptions & ~(NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)) |
1338 NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar;
1339}
1340
Akihiko Odaki9d9bc7d2023-02-28 16:09:46 +09001341/*
1342 * Called when QEMU goes into the background. Note that
1343 * [-NSWindowDelegate windowDidResignKey:] is used here instead of
1344 * [-NSApplicationDelegate applicationWillResignActive:] because it cannot
1345 * detect that the window loses focus when the deck is clicked on macOS 13.2.1.
1346 */
1347- (void) windowDidResignKey: (NSNotification *)aNotification
John Arbuckle3b178b72015-09-25 23:14:00 +01001348{
Akihiko Odaki9d9bc7d2023-02-28 16:09:46 +09001349 COCOA_DEBUG("%s\n", __func__);
Carwyn Ellis69221df2022-01-02 17:41:53 +00001350 [cocoaView ungrabMouse];
John Arbuckle3b178b72015-09-25 23:14:00 +01001351 [cocoaView raiseAllKeys];
1352}
1353
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001354/* We abstract the method called by the Enter Fullscreen menu item
1355 * because Mac OS 10.7 and higher disables it. This is because of the
1356 * menu item's old selector's name toggleFullScreen:
1357 */
1358- (void) doToggleFullScreen:(id)sender
1359{
Akihiko Odaki0c358862024-02-24 21:43:38 +09001360 [[cocoaView window] toggleFullScreen:sender];
thsc304f7e2008-01-22 23:25:15 +00001361}
1362
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +09001363- (void) setFullGrab:(id)sender
1364{
1365 COCOA_DEBUG("QemuCocoaAppController: setFullGrab\n");
1366
1367 [cocoaView setFullGrab:sender];
1368}
1369
John Arbucklef4747902016-03-23 14:26:17 +00001370/* Tries to find then open the specified filename */
1371- (void) openDocumentation: (NSString *) filename
1372{
1373 /* Where to look for local files */
Roman Bolshakov8d6fda82021-01-09 00:38:15 +03001374 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
John Arbucklef4747902016-03-23 14:26:17 +00001375 NSString *full_file_path;
Roman Bolshakov1ff5a062021-01-02 18:07:21 +03001376 NSURL *full_file_url;
John Arbucklef4747902016-03-23 14:26:17 +00001377
1378 /* iterate thru the possible paths until the file is found */
1379 int index;
1380 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1381 full_file_path = [[NSBundle mainBundle] executablePath];
1382 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1383 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1384 path_array[index], filename];
Roman Bolshakov1ff5a062021-01-02 18:07:21 +03001385 full_file_url = [NSURL fileURLWithPath: full_file_path
1386 isDirectory: false];
1387 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
John Arbucklef4747902016-03-23 14:26:17 +00001388 return;
1389 }
1390 }
1391
1392 /* If none of the paths opened a file */
1393 NSBeep();
1394 QEMU_Alert(@"Failed to open file");
1395}
1396
thsc304f7e2008-01-22 23:25:15 +00001397- (void)showQEMUDoc:(id)sender
1398{
1399 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1400
Peter Maydell1879f242020-02-28 15:36:16 +00001401 [self openDocumentation: @"index.html"];
thsc304f7e2008-01-22 23:25:15 +00001402}
1403
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001404/* Stretches video to fit host monitor size */
1405- (void)zoomToFit:(id) sender
1406{
Akihiko Odaki55766632024-02-24 21:43:41 +09001407 NSWindowStyleMask styleMask = [[cocoaView window] styleMask] ^ NSWindowStyleMaskResizable;
1408
1409 [[cocoaView window] setStyleMask:styleMask];
1410 [sender setState:styleMask & NSWindowStyleMaskResizable ? NSControlStateValueOn : NSControlStateValueOff];
Akihiko Odakif69a6f02024-03-23 15:20:02 +09001411 [cocoaView resizeWindow];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001412}
bellard5b0753e2005-03-01 21:37:28 +00001413
Carwyn Ellise28a9092023-11-10 16:17:29 +00001414- (void)toggleZoomInterpolation:(id) sender
1415{
1416 if (zoom_interpolation == kCGInterpolationNone) {
1417 zoom_interpolation = kCGInterpolationLow;
1418 [sender setState: NSControlStateValueOn];
1419 } else {
1420 zoom_interpolation = kCGInterpolationNone;
1421 [sender setState: NSControlStateValueOff];
1422 }
1423}
1424
Programmingkidb4c6a112015-05-19 09:11:18 +01001425/* Displays the console on the screen */
1426- (void)displayConsole:(id)sender
1427{
Akihiko Odaki4b49f922024-02-24 21:43:40 +09001428 with_bql(^{
Akihiko Odakica3de7b2024-03-19 12:08:41 +09001429 [cocoaView selectConsoleLocked:[sender tag]];
Akihiko Odaki4b49f922024-02-24 21:43:40 +09001430 });
Programmingkidb4c6a112015-05-19 09:11:18 +01001431}
John Arbuckle8524f1c2015-06-19 10:53:27 +01001432
1433/* Pause the guest */
1434- (void)pauseQEMU:(id)sender
1435{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001436 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001437 qmp_stop(NULL);
1438 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001439 [sender setEnabled: NO];
1440 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1441 [self displayPause];
1442}
1443
1444/* Resume running the guest operating system */
1445- (void)resumeQEMU:(id) sender
1446{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001447 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001448 qmp_cont(NULL);
1449 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001450 [sender setEnabled: NO];
1451 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1452 [self removePause];
1453}
1454
1455/* Displays the word pause on the screen */
1456- (void)displayPause
1457{
1458 /* Coordinates have to be calculated each time because the window can change its size */
1459 int xCoord, yCoord, width, height;
Akihiko Odaki1a4b64a2024-02-24 21:43:36 +09001460 xCoord = ([cocoaView frame].size.width - [pauseLabel frame].size.width)/2;
1461 yCoord = [cocoaView frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
John Arbuckle8524f1c2015-06-19 10:53:27 +01001462 width = [pauseLabel frame].size.width;
1463 height = [pauseLabel frame].size.height;
1464 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1465 [cocoaView addSubview: pauseLabel];
1466}
1467
1468/* Removes the word pause from the screen */
1469- (void)removePause
1470{
1471 [pauseLabel removeFromSuperview];
1472}
1473
John Arbuckle27074612015-06-19 10:53:27 +01001474/* Restarts QEMU */
1475- (void)restartQEMU:(id)sender
1476{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001477 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001478 qmp_system_reset(NULL);
1479 });
John Arbuckle27074612015-06-19 10:53:27 +01001480}
1481
1482/* Powers down QEMU */
1483- (void)powerDownQEMU:(id)sender
1484{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001485 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001486 qmp_system_powerdown(NULL);
1487 });
John Arbuckle27074612015-06-19 10:53:27 +01001488}
1489
John Arbuckle693a3e02015-06-19 10:53:27 +01001490/* Ejects the media.
1491 * Uses sender's tag to figure out the device to eject.
1492 */
1493- (void)ejectDeviceMedia:(id)sender
1494{
1495 NSString * drive;
1496 drive = [sender representedObject];
1497 if(drive == nil) {
1498 NSBeep();
1499 QEMU_Alert(@"Failed to find drive to eject!");
1500 return;
1501 }
1502
Peter Maydell31819e92019-02-25 10:24:27 +00001503 __block Error *err = NULL;
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001504 with_bql(^{
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001505 qmp_eject([drive cStringUsingEncoding: NSASCIIStringEncoding],
1506 NULL, false, false, &err);
Peter Maydell31819e92019-02-25 10:24:27 +00001507 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001508 handleAnyDeviceErrors(err);
1509}
1510
1511/* Displays a dialog box asking the user to select an image file to load.
1512 * Uses sender's represented object value to figure out which drive to use.
1513 */
1514- (void)changeDeviceMedia:(id)sender
1515{
1516 /* Find the drive name */
1517 NSString * drive;
1518 drive = [sender representedObject];
1519 if(drive == nil) {
1520 NSBeep();
1521 QEMU_Alert(@"Could not find drive!");
1522 return;
1523 }
1524
1525 /* Display the file open dialog */
1526 NSOpenPanel * openPanel;
1527 openPanel = [NSOpenPanel openPanel];
1528 [openPanel setCanChooseFiles: YES];
1529 [openPanel setAllowsMultipleSelection: NO];
Peter Maydellb5725382018-05-29 19:15:23 +01001530 if([openPanel runModal] == NSModalResponseOK) {
John Arbuckle693a3e02015-06-19 10:53:27 +01001531 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1532 if(file == nil) {
1533 NSBeep();
1534 QEMU_Alert(@"Failed to convert URL to file path!");
1535 return;
1536 }
1537
Peter Maydell31819e92019-02-25 10:24:27 +00001538 __block Error *err = NULL;
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001539 with_bql(^{
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001540 qmp_blockdev_change_medium([drive cStringUsingEncoding:
Peter Maydell31819e92019-02-25 10:24:27 +00001541 NSASCIIStringEncoding],
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001542 NULL,
Peter Maydell31819e92019-02-25 10:24:27 +00001543 [file cStringUsingEncoding:
1544 NSASCIIStringEncoding],
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001545 "raw",
Denis V. Lunev80dd5af2022-04-13 01:18:46 +03001546 true, false,
Peter Maydell31819e92019-02-25 10:24:27 +00001547 false, 0,
1548 &err);
1549 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001550 handleAnyDeviceErrors(err);
1551 }
1552}
1553
John Arbuckled9bc14f2015-09-25 23:13:59 +01001554/* Verifies if the user really wants to quit */
1555- (BOOL)verifyQuit
1556{
1557 NSAlert *alert = [NSAlert new];
1558 [alert autorelease];
1559 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1560 [alert addButtonWithTitle: @"Cancel"];
1561 [alert addButtonWithTitle: @"Quit"];
1562 if([alert runModal] == NSAlertSecondButtonReturn) {
1563 return YES;
1564 } else {
1565 return NO;
1566 }
1567}
1568
Programmingkid9e8204b2016-08-15 22:11:06 -04001569/* The action method for the About menu item */
1570- (IBAction) do_about_menu_item: (id) sender
1571{
Akihiko Odaki99eb3132022-02-27 13:22:41 +09001572 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1573 char *icon_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1574 NSString *icon_path = [NSString stringWithUTF8String:icon_path_c];
1575 g_free(icon_path_c);
1576 NSImage *icon = [[NSImage alloc] initWithContentsOfFile:icon_path];
1577 NSString *version = @"QEMU emulator version " QEMU_FULL_VERSION;
1578 NSString *copyright = @QEMU_COPYRIGHT;
1579 NSDictionary *options;
1580 if (icon) {
1581 options = @{
1582 NSAboutPanelOptionApplicationIcon : icon,
1583 NSAboutPanelOptionApplicationVersion : version,
1584 @"Copyright" : copyright,
1585 };
1586 [icon release];
1587 } else {
1588 options = @{
1589 NSAboutPanelOptionApplicationVersion : version,
1590 @"Copyright" : copyright,
1591 };
Akihiko Odakia0f973f2021-03-09 21:22:26 +09001592 }
Akihiko Odaki99eb3132022-02-27 13:22:41 +09001593 [NSApp orderFrontStandardAboutPanelWithOptions:options];
1594 [pool release];
Programmingkid9e8204b2016-08-15 22:11:06 -04001595}
1596
John Arbucklee47ec1a2017-06-13 23:17:38 -04001597/* Used by the Speed menu items */
1598- (void)adjustSpeed:(id)sender
1599{
1600 int throttle_pct; /* throttle percentage */
1601 NSMenu *menu;
1602
1603 menu = [sender menu];
1604 if (menu != nil)
1605 {
1606 /* Unselect the currently selected item */
1607 for (NSMenuItem *item in [menu itemArray]) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001608 if (item.state == NSControlStateValueOn) {
1609 [item setState: NSControlStateValueOff];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001610 break;
1611 }
1612 }
1613 }
1614
1615 // check the menu item
Brendan Shanks5e246002019-01-31 23:12:25 -08001616 [sender setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001617
1618 // get the throttle percentage
1619 throttle_pct = [sender tag];
1620
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001621 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001622 cpu_throttle_set(throttle_pct);
1623 });
John Arbucklee47ec1a2017-06-13 23:17:38 -04001624 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1625}
1626
Programmingkidb4c6a112015-05-19 09:11:18 +01001627@end
bellard5b0753e2005-03-01 21:37:28 +00001628
Peter Maydell61a2ed42019-02-25 10:24:32 +00001629@interface QemuApplication : NSApplication
1630@end
1631
1632@implementation QemuApplication
1633- (void)sendEvent:(NSEvent *)event
1634{
1635 COCOA_DEBUG("QemuApplication: sendEvent\n");
Peter Maydell55888402019-02-25 10:24:33 +00001636 if (![cocoaView handleEvent:event]) {
1637 [super sendEvent: event];
1638 }
Peter Maydell61a2ed42019-02-25 10:24:32 +00001639}
1640@end
1641
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001642static void create_initial_menus(void)
1643{
thsc304f7e2008-01-22 23:25:15 +00001644 // Add menus
1645 NSMenu *menu;
1646 NSMenuItem *menuItem;
1647
bellard5b0753e2005-03-01 21:37:28 +00001648 [NSApp setMainMenu:[[NSMenu alloc] init]];
Akihiko Odaki5b6988c2022-02-14 18:13:20 +09001649 [NSApp setServicesMenu:[[NSMenu alloc] initWithTitle:@"Services"]];
bellard5b0753e2005-03-01 21:37:28 +00001650
thsc304f7e2008-01-22 23:25:15 +00001651 // Application menu
1652 menu = [[NSMenu alloc] initWithTitle:@""];
Programmingkid9e8204b2016-08-15 22:11:06 -04001653 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
thsc304f7e2008-01-22 23:25:15 +00001654 [menu addItem:[NSMenuItem separatorItem]]; //Separator
Akihiko Odaki5b6988c2022-02-14 18:13:20 +09001655 menuItem = [menu addItemWithTitle:@"Services" action:nil keyEquivalent:@""];
1656 [menuItem setSubmenu:[NSApp servicesMenu]];
1657 [menu addItem:[NSMenuItem separatorItem]];
thsc304f7e2008-01-22 23:25:15 +00001658 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1659 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001660 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
thsc304f7e2008-01-22 23:25:15 +00001661 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1662 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1663 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1664 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1665 [menuItem setSubmenu:menu];
1666 [[NSApp mainMenu] addItem:menuItem];
1667 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
ths3b46e622007-09-17 08:09:54 +00001668
John Arbuckle8524f1c2015-06-19 10:53:27 +01001669 // Machine menu
1670 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1671 [menu setAutoenablesItems: NO];
1672 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1673 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1674 [menu addItem: menuItem];
1675 [menuItem setEnabled: NO];
John Arbuckle27074612015-06-19 10:53:27 +01001676 [menu addItem: [NSMenuItem separatorItem]];
1677 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1678 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
John Arbuckle8524f1c2015-06-19 10:53:27 +01001679 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1680 [menuItem setSubmenu:menu];
1681 [[NSApp mainMenu] addItem:menuItem];
1682
thsc304f7e2008-01-22 23:25:15 +00001683 // View menu
1684 menu = [[NSMenu alloc] initWithTitle:@"View"];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001685 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
Carwyn Ellis5ec08982023-10-27 16:49:20 +01001686 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease];
Akihiko Odaki55766632024-02-24 21:43:41 +09001687 [menuItem setState: [[cocoaView window] styleMask] & NSWindowStyleMaskResizable ? NSControlStateValueOn : NSControlStateValueOff];
Carwyn Ellis5ec08982023-10-27 16:49:20 +01001688 [menu addItem: menuItem];
Carwyn Ellise28a9092023-11-10 16:17:29 +00001689 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Zoom Interpolation" action:@selector(toggleZoomInterpolation:) keyEquivalent:@""] autorelease];
1690 [menuItem setState: zoom_interpolation == kCGInterpolationLow ? NSControlStateValueOn : NSControlStateValueOff];
1691 [menu addItem: menuItem];
thsc304f7e2008-01-22 23:25:15 +00001692 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1693 [menuItem setSubmenu:menu];
1694 [[NSApp mainMenu] addItem:menuItem];
1695
John Arbucklee47ec1a2017-06-13 23:17:38 -04001696 // Speed menu
1697 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1698
1699 // Add the rest of the Speed menu items
1700 int p, percentage, throttle_pct;
1701 for (p = 10; p >= 0; p--)
1702 {
1703 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1704
1705 menuItem = [[[NSMenuItem alloc]
1706 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1707
1708 if (percentage == 100) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001709 [menuItem setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001710 }
1711
1712 /* Calculate the throttle percentage */
1713 throttle_pct = -1 * percentage + 100;
1714
1715 [menuItem setTag: throttle_pct];
1716 [menu addItem: menuItem];
1717 }
1718 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1719 [menuItem setSubmenu:menu];
1720 [[NSApp mainMenu] addItem:menuItem];
1721
thsc304f7e2008-01-22 23:25:15 +00001722 // Window menu
1723 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1724 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1725 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1726 [menuItem setSubmenu:menu];
1727 [[NSApp mainMenu] addItem:menuItem];
1728 [NSApp setWindowsMenu:menu];
1729
1730 // Help menu
1731 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1732 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
thsc304f7e2008-01-22 23:25:15 +00001733 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1734 [menuItem setSubmenu:menu];
1735 [[NSApp mainMenu] addItem:menuItem];
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001736}
1737
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001738/* Returns a name for a given console */
1739static NSString * getConsoleName(QemuConsole * console)
1740{
Akihiko Odakica511602022-02-15 09:03:05 +01001741 g_autofree char *label = qemu_console_get_label(console);
1742
1743 return [NSString stringWithUTF8String:label];
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001744}
1745
1746/* Add an entry to the View menu for each console */
1747static void add_console_menu_entries(void)
1748{
1749 NSMenu *menu;
1750 NSMenuItem *menuItem;
1751 int index = 0;
1752
1753 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1754
1755 [menu addItem:[NSMenuItem separatorItem]];
1756
1757 while (qemu_console_lookup_by_index(index) != NULL) {
1758 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1759 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1760 [menuItem setTag: index];
1761 [menu addItem: menuItem];
1762 index++;
1763 }
1764}
1765
1766/* Make menu items for all removable devices.
1767 * Each device is given an 'Eject' and 'Change' menu item.
1768 */
1769static void addRemovableDevicesMenuItems(void)
1770{
1771 NSMenu *menu;
1772 NSMenuItem *menuItem;
1773 BlockInfoList *currentDevice, *pointerToFree;
1774 NSString *deviceName;
1775
1776 currentDevice = qmp_query_block(NULL);
1777 pointerToFree = currentDevice;
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001778
1779 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1780
1781 // Add a separator between related groups of menu items
1782 [menu addItem:[NSMenuItem separatorItem]];
1783
1784 // Set the attributes to the "Removable Media" menu item
1785 NSString *titleString = @"Removable Media";
1786 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1787 NSColor *newColor = [NSColor blackColor];
1788 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1789 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1790 traits:NSBoldFontMask|NSItalicFontMask
1791 weight:0
1792 size:14];
1793 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1794 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1795 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1796
1797 // Add the "Removable Media" menu item
1798 menuItem = [NSMenuItem new];
1799 [menuItem setAttributedTitle: attString];
1800 [menuItem setEnabled: NO];
1801 [menu addItem: menuItem];
1802
1803 /* Loop through all the block devices in the emulator */
1804 while (currentDevice) {
1805 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1806
1807 if(currentDevice->value->removable) {
1808 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1809 action: @selector(changeDeviceMedia:)
1810 keyEquivalent: @""];
1811 [menu addItem: menuItem];
1812 [menuItem setRepresentedObject: deviceName];
1813 [menuItem autorelease];
1814
1815 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1816 action: @selector(ejectDeviceMedia:)
1817 keyEquivalent: @""];
1818 [menu addItem: menuItem];
1819 [menuItem setRepresentedObject: deviceName];
1820 [menuItem autorelease];
1821 }
1822 currentDevice = currentDevice->next;
1823 }
1824 qapi_free_BlockInfoList(pointerToFree);
1825}
1826
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001827@interface QemuCocoaPasteboardTypeOwner : NSObject<NSPasteboardTypeOwner>
1828@end
1829
1830@implementation QemuCocoaPasteboardTypeOwner
1831
1832- (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)type
1833{
1834 if (type != NSPasteboardTypeString) {
1835 return;
1836 }
1837
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001838 with_bql(^{
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001839 QemuClipboardInfo *info = qemu_clipboard_info_ref(cbinfo);
1840 qemu_event_reset(&cbevent);
1841 qemu_clipboard_request(info, QEMU_CLIPBOARD_TYPE_TEXT);
1842
1843 while (info == cbinfo &&
1844 info->types[QEMU_CLIPBOARD_TYPE_TEXT].available &&
1845 info->types[QEMU_CLIPBOARD_TYPE_TEXT].data == NULL) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001846 bql_unlock();
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001847 qemu_event_wait(&cbevent);
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001848 bql_lock();
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001849 }
1850
1851 if (info == cbinfo) {
1852 NSData *data = [[NSData alloc] initWithBytes:info->types[QEMU_CLIPBOARD_TYPE_TEXT].data
1853 length:info->types[QEMU_CLIPBOARD_TYPE_TEXT].size];
1854 [sender setData:data forType:NSPasteboardTypeString];
1855 [data release];
1856 }
1857
1858 qemu_clipboard_info_unref(info);
1859 });
1860}
1861
1862@end
1863
1864static QemuCocoaPasteboardTypeOwner *cbowner;
1865
1866static void cocoa_clipboard_notify(Notifier *notifier, void *data);
1867static void cocoa_clipboard_request(QemuClipboardInfo *info,
1868 QemuClipboardType type);
1869
1870static QemuClipboardPeer cbpeer = {
1871 .name = "cocoa",
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001872 .notifier = { .notify = cocoa_clipboard_notify },
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001873 .request = cocoa_clipboard_request
1874};
1875
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001876static void cocoa_clipboard_update_info(QemuClipboardInfo *info)
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001877{
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001878 if (info->owner == &cbpeer || info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
1879 return;
1880 }
1881
1882 if (info != cbinfo) {
1883 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1884 qemu_clipboard_info_unref(cbinfo);
1885 cbinfo = qemu_clipboard_info_ref(info);
1886 cbchangecount = [[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:cbowner];
1887 [pool release];
1888 }
1889
1890 qemu_event_set(&cbevent);
1891}
1892
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001893static void cocoa_clipboard_notify(Notifier *notifier, void *data)
1894{
1895 QemuClipboardNotify *notify = data;
1896
1897 switch (notify->type) {
1898 case QEMU_CLIPBOARD_UPDATE_INFO:
1899 cocoa_clipboard_update_info(notify->info);
1900 return;
Marc-André Lureau505dbf92021-07-19 19:49:56 +04001901 case QEMU_CLIPBOARD_RESET_SERIAL:
1902 /* ignore */
1903 return;
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001904 }
1905}
1906
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001907static void cocoa_clipboard_request(QemuClipboardInfo *info,
1908 QemuClipboardType type)
1909{
Akihiko Odaki8c0d8022022-06-15 06:21:31 +09001910 NSAutoreleasePool *pool;
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001911 NSData *text;
1912
1913 switch (type) {
1914 case QEMU_CLIPBOARD_TYPE_TEXT:
Akihiko Odaki8c0d8022022-06-15 06:21:31 +09001915 pool = [[NSAutoreleasePool alloc] init];
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001916 text = [[NSPasteboard generalPasteboard] dataForType:NSPasteboardTypeString];
1917 if (text) {
1918 qemu_clipboard_set_data(&cbpeer, info, type,
1919 [text length], [text bytes], true);
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001920 }
Akihiko Odaki8c0d8022022-06-15 06:21:31 +09001921 [pool release];
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001922 break;
1923 default:
1924 break;
1925 }
1926}
1927
Peter Maydell55888402019-02-25 10:24:33 +00001928/*
1929 * The startup process for the OSX/Cocoa UI is complicated, because
1930 * OSX insists that the UI runs on the initial main thread, and so we
Akihiko Odakibab6a302022-08-19 22:27:54 +09001931 * need to start a second thread which runs the qemu_default_main():
Peter Maydell55888402019-02-25 10:24:33 +00001932 * in main():
Akihiko Odakibab6a302022-08-19 22:27:54 +09001933 * in cocoa_display_init():
1934 * assign cocoa_main to qemu_main
1935 * create application, menus, etc
1936 * in cocoa_main():
1937 * create qemu-main thread
1938 * enter OSX run loop
Peter Maydell55888402019-02-25 10:24:33 +00001939 */
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001940
Peter Maydell55888402019-02-25 10:24:33 +00001941static void *call_qemu_main(void *opaque)
1942{
1943 int status;
1944
Akihiko Odakibab6a302022-08-19 22:27:54 +09001945 COCOA_DEBUG("Second thread: calling qemu_default_main()\n");
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001946 bql_lock();
Akihiko Odakibab6a302022-08-19 22:27:54 +09001947 status = qemu_default_main();
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001948 bql_unlock();
Akihiko Odakibab6a302022-08-19 22:27:54 +09001949 COCOA_DEBUG("Second thread: qemu_default_main() returned, exiting\n");
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001950 [cbowner release];
Peter Maydell55888402019-02-25 10:24:33 +00001951 exit(status);
1952}
1953
Philippe Mathieu-Daudéf9750332023-04-23 18:55:28 +02001954static int cocoa_main(void)
Akihiko Odakibab6a302022-08-19 22:27:54 +09001955{
Peter Maydell55888402019-02-25 10:24:33 +00001956 QemuThread thread;
1957
Akihiko Odakibab6a302022-08-19 22:27:54 +09001958 COCOA_DEBUG("Entered %s()\n", __func__);
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001959
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001960 bql_unlock();
Peter Maydell55888402019-02-25 10:24:33 +00001961 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1962 NULL, QEMU_THREAD_DETACHED);
1963
thsc304f7e2008-01-22 23:25:15 +00001964 // Start the main event loop
Peter Maydell55888402019-02-25 10:24:33 +00001965 COCOA_DEBUG("Main thread: entering OSX run loop\n");
bellard5b0753e2005-03-01 21:37:28 +00001966 [NSApp run];
Akihiko Odakibab6a302022-08-19 22:27:54 +09001967 COCOA_DEBUG("Main thread: left OSX run loop, which should never happen\n");
ths3b46e622007-09-17 08:09:54 +00001968
Akihiko Odakibab6a302022-08-19 22:27:54 +09001969 abort();
bellard5b0753e2005-03-01 21:37:28 +00001970}
thsc304f7e2008-01-22 23:25:15 +00001971
1972
1973
1974#pragma mark qemu
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001975static void cocoa_update(DisplayChangeListener *dcl,
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001976 int x, int y, int w, int h)
thsc304f7e2008-01-22 23:25:15 +00001977{
1978 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1979
Peter Maydell55888402019-02-25 10:24:33 +00001980 dispatch_async(dispatch_get_main_queue(), ^{
Akihiko Odakifcb03de2024-02-24 21:43:35 +09001981 NSRect rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
Peter Maydell55888402019-02-25 10:24:33 +00001982 [cocoaView setNeedsDisplayInRect:rect];
1983 });
thsc304f7e2008-01-22 23:25:15 +00001984}
1985
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01001986static void cocoa_switch(DisplayChangeListener *dcl,
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01001987 DisplaySurface *surface)
thsc304f7e2008-01-22 23:25:15 +00001988{
Peter Maydell55888402019-02-25 10:24:33 +00001989 pixman_image_t *image = surface->image;
thsc304f7e2008-01-22 23:25:15 +00001990
Peter Maydell6e657e62013-04-22 10:29:46 +00001991 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
Peter Maydell55888402019-02-25 10:24:33 +00001992
1993 // The DisplaySurface will be freed as soon as this callback returns.
1994 // We take a reference to the underlying pixman image here so it does
1995 // not disappear from under our feet; the switchSurface method will
1996 // deref the old image when it is done with it.
1997 pixman_image_ref(image);
1998
1999 dispatch_async(dispatch_get_main_queue(), ^{
2000 [cocoaView switchSurface:image];
2001 });
thsc304f7e2008-01-22 23:25:15 +00002002}
2003
Gerd Hoffmannbc2ed972013-03-01 13:03:04 +01002004static void cocoa_refresh(DisplayChangeListener *dcl)
thsc304f7e2008-01-22 23:25:15 +00002005{
Peter Maydell6e657e62013-04-22 10:29:46 +00002006 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2007
thsc304f7e2008-01-22 23:25:15 +00002008 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
Akihiko Odakica3de7b2024-03-19 12:08:41 +09002009 graphic_hw_update(dcl->con);
thsc304f7e2008-01-22 23:25:15 +00002010
Akihiko Odaki0337e412023-09-21 17:29:34 +09002011 if (qemu_input_is_absolute(dcl->con)) {
Peter Maydell55888402019-02-25 10:24:33 +00002012 dispatch_async(dispatch_get_main_queue(), ^{
2013 if (![cocoaView isAbsoluteEnabled]) {
2014 if ([cocoaView isMouseGrabbed]) {
2015 [cocoaView ungrabMouse];
2016 }
thsc304f7e2008-01-22 23:25:15 +00002017 }
Peter Maydell55888402019-02-25 10:24:33 +00002018 [cocoaView setAbsoluteEnabled:YES];
2019 });
thsc304f7e2008-01-22 23:25:15 +00002020 }
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09002021
2022 if (cbchangecount != [[NSPasteboard generalPasteboard] changeCount]) {
2023 qemu_clipboard_info_unref(cbinfo);
2024 cbinfo = qemu_clipboard_info_new(&cbpeer, QEMU_CLIPBOARD_SELECTION_CLIPBOARD);
2025 if ([[NSPasteboard generalPasteboard] availableTypeFromArray:@[NSPasteboardTypeString]]) {
2026 cbinfo->types[QEMU_CLIPBOARD_TYPE_TEXT].available = true;
2027 }
2028 qemu_clipboard_update(cbinfo);
2029 cbchangecount = [[NSPasteboard generalPasteboard] changeCount];
2030 qemu_event_set(&cbevent);
2031 }
2032
Peter Maydell6e657e62013-04-22 10:29:46 +00002033 [pool release];
thsc304f7e2008-01-22 23:25:15 +00002034}
2035
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01002036static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
thsc304f7e2008-01-22 23:25:15 +00002037{
Akihiko Odakibab6a302022-08-19 22:27:54 +09002038 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2039
thsc304f7e2008-01-22 23:25:15 +00002040 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
2041
Akihiko Odakibab6a302022-08-19 22:27:54 +09002042 qemu_main = cocoa_main;
Peter Maydell55888402019-02-25 10:24:33 +00002043
Akihiko Odakibab6a302022-08-19 22:27:54 +09002044 // Pull this console process up to being a fully-fledged graphical
2045 // app with a menubar and Dock icon
2046 ProcessSerialNumber psn = { 0, kCurrentProcess };
2047 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
2048
2049 [QemuApplication sharedApplication];
2050
Akihiko Odakibab6a302022-08-19 22:27:54 +09002051 // Create an Application controller
2052 QemuCocoaAppController *controller = [[QemuCocoaAppController alloc] init];
2053 [NSApp setDelegate:controller];
2054
Programmingkid43227af2015-05-19 09:11:17 +01002055 /* if fullscreen mode is to be used */
Gerd Hoffmann767f9bf2018-02-02 12:10:19 +01002056 if (opts->has_full_screen && opts->full_screen) {
Akihiko Odaki0c358862024-02-24 21:43:38 +09002057 [[cocoaView window] toggleFullScreen: nil];
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +09002058 }
2059 if (opts->u.cocoa.has_full_grab && opts->u.cocoa.full_grab) {
Akihiko Odakibab6a302022-08-19 22:27:54 +09002060 [controller setFullGrab: nil];
Programmingkid43227af2015-05-19 09:11:17 +01002061 }
Carwyn Ellis69221df2022-01-02 17:41:53 +00002062
Gerd Hoffmann3487da62020-02-06 12:27:50 +01002063 if (opts->has_show_cursor && opts->show_cursor) {
2064 cursor_hide = 0;
2065 }
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +09002066 if (opts->u.cocoa.has_swap_opt_cmd) {
2067 swap_opt_cmd = opts->u.cocoa.swap_opt_cmd;
2068 }
Programmingkid43227af2015-05-19 09:11:17 +01002069
Carwyn Ellis48941a52022-01-02 17:41:52 +00002070 if (opts->u.cocoa.has_left_command_key && !opts->u.cocoa.left_command_key) {
2071 left_command_key_enabled = 0;
2072 }
2073
Carwyn Ellis5ec08982023-10-27 16:49:20 +01002074 if (opts->u.cocoa.has_zoom_to_fit && opts->u.cocoa.zoom_to_fit) {
Akihiko Odakib6ee03c2024-02-24 21:43:39 +09002075 [cocoaView window].styleMask |= NSWindowStyleMaskResizable;
Carwyn Ellis5ec08982023-10-27 16:49:20 +01002076 }
2077
Carwyn Ellise28a9092023-11-10 16:17:29 +00002078 if (opts->u.cocoa.has_zoom_interpolation && opts->u.cocoa.zoom_interpolation) {
2079 zoom_interpolation = kCGInterpolationLow;
2080 }
2081
Carwyn Ellis5ec08982023-10-27 16:49:20 +01002082 create_initial_menus();
2083 /*
2084 * Create the menu entries which depend on QEMU state (for consoles
2085 * and removable devices). These make calls back into QEMU functions,
2086 * which is OK because at this point we know that the second thread
Stefan Hajnoczia4a411f2024-01-02 10:35:28 -05002087 * holds the BQL and is synchronously waiting for us to
Carwyn Ellis5ec08982023-10-27 16:49:20 +01002088 * finish.
2089 */
2090 add_console_menu_entries();
2091 addRemovableDevicesMenuItems();
2092
Akihiko Odakica3de7b2024-03-19 12:08:41 +09002093 dcl.con = qemu_console_lookup_default();
2094 kbd = qkbd_state_init(dcl.con);
2095
aliguori9794f742009-03-04 19:25:22 +00002096 // register vga output callbacks
Akihiko Odakicc7859c2021-02-19 17:44:19 +09002097 register_displaychangelistener(&dcl);
Akihiko Odakica3de7b2024-03-19 12:08:41 +09002098 [cocoaView updateUIInfo];
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09002099
2100 qemu_event_init(&cbevent, false);
2101 cbowner = [[QemuCocoaPasteboardTypeOwner alloc] init];
2102 qemu_clipboard_peer_register(&cbpeer);
Akihiko Odakibab6a302022-08-19 22:27:54 +09002103
2104 [pool release];
thsc304f7e2008-01-22 23:25:15 +00002105}
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01002106
2107static QemuDisplay qemu_display_cocoa = {
2108 .type = DISPLAY_TYPE_COCOA,
2109 .init = cocoa_display_init,
2110};
2111
2112static void register_cocoa(void)
2113{
2114 qemu_display_register(&qemu_display_cocoa);
2115}
2116
2117type_init(register_cocoa);