blob: f12e21df6e10358a6de3d17a1565cf3aa5a5185c [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
pbrook87ecb682007-11-17 17:14:51 +000030#include "qemu-common.h"
Paolo Bonzini28ecbae2012-11-28 12:06:30 +010031#include "ui/console.h"
Gerd Hoffmann21bae112013-12-04 14:08:04 +010032#include "ui/input.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010033#include "sysemu/sysemu.h"
Markus Armbruster54d31232019-08-12 07:23:59 +020034#include "sysemu/runstate.h"
Markus Armbrustere688df62018-02-01 12:18:31 +010035#include "qapi/error.h"
Markus Armbruster16bf5232018-12-20 09:45:59 +010036#include "qapi/qapi-commands-block.h"
37#include "qapi/qapi-commands-misc.h"
John Arbuckle693a3e02015-06-19 10:53:27 +010038#include "sysemu/blockdev.h"
Programmingkid9e8204b2016-08-15 22:11:06 -040039#include "qemu-version.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020040#include "qemu/main-loop.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020041#include "qemu/module.h"
John Arbuckleaaac7142016-03-23 14:26:18 +000042#include <Carbon/Carbon.h>
Markus Armbruster2e5b09f2019-07-09 17:20:52 +020043#include "hw/core/cpu.h"
bellardda4dbf72005-03-02 22:22:43 +000044
Andreas Färber44e4c0b2009-12-13 00:45:40 +010045#ifndef MAC_OS_X_VERSION_10_5
46#define MAC_OS_X_VERSION_10_5 1050
47#endif
Peter Maydell2ba9de62013-04-22 10:29:49 +000048#ifndef MAC_OS_X_VERSION_10_6
49#define MAC_OS_X_VERSION_10_6 1060
50#endif
Peter Maydellb5725382018-05-29 19:15:23 +010051#ifndef MAC_OS_X_VERSION_10_9
52#define MAC_OS_X_VERSION_10_9 1090
53#endif
Peter Maydell81801ae2015-05-19 09:11:18 +010054#ifndef MAC_OS_X_VERSION_10_10
55#define MAC_OS_X_VERSION_10_10 101000
56#endif
Brendan Shanks4ba967a2017-04-24 23:29:52 -070057#ifndef MAC_OS_X_VERSION_10_12
58#define MAC_OS_X_VERSION_10_12 101200
59#endif
Brendan Shanks5e246002019-01-31 23:12:25 -080060#ifndef MAC_OS_X_VERSION_10_13
61#define MAC_OS_X_VERSION_10_13 101300
62#endif
Andreas Färber44e4c0b2009-12-13 00:45:40 +010063
Brendan Shanks4ba967a2017-04-24 23:29:52 -070064/* macOS 10.12 deprecated many constants, #define the new names for older SDKs */
65#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_12
66#define NSEventMaskAny NSAnyEventMask
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -070067#define NSEventModifierFlagCapsLock NSAlphaShiftKeyMask
68#define NSEventModifierFlagShift NSShiftKeyMask
Brendan Shanks4ba967a2017-04-24 23:29:52 -070069#define NSEventModifierFlagCommand NSCommandKeyMask
70#define NSEventModifierFlagControl NSControlKeyMask
71#define NSEventModifierFlagOption NSAlternateKeyMask
72#define NSEventTypeFlagsChanged NSFlagsChanged
73#define NSEventTypeKeyUp NSKeyUp
74#define NSEventTypeKeyDown NSKeyDown
75#define NSEventTypeMouseMoved NSMouseMoved
76#define NSEventTypeLeftMouseDown NSLeftMouseDown
77#define NSEventTypeRightMouseDown NSRightMouseDown
78#define NSEventTypeOtherMouseDown NSOtherMouseDown
79#define NSEventTypeLeftMouseDragged NSLeftMouseDragged
80#define NSEventTypeRightMouseDragged NSRightMouseDragged
81#define NSEventTypeOtherMouseDragged NSOtherMouseDragged
82#define NSEventTypeLeftMouseUp NSLeftMouseUp
83#define NSEventTypeRightMouseUp NSRightMouseUp
84#define NSEventTypeOtherMouseUp NSOtherMouseUp
85#define NSEventTypeScrollWheel NSScrollWheel
86#define NSTextAlignmentCenter NSCenterTextAlignment
87#define NSWindowStyleMaskBorderless NSBorderlessWindowMask
88#define NSWindowStyleMaskClosable NSClosableWindowMask
89#define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask
90#define NSWindowStyleMaskTitled NSTitledWindowMask
91#endif
Peter Maydellb5725382018-05-29 19:15:23 +010092/* 10.13 deprecates NSFileHandlingPanelOKButton in favour of
93 * NSModalResponseOK, which was introduced in 10.9. Define
94 * it for older versions.
95 */
96#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_9
97#define NSModalResponseOK NSFileHandlingPanelOKButton
98#endif
Brendan Shanks5e246002019-01-31 23:12:25 -080099/* 10.14 deprecates NSOnState and NSOffState in favor of
100 * NSControlStateValueOn/Off, which were introduced in 10.13.
101 * Define for older versions
102 */
103#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
104#define NSControlStateValueOn NSOnState
105#define NSControlStateValueOff NSOffState
106#endif
bellard5b0753e2005-03-01 21:37:28 +0000107
thsc304f7e2008-01-22 23:25:15 +0000108//#define DEBUG
109
110#ifdef DEBUG
111#define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
112#else
113#define COCOA_DEBUG(...) ((void) 0)
114#endif
115
116#define cgrect(nsrect) (*(CGRect *)&(nsrect))
thsc304f7e2008-01-22 23:25:15 +0000117
118typedef struct {
119 int width;
120 int height;
121 int bitsPerComponent;
122 int bitsPerPixel;
123} QEMUScreen;
124
Programmingkid9e8204b2016-08-15 22:11:06 -0400125NSWindow *normalWindow, *about_window;
aliguori9794f742009-03-04 19:25:22 +0000126static DisplayChangeListener *dcl;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100127static int last_buttons;
bellard5b0753e2005-03-01 21:37:28 +0000128
129int gArgc;
130char **gArgv;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100131bool stretch_video;
John Arbuckle8524f1c2015-06-19 10:53:27 +0100132NSTextField *pauseLabel;
John Arbuckle693a3e02015-06-19 10:53:27 +0100133NSArray * supportedImageFileTypes;
bellard5b0753e2005-03-01 21:37:28 +0000134
Peter Maydell55888402019-02-25 10:24:33 +0000135static QemuSemaphore display_init_sem;
136static QemuSemaphore app_started_sem;
137
Peter Maydell60105d72019-02-25 10:24:31 +0000138// Utility functions to run specified code block with iothread lock held
Peter Maydell31819e92019-02-25 10:24:27 +0000139typedef void (^CodeBlock)(void);
Peter Maydell60105d72019-02-25 10:24:31 +0000140typedef bool (^BoolCodeBlock)(void);
Peter Maydell31819e92019-02-25 10:24:27 +0000141
142static void with_iothread_lock(CodeBlock block)
143{
144 bool locked = qemu_mutex_iothread_locked();
145 if (!locked) {
146 qemu_mutex_lock_iothread();
147 }
148 block();
149 if (!locked) {
150 qemu_mutex_unlock_iothread();
151 }
152}
153
Peter Maydell60105d72019-02-25 10:24:31 +0000154static bool bool_with_iothread_lock(BoolCodeBlock block)
155{
156 bool locked = qemu_mutex_iothread_locked();
157 bool val;
158
159 if (!locked) {
160 qemu_mutex_lock_iothread();
161 }
162 val = block();
163 if (!locked) {
164 qemu_mutex_unlock_iothread();
165 }
166 return val;
167}
168
John Arbuckleaaac7142016-03-23 14:26:18 +0000169// Mac to QKeyCode conversion
170const int mac_to_qkeycode_map[] = {
171 [kVK_ANSI_A] = Q_KEY_CODE_A,
172 [kVK_ANSI_B] = Q_KEY_CODE_B,
173 [kVK_ANSI_C] = Q_KEY_CODE_C,
174 [kVK_ANSI_D] = Q_KEY_CODE_D,
175 [kVK_ANSI_E] = Q_KEY_CODE_E,
176 [kVK_ANSI_F] = Q_KEY_CODE_F,
177 [kVK_ANSI_G] = Q_KEY_CODE_G,
178 [kVK_ANSI_H] = Q_KEY_CODE_H,
179 [kVK_ANSI_I] = Q_KEY_CODE_I,
180 [kVK_ANSI_J] = Q_KEY_CODE_J,
181 [kVK_ANSI_K] = Q_KEY_CODE_K,
182 [kVK_ANSI_L] = Q_KEY_CODE_L,
183 [kVK_ANSI_M] = Q_KEY_CODE_M,
184 [kVK_ANSI_N] = Q_KEY_CODE_N,
185 [kVK_ANSI_O] = Q_KEY_CODE_O,
186 [kVK_ANSI_P] = Q_KEY_CODE_P,
187 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
188 [kVK_ANSI_R] = Q_KEY_CODE_R,
189 [kVK_ANSI_S] = Q_KEY_CODE_S,
190 [kVK_ANSI_T] = Q_KEY_CODE_T,
191 [kVK_ANSI_U] = Q_KEY_CODE_U,
192 [kVK_ANSI_V] = Q_KEY_CODE_V,
193 [kVK_ANSI_W] = Q_KEY_CODE_W,
194 [kVK_ANSI_X] = Q_KEY_CODE_X,
195 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
196 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
ths3b46e622007-09-17 08:09:54 +0000197
John Arbuckleaaac7142016-03-23 14:26:18 +0000198 [kVK_ANSI_0] = Q_KEY_CODE_0,
199 [kVK_ANSI_1] = Q_KEY_CODE_1,
200 [kVK_ANSI_2] = Q_KEY_CODE_2,
201 [kVK_ANSI_3] = Q_KEY_CODE_3,
202 [kVK_ANSI_4] = Q_KEY_CODE_4,
203 [kVK_ANSI_5] = Q_KEY_CODE_5,
204 [kVK_ANSI_6] = Q_KEY_CODE_6,
205 [kVK_ANSI_7] = Q_KEY_CODE_7,
206 [kVK_ANSI_8] = Q_KEY_CODE_8,
207 [kVK_ANSI_9] = Q_KEY_CODE_9,
208
209 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
210 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
211 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
212 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
213 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
214 [kVK_Tab] = Q_KEY_CODE_TAB,
215 [kVK_Return] = Q_KEY_CODE_RET,
216 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
217 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
218 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
219 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
220 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
221 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
222 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
223 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
224 [kVK_Shift] = Q_KEY_CODE_SHIFT,
225 [kVK_RightShift] = Q_KEY_CODE_SHIFT_R,
226 [kVK_Control] = Q_KEY_CODE_CTRL,
227 [kVK_RightControl] = Q_KEY_CODE_CTRL_R,
228 [kVK_Option] = Q_KEY_CODE_ALT,
229 [kVK_RightOption] = Q_KEY_CODE_ALT_R,
230 [kVK_Command] = Q_KEY_CODE_META_L,
231 [0x36] = Q_KEY_CODE_META_R, /* There is no kVK_RightCommand */
232 [kVK_Space] = Q_KEY_CODE_SPC,
233
234 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
235 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
236 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
237 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
238 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
239 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
240 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
241 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
242 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
243 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
244 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
245 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
246 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
247 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
248 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
249 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
250 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
251 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
252
253 [kVK_UpArrow] = Q_KEY_CODE_UP,
254 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
255 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
256 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
257
258 [kVK_Help] = Q_KEY_CODE_INSERT,
259 [kVK_Home] = Q_KEY_CODE_HOME,
260 [kVK_PageUp] = Q_KEY_CODE_PGUP,
261 [kVK_PageDown] = Q_KEY_CODE_PGDN,
262 [kVK_End] = Q_KEY_CODE_END,
263 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
264
265 [kVK_Escape] = Q_KEY_CODE_ESC,
266
267 /* The Power key can't be used directly because the operating system uses
268 * it. This key can be emulated by using it in place of another key such as
269 * F1. Don't forget to disable the real key binding.
270 */
271 /* [kVK_F1] = Q_KEY_CODE_POWER, */
272
273 [kVK_F1] = Q_KEY_CODE_F1,
274 [kVK_F2] = Q_KEY_CODE_F2,
275 [kVK_F3] = Q_KEY_CODE_F3,
276 [kVK_F4] = Q_KEY_CODE_F4,
277 [kVK_F5] = Q_KEY_CODE_F5,
278 [kVK_F6] = Q_KEY_CODE_F6,
279 [kVK_F7] = Q_KEY_CODE_F7,
280 [kVK_F8] = Q_KEY_CODE_F8,
281 [kVK_F9] = Q_KEY_CODE_F9,
282 [kVK_F10] = Q_KEY_CODE_F10,
283 [kVK_F11] = Q_KEY_CODE_F11,
284 [kVK_F12] = Q_KEY_CODE_F12,
285 [kVK_F13] = Q_KEY_CODE_PRINT,
286 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
287 [kVK_F15] = Q_KEY_CODE_PAUSE,
288
289 /*
290 * The eject and volume keys can't be used here because they are handled at
291 * a lower level than what an Application can see.
292 */
bellard5b0753e2005-03-01 21:37:28 +0000293};
294
Andreas Färber77047bb2009-12-13 00:55:53 +0100295static int cocoa_keycode_to_qemu(int keycode)
bellard5b0753e2005-03-01 21:37:28 +0000296{
John Arbuckleaaac7142016-03-23 14:26:18 +0000297 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
Peter Maydell01cc4e62013-12-08 22:59:04 +0000298 fprintf(stderr, "(cocoa) warning unknown keycode 0x%x\n", keycode);
bellard5b0753e2005-03-01 21:37:28 +0000299 return 0;
300 }
John Arbuckleaaac7142016-03-23 14:26:18 +0000301 return mac_to_qkeycode_map[keycode];
bellard5b0753e2005-03-01 21:37:28 +0000302}
303
John Arbuckle693a3e02015-06-19 10:53:27 +0100304/* Displays an alert dialog box with the specified message */
305static void QEMU_Alert(NSString *message)
306{
307 NSAlert *alert;
308 alert = [NSAlert new];
309 [alert setMessageText: message];
310 [alert runModal];
311}
thsc304f7e2008-01-22 23:25:15 +0000312
John Arbuckle693a3e02015-06-19 10:53:27 +0100313/* Handles any errors that happen with a device transaction */
314static void handleAnyDeviceErrors(Error * err)
315{
316 if (err) {
317 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
318 encoding: NSASCIIStringEncoding]);
319 error_free(err);
320 }
321}
thsc304f7e2008-01-22 23:25:15 +0000322
bellard5b0753e2005-03-01 21:37:28 +0000323/*
324 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +0000325 QemuCocoaView
bellard5b0753e2005-03-01 21:37:28 +0000326 ------------------------------------------------------
327*/
thsc304f7e2008-01-22 23:25:15 +0000328@interface QemuCocoaView : NSView
bellard5b0753e2005-03-01 21:37:28 +0000329{
thsc304f7e2008-01-22 23:25:15 +0000330 QEMUScreen screen;
331 NSWindow *fullScreenWindow;
332 float cx,cy,cw,ch,cdx,cdy;
333 CGDataProviderRef dataProviderRef;
Peter Maydell55888402019-02-25 10:24:33 +0000334 pixman_image_t *pixman_image;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700335 BOOL modifiers_state[256];
Peter Maydell49b9bd42013-12-08 22:59:03 +0000336 BOOL isMouseGrabbed;
thsc304f7e2008-01-22 23:25:15 +0000337 BOOL isFullscreen;
338 BOOL isAbsoluteEnabled;
Peter Maydellf61c3872014-06-23 10:35:24 +0100339 BOOL isMouseDeassociated;
thsc304f7e2008-01-22 23:25:15 +0000340}
Peter Maydell72a3e312019-02-25 10:24:28 +0000341- (void) switchSurface:(pixman_image_t *)image;
thsc304f7e2008-01-22 23:25:15 +0000342- (void) grabMouse;
343- (void) ungrabMouse;
344- (void) toggleFullScreen:(id)sender;
John Arbuckle9c3a4182017-11-07 10:14:14 +0000345- (void) handleMonitorInput:(NSEvent *)event;
Peter Maydell60105d72019-02-25 10:24:31 +0000346- (bool) handleEvent:(NSEvent *)event;
347- (bool) handleEventLocked:(NSEvent *)event;
thsc304f7e2008-01-22 23:25:15 +0000348- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
Peter Maydellf61c3872014-06-23 10:35:24 +0100349/* The state surrounding mouse grabbing is potentially confusing.
350 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
351 * pointing device an absolute-position one?"], but is only updated on
352 * next refresh.
353 * isMouseGrabbed tracks whether GUI events are directed to the guest;
354 * it controls whether special keys like Cmd get sent to the guest,
355 * and whether we capture the mouse when in non-absolute mode.
356 * isMouseDeassociated tracks whether we've told MacOSX to disassociate
357 * the mouse and mouse cursor position by calling
358 * CGAssociateMouseAndMouseCursorPosition(FALSE)
359 * (which basically happens if we grab in non-absolute mode).
360 */
Peter Maydell49b9bd42013-12-08 22:59:03 +0000361- (BOOL) isMouseGrabbed;
thsc304f7e2008-01-22 23:25:15 +0000362- (BOOL) isAbsoluteEnabled;
Peter Maydellf61c3872014-06-23 10:35:24 +0100363- (BOOL) isMouseDeassociated;
thsc304f7e2008-01-22 23:25:15 +0000364- (float) cdx;
365- (float) cdy;
366- (QEMUScreen) gscreen;
John Arbuckle3b178b72015-09-25 23:14:00 +0100367- (void) raiseAllKeys;
thsc304f7e2008-01-22 23:25:15 +0000368@end
ths3b46e622007-09-17 08:09:54 +0000369
Andreas Färber7fee1992011-06-09 20:53:32 +0200370QemuCocoaView *cocoaView;
371
thsc304f7e2008-01-22 23:25:15 +0000372@implementation QemuCocoaView
373- (id)initWithFrame:(NSRect)frameRect
374{
375 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
ths3b46e622007-09-17 08:09:54 +0000376
thsc304f7e2008-01-22 23:25:15 +0000377 self = [super initWithFrame:frameRect];
378 if (self) {
pbrook95219892006-04-09 01:06:34 +0000379
thsc304f7e2008-01-22 23:25:15 +0000380 screen.bitsPerComponent = 8;
381 screen.bitsPerPixel = 32;
382 screen.width = frameRect.size.width;
383 screen.height = frameRect.size.height;
bellard7c206a72005-12-18 19:18:45 +0000384
thsc304f7e2008-01-22 23:25:15 +0000385 }
386 return self;
387}
bellard7c206a72005-12-18 19:18:45 +0000388
thsc304f7e2008-01-22 23:25:15 +0000389- (void) dealloc
390{
391 COCOA_DEBUG("QemuCocoaView: dealloc\n");
bellard7c206a72005-12-18 19:18:45 +0000392
Peter Maydell55888402019-02-25 10:24:33 +0000393 if (dataProviderRef) {
thsc304f7e2008-01-22 23:25:15 +0000394 CGDataProviderRelease(dataProviderRef);
Peter Maydell55888402019-02-25 10:24:33 +0000395 pixman_image_unref(pixman_image);
396 }
ths3b46e622007-09-17 08:09:54 +0000397
thsc304f7e2008-01-22 23:25:15 +0000398 [super dealloc];
399}
bellard5cbfcd02006-06-14 15:53:24 +0000400
Andreas Färberd50f71d2009-12-13 02:03:33 +0100401- (BOOL) isOpaque
402{
403 return YES;
404}
405
Peter Maydell5dd45be2014-06-23 10:35:23 +0100406- (BOOL) screenContainsPoint:(NSPoint) p
407{
408 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
409}
410
Chen Zhang2044dff2019-06-04 17:36:00 +0800411/* Get location of event and convert to virtual screen coordinate */
412- (CGPoint) screenLocationOfEvent:(NSEvent *)ev
413{
414 NSWindow *eventWindow = [ev window];
415 // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
416 CGRect r = CGRectZero;
417 r.origin = [ev locationInWindow];
418 if (!eventWindow) {
419 if (!isFullscreen) {
420 return [[self window] convertRectFromScreen:r].origin;
421 } else {
422 CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
423 CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
424 if (stretch_video) {
425 loc.x /= cdx;
426 loc.y /= cdy;
427 }
428 return loc;
429 }
430 } else if ([[self window] isEqual:eventWindow]) {
431 if (!isFullscreen) {
432 return r.origin;
433 } else {
434 CGPoint loc = [self convertPoint:r.origin fromView:nil];
435 if (stretch_video) {
436 loc.x /= cdx;
437 loc.y /= cdy;
438 }
439 return loc;
440 }
441 } else {
442 return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
443 }
444}
445
Peter Maydell13aefd32014-06-23 10:35:25 +0100446- (void) hideCursor
447{
448 if (!cursor_hide) {
449 return;
450 }
451 [NSCursor hide];
452}
453
454- (void) unhideCursor
455{
456 if (!cursor_hide) {
457 return;
458 }
459 [NSCursor unhide];
460}
461
thsc304f7e2008-01-22 23:25:15 +0000462- (void) drawRect:(NSRect) rect
463{
464 COCOA_DEBUG("QemuCocoaView: drawRect\n");
bellard5cbfcd02006-06-14 15:53:24 +0000465
thsc304f7e2008-01-22 23:25:15 +0000466 // get CoreGraphic context
Brendan Shanks5e246002019-01-31 23:12:25 -0800467#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10
thsc304f7e2008-01-22 23:25:15 +0000468 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] graphicsPort];
Brendan Shanks5e246002019-01-31 23:12:25 -0800469#else
470 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
471#endif
472
thsc304f7e2008-01-22 23:25:15 +0000473 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
474 CGContextSetShouldAntialias (viewContextRef, NO);
ths3b46e622007-09-17 08:09:54 +0000475
thsc304f7e2008-01-22 23:25:15 +0000476 // draw screen bitmap directly to Core Graphics context
Peter Maydell7d270b12013-12-24 02:51:47 +0000477 if (!dataProviderRef) {
478 // Draw request before any guest device has set up a framebuffer:
479 // just draw an opaque black rectangle
480 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
481 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
482 } else {
thsc304f7e2008-01-22 23:25:15 +0000483 CGImageRef imageRef = CGImageCreate(
484 screen.width, //width
485 screen.height, //height
486 screen.bitsPerComponent, //bitsPerComponent
487 screen.bitsPerPixel, //bitsPerPixel
aliguori9794f742009-03-04 19:25:22 +0000488 (screen.width * (screen.bitsPerComponent/2)), //bytesPerRow
Andreas Färber04afa4a2009-12-13 00:58:21 +0100489#ifdef __LITTLE_ENDIAN__
thsc304f7e2008-01-22 23:25:15 +0000490 CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
aliguori9794f742009-03-04 19:25:22 +0000491 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
thsc304f7e2008-01-22 23:25:15 +0000492#else
493 CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
494 kCGImageAlphaNoneSkipFirst, //bitmapInfo
495#endif
496 dataProviderRef, //provider
497 NULL, //decode
498 0, //interpolate
499 kCGRenderingIntentDefault //intent
500 );
Peter Maydellb63901d2015-05-19 09:11:17 +0100501 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
502 const NSRect *rectList;
Peter Maydellb63901d2015-05-19 09:11:17 +0100503 NSInteger rectCount;
Peter Maydellb63901d2015-05-19 09:11:17 +0100504 int i;
505 CGImageRef clipImageRef;
506 CGRect clipRect;
ths3b46e622007-09-17 08:09:54 +0000507
Peter Maydellb63901d2015-05-19 09:11:17 +0100508 [self getRectsBeingDrawn:&rectList count:&rectCount];
509 for (i = 0; i < rectCount; i++) {
510 clipRect.origin.x = rectList[i].origin.x / cdx;
511 clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
512 clipRect.size.width = rectList[i].size.width / cdx;
513 clipRect.size.height = rectList[i].size.height / cdy;
514 clipImageRef = CGImageCreateWithImageInRect(
515 imageRef,
516 clipRect
517 );
518 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
519 CGImageRelease (clipImageRef);
bellard5b0753e2005-03-01 21:37:28 +0000520 }
thsc304f7e2008-01-22 23:25:15 +0000521 CGImageRelease (imageRef);
bellard5b0753e2005-03-01 21:37:28 +0000522 }
523}
524
thsc304f7e2008-01-22 23:25:15 +0000525- (void) setContentDimensions
bellard5b0753e2005-03-01 21:37:28 +0000526{
thsc304f7e2008-01-22 23:25:15 +0000527 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
ths3b46e622007-09-17 08:09:54 +0000528
thsc304f7e2008-01-22 23:25:15 +0000529 if (isFullscreen) {
530 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
531 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100532
533 /* stretches video, but keeps same aspect ratio */
534 if (stretch_video == true) {
535 /* use smallest stretch value - prevents clipping on sides */
536 if (MIN(cdx, cdy) == cdx) {
537 cdy = cdx;
538 } else {
539 cdx = cdy;
540 }
541 } else { /* No stretching */
542 cdx = cdy = 1;
543 }
thsc304f7e2008-01-22 23:25:15 +0000544 cw = screen.width * cdx;
545 ch = screen.height * cdy;
546 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
547 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
548 } else {
549 cx = 0;
550 cy = 0;
551 cw = screen.width;
552 ch = screen.height;
553 cdx = 1.0;
554 cdy = 1.0;
555 }
bellard5b0753e2005-03-01 21:37:28 +0000556}
557
Peter Maydell72a3e312019-02-25 10:24:28 +0000558- (void) switchSurface:(pixman_image_t *)image
thsc304f7e2008-01-22 23:25:15 +0000559{
Gerd Hoffmann5e00d3a2013-03-01 12:52:06 +0100560 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
thsc304f7e2008-01-22 23:25:15 +0000561
Peter Maydell72a3e312019-02-25 10:24:28 +0000562 int w = pixman_image_get_width(image);
563 int h = pixman_image_get_height(image);
564 pixman_format_code_t image_format = pixman_image_get_format(image);
Peter Maydell381600d2014-06-23 10:35:22 +0100565 /* cdx == 0 means this is our very first surface, in which case we need
566 * to recalculate the content dimensions even if it happens to be the size
567 * of the initial empty window.
568 */
569 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
Peter Maydelld3345a02013-12-24 02:51:46 +0000570
571 int oldh = screen.height;
572 if (isResize) {
573 // Resize before we trigger the redraw, or we'll redraw at the wrong size
574 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
575 screen.width = w;
576 screen.height = h;
577 [self setContentDimensions];
578 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
579 }
Peter Maydell8510d912013-03-18 20:28:21 +0000580
thsc304f7e2008-01-22 23:25:15 +0000581 // update screenBuffer
Peter Maydell55888402019-02-25 10:24:33 +0000582 if (dataProviderRef) {
thsc304f7e2008-01-22 23:25:15 +0000583 CGDataProviderRelease(dataProviderRef);
Peter Maydell55888402019-02-25 10:24:33 +0000584 pixman_image_unref(pixman_image);
585 }
thsc304f7e2008-01-22 23:25:15 +0000586
aliguori9794f742009-03-04 19:25:22 +0000587 //sync host window color space with guests
Peter Maydell72a3e312019-02-25 10:24:28 +0000588 screen.bitsPerPixel = PIXMAN_FORMAT_BPP(image_format);
589 screen.bitsPerComponent = DIV_ROUND_UP(screen.bitsPerPixel, 8) * 2;
thsc304f7e2008-01-22 23:25:15 +0000590
Peter Maydell55888402019-02-25 10:24:33 +0000591 pixman_image = image;
Peter Maydell72a3e312019-02-25 10:24:28 +0000592 dataProviderRef = CGDataProviderCreateWithData(NULL, pixman_image_get_data(image), w * 4 * h, NULL);
thsc304f7e2008-01-22 23:25:15 +0000593
594 // update windows
595 if (isFullscreen) {
596 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
Peter Maydelld3345a02013-12-24 02:51:46 +0000597 [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 +0000598 } else {
599 if (qemu_name)
600 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
Peter Maydelld3345a02013-12-24 02:51:46 +0000601 [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 +0000602 }
Peter Maydelld3345a02013-12-24 02:51:46 +0000603
604 if (isResize) {
605 [normalWindow center];
606 }
thsc304f7e2008-01-22 23:25:15 +0000607}
608
609- (void) toggleFullScreen:(id)sender
610{
611 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
612
613 if (isFullscreen) { // switch from fullscreen to desktop
614 isFullscreen = FALSE;
615 [self ungrabMouse];
616 [self setContentDimensions];
thsc304f7e2008-01-22 23:25:15 +0000617 if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
618 [self exitFullScreenModeWithOptions:nil];
619 } else {
thsc304f7e2008-01-22 23:25:15 +0000620 [fullScreenWindow close];
621 [normalWindow setContentView: self];
622 [normalWindow makeKeyAndOrderFront: self];
623 [NSMenu setMenuBarVisible:YES];
thsc304f7e2008-01-22 23:25:15 +0000624 }
thsc304f7e2008-01-22 23:25:15 +0000625 } else { // switch from desktop to fullscreen
626 isFullscreen = TRUE;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100627 [normalWindow orderOut: nil]; /* Hide the window */
thsc304f7e2008-01-22 23:25:15 +0000628 [self grabMouse];
629 [self setContentDimensions];
thsc304f7e2008-01-22 23:25:15 +0000630 if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
631 [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
632 [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
633 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
634 nil]];
635 } else {
thsc304f7e2008-01-22 23:25:15 +0000636 [NSMenu setMenuBarVisible:NO];
637 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700638 styleMask:NSWindowStyleMaskBorderless
thsc304f7e2008-01-22 23:25:15 +0000639 backing:NSBackingStoreBuffered
640 defer:NO];
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100641 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
thsc304f7e2008-01-22 23:25:15 +0000642 [fullScreenWindow setHasShadow:NO];
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100643 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
644 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
645 [[fullScreenWindow contentView] addSubview: self];
thsc304f7e2008-01-22 23:25:15 +0000646 [fullScreenWindow makeKeyAndOrderFront:self];
thsc304f7e2008-01-22 23:25:15 +0000647 }
thsc304f7e2008-01-22 23:25:15 +0000648 }
649}
650
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700651- (void) toggleModifier: (int)keycode {
652 // Toggle the stored state.
653 modifiers_state[keycode] = !modifiers_state[keycode];
654 // Send a keyup or keydown depending on the state.
655 qemu_input_event_send_key_qcode(dcl->con, keycode, modifiers_state[keycode]);
656}
657
658- (void) toggleStatefulModifier: (int)keycode {
659 // Toggle the stored state.
660 modifiers_state[keycode] = !modifiers_state[keycode];
661 // Generate keydown and keyup.
662 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
663 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
664}
665
John Arbuckle9c3a4182017-11-07 10:14:14 +0000666// Does the work of sending input to the monitor
667- (void) handleMonitorInput:(NSEvent *)event
668{
669 int keysym = 0;
670 int control_key = 0;
671
672 // if the control key is down
673 if ([event modifierFlags] & NSEventModifierFlagControl) {
674 control_key = 1;
675 }
676
677 /* translates Macintosh keycodes to QEMU's keysym */
678
679 int without_control_translation[] = {
680 [0 ... 0xff] = 0, // invalid key
681
682 [kVK_UpArrow] = QEMU_KEY_UP,
683 [kVK_DownArrow] = QEMU_KEY_DOWN,
684 [kVK_RightArrow] = QEMU_KEY_RIGHT,
685 [kVK_LeftArrow] = QEMU_KEY_LEFT,
686 [kVK_Home] = QEMU_KEY_HOME,
687 [kVK_End] = QEMU_KEY_END,
688 [kVK_PageUp] = QEMU_KEY_PAGEUP,
689 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
690 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
691 [kVK_Delete] = QEMU_KEY_BACKSPACE,
692 };
693
694 int with_control_translation[] = {
695 [0 ... 0xff] = 0, // invalid key
696
697 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
698 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
699 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
700 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
701 [kVK_Home] = QEMU_KEY_CTRL_HOME,
702 [kVK_End] = QEMU_KEY_CTRL_END,
703 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
704 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
705 };
706
707 if (control_key != 0) { /* If the control key is being used */
708 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
709 keysym = with_control_translation[[event keyCode]];
710 }
711 } else {
712 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
713 keysym = without_control_translation[[event keyCode]];
714 }
715 }
716
717 // if not a key that needs translating
718 if (keysym == 0) {
719 NSString *ks = [event characters];
720 if ([ks length] > 0) {
721 keysym = [ks characterAtIndex:0];
722 }
723 }
724
725 if (keysym) {
726 kbd_put_keysym(keysym);
727 }
728}
729
Peter Maydell60105d72019-02-25 10:24:31 +0000730- (bool) handleEvent:(NSEvent *)event
thsc304f7e2008-01-22 23:25:15 +0000731{
Peter Maydell60105d72019-02-25 10:24:31 +0000732 return bool_with_iothread_lock(^{
733 return [self handleEventLocked:event];
Peter Maydell31819e92019-02-25 10:24:27 +0000734 });
735}
thsc304f7e2008-01-22 23:25:15 +0000736
Peter Maydell60105d72019-02-25 10:24:31 +0000737- (bool) handleEventLocked:(NSEvent *)event
Peter Maydell31819e92019-02-25 10:24:27 +0000738{
Peter Maydell60105d72019-02-25 10:24:31 +0000739 /* Return true if we handled the event, false if it should be given to OSX */
Peter Maydell31819e92019-02-25 10:24:27 +0000740 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
thsc304f7e2008-01-22 23:25:15 +0000741 int buttons = 0;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700742 int keycode = 0;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100743 bool mouse_event = false;
John Arbuckle0c6c4392018-07-02 22:00:17 -0400744 static bool switched_to_fullscreen = false;
Chen Zhang2044dff2019-06-04 17:36:00 +0800745 // Location of event in virtual screen coordinates
746 NSPoint p = [self screenLocationOfEvent:event];
thsc304f7e2008-01-22 23:25:15 +0000747
748 switch ([event type]) {
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700749 case NSEventTypeFlagsChanged:
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700750 if ([event keyCode] == 0) {
751 // When the Cocoa keyCode is zero that means keys should be
752 // synthesized based on the values in in the eventModifiers
753 // bitmask.
754
755 if (qemu_console_is_graphic(NULL)) {
John Arbucklee7206242017-06-28 15:37:16 -0400756 NSUInteger modifiers = [event modifierFlags];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700757
758 if (!!(modifiers & NSEventModifierFlagCapsLock) != !!modifiers_state[Q_KEY_CODE_CAPS_LOCK]) {
759 [self toggleStatefulModifier:Q_KEY_CODE_CAPS_LOCK];
760 }
761 if (!!(modifiers & NSEventModifierFlagShift) != !!modifiers_state[Q_KEY_CODE_SHIFT]) {
762 [self toggleModifier:Q_KEY_CODE_SHIFT];
763 }
764 if (!!(modifiers & NSEventModifierFlagControl) != !!modifiers_state[Q_KEY_CODE_CTRL]) {
765 [self toggleModifier:Q_KEY_CODE_CTRL];
766 }
767 if (!!(modifiers & NSEventModifierFlagOption) != !!modifiers_state[Q_KEY_CODE_ALT]) {
768 [self toggleModifier:Q_KEY_CODE_ALT];
769 }
770 if (!!(modifiers & NSEventModifierFlagCommand) != !!modifiers_state[Q_KEY_CODE_META_L]) {
771 [self toggleModifier:Q_KEY_CODE_META_L];
772 }
773 }
774 } else {
775 keycode = cocoa_keycode_to_qemu([event keyCode]);
776 }
Peter Maydell88959192013-12-08 22:59:02 +0000777
John Arbuckleaaac7142016-03-23 14:26:18 +0000778 if ((keycode == Q_KEY_CODE_META_L || keycode == Q_KEY_CODE_META_R)
779 && !isMouseGrabbed) {
Peter Maydell88959192013-12-08 22:59:02 +0000780 /* Don't pass command key changes to guest unless mouse is grabbed */
781 keycode = 0;
782 }
783
thsc304f7e2008-01-22 23:25:15 +0000784 if (keycode) {
John Arbuckleaaac7142016-03-23 14:26:18 +0000785 // emulate caps lock and num lock keydown and keyup
786 if (keycode == Q_KEY_CODE_CAPS_LOCK ||
787 keycode == Q_KEY_CODE_NUM_LOCK) {
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700788 [self toggleStatefulModifier:keycode];
Peter Maydell68c0aa62013-04-17 09:16:35 +0000789 } else if (qemu_console_is_graphic(NULL)) {
John Arbuckle0c6c4392018-07-02 22:00:17 -0400790 if (switched_to_fullscreen) {
791 switched_to_fullscreen = false;
792 } else {
793 [self toggleModifier:keycode];
794 }
thsc304f7e2008-01-22 23:25:15 +0000795 }
796 }
797
thsc304f7e2008-01-22 23:25:15 +0000798 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700799 case NSEventTypeKeyDown:
Peter Maydell88959192013-12-08 22:59:02 +0000800 keycode = cocoa_keycode_to_qemu([event keyCode]);
thsc304f7e2008-01-22 23:25:15 +0000801
Peter Maydell88959192013-12-08 22:59:02 +0000802 // forward command key combos to the host UI unless the mouse is grabbed
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700803 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
John Arbuckle0c6c4392018-07-02 22:00:17 -0400804 /*
805 * Prevent the command key from being stuck down in the guest
806 * when using Command-F to switch to full screen mode.
807 */
808 if (keycode == Q_KEY_CODE_F) {
809 switched_to_fullscreen = true;
810 }
Peter Maydell60105d72019-02-25 10:24:31 +0000811 return false;
thsc304f7e2008-01-22 23:25:15 +0000812 }
813
814 // default
thsc304f7e2008-01-22 23:25:15 +0000815
John Arbuckle5929e362017-11-07 10:14:14 +0000816 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700817 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
John Arbuckle5929e362017-11-07 10:14:14 +0000818 NSString *keychar = [event charactersIgnoringModifiers];
819 if ([keychar length] == 1) {
820 char key = [keychar characterAtIndex:0];
821 switch (key) {
thsc304f7e2008-01-22 23:25:15 +0000822
John Arbuckle5929e362017-11-07 10:14:14 +0000823 // enable graphic console
824 case '1' ... '9':
825 console_select(key - '0' - 1); /* ascii math */
Peter Maydell60105d72019-02-25 10:24:31 +0000826 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000827
828 // release the mouse grab
829 case 'g':
830 [self ungrabMouse];
Peter Maydell60105d72019-02-25 10:24:31 +0000831 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000832 }
thsc304f7e2008-01-22 23:25:15 +0000833 }
Peter Maydellef2088f2017-11-07 10:14:14 +0000834 }
thsc304f7e2008-01-22 23:25:15 +0000835
Peter Maydellef2088f2017-11-07 10:14:14 +0000836 if (qemu_console_is_graphic(NULL)) {
John Arbuckleaaac7142016-03-23 14:26:18 +0000837 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
thsc304f7e2008-01-22 23:25:15 +0000838 } else {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000839 [self handleMonitorInput: event];
thsc304f7e2008-01-22 23:25:15 +0000840 }
841 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700842 case NSEventTypeKeyUp:
thsc304f7e2008-01-22 23:25:15 +0000843 keycode = cocoa_keycode_to_qemu([event keyCode]);
Peter Maydell88959192013-12-08 22:59:02 +0000844
845 // don't pass the guest a spurious key-up if we treated this
846 // command-key combo as a host UI action
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700847 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
Peter Maydell60105d72019-02-25 10:24:31 +0000848 return true;
Peter Maydell88959192013-12-08 22:59:02 +0000849 }
850
Peter Maydell68c0aa62013-04-17 09:16:35 +0000851 if (qemu_console_is_graphic(NULL)) {
John Arbuckleaaac7142016-03-23 14:26:18 +0000852 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
thsc304f7e2008-01-22 23:25:15 +0000853 }
854 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700855 case NSEventTypeMouseMoved:
thsc304f7e2008-01-22 23:25:15 +0000856 if (isAbsoluteEnabled) {
Chen Zhang2044dff2019-06-04 17:36:00 +0800857 // Cursor re-entered into a window might generate events bound to screen coordinates
858 // and `nil` window property, and in full screen mode, current window might not be
859 // key window, where event location alone should suffice.
860 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
Peter Maydellf61c3872014-06-23 10:35:24 +0100861 if (isMouseGrabbed) {
862 [self ungrabMouse];
thsc304f7e2008-01-22 23:25:15 +0000863 }
864 } else {
Peter Maydellf61c3872014-06-23 10:35:24 +0100865 if (!isMouseGrabbed) {
866 [self grabMouse];
thsc304f7e2008-01-22 23:25:15 +0000867 }
868 }
869 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100870 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000871 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700872 case NSEventTypeLeftMouseDown:
873 if ([event modifierFlags] & NSEventModifierFlagCommand) {
thsc304f7e2008-01-22 23:25:15 +0000874 buttons |= MOUSE_EVENT_RBUTTON;
875 } else {
876 buttons |= MOUSE_EVENT_LBUTTON;
877 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100878 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000879 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700880 case NSEventTypeRightMouseDown:
thsc304f7e2008-01-22 23:25:15 +0000881 buttons |= MOUSE_EVENT_RBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100882 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000883 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700884 case NSEventTypeOtherMouseDown:
thsc304f7e2008-01-22 23:25:15 +0000885 buttons |= MOUSE_EVENT_MBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100886 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000887 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700888 case NSEventTypeLeftMouseDragged:
889 if ([event modifierFlags] & NSEventModifierFlagCommand) {
thsc304f7e2008-01-22 23:25:15 +0000890 buttons |= MOUSE_EVENT_RBUTTON;
891 } else {
892 buttons |= MOUSE_EVENT_LBUTTON;
893 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100894 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000895 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700896 case NSEventTypeRightMouseDragged:
thsc304f7e2008-01-22 23:25:15 +0000897 buttons |= MOUSE_EVENT_RBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100898 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000899 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700900 case NSEventTypeOtherMouseDragged:
thsc304f7e2008-01-22 23:25:15 +0000901 buttons |= MOUSE_EVENT_MBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100902 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000903 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700904 case NSEventTypeLeftMouseUp:
Peter Maydellf61c3872014-06-23 10:35:24 +0100905 mouse_event = true;
906 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
Chen Zhang8e23e342019-06-04 17:36:48 +0800907 /*
908 * In fullscreen mode, the window of cocoaView may not be the
909 * key window, therefore the position relative to the virtual
910 * screen alone will be sufficient.
911 */
912 if(isFullscreen || [[self window] isKeyWindow]) {
Programmingkid9e8204b2016-08-15 22:11:06 -0400913 [self grabMouse];
914 }
thsc304f7e2008-01-22 23:25:15 +0000915 }
916 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700917 case NSEventTypeRightMouseUp:
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100918 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000919 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700920 case NSEventTypeOtherMouseUp:
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100921 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000922 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700923 case NSEventTypeScrollWheel:
John Arbuckleae7313e2018-01-08 13:07:07 -0500924 /*
925 * Send wheel events to the guest regardless of window focus.
926 * This is in-line with standard Mac OS X UI behaviour.
927 */
928
John Arbuckledc3c89d2018-07-09 11:02:35 -0400929 /*
930 * When deltaY is zero, it means that this scrolling event was
931 * either horizontal, or so fine that it only appears in
932 * scrollingDeltaY. So we drop the event.
933 */
934 if ([event deltaY] != 0) {
John Arbuckleae7313e2018-01-08 13:07:07 -0500935 /* Determine if this is a scroll up or scroll down event */
John Arbuckledc3c89d2018-07-09 11:02:35 -0400936 buttons = ([event deltaY] > 0) ?
937 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
938 qemu_input_queue_btn(dcl->con, buttons, true);
939 qemu_input_event_sync();
940 qemu_input_queue_btn(dcl->con, buttons, false);
941 qemu_input_event_sync();
942 }
John Arbuckleae7313e2018-01-08 13:07:07 -0500943 /*
944 * Since deltaY also reports scroll wheel events we prevent mouse
945 * movement code from executing.
946 */
947 mouse_event = false;
thsc304f7e2008-01-22 23:25:15 +0000948 break;
949 default:
Peter Maydell60105d72019-02-25 10:24:31 +0000950 return false;
thsc304f7e2008-01-22 23:25:15 +0000951 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100952
953 if (mouse_event) {
Peter Maydell8d3a5d92015-11-26 15:19:28 +0000954 /* Don't send button events to the guest unless we've got a
955 * mouse grab or window focus. If we have neither then this event
956 * is the user clicking on the background window to activate and
957 * bring us to the front, which will be done by the sendEvent
958 * call below. We definitely don't want to pass that click through
959 * to the guest.
960 */
961 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
962 (last_buttons != buttons)) {
Eric Blake7fb1cf12015-11-18 01:52:57 -0700963 static uint32_t bmap[INPUT_BUTTON__MAX] = {
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100964 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
965 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
John Arbuckleae7313e2018-01-08 13:07:07 -0500966 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100967 };
968 qemu_input_update_buttons(dcl->con, bmap, last_buttons, buttons);
969 last_buttons = buttons;
970 }
Peter Maydellf61c3872014-06-23 10:35:24 +0100971 if (isMouseGrabbed) {
972 if (isAbsoluteEnabled) {
973 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
974 * The check on screenContainsPoint is to avoid sending out of range values for
975 * clicks in the titlebar.
976 */
977 if ([self screenContainsPoint:p]) {
Philippe Voinov9cfa7ab2017-05-05 15:39:52 +0200978 qemu_input_queue_abs(dcl->con, INPUT_AXIS_X, p.x, 0, screen.width);
979 qemu_input_queue_abs(dcl->con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
Peter Maydellf61c3872014-06-23 10:35:24 +0100980 }
981 } else {
982 qemu_input_queue_rel(dcl->con, INPUT_AXIS_X, (int)[event deltaX]);
983 qemu_input_queue_rel(dcl->con, INPUT_AXIS_Y, (int)[event deltaY]);
984 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100985 } else {
Peter Maydell60105d72019-02-25 10:24:31 +0000986 return false;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100987 }
988 qemu_input_event_sync();
989 }
Peter Maydell60105d72019-02-25 10:24:31 +0000990 return true;
thsc304f7e2008-01-22 23:25:15 +0000991}
992
993- (void) grabMouse
994{
995 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
996
997 if (!isFullscreen) {
998 if (qemu_name)
John Arbuckle5929e362017-11-07 10:14:14 +0000999 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
thsc304f7e2008-01-22 23:25:15 +00001000 else
John Arbuckle5929e362017-11-07 10:14:14 +00001001 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
thsc304f7e2008-01-22 23:25:15 +00001002 }
Peter Maydell13aefd32014-06-23 10:35:25 +01001003 [self hideCursor];
Peter Maydellf61c3872014-06-23 10:35:24 +01001004 if (!isAbsoluteEnabled) {
1005 isMouseDeassociated = TRUE;
1006 CGAssociateMouseAndMouseCursorPosition(FALSE);
1007 }
Peter Maydell49b9bd42013-12-08 22:59:03 +00001008 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
thsc304f7e2008-01-22 23:25:15 +00001009}
1010
1011- (void) ungrabMouse
1012{
1013 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
1014
1015 if (!isFullscreen) {
1016 if (qemu_name)
1017 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
1018 else
1019 [normalWindow setTitle:@"QEMU"];
1020 }
Peter Maydell13aefd32014-06-23 10:35:25 +01001021 [self unhideCursor];
Peter Maydellf61c3872014-06-23 10:35:24 +01001022 if (isMouseDeassociated) {
1023 CGAssociateMouseAndMouseCursorPosition(TRUE);
1024 isMouseDeassociated = FALSE;
1025 }
Peter Maydell49b9bd42013-12-08 22:59:03 +00001026 isMouseGrabbed = FALSE;
thsc304f7e2008-01-22 23:25:15 +00001027}
1028
1029- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
Peter Maydell49b9bd42013-12-08 22:59:03 +00001030- (BOOL) isMouseGrabbed {return isMouseGrabbed;}
thsc304f7e2008-01-22 23:25:15 +00001031- (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
Peter Maydellf61c3872014-06-23 10:35:24 +01001032- (BOOL) isMouseDeassociated {return isMouseDeassociated;}
thsc304f7e2008-01-22 23:25:15 +00001033- (float) cdx {return cdx;}
1034- (float) cdy {return cdy;}
1035- (QEMUScreen) gscreen {return screen;}
John Arbuckle3b178b72015-09-25 23:14:00 +01001036
1037/*
1038 * Makes the target think all down keys are being released.
1039 * This prevents a stuck key problem, since we will not see
1040 * key up events for those keys after we have lost focus.
1041 */
1042- (void) raiseAllKeys
1043{
John Arbuckle3b178b72015-09-25 23:14:00 +01001044 const int max_index = ARRAY_SIZE(modifiers_state);
1045
Peter Maydell31819e92019-02-25 10:24:27 +00001046 with_iothread_lock(^{
1047 int index;
1048
1049 for (index = 0; index < max_index; index++) {
1050 if (modifiers_state[index]) {
1051 modifiers_state[index] = 0;
1052 qemu_input_event_send_key_qcode(dcl->con, index, false);
1053 }
1054 }
1055 });
John Arbuckle3b178b72015-09-25 23:14:00 +01001056}
bellard5b0753e2005-03-01 21:37:28 +00001057@end
1058
1059
thsc304f7e2008-01-22 23:25:15 +00001060
bellard5b0753e2005-03-01 21:37:28 +00001061/*
1062 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +00001063 QemuCocoaAppController
bellard5b0753e2005-03-01 21:37:28 +00001064 ------------------------------------------------------
1065*/
thsc304f7e2008-01-22 23:25:15 +00001066@interface QemuCocoaAppController : NSObject
Peter Maydell2a4c8c52015-05-19 09:11:18 +01001067#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
John Arbuckled9bc14f2015-09-25 23:13:59 +01001068 <NSWindowDelegate, NSApplicationDelegate>
Peter Maydell2a4c8c52015-05-19 09:11:18 +01001069#endif
bellard5b0753e2005-03-01 21:37:28 +00001070{
1071}
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001072- (void)doToggleFullScreen:(id)sender;
thsc304f7e2008-01-22 23:25:15 +00001073- (void)toggleFullScreen:(id)sender;
1074- (void)showQEMUDoc:(id)sender;
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001075- (void)zoomToFit:(id) sender;
Programmingkidb4c6a112015-05-19 09:11:18 +01001076- (void)displayConsole:(id)sender;
John Arbuckle8524f1c2015-06-19 10:53:27 +01001077- (void)pauseQEMU:(id)sender;
1078- (void)resumeQEMU:(id)sender;
1079- (void)displayPause;
1080- (void)removePause;
John Arbuckle27074612015-06-19 10:53:27 +01001081- (void)restartQEMU:(id)sender;
1082- (void)powerDownQEMU:(id)sender;
John Arbuckle693a3e02015-06-19 10:53:27 +01001083- (void)ejectDeviceMedia:(id)sender;
1084- (void)changeDeviceMedia:(id)sender;
John Arbuckled9bc14f2015-09-25 23:13:59 +01001085- (BOOL)verifyQuit;
John Arbucklef4747902016-03-23 14:26:17 +00001086- (void)openDocumentation:(NSString *)filename;
Programmingkid9e8204b2016-08-15 22:11:06 -04001087- (IBAction) do_about_menu_item: (id) sender;
1088- (void)make_about_window;
John Arbucklee47ec1a2017-06-13 23:17:38 -04001089- (void)adjustSpeed:(id)sender;
bellard5b0753e2005-03-01 21:37:28 +00001090@end
1091
thsc304f7e2008-01-22 23:25:15 +00001092@implementation QemuCocoaAppController
1093- (id) init
1094{
1095 COCOA_DEBUG("QemuCocoaAppController: init\n");
1096
1097 self = [super init];
1098 if (self) {
1099
1100 // create a view and add it to the window
1101 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1102 if(!cocoaView) {
1103 fprintf(stderr, "(cocoa) can't create a view\n");
1104 exit(1);
1105 }
1106
1107 // create a window
1108 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001109 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
thsc304f7e2008-01-22 23:25:15 +00001110 backing:NSBackingStoreBuffered defer:NO];
1111 if(!normalWindow) {
1112 fprintf(stderr, "(cocoa) can't create window\n");
1113 exit(1);
1114 }
1115 [normalWindow setAcceptsMouseMovedEvents:YES];
John Arbucklea1dbc052015-10-13 21:51:18 +01001116 [normalWindow setTitle:@"QEMU"];
thsc304f7e2008-01-22 23:25:15 +00001117 [normalWindow setContentView:cocoaView];
Peter Maydell81801ae2015-05-19 09:11:18 +01001118#if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10)
Andreas Färber561ef252009-12-13 03:06:20 +01001119 [normalWindow useOptimizedDrawing:YES];
Peter Maydell81801ae2015-05-19 09:11:18 +01001120#endif
thsc304f7e2008-01-22 23:25:15 +00001121 [normalWindow makeKeyAndOrderFront:self];
Peter Maydell49060c22013-12-24 11:54:12 +00001122 [normalWindow center];
John Arbuckled9bc14f2015-09-25 23:13:59 +01001123 [normalWindow setDelegate: self];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001124 stretch_video = false;
John Arbuckle8524f1c2015-06-19 10:53:27 +01001125
1126 /* Used for displaying pause on the screen */
1127 pauseLabel = [NSTextField new];
1128 [pauseLabel setBezeled:YES];
1129 [pauseLabel setDrawsBackground:YES];
1130 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1131 [pauseLabel setEditable:NO];
1132 [pauseLabel setSelectable:NO];
1133 [pauseLabel setStringValue: @"Paused"];
1134 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1135 [pauseLabel setTextColor: [NSColor blackColor]];
1136 [pauseLabel sizeToFit];
John Arbuckle693a3e02015-06-19 10:53:27 +01001137
1138 // set the supported image file types that can be opened
1139 supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
John Arbuckle9d227f12016-03-30 12:37:11 -04001140 @"qcow", @"qcow2", @"cloop", @"vmdk", @"cdr",
Programmingkid5f26fcf2016-12-30 15:42:21 -05001141 @"toast", nil];
Programmingkid9e8204b2016-08-15 22:11:06 -04001142 [self make_about_window];
thsc304f7e2008-01-22 23:25:15 +00001143 }
1144 return self;
1145}
1146
1147- (void) dealloc
1148{
1149 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1150
1151 if (cocoaView)
1152 [cocoaView release];
1153 [super dealloc];
1154}
1155
bellard5b0753e2005-03-01 21:37:28 +00001156- (void)applicationDidFinishLaunching: (NSNotification *) note
1157{
thsc304f7e2008-01-22 23:25:15 +00001158 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
Peter Maydell55888402019-02-25 10:24:33 +00001159 /* Tell cocoa_display_init to proceed */
1160 qemu_sem_post(&app_started_sem);
bellard5b0753e2005-03-01 21:37:28 +00001161}
1162
1163- (void)applicationWillTerminate:(NSNotification *)aNotification
1164{
thsc304f7e2008-01-22 23:25:15 +00001165 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1166
Eric Blakecf83f142017-05-15 16:41:13 -05001167 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
bellard5b0753e2005-03-01 21:37:28 +00001168 exit(0);
1169}
1170
Andreas Färber41ea49b2009-12-14 22:13:27 +01001171- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1172{
1173 return YES;
1174}
1175
John Arbuckled9bc14f2015-09-25 23:13:59 +01001176- (NSApplicationTerminateReply)applicationShouldTerminate:
1177 (NSApplication *)sender
1178{
1179 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1180 return [self verifyQuit];
1181}
1182
1183/* Called when the user clicks on a window's close button */
1184- (BOOL)windowShouldClose:(id)sender
1185{
1186 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1187 [NSApp terminate: sender];
1188 /* If the user allows the application to quit then the call to
1189 * NSApp terminate will never return. If we get here then the user
1190 * cancelled the quit, so we should return NO to not permit the
1191 * closing of this window.
1192 */
1193 return NO;
1194}
1195
John Arbuckle3b178b72015-09-25 23:14:00 +01001196/* Called when QEMU goes into the background */
1197- (void) applicationWillResignActive: (NSNotification *)aNotification
1198{
1199 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1200 [cocoaView raiseAllKeys];
1201}
1202
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001203/* We abstract the method called by the Enter Fullscreen menu item
1204 * because Mac OS 10.7 and higher disables it. This is because of the
1205 * menu item's old selector's name toggleFullScreen:
1206 */
1207- (void) doToggleFullScreen:(id)sender
1208{
1209 [self toggleFullScreen:(id)sender];
1210}
1211
thsc304f7e2008-01-22 23:25:15 +00001212- (void)toggleFullScreen:(id)sender
bellard5b0753e2005-03-01 21:37:28 +00001213{
thsc304f7e2008-01-22 23:25:15 +00001214 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1215
1216 [cocoaView toggleFullScreen:sender];
1217}
1218
John Arbucklef4747902016-03-23 14:26:17 +00001219/* Tries to find then open the specified filename */
1220- (void) openDocumentation: (NSString *) filename
1221{
1222 /* Where to look for local files */
1223 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"../"};
1224 NSString *full_file_path;
1225
1226 /* iterate thru the possible paths until the file is found */
1227 int index;
1228 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1229 full_file_path = [[NSBundle mainBundle] executablePath];
1230 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1231 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1232 path_array[index], filename];
1233 if ([[NSWorkspace sharedWorkspace] openFile: full_file_path] == YES) {
1234 return;
1235 }
1236 }
1237
1238 /* If none of the paths opened a file */
1239 NSBeep();
1240 QEMU_Alert(@"Failed to open file");
1241}
1242
thsc304f7e2008-01-22 23:25:15 +00001243- (void)showQEMUDoc:(id)sender
1244{
1245 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1246
John Arbucklef4747902016-03-23 14:26:17 +00001247 [self openDocumentation: @"qemu-doc.html"];
thsc304f7e2008-01-22 23:25:15 +00001248}
1249
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001250/* Stretches video to fit host monitor size */
1251- (void)zoomToFit:(id) sender
1252{
1253 stretch_video = !stretch_video;
1254 if (stretch_video == true) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001255 [sender setState: NSControlStateValueOn];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001256 } else {
Brendan Shanks5e246002019-01-31 23:12:25 -08001257 [sender setState: NSControlStateValueOff];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001258 }
1259}
bellard5b0753e2005-03-01 21:37:28 +00001260
Programmingkidb4c6a112015-05-19 09:11:18 +01001261/* Displays the console on the screen */
1262- (void)displayConsole:(id)sender
1263{
1264 console_select([sender tag]);
1265}
John Arbuckle8524f1c2015-06-19 10:53:27 +01001266
1267/* Pause the guest */
1268- (void)pauseQEMU:(id)sender
1269{
Peter Maydell31819e92019-02-25 10:24:27 +00001270 with_iothread_lock(^{
1271 qmp_stop(NULL);
1272 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001273 [sender setEnabled: NO];
1274 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1275 [self displayPause];
1276}
1277
1278/* Resume running the guest operating system */
1279- (void)resumeQEMU:(id) sender
1280{
Peter Maydell31819e92019-02-25 10:24:27 +00001281 with_iothread_lock(^{
1282 qmp_cont(NULL);
1283 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001284 [sender setEnabled: NO];
1285 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1286 [self removePause];
1287}
1288
1289/* Displays the word pause on the screen */
1290- (void)displayPause
1291{
1292 /* Coordinates have to be calculated each time because the window can change its size */
1293 int xCoord, yCoord, width, height;
1294 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1295 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1296 width = [pauseLabel frame].size.width;
1297 height = [pauseLabel frame].size.height;
1298 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1299 [cocoaView addSubview: pauseLabel];
1300}
1301
1302/* Removes the word pause from the screen */
1303- (void)removePause
1304{
1305 [pauseLabel removeFromSuperview];
1306}
1307
John Arbuckle27074612015-06-19 10:53:27 +01001308/* Restarts QEMU */
1309- (void)restartQEMU:(id)sender
1310{
Peter Maydell31819e92019-02-25 10:24:27 +00001311 with_iothread_lock(^{
1312 qmp_system_reset(NULL);
1313 });
John Arbuckle27074612015-06-19 10:53:27 +01001314}
1315
1316/* Powers down QEMU */
1317- (void)powerDownQEMU:(id)sender
1318{
Peter Maydell31819e92019-02-25 10:24:27 +00001319 with_iothread_lock(^{
1320 qmp_system_powerdown(NULL);
1321 });
John Arbuckle27074612015-06-19 10:53:27 +01001322}
1323
John Arbuckle693a3e02015-06-19 10:53:27 +01001324/* Ejects the media.
1325 * Uses sender's tag to figure out the device to eject.
1326 */
1327- (void)ejectDeviceMedia:(id)sender
1328{
1329 NSString * drive;
1330 drive = [sender representedObject];
1331 if(drive == nil) {
1332 NSBeep();
1333 QEMU_Alert(@"Failed to find drive to eject!");
1334 return;
1335 }
1336
Peter Maydell31819e92019-02-25 10:24:27 +00001337 __block Error *err = NULL;
1338 with_iothread_lock(^{
1339 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1340 false, NULL, false, false, &err);
1341 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001342 handleAnyDeviceErrors(err);
1343}
1344
1345/* Displays a dialog box asking the user to select an image file to load.
1346 * Uses sender's represented object value to figure out which drive to use.
1347 */
1348- (void)changeDeviceMedia:(id)sender
1349{
1350 /* Find the drive name */
1351 NSString * drive;
1352 drive = [sender representedObject];
1353 if(drive == nil) {
1354 NSBeep();
1355 QEMU_Alert(@"Could not find drive!");
1356 return;
1357 }
1358
1359 /* Display the file open dialog */
1360 NSOpenPanel * openPanel;
1361 openPanel = [NSOpenPanel openPanel];
1362 [openPanel setCanChooseFiles: YES];
1363 [openPanel setAllowsMultipleSelection: NO];
1364 [openPanel setAllowedFileTypes: supportedImageFileTypes];
Peter Maydellb5725382018-05-29 19:15:23 +01001365 if([openPanel runModal] == NSModalResponseOK) {
John Arbuckle693a3e02015-06-19 10:53:27 +01001366 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1367 if(file == nil) {
1368 NSBeep();
1369 QEMU_Alert(@"Failed to convert URL to file path!");
1370 return;
1371 }
1372
Peter Maydell31819e92019-02-25 10:24:27 +00001373 __block Error *err = NULL;
1374 with_iothread_lock(^{
1375 qmp_blockdev_change_medium(true,
1376 [drive cStringUsingEncoding:
1377 NSASCIIStringEncoding],
1378 false, NULL,
1379 [file cStringUsingEncoding:
1380 NSASCIIStringEncoding],
1381 true, "raw",
1382 false, 0,
1383 &err);
1384 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001385 handleAnyDeviceErrors(err);
1386 }
1387}
1388
John Arbuckled9bc14f2015-09-25 23:13:59 +01001389/* Verifies if the user really wants to quit */
1390- (BOOL)verifyQuit
1391{
1392 NSAlert *alert = [NSAlert new];
1393 [alert autorelease];
1394 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1395 [alert addButtonWithTitle: @"Cancel"];
1396 [alert addButtonWithTitle: @"Quit"];
1397 if([alert runModal] == NSAlertSecondButtonReturn) {
1398 return YES;
1399 } else {
1400 return NO;
1401 }
1402}
1403
Programmingkid9e8204b2016-08-15 22:11:06 -04001404/* The action method for the About menu item */
1405- (IBAction) do_about_menu_item: (id) sender
1406{
1407 [about_window makeKeyAndOrderFront: nil];
1408}
1409
1410/* Create and display the about dialog */
1411- (void)make_about_window
1412{
1413 /* Make the window */
1414 int x = 0, y = 0, about_width = 400, about_height = 200;
1415 NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1416 about_window = [[NSWindow alloc] initWithContentRect:window_rect
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001417 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1418 NSWindowStyleMaskMiniaturizable
Programmingkid9e8204b2016-08-15 22:11:06 -04001419 backing:NSBackingStoreBuffered
1420 defer:NO];
1421 [about_window setTitle: @"About"];
1422 [about_window setReleasedWhenClosed: NO];
1423 [about_window center];
1424 NSView *superView = [about_window contentView];
1425
1426 /* Create the dimensions of the picture */
1427 int picture_width = 80, picture_height = 80;
1428 x = (about_width - picture_width)/2;
1429 y = about_height - picture_height - 10;
1430 NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1431
1432 /* Get the path to the QEMU binary */
1433 NSString *binary_name = [NSString stringWithCString: gArgv[0]
1434 encoding: NSASCIIStringEncoding];
1435 binary_name = [binary_name lastPathComponent];
1436 NSString *program_path = [[NSString alloc] initWithFormat: @"%@/%@",
1437 [[NSBundle mainBundle] bundlePath], binary_name];
1438
1439 /* Make the picture of QEMU */
1440 NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1441 picture_rect];
1442 NSImage *qemu_image = [[NSWorkspace sharedWorkspace] iconForFile:
1443 program_path];
1444 [picture_view setImage: qemu_image];
1445 [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1446 [superView addSubview: picture_view];
1447
1448 /* Make the name label */
1449 x = 0;
1450 y = y - 25;
1451 int name_width = about_width, name_height = 20;
1452 NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1453 NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1454 [name_label setEditable: NO];
1455 [name_label setBezeled: NO];
1456 [name_label setDrawsBackground: NO];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001457 [name_label setAlignment: NSTextAlignmentCenter];
Programmingkid9e8204b2016-08-15 22:11:06 -04001458 NSString *qemu_name = [[NSString alloc] initWithCString: gArgv[0]
1459 encoding: NSASCIIStringEncoding];
1460 qemu_name = [qemu_name lastPathComponent];
1461 [name_label setStringValue: qemu_name];
1462 [superView addSubview: name_label];
1463
1464 /* Set the version label's attributes */
1465 x = 0;
1466 y = 50;
1467 int version_width = about_width, version_height = 20;
1468 NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1469 NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1470 version_rect];
1471 [version_label setEditable: NO];
1472 [version_label setBezeled: NO];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001473 [version_label setAlignment: NSTextAlignmentCenter];
Programmingkid9e8204b2016-08-15 22:11:06 -04001474 [version_label setDrawsBackground: NO];
1475
1476 /* Create the version string*/
1477 NSString *version_string;
1478 version_string = [[NSString alloc] initWithFormat:
Thomas Huth7e563bf2018-02-15 12:06:47 +01001479 @"QEMU emulator version %s", QEMU_FULL_VERSION];
Programmingkid9e8204b2016-08-15 22:11:06 -04001480 [version_label setStringValue: version_string];
1481 [superView addSubview: version_label];
1482
1483 /* Make copyright label */
1484 x = 0;
1485 y = 35;
1486 int copyright_width = about_width, copyright_height = 20;
1487 NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1488 NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1489 copyright_rect];
1490 [copyright_label setEditable: NO];
1491 [copyright_label setBezeled: NO];
1492 [copyright_label setDrawsBackground: NO];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001493 [copyright_label setAlignment: NSTextAlignmentCenter];
Programmingkid9e8204b2016-08-15 22:11:06 -04001494 [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1495 QEMU_COPYRIGHT]];
1496 [superView addSubview: copyright_label];
1497}
1498
John Arbucklee47ec1a2017-06-13 23:17:38 -04001499/* Used by the Speed menu items */
1500- (void)adjustSpeed:(id)sender
1501{
1502 int throttle_pct; /* throttle percentage */
1503 NSMenu *menu;
1504
1505 menu = [sender menu];
1506 if (menu != nil)
1507 {
1508 /* Unselect the currently selected item */
1509 for (NSMenuItem *item in [menu itemArray]) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001510 if (item.state == NSControlStateValueOn) {
1511 [item setState: NSControlStateValueOff];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001512 break;
1513 }
1514 }
1515 }
1516
1517 // check the menu item
Brendan Shanks5e246002019-01-31 23:12:25 -08001518 [sender setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001519
1520 // get the throttle percentage
1521 throttle_pct = [sender tag];
1522
Peter Maydell31819e92019-02-25 10:24:27 +00001523 with_iothread_lock(^{
1524 cpu_throttle_set(throttle_pct);
1525 });
John Arbucklee47ec1a2017-06-13 23:17:38 -04001526 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1527}
1528
Programmingkidb4c6a112015-05-19 09:11:18 +01001529@end
bellard5b0753e2005-03-01 21:37:28 +00001530
Peter Maydell61a2ed42019-02-25 10:24:32 +00001531@interface QemuApplication : NSApplication
1532@end
1533
1534@implementation QemuApplication
1535- (void)sendEvent:(NSEvent *)event
1536{
1537 COCOA_DEBUG("QemuApplication: sendEvent\n");
Peter Maydell55888402019-02-25 10:24:33 +00001538 if (![cocoaView handleEvent:event]) {
1539 [super sendEvent: event];
1540 }
Peter Maydell61a2ed42019-02-25 10:24:32 +00001541}
1542@end
1543
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001544static void create_initial_menus(void)
1545{
thsc304f7e2008-01-22 23:25:15 +00001546 // Add menus
1547 NSMenu *menu;
1548 NSMenuItem *menuItem;
1549
bellard5b0753e2005-03-01 21:37:28 +00001550 [NSApp setMainMenu:[[NSMenu alloc] init]];
bellard5b0753e2005-03-01 21:37:28 +00001551
thsc304f7e2008-01-22 23:25:15 +00001552 // Application menu
1553 menu = [[NSMenu alloc] initWithTitle:@""];
Programmingkid9e8204b2016-08-15 22:11:06 -04001554 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
thsc304f7e2008-01-22 23:25:15 +00001555 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1556 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1557 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001558 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
thsc304f7e2008-01-22 23:25:15 +00001559 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1560 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1561 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1562 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1563 [menuItem setSubmenu:menu];
1564 [[NSApp mainMenu] addItem:menuItem];
1565 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
ths3b46e622007-09-17 08:09:54 +00001566
John Arbuckle8524f1c2015-06-19 10:53:27 +01001567 // Machine menu
1568 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1569 [menu setAutoenablesItems: NO];
1570 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1571 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1572 [menu addItem: menuItem];
1573 [menuItem setEnabled: NO];
John Arbuckle27074612015-06-19 10:53:27 +01001574 [menu addItem: [NSMenuItem separatorItem]];
1575 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1576 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
John Arbuckle8524f1c2015-06-19 10:53:27 +01001577 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1578 [menuItem setSubmenu:menu];
1579 [[NSApp mainMenu] addItem:menuItem];
1580
thsc304f7e2008-01-22 23:25:15 +00001581 // View menu
1582 menu = [[NSMenu alloc] initWithTitle:@"View"];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001583 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1584 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
thsc304f7e2008-01-22 23:25:15 +00001585 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1586 [menuItem setSubmenu:menu];
1587 [[NSApp mainMenu] addItem:menuItem];
1588
John Arbucklee47ec1a2017-06-13 23:17:38 -04001589 // Speed menu
1590 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1591
1592 // Add the rest of the Speed menu items
1593 int p, percentage, throttle_pct;
1594 for (p = 10; p >= 0; p--)
1595 {
1596 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1597
1598 menuItem = [[[NSMenuItem alloc]
1599 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1600
1601 if (percentage == 100) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001602 [menuItem setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001603 }
1604
1605 /* Calculate the throttle percentage */
1606 throttle_pct = -1 * percentage + 100;
1607
1608 [menuItem setTag: throttle_pct];
1609 [menu addItem: menuItem];
1610 }
1611 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1612 [menuItem setSubmenu:menu];
1613 [[NSApp mainMenu] addItem:menuItem];
1614
thsc304f7e2008-01-22 23:25:15 +00001615 // Window menu
1616 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1617 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1618 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1619 [menuItem setSubmenu:menu];
1620 [[NSApp mainMenu] addItem:menuItem];
1621 [NSApp setWindowsMenu:menu];
1622
1623 // Help menu
1624 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1625 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
thsc304f7e2008-01-22 23:25:15 +00001626 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1627 [menuItem setSubmenu:menu];
1628 [[NSApp mainMenu] addItem:menuItem];
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001629}
1630
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001631/* Returns a name for a given console */
1632static NSString * getConsoleName(QemuConsole * console)
1633{
1634 return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1635}
1636
1637/* Add an entry to the View menu for each console */
1638static void add_console_menu_entries(void)
1639{
1640 NSMenu *menu;
1641 NSMenuItem *menuItem;
1642 int index = 0;
1643
1644 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1645
1646 [menu addItem:[NSMenuItem separatorItem]];
1647
1648 while (qemu_console_lookup_by_index(index) != NULL) {
1649 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1650 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1651 [menuItem setTag: index];
1652 [menu addItem: menuItem];
1653 index++;
1654 }
1655}
1656
1657/* Make menu items for all removable devices.
1658 * Each device is given an 'Eject' and 'Change' menu item.
1659 */
1660static void addRemovableDevicesMenuItems(void)
1661{
1662 NSMenu *menu;
1663 NSMenuItem *menuItem;
1664 BlockInfoList *currentDevice, *pointerToFree;
1665 NSString *deviceName;
1666
1667 currentDevice = qmp_query_block(NULL);
1668 pointerToFree = currentDevice;
1669 if(currentDevice == NULL) {
1670 NSBeep();
1671 QEMU_Alert(@"Failed to query for block devices!");
1672 return;
1673 }
1674
1675 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1676
1677 // Add a separator between related groups of menu items
1678 [menu addItem:[NSMenuItem separatorItem]];
1679
1680 // Set the attributes to the "Removable Media" menu item
1681 NSString *titleString = @"Removable Media";
1682 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1683 NSColor *newColor = [NSColor blackColor];
1684 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1685 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1686 traits:NSBoldFontMask|NSItalicFontMask
1687 weight:0
1688 size:14];
1689 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1690 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1691 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1692
1693 // Add the "Removable Media" menu item
1694 menuItem = [NSMenuItem new];
1695 [menuItem setAttributedTitle: attString];
1696 [menuItem setEnabled: NO];
1697 [menu addItem: menuItem];
1698
1699 /* Loop through all the block devices in the emulator */
1700 while (currentDevice) {
1701 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1702
1703 if(currentDevice->value->removable) {
1704 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1705 action: @selector(changeDeviceMedia:)
1706 keyEquivalent: @""];
1707 [menu addItem: menuItem];
1708 [menuItem setRepresentedObject: deviceName];
1709 [menuItem autorelease];
1710
1711 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1712 action: @selector(ejectDeviceMedia:)
1713 keyEquivalent: @""];
1714 [menu addItem: menuItem];
1715 [menuItem setRepresentedObject: deviceName];
1716 [menuItem autorelease];
1717 }
1718 currentDevice = currentDevice->next;
1719 }
1720 qapi_free_BlockInfoList(pointerToFree);
1721}
1722
Peter Maydell55888402019-02-25 10:24:33 +00001723/*
1724 * The startup process for the OSX/Cocoa UI is complicated, because
1725 * OSX insists that the UI runs on the initial main thread, and so we
1726 * need to start a second thread which runs the vl.c qemu_main():
1727 *
1728 * Initial thread: 2nd thread:
1729 * in main():
1730 * create qemu-main thread
1731 * wait on display_init semaphore
1732 * call qemu_main()
1733 * ...
1734 * in cocoa_display_init():
1735 * post the display_init semaphore
1736 * wait on app_started semaphore
1737 * create application, menus, etc
1738 * enter OSX run loop
1739 * in applicationDidFinishLaunching:
1740 * post app_started semaphore
1741 * tell main thread to fullscreen if needed
1742 * [...]
1743 * run qemu main-loop
1744 *
1745 * We do this in two stages so that we don't do the creation of the
1746 * GUI application menus and so on for command line options like --help
1747 * where we want to just print text to stdout and exit immediately.
1748 */
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001749
Peter Maydell55888402019-02-25 10:24:33 +00001750static void *call_qemu_main(void *opaque)
1751{
1752 int status;
1753
1754 COCOA_DEBUG("Second thread: calling qemu_main()\n");
1755 status = qemu_main(gArgc, gArgv, *_NSGetEnviron());
1756 COCOA_DEBUG("Second thread: qemu_main() returned, exiting\n");
1757 exit(status);
1758}
1759
1760int main (int argc, const char * argv[]) {
1761 QemuThread thread;
1762
1763 COCOA_DEBUG("Entered main()\n");
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001764 gArgc = argc;
1765 gArgv = (char **)argv;
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001766
Peter Maydell55888402019-02-25 10:24:33 +00001767 qemu_sem_init(&display_init_sem, 0);
1768 qemu_sem_init(&app_started_sem, 0);
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001769
Peter Maydell55888402019-02-25 10:24:33 +00001770 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1771 NULL, QEMU_THREAD_DETACHED);
1772
1773 COCOA_DEBUG("Main thread: waiting for display_init_sem\n");
1774 qemu_sem_wait(&display_init_sem);
1775 COCOA_DEBUG("Main thread: initializing app\n");
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001776
1777 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1778
1779 // Pull this console process up to being a fully-fledged graphical
1780 // app with a menubar and Dock icon
1781 ProcessSerialNumber psn = { 0, kCurrentProcess };
1782 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1783
Peter Maydell61a2ed42019-02-25 10:24:32 +00001784 [QemuApplication sharedApplication];
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001785
1786 create_initial_menus();
thsc304f7e2008-01-22 23:25:15 +00001787
Peter Maydell55888402019-02-25 10:24:33 +00001788 /*
1789 * Create the menu entries which depend on QEMU state (for consoles
1790 * and removeable devices). These make calls back into QEMU functions,
1791 * which is OK because at this point we know that the second thread
1792 * holds the iothread lock and is synchronously waiting for us to
1793 * finish.
1794 */
1795 add_console_menu_entries();
1796 addRemovableDevicesMenuItems();
1797
thsc304f7e2008-01-22 23:25:15 +00001798 // Create an Application controller
1799 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1800 [NSApp setDelegate:appController];
1801
1802 // Start the main event loop
Peter Maydell55888402019-02-25 10:24:33 +00001803 COCOA_DEBUG("Main thread: entering OSX run loop\n");
bellard5b0753e2005-03-01 21:37:28 +00001804 [NSApp run];
Peter Maydell55888402019-02-25 10:24:33 +00001805 COCOA_DEBUG("Main thread: left OSX run loop, exiting\n");
ths3b46e622007-09-17 08:09:54 +00001806
thsc304f7e2008-01-22 23:25:15 +00001807 [appController release];
bellard5b0753e2005-03-01 21:37:28 +00001808 [pool release];
bellardcae41b12006-05-22 21:25:04 +00001809
bellard5b0753e2005-03-01 21:37:28 +00001810 return 0;
1811}
thsc304f7e2008-01-22 23:25:15 +00001812
1813
1814
1815#pragma mark qemu
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001816static void cocoa_update(DisplayChangeListener *dcl,
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001817 int x, int y, int w, int h)
thsc304f7e2008-01-22 23:25:15 +00001818{
Peter Maydell6e657e62013-04-22 10:29:46 +00001819 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1820
thsc304f7e2008-01-22 23:25:15 +00001821 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1822
Peter Maydell55888402019-02-25 10:24:33 +00001823 dispatch_async(dispatch_get_main_queue(), ^{
1824 NSRect rect;
1825 if ([cocoaView cdx] == 1.0) {
1826 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1827 } else {
1828 rect = NSMakeRect(
1829 x * [cocoaView cdx],
1830 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1831 w * [cocoaView cdx],
1832 h * [cocoaView cdy]);
1833 }
1834 [cocoaView setNeedsDisplayInRect:rect];
1835 });
Peter Maydell6e657e62013-04-22 10:29:46 +00001836
1837 [pool release];
thsc304f7e2008-01-22 23:25:15 +00001838}
1839
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01001840static void cocoa_switch(DisplayChangeListener *dcl,
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01001841 DisplaySurface *surface)
thsc304f7e2008-01-22 23:25:15 +00001842{
Peter Maydell6e657e62013-04-22 10:29:46 +00001843 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Peter Maydell55888402019-02-25 10:24:33 +00001844 pixman_image_t *image = surface->image;
thsc304f7e2008-01-22 23:25:15 +00001845
Peter Maydell6e657e62013-04-22 10:29:46 +00001846 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
Peter Maydell55888402019-02-25 10:24:33 +00001847
1848 // The DisplaySurface will be freed as soon as this callback returns.
1849 // We take a reference to the underlying pixman image here so it does
1850 // not disappear from under our feet; the switchSurface method will
1851 // deref the old image when it is done with it.
1852 pixman_image_ref(image);
1853
1854 dispatch_async(dispatch_get_main_queue(), ^{
1855 [cocoaView switchSurface:image];
1856 });
Peter Maydell6e657e62013-04-22 10:29:46 +00001857 [pool release];
thsc304f7e2008-01-22 23:25:15 +00001858}
1859
Gerd Hoffmannbc2ed972013-03-01 13:03:04 +01001860static void cocoa_refresh(DisplayChangeListener *dcl)
thsc304f7e2008-01-22 23:25:15 +00001861{
Peter Maydell6e657e62013-04-22 10:29:46 +00001862 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1863
thsc304f7e2008-01-22 23:25:15 +00001864 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
John Arbuckle468a8952015-10-13 21:51:18 +01001865 graphic_hw_update(NULL);
thsc304f7e2008-01-22 23:25:15 +00001866
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001867 if (qemu_input_is_absolute()) {
Peter Maydell55888402019-02-25 10:24:33 +00001868 dispatch_async(dispatch_get_main_queue(), ^{
1869 if (![cocoaView isAbsoluteEnabled]) {
1870 if ([cocoaView isMouseGrabbed]) {
1871 [cocoaView ungrabMouse];
1872 }
thsc304f7e2008-01-22 23:25:15 +00001873 }
Peter Maydell55888402019-02-25 10:24:33 +00001874 [cocoaView setAbsoluteEnabled:YES];
1875 });
thsc304f7e2008-01-22 23:25:15 +00001876 }
Peter Maydell6e657e62013-04-22 10:29:46 +00001877 [pool release];
thsc304f7e2008-01-22 23:25:15 +00001878}
1879
1880static void cocoa_cleanup(void)
1881{
1882 COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
Blue Swirl58a06672011-08-21 18:42:08 +00001883 g_free(dcl);
thsc304f7e2008-01-22 23:25:15 +00001884}
1885
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001886static const DisplayChangeListenerOps dcl_ops = {
1887 .dpy_name = "cocoa",
Peter Maydell8510d912013-03-18 20:28:21 +00001888 .dpy_gfx_update = cocoa_update,
1889 .dpy_gfx_switch = cocoa_switch,
1890 .dpy_refresh = cocoa_refresh,
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001891};
1892
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01001893static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
thsc304f7e2008-01-22 23:25:15 +00001894{
1895 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1896
Peter Maydell55888402019-02-25 10:24:33 +00001897 /* Tell main thread to go ahead and create the app and enter the run loop */
1898 qemu_sem_post(&display_init_sem);
1899 qemu_sem_wait(&app_started_sem);
1900 COCOA_DEBUG("cocoa_display_init: app start completed\n");
1901
Programmingkid43227af2015-05-19 09:11:17 +01001902 /* if fullscreen mode is to be used */
Gerd Hoffmann767f9bf2018-02-02 12:10:19 +01001903 if (opts->has_full_screen && opts->full_screen) {
Peter Maydell55888402019-02-25 10:24:33 +00001904 dispatch_async(dispatch_get_main_queue(), ^{
1905 [NSApp activateIgnoringOtherApps: YES];
1906 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1907 });
Programmingkid43227af2015-05-19 09:11:17 +01001908 }
1909
Blue Swirl58a06672011-08-21 18:42:08 +00001910 dcl = g_malloc0(sizeof(DisplayChangeListener));
1911
aliguori9794f742009-03-04 19:25:22 +00001912 // register vga output callbacks
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001913 dcl->ops = &dcl_ops;
Gerd Hoffmann52090892013-04-23 15:44:31 +02001914 register_displaychangelistener(dcl);
thsc304f7e2008-01-22 23:25:15 +00001915
1916 // register cleanup function
1917 atexit(cocoa_cleanup);
1918}
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01001919
1920static QemuDisplay qemu_display_cocoa = {
1921 .type = DISPLAY_TYPE_COCOA,
1922 .init = cocoa_display_init,
1923};
1924
1925static void register_cocoa(void)
1926{
1927 qemu_display_register(&qemu_display_cocoa);
1928}
1929
1930type_init(register_cocoa);