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