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