blob: e1565270824a9cc5ddfffa5b0565cc35b22fa0df [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 Odaki99eb3132022-02-27 13:22:41 +090096static NSWindow *normalWindow;
Akihiko Odakicc7859c2021-02-19 17:44:19 +090097static const DisplayChangeListenerOps dcl_ops = {
98 .dpy_name = "cocoa",
99 .dpy_gfx_update = cocoa_update,
100 .dpy_gfx_switch = cocoa_switch,
101 .dpy_refresh = cocoa_refresh,
102};
103static DisplayChangeListener dcl = {
104 .ops = &dcl_ops,
105};
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
Akihiko Odakicb823402021-02-25 17:42:02 +0900110static bool stretch_video;
Carwyn Ellise28a9092023-11-10 16:17:29 +0000111static CGInterpolationQuality zoom_interpolation = kCGInterpolationNone;
Akihiko Odakicb823402021-02-25 17:42:02 +0900112static NSTextField *pauseLabel;
bellard5b0753e2005-03-01 21:37:28 +0000113
Hikaru Nishidadff742a2019-10-15 10:07:34 +0900114static bool allow_events;
Peter Maydell55888402019-02-25 10:24:33 +0000115
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +0900116static NSInteger cbchangecount = -1;
117static QemuClipboardInfo *cbinfo;
118static QemuEvent cbevent;
119
Stefan Hajnoczia4a411f2024-01-02 10:35:28 -0500120// Utility functions to run specified code block with the BQL held
Peter Maydell31819e92019-02-25 10:24:27 +0000121typedef void (^CodeBlock)(void);
Peter Maydell60105d72019-02-25 10:24:31 +0000122typedef bool (^BoolCodeBlock)(void);
Peter Maydell31819e92019-02-25 10:24:27 +0000123
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500124static void with_bql(CodeBlock block)
Peter Maydell31819e92019-02-25 10:24:27 +0000125{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500126 bool locked = bql_locked();
Peter Maydell31819e92019-02-25 10:24:27 +0000127 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500128 bql_lock();
Peter Maydell31819e92019-02-25 10:24:27 +0000129 }
130 block();
131 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500132 bql_unlock();
Peter Maydell31819e92019-02-25 10:24:27 +0000133 }
134}
135
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500136static bool bool_with_bql(BoolCodeBlock block)
Peter Maydell60105d72019-02-25 10:24:31 +0000137{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500138 bool locked = bql_locked();
Peter Maydell60105d72019-02-25 10:24:31 +0000139 bool val;
140
141 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500142 bql_lock();
Peter Maydell60105d72019-02-25 10:24:31 +0000143 }
144 val = block();
145 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500146 bql_unlock();
Peter Maydell60105d72019-02-25 10:24:31 +0000147 }
148 return val;
149}
150
John Arbuckleaaac7142016-03-23 14:26:18 +0000151// Mac to QKeyCode conversion
Akihiko Odakicb823402021-02-25 17:42:02 +0900152static const int mac_to_qkeycode_map[] = {
John Arbuckleaaac7142016-03-23 14:26:18 +0000153 [kVK_ANSI_A] = Q_KEY_CODE_A,
154 [kVK_ANSI_B] = Q_KEY_CODE_B,
155 [kVK_ANSI_C] = Q_KEY_CODE_C,
156 [kVK_ANSI_D] = Q_KEY_CODE_D,
157 [kVK_ANSI_E] = Q_KEY_CODE_E,
158 [kVK_ANSI_F] = Q_KEY_CODE_F,
159 [kVK_ANSI_G] = Q_KEY_CODE_G,
160 [kVK_ANSI_H] = Q_KEY_CODE_H,
161 [kVK_ANSI_I] = Q_KEY_CODE_I,
162 [kVK_ANSI_J] = Q_KEY_CODE_J,
163 [kVK_ANSI_K] = Q_KEY_CODE_K,
164 [kVK_ANSI_L] = Q_KEY_CODE_L,
165 [kVK_ANSI_M] = Q_KEY_CODE_M,
166 [kVK_ANSI_N] = Q_KEY_CODE_N,
167 [kVK_ANSI_O] = Q_KEY_CODE_O,
168 [kVK_ANSI_P] = Q_KEY_CODE_P,
169 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
170 [kVK_ANSI_R] = Q_KEY_CODE_R,
171 [kVK_ANSI_S] = Q_KEY_CODE_S,
172 [kVK_ANSI_T] = Q_KEY_CODE_T,
173 [kVK_ANSI_U] = Q_KEY_CODE_U,
174 [kVK_ANSI_V] = Q_KEY_CODE_V,
175 [kVK_ANSI_W] = Q_KEY_CODE_W,
176 [kVK_ANSI_X] = Q_KEY_CODE_X,
177 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
178 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
ths3b46e622007-09-17 08:09:54 +0000179
John Arbuckleaaac7142016-03-23 14:26:18 +0000180 [kVK_ANSI_0] = Q_KEY_CODE_0,
181 [kVK_ANSI_1] = Q_KEY_CODE_1,
182 [kVK_ANSI_2] = Q_KEY_CODE_2,
183 [kVK_ANSI_3] = Q_KEY_CODE_3,
184 [kVK_ANSI_4] = Q_KEY_CODE_4,
185 [kVK_ANSI_5] = Q_KEY_CODE_5,
186 [kVK_ANSI_6] = Q_KEY_CODE_6,
187 [kVK_ANSI_7] = Q_KEY_CODE_7,
188 [kVK_ANSI_8] = Q_KEY_CODE_8,
189 [kVK_ANSI_9] = Q_KEY_CODE_9,
190
191 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
192 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
193 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
194 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
195 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
196 [kVK_Tab] = Q_KEY_CODE_TAB,
197 [kVK_Return] = Q_KEY_CODE_RET,
198 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
199 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
200 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
201 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
202 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
203 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
204 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
205 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
John Arbuckleaaac7142016-03-23 14:26:18 +0000206 [kVK_Space] = Q_KEY_CODE_SPC,
207
208 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
209 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
210 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
211 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
212 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
213 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
214 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
215 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
216 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
217 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
218 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
219 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
220 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
221 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
222 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
223 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
224 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
225 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
226
227 [kVK_UpArrow] = Q_KEY_CODE_UP,
228 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
229 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
230 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
231
232 [kVK_Help] = Q_KEY_CODE_INSERT,
233 [kVK_Home] = Q_KEY_CODE_HOME,
234 [kVK_PageUp] = Q_KEY_CODE_PGUP,
235 [kVK_PageDown] = Q_KEY_CODE_PGDN,
236 [kVK_End] = Q_KEY_CODE_END,
237 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
238
239 [kVK_Escape] = Q_KEY_CODE_ESC,
240
241 /* The Power key can't be used directly because the operating system uses
242 * it. This key can be emulated by using it in place of another key such as
243 * F1. Don't forget to disable the real key binding.
244 */
245 /* [kVK_F1] = Q_KEY_CODE_POWER, */
246
247 [kVK_F1] = Q_KEY_CODE_F1,
248 [kVK_F2] = Q_KEY_CODE_F2,
249 [kVK_F3] = Q_KEY_CODE_F3,
250 [kVK_F4] = Q_KEY_CODE_F4,
251 [kVK_F5] = Q_KEY_CODE_F5,
252 [kVK_F6] = Q_KEY_CODE_F6,
253 [kVK_F7] = Q_KEY_CODE_F7,
254 [kVK_F8] = Q_KEY_CODE_F8,
255 [kVK_F9] = Q_KEY_CODE_F9,
256 [kVK_F10] = Q_KEY_CODE_F10,
257 [kVK_F11] = Q_KEY_CODE_F11,
258 [kVK_F12] = Q_KEY_CODE_F12,
259 [kVK_F13] = Q_KEY_CODE_PRINT,
260 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
261 [kVK_F15] = Q_KEY_CODE_PAUSE,
262
Akihiko Odaki708b7252021-02-12 09:04:04 +0900263 // JIS keyboards only
264 [kVK_JIS_Yen] = Q_KEY_CODE_YEN,
265 [kVK_JIS_Underscore] = Q_KEY_CODE_RO,
266 [kVK_JIS_KeypadComma] = Q_KEY_CODE_KP_COMMA,
267 [kVK_JIS_Eisu] = Q_KEY_CODE_MUHENKAN,
268 [kVK_JIS_Kana] = Q_KEY_CODE_HENKAN,
269
John Arbuckleaaac7142016-03-23 14:26:18 +0000270 /*
271 * The eject and volume keys can't be used here because they are handled at
272 * a lower level than what an Application can see.
273 */
bellard5b0753e2005-03-01 21:37:28 +0000274};
275
Andreas Färber77047bb2009-12-13 00:55:53 +0100276static int cocoa_keycode_to_qemu(int keycode)
bellard5b0753e2005-03-01 21:37:28 +0000277{
John Arbuckleaaac7142016-03-23 14:26:18 +0000278 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
Akihiko Odaki43137392021-02-23 22:11:06 +0900279 error_report("(cocoa) warning unknown keycode 0x%x", keycode);
bellard5b0753e2005-03-01 21:37:28 +0000280 return 0;
281 }
John Arbuckleaaac7142016-03-23 14:26:18 +0000282 return mac_to_qkeycode_map[keycode];
bellard5b0753e2005-03-01 21:37:28 +0000283}
284
John Arbuckle693a3e02015-06-19 10:53:27 +0100285/* Displays an alert dialog box with the specified message */
286static void QEMU_Alert(NSString *message)
287{
288 NSAlert *alert;
289 alert = [NSAlert new];
290 [alert setMessageText: message];
291 [alert runModal];
292}
thsc304f7e2008-01-22 23:25:15 +0000293
John Arbuckle693a3e02015-06-19 10:53:27 +0100294/* Handles any errors that happen with a device transaction */
295static void handleAnyDeviceErrors(Error * err)
296{
297 if (err) {
298 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
299 encoding: NSASCIIStringEncoding]);
300 error_free(err);
301 }
302}
thsc304f7e2008-01-22 23:25:15 +0000303
bellard5b0753e2005-03-01 21:37:28 +0000304/*
305 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +0000306 QemuCocoaView
bellard5b0753e2005-03-01 21:37:28 +0000307 ------------------------------------------------------
308*/
thsc304f7e2008-01-22 23:25:15 +0000309@interface QemuCocoaView : NSView
bellard5b0753e2005-03-01 21:37:28 +0000310{
thsc304f7e2008-01-22 23:25:15 +0000311 QEMUScreen screen;
312 NSWindow *fullScreenWindow;
313 float cx,cy,cw,ch,cdx,cdy;
Peter Maydell55888402019-02-25 10:24:33 +0000314 pixman_image_t *pixman_image;
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900315 QKbdState *kbd;
Peter Maydell49b9bd42013-12-08 22:59:03 +0000316 BOOL isMouseGrabbed;
thsc304f7e2008-01-22 23:25:15 +0000317 BOOL isFullscreen;
318 BOOL isAbsoluteEnabled;
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900319 CFMachPortRef eventsTap;
thsc304f7e2008-01-22 23:25:15 +0000320}
Peter Maydell72a3e312019-02-25 10:24:28 +0000321- (void) switchSurface:(pixman_image_t *)image;
thsc304f7e2008-01-22 23:25:15 +0000322- (void) grabMouse;
323- (void) ungrabMouse;
324- (void) toggleFullScreen:(id)sender;
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900325- (void) setFullGrab:(id)sender;
John Arbuckle9c3a4182017-11-07 10:14:14 +0000326- (void) handleMonitorInput:(NSEvent *)event;
Peter Maydell60105d72019-02-25 10:24:31 +0000327- (bool) handleEvent:(NSEvent *)event;
328- (bool) handleEventLocked:(NSEvent *)event;
thsc304f7e2008-01-22 23:25:15 +0000329- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
Peter Maydellf61c3872014-06-23 10:35:24 +0100330/* The state surrounding mouse grabbing is potentially confusing.
331 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
332 * pointing device an absolute-position one?"], but is only updated on
333 * next refresh.
334 * isMouseGrabbed tracks whether GUI events are directed to the guest;
335 * it controls whether special keys like Cmd get sent to the guest,
336 * and whether we capture the mouse when in non-absolute mode.
Peter Maydellf61c3872014-06-23 10:35:24 +0100337 */
Peter Maydell49b9bd42013-12-08 22:59:03 +0000338- (BOOL) isMouseGrabbed;
thsc304f7e2008-01-22 23:25:15 +0000339- (BOOL) isAbsoluteEnabled;
340- (float) cdx;
341- (float) cdy;
342- (QEMUScreen) gscreen;
John Arbuckle3b178b72015-09-25 23:14:00 +0100343- (void) raiseAllKeys;
thsc304f7e2008-01-22 23:25:15 +0000344@end
ths3b46e622007-09-17 08:09:54 +0000345
Andreas Färber7fee1992011-06-09 20:53:32 +0200346QemuCocoaView *cocoaView;
347
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900348static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEventRef cgEvent, void *userInfo)
349{
Philippe Mathieu-Daudé21eb7522023-10-04 14:00:13 +0200350 QemuCocoaView *view = userInfo;
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900351 NSEvent *event = [NSEvent eventWithCGEvent:cgEvent];
Philippe Mathieu-Daudé21eb7522023-10-04 14:00:13 +0200352 if ([view isMouseGrabbed] && [view handleEvent:event]) {
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900353 COCOA_DEBUG("Global events tap: qemu handled the event, capturing!\n");
354 return NULL;
355 }
356 COCOA_DEBUG("Global events tap: qemu did not handle the event, letting it through...\n");
357
358 return cgEvent;
359}
360
thsc304f7e2008-01-22 23:25:15 +0000361@implementation QemuCocoaView
362- (id)initWithFrame:(NSRect)frameRect
363{
364 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
ths3b46e622007-09-17 08:09:54 +0000365
thsc304f7e2008-01-22 23:25:15 +0000366 self = [super initWithFrame:frameRect];
367 if (self) {
pbrook95219892006-04-09 01:06:34 +0000368
thsc304f7e2008-01-22 23:25:15 +0000369 screen.width = frameRect.size.width;
370 screen.height = frameRect.size.height;
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900371 kbd = qkbd_state_init(dcl.con);
David Parsonsf5af8022024-02-24 14:06:20 +0000372#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_14_0
373 [self setClipsToBounds:YES];
374#endif
bellard7c206a72005-12-18 19:18:45 +0000375
thsc304f7e2008-01-22 23:25:15 +0000376 }
377 return self;
378}
bellard7c206a72005-12-18 19:18:45 +0000379
thsc304f7e2008-01-22 23:25:15 +0000380- (void) dealloc
381{
382 COCOA_DEBUG("QemuCocoaView: dealloc\n");
bellard7c206a72005-12-18 19:18:45 +0000383
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900384 if (pixman_image) {
Peter Maydell55888402019-02-25 10:24:33 +0000385 pixman_image_unref(pixman_image);
386 }
ths3b46e622007-09-17 08:09:54 +0000387
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900388 qkbd_state_free(kbd);
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900389
390 if (eventsTap) {
391 CFRelease(eventsTap);
392 }
393
thsc304f7e2008-01-22 23:25:15 +0000394 [super dealloc];
395}
bellard5cbfcd02006-06-14 15:53:24 +0000396
Andreas Färberd50f71d2009-12-13 02:03:33 +0100397- (BOOL) isOpaque
398{
399 return YES;
400}
401
Peter Maydell5dd45be2014-06-23 10:35:23 +0100402- (BOOL) screenContainsPoint:(NSPoint) p
403{
404 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
405}
406
Chen Zhang2044dff2019-06-04 17:36:00 +0800407/* Get location of event and convert to virtual screen coordinate */
408- (CGPoint) screenLocationOfEvent:(NSEvent *)ev
409{
410 NSWindow *eventWindow = [ev window];
411 // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
412 CGRect r = CGRectZero;
413 r.origin = [ev locationInWindow];
414 if (!eventWindow) {
415 if (!isFullscreen) {
416 return [[self window] convertRectFromScreen:r].origin;
417 } else {
418 CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
419 CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
420 if (stretch_video) {
421 loc.x /= cdx;
422 loc.y /= cdy;
423 }
424 return loc;
425 }
426 } else if ([[self window] isEqual:eventWindow]) {
427 if (!isFullscreen) {
428 return r.origin;
429 } else {
430 CGPoint loc = [self convertPoint:r.origin fromView:nil];
431 if (stretch_video) {
432 loc.x /= cdx;
433 loc.y /= cdy;
434 }
435 return loc;
436 }
437 } else {
438 return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
439 }
440}
441
Peter Maydell13aefd32014-06-23 10:35:25 +0100442- (void) hideCursor
443{
444 if (!cursor_hide) {
445 return;
446 }
447 [NSCursor hide];
448}
449
450- (void) unhideCursor
451{
452 if (!cursor_hide) {
453 return;
454 }
455 [NSCursor unhide];
456}
457
thsc304f7e2008-01-22 23:25:15 +0000458- (void) drawRect:(NSRect) rect
459{
460 COCOA_DEBUG("QemuCocoaView: drawRect\n");
bellard5cbfcd02006-06-14 15:53:24 +0000461
thsc304f7e2008-01-22 23:25:15 +0000462 // get CoreGraphic context
Brendan Shanks5e246002019-01-31 23:12:25 -0800463 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
Brendan Shanks5e246002019-01-31 23:12:25 -0800464
Carwyn Ellise28a9092023-11-10 16:17:29 +0000465 CGContextSetInterpolationQuality (viewContextRef, zoom_interpolation);
thsc304f7e2008-01-22 23:25:15 +0000466 CGContextSetShouldAntialias (viewContextRef, NO);
ths3b46e622007-09-17 08:09:54 +0000467
thsc304f7e2008-01-22 23:25:15 +0000468 // draw screen bitmap directly to Core Graphics context
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900469 if (!pixman_image) {
Peter Maydell7d270b12013-12-24 02:51:47 +0000470 // Draw request before any guest device has set up a framebuffer:
471 // just draw an opaque black rectangle
472 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
473 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
474 } else {
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900475 int w = pixman_image_get_width(pixman_image);
476 int h = pixman_image_get_height(pixman_image);
477 int bitsPerPixel = PIXMAN_FORMAT_BPP(pixman_image_get_format(pixman_image));
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900478 int stride = pixman_image_get_stride(pixman_image);
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900479 CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(
480 NULL,
481 pixman_image_get_data(pixman_image),
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900482 stride * h,
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900483 NULL
484 );
thsc304f7e2008-01-22 23:25:15 +0000485 CGImageRef imageRef = CGImageCreate(
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900486 w, //width
487 h, //height
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900488 DIV_ROUND_UP(bitsPerPixel, 8) * 2, //bitsPerComponent
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900489 bitsPerPixel, //bitsPerPixel
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900490 stride, //bytesPerRow
Akihiko Odakiae57d352021-03-05 21:13:04 +0900491 CGColorSpaceCreateWithName(kCGColorSpaceSRGB), //colorspace
492 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst, //bitmapInfo
thsc304f7e2008-01-22 23:25:15 +0000493 dataProviderRef, //provider
494 NULL, //decode
495 0, //interpolate
496 kCGRenderingIntentDefault //intent
497 );
Peter Maydellb63901d2015-05-19 09:11:17 +0100498 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
499 const NSRect *rectList;
Peter Maydellb63901d2015-05-19 09:11:17 +0100500 NSInteger rectCount;
Peter Maydellb63901d2015-05-19 09:11:17 +0100501 int i;
502 CGImageRef clipImageRef;
503 CGRect clipRect;
ths3b46e622007-09-17 08:09:54 +0000504
Peter Maydellb63901d2015-05-19 09:11:17 +0100505 [self getRectsBeingDrawn:&rectList count:&rectCount];
506 for (i = 0; i < rectCount; i++) {
507 clipRect.origin.x = rectList[i].origin.x / cdx;
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900508 clipRect.origin.y = (float)h - (rectList[i].origin.y + rectList[i].size.height) / cdy;
Peter Maydellb63901d2015-05-19 09:11:17 +0100509 clipRect.size.width = rectList[i].size.width / cdx;
510 clipRect.size.height = rectList[i].size.height / cdy;
511 clipImageRef = CGImageCreateWithImageInRect(
512 imageRef,
513 clipRect
514 );
515 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
516 CGImageRelease (clipImageRef);
bellard5b0753e2005-03-01 21:37:28 +0000517 }
thsc304f7e2008-01-22 23:25:15 +0000518 CGImageRelease (imageRef);
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900519 CGDataProviderRelease(dataProviderRef);
bellard5b0753e2005-03-01 21:37:28 +0000520 }
521}
522
thsc304f7e2008-01-22 23:25:15 +0000523- (void) setContentDimensions
bellard5b0753e2005-03-01 21:37:28 +0000524{
thsc304f7e2008-01-22 23:25:15 +0000525 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
ths3b46e622007-09-17 08:09:54 +0000526
thsc304f7e2008-01-22 23:25:15 +0000527 if (isFullscreen) {
528 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
529 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100530
531 /* stretches video, but keeps same aspect ratio */
532 if (stretch_video == true) {
533 /* use smallest stretch value - prevents clipping on sides */
534 if (MIN(cdx, cdy) == cdx) {
535 cdy = cdx;
536 } else {
537 cdx = cdy;
538 }
539 } else { /* No stretching */
540 cdx = cdy = 1;
541 }
thsc304f7e2008-01-22 23:25:15 +0000542 cw = screen.width * cdx;
543 ch = screen.height * cdy;
544 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
545 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
546 } else {
547 cx = 0;
548 cy = 0;
549 cw = screen.width;
550 ch = screen.height;
551 cdx = 1.0;
552 cdy = 1.0;
553 }
bellard5b0753e2005-03-01 21:37:28 +0000554}
555
Peter Maydell8d65dee2022-02-24 10:13:29 +0000556- (void) updateUIInfoLocked
Akihiko Odaki15280e82021-06-16 23:19:10 +0900557{
Stefan Hajnoczia4a411f2024-01-02 10:35:28 -0500558 /* Must be called with the BQL, i.e. via updateUIInfo */
Akihiko Odaki15280e82021-06-16 23:19:10 +0900559 NSSize frameSize;
560 QemuUIInfo info;
561
562 if (!qemu_console_is_graphic(dcl.con)) {
563 return;
564 }
565
566 if ([self window]) {
567 NSDictionary *description = [[[self window] screen] deviceDescription];
568 CGDirectDisplayID display = [[description objectForKey:@"NSScreenNumber"] unsignedIntValue];
569 NSSize screenSize = [[[self window] screen] frame].size;
570 CGSize screenPhysicalSize = CGDisplayScreenSize(display);
Akihiko Odaki52eaefd2022-07-02 23:25:19 +0900571 CVDisplayLinkRef displayLink;
Akihiko Odaki15280e82021-06-16 23:19:10 +0900572
573 frameSize = isFullscreen ? screenSize : [self frame].size;
Akihiko Odaki52eaefd2022-07-02 23:25:19 +0900574
575 if (!CVDisplayLinkCreateWithCGDisplay(display, &displayLink)) {
576 CVTime period = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLink);
577 CVDisplayLinkRelease(displayLink);
578 if (!(period.flags & kCVTimeIsIndefinite)) {
579 update_displaychangelistener(&dcl,
580 1000 * period.timeValue / period.timeScale);
581 info.refresh_rate = (int64_t)1000 * period.timeScale / period.timeValue;
582 }
583 }
584
Akihiko Odaki15280e82021-06-16 23:19:10 +0900585 info.width_mm = frameSize.width / screenSize.width * screenPhysicalSize.width;
586 info.height_mm = frameSize.height / screenSize.height * screenPhysicalSize.height;
587 } else {
588 frameSize = [self frame].size;
589 info.width_mm = 0;
590 info.height_mm = 0;
591 }
592
593 info.xoff = 0;
594 info.yoff = 0;
595 info.width = frameSize.width;
596 info.height = frameSize.height;
597
Marc-André Lureauca19ef52021-04-13 20:39:11 +0400598 dpy_set_ui_info(dcl.con, &info, TRUE);
Akihiko Odaki15280e82021-06-16 23:19:10 +0900599}
600
Peter Maydell8d65dee2022-02-24 10:13:29 +0000601- (void) updateUIInfo
602{
603 if (!allow_events) {
604 /*
605 * Don't try to tell QEMU about UI information in the application
606 * startup phase -- we haven't yet registered dcl with the QEMU UI
Akihiko Odakibab6a302022-08-19 22:27:54 +0900607 * layer.
Peter Maydell8d65dee2022-02-24 10:13:29 +0000608 * When cocoa_display_init() does register the dcl, the UI layer
609 * will call cocoa_switch(), which will call updateUIInfo, so
610 * we don't lose any information here.
611 */
612 return;
613 }
614
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500615 with_bql(^{
Peter Maydell8d65dee2022-02-24 10:13:29 +0000616 [self updateUIInfoLocked];
617 });
618}
619
Akihiko Odaki15280e82021-06-16 23:19:10 +0900620- (void)viewDidMoveToWindow
621{
622 [self updateUIInfo];
623}
624
Peter Maydell72a3e312019-02-25 10:24:28 +0000625- (void) switchSurface:(pixman_image_t *)image
thsc304f7e2008-01-22 23:25:15 +0000626{
Gerd Hoffmann5e00d3a2013-03-01 12:52:06 +0100627 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
thsc304f7e2008-01-22 23:25:15 +0000628
Peter Maydell72a3e312019-02-25 10:24:28 +0000629 int w = pixman_image_get_width(image);
630 int h = pixman_image_get_height(image);
Peter Maydell381600d2014-06-23 10:35:22 +0100631 /* cdx == 0 means this is our very first surface, in which case we need
632 * to recalculate the content dimensions even if it happens to be the size
633 * of the initial empty window.
634 */
635 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
Peter Maydelld3345a02013-12-24 02:51:46 +0000636
637 int oldh = screen.height;
638 if (isResize) {
639 // Resize before we trigger the redraw, or we'll redraw at the wrong size
640 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
641 screen.width = w;
642 screen.height = h;
643 [self setContentDimensions];
644 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
645 }
Peter Maydell8510d912013-03-18 20:28:21 +0000646
thsc304f7e2008-01-22 23:25:15 +0000647 // update screenBuffer
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900648 if (pixman_image) {
Peter Maydell55888402019-02-25 10:24:33 +0000649 pixman_image_unref(pixman_image);
650 }
thsc304f7e2008-01-22 23:25:15 +0000651
Peter Maydell55888402019-02-25 10:24:33 +0000652 pixman_image = image;
thsc304f7e2008-01-22 23:25:15 +0000653
654 // update windows
655 if (isFullscreen) {
656 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
Peter Maydelld3345a02013-12-24 02:51:46 +0000657 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
thsc304f7e2008-01-22 23:25:15 +0000658 } else {
659 if (qemu_name)
660 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
Peter Maydelld3345a02013-12-24 02:51:46 +0000661 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
thsc304f7e2008-01-22 23:25:15 +0000662 }
Peter Maydelld3345a02013-12-24 02:51:46 +0000663
664 if (isResize) {
665 [normalWindow center];
666 }
thsc304f7e2008-01-22 23:25:15 +0000667}
668
669- (void) toggleFullScreen:(id)sender
670{
671 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
672
673 if (isFullscreen) { // switch from fullscreen to desktop
674 isFullscreen = FALSE;
675 [self ungrabMouse];
676 [self setContentDimensions];
Akihiko Odaki1e8b6f22021-02-20 10:31:38 +0900677 [fullScreenWindow close];
678 [normalWindow setContentView: self];
679 [normalWindow makeKeyAndOrderFront: self];
680 [NSMenu setMenuBarVisible:YES];
thsc304f7e2008-01-22 23:25:15 +0000681 } else { // switch from desktop to fullscreen
682 isFullscreen = TRUE;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100683 [normalWindow orderOut: nil]; /* Hide the window */
thsc304f7e2008-01-22 23:25:15 +0000684 [self grabMouse];
685 [self setContentDimensions];
Akihiko Odaki1e8b6f22021-02-20 10:31:38 +0900686 [NSMenu setMenuBarVisible:NO];
687 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
688 styleMask:NSWindowStyleMaskBorderless
689 backing:NSBackingStoreBuffered
690 defer:NO];
691 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
692 [fullScreenWindow setHasShadow:NO];
693 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
694 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
695 [[fullScreenWindow contentView] addSubview: self];
696 [fullScreenWindow makeKeyAndOrderFront:self];
thsc304f7e2008-01-22 23:25:15 +0000697 }
698}
699
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900700- (void) setFullGrab:(id)sender
701{
702 COCOA_DEBUG("QemuCocoaView: setFullGrab\n");
703
704 CGEventMask mask = CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp) | CGEventMaskBit(kCGEventFlagsChanged);
705 eventsTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault,
706 mask, handleTapEvent, self);
707 if (!eventsTap) {
708 warn_report("Could not create event tap, system key combos will not be captured.\n");
709 return;
710 } else {
711 COCOA_DEBUG("Global events tap created! Will capture system key combos.\n");
712 }
713
714 CFRunLoopRef runLoop = CFRunLoopGetCurrent();
715 if (!runLoop) {
716 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
717 return;
718 }
719
720 CFRunLoopSourceRef tapEventsSrc = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventsTap, 0);
721 if (!tapEventsSrc ) {
722 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
723 return;
724 }
725
726 CFRunLoopAddSource(runLoop, tapEventsSrc, kCFRunLoopDefaultMode);
727 CFRelease(tapEventsSrc);
728}
729
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900730- (void) toggleKey: (int)keycode {
731 qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode));
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700732}
733
John Arbuckle9c3a4182017-11-07 10:14:14 +0000734// Does the work of sending input to the monitor
735- (void) handleMonitorInput:(NSEvent *)event
736{
737 int keysym = 0;
738 int control_key = 0;
739
740 // if the control key is down
741 if ([event modifierFlags] & NSEventModifierFlagControl) {
742 control_key = 1;
743 }
744
745 /* translates Macintosh keycodes to QEMU's keysym */
746
Philippe Mathieu-Daudé94592622022-02-15 16:21:14 +0100747 static const int without_control_translation[] = {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000748 [0 ... 0xff] = 0, // invalid key
749
750 [kVK_UpArrow] = QEMU_KEY_UP,
751 [kVK_DownArrow] = QEMU_KEY_DOWN,
752 [kVK_RightArrow] = QEMU_KEY_RIGHT,
753 [kVK_LeftArrow] = QEMU_KEY_LEFT,
754 [kVK_Home] = QEMU_KEY_HOME,
755 [kVK_End] = QEMU_KEY_END,
756 [kVK_PageUp] = QEMU_KEY_PAGEUP,
757 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
758 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
759 [kVK_Delete] = QEMU_KEY_BACKSPACE,
760 };
761
Philippe Mathieu-Daudé94592622022-02-15 16:21:14 +0100762 static const int with_control_translation[] = {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000763 [0 ... 0xff] = 0, // invalid key
764
765 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
766 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
767 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
768 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
769 [kVK_Home] = QEMU_KEY_CTRL_HOME,
770 [kVK_End] = QEMU_KEY_CTRL_END,
771 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
772 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
773 };
774
775 if (control_key != 0) { /* If the control key is being used */
776 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
777 keysym = with_control_translation[[event keyCode]];
778 }
779 } else {
780 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
781 keysym = without_control_translation[[event keyCode]];
782 }
783 }
784
785 // if not a key that needs translating
786 if (keysym == 0) {
787 NSString *ks = [event characters];
788 if ([ks length] > 0) {
789 keysym = [ks characterAtIndex:0];
790 }
791 }
792
793 if (keysym) {
Marc-André Lureaucc6ba2c2023-08-30 13:38:20 +0400794 qemu_text_console_put_keysym(NULL, keysym);
John Arbuckle9c3a4182017-11-07 10:14:14 +0000795 }
796}
797
Peter Maydell60105d72019-02-25 10:24:31 +0000798- (bool) handleEvent:(NSEvent *)event
thsc304f7e2008-01-22 23:25:15 +0000799{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500800 return bool_with_bql(^{
Peter Maydell60105d72019-02-25 10:24:31 +0000801 return [self handleEventLocked:event];
Peter Maydell31819e92019-02-25 10:24:27 +0000802 });
803}
thsc304f7e2008-01-22 23:25:15 +0000804
Peter Maydell60105d72019-02-25 10:24:31 +0000805- (bool) handleEventLocked:(NSEvent *)event
Peter Maydell31819e92019-02-25 10:24:27 +0000806{
Peter Maydell60105d72019-02-25 10:24:31 +0000807 /* Return true if we handled the event, false if it should be given to OSX */
Peter Maydell31819e92019-02-25 10:24:27 +0000808 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
Akihiko Odaki0f7be472024-02-24 21:43:33 +0900809 InputButton button;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700810 int keycode = 0;
Chen Zhang2044dff2019-06-04 17:36:00 +0800811 // Location of event in virtual screen coordinates
812 NSPoint p = [self screenLocationOfEvent:event];
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900813 NSUInteger modifiers = [event modifierFlags];
814
Akihiko Odakiad7f2f82021-03-12 22:32:12 +0900815 /*
816 * Check -[NSEvent modifierFlags] here.
817 *
818 * There is a NSEventType for an event notifying the change of
819 * -[NSEvent modifierFlags], NSEventTypeFlagsChanged but these operations
820 * are performed for any events because a modifier state may change while
821 * the application is inactive (i.e. no events fire) and we don't want to
822 * wait for another modifier state change to detect such a change.
823 *
824 * NSEventModifierFlagCapsLock requires a special treatment. The other flags
825 * are handled in similar manners.
826 *
827 * NSEventModifierFlagCapsLock
828 * ---------------------------
829 *
830 * If CapsLock state is changed, "up" and "down" events will be fired in
831 * sequence, effectively updates CapsLock state on the guest.
832 *
833 * The other flags
834 * ---------------
835 *
836 * If a flag is not set, fire "up" events for all keys which correspond to
837 * the flag. Note that "down" events are not fired here because the flags
838 * checked here do not tell what exact keys are down.
839 *
840 * If one of the keys corresponding to a flag is down, we rely on
841 * -[NSEvent keyCode] of an event whose -[NSEvent type] is
842 * NSEventTypeFlagsChanged to know the exact key which is down, which has
843 * the following two downsides:
844 * - It does not work when the application is inactive as described above.
845 * - It malfactions *after* the modifier state is changed while the
846 * application is inactive. It is because -[NSEvent keyCode] does not tell
847 * if the key is up or down, and requires to infer the current state from
848 * the previous state. It is still possible to fix such a malfanction by
849 * completely leaving your hands from the keyboard, which hopefully makes
850 * this implementation usable enough.
851 */
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900852 if (!!(modifiers & NSEventModifierFlagCapsLock) !=
853 qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) {
854 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true);
855 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false);
856 }
857
858 if (!(modifiers & NSEventModifierFlagShift)) {
859 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false);
860 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false);
861 }
862 if (!(modifiers & NSEventModifierFlagControl)) {
863 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false);
864 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false);
865 }
866 if (!(modifiers & NSEventModifierFlagOption)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900867 if (swap_opt_cmd) {
868 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
869 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
870 } else {
871 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
872 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
873 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900874 }
875 if (!(modifiers & NSEventModifierFlagCommand)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900876 if (swap_opt_cmd) {
877 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
878 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
879 } else {
880 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
881 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
882 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900883 }
thsc304f7e2008-01-22 23:25:15 +0000884
885 switch ([event type]) {
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700886 case NSEventTypeFlagsChanged:
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900887 switch ([event keyCode]) {
888 case kVK_Shift:
889 if (!!(modifiers & NSEventModifierFlagShift)) {
890 [self toggleKey:Q_KEY_CODE_SHIFT];
891 }
892 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700893
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900894 case kVK_RightShift:
895 if (!!(modifiers & NSEventModifierFlagShift)) {
896 [self toggleKey:Q_KEY_CODE_SHIFT_R];
897 }
898 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700899
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900900 case kVK_Control:
901 if (!!(modifiers & NSEventModifierFlagControl)) {
902 [self toggleKey:Q_KEY_CODE_CTRL];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700903 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900904 break;
905
906 case kVK_RightControl:
907 if (!!(modifiers & NSEventModifierFlagControl)) {
908 [self toggleKey:Q_KEY_CODE_CTRL_R];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700909 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900910 break;
911
912 case kVK_Option:
913 if (!!(modifiers & NSEventModifierFlagOption)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900914 if (swap_opt_cmd) {
915 [self toggleKey:Q_KEY_CODE_META_L];
916 } else {
917 [self toggleKey:Q_KEY_CODE_ALT];
918 }
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700919 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900920 break;
921
922 case kVK_RightOption:
923 if (!!(modifiers & NSEventModifierFlagOption)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900924 if (swap_opt_cmd) {
925 [self toggleKey:Q_KEY_CODE_META_R];
926 } else {
927 [self toggleKey:Q_KEY_CODE_ALT_R];
928 }
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700929 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900930 break;
931
932 /* Don't pass command key changes to guest unless mouse is grabbed */
933 case kVK_Command:
934 if (isMouseGrabbed &&
Akihiko Odakid6b6dea2022-03-18 00:29:49 +0900935 !!(modifiers & NSEventModifierFlagCommand) &&
936 left_command_key_enabled) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900937 if (swap_opt_cmd) {
938 [self toggleKey:Q_KEY_CODE_ALT];
939 } else {
940 [self toggleKey:Q_KEY_CODE_META_L];
941 }
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700942 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900943 break;
944
945 case kVK_RightCommand:
946 if (isMouseGrabbed &&
947 !!(modifiers & NSEventModifierFlagCommand)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900948 if (swap_opt_cmd) {
949 [self toggleKey:Q_KEY_CODE_ALT_R];
950 } else {
951 [self toggleKey:Q_KEY_CODE_META_R];
952 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900953 }
954 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700955 }
Akihiko Odaki0f7be472024-02-24 21:43:33 +0900956 return true;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700957 case NSEventTypeKeyDown:
Peter Maydell88959192013-12-08 22:59:02 +0000958 keycode = cocoa_keycode_to_qemu([event keyCode]);
thsc304f7e2008-01-22 23:25:15 +0000959
Peter Maydell88959192013-12-08 22:59:02 +0000960 // forward command key combos to the host UI unless the mouse is grabbed
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700961 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
Peter Maydell60105d72019-02-25 10:24:31 +0000962 return false;
thsc304f7e2008-01-22 23:25:15 +0000963 }
964
965 // default
thsc304f7e2008-01-22 23:25:15 +0000966
John Arbuckle5929e362017-11-07 10:14:14 +0000967 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700968 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
John Arbuckle5929e362017-11-07 10:14:14 +0000969 NSString *keychar = [event charactersIgnoringModifiers];
970 if ([keychar length] == 1) {
971 char key = [keychar characterAtIndex:0];
972 switch (key) {
thsc304f7e2008-01-22 23:25:15 +0000973
John Arbuckle5929e362017-11-07 10:14:14 +0000974 // enable graphic console
975 case '1' ... '9':
976 console_select(key - '0' - 1); /* ascii math */
Peter Maydell60105d72019-02-25 10:24:31 +0000977 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000978
979 // release the mouse grab
980 case 'g':
981 [self ungrabMouse];
Peter Maydell60105d72019-02-25 10:24:31 +0000982 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000983 }
thsc304f7e2008-01-22 23:25:15 +0000984 }
Peter Maydellef2088f2017-11-07 10:14:14 +0000985 }
thsc304f7e2008-01-22 23:25:15 +0000986
Peter Maydellef2088f2017-11-07 10:14:14 +0000987 if (qemu_console_is_graphic(NULL)) {
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900988 qkbd_state_key_event(kbd, keycode, true);
thsc304f7e2008-01-22 23:25:15 +0000989 } else {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000990 [self handleMonitorInput: event];
thsc304f7e2008-01-22 23:25:15 +0000991 }
Akihiko Odaki0f7be472024-02-24 21:43:33 +0900992 return true;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700993 case NSEventTypeKeyUp:
thsc304f7e2008-01-22 23:25:15 +0000994 keycode = cocoa_keycode_to_qemu([event keyCode]);
Peter Maydell88959192013-12-08 22:59:02 +0000995
996 // don't pass the guest a spurious key-up if we treated this
997 // command-key combo as a host UI action
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700998 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
Peter Maydell60105d72019-02-25 10:24:31 +0000999 return true;
Peter Maydell88959192013-12-08 22:59:02 +00001000 }
1001
Peter Maydell68c0aa62013-04-17 09:16:35 +00001002 if (qemu_console_is_graphic(NULL)) {
Akihiko Odaki6d73bb62021-03-10 23:46:02 +09001003 qkbd_state_key_event(kbd, keycode, false);
thsc304f7e2008-01-22 23:25:15 +00001004 }
Akihiko Odaki0f7be472024-02-24 21:43:33 +09001005 return true;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001006 case NSEventTypeMouseMoved:
thsc304f7e2008-01-22 23:25:15 +00001007 if (isAbsoluteEnabled) {
Chen Zhang2044dff2019-06-04 17:36:00 +08001008 // Cursor re-entered into a window might generate events bound to screen coordinates
1009 // and `nil` window property, and in full screen mode, current window might not be
1010 // key window, where event location alone should suffice.
1011 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
Peter Maydellf61c3872014-06-23 10:35:24 +01001012 if (isMouseGrabbed) {
1013 [self ungrabMouse];
thsc304f7e2008-01-22 23:25:15 +00001014 }
1015 } else {
Peter Maydellf61c3872014-06-23 10:35:24 +01001016 if (!isMouseGrabbed) {
1017 [self grabMouse];
thsc304f7e2008-01-22 23:25:15 +00001018 }
1019 }
1020 }
Akihiko Odakif4de9682024-02-24 21:43:34 +09001021 return [self handleMouseEvent:event];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001022 case NSEventTypeLeftMouseDown:
Akihiko Odakif4de9682024-02-24 21:43:34 +09001023 return [self handleMouseEvent:event button:INPUT_BUTTON_LEFT down:true];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001024 case NSEventTypeRightMouseDown:
Akihiko Odakif4de9682024-02-24 21:43:34 +09001025 return [self handleMouseEvent:event button:INPUT_BUTTON_RIGHT down:true];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001026 case NSEventTypeOtherMouseDown:
Akihiko Odakif4de9682024-02-24 21:43:34 +09001027 return [self handleMouseEvent:event button:INPUT_BUTTON_MIDDLE down:true];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001028 case NSEventTypeLeftMouseDragged:
Akihiko Odakif4de9682024-02-24 21:43:34 +09001029 return [self handleMouseEvent:event button:INPUT_BUTTON_LEFT down:true];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001030 case NSEventTypeRightMouseDragged:
Akihiko Odakif4de9682024-02-24 21:43:34 +09001031 return [self handleMouseEvent:event button:INPUT_BUTTON_RIGHT down:true];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001032 case NSEventTypeOtherMouseDragged:
Akihiko Odakif4de9682024-02-24 21:43:34 +09001033 return [self handleMouseEvent:event button:INPUT_BUTTON_MIDDLE down:true];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001034 case NSEventTypeLeftMouseUp:
Peter Maydellf61c3872014-06-23 10:35:24 +01001035 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
Chen Zhang8e23e342019-06-04 17:36:48 +08001036 /*
1037 * In fullscreen mode, the window of cocoaView may not be the
1038 * key window, therefore the position relative to the virtual
1039 * screen alone will be sufficient.
1040 */
1041 if(isFullscreen || [[self window] isKeyWindow]) {
Programmingkid9e8204b2016-08-15 22:11:06 -04001042 [self grabMouse];
1043 }
thsc304f7e2008-01-22 23:25:15 +00001044 }
Akihiko Odakif4de9682024-02-24 21:43:34 +09001045 return [self handleMouseEvent:event button:INPUT_BUTTON_LEFT down:false];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001046 case NSEventTypeRightMouseUp:
Akihiko Odakif4de9682024-02-24 21:43:34 +09001047 return [self handleMouseEvent:event button:INPUT_BUTTON_RIGHT down:false];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001048 case NSEventTypeOtherMouseUp:
Akihiko Odakif4de9682024-02-24 21:43:34 +09001049 return [self handleMouseEvent:event button:INPUT_BUTTON_MIDDLE down:false];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001050 case NSEventTypeScrollWheel:
John Arbuckleae7313e2018-01-08 13:07:07 -05001051 /*
1052 * Send wheel events to the guest regardless of window focus.
1053 * This is in-line with standard Mac OS X UI behaviour.
1054 */
1055
1056 /* Determine if this is a scroll up or scroll down event */
Akihiko Odaki0f7be472024-02-24 21:43:33 +09001057 if ([event deltaY] != 0) {
1058 button = ([event deltaY] > 0) ?
John Arbuckledc3c89d2018-07-09 11:02:35 -04001059 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
Akihiko Odaki0f7be472024-02-24 21:43:33 +09001060 } else if ([event deltaX] != 0) {
1061 button = ([event deltaX] > 0) ?
Dmitry Petrovd70a5de2022-01-08 16:39:44 +01001062 INPUT_BUTTON_WHEEL_LEFT : INPUT_BUTTON_WHEEL_RIGHT;
Akihiko Odaki0f7be472024-02-24 21:43:33 +09001063 } else {
1064 /*
1065 * We shouldn't have got a scroll event when deltaY and delta Y
1066 * are zero, hence no harm in dropping the event
1067 */
1068 return true;
John Arbuckledc3c89d2018-07-09 11:02:35 -04001069 }
Dmitry Petrovd70a5de2022-01-08 16:39:44 +01001070
Akihiko Odaki0f7be472024-02-24 21:43:33 +09001071 qemu_input_queue_btn(dcl.con, button, true);
1072 qemu_input_event_sync();
1073 qemu_input_queue_btn(dcl.con, button, false);
1074 qemu_input_event_sync();
1075
1076 return true;
thsc304f7e2008-01-22 23:25:15 +00001077 default:
Peter Maydell60105d72019-02-25 10:24:31 +00001078 return false;
thsc304f7e2008-01-22 23:25:15 +00001079 }
1080}
1081
Akihiko Odakif4de9682024-02-24 21:43:34 +09001082- (bool) handleMouseEvent:(NSEvent *)event button:(InputButton)button down:(bool)down
Akihiko Odakiaf4efbc2024-02-24 21:43:32 +09001083{
1084 /* Don't send button events to the guest unless we've got a
1085 * mouse grab or window focus. If we have neither then this event
1086 * is the user clicking on the background window to activate and
1087 * bring us to the front, which will be done by the sendEvent
1088 * call below. We definitely don't want to pass that click through
1089 * to the guest.
1090 */
Akihiko Odakif4de9682024-02-24 21:43:34 +09001091 if (!isMouseGrabbed && ![[self window] isKeyWindow]) {
1092 return false;
Akihiko Odakiaf4efbc2024-02-24 21:43:32 +09001093 }
1094
Akihiko Odakif4de9682024-02-24 21:43:34 +09001095 qemu_input_queue_btn(dcl.con, button, down);
1096
Akihiko Odakiaf4efbc2024-02-24 21:43:32 +09001097 return [self handleMouseEvent:event];
1098}
1099
1100- (bool) handleMouseEvent:(NSEvent *)event
1101{
1102 if (!isMouseGrabbed) {
1103 return false;
1104 }
1105
1106 if (isAbsoluteEnabled) {
1107 NSPoint p = [self screenLocationOfEvent:event];
1108
1109 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
1110 * The check on screenContainsPoint is to avoid sending out of range values for
1111 * clicks in the titlebar.
1112 */
1113 if ([self screenContainsPoint:p]) {
1114 qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x, 0, screen.width);
1115 qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
1116 }
1117 } else {
1118 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, (int)[event deltaX]);
1119 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, (int)[event deltaY]);
1120 }
1121
1122 qemu_input_event_sync();
1123
1124 return true;
1125}
1126
thsc304f7e2008-01-22 23:25:15 +00001127- (void) grabMouse
1128{
1129 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
1130
1131 if (!isFullscreen) {
1132 if (qemu_name)
Christian Schoenebeck23bdd0d2022-12-27 17:15:31 +01001133 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press " UC_CTRL_KEY " " UC_ALT_KEY " G to release Mouse)", qemu_name]];
thsc304f7e2008-01-22 23:25:15 +00001134 else
Christian Schoenebeck23bdd0d2022-12-27 17:15:31 +01001135 [normalWindow setTitle:@"QEMU - (Press " UC_CTRL_KEY " " UC_ALT_KEY " G to release Mouse)"];
thsc304f7e2008-01-22 23:25:15 +00001136 }
Peter Maydell13aefd32014-06-23 10:35:25 +01001137 [self hideCursor];
Akihiko Odakid1929062021-02-23 00:07:14 +09001138 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
Peter Maydell49b9bd42013-12-08 22:59:03 +00001139 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
thsc304f7e2008-01-22 23:25:15 +00001140}
1141
1142- (void) ungrabMouse
1143{
1144 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
1145
1146 if (!isFullscreen) {
1147 if (qemu_name)
1148 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
1149 else
1150 [normalWindow setTitle:@"QEMU"];
1151 }
Peter Maydell13aefd32014-06-23 10:35:25 +01001152 [self unhideCursor];
Akihiko Odakid1929062021-02-23 00:07:14 +09001153 CGAssociateMouseAndMouseCursorPosition(TRUE);
Peter Maydell49b9bd42013-12-08 22:59:03 +00001154 isMouseGrabbed = FALSE;
thsc304f7e2008-01-22 23:25:15 +00001155}
1156
Akihiko Odakid1929062021-02-23 00:07:14 +09001157- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {
1158 isAbsoluteEnabled = tIsAbsoluteEnabled;
1159 if (isMouseGrabbed) {
1160 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1161 }
1162}
Peter Maydell49b9bd42013-12-08 22:59:03 +00001163- (BOOL) isMouseGrabbed {return isMouseGrabbed;}
thsc304f7e2008-01-22 23:25:15 +00001164- (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
1165- (float) cdx {return cdx;}
1166- (float) cdy {return cdy;}
1167- (QEMUScreen) gscreen {return screen;}
John Arbuckle3b178b72015-09-25 23:14:00 +01001168
1169/*
1170 * Makes the target think all down keys are being released.
1171 * This prevents a stuck key problem, since we will not see
1172 * key up events for those keys after we have lost focus.
1173 */
1174- (void) raiseAllKeys
1175{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001176 with_bql(^{
Akihiko Odaki6d73bb62021-03-10 23:46:02 +09001177 qkbd_state_lift_all_keys(kbd);
Peter Maydell31819e92019-02-25 10:24:27 +00001178 });
John Arbuckle3b178b72015-09-25 23:14:00 +01001179}
bellard5b0753e2005-03-01 21:37:28 +00001180@end
1181
1182
thsc304f7e2008-01-22 23:25:15 +00001183
bellard5b0753e2005-03-01 21:37:28 +00001184/*
1185 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +00001186 QemuCocoaAppController
bellard5b0753e2005-03-01 21:37:28 +00001187 ------------------------------------------------------
1188*/
thsc304f7e2008-01-22 23:25:15 +00001189@interface QemuCocoaAppController : NSObject
John Arbuckled9bc14f2015-09-25 23:13:59 +01001190 <NSWindowDelegate, NSApplicationDelegate>
bellard5b0753e2005-03-01 21:37:28 +00001191{
1192}
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001193- (void)doToggleFullScreen:(id)sender;
thsc304f7e2008-01-22 23:25:15 +00001194- (void)toggleFullScreen:(id)sender;
1195- (void)showQEMUDoc:(id)sender;
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001196- (void)zoomToFit:(id) sender;
Programmingkidb4c6a112015-05-19 09:11:18 +01001197- (void)displayConsole:(id)sender;
John Arbuckle8524f1c2015-06-19 10:53:27 +01001198- (void)pauseQEMU:(id)sender;
1199- (void)resumeQEMU:(id)sender;
1200- (void)displayPause;
1201- (void)removePause;
John Arbuckle27074612015-06-19 10:53:27 +01001202- (void)restartQEMU:(id)sender;
1203- (void)powerDownQEMU:(id)sender;
John Arbuckle693a3e02015-06-19 10:53:27 +01001204- (void)ejectDeviceMedia:(id)sender;
1205- (void)changeDeviceMedia:(id)sender;
John Arbuckled9bc14f2015-09-25 23:13:59 +01001206- (BOOL)verifyQuit;
John Arbucklef4747902016-03-23 14:26:17 +00001207- (void)openDocumentation:(NSString *)filename;
Programmingkid9e8204b2016-08-15 22:11:06 -04001208- (IBAction) do_about_menu_item: (id) sender;
John Arbucklee47ec1a2017-06-13 23:17:38 -04001209- (void)adjustSpeed:(id)sender;
bellard5b0753e2005-03-01 21:37:28 +00001210@end
1211
thsc304f7e2008-01-22 23:25:15 +00001212@implementation QemuCocoaAppController
1213- (id) init
1214{
1215 COCOA_DEBUG("QemuCocoaAppController: init\n");
1216
1217 self = [super init];
1218 if (self) {
1219
1220 // create a view and add it to the window
1221 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1222 if(!cocoaView) {
Akihiko Odaki43137392021-02-23 22:11:06 +09001223 error_report("(cocoa) can't create a view");
thsc304f7e2008-01-22 23:25:15 +00001224 exit(1);
1225 }
1226
1227 // create a window
1228 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001229 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
thsc304f7e2008-01-22 23:25:15 +00001230 backing:NSBackingStoreBuffered defer:NO];
1231 if(!normalWindow) {
Akihiko Odaki43137392021-02-23 22:11:06 +09001232 error_report("(cocoa) can't create window");
thsc304f7e2008-01-22 23:25:15 +00001233 exit(1);
1234 }
1235 [normalWindow setAcceptsMouseMovedEvents:YES];
John Arbucklea1dbc052015-10-13 21:51:18 +01001236 [normalWindow setTitle:@"QEMU"];
thsc304f7e2008-01-22 23:25:15 +00001237 [normalWindow setContentView:cocoaView];
1238 [normalWindow makeKeyAndOrderFront:self];
Peter Maydell49060c22013-12-24 11:54:12 +00001239 [normalWindow center];
John Arbuckled9bc14f2015-09-25 23:13:59 +01001240 [normalWindow setDelegate: self];
John Arbuckle8524f1c2015-06-19 10:53:27 +01001241
1242 /* Used for displaying pause on the screen */
1243 pauseLabel = [NSTextField new];
1244 [pauseLabel setBezeled:YES];
1245 [pauseLabel setDrawsBackground:YES];
1246 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1247 [pauseLabel setEditable:NO];
1248 [pauseLabel setSelectable:NO];
1249 [pauseLabel setStringValue: @"Paused"];
1250 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1251 [pauseLabel setTextColor: [NSColor blackColor]];
1252 [pauseLabel sizeToFit];
thsc304f7e2008-01-22 23:25:15 +00001253 }
1254 return self;
1255}
1256
1257- (void) dealloc
1258{
1259 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1260
1261 if (cocoaView)
1262 [cocoaView release];
1263 [super dealloc];
1264}
1265
bellard5b0753e2005-03-01 21:37:28 +00001266- (void)applicationDidFinishLaunching: (NSNotification *) note
1267{
thsc304f7e2008-01-22 23:25:15 +00001268 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
Hikaru Nishidadff742a2019-10-15 10:07:34 +09001269 allow_events = true;
bellard5b0753e2005-03-01 21:37:28 +00001270}
1271
1272- (void)applicationWillTerminate:(NSNotification *)aNotification
1273{
thsc304f7e2008-01-22 23:25:15 +00001274 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1275
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001276 with_bql(^{
Akihiko Odaki2910abd2022-05-29 17:25:08 +09001277 shutdown_action = SHUTDOWN_ACTION_POWEROFF;
1278 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1279 });
Akihiko Odaki40c01932021-02-19 20:16:52 +09001280
1281 /*
1282 * Sleep here, because returning will cause OSX to kill us
1283 * immediately; the QEMU main loop will handle the shutdown
1284 * request and terminate the process.
1285 */
1286 [NSThread sleepForTimeInterval:INFINITY];
bellard5b0753e2005-03-01 21:37:28 +00001287}
1288
Andreas Färber41ea49b2009-12-14 22:13:27 +01001289- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1290{
1291 return YES;
1292}
1293
John Arbuckled9bc14f2015-09-25 23:13:59 +01001294- (NSApplicationTerminateReply)applicationShouldTerminate:
1295 (NSApplication *)sender
1296{
1297 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1298 return [self verifyQuit];
1299}
1300
Akihiko Odaki15280e82021-06-16 23:19:10 +09001301- (void)windowDidChangeScreen:(NSNotification *)notification
1302{
1303 [cocoaView updateUIInfo];
1304}
1305
1306- (void)windowDidResize:(NSNotification *)notification
1307{
1308 [cocoaView updateUIInfo];
1309}
1310
John Arbuckled9bc14f2015-09-25 23:13:59 +01001311/* Called when the user clicks on a window's close button */
1312- (BOOL)windowShouldClose:(id)sender
1313{
1314 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1315 [NSApp terminate: sender];
1316 /* If the user allows the application to quit then the call to
1317 * NSApp terminate will never return. If we get here then the user
1318 * cancelled the quit, so we should return NO to not permit the
1319 * closing of this window.
1320 */
1321 return NO;
1322}
1323
Akihiko Odaki9d9bc7d2023-02-28 16:09:46 +09001324/*
1325 * Called when QEMU goes into the background. Note that
1326 * [-NSWindowDelegate windowDidResignKey:] is used here instead of
1327 * [-NSApplicationDelegate applicationWillResignActive:] because it cannot
1328 * detect that the window loses focus when the deck is clicked on macOS 13.2.1.
1329 */
1330- (void) windowDidResignKey: (NSNotification *)aNotification
John Arbuckle3b178b72015-09-25 23:14:00 +01001331{
Akihiko Odaki9d9bc7d2023-02-28 16:09:46 +09001332 COCOA_DEBUG("%s\n", __func__);
Carwyn Ellis69221df2022-01-02 17:41:53 +00001333 [cocoaView ungrabMouse];
John Arbuckle3b178b72015-09-25 23:14:00 +01001334 [cocoaView raiseAllKeys];
1335}
1336
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001337/* We abstract the method called by the Enter Fullscreen menu item
1338 * because Mac OS 10.7 and higher disables it. This is because of the
1339 * menu item's old selector's name toggleFullScreen:
1340 */
1341- (void) doToggleFullScreen:(id)sender
1342{
1343 [self toggleFullScreen:(id)sender];
1344}
1345
thsc304f7e2008-01-22 23:25:15 +00001346- (void)toggleFullScreen:(id)sender
bellard5b0753e2005-03-01 21:37:28 +00001347{
thsc304f7e2008-01-22 23:25:15 +00001348 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1349
1350 [cocoaView toggleFullScreen:sender];
1351}
1352
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +09001353- (void) setFullGrab:(id)sender
1354{
1355 COCOA_DEBUG("QemuCocoaAppController: setFullGrab\n");
1356
1357 [cocoaView setFullGrab:sender];
1358}
1359
John Arbucklef4747902016-03-23 14:26:17 +00001360/* Tries to find then open the specified filename */
1361- (void) openDocumentation: (NSString *) filename
1362{
1363 /* Where to look for local files */
Roman Bolshakov8d6fda82021-01-09 00:38:15 +03001364 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
John Arbucklef4747902016-03-23 14:26:17 +00001365 NSString *full_file_path;
Roman Bolshakov1ff5a062021-01-02 18:07:21 +03001366 NSURL *full_file_url;
John Arbucklef4747902016-03-23 14:26:17 +00001367
1368 /* iterate thru the possible paths until the file is found */
1369 int index;
1370 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1371 full_file_path = [[NSBundle mainBundle] executablePath];
1372 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1373 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1374 path_array[index], filename];
Roman Bolshakov1ff5a062021-01-02 18:07:21 +03001375 full_file_url = [NSURL fileURLWithPath: full_file_path
1376 isDirectory: false];
1377 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
John Arbucklef4747902016-03-23 14:26:17 +00001378 return;
1379 }
1380 }
1381
1382 /* If none of the paths opened a file */
1383 NSBeep();
1384 QEMU_Alert(@"Failed to open file");
1385}
1386
thsc304f7e2008-01-22 23:25:15 +00001387- (void)showQEMUDoc:(id)sender
1388{
1389 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1390
Peter Maydell1879f242020-02-28 15:36:16 +00001391 [self openDocumentation: @"index.html"];
thsc304f7e2008-01-22 23:25:15 +00001392}
1393
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001394/* Stretches video to fit host monitor size */
1395- (void)zoomToFit:(id) sender
1396{
1397 stretch_video = !stretch_video;
1398 if (stretch_video == true) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001399 [sender setState: NSControlStateValueOn];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001400 } else {
Brendan Shanks5e246002019-01-31 23:12:25 -08001401 [sender setState: NSControlStateValueOff];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001402 }
1403}
bellard5b0753e2005-03-01 21:37:28 +00001404
Carwyn Ellise28a9092023-11-10 16:17:29 +00001405- (void)toggleZoomInterpolation:(id) sender
1406{
1407 if (zoom_interpolation == kCGInterpolationNone) {
1408 zoom_interpolation = kCGInterpolationLow;
1409 [sender setState: NSControlStateValueOn];
1410 } else {
1411 zoom_interpolation = kCGInterpolationNone;
1412 [sender setState: NSControlStateValueOff];
1413 }
1414}
1415
Programmingkidb4c6a112015-05-19 09:11:18 +01001416/* Displays the console on the screen */
1417- (void)displayConsole:(id)sender
1418{
1419 console_select([sender tag]);
1420}
John Arbuckle8524f1c2015-06-19 10:53:27 +01001421
1422/* Pause the guest */
1423- (void)pauseQEMU:(id)sender
1424{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001425 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001426 qmp_stop(NULL);
1427 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001428 [sender setEnabled: NO];
1429 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1430 [self displayPause];
1431}
1432
1433/* Resume running the guest operating system */
1434- (void)resumeQEMU:(id) sender
1435{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001436 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001437 qmp_cont(NULL);
1438 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001439 [sender setEnabled: NO];
1440 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1441 [self removePause];
1442}
1443
1444/* Displays the word pause on the screen */
1445- (void)displayPause
1446{
1447 /* Coordinates have to be calculated each time because the window can change its size */
1448 int xCoord, yCoord, width, height;
1449 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1450 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1451 width = [pauseLabel frame].size.width;
1452 height = [pauseLabel frame].size.height;
1453 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1454 [cocoaView addSubview: pauseLabel];
1455}
1456
1457/* Removes the word pause from the screen */
1458- (void)removePause
1459{
1460 [pauseLabel removeFromSuperview];
1461}
1462
John Arbuckle27074612015-06-19 10:53:27 +01001463/* Restarts QEMU */
1464- (void)restartQEMU:(id)sender
1465{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001466 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001467 qmp_system_reset(NULL);
1468 });
John Arbuckle27074612015-06-19 10:53:27 +01001469}
1470
1471/* Powers down QEMU */
1472- (void)powerDownQEMU:(id)sender
1473{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001474 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001475 qmp_system_powerdown(NULL);
1476 });
John Arbuckle27074612015-06-19 10:53:27 +01001477}
1478
John Arbuckle693a3e02015-06-19 10:53:27 +01001479/* Ejects the media.
1480 * Uses sender's tag to figure out the device to eject.
1481 */
1482- (void)ejectDeviceMedia:(id)sender
1483{
1484 NSString * drive;
1485 drive = [sender representedObject];
1486 if(drive == nil) {
1487 NSBeep();
1488 QEMU_Alert(@"Failed to find drive to eject!");
1489 return;
1490 }
1491
Peter Maydell31819e92019-02-25 10:24:27 +00001492 __block Error *err = NULL;
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001493 with_bql(^{
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001494 qmp_eject([drive cStringUsingEncoding: NSASCIIStringEncoding],
1495 NULL, false, false, &err);
Peter Maydell31819e92019-02-25 10:24:27 +00001496 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001497 handleAnyDeviceErrors(err);
1498}
1499
1500/* Displays a dialog box asking the user to select an image file to load.
1501 * Uses sender's represented object value to figure out which drive to use.
1502 */
1503- (void)changeDeviceMedia:(id)sender
1504{
1505 /* Find the drive name */
1506 NSString * drive;
1507 drive = [sender representedObject];
1508 if(drive == nil) {
1509 NSBeep();
1510 QEMU_Alert(@"Could not find drive!");
1511 return;
1512 }
1513
1514 /* Display the file open dialog */
1515 NSOpenPanel * openPanel;
1516 openPanel = [NSOpenPanel openPanel];
1517 [openPanel setCanChooseFiles: YES];
1518 [openPanel setAllowsMultipleSelection: NO];
Peter Maydellb5725382018-05-29 19:15:23 +01001519 if([openPanel runModal] == NSModalResponseOK) {
John Arbuckle693a3e02015-06-19 10:53:27 +01001520 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1521 if(file == nil) {
1522 NSBeep();
1523 QEMU_Alert(@"Failed to convert URL to file path!");
1524 return;
1525 }
1526
Peter Maydell31819e92019-02-25 10:24:27 +00001527 __block Error *err = NULL;
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001528 with_bql(^{
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001529 qmp_blockdev_change_medium([drive cStringUsingEncoding:
Peter Maydell31819e92019-02-25 10:24:27 +00001530 NSASCIIStringEncoding],
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001531 NULL,
Peter Maydell31819e92019-02-25 10:24:27 +00001532 [file cStringUsingEncoding:
1533 NSASCIIStringEncoding],
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001534 "raw",
Denis V. Lunev80dd5af2022-04-13 01:18:46 +03001535 true, false,
Peter Maydell31819e92019-02-25 10:24:27 +00001536 false, 0,
1537 &err);
1538 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001539 handleAnyDeviceErrors(err);
1540 }
1541}
1542
John Arbuckled9bc14f2015-09-25 23:13:59 +01001543/* Verifies if the user really wants to quit */
1544- (BOOL)verifyQuit
1545{
1546 NSAlert *alert = [NSAlert new];
1547 [alert autorelease];
1548 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1549 [alert addButtonWithTitle: @"Cancel"];
1550 [alert addButtonWithTitle: @"Quit"];
1551 if([alert runModal] == NSAlertSecondButtonReturn) {
1552 return YES;
1553 } else {
1554 return NO;
1555 }
1556}
1557
Programmingkid9e8204b2016-08-15 22:11:06 -04001558/* The action method for the About menu item */
1559- (IBAction) do_about_menu_item: (id) sender
1560{
Akihiko Odaki99eb3132022-02-27 13:22:41 +09001561 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1562 char *icon_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1563 NSString *icon_path = [NSString stringWithUTF8String:icon_path_c];
1564 g_free(icon_path_c);
1565 NSImage *icon = [[NSImage alloc] initWithContentsOfFile:icon_path];
1566 NSString *version = @"QEMU emulator version " QEMU_FULL_VERSION;
1567 NSString *copyright = @QEMU_COPYRIGHT;
1568 NSDictionary *options;
1569 if (icon) {
1570 options = @{
1571 NSAboutPanelOptionApplicationIcon : icon,
1572 NSAboutPanelOptionApplicationVersion : version,
1573 @"Copyright" : copyright,
1574 };
1575 [icon release];
1576 } else {
1577 options = @{
1578 NSAboutPanelOptionApplicationVersion : version,
1579 @"Copyright" : copyright,
1580 };
Akihiko Odakia0f973f2021-03-09 21:22:26 +09001581 }
Akihiko Odaki99eb3132022-02-27 13:22:41 +09001582 [NSApp orderFrontStandardAboutPanelWithOptions:options];
1583 [pool release];
Programmingkid9e8204b2016-08-15 22:11:06 -04001584}
1585
John Arbucklee47ec1a2017-06-13 23:17:38 -04001586/* Used by the Speed menu items */
1587- (void)adjustSpeed:(id)sender
1588{
1589 int throttle_pct; /* throttle percentage */
1590 NSMenu *menu;
1591
1592 menu = [sender menu];
1593 if (menu != nil)
1594 {
1595 /* Unselect the currently selected item */
1596 for (NSMenuItem *item in [menu itemArray]) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001597 if (item.state == NSControlStateValueOn) {
1598 [item setState: NSControlStateValueOff];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001599 break;
1600 }
1601 }
1602 }
1603
1604 // check the menu item
Brendan Shanks5e246002019-01-31 23:12:25 -08001605 [sender setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001606
1607 // get the throttle percentage
1608 throttle_pct = [sender tag];
1609
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001610 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001611 cpu_throttle_set(throttle_pct);
1612 });
John Arbucklee47ec1a2017-06-13 23:17:38 -04001613 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1614}
1615
Programmingkidb4c6a112015-05-19 09:11:18 +01001616@end
bellard5b0753e2005-03-01 21:37:28 +00001617
Peter Maydell61a2ed42019-02-25 10:24:32 +00001618@interface QemuApplication : NSApplication
1619@end
1620
1621@implementation QemuApplication
1622- (void)sendEvent:(NSEvent *)event
1623{
1624 COCOA_DEBUG("QemuApplication: sendEvent\n");
Peter Maydell55888402019-02-25 10:24:33 +00001625 if (![cocoaView handleEvent:event]) {
1626 [super sendEvent: event];
1627 }
Peter Maydell61a2ed42019-02-25 10:24:32 +00001628}
1629@end
1630
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001631static void create_initial_menus(void)
1632{
thsc304f7e2008-01-22 23:25:15 +00001633 // Add menus
1634 NSMenu *menu;
1635 NSMenuItem *menuItem;
1636
bellard5b0753e2005-03-01 21:37:28 +00001637 [NSApp setMainMenu:[[NSMenu alloc] init]];
Akihiko Odaki5b6988c2022-02-14 18:13:20 +09001638 [NSApp setServicesMenu:[[NSMenu alloc] initWithTitle:@"Services"]];
bellard5b0753e2005-03-01 21:37:28 +00001639
thsc304f7e2008-01-22 23:25:15 +00001640 // Application menu
1641 menu = [[NSMenu alloc] initWithTitle:@""];
Programmingkid9e8204b2016-08-15 22:11:06 -04001642 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
thsc304f7e2008-01-22 23:25:15 +00001643 [menu addItem:[NSMenuItem separatorItem]]; //Separator
Akihiko Odaki5b6988c2022-02-14 18:13:20 +09001644 menuItem = [menu addItemWithTitle:@"Services" action:nil keyEquivalent:@""];
1645 [menuItem setSubmenu:[NSApp servicesMenu]];
1646 [menu addItem:[NSMenuItem separatorItem]];
thsc304f7e2008-01-22 23:25:15 +00001647 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1648 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001649 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
thsc304f7e2008-01-22 23:25:15 +00001650 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1651 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1652 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1653 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1654 [menuItem setSubmenu:menu];
1655 [[NSApp mainMenu] addItem:menuItem];
1656 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
ths3b46e622007-09-17 08:09:54 +00001657
John Arbuckle8524f1c2015-06-19 10:53:27 +01001658 // Machine menu
1659 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1660 [menu setAutoenablesItems: NO];
1661 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1662 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1663 [menu addItem: menuItem];
1664 [menuItem setEnabled: NO];
John Arbuckle27074612015-06-19 10:53:27 +01001665 [menu addItem: [NSMenuItem separatorItem]];
1666 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1667 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
John Arbuckle8524f1c2015-06-19 10:53:27 +01001668 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1669 [menuItem setSubmenu:menu];
1670 [[NSApp mainMenu] addItem:menuItem];
1671
thsc304f7e2008-01-22 23:25:15 +00001672 // View menu
1673 menu = [[NSMenu alloc] initWithTitle:@"View"];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001674 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
Carwyn Ellis5ec08982023-10-27 16:49:20 +01001675 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease];
1676 [menuItem setState: stretch_video ? NSControlStateValueOn : NSControlStateValueOff];
1677 [menu addItem: menuItem];
Carwyn Ellise28a9092023-11-10 16:17:29 +00001678 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Zoom Interpolation" action:@selector(toggleZoomInterpolation:) keyEquivalent:@""] autorelease];
1679 [menuItem setState: zoom_interpolation == kCGInterpolationLow ? NSControlStateValueOn : NSControlStateValueOff];
1680 [menu addItem: menuItem];
thsc304f7e2008-01-22 23:25:15 +00001681 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1682 [menuItem setSubmenu:menu];
1683 [[NSApp mainMenu] addItem:menuItem];
1684
John Arbucklee47ec1a2017-06-13 23:17:38 -04001685 // Speed menu
1686 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1687
1688 // Add the rest of the Speed menu items
1689 int p, percentage, throttle_pct;
1690 for (p = 10; p >= 0; p--)
1691 {
1692 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1693
1694 menuItem = [[[NSMenuItem alloc]
1695 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1696
1697 if (percentage == 100) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001698 [menuItem setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001699 }
1700
1701 /* Calculate the throttle percentage */
1702 throttle_pct = -1 * percentage + 100;
1703
1704 [menuItem setTag: throttle_pct];
1705 [menu addItem: menuItem];
1706 }
1707 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1708 [menuItem setSubmenu:menu];
1709 [[NSApp mainMenu] addItem:menuItem];
1710
thsc304f7e2008-01-22 23:25:15 +00001711 // Window menu
1712 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1713 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1714 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1715 [menuItem setSubmenu:menu];
1716 [[NSApp mainMenu] addItem:menuItem];
1717 [NSApp setWindowsMenu:menu];
1718
1719 // Help menu
1720 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1721 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
thsc304f7e2008-01-22 23:25:15 +00001722 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1723 [menuItem setSubmenu:menu];
1724 [[NSApp mainMenu] addItem:menuItem];
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001725}
1726
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001727/* Returns a name for a given console */
1728static NSString * getConsoleName(QemuConsole * console)
1729{
Akihiko Odakica511602022-02-15 09:03:05 +01001730 g_autofree char *label = qemu_console_get_label(console);
1731
1732 return [NSString stringWithUTF8String:label];
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001733}
1734
1735/* Add an entry to the View menu for each console */
1736static void add_console_menu_entries(void)
1737{
1738 NSMenu *menu;
1739 NSMenuItem *menuItem;
1740 int index = 0;
1741
1742 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1743
1744 [menu addItem:[NSMenuItem separatorItem]];
1745
1746 while (qemu_console_lookup_by_index(index) != NULL) {
1747 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1748 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1749 [menuItem setTag: index];
1750 [menu addItem: menuItem];
1751 index++;
1752 }
1753}
1754
1755/* Make menu items for all removable devices.
1756 * Each device is given an 'Eject' and 'Change' menu item.
1757 */
1758static void addRemovableDevicesMenuItems(void)
1759{
1760 NSMenu *menu;
1761 NSMenuItem *menuItem;
1762 BlockInfoList *currentDevice, *pointerToFree;
1763 NSString *deviceName;
1764
1765 currentDevice = qmp_query_block(NULL);
1766 pointerToFree = currentDevice;
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001767
1768 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1769
1770 // Add a separator between related groups of menu items
1771 [menu addItem:[NSMenuItem separatorItem]];
1772
1773 // Set the attributes to the "Removable Media" menu item
1774 NSString *titleString = @"Removable Media";
1775 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1776 NSColor *newColor = [NSColor blackColor];
1777 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1778 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1779 traits:NSBoldFontMask|NSItalicFontMask
1780 weight:0
1781 size:14];
1782 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1783 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1784 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1785
1786 // Add the "Removable Media" menu item
1787 menuItem = [NSMenuItem new];
1788 [menuItem setAttributedTitle: attString];
1789 [menuItem setEnabled: NO];
1790 [menu addItem: menuItem];
1791
1792 /* Loop through all the block devices in the emulator */
1793 while (currentDevice) {
1794 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1795
1796 if(currentDevice->value->removable) {
1797 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1798 action: @selector(changeDeviceMedia:)
1799 keyEquivalent: @""];
1800 [menu addItem: menuItem];
1801 [menuItem setRepresentedObject: deviceName];
1802 [menuItem autorelease];
1803
1804 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1805 action: @selector(ejectDeviceMedia:)
1806 keyEquivalent: @""];
1807 [menu addItem: menuItem];
1808 [menuItem setRepresentedObject: deviceName];
1809 [menuItem autorelease];
1810 }
1811 currentDevice = currentDevice->next;
1812 }
1813 qapi_free_BlockInfoList(pointerToFree);
1814}
1815
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001816@interface QemuCocoaPasteboardTypeOwner : NSObject<NSPasteboardTypeOwner>
1817@end
1818
1819@implementation QemuCocoaPasteboardTypeOwner
1820
1821- (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)type
1822{
1823 if (type != NSPasteboardTypeString) {
1824 return;
1825 }
1826
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001827 with_bql(^{
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001828 QemuClipboardInfo *info = qemu_clipboard_info_ref(cbinfo);
1829 qemu_event_reset(&cbevent);
1830 qemu_clipboard_request(info, QEMU_CLIPBOARD_TYPE_TEXT);
1831
1832 while (info == cbinfo &&
1833 info->types[QEMU_CLIPBOARD_TYPE_TEXT].available &&
1834 info->types[QEMU_CLIPBOARD_TYPE_TEXT].data == NULL) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001835 bql_unlock();
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001836 qemu_event_wait(&cbevent);
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001837 bql_lock();
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001838 }
1839
1840 if (info == cbinfo) {
1841 NSData *data = [[NSData alloc] initWithBytes:info->types[QEMU_CLIPBOARD_TYPE_TEXT].data
1842 length:info->types[QEMU_CLIPBOARD_TYPE_TEXT].size];
1843 [sender setData:data forType:NSPasteboardTypeString];
1844 [data release];
1845 }
1846
1847 qemu_clipboard_info_unref(info);
1848 });
1849}
1850
1851@end
1852
1853static QemuCocoaPasteboardTypeOwner *cbowner;
1854
1855static void cocoa_clipboard_notify(Notifier *notifier, void *data);
1856static void cocoa_clipboard_request(QemuClipboardInfo *info,
1857 QemuClipboardType type);
1858
1859static QemuClipboardPeer cbpeer = {
1860 .name = "cocoa",
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001861 .notifier = { .notify = cocoa_clipboard_notify },
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001862 .request = cocoa_clipboard_request
1863};
1864
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001865static void cocoa_clipboard_update_info(QemuClipboardInfo *info)
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001866{
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001867 if (info->owner == &cbpeer || info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
1868 return;
1869 }
1870
1871 if (info != cbinfo) {
1872 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1873 qemu_clipboard_info_unref(cbinfo);
1874 cbinfo = qemu_clipboard_info_ref(info);
1875 cbchangecount = [[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:cbowner];
1876 [pool release];
1877 }
1878
1879 qemu_event_set(&cbevent);
1880}
1881
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001882static void cocoa_clipboard_notify(Notifier *notifier, void *data)
1883{
1884 QemuClipboardNotify *notify = data;
1885
1886 switch (notify->type) {
1887 case QEMU_CLIPBOARD_UPDATE_INFO:
1888 cocoa_clipboard_update_info(notify->info);
1889 return;
Marc-André Lureau505dbf92021-07-19 19:49:56 +04001890 case QEMU_CLIPBOARD_RESET_SERIAL:
1891 /* ignore */
1892 return;
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001893 }
1894}
1895
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001896static void cocoa_clipboard_request(QemuClipboardInfo *info,
1897 QemuClipboardType type)
1898{
Akihiko Odaki8c0d8022022-06-15 06:21:31 +09001899 NSAutoreleasePool *pool;
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001900 NSData *text;
1901
1902 switch (type) {
1903 case QEMU_CLIPBOARD_TYPE_TEXT:
Akihiko Odaki8c0d8022022-06-15 06:21:31 +09001904 pool = [[NSAutoreleasePool alloc] init];
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001905 text = [[NSPasteboard generalPasteboard] dataForType:NSPasteboardTypeString];
1906 if (text) {
1907 qemu_clipboard_set_data(&cbpeer, info, type,
1908 [text length], [text bytes], true);
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001909 }
Akihiko Odaki8c0d8022022-06-15 06:21:31 +09001910 [pool release];
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001911 break;
1912 default:
1913 break;
1914 }
1915}
1916
Peter Maydell55888402019-02-25 10:24:33 +00001917/*
1918 * The startup process for the OSX/Cocoa UI is complicated, because
1919 * OSX insists that the UI runs on the initial main thread, and so we
Akihiko Odakibab6a302022-08-19 22:27:54 +09001920 * need to start a second thread which runs the qemu_default_main():
Peter Maydell55888402019-02-25 10:24:33 +00001921 * in main():
Akihiko Odakibab6a302022-08-19 22:27:54 +09001922 * in cocoa_display_init():
1923 * assign cocoa_main to qemu_main
1924 * create application, menus, etc
1925 * in cocoa_main():
1926 * create qemu-main thread
1927 * enter OSX run loop
Peter Maydell55888402019-02-25 10:24:33 +00001928 */
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001929
Peter Maydell55888402019-02-25 10:24:33 +00001930static void *call_qemu_main(void *opaque)
1931{
1932 int status;
1933
Akihiko Odakibab6a302022-08-19 22:27:54 +09001934 COCOA_DEBUG("Second thread: calling qemu_default_main()\n");
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001935 bql_lock();
Akihiko Odakibab6a302022-08-19 22:27:54 +09001936 status = qemu_default_main();
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001937 bql_unlock();
Akihiko Odakibab6a302022-08-19 22:27:54 +09001938 COCOA_DEBUG("Second thread: qemu_default_main() returned, exiting\n");
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001939 [cbowner release];
Peter Maydell55888402019-02-25 10:24:33 +00001940 exit(status);
1941}
1942
Philippe Mathieu-Daudéf9750332023-04-23 18:55:28 +02001943static int cocoa_main(void)
Akihiko Odakibab6a302022-08-19 22:27:54 +09001944{
Peter Maydell55888402019-02-25 10:24:33 +00001945 QemuThread thread;
1946
Akihiko Odakibab6a302022-08-19 22:27:54 +09001947 COCOA_DEBUG("Entered %s()\n", __func__);
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001948
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001949 bql_unlock();
Peter Maydell55888402019-02-25 10:24:33 +00001950 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1951 NULL, QEMU_THREAD_DETACHED);
1952
thsc304f7e2008-01-22 23:25:15 +00001953 // Start the main event loop
Peter Maydell55888402019-02-25 10:24:33 +00001954 COCOA_DEBUG("Main thread: entering OSX run loop\n");
bellard5b0753e2005-03-01 21:37:28 +00001955 [NSApp run];
Akihiko Odakibab6a302022-08-19 22:27:54 +09001956 COCOA_DEBUG("Main thread: left OSX run loop, which should never happen\n");
ths3b46e622007-09-17 08:09:54 +00001957
Akihiko Odakibab6a302022-08-19 22:27:54 +09001958 abort();
bellard5b0753e2005-03-01 21:37:28 +00001959}
thsc304f7e2008-01-22 23:25:15 +00001960
1961
1962
1963#pragma mark qemu
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001964static void cocoa_update(DisplayChangeListener *dcl,
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001965 int x, int y, int w, int h)
thsc304f7e2008-01-22 23:25:15 +00001966{
1967 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1968
Peter Maydell55888402019-02-25 10:24:33 +00001969 dispatch_async(dispatch_get_main_queue(), ^{
1970 NSRect rect;
1971 if ([cocoaView cdx] == 1.0) {
1972 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1973 } else {
1974 rect = NSMakeRect(
1975 x * [cocoaView cdx],
1976 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1977 w * [cocoaView cdx],
1978 h * [cocoaView cdy]);
1979 }
1980 [cocoaView setNeedsDisplayInRect:rect];
1981 });
thsc304f7e2008-01-22 23:25:15 +00001982}
1983
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01001984static void cocoa_switch(DisplayChangeListener *dcl,
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01001985 DisplaySurface *surface)
thsc304f7e2008-01-22 23:25:15 +00001986{
Peter Maydell55888402019-02-25 10:24:33 +00001987 pixman_image_t *image = surface->image;
thsc304f7e2008-01-22 23:25:15 +00001988
Peter Maydell6e657e62013-04-22 10:29:46 +00001989 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
Peter Maydell55888402019-02-25 10:24:33 +00001990
1991 // The DisplaySurface will be freed as soon as this callback returns.
1992 // We take a reference to the underlying pixman image here so it does
1993 // not disappear from under our feet; the switchSurface method will
1994 // deref the old image when it is done with it.
1995 pixman_image_ref(image);
1996
1997 dispatch_async(dispatch_get_main_queue(), ^{
Peter Maydell8d65dee2022-02-24 10:13:29 +00001998 [cocoaView updateUIInfo];
Peter Maydell55888402019-02-25 10:24:33 +00001999 [cocoaView switchSurface:image];
2000 });
thsc304f7e2008-01-22 23:25:15 +00002001}
2002
Gerd Hoffmannbc2ed972013-03-01 13:03:04 +01002003static void cocoa_refresh(DisplayChangeListener *dcl)
thsc304f7e2008-01-22 23:25:15 +00002004{
Peter Maydell6e657e62013-04-22 10:29:46 +00002005 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2006
thsc304f7e2008-01-22 23:25:15 +00002007 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
John Arbuckle468a8952015-10-13 21:51:18 +01002008 graphic_hw_update(NULL);
thsc304f7e2008-01-22 23:25:15 +00002009
Akihiko Odaki0337e412023-09-21 17:29:34 +09002010 if (qemu_input_is_absolute(dcl->con)) {
Peter Maydell55888402019-02-25 10:24:33 +00002011 dispatch_async(dispatch_get_main_queue(), ^{
2012 if (![cocoaView isAbsoluteEnabled]) {
2013 if ([cocoaView isMouseGrabbed]) {
2014 [cocoaView ungrabMouse];
2015 }
thsc304f7e2008-01-22 23:25:15 +00002016 }
Peter Maydell55888402019-02-25 10:24:33 +00002017 [cocoaView setAbsoluteEnabled:YES];
2018 });
thsc304f7e2008-01-22 23:25:15 +00002019 }
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09002020
2021 if (cbchangecount != [[NSPasteboard generalPasteboard] changeCount]) {
2022 qemu_clipboard_info_unref(cbinfo);
2023 cbinfo = qemu_clipboard_info_new(&cbpeer, QEMU_CLIPBOARD_SELECTION_CLIPBOARD);
2024 if ([[NSPasteboard generalPasteboard] availableTypeFromArray:@[NSPasteboardTypeString]]) {
2025 cbinfo->types[QEMU_CLIPBOARD_TYPE_TEXT].available = true;
2026 }
2027 qemu_clipboard_update(cbinfo);
2028 cbchangecount = [[NSPasteboard generalPasteboard] changeCount];
2029 qemu_event_set(&cbevent);
2030 }
2031
Peter Maydell6e657e62013-04-22 10:29:46 +00002032 [pool release];
thsc304f7e2008-01-22 23:25:15 +00002033}
2034
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01002035static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
thsc304f7e2008-01-22 23:25:15 +00002036{
Akihiko Odakibab6a302022-08-19 22:27:54 +09002037 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2038
thsc304f7e2008-01-22 23:25:15 +00002039 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
2040
Akihiko Odakibab6a302022-08-19 22:27:54 +09002041 qemu_main = cocoa_main;
Peter Maydell55888402019-02-25 10:24:33 +00002042
Akihiko Odakibab6a302022-08-19 22:27:54 +09002043 // Pull this console process up to being a fully-fledged graphical
2044 // app with a menubar and Dock icon
2045 ProcessSerialNumber psn = { 0, kCurrentProcess };
2046 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
2047
2048 [QemuApplication sharedApplication];
2049
Akihiko Odakibab6a302022-08-19 22:27:54 +09002050 // Create an Application controller
2051 QemuCocoaAppController *controller = [[QemuCocoaAppController alloc] init];
2052 [NSApp setDelegate:controller];
2053
Programmingkid43227af2015-05-19 09:11:17 +01002054 /* if fullscreen mode is to be used */
Gerd Hoffmann767f9bf2018-02-02 12:10:19 +01002055 if (opts->has_full_screen && opts->full_screen) {
Akihiko Odakibab6a302022-08-19 22:27:54 +09002056 [NSApp activateIgnoringOtherApps: YES];
2057 [controller 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) {
2075 stretch_video = true;
2076 }
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
aliguori9794f742009-03-04 19:25:22 +00002093 // register vga output callbacks
Akihiko Odakicc7859c2021-02-19 17:44:19 +09002094 register_displaychangelistener(&dcl);
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09002095
2096 qemu_event_init(&cbevent, false);
2097 cbowner = [[QemuCocoaPasteboardTypeOwner alloc] init];
2098 qemu_clipboard_peer_register(&cbpeer);
Akihiko Odakibab6a302022-08-19 22:27:54 +09002099
2100 [pool release];
thsc304f7e2008-01-22 23:25:15 +00002101}
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01002102
2103static QemuDisplay qemu_display_cocoa = {
2104 .type = DISPLAY_TYPE_COCOA,
2105 .init = cocoa_display_init,
2106};
2107
2108static void register_cocoa(void)
2109{
2110 qemu_display_register(&qemu_display_cocoa);
2111}
2112
2113type_init(register_cocoa);