2 * QEMU Cocoa display driver
4 * Copyright (c) 2005 Pierre d'Herbemont
5 * many code/inspiration from SDL 1.2 code (LGPL)
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 Todo : x miniaturize window
28 - save window position
29 - handle keyboard event
34 x simple graphical prompt to demo
35 - better graphical prompt
38 #import <Cocoa/Cocoa.h>
42 NSWindow *window = NULL;
43 NSQuickDrawView *qd_view = NULL;
48 DisplayState current_ds;
50 /* main defined in qemu/vl.c */
51 int qemu_main(int argc, char **argv);
53 /* To deal with miniaturization */
54 @interface QemuWindow : NSWindow
60 ------------------------------------------------------
62 ------------------------------------------------------
66 ------------------------------------------------------
68 ------------------------------------------------------
70 static void cocoa_update(DisplayState *ds, int x, int y, int w, int h)
72 //printf("updating x=%d y=%d w=%d h=%d\n", x, y, w, h);
74 /* Use QDFlushPortBuffer() to flush content to display */
75 RgnHandle dirty = NewRgn ();
76 RgnHandle temp = NewRgn ();
80 /* Build the region of dirty rectangles */
81 MacSetRectRgn (temp, x, y,
83 MacUnionRgn (dirty, temp, dirty);
85 /* Flush the dirty region */
86 QDFlushPortBuffer ( [ qd_view qdPort ], dirty );
92 ------------------------------------------------------
94 ------------------------------------------------------
96 static void cocoa_resize(DisplayState *ds, int w, int h)
98 const int device_bpp = 32;
99 static void *screen_pixels;
100 static int screen_pitch;
103 //printf("resizing to %d %d\n", w, h);
105 contentRect = NSMakeRect (0, 0, w, h);
111 window = [ [ QemuWindow alloc ] initWithContentRect:contentRect
112 styleMask:NSTitledWindowMask|NSMiniaturizableWindowMask|NSClosableWindowMask
113 backing:NSBackingStoreBuffered defer:NO];
116 fprintf(stderr, "(cocoa) can't create window\n");
123 qd_view = [ [ NSQuickDrawView alloc ] initWithFrame:contentRect ];
127 fprintf(stderr, "(cocoa) can't create qd_view\n");
131 [ window setAcceptsMouseMovedEvents:YES ];
132 [ window setTitle:@"Qemu" ];
133 [ window setReleasedWhenClosed:NO ];
135 /* Set screen to black */
136 [ window setBackgroundColor: [NSColor blackColor] ];
138 /* set window position */
141 [ qd_view setAutoresizingMask: NSViewWidthSizable | NSViewHeightSizable ];
142 [ [ window contentView ] addSubview:qd_view ];
144 [ window makeKeyAndOrderFront:nil ];
146 /* Careful here, the window seems to have to be onscreen to do that */
147 LockPortBits ( [ qd_view qdPort ] );
148 screen_pixels = GetPixBaseAddr ( GetPortPixMap ( [ qd_view qdPort ] ) );
149 screen_pitch = GetPixRowBytes ( GetPortPixMap ( [ qd_view qdPort ] ) );
150 UnlockPortBits ( [ qd_view qdPort ] );
152 int vOffset = [ window frame ].size.height -
153 [ qd_view frame ].size.height - [ qd_view frame ].origin.y;
155 int hOffset = [ qd_view frame ].origin.x;
157 screen_pixels += (vOffset * screen_pitch) + hOffset * (device_bpp/8);
159 ds->data = screen_pixels;
160 ds->linesize = screen_pitch;
161 ds->depth = device_bpp;
169 ------------------------------------------------------
171 ------------------------------------------------------
174 static int keymap[] =
225 /* Not completed to finish see http://www.libsdl.org/cgi/cvsweb.cgi/SDL12/src/video/quartz/SDL_QuartzKeys.h?rev=1.6&content-type=text/x-cvsweb-markup */
228 static int cocoa_keycode_to_qemu(int keycode)
230 if(sizeof(keymap) <= keycode)
232 printf("(cocoa) warning unknow keycode 0x%x\n", keycode);
235 return keymap[keycode];
239 ------------------------------------------------------
241 ------------------------------------------------------
243 static void cocoa_refresh(DisplayState *ds)
245 //printf("cocoa_refresh \n");
248 NSAutoreleasePool *pool;
251 pool = [ [ NSAutoreleasePool alloc ] init ];
252 distantPast = [ NSDate distantPast ];
254 if (is_active_console(vga_console))
255 vga_update_display();
257 event = [ NSApp nextEventMatchingMask:NSAnyEventMask untilDate:distantPast
258 inMode: NSDefaultRunLoopMode dequeue:YES ];
260 switch ([event type]) {
264 int keycode = cocoa_keycode_to_qemu([event keyCode]);
267 kbd_put_keycode(0xe0);
268 kbd_put_keycode(keycode & 0x7f);
274 int keycode = cocoa_keycode_to_qemu([event keyCode]);
277 kbd_put_keycode(0xe0);
278 kbd_put_keycode(keycode | 0x80);
283 case NSLeftMouseDown:
286 case NSOtherMouseDown:
287 case NSRightMouseDown:
293 case NSOtherMouseDragged:
294 case NSRightMouseDragged:
295 case NSLeftMouseDragged:
297 default: [NSApp sendEvent:event];
300 } while(event != nil);
304 ------------------------------------------------------
306 ------------------------------------------------------
309 static void cocoa_cleanup(void)
315 ------------------------------------------------------
317 ------------------------------------------------------
320 void cocoa_display_init(DisplayState *ds, int full_screen)
322 ds->dpy_update = cocoa_update;
323 ds->dpy_resize = cocoa_resize;
324 ds->dpy_refresh = cocoa_refresh;
326 cocoa_resize(ds, 640, 400);
328 atexit(cocoa_cleanup);
332 ------------------------------------------------------
334 ------------------------------------------------------
339 ------------------------------------------------------
341 Some trick from SDL to use miniwindow
342 ------------------------------------------------------
344 static void QZ_SetPortAlphaOpaque ()
346 /* Assume 32 bit if( bpp == 32 )*/
349 uint32_t *pixels = (uint32_t*) current_ds.data;
350 uint32_t rowPixels = current_ds.linesize / 4;
353 for (i = 0; i < current_ds.height; i++)
354 for (j = 0; j < current_ds.width; j++) {
356 pixels[ (i * rowPixels) + j ] |= 0xFF000000;
361 @implementation QemuWindow
362 - (void)miniaturize:(id)sender
365 /* make the alpha channel opaque so anim won't have holes in it */
366 QZ_SetPortAlphaOpaque ();
368 [ super miniaturize:sender ];
374 This method fires just before the window deminaturizes from the Dock.
376 We'll save the current visible surface, let the window manager redraw any
377 UI elements, and restore the SDL surface. This way, no expose event
378 is required, and the deminiaturize works perfectly.
381 /* make sure pixels are fully opaque */
382 QZ_SetPortAlphaOpaque ();
384 /* save current visible SDL surface */
385 [ self cacheImageInRect:[ qd_view frame ] ];
387 /* let the window manager redraw controls, border, etc */
390 /* restore visible SDL surface */
391 [ self restoreCachedImage ];
398 ------------------------------------------------------
399 QemuCocoaGUIController
400 NSApp's delegate - indeed main object
401 ------------------------------------------------------
404 @interface QemuCocoaGUIController : NSObject
407 - (void)applicationDidFinishLaunching: (NSNotification *) note;
408 - (void)applicationWillTerminate:(NSNotification *)aNotification;
410 - (void)openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo;
412 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv;
415 @implementation QemuCocoaGUIController
416 /* Called when the internal event loop has just started running */
417 - (void)applicationDidFinishLaunching: (NSNotification *) note
420 /* Do whatever we want here : set up a pc list... */
422 NSOpenPanel *op = [[NSOpenPanel alloc] init];
424 cocoa_resize(¤t_ds, 640, 400);
426 [op setPrompt:@"Boot image"];
428 [op setMessage:@"Select the disk image you want to boot.\n\nHit the \"Cancel\" button to quit"];
430 [op beginSheetForDirectory:nil file:nil types:[NSArray arrayWithObjects:@"img",@"iso",nil]
431 modalForWindow:window modalDelegate:self
432 didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:) contextInfo:NULL];
435 /* or Launch Qemu, with the global args */
436 //[self startEmulationWithArgc:gArgc argv:gArgv];
439 - (void)applicationWillTerminate:(NSNotification *)aNotification
441 printf("Application will terminate\n");
442 qemu_system_shutdown_request();
443 /* In order to avoid a crash */
447 - (void)openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
449 if(returnCode == NSCancelButton)
454 if(returnCode == NSOKButton)
457 char *img = (char*)[ [ sheet filename ] cString];
459 char **argv = (char**)malloc( sizeof(char*)*3 );
461 asprintf(&argv[0], "%s", bin);
462 asprintf(&argv[1], "-hda");
463 asprintf(&argv[2], "%s", img);
465 printf("Using argc %d argv %s -hda %s\n", 3, bin, img);
467 [self startEmulationWithArgc:3 argv:(char**)argv];
471 - (void)startEmulationWithArgc:(int)argc argv:(char**)argv
475 printf("starting qemu...\n");
476 status = qemu_main (argc, argv);
482 ------------------------------------------------------
484 ------------------------------------------------------
487 /* Dock Connection */
488 typedef struct CPSProcessSerNum
494 extern OSErr CPSGetCurrentProcess( CPSProcessSerNum *psn);
495 extern OSErr CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);
496 extern OSErr CPSSetFrontProcess( CPSProcessSerNum *psn);
499 static void setApplicationMenu(void)
501 /* warning: this code is very odd */
503 NSMenuItem *menuItem;
508 appleMenu = [[NSMenu alloc] initWithTitle:@""];
511 title = [@"About " stringByAppendingString:appName];
512 [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
514 [appleMenu addItem:[NSMenuItem separatorItem]];
516 title = [@"Hide " stringByAppendingString:appName];
517 [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
519 menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
520 [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
522 [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
524 [appleMenu addItem:[NSMenuItem separatorItem]];
526 title = [@"Quit " stringByAppendingString:appName];
527 [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
530 /* Put menu into the menubar */
531 menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
532 [menuItem setSubmenu:appleMenu];
533 [[NSApp mainMenu] addItem:menuItem];
535 /* Tell the application object that this is now the application menu */
536 [NSApp setAppleMenu:appleMenu];
538 /* Finally give up our references to the objects */
543 /* Create a window menu */
544 static void setupWindowMenu(void)
547 NSMenuItem *windowMenuItem;
548 NSMenuItem *menuItem;
550 windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
552 /* "Minimize" item */
553 menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
554 [windowMenu addItem:menuItem];
557 /* Put menu into the menubar */
558 windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
559 [windowMenuItem setSubmenu:windowMenu];
560 [[NSApp mainMenu] addItem:windowMenuItem];
562 /* Tell the application object that this is now the window menu */
563 [NSApp setWindowsMenu:windowMenu];
565 /* Finally give up our references to the objects */
566 [windowMenu release];
567 [windowMenuItem release];
571 static void CustomApplicationMain (argc, argv)
573 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
574 QemuCocoaGUIController *gui_controller;
575 CPSProcessSerNum PSN;
577 [NSApplication sharedApplication];
579 if (!CPSGetCurrentProcess(&PSN))
580 if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103))
581 if (!CPSSetFrontProcess(&PSN))
582 [NSApplication sharedApplication];
584 /* Set up the menubar */
585 [NSApp setMainMenu:[[NSMenu alloc] init]];
586 setApplicationMenu();
589 /* Create SDLMain and make it the app delegate */
590 gui_controller = [[QemuCocoaGUIController alloc] init];
591 [NSApp setDelegate:gui_controller];
593 /* Start the main event loop */
596 [gui_controller release];
600 /* Real main of qemu-cocoa */
601 int main(int argc, char **argv)
606 CustomApplicationMain (argc, argv);