Search
lxdream.org :: lxdream/src/cocoaui/cocoaui.c
lxdream 0.9.1
released Jun 29
Download Now
filename src/cocoaui/cocoaui.c
changeset 844:0e645cc6dc59
prev839:51f1c4195790
next874:e3007b8799f3
author nkeynes
date Tue Sep 09 00:50:15 2008 +0000 (15 years ago)
permissions -rw-r--r--
last change Fix set_grab thinko
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 "display.h"
    29 #include "gui.h"
    30 #include "gdrom/gdrom.h"
    31 #include "gdlist.h"
    32 #include "loader.h"
    33 #include "cocoaui/cocoaui.h"
    35 void cocoa_gui_update( void );
    36 void cocoa_gui_start( void );
    37 void cocoa_gui_stop( void );
    38 void cocoa_gui_run_later( 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;
    57 @interface NSApplication (PrivateAdditions)
    58 - (void) setAppleMenu:(NSMenu *)aMenu;
    59 @end
    61 gboolean cocoa_gui_disc_changed( gdrom_disc_t disc, const gchar *disc_name, void *user_data )
    62 {
    63     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    64     LxdreamMainWindow *window = (LxdreamMainWindow *)user_data;
    65     [window updateTitle];
    66     [pool release];
    67     return TRUE;
    68 }
    70 /**
    71  * Produces the menu title by looking the text up in gettext, removing any
    72  * underscores, and returning the result as an NSString.
    73  */
    74 static NSString *NSMENU_( const char *text )
    75 {
    76     const char *s = gettext(text);
    77     char buf[strlen(s)+1];
    78     char *d = buf;
    80     while( *s != '\0' ) {
    81         if( *s != '_' ) {
    82             *d++ = *s;
    83         }
    84         s++;
    85     }
    86     *d = '\0';
    88     return [NSString stringWithUTF8String: buf];
    89 }
    91 static void cocoa_gui_create_menu(void)
    92 {
    93     NSMenu *appleMenu, *services;
    94     NSMenuItem *menuItem;
    95     NSString *title;
    96     NSString *appName;
    98     appName = @"Lxdream";
    99     appleMenu = [[NSMenu alloc] initWithTitle:@""];
   101     /* Add menu items */
   102     title = [@"About " stringByAppendingString:appName];
   103     [appleMenu addItemWithTitle:title action:@selector(about_action:) keyEquivalent:@""];
   105     [appleMenu addItem:[NSMenuItem separatorItem]];
   106     [appleMenu addItemWithTitle: NSMENU_("_Preferences...") action:@selector(preferences_action:) keyEquivalent:@","];
   108     // Services Menu
   109     [appleMenu addItem:[NSMenuItem separatorItem]];
   110     services = [[[NSMenu alloc] init] autorelease];
   111     [appleMenu addItemWithTitle: NS_("Services") action:nil keyEquivalent:@""];
   112     [appleMenu setSubmenu: services forItem: [appleMenu itemWithTitle: @"Services"]];
   114     // Hide AppName
   115     title = [@"Hide " stringByAppendingString:appName];
   116     [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
   118     // Hide Others
   119     menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" 
   120                               action:@selector(hideOtherApplications:) 
   121                               keyEquivalent:@"h"];
   122     [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
   124     // Show All
   125     [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
   126     [appleMenu addItem:[NSMenuItem separatorItem]];
   128     // Quit AppName
   129     title = [@"Quit " stringByAppendingString:appName];
   130     [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
   132     /* Put menu into the menubar */
   133     menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil  keyEquivalent:@""];
   134     [menuItem setSubmenu: appleMenu];
   135     NSMenu *menu = [NSMenu new];
   136     [menu addItem: menuItem];
   138     NSMenu *gdromMenu = cocoa_gdrom_menu_new();
   140     NSMenu *fileMenu = [[NSMenu alloc] initWithTitle: NSMENU_("_File")];
   141     [fileMenu addItemWithTitle: NSMENU_("Load _Binary...") action: @selector(load_binary_action:) keyEquivalent: @"b"];
   142     [[fileMenu addItemWithTitle: NSMENU_("_GD-Rom") action: nil keyEquivalent: @""]
   143       setSubmenu: gdromMenu];
   144     [fileMenu addItem: [NSMenuItem separatorItem]];
   145     [[fileMenu addItemWithTitle: NSMENU_("_Reset") action: @selector(reset_action:) keyEquivalent: @"r"]
   146       setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
   147     [fileMenu addItemWithTitle: NSMENU_("_Pause") action: @selector(pause_action:) keyEquivalent: @"p"];
   148     [fileMenu addItemWithTitle: NS_("Resume") action: @selector(run_action:) keyEquivalent: @"r"];
   149     [fileMenu addItem: [NSMenuItem separatorItem]];
   150     [fileMenu addItemWithTitle: NSMENU_("_Load State...") action: @selector(load_action:) keyEquivalent: @"o"];
   151     [fileMenu addItemWithTitle: NSMENU_("_Save State...") action: @selector(save_action:) keyEquivalent: @"s"];
   153     menuItem = [[NSMenuItem alloc] initWithTitle:NSMENU_("_File") action: nil keyEquivalent: @""];
   154     [menuItem setSubmenu: fileMenu];
   155     [menu addItem: menuItem];
   157     /* Tell the application object that this is now the application menu */
   158     [NSApp setMainMenu: menu];
   159     [NSApp setAppleMenu: appleMenu];
   160     [NSApp setServicesMenu: services];
   162     /* Finally give up our references to the objects */
   163     [appleMenu release];
   164     [menuItem release];
   165     [menu release];
   166 }
   168 @interface LxdreamDelegate : NSObject
   169 @end
   171 @implementation LxdreamDelegate
   172 - (void)windowWillClose: (NSNotification *)notice
   173 {
   174     dreamcast_shutdown();
   175     exit(0);
   176 }
   177 - (void)windowDidBecomeMain: (NSNotification *)notice
   178 {
   179     if( cocoa_gui_autorun ) {
   180         cocoa_gui_autorun = NO;
   181         cocoa_gui_run_later();
   182     }
   183 }
   184 - (void)windowDidBecomeKey: (NSNotification *)notice
   185 {
   186     display_set_focused( TRUE );
   187 }
   188 - (void)windowDidResignKey: (NSNotification *)notice
   189 {
   190     display_set_focused( FALSE );
   191     [((LxdreamMainWindow *)[NSApp mainWindow]) setIsGrabbed: NO];
   192 }
   193 - (BOOL)application: (NSApplication *)app openFile: (NSString *)filename
   194 {
   195     const gchar *cname = [filename UTF8String];
   196     if( file_load_magic(cname) ) {
   197         // Queue up a run event
   198         cocoa_gui_run_later();
   199         return YES;
   200     } else {
   201         return NO;
   202     }
   204 }
   205 - (void) about_action: (id)sender
   206 {
   207     NSArray *keys = [NSArray arrayWithObjects: @"Version", @"Copyright", nil];
   208     NSArray *values = [NSArray arrayWithObjects: NS_(lxdream_full_version), NS_(lxdream_copyright),  nil];
   210     NSDictionary *options= [NSDictionary dictionaryWithObjects: values forKeys: keys];
   212     [NSApp orderFrontStandardAboutPanelWithOptions: options];
   213 }
   214 - (void) preferences_action: (id)sender
   215 {
   216     cocoa_gui_show_preferences();
   217 }
   218 - (void) load_action: (id)sender
   219 {
   220     NSOpenPanel *panel = [NSOpenPanel openPanel];
   221     const gchar *dir = lxdream_get_config_value(CONFIG_SAVE_PATH);
   222     NSString *path = (dir == NULL ? NSHomeDirectory() : [NSString stringWithCString: dir]);
   223     NSArray *fileTypes = [NSArray arrayWithObject: @"dst"];
   224     int result = [panel runModalForDirectory: path file: nil types: fileTypes];
   225     if( result == NSOKButton && [[panel filenames] count] > 0 ) {
   226         NSString *filename = [[panel filenames] objectAtIndex: 0];
   227         dreamcast_load_state( [filename UTF8String] );
   228     }
   229 }
   230 - (void) save_action: (id)sender
   231 {
   232     NSSavePanel *panel = [NSSavePanel savePanel];
   233     const gchar *dir = lxdream_get_config_value(CONFIG_SAVE_PATH);
   234     NSString *path = (dir == NULL ? NSHomeDirectory() : [NSString stringWithCString: dir]);
   235     [panel setRequiredFileType: @"dst"];
   236     int result = [panel runModalForDirectory: path file:@""];
   237     if( result == NSOKButton ) {
   238         NSString *filename = [panel filename];
   239         dreamcast_save_state( [filename UTF8String] );
   240     }
   241 }
   242 - (void) load_binary_action: (id)sender
   243 {
   244     NSOpenPanel *panel = [NSOpenPanel openPanel];
   245     const gchar *dir = lxdream_get_config_value(CONFIG_DEFAULT_PATH);
   246     NSString *path = (dir == NULL ? NSHomeDirectory() : [NSString stringWithCString: dir]);
   247     int result = [panel runModalForDirectory: path file: nil types: nil];
   248     if( result == NSOKButton && [[panel filenames] count] > 0 ) {
   249         NSString *filename = [[panel filenames] objectAtIndex: 0];
   250         file_load_magic( [filename UTF8String] );
   251     }
   252 }
   253 - (void) mount_action: (id)sender
   254 {
   255     NSOpenPanel *panel = [NSOpenPanel openPanel];
   256     const gchar *dir = lxdream_get_config_value(CONFIG_DEFAULT_PATH);
   257     NSString *path = (dir == NULL ? NSHomeDirectory() : [NSString stringWithCString: dir]);
   258     int result = [panel runModalForDirectory: path file: nil types: nil];
   259     if( result == NSOKButton && [[panel filenames] count] > 0 ) {
   260         NSString *filename = [[panel filenames] objectAtIndex: 0];
   261         gdrom_mount_image( [filename UTF8String] );
   262     }
   263 }
   264 - (void) pause_action: (id)sender
   265 {
   266     dreamcast_stop();
   267 }
   269 - (void) reset_action: (id)sender
   270 {
   271     dreamcast_reset();
   272 }
   273 - (void) run_action: (id)sender
   274 {
   275     cocoa_gui_run_later();
   276 }
   277 - (void) run_immediate
   278 {
   279     dreamcast_run();
   280 }
   281 - (void) gdrom_list_action: (id)sender
   282 {
   283     gdrom_list_set_selection( [sender tag] );
   284 }
   285 - (BOOL)validateMenuItem: (NSMenuItem *)item
   286 {
   287     if( [item action] == @selector(run_action:) ) {
   288         return dreamcast_can_run() ? YES : NO;
   289     } else {
   290         return YES;
   291     }
   292 }
   293 - (BOOL)validateToolbarItem: (NSToolbarItem *)item
   294 {
   295     if( [item action] == @selector(run_action:) ) {
   296         return dreamcast_can_run() ? YES : NO;
   297     } else {
   298         return YES;
   299     }
   300 }
   301 @end
   304 gboolean gui_parse_cmdline( int *argc, char **argv[] )
   305 {
   306     /* If started from the finder, the first (and only) arg will look something like 
   307      * -psn_0_... - we want to remove this so that lxdream doesn't try to process it 
   308      * normally
   309      */
   310     if( *argc == 2 && strncmp((*argv)[1], "-psn_", 5) == 0 ) {
   311         *argc = 1;
   312     }
   313     return TRUE;
   314 }
   316 gboolean gui_init( gboolean withDebug )
   317 {
   318     dreamcast_register_module( &cocoa_gui_module );
   320     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   321     [NSApplication sharedApplication];
   323     LxdreamDelegate *delegate = [[LxdreamDelegate alloc] init];
   324     [NSApp setDelegate: delegate];
   325     NSString *iconFile = [[NSBundle mainBundle] pathForResource:@"dcemu" ofType:@"gif"];
   326     NSImage *iconImage = [[NSImage alloc] initWithContentsOfFile: iconFile];
   327     [iconImage setName: @"NSApplicationIcon"];
   328     [NSApp setApplicationIconImage: iconImage];   
   329     cocoa_gui_create_menu();
   330     NSWindow *window = cocoa_gui_create_main_window();
   331     [window makeKeyAndOrderFront: nil];
   332     [NSApp activateIgnoringOtherApps: YES];   
   334     register_gdrom_disc_change_hook( cocoa_gui_disc_changed, window );
   336     [pool release];
   337     return TRUE;
   338 }
   340 void gui_main_loop( gboolean run )
   341 {
   342     if( run ) {
   343         cocoa_gui_autorun = YES;
   344     }
   345     cocoa_gui_is_running = YES;
   346     [NSApp run];
   347     cocoa_gui_is_running = NO;
   348 }
   350 void gui_update_state(void)
   351 {
   352     cocoa_gui_update();
   353 }
   355 void gui_set_use_grab( gboolean grab )
   356 {
   357     [((LxdreamMainWindow *)[NSApp mainWindow]) setUseGrab: (grab ? YES : NO)];
   358 }
   360 gboolean gui_error_dialog( const char *msg, ... )
   361 {
   362     if( cocoa_gui_is_running ) {
   363         NSString *error_string;
   365         va_list args;
   366         va_start(args, msg);
   367         error_string = [[NSString alloc] initWithFormat: [NSString stringWithCString: msg] arguments: args];
   368         NSRunAlertPanel(NS_("Error in Lxdream"), error_string, nil, nil, nil);
   369         va_end(args);
   370         return TRUE;
   371     } else {
   372         return FALSE;
   373     }
   374 }
   376 void gui_update_io_activity( io_activity_type io, gboolean active )
   377 {
   379 }
   382 uint32_t cocoa_gui_run_slice( uint32_t nanosecs )
   383 {
   384     NSEvent *event;
   385     NSAutoreleasePool *pool;
   387     cocoa_gui_nanos += nanosecs;
   388     if( cocoa_gui_nanos > GUI_TICK_PERIOD ) { /* 10 ms */
   389         cocoa_gui_nanos -= GUI_TICK_PERIOD;
   390         cocoa_gui_ticks ++;
   391         uint32_t current_period = cocoa_gui_ticks * GUI_TICK_PERIOD;
   393         // Run the event loop
   394         pool = [NSAutoreleasePool new];
   395         while( (event = [NSApp nextEventMatchingMask: NSAnyEventMask untilDate: nil 
   396                          inMode: NSDefaultRunLoopMode dequeue: YES]) != nil ) {
   397             [NSApp sendEvent: event];
   398         }
   399         [pool release];
   401         struct timeval tv;
   402         gettimeofday(&tv,NULL);
   403         uint32_t ns = ((tv.tv_sec - cocoa_gui_lasttv.tv_sec) * 1000000000) + 
   404         (tv.tv_usec - cocoa_gui_lasttv.tv_usec)*1000;
   405         if( (ns * 1.05) < current_period ) {
   406             // We've gotten ahead - sleep for a little bit
   407             struct timespec tv;
   408             tv.tv_sec = 0;
   409             tv.tv_nsec = current_period - ns;
   410             nanosleep(&tv, &tv);
   411         }
   413         /* Update the display every 10 ticks (ie 10 times a second) and 
   414          * save the current tv value */
   415         if( cocoa_gui_ticks > 10 ) {
   416             gchar buf[32];
   417             cocoa_gui_ticks -= 10;
   419             double speed = (float)( (double)current_period * 100.0 / ns );
   420             cocoa_gui_lasttv.tv_sec = tv.tv_sec;
   421             cocoa_gui_lasttv.tv_usec = tv.tv_usec;
   422             snprintf( buf, 32, _("Running (%2.4f%%)"), speed );
   423             [((LxdreamMainWindow *)[NSApp mainWindow]) setStatusText: buf];
   425         }
   426     }
   427     return nanosecs;
   428 }
   430 void cocoa_gui_update( void )
   431 {
   433 }
   435 void cocoa_gui_start( void )
   436 {
   437     LxdreamMainWindow *win = (LxdreamMainWindow *)[NSApp mainWindow];
   438     [win setRunning: YES];
   439     cocoa_gui_nanos = 0;
   440     gettimeofday(&cocoa_gui_lasttv,NULL);
   441 }
   443 void cocoa_gui_stop( void )
   444 {
   445     LxdreamMainWindow *win = (LxdreamMainWindow *)[NSApp mainWindow];
   446     [win setRunning: NO];
   447 }
   449 /**
   450  * Queue a dreamcast_run() to execute after the currently event(s)
   451  */
   452 void cocoa_gui_run_later( void )
   453 {
   454     [[NSRunLoop currentRunLoop] performSelector: @selector(run_immediate) 
   455      target: [NSApp delegate] argument: nil order: 1 
   456      modes: [NSArray arrayWithObject: NSDefaultRunLoopMode] ];
   457 }
   459 /*************************** Convenience methods ***************************/
   461 NSImage *NSImage_new_from_framebuffer( frame_buffer_t buffer )
   462 {
   463     NSBitmapImageRep *rep = 
   464         [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: &buffer->data
   465          pixelsWide: buffer->width  pixelsHigh: buffer->height
   466          bitsPerSample: 8 samplesPerPixel: 3
   467          hasAlpha: NO isPlanar: NO
   468          colorSpaceName: NSDeviceRGBColorSpace  bitmapFormat: 0
   469          bytesPerRow: buffer->rowstride  bitsPerPixel: 24];
   471     NSImage *image = [[NSImage alloc] initWithSize: NSMakeSize(0.0,0.0)];
   472     [image addRepresentation: rep];
   473     return image;
   474 }
   477 NSTextField *cocoa_gui_add_label( NSView *parent, NSString *text, NSRect frame )
   478 {
   479     NSTextField *label = [[NSTextField alloc] initWithFrame: frame];
   480     [label setStringValue: text];
   481     [label setBordered: NO];
   482     [label setDrawsBackground: NO];
   483     [label setEditable: NO];
   484     [label setAutoresizingMask: (NSViewMinYMargin|NSViewMaxXMargin)];
   485     if( parent != NULL ) {
   486         [parent addSubview: label];
   487     }
   488     return label;
   489 }
.