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