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