Search
lxdream.org :: lxdream/src/cocoaui/cocoaui.c
lxdream 0.9.1
released Jun 29
Download Now
filename src/cocoaui/cocoaui.c
changeset 773:146c3210768b
prev770:429ff505c450
next780:4e4ea322cb84
author nkeynes
date Mon Jul 28 04:51:04 2008 +0000 (15 years ago)
permissions -rw-r--r--
last change Fix build of testsh4x86
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 "cocoaui/cocoaui.h"
    32 void cocoa_gui_update( void );
    33 void cocoa_gui_start( void );
    34 void cocoa_gui_stop( void );
    35 void cocoa_gui_run_later( void );
    36 uint32_t cocoa_gui_run_slice( uint32_t nanosecs );
    38 struct dreamcast_module cocoa_gui_module = { "gui", NULL,
    39         cocoa_gui_update, 
    40         cocoa_gui_start, 
    41         cocoa_gui_run_slice, 
    42         cocoa_gui_stop, 
    43         NULL, NULL };
    45 /**
    46  * Count of running nanoseconds - used to cut back on the GUI runtime
    47  */
    48 static uint32_t cocoa_gui_nanos = 0;
    49 static uint32_t cocoa_gui_ticks = 0;
    50 static struct timeval cocoa_gui_lasttv;
    51 static BOOL cocoa_gui_autorun = NO;
    52 static BOOL cocoa_gui_is_running = NO;
    54 @interface NSApplication (PrivateAdditions)
    55 - (void) setAppleMenu:(NSMenu *)aMenu;
    56 @end
    58 /**
    59  * Produces the menu title by looking the text up in gettext, removing any
    60  * underscores, and returning the result as an NSString.
    61  */
    62 static NSString *NSMENU_( const char *text )
    63 {
    64     return [[NSString stringWithUTF8String: gettext(text)] stringByReplacingOccurrencesOfString: @"_" withString: @""];
    65 }
    67 static void cocoa_gui_create_menu(void)
    68 {
    69     NSMenu *appleMenu, *services;
    70     NSMenuItem *menuItem;
    71     NSString *title;
    72     NSString *appName;
    74     appName = @"Lxdream";
    75     appleMenu = [[NSMenu alloc] initWithTitle:@""];
    77     /* Add menu items */
    78     title = [@"About " stringByAppendingString:appName];
    79     [appleMenu addItemWithTitle:title action:@selector(about_action:) keyEquivalent:@""];
    81     [appleMenu addItem:[NSMenuItem separatorItem]];
    82     [appleMenu addItemWithTitle: NSMENU_("_Preferences...") action:@selector(preferences_action:) keyEquivalent:@","];
    84     // Services Menu
    85     [appleMenu addItem:[NSMenuItem separatorItem]];
    86     services = [[[NSMenu alloc] init] autorelease];
    87     [appleMenu addItemWithTitle: NS_("Services") action:nil keyEquivalent:@""];
    88     [appleMenu setSubmenu: services forItem: [appleMenu itemWithTitle: @"Services"]];
    90     // Hide AppName
    91     title = [@"Hide " stringByAppendingString:appName];
    92     [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
    94     // Hide Others
    95     menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" 
    96                               action:@selector(hideOtherApplications:) 
    97                               keyEquivalent:@"h"];
    98     [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
   100     // Show All
   101     [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
   102     [appleMenu addItem:[NSMenuItem separatorItem]];
   104     // Quit AppName
   105     title = [@"Quit " stringByAppendingString:appName];
   106     [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
   108     /* Put menu into the menubar */
   109     menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil  keyEquivalent:@""];
   110     [menuItem setSubmenu: appleMenu];
   111     NSMenu *menu = [NSMenu new];
   112     [menu addItem: menuItem];
   114     NSMenu *gdromMenu = cocoa_gdrom_menu_new();
   116     NSMenu *fileMenu = [[NSMenu alloc] initWithTitle: NSMENU_("_File")];
   117     [fileMenu addItemWithTitle: NSMENU_("Load _Binary...") action: @selector(load_binary_action:) keyEquivalent: @"b"];
   118     [[fileMenu addItemWithTitle: NSMENU_("_GD-Rom") action: nil keyEquivalent: @""]
   119       setSubmenu: gdromMenu];
   120     [fileMenu addItem: [NSMenuItem separatorItem]];
   121     [[fileMenu addItemWithTitle: NSMENU_("_Reset") action: @selector(reset_action:) keyEquivalent: @"r"]
   122       setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
   123     [fileMenu addItemWithTitle: NSMENU_("_Pause") action: @selector(pause_action:) keyEquivalent: @"p"];
   124     [fileMenu addItemWithTitle: NS_("Resume") action: @selector(run_action:) keyEquivalent: @"r"];
   125     [fileMenu addItem: [NSMenuItem separatorItem]];
   126     [fileMenu addItemWithTitle: NSMENU_("_Load State...") action: @selector(load_action:) keyEquivalent: @"o"];
   127     [fileMenu addItemWithTitle: NSMENU_("_Save State...") action: @selector(save_action:) keyEquivalent: @"s"];
   129     menuItem = [[NSMenuItem alloc] initWithTitle:NSMENU_("_File") action: nil keyEquivalent: @""];
   130     [menuItem setSubmenu: fileMenu];
   131     [menu addItem: menuItem];
   133     /* Tell the application object that this is now the application menu */
   134     [NSApp setMainMenu: menu];
   135     [NSApp setAppleMenu: appleMenu];
   136     [NSApp setServicesMenu: services];
   138     /* Finally give up our references to the objects */
   139     [appleMenu release];
   140     [menuItem release];
   141     [menu release];
   142 }
   144 @interface LxdreamDelegate : NSObject
   145 @end
   147 @implementation LxdreamDelegate
   148 - (void)windowWillClose: (NSNotification *)notice
   149 {
   150     dreamcast_shutdown();
   151     exit(0);
   152 }
   153 - (void)windowDidBecomeMain: (NSNotification *)notice
   154 {
   155     if( cocoa_gui_autorun ) {
   156         cocoa_gui_autorun = NO;
   157         cocoa_gui_run_later();
   158     }
   159 }
   160 - (void) about_action: (id)sender
   161 {
   162     NSArray *keys = [NSArray arrayWithObjects: @"Version", @"Copyright", nil];
   163     NSArray *values = [NSArray arrayWithObjects: NS_(lxdream_full_version), NS_(lxdream_copyright),  nil];
   165     NSDictionary *options= [NSDictionary dictionaryWithObjects: values forKeys: keys];
   167     [NSApp orderFrontStandardAboutPanelWithOptions: options];
   168 }
   169 - (void) preferences_action: (id)sender
   170 {
   171     cocoa_gui_show_preferences();
   172 }
   173 - (void) load_action: (id)sender
   174 {
   175     NSOpenPanel *panel = [NSOpenPanel openPanel];
   176     const gchar *dir = lxdream_get_config_value(CONFIG_SAVE_PATH);
   177     NSString *path = (dir == NULL ? NSHomeDirectory() : [NSString stringWithCString: dir]);
   178     NSArray *fileTypes = [NSArray arrayWithObject: @"dst"];
   179     int result = [panel runModalForDirectory: path file: nil types: fileTypes];
   180     if( result == NSOKButton && [[panel filenames] count] > 0 ) {
   181         NSString *filename = [[panel filenames] objectAtIndex: 0];
   182         dreamcast_load_state( [filename UTF8String] );
   183     }
   184 }
   185 - (void) save_action: (id)sender
   186 {
   187     NSSavePanel *panel = [NSSavePanel savePanel];
   188     const gchar *dir = lxdream_get_config_value(CONFIG_SAVE_PATH);
   189     NSString *path = (dir == NULL ? NSHomeDirectory() : [NSString stringWithCString: dir]);
   190     [panel setRequiredFileType: @"dst"];
   191     int result = [panel runModalForDirectory: path file:@""];
   192     if( result == NSOKButton ) {
   193         NSString *filename = [panel filename];
   194         dreamcast_save_state( [filename UTF8String] );
   195     }
   196 }
   197 - (void) load_binary_action: (id)sender
   198 {
   199     NSOpenPanel *panel = [NSOpenPanel openPanel];
   200     const gchar *dir = lxdream_get_config_value(CONFIG_DEFAULT_PATH);
   201     NSString *path = (dir == NULL ? NSHomeDirectory() : [NSString stringWithCString: dir]);
   202     int result = [panel runModalForDirectory: path file: nil types: nil];
   203     if( result == NSOKButton && [[panel filenames] count] > 0 ) {
   204         NSString *filename = [[panel filenames] objectAtIndex: 0];
   205         file_load_magic( [filename UTF8String] );
   206     }
   207 }
   208 - (void) mount_action: (id)sender
   209 {
   210     NSOpenPanel *panel = [NSOpenPanel openPanel];
   211     const gchar *dir = lxdream_get_config_value(CONFIG_DEFAULT_PATH);
   212     NSString *path = (dir == NULL ? NSHomeDirectory() : [NSString stringWithCString: dir]);
   213     int result = [panel runModalForDirectory: path file: nil types: nil];
   214     if( result == NSOKButton && [[panel filenames] count] > 0 ) {
   215         NSString *filename = [[panel filenames] objectAtIndex: 0];
   216         gdrom_mount_image( [filename UTF8String] );
   217     }
   218 }
   219 - (void) pause_action: (id)sender
   220 {
   221     dreamcast_stop();
   222 }
   224 - (void) reset_action: (id)sender
   225 {
   226     dreamcast_reset();
   227 }
   228 - (void) run_action: (id)sender
   229 {
   230     cocoa_gui_run_later();
   231 }
   232 - (void) run_immediate
   233 {
   234     dreamcast_run();
   235 }
   236 - (void) gdrom_list_action: (id)sender
   237 {
   238     gdrom_list_set_selection( [sender tag] );
   239 }
   240 @end
   243 gboolean gui_parse_cmdline( int *argc, char **argv[] )
   244 {
   245     /* If started from the finder, the first (and only) arg will look something like 
   246      * -psn_0_... - we want to remove this so that lxdream doesn't try to process it 
   247      * normally
   248      */
   249     if( *argc == 2 && strncmp((*argv)[1], "-psn_", 5) == 0 ) {
   250         *argc = 1;
   251     }
   252     return TRUE;
   253 }
   255 gboolean gui_init( gboolean withDebug )
   256 {
   257     dreamcast_register_module( &cocoa_gui_module );
   259     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   260     [NSApplication sharedApplication];
   262     LxdreamDelegate *delegate = [[LxdreamDelegate alloc] init];
   263     [NSApp setDelegate: delegate];
   264     NSString *iconFile = [[NSBundle mainBundle] pathForResource:@"dcemu" ofType:@"gif"];
   265     NSImage *iconImage = [[NSImage alloc] initWithContentsOfFile: iconFile];
   266     [iconImage setName: @"NSApplicationIcon"];
   267     [NSApp setApplicationIconImage: iconImage];   
   268     cocoa_gui_create_menu();
   269     NSWindow *window = cocoa_gui_create_main_window();
   270     [window makeKeyAndOrderFront: nil];
   271     [NSApp activateIgnoringOtherApps: YES];   
   273     [pool release];
   274 }
   276 void gui_main_loop( gboolean run )
   277 {
   278     if( run ) {
   279         cocoa_gui_autorun = YES;
   280     }
   281     cocoa_gui_is_running = YES;
   282     [NSApp run];
   283     cocoa_gui_is_running = NO;
   284 }
   286 void gui_update_state(void)
   287 {
   288     cocoa_gui_update();
   289 }
   291 gboolean gui_error_dialog( const char *msg, ... )
   292 {
   293     if( cocoa_gui_is_running ) {
   294         NSString *error_string;
   296         va_list args;
   297         va_start(args, msg);
   298         error_string = [[NSString alloc] initWithFormat: [NSString stringWithCString: msg] arguments: args];
   299         NSRunAlertPanel(NS_("Error in Lxdream"), error_string, nil, nil, nil);
   300         va_end(args);
   301         return TRUE;
   302     } else {
   303         return FALSE;
   304     }
   305 }
   307 void gui_update_io_activity( io_activity_type io, gboolean active )
   308 {
   310 }
   313 uint32_t cocoa_gui_run_slice( uint32_t nanosecs )
   314 {
   315     NSEvent *event;
   316     NSAutoreleasePool *pool;
   318     cocoa_gui_nanos += nanosecs;
   319     if( cocoa_gui_nanos > GUI_TICK_PERIOD ) { /* 10 ms */
   320         cocoa_gui_nanos -= GUI_TICK_PERIOD;
   321         cocoa_gui_ticks ++;
   322         uint32_t current_period = cocoa_gui_ticks * GUI_TICK_PERIOD;
   324         // Run the event loop
   325         pool = [NSAutoreleasePool new];
   326         while( (event = [NSApp nextEventMatchingMask: NSAnyEventMask untilDate: nil 
   327                          inMode: NSDefaultRunLoopMode dequeue: YES]) != nil ) {
   328             [NSApp sendEvent: event];
   329         }
   330         [pool release];
   332         struct timeval tv;
   333         gettimeofday(&tv,NULL);
   334         uint32_t ns = ((tv.tv_sec - cocoa_gui_lasttv.tv_sec) * 1000000000) + 
   335         (tv.tv_usec - cocoa_gui_lasttv.tv_usec)*1000;
   336         if( (ns * 1.05) < current_period ) {
   337             // We've gotten ahead - sleep for a little bit
   338             struct timespec tv;
   339             tv.tv_sec = 0;
   340             tv.tv_nsec = current_period - ns;
   341             nanosleep(&tv, &tv);
   342         }
   344         /* Update the display every 10 ticks (ie 10 times a second) and 
   345          * save the current tv value */
   346         if( cocoa_gui_ticks > 10 ) {
   347             gchar buf[32];
   348             cocoa_gui_ticks -= 10;
   350             double speed = (float)( (double)current_period * 100.0 / ns );
   351             cocoa_gui_lasttv.tv_sec = tv.tv_sec;
   352             cocoa_gui_lasttv.tv_usec = tv.tv_usec;
   353             snprintf( buf, 32, _("Running (%2.4f%%)"), speed );
   354             [((LxdreamMainWindow *)[NSApp mainWindow]) setStatusText: buf];
   356         }
   357     }
   358     return nanosecs;
   359 }
   361 void cocoa_gui_update( void )
   362 {
   364 }
   366 void cocoa_gui_start( void )
   367 {
   368     LxdreamMainWindow *win = (LxdreamMainWindow *)[NSApp mainWindow];
   369     [win setRunning: YES];
   370     cocoa_gui_nanos = 0;
   371     gettimeofday(&cocoa_gui_lasttv,NULL);
   372 }
   374 void cocoa_gui_stop( void )
   375 {
   376     LxdreamMainWindow *win = (LxdreamMainWindow *)[NSApp mainWindow];
   377     [win setRunning: NO];
   378 }
   380 /**
   381  * Queue a dreamcast_run() to execute after the currently event(s)
   382  */
   383 void cocoa_gui_run_later( void )
   384 {
   385     [[NSRunLoop currentRunLoop] performSelector: @selector(run_immediate) 
   386      target: [NSApp delegate] argument: nil order: 1 
   387      modes: [NSArray arrayWithObject: NSDefaultRunLoopMode] ];
   388 }
   390 /*************************** Convenience methods ***************************/
   392 NSImage *NSImage_new_from_framebuffer( frame_buffer_t buffer )
   393 {
   394     NSBitmapImageRep *rep = 
   395         [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: &buffer->data
   396          pixelsWide: buffer->width  pixelsHigh: buffer->height
   397          bitsPerSample: 8 samplesPerPixel: 3
   398          hasAlpha: NO isPlanar: NO
   399          colorSpaceName: NSDeviceRGBColorSpace  bitmapFormat: 0
   400          bytesPerRow: buffer->rowstride  bitsPerPixel: 24];
   402     NSImage *image = [[NSImage alloc] initWithSize: NSMakeSize(0.0,0.0)];
   403     [image addRepresentation: rep];
   404     return image;
   405 }
   408 NSTextField *cocoa_gui_add_label( NSView *parent, NSString *text, NSRect frame )
   409 {
   410     NSTextField *label = [[NSTextField alloc] initWithFrame: frame];
   411     [label setStringValue: text];
   412     [label setBordered: NO];
   413     [label setDrawsBackground: NO];
   414     [label setEditable: NO];
   415     [label setAutoresizingMask: (NSViewMinYMargin|NSViewMaxXMargin)];
   416     if( parent != NULL ) {
   417         [parent addSubview: label];
   418     }
   419     return label;
   420 }
.