]> Git Repo - qemu.git/blame - ui/cocoa.m
ui/cocoa.m: prevent stuck key situation
[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
5b0753e0 25#import <Cocoa/Cocoa.h>
3bbbee18 26#include <crt_externs.h>
5b0753e0 27
87ecb68b 28#include "qemu-common.h"
28ecbaee 29#include "ui/console.h"
21bae11a 30#include "ui/input.h"
9c17d615 31#include "sysemu/sysemu.h"
8524f1c7 32#include "qmp-commands.h"
693a3e01 33#include "sysemu/blockdev.h"
da4dbf74 34
44e4c0ba
AF
35#ifndef MAC_OS_X_VERSION_10_5
36#define MAC_OS_X_VERSION_10_5 1050
37#endif
2ba9de6e
PM
38#ifndef MAC_OS_X_VERSION_10_6
39#define MAC_OS_X_VERSION_10_6 1060
40#endif
81801ae2
PM
41#ifndef MAC_OS_X_VERSION_10_10
42#define MAC_OS_X_VERSION_10_10 101000
43#endif
44e4c0ba 44
3b46e624 45
c304f7e2 46//#define DEBUG
3b46e624 47
c304f7e2
TS
48#ifdef DEBUG
49#define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
b29169d2 50#else
c304f7e2 51#define COCOA_DEBUG(...) ((void) 0)
b29169d2
BS
52#endif
53
c304f7e2 54#define cgrect(nsrect) (*(CGRect *)&(nsrect))
5b0753e0 55
c304f7e2
TS
56typedef struct {
57 int width;
58 int height;
59 int bitsPerComponent;
60 int bitsPerPixel;
61} QEMUScreen;
62
c304f7e2 63NSWindow *normalWindow;
9794f74f 64static DisplayChangeListener *dcl;
21bae11a 65static int last_buttons;
c304f7e2
TS
66
67int gArgc;
68char **gArgv;
5d1b2eef 69bool stretch_video;
8524f1c7 70NSTextField *pauseLabel;
693a3e01 71NSArray * supportedImageFileTypes;
5b0753e0 72
c304f7e2 73// keymap conversion
87f48e6a 74int keymap[] =
5b0753e0 75{
87f48e6a
FB
76// SdlI macI macH SdlH 104xtH 104xtC sdl
77 30, // 0 0x00 0x1e A QZ_a
78 31, // 1 0x01 0x1f S QZ_s
79 32, // 2 0x02 0x20 D QZ_d
80 33, // 3 0x03 0x21 F QZ_f
81 35, // 4 0x04 0x23 H QZ_h
82 34, // 5 0x05 0x22 G QZ_g
83 44, // 6 0x06 0x2c Z QZ_z
84 45, // 7 0x07 0x2d X QZ_x
85 46, // 8 0x08 0x2e C QZ_c
86 47, // 9 0x09 0x2f V QZ_v
87 0, // 10 0x0A Undefined
88 48, // 11 0x0B 0x30 B QZ_b
89 16, // 12 0x0C 0x10 Q QZ_q
90 17, // 13 0x0D 0x11 W QZ_w
91 18, // 14 0x0E 0x12 E QZ_e
92 19, // 15 0x0F 0x13 R QZ_r
93 21, // 16 0x10 0x15 Y QZ_y
94 20, // 17 0x11 0x14 T QZ_t
95 2, // 18 0x12 0x02 1 QZ_1
96 3, // 19 0x13 0x03 2 QZ_2
97 4, // 20 0x14 0x04 3 QZ_3
98 5, // 21 0x15 0x05 4 QZ_4
99 7, // 22 0x16 0x07 6 QZ_6
100 6, // 23 0x17 0x06 5 QZ_5
101 13, // 24 0x18 0x0d = QZ_EQUALS
102 10, // 25 0x19 0x0a 9 QZ_9
103 8, // 26 0x1A 0x08 7 QZ_7
104 12, // 27 0x1B 0x0c - QZ_MINUS
105 9, // 28 0x1C 0x09 8 QZ_8
106 11, // 29 0x1D 0x0b 0 QZ_0
107 27, // 30 0x1E 0x1b ] QZ_RIGHTBRACKET
108 24, // 31 0x1F 0x18 O QZ_o
109 22, // 32 0x20 0x16 U QZ_u
110 26, // 33 0x21 0x1a [ QZ_LEFTBRACKET
111 23, // 34 0x22 0x17 I QZ_i
112 25, // 35 0x23 0x19 P QZ_p
113 28, // 36 0x24 0x1c ENTER QZ_RETURN
114 38, // 37 0x25 0x26 L QZ_l
115 36, // 38 0x26 0x24 J QZ_j
116 40, // 39 0x27 0x28 ' QZ_QUOTE
117 37, // 40 0x28 0x25 K QZ_k
118 39, // 41 0x29 0x27 ; QZ_SEMICOLON
119 43, // 42 0x2A 0x2b \ QZ_BACKSLASH
120 51, // 43 0x2B 0x33 , QZ_COMMA
121 53, // 44 0x2C 0x35 / QZ_SLASH
122 49, // 45 0x2D 0x31 N QZ_n
123 50, // 46 0x2E 0x32 M QZ_m
124 52, // 47 0x2F 0x34 . QZ_PERIOD
125 15, // 48 0x30 0x0f TAB QZ_TAB
126 57, // 49 0x31 0x39 SPACE QZ_SPACE
127 41, // 50 0x32 0x29 ` QZ_BACKQUOTE
128 14, // 51 0x33 0x0e BKSP QZ_BACKSPACE
129 0, // 52 0x34 Undefined
130 1, // 53 0x35 0x01 ESC QZ_ESCAPE
8895919a
PM
131 220, // 54 0x36 0xdc E0,5C R GUI QZ_RMETA
132 219, // 55 0x37 0xdb E0,5B L GUI QZ_LMETA
87f48e6a
FB
133 42, // 56 0x38 0x2a L SHFT QZ_LSHIFT
134 58, // 57 0x39 0x3a CAPS QZ_CAPSLOCK
135 56, // 58 0x3A 0x38 L ALT QZ_LALT
136 29, // 59 0x3B 0x1d L CTRL QZ_LCTRL
137 54, // 60 0x3C 0x36 R SHFT QZ_RSHIFT
138 184,// 61 0x3D 0xb8 E0,38 R ALT QZ_RALT
139 157,// 62 0x3E 0x9d E0,1D R CTRL QZ_RCTRL
140 0, // 63 0x3F Undefined
141 0, // 64 0x40 Undefined
142 0, // 65 0x41 Undefined
143 0, // 66 0x42 Undefined
144 55, // 67 0x43 0x37 KP * QZ_KP_MULTIPLY
145 0, // 68 0x44 Undefined
146 78, // 69 0x45 0x4e KP + QZ_KP_PLUS
147 0, // 70 0x46 Undefined
148 69, // 71 0x47 0x45 NUM QZ_NUMLOCK
149 0, // 72 0x48 Undefined
150 0, // 73 0x49 Undefined
151 0, // 74 0x4A Undefined
152 181,// 75 0x4B 0xb5 E0,35 KP / QZ_KP_DIVIDE
153 152,// 76 0x4C 0x9c E0,1C KP EN QZ_KP_ENTER
154 0, // 77 0x4D undefined
155 74, // 78 0x4E 0x4a KP - QZ_KP_MINUS
156 0, // 79 0x4F Undefined
157 0, // 80 0x50 Undefined
158 0, // 81 0x51 QZ_KP_EQUALS
159 82, // 82 0x52 0x52 KP 0 QZ_KP0
160 79, // 83 0x53 0x4f KP 1 QZ_KP1
161 80, // 84 0x54 0x50 KP 2 QZ_KP2
162 81, // 85 0x55 0x51 KP 3 QZ_KP3
163 75, // 86 0x56 0x4b KP 4 QZ_KP4
164 76, // 87 0x57 0x4c KP 5 QZ_KP5
165 77, // 88 0x58 0x4d KP 6 QZ_KP6
166 71, // 89 0x59 0x47 KP 7 QZ_KP7
167 0, // 90 0x5A Undefined
168 72, // 91 0x5B 0x48 KP 8 QZ_KP8
169 73, // 92 0x5C 0x49 KP 9 QZ_KP9
170 0, // 93 0x5D Undefined
171 0, // 94 0x5E Undefined
172 0, // 95 0x5F Undefined
173 63, // 96 0x60 0x3f F5 QZ_F5
174 64, // 97 0x61 0x40 F6 QZ_F6
175 65, // 98 0x62 0x41 F7 QZ_F7
176 61, // 99 0x63 0x3d F3 QZ_F3
177 66, // 100 0x64 0x42 F8 QZ_F8
178 67, // 101 0x65 0x43 F9 QZ_F9
179 0, // 102 0x66 Undefined
180 87, // 103 0x67 0x57 F11 QZ_F11
181 0, // 104 0x68 Undefined
c304f7e2 182 183,// 105 0x69 0xb7 QZ_PRINT
87f48e6a
FB
183 0, // 106 0x6A Undefined
184 70, // 107 0x6B 0x46 SCROLL QZ_SCROLLOCK
185 0, // 108 0x6C Undefined
186 68, // 109 0x6D 0x44 F10 QZ_F10
187 0, // 110 0x6E Undefined
188 88, // 111 0x6F 0x58 F12 QZ_F12
189 0, // 112 0x70 Undefined
190 110,// 113 0x71 0x0 QZ_PAUSE
191 210,// 114 0x72 0xd2 E0,52 INSERT QZ_INSERT
192 199,// 115 0x73 0xc7 E0,47 HOME QZ_HOME
193 201,// 116 0x74 0xc9 E0,49 PG UP QZ_PAGEUP
194 211,// 117 0x75 0xd3 E0,53 DELETE QZ_DELETE
195 62, // 118 0x76 0x3e F4 QZ_F4
196 207,// 119 0x77 0xcf E0,4f END QZ_END
197 60, // 120 0x78 0x3c F2 QZ_F2
198 209,// 121 0x79 0xd1 E0,51 PG DN QZ_PAGEDOWN
199 59, // 122 0x7A 0x3b F1 QZ_F1
200 203,// 123 0x7B 0xcb e0,4B L ARROW QZ_LEFT
201 205,// 124 0x7C 0xcd e0,4D R ARROW QZ_RIGHT
202 208,// 125 0x7D 0xd0 E0,50 D ARROW QZ_DOWN
203 200,// 126 0x7E 0xc8 E0,48 U ARROW QZ_UP
204/* completed according to http://www.libsdl.org/cgi/cvsweb.cgi/SDL12/src/video/quartz/SDL_QuartzKeys.h?rev=1.6&content-type=text/x-cvsweb-markup */
3b46e624 205
49b9bd4d 206/* Additional 104 Key XP-Keyboard Scancodes from http://www.computer-engineering.org/ps2keyboard/scancodes1.html */
87f48e6a 207/*
3b46e624
TS
208 221 // 0xdd e0,5d APPS
209 // E0,2A,E0,37 PRNT SCRN
210 // E1,1D,45,E1,9D,C5 PAUSE
211 83 // 0x53 0x53 KP .
212// ACPI Scan Codes
213 222 // 0xde E0, 5E Power
214 223 // 0xdf E0, 5F Sleep
215 227 // 0xe3 E0, 63 Wake
216// Windows Multimedia Scan Codes
217 153 // 0x99 E0, 19 Next Track
218 144 // 0x90 E0, 10 Previous Track
219 164 // 0xa4 E0, 24 Stop
220 162 // 0xa2 E0, 22 Play/Pause
221 160 // 0xa0 E0, 20 Mute
222 176 // 0xb0 E0, 30 Volume Up
5fafdf24 223 174 // 0xae E0, 2E Volume Down
3b46e624
TS
224 237 // 0xed E0, 6D Media Select
225 236 // 0xec E0, 6C E-Mail
226 161 // 0xa1 E0, 21 Calculator
5fafdf24 227 235 // 0xeb E0, 6B My Computer
3b46e624
TS
228 229 // 0xe5 E0, 65 WWW Search
229 178 // 0xb2 E0, 32 WWW Home
230 234 // 0xea E0, 6A WWW Back
5fafdf24 231 233 // 0xe9 E0, 69 WWW Forward
3b46e624 232 232 // 0xe8 E0, 68 WWW Stop
5fafdf24 233 231 // 0xe7 E0, 67 WWW Refresh
3b46e624 234 230 // 0xe6 E0, 66 WWW Favorites
87f48e6a 235*/
5b0753e0
FB
236};
237
77047bb7 238static int cocoa_keycode_to_qemu(int keycode)
5b0753e0 239{
5d70192b 240 if (ARRAY_SIZE(keymap) <= keycode) {
01cc4e6f 241 fprintf(stderr, "(cocoa) warning unknown keycode 0x%x\n", keycode);
5b0753e0
FB
242 return 0;
243 }
244 return keymap[keycode];
245}
246
693a3e01
JA
247/* Displays an alert dialog box with the specified message */
248static void QEMU_Alert(NSString *message)
249{
250 NSAlert *alert;
251 alert = [NSAlert new];
252 [alert setMessageText: message];
253 [alert runModal];
254}
c304f7e2 255
693a3e01
JA
256/* Handles any errors that happen with a device transaction */
257static void handleAnyDeviceErrors(Error * err)
258{
259 if (err) {
260 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
261 encoding: NSASCIIStringEncoding]);
262 error_free(err);
263 }
264}
c304f7e2 265
5b0753e0
FB
266/*
267 ------------------------------------------------------
c304f7e2 268 QemuCocoaView
5b0753e0
FB
269 ------------------------------------------------------
270*/
c304f7e2 271@interface QemuCocoaView : NSView
5b0753e0 272{
c304f7e2
TS
273 QEMUScreen screen;
274 NSWindow *fullScreenWindow;
275 float cx,cy,cw,ch,cdx,cdy;
276 CGDataProviderRef dataProviderRef;
277 int modifiers_state[256];
49b9bd4d 278 BOOL isMouseGrabbed;
c304f7e2
TS
279 BOOL isFullscreen;
280 BOOL isAbsoluteEnabled;
f61c387e 281 BOOL isMouseDeassociated;
c304f7e2 282}
5e00d3ac 283- (void) switchSurface:(DisplaySurface *)surface;
c304f7e2
TS
284- (void) grabMouse;
285- (void) ungrabMouse;
286- (void) toggleFullScreen:(id)sender;
287- (void) handleEvent:(NSEvent *)event;
288- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
f61c387e
PM
289/* The state surrounding mouse grabbing is potentially confusing.
290 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
291 * pointing device an absolute-position one?"], but is only updated on
292 * next refresh.
293 * isMouseGrabbed tracks whether GUI events are directed to the guest;
294 * it controls whether special keys like Cmd get sent to the guest,
295 * and whether we capture the mouse when in non-absolute mode.
296 * isMouseDeassociated tracks whether we've told MacOSX to disassociate
297 * the mouse and mouse cursor position by calling
298 * CGAssociateMouseAndMouseCursorPosition(FALSE)
299 * (which basically happens if we grab in non-absolute mode).
300 */
49b9bd4d 301- (BOOL) isMouseGrabbed;
c304f7e2 302- (BOOL) isAbsoluteEnabled;
f61c387e 303- (BOOL) isMouseDeassociated;
c304f7e2
TS
304- (float) cdx;
305- (float) cdy;
306- (QEMUScreen) gscreen;
3b178b71 307- (void) raiseAllKeys;
c304f7e2 308@end
3b46e624 309
7fee199c
AF
310QemuCocoaView *cocoaView;
311
c304f7e2
TS
312@implementation QemuCocoaView
313- (id)initWithFrame:(NSRect)frameRect
314{
315 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
3b46e624 316
c304f7e2
TS
317 self = [super initWithFrame:frameRect];
318 if (self) {
3b46e624 319
c304f7e2
TS
320 screen.bitsPerComponent = 8;
321 screen.bitsPerPixel = 32;
322 screen.width = frameRect.size.width;
323 screen.height = frameRect.size.height;
3b46e624 324
c304f7e2
TS
325 }
326 return self;
327}
3b46e624 328
c304f7e2
TS
329- (void) dealloc
330{
331 COCOA_DEBUG("QemuCocoaView: dealloc\n");
3b46e624 332
c304f7e2
TS
333 if (dataProviderRef)
334 CGDataProviderRelease(dataProviderRef);
3b46e624 335
c304f7e2
TS
336 [super dealloc];
337}
3b46e624 338
d50f71dc
AF
339- (BOOL) isOpaque
340{
341 return YES;
342}
343
5dd45bee
PM
344- (BOOL) screenContainsPoint:(NSPoint) p
345{
346 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
347}
348
13aefd30
PM
349- (void) hideCursor
350{
351 if (!cursor_hide) {
352 return;
353 }
354 [NSCursor hide];
355}
356
357- (void) unhideCursor
358{
359 if (!cursor_hide) {
360 return;
361 }
362 [NSCursor unhide];
363}
364
c304f7e2
TS
365- (void) drawRect:(NSRect) rect
366{
367 COCOA_DEBUG("QemuCocoaView: drawRect\n");
368
c304f7e2
TS
369 // get CoreGraphic context
370 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] graphicsPort];
371 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
372 CGContextSetShouldAntialias (viewContextRef, NO);
373
374 // draw screen bitmap directly to Core Graphics context
7d270b1c
PM
375 if (!dataProviderRef) {
376 // Draw request before any guest device has set up a framebuffer:
377 // just draw an opaque black rectangle
378 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
379 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
380 } else {
c304f7e2
TS
381 CGImageRef imageRef = CGImageCreate(
382 screen.width, //width
383 screen.height, //height
384 screen.bitsPerComponent, //bitsPerComponent
385 screen.bitsPerPixel, //bitsPerPixel
9794f74f 386 (screen.width * (screen.bitsPerComponent/2)), //bytesPerRow
04afa4a8 387#ifdef __LITTLE_ENDIAN__
c304f7e2 388 CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), //colorspace for OS X >= 10.4
9794f74f 389 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,
c304f7e2
TS
390#else
391 CGColorSpaceCreateDeviceRGB(), //colorspace for OS X < 10.4 (actually ppc)
392 kCGImageAlphaNoneSkipFirst, //bitmapInfo
393#endif
394 dataProviderRef, //provider
395 NULL, //decode
396 0, //interpolate
397 kCGRenderingIntentDefault //intent
398 );
b63901d8
PM
399 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
400 const NSRect *rectList;
b63901d8 401 NSInteger rectCount;
b63901d8
PM
402 int i;
403 CGImageRef clipImageRef;
404 CGRect clipRect;
405
406 [self getRectsBeingDrawn:&rectList count:&rectCount];
407 for (i = 0; i < rectCount; i++) {
408 clipRect.origin.x = rectList[i].origin.x / cdx;
409 clipRect.origin.y = (float)screen.height - (rectList[i].origin.y + rectList[i].size.height) / cdy;
410 clipRect.size.width = rectList[i].size.width / cdx;
411 clipRect.size.height = rectList[i].size.height / cdy;
412 clipImageRef = CGImageCreateWithImageInRect(
413 imageRef,
414 clipRect
415 );
416 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
417 CGImageRelease (clipImageRef);
5b0753e0 418 }
c304f7e2
TS
419 CGImageRelease (imageRef);
420 }
5b0753e0
FB
421}
422
c304f7e2 423- (void) setContentDimensions
5b0753e0 424{
c304f7e2
TS
425 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
426
427 if (isFullscreen) {
428 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
429 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
5d1b2eef
JA
430
431 /* stretches video, but keeps same aspect ratio */
432 if (stretch_video == true) {
433 /* use smallest stretch value - prevents clipping on sides */
434 if (MIN(cdx, cdy) == cdx) {
435 cdy = cdx;
436 } else {
437 cdx = cdy;
438 }
439 } else { /* No stretching */
440 cdx = cdy = 1;
441 }
c304f7e2
TS
442 cw = screen.width * cdx;
443 ch = screen.height * cdy;
444 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
445 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
446 } else {
447 cx = 0;
448 cy = 0;
449 cw = screen.width;
450 ch = screen.height;
451 cdx = 1.0;
452 cdy = 1.0;
453 }
5b0753e0
FB
454}
455
5e00d3ac 456- (void) switchSurface:(DisplaySurface *)surface
5b0753e0 457{
5e00d3ac 458 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
c304f7e2 459
8510d91e
PM
460 int w = surface_width(surface);
461 int h = surface_height(surface);
381600da
PM
462 /* cdx == 0 means this is our very first surface, in which case we need
463 * to recalculate the content dimensions even if it happens to be the size
464 * of the initial empty window.
465 */
466 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
d3345a04
PM
467
468 int oldh = screen.height;
469 if (isResize) {
470 // Resize before we trigger the redraw, or we'll redraw at the wrong size
471 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
472 screen.width = w;
473 screen.height = h;
474 [self setContentDimensions];
475 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
476 }
8510d91e 477
c304f7e2
TS
478 // update screenBuffer
479 if (dataProviderRef)
480 CGDataProviderRelease(dataProviderRef);
3b46e624 481
9794f74f 482 //sync host window color space with guests
49060c29
PM
483 screen.bitsPerPixel = surface_bits_per_pixel(surface);
484 screen.bitsPerComponent = surface_bytes_per_pixel(surface) * 2;
9794f74f 485
5e00d3ac 486 dataProviderRef = CGDataProviderCreateWithData(NULL, surface_data(surface), w * 4 * h, NULL);
3b46e624 487
c304f7e2
TS
488 // update windows
489 if (isFullscreen) {
490 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
d3345a04 491 [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
492 } else {
493 if (qemu_name)
494 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
d3345a04
PM
495 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
496 }
497
498 if (isResize) {
499 [normalWindow center];
c304f7e2 500 }
5b0753e0
FB
501}
502
c304f7e2
TS
503- (void) toggleFullScreen:(id)sender
504{
505 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
506
507 if (isFullscreen) { // switch from fullscreen to desktop
508 isFullscreen = FALSE;
509 [self ungrabMouse];
510 [self setContentDimensions];
c304f7e2
TS
511 if ([NSView respondsToSelector:@selector(exitFullScreenModeWithOptions:)]) { // test if "exitFullScreenModeWithOptions" is supported on host at runtime
512 [self exitFullScreenModeWithOptions:nil];
513 } else {
c304f7e2
TS
514 [fullScreenWindow close];
515 [normalWindow setContentView: self];
516 [normalWindow makeKeyAndOrderFront: self];
517 [NSMenu setMenuBarVisible:YES];
c304f7e2 518 }
c304f7e2
TS
519 } else { // switch from desktop to fullscreen
520 isFullscreen = TRUE;
5d1b2eef 521 [normalWindow orderOut: nil]; /* Hide the window */
c304f7e2
TS
522 [self grabMouse];
523 [self setContentDimensions];
c304f7e2
TS
524 if ([NSView respondsToSelector:@selector(enterFullScreenMode:withOptions:)]) { // test if "enterFullScreenMode:withOptions" is supported on host at runtime
525 [self enterFullScreenMode:[NSScreen mainScreen] withOptions:[NSDictionary dictionaryWithObjectsAndKeys:
526 [NSNumber numberWithBool:NO], NSFullScreenModeAllScreens,
527 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], kCGDisplayModeIsStretched, nil], NSFullScreenModeSetting,
528 nil]];
529 } else {
c304f7e2
TS
530 [NSMenu setMenuBarVisible:NO];
531 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
532 styleMask:NSBorderlessWindowMask
533 backing:NSBackingStoreBuffered
534 defer:NO];
5d1b2eef 535 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
c304f7e2 536 [fullScreenWindow setHasShadow:NO];
5d1b2eef
JA
537 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
538 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
539 [[fullScreenWindow contentView] addSubview: self];
c304f7e2 540 [fullScreenWindow makeKeyAndOrderFront:self];
c304f7e2 541 }
c304f7e2
TS
542 }
543}
5b0753e0 544
c304f7e2 545- (void) handleEvent:(NSEvent *)event
3b46e624 546{
c304f7e2
TS
547 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
548
549 int buttons = 0;
550 int keycode;
21bae11a 551 bool mouse_event = false;
c304f7e2
TS
552 NSPoint p = [event locationInWindow];
553
554 switch ([event type]) {
555 case NSFlagsChanged:
556 keycode = cocoa_keycode_to_qemu([event keyCode]);
8895919a 557
49b9bd4d 558 if ((keycode == 219 || keycode == 220) && !isMouseGrabbed) {
8895919a
PM
559 /* Don't pass command key changes to guest unless mouse is grabbed */
560 keycode = 0;
561 }
562
c304f7e2
TS
563 if (keycode) {
564 if (keycode == 58 || keycode == 69) { // emulate caps lock and num lock keydown and keyup
2e08c665
GH
565 qemu_input_event_send_key_number(dcl->con, keycode, true);
566 qemu_input_event_send_key_number(dcl->con, keycode, false);
68c0aa6e 567 } else if (qemu_console_is_graphic(NULL)) {
c304f7e2 568 if (modifiers_state[keycode] == 0) { // keydown
2e08c665 569 qemu_input_event_send_key_number(dcl->con, keycode, true);
c304f7e2
TS
570 modifiers_state[keycode] = 1;
571 } else { // keyup
2e08c665 572 qemu_input_event_send_key_number(dcl->con, keycode, false);
c304f7e2
TS
573 modifiers_state[keycode] = 0;
574 }
575 }
576 }
3b46e624 577
c304f7e2 578 // release Mouse grab when pressing ctrl+alt
5d1b2eef 579 if (([event modifierFlags] & NSControlKeyMask) && ([event modifierFlags] & NSAlternateKeyMask)) {
c304f7e2
TS
580 [self ungrabMouse];
581 }
582 break;
583 case NSKeyDown:
8895919a 584 keycode = cocoa_keycode_to_qemu([event keyCode]);
3b46e624 585
8895919a 586 // forward command key combos to the host UI unless the mouse is grabbed
49b9bd4d 587 if (!isMouseGrabbed && ([event modifierFlags] & NSCommandKeyMask)) {
c304f7e2
TS
588 [NSApp sendEvent:event];
589 return;
590 }
3b46e624 591
c304f7e2 592 // default
c304f7e2
TS
593
594 // handle control + alt Key Combos (ctrl+alt is reserved for QEMU)
595 if (([event modifierFlags] & NSControlKeyMask) && ([event modifierFlags] & NSAlternateKeyMask)) {
596 switch (keycode) {
597
598 // enable graphic console
599 case 0x02 ... 0x0a: // '1' to '9' keys
600 console_select(keycode - 0x02);
601 break;
602 }
603
604 // handle keys for graphic console
68c0aa6e 605 } else if (qemu_console_is_graphic(NULL)) {
2e08c665 606 qemu_input_event_send_key_number(dcl->con, keycode, true);
c304f7e2
TS
607
608 // handlekeys for Monitor
609 } else {
610 int keysym = 0;
611 switch([event keyCode]) {
612 case 115:
613 keysym = QEMU_KEY_HOME;
614 break;
615 case 117:
616 keysym = QEMU_KEY_DELETE;
617 break;
618 case 119:
619 keysym = QEMU_KEY_END;
620 break;
621 case 123:
622 keysym = QEMU_KEY_LEFT;
623 break;
624 case 124:
625 keysym = QEMU_KEY_RIGHT;
626 break;
627 case 125:
628 keysym = QEMU_KEY_DOWN;
629 break;
630 case 126:
631 keysym = QEMU_KEY_UP;
632 break;
633 default:
634 {
635 NSString *ks = [event characters];
636 if ([ks length] > 0)
637 keysym = [ks characterAtIndex:0];
638 }
639 }
640 if (keysym)
641 kbd_put_keysym(keysym);
642 }
643 break;
644 case NSKeyUp:
645 keycode = cocoa_keycode_to_qemu([event keyCode]);
8895919a
PM
646
647 // don't pass the guest a spurious key-up if we treated this
648 // command-key combo as a host UI action
49b9bd4d 649 if (!isMouseGrabbed && ([event modifierFlags] & NSCommandKeyMask)) {
8895919a
PM
650 return;
651 }
652
68c0aa6e 653 if (qemu_console_is_graphic(NULL)) {
2e08c665 654 qemu_input_event_send_key_number(dcl->con, keycode, false);
c304f7e2
TS
655 }
656 break;
657 case NSMouseMoved:
658 if (isAbsoluteEnabled) {
5dd45bee 659 if (![self screenContainsPoint:p] || ![[self window] isKeyWindow]) {
f61c387e
PM
660 if (isMouseGrabbed) {
661 [self ungrabMouse];
c304f7e2
TS
662 }
663 } else {
f61c387e
PM
664 if (!isMouseGrabbed) {
665 [self grabMouse];
c304f7e2
TS
666 }
667 }
5b0753e0 668 }
21bae11a 669 mouse_event = true;
c304f7e2
TS
670 break;
671 case NSLeftMouseDown:
672 if ([event modifierFlags] & NSCommandKeyMask) {
673 buttons |= MOUSE_EVENT_RBUTTON;
674 } else {
675 buttons |= MOUSE_EVENT_LBUTTON;
676 }
21bae11a 677 mouse_event = true;
c304f7e2
TS
678 break;
679 case NSRightMouseDown:
680 buttons |= MOUSE_EVENT_RBUTTON;
21bae11a 681 mouse_event = true;
c304f7e2
TS
682 break;
683 case NSOtherMouseDown:
684 buttons |= MOUSE_EVENT_MBUTTON;
21bae11a 685 mouse_event = true;
c304f7e2
TS
686 break;
687 case NSLeftMouseDragged:
688 if ([event modifierFlags] & NSCommandKeyMask) {
689 buttons |= MOUSE_EVENT_RBUTTON;
690 } else {
691 buttons |= MOUSE_EVENT_LBUTTON;
692 }
21bae11a 693 mouse_event = true;
c304f7e2
TS
694 break;
695 case NSRightMouseDragged:
696 buttons |= MOUSE_EVENT_RBUTTON;
21bae11a 697 mouse_event = true;
c304f7e2
TS
698 break;
699 case NSOtherMouseDragged:
700 buttons |= MOUSE_EVENT_MBUTTON;
21bae11a 701 mouse_event = true;
c304f7e2
TS
702 break;
703 case NSLeftMouseUp:
f61c387e
PM
704 mouse_event = true;
705 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
706 [self grabMouse];
c304f7e2
TS
707 }
708 break;
709 case NSRightMouseUp:
21bae11a 710 mouse_event = true;
c304f7e2
TS
711 break;
712 case NSOtherMouseUp:
21bae11a 713 mouse_event = true;
c304f7e2
TS
714 break;
715 case NSScrollWheel:
f61c387e 716 if (isMouseGrabbed) {
21bae11a
GH
717 buttons |= ([event deltaY] < 0) ?
718 MOUSE_EVENT_WHEELUP : MOUSE_EVENT_WHEELDN;
c304f7e2 719 }
f61c387e 720 mouse_event = true;
c304f7e2
TS
721 break;
722 default:
723 [NSApp sendEvent:event];
5b0753e0 724 }
21bae11a
GH
725
726 if (mouse_event) {
727 if (last_buttons != buttons) {
728 static uint32_t bmap[INPUT_BUTTON_MAX] = {
729 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
730 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
731 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON,
732 [INPUT_BUTTON_WHEEL_UP] = MOUSE_EVENT_WHEELUP,
733 [INPUT_BUTTON_WHEEL_DOWN] = MOUSE_EVENT_WHEELDN,
734 };
735 qemu_input_update_buttons(dcl->con, bmap, last_buttons, buttons);
736 last_buttons = buttons;
737 }
f61c387e
PM
738 if (isMouseGrabbed) {
739 if (isAbsoluteEnabled) {
740 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
741 * The check on screenContainsPoint is to avoid sending out of range values for
742 * clicks in the titlebar.
743 */
744 if ([self screenContainsPoint:p]) {
745 qemu_input_queue_abs(dcl->con, INPUT_AXIS_X, p.x, screen.width);
746 qemu_input_queue_abs(dcl->con, INPUT_AXIS_Y, screen.height - p.y, screen.height);
747 }
748 } else {
749 qemu_input_queue_rel(dcl->con, INPUT_AXIS_X, (int)[event deltaX]);
750 qemu_input_queue_rel(dcl->con, INPUT_AXIS_Y, (int)[event deltaY]);
751 }
21bae11a
GH
752 } else {
753 [NSApp sendEvent:event];
754 }
755 qemu_input_event_sync();
756 }
5b0753e0
FB
757}
758
c304f7e2 759- (void) grabMouse
5b0753e0 760{
c304f7e2 761 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
3b46e624 762
c304f7e2
TS
763 if (!isFullscreen) {
764 if (qemu_name)
765 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt to release Mouse)", qemu_name]];
766 else
767 [normalWindow setTitle:@"QEMU - (Press ctrl + alt to release Mouse)"];
768 }
13aefd30 769 [self hideCursor];
f61c387e
PM
770 if (!isAbsoluteEnabled) {
771 isMouseDeassociated = TRUE;
772 CGAssociateMouseAndMouseCursorPosition(FALSE);
773 }
49b9bd4d 774 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
5b0753e0 775}
3b46e624 776
c304f7e2
TS
777- (void) ungrabMouse
778{
779 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
3b46e624 780
c304f7e2
TS
781 if (!isFullscreen) {
782 if (qemu_name)
783 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
784 else
785 [normalWindow setTitle:@"QEMU"];
786 }
13aefd30 787 [self unhideCursor];
f61c387e
PM
788 if (isMouseDeassociated) {
789 CGAssociateMouseAndMouseCursorPosition(TRUE);
790 isMouseDeassociated = FALSE;
791 }
49b9bd4d 792 isMouseGrabbed = FALSE;
5b0753e0
FB
793}
794
c304f7e2 795- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {isAbsoluteEnabled = tIsAbsoluteEnabled;}
49b9bd4d 796- (BOOL) isMouseGrabbed {return isMouseGrabbed;}
c304f7e2 797- (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
f61c387e 798- (BOOL) isMouseDeassociated {return isMouseDeassociated;}
c304f7e2
TS
799- (float) cdx {return cdx;}
800- (float) cdy {return cdy;}
801- (QEMUScreen) gscreen {return screen;}
3b178b71
JA
802
803/*
804 * Makes the target think all down keys are being released.
805 * This prevents a stuck key problem, since we will not see
806 * key up events for those keys after we have lost focus.
807 */
808- (void) raiseAllKeys
809{
810 int index;
811 const int max_index = ARRAY_SIZE(modifiers_state);
812
813 for (index = 0; index < max_index; index++) {
814 if (modifiers_state[index]) {
815 modifiers_state[index] = 0;
816 qemu_input_event_send_key_number(dcl->con, index, false);
817 }
818 }
819}
5b0753e0
FB
820@end
821
822
c304f7e2 823
5b0753e0
FB
824/*
825 ------------------------------------------------------
c304f7e2 826 QemuCocoaAppController
5b0753e0
FB
827 ------------------------------------------------------
828*/
c304f7e2 829@interface QemuCocoaAppController : NSObject
2a4c8c53 830#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
d9bc14f6 831 <NSWindowDelegate, NSApplicationDelegate>
2a4c8c53 832#endif
5b0753e0
FB
833{
834}
5b0753e0 835- (void)startEmulationWithArgc:(int)argc argv:(char**)argv;
de1aadee 836- (void)openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo;
5d1b2eef 837- (void)doToggleFullScreen:(id)sender;
c304f7e2
TS
838- (void)toggleFullScreen:(id)sender;
839- (void)showQEMUDoc:(id)sender;
840- (void)showQEMUTec:(id)sender;
5d1b2eef 841- (void)zoomToFit:(id) sender;
b4c6a112 842- (void)displayConsole:(id)sender;
8524f1c7
JA
843- (void)pauseQEMU:(id)sender;
844- (void)resumeQEMU:(id)sender;
845- (void)displayPause;
846- (void)removePause;
27074614
JA
847- (void)restartQEMU:(id)sender;
848- (void)powerDownQEMU:(id)sender;
693a3e01
JA
849- (void)ejectDeviceMedia:(id)sender;
850- (void)changeDeviceMedia:(id)sender;
d9bc14f6 851- (BOOL)verifyQuit;
5b0753e0
FB
852@end
853
c304f7e2
TS
854@implementation QemuCocoaAppController
855- (id) init
5b0753e0 856{
c304f7e2 857 COCOA_DEBUG("QemuCocoaAppController: init\n");
5a246934 858
c304f7e2
TS
859 self = [super init];
860 if (self) {
5a246934 861
c304f7e2
TS
862 // create a view and add it to the window
863 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
864 if(!cocoaView) {
865 fprintf(stderr, "(cocoa) can't create a view\n");
866 exit(1);
867 }
3b46e624 868
c304f7e2
TS
869 // create a window
870 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
871 styleMask:NSTitledWindowMask|NSMiniaturizableWindowMask|NSClosableWindowMask
872 backing:NSBackingStoreBuffered defer:NO];
873 if(!normalWindow) {
874 fprintf(stderr, "(cocoa) can't create window\n");
875 exit(1);
876 }
877 [normalWindow setAcceptsMouseMovedEvents:YES];
878 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU"]];
879 [normalWindow setContentView:cocoaView];
81801ae2 880#if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_10)
561ef251 881 [normalWindow useOptimizedDrawing:YES];
81801ae2 882#endif
c304f7e2 883 [normalWindow makeKeyAndOrderFront:self];
49060c29 884 [normalWindow center];
d9bc14f6 885 [normalWindow setDelegate: self];
5d1b2eef 886 stretch_video = false;
8524f1c7
JA
887
888 /* Used for displaying pause on the screen */
889 pauseLabel = [NSTextField new];
890 [pauseLabel setBezeled:YES];
891 [pauseLabel setDrawsBackground:YES];
892 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
893 [pauseLabel setEditable:NO];
894 [pauseLabel setSelectable:NO];
895 [pauseLabel setStringValue: @"Paused"];
896 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
897 [pauseLabel setTextColor: [NSColor blackColor]];
898 [pauseLabel sizeToFit];
693a3e01
JA
899
900 // set the supported image file types that can be opened
901 supportedImageFileTypes = [NSArray arrayWithObjects: @"img", @"iso", @"dmg",
902 @"qcow", @"qcow2", @"cloop", @"vmdk", nil];
c304f7e2
TS
903 }
904 return self;
905}
3b46e624 906
c304f7e2
TS
907- (void) dealloc
908{
909 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
910
911 if (cocoaView)
912 [cocoaView release];
913 [super dealloc];
914}
3b46e624 915
c304f7e2
TS
916- (void)applicationDidFinishLaunching: (NSNotification *) note
917{
918 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
919
49b9bd4d 920 // Display an open dialog box if no arguments were passed or
c304f7e2
TS
921 // if qemu was launched from the finder ( the Finder passes "-psn" )
922 if( gArgc <= 1 || strncmp ((char *)gArgv[1], "-psn", 4) == 0) {
923 NSOpenPanel *op = [[NSOpenPanel alloc] init];
924 [op setPrompt:@"Boot image"];
925 [op setMessage:@"Select the disk image you want to boot.\n\nHit the \"Cancel\" button to quit"];
2ba9de6e 926#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6)
693a3e01 927 [op setAllowedFileTypes:supportedImageFileTypes];
2ba9de6e
PM
928 [op beginSheetModalForWindow:normalWindow
929 completionHandler:^(NSInteger returnCode)
930 { [self openPanelDidEnd:op
931 returnCode:returnCode contextInfo:NULL ]; } ];
932#else
933 // Compatibility code for pre-10.6, using deprecated method
934 [op beginSheetForDirectory:nil file:nil types:filetypes
c304f7e2 935 modalForWindow:normalWindow modalDelegate:self
5b0753e0 936 didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:) contextInfo:NULL];
2ba9de6e 937#endif
c304f7e2 938 } else {
5cbdb3a3 939 // or launch QEMU, with the global args
c304f7e2 940 [self startEmulationWithArgc:gArgc argv:(char **)gArgv];
5a246934 941 }
5b0753e0
FB
942}
943
944- (void)applicationWillTerminate:(NSNotification *)aNotification
945{
c304f7e2
TS
946 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
947
5b0753e0 948 qemu_system_shutdown_request();
5b0753e0
FB
949 exit(0);
950}
951
41ea49b3
AF
952- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
953{
954 return YES;
955}
956
d9bc14f6
JA
957- (NSApplicationTerminateReply)applicationShouldTerminate:
958 (NSApplication *)sender
959{
960 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
961 return [self verifyQuit];
962}
963
964/* Called when the user clicks on a window's close button */
965- (BOOL)windowShouldClose:(id)sender
966{
967 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
968 [NSApp terminate: sender];
969 /* If the user allows the application to quit then the call to
970 * NSApp terminate will never return. If we get here then the user
971 * cancelled the quit, so we should return NO to not permit the
972 * closing of this window.
973 */
974 return NO;
975}
976
3b178b71
JA
977/* Called when QEMU goes into the background */
978- (void) applicationWillResignActive: (NSNotification *)aNotification
979{
980 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
981 [cocoaView raiseAllKeys];
982}
983
c304f7e2
TS
984- (void)startEmulationWithArgc:(int)argc argv:(char**)argv
985{
986 COCOA_DEBUG("QemuCocoaAppController: startEmulationWithArgc\n");
987
988 int status;
3bbbee18 989 status = qemu_main(argc, argv, *_NSGetEnviron());
c304f7e2
TS
990 exit(status);
991}
992
de1aadee 993- (void)openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
5b0753e0 994{
c304f7e2 995 COCOA_DEBUG("QemuCocoaAppController: openPanelDidEnd\n");
3b46e624 996
8617989e
PM
997 /* The NSFileHandlingPanelOKButton/NSFileHandlingPanelCancelButton values for
998 * returnCode strictly only apply for the 10.6-and-up beginSheetModalForWindow
999 * API. For the legacy pre-10.6 beginSheetForDirectory API they are NSOKButton
1000 * and NSCancelButton. However conveniently the values are the same.
1001 * We use the non-legacy names because the others are deprecated in OSX 10.10.
1002 */
1003 if (returnCode == NSFileHandlingPanelCancelButton) {
c304f7e2 1004 exit(0);
8617989e 1005 } else if (returnCode == NSFileHandlingPanelOKButton) {
8bb3f1e3 1006 char *img = (char*)[ [ [ sheet URL ] path ] cStringUsingEncoding:NSASCIIStringEncoding];
3b46e624 1007
98db429d 1008 char **argv = g_new(char *, 4);
3b46e624 1009
13766eb1
AF
1010 [sheet close];
1011
98db429d
PM
1012 argv[0] = g_strdup(gArgv[0]);
1013 argv[1] = g_strdup("-hda");
1014 argv[2] = g_strdup(img);
1015 argv[3] = NULL;
3b46e624 1016
98db429d 1017 // printf("Using argc %d argv %s -hda %s\n", 3, gArgv[0], img);
3b46e624 1018
5b0753e0
FB
1019 [self startEmulationWithArgc:3 argv:(char**)argv];
1020 }
1021}
5d1b2eef
JA
1022
1023/* We abstract the method called by the Enter Fullscreen menu item
1024 * because Mac OS 10.7 and higher disables it. This is because of the
1025 * menu item's old selector's name toggleFullScreen:
1026 */
1027- (void) doToggleFullScreen:(id)sender
1028{
1029 [self toggleFullScreen:(id)sender];
1030}
1031
c304f7e2
TS
1032- (void)toggleFullScreen:(id)sender
1033{
1034 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1035
1036 [cocoaView toggleFullScreen:sender];
1037}
5b0753e0 1038
c304f7e2 1039- (void)showQEMUDoc:(id)sender
5b0753e0 1040{
c304f7e2
TS
1041 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1042
1043 [[NSWorkspace sharedWorkspace] openFile:[NSString stringWithFormat:@"%@/../doc/qemu/qemu-doc.html",
1044 [[NSBundle mainBundle] resourcePath]] withApplication:@"Help Viewer"];
1045}
1046
1047- (void)showQEMUTec:(id)sender
1048{
1049 COCOA_DEBUG("QemuCocoaAppController: showQEMUTec\n");
1050
1051 [[NSWorkspace sharedWorkspace] openFile:[NSString stringWithFormat:@"%@/../doc/qemu/qemu-tech.html",
1052 [[NSBundle mainBundle] resourcePath]] withApplication:@"Help Viewer"];
5b0753e0 1053}
5d1b2eef
JA
1054
1055/* Stretches video to fit host monitor size */
1056- (void)zoomToFit:(id) sender
1057{
1058 stretch_video = !stretch_video;
1059 if (stretch_video == true) {
1060 [sender setState: NSOnState];
1061 } else {
1062 [sender setState: NSOffState];
1063 }
1064}
5b0753e0 1065
b4c6a112
JA
1066/* Displays the console on the screen */
1067- (void)displayConsole:(id)sender
1068{
1069 console_select([sender tag]);
1070}
8524f1c7
JA
1071
1072/* Pause the guest */
1073- (void)pauseQEMU:(id)sender
1074{
1075 qmp_stop(NULL);
1076 [sender setEnabled: NO];
1077 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1078 [self displayPause];
1079}
1080
1081/* Resume running the guest operating system */
1082- (void)resumeQEMU:(id) sender
1083{
1084 qmp_cont(NULL);
1085 [sender setEnabled: NO];
1086 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1087 [self removePause];
1088}
1089
1090/* Displays the word pause on the screen */
1091- (void)displayPause
1092{
1093 /* Coordinates have to be calculated each time because the window can change its size */
1094 int xCoord, yCoord, width, height;
1095 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1096 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1097 width = [pauseLabel frame].size.width;
1098 height = [pauseLabel frame].size.height;
1099 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1100 [cocoaView addSubview: pauseLabel];
1101}
1102
1103/* Removes the word pause from the screen */
1104- (void)removePause
1105{
1106 [pauseLabel removeFromSuperview];
1107}
1108
27074614
JA
1109/* Restarts QEMU */
1110- (void)restartQEMU:(id)sender
1111{
1112 qmp_system_reset(NULL);
1113}
1114
1115/* Powers down QEMU */
1116- (void)powerDownQEMU:(id)sender
1117{
1118 qmp_system_powerdown(NULL);
1119}
1120
693a3e01
JA
1121/* Ejects the media.
1122 * Uses sender's tag to figure out the device to eject.
1123 */
1124- (void)ejectDeviceMedia:(id)sender
1125{
1126 NSString * drive;
1127 drive = [sender representedObject];
1128 if(drive == nil) {
1129 NSBeep();
1130 QEMU_Alert(@"Failed to find drive to eject!");
1131 return;
1132 }
1133
1134 Error *err = NULL;
1135 qmp_eject([drive cStringUsingEncoding: NSASCIIStringEncoding], false, false, &err);
1136 handleAnyDeviceErrors(err);
1137}
1138
1139/* Displays a dialog box asking the user to select an image file to load.
1140 * Uses sender's represented object value to figure out which drive to use.
1141 */
1142- (void)changeDeviceMedia:(id)sender
1143{
1144 /* Find the drive name */
1145 NSString * drive;
1146 drive = [sender representedObject];
1147 if(drive == nil) {
1148 NSBeep();
1149 QEMU_Alert(@"Could not find drive!");
1150 return;
1151 }
1152
1153 /* Display the file open dialog */
1154 NSOpenPanel * openPanel;
1155 openPanel = [NSOpenPanel openPanel];
1156 [openPanel setCanChooseFiles: YES];
1157 [openPanel setAllowsMultipleSelection: NO];
1158 [openPanel setAllowedFileTypes: supportedImageFileTypes];
1159 if([openPanel runModal] == NSFileHandlingPanelOKButton) {
1160 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1161 if(file == nil) {
1162 NSBeep();
1163 QEMU_Alert(@"Failed to convert URL to file path!");
1164 return;
1165 }
1166
1167 Error *err = NULL;
1168 qmp_change_blockdev([drive cStringUsingEncoding: NSASCIIStringEncoding],
1169 [file cStringUsingEncoding: NSASCIIStringEncoding],
1170 "raw",
1171 &err);
1172 handleAnyDeviceErrors(err);
1173 }
1174}
1175
d9bc14f6
JA
1176/* Verifies if the user really wants to quit */
1177- (BOOL)verifyQuit
1178{
1179 NSAlert *alert = [NSAlert new];
1180 [alert autorelease];
1181 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1182 [alert addButtonWithTitle: @"Cancel"];
1183 [alert addButtonWithTitle: @"Quit"];
1184 if([alert runModal] == NSAlertSecondButtonReturn) {
1185 return YES;
1186 } else {
1187 return NO;
1188 }
1189}
1190
b4c6a112 1191@end
5b0753e0 1192
c304f7e2 1193
c304f7e2 1194int main (int argc, const char * argv[]) {
5b0753e0 1195
c304f7e2
TS
1196 gArgc = argc;
1197 gArgv = (char **)argv;
f4918804
AF
1198 int i;
1199
1200 /* In case we don't need to display a window, let's not do that */
1201 for (i = 1; i < argc; i++) {
e4ebcc1a
TG
1202 const char *opt = argv[i];
1203
1204 if (opt[0] == '-') {
1205 /* Treat --foo the same as -foo. */
1206 if (opt[1] == '-') {
1207 opt++;
1208 }
9851484f
AR
1209 if (!strcmp(opt, "-h") || !strcmp(opt, "-help") ||
1210 !strcmp(opt, "-vnc") ||
e4ebcc1a
TG
1211 !strcmp(opt, "-nographic") ||
1212 !strcmp(opt, "-version") ||
60b46aa2 1213 !strcmp(opt, "-curses") ||
b12a84ce 1214 !strcmp(opt, "-display") ||
60b46aa2 1215 !strcmp(opt, "-qtest")) {
3bbbee18 1216 return qemu_main(gArgc, gArgv, *_NSGetEnviron());
e4ebcc1a 1217 }
f4918804
AF
1218 }
1219 }
5b0753e0 1220
c304f7e2 1221 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
5b0753e0 1222
42a5dfe7
PM
1223 // Pull this console process up to being a fully-fledged graphical
1224 // app with a menubar and Dock icon
1225 ProcessSerialNumber psn = { 0, kCurrentProcess };
1226 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1227
1228 [NSApplication sharedApplication];
5b0753e0 1229
c304f7e2
TS
1230 // Add menus
1231 NSMenu *menu;
1232 NSMenuItem *menuItem;
5b0753e0 1233
c304f7e2 1234 [NSApp setMainMenu:[[NSMenu alloc] init]];
5b0753e0 1235
c304f7e2
TS
1236 // Application menu
1237 menu = [[NSMenu alloc] initWithTitle:@""];
1238 [menu addItemWithTitle:@"About QEMU" action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""]; // About QEMU
1239 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1240 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1241 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1242 [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
1243 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1244 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1245 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1246 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1247 [menuItem setSubmenu:menu];
1248 [[NSApp mainMenu] addItem:menuItem];
1249 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
3b46e624 1250
8524f1c7
JA
1251 // Machine menu
1252 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1253 [menu setAutoenablesItems: NO];
1254 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1255 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1256 [menu addItem: menuItem];
1257 [menuItem setEnabled: NO];
27074614
JA
1258 [menu addItem: [NSMenuItem separatorItem]];
1259 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1260 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
8524f1c7
JA
1261 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1262 [menuItem setSubmenu:menu];
1263 [[NSApp mainMenu] addItem:menuItem];
1264
c304f7e2
TS
1265 // View menu
1266 menu = [[NSMenu alloc] initWithTitle:@"View"];
5d1b2eef
JA
1267 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1268 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
c304f7e2
TS
1269 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1270 [menuItem setSubmenu:menu];
5b0753e0
FB
1271 [[NSApp mainMenu] addItem:menuItem];
1272
c304f7e2
TS
1273 // Window menu
1274 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1275 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1276 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1277 [menuItem setSubmenu:menu];
1278 [[NSApp mainMenu] addItem:menuItem];
1279 [NSApp setWindowsMenu:menu];
1280
1281 // Help menu
1282 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1283 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1284 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Technology" action:@selector(showQEMUTec:) keyEquivalent:@""] autorelease]]; // QEMU Help
1285 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1286 [menuItem setSubmenu:menu];
1287 [[NSApp mainMenu] addItem:menuItem];
5b0753e0 1288
c304f7e2
TS
1289 // Create an Application controller
1290 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1291 [NSApp setDelegate:appController];
5b0753e0 1292
c304f7e2
TS
1293 // Start the main event loop
1294 [NSApp run];
5b0753e0 1295
c304f7e2
TS
1296 [appController release];
1297 [pool release];
3b46e624 1298
c304f7e2
TS
1299 return 0;
1300}
3b46e624 1301
3b46e624 1302
5b0753e0 1303
c304f7e2 1304#pragma mark qemu
7c20b4a3 1305static void cocoa_update(DisplayChangeListener *dcl,
7c20b4a3 1306 int x, int y, int w, int h)
c304f7e2 1307{
6e657e64
PM
1308 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1309
c304f7e2
TS
1310 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1311
1312 NSRect rect;
1313 if ([cocoaView cdx] == 1.0) {
1314 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1315 } else {
1316 rect = NSMakeRect(
1317 x * [cocoaView cdx],
1318 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1319 w * [cocoaView cdx],
1320 h * [cocoaView cdy]);
1321 }
17ccbc27 1322 [cocoaView setNeedsDisplayInRect:rect];
6e657e64
PM
1323
1324 [pool release];
5b0753e0
FB
1325}
1326
c12aeb86 1327static void cocoa_switch(DisplayChangeListener *dcl,
c12aeb86 1328 DisplaySurface *surface)
5b0753e0 1329{
6e657e64 1330 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
3b46e624 1331
6e657e64 1332 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
5e00d3ac 1333 [cocoaView switchSurface:surface];
6e657e64 1334 [pool release];
c304f7e2 1335}
3b46e624 1336
bc2ed970 1337static void cocoa_refresh(DisplayChangeListener *dcl)
c304f7e2 1338{
6e657e64
PM
1339 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1340
c304f7e2 1341 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
3b46e624 1342
21bae11a 1343 if (qemu_input_is_absolute()) {
c304f7e2 1344 if (![cocoaView isAbsoluteEnabled]) {
49b9bd4d 1345 if ([cocoaView isMouseGrabbed]) {
c304f7e2
TS
1346 [cocoaView ungrabMouse];
1347 }
1348 }
1349 [cocoaView setAbsoluteEnabled:YES];
1350 }
5b0753e0 1351
c304f7e2
TS
1352 NSDate *distantPast;
1353 NSEvent *event;
1354 distantPast = [NSDate distantPast];
1355 do {
1356 event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:distantPast
1357 inMode: NSDefaultRunLoopMode dequeue:YES];
1358 if (event != nil) {
1359 [cocoaView handleEvent:event];
1360 }
1361 } while(event != nil);
68c0aa6e 1362 graphic_hw_update(NULL);
6e657e64 1363 [pool release];
c304f7e2 1364}
3b46e624 1365
c304f7e2
TS
1366static void cocoa_cleanup(void)
1367{
1368 COCOA_DEBUG("qemu_cocoa: cocoa_cleanup\n");
58a06675 1369 g_free(dcl);
5b0753e0
FB
1370}
1371
7c20b4a3
GH
1372static const DisplayChangeListenerOps dcl_ops = {
1373 .dpy_name = "cocoa",
8510d91e
PM
1374 .dpy_gfx_update = cocoa_update,
1375 .dpy_gfx_switch = cocoa_switch,
1376 .dpy_refresh = cocoa_refresh,
7c20b4a3
GH
1377};
1378
b4c6a112
JA
1379/* Returns a name for a given console */
1380static NSString * getConsoleName(QemuConsole * console)
1381{
1382 return [NSString stringWithFormat: @"%s", qemu_console_get_label(console)];
1383}
1384
1385/* Add an entry to the View menu for each console */
1386static void add_console_menu_entries(void)
1387{
1388 NSMenu *menu;
1389 NSMenuItem *menuItem;
1390 int index = 0;
1391
1392 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1393
1394 [menu addItem:[NSMenuItem separatorItem]];
1395
1396 while (qemu_console_lookup_by_index(index) != NULL) {
1397 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1398 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1399 [menuItem setTag: index];
1400 [menu addItem: menuItem];
1401 index++;
1402 }
1403}
1404
693a3e01
JA
1405/* Make menu items for all removable devices.
1406 * Each device is given an 'Eject' and 'Change' menu item.
1407 */
1408static void addRemovableDevicesMenuItems()
1409{
1410 NSMenu *menu;
1411 NSMenuItem *menuItem;
1412 BlockInfoList *currentDevice, *pointerToFree;
1413 NSString *deviceName;
1414
1415 currentDevice = qmp_query_block(NULL);
1416 pointerToFree = currentDevice;
1417 if(currentDevice == NULL) {
1418 NSBeep();
1419 QEMU_Alert(@"Failed to query for block devices!");
1420 return;
1421 }
1422
1423 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1424
1425 // Add a separator between related groups of menu items
1426 [menu addItem:[NSMenuItem separatorItem]];
1427
1428 // Set the attributes to the "Removable Media" menu item
1429 NSString *titleString = @"Removable Media";
1430 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1431 NSColor *newColor = [NSColor blackColor];
1432 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1433 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1434 traits:NSBoldFontMask|NSItalicFontMask
1435 weight:0
1436 size:14];
1437 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1438 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1439 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1440
1441 // Add the "Removable Media" menu item
1442 menuItem = [NSMenuItem new];
1443 [menuItem setAttributedTitle: attString];
1444 [menuItem setEnabled: NO];
1445 [menu addItem: menuItem];
1446
1447 /* Loop thru all the block devices in the emulator */
1448 while (currentDevice) {
1449 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1450
1451 if(currentDevice->value->removable) {
1452 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1453 action: @selector(changeDeviceMedia:)
1454 keyEquivalent: @""];
1455 [menu addItem: menuItem];
1456 [menuItem setRepresentedObject: deviceName];
1457 [menuItem autorelease];
1458
1459 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1460 action: @selector(ejectDeviceMedia:)
1461 keyEquivalent: @""];
1462 [menu addItem: menuItem];
1463 [menuItem setRepresentedObject: deviceName];
1464 [menuItem autorelease];
1465 }
1466 currentDevice = currentDevice->next;
1467 }
1468 qapi_free_BlockInfoList(pointerToFree);
1469}
1470
c304f7e2 1471void cocoa_display_init(DisplayState *ds, int full_screen)
5b0753e0 1472{
c304f7e2
TS
1473 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
1474
43227af8
JA
1475 /* if fullscreen mode is to be used */
1476 if (full_screen == true) {
1477 [NSApp activateIgnoringOtherApps: YES];
1478 [(QemuCocoaAppController *)[[NSApplication sharedApplication] delegate] toggleFullScreen: nil];
1479 }
1480
58a06675
BS
1481 dcl = g_malloc0(sizeof(DisplayChangeListener));
1482
9794f74f 1483 // register vga output callbacks
7c20b4a3 1484 dcl->ops = &dcl_ops;
5209089f 1485 register_displaychangelistener(dcl);
cae41b10 1486
c304f7e2
TS
1487 // register cleanup function
1488 atexit(cocoa_cleanup);
b4c6a112
JA
1489
1490 /* At this point QEMU has created all the consoles, so we can add View
1491 * menu entries for them.
1492 */
1493 add_console_menu_entries();
693a3e01
JA
1494
1495 /* Give all removable devices a menu item.
1496 * Has to be called after QEMU has started to
1497 * find out what removable devices it has.
1498 */
1499 addRemovableDevicesMenuItems();
5b0753e0 1500}
This page took 0.908834 seconds and 4 git commands to generate.