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