blob: a2e52ceabcdb0a0934740a84aa34e1840d629212 [file] [log] [blame]
bellard5b0753e2005-03-01 21:37:28 +00001/*
thsc304f7e2008-01-22 23:25:15 +00002 * QEMU Cocoa CG display driver
ths5fafdf22007-09-16 21:08:06 +00003 *
thsc304f7e2008-01-22 23:25:15 +00004 * Copyright (c) 2008 Mike Kronenberg
ths5fafdf22007-09-16 21:08:06 +00005 *
bellard5b0753e2005-03-01 21:37:28 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
bellardda4dbf72005-03-02 22:22:43 +000024
Peter Maydelle4a096b2016-01-29 16:23:34 +000025#include "qemu/osdep.h"
26
bellard5b0753e2005-03-01 21:37:28 +000027#import <Cocoa/Cocoa.h>
Andreas Färber3bbbee12011-05-29 19:42:51 +020028#include <crt_externs.h>
bellard5b0753e2005-03-01 21:37:28 +000029
Marc-André Lureau49f95222022-04-20 17:25:49 +040030#include "qemu/help-texts.h"
Marc-André Lureau88c39c82022-04-20 17:25:47 +040031#include "qemu-main.h"
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +090032#include "ui/clipboard.h"
Paolo Bonzini28ecbae2012-11-28 12:06:30 +010033#include "ui/console.h"
Gerd Hoffmann21bae112013-12-04 14:08:04 +010034#include "ui/input.h"
Akihiko Odaki6d73bb62021-03-10 23:46:02 +090035#include "ui/kbd-state.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010036#include "sysemu/sysemu.h"
Markus Armbruster54d31232019-08-12 07:23:59 +020037#include "sysemu/runstate.h"
Akihiko Odaki2910abd2022-05-29 17:25:08 +090038#include "sysemu/runstate-action.h"
Claudio Fontanab0c3cf92020-06-29 11:35:03 +020039#include "sysemu/cpu-throttle.h"
Markus Armbrustere688df62018-02-01 12:18:31 +010040#include "qapi/error.h"
Markus Armbruster16bf5232018-12-20 09:45:59 +010041#include "qapi/qapi-commands-block.h"
Philippe Mathieu-Daudé90f8c0f2020-10-12 14:15:33 +020042#include "qapi/qapi-commands-machine.h"
Markus Armbruster16bf5232018-12-20 09:45:59 +010043#include "qapi/qapi-commands-misc.h"
John Arbuckle693a3e02015-06-19 10:53:27 +010044#include "sysemu/blockdev.h"
Programmingkid9e8204b2016-08-15 22:11:06 -040045#include "qemu-version.h"
Akihiko Odakie31746e2021-03-09 21:22:25 +090046#include "qemu/cutils.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020047#include "qemu/main-loop.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020048#include "qemu/module.h"
Richard Hendersoncc37d982023-03-15 17:43:13 +000049#include "qemu/error-report.h"
John Arbuckleaaac7142016-03-23 14:26:18 +000050#include <Carbon/Carbon.h>
Markus Armbruster2e5b09f2019-07-09 17:20:52 +020051#include "hw/core/cpu.h"
bellardda4dbf72005-03-02 22:22:43 +000052
Brendan Shanks5e246002019-01-31 23:12:25 -080053#ifndef MAC_OS_X_VERSION_10_13
54#define MAC_OS_X_VERSION_10_13 101300
55#endif
Andreas Färber44e4c0b2009-12-13 00:45:40 +010056
David Parsonsf5af8022024-02-24 14:06:20 +000057#ifndef MAC_OS_VERSION_14_0
58#define MAC_OS_VERSION_14_0 140000
59#endif
60
Brendan Shanks5e246002019-01-31 23:12:25 -080061/* 10.14 deprecates NSOnState and NSOffState in favor of
62 * NSControlStateValueOn/Off, which were introduced in 10.13.
63 * Define for older versions
64 */
65#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
66#define NSControlStateValueOn NSOnState
67#define NSControlStateValueOff NSOffState
68#endif
bellard5b0753e2005-03-01 21:37:28 +000069
thsc304f7e2008-01-22 23:25:15 +000070//#define DEBUG
71
72#ifdef DEBUG
73#define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
74#else
75#define COCOA_DEBUG(...) ((void) 0)
76#endif
77
78#define cgrect(nsrect) (*(CGRect *)&(nsrect))
thsc304f7e2008-01-22 23:25:15 +000079
Christian Schoenebeck23bdd0d2022-12-27 17:15:31 +010080#define UC_CTRL_KEY "\xe2\x8c\x83"
81#define UC_ALT_KEY "\xe2\x8c\xa5"
82
thsc304f7e2008-01-22 23:25:15 +000083typedef struct {
84 int width;
85 int height;
thsc304f7e2008-01-22 23:25:15 +000086} QEMUScreen;
87
Akihiko Odakicc7859c2021-02-19 17:44:19 +090088static void cocoa_update(DisplayChangeListener *dcl,
89 int x, int y, int w, int h);
90
91static void cocoa_switch(DisplayChangeListener *dcl,
92 DisplaySurface *surface);
93
94static void cocoa_refresh(DisplayChangeListener *dcl);
95
Akihiko Odaki99eb3132022-02-27 13:22:41 +090096static NSWindow *normalWindow;
Akihiko Odakicc7859c2021-02-19 17:44:19 +090097static const DisplayChangeListenerOps dcl_ops = {
98 .dpy_name = "cocoa",
99 .dpy_gfx_update = cocoa_update,
100 .dpy_gfx_switch = cocoa_switch,
101 .dpy_refresh = cocoa_refresh,
102};
103static DisplayChangeListener dcl = {
104 .ops = &dcl_ops,
105};
Gerd Hoffmann3487da62020-02-06 12:27:50 +0100106static int cursor_hide = 1;
Carwyn Ellis48941a52022-01-02 17:41:52 +0000107static int left_command_key_enabled = 1;
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900108static bool swap_opt_cmd;
bellard5b0753e2005-03-01 21:37:28 +0000109
Akihiko Odakicb823402021-02-25 17:42:02 +0900110static bool stretch_video;
Carwyn Ellise28a9092023-11-10 16:17:29 +0000111static CGInterpolationQuality zoom_interpolation = kCGInterpolationNone;
Akihiko Odakicb823402021-02-25 17:42:02 +0900112static NSTextField *pauseLabel;
bellard5b0753e2005-03-01 21:37:28 +0000113
Hikaru Nishidadff742a2019-10-15 10:07:34 +0900114static bool allow_events;
Peter Maydell55888402019-02-25 10:24:33 +0000115
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +0900116static NSInteger cbchangecount = -1;
117static QemuClipboardInfo *cbinfo;
118static QemuEvent cbevent;
119
Stefan Hajnoczia4a411f2024-01-02 10:35:28 -0500120// Utility functions to run specified code block with the BQL held
Peter Maydell31819e92019-02-25 10:24:27 +0000121typedef void (^CodeBlock)(void);
Peter Maydell60105d72019-02-25 10:24:31 +0000122typedef bool (^BoolCodeBlock)(void);
Peter Maydell31819e92019-02-25 10:24:27 +0000123
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500124static void with_bql(CodeBlock block)
Peter Maydell31819e92019-02-25 10:24:27 +0000125{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500126 bool locked = bql_locked();
Peter Maydell31819e92019-02-25 10:24:27 +0000127 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500128 bql_lock();
Peter Maydell31819e92019-02-25 10:24:27 +0000129 }
130 block();
131 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500132 bql_unlock();
Peter Maydell31819e92019-02-25 10:24:27 +0000133 }
134}
135
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500136static bool bool_with_bql(BoolCodeBlock block)
Peter Maydell60105d72019-02-25 10:24:31 +0000137{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500138 bool locked = bql_locked();
Peter Maydell60105d72019-02-25 10:24:31 +0000139 bool val;
140
141 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500142 bql_lock();
Peter Maydell60105d72019-02-25 10:24:31 +0000143 }
144 val = block();
145 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500146 bql_unlock();
Peter Maydell60105d72019-02-25 10:24:31 +0000147 }
148 return val;
149}
150
John Arbuckleaaac7142016-03-23 14:26:18 +0000151// Mac to QKeyCode conversion
Akihiko Odakicb823402021-02-25 17:42:02 +0900152static const int mac_to_qkeycode_map[] = {
John Arbuckleaaac7142016-03-23 14:26:18 +0000153 [kVK_ANSI_A] = Q_KEY_CODE_A,
154 [kVK_ANSI_B] = Q_KEY_CODE_B,
155 [kVK_ANSI_C] = Q_KEY_CODE_C,
156 [kVK_ANSI_D] = Q_KEY_CODE_D,
157 [kVK_ANSI_E] = Q_KEY_CODE_E,
158 [kVK_ANSI_F] = Q_KEY_CODE_F,
159 [kVK_ANSI_G] = Q_KEY_CODE_G,
160 [kVK_ANSI_H] = Q_KEY_CODE_H,
161 [kVK_ANSI_I] = Q_KEY_CODE_I,
162 [kVK_ANSI_J] = Q_KEY_CODE_J,
163 [kVK_ANSI_K] = Q_KEY_CODE_K,
164 [kVK_ANSI_L] = Q_KEY_CODE_L,
165 [kVK_ANSI_M] = Q_KEY_CODE_M,
166 [kVK_ANSI_N] = Q_KEY_CODE_N,
167 [kVK_ANSI_O] = Q_KEY_CODE_O,
168 [kVK_ANSI_P] = Q_KEY_CODE_P,
169 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
170 [kVK_ANSI_R] = Q_KEY_CODE_R,
171 [kVK_ANSI_S] = Q_KEY_CODE_S,
172 [kVK_ANSI_T] = Q_KEY_CODE_T,
173 [kVK_ANSI_U] = Q_KEY_CODE_U,
174 [kVK_ANSI_V] = Q_KEY_CODE_V,
175 [kVK_ANSI_W] = Q_KEY_CODE_W,
176 [kVK_ANSI_X] = Q_KEY_CODE_X,
177 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
178 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
ths3b46e622007-09-17 08:09:54 +0000179
John Arbuckleaaac7142016-03-23 14:26:18 +0000180 [kVK_ANSI_0] = Q_KEY_CODE_0,
181 [kVK_ANSI_1] = Q_KEY_CODE_1,
182 [kVK_ANSI_2] = Q_KEY_CODE_2,
183 [kVK_ANSI_3] = Q_KEY_CODE_3,
184 [kVK_ANSI_4] = Q_KEY_CODE_4,
185 [kVK_ANSI_5] = Q_KEY_CODE_5,
186 [kVK_ANSI_6] = Q_KEY_CODE_6,
187 [kVK_ANSI_7] = Q_KEY_CODE_7,
188 [kVK_ANSI_8] = Q_KEY_CODE_8,
189 [kVK_ANSI_9] = Q_KEY_CODE_9,
190
191 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
192 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
193 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
194 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
195 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
196 [kVK_Tab] = Q_KEY_CODE_TAB,
197 [kVK_Return] = Q_KEY_CODE_RET,
198 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
199 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
200 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
201 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
202 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
203 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
204 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
205 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
John Arbuckleaaac7142016-03-23 14:26:18 +0000206 [kVK_Space] = Q_KEY_CODE_SPC,
207
208 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
209 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
210 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
211 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
212 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
213 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
214 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
215 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
216 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
217 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
218 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
219 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
220 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
221 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
222 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
223 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
224 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
225 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
226
227 [kVK_UpArrow] = Q_KEY_CODE_UP,
228 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
229 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
230 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
231
232 [kVK_Help] = Q_KEY_CODE_INSERT,
233 [kVK_Home] = Q_KEY_CODE_HOME,
234 [kVK_PageUp] = Q_KEY_CODE_PGUP,
235 [kVK_PageDown] = Q_KEY_CODE_PGDN,
236 [kVK_End] = Q_KEY_CODE_END,
237 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
238
239 [kVK_Escape] = Q_KEY_CODE_ESC,
240
241 /* The Power key can't be used directly because the operating system uses
242 * it. This key can be emulated by using it in place of another key such as
243 * F1. Don't forget to disable the real key binding.
244 */
245 /* [kVK_F1] = Q_KEY_CODE_POWER, */
246
247 [kVK_F1] = Q_KEY_CODE_F1,
248 [kVK_F2] = Q_KEY_CODE_F2,
249 [kVK_F3] = Q_KEY_CODE_F3,
250 [kVK_F4] = Q_KEY_CODE_F4,
251 [kVK_F5] = Q_KEY_CODE_F5,
252 [kVK_F6] = Q_KEY_CODE_F6,
253 [kVK_F7] = Q_KEY_CODE_F7,
254 [kVK_F8] = Q_KEY_CODE_F8,
255 [kVK_F9] = Q_KEY_CODE_F9,
256 [kVK_F10] = Q_KEY_CODE_F10,
257 [kVK_F11] = Q_KEY_CODE_F11,
258 [kVK_F12] = Q_KEY_CODE_F12,
259 [kVK_F13] = Q_KEY_CODE_PRINT,
260 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
261 [kVK_F15] = Q_KEY_CODE_PAUSE,
262
Akihiko Odaki708b7252021-02-12 09:04:04 +0900263 // JIS keyboards only
264 [kVK_JIS_Yen] = Q_KEY_CODE_YEN,
265 [kVK_JIS_Underscore] = Q_KEY_CODE_RO,
266 [kVK_JIS_KeypadComma] = Q_KEY_CODE_KP_COMMA,
267 [kVK_JIS_Eisu] = Q_KEY_CODE_MUHENKAN,
268 [kVK_JIS_Kana] = Q_KEY_CODE_HENKAN,
269
John Arbuckleaaac7142016-03-23 14:26:18 +0000270 /*
271 * The eject and volume keys can't be used here because they are handled at
272 * a lower level than what an Application can see.
273 */
bellard5b0753e2005-03-01 21:37:28 +0000274};
275
Andreas Färber77047bb2009-12-13 00:55:53 +0100276static int cocoa_keycode_to_qemu(int keycode)
bellard5b0753e2005-03-01 21:37:28 +0000277{
John Arbuckleaaac7142016-03-23 14:26:18 +0000278 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
Akihiko Odaki43137392021-02-23 22:11:06 +0900279 error_report("(cocoa) warning unknown keycode 0x%x", keycode);
bellard5b0753e2005-03-01 21:37:28 +0000280 return 0;
281 }
John Arbuckleaaac7142016-03-23 14:26:18 +0000282 return mac_to_qkeycode_map[keycode];
bellard5b0753e2005-03-01 21:37:28 +0000283}
284
John Arbuckle693a3e02015-06-19 10:53:27 +0100285/* Displays an alert dialog box with the specified message */
286static void QEMU_Alert(NSString *message)
287{
288 NSAlert *alert;
289 alert = [NSAlert new];
290 [alert setMessageText: message];
291 [alert runModal];
292}
thsc304f7e2008-01-22 23:25:15 +0000293
John Arbuckle693a3e02015-06-19 10:53:27 +0100294/* Handles any errors that happen with a device transaction */
295static void handleAnyDeviceErrors(Error * err)
296{
297 if (err) {
298 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
299 encoding: NSASCIIStringEncoding]);
300 error_free(err);
301 }
302}
thsc304f7e2008-01-22 23:25:15 +0000303
bellard5b0753e2005-03-01 21:37:28 +0000304/*
305 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +0000306 QemuCocoaView
bellard5b0753e2005-03-01 21:37:28 +0000307 ------------------------------------------------------
308*/
thsc304f7e2008-01-22 23:25:15 +0000309@interface QemuCocoaView : NSView
bellard5b0753e2005-03-01 21:37:28 +0000310{
thsc304f7e2008-01-22 23:25:15 +0000311 QEMUScreen screen;
312 NSWindow *fullScreenWindow;
313 float cx,cy,cw,ch,cdx,cdy;
Peter Maydell55888402019-02-25 10:24:33 +0000314 pixman_image_t *pixman_image;
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900315 QKbdState *kbd;
Peter Maydell49b9bd42013-12-08 22:59:03 +0000316 BOOL isMouseGrabbed;
thsc304f7e2008-01-22 23:25:15 +0000317 BOOL isFullscreen;
318 BOOL isAbsoluteEnabled;
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900319 CFMachPortRef eventsTap;
thsc304f7e2008-01-22 23:25:15 +0000320}
Peter Maydell72a3e312019-02-25 10:24:28 +0000321- (void) switchSurface:(pixman_image_t *)image;
thsc304f7e2008-01-22 23:25:15 +0000322- (void) grabMouse;
323- (void) ungrabMouse;
324- (void) toggleFullScreen:(id)sender;
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900325- (void) setFullGrab:(id)sender;
John Arbuckle9c3a4182017-11-07 10:14:14 +0000326- (void) handleMonitorInput:(NSEvent *)event;
Peter Maydell60105d72019-02-25 10:24:31 +0000327- (bool) handleEvent:(NSEvent *)event;
328- (bool) handleEventLocked:(NSEvent *)event;
thsc304f7e2008-01-22 23:25:15 +0000329- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
Peter Maydellf61c3872014-06-23 10:35:24 +0100330/* The state surrounding mouse grabbing is potentially confusing.
331 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
332 * pointing device an absolute-position one?"], but is only updated on
333 * next refresh.
334 * isMouseGrabbed tracks whether GUI events are directed to the guest;
335 * it controls whether special keys like Cmd get sent to the guest,
336 * and whether we capture the mouse when in non-absolute mode.
Peter Maydellf61c3872014-06-23 10:35:24 +0100337 */
Peter Maydell49b9bd42013-12-08 22:59:03 +0000338- (BOOL) isMouseGrabbed;
thsc304f7e2008-01-22 23:25:15 +0000339- (BOOL) isAbsoluteEnabled;
340- (float) cdx;
341- (float) cdy;
342- (QEMUScreen) gscreen;
John Arbuckle3b178b72015-09-25 23:14:00 +0100343- (void) raiseAllKeys;
thsc304f7e2008-01-22 23:25:15 +0000344@end
ths3b46e622007-09-17 08:09:54 +0000345
Andreas Färber7fee1992011-06-09 20:53:32 +0200346QemuCocoaView *cocoaView;
347
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900348static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEventRef cgEvent, void *userInfo)
349{
Philippe Mathieu-Daudé21eb7522023-10-04 14:00:13 +0200350 QemuCocoaView *view = userInfo;
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900351 NSEvent *event = [NSEvent eventWithCGEvent:cgEvent];
Philippe Mathieu-Daudé21eb7522023-10-04 14:00:13 +0200352 if ([view isMouseGrabbed] && [view handleEvent:event]) {
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900353 COCOA_DEBUG("Global events tap: qemu handled the event, capturing!\n");
354 return NULL;
355 }
356 COCOA_DEBUG("Global events tap: qemu did not handle the event, letting it through...\n");
357
358 return cgEvent;
359}
360
thsc304f7e2008-01-22 23:25:15 +0000361@implementation QemuCocoaView
362- (id)initWithFrame:(NSRect)frameRect
363{
364 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
ths3b46e622007-09-17 08:09:54 +0000365
thsc304f7e2008-01-22 23:25:15 +0000366 self = [super initWithFrame:frameRect];
367 if (self) {
pbrook95219892006-04-09 01:06:34 +0000368
thsc304f7e2008-01-22 23:25:15 +0000369 screen.width = frameRect.size.width;
370 screen.height = frameRect.size.height;
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900371 kbd = qkbd_state_init(dcl.con);
David Parsonsf5af8022024-02-24 14:06:20 +0000372#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_14_0
373 [self setClipsToBounds:YES];
374#endif
bellard7c206a72005-12-18 19:18:45 +0000375
thsc304f7e2008-01-22 23:25:15 +0000376 }
377 return self;
378}
bellard7c206a72005-12-18 19:18:45 +0000379
thsc304f7e2008-01-22 23:25:15 +0000380- (void) dealloc
381{
382 COCOA_DEBUG("QemuCocoaView: dealloc\n");
bellard7c206a72005-12-18 19:18:45 +0000383
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900384 if (pixman_image) {
Peter Maydell55888402019-02-25 10:24:33 +0000385 pixman_image_unref(pixman_image);
386 }
ths3b46e622007-09-17 08:09:54 +0000387
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900388 qkbd_state_free(kbd);
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900389
390 if (eventsTap) {
391 CFRelease(eventsTap);
392 }
393
thsc304f7e2008-01-22 23:25:15 +0000394 [super dealloc];
395}
bellard5cbfcd02006-06-14 15:53:24 +0000396
Andreas Färberd50f71d2009-12-13 02:03:33 +0100397- (BOOL) isOpaque
398{
399 return YES;
400}
401
Peter Maydell5dd45be2014-06-23 10:35:23 +0100402- (BOOL) screenContainsPoint:(NSPoint) p
403{
404 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
405}
406
Chen Zhang2044dff2019-06-04 17:36:00 +0800407/* Get location of event and convert to virtual screen coordinate */
408- (CGPoint) screenLocationOfEvent:(NSEvent *)ev
409{
410 NSWindow *eventWindow = [ev window];
411 // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
412 CGRect r = CGRectZero;
413 r.origin = [ev locationInWindow];
414 if (!eventWindow) {
415 if (!isFullscreen) {
416 return [[self window] convertRectFromScreen:r].origin;
417 } else {
418 CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
419 CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
420 if (stretch_video) {
421 loc.x /= cdx;
422 loc.y /= cdy;
423 }
424 return loc;
425 }
426 } else if ([[self window] isEqual:eventWindow]) {
427 if (!isFullscreen) {
428 return r.origin;
429 } else {
430 CGPoint loc = [self convertPoint:r.origin fromView:nil];
431 if (stretch_video) {
432 loc.x /= cdx;
433 loc.y /= cdy;
434 }
435 return loc;
436 }
437 } else {
438 return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
439 }
440}
441
Peter Maydell13aefd32014-06-23 10:35:25 +0100442- (void) hideCursor
443{
444 if (!cursor_hide) {
445 return;
446 }
447 [NSCursor hide];
448}
449
450- (void) unhideCursor
451{
452 if (!cursor_hide) {
453 return;
454 }
455 [NSCursor unhide];
456}
457
thsc304f7e2008-01-22 23:25:15 +0000458- (void) drawRect:(NSRect) rect
459{
460 COCOA_DEBUG("QemuCocoaView: drawRect\n");
bellard5cbfcd02006-06-14 15:53:24 +0000461
thsc304f7e2008-01-22 23:25:15 +0000462 // get CoreGraphic context
Brendan Shanks5e246002019-01-31 23:12:25 -0800463 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
Brendan Shanks5e246002019-01-31 23:12:25 -0800464
Carwyn Ellise28a9092023-11-10 16:17:29 +0000465 CGContextSetInterpolationQuality (viewContextRef, zoom_interpolation);
thsc304f7e2008-01-22 23:25:15 +0000466 CGContextSetShouldAntialias (viewContextRef, NO);
ths3b46e622007-09-17 08:09:54 +0000467
thsc304f7e2008-01-22 23:25:15 +0000468 // draw screen bitmap directly to Core Graphics context
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900469 if (!pixman_image) {
Peter Maydell7d270b12013-12-24 02:51:47 +0000470 // Draw request before any guest device has set up a framebuffer:
471 // just draw an opaque black rectangle
472 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
473 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
474 } else {
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900475 int w = pixman_image_get_width(pixman_image);
476 int h = pixman_image_get_height(pixman_image);
477 int bitsPerPixel = PIXMAN_FORMAT_BPP(pixman_image_get_format(pixman_image));
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900478 int stride = pixman_image_get_stride(pixman_image);
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900479 CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(
480 NULL,
481 pixman_image_get_data(pixman_image),
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900482 stride * h,
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900483 NULL
484 );
thsc304f7e2008-01-22 23:25:15 +0000485 CGImageRef imageRef = CGImageCreate(
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900486 w, //width
487 h, //height
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900488 DIV_ROUND_UP(bitsPerPixel, 8) * 2, //bitsPerComponent
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900489 bitsPerPixel, //bitsPerPixel
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900490 stride, //bytesPerRow
Akihiko Odakiae57d352021-03-05 21:13:04 +0900491 CGColorSpaceCreateWithName(kCGColorSpaceSRGB), //colorspace
492 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst, //bitmapInfo
thsc304f7e2008-01-22 23:25:15 +0000493 dataProviderRef, //provider
494 NULL, //decode
495 0, //interpolate
496 kCGRenderingIntentDefault //intent
497 );
Peter Maydellb63901d2015-05-19 09:11:17 +0100498 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
499 const NSRect *rectList;
Peter Maydellb63901d2015-05-19 09:11:17 +0100500 NSInteger rectCount;
Peter Maydellb63901d2015-05-19 09:11:17 +0100501 int i;
502 CGImageRef clipImageRef;
503 CGRect clipRect;
ths3b46e622007-09-17 08:09:54 +0000504
Peter Maydellb63901d2015-05-19 09:11:17 +0100505 [self getRectsBeingDrawn:&rectList count:&rectCount];
506 for (i = 0; i < rectCount; i++) {
Akihiko Odakifcb03de2024-02-24 21:43:35 +0900507 clipRect = rectList[i];
508 clipRect.origin.y = (float)h - (clipRect.origin.y + clipRect.size.height);
Peter Maydellb63901d2015-05-19 09:11:17 +0100509 clipImageRef = CGImageCreateWithImageInRect(
510 imageRef,
511 clipRect
512 );
513 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
514 CGImageRelease (clipImageRef);
bellard5b0753e2005-03-01 21:37:28 +0000515 }
thsc304f7e2008-01-22 23:25:15 +0000516 CGImageRelease (imageRef);
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900517 CGDataProviderRelease(dataProviderRef);
bellard5b0753e2005-03-01 21:37:28 +0000518 }
519}
520
thsc304f7e2008-01-22 23:25:15 +0000521- (void) setContentDimensions
bellard5b0753e2005-03-01 21:37:28 +0000522{
thsc304f7e2008-01-22 23:25:15 +0000523 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
ths3b46e622007-09-17 08:09:54 +0000524
thsc304f7e2008-01-22 23:25:15 +0000525 if (isFullscreen) {
526 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
527 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100528
529 /* stretches video, but keeps same aspect ratio */
530 if (stretch_video == true) {
531 /* use smallest stretch value - prevents clipping on sides */
532 if (MIN(cdx, cdy) == cdx) {
533 cdy = cdx;
534 } else {
535 cdx = cdy;
536 }
537 } else { /* No stretching */
538 cdx = cdy = 1;
539 }
thsc304f7e2008-01-22 23:25:15 +0000540 cw = screen.width * cdx;
541 ch = screen.height * cdy;
542 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
543 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
544 } else {
545 cx = 0;
546 cy = 0;
547 cw = screen.width;
548 ch = screen.height;
549 cdx = 1.0;
550 cdy = 1.0;
551 }
bellard5b0753e2005-03-01 21:37:28 +0000552}
553
Akihiko Odakifcb03de2024-02-24 21:43:35 +0900554- (void) updateBounds
555{
556 [self setBoundsSize:NSMakeSize(screen.width, screen.height)];
557}
558
Peter Maydell8d65dee2022-02-24 10:13:29 +0000559- (void) updateUIInfoLocked
Akihiko Odaki15280e82021-06-16 23:19:10 +0900560{
Stefan Hajnoczia4a411f2024-01-02 10:35:28 -0500561 /* Must be called with the BQL, i.e. via updateUIInfo */
Akihiko Odaki15280e82021-06-16 23:19:10 +0900562 NSSize frameSize;
563 QemuUIInfo info;
564
565 if (!qemu_console_is_graphic(dcl.con)) {
566 return;
567 }
568
569 if ([self window]) {
570 NSDictionary *description = [[[self window] screen] deviceDescription];
571 CGDirectDisplayID display = [[description objectForKey:@"NSScreenNumber"] unsignedIntValue];
572 NSSize screenSize = [[[self window] screen] frame].size;
573 CGSize screenPhysicalSize = CGDisplayScreenSize(display);
Akihiko Odaki52eaefd2022-07-02 23:25:19 +0900574 CVDisplayLinkRef displayLink;
Akihiko Odaki15280e82021-06-16 23:19:10 +0900575
576 frameSize = isFullscreen ? screenSize : [self frame].size;
Akihiko Odaki52eaefd2022-07-02 23:25:19 +0900577
578 if (!CVDisplayLinkCreateWithCGDisplay(display, &displayLink)) {
579 CVTime period = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLink);
580 CVDisplayLinkRelease(displayLink);
581 if (!(period.flags & kCVTimeIsIndefinite)) {
582 update_displaychangelistener(&dcl,
583 1000 * period.timeValue / period.timeScale);
584 info.refresh_rate = (int64_t)1000 * period.timeScale / period.timeValue;
585 }
586 }
587
Akihiko Odaki15280e82021-06-16 23:19:10 +0900588 info.width_mm = frameSize.width / screenSize.width * screenPhysicalSize.width;
589 info.height_mm = frameSize.height / screenSize.height * screenPhysicalSize.height;
590 } else {
591 frameSize = [self frame].size;
592 info.width_mm = 0;
593 info.height_mm = 0;
594 }
595
596 info.xoff = 0;
597 info.yoff = 0;
598 info.width = frameSize.width;
599 info.height = frameSize.height;
600
Marc-André Lureauca19ef52021-04-13 20:39:11 +0400601 dpy_set_ui_info(dcl.con, &info, TRUE);
Akihiko Odaki15280e82021-06-16 23:19:10 +0900602}
603
Peter Maydell8d65dee2022-02-24 10:13:29 +0000604- (void) updateUIInfo
605{
606 if (!allow_events) {
607 /*
608 * Don't try to tell QEMU about UI information in the application
609 * startup phase -- we haven't yet registered dcl with the QEMU UI
Akihiko Odakibab6a302022-08-19 22:27:54 +0900610 * layer.
Peter Maydell8d65dee2022-02-24 10:13:29 +0000611 * When cocoa_display_init() does register the dcl, the UI layer
612 * will call cocoa_switch(), which will call updateUIInfo, so
613 * we don't lose any information here.
614 */
615 return;
616 }
617
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500618 with_bql(^{
Peter Maydell8d65dee2022-02-24 10:13:29 +0000619 [self updateUIInfoLocked];
620 });
621}
622
Akihiko Odaki15280e82021-06-16 23:19:10 +0900623- (void)viewDidMoveToWindow
624{
625 [self updateUIInfo];
626}
627
Peter Maydell72a3e312019-02-25 10:24:28 +0000628- (void) switchSurface:(pixman_image_t *)image
thsc304f7e2008-01-22 23:25:15 +0000629{
Gerd Hoffmann5e00d3a2013-03-01 12:52:06 +0100630 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
thsc304f7e2008-01-22 23:25:15 +0000631
Peter Maydell72a3e312019-02-25 10:24:28 +0000632 int w = pixman_image_get_width(image);
633 int h = pixman_image_get_height(image);
Peter Maydell381600d2014-06-23 10:35:22 +0100634 /* cdx == 0 means this is our very first surface, in which case we need
635 * to recalculate the content dimensions even if it happens to be the size
636 * of the initial empty window.
637 */
638 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
Peter Maydelld3345a02013-12-24 02:51:46 +0000639
640 int oldh = screen.height;
641 if (isResize) {
642 // Resize before we trigger the redraw, or we'll redraw at the wrong size
643 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
644 screen.width = w;
645 screen.height = h;
646 [self setContentDimensions];
647 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
Akihiko Odakifcb03de2024-02-24 21:43:35 +0900648 [self updateBounds];
Peter Maydelld3345a02013-12-24 02:51:46 +0000649 }
Peter Maydell8510d912013-03-18 20:28:21 +0000650
thsc304f7e2008-01-22 23:25:15 +0000651 // update screenBuffer
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900652 if (pixman_image) {
Peter Maydell55888402019-02-25 10:24:33 +0000653 pixman_image_unref(pixman_image);
654 }
thsc304f7e2008-01-22 23:25:15 +0000655
Peter Maydell55888402019-02-25 10:24:33 +0000656 pixman_image = image;
thsc304f7e2008-01-22 23:25:15 +0000657
658 // update windows
659 if (isFullscreen) {
660 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
Peter Maydelld3345a02013-12-24 02:51:46 +0000661 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
thsc304f7e2008-01-22 23:25:15 +0000662 } else {
663 if (qemu_name)
664 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
Peter Maydelld3345a02013-12-24 02:51:46 +0000665 [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 +0000666 }
Peter Maydelld3345a02013-12-24 02:51:46 +0000667
668 if (isResize) {
669 [normalWindow center];
670 }
thsc304f7e2008-01-22 23:25:15 +0000671}
672
673- (void) toggleFullScreen:(id)sender
674{
675 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
676
677 if (isFullscreen) { // switch from fullscreen to desktop
678 isFullscreen = FALSE;
679 [self ungrabMouse];
680 [self setContentDimensions];
Akihiko Odaki1e8b6f22021-02-20 10:31:38 +0900681 [fullScreenWindow close];
682 [normalWindow setContentView: self];
683 [normalWindow makeKeyAndOrderFront: self];
684 [NSMenu setMenuBarVisible:YES];
thsc304f7e2008-01-22 23:25:15 +0000685 } else { // switch from desktop to fullscreen
686 isFullscreen = TRUE;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100687 [normalWindow orderOut: nil]; /* Hide the window */
thsc304f7e2008-01-22 23:25:15 +0000688 [self grabMouse];
689 [self setContentDimensions];
Akihiko Odaki1e8b6f22021-02-20 10:31:38 +0900690 [NSMenu setMenuBarVisible:NO];
691 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
692 styleMask:NSWindowStyleMaskBorderless
693 backing:NSBackingStoreBuffered
694 defer:NO];
695 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
696 [fullScreenWindow setHasShadow:NO];
697 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
698 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
699 [[fullScreenWindow contentView] addSubview: self];
700 [fullScreenWindow makeKeyAndOrderFront:self];
thsc304f7e2008-01-22 23:25:15 +0000701 }
702}
703
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900704- (void) setFullGrab:(id)sender
705{
706 COCOA_DEBUG("QemuCocoaView: setFullGrab\n");
707
708 CGEventMask mask = CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp) | CGEventMaskBit(kCGEventFlagsChanged);
709 eventsTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault,
710 mask, handleTapEvent, self);
711 if (!eventsTap) {
712 warn_report("Could not create event tap, system key combos will not be captured.\n");
713 return;
714 } else {
715 COCOA_DEBUG("Global events tap created! Will capture system key combos.\n");
716 }
717
718 CFRunLoopRef runLoop = CFRunLoopGetCurrent();
719 if (!runLoop) {
720 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
721 return;
722 }
723
724 CFRunLoopSourceRef tapEventsSrc = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventsTap, 0);
725 if (!tapEventsSrc ) {
726 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
727 return;
728 }
729
730 CFRunLoopAddSource(runLoop, tapEventsSrc, kCFRunLoopDefaultMode);
731 CFRelease(tapEventsSrc);
732}
733
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900734- (void) toggleKey: (int)keycode {
735 qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode));
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700736}
737
John Arbuckle9c3a4182017-11-07 10:14:14 +0000738// Does the work of sending input to the monitor
739- (void) handleMonitorInput:(NSEvent *)event
740{
741 int keysym = 0;
742 int control_key = 0;
743
744 // if the control key is down
745 if ([event modifierFlags] & NSEventModifierFlagControl) {
746 control_key = 1;
747 }
748
749 /* translates Macintosh keycodes to QEMU's keysym */
750
Philippe Mathieu-Daudé94592622022-02-15 16:21:14 +0100751 static const int without_control_translation[] = {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000752 [0 ... 0xff] = 0, // invalid key
753
754 [kVK_UpArrow] = QEMU_KEY_UP,
755 [kVK_DownArrow] = QEMU_KEY_DOWN,
756 [kVK_RightArrow] = QEMU_KEY_RIGHT,
757 [kVK_LeftArrow] = QEMU_KEY_LEFT,
758 [kVK_Home] = QEMU_KEY_HOME,
759 [kVK_End] = QEMU_KEY_END,
760 [kVK_PageUp] = QEMU_KEY_PAGEUP,
761 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
762 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
763 [kVK_Delete] = QEMU_KEY_BACKSPACE,
764 };
765
Philippe Mathieu-Daudé94592622022-02-15 16:21:14 +0100766 static const int with_control_translation[] = {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000767 [0 ... 0xff] = 0, // invalid key
768
769 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
770 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
771 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
772 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
773 [kVK_Home] = QEMU_KEY_CTRL_HOME,
774 [kVK_End] = QEMU_KEY_CTRL_END,
775 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
776 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
777 };
778
779 if (control_key != 0) { /* If the control key is being used */
780 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
781 keysym = with_control_translation[[event keyCode]];
782 }
783 } else {
784 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
785 keysym = without_control_translation[[event keyCode]];
786 }
787 }
788
789 // if not a key that needs translating
790 if (keysym == 0) {
791 NSString *ks = [event characters];
792 if ([ks length] > 0) {
793 keysym = [ks characterAtIndex:0];
794 }
795 }
796
797 if (keysym) {
Marc-André Lureaucc6ba2c2023-08-30 13:38:20 +0400798 qemu_text_console_put_keysym(NULL, keysym);
John Arbuckle9c3a4182017-11-07 10:14:14 +0000799 }
800}
801
Peter Maydell60105d72019-02-25 10:24:31 +0000802- (bool) handleEvent:(NSEvent *)event
thsc304f7e2008-01-22 23:25:15 +0000803{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500804 return bool_with_bql(^{
Peter Maydell60105d72019-02-25 10:24:31 +0000805 return [self handleEventLocked:event];
Peter Maydell31819e92019-02-25 10:24:27 +0000806 });
807}
thsc304f7e2008-01-22 23:25:15 +0000808
Peter Maydell60105d72019-02-25 10:24:31 +0000809- (bool) handleEventLocked:(NSEvent *)event
Peter Maydell31819e92019-02-25 10:24:27 +0000810{
Peter Maydell60105d72019-02-25 10:24:31 +0000811 /* Return true if we handled the event, false if it should be given to OSX */
Peter Maydell31819e92019-02-25 10:24:27 +0000812 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
Akihiko Odaki0f7be472024-02-24 21:43:33 +0900813 InputButton button;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700814 int keycode = 0;
Chen Zhang2044dff2019-06-04 17:36:00 +0800815 // Location of event in virtual screen coordinates
816 NSPoint p = [self screenLocationOfEvent:event];
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900817 NSUInteger modifiers = [event modifierFlags];
818
Akihiko Odakiad7f2f82021-03-12 22:32:12 +0900819 /*
820 * Check -[NSEvent modifierFlags] here.
821 *
822 * There is a NSEventType for an event notifying the change of
823 * -[NSEvent modifierFlags], NSEventTypeFlagsChanged but these operations
824 * are performed for any events because a modifier state may change while
825 * the application is inactive (i.e. no events fire) and we don't want to
826 * wait for another modifier state change to detect such a change.
827 *
828 * NSEventModifierFlagCapsLock requires a special treatment. The other flags
829 * are handled in similar manners.
830 *
831 * NSEventModifierFlagCapsLock
832 * ---------------------------
833 *
834 * If CapsLock state is changed, "up" and "down" events will be fired in
835 * sequence, effectively updates CapsLock state on the guest.
836 *
837 * The other flags
838 * ---------------
839 *
840 * If a flag is not set, fire "up" events for all keys which correspond to
841 * the flag. Note that "down" events are not fired here because the flags
842 * checked here do not tell what exact keys are down.
843 *
844 * If one of the keys corresponding to a flag is down, we rely on
845 * -[NSEvent keyCode] of an event whose -[NSEvent type] is
846 * NSEventTypeFlagsChanged to know the exact key which is down, which has
847 * the following two downsides:
848 * - It does not work when the application is inactive as described above.
849 * - It malfactions *after* the modifier state is changed while the
850 * application is inactive. It is because -[NSEvent keyCode] does not tell
851 * if the key is up or down, and requires to infer the current state from
852 * the previous state. It is still possible to fix such a malfanction by
853 * completely leaving your hands from the keyboard, which hopefully makes
854 * this implementation usable enough.
855 */
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900856 if (!!(modifiers & NSEventModifierFlagCapsLock) !=
857 qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) {
858 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true);
859 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false);
860 }
861
862 if (!(modifiers & NSEventModifierFlagShift)) {
863 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false);
864 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false);
865 }
866 if (!(modifiers & NSEventModifierFlagControl)) {
867 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false);
868 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false);
869 }
870 if (!(modifiers & NSEventModifierFlagOption)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900871 if (swap_opt_cmd) {
872 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
873 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
874 } else {
875 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
876 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
877 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900878 }
879 if (!(modifiers & NSEventModifierFlagCommand)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900880 if (swap_opt_cmd) {
881 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
882 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
883 } else {
884 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
885 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
886 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900887 }
thsc304f7e2008-01-22 23:25:15 +0000888
889 switch ([event type]) {
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700890 case NSEventTypeFlagsChanged:
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900891 switch ([event keyCode]) {
892 case kVK_Shift:
893 if (!!(modifiers & NSEventModifierFlagShift)) {
894 [self toggleKey:Q_KEY_CODE_SHIFT];
895 }
896 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700897
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900898 case kVK_RightShift:
899 if (!!(modifiers & NSEventModifierFlagShift)) {
900 [self toggleKey:Q_KEY_CODE_SHIFT_R];
901 }
902 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700903
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900904 case kVK_Control:
905 if (!!(modifiers & NSEventModifierFlagControl)) {
906 [self toggleKey:Q_KEY_CODE_CTRL];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700907 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900908 break;
909
910 case kVK_RightControl:
911 if (!!(modifiers & NSEventModifierFlagControl)) {
912 [self toggleKey:Q_KEY_CODE_CTRL_R];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700913 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900914 break;
915
916 case kVK_Option:
917 if (!!(modifiers & NSEventModifierFlagOption)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900918 if (swap_opt_cmd) {
919 [self toggleKey:Q_KEY_CODE_META_L];
920 } else {
921 [self toggleKey:Q_KEY_CODE_ALT];
922 }
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700923 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900924 break;
925
926 case kVK_RightOption:
927 if (!!(modifiers & NSEventModifierFlagOption)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900928 if (swap_opt_cmd) {
929 [self toggleKey:Q_KEY_CODE_META_R];
930 } else {
931 [self toggleKey:Q_KEY_CODE_ALT_R];
932 }
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700933 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900934 break;
935
936 /* Don't pass command key changes to guest unless mouse is grabbed */
937 case kVK_Command:
938 if (isMouseGrabbed &&
Akihiko Odakid6b6dea2022-03-18 00:29:49 +0900939 !!(modifiers & NSEventModifierFlagCommand) &&
940 left_command_key_enabled) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900941 if (swap_opt_cmd) {
942 [self toggleKey:Q_KEY_CODE_ALT];
943 } else {
944 [self toggleKey:Q_KEY_CODE_META_L];
945 }
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700946 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900947 break;
948
949 case kVK_RightCommand:
950 if (isMouseGrabbed &&
951 !!(modifiers & NSEventModifierFlagCommand)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900952 if (swap_opt_cmd) {
953 [self toggleKey:Q_KEY_CODE_ALT_R];
954 } else {
955 [self toggleKey:Q_KEY_CODE_META_R];
956 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900957 }
958 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700959 }
Akihiko Odaki0f7be472024-02-24 21:43:33 +0900960 return true;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700961 case NSEventTypeKeyDown:
Peter Maydell88959192013-12-08 22:59:02 +0000962 keycode = cocoa_keycode_to_qemu([event keyCode]);
thsc304f7e2008-01-22 23:25:15 +0000963
Peter Maydell88959192013-12-08 22:59:02 +0000964 // forward command key combos to the host UI unless the mouse is grabbed
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700965 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
Peter Maydell60105d72019-02-25 10:24:31 +0000966 return false;
thsc304f7e2008-01-22 23:25:15 +0000967 }
968
969 // default
thsc304f7e2008-01-22 23:25:15 +0000970
John Arbuckle5929e362017-11-07 10:14:14 +0000971 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700972 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
John Arbuckle5929e362017-11-07 10:14:14 +0000973 NSString *keychar = [event charactersIgnoringModifiers];
974 if ([keychar length] == 1) {
975 char key = [keychar characterAtIndex:0];
976 switch (key) {
thsc304f7e2008-01-22 23:25:15 +0000977
John Arbuckle5929e362017-11-07 10:14:14 +0000978 // enable graphic console
979 case '1' ... '9':
980 console_select(key - '0' - 1); /* ascii math */
Peter Maydell60105d72019-02-25 10:24:31 +0000981 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000982
983 // release the mouse grab
984 case 'g':
985 [self ungrabMouse];
Peter Maydell60105d72019-02-25 10:24:31 +0000986 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000987 }
thsc304f7e2008-01-22 23:25:15 +0000988 }
Peter Maydellef2088f2017-11-07 10:14:14 +0000989 }
thsc304f7e2008-01-22 23:25:15 +0000990
Peter Maydellef2088f2017-11-07 10:14:14 +0000991 if (qemu_console_is_graphic(NULL)) {
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900992 qkbd_state_key_event(kbd, keycode, true);
thsc304f7e2008-01-22 23:25:15 +0000993 } else {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000994 [self handleMonitorInput: event];
thsc304f7e2008-01-22 23:25:15 +0000995 }
Akihiko Odaki0f7be472024-02-24 21:43:33 +0900996 return true;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700997 case NSEventTypeKeyUp:
thsc304f7e2008-01-22 23:25:15 +0000998 keycode = cocoa_keycode_to_qemu([event keyCode]);
Peter Maydell88959192013-12-08 22:59:02 +0000999
1000 // don't pass the guest a spurious key-up if we treated this
1001 // command-key combo as a host UI action
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001002 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
Peter Maydell60105d72019-02-25 10:24:31 +00001003 return true;
Peter Maydell88959192013-12-08 22:59:02 +00001004 }
1005
Peter Maydell68c0aa62013-04-17 09:16:35 +00001006 if (qemu_console_is_graphic(NULL)) {
Akihiko Odaki6d73bb62021-03-10 23:46:02 +09001007 qkbd_state_key_event(kbd, keycode, false);
thsc304f7e2008-01-22 23:25:15 +00001008 }
Akihiko Odaki0f7be472024-02-24 21:43:33 +09001009 return true;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001010 case NSEventTypeMouseMoved:
thsc304f7e2008-01-22 23:25:15 +00001011 if (isAbsoluteEnabled) {
Chen Zhang2044dff2019-06-04 17:36:00 +08001012 // Cursor re-entered into a window might generate events bound to screen coordinates
1013 // and `nil` window property, and in full screen mode, current window might not be
1014 // key window, where event location alone should suffice.
1015 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
Peter Maydellf61c3872014-06-23 10:35:24 +01001016 if (isMouseGrabbed) {
1017 [self ungrabMouse];
thsc304f7e2008-01-22 23:25:15 +00001018 }
1019 } else {
Peter Maydellf61c3872014-06-23 10:35:24 +01001020 if (!isMouseGrabbed) {
1021 [self grabMouse];
thsc304f7e2008-01-22 23:25:15 +00001022 }
1023 }
1024 }
Akihiko Odakif4de9682024-02-24 21:43:34 +09001025 return [self handleMouseEvent:event];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001026 case NSEventTypeLeftMouseDown:
Akihiko Odakif4de9682024-02-24 21:43:34 +09001027 return [self handleMouseEvent:event button:INPUT_BUTTON_LEFT down:true];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001028 case NSEventTypeRightMouseDown:
Akihiko Odakif4de9682024-02-24 21:43:34 +09001029 return [self handleMouseEvent:event button:INPUT_BUTTON_RIGHT down:true];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001030 case NSEventTypeOtherMouseDown:
Akihiko Odakif4de9682024-02-24 21:43:34 +09001031 return [self handleMouseEvent:event button:INPUT_BUTTON_MIDDLE down:true];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001032 case NSEventTypeLeftMouseDragged:
Akihiko Odakif4de9682024-02-24 21:43:34 +09001033 return [self handleMouseEvent:event button:INPUT_BUTTON_LEFT down:true];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001034 case NSEventTypeRightMouseDragged:
Akihiko Odakif4de9682024-02-24 21:43:34 +09001035 return [self handleMouseEvent:event button:INPUT_BUTTON_RIGHT down:true];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001036 case NSEventTypeOtherMouseDragged:
Akihiko Odakif4de9682024-02-24 21:43:34 +09001037 return [self handleMouseEvent:event button:INPUT_BUTTON_MIDDLE down:true];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001038 case NSEventTypeLeftMouseUp:
Peter Maydellf61c3872014-06-23 10:35:24 +01001039 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
Chen Zhang8e23e342019-06-04 17:36:48 +08001040 /*
1041 * In fullscreen mode, the window of cocoaView may not be the
1042 * key window, therefore the position relative to the virtual
1043 * screen alone will be sufficient.
1044 */
1045 if(isFullscreen || [[self window] isKeyWindow]) {
Programmingkid9e8204b2016-08-15 22:11:06 -04001046 [self grabMouse];
1047 }
thsc304f7e2008-01-22 23:25:15 +00001048 }
Akihiko Odakif4de9682024-02-24 21:43:34 +09001049 return [self handleMouseEvent:event button:INPUT_BUTTON_LEFT down:false];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001050 case NSEventTypeRightMouseUp:
Akihiko Odakif4de9682024-02-24 21:43:34 +09001051 return [self handleMouseEvent:event button:INPUT_BUTTON_RIGHT down:false];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001052 case NSEventTypeOtherMouseUp:
Akihiko Odakif4de9682024-02-24 21:43:34 +09001053 return [self handleMouseEvent:event button:INPUT_BUTTON_MIDDLE down:false];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001054 case NSEventTypeScrollWheel:
John Arbuckleae7313e2018-01-08 13:07:07 -05001055 /*
1056 * Send wheel events to the guest regardless of window focus.
1057 * This is in-line with standard Mac OS X UI behaviour.
1058 */
1059
1060 /* Determine if this is a scroll up or scroll down event */
Akihiko Odaki0f7be472024-02-24 21:43:33 +09001061 if ([event deltaY] != 0) {
1062 button = ([event deltaY] > 0) ?
John Arbuckledc3c89d2018-07-09 11:02:35 -04001063 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
Akihiko Odaki0f7be472024-02-24 21:43:33 +09001064 } else if ([event deltaX] != 0) {
1065 button = ([event deltaX] > 0) ?
Dmitry Petrovd70a5de2022-01-08 16:39:44 +01001066 INPUT_BUTTON_WHEEL_LEFT : INPUT_BUTTON_WHEEL_RIGHT;
Akihiko Odaki0f7be472024-02-24 21:43:33 +09001067 } else {
1068 /*
1069 * We shouldn't have got a scroll event when deltaY and delta Y
1070 * are zero, hence no harm in dropping the event
1071 */
1072 return true;
John Arbuckledc3c89d2018-07-09 11:02:35 -04001073 }
Dmitry Petrovd70a5de2022-01-08 16:39:44 +01001074
Akihiko Odaki0f7be472024-02-24 21:43:33 +09001075 qemu_input_queue_btn(dcl.con, button, true);
1076 qemu_input_event_sync();
1077 qemu_input_queue_btn(dcl.con, button, false);
1078 qemu_input_event_sync();
1079
1080 return true;
thsc304f7e2008-01-22 23:25:15 +00001081 default:
Peter Maydell60105d72019-02-25 10:24:31 +00001082 return false;
thsc304f7e2008-01-22 23:25:15 +00001083 }
1084}
1085
Akihiko Odakif4de9682024-02-24 21:43:34 +09001086- (bool) handleMouseEvent:(NSEvent *)event button:(InputButton)button down:(bool)down
Akihiko Odakiaf4efbc2024-02-24 21:43:32 +09001087{
1088 /* Don't send button events to the guest unless we've got a
1089 * mouse grab or window focus. If we have neither then this event
1090 * is the user clicking on the background window to activate and
1091 * bring us to the front, which will be done by the sendEvent
1092 * call below. We definitely don't want to pass that click through
1093 * to the guest.
1094 */
Akihiko Odakif4de9682024-02-24 21:43:34 +09001095 if (!isMouseGrabbed && ![[self window] isKeyWindow]) {
1096 return false;
Akihiko Odakiaf4efbc2024-02-24 21:43:32 +09001097 }
1098
Akihiko Odakif4de9682024-02-24 21:43:34 +09001099 qemu_input_queue_btn(dcl.con, button, down);
1100
Akihiko Odakiaf4efbc2024-02-24 21:43:32 +09001101 return [self handleMouseEvent:event];
1102}
1103
1104- (bool) handleMouseEvent:(NSEvent *)event
1105{
1106 if (!isMouseGrabbed) {
1107 return false;
1108 }
1109
1110 if (isAbsoluteEnabled) {
1111 NSPoint p = [self screenLocationOfEvent:event];
1112
1113 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
1114 * The check on screenContainsPoint is to avoid sending out of range values for
1115 * clicks in the titlebar.
1116 */
1117 if ([self screenContainsPoint:p]) {
1118 qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x, 0, screen.width);
1119 qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
1120 }
1121 } else {
1122 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, (int)[event deltaX]);
1123 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, (int)[event deltaY]);
1124 }
1125
1126 qemu_input_event_sync();
1127
1128 return true;
1129}
1130
thsc304f7e2008-01-22 23:25:15 +00001131- (void) grabMouse
1132{
1133 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
1134
1135 if (!isFullscreen) {
1136 if (qemu_name)
Christian Schoenebeck23bdd0d2022-12-27 17:15:31 +01001137 [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 +00001138 else
Christian Schoenebeck23bdd0d2022-12-27 17:15:31 +01001139 [normalWindow setTitle:@"QEMU - (Press " UC_CTRL_KEY " " UC_ALT_KEY " G to release Mouse)"];
thsc304f7e2008-01-22 23:25:15 +00001140 }
Peter Maydell13aefd32014-06-23 10:35:25 +01001141 [self hideCursor];
Akihiko Odakid1929062021-02-23 00:07:14 +09001142 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
Peter Maydell49b9bd42013-12-08 22:59:03 +00001143 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
thsc304f7e2008-01-22 23:25:15 +00001144}
1145
1146- (void) ungrabMouse
1147{
1148 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
1149
1150 if (!isFullscreen) {
1151 if (qemu_name)
1152 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
1153 else
1154 [normalWindow setTitle:@"QEMU"];
1155 }
Peter Maydell13aefd32014-06-23 10:35:25 +01001156 [self unhideCursor];
Akihiko Odakid1929062021-02-23 00:07:14 +09001157 CGAssociateMouseAndMouseCursorPosition(TRUE);
Peter Maydell49b9bd42013-12-08 22:59:03 +00001158 isMouseGrabbed = FALSE;
thsc304f7e2008-01-22 23:25:15 +00001159}
1160
Akihiko Odakid1929062021-02-23 00:07:14 +09001161- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {
1162 isAbsoluteEnabled = tIsAbsoluteEnabled;
1163 if (isMouseGrabbed) {
1164 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1165 }
1166}
Peter Maydell49b9bd42013-12-08 22:59:03 +00001167- (BOOL) isMouseGrabbed {return isMouseGrabbed;}
thsc304f7e2008-01-22 23:25:15 +00001168- (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
1169- (float) cdx {return cdx;}
1170- (float) cdy {return cdy;}
1171- (QEMUScreen) gscreen {return screen;}
John Arbuckle3b178b72015-09-25 23:14:00 +01001172
1173/*
1174 * Makes the target think all down keys are being released.
1175 * This prevents a stuck key problem, since we will not see
1176 * key up events for those keys after we have lost focus.
1177 */
1178- (void) raiseAllKeys
1179{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001180 with_bql(^{
Akihiko Odaki6d73bb62021-03-10 23:46:02 +09001181 qkbd_state_lift_all_keys(kbd);
Peter Maydell31819e92019-02-25 10:24:27 +00001182 });
John Arbuckle3b178b72015-09-25 23:14:00 +01001183}
bellard5b0753e2005-03-01 21:37:28 +00001184@end
1185
1186
thsc304f7e2008-01-22 23:25:15 +00001187
bellard5b0753e2005-03-01 21:37:28 +00001188/*
1189 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +00001190 QemuCocoaAppController
bellard5b0753e2005-03-01 21:37:28 +00001191 ------------------------------------------------------
1192*/
thsc304f7e2008-01-22 23:25:15 +00001193@interface QemuCocoaAppController : NSObject
John Arbuckled9bc14f2015-09-25 23:13:59 +01001194 <NSWindowDelegate, NSApplicationDelegate>
bellard5b0753e2005-03-01 21:37:28 +00001195{
1196}
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001197- (void)doToggleFullScreen:(id)sender;
thsc304f7e2008-01-22 23:25:15 +00001198- (void)toggleFullScreen:(id)sender;
1199- (void)showQEMUDoc:(id)sender;
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001200- (void)zoomToFit:(id) sender;
Programmingkidb4c6a112015-05-19 09:11:18 +01001201- (void)displayConsole:(id)sender;
John Arbuckle8524f1c2015-06-19 10:53:27 +01001202- (void)pauseQEMU:(id)sender;
1203- (void)resumeQEMU:(id)sender;
1204- (void)displayPause;
1205- (void)removePause;
John Arbuckle27074612015-06-19 10:53:27 +01001206- (void)restartQEMU:(id)sender;
1207- (void)powerDownQEMU:(id)sender;
John Arbuckle693a3e02015-06-19 10:53:27 +01001208- (void)ejectDeviceMedia:(id)sender;
1209- (void)changeDeviceMedia:(id)sender;
John Arbuckled9bc14f2015-09-25 23:13:59 +01001210- (BOOL)verifyQuit;
John Arbucklef4747902016-03-23 14:26:17 +00001211- (void)openDocumentation:(NSString *)filename;
Programmingkid9e8204b2016-08-15 22:11:06 -04001212- (IBAction) do_about_menu_item: (id) sender;
John Arbucklee47ec1a2017-06-13 23:17:38 -04001213- (void)adjustSpeed:(id)sender;
bellard5b0753e2005-03-01 21:37:28 +00001214@end
1215
thsc304f7e2008-01-22 23:25:15 +00001216@implementation QemuCocoaAppController
1217- (id) init
1218{
1219 COCOA_DEBUG("QemuCocoaAppController: init\n");
1220
1221 self = [super init];
1222 if (self) {
1223
1224 // create a view and add it to the window
1225 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1226 if(!cocoaView) {
Akihiko Odaki43137392021-02-23 22:11:06 +09001227 error_report("(cocoa) can't create a view");
thsc304f7e2008-01-22 23:25:15 +00001228 exit(1);
1229 }
1230
1231 // create a window
1232 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001233 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
thsc304f7e2008-01-22 23:25:15 +00001234 backing:NSBackingStoreBuffered defer:NO];
1235 if(!normalWindow) {
Akihiko Odaki43137392021-02-23 22:11:06 +09001236 error_report("(cocoa) can't create window");
thsc304f7e2008-01-22 23:25:15 +00001237 exit(1);
1238 }
1239 [normalWindow setAcceptsMouseMovedEvents:YES];
John Arbucklea1dbc052015-10-13 21:51:18 +01001240 [normalWindow setTitle:@"QEMU"];
thsc304f7e2008-01-22 23:25:15 +00001241 [normalWindow setContentView:cocoaView];
1242 [normalWindow makeKeyAndOrderFront:self];
Peter Maydell49060c22013-12-24 11:54:12 +00001243 [normalWindow center];
John Arbuckled9bc14f2015-09-25 23:13:59 +01001244 [normalWindow setDelegate: self];
John Arbuckle8524f1c2015-06-19 10:53:27 +01001245
1246 /* Used for displaying pause on the screen */
1247 pauseLabel = [NSTextField new];
1248 [pauseLabel setBezeled:YES];
1249 [pauseLabel setDrawsBackground:YES];
1250 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1251 [pauseLabel setEditable:NO];
1252 [pauseLabel setSelectable:NO];
1253 [pauseLabel setStringValue: @"Paused"];
1254 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1255 [pauseLabel setTextColor: [NSColor blackColor]];
1256 [pauseLabel sizeToFit];
thsc304f7e2008-01-22 23:25:15 +00001257 }
1258 return self;
1259}
1260
1261- (void) dealloc
1262{
1263 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1264
1265 if (cocoaView)
1266 [cocoaView release];
1267 [super dealloc];
1268}
1269
bellard5b0753e2005-03-01 21:37:28 +00001270- (void)applicationDidFinishLaunching: (NSNotification *) note
1271{
thsc304f7e2008-01-22 23:25:15 +00001272 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
Hikaru Nishidadff742a2019-10-15 10:07:34 +09001273 allow_events = true;
bellard5b0753e2005-03-01 21:37:28 +00001274}
1275
1276- (void)applicationWillTerminate:(NSNotification *)aNotification
1277{
thsc304f7e2008-01-22 23:25:15 +00001278 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1279
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001280 with_bql(^{
Akihiko Odaki2910abd2022-05-29 17:25:08 +09001281 shutdown_action = SHUTDOWN_ACTION_POWEROFF;
1282 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1283 });
Akihiko Odaki40c01932021-02-19 20:16:52 +09001284
1285 /*
1286 * Sleep here, because returning will cause OSX to kill us
1287 * immediately; the QEMU main loop will handle the shutdown
1288 * request and terminate the process.
1289 */
1290 [NSThread sleepForTimeInterval:INFINITY];
bellard5b0753e2005-03-01 21:37:28 +00001291}
1292
Andreas Färber41ea49b2009-12-14 22:13:27 +01001293- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1294{
1295 return YES;
1296}
1297
John Arbuckled9bc14f2015-09-25 23:13:59 +01001298- (NSApplicationTerminateReply)applicationShouldTerminate:
1299 (NSApplication *)sender
1300{
1301 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1302 return [self verifyQuit];
1303}
1304
Akihiko Odaki15280e82021-06-16 23:19:10 +09001305- (void)windowDidChangeScreen:(NSNotification *)notification
1306{
1307 [cocoaView updateUIInfo];
1308}
1309
1310- (void)windowDidResize:(NSNotification *)notification
1311{
Akihiko Odakifcb03de2024-02-24 21:43:35 +09001312 [cocoaView updateBounds];
Akihiko Odaki15280e82021-06-16 23:19:10 +09001313 [cocoaView updateUIInfo];
1314}
1315
John Arbuckled9bc14f2015-09-25 23:13:59 +01001316/* Called when the user clicks on a window's close button */
1317- (BOOL)windowShouldClose:(id)sender
1318{
1319 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1320 [NSApp terminate: sender];
1321 /* If the user allows the application to quit then the call to
1322 * NSApp terminate will never return. If we get here then the user
1323 * cancelled the quit, so we should return NO to not permit the
1324 * closing of this window.
1325 */
1326 return NO;
1327}
1328
Akihiko Odaki9d9bc7d2023-02-28 16:09:46 +09001329/*
1330 * Called when QEMU goes into the background. Note that
1331 * [-NSWindowDelegate windowDidResignKey:] is used here instead of
1332 * [-NSApplicationDelegate applicationWillResignActive:] because it cannot
1333 * detect that the window loses focus when the deck is clicked on macOS 13.2.1.
1334 */
1335- (void) windowDidResignKey: (NSNotification *)aNotification
John Arbuckle3b178b72015-09-25 23:14:00 +01001336{
Akihiko Odaki9d9bc7d2023-02-28 16:09:46 +09001337 COCOA_DEBUG("%s\n", __func__);
Carwyn Ellis69221df2022-01-02 17:41:53 +00001338 [cocoaView ungrabMouse];
John Arbuckle3b178b72015-09-25 23:14:00 +01001339 [cocoaView raiseAllKeys];
1340}
1341
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001342/* We abstract the method called by the Enter Fullscreen menu item
1343 * because Mac OS 10.7 and higher disables it. This is because of the
1344 * menu item's old selector's name toggleFullScreen:
1345 */
1346- (void) doToggleFullScreen:(id)sender
1347{
1348 [self toggleFullScreen:(id)sender];
1349}
1350
thsc304f7e2008-01-22 23:25:15 +00001351- (void)toggleFullScreen:(id)sender
bellard5b0753e2005-03-01 21:37:28 +00001352{
thsc304f7e2008-01-22 23:25:15 +00001353 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1354
1355 [cocoaView toggleFullScreen:sender];
1356}
1357
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +09001358- (void) setFullGrab:(id)sender
1359{
1360 COCOA_DEBUG("QemuCocoaAppController: setFullGrab\n");
1361
1362 [cocoaView setFullGrab:sender];
1363}
1364
John Arbucklef4747902016-03-23 14:26:17 +00001365/* Tries to find then open the specified filename */
1366- (void) openDocumentation: (NSString *) filename
1367{
1368 /* Where to look for local files */
Roman Bolshakov8d6fda82021-01-09 00:38:15 +03001369 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
John Arbucklef4747902016-03-23 14:26:17 +00001370 NSString *full_file_path;
Roman Bolshakov1ff5a062021-01-02 18:07:21 +03001371 NSURL *full_file_url;
John Arbucklef4747902016-03-23 14:26:17 +00001372
1373 /* iterate thru the possible paths until the file is found */
1374 int index;
1375 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1376 full_file_path = [[NSBundle mainBundle] executablePath];
1377 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1378 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1379 path_array[index], filename];
Roman Bolshakov1ff5a062021-01-02 18:07:21 +03001380 full_file_url = [NSURL fileURLWithPath: full_file_path
1381 isDirectory: false];
1382 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
John Arbucklef4747902016-03-23 14:26:17 +00001383 return;
1384 }
1385 }
1386
1387 /* If none of the paths opened a file */
1388 NSBeep();
1389 QEMU_Alert(@"Failed to open file");
1390}
1391
thsc304f7e2008-01-22 23:25:15 +00001392- (void)showQEMUDoc:(id)sender
1393{
1394 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1395
Peter Maydell1879f242020-02-28 15:36:16 +00001396 [self openDocumentation: @"index.html"];
thsc304f7e2008-01-22 23:25:15 +00001397}
1398
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001399/* Stretches video to fit host monitor size */
1400- (void)zoomToFit:(id) sender
1401{
1402 stretch_video = !stretch_video;
1403 if (stretch_video == true) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001404 [sender setState: NSControlStateValueOn];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001405 } else {
Brendan Shanks5e246002019-01-31 23:12:25 -08001406 [sender setState: NSControlStateValueOff];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001407 }
1408}
bellard5b0753e2005-03-01 21:37:28 +00001409
Carwyn Ellise28a9092023-11-10 16:17:29 +00001410- (void)toggleZoomInterpolation:(id) sender
1411{
1412 if (zoom_interpolation == kCGInterpolationNone) {
1413 zoom_interpolation = kCGInterpolationLow;
1414 [sender setState: NSControlStateValueOn];
1415 } else {
1416 zoom_interpolation = kCGInterpolationNone;
1417 [sender setState: NSControlStateValueOff];
1418 }
1419}
1420
Programmingkidb4c6a112015-05-19 09:11:18 +01001421/* Displays the console on the screen */
1422- (void)displayConsole:(id)sender
1423{
1424 console_select([sender tag]);
1425}
John Arbuckle8524f1c2015-06-19 10:53:27 +01001426
1427/* Pause the guest */
1428- (void)pauseQEMU:(id)sender
1429{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001430 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001431 qmp_stop(NULL);
1432 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001433 [sender setEnabled: NO];
1434 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1435 [self displayPause];
1436}
1437
1438/* Resume running the guest operating system */
1439- (void)resumeQEMU:(id) sender
1440{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001441 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001442 qmp_cont(NULL);
1443 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001444 [sender setEnabled: NO];
1445 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1446 [self removePause];
1447}
1448
1449/* Displays the word pause on the screen */
1450- (void)displayPause
1451{
1452 /* Coordinates have to be calculated each time because the window can change its size */
1453 int xCoord, yCoord, width, height;
Akihiko Odaki1a4b64a2024-02-24 21:43:36 +09001454 xCoord = ([cocoaView frame].size.width - [pauseLabel frame].size.width)/2;
1455 yCoord = [cocoaView frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
John Arbuckle8524f1c2015-06-19 10:53:27 +01001456 width = [pauseLabel frame].size.width;
1457 height = [pauseLabel frame].size.height;
1458 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1459 [cocoaView addSubview: pauseLabel];
1460}
1461
1462/* Removes the word pause from the screen */
1463- (void)removePause
1464{
1465 [pauseLabel removeFromSuperview];
1466}
1467
John Arbuckle27074612015-06-19 10:53:27 +01001468/* Restarts QEMU */
1469- (void)restartQEMU:(id)sender
1470{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001471 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001472 qmp_system_reset(NULL);
1473 });
John Arbuckle27074612015-06-19 10:53:27 +01001474}
1475
1476/* Powers down QEMU */
1477- (void)powerDownQEMU:(id)sender
1478{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001479 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001480 qmp_system_powerdown(NULL);
1481 });
John Arbuckle27074612015-06-19 10:53:27 +01001482}
1483
John Arbuckle693a3e02015-06-19 10:53:27 +01001484/* Ejects the media.
1485 * Uses sender's tag to figure out the device to eject.
1486 */
1487- (void)ejectDeviceMedia:(id)sender
1488{
1489 NSString * drive;
1490 drive = [sender representedObject];
1491 if(drive == nil) {
1492 NSBeep();
1493 QEMU_Alert(@"Failed to find drive to eject!");
1494 return;
1495 }
1496
Peter Maydell31819e92019-02-25 10:24:27 +00001497 __block Error *err = NULL;
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001498 with_bql(^{
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001499 qmp_eject([drive cStringUsingEncoding: NSASCIIStringEncoding],
1500 NULL, false, false, &err);
Peter Maydell31819e92019-02-25 10:24:27 +00001501 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001502 handleAnyDeviceErrors(err);
1503}
1504
1505/* Displays a dialog box asking the user to select an image file to load.
1506 * Uses sender's represented object value to figure out which drive to use.
1507 */
1508- (void)changeDeviceMedia:(id)sender
1509{
1510 /* Find the drive name */
1511 NSString * drive;
1512 drive = [sender representedObject];
1513 if(drive == nil) {
1514 NSBeep();
1515 QEMU_Alert(@"Could not find drive!");
1516 return;
1517 }
1518
1519 /* Display the file open dialog */
1520 NSOpenPanel * openPanel;
1521 openPanel = [NSOpenPanel openPanel];
1522 [openPanel setCanChooseFiles: YES];
1523 [openPanel setAllowsMultipleSelection: NO];
Peter Maydellb5725382018-05-29 19:15:23 +01001524 if([openPanel runModal] == NSModalResponseOK) {
John Arbuckle693a3e02015-06-19 10:53:27 +01001525 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1526 if(file == nil) {
1527 NSBeep();
1528 QEMU_Alert(@"Failed to convert URL to file path!");
1529 return;
1530 }
1531
Peter Maydell31819e92019-02-25 10:24:27 +00001532 __block Error *err = NULL;
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001533 with_bql(^{
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001534 qmp_blockdev_change_medium([drive cStringUsingEncoding:
Peter Maydell31819e92019-02-25 10:24:27 +00001535 NSASCIIStringEncoding],
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001536 NULL,
Peter Maydell31819e92019-02-25 10:24:27 +00001537 [file cStringUsingEncoding:
1538 NSASCIIStringEncoding],
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001539 "raw",
Denis V. Lunev80dd5af2022-04-13 01:18:46 +03001540 true, false,
Peter Maydell31819e92019-02-25 10:24:27 +00001541 false, 0,
1542 &err);
1543 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001544 handleAnyDeviceErrors(err);
1545 }
1546}
1547
John Arbuckled9bc14f2015-09-25 23:13:59 +01001548/* Verifies if the user really wants to quit */
1549- (BOOL)verifyQuit
1550{
1551 NSAlert *alert = [NSAlert new];
1552 [alert autorelease];
1553 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1554 [alert addButtonWithTitle: @"Cancel"];
1555 [alert addButtonWithTitle: @"Quit"];
1556 if([alert runModal] == NSAlertSecondButtonReturn) {
1557 return YES;
1558 } else {
1559 return NO;
1560 }
1561}
1562
Programmingkid9e8204b2016-08-15 22:11:06 -04001563/* The action method for the About menu item */
1564- (IBAction) do_about_menu_item: (id) sender
1565{
Akihiko Odaki99eb3132022-02-27 13:22:41 +09001566 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1567 char *icon_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1568 NSString *icon_path = [NSString stringWithUTF8String:icon_path_c];
1569 g_free(icon_path_c);
1570 NSImage *icon = [[NSImage alloc] initWithContentsOfFile:icon_path];
1571 NSString *version = @"QEMU emulator version " QEMU_FULL_VERSION;
1572 NSString *copyright = @QEMU_COPYRIGHT;
1573 NSDictionary *options;
1574 if (icon) {
1575 options = @{
1576 NSAboutPanelOptionApplicationIcon : icon,
1577 NSAboutPanelOptionApplicationVersion : version,
1578 @"Copyright" : copyright,
1579 };
1580 [icon release];
1581 } else {
1582 options = @{
1583 NSAboutPanelOptionApplicationVersion : version,
1584 @"Copyright" : copyright,
1585 };
Akihiko Odakia0f973f2021-03-09 21:22:26 +09001586 }
Akihiko Odaki99eb3132022-02-27 13:22:41 +09001587 [NSApp orderFrontStandardAboutPanelWithOptions:options];
1588 [pool release];
Programmingkid9e8204b2016-08-15 22:11:06 -04001589}
1590
John Arbucklee47ec1a2017-06-13 23:17:38 -04001591/* Used by the Speed menu items */
1592- (void)adjustSpeed:(id)sender
1593{
1594 int throttle_pct; /* throttle percentage */
1595 NSMenu *menu;
1596
1597 menu = [sender menu];
1598 if (menu != nil)
1599 {
1600 /* Unselect the currently selected item */
1601 for (NSMenuItem *item in [menu itemArray]) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001602 if (item.state == NSControlStateValueOn) {
1603 [item setState: NSControlStateValueOff];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001604 break;
1605 }
1606 }
1607 }
1608
1609 // check the menu item
Brendan Shanks5e246002019-01-31 23:12:25 -08001610 [sender setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001611
1612 // get the throttle percentage
1613 throttle_pct = [sender tag];
1614
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001615 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001616 cpu_throttle_set(throttle_pct);
1617 });
John Arbucklee47ec1a2017-06-13 23:17:38 -04001618 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1619}
1620
Programmingkidb4c6a112015-05-19 09:11:18 +01001621@end
bellard5b0753e2005-03-01 21:37:28 +00001622
Peter Maydell61a2ed42019-02-25 10:24:32 +00001623@interface QemuApplication : NSApplication
1624@end
1625
1626@implementation QemuApplication
1627- (void)sendEvent:(NSEvent *)event
1628{
1629 COCOA_DEBUG("QemuApplication: sendEvent\n");
Peter Maydell55888402019-02-25 10:24:33 +00001630 if (![cocoaView handleEvent:event]) {
1631 [super sendEvent: event];
1632 }
Peter Maydell61a2ed42019-02-25 10:24:32 +00001633}
1634@end
1635
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001636static void create_initial_menus(void)
1637{
thsc304f7e2008-01-22 23:25:15 +00001638 // Add menus
1639 NSMenu *menu;
1640 NSMenuItem *menuItem;
1641
bellard5b0753e2005-03-01 21:37:28 +00001642 [NSApp setMainMenu:[[NSMenu alloc] init]];
Akihiko Odaki5b6988c2022-02-14 18:13:20 +09001643 [NSApp setServicesMenu:[[NSMenu alloc] initWithTitle:@"Services"]];
bellard5b0753e2005-03-01 21:37:28 +00001644
thsc304f7e2008-01-22 23:25:15 +00001645 // Application menu
1646 menu = [[NSMenu alloc] initWithTitle:@""];
Programmingkid9e8204b2016-08-15 22:11:06 -04001647 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
thsc304f7e2008-01-22 23:25:15 +00001648 [menu addItem:[NSMenuItem separatorItem]]; //Separator
Akihiko Odaki5b6988c2022-02-14 18:13:20 +09001649 menuItem = [menu addItemWithTitle:@"Services" action:nil keyEquivalent:@""];
1650 [menuItem setSubmenu:[NSApp servicesMenu]];
1651 [menu addItem:[NSMenuItem separatorItem]];
thsc304f7e2008-01-22 23:25:15 +00001652 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1653 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001654 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
thsc304f7e2008-01-22 23:25:15 +00001655 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1656 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1657 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1658 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1659 [menuItem setSubmenu:menu];
1660 [[NSApp mainMenu] addItem:menuItem];
1661 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
ths3b46e622007-09-17 08:09:54 +00001662
John Arbuckle8524f1c2015-06-19 10:53:27 +01001663 // Machine menu
1664 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1665 [menu setAutoenablesItems: NO];
1666 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1667 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1668 [menu addItem: menuItem];
1669 [menuItem setEnabled: NO];
John Arbuckle27074612015-06-19 10:53:27 +01001670 [menu addItem: [NSMenuItem separatorItem]];
1671 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1672 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
John Arbuckle8524f1c2015-06-19 10:53:27 +01001673 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1674 [menuItem setSubmenu:menu];
1675 [[NSApp mainMenu] addItem:menuItem];
1676
thsc304f7e2008-01-22 23:25:15 +00001677 // View menu
1678 menu = [[NSMenu alloc] initWithTitle:@"View"];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001679 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
Carwyn Ellis5ec08982023-10-27 16:49:20 +01001680 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease];
1681 [menuItem setState: stretch_video ? NSControlStateValueOn : NSControlStateValueOff];
1682 [menu addItem: menuItem];
Carwyn Ellise28a9092023-11-10 16:17:29 +00001683 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Zoom Interpolation" action:@selector(toggleZoomInterpolation:) keyEquivalent:@""] autorelease];
1684 [menuItem setState: zoom_interpolation == kCGInterpolationLow ? NSControlStateValueOn : NSControlStateValueOff];
1685 [menu addItem: menuItem];
thsc304f7e2008-01-22 23:25:15 +00001686 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1687 [menuItem setSubmenu:menu];
1688 [[NSApp mainMenu] addItem:menuItem];
1689
John Arbucklee47ec1a2017-06-13 23:17:38 -04001690 // Speed menu
1691 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1692
1693 // Add the rest of the Speed menu items
1694 int p, percentage, throttle_pct;
1695 for (p = 10; p >= 0; p--)
1696 {
1697 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1698
1699 menuItem = [[[NSMenuItem alloc]
1700 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1701
1702 if (percentage == 100) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001703 [menuItem setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001704 }
1705
1706 /* Calculate the throttle percentage */
1707 throttle_pct = -1 * percentage + 100;
1708
1709 [menuItem setTag: throttle_pct];
1710 [menu addItem: menuItem];
1711 }
1712 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1713 [menuItem setSubmenu:menu];
1714 [[NSApp mainMenu] addItem:menuItem];
1715
thsc304f7e2008-01-22 23:25:15 +00001716 // Window menu
1717 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1718 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1719 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1720 [menuItem setSubmenu:menu];
1721 [[NSApp mainMenu] addItem:menuItem];
1722 [NSApp setWindowsMenu:menu];
1723
1724 // Help menu
1725 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1726 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
thsc304f7e2008-01-22 23:25:15 +00001727 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1728 [menuItem setSubmenu:menu];
1729 [[NSApp mainMenu] addItem:menuItem];
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001730}
1731
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001732/* Returns a name for a given console */
1733static NSString * getConsoleName(QemuConsole * console)
1734{
Akihiko Odakica511602022-02-15 09:03:05 +01001735 g_autofree char *label = qemu_console_get_label(console);
1736
1737 return [NSString stringWithUTF8String:label];
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001738}
1739
1740/* Add an entry to the View menu for each console */
1741static void add_console_menu_entries(void)
1742{
1743 NSMenu *menu;
1744 NSMenuItem *menuItem;
1745 int index = 0;
1746
1747 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1748
1749 [menu addItem:[NSMenuItem separatorItem]];
1750
1751 while (qemu_console_lookup_by_index(index) != NULL) {
1752 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1753 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1754 [menuItem setTag: index];
1755 [menu addItem: menuItem];
1756 index++;
1757 }
1758}
1759
1760/* Make menu items for all removable devices.
1761 * Each device is given an 'Eject' and 'Change' menu item.
1762 */
1763static void addRemovableDevicesMenuItems(void)
1764{
1765 NSMenu *menu;
1766 NSMenuItem *menuItem;
1767 BlockInfoList *currentDevice, *pointerToFree;
1768 NSString *deviceName;
1769
1770 currentDevice = qmp_query_block(NULL);
1771 pointerToFree = currentDevice;
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001772
1773 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1774
1775 // Add a separator between related groups of menu items
1776 [menu addItem:[NSMenuItem separatorItem]];
1777
1778 // Set the attributes to the "Removable Media" menu item
1779 NSString *titleString = @"Removable Media";
1780 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1781 NSColor *newColor = [NSColor blackColor];
1782 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1783 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1784 traits:NSBoldFontMask|NSItalicFontMask
1785 weight:0
1786 size:14];
1787 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1788 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1789 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1790
1791 // Add the "Removable Media" menu item
1792 menuItem = [NSMenuItem new];
1793 [menuItem setAttributedTitle: attString];
1794 [menuItem setEnabled: NO];
1795 [menu addItem: menuItem];
1796
1797 /* Loop through all the block devices in the emulator */
1798 while (currentDevice) {
1799 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1800
1801 if(currentDevice->value->removable) {
1802 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1803 action: @selector(changeDeviceMedia:)
1804 keyEquivalent: @""];
1805 [menu addItem: menuItem];
1806 [menuItem setRepresentedObject: deviceName];
1807 [menuItem autorelease];
1808
1809 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1810 action: @selector(ejectDeviceMedia:)
1811 keyEquivalent: @""];
1812 [menu addItem: menuItem];
1813 [menuItem setRepresentedObject: deviceName];
1814 [menuItem autorelease];
1815 }
1816 currentDevice = currentDevice->next;
1817 }
1818 qapi_free_BlockInfoList(pointerToFree);
1819}
1820
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001821@interface QemuCocoaPasteboardTypeOwner : NSObject<NSPasteboardTypeOwner>
1822@end
1823
1824@implementation QemuCocoaPasteboardTypeOwner
1825
1826- (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)type
1827{
1828 if (type != NSPasteboardTypeString) {
1829 return;
1830 }
1831
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001832 with_bql(^{
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001833 QemuClipboardInfo *info = qemu_clipboard_info_ref(cbinfo);
1834 qemu_event_reset(&cbevent);
1835 qemu_clipboard_request(info, QEMU_CLIPBOARD_TYPE_TEXT);
1836
1837 while (info == cbinfo &&
1838 info->types[QEMU_CLIPBOARD_TYPE_TEXT].available &&
1839 info->types[QEMU_CLIPBOARD_TYPE_TEXT].data == NULL) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001840 bql_unlock();
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001841 qemu_event_wait(&cbevent);
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001842 bql_lock();
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001843 }
1844
1845 if (info == cbinfo) {
1846 NSData *data = [[NSData alloc] initWithBytes:info->types[QEMU_CLIPBOARD_TYPE_TEXT].data
1847 length:info->types[QEMU_CLIPBOARD_TYPE_TEXT].size];
1848 [sender setData:data forType:NSPasteboardTypeString];
1849 [data release];
1850 }
1851
1852 qemu_clipboard_info_unref(info);
1853 });
1854}
1855
1856@end
1857
1858static QemuCocoaPasteboardTypeOwner *cbowner;
1859
1860static void cocoa_clipboard_notify(Notifier *notifier, void *data);
1861static void cocoa_clipboard_request(QemuClipboardInfo *info,
1862 QemuClipboardType type);
1863
1864static QemuClipboardPeer cbpeer = {
1865 .name = "cocoa",
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001866 .notifier = { .notify = cocoa_clipboard_notify },
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001867 .request = cocoa_clipboard_request
1868};
1869
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001870static void cocoa_clipboard_update_info(QemuClipboardInfo *info)
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001871{
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001872 if (info->owner == &cbpeer || info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
1873 return;
1874 }
1875
1876 if (info != cbinfo) {
1877 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1878 qemu_clipboard_info_unref(cbinfo);
1879 cbinfo = qemu_clipboard_info_ref(info);
1880 cbchangecount = [[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:cbowner];
1881 [pool release];
1882 }
1883
1884 qemu_event_set(&cbevent);
1885}
1886
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001887static void cocoa_clipboard_notify(Notifier *notifier, void *data)
1888{
1889 QemuClipboardNotify *notify = data;
1890
1891 switch (notify->type) {
1892 case QEMU_CLIPBOARD_UPDATE_INFO:
1893 cocoa_clipboard_update_info(notify->info);
1894 return;
Marc-André Lureau505dbf92021-07-19 19:49:56 +04001895 case QEMU_CLIPBOARD_RESET_SERIAL:
1896 /* ignore */
1897 return;
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001898 }
1899}
1900
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001901static void cocoa_clipboard_request(QemuClipboardInfo *info,
1902 QemuClipboardType type)
1903{
Akihiko Odaki8c0d8022022-06-15 06:21:31 +09001904 NSAutoreleasePool *pool;
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001905 NSData *text;
1906
1907 switch (type) {
1908 case QEMU_CLIPBOARD_TYPE_TEXT:
Akihiko Odaki8c0d8022022-06-15 06:21:31 +09001909 pool = [[NSAutoreleasePool alloc] init];
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001910 text = [[NSPasteboard generalPasteboard] dataForType:NSPasteboardTypeString];
1911 if (text) {
1912 qemu_clipboard_set_data(&cbpeer, info, type,
1913 [text length], [text bytes], true);
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001914 }
Akihiko Odaki8c0d8022022-06-15 06:21:31 +09001915 [pool release];
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001916 break;
1917 default:
1918 break;
1919 }
1920}
1921
Peter Maydell55888402019-02-25 10:24:33 +00001922/*
1923 * The startup process for the OSX/Cocoa UI is complicated, because
1924 * OSX insists that the UI runs on the initial main thread, and so we
Akihiko Odakibab6a302022-08-19 22:27:54 +09001925 * need to start a second thread which runs the qemu_default_main():
Peter Maydell55888402019-02-25 10:24:33 +00001926 * in main():
Akihiko Odakibab6a302022-08-19 22:27:54 +09001927 * in cocoa_display_init():
1928 * assign cocoa_main to qemu_main
1929 * create application, menus, etc
1930 * in cocoa_main():
1931 * create qemu-main thread
1932 * enter OSX run loop
Peter Maydell55888402019-02-25 10:24:33 +00001933 */
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001934
Peter Maydell55888402019-02-25 10:24:33 +00001935static void *call_qemu_main(void *opaque)
1936{
1937 int status;
1938
Akihiko Odakibab6a302022-08-19 22:27:54 +09001939 COCOA_DEBUG("Second thread: calling qemu_default_main()\n");
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001940 bql_lock();
Akihiko Odakibab6a302022-08-19 22:27:54 +09001941 status = qemu_default_main();
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001942 bql_unlock();
Akihiko Odakibab6a302022-08-19 22:27:54 +09001943 COCOA_DEBUG("Second thread: qemu_default_main() returned, exiting\n");
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001944 [cbowner release];
Peter Maydell55888402019-02-25 10:24:33 +00001945 exit(status);
1946}
1947
Philippe Mathieu-Daudéf9750332023-04-23 18:55:28 +02001948static int cocoa_main(void)
Akihiko Odakibab6a302022-08-19 22:27:54 +09001949{
Peter Maydell55888402019-02-25 10:24:33 +00001950 QemuThread thread;
1951
Akihiko Odakibab6a302022-08-19 22:27:54 +09001952 COCOA_DEBUG("Entered %s()\n", __func__);
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001953
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001954 bql_unlock();
Peter Maydell55888402019-02-25 10:24:33 +00001955 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1956 NULL, QEMU_THREAD_DETACHED);
1957
thsc304f7e2008-01-22 23:25:15 +00001958 // Start the main event loop
Peter Maydell55888402019-02-25 10:24:33 +00001959 COCOA_DEBUG("Main thread: entering OSX run loop\n");
bellard5b0753e2005-03-01 21:37:28 +00001960 [NSApp run];
Akihiko Odakibab6a302022-08-19 22:27:54 +09001961 COCOA_DEBUG("Main thread: left OSX run loop, which should never happen\n");
ths3b46e622007-09-17 08:09:54 +00001962
Akihiko Odakibab6a302022-08-19 22:27:54 +09001963 abort();
bellard5b0753e2005-03-01 21:37:28 +00001964}
thsc304f7e2008-01-22 23:25:15 +00001965
1966
1967
1968#pragma mark qemu
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001969static void cocoa_update(DisplayChangeListener *dcl,
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001970 int x, int y, int w, int h)
thsc304f7e2008-01-22 23:25:15 +00001971{
1972 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1973
Peter Maydell55888402019-02-25 10:24:33 +00001974 dispatch_async(dispatch_get_main_queue(), ^{
Akihiko Odakifcb03de2024-02-24 21:43:35 +09001975 NSRect rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
Peter Maydell55888402019-02-25 10:24:33 +00001976 [cocoaView setNeedsDisplayInRect:rect];
1977 });
thsc304f7e2008-01-22 23:25:15 +00001978}
1979
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01001980static void cocoa_switch(DisplayChangeListener *dcl,
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01001981 DisplaySurface *surface)
thsc304f7e2008-01-22 23:25:15 +00001982{
Peter Maydell55888402019-02-25 10:24:33 +00001983 pixman_image_t *image = surface->image;
thsc304f7e2008-01-22 23:25:15 +00001984
Peter Maydell6e657e62013-04-22 10:29:46 +00001985 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
Peter Maydell55888402019-02-25 10:24:33 +00001986
1987 // The DisplaySurface will be freed as soon as this callback returns.
1988 // We take a reference to the underlying pixman image here so it does
1989 // not disappear from under our feet; the switchSurface method will
1990 // deref the old image when it is done with it.
1991 pixman_image_ref(image);
1992
1993 dispatch_async(dispatch_get_main_queue(), ^{
Peter Maydell8d65dee2022-02-24 10:13:29 +00001994 [cocoaView updateUIInfo];
Peter Maydell55888402019-02-25 10:24:33 +00001995 [cocoaView switchSurface:image];
1996 });
thsc304f7e2008-01-22 23:25:15 +00001997}
1998
Gerd Hoffmannbc2ed972013-03-01 13:03:04 +01001999static void cocoa_refresh(DisplayChangeListener *dcl)
thsc304f7e2008-01-22 23:25:15 +00002000{
Peter Maydell6e657e62013-04-22 10:29:46 +00002001 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2002
thsc304f7e2008-01-22 23:25:15 +00002003 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
John Arbuckle468a8952015-10-13 21:51:18 +01002004 graphic_hw_update(NULL);
thsc304f7e2008-01-22 23:25:15 +00002005
Akihiko Odaki0337e412023-09-21 17:29:34 +09002006 if (qemu_input_is_absolute(dcl->con)) {
Peter Maydell55888402019-02-25 10:24:33 +00002007 dispatch_async(dispatch_get_main_queue(), ^{
2008 if (![cocoaView isAbsoluteEnabled]) {
2009 if ([cocoaView isMouseGrabbed]) {
2010 [cocoaView ungrabMouse];
2011 }
thsc304f7e2008-01-22 23:25:15 +00002012 }
Peter Maydell55888402019-02-25 10:24:33 +00002013 [cocoaView setAbsoluteEnabled:YES];
2014 });
thsc304f7e2008-01-22 23:25:15 +00002015 }
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09002016
2017 if (cbchangecount != [[NSPasteboard generalPasteboard] changeCount]) {
2018 qemu_clipboard_info_unref(cbinfo);
2019 cbinfo = qemu_clipboard_info_new(&cbpeer, QEMU_CLIPBOARD_SELECTION_CLIPBOARD);
2020 if ([[NSPasteboard generalPasteboard] availableTypeFromArray:@[NSPasteboardTypeString]]) {
2021 cbinfo->types[QEMU_CLIPBOARD_TYPE_TEXT].available = true;
2022 }
2023 qemu_clipboard_update(cbinfo);
2024 cbchangecount = [[NSPasteboard generalPasteboard] changeCount];
2025 qemu_event_set(&cbevent);
2026 }
2027
Peter Maydell6e657e62013-04-22 10:29:46 +00002028 [pool release];
thsc304f7e2008-01-22 23:25:15 +00002029}
2030
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01002031static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
thsc304f7e2008-01-22 23:25:15 +00002032{
Akihiko Odakibab6a302022-08-19 22:27:54 +09002033 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2034
thsc304f7e2008-01-22 23:25:15 +00002035 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
2036
Akihiko Odakibab6a302022-08-19 22:27:54 +09002037 qemu_main = cocoa_main;
Peter Maydell55888402019-02-25 10:24:33 +00002038
Akihiko Odakibab6a302022-08-19 22:27:54 +09002039 // Pull this console process up to being a fully-fledged graphical
2040 // app with a menubar and Dock icon
2041 ProcessSerialNumber psn = { 0, kCurrentProcess };
2042 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
2043
2044 [QemuApplication sharedApplication];
2045
Akihiko Odakibab6a302022-08-19 22:27:54 +09002046 // Create an Application controller
2047 QemuCocoaAppController *controller = [[QemuCocoaAppController alloc] init];
2048 [NSApp setDelegate:controller];
2049
Programmingkid43227af2015-05-19 09:11:17 +01002050 /* if fullscreen mode is to be used */
Gerd Hoffmann767f9bf2018-02-02 12:10:19 +01002051 if (opts->has_full_screen && opts->full_screen) {
Akihiko Odakibab6a302022-08-19 22:27:54 +09002052 [NSApp activateIgnoringOtherApps: YES];
2053 [controller toggleFullScreen: nil];
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +09002054 }
2055 if (opts->u.cocoa.has_full_grab && opts->u.cocoa.full_grab) {
Akihiko Odakibab6a302022-08-19 22:27:54 +09002056 [controller setFullGrab: nil];
Programmingkid43227af2015-05-19 09:11:17 +01002057 }
Carwyn Ellis69221df2022-01-02 17:41:53 +00002058
Gerd Hoffmann3487da62020-02-06 12:27:50 +01002059 if (opts->has_show_cursor && opts->show_cursor) {
2060 cursor_hide = 0;
2061 }
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +09002062 if (opts->u.cocoa.has_swap_opt_cmd) {
2063 swap_opt_cmd = opts->u.cocoa.swap_opt_cmd;
2064 }
Programmingkid43227af2015-05-19 09:11:17 +01002065
Carwyn Ellis48941a52022-01-02 17:41:52 +00002066 if (opts->u.cocoa.has_left_command_key && !opts->u.cocoa.left_command_key) {
2067 left_command_key_enabled = 0;
2068 }
2069
Carwyn Ellis5ec08982023-10-27 16:49:20 +01002070 if (opts->u.cocoa.has_zoom_to_fit && opts->u.cocoa.zoom_to_fit) {
2071 stretch_video = true;
2072 }
2073
Carwyn Ellise28a9092023-11-10 16:17:29 +00002074 if (opts->u.cocoa.has_zoom_interpolation && opts->u.cocoa.zoom_interpolation) {
2075 zoom_interpolation = kCGInterpolationLow;
2076 }
2077
Carwyn Ellis5ec08982023-10-27 16:49:20 +01002078 create_initial_menus();
2079 /*
2080 * Create the menu entries which depend on QEMU state (for consoles
2081 * and removable devices). These make calls back into QEMU functions,
2082 * which is OK because at this point we know that the second thread
Stefan Hajnoczia4a411f2024-01-02 10:35:28 -05002083 * holds the BQL and is synchronously waiting for us to
Carwyn Ellis5ec08982023-10-27 16:49:20 +01002084 * finish.
2085 */
2086 add_console_menu_entries();
2087 addRemovableDevicesMenuItems();
2088
aliguori9794f742009-03-04 19:25:22 +00002089 // register vga output callbacks
Akihiko Odakicc7859c2021-02-19 17:44:19 +09002090 register_displaychangelistener(&dcl);
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09002091
2092 qemu_event_init(&cbevent, false);
2093 cbowner = [[QemuCocoaPasteboardTypeOwner alloc] init];
2094 qemu_clipboard_peer_register(&cbpeer);
Akihiko Odakibab6a302022-08-19 22:27:54 +09002095
2096 [pool release];
thsc304f7e2008-01-22 23:25:15 +00002097}
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01002098
2099static QemuDisplay qemu_display_cocoa = {
2100 .type = DISPLAY_TYPE_COCOA,
2101 .init = cocoa_display_init,
2102};
2103
2104static void register_cocoa(void)
2105{
2106 qemu_display_register(&qemu_display_cocoa);
2107}
2108
2109type_init(register_cocoa);