2 * QEMU Cocoa CG display driver
4 * Copyright (c) 2008 Mike Kronenberg
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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
25 #include "qemu/osdep.h"
27 #import <Cocoa/Cocoa.h>
28 #include <crt_externs.h>
30 #include "qemu-common.h"
31 #include "ui/clipboard.h"
32 #include "ui/console.h"
34 #include "ui/kbd-state.h"
35 #include "sysemu/sysemu.h"
36 #include "sysemu/runstate.h"
37 #include "sysemu/cpu-throttle.h"
38 #include "qapi/error.h"
39 #include "qapi/qapi-commands-block.h"
40 #include "qapi/qapi-commands-machine.h"
41 #include "qapi/qapi-commands-misc.h"
42 #include "sysemu/blockdev.h"
43 #include "qemu-version.h"
44 #include "qemu/cutils.h"
45 #include "qemu/main-loop.h"
46 #include "qemu/module.h"
47 #include <Carbon/Carbon.h>
48 #include "hw/core/cpu.h"
50 #ifndef MAC_OS_X_VERSION_10_13
51 #define MAC_OS_X_VERSION_10_13 101300
54 /* 10.14 deprecates NSOnState and NSOffState in favor of
55 * NSControlStateValueOn/Off, which were introduced in 10.13.
56 * Define for older versions
58 #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_13
59 #define NSControlStateValueOn NSOnState
60 #define NSControlStateValueOff NSOffState
66 #define COCOA_DEBUG(...) { (void) fprintf (stdout, __VA_ARGS__); }
68 #define COCOA_DEBUG(...) ((void) 0)
71 #define cgrect(nsrect) (*(CGRect *)&(nsrect))
78 static void cocoa_update(DisplayChangeListener *dcl,
79 int x, int y, int w, int h);
81 static void cocoa_switch(DisplayChangeListener *dcl,
82 DisplaySurface *surface);
84 static void cocoa_refresh(DisplayChangeListener *dcl);
86 static NSWindow *normalWindow;
87 static const DisplayChangeListenerOps dcl_ops = {
89 .dpy_gfx_update = cocoa_update,
90 .dpy_gfx_switch = cocoa_switch,
91 .dpy_refresh = cocoa_refresh,
93 static DisplayChangeListener dcl = {
96 static int last_buttons;
97 static int cursor_hide = 1;
98 static int left_command_key_enabled = 1;
99 static bool swap_opt_cmd;
103 static bool stretch_video;
104 static NSTextField *pauseLabel;
106 static QemuSemaphore display_init_sem;
107 static QemuSemaphore app_started_sem;
108 static bool allow_events;
110 static NSInteger cbchangecount = -1;
111 static QemuClipboardInfo *cbinfo;
112 static QemuEvent cbevent;
114 // Utility functions to run specified code block with iothread lock held
115 typedef void (^CodeBlock)(void);
116 typedef bool (^BoolCodeBlock)(void);
118 static void with_iothread_lock(CodeBlock block)
120 bool locked = qemu_mutex_iothread_locked();
122 qemu_mutex_lock_iothread();
126 qemu_mutex_unlock_iothread();
130 static bool bool_with_iothread_lock(BoolCodeBlock block)
132 bool locked = qemu_mutex_iothread_locked();
136 qemu_mutex_lock_iothread();
140 qemu_mutex_unlock_iothread();
145 // Mac to QKeyCode conversion
146 static const int mac_to_qkeycode_map[] = {
147 [kVK_ANSI_A] = Q_KEY_CODE_A,
148 [kVK_ANSI_B] = Q_KEY_CODE_B,
149 [kVK_ANSI_C] = Q_KEY_CODE_C,
150 [kVK_ANSI_D] = Q_KEY_CODE_D,
151 [kVK_ANSI_E] = Q_KEY_CODE_E,
152 [kVK_ANSI_F] = Q_KEY_CODE_F,
153 [kVK_ANSI_G] = Q_KEY_CODE_G,
154 [kVK_ANSI_H] = Q_KEY_CODE_H,
155 [kVK_ANSI_I] = Q_KEY_CODE_I,
156 [kVK_ANSI_J] = Q_KEY_CODE_J,
157 [kVK_ANSI_K] = Q_KEY_CODE_K,
158 [kVK_ANSI_L] = Q_KEY_CODE_L,
159 [kVK_ANSI_M] = Q_KEY_CODE_M,
160 [kVK_ANSI_N] = Q_KEY_CODE_N,
161 [kVK_ANSI_O] = Q_KEY_CODE_O,
162 [kVK_ANSI_P] = Q_KEY_CODE_P,
163 [kVK_ANSI_Q] = Q_KEY_CODE_Q,
164 [kVK_ANSI_R] = Q_KEY_CODE_R,
165 [kVK_ANSI_S] = Q_KEY_CODE_S,
166 [kVK_ANSI_T] = Q_KEY_CODE_T,
167 [kVK_ANSI_U] = Q_KEY_CODE_U,
168 [kVK_ANSI_V] = Q_KEY_CODE_V,
169 [kVK_ANSI_W] = Q_KEY_CODE_W,
170 [kVK_ANSI_X] = Q_KEY_CODE_X,
171 [kVK_ANSI_Y] = Q_KEY_CODE_Y,
172 [kVK_ANSI_Z] = Q_KEY_CODE_Z,
174 [kVK_ANSI_0] = Q_KEY_CODE_0,
175 [kVK_ANSI_1] = Q_KEY_CODE_1,
176 [kVK_ANSI_2] = Q_KEY_CODE_2,
177 [kVK_ANSI_3] = Q_KEY_CODE_3,
178 [kVK_ANSI_4] = Q_KEY_CODE_4,
179 [kVK_ANSI_5] = Q_KEY_CODE_5,
180 [kVK_ANSI_6] = Q_KEY_CODE_6,
181 [kVK_ANSI_7] = Q_KEY_CODE_7,
182 [kVK_ANSI_8] = Q_KEY_CODE_8,
183 [kVK_ANSI_9] = Q_KEY_CODE_9,
185 [kVK_ANSI_Grave] = Q_KEY_CODE_GRAVE_ACCENT,
186 [kVK_ANSI_Minus] = Q_KEY_CODE_MINUS,
187 [kVK_ANSI_Equal] = Q_KEY_CODE_EQUAL,
188 [kVK_Delete] = Q_KEY_CODE_BACKSPACE,
189 [kVK_CapsLock] = Q_KEY_CODE_CAPS_LOCK,
190 [kVK_Tab] = Q_KEY_CODE_TAB,
191 [kVK_Return] = Q_KEY_CODE_RET,
192 [kVK_ANSI_LeftBracket] = Q_KEY_CODE_BRACKET_LEFT,
193 [kVK_ANSI_RightBracket] = Q_KEY_CODE_BRACKET_RIGHT,
194 [kVK_ANSI_Backslash] = Q_KEY_CODE_BACKSLASH,
195 [kVK_ANSI_Semicolon] = Q_KEY_CODE_SEMICOLON,
196 [kVK_ANSI_Quote] = Q_KEY_CODE_APOSTROPHE,
197 [kVK_ANSI_Comma] = Q_KEY_CODE_COMMA,
198 [kVK_ANSI_Period] = Q_KEY_CODE_DOT,
199 [kVK_ANSI_Slash] = Q_KEY_CODE_SLASH,
200 [kVK_Space] = Q_KEY_CODE_SPC,
202 [kVK_ANSI_Keypad0] = Q_KEY_CODE_KP_0,
203 [kVK_ANSI_Keypad1] = Q_KEY_CODE_KP_1,
204 [kVK_ANSI_Keypad2] = Q_KEY_CODE_KP_2,
205 [kVK_ANSI_Keypad3] = Q_KEY_CODE_KP_3,
206 [kVK_ANSI_Keypad4] = Q_KEY_CODE_KP_4,
207 [kVK_ANSI_Keypad5] = Q_KEY_CODE_KP_5,
208 [kVK_ANSI_Keypad6] = Q_KEY_CODE_KP_6,
209 [kVK_ANSI_Keypad7] = Q_KEY_CODE_KP_7,
210 [kVK_ANSI_Keypad8] = Q_KEY_CODE_KP_8,
211 [kVK_ANSI_Keypad9] = Q_KEY_CODE_KP_9,
212 [kVK_ANSI_KeypadDecimal] = Q_KEY_CODE_KP_DECIMAL,
213 [kVK_ANSI_KeypadEnter] = Q_KEY_CODE_KP_ENTER,
214 [kVK_ANSI_KeypadPlus] = Q_KEY_CODE_KP_ADD,
215 [kVK_ANSI_KeypadMinus] = Q_KEY_CODE_KP_SUBTRACT,
216 [kVK_ANSI_KeypadMultiply] = Q_KEY_CODE_KP_MULTIPLY,
217 [kVK_ANSI_KeypadDivide] = Q_KEY_CODE_KP_DIVIDE,
218 [kVK_ANSI_KeypadEquals] = Q_KEY_CODE_KP_EQUALS,
219 [kVK_ANSI_KeypadClear] = Q_KEY_CODE_NUM_LOCK,
221 [kVK_UpArrow] = Q_KEY_CODE_UP,
222 [kVK_DownArrow] = Q_KEY_CODE_DOWN,
223 [kVK_LeftArrow] = Q_KEY_CODE_LEFT,
224 [kVK_RightArrow] = Q_KEY_CODE_RIGHT,
226 [kVK_Help] = Q_KEY_CODE_INSERT,
227 [kVK_Home] = Q_KEY_CODE_HOME,
228 [kVK_PageUp] = Q_KEY_CODE_PGUP,
229 [kVK_PageDown] = Q_KEY_CODE_PGDN,
230 [kVK_End] = Q_KEY_CODE_END,
231 [kVK_ForwardDelete] = Q_KEY_CODE_DELETE,
233 [kVK_Escape] = Q_KEY_CODE_ESC,
235 /* The Power key can't be used directly because the operating system uses
236 * it. This key can be emulated by using it in place of another key such as
237 * F1. Don't forget to disable the real key binding.
239 /* [kVK_F1] = Q_KEY_CODE_POWER, */
241 [kVK_F1] = Q_KEY_CODE_F1,
242 [kVK_F2] = Q_KEY_CODE_F2,
243 [kVK_F3] = Q_KEY_CODE_F3,
244 [kVK_F4] = Q_KEY_CODE_F4,
245 [kVK_F5] = Q_KEY_CODE_F5,
246 [kVK_F6] = Q_KEY_CODE_F6,
247 [kVK_F7] = Q_KEY_CODE_F7,
248 [kVK_F8] = Q_KEY_CODE_F8,
249 [kVK_F9] = Q_KEY_CODE_F9,
250 [kVK_F10] = Q_KEY_CODE_F10,
251 [kVK_F11] = Q_KEY_CODE_F11,
252 [kVK_F12] = Q_KEY_CODE_F12,
253 [kVK_F13] = Q_KEY_CODE_PRINT,
254 [kVK_F14] = Q_KEY_CODE_SCROLL_LOCK,
255 [kVK_F15] = Q_KEY_CODE_PAUSE,
257 // JIS keyboards only
258 [kVK_JIS_Yen] = Q_KEY_CODE_YEN,
259 [kVK_JIS_Underscore] = Q_KEY_CODE_RO,
260 [kVK_JIS_KeypadComma] = Q_KEY_CODE_KP_COMMA,
261 [kVK_JIS_Eisu] = Q_KEY_CODE_MUHENKAN,
262 [kVK_JIS_Kana] = Q_KEY_CODE_HENKAN,
265 * The eject and volume keys can't be used here because they are handled at
266 * a lower level than what an Application can see.
270 static int cocoa_keycode_to_qemu(int keycode)
272 if (ARRAY_SIZE(mac_to_qkeycode_map) <= keycode) {
273 error_report("(cocoa) warning unknown keycode 0x%x", keycode);
276 return mac_to_qkeycode_map[keycode];
279 /* Displays an alert dialog box with the specified message */
280 static void QEMU_Alert(NSString *message)
283 alert = [NSAlert new];
284 [alert setMessageText: message];
288 /* Handles any errors that happen with a device transaction */
289 static void handleAnyDeviceErrors(Error * err)
292 QEMU_Alert([NSString stringWithCString: error_get_pretty(err)
293 encoding: NSASCIIStringEncoding]);
299 ------------------------------------------------------
301 ------------------------------------------------------
303 @interface QemuCocoaView : NSView
306 NSWindow *fullScreenWindow;
307 float cx,cy,cw,ch,cdx,cdy;
308 pixman_image_t *pixman_image;
312 BOOL isAbsoluteEnabled;
313 CFMachPortRef eventsTap;
315 - (void) switchSurface:(pixman_image_t *)image;
317 - (void) ungrabMouse;
318 - (void) toggleFullScreen:(id)sender;
319 - (void) setFullGrab:(id)sender;
320 - (void) handleMonitorInput:(NSEvent *)event;
321 - (bool) handleEvent:(NSEvent *)event;
322 - (bool) handleEventLocked:(NSEvent *)event;
323 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled;
324 /* The state surrounding mouse grabbing is potentially confusing.
325 * isAbsoluteEnabled tracks qemu_input_is_absolute() [ie "is the emulated
326 * pointing device an absolute-position one?"], but is only updated on
328 * isMouseGrabbed tracks whether GUI events are directed to the guest;
329 * it controls whether special keys like Cmd get sent to the guest,
330 * and whether we capture the mouse when in non-absolute mode.
332 - (BOOL) isMouseGrabbed;
333 - (BOOL) isAbsoluteEnabled;
336 - (QEMUScreen) gscreen;
337 - (void) raiseAllKeys;
340 QemuCocoaView *cocoaView;
342 static CGEventRef handleTapEvent(CGEventTapProxy proxy, CGEventType type, CGEventRef cgEvent, void *userInfo)
344 QemuCocoaView *cocoaView = userInfo;
345 NSEvent *event = [NSEvent eventWithCGEvent:cgEvent];
346 if ([cocoaView isMouseGrabbed] && [cocoaView handleEvent:event]) {
347 COCOA_DEBUG("Global events tap: qemu handled the event, capturing!\n");
350 COCOA_DEBUG("Global events tap: qemu did not handle the event, letting it through...\n");
355 @implementation QemuCocoaView
356 - (id)initWithFrame:(NSRect)frameRect
358 COCOA_DEBUG("QemuCocoaView: initWithFrame\n");
360 self = [super initWithFrame:frameRect];
363 screen.width = frameRect.size.width;
364 screen.height = frameRect.size.height;
365 kbd = qkbd_state_init(dcl.con);
373 COCOA_DEBUG("QemuCocoaView: dealloc\n");
376 pixman_image_unref(pixman_image);
379 qkbd_state_free(kbd);
382 CFRelease(eventsTap);
393 - (BOOL) screenContainsPoint:(NSPoint) p
395 return (p.x > -1 && p.x < screen.width && p.y > -1 && p.y < screen.height);
398 /* Get location of event and convert to virtual screen coordinate */
399 - (CGPoint) screenLocationOfEvent:(NSEvent *)ev
401 NSWindow *eventWindow = [ev window];
402 // XXX: Use CGRect and -convertRectFromScreen: to support macOS 10.10
403 CGRect r = CGRectZero;
404 r.origin = [ev locationInWindow];
407 return [[self window] convertRectFromScreen:r].origin;
409 CGPoint locationInSelfWindow = [[self window] convertRectFromScreen:r].origin;
410 CGPoint loc = [self convertPoint:locationInSelfWindow fromView:nil];
417 } else if ([[self window] isEqual:eventWindow]) {
421 CGPoint loc = [self convertPoint:r.origin fromView:nil];
429 return [[self window] convertRectFromScreen:[eventWindow convertRectToScreen:r]].origin;
441 - (void) unhideCursor
449 - (void) drawRect:(NSRect) rect
451 COCOA_DEBUG("QemuCocoaView: drawRect\n");
453 // get CoreGraphic context
454 CGContextRef viewContextRef = [[NSGraphicsContext currentContext] CGContext];
456 CGContextSetInterpolationQuality (viewContextRef, kCGInterpolationNone);
457 CGContextSetShouldAntialias (viewContextRef, NO);
459 // draw screen bitmap directly to Core Graphics context
461 // Draw request before any guest device has set up a framebuffer:
462 // just draw an opaque black rectangle
463 CGContextSetRGBFillColor(viewContextRef, 0, 0, 0, 1.0);
464 CGContextFillRect(viewContextRef, NSRectToCGRect(rect));
466 int w = pixman_image_get_width(pixman_image);
467 int h = pixman_image_get_height(pixman_image);
468 int bitsPerPixel = PIXMAN_FORMAT_BPP(pixman_image_get_format(pixman_image));
469 int stride = pixman_image_get_stride(pixman_image);
470 CGDataProviderRef dataProviderRef = CGDataProviderCreateWithData(
472 pixman_image_get_data(pixman_image),
476 CGImageRef imageRef = CGImageCreate(
479 DIV_ROUND_UP(bitsPerPixel, 8) * 2, //bitsPerComponent
480 bitsPerPixel, //bitsPerPixel
481 stride, //bytesPerRow
482 CGColorSpaceCreateWithName(kCGColorSpaceSRGB), //colorspace
483 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst, //bitmapInfo
484 dataProviderRef, //provider
487 kCGRenderingIntentDefault //intent
489 // selective drawing code (draws only dirty rectangles) (OS X >= 10.4)
490 const NSRect *rectList;
493 CGImageRef clipImageRef;
496 [self getRectsBeingDrawn:&rectList count:&rectCount];
497 for (i = 0; i < rectCount; i++) {
498 clipRect.origin.x = rectList[i].origin.x / cdx;
499 clipRect.origin.y = (float)h - (rectList[i].origin.y + rectList[i].size.height) / cdy;
500 clipRect.size.width = rectList[i].size.width / cdx;
501 clipRect.size.height = rectList[i].size.height / cdy;
502 clipImageRef = CGImageCreateWithImageInRect(
506 CGContextDrawImage (viewContextRef, cgrect(rectList[i]), clipImageRef);
507 CGImageRelease (clipImageRef);
509 CGImageRelease (imageRef);
510 CGDataProviderRelease(dataProviderRef);
514 - (void) setContentDimensions
516 COCOA_DEBUG("QemuCocoaView: setContentDimensions\n");
519 cdx = [[NSScreen mainScreen] frame].size.width / (float)screen.width;
520 cdy = [[NSScreen mainScreen] frame].size.height / (float)screen.height;
522 /* stretches video, but keeps same aspect ratio */
523 if (stretch_video == true) {
524 /* use smallest stretch value - prevents clipping on sides */
525 if (MIN(cdx, cdy) == cdx) {
530 } else { /* No stretching */
533 cw = screen.width * cdx;
534 ch = screen.height * cdy;
535 cx = ([[NSScreen mainScreen] frame].size.width - cw) / 2.0;
536 cy = ([[NSScreen mainScreen] frame].size.height - ch) / 2.0;
547 - (void) updateUIInfoLocked
549 /* Must be called with the iothread lock, i.e. via updateUIInfo */
553 if (!qemu_console_is_graphic(dcl.con)) {
558 NSDictionary *description = [[[self window] screen] deviceDescription];
559 CGDirectDisplayID display = [[description objectForKey:@"NSScreenNumber"] unsignedIntValue];
560 NSSize screenSize = [[[self window] screen] frame].size;
561 CGSize screenPhysicalSize = CGDisplayScreenSize(display);
563 frameSize = isFullscreen ? screenSize : [self frame].size;
564 info.width_mm = frameSize.width / screenSize.width * screenPhysicalSize.width;
565 info.height_mm = frameSize.height / screenSize.height * screenPhysicalSize.height;
567 frameSize = [self frame].size;
574 info.width = frameSize.width;
575 info.height = frameSize.height;
577 dpy_set_ui_info(dcl.con, &info, TRUE);
580 - (void) updateUIInfo
584 * Don't try to tell QEMU about UI information in the application
585 * startup phase -- we haven't yet registered dcl with the QEMU UI
586 * layer, and also trying to take the iothread lock would deadlock.
587 * When cocoa_display_init() does register the dcl, the UI layer
588 * will call cocoa_switch(), which will call updateUIInfo, so
589 * we don't lose any information here.
594 with_iothread_lock(^{
595 [self updateUIInfoLocked];
599 - (void)viewDidMoveToWindow
604 - (void) switchSurface:(pixman_image_t *)image
606 COCOA_DEBUG("QemuCocoaView: switchSurface\n");
608 int w = pixman_image_get_width(image);
609 int h = pixman_image_get_height(image);
610 /* cdx == 0 means this is our very first surface, in which case we need
611 * to recalculate the content dimensions even if it happens to be the size
612 * of the initial empty window.
614 bool isResize = (w != screen.width || h != screen.height || cdx == 0.0);
616 int oldh = screen.height;
618 // Resize before we trigger the redraw, or we'll redraw at the wrong size
619 COCOA_DEBUG("switchSurface: new size %d x %d\n", w, h);
622 [self setContentDimensions];
623 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
626 // update screenBuffer
628 pixman_image_unref(pixman_image);
631 pixman_image = image;
635 [[fullScreenWindow contentView] setFrame:[[NSScreen mainScreen] frame]];
636 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:NO animate:NO];
639 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
640 [normalWindow setFrame:NSMakeRect([normalWindow frame].origin.x, [normalWindow frame].origin.y - h + oldh, w, h + [normalWindow frame].size.height - oldh) display:YES animate:NO];
644 [normalWindow center];
648 - (void) toggleFullScreen:(id)sender
650 COCOA_DEBUG("QemuCocoaView: toggleFullScreen\n");
652 if (isFullscreen) { // switch from fullscreen to desktop
653 isFullscreen = FALSE;
655 [self setContentDimensions];
656 [fullScreenWindow close];
657 [normalWindow setContentView: self];
658 [normalWindow makeKeyAndOrderFront: self];
659 [NSMenu setMenuBarVisible:YES];
660 } else { // switch from desktop to fullscreen
662 [normalWindow orderOut: nil]; /* Hide the window */
664 [self setContentDimensions];
665 [NSMenu setMenuBarVisible:NO];
666 fullScreenWindow = [[NSWindow alloc] initWithContentRect:[[NSScreen mainScreen] frame]
667 styleMask:NSWindowStyleMaskBorderless
668 backing:NSBackingStoreBuffered
670 [fullScreenWindow setAcceptsMouseMovedEvents: YES];
671 [fullScreenWindow setHasShadow:NO];
672 [fullScreenWindow setBackgroundColor: [NSColor blackColor]];
673 [self setFrame:NSMakeRect(cx, cy, cw, ch)];
674 [[fullScreenWindow contentView] addSubview: self];
675 [fullScreenWindow makeKeyAndOrderFront:self];
679 - (void) setFullGrab:(id)sender
681 COCOA_DEBUG("QemuCocoaView: setFullGrab\n");
683 CGEventMask mask = CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventKeyUp) | CGEventMaskBit(kCGEventFlagsChanged);
684 eventsTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault,
685 mask, handleTapEvent, self);
687 warn_report("Could not create event tap, system key combos will not be captured.\n");
690 COCOA_DEBUG("Global events tap created! Will capture system key combos.\n");
693 CFRunLoopRef runLoop = CFRunLoopGetCurrent();
695 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
699 CFRunLoopSourceRef tapEventsSrc = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventsTap, 0);
700 if (!tapEventsSrc ) {
701 warn_report("Could not obtain current CF RunLoop, system key combos will not be captured.\n");
705 CFRunLoopAddSource(runLoop, tapEventsSrc, kCFRunLoopDefaultMode);
706 CFRelease(tapEventsSrc);
709 - (void) toggleKey: (int)keycode {
710 qkbd_state_key_event(kbd, keycode, !qkbd_state_key_get(kbd, keycode));
713 // Does the work of sending input to the monitor
714 - (void) handleMonitorInput:(NSEvent *)event
719 // if the control key is down
720 if ([event modifierFlags] & NSEventModifierFlagControl) {
724 /* translates Macintosh keycodes to QEMU's keysym */
726 static const int without_control_translation[] = {
727 [0 ... 0xff] = 0, // invalid key
729 [kVK_UpArrow] = QEMU_KEY_UP,
730 [kVK_DownArrow] = QEMU_KEY_DOWN,
731 [kVK_RightArrow] = QEMU_KEY_RIGHT,
732 [kVK_LeftArrow] = QEMU_KEY_LEFT,
733 [kVK_Home] = QEMU_KEY_HOME,
734 [kVK_End] = QEMU_KEY_END,
735 [kVK_PageUp] = QEMU_KEY_PAGEUP,
736 [kVK_PageDown] = QEMU_KEY_PAGEDOWN,
737 [kVK_ForwardDelete] = QEMU_KEY_DELETE,
738 [kVK_Delete] = QEMU_KEY_BACKSPACE,
741 static const int with_control_translation[] = {
742 [0 ... 0xff] = 0, // invalid key
744 [kVK_UpArrow] = QEMU_KEY_CTRL_UP,
745 [kVK_DownArrow] = QEMU_KEY_CTRL_DOWN,
746 [kVK_RightArrow] = QEMU_KEY_CTRL_RIGHT,
747 [kVK_LeftArrow] = QEMU_KEY_CTRL_LEFT,
748 [kVK_Home] = QEMU_KEY_CTRL_HOME,
749 [kVK_End] = QEMU_KEY_CTRL_END,
750 [kVK_PageUp] = QEMU_KEY_CTRL_PAGEUP,
751 [kVK_PageDown] = QEMU_KEY_CTRL_PAGEDOWN,
754 if (control_key != 0) { /* If the control key is being used */
755 if ([event keyCode] < ARRAY_SIZE(with_control_translation)) {
756 keysym = with_control_translation[[event keyCode]];
759 if ([event keyCode] < ARRAY_SIZE(without_control_translation)) {
760 keysym = without_control_translation[[event keyCode]];
764 // if not a key that needs translating
766 NSString *ks = [event characters];
767 if ([ks length] > 0) {
768 keysym = [ks characterAtIndex:0];
773 kbd_put_keysym(keysym);
777 - (bool) handleEvent:(NSEvent *)event
781 * Just let OSX have all events that arrive before
782 * applicationDidFinishLaunching.
783 * This avoids a deadlock on the iothread lock, which cocoa_display_init()
784 * will not drop until after the app_started_sem is posted. (In theory
785 * there should not be any such events, but OSX Catalina now emits some.)
789 return bool_with_iothread_lock(^{
790 return [self handleEventLocked:event];
794 - (bool) handleEventLocked:(NSEvent *)event
796 /* Return true if we handled the event, false if it should be given to OSX */
797 COCOA_DEBUG("QemuCocoaView: handleEvent\n");
800 bool mouse_event = false;
801 static bool switched_to_fullscreen = false;
802 // Location of event in virtual screen coordinates
803 NSPoint p = [self screenLocationOfEvent:event];
804 NSUInteger modifiers = [event modifierFlags];
807 * Check -[NSEvent modifierFlags] here.
809 * There is a NSEventType for an event notifying the change of
810 * -[NSEvent modifierFlags], NSEventTypeFlagsChanged but these operations
811 * are performed for any events because a modifier state may change while
812 * the application is inactive (i.e. no events fire) and we don't want to
813 * wait for another modifier state change to detect such a change.
815 * NSEventModifierFlagCapsLock requires a special treatment. The other flags
816 * are handled in similar manners.
818 * NSEventModifierFlagCapsLock
819 * ---------------------------
821 * If CapsLock state is changed, "up" and "down" events will be fired in
822 * sequence, effectively updates CapsLock state on the guest.
827 * If a flag is not set, fire "up" events for all keys which correspond to
828 * the flag. Note that "down" events are not fired here because the flags
829 * checked here do not tell what exact keys are down.
831 * If one of the keys corresponding to a flag is down, we rely on
832 * -[NSEvent keyCode] of an event whose -[NSEvent type] is
833 * NSEventTypeFlagsChanged to know the exact key which is down, which has
834 * the following two downsides:
835 * - It does not work when the application is inactive as described above.
836 * - It malfactions *after* the modifier state is changed while the
837 * application is inactive. It is because -[NSEvent keyCode] does not tell
838 * if the key is up or down, and requires to infer the current state from
839 * the previous state. It is still possible to fix such a malfanction by
840 * completely leaving your hands from the keyboard, which hopefully makes
841 * this implementation usable enough.
843 if (!!(modifiers & NSEventModifierFlagCapsLock) !=
844 qkbd_state_modifier_get(kbd, QKBD_MOD_CAPSLOCK)) {
845 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, true);
846 qkbd_state_key_event(kbd, Q_KEY_CODE_CAPS_LOCK, false);
849 if (!(modifiers & NSEventModifierFlagShift)) {
850 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT, false);
851 qkbd_state_key_event(kbd, Q_KEY_CODE_SHIFT_R, false);
853 if (!(modifiers & NSEventModifierFlagControl)) {
854 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL, false);
855 qkbd_state_key_event(kbd, Q_KEY_CODE_CTRL_R, false);
857 if (!(modifiers & NSEventModifierFlagOption)) {
859 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
860 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
862 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
863 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
866 if (!(modifiers & NSEventModifierFlagCommand)) {
868 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT, false);
869 qkbd_state_key_event(kbd, Q_KEY_CODE_ALT_R, false);
871 qkbd_state_key_event(kbd, Q_KEY_CODE_META_L, false);
872 qkbd_state_key_event(kbd, Q_KEY_CODE_META_R, false);
876 switch ([event type]) {
877 case NSEventTypeFlagsChanged:
878 switch ([event keyCode]) {
880 if (!!(modifiers & NSEventModifierFlagShift)) {
881 [self toggleKey:Q_KEY_CODE_SHIFT];
886 if (!!(modifiers & NSEventModifierFlagShift)) {
887 [self toggleKey:Q_KEY_CODE_SHIFT_R];
892 if (!!(modifiers & NSEventModifierFlagControl)) {
893 [self toggleKey:Q_KEY_CODE_CTRL];
897 case kVK_RightControl:
898 if (!!(modifiers & NSEventModifierFlagControl)) {
899 [self toggleKey:Q_KEY_CODE_CTRL_R];
904 if (!!(modifiers & NSEventModifierFlagOption)) {
906 [self toggleKey:Q_KEY_CODE_META_L];
908 [self toggleKey:Q_KEY_CODE_ALT];
913 case kVK_RightOption:
914 if (!!(modifiers & NSEventModifierFlagOption)) {
916 [self toggleKey:Q_KEY_CODE_META_R];
918 [self toggleKey:Q_KEY_CODE_ALT_R];
923 /* Don't pass command key changes to guest unless mouse is grabbed */
925 if (isMouseGrabbed &&
926 !!(modifiers & NSEventModifierFlagCommand) &&
927 left_command_key_enabled) {
929 [self toggleKey:Q_KEY_CODE_ALT];
931 [self toggleKey:Q_KEY_CODE_META_L];
936 case kVK_RightCommand:
937 if (isMouseGrabbed &&
938 !!(modifiers & NSEventModifierFlagCommand)) {
940 [self toggleKey:Q_KEY_CODE_ALT_R];
942 [self toggleKey:Q_KEY_CODE_META_R];
948 case NSEventTypeKeyDown:
949 keycode = cocoa_keycode_to_qemu([event keyCode]);
951 // forward command key combos to the host UI unless the mouse is grabbed
952 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
954 * Prevent the command key from being stuck down in the guest
955 * when using Command-F to switch to full screen mode.
957 if (keycode == Q_KEY_CODE_F) {
958 switched_to_fullscreen = true;
965 // handle control + alt Key Combos (ctrl+alt+[1..9,g] is reserved for QEMU)
966 if (([event modifierFlags] & NSEventModifierFlagControl) && ([event modifierFlags] & NSEventModifierFlagOption)) {
967 NSString *keychar = [event charactersIgnoringModifiers];
968 if ([keychar length] == 1) {
969 char key = [keychar characterAtIndex:0];
972 // enable graphic console
974 console_select(key - '0' - 1); /* ascii math */
977 // release the mouse grab
985 if (qemu_console_is_graphic(NULL)) {
986 qkbd_state_key_event(kbd, keycode, true);
988 [self handleMonitorInput: event];
991 case NSEventTypeKeyUp:
992 keycode = cocoa_keycode_to_qemu([event keyCode]);
994 // don't pass the guest a spurious key-up if we treated this
995 // command-key combo as a host UI action
996 if (!isMouseGrabbed && ([event modifierFlags] & NSEventModifierFlagCommand)) {
1000 if (qemu_console_is_graphic(NULL)) {
1001 qkbd_state_key_event(kbd, keycode, false);
1004 case NSEventTypeMouseMoved:
1005 if (isAbsoluteEnabled) {
1006 // Cursor re-entered into a window might generate events bound to screen coordinates
1007 // and `nil` window property, and in full screen mode, current window might not be
1008 // key window, where event location alone should suffice.
1009 if (![self screenContainsPoint:p] || !([[self window] isKeyWindow] || isFullscreen)) {
1010 if (isMouseGrabbed) {
1014 if (!isMouseGrabbed) {
1021 case NSEventTypeLeftMouseDown:
1022 buttons |= MOUSE_EVENT_LBUTTON;
1025 case NSEventTypeRightMouseDown:
1026 buttons |= MOUSE_EVENT_RBUTTON;
1029 case NSEventTypeOtherMouseDown:
1030 buttons |= MOUSE_EVENT_MBUTTON;
1033 case NSEventTypeLeftMouseDragged:
1034 buttons |= MOUSE_EVENT_LBUTTON;
1037 case NSEventTypeRightMouseDragged:
1038 buttons |= MOUSE_EVENT_RBUTTON;
1041 case NSEventTypeOtherMouseDragged:
1042 buttons |= MOUSE_EVENT_MBUTTON;
1045 case NSEventTypeLeftMouseUp:
1047 if (!isMouseGrabbed && [self screenContainsPoint:p]) {
1049 * In fullscreen mode, the window of cocoaView may not be the
1050 * key window, therefore the position relative to the virtual
1051 * screen alone will be sufficient.
1053 if(isFullscreen || [[self window] isKeyWindow]) {
1058 case NSEventTypeRightMouseUp:
1061 case NSEventTypeOtherMouseUp:
1064 case NSEventTypeScrollWheel:
1066 * Send wheel events to the guest regardless of window focus.
1067 * This is in-line with standard Mac OS X UI behaviour.
1071 * We shouldn't have got a scroll event when deltaY and delta Y
1072 * are zero, hence no harm in dropping the event
1074 if ([event deltaY] != 0 || [event deltaX] != 0) {
1075 /* Determine if this is a scroll up or scroll down event */
1076 if ([event deltaY] != 0) {
1077 buttons = ([event deltaY] > 0) ?
1078 INPUT_BUTTON_WHEEL_UP : INPUT_BUTTON_WHEEL_DOWN;
1079 } else if ([event deltaX] != 0) {
1080 buttons = ([event deltaX] > 0) ?
1081 INPUT_BUTTON_WHEEL_LEFT : INPUT_BUTTON_WHEEL_RIGHT;
1084 qemu_input_queue_btn(dcl.con, buttons, true);
1085 qemu_input_event_sync();
1086 qemu_input_queue_btn(dcl.con, buttons, false);
1087 qemu_input_event_sync();
1091 * Since deltaX/deltaY also report scroll wheel events we prevent mouse
1092 * movement code from executing.
1094 mouse_event = false;
1101 /* Don't send button events to the guest unless we've got a
1102 * mouse grab or window focus. If we have neither then this event
1103 * is the user clicking on the background window to activate and
1104 * bring us to the front, which will be done by the sendEvent
1105 * call below. We definitely don't want to pass that click through
1108 if ((isMouseGrabbed || [[self window] isKeyWindow]) &&
1109 (last_buttons != buttons)) {
1110 static uint32_t bmap[INPUT_BUTTON__MAX] = {
1111 [INPUT_BUTTON_LEFT] = MOUSE_EVENT_LBUTTON,
1112 [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,
1113 [INPUT_BUTTON_RIGHT] = MOUSE_EVENT_RBUTTON
1115 qemu_input_update_buttons(dcl.con, bmap, last_buttons, buttons);
1116 last_buttons = buttons;
1118 if (isMouseGrabbed) {
1119 if (isAbsoluteEnabled) {
1120 /* Note that the origin for Cocoa mouse coords is bottom left, not top left.
1121 * The check on screenContainsPoint is to avoid sending out of range values for
1122 * clicks in the titlebar.
1124 if ([self screenContainsPoint:p]) {
1125 qemu_input_queue_abs(dcl.con, INPUT_AXIS_X, p.x, 0, screen.width);
1126 qemu_input_queue_abs(dcl.con, INPUT_AXIS_Y, screen.height - p.y, 0, screen.height);
1129 qemu_input_queue_rel(dcl.con, INPUT_AXIS_X, (int)[event deltaX]);
1130 qemu_input_queue_rel(dcl.con, INPUT_AXIS_Y, (int)[event deltaY]);
1135 qemu_input_event_sync();
1142 COCOA_DEBUG("QemuCocoaView: grabMouse\n");
1144 if (!isFullscreen) {
1146 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s - (Press ctrl + alt + g to release Mouse)", qemu_name]];
1148 [normalWindow setTitle:@"QEMU - (Press ctrl + alt + g to release Mouse)"];
1151 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1152 isMouseGrabbed = TRUE; // while isMouseGrabbed = TRUE, QemuCocoaApp sends all events to [cocoaView handleEvent:]
1155 - (void) ungrabMouse
1157 COCOA_DEBUG("QemuCocoaView: ungrabMouse\n");
1159 if (!isFullscreen) {
1161 [normalWindow setTitle:[NSString stringWithFormat:@"QEMU %s", qemu_name]];
1163 [normalWindow setTitle:@"QEMU"];
1165 [self unhideCursor];
1166 CGAssociateMouseAndMouseCursorPosition(TRUE);
1167 isMouseGrabbed = FALSE;
1170 - (void) setAbsoluteEnabled:(BOOL)tIsAbsoluteEnabled {
1171 isAbsoluteEnabled = tIsAbsoluteEnabled;
1172 if (isMouseGrabbed) {
1173 CGAssociateMouseAndMouseCursorPosition(isAbsoluteEnabled);
1176 - (BOOL) isMouseGrabbed {return isMouseGrabbed;}
1177 - (BOOL) isAbsoluteEnabled {return isAbsoluteEnabled;}
1178 - (float) cdx {return cdx;}
1179 - (float) cdy {return cdy;}
1180 - (QEMUScreen) gscreen {return screen;}
1183 * Makes the target think all down keys are being released.
1184 * This prevents a stuck key problem, since we will not see
1185 * key up events for those keys after we have lost focus.
1187 - (void) raiseAllKeys
1189 with_iothread_lock(^{
1190 qkbd_state_lift_all_keys(kbd);
1198 ------------------------------------------------------
1199 QemuCocoaAppController
1200 ------------------------------------------------------
1202 @interface QemuCocoaAppController : NSObject
1203 <NSWindowDelegate, NSApplicationDelegate>
1206 - (void)doToggleFullScreen:(id)sender;
1207 - (void)toggleFullScreen:(id)sender;
1208 - (void)showQEMUDoc:(id)sender;
1209 - (void)zoomToFit:(id) sender;
1210 - (void)displayConsole:(id)sender;
1211 - (void)pauseQEMU:(id)sender;
1212 - (void)resumeQEMU:(id)sender;
1213 - (void)displayPause;
1214 - (void)removePause;
1215 - (void)restartQEMU:(id)sender;
1216 - (void)powerDownQEMU:(id)sender;
1217 - (void)ejectDeviceMedia:(id)sender;
1218 - (void)changeDeviceMedia:(id)sender;
1220 - (void)openDocumentation:(NSString *)filename;
1221 - (IBAction) do_about_menu_item: (id) sender;
1222 - (void)adjustSpeed:(id)sender;
1225 @implementation QemuCocoaAppController
1228 COCOA_DEBUG("QemuCocoaAppController: init\n");
1230 self = [super init];
1233 // create a view and add it to the window
1234 cocoaView = [[QemuCocoaView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 640.0, 480.0)];
1236 error_report("(cocoa) can't create a view");
1241 normalWindow = [[NSWindow alloc] initWithContentRect:[cocoaView frame]
1242 styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskClosable
1243 backing:NSBackingStoreBuffered defer:NO];
1245 error_report("(cocoa) can't create window");
1248 [normalWindow setAcceptsMouseMovedEvents:YES];
1249 [normalWindow setTitle:@"QEMU"];
1250 [normalWindow setContentView:cocoaView];
1251 [normalWindow makeKeyAndOrderFront:self];
1252 [normalWindow center];
1253 [normalWindow setDelegate: self];
1254 stretch_video = false;
1256 /* Used for displaying pause on the screen */
1257 pauseLabel = [NSTextField new];
1258 [pauseLabel setBezeled:YES];
1259 [pauseLabel setDrawsBackground:YES];
1260 [pauseLabel setBackgroundColor: [NSColor whiteColor]];
1261 [pauseLabel setEditable:NO];
1262 [pauseLabel setSelectable:NO];
1263 [pauseLabel setStringValue: @"Paused"];
1264 [pauseLabel setFont: [NSFont fontWithName: @"Helvetica" size: 90]];
1265 [pauseLabel setTextColor: [NSColor blackColor]];
1266 [pauseLabel sizeToFit];
1273 COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
1276 [cocoaView release];
1280 - (void)applicationDidFinishLaunching: (NSNotification *) note
1282 COCOA_DEBUG("QemuCocoaAppController: applicationDidFinishLaunching\n");
1283 allow_events = true;
1284 /* Tell cocoa_display_init to proceed */
1285 qemu_sem_post(&app_started_sem);
1288 - (void)applicationWillTerminate:(NSNotification *)aNotification
1290 COCOA_DEBUG("QemuCocoaAppController: applicationWillTerminate\n");
1292 qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
1295 * Sleep here, because returning will cause OSX to kill us
1296 * immediately; the QEMU main loop will handle the shutdown
1297 * request and terminate the process.
1299 [NSThread sleepForTimeInterval:INFINITY];
1302 - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
1307 - (NSApplicationTerminateReply)applicationShouldTerminate:
1308 (NSApplication *)sender
1310 COCOA_DEBUG("QemuCocoaAppController: applicationShouldTerminate\n");
1311 return [self verifyQuit];
1314 - (void)windowDidChangeScreen:(NSNotification *)notification
1316 [cocoaView updateUIInfo];
1319 - (void)windowDidResize:(NSNotification *)notification
1321 [cocoaView updateUIInfo];
1324 /* Called when the user clicks on a window's close button */
1325 - (BOOL)windowShouldClose:(id)sender
1327 COCOA_DEBUG("QemuCocoaAppController: windowShouldClose\n");
1328 [NSApp terminate: sender];
1329 /* If the user allows the application to quit then the call to
1330 * NSApp terminate will never return. If we get here then the user
1331 * cancelled the quit, so we should return NO to not permit the
1332 * closing of this window.
1337 /* Called when QEMU goes into the background */
1338 - (void) applicationWillResignActive: (NSNotification *)aNotification
1340 COCOA_DEBUG("QemuCocoaAppController: applicationWillResignActive\n");
1341 [cocoaView ungrabMouse];
1342 [cocoaView raiseAllKeys];
1345 /* We abstract the method called by the Enter Fullscreen menu item
1346 * because Mac OS 10.7 and higher disables it. This is because of the
1347 * menu item's old selector's name toggleFullScreen:
1349 - (void) doToggleFullScreen:(id)sender
1351 [self toggleFullScreen:(id)sender];
1354 - (void)toggleFullScreen:(id)sender
1356 COCOA_DEBUG("QemuCocoaAppController: toggleFullScreen\n");
1358 [cocoaView toggleFullScreen:sender];
1361 - (void) setFullGrab:(id)sender
1363 COCOA_DEBUG("QemuCocoaAppController: setFullGrab\n");
1365 [cocoaView setFullGrab:sender];
1368 /* Tries to find then open the specified filename */
1369 - (void) openDocumentation: (NSString *) filename
1371 /* Where to look for local files */
1372 NSString *path_array[] = {@"../share/doc/qemu/", @"../doc/qemu/", @"docs/"};
1373 NSString *full_file_path;
1374 NSURL *full_file_url;
1376 /* iterate thru the possible paths until the file is found */
1378 for (index = 0; index < ARRAY_SIZE(path_array); index++) {
1379 full_file_path = [[NSBundle mainBundle] executablePath];
1380 full_file_path = [full_file_path stringByDeletingLastPathComponent];
1381 full_file_path = [NSString stringWithFormat: @"%@/%@%@", full_file_path,
1382 path_array[index], filename];
1383 full_file_url = [NSURL fileURLWithPath: full_file_path
1384 isDirectory: false];
1385 if ([[NSWorkspace sharedWorkspace] openURL: full_file_url] == YES) {
1390 /* If none of the paths opened a file */
1392 QEMU_Alert(@"Failed to open file");
1395 - (void)showQEMUDoc:(id)sender
1397 COCOA_DEBUG("QemuCocoaAppController: showQEMUDoc\n");
1399 [self openDocumentation: @"index.html"];
1402 /* Stretches video to fit host monitor size */
1403 - (void)zoomToFit:(id) sender
1405 stretch_video = !stretch_video;
1406 if (stretch_video == true) {
1407 [sender setState: NSControlStateValueOn];
1409 [sender setState: NSControlStateValueOff];
1413 /* Displays the console on the screen */
1414 - (void)displayConsole:(id)sender
1416 console_select([sender tag]);
1419 /* Pause the guest */
1420 - (void)pauseQEMU:(id)sender
1422 with_iothread_lock(^{
1425 [sender setEnabled: NO];
1426 [[[sender menu] itemWithTitle: @"Resume"] setEnabled: YES];
1427 [self displayPause];
1430 /* Resume running the guest operating system */
1431 - (void)resumeQEMU:(id) sender
1433 with_iothread_lock(^{
1436 [sender setEnabled: NO];
1437 [[[sender menu] itemWithTitle: @"Pause"] setEnabled: YES];
1441 /* Displays the word pause on the screen */
1442 - (void)displayPause
1444 /* Coordinates have to be calculated each time because the window can change its size */
1445 int xCoord, yCoord, width, height;
1446 xCoord = ([normalWindow frame].size.width - [pauseLabel frame].size.width)/2;
1447 yCoord = [normalWindow frame].size.height - [pauseLabel frame].size.height - ([pauseLabel frame].size.height * .5);
1448 width = [pauseLabel frame].size.width;
1449 height = [pauseLabel frame].size.height;
1450 [pauseLabel setFrame: NSMakeRect(xCoord, yCoord, width, height)];
1451 [cocoaView addSubview: pauseLabel];
1454 /* Removes the word pause from the screen */
1457 [pauseLabel removeFromSuperview];
1461 - (void)restartQEMU:(id)sender
1463 with_iothread_lock(^{
1464 qmp_system_reset(NULL);
1468 /* Powers down QEMU */
1469 - (void)powerDownQEMU:(id)sender
1471 with_iothread_lock(^{
1472 qmp_system_powerdown(NULL);
1476 /* Ejects the media.
1477 * Uses sender's tag to figure out the device to eject.
1479 - (void)ejectDeviceMedia:(id)sender
1482 drive = [sender representedObject];
1485 QEMU_Alert(@"Failed to find drive to eject!");
1489 __block Error *err = NULL;
1490 with_iothread_lock(^{
1491 qmp_eject(true, [drive cStringUsingEncoding: NSASCIIStringEncoding],
1492 false, NULL, false, false, &err);
1494 handleAnyDeviceErrors(err);
1497 /* Displays a dialog box asking the user to select an image file to load.
1498 * Uses sender's represented object value to figure out which drive to use.
1500 - (void)changeDeviceMedia:(id)sender
1502 /* Find the drive name */
1504 drive = [sender representedObject];
1507 QEMU_Alert(@"Could not find drive!");
1511 /* Display the file open dialog */
1512 NSOpenPanel * openPanel;
1513 openPanel = [NSOpenPanel openPanel];
1514 [openPanel setCanChooseFiles: YES];
1515 [openPanel setAllowsMultipleSelection: NO];
1516 if([openPanel runModal] == NSModalResponseOK) {
1517 NSString * file = [[[openPanel URLs] objectAtIndex: 0] path];
1520 QEMU_Alert(@"Failed to convert URL to file path!");
1524 __block Error *err = NULL;
1525 with_iothread_lock(^{
1526 qmp_blockdev_change_medium(true,
1527 [drive cStringUsingEncoding:
1528 NSASCIIStringEncoding],
1530 [file cStringUsingEncoding:
1531 NSASCIIStringEncoding],
1536 handleAnyDeviceErrors(err);
1540 /* Verifies if the user really wants to quit */
1543 NSAlert *alert = [NSAlert new];
1544 [alert autorelease];
1545 [alert setMessageText: @"Are you sure you want to quit QEMU?"];
1546 [alert addButtonWithTitle: @"Cancel"];
1547 [alert addButtonWithTitle: @"Quit"];
1548 if([alert runModal] == NSAlertSecondButtonReturn) {
1555 /* The action method for the About menu item */
1556 - (IBAction) do_about_menu_item: (id) sender
1558 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1559 char *icon_path_c = get_relocated_path(CONFIG_QEMU_ICONDIR "/hicolor/512x512/apps/qemu.png");
1560 NSString *icon_path = [NSString stringWithUTF8String:icon_path_c];
1561 g_free(icon_path_c);
1562 NSImage *icon = [[NSImage alloc] initWithContentsOfFile:icon_path];
1563 NSString *version = @"QEMU emulator version " QEMU_FULL_VERSION;
1564 NSString *copyright = @QEMU_COPYRIGHT;
1565 NSDictionary *options;
1568 NSAboutPanelOptionApplicationIcon : icon,
1569 NSAboutPanelOptionApplicationVersion : version,
1570 @"Copyright" : copyright,
1575 NSAboutPanelOptionApplicationVersion : version,
1576 @"Copyright" : copyright,
1579 [NSApp orderFrontStandardAboutPanelWithOptions:options];
1583 /* Used by the Speed menu items */
1584 - (void)adjustSpeed:(id)sender
1586 int throttle_pct; /* throttle percentage */
1589 menu = [sender menu];
1592 /* Unselect the currently selected item */
1593 for (NSMenuItem *item in [menu itemArray]) {
1594 if (item.state == NSControlStateValueOn) {
1595 [item setState: NSControlStateValueOff];
1601 // check the menu item
1602 [sender setState: NSControlStateValueOn];
1604 // get the throttle percentage
1605 throttle_pct = [sender tag];
1607 with_iothread_lock(^{
1608 cpu_throttle_set(throttle_pct);
1610 COCOA_DEBUG("cpu throttling at %d%c\n", cpu_throttle_get_percentage(), '%');
1615 @interface QemuApplication : NSApplication
1618 @implementation QemuApplication
1619 - (void)sendEvent:(NSEvent *)event
1621 COCOA_DEBUG("QemuApplication: sendEvent\n");
1622 if (![cocoaView handleEvent:event]) {
1623 [super sendEvent: event];
1628 static void create_initial_menus(void)
1632 NSMenuItem *menuItem;
1634 [NSApp setMainMenu:[[NSMenu alloc] init]];
1635 [NSApp setServicesMenu:[[NSMenu alloc] initWithTitle:@"Services"]];
1638 menu = [[NSMenu alloc] initWithTitle:@""];
1639 [menu addItemWithTitle:@"About QEMU" action:@selector(do_about_menu_item:) keyEquivalent:@""]; // About QEMU
1640 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1641 menuItem = [menu addItemWithTitle:@"Services" action:nil keyEquivalent:@""];
1642 [menuItem setSubmenu:[NSApp servicesMenu]];
1643 [menu addItem:[NSMenuItem separatorItem]];
1644 [menu addItemWithTitle:@"Hide QEMU" action:@selector(hide:) keyEquivalent:@"h"]; //Hide QEMU
1645 menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"]; // Hide Others
1646 [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
1647 [menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""]; // Show All
1648 [menu addItem:[NSMenuItem separatorItem]]; //Separator
1649 [menu addItemWithTitle:@"Quit QEMU" action:@selector(terminate:) keyEquivalent:@"q"];
1650 menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
1651 [menuItem setSubmenu:menu];
1652 [[NSApp mainMenu] addItem:menuItem];
1653 [NSApp performSelector:@selector(setAppleMenu:) withObject:menu]; // Workaround (this method is private since 10.4+)
1656 menu = [[NSMenu alloc] initWithTitle: @"Machine"];
1657 [menu setAutoenablesItems: NO];
1658 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Pause" action: @selector(pauseQEMU:) keyEquivalent: @""] autorelease]];
1659 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Resume" action: @selector(resumeQEMU:) keyEquivalent: @""] autorelease];
1660 [menu addItem: menuItem];
1661 [menuItem setEnabled: NO];
1662 [menu addItem: [NSMenuItem separatorItem]];
1663 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Reset" action: @selector(restartQEMU:) keyEquivalent: @""] autorelease]];
1664 [menu addItem: [[[NSMenuItem alloc] initWithTitle: @"Power Down" action: @selector(powerDownQEMU:) keyEquivalent: @""] autorelease]];
1665 menuItem = [[[NSMenuItem alloc] initWithTitle: @"Machine" action:nil keyEquivalent:@""] autorelease];
1666 [menuItem setSubmenu:menu];
1667 [[NSApp mainMenu] addItem:menuItem];
1670 menu = [[NSMenu alloc] initWithTitle:@"View"];
1671 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Enter Fullscreen" action:@selector(doToggleFullScreen:) keyEquivalent:@"f"] autorelease]]; // Fullscreen
1672 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Zoom To Fit" action:@selector(zoomToFit:) keyEquivalent:@""] autorelease]];
1673 menuItem = [[[NSMenuItem alloc] initWithTitle:@"View" action:nil keyEquivalent:@""] autorelease];
1674 [menuItem setSubmenu:menu];
1675 [[NSApp mainMenu] addItem:menuItem];
1678 menu = [[NSMenu alloc] initWithTitle:@"Speed"];
1680 // Add the rest of the Speed menu items
1681 int p, percentage, throttle_pct;
1682 for (p = 10; p >= 0; p--)
1684 percentage = p * 10 > 1 ? p * 10 : 1; // prevent a 0% menu item
1686 menuItem = [[[NSMenuItem alloc]
1687 initWithTitle: [NSString stringWithFormat: @"%d%%", percentage] action:@selector(adjustSpeed:) keyEquivalent:@""] autorelease];
1689 if (percentage == 100) {
1690 [menuItem setState: NSControlStateValueOn];
1693 /* Calculate the throttle percentage */
1694 throttle_pct = -1 * percentage + 100;
1696 [menuItem setTag: throttle_pct];
1697 [menu addItem: menuItem];
1699 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Speed" action:nil keyEquivalent:@""] autorelease];
1700 [menuItem setSubmenu:menu];
1701 [[NSApp mainMenu] addItem:menuItem];
1704 menu = [[NSMenu alloc] initWithTitle:@"Window"];
1705 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"] autorelease]]; // Miniaturize
1706 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1707 [menuItem setSubmenu:menu];
1708 [[NSApp mainMenu] addItem:menuItem];
1709 [NSApp setWindowsMenu:menu];
1712 menu = [[NSMenu alloc] initWithTitle:@"Help"];
1713 [menu addItem: [[[NSMenuItem alloc] initWithTitle:@"QEMU Documentation" action:@selector(showQEMUDoc:) keyEquivalent:@"?"] autorelease]]; // QEMU Help
1714 menuItem = [[[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""] autorelease];
1715 [menuItem setSubmenu:menu];
1716 [[NSApp mainMenu] addItem:menuItem];
1719 /* Returns a name for a given console */
1720 static NSString * getConsoleName(QemuConsole * console)
1722 g_autofree char *label = qemu_console_get_label(console);
1724 return [NSString stringWithUTF8String:label];
1727 /* Add an entry to the View menu for each console */
1728 static void add_console_menu_entries(void)
1731 NSMenuItem *menuItem;
1734 menu = [[[NSApp mainMenu] itemWithTitle:@"View"] submenu];
1736 [menu addItem:[NSMenuItem separatorItem]];
1738 while (qemu_console_lookup_by_index(index) != NULL) {
1739 menuItem = [[[NSMenuItem alloc] initWithTitle: getConsoleName(qemu_console_lookup_by_index(index))
1740 action: @selector(displayConsole:) keyEquivalent: @""] autorelease];
1741 [menuItem setTag: index];
1742 [menu addItem: menuItem];
1747 /* Make menu items for all removable devices.
1748 * Each device is given an 'Eject' and 'Change' menu item.
1750 static void addRemovableDevicesMenuItems(void)
1753 NSMenuItem *menuItem;
1754 BlockInfoList *currentDevice, *pointerToFree;
1755 NSString *deviceName;
1757 currentDevice = qmp_query_block(NULL);
1758 pointerToFree = currentDevice;
1760 menu = [[[NSApp mainMenu] itemWithTitle:@"Machine"] submenu];
1762 // Add a separator between related groups of menu items
1763 [menu addItem:[NSMenuItem separatorItem]];
1765 // Set the attributes to the "Removable Media" menu item
1766 NSString *titleString = @"Removable Media";
1767 NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:titleString];
1768 NSColor *newColor = [NSColor blackColor];
1769 NSFontManager *fontManager = [NSFontManager sharedFontManager];
1770 NSFont *font = [fontManager fontWithFamily:@"Helvetica"
1771 traits:NSBoldFontMask|NSItalicFontMask
1774 [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [titleString length])];
1775 [attString addAttribute:NSForegroundColorAttributeName value:newColor range:NSMakeRange(0, [titleString length])];
1776 [attString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt: 1] range:NSMakeRange(0, [titleString length])];
1778 // Add the "Removable Media" menu item
1779 menuItem = [NSMenuItem new];
1780 [menuItem setAttributedTitle: attString];
1781 [menuItem setEnabled: NO];
1782 [menu addItem: menuItem];
1784 /* Loop through all the block devices in the emulator */
1785 while (currentDevice) {
1786 deviceName = [[NSString stringWithFormat: @"%s", currentDevice->value->device] retain];
1788 if(currentDevice->value->removable) {
1789 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Change %s...", currentDevice->value->device]
1790 action: @selector(changeDeviceMedia:)
1791 keyEquivalent: @""];
1792 [menu addItem: menuItem];
1793 [menuItem setRepresentedObject: deviceName];
1794 [menuItem autorelease];
1796 menuItem = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: @"Eject %s", currentDevice->value->device]
1797 action: @selector(ejectDeviceMedia:)
1798 keyEquivalent: @""];
1799 [menu addItem: menuItem];
1800 [menuItem setRepresentedObject: deviceName];
1801 [menuItem autorelease];
1803 currentDevice = currentDevice->next;
1805 qapi_free_BlockInfoList(pointerToFree);
1808 @interface QemuCocoaPasteboardTypeOwner : NSObject<NSPasteboardTypeOwner>
1811 @implementation QemuCocoaPasteboardTypeOwner
1813 - (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)type
1815 if (type != NSPasteboardTypeString) {
1819 with_iothread_lock(^{
1820 QemuClipboardInfo *info = qemu_clipboard_info_ref(cbinfo);
1821 qemu_event_reset(&cbevent);
1822 qemu_clipboard_request(info, QEMU_CLIPBOARD_TYPE_TEXT);
1824 while (info == cbinfo &&
1825 info->types[QEMU_CLIPBOARD_TYPE_TEXT].available &&
1826 info->types[QEMU_CLIPBOARD_TYPE_TEXT].data == NULL) {
1827 qemu_mutex_unlock_iothread();
1828 qemu_event_wait(&cbevent);
1829 qemu_mutex_lock_iothread();
1832 if (info == cbinfo) {
1833 NSData *data = [[NSData alloc] initWithBytes:info->types[QEMU_CLIPBOARD_TYPE_TEXT].data
1834 length:info->types[QEMU_CLIPBOARD_TYPE_TEXT].size];
1835 [sender setData:data forType:NSPasteboardTypeString];
1839 qemu_clipboard_info_unref(info);
1845 static QemuCocoaPasteboardTypeOwner *cbowner;
1847 static void cocoa_clipboard_notify(Notifier *notifier, void *data);
1848 static void cocoa_clipboard_request(QemuClipboardInfo *info,
1849 QemuClipboardType type);
1851 static QemuClipboardPeer cbpeer = {
1853 .notifier = { .notify = cocoa_clipboard_notify },
1854 .request = cocoa_clipboard_request
1857 static void cocoa_clipboard_update_info(QemuClipboardInfo *info)
1859 if (info->owner == &cbpeer || info->selection != QEMU_CLIPBOARD_SELECTION_CLIPBOARD) {
1863 if (info != cbinfo) {
1864 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1865 qemu_clipboard_info_unref(cbinfo);
1866 cbinfo = qemu_clipboard_info_ref(info);
1867 cbchangecount = [[NSPasteboard generalPasteboard] declareTypes:@[NSPasteboardTypeString] owner:cbowner];
1871 qemu_event_set(&cbevent);
1874 static void cocoa_clipboard_notify(Notifier *notifier, void *data)
1876 QemuClipboardNotify *notify = data;
1878 switch (notify->type) {
1879 case QEMU_CLIPBOARD_UPDATE_INFO:
1880 cocoa_clipboard_update_info(notify->info);
1882 case QEMU_CLIPBOARD_RESET_SERIAL:
1888 static void cocoa_clipboard_request(QemuClipboardInfo *info,
1889 QemuClipboardType type)
1894 case QEMU_CLIPBOARD_TYPE_TEXT:
1895 text = [[NSPasteboard generalPasteboard] dataForType:NSPasteboardTypeString];
1897 qemu_clipboard_set_data(&cbpeer, info, type,
1898 [text length], [text bytes], true);
1908 * The startup process for the OSX/Cocoa UI is complicated, because
1909 * OSX insists that the UI runs on the initial main thread, and so we
1910 * need to start a second thread which runs the vl.c qemu_main():
1912 * Initial thread: 2nd thread:
1914 * create qemu-main thread
1915 * wait on display_init semaphore
1918 * in cocoa_display_init():
1919 * post the display_init semaphore
1920 * wait on app_started semaphore
1921 * create application, menus, etc
1922 * enter OSX run loop
1923 * in applicationDidFinishLaunching:
1924 * post app_started semaphore
1925 * tell main thread to fullscreen if needed
1927 * run qemu main-loop
1929 * We do this in two stages so that we don't do the creation of the
1930 * GUI application menus and so on for command line options like --help
1931 * where we want to just print text to stdout and exit immediately.
1934 static void *call_qemu_main(void *opaque)
1938 COCOA_DEBUG("Second thread: calling qemu_main()\n");
1939 status = qemu_main(gArgc, gArgv, *_NSGetEnviron());
1940 COCOA_DEBUG("Second thread: qemu_main() returned, exiting\n");
1945 int main (int argc, char **argv) {
1948 COCOA_DEBUG("Entered main()\n");
1952 qemu_sem_init(&display_init_sem, 0);
1953 qemu_sem_init(&app_started_sem, 0);
1955 qemu_thread_create(&thread, "qemu_main", call_qemu_main,
1956 NULL, QEMU_THREAD_DETACHED);
1958 COCOA_DEBUG("Main thread: waiting for display_init_sem\n");
1959 qemu_sem_wait(&display_init_sem);
1960 COCOA_DEBUG("Main thread: initializing app\n");
1962 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
1964 // Pull this console process up to being a fully-fledged graphical
1965 // app with a menubar and Dock icon
1966 ProcessSerialNumber psn = { 0, kCurrentProcess };
1967 TransformProcessType(&psn, kProcessTransformToForegroundApplication);
1969 [QemuApplication sharedApplication];
1971 create_initial_menus();
1974 * Create the menu entries which depend on QEMU state (for consoles
1975 * and removeable devices). These make calls back into QEMU functions,
1976 * which is OK because at this point we know that the second thread
1977 * holds the iothread lock and is synchronously waiting for us to
1980 add_console_menu_entries();
1981 addRemovableDevicesMenuItems();
1983 // Create an Application controller
1984 QemuCocoaAppController *appController = [[QemuCocoaAppController alloc] init];
1985 [NSApp setDelegate:appController];
1987 // Start the main event loop
1988 COCOA_DEBUG("Main thread: entering OSX run loop\n");
1990 COCOA_DEBUG("Main thread: left OSX run loop, exiting\n");
1992 [appController release];
2001 static void cocoa_update(DisplayChangeListener *dcl,
2002 int x, int y, int w, int h)
2004 COCOA_DEBUG("qemu_cocoa: cocoa_update\n");
2006 dispatch_async(dispatch_get_main_queue(), ^{
2008 if ([cocoaView cdx] == 1.0) {
2009 rect = NSMakeRect(x, [cocoaView gscreen].height - y - h, w, h);
2012 x * [cocoaView cdx],
2013 ([cocoaView gscreen].height - y - h) * [cocoaView cdy],
2014 w * [cocoaView cdx],
2015 h * [cocoaView cdy]);
2017 [cocoaView setNeedsDisplayInRect:rect];
2021 static void cocoa_switch(DisplayChangeListener *dcl,
2022 DisplaySurface *surface)
2024 pixman_image_t *image = surface->image;
2026 COCOA_DEBUG("qemu_cocoa: cocoa_switch\n");
2028 // The DisplaySurface will be freed as soon as this callback returns.
2029 // We take a reference to the underlying pixman image here so it does
2030 // not disappear from under our feet; the switchSurface method will
2031 // deref the old image when it is done with it.
2032 pixman_image_ref(image);
2034 dispatch_async(dispatch_get_main_queue(), ^{
2035 [cocoaView updateUIInfo];
2036 [cocoaView switchSurface:image];
2040 static void cocoa_refresh(DisplayChangeListener *dcl)
2042 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
2044 COCOA_DEBUG("qemu_cocoa: cocoa_refresh\n");
2045 graphic_hw_update(NULL);
2047 if (qemu_input_is_absolute()) {
2048 dispatch_async(dispatch_get_main_queue(), ^{
2049 if (![cocoaView isAbsoluteEnabled]) {
2050 if ([cocoaView isMouseGrabbed]) {
2051 [cocoaView ungrabMouse];
2054 [cocoaView setAbsoluteEnabled:YES];
2058 if (cbchangecount != [[NSPasteboard generalPasteboard] changeCount]) {
2059 qemu_clipboard_info_unref(cbinfo);
2060 cbinfo = qemu_clipboard_info_new(&cbpeer, QEMU_CLIPBOARD_SELECTION_CLIPBOARD);
2061 if ([[NSPasteboard generalPasteboard] availableTypeFromArray:@[NSPasteboardTypeString]]) {
2062 cbinfo->types[QEMU_CLIPBOARD_TYPE_TEXT].available = true;
2064 qemu_clipboard_update(cbinfo);
2065 cbchangecount = [[NSPasteboard generalPasteboard] changeCount];
2066 qemu_event_set(&cbevent);
2072 static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
2074 COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
2076 /* Tell main thread to go ahead and create the app and enter the run loop */
2077 qemu_sem_post(&display_init_sem);
2078 qemu_sem_wait(&app_started_sem);
2079 COCOA_DEBUG("cocoa_display_init: app start completed\n");
2081 QemuCocoaAppController *controller = (QemuCocoaAppController *)[[NSApplication sharedApplication] delegate];
2082 /* if fullscreen mode is to be used */
2083 if (opts->has_full_screen && opts->full_screen) {
2084 dispatch_async(dispatch_get_main_queue(), ^{
2085 [NSApp activateIgnoringOtherApps: YES];
2086 [controller toggleFullScreen: nil];
2089 if (opts->u.cocoa.has_full_grab && opts->u.cocoa.full_grab) {
2090 dispatch_async(dispatch_get_main_queue(), ^{
2091 [controller setFullGrab: nil];
2095 if (opts->has_show_cursor && opts->show_cursor) {
2098 if (opts->u.cocoa.has_swap_opt_cmd) {
2099 swap_opt_cmd = opts->u.cocoa.swap_opt_cmd;
2102 if (opts->u.cocoa.has_left_command_key && !opts->u.cocoa.left_command_key) {
2103 left_command_key_enabled = 0;
2106 // register vga output callbacks
2107 register_displaychangelistener(&dcl);
2109 qemu_event_init(&cbevent, false);
2110 cbowner = [[QemuCocoaPasteboardTypeOwner alloc] init];
2111 qemu_clipboard_peer_register(&cbpeer);
2114 static QemuDisplay qemu_display_cocoa = {
2115 .type = DISPLAY_TYPE_COCOA,
2116 .init = cocoa_display_init,
2119 static void register_cocoa(void)
2121 qemu_display_register(&qemu_display_cocoa);
2124 type_init(register_cocoa);