blob: eb99064beeb4f95031355659b4ed4e491c89b7e4 [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
Brendan Shanks5e246002019-01-31 23:12:25 -080057/* 10.14 deprecates NSOnState and NSOffState in favor of
58 * NSControlStateValueOn/Off, which were introduced in 10.13.
59 * Define for older versions
60 */
61#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
62#define NSControlStateValueOn NSOnState
63#define NSControlStateValueOff NSOffState
64#endif
bellard5b0753e2005-03-01 21:37:28 +000065
thsc304f7e2008-01-22 23:25:15 +000066//#define DEBUG
67
68#ifdef DEBUG
69#define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
70#else
71#define COCOA_DEBUG(...) ((void) 0)
72#endif
73
74#define cgrect(nsrect) (*(CGRect *)&(nsrect))
thsc304f7e2008-01-22 23:25:15 +000075
Christian Schoenebeck23bdd0d2022-12-27 17:15:31 +010076#define UC_CTRL_KEY "\xe2\x8c\x83"
77#define UC_ALT_KEY "\xe2\x8c\xa5"
78
thsc304f7e2008-01-22 23:25:15 +000079typedef struct {
80 int width;
81 int height;
thsc304f7e2008-01-22 23:25:15 +000082} QEMUScreen;
83
Akihiko Odakicc7859c2021-02-19 17:44:19 +090084static void cocoa_update(DisplayChangeListener *dcl,
85 int x, int y, int w, int h);
86
87static void cocoa_switch(DisplayChangeListener *dcl,
88 DisplaySurface *surface);
89
90static void cocoa_refresh(DisplayChangeListener *dcl);
91
Akihiko Odaki99eb3132022-02-27 13:22:41 +090092static NSWindow *normalWindow;
Akihiko Odakicc7859c2021-02-19 17:44:19 +090093static const DisplayChangeListenerOps dcl_ops = {
94 .dpy_name = "cocoa",
95 .dpy_gfx_update = cocoa_update,
96 .dpy_gfx_switch = cocoa_switch,
97 .dpy_refresh = cocoa_refresh,
98};
99static DisplayChangeListener dcl = {
100 .ops = &dcl_ops,
101};
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100102static int last_buttons;
Gerd Hoffmann3487da62020-02-06 12:27:50 +0100103static int cursor_hide = 1;
Carwyn Ellis48941a52022-01-02 17:41:52 +0000104static int left_command_key_enabled = 1;
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900105static bool swap_opt_cmd;
bellard5b0753e2005-03-01 21:37:28 +0000106
Akihiko Odakicb823402021-02-25 17:42:02 +0900107static bool stretch_video;
108static NSTextField *pauseLabel;
bellard5b0753e2005-03-01 21:37:28 +0000109
Hikaru Nishidadff742a2019-10-15 10:07:34 +0900110static bool allow_events;
Peter Maydell55888402019-02-25 10:24:33 +0000111
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +0900112static NSInteger cbchangecount = -1;
113static QemuClipboardInfo *cbinfo;
114static QemuEvent cbevent;
115
Stefan Hajnoczia4a411f2024-01-02 10:35:28 -0500116// Utility functions to run specified code block with the BQL held
Peter Maydell31819e92019-02-25 10:24:27 +0000117typedef void (^CodeBlock)(void);
Peter Maydell60105d72019-02-25 10:24:31 +0000118typedef bool (^BoolCodeBlock)(void);
Peter Maydell31819e92019-02-25 10:24:27 +0000119
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500120static void with_bql(CodeBlock block)
Peter Maydell31819e92019-02-25 10:24:27 +0000121{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500122 bool locked = bql_locked();
Peter Maydell31819e92019-02-25 10:24:27 +0000123 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500124 bql_lock();
Peter Maydell31819e92019-02-25 10:24:27 +0000125 }
126 block();
127 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500128 bql_unlock();
Peter Maydell31819e92019-02-25 10:24:27 +0000129 }
130}
131
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500132static bool bool_with_bql(BoolCodeBlock block)
Peter Maydell60105d72019-02-25 10:24:31 +0000133{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500134 bool locked = bql_locked();
Peter Maydell60105d72019-02-25 10:24:31 +0000135 bool val;
136
137 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500138 bql_lock();
Peter Maydell60105d72019-02-25 10:24:31 +0000139 }
140 val = block();
141 if (!locked) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500142 bql_unlock();
Peter Maydell60105d72019-02-25 10:24:31 +0000143 }
144 return val;
145}
146
John Arbuckleaaac7142016-03-23 14:26:18 +0000147// Mac to QKeyCode conversion
Akihiko Odakicb823402021-02-25 17:42:02 +0900148static const int mac_to_qkeycode_map[] = {
John Arbuckleaaac7142016-03-23 14:26:18 +0000149 [kVK_ANSI_A] = Q_KEY_CODE_A,
150 [kVK_ANSI_B] = Q_KEY_CODE_B,
151 [kVK_ANSI_C] = Q_KEY_CODE_C,
152 [kVK_ANSI_D] = Q_KEY_CODE_D,
153 [kVK_ANSI_E] = Q_KEY_CODE_E,
154 [kVK_ANSI_F] = Q_KEY_CODE_F,
155 [kVK_ANSI_G] = Q_KEY_CODE_G,
156 [kVK_ANSI_H] = Q_KEY_CODE_H,
157 [kVK_ANSI_I] = Q_KEY_CODE_I,
158 [kVK_ANSI_J] = Q_KEY_CODE_J,
159 [kVK_ANSI_K] = Q_KEY_CODE_K,
160 [kVK_ANSI_L] = Q_KEY_CODE_L,
161 [kVK_ANSI_M] = Q_KEY_CODE_M,
162 [kVK_ANSI_N] = Q_KEY_CODE_N,
163 [kVK_ANSI_O] = Q_KEY_CODE_O,
164 [kVK_ANSI_P] = Q_KEY_CODE_P,
165 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
166 [kVK_ANSI_R] = Q_KEY_CODE_R,
167 [kVK_ANSI_S] = Q_KEY_CODE_S,
168 [kVK_ANSI_T] = Q_KEY_CODE_T,
169 [kVK_ANSI_U] = Q_KEY_CODE_U,
170 [kVK_ANSI_V] = Q_KEY_CODE_V,
171 [kVK_ANSI_W] = Q_KEY_CODE_W,
172 [kVK_ANSI_X] = Q_KEY_CODE_X,
173 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
174 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
ths3b46e622007-09-17 08:09:54 +0000175
John Arbuckleaaac7142016-03-23 14:26:18 +0000176 [kVK_ANSI_0] = Q_KEY_CODE_0,
177 [kVK_ANSI_1] = Q_KEY_CODE_1,
178 [kVK_ANSI_2] = Q_KEY_CODE_2,
179 [kVK_ANSI_3] = Q_KEY_CODE_3,
180 [kVK_ANSI_4] = Q_KEY_CODE_4,
181 [kVK_ANSI_5] = Q_KEY_CODE_5,
182 [kVK_ANSI_6] = Q_KEY_CODE_6,
183 [kVK_ANSI_7] = Q_KEY_CODE_7,
184 [kVK_ANSI_8] = Q_KEY_CODE_8,
185 [kVK_ANSI_9] = Q_KEY_CODE_9,
186
187 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
188 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
189 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
190 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
191 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
192 [kVK_Tab] = Q_KEY_CODE_TAB,
193 [kVK_Return] = Q_KEY_CODE_RET,
194 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
195 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
196 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
197 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
198 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
199 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
200 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
201 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
John Arbuckleaaac7142016-03-23 14:26:18 +0000202 [kVK_Space] = Q_KEY_CODE_SPC,
203
204 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
205 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
206 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
207 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
208 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
209 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
210 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
211 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
212 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
213 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
214 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
215 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
216 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
217 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
218 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
219 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
220 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
221 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
222
223 [kVK_UpArrow] = Q_KEY_CODE_UP,
224 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
225 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
226 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
227
228 [kVK_Help] = Q_KEY_CODE_INSERT,
229 [kVK_Home] = Q_KEY_CODE_HOME,
230 [kVK_PageUp] = Q_KEY_CODE_PGUP,
231 [kVK_PageDown] = Q_KEY_CODE_PGDN,
232 [kVK_End] = Q_KEY_CODE_END,
233 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
234
235 [kVK_Escape] = Q_KEY_CODE_ESC,
236
237 /* The Power key can't be used directly because the operating system uses
238 * it. This key can be emulated by using it in place of another key such as
239 * F1. Don't forget to disable the real key binding.
240 */
241 /* [kVK_F1] = Q_KEY_CODE_POWER, */
242
243 [kVK_F1] = Q_KEY_CODE_F1,
244 [kVK_F2] = Q_KEY_CODE_F2,
245 [kVK_F3] = Q_KEY_CODE_F3,
246 [kVK_F4] = Q_KEY_CODE_F4,
247 [kVK_F5] = Q_KEY_CODE_F5,
248 [kVK_F6] = Q_KEY_CODE_F6,
249 [kVK_F7] = Q_KEY_CODE_F7,
250 [kVK_F8] = Q_KEY_CODE_F8,
251 [kVK_F9] = Q_KEY_CODE_F9,
252 [kVK_F10] = Q_KEY_CODE_F10,
253 [kVK_F11] = Q_KEY_CODE_F11,
254 [kVK_F12] = Q_KEY_CODE_F12,
255 [kVK_F13] = Q_KEY_CODE_PRINT,
256 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
257 [kVK_F15] = Q_KEY_CODE_PAUSE,
258
Akihiko Odaki708b7252021-02-12 09:04:04 +0900259 // JIS keyboards only
260 [kVK_JIS_Yen] = Q_KEY_CODE_YEN,
261 [kVK_JIS_Underscore] = Q_KEY_CODE_RO,
262 [kVK_JIS_KeypadComma] = Q_KEY_CODE_KP_COMMA,
263 [kVK_JIS_Eisu] = Q_KEY_CODE_MUHENKAN,
264 [kVK_JIS_Kana] = Q_KEY_CODE_HENKAN,
265
John Arbuckleaaac7142016-03-23 14:26:18 +0000266 /*
267 * The eject and volume keys can't be used here because they are handled at
268 * a lower level than what an Application can see.
269 */
bellard5b0753e2005-03-01 21:37:28 +0000270};
271
Andreas Färber77047bb2009-12-13 00:55:53 +0100272static int cocoa_keycode_to_qemu(int keycode)
bellard5b0753e2005-03-01 21:37:28 +0000273{
John Arbuckleaaac7142016-03-23 14:26:18 +0000274 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
Akihiko Odaki43137392021-02-23 22:11:06 +0900275 error_report("(cocoa) warning unknown keycode 0x%x", keycode);
bellard5b0753e2005-03-01 21:37:28 +0000276 return 0;
277 }
John Arbuckleaaac7142016-03-23 14:26:18 +0000278 return mac_to_qkeycode_map[keycode];
bellard5b0753e2005-03-01 21:37:28 +0000279}
280
John Arbuckle693a3e02015-06-19 10:53:27 +0100281/* Displays an alert dialog box with the specified message */
282static void QEMU_Alert(NSString *message)
283{
284 NSAlert *alert;
285 alert = [NSAlert new];
286 [alert setMessageText: message];
287 [alert runModal];
288}
thsc304f7e2008-01-22 23:25:15 +0000289
John Arbuckle693a3e02015-06-19 10:53:27 +0100290/* Handles any errors that happen with a device transaction */
291static void handleAnyDeviceErrors(Error * err)
292{
293 if (err) {
294 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
295 encoding: NSASCIIStringEncoding]);
296 error_free(err);
297 }
298}
thsc304f7e2008-01-22 23:25:15 +0000299
bellard5b0753e2005-03-01 21:37:28 +0000300/*
301 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +0000302 QemuCocoaView
bellard5b0753e2005-03-01 21:37:28 +0000303 ------------------------------------------------------
304*/
thsc304f7e2008-01-22 23:25:15 +0000305@interface QemuCocoaView : NSView
bellard5b0753e2005-03-01 21:37:28 +0000306{
thsc304f7e2008-01-22 23:25:15 +0000307 QEMUScreen screen;
308 NSWindow *fullScreenWindow;
309 float cx,cy,cw,ch,cdx,cdy;
Peter Maydell55888402019-02-25 10:24:33 +0000310 pixman_image_t *pixman_image;
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900311 QKbdState *kbd;
Peter Maydell49b9bd42013-12-08 22:59:03 +0000312 BOOL isMouseGrabbed;
thsc304f7e2008-01-22 23:25:15 +0000313 BOOL isFullscreen;
314 BOOL isAbsoluteEnabled;
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900315 CFMachPortRef eventsTap;
thsc304f7e2008-01-22 23:25:15 +0000316}
Peter Maydell72a3e312019-02-25 10:24:28 +0000317- (void) switchSurface:(pixman_image_t *)image;
thsc304f7e2008-01-22 23:25:15 +0000318- (void) grabMouse;
319- (void) ungrabMouse;
320- (void) toggleFullScreen:(id)sender;
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900321- (void) setFullGrab:(id)sender;
John Arbuckle9c3a4182017-11-07 10:14:14 +0000322- (void) handleMonitorInput:(NSEvent *)event;
Peter Maydell60105d72019-02-25 10:24:31 +0000323- (bool) handleEvent:(NSEvent *)event;
324- (bool) handleEventLocked:(NSEvent *)event;
thsc304f7e2008-01-22 23:25:15 +0000325- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
Peter Maydellf61c3872014-06-23 10:35:24 +0100326/* The state surrounding mouse grabbing is potentially confusing.
327 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
328 * pointing device an absolute-position one?"], but is only updated on
329 * next refresh.
330 * isMouseGrabbed tracks whether GUI events are directed to the guest;
331 * it controls whether special keys like Cmd get sent to the guest,
332 * and whether we capture the mouse when in non-absolute mode.
Peter Maydellf61c3872014-06-23 10:35:24 +0100333 */
Peter Maydell49b9bd42013-12-08 22:59:03 +0000334- (BOOL) isMouseGrabbed;
thsc304f7e2008-01-22 23:25:15 +0000335- (BOOL) isAbsoluteEnabled;
336- (float) cdx;
337- (float) cdy;
338- (QEMUScreen) gscreen;
John Arbuckle3b178b72015-09-25 23:14:00 +0100339- (void) raiseAllKeys;
thsc304f7e2008-01-22 23:25:15 +0000340@end
ths3b46e622007-09-17 08:09:54 +0000341
Andreas Färber7fee1992011-06-09 20:53:32 +0200342QemuCocoaView *cocoaView;
343
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900344static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEventRef cgEvent, void *userInfo)
345{
Philippe Mathieu-Daudé21eb7522023-10-04 14:00:13 +0200346 QemuCocoaView *view = userInfo;
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900347 NSEvent *event = [NSEvent eventWithCGEvent:cgEvent];
Philippe Mathieu-Daudé21eb7522023-10-04 14:00:13 +0200348 if ([view isMouseGrabbed] && [view handleEvent:event]) {
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900349 COCOA_DEBUG("Global events tap: qemu handled the event, capturing!\n");
350 return NULL;
351 }
352 COCOA_DEBUG("Global events tap: qemu did not handle the event, letting it through...\n");
353
354 return cgEvent;
355}
356
thsc304f7e2008-01-22 23:25:15 +0000357@implementation QemuCocoaView
358- (id)initWithFrame:(NSRect)frameRect
359{
360 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
ths3b46e622007-09-17 08:09:54 +0000361
thsc304f7e2008-01-22 23:25:15 +0000362 self = [super initWithFrame:frameRect];
363 if (self) {
pbrook95219892006-04-09 01:06:34 +0000364
thsc304f7e2008-01-22 23:25:15 +0000365 screen.width = frameRect.size.width;
366 screen.height = frameRect.size.height;
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900367 kbd = qkbd_state_init(dcl.con);
bellard7c206a72005-12-18 19:18:45 +0000368
thsc304f7e2008-01-22 23:25:15 +0000369 }
370 return self;
371}
bellard7c206a72005-12-18 19:18:45 +0000372
thsc304f7e2008-01-22 23:25:15 +0000373- (void) dealloc
374{
375 COCOA_DEBUG("QemuCocoaView: dealloc\n");
bellard7c206a72005-12-18 19:18:45 +0000376
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900377 if (pixman_image) {
Peter Maydell55888402019-02-25 10:24:33 +0000378 pixman_image_unref(pixman_image);
379 }
ths3b46e622007-09-17 08:09:54 +0000380
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900381 qkbd_state_free(kbd);
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900382
383 if (eventsTap) {
384 CFRelease(eventsTap);
385 }
386
thsc304f7e2008-01-22 23:25:15 +0000387 [super dealloc];
388}
bellard5cbfcd02006-06-14 15:53:24 +0000389
Andreas Färberd50f71d2009-12-13 02:03:33 +0100390- (BOOL) isOpaque
391{
392 return YES;
393}
394
Peter Maydell5dd45be2014-06-23 10:35:23 +0100395- (BOOL) screenContainsPoint:(NSPoint) p
396{
397 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
398}
399
Chen Zhang2044dff2019-06-04 17:36:00 +0800400/* Get location of event and convert to virtual screen coordinate */
401- (CGPoint) screenLocationOfEvent:(NSEvent *)ev
402{
403 NSWindow *eventWindow = [ev window];
404 // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
405 CGRect r = CGRectZero;
406 r.origin = [ev locationInWindow];
407 if (!eventWindow) {
408 if (!isFullscreen) {
409 return [[self window] convertRectFromScreen:r].origin;
410 } else {
411 CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
412 CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
413 if (stretch_video) {
414 loc.x /= cdx;
415 loc.y /= cdy;
416 }
417 return loc;
418 }
419 } else if ([[self window] isEqual:eventWindow]) {
420 if (!isFullscreen) {
421 return r.origin;
422 } else {
423 CGPoint loc = [self convertPoint:r.origin fromView:nil];
424 if (stretch_video) {
425 loc.x /= cdx;
426 loc.y /= cdy;
427 }
428 return loc;
429 }
430 } else {
431 return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
432 }
433}
434
Peter Maydell13aefd32014-06-23 10:35:25 +0100435- (void) hideCursor
436{
437 if (!cursor_hide) {
438 return;
439 }
440 [NSCursor hide];
441}
442
443- (void) unhideCursor
444{
445 if (!cursor_hide) {
446 return;
447 }
448 [NSCursor unhide];
449}
450
thsc304f7e2008-01-22 23:25:15 +0000451- (void) drawRect:(NSRect) rect
452{
453 COCOA_DEBUG("QemuCocoaView: drawRect\n");
bellard5cbfcd02006-06-14 15:53:24 +0000454
thsc304f7e2008-01-22 23:25:15 +0000455 // get CoreGraphic context
Brendan Shanks5e246002019-01-31 23:12:25 -0800456 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
Brendan Shanks5e246002019-01-31 23:12:25 -0800457
thsc304f7e2008-01-22 23:25:15 +0000458 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
459 CGContextSetShouldAntialias (viewContextRef, NO);
ths3b46e622007-09-17 08:09:54 +0000460
thsc304f7e2008-01-22 23:25:15 +0000461 // draw screen bitmap directly to Core Graphics context
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900462 if (!pixman_image) {
Peter Maydell7d270b12013-12-24 02:51:47 +0000463 // Draw request before any guest device has set up a framebuffer:
464 // just draw an opaque black rectangle
465 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
466 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
467 } else {
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900468 int w = pixman_image_get_width(pixman_image);
469 int h = pixman_image_get_height(pixman_image);
470 int bitsPerPixel = PIXMAN_FORMAT_BPP(pixman_image_get_format(pixman_image));
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900471 int stride = pixman_image_get_stride(pixman_image);
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900472 CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(
473 NULL,
474 pixman_image_get_data(pixman_image),
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900475 stride * h,
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900476 NULL
477 );
thsc304f7e2008-01-22 23:25:15 +0000478 CGImageRef imageRef = CGImageCreate(
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900479 w, //width
480 h, //height
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900481 DIV_ROUND_UP(bitsPerPixel, 8) * 2, //bitsPerComponent
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900482 bitsPerPixel, //bitsPerPixel
Akihiko Odakid9c32b82021-02-22 23:40:12 +0900483 stride, //bytesPerRow
Akihiko Odakiae57d352021-03-05 21:13:04 +0900484 CGColorSpaceCreateWithName(kCGColorSpaceSRGB), //colorspace
485 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst, //bitmapInfo
thsc304f7e2008-01-22 23:25:15 +0000486 dataProviderRef, //provider
487 NULL, //decode
488 0, //interpolate
489 kCGRenderingIntentDefault //intent
490 );
Peter Maydellb63901d2015-05-19 09:11:17 +0100491 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
492 const NSRect *rectList;
Peter Maydellb63901d2015-05-19 09:11:17 +0100493 NSInteger rectCount;
Peter Maydellb63901d2015-05-19 09:11:17 +0100494 int i;
495 CGImageRef clipImageRef;
496 CGRect clipRect;
ths3b46e622007-09-17 08:09:54 +0000497
Peter Maydellb63901d2015-05-19 09:11:17 +0100498 [self getRectsBeingDrawn:&rectList count:&rectCount];
499 for (i = 0; i < rectCount; i++) {
500 clipRect.origin.x = rectList[i].origin.x / cdx;
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900501 clipRect.origin.y = (float)h - (rectList[i].origin.y + rectList[i].size.height) / cdy;
Peter Maydellb63901d2015-05-19 09:11:17 +0100502 clipRect.size.width = rectList[i].size.width / cdx;
503 clipRect.size.height = rectList[i].size.height / cdy;
504 clipImageRef = CGImageCreateWithImageInRect(
505 imageRef,
506 clipRect
507 );
508 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
509 CGImageRelease (clipImageRef);
bellard5b0753e2005-03-01 21:37:28 +0000510 }
thsc304f7e2008-01-22 23:25:15 +0000511 CGImageRelease (imageRef);
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900512 CGDataProviderRelease(dataProviderRef);
bellard5b0753e2005-03-01 21:37:28 +0000513 }
514}
515
thsc304f7e2008-01-22 23:25:15 +0000516- (void) setContentDimensions
bellard5b0753e2005-03-01 21:37:28 +0000517{
thsc304f7e2008-01-22 23:25:15 +0000518 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
ths3b46e622007-09-17 08:09:54 +0000519
thsc304f7e2008-01-22 23:25:15 +0000520 if (isFullscreen) {
521 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
522 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100523
524 /* stretches video, but keeps same aspect ratio */
525 if (stretch_video == true) {
526 /* use smallest stretch value - prevents clipping on sides */
527 if (MIN(cdx, cdy) == cdx) {
528 cdy = cdx;
529 } else {
530 cdx = cdy;
531 }
532 } else { /* No stretching */
533 cdx = cdy = 1;
534 }
thsc304f7e2008-01-22 23:25:15 +0000535 cw = screen.width * cdx;
536 ch = screen.height * cdy;
537 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
538 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
539 } else {
540 cx = 0;
541 cy = 0;
542 cw = screen.width;
543 ch = screen.height;
544 cdx = 1.0;
545 cdy = 1.0;
546 }
bellard5b0753e2005-03-01 21:37:28 +0000547}
548
Peter Maydell8d65dee2022-02-24 10:13:29 +0000549- (void) updateUIInfoLocked
Akihiko Odaki15280e82021-06-16 23:19:10 +0900550{
Stefan Hajnoczia4a411f2024-01-02 10:35:28 -0500551 /* Must be called with the BQL, i.e. via updateUIInfo */
Akihiko Odaki15280e82021-06-16 23:19:10 +0900552 NSSize frameSize;
553 QemuUIInfo info;
554
555 if (!qemu_console_is_graphic(dcl.con)) {
556 return;
557 }
558
559 if ([self window]) {
560 NSDictionary *description = [[[self window] screen] deviceDescription];
561 CGDirectDisplayID display = [[description objectForKey:@"NSScreenNumber"] unsignedIntValue];
562 NSSize screenSize = [[[self window] screen] frame].size;
563 CGSize screenPhysicalSize = CGDisplayScreenSize(display);
Akihiko Odaki52eaefd2022-07-02 23:25:19 +0900564 CVDisplayLinkRef displayLink;
Akihiko Odaki15280e82021-06-16 23:19:10 +0900565
566 frameSize = isFullscreen ? screenSize : [self frame].size;
Akihiko Odaki52eaefd2022-07-02 23:25:19 +0900567
568 if (!CVDisplayLinkCreateWithCGDisplay(display, &displayLink)) {
569 CVTime period = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLink);
570 CVDisplayLinkRelease(displayLink);
571 if (!(period.flags & kCVTimeIsIndefinite)) {
572 update_displaychangelistener(&dcl,
573 1000 * period.timeValue / period.timeScale);
574 info.refresh_rate = (int64_t)1000 * period.timeScale / period.timeValue;
575 }
576 }
577
Akihiko Odaki15280e82021-06-16 23:19:10 +0900578 info.width_mm = frameSize.width / screenSize.width * screenPhysicalSize.width;
579 info.height_mm = frameSize.height / screenSize.height * screenPhysicalSize.height;
580 } else {
581 frameSize = [self frame].size;
582 info.width_mm = 0;
583 info.height_mm = 0;
584 }
585
586 info.xoff = 0;
587 info.yoff = 0;
588 info.width = frameSize.width;
589 info.height = frameSize.height;
590
Marc-André Lureauca19ef52021-04-13 20:39:11 +0400591 dpy_set_ui_info(dcl.con, &info, TRUE);
Akihiko Odaki15280e82021-06-16 23:19:10 +0900592}
593
Peter Maydell8d65dee2022-02-24 10:13:29 +0000594- (void) updateUIInfo
595{
596 if (!allow_events) {
597 /*
598 * Don't try to tell QEMU about UI information in the application
599 * startup phase -- we haven't yet registered dcl with the QEMU UI
Akihiko Odakibab6a302022-08-19 22:27:54 +0900600 * layer.
Peter Maydell8d65dee2022-02-24 10:13:29 +0000601 * When cocoa_display_init() does register the dcl, the UI layer
602 * will call cocoa_switch(), which will call updateUIInfo, so
603 * we don't lose any information here.
604 */
605 return;
606 }
607
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500608 with_bql(^{
Peter Maydell8d65dee2022-02-24 10:13:29 +0000609 [self updateUIInfoLocked];
610 });
611}
612
Akihiko Odaki15280e82021-06-16 23:19:10 +0900613- (void)viewDidMoveToWindow
614{
615 [self updateUIInfo];
616}
617
Peter Maydell72a3e312019-02-25 10:24:28 +0000618- (void) switchSurface:(pixman_image_t *)image
thsc304f7e2008-01-22 23:25:15 +0000619{
Gerd Hoffmann5e00d3a2013-03-01 12:52:06 +0100620 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
thsc304f7e2008-01-22 23:25:15 +0000621
Peter Maydell72a3e312019-02-25 10:24:28 +0000622 int w = pixman_image_get_width(image);
623 int h = pixman_image_get_height(image);
Peter Maydell381600d2014-06-23 10:35:22 +0100624 /* cdx == 0 means this is our very first surface, in which case we need
625 * to recalculate the content dimensions even if it happens to be the size
626 * of the initial empty window.
627 */
628 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
Peter Maydelld3345a02013-12-24 02:51:46 +0000629
630 int oldh = screen.height;
631 if (isResize) {
632 // Resize before we trigger the redraw, or we'll redraw at the wrong size
633 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
634 screen.width = w;
635 screen.height = h;
636 [self setContentDimensions];
637 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
638 }
Peter Maydell8510d912013-03-18 20:28:21 +0000639
thsc304f7e2008-01-22 23:25:15 +0000640 // update screenBuffer
Akihiko Odakic0ff29d2021-02-12 09:06:29 +0900641 if (pixman_image) {
Peter Maydell55888402019-02-25 10:24:33 +0000642 pixman_image_unref(pixman_image);
643 }
thsc304f7e2008-01-22 23:25:15 +0000644
Peter Maydell55888402019-02-25 10:24:33 +0000645 pixman_image = image;
thsc304f7e2008-01-22 23:25:15 +0000646
647 // update windows
648 if (isFullscreen) {
649 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
Peter Maydelld3345a02013-12-24 02:51:46 +0000650 [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 +0000651 } else {
652 if (qemu_name)
653 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
Peter Maydelld3345a02013-12-24 02:51:46 +0000654 [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 +0000655 }
Peter Maydelld3345a02013-12-24 02:51:46 +0000656
657 if (isResize) {
658 [normalWindow center];
659 }
thsc304f7e2008-01-22 23:25:15 +0000660}
661
662- (void) toggleFullScreen:(id)sender
663{
664 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
665
666 if (isFullscreen) { // switch from fullscreen to desktop
667 isFullscreen = FALSE;
668 [self ungrabMouse];
669 [self setContentDimensions];
Akihiko Odaki1e8b6f22021-02-20 10:31:38 +0900670 [fullScreenWindow close];
671 [normalWindow setContentView: self];
672 [normalWindow makeKeyAndOrderFront: self];
673 [NSMenu setMenuBarVisible:YES];
thsc304f7e2008-01-22 23:25:15 +0000674 } else { // switch from desktop to fullscreen
675 isFullscreen = TRUE;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100676 [normalWindow orderOut: nil]; /* Hide the window */
thsc304f7e2008-01-22 23:25:15 +0000677 [self grabMouse];
678 [self setContentDimensions];
Akihiko Odaki1e8b6f22021-02-20 10:31:38 +0900679 [NSMenu setMenuBarVisible:NO];
680 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
681 styleMask:NSWindowStyleMaskBorderless
682 backing:NSBackingStoreBuffered
683 defer:NO];
684 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
685 [fullScreenWindow setHasShadow:NO];
686 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
687 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
688 [[fullScreenWindow contentView] addSubview: self];
689 [fullScreenWindow makeKeyAndOrderFront:self];
thsc304f7e2008-01-22 23:25:15 +0000690 }
691}
692
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +0900693- (void) setFullGrab:(id)sender
694{
695 COCOA_DEBUG("QemuCocoaView: setFullGrab\n");
696
697 CGEventMask mask = CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp) | CGEventMaskBit(kCGEventFlagsChanged);
698 eventsTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault,
699 mask, handleTapEvent, self);
700 if (!eventsTap) {
701 warn_report("Could not create event tap, system key combos will not be captured.\n");
702 return;
703 } else {
704 COCOA_DEBUG("Global events tap created! Will capture system key combos.\n");
705 }
706
707 CFRunLoopRef runLoop = CFRunLoopGetCurrent();
708 if (!runLoop) {
709 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
710 return;
711 }
712
713 CFRunLoopSourceRef tapEventsSrc = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventsTap, 0);
714 if (!tapEventsSrc ) {
715 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
716 return;
717 }
718
719 CFRunLoopAddSource(runLoop, tapEventsSrc, kCFRunLoopDefaultMode);
720 CFRelease(tapEventsSrc);
721}
722
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900723- (void) toggleKey: (int)keycode {
724 qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode));
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700725}
726
John Arbuckle9c3a4182017-11-07 10:14:14 +0000727// Does the work of sending input to the monitor
728- (void) handleMonitorInput:(NSEvent *)event
729{
730 int keysym = 0;
731 int control_key = 0;
732
733 // if the control key is down
734 if ([event modifierFlags] & NSEventModifierFlagControl) {
735 control_key = 1;
736 }
737
738 /* translates Macintosh keycodes to QEMU's keysym */
739
Philippe Mathieu-Daudé94592622022-02-15 16:21:14 +0100740 static const int without_control_translation[] = {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000741 [0 ... 0xff] = 0, // invalid key
742
743 [kVK_UpArrow] = QEMU_KEY_UP,
744 [kVK_DownArrow] = QEMU_KEY_DOWN,
745 [kVK_RightArrow] = QEMU_KEY_RIGHT,
746 [kVK_LeftArrow] = QEMU_KEY_LEFT,
747 [kVK_Home] = QEMU_KEY_HOME,
748 [kVK_End] = QEMU_KEY_END,
749 [kVK_PageUp] = QEMU_KEY_PAGEUP,
750 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
751 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
752 [kVK_Delete] = QEMU_KEY_BACKSPACE,
753 };
754
Philippe Mathieu-Daudé94592622022-02-15 16:21:14 +0100755 static const int with_control_translation[] = {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000756 [0 ... 0xff] = 0, // invalid key
757
758 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
759 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
760 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
761 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
762 [kVK_Home] = QEMU_KEY_CTRL_HOME,
763 [kVK_End] = QEMU_KEY_CTRL_END,
764 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
765 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
766 };
767
768 if (control_key != 0) { /* If the control key is being used */
769 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
770 keysym = with_control_translation[[event keyCode]];
771 }
772 } else {
773 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
774 keysym = without_control_translation[[event keyCode]];
775 }
776 }
777
778 // if not a key that needs translating
779 if (keysym == 0) {
780 NSString *ks = [event characters];
781 if ([ks length] > 0) {
782 keysym = [ks characterAtIndex:0];
783 }
784 }
785
786 if (keysym) {
Marc-André Lureaucc6ba2c2023-08-30 13:38:20 +0400787 qemu_text_console_put_keysym(NULL, keysym);
John Arbuckle9c3a4182017-11-07 10:14:14 +0000788 }
789}
790
Peter Maydell60105d72019-02-25 10:24:31 +0000791- (bool) handleEvent:(NSEvent *)event
thsc304f7e2008-01-22 23:25:15 +0000792{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -0500793 return bool_with_bql(^{
Peter Maydell60105d72019-02-25 10:24:31 +0000794 return [self handleEventLocked:event];
Peter Maydell31819e92019-02-25 10:24:27 +0000795 });
796}
thsc304f7e2008-01-22 23:25:15 +0000797
Peter Maydell60105d72019-02-25 10:24:31 +0000798- (bool) handleEventLocked:(NSEvent *)event
Peter Maydell31819e92019-02-25 10:24:27 +0000799{
Peter Maydell60105d72019-02-25 10:24:31 +0000800 /* Return true if we handled the event, false if it should be given to OSX */
Peter Maydell31819e92019-02-25 10:24:27 +0000801 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
thsc304f7e2008-01-22 23:25:15 +0000802 int buttons = 0;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700803 int keycode = 0;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100804 bool mouse_event = false;
Chen Zhang2044dff2019-06-04 17:36:00 +0800805 // Location of event in virtual screen coordinates
806 NSPoint p = [self screenLocationOfEvent:event];
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900807 NSUInteger modifiers = [event modifierFlags];
808
Akihiko Odakiad7f2f82021-03-12 22:32:12 +0900809 /*
810 * Check -[NSEvent modifierFlags] here.
811 *
812 * There is a NSEventType for an event notifying the change of
813 * -[NSEvent modifierFlags], NSEventTypeFlagsChanged but these operations
814 * are performed for any events because a modifier state may change while
815 * the application is inactive (i.e. no events fire) and we don't want to
816 * wait for another modifier state change to detect such a change.
817 *
818 * NSEventModifierFlagCapsLock requires a special treatment. The other flags
819 * are handled in similar manners.
820 *
821 * NSEventModifierFlagCapsLock
822 * ---------------------------
823 *
824 * If CapsLock state is changed, "up" and "down" events will be fired in
825 * sequence, effectively updates CapsLock state on the guest.
826 *
827 * The other flags
828 * ---------------
829 *
830 * If a flag is not set, fire "up" events for all keys which correspond to
831 * the flag. Note that "down" events are not fired here because the flags
832 * checked here do not tell what exact keys are down.
833 *
834 * If one of the keys corresponding to a flag is down, we rely on
835 * -[NSEvent keyCode] of an event whose -[NSEvent type] is
836 * NSEventTypeFlagsChanged to know the exact key which is down, which has
837 * the following two downsides:
838 * - It does not work when the application is inactive as described above.
839 * - It malfactions *after* the modifier state is changed while the
840 * application is inactive. It is because -[NSEvent keyCode] does not tell
841 * if the key is up or down, and requires to infer the current state from
842 * the previous state. It is still possible to fix such a malfanction by
843 * completely leaving your hands from the keyboard, which hopefully makes
844 * this implementation usable enough.
845 */
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900846 if (!!(modifiers & NSEventModifierFlagCapsLock) !=
847 qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) {
848 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true);
849 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false);
850 }
851
852 if (!(modifiers & NSEventModifierFlagShift)) {
853 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false);
854 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false);
855 }
856 if (!(modifiers & NSEventModifierFlagControl)) {
857 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false);
858 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false);
859 }
860 if (!(modifiers & NSEventModifierFlagOption)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900861 if (swap_opt_cmd) {
862 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
863 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
864 } else {
865 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
866 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
867 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900868 }
869 if (!(modifiers & NSEventModifierFlagCommand)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900870 if (swap_opt_cmd) {
871 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
872 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
873 } else {
874 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
875 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
876 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900877 }
thsc304f7e2008-01-22 23:25:15 +0000878
879 switch ([event type]) {
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700880 case NSEventTypeFlagsChanged:
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900881 switch ([event keyCode]) {
882 case kVK_Shift:
883 if (!!(modifiers & NSEventModifierFlagShift)) {
884 [self toggleKey:Q_KEY_CODE_SHIFT];
885 }
886 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700887
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900888 case kVK_RightShift:
889 if (!!(modifiers & NSEventModifierFlagShift)) {
890 [self toggleKey:Q_KEY_CODE_SHIFT_R];
891 }
892 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700893
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900894 case kVK_Control:
895 if (!!(modifiers & NSEventModifierFlagControl)) {
896 [self toggleKey:Q_KEY_CODE_CTRL];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700897 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900898 break;
899
900 case kVK_RightControl:
901 if (!!(modifiers & NSEventModifierFlagControl)) {
902 [self toggleKey:Q_KEY_CODE_CTRL_R];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700903 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900904 break;
905
906 case kVK_Option:
907 if (!!(modifiers & NSEventModifierFlagOption)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900908 if (swap_opt_cmd) {
909 [self toggleKey:Q_KEY_CODE_META_L];
910 } else {
911 [self toggleKey:Q_KEY_CODE_ALT];
912 }
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700913 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900914 break;
915
916 case kVK_RightOption:
917 if (!!(modifiers & NSEventModifierFlagOption)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900918 if (swap_opt_cmd) {
919 [self toggleKey:Q_KEY_CODE_META_R];
920 } else {
921 [self toggleKey:Q_KEY_CODE_ALT_R];
922 }
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700923 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900924 break;
925
926 /* Don't pass command key changes to guest unless mouse is grabbed */
927 case kVK_Command:
928 if (isMouseGrabbed &&
Akihiko Odakid6b6dea2022-03-18 00:29:49 +0900929 !!(modifiers & NSEventModifierFlagCommand) &&
930 left_command_key_enabled) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900931 if (swap_opt_cmd) {
932 [self toggleKey:Q_KEY_CODE_ALT];
933 } else {
934 [self toggleKey:Q_KEY_CODE_META_L];
935 }
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700936 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900937 break;
938
939 case kVK_RightCommand:
940 if (isMouseGrabbed &&
941 !!(modifiers & NSEventModifierFlagCommand)) {
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +0900942 if (swap_opt_cmd) {
943 [self toggleKey:Q_KEY_CODE_ALT_R];
944 } else {
945 [self toggleKey:Q_KEY_CODE_META_R];
946 }
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900947 }
948 break;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700949 }
thsc304f7e2008-01-22 23:25:15 +0000950 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700951 case NSEventTypeKeyDown:
Peter Maydell88959192013-12-08 22:59:02 +0000952 keycode = cocoa_keycode_to_qemu([event keyCode]);
thsc304f7e2008-01-22 23:25:15 +0000953
Peter Maydell88959192013-12-08 22:59:02 +0000954 // forward command key combos to the host UI unless the mouse is grabbed
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700955 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
Peter Maydell60105d72019-02-25 10:24:31 +0000956 return false;
thsc304f7e2008-01-22 23:25:15 +0000957 }
958
959 // default
thsc304f7e2008-01-22 23:25:15 +0000960
John Arbuckle5929e362017-11-07 10:14:14 +0000961 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700962 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
John Arbuckle5929e362017-11-07 10:14:14 +0000963 NSString *keychar = [event charactersIgnoringModifiers];
964 if ([keychar length] == 1) {
965 char key = [keychar characterAtIndex:0];
966 switch (key) {
thsc304f7e2008-01-22 23:25:15 +0000967
John Arbuckle5929e362017-11-07 10:14:14 +0000968 // enable graphic console
969 case '1' ... '9':
970 console_select(key - '0' - 1); /* ascii math */
Peter Maydell60105d72019-02-25 10:24:31 +0000971 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000972
973 // release the mouse grab
974 case 'g':
975 [self ungrabMouse];
Peter Maydell60105d72019-02-25 10:24:31 +0000976 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000977 }
thsc304f7e2008-01-22 23:25:15 +0000978 }
Peter Maydellef2088f2017-11-07 10:14:14 +0000979 }
thsc304f7e2008-01-22 23:25:15 +0000980
Peter Maydellef2088f2017-11-07 10:14:14 +0000981 if (qemu_console_is_graphic(NULL)) {
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900982 qkbd_state_key_event(kbd, keycode, true);
thsc304f7e2008-01-22 23:25:15 +0000983 } else {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000984 [self handleMonitorInput: event];
thsc304f7e2008-01-22 23:25:15 +0000985 }
986 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700987 case NSEventTypeKeyUp:
thsc304f7e2008-01-22 23:25:15 +0000988 keycode = cocoa_keycode_to_qemu([event keyCode]);
Peter Maydell88959192013-12-08 22:59:02 +0000989
990 // don't pass the guest a spurious key-up if we treated this
991 // command-key combo as a host UI action
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700992 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
Peter Maydell60105d72019-02-25 10:24:31 +0000993 return true;
Peter Maydell88959192013-12-08 22:59:02 +0000994 }
995
Peter Maydell68c0aa62013-04-17 09:16:35 +0000996 if (qemu_console_is_graphic(NULL)) {
Akihiko Odaki6d73bb62021-03-10 23:46:02 +0900997 qkbd_state_key_event(kbd, keycode, false);
thsc304f7e2008-01-22 23:25:15 +0000998 }
999 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001000 case NSEventTypeMouseMoved:
thsc304f7e2008-01-22 23:25:15 +00001001 if (isAbsoluteEnabled) {
Chen Zhang2044dff2019-06-04 17:36:00 +08001002 // Cursor re-entered into a window might generate events bound to screen coordinates
1003 // and `nil` window property, and in full screen mode, current window might not be
1004 // key window, where event location alone should suffice.
1005 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
Peter Maydellf61c3872014-06-23 10:35:24 +01001006 if (isMouseGrabbed) {
1007 [self ungrabMouse];
thsc304f7e2008-01-22 23:25:15 +00001008 }
1009 } else {
Peter Maydellf61c3872014-06-23 10:35:24 +01001010 if (!isMouseGrabbed) {
1011 [self grabMouse];
thsc304f7e2008-01-22 23:25:15 +00001012 }
1013 }
1014 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001015 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +00001016 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001017 case NSEventTypeLeftMouseDown:
Akihiko Odaki4295f832021-02-12 09:07:06 +09001018 buttons |= MOUSE_EVENT_LBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001019 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +00001020 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001021 case NSEventTypeRightMouseDown:
thsc304f7e2008-01-22 23:25:15 +00001022 buttons |= MOUSE_EVENT_RBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001023 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +00001024 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001025 case NSEventTypeOtherMouseDown:
thsc304f7e2008-01-22 23:25:15 +00001026 buttons |= MOUSE_EVENT_MBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001027 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +00001028 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001029 case NSEventTypeLeftMouseDragged:
Akihiko Odaki4295f832021-02-12 09:07:06 +09001030 buttons |= MOUSE_EVENT_LBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001031 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +00001032 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001033 case NSEventTypeRightMouseDragged:
thsc304f7e2008-01-22 23:25:15 +00001034 buttons |= MOUSE_EVENT_RBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001035 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +00001036 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001037 case NSEventTypeOtherMouseDragged:
thsc304f7e2008-01-22 23:25:15 +00001038 buttons |= MOUSE_EVENT_MBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001039 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +00001040 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001041 case NSEventTypeLeftMouseUp:
Peter Maydellf61c3872014-06-23 10:35:24 +01001042 mouse_event = true;
1043 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
Chen Zhang8e23e342019-06-04 17:36:48 +08001044 /*
1045 * In fullscreen mode, the window of cocoaView may not be the
1046 * key window, therefore the position relative to the virtual
1047 * screen alone will be sufficient.
1048 */
1049 if(isFullscreen || [[self window] isKeyWindow]) {
Programmingkid9e8204b2016-08-15 22:11:06 -04001050 [self grabMouse];
1051 }
thsc304f7e2008-01-22 23:25:15 +00001052 }
1053 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001054 case NSEventTypeRightMouseUp:
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001055 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +00001056 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001057 case NSEventTypeOtherMouseUp:
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001058 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +00001059 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001060 case NSEventTypeScrollWheel:
John Arbuckleae7313e2018-01-08 13:07:07 -05001061 /*
1062 * Send wheel events to the guest regardless of window focus.
1063 * This is in-line with standard Mac OS X UI behaviour.
1064 */
1065
John Arbuckledc3c89d2018-07-09 11:02:35 -04001066 /*
Dmitry Petrovd70a5de2022-01-08 16:39:44 +01001067 * We shouldn't have got a scroll event when deltaY and delta Y
1068 * are zero, hence no harm in dropping the event
John Arbuckledc3c89d2018-07-09 11:02:35 -04001069 */
Dmitry Petrovd70a5de2022-01-08 16:39:44 +01001070 if ([event deltaY] != 0 || [event deltaX] != 0) {
John Arbuckleae7313e2018-01-08 13:07:07 -05001071 /* Determine if this is a scroll up or scroll down event */
Dmitry Petrovd70a5de2022-01-08 16:39:44 +01001072 if ([event deltaY] != 0) {
1073 buttons = ([event deltaY] > 0) ?
John Arbuckledc3c89d2018-07-09 11:02:35 -04001074 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
Dmitry Petrovd70a5de2022-01-08 16:39:44 +01001075 } else if ([event deltaX] != 0) {
1076 buttons = ([event deltaX] > 0) ?
1077 INPUT_BUTTON_WHEEL_LEFT : INPUT_BUTTON_WHEEL_RIGHT;
1078 }
1079
Akihiko Odakicc7859c2021-02-19 17:44:19 +09001080 qemu_input_queue_btn(dcl.con, buttons, true);
John Arbuckledc3c89d2018-07-09 11:02:35 -04001081 qemu_input_event_sync();
Akihiko Odakicc7859c2021-02-19 17:44:19 +09001082 qemu_input_queue_btn(dcl.con, buttons, false);
John Arbuckledc3c89d2018-07-09 11:02:35 -04001083 qemu_input_event_sync();
1084 }
Dmitry Petrovd70a5de2022-01-08 16:39:44 +01001085
John Arbuckleae7313e2018-01-08 13:07:07 -05001086 /*
Dmitry Petrovd70a5de2022-01-08 16:39:44 +01001087 * Since deltaX/deltaY also report scroll wheel events we prevent mouse
John Arbuckleae7313e2018-01-08 13:07:07 -05001088 * movement code from executing.
1089 */
1090 mouse_event = false;
thsc304f7e2008-01-22 23:25:15 +00001091 break;
1092 default:
Peter Maydell60105d72019-02-25 10:24:31 +00001093 return false;
thsc304f7e2008-01-22 23:25:15 +00001094 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001095
1096 if (mouse_event) {
Peter Maydell8d3a5d92015-11-26 15:19:28 +00001097 /* Don't send button events to the guest unless we've got a
1098 * mouse grab or window focus. If we have neither then this event
1099 * is the user clicking on the background window to activate and
1100 * bring us to the front, which will be done by the sendEvent
1101 * call below. We definitely don't want to pass that click through
1102 * to the guest.
1103 */
1104 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
1105 (last_buttons != buttons)) {
Eric Blake7fb1cf12015-11-18 01:52:57 -07001106 static uint32_t bmap[INPUT_BUTTON__MAX] = {
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001107 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1108 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
John Arbuckleae7313e2018-01-08 13:07:07 -05001109 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001110 };
Akihiko Odakicc7859c2021-02-19 17:44:19 +09001111 qemu_input_update_buttons(dcl.con, bmap, last_buttons, buttons);
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001112 last_buttons = buttons;
1113 }
Peter Maydellf61c3872014-06-23 10:35:24 +01001114 if (isMouseGrabbed) {
1115 if (isAbsoluteEnabled) {
1116 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
1117 * The check on screenContainsPoint is to avoid sending out of range values for
1118 * clicks in the titlebar.
1119 */
1120 if ([self screenContainsPoint:p]) {
Akihiko Odakicc7859c2021-02-19 17:44:19 +09001121 qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x, 0, screen.width);
1122 qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
Peter Maydellf61c3872014-06-23 10:35:24 +01001123 }
1124 } else {
Akihiko Odakicc7859c2021-02-19 17:44:19 +09001125 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, (int)[event deltaX]);
1126 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, (int)[event deltaY]);
Peter Maydellf61c3872014-06-23 10:35:24 +01001127 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001128 } else {
Peter Maydell60105d72019-02-25 10:24:31 +00001129 return false;
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001130 }
1131 qemu_input_event_sync();
1132 }
Peter Maydell60105d72019-02-25 10:24:31 +00001133 return true;
thsc304f7e2008-01-22 23:25:15 +00001134}
1135
1136- (void) grabMouse
1137{
1138 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
1139
1140 if (!isFullscreen) {
1141 if (qemu_name)
Christian Schoenebeck23bdd0d2022-12-27 17:15:31 +01001142 [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 +00001143 else
Christian Schoenebeck23bdd0d2022-12-27 17:15:31 +01001144 [normalWindow setTitle:@"QEMU - (Press " UC_CTRL_KEY " " UC_ALT_KEY " G to release Mouse)"];
thsc304f7e2008-01-22 23:25:15 +00001145 }
Peter Maydell13aefd32014-06-23 10:35:25 +01001146 [self hideCursor];
Akihiko Odakid1929062021-02-23 00:07:14 +09001147 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
Peter Maydell49b9bd42013-12-08 22:59:03 +00001148 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
thsc304f7e2008-01-22 23:25:15 +00001149}
1150
1151- (void) ungrabMouse
1152{
1153 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
1154
1155 if (!isFullscreen) {
1156 if (qemu_name)
1157 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
1158 else
1159 [normalWindow setTitle:@"QEMU"];
1160 }
Peter Maydell13aefd32014-06-23 10:35:25 +01001161 [self unhideCursor];
Akihiko Odakid1929062021-02-23 00:07:14 +09001162 CGAssociateMouseAndMouseCursorPosition(TRUE);
Peter Maydell49b9bd42013-12-08 22:59:03 +00001163 isMouseGrabbed = FALSE;
thsc304f7e2008-01-22 23:25:15 +00001164}
1165
Akihiko Odakid1929062021-02-23 00:07:14 +09001166- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {
1167 isAbsoluteEnabled = tIsAbsoluteEnabled;
1168 if (isMouseGrabbed) {
1169 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1170 }
1171}
Peter Maydell49b9bd42013-12-08 22:59:03 +00001172- (BOOL) isMouseGrabbed {return isMouseGrabbed;}
thsc304f7e2008-01-22 23:25:15 +00001173- (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
1174- (float) cdx {return cdx;}
1175- (float) cdy {return cdy;}
1176- (QEMUScreen) gscreen {return screen;}
John Arbuckle3b178b72015-09-25 23:14:00 +01001177
1178/*
1179 * Makes the target think all down keys are being released.
1180 * This prevents a stuck key problem, since we will not see
1181 * key up events for those keys after we have lost focus.
1182 */
1183- (void) raiseAllKeys
1184{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001185 with_bql(^{
Akihiko Odaki6d73bb62021-03-10 23:46:02 +09001186 qkbd_state_lift_all_keys(kbd);
Peter Maydell31819e92019-02-25 10:24:27 +00001187 });
John Arbuckle3b178b72015-09-25 23:14:00 +01001188}
bellard5b0753e2005-03-01 21:37:28 +00001189@end
1190
1191
thsc304f7e2008-01-22 23:25:15 +00001192
bellard5b0753e2005-03-01 21:37:28 +00001193/*
1194 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +00001195 QemuCocoaAppController
bellard5b0753e2005-03-01 21:37:28 +00001196 ------------------------------------------------------
1197*/
thsc304f7e2008-01-22 23:25:15 +00001198@interface QemuCocoaAppController : NSObject
John Arbuckled9bc14f2015-09-25 23:13:59 +01001199 <NSWindowDelegate, NSApplicationDelegate>
bellard5b0753e2005-03-01 21:37:28 +00001200{
1201}
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001202- (void)doToggleFullScreen:(id)sender;
thsc304f7e2008-01-22 23:25:15 +00001203- (void)toggleFullScreen:(id)sender;
1204- (void)showQEMUDoc:(id)sender;
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001205- (void)zoomToFit:(id) sender;
Programmingkidb4c6a112015-05-19 09:11:18 +01001206- (void)displayConsole:(id)sender;
John Arbuckle8524f1c2015-06-19 10:53:27 +01001207- (void)pauseQEMU:(id)sender;
1208- (void)resumeQEMU:(id)sender;
1209- (void)displayPause;
1210- (void)removePause;
John Arbuckle27074612015-06-19 10:53:27 +01001211- (void)restartQEMU:(id)sender;
1212- (void)powerDownQEMU:(id)sender;
John Arbuckle693a3e02015-06-19 10:53:27 +01001213- (void)ejectDeviceMedia:(id)sender;
1214- (void)changeDeviceMedia:(id)sender;
John Arbuckled9bc14f2015-09-25 23:13:59 +01001215- (BOOL)verifyQuit;
John Arbucklef4747902016-03-23 14:26:17 +00001216- (void)openDocumentation:(NSString *)filename;
Programmingkid9e8204b2016-08-15 22:11:06 -04001217- (IBAction) do_about_menu_item: (id) sender;
John Arbucklee47ec1a2017-06-13 23:17:38 -04001218- (void)adjustSpeed:(id)sender;
bellard5b0753e2005-03-01 21:37:28 +00001219@end
1220
thsc304f7e2008-01-22 23:25:15 +00001221@implementation QemuCocoaAppController
1222- (id) init
1223{
1224 COCOA_DEBUG("QemuCocoaAppController: init\n");
1225
1226 self = [super init];
1227 if (self) {
1228
1229 // create a view and add it to the window
1230 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1231 if(!cocoaView) {
Akihiko Odaki43137392021-02-23 22:11:06 +09001232 error_report("(cocoa) can't create a view");
thsc304f7e2008-01-22 23:25:15 +00001233 exit(1);
1234 }
1235
1236 // create a window
1237 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001238 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
thsc304f7e2008-01-22 23:25:15 +00001239 backing:NSBackingStoreBuffered defer:NO];
1240 if(!normalWindow) {
Akihiko Odaki43137392021-02-23 22:11:06 +09001241 error_report("(cocoa) can't create window");
thsc304f7e2008-01-22 23:25:15 +00001242 exit(1);
1243 }
1244 [normalWindow setAcceptsMouseMovedEvents:YES];
John Arbucklea1dbc052015-10-13 21:51:18 +01001245 [normalWindow setTitle:@"QEMU"];
thsc304f7e2008-01-22 23:25:15 +00001246 [normalWindow setContentView:cocoaView];
1247 [normalWindow makeKeyAndOrderFront:self];
Peter Maydell49060c22013-12-24 11:54:12 +00001248 [normalWindow center];
John Arbuckled9bc14f2015-09-25 23:13:59 +01001249 [normalWindow setDelegate: self];
John Arbuckle8524f1c2015-06-19 10:53:27 +01001250
1251 /* Used for displaying pause on the screen */
1252 pauseLabel = [NSTextField new];
1253 [pauseLabel setBezeled:YES];
1254 [pauseLabel setDrawsBackground:YES];
1255 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1256 [pauseLabel setEditable:NO];
1257 [pauseLabel setSelectable:NO];
1258 [pauseLabel setStringValue: @"Paused"];
1259 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1260 [pauseLabel setTextColor: [NSColor blackColor]];
1261 [pauseLabel sizeToFit];
thsc304f7e2008-01-22 23:25:15 +00001262 }
1263 return self;
1264}
1265
1266- (void) dealloc
1267{
1268 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1269
1270 if (cocoaView)
1271 [cocoaView release];
1272 [super dealloc];
1273}
1274
bellard5b0753e2005-03-01 21:37:28 +00001275- (void)applicationDidFinishLaunching: (NSNotification *) note
1276{
thsc304f7e2008-01-22 23:25:15 +00001277 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
Hikaru Nishidadff742a2019-10-15 10:07:34 +09001278 allow_events = true;
bellard5b0753e2005-03-01 21:37:28 +00001279}
1280
1281- (void)applicationWillTerminate:(NSNotification *)aNotification
1282{
thsc304f7e2008-01-22 23:25:15 +00001283 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1284
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001285 with_bql(^{
Akihiko Odaki2910abd2022-05-29 17:25:08 +09001286 shutdown_action = SHUTDOWN_ACTION_POWEROFF;
1287 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1288 });
Akihiko Odaki40c01932021-02-19 20:16:52 +09001289
1290 /*
1291 * Sleep here, because returning will cause OSX to kill us
1292 * immediately; the QEMU main loop will handle the shutdown
1293 * request and terminate the process.
1294 */
1295 [NSThread sleepForTimeInterval:INFINITY];
bellard5b0753e2005-03-01 21:37:28 +00001296}
1297
Andreas Färber41ea49b2009-12-14 22:13:27 +01001298- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1299{
1300 return YES;
1301}
1302
John Arbuckled9bc14f2015-09-25 23:13:59 +01001303- (NSApplicationTerminateReply)applicationShouldTerminate:
1304 (NSApplication *)sender
1305{
1306 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1307 return [self verifyQuit];
1308}
1309
Akihiko Odaki15280e82021-06-16 23:19:10 +09001310- (void)windowDidChangeScreen:(NSNotification *)notification
1311{
1312 [cocoaView updateUIInfo];
1313}
1314
1315- (void)windowDidResize:(NSNotification *)notification
1316{
1317 [cocoaView updateUIInfo];
1318}
1319
John Arbuckled9bc14f2015-09-25 23:13:59 +01001320/* Called when the user clicks on a window's close button */
1321- (BOOL)windowShouldClose:(id)sender
1322{
1323 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1324 [NSApp terminate: sender];
1325 /* If the user allows the application to quit then the call to
1326 * NSApp terminate will never return. If we get here then the user
1327 * cancelled the quit, so we should return NO to not permit the
1328 * closing of this window.
1329 */
1330 return NO;
1331}
1332
Akihiko Odaki9d9bc7d2023-02-28 16:09:46 +09001333/*
1334 * Called when QEMU goes into the background. Note that
1335 * [-NSWindowDelegate windowDidResignKey:] is used here instead of
1336 * [-NSApplicationDelegate applicationWillResignActive:] because it cannot
1337 * detect that the window loses focus when the deck is clicked on macOS 13.2.1.
1338 */
1339- (void) windowDidResignKey: (NSNotification *)aNotification
John Arbuckle3b178b72015-09-25 23:14:00 +01001340{
Akihiko Odaki9d9bc7d2023-02-28 16:09:46 +09001341 COCOA_DEBUG("%s\n", __func__);
Carwyn Ellis69221df2022-01-02 17:41:53 +00001342 [cocoaView ungrabMouse];
John Arbuckle3b178b72015-09-25 23:14:00 +01001343 [cocoaView raiseAllKeys];
1344}
1345
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001346/* We abstract the method called by the Enter Fullscreen menu item
1347 * because Mac OS 10.7 and higher disables it. This is because of the
1348 * menu item's old selector's name toggleFullScreen:
1349 */
1350- (void) doToggleFullScreen:(id)sender
1351{
1352 [self toggleFullScreen:(id)sender];
1353}
1354
thsc304f7e2008-01-22 23:25:15 +00001355- (void)toggleFullScreen:(id)sender
bellard5b0753e2005-03-01 21:37:28 +00001356{
thsc304f7e2008-01-22 23:25:15 +00001357 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1358
1359 [cocoaView toggleFullScreen:sender];
1360}
1361
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +09001362- (void) setFullGrab:(id)sender
1363{
1364 COCOA_DEBUG("QemuCocoaAppController: setFullGrab\n");
1365
1366 [cocoaView setFullGrab:sender];
1367}
1368
John Arbucklef4747902016-03-23 14:26:17 +00001369/* Tries to find then open the specified filename */
1370- (void) openDocumentation: (NSString *) filename
1371{
1372 /* Where to look for local files */
Roman Bolshakov8d6fda82021-01-09 00:38:15 +03001373 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
John Arbucklef4747902016-03-23 14:26:17 +00001374 NSString *full_file_path;
Roman Bolshakov1ff5a062021-01-02 18:07:21 +03001375 NSURL *full_file_url;
John Arbucklef4747902016-03-23 14:26:17 +00001376
1377 /* iterate thru the possible paths until the file is found */
1378 int index;
1379 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1380 full_file_path = [[NSBundle mainBundle] executablePath];
1381 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1382 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1383 path_array[index], filename];
Roman Bolshakov1ff5a062021-01-02 18:07:21 +03001384 full_file_url = [NSURL fileURLWithPath: full_file_path
1385 isDirectory: false];
1386 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
John Arbucklef4747902016-03-23 14:26:17 +00001387 return;
1388 }
1389 }
1390
1391 /* If none of the paths opened a file */
1392 NSBeep();
1393 QEMU_Alert(@"Failed to open file");
1394}
1395
thsc304f7e2008-01-22 23:25:15 +00001396- (void)showQEMUDoc:(id)sender
1397{
1398 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1399
Peter Maydell1879f242020-02-28 15:36:16 +00001400 [self openDocumentation: @"index.html"];
thsc304f7e2008-01-22 23:25:15 +00001401}
1402
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001403/* Stretches video to fit host monitor size */
1404- (void)zoomToFit:(id) sender
1405{
1406 stretch_video = !stretch_video;
1407 if (stretch_video == true) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001408 [sender setState: NSControlStateValueOn];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001409 } else {
Brendan Shanks5e246002019-01-31 23:12:25 -08001410 [sender setState: NSControlStateValueOff];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001411 }
1412}
bellard5b0753e2005-03-01 21:37:28 +00001413
Programmingkidb4c6a112015-05-19 09:11:18 +01001414/* Displays the console on the screen */
1415- (void)displayConsole:(id)sender
1416{
1417 console_select([sender tag]);
1418}
John Arbuckle8524f1c2015-06-19 10:53:27 +01001419
1420/* Pause the guest */
1421- (void)pauseQEMU:(id)sender
1422{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001423 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001424 qmp_stop(NULL);
1425 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001426 [sender setEnabled: NO];
1427 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1428 [self displayPause];
1429}
1430
1431/* Resume running the guest operating system */
1432- (void)resumeQEMU:(id) sender
1433{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001434 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001435 qmp_cont(NULL);
1436 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001437 [sender setEnabled: NO];
1438 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1439 [self removePause];
1440}
1441
1442/* Displays the word pause on the screen */
1443- (void)displayPause
1444{
1445 /* Coordinates have to be calculated each time because the window can change its size */
1446 int xCoord, yCoord, width, height;
1447 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1448 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1449 width = [pauseLabel frame].size.width;
1450 height = [pauseLabel frame].size.height;
1451 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1452 [cocoaView addSubview: pauseLabel];
1453}
1454
1455/* Removes the word pause from the screen */
1456- (void)removePause
1457{
1458 [pauseLabel removeFromSuperview];
1459}
1460
John Arbuckle27074612015-06-19 10:53:27 +01001461/* Restarts QEMU */
1462- (void)restartQEMU:(id)sender
1463{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001464 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001465 qmp_system_reset(NULL);
1466 });
John Arbuckle27074612015-06-19 10:53:27 +01001467}
1468
1469/* Powers down QEMU */
1470- (void)powerDownQEMU:(id)sender
1471{
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001472 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001473 qmp_system_powerdown(NULL);
1474 });
John Arbuckle27074612015-06-19 10:53:27 +01001475}
1476
John Arbuckle693a3e02015-06-19 10:53:27 +01001477/* Ejects the media.
1478 * Uses sender's tag to figure out the device to eject.
1479 */
1480- (void)ejectDeviceMedia:(id)sender
1481{
1482 NSString * drive;
1483 drive = [sender representedObject];
1484 if(drive == nil) {
1485 NSBeep();
1486 QEMU_Alert(@"Failed to find drive to eject!");
1487 return;
1488 }
1489
Peter Maydell31819e92019-02-25 10:24:27 +00001490 __block Error *err = NULL;
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001491 with_bql(^{
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001492 qmp_eject([drive cStringUsingEncoding: NSASCIIStringEncoding],
1493 NULL, false, false, &err);
Peter Maydell31819e92019-02-25 10:24:27 +00001494 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001495 handleAnyDeviceErrors(err);
1496}
1497
1498/* Displays a dialog box asking the user to select an image file to load.
1499 * Uses sender's represented object value to figure out which drive to use.
1500 */
1501- (void)changeDeviceMedia:(id)sender
1502{
1503 /* Find the drive name */
1504 NSString * drive;
1505 drive = [sender representedObject];
1506 if(drive == nil) {
1507 NSBeep();
1508 QEMU_Alert(@"Could not find drive!");
1509 return;
1510 }
1511
1512 /* Display the file open dialog */
1513 NSOpenPanel * openPanel;
1514 openPanel = [NSOpenPanel openPanel];
1515 [openPanel setCanChooseFiles: YES];
1516 [openPanel setAllowsMultipleSelection: NO];
Peter Maydellb5725382018-05-29 19:15:23 +01001517 if([openPanel runModal] == NSModalResponseOK) {
John Arbuckle693a3e02015-06-19 10:53:27 +01001518 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1519 if(file == nil) {
1520 NSBeep();
1521 QEMU_Alert(@"Failed to convert URL to file path!");
1522 return;
1523 }
1524
Peter Maydell31819e92019-02-25 10:24:27 +00001525 __block Error *err = NULL;
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001526 with_bql(^{
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001527 qmp_blockdev_change_medium([drive cStringUsingEncoding:
Peter Maydell31819e92019-02-25 10:24:27 +00001528 NSASCIIStringEncoding],
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001529 NULL,
Peter Maydell31819e92019-02-25 10:24:27 +00001530 [file cStringUsingEncoding:
1531 NSASCIIStringEncoding],
Markus Armbruster54fde4f2022-11-04 17:06:52 +01001532 "raw",
Denis V. Lunev80dd5af2022-04-13 01:18:46 +03001533 true, false,
Peter Maydell31819e92019-02-25 10:24:27 +00001534 false, 0,
1535 &err);
1536 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001537 handleAnyDeviceErrors(err);
1538 }
1539}
1540
John Arbuckled9bc14f2015-09-25 23:13:59 +01001541/* Verifies if the user really wants to quit */
1542- (BOOL)verifyQuit
1543{
1544 NSAlert *alert = [NSAlert new];
1545 [alert autorelease];
1546 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1547 [alert addButtonWithTitle: @"Cancel"];
1548 [alert addButtonWithTitle: @"Quit"];
1549 if([alert runModal] == NSAlertSecondButtonReturn) {
1550 return YES;
1551 } else {
1552 return NO;
1553 }
1554}
1555
Programmingkid9e8204b2016-08-15 22:11:06 -04001556/* The action method for the About menu item */
1557- (IBAction) do_about_menu_item: (id) sender
1558{
Akihiko Odaki99eb3132022-02-27 13:22:41 +09001559 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1560 char *icon_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1561 NSString *icon_path = [NSString stringWithUTF8String:icon_path_c];
1562 g_free(icon_path_c);
1563 NSImage *icon = [[NSImage alloc] initWithContentsOfFile:icon_path];
1564 NSString *version = @"QEMU emulator version " QEMU_FULL_VERSION;
1565 NSString *copyright = @QEMU_COPYRIGHT;
1566 NSDictionary *options;
1567 if (icon) {
1568 options = @{
1569 NSAboutPanelOptionApplicationIcon : icon,
1570 NSAboutPanelOptionApplicationVersion : version,
1571 @"Copyright" : copyright,
1572 };
1573 [icon release];
1574 } else {
1575 options = @{
1576 NSAboutPanelOptionApplicationVersion : version,
1577 @"Copyright" : copyright,
1578 };
Akihiko Odakia0f973f2021-03-09 21:22:26 +09001579 }
Akihiko Odaki99eb3132022-02-27 13:22:41 +09001580 [NSApp orderFrontStandardAboutPanelWithOptions:options];
1581 [pool release];
Programmingkid9e8204b2016-08-15 22:11:06 -04001582}
1583
John Arbucklee47ec1a2017-06-13 23:17:38 -04001584/* Used by the Speed menu items */
1585- (void)adjustSpeed:(id)sender
1586{
1587 int throttle_pct; /* throttle percentage */
1588 NSMenu *menu;
1589
1590 menu = [sender menu];
1591 if (menu != nil)
1592 {
1593 /* Unselect the currently selected item */
1594 for (NSMenuItem *item in [menu itemArray]) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001595 if (item.state == NSControlStateValueOn) {
1596 [item setState: NSControlStateValueOff];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001597 break;
1598 }
1599 }
1600 }
1601
1602 // check the menu item
Brendan Shanks5e246002019-01-31 23:12:25 -08001603 [sender setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001604
1605 // get the throttle percentage
1606 throttle_pct = [sender tag];
1607
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001608 with_bql(^{
Peter Maydell31819e92019-02-25 10:24:27 +00001609 cpu_throttle_set(throttle_pct);
1610 });
John Arbucklee47ec1a2017-06-13 23:17:38 -04001611 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1612}
1613
Programmingkidb4c6a112015-05-19 09:11:18 +01001614@end
bellard5b0753e2005-03-01 21:37:28 +00001615
Peter Maydell61a2ed42019-02-25 10:24:32 +00001616@interface QemuApplication : NSApplication
1617@end
1618
1619@implementation QemuApplication
1620- (void)sendEvent:(NSEvent *)event
1621{
1622 COCOA_DEBUG("QemuApplication: sendEvent\n");
Peter Maydell55888402019-02-25 10:24:33 +00001623 if (![cocoaView handleEvent:event]) {
1624 [super sendEvent: event];
1625 }
Peter Maydell61a2ed42019-02-25 10:24:32 +00001626}
1627@end
1628
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001629static void create_initial_menus(void)
1630{
thsc304f7e2008-01-22 23:25:15 +00001631 // Add menus
1632 NSMenu *menu;
1633 NSMenuItem *menuItem;
1634
bellard5b0753e2005-03-01 21:37:28 +00001635 [NSApp setMainMenu:[[NSMenu alloc] init]];
Akihiko Odaki5b6988c2022-02-14 18:13:20 +09001636 [NSApp setServicesMenu:[[NSMenu alloc] initWithTitle:@"Services"]];
bellard5b0753e2005-03-01 21:37:28 +00001637
thsc304f7e2008-01-22 23:25:15 +00001638 // Application menu
1639 menu = [[NSMenu alloc] initWithTitle:@""];
Programmingkid9e8204b2016-08-15 22:11:06 -04001640 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
thsc304f7e2008-01-22 23:25:15 +00001641 [menu addItem:[NSMenuItem separatorItem]]; //Separator
Akihiko Odaki5b6988c2022-02-14 18:13:20 +09001642 menuItem = [menu addItemWithTitle:@"Services" action:nil keyEquivalent:@""];
1643 [menuItem setSubmenu:[NSApp servicesMenu]];
1644 [menu addItem:[NSMenuItem separatorItem]];
thsc304f7e2008-01-22 23:25:15 +00001645 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1646 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001647 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
thsc304f7e2008-01-22 23:25:15 +00001648 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1649 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1650 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1651 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1652 [menuItem setSubmenu:menu];
1653 [[NSApp mainMenu] addItem:menuItem];
1654 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
ths3b46e622007-09-17 08:09:54 +00001655
John Arbuckle8524f1c2015-06-19 10:53:27 +01001656 // Machine menu
1657 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1658 [menu setAutoenablesItems: NO];
1659 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1660 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1661 [menu addItem: menuItem];
1662 [menuItem setEnabled: NO];
John Arbuckle27074612015-06-19 10:53:27 +01001663 [menu addItem: [NSMenuItem separatorItem]];
1664 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1665 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
John Arbuckle8524f1c2015-06-19 10:53:27 +01001666 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1667 [menuItem setSubmenu:menu];
1668 [[NSApp mainMenu] addItem:menuItem];
1669
thsc304f7e2008-01-22 23:25:15 +00001670 // View menu
1671 menu = [[NSMenu alloc] initWithTitle:@"View"];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001672 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
Carwyn Ellis5ec08982023-10-27 16:49:20 +01001673 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease];
1674 [menuItem setState: stretch_video ? NSControlStateValueOn : NSControlStateValueOff];
1675 [menu addItem: menuItem];
thsc304f7e2008-01-22 23:25:15 +00001676 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1677 [menuItem setSubmenu:menu];
1678 [[NSApp mainMenu] addItem:menuItem];
1679
John Arbucklee47ec1a2017-06-13 23:17:38 -04001680 // Speed menu
1681 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1682
1683 // Add the rest of the Speed menu items
1684 int p, percentage, throttle_pct;
1685 for (p = 10; p >= 0; p--)
1686 {
1687 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1688
1689 menuItem = [[[NSMenuItem alloc]
1690 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1691
1692 if (percentage == 100) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001693 [menuItem setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001694 }
1695
1696 /* Calculate the throttle percentage */
1697 throttle_pct = -1 * percentage + 100;
1698
1699 [menuItem setTag: throttle_pct];
1700 [menu addItem: menuItem];
1701 }
1702 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1703 [menuItem setSubmenu:menu];
1704 [[NSApp mainMenu] addItem:menuItem];
1705
thsc304f7e2008-01-22 23:25:15 +00001706 // Window menu
1707 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1708 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1709 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1710 [menuItem setSubmenu:menu];
1711 [[NSApp mainMenu] addItem:menuItem];
1712 [NSApp setWindowsMenu:menu];
1713
1714 // Help menu
1715 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1716 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
thsc304f7e2008-01-22 23:25:15 +00001717 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1718 [menuItem setSubmenu:menu];
1719 [[NSApp mainMenu] addItem:menuItem];
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001720}
1721
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001722/* Returns a name for a given console */
1723static NSString * getConsoleName(QemuConsole * console)
1724{
Akihiko Odakica511602022-02-15 09:03:05 +01001725 g_autofree char *label = qemu_console_get_label(console);
1726
1727 return [NSString stringWithUTF8String:label];
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001728}
1729
1730/* Add an entry to the View menu for each console */
1731static void add_console_menu_entries(void)
1732{
1733 NSMenu *menu;
1734 NSMenuItem *menuItem;
1735 int index = 0;
1736
1737 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1738
1739 [menu addItem:[NSMenuItem separatorItem]];
1740
1741 while (qemu_console_lookup_by_index(index) != NULL) {
1742 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1743 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1744 [menuItem setTag: index];
1745 [menu addItem: menuItem];
1746 index++;
1747 }
1748}
1749
1750/* Make menu items for all removable devices.
1751 * Each device is given an 'Eject' and 'Change' menu item.
1752 */
1753static void addRemovableDevicesMenuItems(void)
1754{
1755 NSMenu *menu;
1756 NSMenuItem *menuItem;
1757 BlockInfoList *currentDevice, *pointerToFree;
1758 NSString *deviceName;
1759
1760 currentDevice = qmp_query_block(NULL);
1761 pointerToFree = currentDevice;
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001762
1763 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1764
1765 // Add a separator between related groups of menu items
1766 [menu addItem:[NSMenuItem separatorItem]];
1767
1768 // Set the attributes to the "Removable Media" menu item
1769 NSString *titleString = @"Removable Media";
1770 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1771 NSColor *newColor = [NSColor blackColor];
1772 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1773 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1774 traits:NSBoldFontMask|NSItalicFontMask
1775 weight:0
1776 size:14];
1777 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1778 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1779 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1780
1781 // Add the "Removable Media" menu item
1782 menuItem = [NSMenuItem new];
1783 [menuItem setAttributedTitle: attString];
1784 [menuItem setEnabled: NO];
1785 [menu addItem: menuItem];
1786
1787 /* Loop through all the block devices in the emulator */
1788 while (currentDevice) {
1789 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1790
1791 if(currentDevice->value->removable) {
1792 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1793 action: @selector(changeDeviceMedia:)
1794 keyEquivalent: @""];
1795 [menu addItem: menuItem];
1796 [menuItem setRepresentedObject: deviceName];
1797 [menuItem autorelease];
1798
1799 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1800 action: @selector(ejectDeviceMedia:)
1801 keyEquivalent: @""];
1802 [menu addItem: menuItem];
1803 [menuItem setRepresentedObject: deviceName];
1804 [menuItem autorelease];
1805 }
1806 currentDevice = currentDevice->next;
1807 }
1808 qapi_free_BlockInfoList(pointerToFree);
1809}
1810
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001811@interface QemuCocoaPasteboardTypeOwner : NSObject<NSPasteboardTypeOwner>
1812@end
1813
1814@implementation QemuCocoaPasteboardTypeOwner
1815
1816- (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)type
1817{
1818 if (type != NSPasteboardTypeString) {
1819 return;
1820 }
1821
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001822 with_bql(^{
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001823 QemuClipboardInfo *info = qemu_clipboard_info_ref(cbinfo);
1824 qemu_event_reset(&cbevent);
1825 qemu_clipboard_request(info, QEMU_CLIPBOARD_TYPE_TEXT);
1826
1827 while (info == cbinfo &&
1828 info->types[QEMU_CLIPBOARD_TYPE_TEXT].available &&
1829 info->types[QEMU_CLIPBOARD_TYPE_TEXT].data == NULL) {
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001830 bql_unlock();
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001831 qemu_event_wait(&cbevent);
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001832 bql_lock();
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001833 }
1834
1835 if (info == cbinfo) {
1836 NSData *data = [[NSData alloc] initWithBytes:info->types[QEMU_CLIPBOARD_TYPE_TEXT].data
1837 length:info->types[QEMU_CLIPBOARD_TYPE_TEXT].size];
1838 [sender setData:data forType:NSPasteboardTypeString];
1839 [data release];
1840 }
1841
1842 qemu_clipboard_info_unref(info);
1843 });
1844}
1845
1846@end
1847
1848static QemuCocoaPasteboardTypeOwner *cbowner;
1849
1850static void cocoa_clipboard_notify(Notifier *notifier, void *data);
1851static void cocoa_clipboard_request(QemuClipboardInfo *info,
1852 QemuClipboardType type);
1853
1854static QemuClipboardPeer cbpeer = {
1855 .name = "cocoa",
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001856 .notifier = { .notify = cocoa_clipboard_notify },
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001857 .request = cocoa_clipboard_request
1858};
1859
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001860static void cocoa_clipboard_update_info(QemuClipboardInfo *info)
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001861{
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001862 if (info->owner == &cbpeer || info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
1863 return;
1864 }
1865
1866 if (info != cbinfo) {
1867 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1868 qemu_clipboard_info_unref(cbinfo);
1869 cbinfo = qemu_clipboard_info_ref(info);
1870 cbchangecount = [[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:cbowner];
1871 [pool release];
1872 }
1873
1874 qemu_event_set(&cbevent);
1875}
1876
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001877static void cocoa_clipboard_notify(Notifier *notifier, void *data)
1878{
1879 QemuClipboardNotify *notify = data;
1880
1881 switch (notify->type) {
1882 case QEMU_CLIPBOARD_UPDATE_INFO:
1883 cocoa_clipboard_update_info(notify->info);
1884 return;
Marc-André Lureau505dbf92021-07-19 19:49:56 +04001885 case QEMU_CLIPBOARD_RESET_SERIAL:
1886 /* ignore */
1887 return;
Marc-André Lureau1b17f1e2021-07-19 19:42:15 +04001888 }
1889}
1890
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001891static void cocoa_clipboard_request(QemuClipboardInfo *info,
1892 QemuClipboardType type)
1893{
Akihiko Odaki8c0d8022022-06-15 06:21:31 +09001894 NSAutoreleasePool *pool;
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001895 NSData *text;
1896
1897 switch (type) {
1898 case QEMU_CLIPBOARD_TYPE_TEXT:
Akihiko Odaki8c0d8022022-06-15 06:21:31 +09001899 pool = [[NSAutoreleasePool alloc] init];
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001900 text = [[NSPasteboard generalPasteboard] dataForType:NSPasteboardTypeString];
1901 if (text) {
1902 qemu_clipboard_set_data(&cbpeer, info, type,
1903 [text length], [text bytes], true);
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001904 }
Akihiko Odaki8c0d8022022-06-15 06:21:31 +09001905 [pool release];
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001906 break;
1907 default:
1908 break;
1909 }
1910}
1911
Peter Maydell55888402019-02-25 10:24:33 +00001912/*
1913 * The startup process for the OSX/Cocoa UI is complicated, because
1914 * OSX insists that the UI runs on the initial main thread, and so we
Akihiko Odakibab6a302022-08-19 22:27:54 +09001915 * need to start a second thread which runs the qemu_default_main():
Peter Maydell55888402019-02-25 10:24:33 +00001916 * in main():
Akihiko Odakibab6a302022-08-19 22:27:54 +09001917 * in cocoa_display_init():
1918 * assign cocoa_main to qemu_main
1919 * create application, menus, etc
1920 * in cocoa_main():
1921 * create qemu-main thread
1922 * enter OSX run loop
Peter Maydell55888402019-02-25 10:24:33 +00001923 */
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001924
Peter Maydell55888402019-02-25 10:24:33 +00001925static void *call_qemu_main(void *opaque)
1926{
1927 int status;
1928
Akihiko Odakibab6a302022-08-19 22:27:54 +09001929 COCOA_DEBUG("Second thread: calling qemu_default_main()\n");
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001930 bql_lock();
Akihiko Odakibab6a302022-08-19 22:27:54 +09001931 status = qemu_default_main();
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001932 bql_unlock();
Akihiko Odakibab6a302022-08-19 22:27:54 +09001933 COCOA_DEBUG("Second thread: qemu_default_main() returned, exiting\n");
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09001934 [cbowner release];
Peter Maydell55888402019-02-25 10:24:33 +00001935 exit(status);
1936}
1937
Philippe Mathieu-Daudéf9750332023-04-23 18:55:28 +02001938static int cocoa_main(void)
Akihiko Odakibab6a302022-08-19 22:27:54 +09001939{
Peter Maydell55888402019-02-25 10:24:33 +00001940 QemuThread thread;
1941
Akihiko Odakibab6a302022-08-19 22:27:54 +09001942 COCOA_DEBUG("Entered %s()\n", __func__);
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001943
Stefan Hajnoczi195801d2024-01-02 10:35:25 -05001944 bql_unlock();
Peter Maydell55888402019-02-25 10:24:33 +00001945 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1946 NULL, QEMU_THREAD_DETACHED);
1947
thsc304f7e2008-01-22 23:25:15 +00001948 // Start the main event loop
Peter Maydell55888402019-02-25 10:24:33 +00001949 COCOA_DEBUG("Main thread: entering OSX run loop\n");
bellard5b0753e2005-03-01 21:37:28 +00001950 [NSApp run];
Akihiko Odakibab6a302022-08-19 22:27:54 +09001951 COCOA_DEBUG("Main thread: left OSX run loop, which should never happen\n");
ths3b46e622007-09-17 08:09:54 +00001952
Akihiko Odakibab6a302022-08-19 22:27:54 +09001953 abort();
bellard5b0753e2005-03-01 21:37:28 +00001954}
thsc304f7e2008-01-22 23:25:15 +00001955
1956
1957
1958#pragma mark qemu
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001959static void cocoa_update(DisplayChangeListener *dcl,
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001960 int x, int y, int w, int h)
thsc304f7e2008-01-22 23:25:15 +00001961{
1962 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1963
Peter Maydell55888402019-02-25 10:24:33 +00001964 dispatch_async(dispatch_get_main_queue(), ^{
1965 NSRect rect;
1966 if ([cocoaView cdx] == 1.0) {
1967 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1968 } else {
1969 rect = NSMakeRect(
1970 x * [cocoaView cdx],
1971 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1972 w * [cocoaView cdx],
1973 h * [cocoaView cdy]);
1974 }
1975 [cocoaView setNeedsDisplayInRect:rect];
1976 });
thsc304f7e2008-01-22 23:25:15 +00001977}
1978
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01001979static void cocoa_switch(DisplayChangeListener *dcl,
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01001980 DisplaySurface *surface)
thsc304f7e2008-01-22 23:25:15 +00001981{
Peter Maydell55888402019-02-25 10:24:33 +00001982 pixman_image_t *image = surface->image;
thsc304f7e2008-01-22 23:25:15 +00001983
Peter Maydell6e657e62013-04-22 10:29:46 +00001984 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
Peter Maydell55888402019-02-25 10:24:33 +00001985
1986 // The DisplaySurface will be freed as soon as this callback returns.
1987 // We take a reference to the underlying pixman image here so it does
1988 // not disappear from under our feet; the switchSurface method will
1989 // deref the old image when it is done with it.
1990 pixman_image_ref(image);
1991
1992 dispatch_async(dispatch_get_main_queue(), ^{
Peter Maydell8d65dee2022-02-24 10:13:29 +00001993 [cocoaView updateUIInfo];
Peter Maydell55888402019-02-25 10:24:33 +00001994 [cocoaView switchSurface:image];
1995 });
thsc304f7e2008-01-22 23:25:15 +00001996}
1997
Gerd Hoffmannbc2ed972013-03-01 13:03:04 +01001998static void cocoa_refresh(DisplayChangeListener *dcl)
thsc304f7e2008-01-22 23:25:15 +00001999{
Peter Maydell6e657e62013-04-22 10:29:46 +00002000 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2001
thsc304f7e2008-01-22 23:25:15 +00002002 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
John Arbuckle468a8952015-10-13 21:51:18 +01002003 graphic_hw_update(NULL);
thsc304f7e2008-01-22 23:25:15 +00002004
Akihiko Odaki0337e412023-09-21 17:29:34 +09002005 if (qemu_input_is_absolute(dcl->con)) {
Peter Maydell55888402019-02-25 10:24:33 +00002006 dispatch_async(dispatch_get_main_queue(), ^{
2007 if (![cocoaView isAbsoluteEnabled]) {
2008 if ([cocoaView isMouseGrabbed]) {
2009 [cocoaView ungrabMouse];
2010 }
thsc304f7e2008-01-22 23:25:15 +00002011 }
Peter Maydell55888402019-02-25 10:24:33 +00002012 [cocoaView setAbsoluteEnabled:YES];
2013 });
thsc304f7e2008-01-22 23:25:15 +00002014 }
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09002015
2016 if (cbchangecount != [[NSPasteboard generalPasteboard] changeCount]) {
2017 qemu_clipboard_info_unref(cbinfo);
2018 cbinfo = qemu_clipboard_info_new(&cbpeer, QEMU_CLIPBOARD_SELECTION_CLIPBOARD);
2019 if ([[NSPasteboard generalPasteboard] availableTypeFromArray:@[NSPasteboardTypeString]]) {
2020 cbinfo->types[QEMU_CLIPBOARD_TYPE_TEXT].available = true;
2021 }
2022 qemu_clipboard_update(cbinfo);
2023 cbchangecount = [[NSPasteboard generalPasteboard] changeCount];
2024 qemu_event_set(&cbevent);
2025 }
2026
Peter Maydell6e657e62013-04-22 10:29:46 +00002027 [pool release];
thsc304f7e2008-01-22 23:25:15 +00002028}
2029
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01002030static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
thsc304f7e2008-01-22 23:25:15 +00002031{
Akihiko Odakibab6a302022-08-19 22:27:54 +09002032 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2033
thsc304f7e2008-01-22 23:25:15 +00002034 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
2035
Akihiko Odakibab6a302022-08-19 22:27:54 +09002036 qemu_main = cocoa_main;
Peter Maydell55888402019-02-25 10:24:33 +00002037
Akihiko Odakibab6a302022-08-19 22:27:54 +09002038 // Pull this console process up to being a fully-fledged graphical
2039 // app with a menubar and Dock icon
2040 ProcessSerialNumber psn = { 0, kCurrentProcess };
2041 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
2042
2043 [QemuApplication sharedApplication];
2044
Akihiko Odakibab6a302022-08-19 22:27:54 +09002045 // Create an Application controller
2046 QemuCocoaAppController *controller = [[QemuCocoaAppController alloc] init];
2047 [NSApp setDelegate:controller];
2048
Programmingkid43227af2015-05-19 09:11:17 +01002049 /* if fullscreen mode is to be used */
Gerd Hoffmann767f9bf2018-02-02 12:10:19 +01002050 if (opts->has_full_screen && opts->full_screen) {
Akihiko Odakibab6a302022-08-19 22:27:54 +09002051 [NSApp activateIgnoringOtherApps: YES];
2052 [controller toggleFullScreen: nil];
Gustavo Noronha Silvaf844cdb2022-03-06 21:11:18 +09002053 }
2054 if (opts->u.cocoa.has_full_grab && opts->u.cocoa.full_grab) {
Akihiko Odakibab6a302022-08-19 22:27:54 +09002055 [controller setFullGrab: nil];
Programmingkid43227af2015-05-19 09:11:17 +01002056 }
Carwyn Ellis69221df2022-01-02 17:41:53 +00002057
Gerd Hoffmann3487da62020-02-06 12:27:50 +01002058 if (opts->has_show_cursor && opts->show_cursor) {
2059 cursor_hide = 0;
2060 }
Gustavo Noronha Silva4797adc2022-03-06 21:11:19 +09002061 if (opts->u.cocoa.has_swap_opt_cmd) {
2062 swap_opt_cmd = opts->u.cocoa.swap_opt_cmd;
2063 }
Programmingkid43227af2015-05-19 09:11:17 +01002064
Carwyn Ellis48941a52022-01-02 17:41:52 +00002065 if (opts->u.cocoa.has_left_command_key && !opts->u.cocoa.left_command_key) {
2066 left_command_key_enabled = 0;
2067 }
2068
Carwyn Ellis5ec08982023-10-27 16:49:20 +01002069 if (opts->u.cocoa.has_zoom_to_fit && opts->u.cocoa.zoom_to_fit) {
2070 stretch_video = true;
2071 }
2072
2073 create_initial_menus();
2074 /*
2075 * Create the menu entries which depend on QEMU state (for consoles
2076 * and removable devices). These make calls back into QEMU functions,
2077 * which is OK because at this point we know that the second thread
Stefan Hajnoczia4a411f2024-01-02 10:35:28 -05002078 * holds the BQL and is synchronously waiting for us to
Carwyn Ellis5ec08982023-10-27 16:49:20 +01002079 * finish.
2080 */
2081 add_console_menu_entries();
2082 addRemovableDevicesMenuItems();
2083
aliguori9794f742009-03-04 19:25:22 +00002084 // register vga output callbacks
Akihiko Odakicc7859c2021-02-19 17:44:19 +09002085 register_displaychangelistener(&dcl);
Akihiko Odaki7e3e20d2021-06-16 23:19:54 +09002086
2087 qemu_event_init(&cbevent, false);
2088 cbowner = [[QemuCocoaPasteboardTypeOwner alloc] init];
2089 qemu_clipboard_peer_register(&cbpeer);
Akihiko Odakibab6a302022-08-19 22:27:54 +09002090
2091 [pool release];
thsc304f7e2008-01-22 23:25:15 +00002092}
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01002093
2094static QemuDisplay qemu_display_cocoa = {
2095 .type = DISPLAY_TYPE_COCOA,
2096 .init = cocoa_display_init,
2097};
2098
2099static void register_cocoa(void)
2100{
2101 qemu_display_register(&qemu_display_cocoa);
2102}
2103
2104type_init(register_cocoa);