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