]> git.proxmox.com Git - mirror_qemu.git/blame - ui/cocoa.m
qapi block: Elide redundant has_FOO in generated C
[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
49f95221 30#include "qemu/help-texts.h"
88c39c86 31#include "qemu-main.h"
7e3e20d8 32#include "ui/clipboard.h"
28ecbaee 33#include "ui/console.h"
21bae11a 34#include "ui/input.h"
6d73bb64 35#include "ui/kbd-state.h"
9c17d615 36#include "sysemu/sysemu.h"
54d31236 37#include "sysemu/runstate.h"
2910abd6 38#include "sysemu/runstate-action.h"
b0c3cf94 39#include "sysemu/cpu-throttle.h"
e688df6b 40#include "qapi/error.h"
16bf5234 41#include "qapi/qapi-commands-block.h"
90f8c0f9 42#include "qapi/qapi-commands-machine.h"
16bf5234 43#include "qapi/qapi-commands-misc.h"
693a3e01 44#include "sysemu/blockdev.h"
9e8204b1 45#include "qemu-version.h"
e31746ec 46#include "qemu/cutils.h"
db725815 47#include "qemu/main-loop.h"
0b8fa32f 48#include "qemu/module.h"
aaac714f 49#include <Carbon/Carbon.h>
2e5b09fd 50#include "hw/core/cpu.h"
da4dbf74 51
5e24600a
BS
52#ifndef MAC_OS_X_VERSION_10_13
53#define MAC_OS_X_VERSION_10_13 101300
54#endif
44e4c0ba 55
5e24600a
BS
56/* 10.14 deprecates NSOnState and NSOffState in favor of
57 * NSControlStateValueOn/Off, which were introduced in 10.13.
58 * Define for older versions
59 */
60#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
61#define NSControlStateValueOn NSOnState
62#define NSControlStateValueOff NSOffState
63#endif
3b46e624 64
c304f7e2 65//#define DEBUG
3b46e624 66
c304f7e2
TS
67#ifdef DEBUG
68#define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
b29169d2 69#else
c304f7e2 70#define COCOA_DEBUG(...) ((void) 0)
b29169d2
BS
71#endif
72
c304f7e2 73#define cgrect(nsrect) (*(CGRect *)&(nsrect))
5b0753e0 74
c304f7e2
TS
75typedef struct {
76 int width;
77 int height;
c304f7e2
TS
78} QEMUScreen;
79
cc7859c3
AO
80static void cocoa_update(DisplayChangeListener *dcl,
81 int x, int y, int w, int h);
82
83static void cocoa_switch(DisplayChangeListener *dcl,
84 DisplaySurface *surface);
85
86static void cocoa_refresh(DisplayChangeListener *dcl);
87
99eb313d 88static NSWindow *normalWindow;
cc7859c3
AO
89static const DisplayChangeListenerOps dcl_ops = {
90 .dpy_name = "cocoa",
91 .dpy_gfx_update = cocoa_update,
92 .dpy_gfx_switch = cocoa_switch,
93 .dpy_refresh = cocoa_refresh,
94};
95static DisplayChangeListener dcl = {
96 .ops = &dcl_ops,
97};
21bae11a 98static int last_buttons;
3487da6a 99static int cursor_hide = 1;
48941a52 100static int left_command_key_enabled = 1;
4797adce 101static bool swap_opt_cmd;
c304f7e2 102
cb823408
AO
103static bool stretch_video;
104static NSTextField *pauseLabel;
5b0753e0 105
dff742ad 106static bool allow_events;
5588840f 107
7e3e20d8
AO
108static NSInteger cbchangecount = -1;
109static QemuClipboardInfo *cbinfo;
110static QemuEvent cbevent;
111
60105d7a 112// Utility functions to run specified code block with iothread lock held
31819e95 113typedef void (^CodeBlock)(void);
60105d7a 114typedef bool (^BoolCodeBlock)(void);
31819e95
PM
115
116static void with_iothread_lock(CodeBlock block)
117{
118 bool locked = qemu_mutex_iothread_locked();
119 if (!locked) {
120 qemu_mutex_lock_iothread();
121 }
122 block();
123 if (!locked) {
124 qemu_mutex_unlock_iothread();
125 }
126}
127
60105d7a
PM
128static bool bool_with_iothread_lock(BoolCodeBlock block)
129{
130 bool locked = qemu_mutex_iothread_locked();
131 bool val;
132
133 if (!locked) {
134 qemu_mutex_lock_iothread();
135 }
136 val = block();
137 if (!locked) {
138 qemu_mutex_unlock_iothread();
139 }
140 return val;
141}
142
aaac714f 143// Mac to QKeyCode conversion
cb823408 144static const int mac_to_qkeycode_map[] = {
aaac714f
JA
145 [kVK_ANSI_A] = Q_KEY_CODE_A,
146 [kVK_ANSI_B] = Q_KEY_CODE_B,
147 [kVK_ANSI_C] = Q_KEY_CODE_C,
148 [kVK_ANSI_D] = Q_KEY_CODE_D,
149 [kVK_ANSI_E] = Q_KEY_CODE_E,
150 [kVK_ANSI_F] = Q_KEY_CODE_F,
151 [kVK_ANSI_G] = Q_KEY_CODE_G,
152 [kVK_ANSI_H] = Q_KEY_CODE_H,
153 [kVK_ANSI_I] = Q_KEY_CODE_I,
154 [kVK_ANSI_J] = Q_KEY_CODE_J,
155 [kVK_ANSI_K] = Q_KEY_CODE_K,
156 [kVK_ANSI_L] = Q_KEY_CODE_L,
157 [kVK_ANSI_M] = Q_KEY_CODE_M,
158 [kVK_ANSI_N] = Q_KEY_CODE_N,
159 [kVK_ANSI_O] = Q_KEY_CODE_O,
160 [kVK_ANSI_P] = Q_KEY_CODE_P,
161 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
162 [kVK_ANSI_R] = Q_KEY_CODE_R,
163 [kVK_ANSI_S] = Q_KEY_CODE_S,
164 [kVK_ANSI_T] = Q_KEY_CODE_T,
165 [kVK_ANSI_U] = Q_KEY_CODE_U,
166 [kVK_ANSI_V] = Q_KEY_CODE_V,
167 [kVK_ANSI_W] = Q_KEY_CODE_W,
168 [kVK_ANSI_X] = Q_KEY_CODE_X,
169 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
170 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
171
172 [kVK_ANSI_0] = Q_KEY_CODE_0,
173 [kVK_ANSI_1] = Q_KEY_CODE_1,
174 [kVK_ANSI_2] = Q_KEY_CODE_2,
175 [kVK_ANSI_3] = Q_KEY_CODE_3,
176 [kVK_ANSI_4] = Q_KEY_CODE_4,
177 [kVK_ANSI_5] = Q_KEY_CODE_5,
178 [kVK_ANSI_6] = Q_KEY_CODE_6,
179 [kVK_ANSI_7] = Q_KEY_CODE_7,
180 [kVK_ANSI_8] = Q_KEY_CODE_8,
181 [kVK_ANSI_9] = Q_KEY_CODE_9,
182
183 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
184 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
185 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
186 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
187 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
188 [kVK_Tab] = Q_KEY_CODE_TAB,
189 [kVK_Return] = Q_KEY_CODE_RET,
190 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
191 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
192 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
193 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
194 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
195 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
196 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
197 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
aaac714f
JA
198 [kVK_Space] = Q_KEY_CODE_SPC,
199
200 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
201 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
202 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
203 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
204 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
205 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
206 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
207 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
208 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
209 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
210 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
211 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
212 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
213 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
214 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
215 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
216 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
217 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
218
219 [kVK_UpArrow] = Q_KEY_CODE_UP,
220 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
221 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
222 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
223
224 [kVK_Help] = Q_KEY_CODE_INSERT,
225 [kVK_Home] = Q_KEY_CODE_HOME,
226 [kVK_PageUp] = Q_KEY_CODE_PGUP,
227 [kVK_PageDown] = Q_KEY_CODE_PGDN,
228 [kVK_End] = Q_KEY_CODE_END,
229 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
230
231 [kVK_Escape] = Q_KEY_CODE_ESC,
232
233 /* The Power key can't be used directly because the operating system uses
234 * it. This key can be emulated by using it in place of another key such as
235 * F1. Don't forget to disable the real key binding.
236 */
237 /* [kVK_F1] = Q_KEY_CODE_POWER, */
238
239 [kVK_F1] = Q_KEY_CODE_F1,
240 [kVK_F2] = Q_KEY_CODE_F2,
241 [kVK_F3] = Q_KEY_CODE_F3,
242 [kVK_F4] = Q_KEY_CODE_F4,
243 [kVK_F5] = Q_KEY_CODE_F5,
244 [kVK_F6] = Q_KEY_CODE_F6,
245 [kVK_F7] = Q_KEY_CODE_F7,
246 [kVK_F8] = Q_KEY_CODE_F8,
247 [kVK_F9] = Q_KEY_CODE_F9,
248 [kVK_F10] = Q_KEY_CODE_F10,
249 [kVK_F11] = Q_KEY_CODE_F11,
250 [kVK_F12] = Q_KEY_CODE_F12,
251 [kVK_F13] = Q_KEY_CODE_PRINT,
252 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
253 [kVK_F15] = Q_KEY_CODE_PAUSE,
254
708b7255
AO
255 // JIS keyboards only
256 [kVK_JIS_Yen] = Q_KEY_CODE_YEN,
257 [kVK_JIS_Underscore] = Q_KEY_CODE_RO,
258 [kVK_JIS_KeypadComma] = Q_KEY_CODE_KP_COMMA,
259 [kVK_JIS_Eisu] = Q_KEY_CODE_MUHENKAN,
260 [kVK_JIS_Kana] = Q_KEY_CODE_HENKAN,
261
aaac714f
JA
262 /*
263 * The eject and volume keys can't be used here because they are handled at
264 * a lower level than what an Application can see.
265 */
5b0753e0
FB
266};
267
77047bb7 268static int cocoa_keycode_to_qemu(int keycode)
5b0753e0 269{
aaac714f 270 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
4313739a 271 error_report("(cocoa) warning unknown keycode 0x%x", keycode);
5b0753e0
FB
272 return 0;
273 }
aaac714f 274 return mac_to_qkeycode_map[keycode];
5b0753e0
FB
275}
276
693a3e01
JA
277/* Displays an alert dialog box with the specified message */
278static void QEMU_Alert(NSString *message)
279{
280 NSAlert *alert;
281 alert = [NSAlert new];
282 [alert setMessageText: message];
283 [alert runModal];
284}
c304f7e2 285
693a3e01
JA
286/* Handles any errors that happen with a device transaction */
287static void handleAnyDeviceErrors(Error * err)
288{
289 if (err) {
290 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
291 encoding: NSASCIIStringEncoding]);
292 error_free(err);
293 }
294}
c304f7e2 295
5b0753e0
FB
296/*
297 ------------------------------------------------------
c304f7e2 298 QemuCocoaView
5b0753e0
FB
299 ------------------------------------------------------
300*/
c304f7e2 301@interface QemuCocoaView : NSView
5b0753e0 302{
c304f7e2
TS
303 QEMUScreen screen;
304 NSWindow *fullScreenWindow;
305 float cx,cy,cw,ch,cdx,cdy;
5588840f 306 pixman_image_t *pixman_image;
6d73bb64 307 QKbdState *kbd;
49b9bd4d 308 BOOL isMouseGrabbed;
c304f7e2
TS
309 BOOL isFullscreen;
310 BOOL isAbsoluteEnabled;
f844cdb9 311 CFMachPortRef eventsTap;
c304f7e2 312}
72a3e316 313- (void) switchSurface:(pixman_image_t *)image;
c304f7e2
TS
314- (void) grabMouse;
315- (void) ungrabMouse;
316- (void) toggleFullScreen:(id)sender;
f844cdb9 317- (void) setFullGrab:(id)sender;
9c3a418e 318- (void) handleMonitorInput:(NSEvent *)event;
60105d7a
PM
319- (bool) handleEvent:(NSEvent *)event;
320- (bool) handleEventLocked:(NSEvent *)event;
c304f7e2 321- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
f61c387e
PM
322/* The state surrounding mouse grabbing is potentially confusing.
323 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
324 * pointing device an absolute-position one?"], but is only updated on
325 * next refresh.
326 * isMouseGrabbed tracks whether GUI events are directed to the guest;
327 * it controls whether special keys like Cmd get sent to the guest,
328 * and whether we capture the mouse when in non-absolute mode.
f61c387e 329 */
49b9bd4d 330- (BOOL) isMouseGrabbed;
c304f7e2
TS
331- (BOOL) isAbsoluteEnabled;
332- (float) cdx;
333- (float) cdy;
334- (QEMUScreen) gscreen;
3b178b71 335- (void) raiseAllKeys;
c304f7e2 336@end
3b46e624 337
7fee199c
AF
338QemuCocoaView *cocoaView;
339
f844cdb9
GNS
340static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEventRef cgEvent, void *userInfo)
341{
342 QemuCocoaView *cocoaView = userInfo;
343 NSEvent *event = [NSEvent eventWithCGEvent:cgEvent];
344 if ([cocoaView isMouseGrabbed] && [cocoaView handleEvent:event]) {
345 COCOA_DEBUG("Global events tap: qemu handled the event, capturing!\n");
346 return NULL;
347 }
348 COCOA_DEBUG("Global events tap: qemu did not handle the event, letting it through...\n");
349
350 return cgEvent;
351}
352
c304f7e2
TS
353@implementation QemuCocoaView
354- (id)initWithFrame:(NSRect)frameRect
355{
356 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
3b46e624 357
c304f7e2
TS
358 self = [super initWithFrame:frameRect];
359 if (self) {
3b46e624 360
c304f7e2
TS
361 screen.width = frameRect.size.width;
362 screen.height = frameRect.size.height;
6d73bb64 363 kbd = qkbd_state_init(dcl.con);
3b46e624 364
c304f7e2
TS
365 }
366 return self;
367}
3b46e624 368
c304f7e2
TS
369- (void) dealloc
370{
371 COCOA_DEBUG("QemuCocoaView: dealloc\n");
3b46e624 372
c0ff29d1 373 if (pixman_image) {
5588840f
PM
374 pixman_image_unref(pixman_image);
375 }
3b46e624 376
6d73bb64 377 qkbd_state_free(kbd);
f844cdb9
GNS
378
379 if (eventsTap) {
380 CFRelease(eventsTap);
381 }
382
c304f7e2
TS
383 [super dealloc];
384}
3b46e624 385
d50f71dc
AF
386- (BOOL) isOpaque
387{
388 return YES;
389}
390
5dd45bee
PM
391- (BOOL) screenContainsPoint:(NSPoint) p
392{
393 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
394}
395
2044dff8
CZ
396/* Get location of event and convert to virtual screen coordinate */
397- (CGPoint) screenLocationOfEvent:(NSEvent *)ev
398{
399 NSWindow *eventWindow = [ev window];
400 // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
401 CGRect r = CGRectZero;
402 r.origin = [ev locationInWindow];
403 if (!eventWindow) {
404 if (!isFullscreen) {
405 return [[self window] convertRectFromScreen:r].origin;
406 } else {
407 CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
408 CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
409 if (stretch_video) {
410 loc.x /= cdx;
411 loc.y /= cdy;
412 }
413 return loc;
414 }
415 } else if ([[self window] isEqual:eventWindow]) {
416 if (!isFullscreen) {
417 return r.origin;
418 } else {
419 CGPoint loc = [self convertPoint:r.origin fromView:nil];
420 if (stretch_video) {
421 loc.x /= cdx;
422 loc.y /= cdy;
423 }
424 return loc;
425 }
426 } else {
427 return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
428 }
429}
430
13aefd30
PM
431- (void) hideCursor
432{
433 if (!cursor_hide) {
434 return;
435 }
436 [NSCursor hide];
437}
438
439- (void) unhideCursor
440{
441 if (!cursor_hide) {
442 return;
443 }
444 [NSCursor unhide];
445}
446
c304f7e2
TS
447- (void) drawRect:(NSRect) rect
448{
449 COCOA_DEBUG("QemuCocoaView: drawRect\n");
450
c304f7e2 451 // get CoreGraphic context
5e24600a 452 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
5e24600a 453
c304f7e2
TS
454 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
455 CGContextSetShouldAntialias (viewContextRef, NO);
456
457 // draw screen bitmap directly to Core Graphics context
c0ff29d1 458 if (!pixman_image) {
7d270b1c
PM
459 // Draw request before any guest device has set up a framebuffer:
460 // just draw an opaque black rectangle
461 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
462 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
463 } else {
c0ff29d1
AO
464 int w = pixman_image_get_width(pixman_image);
465 int h = pixman_image_get_height(pixman_image);
466 int bitsPerPixel = PIXMAN_FORMAT_BPP(pixman_image_get_format(pixman_image));
d9c32b8f 467 int stride = pixman_image_get_stride(pixman_image);
c0ff29d1
AO
468 CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(
469 NULL,
470 pixman_image_get_data(pixman_image),
d9c32b8f 471 stride * h,
c0ff29d1
AO
472 NULL
473 );
c304f7e2 474 CGImageRef imageRef = CGImageCreate(
c0ff29d1
AO
475 w, //width
476 h, //height
d9c32b8f 477 DIV_ROUND_UP(bitsPerPixel, 8) * 2, //bitsPerComponent
c0ff29d1 478 bitsPerPixel, //bitsPerPixel
d9c32b8f 479 stride, //bytesPerRow
ae57d35c
AO
480 CGColorSpaceCreateWithName(kCGColorSpaceSRGB), //colorspace
481 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst, //bitmapInfo
c304f7e2
TS
482 dataProviderRef, //provider
483 NULL, //decode
484 0, //interpolate
485 kCGRenderingIntentDefault //intent
486 );
b63901d8
PM
487 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
488 const NSRect *rectList;
b63901d8 489 NSInteger rectCount;
b63901d8
PM
490 int i;
491 CGImageRef clipImageRef;
492 CGRect clipRect;
493
494 [self getRectsBeingDrawn:&rectList count:&rectCount];
495 for (i = 0; i < rectCount; i++) {
496 clipRect.origin.x = rectList[i].origin.x / cdx;
c0ff29d1 497 clipRect.origin.y = (float)h - (rectList[i].origin.y + rectList[i].size.height) / cdy;
b63901d8
PM
498 clipRect.size.width = rectList[i].size.width / cdx;
499 clipRect.size.height = rectList[i].size.height / cdy;
500 clipImageRef = CGImageCreateWithImageInRect(
501 imageRef,
502 clipRect
503 );
504 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
505 CGImageRelease (clipImageRef);
5b0753e0 506 }
c304f7e2 507 CGImageRelease (imageRef);
c0ff29d1 508 CGDataProviderRelease(dataProviderRef);
c304f7e2 509 }
5b0753e0
FB
510}
511
c304f7e2 512- (void) setContentDimensions
5b0753e0 513{
c304f7e2
TS
514 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
515
516 if (isFullscreen) {
517 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
518 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
5d1b2eef
JA
519
520 /* stretches video, but keeps same aspect ratio */
521 if (stretch_video == true) {
522 /* use smallest stretch value - prevents clipping on sides */
523 if (MIN(cdx, cdy) == cdx) {
524 cdy = cdx;
525 } else {
526 cdx = cdy;
527 }
528 } else { /* No stretching */
529 cdx = cdy = 1;
530 }
c304f7e2
TS
531 cw = screen.width * cdx;
532 ch = screen.height * cdy;
533 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
534 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
535 } else {
536 cx = 0;
537 cy = 0;
538 cw = screen.width;
539 ch = screen.height;
540 cdx = 1.0;
541 cdy = 1.0;
542 }
5b0753e0
FB
543}
544
8d65dee2 545- (void) updateUIInfoLocked
15280e85 546{
8d65dee2 547 /* Must be called with the iothread lock, i.e. via updateUIInfo */
15280e85
AO
548 NSSize frameSize;
549 QemuUIInfo info;
550
551 if (!qemu_console_is_graphic(dcl.con)) {
552 return;
553 }
554
555 if ([self window]) {
556 NSDictionary *description = [[[self window] screen] deviceDescription];
557 CGDirectDisplayID display = [[description objectForKey:@"NSScreenNumber"] unsignedIntValue];
558 NSSize screenSize = [[[self window] screen] frame].size;
559 CGSize screenPhysicalSize = CGDisplayScreenSize(display);
52eaefd3 560 CVDisplayLinkRef displayLink;
15280e85
AO
561
562 frameSize = isFullscreen ? screenSize : [self frame].size;
52eaefd3
AO
563
564 if (!CVDisplayLinkCreateWithCGDisplay(display, &displayLink)) {
565 CVTime period = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLink);
566 CVDisplayLinkRelease(displayLink);
567 if (!(period.flags & kCVTimeIsIndefinite)) {
568 update_displaychangelistener(&dcl,
569 1000 * period.timeValue / period.timeScale);
570 info.refresh_rate = (int64_t)1000 * period.timeScale / period.timeValue;
571 }
572 }
573
15280e85
AO
574 info.width_mm = frameSize.width / screenSize.width * screenPhysicalSize.width;
575 info.height_mm = frameSize.height / screenSize.height * screenPhysicalSize.height;
576 } else {
577 frameSize = [self frame].size;
578 info.width_mm = 0;
579 info.height_mm = 0;
580 }
581
582 info.xoff = 0;
583 info.yoff = 0;
584 info.width = frameSize.width;
585 info.height = frameSize.height;
586
ca19ef52 587 dpy_set_ui_info(dcl.con, &info, TRUE);
15280e85
AO
588}
589
8d65dee2
PM
590- (void) updateUIInfo
591{
592 if (!allow_events) {
593 /*
594 * Don't try to tell QEMU about UI information in the application
595 * startup phase -- we haven't yet registered dcl with the QEMU UI
bab6a301 596 * layer.
8d65dee2
PM
597 * When cocoa_display_init() does register the dcl, the UI layer
598 * will call cocoa_switch(), which will call updateUIInfo, so
599 * we don't lose any information here.
600 */
601 return;
602 }
603
604 with_iothread_lock(^{
605 [self updateUIInfoLocked];
606 });
607}
608
15280e85
AO
609- (void)viewDidMoveToWindow
610{
611 [self updateUIInfo];
612}
613
72a3e316 614- (void) switchSurface:(pixman_image_t *)image
5b0753e0 615{
5e00d3ac 616 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
c304f7e2 617
72a3e316
PM
618 int w = pixman_image_get_width(image);
619 int h = pixman_image_get_height(image);
381600da
PM
620 /* cdx == 0 means this is our very first surface, in which case we need
621 * to recalculate the content dimensions even if it happens to be the size
622 * of the initial empty window.
623 */
624 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
d3345a04
PM
625
626 int oldh = screen.height;
627 if (isResize) {
628 // Resize before we trigger the redraw, or we'll redraw at the wrong size
629 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
630 screen.width = w;
631 screen.height = h;
632 [self setContentDimensions];
633 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
634 }
8510d91e 635
c304f7e2 636 // update screenBuffer
c0ff29d1 637 if (pixman_image) {
5588840f
PM
638 pixman_image_unref(pixman_image);
639 }
3b46e624 640
5588840f 641 pixman_image = image;
3b46e624 642
c304f7e2
TS
643 // update windows
644 if (isFullscreen) {
645 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
d3345a04 646 [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
647 } else {
648 if (qemu_name)
649 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
d3345a04
PM
650 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
651 }
652
653 if (isResize) {
654 [normalWindow center];
c304f7e2 655 }
5b0753e0
FB
656}
657
c304f7e2
TS
658- (void) toggleFullScreen:(id)sender
659{
660 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
661
662 if (isFullscreen) { // switch from fullscreen to desktop
663 isFullscreen = FALSE;
664 [self ungrabMouse];
665 [self setContentDimensions];
1e8b6f2b
AO
666 [fullScreenWindow close];
667 [normalWindow setContentView: self];
668 [normalWindow makeKeyAndOrderFront: self];
669 [NSMenu setMenuBarVisible:YES];
c304f7e2
TS
670 } else { // switch from desktop to fullscreen
671 isFullscreen = TRUE;
5d1b2eef 672 [normalWindow orderOut: nil]; /* Hide the window */
c304f7e2
TS
673 [self grabMouse];
674 [self setContentDimensions];
1e8b6f2b
AO
675 [NSMenu setMenuBarVisible:NO];
676 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
677 styleMask:NSWindowStyleMaskBorderless
678 backing:NSBackingStoreBuffered
679 defer:NO];
680 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
681 [fullScreenWindow setHasShadow:NO];
682 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
683 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
684 [[fullScreenWindow contentView] addSubview: self];
685 [fullScreenWindow makeKeyAndOrderFront:self];
c304f7e2
TS
686 }
687}
5b0753e0 688
f844cdb9
GNS
689- (void) setFullGrab:(id)sender
690{
691 COCOA_DEBUG("QemuCocoaView: setFullGrab\n");
692
693 CGEventMask mask = CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp) | CGEventMaskBit(kCGEventFlagsChanged);
694 eventsTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault,
695 mask, handleTapEvent, self);
696 if (!eventsTap) {
697 warn_report("Could not create event tap, system key combos will not be captured.\n");
698 return;
699 } else {
700 COCOA_DEBUG("Global events tap created! Will capture system key combos.\n");
701 }
702
703 CFRunLoopRef runLoop = CFRunLoopGetCurrent();
704 if (!runLoop) {
705 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
706 return;
707 }
708
709 CFRunLoopSourceRef tapEventsSrc = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventsTap, 0);
710 if (!tapEventsSrc ) {
711 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
712 return;
713 }
714
715 CFRunLoopAddSource(runLoop, tapEventsSrc, kCFRunLoopDefaultMode);
716 CFRelease(tapEventsSrc);
717}
718
6d73bb64
AO
719- (void) toggleKey: (int)keycode {
720 qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode));
af8862b2
IM
721}
722
9c3a418e
JA
723// Does the work of sending input to the monitor
724- (void) handleMonitorInput:(NSEvent *)event
725{
726 int keysym = 0;
727 int control_key = 0;
728
729 // if the control key is down
730 if ([event modifierFlags] & NSEventModifierFlagControl) {
731 control_key = 1;
732 }
733
734 /* translates Macintosh keycodes to QEMU's keysym */
735
9459262d 736 static const int without_control_translation[] = {
9c3a418e
JA
737 [0 ... 0xff] = 0, // invalid key
738
739 [kVK_UpArrow] = QEMU_KEY_UP,
740 [kVK_DownArrow] = QEMU_KEY_DOWN,
741 [kVK_RightArrow] = QEMU_KEY_RIGHT,
742 [kVK_LeftArrow] = QEMU_KEY_LEFT,
743 [kVK_Home] = QEMU_KEY_HOME,
744 [kVK_End] = QEMU_KEY_END,
745 [kVK_PageUp] = QEMU_KEY_PAGEUP,
746 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
747 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
748 [kVK_Delete] = QEMU_KEY_BACKSPACE,
749 };
750
9459262d 751 static const int with_control_translation[] = {
9c3a418e
JA
752 [0 ... 0xff] = 0, // invalid key
753
754 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
755 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
756 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
757 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
758 [kVK_Home] = QEMU_KEY_CTRL_HOME,
759 [kVK_End] = QEMU_KEY_CTRL_END,
760 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
761 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
762 };
763
764 if (control_key != 0) { /* If the control key is being used */
765 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
766 keysym = with_control_translation[[event keyCode]];
767 }
768 } else {
769 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
770 keysym = without_control_translation[[event keyCode]];
771 }
772 }
773
774 // if not a key that needs translating
775 if (keysym == 0) {
776 NSString *ks = [event characters];
777 if ([ks length] > 0) {
778 keysym = [ks characterAtIndex:0];
779 }
780 }
781
782 if (keysym) {
783 kbd_put_keysym(keysym);
784 }
785}
786
60105d7a 787- (bool) handleEvent:(NSEvent *)event
3b46e624 788{
60105d7a
PM
789 return bool_with_iothread_lock(^{
790 return [self handleEventLocked:event];
31819e95
PM
791 });
792}
c304f7e2 793
60105d7a 794- (bool) handleEventLocked:(NSEvent *)event
31819e95 795{
60105d7a 796 /* Return true if we handled the event, false if it should be given to OSX */
31819e95 797 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
c304f7e2 798 int buttons = 0;
af8862b2 799 int keycode = 0;
21bae11a 800 bool mouse_event = false;
2044dff8
CZ
801 // Location of event in virtual screen coordinates
802 NSPoint p = [self screenLocationOfEvent:event];
6d73bb64
AO
803 NSUInteger modifiers = [event modifierFlags];
804
ad7f2f8e
AO
805 /*
806 * Check -[NSEvent modifierFlags] here.
807 *
808 * There is a NSEventType for an event notifying the change of
809 * -[NSEvent modifierFlags], NSEventTypeFlagsChanged but these operations
810 * are performed for any events because a modifier state may change while
811 * the application is inactive (i.e. no events fire) and we don't want to
812 * wait for another modifier state change to detect such a change.
813 *
814 * NSEventModifierFlagCapsLock requires a special treatment. The other flags
815 * are handled in similar manners.
816 *
817 * NSEventModifierFlagCapsLock
818 * ---------------------------
819 *
820 * If CapsLock state is changed, "up" and "down" events will be fired in
821 * sequence, effectively updates CapsLock state on the guest.
822 *
823 * The other flags
824 * ---------------
825 *
826 * If a flag is not set, fire "up" events for all keys which correspond to
827 * the flag. Note that "down" events are not fired here because the flags
828 * checked here do not tell what exact keys are down.
829 *
830 * If one of the keys corresponding to a flag is down, we rely on
831 * -[NSEvent keyCode] of an event whose -[NSEvent type] is
832 * NSEventTypeFlagsChanged to know the exact key which is down, which has
833 * the following two downsides:
834 * - It does not work when the application is inactive as described above.
835 * - It malfactions *after* the modifier state is changed while the
836 * application is inactive. It is because -[NSEvent keyCode] does not tell
837 * if the key is up or down, and requires to infer the current state from
838 * the previous state. It is still possible to fix such a malfanction by
839 * completely leaving your hands from the keyboard, which hopefully makes
840 * this implementation usable enough.
841 */
6d73bb64
AO
842 if (!!(modifiers & NSEventModifierFlagCapsLock) !=
843 qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) {
844 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true);
845 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false);
846 }
847
848 if (!(modifiers & NSEventModifierFlagShift)) {
849 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false);
850 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false);
851 }
852 if (!(modifiers & NSEventModifierFlagControl)) {
853 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false);
854 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false);
855 }
856 if (!(modifiers & NSEventModifierFlagOption)) {
4797adce
GNS
857 if (swap_opt_cmd) {
858 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
859 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
860 } else {
861 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
862 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
863 }
6d73bb64
AO
864 }
865 if (!(modifiers & NSEventModifierFlagCommand)) {
4797adce
GNS
866 if (swap_opt_cmd) {
867 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
868 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
869 } else {
870 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
871 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
872 }
6d73bb64 873 }
c304f7e2
TS
874
875 switch ([event type]) {
4ba967ad 876 case NSEventTypeFlagsChanged:
6d73bb64
AO
877 switch ([event keyCode]) {
878 case kVK_Shift:
879 if (!!(modifiers & NSEventModifierFlagShift)) {
880 [self toggleKey:Q_KEY_CODE_SHIFT];
881 }
882 break;
af8862b2 883
6d73bb64
AO
884 case kVK_RightShift:
885 if (!!(modifiers & NSEventModifierFlagShift)) {
886 [self toggleKey:Q_KEY_CODE_SHIFT_R];
af8862b2 887 }
6d73bb64
AO
888 break;
889
890 case kVK_Control:
891 if (!!(modifiers & NSEventModifierFlagControl)) {
892 [self toggleKey:Q_KEY_CODE_CTRL];
af8862b2 893 }
6d73bb64
AO
894 break;
895
896 case kVK_RightControl:
897 if (!!(modifiers & NSEventModifierFlagControl)) {
898 [self toggleKey:Q_KEY_CODE_CTRL_R];
af8862b2 899 }
6d73bb64
AO
900 break;
901
902 case kVK_Option:
903 if (!!(modifiers & NSEventModifierFlagOption)) {
4797adce
GNS
904 if (swap_opt_cmd) {
905 [self toggleKey:Q_KEY_CODE_META_L];
906 } else {
907 [self toggleKey:Q_KEY_CODE_ALT];
908 }
af8862b2 909 }
6d73bb64
AO
910 break;
911
912 case kVK_RightOption:
913 if (!!(modifiers & NSEventModifierFlagOption)) {
4797adce
GNS
914 if (swap_opt_cmd) {
915 [self toggleKey:Q_KEY_CODE_META_R];
916 } else {
917 [self toggleKey:Q_KEY_CODE_ALT_R];
918 }
af8862b2 919 }
6d73bb64 920 break;
8895919a 921
6d73bb64
AO
922 /* Don't pass command key changes to guest unless mouse is grabbed */
923 case kVK_Command:
924 if (isMouseGrabbed &&
d6b6dea7
AO
925 !!(modifiers & NSEventModifierFlagCommand) &&
926 left_command_key_enabled) {
4797adce
GNS
927 if (swap_opt_cmd) {
928 [self toggleKey:Q_KEY_CODE_ALT];
929 } else {
930 [self toggleKey:Q_KEY_CODE_META_L];
931 }
6d73bb64
AO
932 }
933 break;
8895919a 934
6d73bb64
AO
935 case kVK_RightCommand:
936 if (isMouseGrabbed &&
937 !!(modifiers & NSEventModifierFlagCommand)) {
4797adce
GNS
938 if (swap_opt_cmd) {
939 [self toggleKey:Q_KEY_CODE_ALT_R];
940 } else {
941 [self toggleKey:Q_KEY_CODE_META_R];
942 }
0c6c4395 943 }
6d73bb64 944 break;
c304f7e2 945 }
c304f7e2 946 break;
4ba967ad 947 case NSEventTypeKeyDown:
8895919a 948 keycode = cocoa_keycode_to_qemu([event keyCode]);
3b46e624 949
8895919a 950 // forward command key combos to the host UI unless the mouse is grabbed
4ba967ad 951 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
60105d7a 952 return false;
c304f7e2 953 }
3b46e624 954
c304f7e2 955 // default
c304f7e2 956
5929e36c 957 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
4ba967ad 958 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
5929e36c
JA
959 NSString *keychar = [event charactersIgnoringModifiers];
960 if ([keychar length] == 1) {
961 char key = [keychar characterAtIndex:0];
962 switch (key) {
963
964 // enable graphic console
965 case '1' ... '9':
966 console_select(key - '0' - 1); /* ascii math */
60105d7a 967 return true;
5929e36c
JA
968
969 // release the mouse grab
970 case 'g':
971 [self ungrabMouse];
60105d7a 972 return true;
5929e36c 973 }
c304f7e2 974 }
ef2088f9 975 }
c304f7e2 976
ef2088f9 977 if (qemu_console_is_graphic(NULL)) {
6d73bb64 978 qkbd_state_key_event(kbd, keycode, true);
c304f7e2 979 } else {
9c3a418e 980 [self handleMonitorInput: event];
c304f7e2
TS
981 }
982 break;
4ba967ad 983 case NSEventTypeKeyUp:
c304f7e2 984 keycode = cocoa_keycode_to_qemu([event keyCode]);
8895919a
PM
985
986 // don't pass the guest a spurious key-up if we treated this
987 // command-key combo as a host UI action
4ba967ad 988 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
60105d7a 989 return true;
8895919a
PM
990 }
991
68c0aa6e 992 if (qemu_console_is_graphic(NULL)) {
6d73bb64 993 qkbd_state_key_event(kbd, keycode, false);
c304f7e2
TS
994 }
995 break;
4ba967ad 996 case NSEventTypeMouseMoved:
c304f7e2 997 if (isAbsoluteEnabled) {
2044dff8
CZ
998 // Cursor re-entered into a window might generate events bound to screen coordinates
999 // and `nil` window property, and in full screen mode, current window might not be
1000 // key window, where event location alone should suffice.
1001 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
f61c387e
PM
1002 if (isMouseGrabbed) {
1003 [self ungrabMouse];
c304f7e2
TS
1004 }
1005 } else {
f61c387e
PM
1006 if (!isMouseGrabbed) {
1007 [self grabMouse];
c304f7e2
TS
1008 }
1009 }
5b0753e0 1010 }
21bae11a 1011 mouse_event = true;
c304f7e2 1012 break;
4ba967ad 1013 case NSEventTypeLeftMouseDown:
4295f836 1014 buttons |= MOUSE_EVENT_LBUTTON;
21bae11a 1015 mouse_event = true;
c304f7e2 1016 break;
4ba967ad 1017 case NSEventTypeRightMouseDown:
c304f7e2 1018 buttons |= MOUSE_EVENT_RBUTTON;
21bae11a 1019 mouse_event = true;
c304f7e2 1020 break;
4ba967ad 1021 case NSEventTypeOtherMouseDown:
c304f7e2 1022 buttons |= MOUSE_EVENT_MBUTTON;
21bae11a 1023 mouse_event = true;
c304f7e2 1024 break;
4ba967ad 1025 case NSEventTypeLeftMouseDragged:
4295f836 1026 buttons |= MOUSE_EVENT_LBUTTON;
21bae11a 1027 mouse_event = true;
c304f7e2 1028 break;
4ba967ad 1029 case NSEventTypeRightMouseDragged:
c304f7e2 1030 buttons |= MOUSE_EVENT_RBUTTON;
21bae11a 1031 mouse_event = true;
c304f7e2 1032 break;
4ba967ad 1033 case NSEventTypeOtherMouseDragged:
c304f7e2 1034 buttons |= MOUSE_EVENT_MBUTTON;
21bae11a 1035 mouse_event = true;
c304f7e2 1036 break;
4ba967ad 1037 case NSEventTypeLeftMouseUp:
f61c387e
PM
1038 mouse_event = true;
1039 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
8e23e34d
CZ
1040 /*
1041 * In fullscreen mode, the window of cocoaView may not be the
1042 * key window, therefore the position relative to the virtual
1043 * screen alone will be sufficient.
1044 */
1045 if(isFullscreen || [[self window] isKeyWindow]) {
9e8204b1
JA
1046 [self grabMouse];
1047 }
c304f7e2
TS
1048 }
1049 break;
4ba967ad 1050 case NSEventTypeRightMouseUp:
21bae11a 1051 mouse_event = true;
c304f7e2 1052 break;
4ba967ad 1053 case NSEventTypeOtherMouseUp:
21bae11a 1054 mouse_event = true;
c304f7e2 1055 break;
4ba967ad 1056 case NSEventTypeScrollWheel:
ae7313e7
JA
1057 /*
1058 * Send wheel events to the guest regardless of window focus.
1059 * This is in-line with standard Mac OS X UI behaviour.
1060 */
1061
dc3c89d6 1062 /*
d70a5de4
DP
1063 * We shouldn't have got a scroll event when deltaY and delta Y
1064 * are zero, hence no harm in dropping the event
dc3c89d6 1065 */
d70a5de4 1066 if ([event deltaY] != 0 || [event deltaX] != 0) {
ae7313e7 1067 /* Determine if this is a scroll up or scroll down event */
d70a5de4
DP
1068 if ([event deltaY] != 0) {
1069 buttons = ([event deltaY] > 0) ?
dc3c89d6 1070 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
d70a5de4
DP
1071 } else if ([event deltaX] != 0) {
1072 buttons = ([event deltaX] > 0) ?
1073 INPUT_BUTTON_WHEEL_LEFT : INPUT_BUTTON_WHEEL_RIGHT;
1074 }
1075
cc7859c3 1076 qemu_input_queue_btn(dcl.con, buttons, true);
dc3c89d6 1077 qemu_input_event_sync();
cc7859c3 1078 qemu_input_queue_btn(dcl.con, buttons, false);
dc3c89d6
JA
1079 qemu_input_event_sync();
1080 }
d70a5de4 1081
ae7313e7 1082 /*
d70a5de4 1083 * Since deltaX/deltaY also report scroll wheel events we prevent mouse
ae7313e7
JA
1084 * movement code from executing.
1085 */
1086 mouse_event = false;
c304f7e2
TS
1087 break;
1088 default:
60105d7a 1089 return false;
5b0753e0 1090 }
21bae11a
GH
1091
1092 if (mouse_event) {
8d3a5d9b
PM
1093 /* Don't send button events to the guest unless we've got a
1094 * mouse grab or window focus. If we have neither then this event
1095 * is the user clicking on the background window to activate and
1096 * bring us to the front, which will be done by the sendEvent
1097 * call below. We definitely don't want to pass that click through
1098 * to the guest.
1099 */
1100 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
1101 (last_buttons != buttons)) {
7fb1cf16 1102 static uint32_t bmap[INPUT_BUTTON__MAX] = {
21bae11a
GH
1103 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1104 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
ae7313e7 1105 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
21bae11a 1106 };
cc7859c3 1107 qemu_input_update_buttons(dcl.con, bmap, last_buttons, buttons);
21bae11a
GH
1108 last_buttons = buttons;
1109 }
f61c387e
PM
1110 if (isMouseGrabbed) {
1111 if (isAbsoluteEnabled) {
1112 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
1113 * The check on screenContainsPoint is to avoid sending out of range values for
1114 * clicks in the titlebar.
1115 */
1116 if ([self screenContainsPoint:p]) {
cc7859c3
AO
1117 qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x, 0, screen.width);
1118 qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
f61c387e
PM
1119 }
1120 } else {
cc7859c3
AO
1121 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, (int)[event deltaX]);
1122 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, (int)[event deltaY]);
f61c387e 1123 }
21bae11a 1124 } else {
60105d7a 1125 return false;
21bae11a
GH
1126 }
1127 qemu_input_event_sync();
1128 }
60105d7a 1129 return true;
5b0753e0
FB
1130}
1131
c304f7e2 1132- (void) grabMouse
5b0753e0 1133{
c304f7e2 1134 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
3b46e624 1135
c304f7e2
TS
1136 if (!isFullscreen) {
1137 if (qemu_name)
5929e36c 1138 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
c304f7e2 1139 else
5929e36c 1140 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
c304f7e2 1141 }
13aefd30 1142 [self hideCursor];
d1929069 1143 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
49b9bd4d 1144 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
5b0753e0 1145}
3b46e624 1146
c304f7e2
TS
1147- (void) ungrabMouse
1148{
1149 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
3b46e624 1150
c304f7e2
TS
1151 if (!isFullscreen) {
1152 if (qemu_name)
1153 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
1154 else
1155 [normalWindow setTitle:@"QEMU"];
1156 }
13aefd30 1157 [self unhideCursor];
d1929069 1158 CGAssociateMouseAndMouseCursorPosition(TRUE);
49b9bd4d 1159 isMouseGrabbed = FALSE;
5b0753e0
FB
1160}
1161
d1929069
AO
1162- (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {
1163 isAbsoluteEnabled = tIsAbsoluteEnabled;
1164 if (isMouseGrabbed) {
1165 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1166 }
1167}
49b9bd4d 1168- (BOOL) isMouseGrabbed {return isMouseGrabbed;}
c304f7e2
TS
1169- (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
1170- (float) cdx {return cdx;}
1171- (float) cdy {return cdy;}
1172- (QEMUScreen) gscreen {return screen;}
3b178b71
JA
1173
1174/*
1175 * Makes the target think all down keys are being released.
1176 * This prevents a stuck key problem, since we will not see
1177 * key up events for those keys after we have lost focus.
1178 */
1179- (void) raiseAllKeys
1180{
31819e95 1181 with_iothread_lock(^{
6d73bb64 1182 qkbd_state_lift_all_keys(kbd);
31819e95 1183 });
3b178b71 1184}
5b0753e0
FB
1185@end
1186
1187
c304f7e2 1188
5b0753e0
FB
1189/*
1190 ------------------------------------------------------
c304f7e2 1191 QemuCocoaAppController
5b0753e0
FB
1192 ------------------------------------------------------
1193*/
c304f7e2 1194@interface QemuCocoaAppController : NSObject
d9bc14f6 1195 <NSWindowDelegate, NSApplicationDelegate>
5b0753e0
FB
1196{
1197}
5d1b2eef 1198- (void)doToggleFullScreen:(id)sender;
c304f7e2
TS
1199- (void)toggleFullScreen:(id)sender;
1200- (void)showQEMUDoc:(id)sender;
5d1b2eef 1201- (void)zoomToFit:(id) sender;
b4c6a112 1202- (void)displayConsole:(id)sender;
8524f1c7
JA
1203- (void)pauseQEMU:(id)sender;
1204- (void)resumeQEMU:(id)sender;
1205- (void)displayPause;
1206- (void)removePause;
27074614
JA
1207- (void)restartQEMU:(id)sender;
1208- (void)powerDownQEMU:(id)sender;
693a3e01
JA
1209- (void)ejectDeviceMedia:(id)sender;
1210- (void)changeDeviceMedia:(id)sender;
d9bc14f6 1211- (BOOL)verifyQuit;
f4747900 1212- (void)openDocumentation:(NSString *)filename;
9e8204b1 1213- (IBAction) do_about_menu_item: (id) sender;
e47ec1a9 1214- (void)adjustSpeed:(id)sender;
5b0753e0
FB
1215@end
1216
c304f7e2
TS
1217@implementation QemuCocoaAppController
1218- (id) init
5b0753e0 1219{
c304f7e2 1220 COCOA_DEBUG("QemuCocoaAppController: init\n");
5a246934 1221
c304f7e2
TS
1222 self = [super init];
1223 if (self) {
5a246934 1224
c304f7e2
TS
1225 // create a view and add it to the window
1226 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1227 if(!cocoaView) {
4313739a 1228 error_report("(cocoa) can't create a view");
c304f7e2
TS
1229 exit(1);
1230 }
3b46e624 1231
c304f7e2
TS
1232 // create a window
1233 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
4ba967ad 1234 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
c304f7e2
TS
1235 backing:NSBackingStoreBuffered defer:NO];
1236 if(!normalWindow) {
4313739a 1237 error_report("(cocoa) can't create window");
c304f7e2
TS
1238 exit(1);
1239 }
1240 [normalWindow setAcceptsMouseMovedEvents:YES];
a1dbc05a 1241 [normalWindow setTitle:@"QEMU"];
c304f7e2
TS
1242 [normalWindow setContentView:cocoaView];
1243 [normalWindow makeKeyAndOrderFront:self];
49060c29 1244 [normalWindow center];
d9bc14f6 1245 [normalWindow setDelegate: self];
5d1b2eef 1246 stretch_video = false;
8524f1c7
JA
1247
1248 /* Used for displaying pause on the screen */
1249 pauseLabel = [NSTextField new];
1250 [pauseLabel setBezeled:YES];
1251 [pauseLabel setDrawsBackground:YES];
1252 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1253 [pauseLabel setEditable:NO];
1254 [pauseLabel setSelectable:NO];
1255 [pauseLabel setStringValue: @"Paused"];
1256 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1257 [pauseLabel setTextColor: [NSColor blackColor]];
1258 [pauseLabel sizeToFit];
c304f7e2
TS
1259 }
1260 return self;
1261}
3b46e624 1262
c304f7e2
TS
1263- (void) dealloc
1264{
1265 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1266
1267 if (cocoaView)
1268 [cocoaView release];
1269 [super dealloc];
1270}
3b46e624 1271
c304f7e2
TS
1272- (void)applicationDidFinishLaunching: (NSNotification *) note
1273{
1274 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
dff742ad 1275 allow_events = true;
5b0753e0
FB
1276}
1277
1278- (void)applicationWillTerminate:(NSNotification *)aNotification
1279{
c304f7e2
TS
1280 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1281
2910abd6
AO
1282 with_iothread_lock(^{
1283 shutdown_action = SHUTDOWN_ACTION_POWEROFF;
1284 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1285 });
40c01937
AO
1286
1287 /*
1288 * Sleep here, because returning will cause OSX to kill us
1289 * immediately; the QEMU main loop will handle the shutdown
1290 * request and terminate the process.
1291 */
1292 [NSThread sleepForTimeInterval:INFINITY];
5b0753e0
FB
1293}
1294
41ea49b3
AF
1295- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1296{
1297 return YES;
1298}
1299
d9bc14f6
JA
1300- (NSApplicationTerminateReply)applicationShouldTerminate:
1301 (NSApplication *)sender
1302{
1303 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1304 return [self verifyQuit];
1305}
1306
15280e85
AO
1307- (void)windowDidChangeScreen:(NSNotification *)notification
1308{
1309 [cocoaView updateUIInfo];
1310}
1311
1312- (void)windowDidResize:(NSNotification *)notification
1313{
1314 [cocoaView updateUIInfo];
1315}
1316
d9bc14f6
JA
1317/* Called when the user clicks on a window's close button */
1318- (BOOL)windowShouldClose:(id)sender
1319{
1320 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1321 [NSApp terminate: sender];
1322 /* If the user allows the application to quit then the call to
1323 * NSApp terminate will never return. If we get here then the user
1324 * cancelled the quit, so we should return NO to not permit the
1325 * closing of this window.
1326 */
1327 return NO;
1328}
1329
3b178b71
JA
1330/* Called when QEMU goes into the background */
1331- (void) applicationWillResignActive: (NSNotification *)aNotification
1332{
1333 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
69221df8 1334 [cocoaView ungrabMouse];
3b178b71
JA
1335 [cocoaView raiseAllKeys];
1336}
1337
5d1b2eef
JA
1338/* We abstract the method called by the Enter Fullscreen menu item
1339 * because Mac OS 10.7 and higher disables it. This is because of the
1340 * menu item's old selector's name toggleFullScreen:
1341 */
1342- (void) doToggleFullScreen:(id)sender
1343{
1344 [self toggleFullScreen:(id)sender];
1345}
1346
c304f7e2
TS
1347- (void)toggleFullScreen:(id)sender
1348{
1349 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1350
1351 [cocoaView toggleFullScreen:sender];
1352}
5b0753e0 1353
f844cdb9
GNS
1354- (void) setFullGrab:(id)sender
1355{
1356 COCOA_DEBUG("QemuCocoaAppController: setFullGrab\n");
1357
1358 [cocoaView setFullGrab:sender];
1359}
1360
f4747900
JA
1361/* Tries to find then open the specified filename */
1362- (void) openDocumentation: (NSString *) filename
1363{
1364 /* Where to look for local files */
8d6fda8c 1365 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
f4747900 1366 NSString *full_file_path;
1ff5a063 1367 NSURL *full_file_url;
f4747900
JA
1368
1369 /* iterate thru the possible paths until the file is found */
1370 int index;
1371 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1372 full_file_path = [[NSBundle mainBundle] executablePath];
1373 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1374 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1375 path_array[index], filename];
1ff5a063
RB
1376 full_file_url = [NSURL fileURLWithPath: full_file_path
1377 isDirectory: false];
1378 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
f4747900
JA
1379 return;
1380 }
1381 }
1382
1383 /* If none of the paths opened a file */
1384 NSBeep();
1385 QEMU_Alert(@"Failed to open file");
1386}
1387
c304f7e2 1388- (void)showQEMUDoc:(id)sender
5b0753e0 1389{
c304f7e2
TS
1390 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1391
1879f241 1392 [self openDocumentation: @"index.html"];
c304f7e2
TS
1393}
1394
5d1b2eef
JA
1395/* Stretches video to fit host monitor size */
1396- (void)zoomToFit:(id) sender
1397{
1398 stretch_video = !stretch_video;
1399 if (stretch_video == true) {
5e24600a 1400 [sender setState: NSControlStateValueOn];
5d1b2eef 1401 } else {
5e24600a 1402 [sender setState: NSControlStateValueOff];
5d1b2eef
JA
1403 }
1404}
5b0753e0 1405
b4c6a112
JA
1406/* Displays the console on the screen */
1407- (void)displayConsole:(id)sender
1408{
1409 console_select([sender tag]);
1410}
8524f1c7
JA
1411
1412/* Pause the guest */
1413- (void)pauseQEMU:(id)sender
1414{
31819e95
PM
1415 with_iothread_lock(^{
1416 qmp_stop(NULL);
1417 });
8524f1c7
JA
1418 [sender setEnabled: NO];
1419 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1420 [self displayPause];
1421}
1422
1423/* Resume running the guest operating system */
1424- (void)resumeQEMU:(id) sender
1425{
31819e95
PM
1426 with_iothread_lock(^{
1427 qmp_cont(NULL);
1428 });
8524f1c7
JA
1429 [sender setEnabled: NO];
1430 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1431 [self removePause];
1432}
1433
1434/* Displays the word pause on the screen */
1435- (void)displayPause
1436{
1437 /* Coordinates have to be calculated each time because the window can change its size */
1438 int xCoord, yCoord, width, height;
1439 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1440 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1441 width = [pauseLabel frame].size.width;
1442 height = [pauseLabel frame].size.height;
1443 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1444 [cocoaView addSubview: pauseLabel];
1445}
1446
1447/* Removes the word pause from the screen */
1448- (void)removePause
1449{
1450 [pauseLabel removeFromSuperview];
1451}
1452
27074614
JA
1453/* Restarts QEMU */
1454- (void)restartQEMU:(id)sender
1455{
31819e95
PM
1456 with_iothread_lock(^{
1457 qmp_system_reset(NULL);
1458 });
27074614
JA
1459}
1460
1461/* Powers down QEMU */
1462- (void)powerDownQEMU:(id)sender
1463{
31819e95
PM
1464 with_iothread_lock(^{
1465 qmp_system_powerdown(NULL);
1466 });
27074614
JA
1467}
1468
693a3e01
JA
1469/* Ejects the media.
1470 * Uses sender's tag to figure out the device to eject.
1471 */
1472- (void)ejectDeviceMedia:(id)sender
1473{
1474 NSString * drive;
1475 drive = [sender representedObject];
1476 if(drive == nil) {
1477 NSBeep();
1478 QEMU_Alert(@"Failed to find drive to eject!");
1479 return;
1480 }
1481
31819e95
PM
1482 __block Error *err = NULL;
1483 with_iothread_lock(^{
54fde4ff
MA
1484 qmp_eject([drive cStringUsingEncoding: NSASCIIStringEncoding],
1485 NULL, false, false, &err);
31819e95 1486 });
693a3e01
JA
1487 handleAnyDeviceErrors(err);
1488}
1489
1490/* Displays a dialog box asking the user to select an image file to load.
1491 * Uses sender's represented object value to figure out which drive to use.
1492 */
1493- (void)changeDeviceMedia:(id)sender
1494{
1495 /* Find the drive name */
1496 NSString * drive;
1497 drive = [sender representedObject];
1498 if(drive == nil) {
1499 NSBeep();
1500 QEMU_Alert(@"Could not find drive!");
1501 return;
1502 }
1503
1504 /* Display the file open dialog */
1505 NSOpenPanel * openPanel;
1506 openPanel = [NSOpenPanel openPanel];
1507 [openPanel setCanChooseFiles: YES];
1508 [openPanel setAllowsMultipleSelection: NO];
b5725385 1509 if([openPanel runModal] == NSModalResponseOK) {
693a3e01
JA
1510 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1511 if(file == nil) {
1512 NSBeep();
1513 QEMU_Alert(@"Failed to convert URL to file path!");
1514 return;
1515 }
1516
31819e95
PM
1517 __block Error *err = NULL;
1518 with_iothread_lock(^{
54fde4ff 1519 qmp_blockdev_change_medium([drive cStringUsingEncoding:
31819e95 1520 NSASCIIStringEncoding],
54fde4ff 1521 NULL,
31819e95
PM
1522 [file cStringUsingEncoding:
1523 NSASCIIStringEncoding],
54fde4ff 1524 "raw",
80dd5aff 1525 true, false,
31819e95
PM
1526 false, 0,
1527 &err);
1528 });
693a3e01
JA
1529 handleAnyDeviceErrors(err);
1530 }
1531}
1532
d9bc14f6
JA
1533/* Verifies if the user really wants to quit */
1534- (BOOL)verifyQuit
1535{
1536 NSAlert *alert = [NSAlert new];
1537 [alert autorelease];
1538 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1539 [alert addButtonWithTitle: @"Cancel"];
1540 [alert addButtonWithTitle: @"Quit"];
1541 if([alert runModal] == NSAlertSecondButtonReturn) {
1542 return YES;
1543 } else {
1544 return NO;
1545 }
1546}
1547
9e8204b1
JA
1548/* The action method for the About menu item */
1549- (IBAction) do_about_menu_item: (id) sender
1550{
99eb313d
AO
1551 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1552 char *icon_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1553 NSString *icon_path = [NSString stringWithUTF8String:icon_path_c];
1554 g_free(icon_path_c);
1555 NSImage *icon = [[NSImage alloc] initWithContentsOfFile:icon_path];
1556 NSString *version = @"QEMU emulator version " QEMU_FULL_VERSION;
1557 NSString *copyright = @QEMU_COPYRIGHT;
1558 NSDictionary *options;
1559 if (icon) {
1560 options = @{
1561 NSAboutPanelOptionApplicationIcon : icon,
1562 NSAboutPanelOptionApplicationVersion : version,
1563 @"Copyright" : copyright,
1564 };
1565 [icon release];
1566 } else {
1567 options = @{
1568 NSAboutPanelOptionApplicationVersion : version,
1569 @"Copyright" : copyright,
1570 };
a0f973f9 1571 }
99eb313d
AO
1572 [NSApp orderFrontStandardAboutPanelWithOptions:options];
1573 [pool release];
9e8204b1
JA
1574}
1575
e47ec1a9
JA
1576/* Used by the Speed menu items */
1577- (void)adjustSpeed:(id)sender
1578{
1579 int throttle_pct; /* throttle percentage */
1580 NSMenu *menu;
1581
1582 menu = [sender menu];
1583 if (menu != nil)
1584 {
1585 /* Unselect the currently selected item */
1586 for (NSMenuItem *item in [menu itemArray]) {
5e24600a
BS
1587 if (item.state == NSControlStateValueOn) {
1588 [item setState: NSControlStateValueOff];
e47ec1a9
JA
1589 break;
1590 }
1591 }
1592 }
1593
1594 // check the menu item
5e24600a 1595 [sender setState: NSControlStateValueOn];
e47ec1a9
JA
1596
1597 // get the throttle percentage
1598 throttle_pct = [sender tag];
1599
31819e95
PM
1600 with_iothread_lock(^{
1601 cpu_throttle_set(throttle_pct);
1602 });
e47ec1a9
JA
1603 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1604}
1605
b4c6a112 1606@end
5b0753e0 1607
61a2ed44
PM
1608@interface QemuApplication : NSApplication
1609@end
1610
1611@implementation QemuApplication
1612- (void)sendEvent:(NSEvent *)event
1613{
1614 COCOA_DEBUG("QemuApplication: sendEvent\n");
5588840f
PM
1615 if (![cocoaView handleEvent:event]) {
1616 [super sendEvent: event];
1617 }
61a2ed44
PM
1618}
1619@end
1620
c6fd6c70
PM
1621static void create_initial_menus(void)
1622{
c304f7e2
TS
1623 // Add menus
1624 NSMenu *menu;
1625 NSMenuItem *menuItem;
5b0753e0 1626
c304f7e2 1627 [NSApp setMainMenu:[[NSMenu alloc] init]];
5b6988c1 1628 [NSApp setServicesMenu:[[NSMenu alloc] initWithTitle:@"Services"]];
5b0753e0 1629
c304f7e2
TS
1630 // Application menu
1631 menu = [[NSMenu alloc] initWithTitle:@""];
9e8204b1 1632 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
c304f7e2 1633 [menu addItem:[NSMenuItem separatorItem]]; //Separator
5b6988c1
AO
1634 menuItem = [menu addItemWithTitle:@"Services" action:nil keyEquivalent:@""];
1635 [menuItem setSubmenu:[NSApp servicesMenu]];
1636 [menu addItem:[NSMenuItem separatorItem]];
c304f7e2
TS
1637 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1638 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
4ba967ad 1639 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
c304f7e2
TS
1640 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1641 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1642 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1643 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1644 [menuItem setSubmenu:menu];
1645 [[NSApp mainMenu] addItem:menuItem];
1646 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
3b46e624 1647
8524f1c7
JA
1648 // Machine menu
1649 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1650 [menu setAutoenablesItems: NO];
1651 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1652 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1653 [menu addItem: menuItem];
1654 [menuItem setEnabled: NO];
27074614
JA
1655 [menu addItem: [NSMenuItem separatorItem]];
1656 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1657 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
8524f1c7
JA
1658 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1659 [menuItem setSubmenu:menu];
1660 [[NSApp mainMenu] addItem:menuItem];
1661
c304f7e2
TS
1662 // View menu
1663 menu = [[NSMenu alloc] initWithTitle:@"View"];
5d1b2eef
JA
1664 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1665 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
c304f7e2
TS
1666 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1667 [menuItem setSubmenu:menu];
5b0753e0
FB
1668 [[NSApp mainMenu] addItem:menuItem];
1669
e47ec1a9
JA
1670 // Speed menu
1671 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1672
1673 // Add the rest of the Speed menu items
1674 int p, percentage, throttle_pct;
1675 for (p = 10; p >= 0; p--)
1676 {
1677 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1678
1679 menuItem = [[[NSMenuItem alloc]
1680 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1681
1682 if (percentage == 100) {
5e24600a 1683 [menuItem setState: NSControlStateValueOn];
e47ec1a9
JA
1684 }
1685
1686 /* Calculate the throttle percentage */
1687 throttle_pct = -1 * percentage + 100;
1688
1689 [menuItem setTag: throttle_pct];
1690 [menu addItem: menuItem];
1691 }
1692 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1693 [menuItem setSubmenu:menu];
1694 [[NSApp mainMenu] addItem:menuItem];
1695
c304f7e2
TS
1696 // Window menu
1697 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1698 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1699 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1700 [menuItem setSubmenu:menu];
1701 [[NSApp mainMenu] addItem:menuItem];
1702 [NSApp setWindowsMenu:menu];
1703
1704 // Help menu
1705 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1706 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
c304f7e2
TS
1707 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1708 [menuItem setSubmenu:menu];
1709 [[NSApp mainMenu] addItem:menuItem];
c6fd6c70
PM
1710}
1711
8b00e4e7
PM
1712/* Returns a name for a given console */
1713static NSString * getConsoleName(QemuConsole * console)
1714{
ca511604
AO
1715 g_autofree char *label = qemu_console_get_label(console);
1716
1717 return [NSString stringWithUTF8String:label];
8b00e4e7
PM
1718}
1719
1720/* Add an entry to the View menu for each console */
1721static void add_console_menu_entries(void)
1722{
1723 NSMenu *menu;
1724 NSMenuItem *menuItem;
1725 int index = 0;
1726
1727 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1728
1729 [menu addItem:[NSMenuItem separatorItem]];
1730
1731 while (qemu_console_lookup_by_index(index) != NULL) {
1732 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1733 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1734 [menuItem setTag: index];
1735 [menu addItem: menuItem];
1736 index++;
1737 }
1738}
1739
1740/* Make menu items for all removable devices.
1741 * Each device is given an 'Eject' and 'Change' menu item.
1742 */
1743static void addRemovableDevicesMenuItems(void)
1744{
1745 NSMenu *menu;
1746 NSMenuItem *menuItem;
1747 BlockInfoList *currentDevice, *pointerToFree;
1748 NSString *deviceName;
1749
1750 currentDevice = qmp_query_block(NULL);
1751 pointerToFree = currentDevice;
8b00e4e7
PM
1752
1753 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1754
1755 // Add a separator between related groups of menu items
1756 [menu addItem:[NSMenuItem separatorItem]];
1757
1758 // Set the attributes to the "Removable Media" menu item
1759 NSString *titleString = @"Removable Media";
1760 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1761 NSColor *newColor = [NSColor blackColor];
1762 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1763 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1764 traits:NSBoldFontMask|NSItalicFontMask
1765 weight:0
1766 size:14];
1767 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1768 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1769 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1770
1771 // Add the "Removable Media" menu item
1772 menuItem = [NSMenuItem new];
1773 [menuItem setAttributedTitle: attString];
1774 [menuItem setEnabled: NO];
1775 [menu addItem: menuItem];
1776
1777 /* Loop through all the block devices in the emulator */
1778 while (currentDevice) {
1779 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1780
1781 if(currentDevice->value->removable) {
1782 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1783 action: @selector(changeDeviceMedia:)
1784 keyEquivalent: @""];
1785 [menu addItem: menuItem];
1786 [menuItem setRepresentedObject: deviceName];
1787 [menuItem autorelease];
1788
1789 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1790 action: @selector(ejectDeviceMedia:)
1791 keyEquivalent: @""];
1792 [menu addItem: menuItem];
1793 [menuItem setRepresentedObject: deviceName];
1794 [menuItem autorelease];
1795 }
1796 currentDevice = currentDevice->next;
1797 }
1798 qapi_free_BlockInfoList(pointerToFree);
1799}
1800
7e3e20d8
AO
1801@interface QemuCocoaPasteboardTypeOwner : NSObject<NSPasteboardTypeOwner>
1802@end
1803
1804@implementation QemuCocoaPasteboardTypeOwner
1805
1806- (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)type
1807{
1808 if (type != NSPasteboardTypeString) {
1809 return;
1810 }
1811
1812 with_iothread_lock(^{
1813 QemuClipboardInfo *info = qemu_clipboard_info_ref(cbinfo);
1814 qemu_event_reset(&cbevent);
1815 qemu_clipboard_request(info, QEMU_CLIPBOARD_TYPE_TEXT);
1816
1817 while (info == cbinfo &&
1818 info->types[QEMU_CLIPBOARD_TYPE_TEXT].available &&
1819 info->types[QEMU_CLIPBOARD_TYPE_TEXT].data == NULL) {
1820 qemu_mutex_unlock_iothread();
1821 qemu_event_wait(&cbevent);
1822 qemu_mutex_lock_iothread();
1823 }
1824
1825 if (info == cbinfo) {
1826 NSData *data = [[NSData alloc] initWithBytes:info->types[QEMU_CLIPBOARD_TYPE_TEXT].data
1827 length:info->types[QEMU_CLIPBOARD_TYPE_TEXT].size];
1828 [sender setData:data forType:NSPasteboardTypeString];
1829 [data release];
1830 }
1831
1832 qemu_clipboard_info_unref(info);
1833 });
1834}
1835
1836@end
1837
1838static QemuCocoaPasteboardTypeOwner *cbowner;
1839
1840static void cocoa_clipboard_notify(Notifier *notifier, void *data);
1841static void cocoa_clipboard_request(QemuClipboardInfo *info,
1842 QemuClipboardType type);
1843
1844static QemuClipboardPeer cbpeer = {
1845 .name = "cocoa",
1b17f1e9 1846 .notifier = { .notify = cocoa_clipboard_notify },
7e3e20d8
AO
1847 .request = cocoa_clipboard_request
1848};
1849
1b17f1e9 1850static void cocoa_clipboard_update_info(QemuClipboardInfo *info)
7e3e20d8 1851{
7e3e20d8
AO
1852 if (info->owner == &cbpeer || info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
1853 return;
1854 }
1855
1856 if (info != cbinfo) {
1857 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1858 qemu_clipboard_info_unref(cbinfo);
1859 cbinfo = qemu_clipboard_info_ref(info);
1860 cbchangecount = [[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:cbowner];
1861 [pool release];
1862 }
1863
1864 qemu_event_set(&cbevent);
1865}
1866
1b17f1e9
MAL
1867static void cocoa_clipboard_notify(Notifier *notifier, void *data)
1868{
1869 QemuClipboardNotify *notify = data;
1870
1871 switch (notify->type) {
1872 case QEMU_CLIPBOARD_UPDATE_INFO:
1873 cocoa_clipboard_update_info(notify->info);
1874 return;
505dbf9b
MAL
1875 case QEMU_CLIPBOARD_RESET_SERIAL:
1876 /* ignore */
1877 return;
1b17f1e9
MAL
1878 }
1879}
1880
7e3e20d8
AO
1881static void cocoa_clipboard_request(QemuClipboardInfo *info,
1882 QemuClipboardType type)
1883{
8c0d8024 1884 NSAutoreleasePool *pool;
7e3e20d8
AO
1885 NSData *text;
1886
1887 switch (type) {
1888 case QEMU_CLIPBOARD_TYPE_TEXT:
8c0d8024 1889 pool = [[NSAutoreleasePool alloc] init];
7e3e20d8
AO
1890 text = [[NSPasteboard generalPasteboard] dataForType:NSPasteboardTypeString];
1891 if (text) {
1892 qemu_clipboard_set_data(&cbpeer, info, type,
1893 [text length], [text bytes], true);
7e3e20d8 1894 }
8c0d8024 1895 [pool release];
7e3e20d8
AO
1896 break;
1897 default:
1898 break;
1899 }
1900}
1901
5588840f
PM
1902/*
1903 * The startup process for the OSX/Cocoa UI is complicated, because
1904 * OSX insists that the UI runs on the initial main thread, and so we
bab6a301 1905 * need to start a second thread which runs the qemu_default_main():
5588840f 1906 * in main():
bab6a301
AO
1907 * in cocoa_display_init():
1908 * assign cocoa_main to qemu_main
1909 * create application, menus, etc
1910 * in cocoa_main():
1911 * create qemu-main thread
1912 * enter OSX run loop
5588840f
PM
1913 */
1914
1915static void *call_qemu_main(void *opaque)
1916{
1917 int status;
1918
bab6a301
AO
1919 COCOA_DEBUG("Second thread: calling qemu_default_main()\n");
1920 qemu_mutex_lock_iothread();
1921 status = qemu_default_main();
1922 qemu_mutex_unlock_iothread();
1923 COCOA_DEBUG("Second thread: qemu_default_main() returned, exiting\n");
7e3e20d8 1924 [cbowner release];
5588840f
PM
1925 exit(status);
1926}
1927
bab6a301
AO
1928static int cocoa_main()
1929{
5588840f 1930 QemuThread thread;
c6fd6c70 1931
bab6a301 1932 COCOA_DEBUG("Entered %s()\n", __func__);
c6fd6c70 1933
bab6a301 1934 qemu_mutex_unlock_iothread();
5588840f
PM
1935 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1936 NULL, QEMU_THREAD_DETACHED);
1937
c304f7e2 1938 // Start the main event loop
5588840f 1939 COCOA_DEBUG("Main thread: entering OSX run loop\n");
c304f7e2 1940 [NSApp run];
bab6a301 1941 COCOA_DEBUG("Main thread: left OSX run loop, which should never happen\n");
5b0753e0 1942
bab6a301 1943 abort();
c304f7e2 1944}
3b46e624 1945
3b46e624 1946
5b0753e0 1947
c304f7e2 1948#pragma mark qemu
7c20b4a3 1949static void cocoa_update(DisplayChangeListener *dcl,
7c20b4a3 1950 int x, int y, int w, int h)
c304f7e2
TS
1951{
1952 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
1953
5588840f
PM
1954 dispatch_async(dispatch_get_main_queue(), ^{
1955 NSRect rect;
1956 if ([cocoaView cdx] == 1.0) {
1957 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
1958 } else {
1959 rect = NSMakeRect(
1960 x * [cocoaView cdx],
1961 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
1962 w * [cocoaView cdx],
1963 h * [cocoaView cdy]);
1964 }
1965 [cocoaView setNeedsDisplayInRect:rect];
1966 });
5b0753e0
FB
1967}
1968
c12aeb86 1969static void cocoa_switch(DisplayChangeListener *dcl,
c12aeb86 1970 DisplaySurface *surface)
5b0753e0 1971{
5588840f 1972 pixman_image_t *image = surface->image;
3b46e624 1973
6e657e64 1974 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
5588840f
PM
1975
1976 // The DisplaySurface will be freed as soon as this callback returns.
1977 // We take a reference to the underlying pixman image here so it does
1978 // not disappear from under our feet; the switchSurface method will
1979 // deref the old image when it is done with it.
1980 pixman_image_ref(image);
1981
1982 dispatch_async(dispatch_get_main_queue(), ^{
8d65dee2 1983 [cocoaView updateUIInfo];
5588840f
PM
1984 [cocoaView switchSurface:image];
1985 });
c304f7e2 1986}
3b46e624 1987
bc2ed970 1988static void cocoa_refresh(DisplayChangeListener *dcl)
c304f7e2 1989{
6e657e64
PM
1990 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1991
c304f7e2 1992 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
468a895b 1993 graphic_hw_update(NULL);
3b46e624 1994
21bae11a 1995 if (qemu_input_is_absolute()) {
5588840f
PM
1996 dispatch_async(dispatch_get_main_queue(), ^{
1997 if (![cocoaView isAbsoluteEnabled]) {
1998 if ([cocoaView isMouseGrabbed]) {
1999 [cocoaView ungrabMouse];
2000 }
c304f7e2 2001 }
5588840f
PM
2002 [cocoaView setAbsoluteEnabled:YES];
2003 });
c304f7e2 2004 }
7e3e20d8
AO
2005
2006 if (cbchangecount != [[NSPasteboard generalPasteboard] changeCount]) {
2007 qemu_clipboard_info_unref(cbinfo);
2008 cbinfo = qemu_clipboard_info_new(&cbpeer, QEMU_CLIPBOARD_SELECTION_CLIPBOARD);
2009 if ([[NSPasteboard generalPasteboard] availableTypeFromArray:@[NSPasteboardTypeString]]) {
2010 cbinfo->types[QEMU_CLIPBOARD_TYPE_TEXT].available = true;
2011 }
2012 qemu_clipboard_update(cbinfo);
2013 cbchangecount = [[NSPasteboard generalPasteboard] changeCount];
2014 qemu_event_set(&cbevent);
2015 }
2016
6e657e64 2017 [pool release];
c304f7e2 2018}
3b46e624 2019
5013b9e4 2020static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
5b0753e0 2021{
bab6a301
AO
2022 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2023
c304f7e2
TS
2024 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
2025
bab6a301
AO
2026 qemu_main = cocoa_main;
2027
2028 // Pull this console process up to being a fully-fledged graphical
2029 // app with a menubar and Dock icon
2030 ProcessSerialNumber psn = { 0, kCurrentProcess };
2031 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
2032
2033 [QemuApplication sharedApplication];
2034
2035 create_initial_menus();
2036
2037 /*
2038 * Create the menu entries which depend on QEMU state (for consoles
2039 * and removeable devices). These make calls back into QEMU functions,
2040 * which is OK because at this point we know that the second thread
2041 * holds the iothread lock and is synchronously waiting for us to
2042 * finish.
2043 */
2044 add_console_menu_entries();
2045 addRemovableDevicesMenuItems();
2046
2047 // Create an Application controller
2048 QemuCocoaAppController *controller = [[QemuCocoaAppController alloc] init];
2049 [NSApp setDelegate:controller];
5588840f 2050
43227af8 2051 /* if fullscreen mode is to be used */
767f9bf3 2052 if (opts->has_full_screen && opts->full_screen) {
bab6a301
AO
2053 [NSApp activateIgnoringOtherApps: YES];
2054 [controller toggleFullScreen: nil];
f844cdb9
GNS
2055 }
2056 if (opts->u.cocoa.has_full_grab && opts->u.cocoa.full_grab) {
bab6a301 2057 [controller setFullGrab: nil];
43227af8 2058 }
69221df8 2059
3487da6a
GH
2060 if (opts->has_show_cursor && opts->show_cursor) {
2061 cursor_hide = 0;
2062 }
4797adce
GNS
2063 if (opts->u.cocoa.has_swap_opt_cmd) {
2064 swap_opt_cmd = opts->u.cocoa.swap_opt_cmd;
2065 }
43227af8 2066
48941a52
CE
2067 if (opts->u.cocoa.has_left_command_key && !opts->u.cocoa.left_command_key) {
2068 left_command_key_enabled = 0;
2069 }
2070
9794f74f 2071 // register vga output callbacks
cc7859c3 2072 register_displaychangelistener(&dcl);
7e3e20d8
AO
2073
2074 qemu_event_init(&cbevent, false);
2075 cbowner = [[QemuCocoaPasteboardTypeOwner alloc] init];
2076 qemu_clipboard_peer_register(&cbpeer);
bab6a301
AO
2077
2078 [pool release];
5b0753e0 2079}
5013b9e4
GH
2080
2081static QemuDisplay qemu_display_cocoa = {
2082 .type = DISPLAY_TYPE_COCOA,
2083 .init = cocoa_display_init,
2084};
2085
2086static void register_cocoa(void)
2087{
2088 qemu_display_register(&qemu_display_cocoa);
2089}
2090
2091type_init(register_cocoa);