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