]> git.proxmox.com Git - mirror_qemu.git/blame - ui/cocoa.m
Merge remote-tracking branch 'remotes/stsquad/tags/pull-testing-for-4.0-120319-1...
[mirror_qemu.git] / ui / cocoa.m
CommitLineData
5b0753e0 1/*
c304f7e2 2 * QEMU Cocoa CG display driver
5fafdf24 3 *
c304f7e2 4 * Copyright (c) 2008 Mike Kronenberg
5fafdf24 5 *
5b0753e0
FB
6 * 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 */
da4dbf74 24
e4a096b1
PM
25#include "qemu/osdep.h"
26
5b0753e0 27#import <Cocoa/Cocoa.h>
3bbbee18 28#include <crt_externs.h>
5b0753e0 29
87ecb68b 30#include "qemu-common.h"
28ecbaee 31#include "ui/console.h"
21bae11a 32#include "ui/input.h"
9c17d615 33#include "sysemu/sysemu.h"
e688df6b 34#include "qapi/error.h"
16bf5234
MA
35#include "qapi/qapi-commands-block.h"
36#include "qapi/qapi-commands-misc.h"
693a3e01 37#include "sysemu/blockdev.h"
9e8204b1 38#include "qemu-version.h"
aaac714f 39#include <Carbon/Carbon.h>
e47ec1a9 40#include "qom/cpu.h"
da4dbf74 41
44e4c0ba
AF
42#ifndef MAC_OS_X_VERSION_10_5
43#define MAC_OS_X_VERSION_10_5 1050
44#endif
2ba9de6e
PM
45#ifndef MAC_OS_X_VERSION_10_6
46#define MAC_OS_X_VERSION_10_6 1060
47#endif
b5725385
PM
48#ifndef MAC_OS_X_VERSION_10_9
49#define MAC_OS_X_VERSION_10_9 1090
50#endif
81801ae2
PM
51#ifndef MAC_OS_X_VERSION_10_10
52#define MAC_OS_X_VERSION_10_10 101000
53#endif
4ba967ad
BS
54#ifndef MAC_OS_X_VERSION_10_12
55#define MAC_OS_X_VERSION_10_12 101200
56#endif
5e24600a
BS
57#ifndef MAC_OS_X_VERSION_10_13
58#define MAC_OS_X_VERSION_10_13 101300
59#endif
44e4c0ba 60
4ba967ad
BS
61/* macOS 10.12 deprecated many constants, #define the new names for older SDKs */
62#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_12
63#define NSEventMaskAny NSAnyEventMask
af8862b2
IM
64#define NSEventModifierFlagCapsLock NSAlphaShiftKeyMask
65#define NSEventModifierFlagShift NSShiftKeyMask
4ba967ad
BS
66#define NSEventModifierFlagCommand NSCommandKeyMask
67#define NSEventModifierFlagControl NSControlKeyMask
68#define NSEventModifierFlagOption NSAlternateKeyMask
69#define NSEventTypeFlagsChanged NSFlagsChanged
70#define NSEventTypeKeyUp NSKeyUp
71#define NSEventTypeKeyDown NSKeyDown
72#define NSEventTypeMouseMoved NSMouseMoved
73#define NSEventTypeLeftMouseDown NSLeftMouseDown
74#define NSEventTypeRightMouseDown NSRightMouseDown
75#define NSEventTypeOtherMouseDown NSOtherMouseDown
76#define NSEventTypeLeftMouseDragged NSLeftMouseDragged
77#define NSEventTypeRightMouseDragged NSRightMouseDragged
78#define NSEventTypeOtherMouseDragged NSOtherMouseDragged
79#define NSEventTypeLeftMouseUp NSLeftMouseUp
80#define NSEventTypeRightMouseUp NSRightMouseUp
81#define NSEventTypeOtherMouseUp NSOtherMouseUp
82#define NSEventTypeScrollWheel NSScrollWheel
83#define NSTextAlignmentCenter NSCenterTextAlignment
84#define NSWindowStyleMaskBorderless NSBorderlessWindowMask
85#define NSWindowStyleMaskClosable NSClosableWindowMask
86#define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask
87#define NSWindowStyleMaskTitled NSTitledWindowMask
88#endif
b5725385
PM
89/* 10.13 deprecates NSFileHandlingPanelOKButton in favour of
90 * NSModalResponseOK, which was introduced in 10.9. Define
91 * it for older versions.
92 */
93#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_9
94#define NSModalResponseOK NSFileHandlingPanelOKButton
95#endif
5e24600a
BS
96/* 10.14 deprecates NSOnState and NSOffState in favor of
97 * NSControlStateValueOn/Off, which were introduced in 10.13.
98 * Define for older versions
99 */
100#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
101#define NSControlStateValueOn NSOnState
102#define NSControlStateValueOff NSOffState
103#endif
3b46e624 104
c304f7e2 105//#define DEBUG
3b46e624 106
c304f7e2
TS
107#ifdef DEBUG
108#define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
b29169d2 109#else
c304f7e2 110#define COCOA_DEBUG(...) ((void) 0)
b29169d2
BS
111#endif
112
c304f7e2 113#define cgrect(nsrect) (*(CGRect *)&(nsrect))
5b0753e0 114
c304f7e2
TS
115typedef struct {
116 int width;
117 int height;
118 int bitsPerComponent;
119 int bitsPerPixel;
120} QEMUScreen;
121
9e8204b1 122NSWindow *normalWindow, *about_window;
9794f74f 123static DisplayChangeListener *dcl;
21bae11a 124static int last_buttons;
c304f7e2
TS
125
126int gArgc;
127char **gArgv;
5d1b2eef 128bool stretch_video;
8524f1c7 129NSTextField *pauseLabel;
693a3e01 130NSArray * supportedImageFileTypes;
5b0753e0 131
5588840f
PM
132static QemuSemaphore display_init_sem;
133static QemuSemaphore app_started_sem;
134
60105d7a 135// Utility functions to run specified code block with iothread lock held
31819e95 136typedef void (^CodeBlock)(void);
60105d7a 137typedef bool (^BoolCodeBlock)(void);
31819e95
PM
138
139static void with_iothread_lock(CodeBlock block)
140{
141 bool locked = qemu_mutex_iothread_locked();
142 if (!locked) {
143 qemu_mutex_lock_iothread();
144 }
145 block();
146 if (!locked) {
147 qemu_mutex_unlock_iothread();
148 }
149}
150
60105d7a
PM
151static bool bool_with_iothread_lock(BoolCodeBlock block)
152{
153 bool locked = qemu_mutex_iothread_locked();
154 bool val;
155
156 if (!locked) {
157 qemu_mutex_lock_iothread();
158 }
159 val = block();
160 if (!locked) {
161 qemu_mutex_unlock_iothread();
162 }
163 return val;
164}
165
aaac714f
JA
166// Mac to QKeyCode conversion
167const int mac_to_qkeycode_map[] = {
168 [kVK_ANSI_A] = Q_KEY_CODE_A,
169 [kVK_ANSI_B] = Q_KEY_CODE_B,
170 [kVK_ANSI_C] = Q_KEY_CODE_C,
171 [kVK_ANSI_D] = Q_KEY_CODE_D,
172 [kVK_ANSI_E] = Q_KEY_CODE_E,
173 [kVK_ANSI_F] = Q_KEY_CODE_F,
174 [kVK_ANSI_G] = Q_KEY_CODE_G,
175 [kVK_ANSI_H] = Q_KEY_CODE_H,
176 [kVK_ANSI_I] = Q_KEY_CODE_I,
177 [kVK_ANSI_J] = Q_KEY_CODE_J,
178 [kVK_ANSI_K] = Q_KEY_CODE_K,
179 [kVK_ANSI_L] = Q_KEY_CODE_L,
180 [kVK_ANSI_M] = Q_KEY_CODE_M,
181 [kVK_ANSI_N] = Q_KEY_CODE_N,
182 [kVK_ANSI_O] = Q_KEY_CODE_O,
183 [kVK_ANSI_P] = Q_KEY_CODE_P,
184 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
185 [kVK_ANSI_R] = Q_KEY_CODE_R,
186 [kVK_ANSI_S] = Q_KEY_CODE_S,
187 [kVK_ANSI_T] = Q_KEY_CODE_T,
188 [kVK_ANSI_U] = Q_KEY_CODE_U,
189 [kVK_ANSI_V] = Q_KEY_CODE_V,
190 [kVK_ANSI_W] = Q_KEY_CODE_W,
191 [kVK_ANSI_X] = Q_KEY_CODE_X,
192 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
193 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
194
195 [kVK_ANSI_0] = Q_KEY_CODE_0,
196 [kVK_ANSI_1] = Q_KEY_CODE_1,
197 [kVK_ANSI_2] = Q_KEY_CODE_2,
198 [kVK_ANSI_3] = Q_KEY_CODE_3,
199 [kVK_ANSI_4] = Q_KEY_CODE_4,
200 [kVK_ANSI_5] = Q_KEY_CODE_5,
201 [kVK_ANSI_6] = Q_KEY_CODE_6,
202 [kVK_ANSI_7] = Q_KEY_CODE_7,
203 [kVK_ANSI_8] = Q_KEY_CODE_8,
204 [kVK_ANSI_9] = Q_KEY_CODE_9,
205
206 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
207 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
208 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
209 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
210 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
211 [kVK_Tab] = Q_KEY_CODE_TAB,
212 [kVK_Return] = Q_KEY_CODE_RET,
213 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
214 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
215 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
216 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
217 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
218 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
219 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
220 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
221 [kVK_Shift] = Q_KEY_CODE_SHIFT,
222 [kVK_RightShift] = Q_KEY_CODE_SHIFT_R,
223 [kVK_Control] = Q_KEY_CODE_CTRL,
224 [kVK_RightControl] = Q_KEY_CODE_CTRL_R,
225 [kVK_Option] = Q_KEY_CODE_ALT,
226 [kVK_RightOption] = Q_KEY_CODE_ALT_R,
227 [kVK_Command] = Q_KEY_CODE_META_L,
228 [0x36] = Q_KEY_CODE_META_R, /* There is no kVK_RightCommand */
229 [kVK_Space] = Q_KEY_CODE_SPC,
230
231 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
232 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
233 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
234 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
235 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
236 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
237 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
238 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
239 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
240 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
241 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
242 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
243 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
244 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
245 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
246 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
247 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
248 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
249
250 [kVK_UpArrow] = Q_KEY_CODE_UP,
251 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
252 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
253 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
254
255 [kVK_Help] = Q_KEY_CODE_INSERT,
256 [kVK_Home] = Q_KEY_CODE_HOME,
257 [kVK_PageUp] = Q_KEY_CODE_PGUP,
258 [kVK_PageDown] = Q_KEY_CODE_PGDN,
259 [kVK_End] = Q_KEY_CODE_END,
260 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
261
262 [kVK_Escape] = Q_KEY_CODE_ESC,
263
264 /* The Power key can't be used directly because the operating system uses
265 * it. This key can be emulated by using it in place of another key such as
266 * F1. Don't forget to disable the real key binding.
267 */
268 /* [kVK_F1] = Q_KEY_CODE_POWER, */
269
270 [kVK_F1] = Q_KEY_CODE_F1,
271 [kVK_F2] = Q_KEY_CODE_F2,
272 [kVK_F3] = Q_KEY_CODE_F3,
273 [kVK_F4] = Q_KEY_CODE_F4,
274 [kVK_F5] = Q_KEY_CODE_F5,
275 [kVK_F6] = Q_KEY_CODE_F6,
276 [kVK_F7] = Q_KEY_CODE_F7,
277 [kVK_F8] = Q_KEY_CODE_F8,
278 [kVK_F9] = Q_KEY_CODE_F9,
279 [kVK_F10] = Q_KEY_CODE_F10,
280 [kVK_F11] = Q_KEY_CODE_F11,
281 [kVK_F12] = Q_KEY_CODE_F12,
282 [kVK_F13] = Q_KEY_CODE_PRINT,
283 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
284 [kVK_F15] = Q_KEY_CODE_PAUSE,
285
286 /*
287 * The eject and volume keys can't be used here because they are handled at
288 * a lower level than what an Application can see.
289 */
5b0753e0
FB
290};
291
77047bb7 292static int cocoa_keycode_to_qemu(int keycode)
5b0753e0 293{
aaac714f 294 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
01cc4e6f 295 fprintf(stderr, "(cocoa) warning unknown keycode 0x%x\n", keycode);
5b0753e0
FB
296 return 0;
297 }
aaac714f 298 return mac_to_qkeycode_map[keycode];
5b0753e0
FB
299}
300
693a3e01
JA
301/* Displays an alert dialog box with the specified message */
302static void QEMU_Alert(NSString *message)
303{
304 NSAlert *alert;
305 alert = [NSAlert new];
306 [alert setMessageText: message];
307 [alert runModal];
308}
c304f7e2 309
693a3e01
JA
310/* Handles any errors that happen with a device transaction */
311static void handleAnyDeviceErrors(Error * err)
312{
313 if (err) {
314 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
315 encoding: NSASCIIStringEncoding]);
316 error_free(err);
317 }
318}
c304f7e2 319
5b0753e0
FB
320/*
321 ------------------------------------------------------
c304f7e2 322 QemuCocoaView
5b0753e0
FB
323 ------------------------------------------------------
324*/
c304f7e2 325@interface QemuCocoaView : NSView
5b0753e0 326{
c304f7e2
TS
327 QEMUScreen screen;
328 NSWindow *fullScreenWindow;
329 float cx,cy,cw,ch,cdx,cdy;
330 CGDataProviderRef dataProviderRef;
5588840f 331 pixman_image_t *pixman_image;
af8862b2 332 BOOL modifiers_state[256];
49b9bd4d 333 BOOL isMouseGrabbed;
c304f7e2
TS
334 BOOL isFullscreen;
335 BOOL isAbsoluteEnabled;
f61c387e 336 BOOL isMouseDeassociated;
c304f7e2 337}
72a3e316 338- (void) switchSurface:(pixman_image_t *)image;
c304f7e2
TS
339- (void) grabMouse;
340- (void) ungrabMouse;
341- (void) toggleFullScreen:(id)sender;
9c3a418e 342- (void) handleMonitorInput:(NSEvent *)event;
60105d7a
PM
343- (bool) handleEvent:(NSEvent *)event;
344- (bool) handleEventLocked:(NSEvent *)event;
c304f7e2 345- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
f61c387e
PM
346/* The state surrounding mouse grabbing is potentially confusing.
347 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
348 * pointing device an absolute-position one?"], but is only updated on
349 * next refresh.
350 * isMouseGrabbed tracks whether GUI events are directed to the guest;
351 * it controls whether special keys like Cmd get sent to the guest,
352 * and whether we capture the mouse when in non-absolute mode.
353 * isMouseDeassociated tracks whether we've told MacOSX to disassociate
354 * the mouse and mouse cursor position by calling
355 * CGAssociateMouseAndMouseCursorPosition(FALSE)
356 * (which basically happens if we grab in non-absolute mode).
357 */
49b9bd4d 358- (BOOL) isMouseGrabbed;
c304f7e2 359- (BOOL) isAbsoluteEnabled;
f61c387e 360- (BOOL) isMouseDeassociated;
c304f7e2
TS
361- (float) cdx;
362- (float) cdy;
363- (QEMUScreen) gscreen;
3b178b71 364- (void) raiseAllKeys;
c304f7e2 365@end
3b46e624 366
7fee199c
AF
367QemuCocoaView *cocoaView;
368
c304f7e2
TS
369@implementation QemuCocoaView
370- (id)initWithFrame:(NSRect)frameRect
371{
372 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
3b46e624 373
c304f7e2
TS
374 self = [super initWithFrame:frameRect];
375 if (self) {
3b46e624 376
c304f7e2
TS
377 screen.bitsPerComponent = 8;
378 screen.bitsPerPixel = 32;
379 screen.width = frameRect.size.width;
380 screen.height = frameRect.size.height;
3b46e624 381
c304f7e2
TS
382 }
383 return self;
384}
3b46e624 385
c304f7e2
TS
386- (void) dealloc
387{
388 COCOA_DEBUG("QemuCocoaView: dealloc\n");
3b46e624 389
5588840f 390 if (dataProviderRef) {
c304f7e2 391 CGDataProviderRelease(dataProviderRef);
5588840f
PM
392 pixman_image_unref(pixman_image);
393 }
3b46e624 394
c304f7e2
TS
395 [super dealloc];
396}
3b46e624 397
d50f71dc
AF
398- (BOOL) isOpaque
399{
400 return YES;
401}
402
5dd45bee
PM
403- (BOOL) screenContainsPoint:(NSPoint) p
404{
405 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
406}
407
13aefd30
PM
408- (void) hideCursor
409{
410 if (!cursor_hide) {
411 return;
412 }
413 [NSCursor hide];
414}
415
416- (void) unhideCursor
417{
418 if (!cursor_hide) {
419 return;
420 }
421 [NSCursor unhide];
422}
423
c304f7e2
TS
424- (void) drawRect:(NSRect) rect
425{
426 COCOA_DEBUG("QemuCocoaView: drawRect\n");
427
c304f7e2 428 // get CoreGraphic context
5e24600a 429#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10
c304f7e2 430 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] graphicsPort];
5e24600a
BS
431#else
432 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
433#endif
434
c304f7e2
TS
435 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
436 CGContextSetShouldAntialias (viewContextRef, NO);
437
438 // draw screen bitmap directly to Core Graphics context
7d270b1c
PM
439 if (!dataProviderRef) {
440 // Draw request before any guest device has set up a framebuffer:
441 // just draw an opaque black rectangle
442 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
443 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
444 } else {
c304f7e2
TS
445 CGImageRef imageRef = CGImageCreate(
446 screen.width, //width
447 screen.height, //height
448 screen.bitsPerComponent, //bitsPerComponent
449 screen.bitsPerPixel, //bitsPerPixel
9794f74f 450 (screen.width * (screen.bitsPerComponent/2)), //bytesPerRow
04afa4a8 451#ifdef __LITTLE_ENDIAN__
c304f7e2 452 CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
9794f74f 453 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
c304f7e2
TS
454#else
455 CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
456 kCGImageAlphaNoneSkipFirst, //bitmapInfo
457#endif
458 dataProviderRef, //provider
459 NULL, //decode
460 0, //interpolate
461 kCGRenderingIntentDefault //intent
462 );
b63901d8
PM
463 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
464 const NSRect *rectList;
b63901d8 465 NSInteger rectCount;
b63901d8
PM
466 int i;
467 CGImageRef clipImageRef;
468 CGRect clipRect;
469
470 [self getRectsBeingDrawn:&rectList count:&rectCount];
471 for (i = 0; i < rectCount; i++) {
472 clipRect.origin.x = rectList[i].origin.x / cdx;
473 clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
474 clipRect.size.width = rectList[i].size.width / cdx;
475 clipRect.size.height = rectList[i].size.height / cdy;
476 clipImageRef = CGImageCreateWithImageInRect(
477 imageRef,
478 clipRect
479 );
480 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
481 CGImageRelease (clipImageRef);
5b0753e0 482 }
c304f7e2
TS
483 CGImageRelease (imageRef);
484 }
5b0753e0
FB
485}
486
c304f7e2 487- (void) setContentDimensions
5b0753e0 488{
c304f7e2
TS
489 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
490
491 if (isFullscreen) {
492 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
493 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
5d1b2eef
JA
494
495 /* stretches video, but keeps same aspect ratio */
496 if (stretch_video == true) {
497 /* use smallest stretch value - prevents clipping on sides */
498 if (MIN(cdx, cdy) == cdx) {
499 cdy = cdx;
500 } else {
501 cdx = cdy;
502 }
503 } else { /* No stretching */
504 cdx = cdy = 1;
505 }
c304f7e2
TS
506 cw = screen.width * cdx;
507 ch = screen.height * cdy;
508 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
509 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
510 } else {
511 cx = 0;
512 cy = 0;
513 cw = screen.width;
514 ch = screen.height;
515 cdx = 1.0;
516 cdy = 1.0;
517 }
5b0753e0
FB
518}
519
72a3e316 520- (void) switchSurface:(pixman_image_t *)image
5b0753e0 521{
5e00d3ac 522 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
c304f7e2 523
72a3e316
PM
524 int w = pixman_image_get_width(image);
525 int h = pixman_image_get_height(image);
526 pixman_format_code_t image_format = pixman_image_get_format(image);
381600da
PM
527 /* cdx == 0 means this is our very first surface, in which case we need
528 * to recalculate the content dimensions even if it happens to be the size
529 * of the initial empty window.
530 */
531 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
d3345a04
PM
532
533 int oldh = screen.height;
534 if (isResize) {
535 // Resize before we trigger the redraw, or we'll redraw at the wrong size
536 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
537 screen.width = w;
538 screen.height = h;
539 [self setContentDimensions];
540 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
541 }
8510d91e 542
c304f7e2 543 // update screenBuffer
5588840f 544 if (dataProviderRef) {
c304f7e2 545 CGDataProviderRelease(dataProviderRef);
5588840f
PM
546 pixman_image_unref(pixman_image);
547 }
3b46e624 548
9794f74f 549 //sync host window color space with guests
72a3e316
PM
550 screen.bitsPerPixel = PIXMAN_FORMAT_BPP(image_format);
551 screen.bitsPerComponent = DIV_ROUND_UP(screen.bitsPerPixel, 8) * 2;
9794f74f 552
5588840f 553 pixman_image = image;
72a3e316 554 dataProviderRef = CGDataProviderCreateWithData(NULL, pixman_image_get_data(image), w * 4 * h, NULL);
3b46e624 555
c304f7e2
TS
556 // update windows
557 if (isFullscreen) {
558 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
d3345a04 559 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
c304f7e2
TS
560 } else {
561 if (qemu_name)
562 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
d3345a04
PM
563 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
564 }
565
566 if (isResize) {
567 [normalWindow center];
c304f7e2 568 }
5b0753e0
FB
569}
570
c304f7e2
TS
571- (void) toggleFullScreen:(id)sender
572{
573 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
574
575 if (isFullscreen) { // switch from fullscreen to desktop
576 isFullscreen = FALSE;
577 [self ungrabMouse];
578 [self setContentDimensions];
c304f7e2
TS
579 if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
580 [self exitFullScreenModeWithOptions:nil];
581 } else {
c304f7e2
TS
582 [fullScreenWindow close];
583 [normalWindow setContentView: self];
584 [normalWindow makeKeyAndOrderFront: self];
585 [NSMenu setMenuBarVisible:YES];
c304f7e2 586 }
c304f7e2
TS
587 } else { // switch from desktop to fullscreen
588 isFullscreen = TRUE;
5d1b2eef 589 [normalWindow orderOut: nil]; /* Hide the window */
c304f7e2
TS
590 [self grabMouse];
591 [self setContentDimensions];
c304f7e2
TS
592 if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
593 [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
594 [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
595 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
596 nil]];
597 } else {
c304f7e2
TS
598 [NSMenu setMenuBarVisible:NO];
599 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
4ba967ad 600 styleMask:NSWindowStyleMaskBorderless
c304f7e2
TS
601 backing:NSBackingStoreBuffered
602 defer:NO];
5d1b2eef 603 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
c304f7e2 604 [fullScreenWindow setHasShadow:NO];
5d1b2eef
JA
605 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
606 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
607 [[fullScreenWindow contentView] addSubview: self];
c304f7e2 608 [fullScreenWindow makeKeyAndOrderFront:self];
c304f7e2 609 }
c304f7e2
TS
610 }
611}
5b0753e0 612
af8862b2
IM
613- (void) toggleModifier: (int)keycode {
614 // Toggle the stored state.
615 modifiers_state[keycode] = !modifiers_state[keycode];
616 // Send a keyup or keydown depending on the state.
617 qemu_input_event_send_key_qcode(dcl->con, keycode, modifiers_state[keycode]);
618}
619
620- (void) toggleStatefulModifier: (int)keycode {
621 // Toggle the stored state.
622 modifiers_state[keycode] = !modifiers_state[keycode];
623 // Generate keydown and keyup.
624 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
625 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
626}
627
9c3a418e
JA
628// Does the work of sending input to the monitor
629- (void) handleMonitorInput:(NSEvent *)event
630{
631 int keysym = 0;
632 int control_key = 0;
633
634 // if the control key is down
635 if ([event modifierFlags] & NSEventModifierFlagControl) {
636 control_key = 1;
637 }
638
639 /* translates Macintosh keycodes to QEMU's keysym */
640
641 int without_control_translation[] = {
642 [0 ... 0xff] = 0, // invalid key
643
644 [kVK_UpArrow] = QEMU_KEY_UP,
645 [kVK_DownArrow] = QEMU_KEY_DOWN,
646 [kVK_RightArrow] = QEMU_KEY_RIGHT,
647 [kVK_LeftArrow] = QEMU_KEY_LEFT,
648 [kVK_Home] = QEMU_KEY_HOME,
649 [kVK_End] = QEMU_KEY_END,
650 [kVK_PageUp] = QEMU_KEY_PAGEUP,
651 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
652 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
653 [kVK_Delete] = QEMU_KEY_BACKSPACE,
654 };
655
656 int with_control_translation[] = {
657 [0 ... 0xff] = 0, // invalid key
658
659 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
660 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
661 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
662 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
663 [kVK_Home] = QEMU_KEY_CTRL_HOME,
664 [kVK_End] = QEMU_KEY_CTRL_END,
665 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
666 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
667 };
668
669 if (control_key != 0) { /* If the control key is being used */
670 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
671 keysym = with_control_translation[[event keyCode]];
672 }
673 } else {
674 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
675 keysym = without_control_translation[[event keyCode]];
676 }
677 }
678
679 // if not a key that needs translating
680 if (keysym == 0) {
681 NSString *ks = [event characters];
682 if ([ks length] > 0) {
683 keysym = [ks characterAtIndex:0];
684 }
685 }
686
687 if (keysym) {
688 kbd_put_keysym(keysym);
689 }
690}
691
60105d7a 692- (bool) handleEvent:(NSEvent *)event
3b46e624 693{
60105d7a
PM
694 return bool_with_iothread_lock(^{
695 return [self handleEventLocked:event];
31819e95
PM
696 });
697}
c304f7e2 698
60105d7a 699- (bool) handleEventLocked:(NSEvent *)event
31819e95 700{
60105d7a 701 /* Return true if we handled the event, false if it should be given to OSX */
31819e95 702 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
c304f7e2 703 int buttons = 0;
af8862b2 704 int keycode = 0;
21bae11a 705 bool mouse_event = false;
0c6c4395 706 static bool switched_to_fullscreen = false;
c304f7e2
TS
707 NSPoint p = [event locationInWindow];
708
709 switch ([event type]) {
4ba967ad 710 case NSEventTypeFlagsChanged:
af8862b2
IM
711 if ([event keyCode] == 0) {
712 // When the Cocoa keyCode is zero that means keys should be
713 // synthesized based on the values in in the eventModifiers
714 // bitmask.
715
716 if (qemu_console_is_graphic(NULL)) {
e7206249 717 NSUInteger modifiers = [event modifierFlags];
af8862b2
IM
718
719 if (!!(modifiers & NSEventModifierFlagCapsLock) != !!modifiers_state[Q_KEY_CODE_CAPS_LOCK]) {
720 [self toggleStatefulModifier:Q_KEY_CODE_CAPS_LOCK];
721 }
722 if (!!(modifiers & NSEventModifierFlagShift) != !!modifiers_state[Q_KEY_CODE_SHIFT]) {
723 [self toggleModifier:Q_KEY_CODE_SHIFT];
724 }
725 if (!!(modifiers & NSEventModifierFlagControl) != !!modifiers_state[Q_KEY_CODE_CTRL]) {
726 [self toggleModifier:Q_KEY_CODE_CTRL];
727 }
728 if (!!(modifiers & NSEventModifierFlagOption) != !!modifiers_state[Q_KEY_CODE_ALT]) {
729 [self toggleModifier:Q_KEY_CODE_ALT];
730 }
731 if (!!(modifiers & NSEventModifierFlagCommand) != !!modifiers_state[Q_KEY_CODE_META_L]) {
732 [self toggleModifier:Q_KEY_CODE_META_L];
733 }
734 }
735 } else {
736 keycode = cocoa_keycode_to_qemu([event keyCode]);
737 }
8895919a 738
aaac714f
JA
739 if ((keycode == Q_KEY_CODE_META_L || keycode == Q_KEY_CODE_META_R)
740 && !isMouseGrabbed) {
8895919a
PM
741 /* Don't pass command key changes to guest unless mouse is grabbed */
742 keycode = 0;
743 }
744
c304f7e2 745 if (keycode) {
aaac714f
JA
746 // emulate caps lock and num lock keydown and keyup
747 if (keycode == Q_KEY_CODE_CAPS_LOCK ||
748 keycode == Q_KEY_CODE_NUM_LOCK) {
af8862b2 749 [self toggleStatefulModifier:keycode];
68c0aa6e 750 } else if (qemu_console_is_graphic(NULL)) {
0c6c4395
JA
751 if (switched_to_fullscreen) {
752 switched_to_fullscreen = false;
753 } else {
754 [self toggleModifier:keycode];
755 }
c304f7e2
TS
756 }
757 }
3b46e624 758
c304f7e2 759 break;
4ba967ad 760 case NSEventTypeKeyDown:
8895919a 761 keycode = cocoa_keycode_to_qemu([event keyCode]);
3b46e624 762
8895919a 763 // forward command key combos to the host UI unless the mouse is grabbed
4ba967ad 764 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
0c6c4395
JA
765 /*
766 * Prevent the command key from being stuck down in the guest
767 * when using Command-F to switch to full screen mode.
768 */
769 if (keycode == Q_KEY_CODE_F) {
770 switched_to_fullscreen = true;
771 }
60105d7a 772 return false;
c304f7e2 773 }
3b46e624 774
c304f7e2 775 // default
c304f7e2 776
5929e36c 777 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
4ba967ad 778 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
5929e36c
JA
779 NSString *keychar = [event charactersIgnoringModifiers];
780 if ([keychar length] == 1) {
781 char key = [keychar characterAtIndex:0];
782 switch (key) {
783
784 // enable graphic console
785 case '1' ... '9':
786 console_select(key - '0' - 1); /* ascii math */
60105d7a 787 return true;
5929e36c
JA
788
789 // release the mouse grab
790 case 'g':
791 [self ungrabMouse];
60105d7a 792 return true;
5929e36c 793 }
c304f7e2 794 }
ef2088f9 795 }
c304f7e2 796
ef2088f9 797 if (qemu_console_is_graphic(NULL)) {
aaac714f 798 qemu_input_event_send_key_qcode(dcl->con, keycode, true);
c304f7e2 799 } else {
9c3a418e 800 [self handleMonitorInput: event];
c304f7e2
TS
801 }
802 break;
4ba967ad 803 case NSEventTypeKeyUp:
c304f7e2 804 keycode = cocoa_keycode_to_qemu([event keyCode]);
8895919a
PM
805
806 // don't pass the guest a spurious key-up if we treated this
807 // command-key combo as a host UI action
4ba967ad 808 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
60105d7a 809 return true;
8895919a
PM
810 }
811
68c0aa6e 812 if (qemu_console_is_graphic(NULL)) {
aaac714f 813 qemu_input_event_send_key_qcode(dcl->con, keycode, false);
c304f7e2
TS
814 }
815 break;
4ba967ad 816 case NSEventTypeMouseMoved:
c304f7e2 817 if (isAbsoluteEnabled) {
5dd45bee 818 if (![self screenContainsPoint:p] || ![[self window] isKeyWindow]) {
f61c387e
PM
819 if (isMouseGrabbed) {
820 [self ungrabMouse];
c304f7e2
TS
821 }
822 } else {
f61c387e
PM
823 if (!isMouseGrabbed) {
824 [self grabMouse];
c304f7e2
TS
825 }
826 }
5b0753e0 827 }
21bae11a 828 mouse_event = true;
c304f7e2 829 break;
4ba967ad
BS
830 case NSEventTypeLeftMouseDown:
831 if ([event modifierFlags] & NSEventModifierFlagCommand) {
c304f7e2
TS
832 buttons |= MOUSE_EVENT_RBUTTON;
833 } else {
834 buttons |= MOUSE_EVENT_LBUTTON;
835 }
21bae11a 836 mouse_event = true;
c304f7e2 837 break;
4ba967ad 838 case NSEventTypeRightMouseDown:
c304f7e2 839 buttons |= MOUSE_EVENT_RBUTTON;
21bae11a 840 mouse_event = true;
c304f7e2 841 break;
4ba967ad 842 case NSEventTypeOtherMouseDown:
c304f7e2 843 buttons |= MOUSE_EVENT_MBUTTON;
21bae11a 844 mouse_event = true;
c304f7e2 845 break;
4ba967ad
BS
846 case NSEventTypeLeftMouseDragged:
847 if ([event modifierFlags] & NSEventModifierFlagCommand) {
c304f7e2
TS
848 buttons |= MOUSE_EVENT_RBUTTON;
849 } else {
850 buttons |= MOUSE_EVENT_LBUTTON;
851 }
21bae11a 852 mouse_event = true;
c304f7e2 853 break;
4ba967ad 854 case NSEventTypeRightMouseDragged:
c304f7e2 855 buttons |= MOUSE_EVENT_RBUTTON;
21bae11a 856 mouse_event = true;
c304f7e2 857 break;
4ba967ad 858 case NSEventTypeOtherMouseDragged:
c304f7e2 859 buttons |= MOUSE_EVENT_MBUTTON;
21bae11a 860 mouse_event = true;
c304f7e2 861 break;
4ba967ad 862 case NSEventTypeLeftMouseUp:
f61c387e
PM
863 mouse_event = true;
864 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
9e8204b1
JA
865 if([[self window] isKeyWindow]) {
866 [self grabMouse];
867 }
c304f7e2
TS
868 }
869 break;
4ba967ad 870 case NSEventTypeRightMouseUp:
21bae11a 871 mouse_event = true;
c304f7e2 872 break;
4ba967ad 873 case NSEventTypeOtherMouseUp:
21bae11a 874 mouse_event = true;
c304f7e2 875 break;
4ba967ad 876 case NSEventTypeScrollWheel:
ae7313e7
JA
877 /*
878 * Send wheel events to the guest regardless of window focus.
879 * This is in-line with standard Mac OS X UI behaviour.
880 */
881
dc3c89d6
JA
882 /*
883 * When deltaY is zero, it means that this scrolling event was
884 * either horizontal, or so fine that it only appears in
885 * scrollingDeltaY. So we drop the event.
886 */
887 if ([event deltaY] != 0) {
ae7313e7 888 /* Determine if this is a scroll up or scroll down event */
dc3c89d6
JA
889 buttons = ([event deltaY] > 0) ?
890 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
891 qemu_input_queue_btn(dcl->con, buttons, true);
892 qemu_input_event_sync();
893 qemu_input_queue_btn(dcl->con, buttons, false);
894 qemu_input_event_sync();
895 }
ae7313e7
JA
896 /*
897 * Since deltaY also reports scroll wheel events we prevent mouse
898 * movement code from executing.
899 */
900 mouse_event = false;
c304f7e2
TS
901 break;
902 default:
60105d7a 903 return false;
5b0753e0 904 }
21bae11a
GH
905
906 if (mouse_event) {
8d3a5d9b
PM
907 /* Don't send button events to the guest unless we've got a
908 * mouse grab or window focus. If we have neither then this event
909 * is the user clicking on the background window to activate and
910 * bring us to the front, which will be done by the sendEvent
911 * call below. We definitely don't want to pass that click through
912 * to the guest.
913 */
914 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
915 (last_buttons != buttons)) {
7fb1cf16 916 static uint32_t bmap[INPUT_BUTTON__MAX] = {
21bae11a
GH
917 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
918 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
ae7313e7 919 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
21bae11a
GH
920 };
921 qemu_input_update_buttons(dcl->con, bmap, last_buttons, buttons);
922 last_buttons = buttons;
923 }
f61c387e
PM
924 if (isMouseGrabbed) {
925 if (isAbsoluteEnabled) {
926 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
927 * The check on screenContainsPoint is to avoid sending out of range values for
928 * clicks in the titlebar.
929 */
930 if ([self screenContainsPoint:p]) {
9cfa7ab9
PV
931 qemu_input_queue_abs(dcl->con, INPUT_AXIS_X, p.x, 0, screen.width);
932 qemu_input_queue_abs(dcl->con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
f61c387e
PM
933 }
934 } else {
935 qemu_input_queue_rel(dcl->con, INPUT_AXIS_X, (int)[event deltaX]);
936 qemu_input_queue_rel(dcl->con, INPUT_AXIS_Y, (int)[event deltaY]);
937 }
21bae11a 938 } else {
60105d7a 939 return false;
21bae11a
GH
940 }
941 qemu_input_event_sync();
942 }
60105d7a 943 return true;
5b0753e0
FB
944}
945
c304f7e2 946- (void) grabMouse
5b0753e0 947{
c304f7e2 948 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
3b46e624 949
c304f7e2
TS
950 if (!isFullscreen) {
951 if (qemu_name)
5929e36c 952 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
c304f7e2 953 else
5929e36c 954 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
c304f7e2 955 }
13aefd30 956 [self hideCursor];
f61c387e
PM
957 if (!isAbsoluteEnabled) {
958 isMouseDeassociated = TRUE;
959 CGAssociateMouseAndMouseCursorPosition(FALSE);
960 }
49b9bd4d 961 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
5b0753e0 962}
3b46e624 963
c304f7e2
TS
964- (void) ungrabMouse
965{
966 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
3b46e624 967
c304f7e2
TS
968 if (!isFullscreen) {
969 if (qemu_name)
970 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
971 else
972 [normalWindow setTitle:@"QEMU"];
973 }
13aefd30 974 [self unhideCursor];
f61c387e
PM
975 if (isMouseDeassociated) {
976 CGAssociateMouseAndMouseCursorPosition(TRUE);
977 isMouseDeassociated = FALSE;
978 }
49b9bd4d 979 isMouseGrabbed = FALSE;
5b0753e0
FB
980}
981
c304f7e2 982- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
49b9bd4d 983- (BOOL) isMouseGrabbed {return isMouseGrabbed;}
c304f7e2 984- (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
f61c387e 985- (BOOL) isMouseDeassociated {return isMouseDeassociated;}
c304f7e2
TS
986- (float) cdx {return cdx;}
987- (float) cdy {return cdy;}
988- (QEMUScreen) gscreen {return screen;}
3b178b71
JA
989
990/*
991 * Makes the target think all down keys are being released.
992 * This prevents a stuck key problem, since we will not see
993 * key up events for those keys after we have lost focus.
994 */
995- (void) raiseAllKeys
996{
3b178b71
JA
997 const int max_index = ARRAY_SIZE(modifiers_state);
998
31819e95
PM
999 with_iothread_lock(^{
1000 int index;
1001
1002 for (index = 0; index < max_index; index++) {
1003 if (modifiers_state[index]) {
1004 modifiers_state[index] = 0;
1005 qemu_input_event_send_key_qcode(dcl->con, index, false);
1006 }
1007 }
1008 });
3b178b71 1009}
5b0753e0
FB
1010@end
1011
1012
c304f7e2 1013
5b0753e0
FB
1014/*
1015 ------------------------------------------------------
c304f7e2 1016 QemuCocoaAppController
5b0753e0
FB
1017 ------------------------------------------------------
1018*/
c304f7e2 1019@interface QemuCocoaAppController : NSObject
2a4c8c53 1020#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
d9bc14f6 1021 <NSWindowDelegate, NSApplicationDelegate>
2a4c8c53 1022#endif
5b0753e0
FB
1023{
1024}
5d1b2eef 1025- (void)doToggleFullScreen:(id)sender;
c304f7e2
TS
1026- (void)toggleFullScreen:(id)sender;
1027- (void)showQEMUDoc:(id)sender;
5d1b2eef 1028- (void)zoomToFit:(id) sender;
b4c6a112 1029- (void)displayConsole:(id)sender;
8524f1c7
JA
1030- (void)pauseQEMU:(id)sender;
1031- (void)resumeQEMU:(id)sender;
1032- (void)displayPause;
1033- (void)removePause;
27074614
JA
1034- (void)restartQEMU:(id)sender;
1035- (void)powerDownQEMU:(id)sender;
693a3e01
JA
1036- (void)ejectDeviceMedia:(id)sender;
1037- (void)changeDeviceMedia:(id)sender;
d9bc14f6 1038- (BOOL)verifyQuit;
f4747900 1039- (void)openDocumentation:(NSString *)filename;
9e8204b1
JA
1040- (IBAction) do_about_menu_item: (id) sender;
1041- (void)make_about_window;
e47ec1a9 1042- (void)adjustSpeed:(id)sender;
5b0753e0
FB
1043@end
1044
c304f7e2
TS
1045@implementation QemuCocoaAppController
1046- (id) init
5b0753e0 1047{
c304f7e2 1048 COCOA_DEBUG("QemuCocoaAppController: init\n");
5a246934 1049
c304f7e2
TS
1050 self = [super init];
1051 if (self) {
5a246934 1052
c304f7e2
TS
1053 // create a view and add it to the window
1054 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1055 if(!cocoaView) {
1056 fprintf(stderr, "(cocoa) can't create a view\n");
1057 exit(1);
1058 }
3b46e624 1059
c304f7e2
TS
1060 // create a window
1061 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
4ba967ad 1062 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
c304f7e2
TS
1063 backing:NSBackingStoreBuffered defer:NO];
1064 if(!normalWindow) {
1065 fprintf(stderr, "(cocoa) can't create window\n");
1066 exit(1);
1067 }
1068 [normalWindow setAcceptsMouseMovedEvents:YES];
a1dbc05a 1069 [normalWindow setTitle:@"QEMU"];
c304f7e2 1070 [normalWindow setContentView:cocoaView];
81801ae2 1071#if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10)
561ef251 1072 [normalWindow useOptimizedDrawing:YES];
81801ae2 1073#endif
c304f7e2 1074 [normalWindow makeKeyAndOrderFront:self];
49060c29 1075 [normalWindow center];
d9bc14f6 1076 [normalWindow setDelegate: self];
5d1b2eef 1077 stretch_video = false;
8524f1c7
JA
1078
1079 /* Used for displaying pause on the screen */
1080 pauseLabel = [NSTextField new];
1081 [pauseLabel setBezeled:YES];
1082 [pauseLabel setDrawsBackground:YES];
1083 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1084 [pauseLabel setEditable:NO];
1085 [pauseLabel setSelectable:NO];
1086 [pauseLabel setStringValue: @"Paused"];
1087 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1088 [pauseLabel setTextColor: [NSColor blackColor]];
1089 [pauseLabel sizeToFit];
693a3e01
JA
1090
1091 // set the supported image file types that can be opened
1092 supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
9d227f19 1093 @"qcow", @"qcow2", @"cloop", @"vmdk", @"cdr",
5f26fcfb 1094 @"toast", nil];
9e8204b1 1095 [self make_about_window];
c304f7e2
TS
1096 }
1097 return self;
1098}
3b46e624 1099
c304f7e2
TS
1100- (void) dealloc
1101{
1102 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1103
1104 if (cocoaView)
1105 [cocoaView release];
1106 [super dealloc];
1107}
3b46e624 1108
c304f7e2
TS
1109- (void)applicationDidFinishLaunching: (NSNotification *) note
1110{
1111 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
5588840f
PM
1112 /* Tell cocoa_display_init to proceed */
1113 qemu_sem_post(&app_started_sem);
5b0753e0
FB
1114}
1115
1116- (void)applicationWillTerminate:(NSNotification *)aNotification
1117{
c304f7e2
TS
1118 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1119
cf83f140 1120 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
5b0753e0
FB
1121 exit(0);
1122}
1123
41ea49b3
AF
1124- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1125{
1126 return YES;
1127}
1128
d9bc14f6
JA
1129- (NSApplicationTerminateReply)applicationShouldTerminate:
1130 (NSApplication *)sender
1131{
1132 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1133 return [self verifyQuit];
1134}
1135
1136/* Called when the user clicks on a window's close button */
1137- (BOOL)windowShouldClose:(id)sender
1138{
1139 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1140 [NSApp terminate: sender];
1141 /* If the user allows the application to quit then the call to
1142 * NSApp terminate will never return. If we get here then the user
1143 * cancelled the quit, so we should return NO to not permit the
1144 * closing of this window.
1145 */
1146 return NO;
1147}
1148
3b178b71
JA
1149/* Called when QEMU goes into the background */
1150- (void) applicationWillResignActive: (NSNotification *)aNotification
1151{
1152 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1153 [cocoaView raiseAllKeys];
1154}
1155
5d1b2eef
JA
1156/* We abstract the method called by the Enter Fullscreen menu item
1157 * because Mac OS 10.7 and higher disables it. This is because of the
1158 * menu item's old selector's name toggleFullScreen:
1159 */
1160- (void) doToggleFullScreen:(id)sender
1161{
1162 [self toggleFullScreen:(id)sender];
1163}
1164
c304f7e2
TS
1165- (void)toggleFullScreen:(id)sender
1166{
1167 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1168
1169 [cocoaView toggleFullScreen:sender];
1170}
5b0753e0 1171
f4747900
JA
1172/* Tries to find then open the specified filename */
1173- (void) openDocumentation: (NSString *) filename
1174{
1175 /* Where to look for local files */
1176 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"../"};
1177 NSString *full_file_path;
1178
1179 /* iterate thru the possible paths until the file is found */
1180 int index;
1181 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1182 full_file_path = [[NSBundle mainBundle] executablePath];
1183 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1184 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1185 path_array[index], filename];
1186 if ([[NSWorkspace sharedWorkspace] openFile: full_file_path] == YES) {
1187 return;
1188 }
1189 }
1190
1191 /* If none of the paths opened a file */
1192 NSBeep();
1193 QEMU_Alert(@"Failed to open file");
1194}
1195
c304f7e2 1196- (void)showQEMUDoc:(id)sender
5b0753e0 1197{
c304f7e2
TS
1198 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1199
f4747900 1200 [self openDocumentation: @"qemu-doc.html"];
c304f7e2
TS
1201}
1202
5d1b2eef
JA
1203/* Stretches video to fit host monitor size */
1204- (void)zoomToFit:(id) sender
1205{
1206 stretch_video = !stretch_video;
1207 if (stretch_video == true) {
5e24600a 1208 [sender setState: NSControlStateValueOn];
5d1b2eef 1209 } else {
5e24600a 1210 [sender setState: NSControlStateValueOff];
5d1b2eef
JA
1211 }
1212}
5b0753e0 1213
b4c6a112
JA
1214/* Displays the console on the screen */
1215- (void)displayConsole:(id)sender
1216{
1217 console_select([sender tag]);
1218}
8524f1c7
JA
1219
1220/* Pause the guest */
1221- (void)pauseQEMU:(id)sender
1222{
31819e95
PM
1223 with_iothread_lock(^{
1224 qmp_stop(NULL);
1225 });
8524f1c7
JA
1226 [sender setEnabled: NO];
1227 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1228 [self displayPause];
1229}
1230
1231/* Resume running the guest operating system */
1232- (void)resumeQEMU:(id) sender
1233{
31819e95
PM
1234 with_iothread_lock(^{
1235 qmp_cont(NULL);
1236 });
8524f1c7
JA
1237 [sender setEnabled: NO];
1238 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1239 [self removePause];
1240}
1241
1242/* Displays the word pause on the screen */
1243- (void)displayPause
1244{
1245 /* Coordinates have to be calculated each time because the window can change its size */
1246 int xCoord, yCoord, width, height;
1247 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1248 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1249 width = [pauseLabel frame].size.width;
1250 height = [pauseLabel frame].size.height;
1251 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1252 [cocoaView addSubview: pauseLabel];
1253}
1254
1255/* Removes the word pause from the screen */
1256- (void)removePause
1257{
1258 [pauseLabel removeFromSuperview];
1259}
1260
27074614
JA
1261/* Restarts QEMU */
1262- (void)restartQEMU:(id)sender
1263{
31819e95
PM
1264 with_iothread_lock(^{
1265 qmp_system_reset(NULL);
1266 });
27074614
JA
1267}
1268
1269/* Powers down QEMU */
1270- (void)powerDownQEMU:(id)sender
1271{
31819e95
PM
1272 with_iothread_lock(^{
1273 qmp_system_powerdown(NULL);
1274 });
27074614
JA
1275}
1276
693a3e01
JA
1277/* Ejects the media.
1278 * Uses sender's tag to figure out the device to eject.
1279 */
1280- (void)ejectDeviceMedia:(id)sender
1281{
1282 NSString * drive;
1283 drive = [sender representedObject];
1284 if(drive == nil) {
1285 NSBeep();
1286 QEMU_Alert(@"Failed to find drive to eject!");
1287 return;
1288 }
1289
31819e95
PM
1290 __block Error *err = NULL;
1291 with_iothread_lock(^{
1292 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1293 false, NULL, false, false, &err);
1294 });
693a3e01
JA
1295 handleAnyDeviceErrors(err);
1296}
1297
1298/* Displays a dialog box asking the user to select an image file to load.
1299 * Uses sender's represented object value to figure out which drive to use.
1300 */
1301- (void)changeDeviceMedia:(id)sender
1302{
1303 /* Find the drive name */
1304 NSString * drive;
1305 drive = [sender representedObject];
1306 if(drive == nil) {
1307 NSBeep();
1308 QEMU_Alert(@"Could not find drive!");
1309 return;
1310 }
1311
1312 /* Display the file open dialog */
1313 NSOpenPanel * openPanel;
1314 openPanel = [NSOpenPanel openPanel];
1315 [openPanel setCanChooseFiles: YES];
1316 [openPanel setAllowsMultipleSelection: NO];
1317 [openPanel setAllowedFileTypes: supportedImageFileTypes];
b5725385 1318 if([openPanel runModal] == NSModalResponseOK) {
693a3e01
JA
1319 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1320 if(file == nil) {
1321 NSBeep();
1322 QEMU_Alert(@"Failed to convert URL to file path!");
1323 return;
1324 }
1325
31819e95
PM
1326 __block Error *err = NULL;
1327 with_iothread_lock(^{
1328 qmp_blockdev_change_medium(true,
1329 [drive cStringUsingEncoding:
1330 NSASCIIStringEncoding],
1331 false, NULL,
1332 [file cStringUsingEncoding:
1333 NSASCIIStringEncoding],
1334 true, "raw",
1335 false, 0,
1336 &err);
1337 });
693a3e01
JA
1338 handleAnyDeviceErrors(err);
1339 }
1340}
1341
d9bc14f6
JA
1342/* Verifies if the user really wants to quit */
1343- (BOOL)verifyQuit
1344{
1345 NSAlert *alert = [NSAlert new];
1346 [alert autorelease];
1347 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1348 [alert addButtonWithTitle: @"Cancel"];
1349 [alert addButtonWithTitle: @"Quit"];
1350 if([alert runModal] == NSAlertSecondButtonReturn) {
1351 return YES;
1352 } else {
1353 return NO;
1354 }
1355}
1356
9e8204b1
JA
1357/* The action method for the About menu item */
1358- (IBAction) do_about_menu_item: (id) sender
1359{
1360 [about_window makeKeyAndOrderFront: nil];
1361}
1362
1363/* Create and display the about dialog */
1364- (void)make_about_window
1365{
1366 /* Make the window */
1367 int x = 0, y = 0, about_width = 400, about_height = 200;
1368 NSRect window_rect = NSMakeRect(x, y, about_width, about_height);
1369 about_window = [[NSWindow alloc] initWithContentRect:window_rect
4ba967ad
BS
1370 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
1371 NSWindowStyleMaskMiniaturizable
9e8204b1
JA
1372 backing:NSBackingStoreBuffered
1373 defer:NO];
1374 [about_window setTitle: @"About"];
1375 [about_window setReleasedWhenClosed: NO];
1376 [about_window center];
1377 NSView *superView = [about_window contentView];
1378
1379 /* Create the dimensions of the picture */
1380 int picture_width = 80, picture_height = 80;
1381 x = (about_width - picture_width)/2;
1382 y = about_height - picture_height - 10;
1383 NSRect picture_rect = NSMakeRect(x, y, picture_width, picture_height);
1384
1385 /* Get the path to the QEMU binary */
1386 NSString *binary_name = [NSString stringWithCString: gArgv[0]
1387 encoding: NSASCIIStringEncoding];
1388 binary_name = [binary_name lastPathComponent];
1389 NSString *program_path = [[NSString alloc] initWithFormat: @"%@/%@",
1390 [[NSBundle mainBundle] bundlePath], binary_name];
1391
1392 /* Make the picture of QEMU */
1393 NSImageView *picture_view = [[NSImageView alloc] initWithFrame:
1394 picture_rect];
1395 NSImage *qemu_image = [[NSWorkspace sharedWorkspace] iconForFile:
1396 program_path];
1397 [picture_view setImage: qemu_image];
1398 [picture_view setImageScaling: NSImageScaleProportionallyUpOrDown];
1399 [superView addSubview: picture_view];
1400
1401 /* Make the name label */
1402 x = 0;
1403 y = y - 25;
1404 int name_width = about_width, name_height = 20;
1405 NSRect name_rect = NSMakeRect(x, y, name_width, name_height);
1406 NSTextField *name_label = [[NSTextField alloc] initWithFrame: name_rect];
1407 [name_label setEditable: NO];
1408 [name_label setBezeled: NO];
1409 [name_label setDrawsBackground: NO];
4ba967ad 1410 [name_label setAlignment: NSTextAlignmentCenter];
9e8204b1
JA
1411 NSString *qemu_name = [[NSString alloc] initWithCString: gArgv[0]
1412 encoding: NSASCIIStringEncoding];
1413 qemu_name = [qemu_name lastPathComponent];
1414 [name_label setStringValue: qemu_name];
1415 [superView addSubview: name_label];
1416
1417 /* Set the version label's attributes */
1418 x = 0;
1419 y = 50;
1420 int version_width = about_width, version_height = 20;
1421 NSRect version_rect = NSMakeRect(x, y, version_width, version_height);
1422 NSTextField *version_label = [[NSTextField alloc] initWithFrame:
1423 version_rect];
1424 [version_label setEditable: NO];
1425 [version_label setBezeled: NO];
4ba967ad 1426 [version_label setAlignment: NSTextAlignmentCenter];
9e8204b1
JA
1427 [version_label setDrawsBackground: NO];
1428
1429 /* Create the version string*/
1430 NSString *version_string;
1431 version_string = [[NSString alloc] initWithFormat:
7e563bfb 1432 @"QEMU emulator version %s", QEMU_FULL_VERSION];
9e8204b1
JA
1433 [version_label setStringValue: version_string];
1434 [superView addSubview: version_label];
1435
1436 /* Make copyright label */
1437 x = 0;
1438 y = 35;
1439 int copyright_width = about_width, copyright_height = 20;
1440 NSRect copyright_rect = NSMakeRect(x, y, copyright_width, copyright_height);
1441 NSTextField *copyright_label = [[NSTextField alloc] initWithFrame:
1442 copyright_rect];
1443 [copyright_label setEditable: NO];
1444 [copyright_label setBezeled: NO];
1445 [copyright_label setDrawsBackground: NO];
4ba967ad 1446 [copyright_label setAlignment: NSTextAlignmentCenter];
9e8204b1
JA
1447 [copyright_label setStringValue: [NSString stringWithFormat: @"%s",
1448 QEMU_COPYRIGHT]];
1449 [superView addSubview: copyright_label];
1450}
1451
e47ec1a9
JA
1452/* Used by the Speed menu items */
1453- (void)adjustSpeed:(id)sender
1454{
1455 int throttle_pct; /* throttle percentage */
1456 NSMenu *menu;
1457
1458 menu = [sender menu];
1459 if (menu != nil)
1460 {
1461 /* Unselect the currently selected item */
1462 for (NSMenuItem *item in [menu itemArray]) {
5e24600a
BS
1463 if (item.state == NSControlStateValueOn) {
1464 [item setState: NSControlStateValueOff];
e47ec1a9
JA
1465 break;
1466 }
1467 }
1468 }
1469
1470 // check the menu item
5e24600a 1471 [sender setState: NSControlStateValueOn];
e47ec1a9
JA
1472
1473 // get the throttle percentage
1474 throttle_pct = [sender tag];
1475
31819e95
PM
1476 with_iothread_lock(^{
1477 cpu_throttle_set(throttle_pct);
1478 });
e47ec1a9
JA
1479 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1480}
1481
b4c6a112 1482@end
5b0753e0 1483
61a2ed44
PM
1484@interface QemuApplication : NSApplication
1485@end
1486
1487@implementation QemuApplication
1488- (void)sendEvent:(NSEvent *)event
1489{
1490 COCOA_DEBUG("QemuApplication: sendEvent\n");
5588840f
PM
1491 if (![cocoaView handleEvent:event]) {
1492 [super sendEvent: event];
1493 }
61a2ed44
PM
1494}
1495@end
1496
c6fd6c70
PM
1497static void create_initial_menus(void)
1498{
c304f7e2
TS
1499 // Add menus
1500 NSMenu *menu;
1501 NSMenuItem *menuItem;
5b0753e0 1502
c304f7e2 1503 [NSApp setMainMenu:[[NSMenu alloc] init]];
5b0753e0 1504
c304f7e2
TS
1505 // Application menu
1506 menu = [[NSMenu alloc] initWithTitle:@""];
9e8204b1 1507 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
c304f7e2
TS
1508 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1509 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1510 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
4ba967ad 1511 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
c304f7e2
TS
1512 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1513 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1514 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1515 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1516 [menuItem setSubmenu:menu];
1517 [[NSApp mainMenu] addItem:menuItem];
1518 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
3b46e624 1519
8524f1c7
JA
1520 // Machine menu
1521 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1522 [menu setAutoenablesItems: NO];
1523 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1524 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1525 [menu addItem: menuItem];
1526 [menuItem setEnabled: NO];
27074614
JA
1527 [menu addItem: [NSMenuItem separatorItem]];
1528 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1529 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
8524f1c7
JA
1530 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1531 [menuItem setSubmenu:menu];
1532 [[NSApp mainMenu] addItem:menuItem];
1533
c304f7e2
TS
1534 // View menu
1535 menu = [[NSMenu alloc] initWithTitle:@"View"];
5d1b2eef
JA
1536 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1537 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
c304f7e2
TS
1538 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1539 [menuItem setSubmenu:menu];
5b0753e0
FB
1540 [[NSApp mainMenu] addItem:menuItem];
1541
e47ec1a9
JA
1542 // Speed menu
1543 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1544
1545 // Add the rest of the Speed menu items
1546 int p, percentage, throttle_pct;
1547 for (p = 10; p >= 0; p--)
1548 {
1549 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1550
1551 menuItem = [[[NSMenuItem alloc]
1552 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1553
1554 if (percentage == 100) {
5e24600a 1555 [menuItem setState: NSControlStateValueOn];
e47ec1a9
JA
1556 }
1557
1558 /* Calculate the throttle percentage */
1559 throttle_pct = -1 * percentage + 100;
1560
1561 [menuItem setTag: throttle_pct];
1562 [menu addItem: menuItem];
1563 }
1564 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1565 [menuItem setSubmenu:menu];
1566 [[NSApp mainMenu] addItem:menuItem];
1567
c304f7e2
TS
1568 // Window menu
1569 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1570 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1571 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1572 [menuItem setSubmenu:menu];
1573 [[NSApp mainMenu] addItem:menuItem];
1574 [NSApp setWindowsMenu:menu];
1575
1576 // Help menu
1577 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1578 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
c304f7e2
TS
1579 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1580 [menuItem setSubmenu:menu];
1581 [[NSApp mainMenu] addItem:menuItem];
c6fd6c70
PM
1582}
1583
8b00e4e7
PM
1584/* Returns a name for a given console */
1585static NSString * getConsoleName(QemuConsole * console)
1586{
1587 return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1588}
1589
1590/* Add an entry to the View menu for each console */
1591static void add_console_menu_entries(void)
1592{
1593 NSMenu *menu;
1594 NSMenuItem *menuItem;
1595 int index = 0;
1596
1597 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1598
1599 [menu addItem:[NSMenuItem separatorItem]];
1600
1601 while (qemu_console_lookup_by_index(index) != NULL) {
1602 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1603 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1604 [menuItem setTag: index];
1605 [menu addItem: menuItem];
1606 index++;
1607 }
1608}
1609
1610/* Make menu items for all removable devices.
1611 * Each device is given an 'Eject' and 'Change' menu item.
1612 */
1613static void addRemovableDevicesMenuItems(void)
1614{
1615 NSMenu *menu;
1616 NSMenuItem *menuItem;
1617 BlockInfoList *currentDevice, *pointerToFree;
1618 NSString *deviceName;
1619
1620 currentDevice = qmp_query_block(NULL);
1621 pointerToFree = currentDevice;
1622 if(currentDevice == NULL) {
1623 NSBeep();
1624 QEMU_Alert(@"Failed to query for block devices!");
1625 return;
1626 }
1627
1628 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1629
1630 // Add a separator between related groups of menu items
1631 [menu addItem:[NSMenuItem separatorItem]];
1632
1633 // Set the attributes to the "Removable Media" menu item
1634 NSString *titleString = @"Removable Media";
1635 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1636 NSColor *newColor = [NSColor blackColor];
1637 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1638 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1639 traits:NSBoldFontMask|NSItalicFontMask
1640 weight:0
1641 size:14];
1642 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1643 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1644 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1645
1646 // Add the "Removable Media" menu item
1647 menuItem = [NSMenuItem new];
1648 [menuItem setAttributedTitle: attString];
1649 [menuItem setEnabled: NO];
1650 [menu addItem: menuItem];
1651
1652 /* Loop through all the block devices in the emulator */
1653 while (currentDevice) {
1654 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1655
1656 if(currentDevice->value->removable) {
1657 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1658 action: @selector(changeDeviceMedia:)
1659 keyEquivalent: @""];
1660 [menu addItem: menuItem];
1661 [menuItem setRepresentedObject: deviceName];
1662 [menuItem autorelease];
1663
1664 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1665 action: @selector(ejectDeviceMedia:)
1666 keyEquivalent: @""];
1667 [menu addItem: menuItem];
1668 [menuItem setRepresentedObject: deviceName];
1669 [menuItem autorelease];
1670 }
1671 currentDevice = currentDevice->next;
1672 }
1673 qapi_free_BlockInfoList(pointerToFree);
1674}
1675
5588840f
PM
1676/*
1677 * The startup process for the OSX/Cocoa UI is complicated, because
1678 * OSX insists that the UI runs on the initial main thread, and so we
1679 * need to start a second thread which runs the vl.c qemu_main():
1680 *
1681 * Initial thread: 2nd thread:
1682 * in main():
1683 * create qemu-main thread
1684 * wait on display_init semaphore
1685 * call qemu_main()
1686 * ...
1687 * in cocoa_display_init():
1688 * post the display_init semaphore
1689 * wait on app_started semaphore
1690 * create application, menus, etc
1691 * enter OSX run loop
1692 * in applicationDidFinishLaunching:
1693 * post app_started semaphore
1694 * tell main thread to fullscreen if needed
1695 * [...]
1696 * run qemu main-loop
1697 *
1698 * We do this in two stages so that we don't do the creation of the
1699 * GUI application menus and so on for command line options like --help
1700 * where we want to just print text to stdout and exit immediately.
1701 */
1702
1703static void *call_qemu_main(void *opaque)
1704{
1705 int status;
1706
1707 COCOA_DEBUG("Second thread: calling qemu_main()\n");
1708 status = qemu_main(gArgc, gArgv, *_NSGetEnviron());
1709 COCOA_DEBUG("Second thread: qemu_main() returned, exiting\n");
1710 exit(status);
1711}
1712
c6fd6c70 1713int main (int argc, const char * argv[]) {
5588840f 1714 QemuThread thread;
c6fd6c70 1715
5588840f 1716 COCOA_DEBUG("Entered main()\n");
c6fd6c70
PM
1717 gArgc = argc;
1718 gArgv = (char **)argv;
c6fd6c70 1719
5588840f
PM
1720 qemu_sem_init(&display_init_sem, 0);
1721 qemu_sem_init(&app_started_sem, 0);
c6fd6c70 1722
5588840f
PM
1723 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1724 NULL, QEMU_THREAD_DETACHED);
1725
1726 COCOA_DEBUG("Main thread: waiting for display_init_sem\n");
1727 qemu_sem_wait(&display_init_sem);
1728 COCOA_DEBUG("Main thread: initializing app\n");
c6fd6c70
PM
1729
1730 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1731
1732 // Pull this console process up to being a fully-fledged graphical
1733 // app with a menubar and Dock icon
1734 ProcessSerialNumber psn = { 0, kCurrentProcess };
1735 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1736
61a2ed44 1737 [QemuApplication sharedApplication];
c6fd6c70
PM
1738
1739 create_initial_menus();
5b0753e0 1740
5588840f
PM
1741 /*
1742 * Create the menu entries which depend on QEMU state (for consoles
1743 * and removeable devices). These make calls back into QEMU functions,
1744 * which is OK because at this point we know that the second thread
1745 * holds the iothread lock and is synchronously waiting for us to
1746 * finish.
1747 */
1748 add_console_menu_entries();
1749 addRemovableDevicesMenuItems();
1750
c304f7e2
TS
1751 // Create an Application controller
1752 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1753 [NSApp setDelegate:appController];
5b0753e0 1754
c304f7e2 1755 // Start the main event loop
5588840f 1756 COCOA_DEBUG("Main thread: entering OSX run loop\n");
c304f7e2 1757 [NSApp run];
5588840f 1758 COCOA_DEBUG("Main thread: left OSX run loop, exiting\n");
5b0753e0 1759
c304f7e2
TS
1760 [appController release];
1761 [pool release];
3b46e624 1762
c304f7e2
TS
1763 return 0;
1764}
3b46e624 1765
3b46e624 1766
5b0753e0 1767
c304f7e2 1768#pragma mark qemu
7c20b4a3 1769static void cocoa_update(DisplayChangeListener *dcl,
7c20b4a3 1770 int x, int y, int w, int h)
c304f7e2 1771{
6e657e64
PM
1772 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1773
c304f7e2
TS
1774 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1775
5588840f
PM
1776 dispatch_async(dispatch_get_main_queue(), ^{
1777 NSRect rect;
1778 if ([cocoaView cdx] == 1.0) {
1779 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1780 } else {
1781 rect = NSMakeRect(
1782 x * [cocoaView cdx],
1783 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1784 w * [cocoaView cdx],
1785 h * [cocoaView cdy]);
1786 }
1787 [cocoaView setNeedsDisplayInRect:rect];
1788 });
6e657e64
PM
1789
1790 [pool release];
5b0753e0
FB
1791}
1792
c12aeb86 1793static void cocoa_switch(DisplayChangeListener *dcl,
c12aeb86 1794 DisplaySurface *surface)
5b0753e0 1795{
6e657e64 1796 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
5588840f 1797 pixman_image_t *image = surface->image;
3b46e624 1798
6e657e64 1799 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
5588840f
PM
1800
1801 // The DisplaySurface will be freed as soon as this callback returns.
1802 // We take a reference to the underlying pixman image here so it does
1803 // not disappear from under our feet; the switchSurface method will
1804 // deref the old image when it is done with it.
1805 pixman_image_ref(image);
1806
1807 dispatch_async(dispatch_get_main_queue(), ^{
1808 [cocoaView switchSurface:image];
1809 });
6e657e64 1810 [pool release];
c304f7e2 1811}
3b46e624 1812
bc2ed970 1813static void cocoa_refresh(DisplayChangeListener *dcl)
c304f7e2 1814{
6e657e64
PM
1815 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1816
c304f7e2 1817 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
468a895b 1818 graphic_hw_update(NULL);
3b46e624 1819
21bae11a 1820 if (qemu_input_is_absolute()) {
5588840f
PM
1821 dispatch_async(dispatch_get_main_queue(), ^{
1822 if (![cocoaView isAbsoluteEnabled]) {
1823 if ([cocoaView isMouseGrabbed]) {
1824 [cocoaView ungrabMouse];
1825 }
c304f7e2 1826 }
5588840f
PM
1827 [cocoaView setAbsoluteEnabled:YES];
1828 });
c304f7e2 1829 }
6e657e64 1830 [pool release];
c304f7e2 1831}
3b46e624 1832
c304f7e2
TS
1833static void cocoa_cleanup(void)
1834{
1835 COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
58a06675 1836 g_free(dcl);
5b0753e0
FB
1837}
1838
7c20b4a3
GH
1839static const DisplayChangeListenerOps dcl_ops = {
1840 .dpy_name = "cocoa",
8510d91e
PM
1841 .dpy_gfx_update = cocoa_update,
1842 .dpy_gfx_switch = cocoa_switch,
1843 .dpy_refresh = cocoa_refresh,
7c20b4a3
GH
1844};
1845
5013b9e4 1846static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
5b0753e0 1847{
c304f7e2
TS
1848 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1849
5588840f
PM
1850 /* Tell main thread to go ahead and create the app and enter the run loop */
1851 qemu_sem_post(&display_init_sem);
1852 qemu_sem_wait(&app_started_sem);
1853 COCOA_DEBUG("cocoa_display_init: app start completed\n");
1854
43227af8 1855 /* if fullscreen mode is to be used */
767f9bf3 1856 if (opts->has_full_screen && opts->full_screen) {
5588840f
PM
1857 dispatch_async(dispatch_get_main_queue(), ^{
1858 [NSApp activateIgnoringOtherApps: YES];
1859 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1860 });
43227af8
JA
1861 }
1862
58a06675
BS
1863 dcl = g_malloc0(sizeof(DisplayChangeListener));
1864
9794f74f 1865 // register vga output callbacks
7c20b4a3 1866 dcl->ops = &dcl_ops;
5209089f 1867 register_displaychangelistener(dcl);
cae41b10 1868
c304f7e2
TS
1869 // register cleanup function
1870 atexit(cocoa_cleanup);
5b0753e0 1871}
5013b9e4
GH
1872
1873static QemuDisplay qemu_display_cocoa = {
1874 .type = DISPLAY_TYPE_COCOA,
1875 .init = cocoa_display_init,
1876};
1877
1878static void register_cocoa(void)
1879{
1880 qemu_display_register(&qemu_display_cocoa);
1881}
1882
1883type_init(register_cocoa);