blob: 5618d294c43cb5172ae781bb419e1c4635ae3f03 [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 Hoffmann21bae112013-12-04 14:08:04 +0100106static int last_buttons;
Gerd Hoffmann3487da62020-02-06 12:27:50 +0100107static int cursor_hide = 1;
Carwyn Ellis48941a52022-01-02 17:41:52 +0000108static int left_command_key_enabled = 1;
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900109static bool swap_opt_cmd;
bellard5b0753e2005-03-01 21:37:28 +0000110
Akihiko Odakicb823402021-02-25 17:42:02 +0900111static bool stretch_video;
Carwyn Ellise28a9092023-11-10 16:17:29 +0000112static CGInterpolationQuality zoom_interpolation = kCGInterpolationNone;
Akihiko Odakicb823402021-02-25 17:42:02 +0900113static NSTextField *pauseLabel;
bellard5b0753e2005-03-01 21:37:28 +0000114
Hikaru Nishidadff742a2019-10-15 10:07:34 +0900115static bool allow_events;
Peter Maydell55888402019-02-25 10:24:33 +0000116
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +0900117static NSInteger cbchangecount = -1;
118static QemuClipboardInfo *cbinfo;
119static QemuEvent cbevent;
120
Stefan Hajnoczia4a411f2024-01-02 10:35:28 -0500121// Utility functions to run specified code block with the BQL held
Peter Maydell31819e92019-02-25 10:24:27 +0000122typedef void (^CodeBlock)(void);
Peter Maydell60105d72019-02-25 10:24:31 +0000123typedef bool (^BoolCodeBlock)(void);
Peter Maydell31819e92019-02-25 10:24:27 +0000124
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500125static void with_bql(CodeBlock block)
Peter Maydell31819e92019-02-25 10:24:27 +0000126{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500127 bool locked = bql_locked();
Peter Maydell31819e92019-02-25 10:24:27 +0000128 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500129 bql_lock();
Peter Maydell31819e92019-02-25 10:24:27 +0000130 }
131 block();
132 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500133 bql_unlock();
Peter Maydell31819e92019-02-25 10:24:27 +0000134 }
135}
136
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500137static bool bool_with_bql(BoolCodeBlock block)
Peter Maydell60105d72019-02-25 10:24:31 +0000138{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500139 bool locked = bql_locked();
Peter Maydell60105d72019-02-25 10:24:31 +0000140 bool val;
141
142 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500143 bql_lock();
Peter Maydell60105d72019-02-25 10:24:31 +0000144 }
145 val = block();
146 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500147 bql_unlock();
Peter Maydell60105d72019-02-25 10:24:31 +0000148 }
149 return val;
150}
151
John Arbuckleaaac7142016-03-23 14:26:18 +0000152// Mac to QKeyCode conversion
Akihiko Odakicb823402021-02-25 17:42:02 +0900153static const int mac_to_qkeycode_map[] = {
John Arbuckleaaac7142016-03-23 14:26:18 +0000154 [kVK_ANSI_A] = Q_KEY_CODE_A,
155 [kVK_ANSI_B] = Q_KEY_CODE_B,
156 [kVK_ANSI_C] = Q_KEY_CODE_C,
157 [kVK_ANSI_D] = Q_KEY_CODE_D,
158 [kVK_ANSI_E] = Q_KEY_CODE_E,
159 [kVK_ANSI_F] = Q_KEY_CODE_F,
160 [kVK_ANSI_G] = Q_KEY_CODE_G,
161 [kVK_ANSI_H] = Q_KEY_CODE_H,
162 [kVK_ANSI_I] = Q_KEY_CODE_I,
163 [kVK_ANSI_J] = Q_KEY_CODE_J,
164 [kVK_ANSI_K] = Q_KEY_CODE_K,
165 [kVK_ANSI_L] = Q_KEY_CODE_L,
166 [kVK_ANSI_M] = Q_KEY_CODE_M,
167 [kVK_ANSI_N] = Q_KEY_CODE_N,
168 [kVK_ANSI_O] = Q_KEY_CODE_O,
169 [kVK_ANSI_P] = Q_KEY_CODE_P,
170 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
171 [kVK_ANSI_R] = Q_KEY_CODE_R,
172 [kVK_ANSI_S] = Q_KEY_CODE_S,
173 [kVK_ANSI_T] = Q_KEY_CODE_T,
174 [kVK_ANSI_U] = Q_KEY_CODE_U,
175 [kVK_ANSI_V] = Q_KEY_CODE_V,
176 [kVK_ANSI_W] = Q_KEY_CODE_W,
177 [kVK_ANSI_X] = Q_KEY_CODE_X,
178 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
179 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
ths3b46e622007-09-17 08:09:54 +0000180
John Arbuckleaaac7142016-03-23 14:26:18 +0000181 [kVK_ANSI_0] = Q_KEY_CODE_0,
182 [kVK_ANSI_1] = Q_KEY_CODE_1,
183 [kVK_ANSI_2] = Q_KEY_CODE_2,
184 [kVK_ANSI_3] = Q_KEY_CODE_3,
185 [kVK_ANSI_4] = Q_KEY_CODE_4,
186 [kVK_ANSI_5] = Q_KEY_CODE_5,
187 [kVK_ANSI_6] = Q_KEY_CODE_6,
188 [kVK_ANSI_7] = Q_KEY_CODE_7,
189 [kVK_ANSI_8] = Q_KEY_CODE_8,
190 [kVK_ANSI_9] = Q_KEY_CODE_9,
191
192 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
193 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
194 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
195 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
196 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
197 [kVK_Tab] = Q_KEY_CODE_TAB,
198 [kVK_Return] = Q_KEY_CODE_RET,
199 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
200 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
201 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
202 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
203 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
204 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
205 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
206 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
John Arbuckleaaac7142016-03-23 14:26:18 +0000207 [kVK_Space] = Q_KEY_CODE_SPC,
208
209 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
210 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
211 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
212 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
213 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
214 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
215 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
216 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
217 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
218 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
219 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
220 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
221 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
222 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
223 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
224 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
225 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
226 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
227
228 [kVK_UpArrow] = Q_KEY_CODE_UP,
229 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
230 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
231 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
232
233 [kVK_Help] = Q_KEY_CODE_INSERT,
234 [kVK_Home] = Q_KEY_CODE_HOME,
235 [kVK_PageUp] = Q_KEY_CODE_PGUP,
236 [kVK_PageDown] = Q_KEY_CODE_PGDN,
237 [kVK_End] = Q_KEY_CODE_END,
238 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
239
240 [kVK_Escape] = Q_KEY_CODE_ESC,
241
242 /* The Power key can't be used directly because the operating system uses
243 * it. This key can be emulated by using it in place of another key such as
244 * F1. Don't forget to disable the real key binding.
245 */
246 /* [kVK_F1] = Q_KEY_CODE_POWER, */
247
248 [kVK_F1] = Q_KEY_CODE_F1,
249 [kVK_F2] = Q_KEY_CODE_F2,
250 [kVK_F3] = Q_KEY_CODE_F3,
251 [kVK_F4] = Q_KEY_CODE_F4,
252 [kVK_F5] = Q_KEY_CODE_F5,
253 [kVK_F6] = Q_KEY_CODE_F6,
254 [kVK_F7] = Q_KEY_CODE_F7,
255 [kVK_F8] = Q_KEY_CODE_F8,
256 [kVK_F9] = Q_KEY_CODE_F9,
257 [kVK_F10] = Q_KEY_CODE_F10,
258 [kVK_F11] = Q_KEY_CODE_F11,
259 [kVK_F12] = Q_KEY_CODE_F12,
260 [kVK_F13] = Q_KEY_CODE_PRINT,
261 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
262 [kVK_F15] = Q_KEY_CODE_PAUSE,
263
Akihiko Odaki708b7252021-02-12 09:04:04 +0900264 // JIS keyboards only
265 [kVK_JIS_Yen] = Q_KEY_CODE_YEN,
266 [kVK_JIS_Underscore] = Q_KEY_CODE_RO,
267 [kVK_JIS_KeypadComma] = Q_KEY_CODE_KP_COMMA,
268 [kVK_JIS_Eisu] = Q_KEY_CODE_MUHENKAN,
269 [kVK_JIS_Kana] = Q_KEY_CODE_HENKAN,
270
John Arbuckleaaac7142016-03-23 14:26:18 +0000271 /*
272 * The eject and volume keys can't be used here because they are handled at
273 * a lower level than what an Application can see.
274 */
bellard5b0753e2005-03-01 21:37:28 +0000275};
276
Andreas Färber77047bb2009-12-13 00:55:53 +0100277static int cocoa_keycode_to_qemu(int keycode)
bellard5b0753e2005-03-01 21:37:28 +0000278{
John Arbuckleaaac7142016-03-23 14:26:18 +0000279 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
Akihiko Odaki43137392021-02-23 22:11:06 +0900280 error_report("(cocoa) warning unknown keycode 0x%x", keycode);
bellard5b0753e2005-03-01 21:37:28 +0000281 return 0;
282 }
John Arbuckleaaac7142016-03-23 14:26:18 +0000283 return mac_to_qkeycode_map[keycode];
bellard5b0753e2005-03-01 21:37:28 +0000284}
285
John Arbuckle693a3e02015-06-19 10:53:27 +0100286/* Displays an alert dialog box with the specified message */
287static void QEMU_Alert(NSString *message)
288{
289 NSAlert *alert;
290 alert = [NSAlert new];
291 [alert setMessageText: message];
292 [alert runModal];
293}
thsc304f7e2008-01-22 23:25:15 +0000294
John Arbuckle693a3e02015-06-19 10:53:27 +0100295/* Handles any errors that happen with a device transaction */
296static void handleAnyDeviceErrors(Error * err)
297{
298 if (err) {
299 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
300 encoding: NSASCIIStringEncoding]);
301 error_free(err);
302 }
303}
thsc304f7e2008-01-22 23:25:15 +0000304
bellard5b0753e2005-03-01 21:37:28 +0000305/*
306 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +0000307 QemuCocoaView
bellard5b0753e2005-03-01 21:37:28 +0000308 ------------------------------------------------------
309*/
thsc304f7e2008-01-22 23:25:15 +0000310@interface QemuCocoaView : NSView
bellard5b0753e2005-03-01 21:37:28 +0000311{
thsc304f7e2008-01-22 23:25:15 +0000312 QEMUScreen screen;
313 NSWindow *fullScreenWindow;
314 float cx,cy,cw,ch,cdx,cdy;
Peter Maydell55888402019-02-25 10:24:33 +0000315 pixman_image_t *pixman_image;
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900316 QKbdState *kbd;
Peter Maydell49b9bd42013-12-08 22:59:03 +0000317 BOOL isMouseGrabbed;
thsc304f7e2008-01-22 23:25:15 +0000318 BOOL isFullscreen;
319 BOOL isAbsoluteEnabled;
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900320 CFMachPortRef eventsTap;
thsc304f7e2008-01-22 23:25:15 +0000321}
Peter Maydell72a3e312019-02-25 10:24:28 +0000322- (void) switchSurface:(pixman_image_t *)image;
thsc304f7e2008-01-22 23:25:15 +0000323- (void) grabMouse;
324- (void) ungrabMouse;
325- (void) toggleFullScreen:(id)sender;
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900326- (void) setFullGrab:(id)sender;
John Arbuckle9c3a4182017-11-07 10:14:14 +0000327- (void) handleMonitorInput:(NSEvent *)event;
Peter Maydell60105d72019-02-25 10:24:31 +0000328- (bool) handleEvent:(NSEvent *)event;
329- (bool) handleEventLocked:(NSEvent *)event;
thsc304f7e2008-01-22 23:25:15 +0000330- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
Peter Maydellf61c3872014-06-23 10:35:24 +0100331/* The state surrounding mouse grabbing is potentially confusing.
332 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
333 * pointing device an absolute-position one?"], but is only updated on
334 * next refresh.
335 * isMouseGrabbed tracks whether GUI events are directed to the guest;
336 * it controls whether special keys like Cmd get sent to the guest,
337 * and whether we capture the mouse when in non-absolute mode.
Peter Maydellf61c3872014-06-23 10:35:24 +0100338 */
Peter Maydell49b9bd42013-12-08 22:59:03 +0000339- (BOOL) isMouseGrabbed;
thsc304f7e2008-01-22 23:25:15 +0000340- (BOOL) isAbsoluteEnabled;
341- (float) cdx;
342- (float) cdy;
343- (QEMUScreen) gscreen;
John Arbuckle3b178b72015-09-25 23:14:00 +0100344- (void) raiseAllKeys;
thsc304f7e2008-01-22 23:25:15 +0000345@end
ths3b46e622007-09-17 08:09:54 +0000346
Andreas Färber7fee1992011-06-09 20:53:32 +0200347QemuCocoaView *cocoaView;
348
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900349static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEventRef cgEvent, void *userInfo)
350{
Philippe Mathieu-Daudé21eb7522023-10-04 14:00:13 +0200351 QemuCocoaView *view = userInfo;
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900352 NSEvent *event = [NSEvent eventWithCGEvent:cgEvent];
Philippe Mathieu-Daudé21eb7522023-10-04 14:00:13 +0200353 if ([view isMouseGrabbed] && [view handleEvent:event]) {
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900354 COCOA_DEBUG("Global events tap: qemu handled the event, capturing!\n");
355 return NULL;
356 }
357 COCOA_DEBUG("Global events tap: qemu did not handle the event, letting it through...\n");
358
359 return cgEvent;
360}
361
thsc304f7e2008-01-22 23:25:15 +0000362@implementation QemuCocoaView
363- (id)initWithFrame:(NSRect)frameRect
364{
365 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
ths3b46e622007-09-17 08:09:54 +0000366
thsc304f7e2008-01-22 23:25:15 +0000367 self = [super initWithFrame:frameRect];
368 if (self) {
pbrook95219892006-04-09 01:06:34 +0000369
thsc304f7e2008-01-22 23:25:15 +0000370 screen.width = frameRect.size.width;
371 screen.height = frameRect.size.height;
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900372 kbd = qkbd_state_init(dcl.con);
David Parsonsf5af8022024-02-24 14:06:20 +0000373#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_14_0
374 [self setClipsToBounds:YES];
375#endif
bellard7c206a72005-12-18 19:18:45 +0000376
thsc304f7e2008-01-22 23:25:15 +0000377 }
378 return self;
379}
bellard7c206a72005-12-18 19:18:45 +0000380
thsc304f7e2008-01-22 23:25:15 +0000381- (void) dealloc
382{
383 COCOA_DEBUG("QemuCocoaView: dealloc\n");
bellard7c206a72005-12-18 19:18:45 +0000384
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900385 if (pixman_image) {
Peter Maydell55888402019-02-25 10:24:33 +0000386 pixman_image_unref(pixman_image);
387 }
ths3b46e622007-09-17 08:09:54 +0000388
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900389 qkbd_state_free(kbd);
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900390
391 if (eventsTap) {
392 CFRelease(eventsTap);
393 }
394
thsc304f7e2008-01-22 23:25:15 +0000395 [super dealloc];
396}
bellard5cbfcd02006-06-14 15:53:24 +0000397
Andreas Färberd50f71d2009-12-13 02:03:33 +0100398- (BOOL) isOpaque
399{
400 return YES;
401}
402
Peter Maydell5dd45be2014-06-23 10:35:23 +0100403- (BOOL) screenContainsPoint:(NSPoint) p
404{
405 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
406}
407
Chen Zhang2044dff2019-06-04 17:36:00 +0800408/* Get location of event and convert to virtual screen coordinate */
409- (CGPoint) screenLocationOfEvent:(NSEvent *)ev
410{
411 NSWindow *eventWindow = [ev window];
412 // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
413 CGRect r = CGRectZero;
414 r.origin = [ev locationInWindow];
415 if (!eventWindow) {
416 if (!isFullscreen) {
417 return [[self window] convertRectFromScreen:r].origin;
418 } else {
419 CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
420 CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
421 if (stretch_video) {
422 loc.x /= cdx;
423 loc.y /= cdy;
424 }
425 return loc;
426 }
427 } else if ([[self window] isEqual:eventWindow]) {
428 if (!isFullscreen) {
429 return r.origin;
430 } else {
431 CGPoint loc = [self convertPoint:r.origin fromView:nil];
432 if (stretch_video) {
433 loc.x /= cdx;
434 loc.y /= cdy;
435 }
436 return loc;
437 }
438 } else {
439 return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
440 }
441}
442
Peter Maydell13aefd32014-06-23 10:35:25 +0100443- (void) hideCursor
444{
445 if (!cursor_hide) {
446 return;
447 }
448 [NSCursor hide];
449}
450
451- (void) unhideCursor
452{
453 if (!cursor_hide) {
454 return;
455 }
456 [NSCursor unhide];
457}
458
thsc304f7e2008-01-22 23:25:15 +0000459- (void) drawRect:(NSRect) rect
460{
461 COCOA_DEBUG("QemuCocoaView: drawRect\n");
bellard5cbfcd02006-06-14 15:53:24 +0000462
thsc304f7e2008-01-22 23:25:15 +0000463 // get CoreGraphic context
Brendan Shanks5e246002019-01-31 23:12:25 -0800464 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
Brendan Shanks5e246002019-01-31 23:12:25 -0800465
Carwyn Ellise28a9092023-11-10 16:17:29 +0000466 CGContextSetInterpolationQuality (viewContextRef, zoom_interpolation);
thsc304f7e2008-01-22 23:25:15 +0000467 CGContextSetShouldAntialias (viewContextRef, NO);
ths3b46e622007-09-17 08:09:54 +0000468
thsc304f7e2008-01-22 23:25:15 +0000469 // draw screen bitmap directly to Core Graphics context
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900470 if (!pixman_image) {
Peter Maydell7d270b12013-12-24 02:51:47 +0000471 // Draw request before any guest device has set up a framebuffer:
472 // just draw an opaque black rectangle
473 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
474 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
475 } else {
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900476 int w = pixman_image_get_width(pixman_image);
477 int h = pixman_image_get_height(pixman_image);
478 int bitsPerPixel = PIXMAN_FORMAT_BPP(pixman_image_get_format(pixman_image));
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900479 int stride = pixman_image_get_stride(pixman_image);
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900480 CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(
481 NULL,
482 pixman_image_get_data(pixman_image),
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900483 stride * h,
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900484 NULL
485 );
thsc304f7e2008-01-22 23:25:15 +0000486 CGImageRef imageRef = CGImageCreate(
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900487 w, //width
488 h, //height
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900489 DIV_ROUND_UP(bitsPerPixel, 8) * 2, //bitsPerComponent
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900490 bitsPerPixel, //bitsPerPixel
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900491 stride, //bytesPerRow
Akihiko Odakiae57d352021-03-05 21:13:04 +0900492 CGColorSpaceCreateWithName(kCGColorSpaceSRGB), //colorspace
493 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst, //bitmapInfo
thsc304f7e2008-01-22 23:25:15 +0000494 dataProviderRef, //provider
495 NULL, //decode
496 0, //interpolate
497 kCGRenderingIntentDefault //intent
498 );
Peter Maydellb63901d2015-05-19 09:11:17 +0100499 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
500 const NSRect *rectList;
Peter Maydellb63901d2015-05-19 09:11:17 +0100501 NSInteger rectCount;
Peter Maydellb63901d2015-05-19 09:11:17 +0100502 int i;
503 CGImageRef clipImageRef;
504 CGRect clipRect;
ths3b46e622007-09-17 08:09:54 +0000505
Peter Maydellb63901d2015-05-19 09:11:17 +0100506 [self getRectsBeingDrawn:&rectList count:&rectCount];
507 for (i = 0; i < rectCount; i++) {
508 clipRect.origin.x = rectList[i].origin.x / cdx;
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900509 clipRect.origin.y = (float)h - (rectList[i].origin.y + rectList[i].size.height) / cdy;
Peter Maydellb63901d2015-05-19 09:11:17 +0100510 clipRect.size.width = rectList[i].size.width / cdx;
511 clipRect.size.height = rectList[i].size.height / cdy;
512 clipImageRef = CGImageCreateWithImageInRect(
513 imageRef,
514 clipRect
515 );
516 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
517 CGImageRelease (clipImageRef);
bellard5b0753e2005-03-01 21:37:28 +0000518 }
thsc304f7e2008-01-22 23:25:15 +0000519 CGImageRelease (imageRef);
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900520 CGDataProviderRelease(dataProviderRef);
bellard5b0753e2005-03-01 21:37:28 +0000521 }
522}
523
thsc304f7e2008-01-22 23:25:15 +0000524- (void) setContentDimensions
bellard5b0753e2005-03-01 21:37:28 +0000525{
thsc304f7e2008-01-22 23:25:15 +0000526 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
ths3b46e622007-09-17 08:09:54 +0000527
thsc304f7e2008-01-22 23:25:15 +0000528 if (isFullscreen) {
529 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
530 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100531
532 /* stretches video, but keeps same aspect ratio */
533 if (stretch_video == true) {
534 /* use smallest stretch value - prevents clipping on sides */
535 if (MIN(cdx, cdy) == cdx) {
536 cdy = cdx;
537 } else {
538 cdx = cdy;
539 }
540 } else { /* No stretching */
541 cdx = cdy = 1;
542 }
thsc304f7e2008-01-22 23:25:15 +0000543 cw = screen.width * cdx;
544 ch = screen.height * cdy;
545 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
546 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
547 } else {
548 cx = 0;
549 cy = 0;
550 cw = screen.width;
551 ch = screen.height;
552 cdx = 1.0;
553 cdy = 1.0;
554 }
bellard5b0753e2005-03-01 21:37:28 +0000555}
556
Peter Maydell8d65dee2022-02-24 10:13:29 +0000557- (void) updateUIInfoLocked
Akihiko Odaki15280e82021-06-16 23:19:10 +0900558{
Stefan Hajnoczia4a411f2024-01-02 10:35:28 -0500559 /* Must be called with the BQL, i.e. via updateUIInfo */
Akihiko Odaki15280e82021-06-16 23:19:10 +0900560 NSSize frameSize;
561 QemuUIInfo info;
562
563 if (!qemu_console_is_graphic(dcl.con)) {
564 return;
565 }
566
567 if ([self window]) {
568 NSDictionary *description = [[[self window] screen] deviceDescription];
569 CGDirectDisplayID display = [[description objectForKey:@"NSScreenNumber"] unsignedIntValue];
570 NSSize screenSize = [[[self window] screen] frame].size;
571 CGSize screenPhysicalSize = CGDisplayScreenSize(display);
Akihiko Odaki52eaefd2022-07-02 23:25:19 +0900572 CVDisplayLinkRef displayLink;
Akihiko Odaki15280e82021-06-16 23:19:10 +0900573
574 frameSize = isFullscreen ? screenSize : [self frame].size;
Akihiko Odaki52eaefd2022-07-02 23:25:19 +0900575
576 if (!CVDisplayLinkCreateWithCGDisplay(display, &displayLink)) {
577 CVTime period = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLink);
578 CVDisplayLinkRelease(displayLink);
579 if (!(period.flags & kCVTimeIsIndefinite)) {
580 update_displaychangelistener(&dcl,
581 1000 * period.timeValue / period.timeScale);
582 info.refresh_rate = (int64_t)1000 * period.timeScale / period.timeValue;
583 }
584 }
585
Akihiko Odaki15280e82021-06-16 23:19:10 +0900586 info.width_mm = frameSize.width / screenSize.width * screenPhysicalSize.width;
587 info.height_mm = frameSize.height / screenSize.height * screenPhysicalSize.height;
588 } else {
589 frameSize = [self frame].size;
590 info.width_mm = 0;
591 info.height_mm = 0;
592 }
593
594 info.xoff = 0;
595 info.yoff = 0;
596 info.width = frameSize.width;
597 info.height = frameSize.height;
598
Marc-André Lureauca19ef52021-04-13 20:39:11 +0400599 dpy_set_ui_info(dcl.con, &info, TRUE);
Akihiko Odaki15280e82021-06-16 23:19:10 +0900600}
601
Peter Maydell8d65dee2022-02-24 10:13:29 +0000602- (void) updateUIInfo
603{
604 if (!allow_events) {
605 /*
606 * Don't try to tell QEMU about UI information in the application
607 * startup phase -- we haven't yet registered dcl with the QEMU UI
Akihiko Odakibab6a302022-08-19 22:27:54 +0900608 * layer.
Peter Maydell8d65dee2022-02-24 10:13:29 +0000609 * When cocoa_display_init() does register the dcl, the UI layer
610 * will call cocoa_switch(), which will call updateUIInfo, so
611 * we don't lose any information here.
612 */
613 return;
614 }
615
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500616 with_bql(^{
Peter Maydell8d65dee2022-02-24 10:13:29 +0000617 [self updateUIInfoLocked];
618 });
619}
620
Akihiko Odaki15280e82021-06-16 23:19:10 +0900621- (void)viewDidMoveToWindow
622{
623 [self updateUIInfo];
624}
625
Peter Maydell72a3e312019-02-25 10:24:28 +0000626- (void) switchSurface:(pixman_image_t *)image
thsc304f7e2008-01-22 23:25:15 +0000627{
Gerd Hoffmann5e00d3a2013-03-01 12:52:06 +0100628 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
thsc304f7e2008-01-22 23:25:15 +0000629
Peter Maydell72a3e312019-02-25 10:24:28 +0000630 int w = pixman_image_get_width(image);
631 int h = pixman_image_get_height(image);
Peter Maydell381600d2014-06-23 10:35:22 +0100632 /* cdx == 0 means this is our very first surface, in which case we need
633 * to recalculate the content dimensions even if it happens to be the size
634 * of the initial empty window.
635 */
636 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
Peter Maydelld3345a02013-12-24 02:51:46 +0000637
638 int oldh = screen.height;
639 if (isResize) {
640 // Resize before we trigger the redraw, or we'll redraw at the wrong size
641 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
642 screen.width = w;
643 screen.height = h;
644 [self setContentDimensions];
645 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
646 }
Peter Maydell8510d912013-03-18 20:28:21 +0000647
thsc304f7e2008-01-22 23:25:15 +0000648 // update screenBuffer
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900649 if (pixman_image) {
Peter Maydell55888402019-02-25 10:24:33 +0000650 pixman_image_unref(pixman_image);
651 }
thsc304f7e2008-01-22 23:25:15 +0000652
Peter Maydell55888402019-02-25 10:24:33 +0000653 pixman_image = image;
thsc304f7e2008-01-22 23:25:15 +0000654
655 // update windows
656 if (isFullscreen) {
657 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
Peter Maydelld3345a02013-12-24 02:51:46 +0000658 [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 +0000659 } else {
660 if (qemu_name)
661 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
Peter Maydelld3345a02013-12-24 02:51:46 +0000662 [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 +0000663 }
Peter Maydelld3345a02013-12-24 02:51:46 +0000664
665 if (isResize) {
666 [normalWindow center];
667 }
thsc304f7e2008-01-22 23:25:15 +0000668}
669
670- (void) toggleFullScreen:(id)sender
671{
672 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
673
674 if (isFullscreen) { // switch from fullscreen to desktop
675 isFullscreen = FALSE;
676 [self ungrabMouse];
677 [self setContentDimensions];
Akihiko Odaki1e8b6f22021-02-20 10:31:38 +0900678 [fullScreenWindow close];
679 [normalWindow setContentView: self];
680 [normalWindow makeKeyAndOrderFront: self];
681 [NSMenu setMenuBarVisible:YES];
thsc304f7e2008-01-22 23:25:15 +0000682 } else { // switch from desktop to fullscreen
683 isFullscreen = TRUE;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100684 [normalWindow orderOut: nil]; /* Hide the window */
thsc304f7e2008-01-22 23:25:15 +0000685 [self grabMouse];
686 [self setContentDimensions];
Akihiko Odaki1e8b6f22021-02-20 10:31:38 +0900687 [NSMenu setMenuBarVisible:NO];
688 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
689 styleMask:NSWindowStyleMaskBorderless
690 backing:NSBackingStoreBuffered
691 defer:NO];
692 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
693 [fullScreenWindow setHasShadow:NO];
694 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
695 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
696 [[fullScreenWindow contentView] addSubview: self];
697 [fullScreenWindow makeKeyAndOrderFront:self];
thsc304f7e2008-01-22 23:25:15 +0000698 }
699}
700
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900701- (void) setFullGrab:(id)sender
702{
703 COCOA_DEBUG("QemuCocoaView: setFullGrab\n");
704
705 CGEventMask mask = CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp) | CGEventMaskBit(kCGEventFlagsChanged);
706 eventsTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault,
707 mask, handleTapEvent, self);
708 if (!eventsTap) {
709 warn_report("Could not create event tap, system key combos will not be captured.\n");
710 return;
711 } else {
712 COCOA_DEBUG("Global events tap created! Will capture system key combos.\n");
713 }
714
715 CFRunLoopRef runLoop = CFRunLoopGetCurrent();
716 if (!runLoop) {
717 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
718 return;
719 }
720
721 CFRunLoopSourceRef tapEventsSrc = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventsTap, 0);
722 if (!tapEventsSrc ) {
723 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
724 return;
725 }
726
727 CFRunLoopAddSource(runLoop, tapEventsSrc, kCFRunLoopDefaultMode);
728 CFRelease(tapEventsSrc);
729}
730
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900731- (void) toggleKey: (int)keycode {
732 qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode));
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700733}
734
John Arbuckle9c3a4182017-11-07 10:14:14 +0000735// Does the work of sending input to the monitor
736- (void) handleMonitorInput:(NSEvent *)event
737{
738 int keysym = 0;
739 int control_key = 0;
740
741 // if the control key is down
742 if ([event modifierFlags] & NSEventModifierFlagControl) {
743 control_key = 1;
744 }
745
746 /* translates Macintosh keycodes to QEMU's keysym */
747
Philippe Mathieu-Daudé94592622022-02-15 16:21:14 +0100748 static const int without_control_translation[] = {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000749 [0 ... 0xff] = 0, // invalid key
750
751 [kVK_UpArrow] = QEMU_KEY_UP,
752 [kVK_DownArrow] = QEMU_KEY_DOWN,
753 [kVK_RightArrow] = QEMU_KEY_RIGHT,
754 [kVK_LeftArrow] = QEMU_KEY_LEFT,
755 [kVK_Home] = QEMU_KEY_HOME,
756 [kVK_End] = QEMU_KEY_END,
757 [kVK_PageUp] = QEMU_KEY_PAGEUP,
758 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
759 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
760 [kVK_Delete] = QEMU_KEY_BACKSPACE,
761 };
762
Philippe Mathieu-Daudé94592622022-02-15 16:21:14 +0100763 static const int with_control_translation[] = {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000764 [0 ... 0xff] = 0, // invalid key
765
766 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
767 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
768 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
769 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
770 [kVK_Home] = QEMU_KEY_CTRL_HOME,
771 [kVK_End] = QEMU_KEY_CTRL_END,
772 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
773 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
774 };
775
776 if (control_key != 0) { /* If the control key is being used */
777 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
778 keysym = with_control_translation[[event keyCode]];
779 }
780 } else {
781 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
782 keysym = without_control_translation[[event keyCode]];
783 }
784 }
785
786 // if not a key that needs translating
787 if (keysym == 0) {
788 NSString *ks = [event characters];
789 if ([ks length] > 0) {
790 keysym = [ks characterAtIndex:0];
791 }
792 }
793
794 if (keysym) {
Marc-André Lureaucc6ba2c2023-08-30 13:38:20 +0400795 qemu_text_console_put_keysym(NULL, keysym);
John Arbuckle9c3a4182017-11-07 10:14:14 +0000796 }
797}
798
Peter Maydell60105d72019-02-25 10:24:31 +0000799- (bool) handleEvent:(NSEvent *)event
thsc304f7e2008-01-22 23:25:15 +0000800{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500801 return bool_with_bql(^{
Peter Maydell60105d72019-02-25 10:24:31 +0000802 return [self handleEventLocked:event];
Peter Maydell31819e92019-02-25 10:24:27 +0000803 });
804}
thsc304f7e2008-01-22 23:25:15 +0000805
Peter Maydell60105d72019-02-25 10:24:31 +0000806- (bool) handleEventLocked:(NSEvent *)event
Peter Maydell31819e92019-02-25 10:24:27 +0000807{
Peter Maydell60105d72019-02-25 10:24:31 +0000808 /* Return true if we handled the event, false if it should be given to OSX */
Peter Maydell31819e92019-02-25 10:24:27 +0000809 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
thsc304f7e2008-01-22 23:25:15 +0000810 int buttons = 0;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700811 int keycode = 0;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100812 bool mouse_event = false;
Chen Zhang2044dff2019-06-04 17:36:00 +0800813 // Location of event in virtual screen coordinates
814 NSPoint p = [self screenLocationOfEvent:event];
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900815 NSUInteger modifiers = [event modifierFlags];
816
Akihiko Odakiad7f2f82021-03-12 22:32:12 +0900817 /*
818 * Check -[NSEvent modifierFlags] here.
819 *
820 * There is a NSEventType for an event notifying the change of
821 * -[NSEvent modifierFlags], NSEventTypeFlagsChanged but these operations
822 * are performed for any events because a modifier state may change while
823 * the application is inactive (i.e. no events fire) and we don't want to
824 * wait for another modifier state change to detect such a change.
825 *
826 * NSEventModifierFlagCapsLock requires a special treatment. The other flags
827 * are handled in similar manners.
828 *
829 * NSEventModifierFlagCapsLock
830 * ---------------------------
831 *
832 * If CapsLock state is changed, "up" and "down" events will be fired in
833 * sequence, effectively updates CapsLock state on the guest.
834 *
835 * The other flags
836 * ---------------
837 *
838 * If a flag is not set, fire "up" events for all keys which correspond to
839 * the flag. Note that "down" events are not fired here because the flags
840 * checked here do not tell what exact keys are down.
841 *
842 * If one of the keys corresponding to a flag is down, we rely on
843 * -[NSEvent keyCode] of an event whose -[NSEvent type] is
844 * NSEventTypeFlagsChanged to know the exact key which is down, which has
845 * the following two downsides:
846 * - It does not work when the application is inactive as described above.
847 * - It malfactions *after* the modifier state is changed while the
848 * application is inactive. It is because -[NSEvent keyCode] does not tell
849 * if the key is up or down, and requires to infer the current state from
850 * the previous state. It is still possible to fix such a malfanction by
851 * completely leaving your hands from the keyboard, which hopefully makes
852 * this implementation usable enough.
853 */
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900854 if (!!(modifiers & NSEventModifierFlagCapsLock) !=
855 qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) {
856 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true);
857 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false);
858 }
859
860 if (!(modifiers & NSEventModifierFlagShift)) {
861 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false);
862 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false);
863 }
864 if (!(modifiers & NSEventModifierFlagControl)) {
865 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false);
866 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false);
867 }
868 if (!(modifiers & NSEventModifierFlagOption)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900869 if (swap_opt_cmd) {
870 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
871 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
872 } else {
873 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
874 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
875 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900876 }
877 if (!(modifiers & NSEventModifierFlagCommand)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900878 if (swap_opt_cmd) {
879 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
880 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
881 } else {
882 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
883 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
884 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900885 }
thsc304f7e2008-01-22 23:25:15 +0000886
887 switch ([event type]) {
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700888 case NSEventTypeFlagsChanged:
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900889 switch ([event keyCode]) {
890 case kVK_Shift:
891 if (!!(modifiers & NSEventModifierFlagShift)) {
892 [self toggleKey:Q_KEY_CODE_SHIFT];
893 }
894 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700895
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900896 case kVK_RightShift:
897 if (!!(modifiers & NSEventModifierFlagShift)) {
898 [self toggleKey:Q_KEY_CODE_SHIFT_R];
899 }
900 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700901
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900902 case kVK_Control:
903 if (!!(modifiers & NSEventModifierFlagControl)) {
904 [self toggleKey:Q_KEY_CODE_CTRL];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700905 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900906 break;
907
908 case kVK_RightControl:
909 if (!!(modifiers & NSEventModifierFlagControl)) {
910 [self toggleKey:Q_KEY_CODE_CTRL_R];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700911 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900912 break;
913
914 case kVK_Option:
915 if (!!(modifiers & NSEventModifierFlagOption)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900916 if (swap_opt_cmd) {
917 [self toggleKey:Q_KEY_CODE_META_L];
918 } else {
919 [self toggleKey:Q_KEY_CODE_ALT];
920 }
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700921 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900922 break;
923
924 case kVK_RightOption:
925 if (!!(modifiers & NSEventModifierFlagOption)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900926 if (swap_opt_cmd) {
927 [self toggleKey:Q_KEY_CODE_META_R];
928 } else {
929 [self toggleKey:Q_KEY_CODE_ALT_R];
930 }
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700931 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900932 break;
933
934 /* Don't pass command key changes to guest unless mouse is grabbed */
935 case kVK_Command:
936 if (isMouseGrabbed &&
Akihiko Odakid6b6dea2022-03-18 00:29:49 +0900937 !!(modifiers & NSEventModifierFlagCommand) &&
938 left_command_key_enabled) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900939 if (swap_opt_cmd) {
940 [self toggleKey:Q_KEY_CODE_ALT];
941 } else {
942 [self toggleKey:Q_KEY_CODE_META_L];
943 }
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700944 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900945 break;
946
947 case kVK_RightCommand:
948 if (isMouseGrabbed &&
949 !!(modifiers & NSEventModifierFlagCommand)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900950 if (swap_opt_cmd) {
951 [self toggleKey:Q_KEY_CODE_ALT_R];
952 } else {
953 [self toggleKey:Q_KEY_CODE_META_R];
954 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900955 }
956 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700957 }
thsc304f7e2008-01-22 23:25:15 +0000958 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700959 case NSEventTypeKeyDown:
Peter Maydell88959192013-12-08 22:59:02 +0000960 keycode = cocoa_keycode_to_qemu([event keyCode]);
thsc304f7e2008-01-22 23:25:15 +0000961
Peter Maydell88959192013-12-08 22:59:02 +0000962 // forward command key combos to the host UI unless the mouse is grabbed
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700963 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
Peter Maydell60105d72019-02-25 10:24:31 +0000964 return false;
thsc304f7e2008-01-22 23:25:15 +0000965 }
966
967 // default
thsc304f7e2008-01-22 23:25:15 +0000968
John Arbuckle5929e362017-11-07 10:14:14 +0000969 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700970 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
John Arbuckle5929e362017-11-07 10:14:14 +0000971 NSString *keychar = [event charactersIgnoringModifiers];
972 if ([keychar length] == 1) {
973 char key = [keychar characterAtIndex:0];
974 switch (key) {
thsc304f7e2008-01-22 23:25:15 +0000975
John Arbuckle5929e362017-11-07 10:14:14 +0000976 // enable graphic console
977 case '1' ... '9':
978 console_select(key - '0' - 1); /* ascii math */
Peter Maydell60105d72019-02-25 10:24:31 +0000979 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000980
981 // release the mouse grab
982 case 'g':
983 [self ungrabMouse];
Peter Maydell60105d72019-02-25 10:24:31 +0000984 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000985 }
thsc304f7e2008-01-22 23:25:15 +0000986 }
Peter Maydellef2088f2017-11-07 10:14:14 +0000987 }
thsc304f7e2008-01-22 23:25:15 +0000988
Peter Maydellef2088f2017-11-07 10:14:14 +0000989 if (qemu_console_is_graphic(NULL)) {
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900990 qkbd_state_key_event(kbd, keycode, true);
thsc304f7e2008-01-22 23:25:15 +0000991 } else {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000992 [self handleMonitorInput: event];
thsc304f7e2008-01-22 23:25:15 +0000993 }
994 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700995 case NSEventTypeKeyUp:
thsc304f7e2008-01-22 23:25:15 +0000996 keycode = cocoa_keycode_to_qemu([event keyCode]);
Peter Maydell88959192013-12-08 22:59:02 +0000997
998 // don't pass the guest a spurious key-up if we treated this
999 // command-key combo as a host UI action
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001000 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
Peter Maydell60105d72019-02-25 10:24:31 +00001001 return true;
Peter Maydell88959192013-12-08 22:59:02 +00001002 }
1003
Peter Maydell68c0aa62013-04-17 09:16:35 +00001004 if (qemu_console_is_graphic(NULL)) {
Akihiko Odaki6d73bb62021-03-10 23:46:02 +09001005 qkbd_state_key_event(kbd, keycode, false);
thsc304f7e2008-01-22 23:25:15 +00001006 }
1007 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001008 case NSEventTypeMouseMoved:
thsc304f7e2008-01-22 23:25:15 +00001009 if (isAbsoluteEnabled) {
Chen Zhang2044dff2019-06-04 17:36:00 +08001010 // Cursor re-entered into a window might generate events bound to screen coordinates
1011 // and `nil` window property, and in full screen mode, current window might not be
1012 // key window, where event location alone should suffice.
1013 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
Peter Maydellf61c3872014-06-23 10:35:24 +01001014 if (isMouseGrabbed) {
1015 [self ungrabMouse];
thsc304f7e2008-01-22 23:25:15 +00001016 }
1017 } else {
Peter Maydellf61c3872014-06-23 10:35:24 +01001018 if (!isMouseGrabbed) {
1019 [self grabMouse];
thsc304f7e2008-01-22 23:25:15 +00001020 }
1021 }
1022 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001023 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +00001024 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001025 case NSEventTypeLeftMouseDown:
Akihiko Odaki4295f832021-02-12 09:07:06 +09001026 buttons |= MOUSE_EVENT_LBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001027 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +00001028 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001029 case NSEventTypeRightMouseDown:
thsc304f7e2008-01-22 23:25:15 +00001030 buttons |= MOUSE_EVENT_RBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001031 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +00001032 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001033 case NSEventTypeOtherMouseDown:
thsc304f7e2008-01-22 23:25:15 +00001034 buttons |= MOUSE_EVENT_MBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001035 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +00001036 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001037 case NSEventTypeLeftMouseDragged:
Akihiko Odaki4295f832021-02-12 09:07:06 +09001038 buttons |= MOUSE_EVENT_LBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001039 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +00001040 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001041 case NSEventTypeRightMouseDragged:
thsc304f7e2008-01-22 23:25:15 +00001042 buttons |= MOUSE_EVENT_RBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001043 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +00001044 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001045 case NSEventTypeOtherMouseDragged:
thsc304f7e2008-01-22 23:25:15 +00001046 buttons |= MOUSE_EVENT_MBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001047 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +00001048 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001049 case NSEventTypeLeftMouseUp:
Peter Maydellf61c3872014-06-23 10:35:24 +01001050 mouse_event = true;
1051 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
Chen Zhang8e23e342019-06-04 17:36:48 +08001052 /*
1053 * In fullscreen mode, the window of cocoaView may not be the
1054 * key window, therefore the position relative to the virtual
1055 * screen alone will be sufficient.
1056 */
1057 if(isFullscreen || [[self window] isKeyWindow]) {
Programmingkid9e8204b2016-08-15 22:11:06 -04001058 [self grabMouse];
1059 }
thsc304f7e2008-01-22 23:25:15 +00001060 }
1061 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001062 case NSEventTypeRightMouseUp:
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001063 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +00001064 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001065 case NSEventTypeOtherMouseUp:
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001066 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +00001067 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001068 case NSEventTypeScrollWheel:
John Arbuckleae7313e2018-01-08 13:07:07 -05001069 /*
1070 * Send wheel events to the guest regardless of window focus.
1071 * This is in-line with standard Mac OS X UI behaviour.
1072 */
1073
John Arbuckledc3c89d2018-07-09 11:02:35 -04001074 /*
Dmitry Petrovd70a5de2022-01-08 16:39:44 +01001075 * We shouldn't have got a scroll event when deltaY and delta Y
1076 * are zero, hence no harm in dropping the event
John Arbuckledc3c89d2018-07-09 11:02:35 -04001077 */
Dmitry Petrovd70a5de2022-01-08 16:39:44 +01001078 if ([event deltaY] != 0 || [event deltaX] != 0) {
John Arbuckleae7313e2018-01-08 13:07:07 -05001079 /* Determine if this is a scroll up or scroll down event */
Dmitry Petrovd70a5de2022-01-08 16:39:44 +01001080 if ([event deltaY] != 0) {
1081 buttons = ([event deltaY] > 0) ?
John Arbuckledc3c89d2018-07-09 11:02:35 -04001082 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
Dmitry Petrovd70a5de2022-01-08 16:39:44 +01001083 } else if ([event deltaX] != 0) {
1084 buttons = ([event deltaX] > 0) ?
1085 INPUT_BUTTON_WHEEL_LEFT : INPUT_BUTTON_WHEEL_RIGHT;
1086 }
1087
Akihiko Odakicc7859c2021-02-19 17:44:19 +09001088 qemu_input_queue_btn(dcl.con, buttons, true);
John Arbuckledc3c89d2018-07-09 11:02:35 -04001089 qemu_input_event_sync();
Akihiko Odakicc7859c2021-02-19 17:44:19 +09001090 qemu_input_queue_btn(dcl.con, buttons, false);
John Arbuckledc3c89d2018-07-09 11:02:35 -04001091 qemu_input_event_sync();
1092 }
Dmitry Petrovd70a5de2022-01-08 16:39:44 +01001093
John Arbuckleae7313e2018-01-08 13:07:07 -05001094 /*
Dmitry Petrovd70a5de2022-01-08 16:39:44 +01001095 * Since deltaX/deltaY also report scroll wheel events we prevent mouse
John Arbuckleae7313e2018-01-08 13:07:07 -05001096 * movement code from executing.
1097 */
1098 mouse_event = false;
thsc304f7e2008-01-22 23:25:15 +00001099 break;
1100 default:
Peter Maydell60105d72019-02-25 10:24:31 +00001101 return false;
thsc304f7e2008-01-22 23:25:15 +00001102 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001103
1104 if (mouse_event) {
Peter Maydell8d3a5d92015-11-26 15:19:28 +00001105 /* Don't send button events to the guest unless we've got a
1106 * mouse grab or window focus. If we have neither then this event
1107 * is the user clicking on the background window to activate and
1108 * bring us to the front, which will be done by the sendEvent
1109 * call below. We definitely don't want to pass that click through
1110 * to the guest.
1111 */
1112 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
1113 (last_buttons != buttons)) {
Eric Blake7fb1cf12015-11-18 01:52:57 -07001114 static uint32_t bmap[INPUT_BUTTON__MAX] = {
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001115 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1116 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
John Arbuckleae7313e2018-01-08 13:07:07 -05001117 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001118 };
Akihiko Odakicc7859c2021-02-19 17:44:19 +09001119 qemu_input_update_buttons(dcl.con, bmap, last_buttons, buttons);
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001120 last_buttons = buttons;
1121 }
Peter Maydellf61c3872014-06-23 10:35:24 +01001122 if (isMouseGrabbed) {
1123 if (isAbsoluteEnabled) {
1124 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
1125 * The check on screenContainsPoint is to avoid sending out of range values for
1126 * clicks in the titlebar.
1127 */
1128 if ([self screenContainsPoint:p]) {
Akihiko Odakicc7859c2021-02-19 17:44:19 +09001129 qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x, 0, screen.width);
1130 qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
Peter Maydellf61c3872014-06-23 10:35:24 +01001131 }
1132 } else {
Akihiko Odakicc7859c2021-02-19 17:44:19 +09001133 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, (int)[event deltaX]);
1134 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, (int)[event deltaY]);
Peter Maydellf61c3872014-06-23 10:35:24 +01001135 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001136 } else {
Peter Maydell60105d72019-02-25 10:24:31 +00001137 return false;
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001138 }
1139 qemu_input_event_sync();
1140 }
Peter Maydell60105d72019-02-25 10:24:31 +00001141 return true;
thsc304f7e2008-01-22 23:25:15 +00001142}
1143
1144- (void) grabMouse
1145{
1146 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
1147
1148 if (!isFullscreen) {
1149 if (qemu_name)
Christian Schoenebeck23bdd0d2022-12-27 17:15:31 +01001150 [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 +00001151 else
Christian Schoenebeck23bdd0d2022-12-27 17:15:31 +01001152 [normalWindow setTitle:@"QEMU - (Press " UC_CTRL_KEY " " UC_ALT_KEY " G to release Mouse)"];
thsc304f7e2008-01-22 23:25:15 +00001153 }
Peter Maydell13aefd32014-06-23 10:35:25 +01001154 [self hideCursor];
Akihiko Odakid1929062021-02-23 00:07:14 +09001155 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
Peter Maydell49b9bd42013-12-08 22:59:03 +00001156 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
thsc304f7e2008-01-22 23:25:15 +00001157}
1158
1159- (void) ungrabMouse
1160{
1161 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
1162
1163 if (!isFullscreen) {
1164 if (qemu_name)
1165 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
1166 else
1167 [normalWindow setTitle:@"QEMU"];
1168 }
Peter Maydell13aefd32014-06-23 10:35:25 +01001169 [self unhideCursor];
Akihiko Odakid1929062021-02-23 00:07:14 +09001170 CGAssociateMouseAndMouseCursorPosition(TRUE);
Peter Maydell49b9bd42013-12-08 22:59:03 +00001171 isMouseGrabbed = FALSE;
thsc304f7e2008-01-22 23:25:15 +00001172}
1173
Akihiko Odakid1929062021-02-23 00:07:14 +09001174- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {
1175 isAbsoluteEnabled = tIsAbsoluteEnabled;
1176 if (isMouseGrabbed) {
1177 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1178 }
1179}
Peter Maydell49b9bd42013-12-08 22:59:03 +00001180- (BOOL) isMouseGrabbed {return isMouseGrabbed;}
thsc304f7e2008-01-22 23:25:15 +00001181- (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
1182- (float) cdx {return cdx;}
1183- (float) cdy {return cdy;}
1184- (QEMUScreen) gscreen {return screen;}
John Arbuckle3b178b72015-09-25 23:14:00 +01001185
1186/*
1187 * Makes the target think all down keys are being released.
1188 * This prevents a stuck key problem, since we will not see
1189 * key up events for those keys after we have lost focus.
1190 */
1191- (void) raiseAllKeys
1192{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001193 with_bql(^{
Akihiko Odaki6d73bb62021-03-10 23:46:02 +09001194 qkbd_state_lift_all_keys(kbd);
Peter Maydell31819e92019-02-25 10:24:27 +00001195 });
John Arbuckle3b178b72015-09-25 23:14:00 +01001196}
bellard5b0753e2005-03-01 21:37:28 +00001197@end
1198
1199
thsc304f7e2008-01-22 23:25:15 +00001200
bellard5b0753e2005-03-01 21:37:28 +00001201/*
1202 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +00001203 QemuCocoaAppController
bellard5b0753e2005-03-01 21:37:28 +00001204 ------------------------------------------------------
1205*/
thsc304f7e2008-01-22 23:25:15 +00001206@interface QemuCocoaAppController : NSObject
John Arbuckled9bc14f2015-09-25 23:13:59 +01001207 <NSWindowDelegate, NSApplicationDelegate>
bellard5b0753e2005-03-01 21:37:28 +00001208{
1209}
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001210- (void)doToggleFullScreen:(id)sender;
thsc304f7e2008-01-22 23:25:15 +00001211- (void)toggleFullScreen:(id)sender;
1212- (void)showQEMUDoc:(id)sender;
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001213- (void)zoomToFit:(id) sender;
Programmingkidb4c6a112015-05-19 09:11:18 +01001214- (void)displayConsole:(id)sender;
John Arbuckle8524f1c2015-06-19 10:53:27 +01001215- (void)pauseQEMU:(id)sender;
1216- (void)resumeQEMU:(id)sender;
1217- (void)displayPause;
1218- (void)removePause;
John Arbuckle27074612015-06-19 10:53:27 +01001219- (void)restartQEMU:(id)sender;
1220- (void)powerDownQEMU:(id)sender;
John Arbuckle693a3e02015-06-19 10:53:27 +01001221- (void)ejectDeviceMedia:(id)sender;
1222- (void)changeDeviceMedia:(id)sender;
John Arbuckled9bc14f2015-09-25 23:13:59 +01001223- (BOOL)verifyQuit;
John Arbucklef4747902016-03-23 14:26:17 +00001224- (void)openDocumentation:(NSString *)filename;
Programmingkid9e8204b2016-08-15 22:11:06 -04001225- (IBAction) do_about_menu_item: (id) sender;
John Arbucklee47ec1a2017-06-13 23:17:38 -04001226- (void)adjustSpeed:(id)sender;
bellard5b0753e2005-03-01 21:37:28 +00001227@end
1228
thsc304f7e2008-01-22 23:25:15 +00001229@implementation QemuCocoaAppController
1230- (id) init
1231{
1232 COCOA_DEBUG("QemuCocoaAppController: init\n");
1233
1234 self = [super init];
1235 if (self) {
1236
1237 // create a view and add it to the window
1238 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1239 if(!cocoaView) {
Akihiko Odaki43137392021-02-23 22:11:06 +09001240 error_report("(cocoa) can't create a view");
thsc304f7e2008-01-22 23:25:15 +00001241 exit(1);
1242 }
1243
1244 // create a window
1245 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001246 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
thsc304f7e2008-01-22 23:25:15 +00001247 backing:NSBackingStoreBuffered defer:NO];
1248 if(!normalWindow) {
Akihiko Odaki43137392021-02-23 22:11:06 +09001249 error_report("(cocoa) can't create window");
thsc304f7e2008-01-22 23:25:15 +00001250 exit(1);
1251 }
1252 [normalWindow setAcceptsMouseMovedEvents:YES];
John Arbucklea1dbc052015-10-13 21:51:18 +01001253 [normalWindow setTitle:@"QEMU"];
thsc304f7e2008-01-22 23:25:15 +00001254 [normalWindow setContentView:cocoaView];
1255 [normalWindow makeKeyAndOrderFront:self];
Peter Maydell49060c22013-12-24 11:54:12 +00001256 [normalWindow center];
John Arbuckled9bc14f2015-09-25 23:13:59 +01001257 [normalWindow setDelegate: self];
John Arbuckle8524f1c2015-06-19 10:53:27 +01001258
1259 /* Used for displaying pause on the screen */
1260 pauseLabel = [NSTextField new];
1261 [pauseLabel setBezeled:YES];
1262 [pauseLabel setDrawsBackground:YES];
1263 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1264 [pauseLabel setEditable:NO];
1265 [pauseLabel setSelectable:NO];
1266 [pauseLabel setStringValue: @"Paused"];
1267 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1268 [pauseLabel setTextColor: [NSColor blackColor]];
1269 [pauseLabel sizeToFit];
thsc304f7e2008-01-22 23:25:15 +00001270 }
1271 return self;
1272}
1273
1274- (void) dealloc
1275{
1276 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1277
1278 if (cocoaView)
1279 [cocoaView release];
1280 [super dealloc];
1281}
1282
bellard5b0753e2005-03-01 21:37:28 +00001283- (void)applicationDidFinishLaunching: (NSNotification *) note
1284{
thsc304f7e2008-01-22 23:25:15 +00001285 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
Hikaru Nishidadff742a2019-10-15 10:07:34 +09001286 allow_events = true;
bellard5b0753e2005-03-01 21:37:28 +00001287}
1288
1289- (void)applicationWillTerminate:(NSNotification *)aNotification
1290{
thsc304f7e2008-01-22 23:25:15 +00001291 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1292
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001293 with_bql(^{
Akihiko Odaki2910abd2022-05-29 17:25:08 +09001294 shutdown_action = SHUTDOWN_ACTION_POWEROFF;
1295 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1296 });
Akihiko Odaki40c01932021-02-19 20:16:52 +09001297
1298 /*
1299 * Sleep here, because returning will cause OSX to kill us
1300 * immediately; the QEMU main loop will handle the shutdown
1301 * request and terminate the process.
1302 */
1303 [NSThread sleepForTimeInterval:INFINITY];
bellard5b0753e2005-03-01 21:37:28 +00001304}
1305
Andreas Färber41ea49b2009-12-14 22:13:27 +01001306- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1307{
1308 return YES;
1309}
1310
John Arbuckled9bc14f2015-09-25 23:13:59 +01001311- (NSApplicationTerminateReply)applicationShouldTerminate:
1312 (NSApplication *)sender
1313{
1314 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1315 return [self verifyQuit];
1316}
1317
Akihiko Odaki15280e82021-06-16 23:19:10 +09001318- (void)windowDidChangeScreen:(NSNotification *)notification
1319{
1320 [cocoaView updateUIInfo];
1321}
1322
1323- (void)windowDidResize:(NSNotification *)notification
1324{
1325 [cocoaView updateUIInfo];
1326}
1327
John Arbuckled9bc14f2015-09-25 23:13:59 +01001328/* Called when the user clicks on a window's close button */
1329- (BOOL)windowShouldClose:(id)sender
1330{
1331 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1332 [NSApp terminate: sender];
1333 /* If the user allows the application to quit then the call to
1334 * NSApp terminate will never return. If we get here then the user
1335 * cancelled the quit, so we should return NO to not permit the
1336 * closing of this window.
1337 */
1338 return NO;
1339}
1340
Akihiko Odaki9d9bc7d2023-02-28 16:09:46 +09001341/*
1342 * Called when QEMU goes into the background. Note that
1343 * [-NSWindowDelegate windowDidResignKey:] is used here instead of
1344 * [-NSApplicationDelegate applicationWillResignActive:] because it cannot
1345 * detect that the window loses focus when the deck is clicked on macOS 13.2.1.
1346 */
1347- (void) windowDidResignKey: (NSNotification *)aNotification
John Arbuckle3b178b72015-09-25 23:14:00 +01001348{
Akihiko Odaki9d9bc7d2023-02-28 16:09:46 +09001349 COCOA_DEBUG("%s\n", __func__);
Carwyn Ellis69221df2022-01-02 17:41:53 +00001350 [cocoaView ungrabMouse];
John Arbuckle3b178b72015-09-25 23:14:00 +01001351 [cocoaView raiseAllKeys];
1352}
1353
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001354/* We abstract the method called by the Enter Fullscreen menu item
1355 * because Mac OS 10.7 and higher disables it. This is because of the
1356 * menu item's old selector's name toggleFullScreen:
1357 */
1358- (void) doToggleFullScreen:(id)sender
1359{
1360 [self toggleFullScreen:(id)sender];
1361}
1362
thsc304f7e2008-01-22 23:25:15 +00001363- (void)toggleFullScreen:(id)sender
bellard5b0753e2005-03-01 21:37:28 +00001364{
thsc304f7e2008-01-22 23:25:15 +00001365 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1366
1367 [cocoaView toggleFullScreen:sender];
1368}
1369
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +09001370- (void) setFullGrab:(id)sender
1371{
1372 COCOA_DEBUG("QemuCocoaAppController: setFullGrab\n");
1373
1374 [cocoaView setFullGrab:sender];
1375}
1376
John Arbucklef4747902016-03-23 14:26:17 +00001377/* Tries to find then open the specified filename */
1378- (void) openDocumentation: (NSString *) filename
1379{
1380 /* Where to look for local files */
Roman Bolshakov8d6fda82021-01-09 00:38:15 +03001381 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
John Arbucklef4747902016-03-23 14:26:17 +00001382 NSString *full_file_path;
Roman Bolshakov1ff5a062021-01-02 18:07:21 +03001383 NSURL *full_file_url;
John Arbucklef4747902016-03-23 14:26:17 +00001384
1385 /* iterate thru the possible paths until the file is found */
1386 int index;
1387 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1388 full_file_path = [[NSBundle mainBundle] executablePath];
1389 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1390 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1391 path_array[index], filename];
Roman Bolshakov1ff5a062021-01-02 18:07:21 +03001392 full_file_url = [NSURL fileURLWithPath: full_file_path
1393 isDirectory: false];
1394 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
John Arbucklef4747902016-03-23 14:26:17 +00001395 return;
1396 }
1397 }
1398
1399 /* If none of the paths opened a file */
1400 NSBeep();
1401 QEMU_Alert(@"Failed to open file");
1402}
1403
thsc304f7e2008-01-22 23:25:15 +00001404- (void)showQEMUDoc:(id)sender
1405{
1406 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1407
Peter Maydell1879f242020-02-28 15:36:16 +00001408 [self openDocumentation: @"index.html"];
thsc304f7e2008-01-22 23:25:15 +00001409}
1410
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001411/* Stretches video to fit host monitor size */
1412- (void)zoomToFit:(id) sender
1413{
1414 stretch_video = !stretch_video;
1415 if (stretch_video == true) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001416 [sender setState: NSControlStateValueOn];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001417 } else {
Brendan Shanks5e246002019-01-31 23:12:25 -08001418 [sender setState: NSControlStateValueOff];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001419 }
1420}
bellard5b0753e2005-03-01 21:37:28 +00001421
Carwyn Ellise28a9092023-11-10 16:17:29 +00001422- (void)toggleZoomInterpolation:(id) sender
1423{
1424 if (zoom_interpolation == kCGInterpolationNone) {
1425 zoom_interpolation = kCGInterpolationLow;
1426 [sender setState: NSControlStateValueOn];
1427 } else {
1428 zoom_interpolation = kCGInterpolationNone;
1429 [sender setState: NSControlStateValueOff];
1430 }
1431}
1432
Programmingkidb4c6a112015-05-19 09:11:18 +01001433/* Displays the console on the screen */
1434- (void)displayConsole:(id)sender
1435{
1436 console_select([sender tag]);
1437}
John Arbuckle8524f1c2015-06-19 10:53:27 +01001438
1439/* Pause the guest */
1440- (void)pauseQEMU:(id)sender
1441{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001442 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001443 qmp_stop(NULL);
1444 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001445 [sender setEnabled: NO];
1446 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1447 [self displayPause];
1448}
1449
1450/* Resume running the guest operating system */
1451- (void)resumeQEMU:(id) sender
1452{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001453 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001454 qmp_cont(NULL);
1455 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001456 [sender setEnabled: NO];
1457 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1458 [self removePause];
1459}
1460
1461/* Displays the word pause on the screen */
1462- (void)displayPause
1463{
1464 /* Coordinates have to be calculated each time because the window can change its size */
1465 int xCoord, yCoord, width, height;
1466 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1467 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1468 width = [pauseLabel frame].size.width;
1469 height = [pauseLabel frame].size.height;
1470 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1471 [cocoaView addSubview: pauseLabel];
1472}
1473
1474/* Removes the word pause from the screen */
1475- (void)removePause
1476{
1477 [pauseLabel removeFromSuperview];
1478}
1479
John Arbuckle27074612015-06-19 10:53:27 +01001480/* Restarts QEMU */
1481- (void)restartQEMU:(id)sender
1482{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001483 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001484 qmp_system_reset(NULL);
1485 });
John Arbuckle27074612015-06-19 10:53:27 +01001486}
1487
1488/* Powers down QEMU */
1489- (void)powerDownQEMU:(id)sender
1490{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001491 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001492 qmp_system_powerdown(NULL);
1493 });
John Arbuckle27074612015-06-19 10:53:27 +01001494}
1495
John Arbuckle693a3e02015-06-19 10:53:27 +01001496/* Ejects the media.
1497 * Uses sender's tag to figure out the device to eject.
1498 */
1499- (void)ejectDeviceMedia:(id)sender
1500{
1501 NSString * drive;
1502 drive = [sender representedObject];
1503 if(drive == nil) {
1504 NSBeep();
1505 QEMU_Alert(@"Failed to find drive to eject!");
1506 return;
1507 }
1508
Peter Maydell31819e92019-02-25 10:24:27 +00001509 __block Error *err = NULL;
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001510 with_bql(^{
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001511 qmp_eject([drive cStringUsingEncoding: NSASCIIStringEncoding],
1512 NULL, false, false, &err);
Peter Maydell31819e92019-02-25 10:24:27 +00001513 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001514 handleAnyDeviceErrors(err);
1515}
1516
1517/* Displays a dialog box asking the user to select an image file to load.
1518 * Uses sender's represented object value to figure out which drive to use.
1519 */
1520- (void)changeDeviceMedia:(id)sender
1521{
1522 /* Find the drive name */
1523 NSString * drive;
1524 drive = [sender representedObject];
1525 if(drive == nil) {
1526 NSBeep();
1527 QEMU_Alert(@"Could not find drive!");
1528 return;
1529 }
1530
1531 /* Display the file open dialog */
1532 NSOpenPanel * openPanel;
1533 openPanel = [NSOpenPanel openPanel];
1534 [openPanel setCanChooseFiles: YES];
1535 [openPanel setAllowsMultipleSelection: NO];
Peter Maydellb5725382018-05-29 19:15:23 +01001536 if([openPanel runModal] == NSModalResponseOK) {
John Arbuckle693a3e02015-06-19 10:53:27 +01001537 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1538 if(file == nil) {
1539 NSBeep();
1540 QEMU_Alert(@"Failed to convert URL to file path!");
1541 return;
1542 }
1543
Peter Maydell31819e92019-02-25 10:24:27 +00001544 __block Error *err = NULL;
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001545 with_bql(^{
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001546 qmp_blockdev_change_medium([drive cStringUsingEncoding:
Peter Maydell31819e92019-02-25 10:24:27 +00001547 NSASCIIStringEncoding],
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001548 NULL,
Peter Maydell31819e92019-02-25 10:24:27 +00001549 [file cStringUsingEncoding:
1550 NSASCIIStringEncoding],
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001551 "raw",
Denis V. Lunev80dd5af2022-04-13 01:18:46 +03001552 true, false,
Peter Maydell31819e92019-02-25 10:24:27 +00001553 false, 0,
1554 &err);
1555 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001556 handleAnyDeviceErrors(err);
1557 }
1558}
1559
John Arbuckled9bc14f2015-09-25 23:13:59 +01001560/* Verifies if the user really wants to quit */
1561- (BOOL)verifyQuit
1562{
1563 NSAlert *alert = [NSAlert new];
1564 [alert autorelease];
1565 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1566 [alert addButtonWithTitle: @"Cancel"];
1567 [alert addButtonWithTitle: @"Quit"];
1568 if([alert runModal] == NSAlertSecondButtonReturn) {
1569 return YES;
1570 } else {
1571 return NO;
1572 }
1573}
1574
Programmingkid9e8204b2016-08-15 22:11:06 -04001575/* The action method for the About menu item */
1576- (IBAction) do_about_menu_item: (id) sender
1577{
Akihiko Odaki99eb3132022-02-27 13:22:41 +09001578 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1579 char *icon_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1580 NSString *icon_path = [NSString stringWithUTF8String:icon_path_c];
1581 g_free(icon_path_c);
1582 NSImage *icon = [[NSImage alloc] initWithContentsOfFile:icon_path];
1583 NSString *version = @"QEMU emulator version " QEMU_FULL_VERSION;
1584 NSString *copyright = @QEMU_COPYRIGHT;
1585 NSDictionary *options;
1586 if (icon) {
1587 options = @{
1588 NSAboutPanelOptionApplicationIcon : icon,
1589 NSAboutPanelOptionApplicationVersion : version,
1590 @"Copyright" : copyright,
1591 };
1592 [icon release];
1593 } else {
1594 options = @{
1595 NSAboutPanelOptionApplicationVersion : version,
1596 @"Copyright" : copyright,
1597 };
Akihiko Odakia0f973f2021-03-09 21:22:26 +09001598 }
Akihiko Odaki99eb3132022-02-27 13:22:41 +09001599 [NSApp orderFrontStandardAboutPanelWithOptions:options];
1600 [pool release];
Programmingkid9e8204b2016-08-15 22:11:06 -04001601}
1602
John Arbucklee47ec1a2017-06-13 23:17:38 -04001603/* Used by the Speed menu items */
1604- (void)adjustSpeed:(id)sender
1605{
1606 int throttle_pct; /* throttle percentage */
1607 NSMenu *menu;
1608
1609 menu = [sender menu];
1610 if (menu != nil)
1611 {
1612 /* Unselect the currently selected item */
1613 for (NSMenuItem *item in [menu itemArray]) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001614 if (item.state == NSControlStateValueOn) {
1615 [item setState: NSControlStateValueOff];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001616 break;
1617 }
1618 }
1619 }
1620
1621 // check the menu item
Brendan Shanks5e246002019-01-31 23:12:25 -08001622 [sender setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001623
1624 // get the throttle percentage
1625 throttle_pct = [sender tag];
1626
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001627 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001628 cpu_throttle_set(throttle_pct);
1629 });
John Arbucklee47ec1a2017-06-13 23:17:38 -04001630 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1631}
1632
Programmingkidb4c6a112015-05-19 09:11:18 +01001633@end
bellard5b0753e2005-03-01 21:37:28 +00001634
Peter Maydell61a2ed42019-02-25 10:24:32 +00001635@interface QemuApplication : NSApplication
1636@end
1637
1638@implementation QemuApplication
1639- (void)sendEvent:(NSEvent *)event
1640{
1641 COCOA_DEBUG("QemuApplication: sendEvent\n");
Peter Maydell55888402019-02-25 10:24:33 +00001642 if (![cocoaView handleEvent:event]) {
1643 [super sendEvent: event];
1644 }
Peter Maydell61a2ed42019-02-25 10:24:32 +00001645}
1646@end
1647
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001648static void create_initial_menus(void)
1649{
thsc304f7e2008-01-22 23:25:15 +00001650 // Add menus
1651 NSMenu *menu;
1652 NSMenuItem *menuItem;
1653
bellard5b0753e2005-03-01 21:37:28 +00001654 [NSApp setMainMenu:[[NSMenu alloc] init]];
Akihiko Odaki5b6988c2022-02-14 18:13:20 +09001655 [NSApp setServicesMenu:[[NSMenu alloc] initWithTitle:@"Services"]];
bellard5b0753e2005-03-01 21:37:28 +00001656
thsc304f7e2008-01-22 23:25:15 +00001657 // Application menu
1658 menu = [[NSMenu alloc] initWithTitle:@""];
Programmingkid9e8204b2016-08-15 22:11:06 -04001659 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
thsc304f7e2008-01-22 23:25:15 +00001660 [menu addItem:[NSMenuItem separatorItem]]; //Separator
Akihiko Odaki5b6988c2022-02-14 18:13:20 +09001661 menuItem = [menu addItemWithTitle:@"Services" action:nil keyEquivalent:@""];
1662 [menuItem setSubmenu:[NSApp servicesMenu]];
1663 [menu addItem:[NSMenuItem separatorItem]];
thsc304f7e2008-01-22 23:25:15 +00001664 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1665 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001666 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
thsc304f7e2008-01-22 23:25:15 +00001667 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1668 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1669 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1670 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1671 [menuItem setSubmenu:menu];
1672 [[NSApp mainMenu] addItem:menuItem];
1673 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
ths3b46e622007-09-17 08:09:54 +00001674
John Arbuckle8524f1c2015-06-19 10:53:27 +01001675 // Machine menu
1676 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1677 [menu setAutoenablesItems: NO];
1678 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1679 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1680 [menu addItem: menuItem];
1681 [menuItem setEnabled: NO];
John Arbuckle27074612015-06-19 10:53:27 +01001682 [menu addItem: [NSMenuItem separatorItem]];
1683 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1684 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
John Arbuckle8524f1c2015-06-19 10:53:27 +01001685 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1686 [menuItem setSubmenu:menu];
1687 [[NSApp mainMenu] addItem:menuItem];
1688
thsc304f7e2008-01-22 23:25:15 +00001689 // View menu
1690 menu = [[NSMenu alloc] initWithTitle:@"View"];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001691 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
Carwyn Ellis5ec08982023-10-27 16:49:20 +01001692 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease];
1693 [menuItem setState: stretch_video ? NSControlStateValueOn : NSControlStateValueOff];
1694 [menu addItem: menuItem];
Carwyn Ellise28a9092023-11-10 16:17:29 +00001695 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Zoom Interpolation" action:@selector(toggleZoomInterpolation:) keyEquivalent:@""] autorelease];
1696 [menuItem setState: zoom_interpolation == kCGInterpolationLow ? NSControlStateValueOn : NSControlStateValueOff];
1697 [menu addItem: menuItem];
thsc304f7e2008-01-22 23:25:15 +00001698 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1699 [menuItem setSubmenu:menu];
1700 [[NSApp mainMenu] addItem:menuItem];
1701
John Arbucklee47ec1a2017-06-13 23:17:38 -04001702 // Speed menu
1703 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1704
1705 // Add the rest of the Speed menu items
1706 int p, percentage, throttle_pct;
1707 for (p = 10; p >= 0; p--)
1708 {
1709 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1710
1711 menuItem = [[[NSMenuItem alloc]
1712 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1713
1714 if (percentage == 100) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001715 [menuItem setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001716 }
1717
1718 /* Calculate the throttle percentage */
1719 throttle_pct = -1 * percentage + 100;
1720
1721 [menuItem setTag: throttle_pct];
1722 [menu addItem: menuItem];
1723 }
1724 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1725 [menuItem setSubmenu:menu];
1726 [[NSApp mainMenu] addItem:menuItem];
1727
thsc304f7e2008-01-22 23:25:15 +00001728 // Window menu
1729 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1730 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1731 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1732 [menuItem setSubmenu:menu];
1733 [[NSApp mainMenu] addItem:menuItem];
1734 [NSApp setWindowsMenu:menu];
1735
1736 // Help menu
1737 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1738 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
thsc304f7e2008-01-22 23:25:15 +00001739 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1740 [menuItem setSubmenu:menu];
1741 [[NSApp mainMenu] addItem:menuItem];
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001742}
1743
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001744/* Returns a name for a given console */
1745static NSString * getConsoleName(QemuConsole * console)
1746{
Akihiko Odakica511602022-02-15 09:03:05 +01001747 g_autofree char *label = qemu_console_get_label(console);
1748
1749 return [NSString stringWithUTF8String:label];
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001750}
1751
1752/* Add an entry to the View menu for each console */
1753static void add_console_menu_entries(void)
1754{
1755 NSMenu *menu;
1756 NSMenuItem *menuItem;
1757 int index = 0;
1758
1759 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1760
1761 [menu addItem:[NSMenuItem separatorItem]];
1762
1763 while (qemu_console_lookup_by_index(index) != NULL) {
1764 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1765 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1766 [menuItem setTag: index];
1767 [menu addItem: menuItem];
1768 index++;
1769 }
1770}
1771
1772/* Make menu items for all removable devices.
1773 * Each device is given an 'Eject' and 'Change' menu item.
1774 */
1775static void addRemovableDevicesMenuItems(void)
1776{
1777 NSMenu *menu;
1778 NSMenuItem *menuItem;
1779 BlockInfoList *currentDevice, *pointerToFree;
1780 NSString *deviceName;
1781
1782 currentDevice = qmp_query_block(NULL);
1783 pointerToFree = currentDevice;
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001784
1785 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1786
1787 // Add a separator between related groups of menu items
1788 [menu addItem:[NSMenuItem separatorItem]];
1789
1790 // Set the attributes to the "Removable Media" menu item
1791 NSString *titleString = @"Removable Media";
1792 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1793 NSColor *newColor = [NSColor blackColor];
1794 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1795 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1796 traits:NSBoldFontMask|NSItalicFontMask
1797 weight:0
1798 size:14];
1799 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1800 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1801 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1802
1803 // Add the "Removable Media" menu item
1804 menuItem = [NSMenuItem new];
1805 [menuItem setAttributedTitle: attString];
1806 [menuItem setEnabled: NO];
1807 [menu addItem: menuItem];
1808
1809 /* Loop through all the block devices in the emulator */
1810 while (currentDevice) {
1811 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1812
1813 if(currentDevice->value->removable) {
1814 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1815 action: @selector(changeDeviceMedia:)
1816 keyEquivalent: @""];
1817 [menu addItem: menuItem];
1818 [menuItem setRepresentedObject: deviceName];
1819 [menuItem autorelease];
1820
1821 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1822 action: @selector(ejectDeviceMedia:)
1823 keyEquivalent: @""];
1824 [menu addItem: menuItem];
1825 [menuItem setRepresentedObject: deviceName];
1826 [menuItem autorelease];
1827 }
1828 currentDevice = currentDevice->next;
1829 }
1830 qapi_free_BlockInfoList(pointerToFree);
1831}
1832
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001833@interface QemuCocoaPasteboardTypeOwner : NSObject<NSPasteboardTypeOwner>
1834@end
1835
1836@implementation QemuCocoaPasteboardTypeOwner
1837
1838- (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)type
1839{
1840 if (type != NSPasteboardTypeString) {
1841 return;
1842 }
1843
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001844 with_bql(^{
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001845 QemuClipboardInfo *info = qemu_clipboard_info_ref(cbinfo);
1846 qemu_event_reset(&cbevent);
1847 qemu_clipboard_request(info, QEMU_CLIPBOARD_TYPE_TEXT);
1848
1849 while (info == cbinfo &&
1850 info->types[QEMU_CLIPBOARD_TYPE_TEXT].available &&
1851 info->types[QEMU_CLIPBOARD_TYPE_TEXT].data == NULL) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001852 bql_unlock();
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001853 qemu_event_wait(&cbevent);
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001854 bql_lock();
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001855 }
1856
1857 if (info == cbinfo) {
1858 NSData *data = [[NSData alloc] initWithBytes:info->types[QEMU_CLIPBOARD_TYPE_TEXT].data
1859 length:info->types[QEMU_CLIPBOARD_TYPE_TEXT].size];
1860 [sender setData:data forType:NSPasteboardTypeString];
1861 [data release];
1862 }
1863
1864 qemu_clipboard_info_unref(info);
1865 });
1866}
1867
1868@end
1869
1870static QemuCocoaPasteboardTypeOwner *cbowner;
1871
1872static void cocoa_clipboard_notify(Notifier *notifier, void *data);
1873static void cocoa_clipboard_request(QemuClipboardInfo *info,
1874 QemuClipboardType type);
1875
1876static QemuClipboardPeer cbpeer = {
1877 .name = "cocoa",
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001878 .notifier = { .notify = cocoa_clipboard_notify },
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001879 .request = cocoa_clipboard_request
1880};
1881
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001882static void cocoa_clipboard_update_info(QemuClipboardInfo *info)
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001883{
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001884 if (info->owner == &cbpeer || info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
1885 return;
1886 }
1887
1888 if (info != cbinfo) {
1889 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1890 qemu_clipboard_info_unref(cbinfo);
1891 cbinfo = qemu_clipboard_info_ref(info);
1892 cbchangecount = [[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:cbowner];
1893 [pool release];
1894 }
1895
1896 qemu_event_set(&cbevent);
1897}
1898
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001899static void cocoa_clipboard_notify(Notifier *notifier, void *data)
1900{
1901 QemuClipboardNotify *notify = data;
1902
1903 switch (notify->type) {
1904 case QEMU_CLIPBOARD_UPDATE_INFO:
1905 cocoa_clipboard_update_info(notify->info);
1906 return;
Marc-André Lureau505dbf92021-07-19 19:49:56 +04001907 case QEMU_CLIPBOARD_RESET_SERIAL:
1908 /* ignore */
1909 return;
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001910 }
1911}
1912
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001913static void cocoa_clipboard_request(QemuClipboardInfo *info,
1914 QemuClipboardType type)
1915{
Akihiko Odaki8c0d8022022-06-15 06:21:31 +09001916 NSAutoreleasePool *pool;
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001917 NSData *text;
1918
1919 switch (type) {
1920 case QEMU_CLIPBOARD_TYPE_TEXT:
Akihiko Odaki8c0d8022022-06-15 06:21:31 +09001921 pool = [[NSAutoreleasePool alloc] init];
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001922 text = [[NSPasteboard generalPasteboard] dataForType:NSPasteboardTypeString];
1923 if (text) {
1924 qemu_clipboard_set_data(&cbpeer, info, type,
1925 [text length], [text bytes], true);
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001926 }
Akihiko Odaki8c0d8022022-06-15 06:21:31 +09001927 [pool release];
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001928 break;
1929 default:
1930 break;
1931 }
1932}
1933
Peter Maydell55888402019-02-25 10:24:33 +00001934/*
1935 * The startup process for the OSX/Cocoa UI is complicated, because
1936 * OSX insists that the UI runs on the initial main thread, and so we
Akihiko Odakibab6a302022-08-19 22:27:54 +09001937 * need to start a second thread which runs the qemu_default_main():
Peter Maydell55888402019-02-25 10:24:33 +00001938 * in main():
Akihiko Odakibab6a302022-08-19 22:27:54 +09001939 * in cocoa_display_init():
1940 * assign cocoa_main to qemu_main
1941 * create application, menus, etc
1942 * in cocoa_main():
1943 * create qemu-main thread
1944 * enter OSX run loop
Peter Maydell55888402019-02-25 10:24:33 +00001945 */
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001946
Peter Maydell55888402019-02-25 10:24:33 +00001947static void *call_qemu_main(void *opaque)
1948{
1949 int status;
1950
Akihiko Odakibab6a302022-08-19 22:27:54 +09001951 COCOA_DEBUG("Second thread: calling qemu_default_main()\n");
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001952 bql_lock();
Akihiko Odakibab6a302022-08-19 22:27:54 +09001953 status = qemu_default_main();
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001954 bql_unlock();
Akihiko Odakibab6a302022-08-19 22:27:54 +09001955 COCOA_DEBUG("Second thread: qemu_default_main() returned, exiting\n");
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001956 [cbowner release];
Peter Maydell55888402019-02-25 10:24:33 +00001957 exit(status);
1958}
1959
Philippe Mathieu-Daudéf9750332023-04-23 18:55:28 +02001960static int cocoa_main(void)
Akihiko Odakibab6a302022-08-19 22:27:54 +09001961{
Peter Maydell55888402019-02-25 10:24:33 +00001962 QemuThread thread;
1963
Akihiko Odakibab6a302022-08-19 22:27:54 +09001964 COCOA_DEBUG("Entered %s()\n", __func__);
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001965
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001966 bql_unlock();
Peter Maydell55888402019-02-25 10:24:33 +00001967 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1968 NULL, QEMU_THREAD_DETACHED);
1969
thsc304f7e2008-01-22 23:25:15 +00001970 // Start the main event loop
Peter Maydell55888402019-02-25 10:24:33 +00001971 COCOA_DEBUG("Main thread: entering OSX run loop\n");
bellard5b0753e2005-03-01 21:37:28 +00001972 [NSApp run];
Akihiko Odakibab6a302022-08-19 22:27:54 +09001973 COCOA_DEBUG("Main thread: left OSX run loop, which should never happen\n");
ths3b46e622007-09-17 08:09:54 +00001974
Akihiko Odakibab6a302022-08-19 22:27:54 +09001975 abort();
bellard5b0753e2005-03-01 21:37:28 +00001976}
thsc304f7e2008-01-22 23:25:15 +00001977
1978
1979
1980#pragma mark qemu
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001981static void cocoa_update(DisplayChangeListener *dcl,
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001982 int x, int y, int w, int h)
thsc304f7e2008-01-22 23:25:15 +00001983{
1984 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1985
Peter Maydell55888402019-02-25 10:24:33 +00001986 dispatch_async(dispatch_get_main_queue(), ^{
1987 NSRect rect;
1988 if ([cocoaView cdx] == 1.0) {
1989 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1990 } else {
1991 rect = NSMakeRect(
1992 x * [cocoaView cdx],
1993 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1994 w * [cocoaView cdx],
1995 h * [cocoaView cdy]);
1996 }
1997 [cocoaView setNeedsDisplayInRect:rect];
1998 });
thsc304f7e2008-01-22 23:25:15 +00001999}
2000
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01002001static void cocoa_switch(DisplayChangeListener *dcl,
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01002002 DisplaySurface *surface)
thsc304f7e2008-01-22 23:25:15 +00002003{
Peter Maydell55888402019-02-25 10:24:33 +00002004 pixman_image_t *image = surface->image;
thsc304f7e2008-01-22 23:25:15 +00002005
Peter Maydell6e657e62013-04-22 10:29:46 +00002006 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
Peter Maydell55888402019-02-25 10:24:33 +00002007
2008 // The DisplaySurface will be freed as soon as this callback returns.
2009 // We take a reference to the underlying pixman image here so it does
2010 // not disappear from under our feet; the switchSurface method will
2011 // deref the old image when it is done with it.
2012 pixman_image_ref(image);
2013
2014 dispatch_async(dispatch_get_main_queue(), ^{
Peter Maydell8d65dee2022-02-24 10:13:29 +00002015 [cocoaView updateUIInfo];
Peter Maydell55888402019-02-25 10:24:33 +00002016 [cocoaView switchSurface:image];
2017 });
thsc304f7e2008-01-22 23:25:15 +00002018}
2019
Gerd Hoffmannbc2ed972013-03-01 13:03:04 +01002020static void cocoa_refresh(DisplayChangeListener *dcl)
thsc304f7e2008-01-22 23:25:15 +00002021{
Peter Maydell6e657e62013-04-22 10:29:46 +00002022 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2023
thsc304f7e2008-01-22 23:25:15 +00002024 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
John Arbuckle468a8952015-10-13 21:51:18 +01002025 graphic_hw_update(NULL);
thsc304f7e2008-01-22 23:25:15 +00002026
Akihiko Odaki0337e412023-09-21 17:29:34 +09002027 if (qemu_input_is_absolute(dcl->con)) {
Peter Maydell55888402019-02-25 10:24:33 +00002028 dispatch_async(dispatch_get_main_queue(), ^{
2029 if (![cocoaView isAbsoluteEnabled]) {
2030 if ([cocoaView isMouseGrabbed]) {
2031 [cocoaView ungrabMouse];
2032 }
thsc304f7e2008-01-22 23:25:15 +00002033 }
Peter Maydell55888402019-02-25 10:24:33 +00002034 [cocoaView setAbsoluteEnabled:YES];
2035 });
thsc304f7e2008-01-22 23:25:15 +00002036 }
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09002037
2038 if (cbchangecount != [[NSPasteboard generalPasteboard] changeCount]) {
2039 qemu_clipboard_info_unref(cbinfo);
2040 cbinfo = qemu_clipboard_info_new(&cbpeer, QEMU_CLIPBOARD_SELECTION_CLIPBOARD);
2041 if ([[NSPasteboard generalPasteboard] availableTypeFromArray:@[NSPasteboardTypeString]]) {
2042 cbinfo->types[QEMU_CLIPBOARD_TYPE_TEXT].available = true;
2043 }
2044 qemu_clipboard_update(cbinfo);
2045 cbchangecount = [[NSPasteboard generalPasteboard] changeCount];
2046 qemu_event_set(&cbevent);
2047 }
2048
Peter Maydell6e657e62013-04-22 10:29:46 +00002049 [pool release];
thsc304f7e2008-01-22 23:25:15 +00002050}
2051
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01002052static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
thsc304f7e2008-01-22 23:25:15 +00002053{
Akihiko Odakibab6a302022-08-19 22:27:54 +09002054 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2055
thsc304f7e2008-01-22 23:25:15 +00002056 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
2057
Akihiko Odakibab6a302022-08-19 22:27:54 +09002058 qemu_main = cocoa_main;
Peter Maydell55888402019-02-25 10:24:33 +00002059
Akihiko Odakibab6a302022-08-19 22:27:54 +09002060 // Pull this console process up to being a fully-fledged graphical
2061 // app with a menubar and Dock icon
2062 ProcessSerialNumber psn = { 0, kCurrentProcess };
2063 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
2064
2065 [QemuApplication sharedApplication];
2066
Akihiko Odakibab6a302022-08-19 22:27:54 +09002067 // Create an Application controller
2068 QemuCocoaAppController *controller = [[QemuCocoaAppController alloc] init];
2069 [NSApp setDelegate:controller];
2070
Programmingkid43227af2015-05-19 09:11:17 +01002071 /* if fullscreen mode is to be used */
Gerd Hoffmann767f9bf2018-02-02 12:10:19 +01002072 if (opts->has_full_screen && opts->full_screen) {
Akihiko Odakibab6a302022-08-19 22:27:54 +09002073 [NSApp activateIgnoringOtherApps: YES];
2074 [controller toggleFullScreen: nil];
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +09002075 }
2076 if (opts->u.cocoa.has_full_grab && opts->u.cocoa.full_grab) {
Akihiko Odakibab6a302022-08-19 22:27:54 +09002077 [controller setFullGrab: nil];
Programmingkid43227af2015-05-19 09:11:17 +01002078 }
Carwyn Ellis69221df2022-01-02 17:41:53 +00002079
Gerd Hoffmann3487da62020-02-06 12:27:50 +01002080 if (opts->has_show_cursor && opts->show_cursor) {
2081 cursor_hide = 0;
2082 }
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +09002083 if (opts->u.cocoa.has_swap_opt_cmd) {
2084 swap_opt_cmd = opts->u.cocoa.swap_opt_cmd;
2085 }
Programmingkid43227af2015-05-19 09:11:17 +01002086
Carwyn Ellis48941a52022-01-02 17:41:52 +00002087 if (opts->u.cocoa.has_left_command_key && !opts->u.cocoa.left_command_key) {
2088 left_command_key_enabled = 0;
2089 }
2090
Carwyn Ellis5ec08982023-10-27 16:49:20 +01002091 if (opts->u.cocoa.has_zoom_to_fit && opts->u.cocoa.zoom_to_fit) {
2092 stretch_video = true;
2093 }
2094
Carwyn Ellise28a9092023-11-10 16:17:29 +00002095 if (opts->u.cocoa.has_zoom_interpolation && opts->u.cocoa.zoom_interpolation) {
2096 zoom_interpolation = kCGInterpolationLow;
2097 }
2098
Carwyn Ellis5ec08982023-10-27 16:49:20 +01002099 create_initial_menus();
2100 /*
2101 * Create the menu entries which depend on QEMU state (for consoles
2102 * and removable devices). These make calls back into QEMU functions,
2103 * which is OK because at this point we know that the second thread
Stefan Hajnoczia4a411f2024-01-02 10:35:28 -05002104 * holds the BQL and is synchronously waiting for us to
Carwyn Ellis5ec08982023-10-27 16:49:20 +01002105 * finish.
2106 */
2107 add_console_menu_entries();
2108 addRemovableDevicesMenuItems();
2109
aliguori9794f742009-03-04 19:25:22 +00002110 // register vga output callbacks
Akihiko Odakicc7859c2021-02-19 17:44:19 +09002111 register_displaychangelistener(&dcl);
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09002112
2113 qemu_event_init(&cbevent, false);
2114 cbowner = [[QemuCocoaPasteboardTypeOwner alloc] init];
2115 qemu_clipboard_peer_register(&cbpeer);
Akihiko Odakibab6a302022-08-19 22:27:54 +09002116
2117 [pool release];
thsc304f7e2008-01-22 23:25:15 +00002118}
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01002119
2120static QemuDisplay qemu_display_cocoa = {
2121 .type = DISPLAY_TYPE_COCOA,
2122 .init = cocoa_display_init,
2123};
2124
2125static void register_cocoa(void)
2126{
2127 qemu_display_register(&qemu_display_cocoa);
2128}
2129
2130type_init(register_cocoa);