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"
30 #include "gdrom/gdrom.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,
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( gdrom_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)
94 NSMenu *appleMenu, *services;
100 appleMenu = [[NSMenu alloc] initWithTitle:@""];
103 title = [@"About " stringByAppendingString:appName];
104 [appleMenu addItemWithTitle:title action:@selector(about_action:) keyEquivalent:@""];
106 [appleMenu addItem:[NSMenuItem separatorItem]];
107 [appleMenu addItemWithTitle: NSMENU_("_Preferences...") action:@selector(preferences_action:) keyEquivalent:@","];
110 [appleMenu addItem:[NSMenuItem separatorItem]];
111 services = [[[NSMenu alloc] init] autorelease];
112 [appleMenu addItemWithTitle: NS_("Services") action:nil keyEquivalent:@""];
113 [appleMenu setSubmenu: services forItem: [appleMenu itemWithTitle: @"Services"]];
116 title = [@"Hide " stringByAppendingString:appName];
117 [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
120 menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others"
121 action:@selector(hideOtherApplications:)
123 [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
126 [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
127 [appleMenu addItem:[NSMenuItem separatorItem]];
130 title = [@"Quit " stringByAppendingString:appName];
131 [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
133 /* Put menu into the menubar */
134 menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
135 [menuItem setSubmenu: appleMenu];
136 NSMenu *menu = [NSMenu new];
137 [menu addItem: menuItem];
139 NSMenu *gdromMenu = cocoa_gdrom_menu_new();
141 NSMenu *fileMenu = [[NSMenu alloc] initWithTitle: NSMENU_("_File")];
142 [fileMenu addItemWithTitle: NSMENU_("Load _Binary...") action: @selector(load_binary_action:) keyEquivalent: @"b"];
143 [[fileMenu addItemWithTitle: NSMENU_("_GD-Rom") action: nil keyEquivalent: @""]
144 setSubmenu: gdromMenu];
145 [fileMenu addItem: [NSMenuItem separatorItem]];
146 [[fileMenu addItemWithTitle: NSMENU_("_Reset") action: @selector(reset_action:) keyEquivalent: @"r"]
147 setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
148 [fileMenu addItemWithTitle: NSMENU_("_Pause") action: @selector(pause_action:) keyEquivalent: @"p"];
149 [fileMenu addItemWithTitle: NS_("Resume") action: @selector(run_action:) keyEquivalent: @"r"];
150 [fileMenu addItem: [NSMenuItem separatorItem]];
151 [fileMenu addItemWithTitle: NSMENU_("_Load State...") action: @selector(load_action:) keyEquivalent: @"o"];
152 [fileMenu addItemWithTitle: NSMENU_("_Save State...") action: @selector(save_action:) keyEquivalent: @"s"];
154 menuItem = [[NSMenuItem alloc] initWithTitle:NSMENU_("_File") action: nil keyEquivalent: @""];
155 [menuItem setSubmenu: fileMenu];
156 [menu addItem: menuItem];
158 /* Tell the application object that this is now the application menu */
159 [NSApp setMainMenu: menu];
160 [NSApp setAppleMenu: appleMenu];
161 [NSApp setServicesMenu: services];
163 /* Finally give up our references to the objects */
169 @interface LxdreamDelegate : NSObject
172 @implementation LxdreamDelegate
173 - (void)windowWillClose: (NSNotification *)notice
175 dreamcast_shutdown();
178 - (void)windowDidBecomeMain: (NSNotification *)notice
180 if( cocoa_gui_autorun ) {
181 cocoa_gui_autorun = NO;
182 cocoa_gui_run_later();
185 - (void)windowDidBecomeKey: (NSNotification *)notice
187 display_set_focused( TRUE );
189 - (void)windowDidResignKey: (NSNotification *)notice
191 display_set_focused( FALSE );
192 [mainWindow setIsGrabbed: NO];
194 - (BOOL)application: (NSApplication *)app openFile: (NSString *)filename
196 const gchar *cname = [filename UTF8String];
197 if( file_load_magic(cname) ) {
198 // Queue up a run event
199 cocoa_gui_run_later();
206 - (void) about_action: (id)sender
208 NSArray *keys = [NSArray arrayWithObjects: @"Version", @"Copyright", nil];
209 NSArray *values = [NSArray arrayWithObjects: NS_(lxdream_full_version), NS_(lxdream_copyright), nil];
211 NSDictionary *options= [NSDictionary dictionaryWithObjects: values forKeys: keys];
213 [NSApp orderFrontStandardAboutPanelWithOptions: options];
215 - (void) preferences_action: (id)sender
217 cocoa_gui_show_preferences();
219 - (void) load_action: (id)sender
221 NSOpenPanel *panel = [NSOpenPanel openPanel];
222 const gchar *dir = lxdream_get_config_value(CONFIG_SAVE_PATH);
223 NSString *path = (dir == NULL ? NSHomeDirectory() : [NSString stringWithCString: dir]);
224 NSArray *fileTypes = [NSArray arrayWithObject: @"dst"];
225 int result = [panel runModalForDirectory: path file: nil types: fileTypes];
226 if( result == NSOKButton && [[panel filenames] count] > 0 ) {
227 NSString *filename = [[panel filenames] objectAtIndex: 0];
228 dreamcast_load_state( [filename UTF8String] );
231 - (void) save_action: (id)sender
233 NSSavePanel *panel = [NSSavePanel savePanel];
234 const gchar *dir = lxdream_get_config_value(CONFIG_SAVE_PATH);
235 NSString *path = (dir == NULL ? NSHomeDirectory() : [NSString stringWithCString: dir]);
236 [panel setRequiredFileType: @"dst"];
237 int result = [panel runModalForDirectory: path file:@""];
238 if( result == NSOKButton ) {
239 NSString *filename = [panel filename];
240 dreamcast_save_state( [filename UTF8String] );
243 - (void) load_binary_action: (id)sender
245 NSOpenPanel *panel = [NSOpenPanel openPanel];
246 const gchar *dir = lxdream_get_config_value(CONFIG_DEFAULT_PATH);
247 NSString *path = (dir == NULL ? NSHomeDirectory() : [NSString stringWithCString: dir]);
248 int result = [panel runModalForDirectory: path file: nil types: nil];
249 if( result == NSOKButton && [[panel filenames] count] > 0 ) {
250 NSString *filename = [[panel filenames] objectAtIndex: 0];
251 file_load_magic( [filename UTF8String] );
254 - (void) mount_action: (id)sender
256 NSOpenPanel *panel = [NSOpenPanel openPanel];
257 const gchar *dir = lxdream_get_config_value(CONFIG_DEFAULT_PATH);
258 NSString *path = (dir == NULL ? NSHomeDirectory() : [NSString stringWithCString: dir]);
259 int result = [panel runModalForDirectory: path file: nil types: nil];
260 if( result == NSOKButton && [[panel filenames] count] > 0 ) {
261 NSString *filename = [[panel filenames] objectAtIndex: 0];
262 gdrom_mount_image( [filename UTF8String] );
265 - (void) pause_action: (id)sender
270 - (void) reset_action: (id)sender
274 - (void) run_action: (id)sender
276 if( !dreamcast_is_running() ) {
277 cocoa_gui_run_later();
280 - (void) run_immediate
283 [mainWindow setRunning: NO];
285 - (void) gdrom_list_action: (id)sender
287 gdrom_list_set_selection( [sender tag] );
292 gboolean gui_parse_cmdline( int *argc, char **argv[] )
294 /* If started from the finder, the first (and only) arg will look something like
295 * -psn_0_... - we want to remove this so that lxdream doesn't try to process it
298 if( *argc == 2 && strncmp((*argv)[1], "-psn_", 5) == 0 ) {
304 gboolean gui_init( gboolean withDebug )
306 dreamcast_register_module( &cocoa_gui_module );
308 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
309 [NSApplication sharedApplication];
311 LxdreamDelegate *delegate = [[LxdreamDelegate alloc] init];
312 [NSApp setDelegate: delegate];
313 NSString *iconFile = [[NSBundle mainBundle] pathForResource:@"dcemu" ofType:@"gif"];
314 NSImage *iconImage = [[NSImage alloc] initWithContentsOfFile: iconFile];
315 [iconImage setName: @"NSApplicationIcon"];
316 [NSApp setApplicationIconImage: iconImage];
317 cocoa_gui_create_menu();
318 mainWindow = cocoa_gui_create_main_window();
319 [mainWindow makeKeyAndOrderFront: nil];
320 [NSApp activateIgnoringOtherApps: YES];
322 register_gdrom_disc_change_hook( cocoa_gui_disc_changed, mainWindow );
328 void gui_main_loop( gboolean run )
331 cocoa_gui_autorun = YES;
333 cocoa_gui_is_running = YES;
335 cocoa_gui_is_running = NO;
338 void gui_update_state(void)
343 void gui_set_use_grab( gboolean grab )
345 [mainWindow setUseGrab: (grab ? YES : NO)];
348 gboolean gui_error_dialog( const char *msg, ... )
350 if( cocoa_gui_is_running ) {
351 NSString *error_string;
355 error_string = [[NSString alloc] initWithFormat: [NSString stringWithCString: msg] arguments: args];
356 NSRunAlertPanel(NS_("Error in Lxdream"), error_string, nil, nil, nil);
364 void gui_update_io_activity( io_activity_type io, gboolean active )
370 uint32_t cocoa_gui_run_slice( uint32_t nanosecs )
373 NSAutoreleasePool *pool;
375 cocoa_gui_nanos += nanosecs;
376 if( cocoa_gui_nanos > GUI_TICK_PERIOD ) { /* 10 ms */
377 cocoa_gui_nanos -= GUI_TICK_PERIOD;
379 uint32_t current_period = cocoa_gui_ticks * GUI_TICK_PERIOD;
381 // Run the event loop
382 pool = [NSAutoreleasePool new];
383 while( (event = [NSApp nextEventMatchingMask: NSAnyEventMask untilDate: nil
384 inMode: NSDefaultRunLoopMode dequeue: YES]) != nil ) {
385 [NSApp sendEvent: event];
390 gettimeofday(&tv,NULL);
391 uint32_t ns = ((tv.tv_sec - cocoa_gui_lasttv.tv_sec) * 1000000000) +
392 (tv.tv_usec - cocoa_gui_lasttv.tv_usec)*1000;
393 if( (ns * 1.05) < current_period ) {
394 // We've gotten ahead - sleep for a little bit
397 tv.tv_nsec = current_period - ns;
401 /* Update the display every 10 ticks (ie 10 times a second) and
402 * save the current tv value */
403 if( cocoa_gui_ticks > 10 ) {
405 cocoa_gui_ticks -= 10;
407 double speed = (float)( (double)current_period * 100.0 / ns );
408 cocoa_gui_lasttv.tv_sec = tv.tv_sec;
409 cocoa_gui_lasttv.tv_usec = tv.tv_usec;
410 snprintf( buf, 32, _("Running (%2.4f%%)"), speed );
411 [mainWindow setStatusText: buf];
418 void cocoa_gui_update( void )
423 void cocoa_gui_start( void )
425 [mainWindow setRunning: YES];
427 gettimeofday(&cocoa_gui_lasttv,NULL);
430 void cocoa_gui_stop( void )
432 [mainWindow setRunning: NO];
436 * Queue a dreamcast_run() to execute after the currently event(s)
438 void cocoa_gui_run_later( void )
440 [[NSRunLoop currentRunLoop] performSelector: @selector(run_immediate)
441 target: [NSApp delegate] argument: nil order: 1
442 modes: [NSArray arrayWithObject: NSDefaultRunLoopMode] ];
445 /*************************** Convenience methods ***************************/
447 NSImage *NSImage_new_from_framebuffer( frame_buffer_t buffer )
449 NSBitmapImageRep *rep =
450 [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: &buffer->data
451 pixelsWide: buffer->width pixelsHigh: buffer->height
452 bitsPerSample: 8 samplesPerPixel: 3
453 hasAlpha: NO isPlanar: NO
454 colorSpaceName: NSDeviceRGBColorSpace bitmapFormat: 0
455 bytesPerRow: buffer->rowstride bitsPerPixel: 24];
457 NSImage *image = [[NSImage alloc] initWithSize: NSMakeSize(0.0,0.0)];
458 [image addRepresentation: rep];
463 NSTextField *cocoa_gui_add_label( NSView *parent, NSString *text, NSRect frame )
465 NSTextField *label = [[NSTextField alloc] initWithFrame: frame];
466 [label setStringValue: text];
467 [label setBordered: NO];
468 [label setDrawsBackground: NO];
469 [label setEditable: NO];
470 [label setAutoresizingMask: (NSViewMinYMargin|NSViewMaxXMargin)];
471 if( parent != NULL ) {
472 [parent addSubview: label];
.