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