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