filename | src/cocoaui/cocoaui.m |
changeset | 1019:87f191f92f8f |
prev | 1017:f94af28e38b7 |
next | 1028:f99eeaf084c2 |
author | nkeynes |
date | Wed Jun 03 10:29:16 2009 +0000 (13 years ago) |
permissions | -rw-r--r-- |
last change | Allow multiple input hooks to be registered for the same key - useful to allow eg binding the same hotkey for run/stop so that it works as a toggle. |
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 uint32_t cocoa_gui_run_slice( uint32_t nanosecs );
40 struct dreamcast_module cocoa_gui_module = { "gui", NULL,
41 cocoa_gui_update,
42 cocoa_gui_start,
43 cocoa_gui_run_slice,
44 cocoa_gui_stop,
45 NULL, NULL };
47 /**
48 * Count of running nanoseconds - used to cut back on the GUI runtime
49 */
50 static uint32_t cocoa_gui_nanos = 0;
51 static uint32_t cocoa_gui_ticks = 0;
52 static struct timeval cocoa_gui_lasttv;
53 static BOOL cocoa_gui_autorun = NO;
54 static BOOL cocoa_gui_is_running = NO;
55 static LxdreamMainWindow *mainWindow = NULL;
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 gui_do_later(dreamcast_run);
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 [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 gui_do_later(dreamcast_run);
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 if( !dreamcast_is_running() ) {
276 gui_do_later(dreamcast_run);
277 }
278 }
279 - (void) gdrom_list_action: (id)sender
280 {
281 gdrom_list_set_selection( [sender tag] );
282 }
283 @end
286 gboolean gui_parse_cmdline( int *argc, char **argv[] )
287 {
288 /* If started from the finder, the first (and only) arg will look something like
289 * -psn_0_... - we want to remove this so that lxdream doesn't try to process it
290 * normally
291 */
292 if( *argc == 2 && strncmp((*argv)[1], "-psn_", 5) == 0 ) {
293 *argc = 1;
294 }
295 return TRUE;
296 }
298 gboolean gui_init( gboolean withDebug, gboolean withFullscreen )
299 {
300 dreamcast_register_module( &cocoa_gui_module );
302 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
303 [NSApplication sharedApplication];
305 LxdreamDelegate *delegate = [[LxdreamDelegate alloc] init];
306 [NSApp setDelegate: delegate];
307 NSString *iconFile = [[NSBundle mainBundle] pathForResource:@"lxdream" ofType:@"png"];
308 NSImage *iconImage = [[NSImage alloc] initWithContentsOfFile: iconFile];
309 [iconImage setName: @"NSApplicationIcon"];
310 [NSApp setApplicationIconImage: iconImage];
311 cocoa_gui_create_menu();
312 mainWindow = cocoa_gui_create_main_window();
313 [mainWindow makeKeyAndOrderFront: nil];
314 [NSApp activateIgnoringOtherApps: YES];
316 register_gdrom_disc_change_hook( cocoa_gui_disc_changed, mainWindow );
318 [pool release];
319 return TRUE;
320 }
322 void gui_main_loop( gboolean run )
323 {
324 if( run ) {
325 cocoa_gui_autorun = YES;
326 }
327 cocoa_gui_is_running = YES;
328 [NSApp run];
329 cocoa_gui_is_running = NO;
330 }
332 void gui_update_state(void)
333 {
334 cocoa_gui_update();
335 }
337 void gui_set_use_grab( gboolean grab )
338 {
339 [mainWindow setUseGrab: (grab ? YES : NO)];
340 }
342 gboolean gui_error_dialog( const char *msg, ... )
343 {
344 if( cocoa_gui_is_running ) {
345 NSString *error_string;
347 va_list args;
348 va_start(args, msg);
349 error_string = [[NSString alloc] initWithFormat: [NSString stringWithCString: msg] arguments: args];
350 NSRunAlertPanel(NS_("Error in Lxdream"), error_string, nil, nil, nil);
351 va_end(args);
352 return TRUE;
353 } else {
354 return FALSE;
355 }
356 }
358 void gui_update_io_activity( io_activity_type io, gboolean active )
359 {
361 }
364 uint32_t cocoa_gui_run_slice( uint32_t nanosecs )
365 {
366 NSEvent *event;
367 NSAutoreleasePool *pool;
369 cocoa_gui_nanos += nanosecs;
370 if( cocoa_gui_nanos > GUI_TICK_PERIOD ) { /* 10 ms */
371 cocoa_gui_nanos -= GUI_TICK_PERIOD;
372 cocoa_gui_ticks ++;
373 uint32_t current_period = cocoa_gui_ticks * GUI_TICK_PERIOD;
375 // Run the event loop
376 pool = [NSAutoreleasePool new];
377 while( (event = [NSApp nextEventMatchingMask: NSAnyEventMask untilDate: nil
378 inMode: NSDefaultRunLoopMode dequeue: YES]) != nil ) {
379 [NSApp sendEvent: event];
380 }
381 [pool release];
383 struct timeval tv;
384 gettimeofday(&tv,NULL);
385 uint32_t ns = ((tv.tv_sec - cocoa_gui_lasttv.tv_sec) * 1000000000) +
386 (tv.tv_usec - cocoa_gui_lasttv.tv_usec)*1000;
387 if( (ns * 1.05) < current_period ) {
388 // We've gotten ahead - sleep for a little bit
389 struct timespec tv;
390 tv.tv_sec = 0;
391 tv.tv_nsec = current_period - ns;
392 nanosleep(&tv, &tv);
393 }
395 /* Update the display every 10 ticks (ie 10 times a second) and
396 * save the current tv value */
397 if( cocoa_gui_ticks > 10 ) {
398 gchar buf[32];
399 cocoa_gui_ticks -= 10;
401 double speed = (float)( (double)current_period * 100.0 / ns );
402 cocoa_gui_lasttv.tv_sec = tv.tv_sec;
403 cocoa_gui_lasttv.tv_usec = tv.tv_usec;
404 snprintf( buf, 32, _("Running (%2.4f%%)"), speed );
405 [mainWindow setStatusText: buf];
407 }
408 }
409 return nanosecs;
410 }
412 void cocoa_gui_update( void )
413 {
415 }
417 void cocoa_gui_start( void )
418 {
419 [mainWindow setRunning: YES];
420 cocoa_gui_nanos = 0;
421 gettimeofday(&cocoa_gui_lasttv,NULL);
422 }
424 void cocoa_gui_stop( void )
425 {
426 [mainWindow setRunning: NO];
427 }
429 @interface DoLaterStub : NSObject
430 {
431 do_later_callback_t func;
432 }
433 @end
435 @implementation DoLaterStub
436 - (id) init: (do_later_callback_t)f
437 {
438 [super init];
439 func = f;
440 return self;
441 }
442 - (void) do
443 {
444 func();
445 }
446 @end
448 /**
449 * Queue a dreamcast_run() to execute after the currently event(s)
450 */
451 void gui_do_later( do_later_callback_t func )
452 {
453 DoLaterStub *stub = [[[DoLaterStub alloc] init: func] autorelease];
454 [[NSRunLoop currentRunLoop] performSelector: @selector(do)
455 target: stub 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 }
.