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