blob: 89b16e0e440612a18864930d42a04b5b54889464 [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 Armbrustere688df62018-02-01 12:18:31 +010034#include "qapi/error.h"
Markus Armbruster16bf5232018-12-20 09:45:59 +010035#include "qapi/qapi-commands-block.h"
36#include "qapi/qapi-commands-misc.h"
John Arbuckle693a3e02015-06-19 10:53:27 +010037#include "sysemu/blockdev.h"
Programmingkid9e8204b2016-08-15 22:11:06 -040038#include "qemu-version.h"
Markus Armbruster0b8fa322019-05-23 16:35:07 +020039#include "qemu/module.h"
John Arbuckleaaac7142016-03-23 14:26:18 +000040#include <Carbon/Carbon.h>
John Arbucklee47ec1a2017-06-13 23:17:38 -040041#include "qom/cpu.h"
bellardda4dbf72005-03-02 22:22:43 +000042
Andreas Färber44e4c0b2009-12-13 00:45:40 +010043#ifndef MAC_OS_X_VERSION_10_5
44#define MAC_OS_X_VERSION_10_5 1050
45#endif
Peter Maydell2ba9de62013-04-22 10:29:49 +000046#ifndef MAC_OS_X_VERSION_10_6
47#define MAC_OS_X_VERSION_10_6 1060
48#endif
Peter Maydellb5725382018-05-29 19:15:23 +010049#ifndef MAC_OS_X_VERSION_10_9
50#define MAC_OS_X_VERSION_10_9 1090
51#endif
Peter Maydell81801ae2015-05-19 09:11:18 +010052#ifndef MAC_OS_X_VERSION_10_10
53#define MAC_OS_X_VERSION_10_10 101000
54#endif
Brendan Shanks4ba967a2017-04-24 23:29:52 -070055#ifndef MAC_OS_X_VERSION_10_12
56#define MAC_OS_X_VERSION_10_12 101200
57#endif
Brendan Shanks5e246002019-01-31 23:12:25 -080058#ifndef MAC_OS_X_VERSION_10_13
59#define MAC_OS_X_VERSION_10_13 101300
60#endif
Andreas Färber44e4c0b2009-12-13 00:45:40 +010061
Brendan Shanks4ba967a2017-04-24 23:29:52 -070062/* macOS 10.12 deprecated many constants, #define the new names for older SDKs */
63#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_12
64#define NSEventMaskAny NSAnyEventMask
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -070065#define NSEventModifierFlagCapsLock NSAlphaShiftKeyMask
66#define NSEventModifierFlagShift NSShiftKeyMask
Brendan Shanks4ba967a2017-04-24 23:29:52 -070067#define NSEventModifierFlagCommand NSCommandKeyMask
68#define NSEventModifierFlagControl NSControlKeyMask
69#define NSEventModifierFlagOption NSAlternateKeyMask
70#define NSEventTypeFlagsChanged NSFlagsChanged
71#define NSEventTypeKeyUp NSKeyUp
72#define NSEventTypeKeyDown NSKeyDown
73#define NSEventTypeMouseMoved NSMouseMoved
74#define NSEventTypeLeftMouseDown NSLeftMouseDown
75#define NSEventTypeRightMouseDown NSRightMouseDown
76#define NSEventTypeOtherMouseDown NSOtherMouseDown
77#define NSEventTypeLeftMouseDragged NSLeftMouseDragged
78#define NSEventTypeRightMouseDragged NSRightMouseDragged
79#define NSEventTypeOtherMouseDragged NSOtherMouseDragged
80#define NSEventTypeLeftMouseUp NSLeftMouseUp
81#define NSEventTypeRightMouseUp NSRightMouseUp
82#define NSEventTypeOtherMouseUp NSOtherMouseUp
83#define NSEventTypeScrollWheel NSScrollWheel
84#define NSTextAlignmentCenter NSCenterTextAlignment
85#define NSWindowStyleMaskBorderless NSBorderlessWindowMask
86#define NSWindowStyleMaskClosable NSClosableWindowMask
87#define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask
88#define NSWindowStyleMaskTitled NSTitledWindowMask
89#endif
Peter Maydellb5725382018-05-29 19:15:23 +010090/* 10.13 deprecates NSFileHandlingPanelOKButton in favour of
91 * NSModalResponseOK, which was introduced in 10.9. Define
92 * it for older versions.
93 */
94#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_9
95#define NSModalResponseOK NSFileHandlingPanelOKButton
96#endif
Brendan Shanks5e246002019-01-31 23:12:25 -080097/* 10.14 deprecates NSOnState and NSOffState in favor of
98 * NSControlStateValueOn/Off, which were introduced in 10.13.
99 * Define for older versions
100 */
101#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
102#define NSControlStateValueOn NSOnState
103#define NSControlStateValueOff NSOffState
104#endif
bellard5b0753e2005-03-01 21:37:28 +0000105
thsc304f7e2008-01-22 23:25:15 +0000106//#define DEBUG
107
108#ifdef DEBUG
109#define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
110#else
111#define COCOA_DEBUG(...) ((void) 0)
112#endif
113
114#define cgrect(nsrect) (*(CGRect *)&(nsrect))
thsc304f7e2008-01-22 23:25:15 +0000115
116typedef struct {
117 int width;
118 int height;
119 int bitsPerComponent;
120 int bitsPerPixel;
121} QEMUScreen;
122
Programmingkid9e8204b2016-08-15 22:11:06 -0400123NSWindow *normalWindow, *about_window;
aliguori9794f742009-03-04 19:25:22 +0000124static DisplayChangeListener *dcl;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100125static int last_buttons;
bellard5b0753e2005-03-01 21:37:28 +0000126
127int gArgc;
128char **gArgv;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100129bool stretch_video;
John Arbuckle8524f1c2015-06-19 10:53:27 +0100130NSTextField *pauseLabel;
John Arbuckle693a3e02015-06-19 10:53:27 +0100131NSArray * supportedImageFileTypes;
bellard5b0753e2005-03-01 21:37:28 +0000132
Peter Maydell55888402019-02-25 10:24:33 +0000133static QemuSemaphore display_init_sem;
134static QemuSemaphore app_started_sem;
135
Peter Maydell60105d72019-02-25 10:24:31 +0000136// Utility functions to run specified code block with iothread lock held
Peter Maydell31819e92019-02-25 10:24:27 +0000137typedef void (^CodeBlock)(void);
Peter Maydell60105d72019-02-25 10:24:31 +0000138typedef bool (^BoolCodeBlock)(void);
Peter Maydell31819e92019-02-25 10:24:27 +0000139
140static void with_iothread_lock(CodeBlock block)
141{
142 bool locked = qemu_mutex_iothread_locked();
143 if (!locked) {
144 qemu_mutex_lock_iothread();
145 }
146 block();
147 if (!locked) {
148 qemu_mutex_unlock_iothread();
149 }
150}
151
Peter Maydell60105d72019-02-25 10:24:31 +0000152static bool bool_with_iothread_lock(BoolCodeBlock block)
153{
154 bool locked = qemu_mutex_iothread_locked();
155 bool val;
156
157 if (!locked) {
158 qemu_mutex_lock_iothread();
159 }
160 val = block();
161 if (!locked) {
162 qemu_mutex_unlock_iothread();
163 }
164 return val;
165}
166
John Arbuckleaaac7142016-03-23 14:26:18 +0000167// Mac to QKeyCode conversion
168const int mac_to_qkeycode_map[] = {
169 [kVK_ANSI_A] = Q_KEY_CODE_A,
170 [kVK_ANSI_B] = Q_KEY_CODE_B,
171 [kVK_ANSI_C] = Q_KEY_CODE_C,
172 [kVK_ANSI_D] = Q_KEY_CODE_D,
173 [kVK_ANSI_E] = Q_KEY_CODE_E,
174 [kVK_ANSI_F] = Q_KEY_CODE_F,
175 [kVK_ANSI_G] = Q_KEY_CODE_G,
176 [kVK_ANSI_H] = Q_KEY_CODE_H,
177 [kVK_ANSI_I] = Q_KEY_CODE_I,
178 [kVK_ANSI_J] = Q_KEY_CODE_J,
179 [kVK_ANSI_K] = Q_KEY_CODE_K,
180 [kVK_ANSI_L] = Q_KEY_CODE_L,
181 [kVK_ANSI_M] = Q_KEY_CODE_M,
182 [kVK_ANSI_N] = Q_KEY_CODE_N,
183 [kVK_ANSI_O] = Q_KEY_CODE_O,
184 [kVK_ANSI_P] = Q_KEY_CODE_P,
185 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
186 [kVK_ANSI_R] = Q_KEY_CODE_R,
187 [kVK_ANSI_S] = Q_KEY_CODE_S,
188 [kVK_ANSI_T] = Q_KEY_CODE_T,
189 [kVK_ANSI_U] = Q_KEY_CODE_U,
190 [kVK_ANSI_V] = Q_KEY_CODE_V,
191 [kVK_ANSI_W] = Q_KEY_CODE_W,
192 [kVK_ANSI_X] = Q_KEY_CODE_X,
193 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
194 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
ths3b46e622007-09-17 08:09:54 +0000195
John Arbuckleaaac7142016-03-23 14:26:18 +0000196 [kVK_ANSI_0] = Q_KEY_CODE_0,
197 [kVK_ANSI_1] = Q_KEY_CODE_1,
198 [kVK_ANSI_2] = Q_KEY_CODE_2,
199 [kVK_ANSI_3] = Q_KEY_CODE_3,
200 [kVK_ANSI_4] = Q_KEY_CODE_4,
201 [kVK_ANSI_5] = Q_KEY_CODE_5,
202 [kVK_ANSI_6] = Q_KEY_CODE_6,
203 [kVK_ANSI_7] = Q_KEY_CODE_7,
204 [kVK_ANSI_8] = Q_KEY_CODE_8,
205 [kVK_ANSI_9] = Q_KEY_CODE_9,
206
207 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
208 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
209 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
210 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
211 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
212 [kVK_Tab] = Q_KEY_CODE_TAB,
213 [kVK_Return] = Q_KEY_CODE_RET,
214 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
215 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
216 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
217 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
218 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
219 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
220 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
221 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
222 [kVK_Shift] = Q_KEY_CODE_SHIFT,
223 [kVK_RightShift] = Q_KEY_CODE_SHIFT_R,
224 [kVK_Control] = Q_KEY_CODE_CTRL,
225 [kVK_RightControl] = Q_KEY_CODE_CTRL_R,
226 [kVK_Option] = Q_KEY_CODE_ALT,
227 [kVK_RightOption] = Q_KEY_CODE_ALT_R,
228 [kVK_Command] = Q_KEY_CODE_META_L,
229 [0x36] = Q_KEY_CODE_META_R, /* There is no kVK_RightCommand */
230 [kVK_Space] = Q_KEY_CODE_SPC,
231
232 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
233 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
234 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
235 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
236 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
237 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
238 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
239 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
240 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
241 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
242 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
243 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
244 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
245 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
246 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
247 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
248 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
249 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
250
251 [kVK_UpArrow] = Q_KEY_CODE_UP,
252 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
253 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
254 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
255
256 [kVK_Help] = Q_KEY_CODE_INSERT,
257 [kVK_Home] = Q_KEY_CODE_HOME,
258 [kVK_PageUp] = Q_KEY_CODE_PGUP,
259 [kVK_PageDown] = Q_KEY_CODE_PGDN,
260 [kVK_End] = Q_KEY_CODE_END,
261 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
262
263 [kVK_Escape] = Q_KEY_CODE_ESC,
264
265 /* The Power key can't be used directly because the operating system uses
266 * it. This key can be emulated by using it in place of another key such as
267 * F1. Don't forget to disable the real key binding.
268 */
269 /* [kVK_F1] = Q_KEY_CODE_POWER, */
270
271 [kVK_F1] = Q_KEY_CODE_F1,
272 [kVK_F2] = Q_KEY_CODE_F2,
273 [kVK_F3] = Q_KEY_CODE_F3,
274 [kVK_F4] = Q_KEY_CODE_F4,
275 [kVK_F5] = Q_KEY_CODE_F5,
276 [kVK_F6] = Q_KEY_CODE_F6,
277 [kVK_F7] = Q_KEY_CODE_F7,
278 [kVK_F8] = Q_KEY_CODE_F8,
279 [kVK_F9] = Q_KEY_CODE_F9,
280 [kVK_F10] = Q_KEY_CODE_F10,
281 [kVK_F11] = Q_KEY_CODE_F11,
282 [kVK_F12] = Q_KEY_CODE_F12,
283 [kVK_F13] = Q_KEY_CODE_PRINT,
284 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
285 [kVK_F15] = Q_KEY_CODE_PAUSE,
286
287 /*
288 * The eject and volume keys can't be used here because they are handled at
289 * a lower level than what an Application can see.
290 */
bellard5b0753e2005-03-01 21:37:28 +0000291};
292
Andreas Färber77047bb2009-12-13 00:55:53 +0100293static int cocoa_keycode_to_qemu(int keycode)
bellard5b0753e2005-03-01 21:37:28 +0000294{
John Arbuckleaaac7142016-03-23 14:26:18 +0000295 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
Peter Maydell01cc4e62013-12-08 22:59:04 +0000296 fprintf(stderr, "(cocoa) warning unknown keycode 0x%x\n", keycode);
bellard5b0753e2005-03-01 21:37:28 +0000297 return 0;
298 }
John Arbuckleaaac7142016-03-23 14:26:18 +0000299 return mac_to_qkeycode_map[keycode];
bellard5b0753e2005-03-01 21:37:28 +0000300}
301
John Arbuckle693a3e02015-06-19 10:53:27 +0100302/* Displays an alert dialog box with the specified message */
303static void QEMU_Alert(NSString *message)
304{
305 NSAlert *alert;
306 alert = [NSAlert new];
307 [alert setMessageText: message];
308 [alert runModal];
309}
thsc304f7e2008-01-22 23:25:15 +0000310
John Arbuckle693a3e02015-06-19 10:53:27 +0100311/* Handles any errors that happen with a device transaction */
312static void handleAnyDeviceErrors(Error * err)
313{
314 if (err) {
315 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
316 encoding: NSASCIIStringEncoding]);
317 error_free(err);
318 }
319}
thsc304f7e2008-01-22 23:25:15 +0000320
bellard5b0753e2005-03-01 21:37:28 +0000321/*
322 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +0000323 QemuCocoaView
bellard5b0753e2005-03-01 21:37:28 +0000324 ------------------------------------------------------
325*/
thsc304f7e2008-01-22 23:25:15 +0000326@interface QemuCocoaView : NSView
bellard5b0753e2005-03-01 21:37:28 +0000327{
thsc304f7e2008-01-22 23:25:15 +0000328 QEMUScreen screen;
329 NSWindow *fullScreenWindow;
330 float cx,cy,cw,ch,cdx,cdy;
331 CGDataProviderRef dataProviderRef;
Peter Maydell55888402019-02-25 10:24:33 +0000332 pixman_image_t *pixman_image;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700333 BOOL modifiers_state[256];
Peter Maydell49b9bd42013-12-08 22:59:03 +0000334 BOOL isMouseGrabbed;
thsc304f7e2008-01-22 23:25:15 +0000335 BOOL isFullscreen;
336 BOOL isAbsoluteEnabled;
Peter Maydellf61c3872014-06-23 10:35:24 +0100337 BOOL isMouseDeassociated;
thsc304f7e2008-01-22 23:25:15 +0000338}
Peter Maydell72a3e312019-02-25 10:24:28 +0000339- (void) switchSurface:(pixman_image_t *)image;
thsc304f7e2008-01-22 23:25:15 +0000340- (void) grabMouse;
341- (void) ungrabMouse;
342- (void) toggleFullScreen:(id)sender;
John Arbuckle9c3a4182017-11-07 10:14:14 +0000343- (void) handleMonitorInput:(NSEvent *)event;
Peter Maydell60105d72019-02-25 10:24:31 +0000344- (bool) handleEvent:(NSEvent *)event;
345- (bool) handleEventLocked:(NSEvent *)event;
thsc304f7e2008-01-22 23:25:15 +0000346- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
Peter Maydellf61c3872014-06-23 10:35:24 +0100347/* The state surrounding mouse grabbing is potentially confusing.
348 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
349 * pointing device an absolute-position one?"], but is only updated on
350 * next refresh.
351 * isMouseGrabbed tracks whether GUI events are directed to the guest;
352 * it controls whether special keys like Cmd get sent to the guest,
353 * and whether we capture the mouse when in non-absolute mode.
354 * isMouseDeassociated tracks whether we've told MacOSX to disassociate
355 * the mouse and mouse cursor position by calling
356 * CGAssociateMouseAndMouseCursorPosition(FALSE)
357 * (which basically happens if we grab in non-absolute mode).
358 */
Peter Maydell49b9bd42013-12-08 22:59:03 +0000359- (BOOL) isMouseGrabbed;
thsc304f7e2008-01-22 23:25:15 +0000360- (BOOL) isAbsoluteEnabled;
Peter Maydellf61c3872014-06-23 10:35:24 +0100361- (BOOL) isMouseDeassociated;
thsc304f7e2008-01-22 23:25:15 +0000362- (float) cdx;
363- (float) cdy;
364- (QEMUScreen) gscreen;
John Arbuckle3b178b72015-09-25 23:14:00 +0100365- (void) raiseAllKeys;
thsc304f7e2008-01-22 23:25:15 +0000366@end
ths3b46e622007-09-17 08:09:54 +0000367
Andreas Färber7fee1992011-06-09 20:53:32 +0200368QemuCocoaView *cocoaView;
369
thsc304f7e2008-01-22 23:25:15 +0000370@implementation QemuCocoaView
371- (id)initWithFrame:(NSRect)frameRect
372{
373 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
ths3b46e622007-09-17 08:09:54 +0000374
thsc304f7e2008-01-22 23:25:15 +0000375 self = [super initWithFrame:frameRect];
376 if (self) {
pbrook95219892006-04-09 01:06:34 +0000377
thsc304f7e2008-01-22 23:25:15 +0000378 screen.bitsPerComponent = 8;
379 screen.bitsPerPixel = 32;
380 screen.width = frameRect.size.width;
381 screen.height = frameRect.size.height;
bellard7c206a72005-12-18 19:18:45 +0000382
thsc304f7e2008-01-22 23:25:15 +0000383 }
384 return self;
385}
bellard7c206a72005-12-18 19:18:45 +0000386
thsc304f7e2008-01-22 23:25:15 +0000387- (void) dealloc
388{
389 COCOA_DEBUG("QemuCocoaView: dealloc\n");
bellard7c206a72005-12-18 19:18:45 +0000390
Peter Maydell55888402019-02-25 10:24:33 +0000391 if (dataProviderRef) {
thsc304f7e2008-01-22 23:25:15 +0000392 CGDataProviderRelease(dataProviderRef);
Peter Maydell55888402019-02-25 10:24:33 +0000393 pixman_image_unref(pixman_image);
394 }
ths3b46e622007-09-17 08:09:54 +0000395
thsc304f7e2008-01-22 23:25:15 +0000396 [super dealloc];
397}
bellard5cbfcd02006-06-14 15:53:24 +0000398
Andreas Färberd50f71d2009-12-13 02:03:33 +0100399- (BOOL) isOpaque
400{
401 return YES;
402}
403
Peter Maydell5dd45be2014-06-23 10:35:23 +0100404- (BOOL) screenContainsPoint:(NSPoint) p
405{
406 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
407}
408
Peter Maydell13aefd32014-06-23 10:35:25 +0100409- (void) hideCursor
410{
411 if (!cursor_hide) {
412 return;
413 }
414 [NSCursor hide];
415}
416
417- (void) unhideCursor
418{
419 if (!cursor_hide) {
420 return;
421 }
422 [NSCursor unhide];
423}
424
thsc304f7e2008-01-22 23:25:15 +0000425- (void) drawRect:(NSRect) rect
426{
427 COCOA_DEBUG("QemuCocoaView: drawRect\n");
bellard5cbfcd02006-06-14 15:53:24 +0000428
thsc304f7e2008-01-22 23:25:15 +0000429 // get CoreGraphic context
Brendan Shanks5e246002019-01-31 23:12:25 -0800430#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10
thsc304f7e2008-01-22 23:25:15 +0000431 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] graphicsPort];
Brendan Shanks5e246002019-01-31 23:12:25 -0800432#else
433 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
434#endif
435
thsc304f7e2008-01-22 23:25:15 +0000436 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
437 CGContextSetShouldAntialias (viewContextRef, NO);
ths3b46e622007-09-17 08:09:54 +0000438
thsc304f7e2008-01-22 23:25:15 +0000439 // draw screen bitmap directly to Core Graphics context
Peter Maydell7d270b12013-12-24 02:51:47 +0000440 if (!dataProviderRef) {
441 // Draw request before any guest device has set up a framebuffer:
442 // just draw an opaque black rectangle
443 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
444 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
445 } else {
thsc304f7e2008-01-22 23:25:15 +0000446 CGImageRef imageRef = CGImageCreate(
447 screen.width, //width
448 screen.height, //height
449 screen.bitsPerComponent, //bitsPerComponent
450 screen.bitsPerPixel, //bitsPerPixel
aliguori9794f742009-03-04 19:25:22 +0000451 (screen.width * (screen.bitsPerComponent/2)), //bytesPerRow
Andreas Färber04afa4a2009-12-13 00:58:21 +0100452#ifdef __LITTLE_ENDIAN__
thsc304f7e2008-01-22 23:25:15 +0000453 CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
aliguori9794f742009-03-04 19:25:22 +0000454 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
thsc304f7e2008-01-22 23:25:15 +0000455#else
456 CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
457 kCGImageAlphaNoneSkipFirst, //bitmapInfo
458#endif
459 dataProviderRef, //provider
460 NULL, //decode
461 0, //interpolate
462 kCGRenderingIntentDefault //intent
463 );
Peter Maydellb63901d2015-05-19 09:11:17 +0100464 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
465 const NSRect *rectList;
Peter Maydellb63901d2015-05-19 09:11:17 +0100466 NSInteger rectCount;
Peter Maydellb63901d2015-05-19 09:11:17 +0100467 int i;
468 CGImageRef clipImageRef;
469 CGRect clipRect;
ths3b46e622007-09-17 08:09:54 +0000470
Peter Maydellb63901d2015-05-19 09:11:17 +0100471 [self getRectsBeingDrawn:&rectList count:&rectCount];
472 for (i = 0; i < rectCount; i++) {
473 clipRect.origin.x = rectList[i].origin.x / cdx;
474 clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
475 clipRect.size.width = rectList[i].size.width / cdx;
476 clipRect.size.height = rectList[i].size.height / cdy;
477 clipImageRef = CGImageCreateWithImageInRect(
478 imageRef,
479 clipRect
480 );
481 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
482 CGImageRelease (clipImageRef);
bellard5b0753e2005-03-01 21:37:28 +0000483 }
thsc304f7e2008-01-22 23:25:15 +0000484 CGImageRelease (imageRef);
bellard5b0753e2005-03-01 21:37:28 +0000485 }
486}
487
thsc304f7e2008-01-22 23:25:15 +0000488- (void) setContentDimensions
bellard5b0753e2005-03-01 21:37:28 +0000489{
thsc304f7e2008-01-22 23:25:15 +0000490 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
ths3b46e622007-09-17 08:09:54 +0000491
thsc304f7e2008-01-22 23:25:15 +0000492 if (isFullscreen) {
493 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
494 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100495
496 /* stretches video, but keeps same aspect ratio */
497 if (stretch_video == true) {
498 /* use smallest stretch value - prevents clipping on sides */
499 if (MIN(cdx, cdy) == cdx) {
500 cdy = cdx;
501 } else {
502 cdx = cdy;
503 }
504 } else { /* No stretching */
505 cdx = cdy = 1;
506 }
thsc304f7e2008-01-22 23:25:15 +0000507 cw = screen.width * cdx;
508 ch = screen.height * cdy;
509 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
510 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
511 } else {
512 cx = 0;
513 cy = 0;
514 cw = screen.width;
515 ch = screen.height;
516 cdx = 1.0;
517 cdy = 1.0;
518 }
bellard5b0753e2005-03-01 21:37:28 +0000519}
520
Peter Maydell72a3e312019-02-25 10:24:28 +0000521- (void) switchSurface:(pixman_image_t *)image
thsc304f7e2008-01-22 23:25:15 +0000522{
Gerd Hoffmann5e00d3a2013-03-01 12:52:06 +0100523 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
thsc304f7e2008-01-22 23:25:15 +0000524
Peter Maydell72a3e312019-02-25 10:24:28 +0000525 int w = pixman_image_get_width(image);
526 int h = pixman_image_get_height(image);
527 pixman_format_code_t image_format = pixman_image_get_format(image);
Peter Maydell381600d2014-06-23 10:35:22 +0100528 /* cdx == 0 means this is our very first surface, in which case we need
529 * to recalculate the content dimensions even if it happens to be the size
530 * of the initial empty window.
531 */
532 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
Peter Maydelld3345a02013-12-24 02:51:46 +0000533
534 int oldh = screen.height;
535 if (isResize) {
536 // Resize before we trigger the redraw, or we'll redraw at the wrong size
537 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
538 screen.width = w;
539 screen.height = h;
540 [self setContentDimensions];
541 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
542 }
Peter Maydell8510d912013-03-18 20:28:21 +0000543
thsc304f7e2008-01-22 23:25:15 +0000544 // update screenBuffer
Peter Maydell55888402019-02-25 10:24:33 +0000545 if (dataProviderRef) {
thsc304f7e2008-01-22 23:25:15 +0000546 CGDataProviderRelease(dataProviderRef);
Peter Maydell55888402019-02-25 10:24:33 +0000547 pixman_image_unref(pixman_image);
548 }
thsc304f7e2008-01-22 23:25:15 +0000549
aliguori9794f742009-03-04 19:25:22 +0000550 //sync host window color space with guests
Peter Maydell72a3e312019-02-25 10:24:28 +0000551 screen.bitsPerPixel = PIXMAN_FORMAT_BPP(image_format);
552 screen.bitsPerComponent = DIV_ROUND_UP(screen.bitsPerPixel, 8) * 2;
thsc304f7e2008-01-22 23:25:15 +0000553
Peter Maydell55888402019-02-25 10:24:33 +0000554 pixman_image = image;
Peter Maydell72a3e312019-02-25 10:24:28 +0000555 dataProviderRef = CGDataProviderCreateWithData(NULL, pixman_image_get_data(image), w * 4 * h, NULL);
thsc304f7e2008-01-22 23:25:15 +0000556
557 // update windows
558 if (isFullscreen) {
559 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
Peter Maydelld3345a02013-12-24 02:51:46 +0000560 [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 +0000561 } else {
562 if (qemu_name)
563 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
Peter Maydelld3345a02013-12-24 02:51:46 +0000564 [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 +0000565 }
Peter Maydelld3345a02013-12-24 02:51:46 +0000566
567 if (isResize) {
568 [normalWindow center];
569 }
thsc304f7e2008-01-22 23:25:15 +0000570}
571
572- (void) toggleFullScreen:(id)sender
573{
574 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
575
576 if (isFullscreen) { // switch from fullscreen to desktop
577 isFullscreen = FALSE;
578 [self ungrabMouse];
579 [self setContentDimensions];
thsc304f7e2008-01-22 23:25:15 +0000580 if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
581 [self exitFullScreenModeWithOptions:nil];
582 } else {
thsc304f7e2008-01-22 23:25:15 +0000583 [fullScreenWindow close];
584 [normalWindow setContentView: self];
585 [normalWindow makeKeyAndOrderFront: self];
586 [NSMenu setMenuBarVisible:YES];
thsc304f7e2008-01-22 23:25:15 +0000587 }
thsc304f7e2008-01-22 23:25:15 +0000588 } else { // switch from desktop to fullscreen
589 isFullscreen = TRUE;
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100590 [normalWindow orderOut: nil]; /* Hide the window */
thsc304f7e2008-01-22 23:25:15 +0000591 [self grabMouse];
592 [self setContentDimensions];
thsc304f7e2008-01-22 23:25:15 +0000593 if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
594 [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
595 [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
596 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
597 nil]];
598 } else {
thsc304f7e2008-01-22 23:25:15 +0000599 [NSMenu setMenuBarVisible:NO];
600 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700601 styleMask:NSWindowStyleMaskBorderless
thsc304f7e2008-01-22 23:25:15 +0000602 backing:NSBackingStoreBuffered
603 defer:NO];
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100604 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
thsc304f7e2008-01-22 23:25:15 +0000605 [fullScreenWindow setHasShadow:NO];
Programmingkid5d1b2ee2015-05-19 09:11:17 +0100606 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
607 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
608 [[fullScreenWindow contentView] addSubview: self];
thsc304f7e2008-01-22 23:25:15 +0000609 [fullScreenWindow makeKeyAndOrderFront:self];
thsc304f7e2008-01-22 23:25:15 +0000610 }
thsc304f7e2008-01-22 23:25:15 +0000611 }
612}
613
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700614- (void) toggleModifier: (int)keycode {
615 // Toggle the stored state.
616 modifiers_state[keycode] = !modifiers_state[keycode];
617 // Send a keyup or keydown depending on the state.
618 qemu_input_event_send_key_qcode(dcl->con, keycode, modifiers_state[keycode]);
619}
620
621- (void) toggleStatefulModifier: (int)keycode {
622 // Toggle the stored state.
623 modifiers_state[keycode] = !modifiers_state[keycode];
624 // Generate keydown and keyup.
625 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
626 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
627}
628
John Arbuckle9c3a4182017-11-07 10:14:14 +0000629// Does the work of sending input to the monitor
630- (void) handleMonitorInput:(NSEvent *)event
631{
632 int keysym = 0;
633 int control_key = 0;
634
635 // if the control key is down
636 if ([event modifierFlags] & NSEventModifierFlagControl) {
637 control_key = 1;
638 }
639
640 /* translates Macintosh keycodes to QEMU's keysym */
641
642 int without_control_translation[] = {
643 [0 ... 0xff] = 0, // invalid key
644
645 [kVK_UpArrow] = QEMU_KEY_UP,
646 [kVK_DownArrow] = QEMU_KEY_DOWN,
647 [kVK_RightArrow] = QEMU_KEY_RIGHT,
648 [kVK_LeftArrow] = QEMU_KEY_LEFT,
649 [kVK_Home] = QEMU_KEY_HOME,
650 [kVK_End] = QEMU_KEY_END,
651 [kVK_PageUp] = QEMU_KEY_PAGEUP,
652 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
653 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
654 [kVK_Delete] = QEMU_KEY_BACKSPACE,
655 };
656
657 int with_control_translation[] = {
658 [0 ... 0xff] = 0, // invalid key
659
660 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
661 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
662 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
663 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
664 [kVK_Home] = QEMU_KEY_CTRL_HOME,
665 [kVK_End] = QEMU_KEY_CTRL_END,
666 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
667 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
668 };
669
670 if (control_key != 0) { /* If the control key is being used */
671 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
672 keysym = with_control_translation[[event keyCode]];
673 }
674 } else {
675 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
676 keysym = without_control_translation[[event keyCode]];
677 }
678 }
679
680 // if not a key that needs translating
681 if (keysym == 0) {
682 NSString *ks = [event characters];
683 if ([ks length] > 0) {
684 keysym = [ks characterAtIndex:0];
685 }
686 }
687
688 if (keysym) {
689 kbd_put_keysym(keysym);
690 }
691}
692
Peter Maydell60105d72019-02-25 10:24:31 +0000693- (bool) handleEvent:(NSEvent *)event
thsc304f7e2008-01-22 23:25:15 +0000694{
Peter Maydell60105d72019-02-25 10:24:31 +0000695 return bool_with_iothread_lock(^{
696 return [self handleEventLocked:event];
Peter Maydell31819e92019-02-25 10:24:27 +0000697 });
698}
thsc304f7e2008-01-22 23:25:15 +0000699
Peter Maydell60105d72019-02-25 10:24:31 +0000700- (bool) handleEventLocked:(NSEvent *)event
Peter Maydell31819e92019-02-25 10:24:27 +0000701{
Peter Maydell60105d72019-02-25 10:24:31 +0000702 /* Return true if we handled the event, false if it should be given to OSX */
Peter Maydell31819e92019-02-25 10:24:27 +0000703 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
thsc304f7e2008-01-22 23:25:15 +0000704 int buttons = 0;
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700705 int keycode = 0;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100706 bool mouse_event = false;
John Arbuckle0c6c4392018-07-02 22:00:17 -0400707 static bool switched_to_fullscreen = false;
thsc304f7e2008-01-22 23:25:15 +0000708 NSPoint p = [event locationInWindow];
709
710 switch ([event type]) {
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700711 case NSEventTypeFlagsChanged:
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700712 if ([event keyCode] == 0) {
713 // When the Cocoa keyCode is zero that means keys should be
714 // synthesized based on the values in in the eventModifiers
715 // bitmask.
716
717 if (qemu_console_is_graphic(NULL)) {
John Arbucklee7206242017-06-28 15:37:16 -0400718 NSUInteger modifiers = [event modifierFlags];
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700719
720 if (!!(modifiers & NSEventModifierFlagCapsLock) != !!modifiers_state[Q_KEY_CODE_CAPS_LOCK]) {
721 [self toggleStatefulModifier:Q_KEY_CODE_CAPS_LOCK];
722 }
723 if (!!(modifiers & NSEventModifierFlagShift) != !!modifiers_state[Q_KEY_CODE_SHIFT]) {
724 [self toggleModifier:Q_KEY_CODE_SHIFT];
725 }
726 if (!!(modifiers & NSEventModifierFlagControl) != !!modifiers_state[Q_KEY_CODE_CTRL]) {
727 [self toggleModifier:Q_KEY_CODE_CTRL];
728 }
729 if (!!(modifiers & NSEventModifierFlagOption) != !!modifiers_state[Q_KEY_CODE_ALT]) {
730 [self toggleModifier:Q_KEY_CODE_ALT];
731 }
732 if (!!(modifiers & NSEventModifierFlagCommand) != !!modifiers_state[Q_KEY_CODE_META_L]) {
733 [self toggleModifier:Q_KEY_CODE_META_L];
734 }
735 }
736 } else {
737 keycode = cocoa_keycode_to_qemu([event keyCode]);
738 }
Peter Maydell88959192013-12-08 22:59:02 +0000739
John Arbuckleaaac7142016-03-23 14:26:18 +0000740 if ((keycode == Q_KEY_CODE_META_L || keycode == Q_KEY_CODE_META_R)
741 && !isMouseGrabbed) {
Peter Maydell88959192013-12-08 22:59:02 +0000742 /* Don't pass command key changes to guest unless mouse is grabbed */
743 keycode = 0;
744 }
745
thsc304f7e2008-01-22 23:25:15 +0000746 if (keycode) {
John Arbuckleaaac7142016-03-23 14:26:18 +0000747 // emulate caps lock and num lock keydown and keyup
748 if (keycode == Q_KEY_CODE_CAPS_LOCK ||
749 keycode == Q_KEY_CODE_NUM_LOCK) {
Ian McKellar via Qemu-develaf8862b2017-05-26 16:38:16 -0700750 [self toggleStatefulModifier:keycode];
Peter Maydell68c0aa62013-04-17 09:16:35 +0000751 } else if (qemu_console_is_graphic(NULL)) {
John Arbuckle0c6c4392018-07-02 22:00:17 -0400752 if (switched_to_fullscreen) {
753 switched_to_fullscreen = false;
754 } else {
755 [self toggleModifier:keycode];
756 }
thsc304f7e2008-01-22 23:25:15 +0000757 }
758 }
759
thsc304f7e2008-01-22 23:25:15 +0000760 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700761 case NSEventTypeKeyDown:
Peter Maydell88959192013-12-08 22:59:02 +0000762 keycode = cocoa_keycode_to_qemu([event keyCode]);
thsc304f7e2008-01-22 23:25:15 +0000763
Peter Maydell88959192013-12-08 22:59:02 +0000764 // forward command key combos to the host UI unless the mouse is grabbed
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700765 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
John Arbuckle0c6c4392018-07-02 22:00:17 -0400766 /*
767 * Prevent the command key from being stuck down in the guest
768 * when using Command-F to switch to full screen mode.
769 */
770 if (keycode == Q_KEY_CODE_F) {
771 switched_to_fullscreen = true;
772 }
Peter Maydell60105d72019-02-25 10:24:31 +0000773 return false;
thsc304f7e2008-01-22 23:25:15 +0000774 }
775
776 // default
thsc304f7e2008-01-22 23:25:15 +0000777
John Arbuckle5929e362017-11-07 10:14:14 +0000778 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700779 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
John Arbuckle5929e362017-11-07 10:14:14 +0000780 NSString *keychar = [event charactersIgnoringModifiers];
781 if ([keychar length] == 1) {
782 char key = [keychar characterAtIndex:0];
783 switch (key) {
thsc304f7e2008-01-22 23:25:15 +0000784
John Arbuckle5929e362017-11-07 10:14:14 +0000785 // enable graphic console
786 case '1' ... '9':
787 console_select(key - '0' - 1); /* ascii math */
Peter Maydell60105d72019-02-25 10:24:31 +0000788 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000789
790 // release the mouse grab
791 case 'g':
792 [self ungrabMouse];
Peter Maydell60105d72019-02-25 10:24:31 +0000793 return true;
John Arbuckle5929e362017-11-07 10:14:14 +0000794 }
thsc304f7e2008-01-22 23:25:15 +0000795 }
Peter Maydellef2088f2017-11-07 10:14:14 +0000796 }
thsc304f7e2008-01-22 23:25:15 +0000797
Peter Maydellef2088f2017-11-07 10:14:14 +0000798 if (qemu_console_is_graphic(NULL)) {
John Arbuckleaaac7142016-03-23 14:26:18 +0000799 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
thsc304f7e2008-01-22 23:25:15 +0000800 } else {
John Arbuckle9c3a4182017-11-07 10:14:14 +0000801 [self handleMonitorInput: event];
thsc304f7e2008-01-22 23:25:15 +0000802 }
803 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700804 case NSEventTypeKeyUp:
thsc304f7e2008-01-22 23:25:15 +0000805 keycode = cocoa_keycode_to_qemu([event keyCode]);
Peter Maydell88959192013-12-08 22:59:02 +0000806
807 // don't pass the guest a spurious key-up if we treated this
808 // command-key combo as a host UI action
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700809 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
Peter Maydell60105d72019-02-25 10:24:31 +0000810 return true;
Peter Maydell88959192013-12-08 22:59:02 +0000811 }
812
Peter Maydell68c0aa62013-04-17 09:16:35 +0000813 if (qemu_console_is_graphic(NULL)) {
John Arbuckleaaac7142016-03-23 14:26:18 +0000814 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
thsc304f7e2008-01-22 23:25:15 +0000815 }
816 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700817 case NSEventTypeMouseMoved:
thsc304f7e2008-01-22 23:25:15 +0000818 if (isAbsoluteEnabled) {
Peter Maydell5dd45be2014-06-23 10:35:23 +0100819 if (![self screenContainsPoint:p] || ![[self window] isKeyWindow]) {
Peter Maydellf61c3872014-06-23 10:35:24 +0100820 if (isMouseGrabbed) {
821 [self ungrabMouse];
thsc304f7e2008-01-22 23:25:15 +0000822 }
823 } else {
Peter Maydellf61c3872014-06-23 10:35:24 +0100824 if (!isMouseGrabbed) {
825 [self grabMouse];
thsc304f7e2008-01-22 23:25:15 +0000826 }
827 }
828 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100829 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000830 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700831 case NSEventTypeLeftMouseDown:
832 if ([event modifierFlags] & NSEventModifierFlagCommand) {
thsc304f7e2008-01-22 23:25:15 +0000833 buttons |= MOUSE_EVENT_RBUTTON;
834 } else {
835 buttons |= MOUSE_EVENT_LBUTTON;
836 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100837 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000838 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700839 case NSEventTypeRightMouseDown:
thsc304f7e2008-01-22 23:25:15 +0000840 buttons |= MOUSE_EVENT_RBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100841 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000842 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700843 case NSEventTypeOtherMouseDown:
thsc304f7e2008-01-22 23:25:15 +0000844 buttons |= MOUSE_EVENT_MBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100845 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000846 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700847 case NSEventTypeLeftMouseDragged:
848 if ([event modifierFlags] & NSEventModifierFlagCommand) {
thsc304f7e2008-01-22 23:25:15 +0000849 buttons |= MOUSE_EVENT_RBUTTON;
850 } else {
851 buttons |= MOUSE_EVENT_LBUTTON;
852 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100853 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000854 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700855 case NSEventTypeRightMouseDragged:
thsc304f7e2008-01-22 23:25:15 +0000856 buttons |= MOUSE_EVENT_RBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100857 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000858 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700859 case NSEventTypeOtherMouseDragged:
thsc304f7e2008-01-22 23:25:15 +0000860 buttons |= MOUSE_EVENT_MBUTTON;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100861 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000862 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700863 case NSEventTypeLeftMouseUp:
Peter Maydellf61c3872014-06-23 10:35:24 +0100864 mouse_event = true;
865 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
Programmingkid9e8204b2016-08-15 22:11:06 -0400866 if([[self window] isKeyWindow]) {
867 [self grabMouse];
868 }
thsc304f7e2008-01-22 23:25:15 +0000869 }
870 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700871 case NSEventTypeRightMouseUp:
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100872 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000873 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700874 case NSEventTypeOtherMouseUp:
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100875 mouse_event = true;
thsc304f7e2008-01-22 23:25:15 +0000876 break;
Brendan Shanks4ba967a2017-04-24 23:29:52 -0700877 case NSEventTypeScrollWheel:
John Arbuckleae7313e2018-01-08 13:07:07 -0500878 /*
879 * Send wheel events to the guest regardless of window focus.
880 * This is in-line with standard Mac OS X UI behaviour.
881 */
882
John Arbuckledc3c89d2018-07-09 11:02:35 -0400883 /*
884 * When deltaY is zero, it means that this scrolling event was
885 * either horizontal, or so fine that it only appears in
886 * scrollingDeltaY. So we drop the event.
887 */
888 if ([event deltaY] != 0) {
John Arbuckleae7313e2018-01-08 13:07:07 -0500889 /* Determine if this is a scroll up or scroll down event */
John Arbuckledc3c89d2018-07-09 11:02:35 -0400890 buttons = ([event deltaY] > 0) ?
891 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
892 qemu_input_queue_btn(dcl->con, buttons, true);
893 qemu_input_event_sync();
894 qemu_input_queue_btn(dcl->con, buttons, false);
895 qemu_input_event_sync();
896 }
John Arbuckleae7313e2018-01-08 13:07:07 -0500897 /*
898 * Since deltaY also reports scroll wheel events we prevent mouse
899 * movement code from executing.
900 */
901 mouse_event = false;
thsc304f7e2008-01-22 23:25:15 +0000902 break;
903 default:
Peter Maydell60105d72019-02-25 10:24:31 +0000904 return false;
thsc304f7e2008-01-22 23:25:15 +0000905 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100906
907 if (mouse_event) {
Peter Maydell8d3a5d92015-11-26 15:19:28 +0000908 /* Don't send button events to the guest unless we've got a
909 * mouse grab or window focus. If we have neither then this event
910 * is the user clicking on the background window to activate and
911 * bring us to the front, which will be done by the sendEvent
912 * call below. We definitely don't want to pass that click through
913 * to the guest.
914 */
915 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
916 (last_buttons != buttons)) {
Eric Blake7fb1cf12015-11-18 01:52:57 -0700917 static uint32_t bmap[INPUT_BUTTON__MAX] = {
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100918 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
919 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
John Arbuckleae7313e2018-01-08 13:07:07 -0500920 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100921 };
922 qemu_input_update_buttons(dcl->con, bmap, last_buttons, buttons);
923 last_buttons = buttons;
924 }
Peter Maydellf61c3872014-06-23 10:35:24 +0100925 if (isMouseGrabbed) {
926 if (isAbsoluteEnabled) {
927 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
928 * The check on screenContainsPoint is to avoid sending out of range values for
929 * clicks in the titlebar.
930 */
931 if ([self screenContainsPoint:p]) {
Philippe Voinov9cfa7ab2017-05-05 15:39:52 +0200932 qemu_input_queue_abs(dcl->con, INPUT_AXIS_X, p.x, 0, screen.width);
933 qemu_input_queue_abs(dcl->con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
Peter Maydellf61c3872014-06-23 10:35:24 +0100934 }
935 } else {
936 qemu_input_queue_rel(dcl->con, INPUT_AXIS_X, (int)[event deltaX]);
937 qemu_input_queue_rel(dcl->con, INPUT_AXIS_Y, (int)[event deltaY]);
938 }
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100939 } else {
Peter Maydell60105d72019-02-25 10:24:31 +0000940 return false;
Gerd Hoffmann21bae112013-12-04 14:08:04 +0100941 }
942 qemu_input_event_sync();
943 }
Peter Maydell60105d72019-02-25 10:24:31 +0000944 return true;
thsc304f7e2008-01-22 23:25:15 +0000945}
946
947- (void) grabMouse
948{
949 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
950
951 if (!isFullscreen) {
952 if (qemu_name)
John Arbuckle5929e362017-11-07 10:14:14 +0000953 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
thsc304f7e2008-01-22 23:25:15 +0000954 else
John Arbuckle5929e362017-11-07 10:14:14 +0000955 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
thsc304f7e2008-01-22 23:25:15 +0000956 }
Peter Maydell13aefd32014-06-23 10:35:25 +0100957 [self hideCursor];
Peter Maydellf61c3872014-06-23 10:35:24 +0100958 if (!isAbsoluteEnabled) {
959 isMouseDeassociated = TRUE;
960 CGAssociateMouseAndMouseCursorPosition(FALSE);
961 }
Peter Maydell49b9bd42013-12-08 22:59:03 +0000962 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
thsc304f7e2008-01-22 23:25:15 +0000963}
964
965- (void) ungrabMouse
966{
967 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
968
969 if (!isFullscreen) {
970 if (qemu_name)
971 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
972 else
973 [normalWindow setTitle:@"QEMU"];
974 }
Peter Maydell13aefd32014-06-23 10:35:25 +0100975 [self unhideCursor];
Peter Maydellf61c3872014-06-23 10:35:24 +0100976 if (isMouseDeassociated) {
977 CGAssociateMouseAndMouseCursorPosition(TRUE);
978 isMouseDeassociated = FALSE;
979 }
Peter Maydell49b9bd42013-12-08 22:59:03 +0000980 isMouseGrabbed = FALSE;
thsc304f7e2008-01-22 23:25:15 +0000981}
982
983- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
Peter Maydell49b9bd42013-12-08 22:59:03 +0000984- (BOOL) isMouseGrabbed {return isMouseGrabbed;}
thsc304f7e2008-01-22 23:25:15 +0000985- (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
Peter Maydellf61c3872014-06-23 10:35:24 +0100986- (BOOL) isMouseDeassociated {return isMouseDeassociated;}
thsc304f7e2008-01-22 23:25:15 +0000987- (float) cdx {return cdx;}
988- (float) cdy {return cdy;}
989- (QEMUScreen) gscreen {return screen;}
John Arbuckle3b178b72015-09-25 23:14:00 +0100990
991/*
992 * Makes the target think all down keys are being released.
993 * This prevents a stuck key problem, since we will not see
994 * key up events for those keys after we have lost focus.
995 */
996- (void) raiseAllKeys
997{
John Arbuckle3b178b72015-09-25 23:14:00 +0100998 const int max_index = ARRAY_SIZE(modifiers_state);
999
Peter Maydell31819e92019-02-25 10:24:27 +00001000 with_iothread_lock(^{
1001 int index;
1002
1003 for (index = 0; index < max_index; index++) {
1004 if (modifiers_state[index]) {
1005 modifiers_state[index] = 0;
1006 qemu_input_event_send_key_qcode(dcl->con, index, false);
1007 }
1008 }
1009 });
John Arbuckle3b178b72015-09-25 23:14:00 +01001010}
bellard5b0753e2005-03-01 21:37:28 +00001011@end
1012
1013
thsc304f7e2008-01-22 23:25:15 +00001014
bellard5b0753e2005-03-01 21:37:28 +00001015/*
1016 ------------------------------------------------------
thsc304f7e2008-01-22 23:25:15 +00001017 QemuCocoaAppController
bellard5b0753e2005-03-01 21:37:28 +00001018 ------------------------------------------------------
1019*/
thsc304f7e2008-01-22 23:25:15 +00001020@interface QemuCocoaAppController : NSObject
Peter Maydell2a4c8c52015-05-19 09:11:18 +01001021#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
John Arbuckled9bc14f2015-09-25 23:13:59 +01001022 <NSWindowDelegate, NSApplicationDelegate>
Peter Maydell2a4c8c52015-05-19 09:11:18 +01001023#endif
bellard5b0753e2005-03-01 21:37:28 +00001024{
1025}
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001026- (void)doToggleFullScreen:(id)sender;
thsc304f7e2008-01-22 23:25:15 +00001027- (void)toggleFullScreen:(id)sender;
1028- (void)showQEMUDoc:(id)sender;
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001029- (void)zoomToFit:(id) sender;
Programmingkidb4c6a112015-05-19 09:11:18 +01001030- (void)displayConsole:(id)sender;
John Arbuckle8524f1c2015-06-19 10:53:27 +01001031- (void)pauseQEMU:(id)sender;
1032- (void)resumeQEMU:(id)sender;
1033- (void)displayPause;
1034- (void)removePause;
John Arbuckle27074612015-06-19 10:53:27 +01001035- (void)restartQEMU:(id)sender;
1036- (void)powerDownQEMU:(id)sender;
John Arbuckle693a3e02015-06-19 10:53:27 +01001037- (void)ejectDeviceMedia:(id)sender;
1038- (void)changeDeviceMedia:(id)sender;
John Arbuckled9bc14f2015-09-25 23:13:59 +01001039- (BOOL)verifyQuit;
John Arbucklef4747902016-03-23 14:26:17 +00001040- (void)openDocumentation:(NSString *)filename;
Programmingkid9e8204b2016-08-15 22:11:06 -04001041- (IBAction) do_about_menu_item: (id) sender;
1042- (void)make_about_window;
John Arbucklee47ec1a2017-06-13 23:17:38 -04001043- (void)adjustSpeed:(id)sender;
bellard5b0753e2005-03-01 21:37:28 +00001044@end
1045
thsc304f7e2008-01-22 23:25:15 +00001046@implementation QemuCocoaAppController
1047- (id) init
1048{
1049 COCOA_DEBUG("QemuCocoaAppController: init\n");
1050
1051 self = [super init];
1052 if (self) {
1053
1054 // create a view and add it to the window
1055 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1056 if(!cocoaView) {
1057 fprintf(stderr, "(cocoa) can't create a view\n");
1058 exit(1);
1059 }
1060
1061 // create a window
1062 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001063 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
thsc304f7e2008-01-22 23:25:15 +00001064 backing:NSBackingStoreBuffered defer:NO];
1065 if(!normalWindow) {
1066 fprintf(stderr, "(cocoa) can't create window\n");
1067 exit(1);
1068 }
1069 [normalWindow setAcceptsMouseMovedEvents:YES];
John Arbucklea1dbc052015-10-13 21:51:18 +01001070 [normalWindow setTitle:@"QEMU"];
thsc304f7e2008-01-22 23:25:15 +00001071 [normalWindow setContentView:cocoaView];
Peter Maydell81801ae2015-05-19 09:11:18 +01001072#if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10)
Andreas Färber561ef252009-12-13 03:06:20 +01001073 [normalWindow useOptimizedDrawing:YES];
Peter Maydell81801ae2015-05-19 09:11:18 +01001074#endif
thsc304f7e2008-01-22 23:25:15 +00001075 [normalWindow makeKeyAndOrderFront:self];
Peter Maydell49060c22013-12-24 11:54:12 +00001076 [normalWindow center];
John Arbuckled9bc14f2015-09-25 23:13:59 +01001077 [normalWindow setDelegate: self];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001078 stretch_video = false;
John Arbuckle8524f1c2015-06-19 10:53:27 +01001079
1080 /* Used for displaying pause on the screen */
1081 pauseLabel = [NSTextField new];
1082 [pauseLabel setBezeled:YES];
1083 [pauseLabel setDrawsBackground:YES];
1084 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1085 [pauseLabel setEditable:NO];
1086 [pauseLabel setSelectable:NO];
1087 [pauseLabel setStringValue: @"Paused"];
1088 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1089 [pauseLabel setTextColor: [NSColor blackColor]];
1090 [pauseLabel sizeToFit];
John Arbuckle693a3e02015-06-19 10:53:27 +01001091
1092 // set the supported image file types that can be opened
1093 supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
John Arbuckle9d227f12016-03-30 12:37:11 -04001094 @"qcow", @"qcow2", @"cloop", @"vmdk", @"cdr",
Programmingkid5f26fcf2016-12-30 15:42:21 -05001095 @"toast", nil];
Programmingkid9e8204b2016-08-15 22:11:06 -04001096 [self make_about_window];
thsc304f7e2008-01-22 23:25:15 +00001097 }
1098 return self;
1099}
1100
1101- (void) dealloc
1102{
1103 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1104
1105 if (cocoaView)
1106 [cocoaView release];
1107 [super dealloc];
1108}
1109
bellard5b0753e2005-03-01 21:37:28 +00001110- (void)applicationDidFinishLaunching: (NSNotification *) note
1111{
thsc304f7e2008-01-22 23:25:15 +00001112 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
Peter Maydell55888402019-02-25 10:24:33 +00001113 /* Tell cocoa_display_init to proceed */
1114 qemu_sem_post(&app_started_sem);
bellard5b0753e2005-03-01 21:37:28 +00001115}
1116
1117- (void)applicationWillTerminate:(NSNotification *)aNotification
1118{
thsc304f7e2008-01-22 23:25:15 +00001119 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1120
Eric Blakecf83f142017-05-15 16:41:13 -05001121 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
bellard5b0753e2005-03-01 21:37:28 +00001122 exit(0);
1123}
1124
Andreas Färber41ea49b2009-12-14 22:13:27 +01001125- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1126{
1127 return YES;
1128}
1129
John Arbuckled9bc14f2015-09-25 23:13:59 +01001130- (NSApplicationTerminateReply)applicationShouldTerminate:
1131 (NSApplication *)sender
1132{
1133 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1134 return [self verifyQuit];
1135}
1136
1137/* Called when the user clicks on a window's close button */
1138- (BOOL)windowShouldClose:(id)sender
1139{
1140 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1141 [NSApp terminate: sender];
1142 /* If the user allows the application to quit then the call to
1143 * NSApp terminate will never return. If we get here then the user
1144 * cancelled the quit, so we should return NO to not permit the
1145 * closing of this window.
1146 */
1147 return NO;
1148}
1149
John Arbuckle3b178b72015-09-25 23:14:00 +01001150/* Called when QEMU goes into the background */
1151- (void) applicationWillResignActive: (NSNotification *)aNotification
1152{
1153 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1154 [cocoaView raiseAllKeys];
1155}
1156
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001157/* We abstract the method called by the Enter Fullscreen menu item
1158 * because Mac OS 10.7 and higher disables it. This is because of the
1159 * menu item's old selector's name toggleFullScreen:
1160 */
1161- (void) doToggleFullScreen:(id)sender
1162{
1163 [self toggleFullScreen:(id)sender];
1164}
1165
thsc304f7e2008-01-22 23:25:15 +00001166- (void)toggleFullScreen:(id)sender
bellard5b0753e2005-03-01 21:37:28 +00001167{
thsc304f7e2008-01-22 23:25:15 +00001168 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1169
1170 [cocoaView toggleFullScreen:sender];
1171}
1172
John Arbucklef4747902016-03-23 14:26:17 +00001173/* Tries to find then open the specified filename */
1174- (void) openDocumentation: (NSString *) filename
1175{
1176 /* Where to look for local files */
1177 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"../"};
1178 NSString *full_file_path;
1179
1180 /* iterate thru the possible paths until the file is found */
1181 int index;
1182 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1183 full_file_path = [[NSBundle mainBundle] executablePath];
1184 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1185 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1186 path_array[index], filename];
1187 if ([[NSWorkspace sharedWorkspace] openFile: full_file_path] == YES) {
1188 return;
1189 }
1190 }
1191
1192 /* If none of the paths opened a file */
1193 NSBeep();
1194 QEMU_Alert(@"Failed to open file");
1195}
1196
thsc304f7e2008-01-22 23:25:15 +00001197- (void)showQEMUDoc:(id)sender
1198{
1199 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1200
John Arbucklef4747902016-03-23 14:26:17 +00001201 [self openDocumentation: @"qemu-doc.html"];
thsc304f7e2008-01-22 23:25:15 +00001202}
1203
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001204/* Stretches video to fit host monitor size */
1205- (void)zoomToFit:(id) sender
1206{
1207 stretch_video = !stretch_video;
1208 if (stretch_video == true) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001209 [sender setState: NSControlStateValueOn];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001210 } else {
Brendan Shanks5e246002019-01-31 23:12:25 -08001211 [sender setState: NSControlStateValueOff];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001212 }
1213}
bellard5b0753e2005-03-01 21:37:28 +00001214
Programmingkidb4c6a112015-05-19 09:11:18 +01001215/* Displays the console on the screen */
1216- (void)displayConsole:(id)sender
1217{
1218 console_select([sender tag]);
1219}
John Arbuckle8524f1c2015-06-19 10:53:27 +01001220
1221/* Pause the guest */
1222- (void)pauseQEMU:(id)sender
1223{
Peter Maydell31819e92019-02-25 10:24:27 +00001224 with_iothread_lock(^{
1225 qmp_stop(NULL);
1226 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001227 [sender setEnabled: NO];
1228 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1229 [self displayPause];
1230}
1231
1232/* Resume running the guest operating system */
1233- (void)resumeQEMU:(id) sender
1234{
Peter Maydell31819e92019-02-25 10:24:27 +00001235 with_iothread_lock(^{
1236 qmp_cont(NULL);
1237 });
John Arbuckle8524f1c2015-06-19 10:53:27 +01001238 [sender setEnabled: NO];
1239 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1240 [self removePause];
1241}
1242
1243/* Displays the word pause on the screen */
1244- (void)displayPause
1245{
1246 /* Coordinates have to be calculated each time because the window can change its size */
1247 int xCoord, yCoord, width, height;
1248 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1249 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1250 width = [pauseLabel frame].size.width;
1251 height = [pauseLabel frame].size.height;
1252 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1253 [cocoaView addSubview: pauseLabel];
1254}
1255
1256/* Removes the word pause from the screen */
1257- (void)removePause
1258{
1259 [pauseLabel removeFromSuperview];
1260}
1261
John Arbuckle27074612015-06-19 10:53:27 +01001262/* Restarts QEMU */
1263- (void)restartQEMU:(id)sender
1264{
Peter Maydell31819e92019-02-25 10:24:27 +00001265 with_iothread_lock(^{
1266 qmp_system_reset(NULL);
1267 });
John Arbuckle27074612015-06-19 10:53:27 +01001268}
1269
1270/* Powers down QEMU */
1271- (void)powerDownQEMU:(id)sender
1272{
Peter Maydell31819e92019-02-25 10:24:27 +00001273 with_iothread_lock(^{
1274 qmp_system_powerdown(NULL);
1275 });
John Arbuckle27074612015-06-19 10:53:27 +01001276}
1277
John Arbuckle693a3e02015-06-19 10:53:27 +01001278/* Ejects the media.
1279 * Uses sender's tag to figure out the device to eject.
1280 */
1281- (void)ejectDeviceMedia:(id)sender
1282{
1283 NSString * drive;
1284 drive = [sender representedObject];
1285 if(drive == nil) {
1286 NSBeep();
1287 QEMU_Alert(@"Failed to find drive to eject!");
1288 return;
1289 }
1290
Peter Maydell31819e92019-02-25 10:24:27 +00001291 __block Error *err = NULL;
1292 with_iothread_lock(^{
1293 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1294 false, NULL, false, false, &err);
1295 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001296 handleAnyDeviceErrors(err);
1297}
1298
1299/* Displays a dialog box asking the user to select an image file to load.
1300 * Uses sender's represented object value to figure out which drive to use.
1301 */
1302- (void)changeDeviceMedia:(id)sender
1303{
1304 /* Find the drive name */
1305 NSString * drive;
1306 drive = [sender representedObject];
1307 if(drive == nil) {
1308 NSBeep();
1309 QEMU_Alert(@"Could not find drive!");
1310 return;
1311 }
1312
1313 /* Display the file open dialog */
1314 NSOpenPanel * openPanel;
1315 openPanel = [NSOpenPanel openPanel];
1316 [openPanel setCanChooseFiles: YES];
1317 [openPanel setAllowsMultipleSelection: NO];
1318 [openPanel setAllowedFileTypes: supportedImageFileTypes];
Peter Maydellb5725382018-05-29 19:15:23 +01001319 if([openPanel runModal] == NSModalResponseOK) {
John Arbuckle693a3e02015-06-19 10:53:27 +01001320 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1321 if(file == nil) {
1322 NSBeep();
1323 QEMU_Alert(@"Failed to convert URL to file path!");
1324 return;
1325 }
1326
Peter Maydell31819e92019-02-25 10:24:27 +00001327 __block Error *err = NULL;
1328 with_iothread_lock(^{
1329 qmp_blockdev_change_medium(true,
1330 [drive cStringUsingEncoding:
1331 NSASCIIStringEncoding],
1332 false, NULL,
1333 [file cStringUsingEncoding:
1334 NSASCIIStringEncoding],
1335 true, "raw",
1336 false, 0,
1337 &err);
1338 });
John Arbuckle693a3e02015-06-19 10:53:27 +01001339 handleAnyDeviceErrors(err);
1340 }
1341}
1342
John Arbuckled9bc14f2015-09-25 23:13:59 +01001343/* Verifies if the user really wants to quit */
1344- (BOOL)verifyQuit
1345{
1346 NSAlert *alert = [NSAlert new];
1347 [alert autorelease];
1348 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1349 [alert addButtonWithTitle: @"Cancel"];
1350 [alert addButtonWithTitle: @"Quit"];
1351 if([alert runModal] == NSAlertSecondButtonReturn) {
1352 return YES;
1353 } else {
1354 return NO;
1355 }
1356}
1357
Programmingkid9e8204b2016-08-15 22:11:06 -04001358/* The action method for the About menu item */
1359- (IBAction) do_about_menu_item: (id) sender
1360{
1361 [about_window makeKeyAndOrderFront: nil];
1362}
1363
1364/* Create and display the about dialog */
1365- (void)make_about_window
1366{
1367 /* Make the window */
1368 int x = 0, y = 0, about_width = 400, about_height = 200;
1369 NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1370 about_window = [[NSWindow alloc] initWithContentRect:window_rect
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001371 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1372 NSWindowStyleMaskMiniaturizable
Programmingkid9e8204b2016-08-15 22:11:06 -04001373 backing:NSBackingStoreBuffered
1374 defer:NO];
1375 [about_window setTitle: @"About"];
1376 [about_window setReleasedWhenClosed: NO];
1377 [about_window center];
1378 NSView *superView = [about_window contentView];
1379
1380 /* Create the dimensions of the picture */
1381 int picture_width = 80, picture_height = 80;
1382 x = (about_width - picture_width)/2;
1383 y = about_height - picture_height - 10;
1384 NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1385
1386 /* Get the path to the QEMU binary */
1387 NSString *binary_name = [NSString stringWithCString: gArgv[0]
1388 encoding: NSASCIIStringEncoding];
1389 binary_name = [binary_name lastPathComponent];
1390 NSString *program_path = [[NSString alloc] initWithFormat: @"%@/%@",
1391 [[NSBundle mainBundle] bundlePath], binary_name];
1392
1393 /* Make the picture of QEMU */
1394 NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1395 picture_rect];
1396 NSImage *qemu_image = [[NSWorkspace sharedWorkspace] iconForFile:
1397 program_path];
1398 [picture_view setImage: qemu_image];
1399 [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1400 [superView addSubview: picture_view];
1401
1402 /* Make the name label */
1403 x = 0;
1404 y = y - 25;
1405 int name_width = about_width, name_height = 20;
1406 NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1407 NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1408 [name_label setEditable: NO];
1409 [name_label setBezeled: NO];
1410 [name_label setDrawsBackground: NO];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001411 [name_label setAlignment: NSTextAlignmentCenter];
Programmingkid9e8204b2016-08-15 22:11:06 -04001412 NSString *qemu_name = [[NSString alloc] initWithCString: gArgv[0]
1413 encoding: NSASCIIStringEncoding];
1414 qemu_name = [qemu_name lastPathComponent];
1415 [name_label setStringValue: qemu_name];
1416 [superView addSubview: name_label];
1417
1418 /* Set the version label's attributes */
1419 x = 0;
1420 y = 50;
1421 int version_width = about_width, version_height = 20;
1422 NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1423 NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1424 version_rect];
1425 [version_label setEditable: NO];
1426 [version_label setBezeled: NO];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001427 [version_label setAlignment: NSTextAlignmentCenter];
Programmingkid9e8204b2016-08-15 22:11:06 -04001428 [version_label setDrawsBackground: NO];
1429
1430 /* Create the version string*/
1431 NSString *version_string;
1432 version_string = [[NSString alloc] initWithFormat:
Thomas Huth7e563bf2018-02-15 12:06:47 +01001433 @"QEMU emulator version %s", QEMU_FULL_VERSION];
Programmingkid9e8204b2016-08-15 22:11:06 -04001434 [version_label setStringValue: version_string];
1435 [superView addSubview: version_label];
1436
1437 /* Make copyright label */
1438 x = 0;
1439 y = 35;
1440 int copyright_width = about_width, copyright_height = 20;
1441 NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1442 NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1443 copyright_rect];
1444 [copyright_label setEditable: NO];
1445 [copyright_label setBezeled: NO];
1446 [copyright_label setDrawsBackground: NO];
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001447 [copyright_label setAlignment: NSTextAlignmentCenter];
Programmingkid9e8204b2016-08-15 22:11:06 -04001448 [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1449 QEMU_COPYRIGHT]];
1450 [superView addSubview: copyright_label];
1451}
1452
John Arbucklee47ec1a2017-06-13 23:17:38 -04001453/* Used by the Speed menu items */
1454- (void)adjustSpeed:(id)sender
1455{
1456 int throttle_pct; /* throttle percentage */
1457 NSMenu *menu;
1458
1459 menu = [sender menu];
1460 if (menu != nil)
1461 {
1462 /* Unselect the currently selected item */
1463 for (NSMenuItem *item in [menu itemArray]) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001464 if (item.state == NSControlStateValueOn) {
1465 [item setState: NSControlStateValueOff];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001466 break;
1467 }
1468 }
1469 }
1470
1471 // check the menu item
Brendan Shanks5e246002019-01-31 23:12:25 -08001472 [sender setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001473
1474 // get the throttle percentage
1475 throttle_pct = [sender tag];
1476
Peter Maydell31819e92019-02-25 10:24:27 +00001477 with_iothread_lock(^{
1478 cpu_throttle_set(throttle_pct);
1479 });
John Arbucklee47ec1a2017-06-13 23:17:38 -04001480 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1481}
1482
Programmingkidb4c6a112015-05-19 09:11:18 +01001483@end
bellard5b0753e2005-03-01 21:37:28 +00001484
Peter Maydell61a2ed42019-02-25 10:24:32 +00001485@interface QemuApplication : NSApplication
1486@end
1487
1488@implementation QemuApplication
1489- (void)sendEvent:(NSEvent *)event
1490{
1491 COCOA_DEBUG("QemuApplication: sendEvent\n");
Peter Maydell55888402019-02-25 10:24:33 +00001492 if (![cocoaView handleEvent:event]) {
1493 [super sendEvent: event];
1494 }
Peter Maydell61a2ed42019-02-25 10:24:32 +00001495}
1496@end
1497
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001498static void create_initial_menus(void)
1499{
thsc304f7e2008-01-22 23:25:15 +00001500 // Add menus
1501 NSMenu *menu;
1502 NSMenuItem *menuItem;
1503
bellard5b0753e2005-03-01 21:37:28 +00001504 [NSApp setMainMenu:[[NSMenu alloc] init]];
bellard5b0753e2005-03-01 21:37:28 +00001505
thsc304f7e2008-01-22 23:25:15 +00001506 // Application menu
1507 menu = [[NSMenu alloc] initWithTitle:@""];
Programmingkid9e8204b2016-08-15 22:11:06 -04001508 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
thsc304f7e2008-01-22 23:25:15 +00001509 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1510 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1511 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
Brendan Shanks4ba967a2017-04-24 23:29:52 -07001512 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
thsc304f7e2008-01-22 23:25:15 +00001513 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1514 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1515 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1516 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1517 [menuItem setSubmenu:menu];
1518 [[NSApp mainMenu] addItem:menuItem];
1519 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
ths3b46e622007-09-17 08:09:54 +00001520
John Arbuckle8524f1c2015-06-19 10:53:27 +01001521 // Machine menu
1522 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1523 [menu setAutoenablesItems: NO];
1524 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1525 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1526 [menu addItem: menuItem];
1527 [menuItem setEnabled: NO];
John Arbuckle27074612015-06-19 10:53:27 +01001528 [menu addItem: [NSMenuItem separatorItem]];
1529 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1530 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
John Arbuckle8524f1c2015-06-19 10:53:27 +01001531 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1532 [menuItem setSubmenu:menu];
1533 [[NSApp mainMenu] addItem:menuItem];
1534
thsc304f7e2008-01-22 23:25:15 +00001535 // View menu
1536 menu = [[NSMenu alloc] initWithTitle:@"View"];
Programmingkid5d1b2ee2015-05-19 09:11:17 +01001537 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1538 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
thsc304f7e2008-01-22 23:25:15 +00001539 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1540 [menuItem setSubmenu:menu];
1541 [[NSApp mainMenu] addItem:menuItem];
1542
John Arbucklee47ec1a2017-06-13 23:17:38 -04001543 // Speed menu
1544 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1545
1546 // Add the rest of the Speed menu items
1547 int p, percentage, throttle_pct;
1548 for (p = 10; p >= 0; p--)
1549 {
1550 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1551
1552 menuItem = [[[NSMenuItem alloc]
1553 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1554
1555 if (percentage == 100) {
Brendan Shanks5e246002019-01-31 23:12:25 -08001556 [menuItem setState: NSControlStateValueOn];
John Arbucklee47ec1a2017-06-13 23:17:38 -04001557 }
1558
1559 /* Calculate the throttle percentage */
1560 throttle_pct = -1 * percentage + 100;
1561
1562 [menuItem setTag: throttle_pct];
1563 [menu addItem: menuItem];
1564 }
1565 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1566 [menuItem setSubmenu:menu];
1567 [[NSApp mainMenu] addItem:menuItem];
1568
thsc304f7e2008-01-22 23:25:15 +00001569 // Window menu
1570 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1571 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1572 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1573 [menuItem setSubmenu:menu];
1574 [[NSApp mainMenu] addItem:menuItem];
1575 [NSApp setWindowsMenu:menu];
1576
1577 // Help menu
1578 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1579 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
thsc304f7e2008-01-22 23:25:15 +00001580 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1581 [menuItem setSubmenu:menu];
1582 [[NSApp mainMenu] addItem:menuItem];
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001583}
1584
Peter Maydell8b00e4e2019-02-25 10:24:30 +00001585/* Returns a name for a given console */
1586static NSString * getConsoleName(QemuConsole * console)
1587{
1588 return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1589}
1590
1591/* Add an entry to the View menu for each console */
1592static void add_console_menu_entries(void)
1593{
1594 NSMenu *menu;
1595 NSMenuItem *menuItem;
1596 int index = 0;
1597
1598 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1599
1600 [menu addItem:[NSMenuItem separatorItem]];
1601
1602 while (qemu_console_lookup_by_index(index) != NULL) {
1603 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1604 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1605 [menuItem setTag: index];
1606 [menu addItem: menuItem];
1607 index++;
1608 }
1609}
1610
1611/* Make menu items for all removable devices.
1612 * Each device is given an 'Eject' and 'Change' menu item.
1613 */
1614static void addRemovableDevicesMenuItems(void)
1615{
1616 NSMenu *menu;
1617 NSMenuItem *menuItem;
1618 BlockInfoList *currentDevice, *pointerToFree;
1619 NSString *deviceName;
1620
1621 currentDevice = qmp_query_block(NULL);
1622 pointerToFree = currentDevice;
1623 if(currentDevice == NULL) {
1624 NSBeep();
1625 QEMU_Alert(@"Failed to query for block devices!");
1626 return;
1627 }
1628
1629 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1630
1631 // Add a separator between related groups of menu items
1632 [menu addItem:[NSMenuItem separatorItem]];
1633
1634 // Set the attributes to the "Removable Media" menu item
1635 NSString *titleString = @"Removable Media";
1636 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1637 NSColor *newColor = [NSColor blackColor];
1638 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1639 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1640 traits:NSBoldFontMask|NSItalicFontMask
1641 weight:0
1642 size:14];
1643 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1644 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1645 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1646
1647 // Add the "Removable Media" menu item
1648 menuItem = [NSMenuItem new];
1649 [menuItem setAttributedTitle: attString];
1650 [menuItem setEnabled: NO];
1651 [menu addItem: menuItem];
1652
1653 /* Loop through all the block devices in the emulator */
1654 while (currentDevice) {
1655 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1656
1657 if(currentDevice->value->removable) {
1658 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1659 action: @selector(changeDeviceMedia:)
1660 keyEquivalent: @""];
1661 [menu addItem: menuItem];
1662 [menuItem setRepresentedObject: deviceName];
1663 [menuItem autorelease];
1664
1665 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1666 action: @selector(ejectDeviceMedia:)
1667 keyEquivalent: @""];
1668 [menu addItem: menuItem];
1669 [menuItem setRepresentedObject: deviceName];
1670 [menuItem autorelease];
1671 }
1672 currentDevice = currentDevice->next;
1673 }
1674 qapi_free_BlockInfoList(pointerToFree);
1675}
1676
Peter Maydell55888402019-02-25 10:24:33 +00001677/*
1678 * The startup process for the OSX/Cocoa UI is complicated, because
1679 * OSX insists that the UI runs on the initial main thread, and so we
1680 * need to start a second thread which runs the vl.c qemu_main():
1681 *
1682 * Initial thread: 2nd thread:
1683 * in main():
1684 * create qemu-main thread
1685 * wait on display_init semaphore
1686 * call qemu_main()
1687 * ...
1688 * in cocoa_display_init():
1689 * post the display_init semaphore
1690 * wait on app_started semaphore
1691 * create application, menus, etc
1692 * enter OSX run loop
1693 * in applicationDidFinishLaunching:
1694 * post app_started semaphore
1695 * tell main thread to fullscreen if needed
1696 * [...]
1697 * run qemu main-loop
1698 *
1699 * We do this in two stages so that we don't do the creation of the
1700 * GUI application menus and so on for command line options like --help
1701 * where we want to just print text to stdout and exit immediately.
1702 */
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001703
Peter Maydell55888402019-02-25 10:24:33 +00001704static void *call_qemu_main(void *opaque)
1705{
1706 int status;
1707
1708 COCOA_DEBUG("Second thread: calling qemu_main()\n");
1709 status = qemu_main(gArgc, gArgv, *_NSGetEnviron());
1710 COCOA_DEBUG("Second thread: qemu_main() returned, exiting\n");
1711 exit(status);
1712}
1713
1714int main (int argc, const char * argv[]) {
1715 QemuThread thread;
1716
1717 COCOA_DEBUG("Entered main()\n");
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001718 gArgc = argc;
1719 gArgv = (char **)argv;
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001720
Peter Maydell55888402019-02-25 10:24:33 +00001721 qemu_sem_init(&display_init_sem, 0);
1722 qemu_sem_init(&app_started_sem, 0);
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001723
Peter Maydell55888402019-02-25 10:24:33 +00001724 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1725 NULL, QEMU_THREAD_DETACHED);
1726
1727 COCOA_DEBUG("Main thread: waiting for display_init_sem\n");
1728 qemu_sem_wait(&display_init_sem);
1729 COCOA_DEBUG("Main thread: initializing app\n");
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001730
1731 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1732
1733 // Pull this console process up to being a fully-fledged graphical
1734 // app with a menubar and Dock icon
1735 ProcessSerialNumber psn = { 0, kCurrentProcess };
1736 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1737
Peter Maydell61a2ed42019-02-25 10:24:32 +00001738 [QemuApplication sharedApplication];
Peter Maydellc6fd6c72019-02-25 10:24:29 +00001739
1740 create_initial_menus();
thsc304f7e2008-01-22 23:25:15 +00001741
Peter Maydell55888402019-02-25 10:24:33 +00001742 /*
1743 * Create the menu entries which depend on QEMU state (for consoles
1744 * and removeable devices). These make calls back into QEMU functions,
1745 * which is OK because at this point we know that the second thread
1746 * holds the iothread lock and is synchronously waiting for us to
1747 * finish.
1748 */
1749 add_console_menu_entries();
1750 addRemovableDevicesMenuItems();
1751
thsc304f7e2008-01-22 23:25:15 +00001752 // Create an Application controller
1753 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1754 [NSApp setDelegate:appController];
1755
1756 // Start the main event loop
Peter Maydell55888402019-02-25 10:24:33 +00001757 COCOA_DEBUG("Main thread: entering OSX run loop\n");
bellard5b0753e2005-03-01 21:37:28 +00001758 [NSApp run];
Peter Maydell55888402019-02-25 10:24:33 +00001759 COCOA_DEBUG("Main thread: left OSX run loop, exiting\n");
ths3b46e622007-09-17 08:09:54 +00001760
thsc304f7e2008-01-22 23:25:15 +00001761 [appController release];
bellard5b0753e2005-03-01 21:37:28 +00001762 [pool release];
bellardcae41b12006-05-22 21:25:04 +00001763
bellard5b0753e2005-03-01 21:37:28 +00001764 return 0;
1765}
thsc304f7e2008-01-22 23:25:15 +00001766
1767
1768
1769#pragma mark qemu
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001770static void cocoa_update(DisplayChangeListener *dcl,
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001771 int x, int y, int w, int h)
thsc304f7e2008-01-22 23:25:15 +00001772{
Peter Maydell6e657e62013-04-22 10:29:46 +00001773 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1774
thsc304f7e2008-01-22 23:25:15 +00001775 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1776
Peter Maydell55888402019-02-25 10:24:33 +00001777 dispatch_async(dispatch_get_main_queue(), ^{
1778 NSRect rect;
1779 if ([cocoaView cdx] == 1.0) {
1780 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1781 } else {
1782 rect = NSMakeRect(
1783 x * [cocoaView cdx],
1784 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1785 w * [cocoaView cdx],
1786 h * [cocoaView cdy]);
1787 }
1788 [cocoaView setNeedsDisplayInRect:rect];
1789 });
Peter Maydell6e657e62013-04-22 10:29:46 +00001790
1791 [pool release];
thsc304f7e2008-01-22 23:25:15 +00001792}
1793
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01001794static void cocoa_switch(DisplayChangeListener *dcl,
Gerd Hoffmannc12aeb82013-02-28 15:03:04 +01001795 DisplaySurface *surface)
thsc304f7e2008-01-22 23:25:15 +00001796{
Peter Maydell6e657e62013-04-22 10:29:46 +00001797 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Peter Maydell55888402019-02-25 10:24:33 +00001798 pixman_image_t *image = surface->image;
thsc304f7e2008-01-22 23:25:15 +00001799
Peter Maydell6e657e62013-04-22 10:29:46 +00001800 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
Peter Maydell55888402019-02-25 10:24:33 +00001801
1802 // The DisplaySurface will be freed as soon as this callback returns.
1803 // We take a reference to the underlying pixman image here so it does
1804 // not disappear from under our feet; the switchSurface method will
1805 // deref the old image when it is done with it.
1806 pixman_image_ref(image);
1807
1808 dispatch_async(dispatch_get_main_queue(), ^{
1809 [cocoaView switchSurface:image];
1810 });
Peter Maydell6e657e62013-04-22 10:29:46 +00001811 [pool release];
thsc304f7e2008-01-22 23:25:15 +00001812}
1813
Gerd Hoffmannbc2ed972013-03-01 13:03:04 +01001814static void cocoa_refresh(DisplayChangeListener *dcl)
thsc304f7e2008-01-22 23:25:15 +00001815{
Peter Maydell6e657e62013-04-22 10:29:46 +00001816 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1817
thsc304f7e2008-01-22 23:25:15 +00001818 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
John Arbuckle468a8952015-10-13 21:51:18 +01001819 graphic_hw_update(NULL);
thsc304f7e2008-01-22 23:25:15 +00001820
Gerd Hoffmann21bae112013-12-04 14:08:04 +01001821 if (qemu_input_is_absolute()) {
Peter Maydell55888402019-02-25 10:24:33 +00001822 dispatch_async(dispatch_get_main_queue(), ^{
1823 if (![cocoaView isAbsoluteEnabled]) {
1824 if ([cocoaView isMouseGrabbed]) {
1825 [cocoaView ungrabMouse];
1826 }
thsc304f7e2008-01-22 23:25:15 +00001827 }
Peter Maydell55888402019-02-25 10:24:33 +00001828 [cocoaView setAbsoluteEnabled:YES];
1829 });
thsc304f7e2008-01-22 23:25:15 +00001830 }
Peter Maydell6e657e62013-04-22 10:29:46 +00001831 [pool release];
thsc304f7e2008-01-22 23:25:15 +00001832}
1833
1834static void cocoa_cleanup(void)
1835{
1836 COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
Blue Swirl58a06672011-08-21 18:42:08 +00001837 g_free(dcl);
thsc304f7e2008-01-22 23:25:15 +00001838}
1839
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001840static const DisplayChangeListenerOps dcl_ops = {
1841 .dpy_name = "cocoa",
Peter Maydell8510d912013-03-18 20:28:21 +00001842 .dpy_gfx_update = cocoa_update,
1843 .dpy_gfx_switch = cocoa_switch,
1844 .dpy_refresh = cocoa_refresh,
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001845};
1846
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01001847static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
thsc304f7e2008-01-22 23:25:15 +00001848{
1849 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1850
Peter Maydell55888402019-02-25 10:24:33 +00001851 /* Tell main thread to go ahead and create the app and enter the run loop */
1852 qemu_sem_post(&display_init_sem);
1853 qemu_sem_wait(&app_started_sem);
1854 COCOA_DEBUG("cocoa_display_init: app start completed\n");
1855
Programmingkid43227af2015-05-19 09:11:17 +01001856 /* if fullscreen mode is to be used */
Gerd Hoffmann767f9bf2018-02-02 12:10:19 +01001857 if (opts->has_full_screen && opts->full_screen) {
Peter Maydell55888402019-02-25 10:24:33 +00001858 dispatch_async(dispatch_get_main_queue(), ^{
1859 [NSApp activateIgnoringOtherApps: YES];
1860 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1861 });
Programmingkid43227af2015-05-19 09:11:17 +01001862 }
1863
Blue Swirl58a06672011-08-21 18:42:08 +00001864 dcl = g_malloc0(sizeof(DisplayChangeListener));
1865
aliguori9794f742009-03-04 19:25:22 +00001866 // register vga output callbacks
Gerd Hoffmann7c20b4a2012-11-13 14:51:41 +01001867 dcl->ops = &dcl_ops;
Gerd Hoffmann52090892013-04-23 15:44:31 +02001868 register_displaychangelistener(dcl);
thsc304f7e2008-01-22 23:25:15 +00001869
1870 // register cleanup function
1871 atexit(cocoa_cleanup);
1872}
Gerd Hoffmann5013b9e2018-03-01 11:05:37 +01001873
1874static QemuDisplay qemu_display_cocoa = {
1875 .type = DISPLAY_TYPE_COCOA,
1876 .init = cocoa_display_init,
1877};
1878
1879static void register_cocoa(void)
1880{
1881 qemu_display_register(&qemu_display_cocoa);
1882}
1883
1884type_init(register_cocoa);