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