Search
lxdream.org :: lxdream/src/cocoaui/cocoaui.m
lxdream 0.9.1
released Jun 29
Download Now
filename src/cocoaui/cocoaui.m
changeset 1098:4f2750753a6c
prev1041:5fcc39857c5c
next1109:700c5ab26a63
author nkeynes
date Sun Jan 31 18:36:06 2010 +1000 (12 years ago)
permissions -rw-r--r--
last change Show '<no disc>' in the title bar when there is no cdrom disc attached
view annotate diff log raw
     1 /**
     2  * $Id$
     3  *
     4  * Core Cocoa-based user interface
     5  *
     6  * Copyright (c) 2008 Nathan Keynes.
     7  *
     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.
    12  *
    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.
    17  */
    19 #include <AppKit/AppKit.h>
    20 #include <stdio.h>
    21 #include <stdlib.h>
    22 #include <string.h>
    23 #include <sys/time.h>
    24 #include "lxdream.h"
    25 #include "dream.h"
    26 #include "dreamcast.h"
    27 #include "config.h"
    28 #include "lxpaths.h"
    29 #include "display.h"
    30 #include "gui.h"
    31 #include "gdrom/gdrom.h"
    32 #include "gdlist.h"
    33 #include "loader.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,
    42         cocoa_gui_update, 
    43         cocoa_gui_start, 
    44         cocoa_gui_run_slice, 
    45         cocoa_gui_stop, 
    46         NULL, NULL };
    48 /**
    49  * Count of running nanoseconds - used to cut back on the GUI runtime
    50  */
    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;
    60 @end
    62 gboolean cocoa_gui_disc_changed( cdrom_disc_t disc, const gchar *disc_name, void *user_data )
    63 {
    64     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    65     LxdreamMainWindow *window = (LxdreamMainWindow *)user_data;
    66     [window updateTitle];
    67     [pool release];
    68     return TRUE;
    69 }
    71 /**
    72  * Produces the menu title by looking the text up in gettext, removing any
    73  * underscores, and returning the result as an NSString.
    74  */
    75 static NSString *NSMENU_( const char *text )
    76 {
    77     const char *s = gettext(text);
    78     char buf[strlen(s)+1];
    79     char *d = buf;
    81     while( *s != '\0' ) {
    82         if( *s != '_' ) {
    83             *d++ = *s;
    84         }
    85         s++;
    86     }
    87     *d = '\0';
    89     return [NSString stringWithUTF8String: buf];
    90 }
    92 static void cocoa_gui_create_menu(void)
    93 {
    94     int i;
    95     NSMenu *appleMenu, *services;
    96     NSMenuItem *menuItem;
    97     NSString *title;
    98     NSString *appName;
   100     appName = @"Lxdream";
   101     appleMenu = [[NSMenu alloc] initWithTitle:@""];
   103     /* Add menu items */
   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:@","];
   110     // Services Menu
   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"]];
   116     // Hide AppName
   117     title = [@"Hide " stringByAppendingString:appName];
   118     [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
   120     // Hide Others
   121     menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" 
   122                               action:@selector(hideOtherApplications:) 
   123                               keyEquivalent:@"h"];
   124     [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
   126     // Show All
   127     [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
   128     [appleMenu addItem:[NSMenuItem separatorItem]];
   130     // Quit AppName
   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];
   151     	}
   152     	[quickStateMenu addItem: menuItem];
   153     }
   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 */
   186     [appleMenu release];
   187     [menuItem release];
   188     [menu release];
   189 }
   191 @interface LxdreamDelegate : NSObject
   192 @end
   194 @implementation LxdreamDelegate
   195 - (void)windowWillClose: (NSNotification *)notice
   196 {
   197     dreamcast_shutdown();
   198     exit(0);
   199 }
   200 - (void)windowDidBecomeMain: (NSNotification *)notice
   201 {
   202     if( cocoa_gui_autorun ) {
   203         cocoa_gui_autorun = NO;
   204         gui_do_later(dreamcast_run);
   205     }
   206 }
   207 - (void)windowDidBecomeKey: (NSNotification *)notice
   208 {
   209     display_set_focused( TRUE );
   210 }
   211 - (void)windowDidResignKey: (NSNotification *)notice
   212 {
   213     display_set_focused( FALSE );
   214     [mainWindow setIsGrabbed: NO];
   215 }
   216 - (BOOL)application: (NSApplication *)app openFile: (NSString *)filename
   217 {
   218     const gchar *cname = [filename UTF8String];
   219     if( file_load_magic(cname) ) {
   220         // Queue up a run event
   221         gui_do_later(dreamcast_run);
   222         return YES;
   223     } else {
   224         return NO;
   225     }
   227 }
   228 - (void) about_action: (id)sender
   229 {
   230     NSArray *keys = [NSArray arrayWithObjects: @"Version", @"Copyright", nil];
   231     NSArray *values = [NSArray arrayWithObjects: NS_(lxdream_full_version), NS_(lxdream_copyright),  nil];
   233     NSDictionary *options= [NSDictionary dictionaryWithObjects: values forKeys: keys];
   235     [NSApp orderFrontStandardAboutPanelWithOptions: options];
   236 }
   237 - (void) preferences_action: (id)sender
   238 {
   239     cocoa_gui_show_preferences();
   240 }
   241 - (void) load_action: (id)sender
   242 {
   243     NSOpenPanel *panel = [NSOpenPanel openPanel];
   244     NSString *path = [NSString stringWithCString: get_gui_path(CONFIG_SAVE_PATH)];
   245     NSArray *fileTypes = [NSArray arrayWithObject: @"dst"];
   246     int result = [panel runModalForDirectory: path file: nil types: fileTypes];
   247     if( result == NSOKButton && [[panel filenames] count] > 0 ) {
   248         NSString *filename = [[panel filenames] objectAtIndex: 0];
   249         dreamcast_load_state( [filename UTF8String] );
   250         set_gui_path(CONFIG_SAVE_PATH, [[panel directory] UTF8String]);
   251     }
   252 }
   253 - (void) save_action: (id)sender
   254 {
   255     NSSavePanel *panel = [NSSavePanel savePanel];
   256     NSString *path = [NSString stringWithCString: get_gui_path(CONFIG_SAVE_PATH)];
   257     [panel setRequiredFileType: @"dst"];
   258     int result = [panel runModalForDirectory: path file:@""];
   259     if( result == NSOKButton ) {
   260         NSString *filename = [panel filename];
   261         dreamcast_save_state( [filename UTF8String] );
   262         set_gui_path(CONFIG_SAVE_PATH, [[panel directory] UTF8String]);
   263     }
   264 }
   265 - (void) load_binary_action: (id)sender
   266 {
   267     NSOpenPanel *panel = [NSOpenPanel openPanel];
   268     NSString *path = [NSString stringWithCString: get_gui_path(CONFIG_DEFAULT_PATH)];
   269     int result = [panel runModalForDirectory: path file: nil types: nil];
   270     if( result == NSOKButton && [[panel filenames] count] > 0 ) {
   271         NSString *filename = [[panel filenames] objectAtIndex: 0];
   272         file_load_magic( [filename UTF8String] );
   273         set_gui_path(CONFIG_DEFAULT_PATH, [[panel directory] UTF8String]);
   274     }
   275 }
   276 - (void) mount_action: (id)sender
   277 {
   278     NSOpenPanel *panel = [NSOpenPanel openPanel];
   279     NSString *path = [NSString stringWithCString: get_gui_path(CONFIG_DEFAULT_PATH)];
   280     int result = [panel runModalForDirectory: path file: nil types: nil];
   281     if( result == NSOKButton && [[panel filenames] count] > 0 ) {
   282         NSString *filename = [[panel filenames] objectAtIndex: 0];
   283         gdrom_mount_image( [filename UTF8String] );
   284         set_gui_path(CONFIG_DEFAULT_PATH, [[panel directory] UTF8String]);
   285     }
   286 }
   287 - (void) pause_action: (id)sender
   288 {
   289     dreamcast_stop();
   290 }
   292 - (void) reset_action: (id)sender
   293 {
   294     dreamcast_reset();
   295 }
   296 - (void) run_action: (id)sender
   297 {
   298     if( !dreamcast_is_running() ) {
   299         gui_do_later(dreamcast_run);
   300     }
   301 }
   302 - (void) gdrom_list_action: (id)sender
   303 {
   304     gdrom_list_set_selection( [sender tag] );
   305 }
   306 - (void) fullscreen_action: (id)sender
   307 {
   308     [mainWindow setFullscreen: ![mainWindow isFullscreen]]; 
   309 }
   310 - (void) quick_state_action: (id)sender
   311 {
   312     [[[sender menu] itemWithTag: dreamcast_get_quick_state()] setState: NSOffState ];
   313     [sender setState: NSOnState ];
   314     dreamcast_set_quick_state( [sender tag] );
   315 }
   316 - (void) quick_save_action: (id)sender
   317 {
   318     dreamcast_quick_save();
   319 }
   320 - (void) quick_load_action: (id)sender
   321 {
   322     dreamcast_quick_load();
   323 }
   324 @end
   327 gboolean gui_parse_cmdline( int *argc, char **argv[] )
   328 {
   329     /* If started from the finder, the first (and only) arg will look something like 
   330      * -psn_0_... - we want to remove this so that lxdream doesn't try to process it 
   331      * normally
   332      */
   333     if( *argc == 2 && strncmp((*argv)[1], "-psn_", 5) == 0 ) {
   334         *argc = 1;
   335     }
   336     return TRUE;
   337 }
   339 gboolean gui_init( gboolean withDebug, gboolean withFullscreen )
   340 {
   341     dreamcast_register_module( &cocoa_gui_module );
   343     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   344     [NSApplication sharedApplication];
   346     LxdreamDelegate *delegate = [[LxdreamDelegate alloc] init];
   347     [NSApp setDelegate: delegate];
   348     NSString *iconFile = [[NSBundle mainBundle] pathForResource:@"lxdream" ofType:@"png"];
   349     NSImage *iconImage = [[NSImage alloc] initWithContentsOfFile: iconFile];
   350     [iconImage setName: @"NSApplicationIcon"];
   351     [NSApp setApplicationIconImage: iconImage];   
   352     cocoa_gui_create_menu();
   353     mainWindow = cocoa_gui_create_main_window();
   354     [mainWindow makeKeyAndOrderFront: nil];
   355     [NSApp activateIgnoringOtherApps: YES];   
   357     register_gdrom_disc_change_hook( cocoa_gui_disc_changed, mainWindow );
   358     if( withFullscreen ) {
   359     	[mainWindow setFullscreen: YES];
   360     }
   361     [pool release];
   362     return TRUE;
   363 }
   365 void gui_main_loop( gboolean run )
   366 {
   367     if( run ) {
   368         cocoa_gui_autorun = YES;
   369     }
   370     cocoa_gui_is_running = YES;
   371     [NSApp run];
   372     cocoa_gui_is_running = NO;
   373 }
   375 void gui_update_state(void)
   376 {
   377     cocoa_gui_update();
   378 }
   380 void gui_set_use_grab( gboolean grab )
   381 {
   382     [mainWindow setUseGrab: (grab ? YES : NO)];
   383 }
   385 gboolean gui_error_dialog( const char *msg, ... )
   386 {
   387     if( cocoa_gui_is_running ) {
   388         NSString *error_string;
   390         va_list args;
   391         va_start(args, msg);
   392         error_string = [[NSString alloc] initWithFormat: [NSString stringWithCString: msg] arguments: args];
   393         NSRunAlertPanel(NS_("Error in Lxdream"), error_string, nil, nil, nil);
   394         va_end(args);
   395         return TRUE;
   396     } else {
   397         return FALSE;
   398     }
   399 }
   401 void gui_update_io_activity( io_activity_type io, gboolean active )
   402 {
   404 }
   407 uint32_t cocoa_gui_run_slice( uint32_t nanosecs )
   408 {
   409     NSEvent *event;
   410     NSAutoreleasePool *pool;
   412     cocoa_gui_nanos += nanosecs;
   413     if( cocoa_gui_nanos > GUI_TICK_PERIOD ) { /* 10 ms */
   414         cocoa_gui_nanos -= GUI_TICK_PERIOD;
   415         cocoa_gui_ticks ++;
   416         uint32_t current_period = cocoa_gui_ticks * GUI_TICK_PERIOD;
   418         // Run the event loop
   419         pool = [NSAutoreleasePool new];
   420         while( (event = [NSApp nextEventMatchingMask: NSAnyEventMask untilDate: nil 
   421                          inMode: NSDefaultRunLoopMode dequeue: YES]) != nil ) {
   422             [NSApp sendEvent: event];
   423         }
   424         [pool release];
   426         struct timeval tv;
   427         gettimeofday(&tv,NULL);
   428         uint32_t ns = ((tv.tv_sec - cocoa_gui_lasttv.tv_sec) * 1000000000) + 
   429         (tv.tv_usec - cocoa_gui_lasttv.tv_usec)*1000;
   430         if( (ns * 1.05) < current_period ) {
   431             // We've gotten ahead - sleep for a little bit
   432             struct timespec tv;
   433             tv.tv_sec = 0;
   434             tv.tv_nsec = current_period - ns;
   435             nanosleep(&tv, &tv);
   436         }
   438         /* Update the display every 10 ticks (ie 10 times a second) and 
   439          * save the current tv value */
   440         if( cocoa_gui_ticks > 10 ) {
   441             gchar buf[32];
   442             cocoa_gui_ticks -= 10;
   444             double speed = (float)( (double)current_period * 100.0 / ns );
   445             cocoa_gui_lasttv.tv_sec = tv.tv_sec;
   446             cocoa_gui_lasttv.tv_usec = tv.tv_usec;
   447             snprintf( buf, 32, _("Running (%2.4f%%)"), speed );
   448             [mainWindow setStatusText: buf];
   450         }
   451     }
   452     return nanosecs;
   453 }
   455 void cocoa_gui_update( void )
   456 {
   458 }
   460 void cocoa_gui_start( void )
   461 {
   462     [mainWindow setRunning: YES];
   463     cocoa_gui_nanos = 0;
   464     gettimeofday(&cocoa_gui_lasttv,NULL);
   465 }
   467 void cocoa_gui_stop( void )
   468 {
   469     [mainWindow setRunning: NO];
   470 }
   472 @interface DoLaterStub : NSObject
   473 {
   474     do_later_callback_t func;
   475 }
   476 @end    
   478 @implementation DoLaterStub
   479 - (id) init: (do_later_callback_t)f
   480 {
   481     [super init];
   482     func = f;
   483     return self;
   484 }
   485 - (void) do
   486 {
   487     func();
   488 }
   489 @end
   491 /**
   492  * Queue a dreamcast_run() to execute after the currently event(s)
   493  */
   494 void gui_do_later( do_later_callback_t func )
   495 {
   496     DoLaterStub *stub = [[[DoLaterStub alloc] init: func] autorelease]; 
   497     [[NSRunLoop currentRunLoop] performSelector: @selector(do) 
   498      target: stub argument: nil order: 1 
   499      modes: [NSArray arrayWithObject: NSDefaultRunLoopMode] ];
   500 }
   502 /*************************** Convenience methods ***************************/
   504 NSImage *NSImage_new_from_framebuffer( frame_buffer_t buffer )
   505 {
   506     NSBitmapImageRep *rep = 
   507         [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: &buffer->data
   508          pixelsWide: buffer->width  pixelsHigh: buffer->height
   509          bitsPerSample: 8 samplesPerPixel: 3
   510          hasAlpha: NO isPlanar: NO
   511          colorSpaceName: NSDeviceRGBColorSpace  bitmapFormat: 0
   512          bytesPerRow: buffer->rowstride  bitsPerPixel: 24];
   514     NSImage *image = [[NSImage alloc] initWithSize: NSMakeSize(0.0,0.0)];
   515     [image addRepresentation: rep];
   516     return image;
   517 }
   520 NSTextField *cocoa_gui_add_label( NSView *parent, NSString *text, NSRect frame )
   521 {
   522     NSTextField *label = [[NSTextField alloc] initWithFrame: frame];
   523     [label setStringValue: text];
   524     [label setBordered: NO];
   525     [label setDrawsBackground: NO];
   526     [label setEditable: NO];
   527     [label setAutoresizingMask: (NSViewMinYMargin|NSViewMaxXMargin)];
   528     if( parent != NULL ) {
   529         [parent addSubview: label];
   530     }
   531     return label;
   532 }
.