4 * Core Cocoa-based user interface
6 * Copyright (c) 2008 Nathan Keynes.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
19 #include <AppKit/AppKit.h>
26 #include "dreamcast.h"
31 #include "gdrom/gdrom.h"
34 #include "cocoaui/cocoaui.h"
36 void cocoa_gui_update( void );
37 void cocoa_gui_start( void );
38 void cocoa_gui_stop( void );
39 uint32_t cocoa_gui_run_slice( uint32_t nanosecs );
41 struct dreamcast_module cocoa_gui_module = { "gui", NULL,
49 * Count of running nanoseconds - used to cut back on the GUI runtime
51 static uint32_t cocoa_gui_nanos = 0;
52 static uint32_t cocoa_gui_ticks = 0;
53 static struct timeval cocoa_gui_lasttv;
54 static BOOL cocoa_gui_autorun = NO;
55 static BOOL cocoa_gui_is_running = NO;
56 static LxdreamMainWindow *mainWindow = NULL;
58 @interface NSApplication (PrivateAdditions)
59 - (void) setAppleMenu:(NSMenu *)aMenu;
62 gboolean cocoa_gui_disc_changed( cdrom_disc_t disc, const gchar *disc_name, void *user_data )
64 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
65 LxdreamMainWindow *window = (LxdreamMainWindow *)user_data;
72 * Produces the menu title by looking the text up in gettext, removing any
73 * underscores, and returning the result as an NSString.
75 static NSString *NSMENU_( const char *text )
77 const char *s = gettext(text);
78 char buf[strlen(s)+1];
89 return [NSString stringWithUTF8String: buf];
92 static void cocoa_gui_create_menu(void)
95 NSMenu *appleMenu, *services;
100 appName = @"Lxdream";
101 appleMenu = [[NSMenu alloc] initWithTitle:@""];
104 title = [@"About " stringByAppendingString:appName];
105 [appleMenu addItemWithTitle:title action:@selector(about_action:) keyEquivalent:@""];
107 [appleMenu addItem:[NSMenuItem separatorItem]];
108 [appleMenu addItemWithTitle: NSMENU_("_Preferences...") action:@selector(preferences_action:) keyEquivalent:@","];
111 [appleMenu addItem:[NSMenuItem separatorItem]];
112 services = [[[NSMenu alloc] init] autorelease];
113 [appleMenu addItemWithTitle: NS_("Services") action:nil keyEquivalent:@""];
114 [appleMenu setSubmenu: services forItem: [appleMenu itemWithTitle: @"Services"]];
117 title = [@"Hide " stringByAppendingString:appName];
118 [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
121 menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others"
122 action:@selector(hideOtherApplications:)
124 [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
127 [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
128 [appleMenu addItem:[NSMenuItem separatorItem]];
131 title = [@"Quit " stringByAppendingString:appName];
132 [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
134 /* Put menu into the menubar */
135 menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
136 [menuItem setSubmenu: appleMenu];
137 NSMenu *menu = [NSMenu new];
138 [menu addItem: menuItem];
140 NSMenu *gdromMenu = cocoa_gdrom_menu_new();
142 NSMenu *quickStateMenu = [[NSMenu alloc] initWithTitle:NSMENU_("_Quick State")];
143 int quickState = dreamcast_get_quick_state();
144 for( i=0; i<=MAX_QUICK_STATE; i++ ) {
145 NSString *label = [NSString stringWithFormat: NSMENU_("State _%d"), i];
146 NSString *keyEquiv = [NSString stringWithFormat: @"%d", i];
147 menuItem = [[NSMenuItem alloc] initWithTitle: label action: @selector(quick_state_action:) keyEquivalent: keyEquiv];
148 [menuItem setTag: i];
149 if( i == quickState ) {
150 [menuItem setState:NSOnState];
152 [quickStateMenu addItem: menuItem];
155 NSMenu *fileMenu = [[NSMenu alloc] initWithTitle: NSMENU_("_File")];
156 [fileMenu addItemWithTitle: NSMENU_("Load _Binary...") action: @selector(load_binary_action:) keyEquivalent: @"b"];
157 [[fileMenu addItemWithTitle: NSMENU_("_GD-Rom") action: nil keyEquivalent: @""]
158 setSubmenu: gdromMenu];
159 [fileMenu addItem: [NSMenuItem separatorItem]];
160 [[fileMenu addItemWithTitle: NSMENU_("_Reset") action: @selector(reset_action:) keyEquivalent: @"r"]
161 setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
162 [fileMenu addItemWithTitle: NSMENU_("_Pause") action: @selector(pause_action:) keyEquivalent: @"p"];
163 [fileMenu addItemWithTitle: NS_("Resume") action: @selector(run_action:) keyEquivalent: @"r"];
164 [fileMenu addItem: [NSMenuItem separatorItem]];
165 [fileMenu addItemWithTitle: NSMENU_("L_oad State...") action: @selector(load_action:) keyEquivalent: @"o"];
166 [fileMenu addItemWithTitle: NSMENU_("S_ave State...") action: @selector(save_action:) keyEquivalent: @"a"];
167 menuItem = [[NSMenuItem alloc] initWithTitle:NSMENU_("Select _Quick State") action: nil keyEquivalent: @""];
168 [fileMenu addItem: [NSMenuItem separatorItem]];
169 [fileMenu addItemWithTitle: NSMENU_("_Load Quick State") action: @selector(quick_load_action:) keyEquivalent: @"l"];
170 [fileMenu addItemWithTitle: NSMENU_("_Save Quick State") action: @selector(quick_save_action:) keyEquivalent: @"s"];
171 [menuItem setSubmenu: quickStateMenu];
172 [fileMenu addItem: menuItem];
173 [fileMenu addItem: [NSMenuItem separatorItem]];
174 [fileMenu addItemWithTitle: NSMENU_("_Full Screen...") action: @selector(fullscreen_action:) keyEquivalent: @"\r"];
176 menuItem = [[NSMenuItem alloc] initWithTitle:NSMENU_("_File") action: nil keyEquivalent: @""];
177 [menuItem setSubmenu: fileMenu];
178 [menu addItem: menuItem];
180 /* Tell the application object that this is now the application menu */
181 [NSApp setMainMenu: menu];
182 [NSApp setAppleMenu: appleMenu];
183 [NSApp setServicesMenu: services];
185 /* Finally give up our references to the objects */
191 @interface LxdreamDelegate : NSObject
194 @implementation LxdreamDelegate
195 - (void)windowWillClose: (NSNotification *)notice
197 dreamcast_shutdown();
200 - (void)windowDidBecomeMain: (NSNotification *)notice
202 if( cocoa_gui_autorun ) {
203 cocoa_gui_autorun = NO;
204 gui_do_later(dreamcast_run);
207 - (void)windowDidBecomeKey: (NSNotification *)notice
209 display_set_focused( TRUE );
211 - (void)windowDidResignKey: (NSNotification *)notice
213 display_set_focused( FALSE );
214 [mainWindow setIsGrabbed: NO];
216 - (BOOL)application: (NSApplication *)app openFile: (NSString *)filename
218 const gchar *cname = [filename UTF8String];
220 if( file_load_magic(cname, FALSE, &err) != FILE_ERROR ) {
221 // Queue up a run event
222 gui_do_later(dreamcast_run);
229 - (void) about_action: (id)sender
231 NSArray *keys = [NSArray arrayWithObjects: @"Version", @"Copyright", nil];
232 NSArray *values = [NSArray arrayWithObjects: NS_(lxdream_full_version), NS_(lxdream_copyright), nil];
234 NSDictionary *options= [NSDictionary dictionaryWithObjects: values forKeys: keys];
236 [NSApp orderFrontStandardAboutPanelWithOptions: options];
238 - (void) preferences_action: (id)sender
240 cocoa_gui_show_preferences();
242 - (void) load_action: (id)sender
244 NSOpenPanel *panel = [NSOpenPanel openPanel];
245 NSString *path = [NSString stringWithCString: get_gui_path(CONFIG_SAVE_PATH)];
246 NSArray *fileTypes = [NSArray arrayWithObject: @"dst"];
247 int result = [panel runModalForDirectory: path file: nil types: fileTypes];
248 if( result == NSOKButton && [[panel filenames] count] > 0 ) {
249 NSString *filename = [[panel filenames] objectAtIndex: 0];
250 dreamcast_load_state( [filename UTF8String] );
251 set_gui_path(CONFIG_SAVE_PATH, [[panel directory] UTF8String]);
254 - (void) save_action: (id)sender
256 NSSavePanel *panel = [NSSavePanel savePanel];
257 NSString *path = [NSString stringWithCString: get_gui_path(CONFIG_SAVE_PATH)];
258 [panel setRequiredFileType: @"dst"];
259 int result = [panel runModalForDirectory: path file:@""];
260 if( result == NSOKButton ) {
261 NSString *filename = [panel filename];
262 dreamcast_save_state( [filename UTF8String] );
263 set_gui_path(CONFIG_SAVE_PATH, [[panel directory] UTF8String]);
266 - (void) load_binary_action: (id)sender
268 NSOpenPanel *panel = [NSOpenPanel openPanel];
269 NSString *path = [NSString stringWithCString: get_gui_path(CONFIG_DEFAULT_PATH)];
270 int result = [panel runModalForDirectory: path file: nil types: nil];
271 if( result == NSOKButton && [[panel filenames] count] > 0 ) {
272 NSString *filename = [[panel filenames] objectAtIndex: 0];
274 gboolean ok = file_load_exec( [filename UTF8String], &err );
275 set_gui_path(CONFIG_DEFAULT_PATH, [[panel directory] UTF8String]);
281 - (void) mount_action: (id)sender
283 NSOpenPanel *panel = [NSOpenPanel openPanel];
284 NSString *path = [NSString stringWithCString: get_gui_path(CONFIG_DEFAULT_PATH)];
285 int result = [panel runModalForDirectory: path file: nil types: nil];
286 if( result == NSOKButton && [[panel filenames] count] > 0 ) {
288 NSString *filename = [[panel filenames] objectAtIndex: 0];
289 gboolean ok = gdrom_mount_image( [filename UTF8String], &err );
293 set_gui_path(CONFIG_DEFAULT_PATH, [[panel directory] UTF8String]);
296 - (void) pause_action: (id)sender
301 - (void) reset_action: (id)sender
305 - (void) run_action: (id)sender
307 if( !dreamcast_is_running() ) {
308 gui_do_later(dreamcast_run);
311 - (void) gdrom_list_action: (id)sender
314 gboolean ok = gdrom_list_set_selection( [sender tag], &err );
319 - (void) fullscreen_action: (id)sender
321 [mainWindow setFullscreen: ![mainWindow isFullscreen]];
323 - (void) quick_state_action: (id)sender
325 [[[sender menu] itemWithTag: dreamcast_get_quick_state()] setState: NSOffState ];
326 [sender setState: NSOnState ];
327 dreamcast_set_quick_state( [sender tag] );
329 - (void) quick_save_action: (id)sender
331 dreamcast_quick_save();
333 - (void) quick_load_action: (id)sender
335 dreamcast_quick_load();
340 gboolean gui_parse_cmdline( int *argc, char **argv[] )
342 /* If started from the finder, the first (and only) arg will look something like
343 * -psn_0_... - we want to remove this so that lxdream doesn't try to process it
346 if( *argc == 2 && strncmp((*argv)[1], "-psn_", 5) == 0 ) {
352 gboolean gui_init( gboolean withDebug, gboolean withFullscreen )
354 dreamcast_register_module( &cocoa_gui_module );
356 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
357 [NSApplication sharedApplication];
359 LxdreamDelegate *delegate = [[LxdreamDelegate alloc] init];
360 [NSApp setDelegate: delegate];
361 NSString *iconFile = [[NSBundle mainBundle] pathForResource:@"lxdream" ofType:@"png"];
362 NSImage *iconImage = [[NSImage alloc] initWithContentsOfFile: iconFile];
363 [iconImage setName: @"NSApplicationIcon"];
364 [NSApp setApplicationIconImage: iconImage];
365 cocoa_gui_create_menu();
366 mainWindow = cocoa_gui_create_main_window();
367 [mainWindow makeKeyAndOrderFront: nil];
368 [NSApp activateIgnoringOtherApps: YES];
370 register_gdrom_disc_change_hook( cocoa_gui_disc_changed, mainWindow );
371 if( withFullscreen ) {
372 [mainWindow setFullscreen: YES];
378 void gui_main_loop( gboolean run )
381 cocoa_gui_autorun = YES;
383 cocoa_gui_is_running = YES;
385 cocoa_gui_is_running = NO;
388 void gui_update_state(void)
393 void gui_set_use_grab( gboolean grab )
395 [mainWindow setUseGrab: (grab ? YES : NO)];
398 gboolean gui_error_dialog( const char *msg, ... )
400 if( cocoa_gui_is_running ) {
401 NSString *error_string;
405 error_string = [[NSString alloc] initWithFormat: [NSString stringWithCString: msg] arguments: args];
406 NSRunAlertPanel(NS_("Error in Lxdream"), error_string, nil, nil, nil);
414 void gui_update_io_activity( io_activity_type io, gboolean active )
420 uint32_t cocoa_gui_run_slice( uint32_t nanosecs )
423 NSAutoreleasePool *pool;
425 cocoa_gui_nanos += nanosecs;
426 if( cocoa_gui_nanos > GUI_TICK_PERIOD ) { /* 10 ms */
427 cocoa_gui_nanos -= GUI_TICK_PERIOD;
429 uint32_t current_period = cocoa_gui_ticks * GUI_TICK_PERIOD;
431 // Run the event loop
432 pool = [NSAutoreleasePool new];
433 while( (event = [NSApp nextEventMatchingMask: NSAnyEventMask untilDate: nil
434 inMode: NSDefaultRunLoopMode dequeue: YES]) != nil ) {
435 [NSApp sendEvent: event];
440 gettimeofday(&tv,NULL);
441 uint32_t ns = ((tv.tv_sec - cocoa_gui_lasttv.tv_sec) * 1000000000) +
442 (tv.tv_usec - cocoa_gui_lasttv.tv_usec)*1000;
443 if( (ns * 1.05) < current_period ) {
444 // We've gotten ahead - sleep for a little bit
447 tv.tv_nsec = current_period - ns;
451 /* Update the display every 10 ticks (ie 10 times a second) and
452 * save the current tv value */
453 if( cocoa_gui_ticks > 10 ) {
455 cocoa_gui_ticks -= 10;
457 double speed = (float)( (double)current_period * 100.0 / ns );
458 cocoa_gui_lasttv.tv_sec = tv.tv_sec;
459 cocoa_gui_lasttv.tv_usec = tv.tv_usec;
460 snprintf( buf, 32, _("Running (%2.4f%%)"), speed );
461 [mainWindow setStatusText: buf];
468 void cocoa_gui_update( void )
473 void cocoa_gui_start( void )
475 [mainWindow setRunning: YES];
477 gettimeofday(&cocoa_gui_lasttv,NULL);
480 void cocoa_gui_stop( void )
482 [mainWindow setRunning: NO];
485 @interface DoLaterStub : NSObject
487 do_later_callback_t func;
491 @implementation DoLaterStub
492 - (id) init: (do_later_callback_t)f
505 * Queue a dreamcast_run() to execute after the currently event(s)
507 void gui_do_later( do_later_callback_t func )
509 DoLaterStub *stub = [[[DoLaterStub alloc] init: func] autorelease];
510 [[NSRunLoop currentRunLoop] performSelector: @selector(do)
511 target: stub argument: nil order: 1
512 modes: [NSArray arrayWithObject: NSDefaultRunLoopMode] ];
515 /*************************** Convenience methods ***************************/
517 NSImage *NSImage_new_from_framebuffer( frame_buffer_t buffer )
519 NSBitmapImageRep *rep =
520 [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: &buffer->data
521 pixelsWide: buffer->width pixelsHigh: buffer->height
522 bitsPerSample: 8 samplesPerPixel: 3
523 hasAlpha: NO isPlanar: NO
524 colorSpaceName: NSDeviceRGBColorSpace bitmapFormat: 0
525 bytesPerRow: buffer->rowstride bitsPerPixel: 24];
527 NSImage *image = [[NSImage alloc] initWithSize: NSMakeSize(0.0,0.0)];
528 [image addRepresentation: rep];
533 NSTextField *cocoa_gui_add_label( NSView *parent, NSString *text, NSRect frame )
535 NSTextField *label = [[NSTextField alloc] initWithFrame: frame];
536 [label setStringValue: text];
537 [label setBordered: NO];
538 [label setDrawsBackground: NO];
539 [label setEditable: NO];
540 [label setAutoresizingMask: (NSViewMinYMargin|NSViewMaxXMargin)];
541 if( parent != NULL ) {
542 [parent addSubview: label];
.