root/OpenSceneGraph/trunk/examples/osgsimpleviewerSDL/SDLMainForMacOSX.m @ 6214

Revision 6214, 11.1 kB (checked in by robert, 7 years ago)

From Eric Wing, updates to XCode projects and introduction of two SDL OSX files to the osgsimpleviewerSDL example

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/*   SDLMain.m - main entry point for our Cocoa-ized SDL app
2       Initial Version: Darrell Walisser <dwaliss1@purdue.edu>
3       Non-NIB-Code & other changes: Max Horn <max@quendi.de>
4
5    Feel free to customize this file to suit your needs
6       
7        OSG users: This is the standard SDLMain (nibless) that
8        comes with the SDL distribution. Only the file name has
9        been changed to avoid confusing non-Mac users.
10*/
11
12#import "SDL.h"
13#import "SDLMainForMacOSX.h"
14#import <sys/param.h> /* for MAXPATHLEN */
15#import <unistd.h>
16
17/* For some reaon, Apple removed setAppleMenu from the headers in 10.4,
18 but the method still is there and works. To avoid warnings, we declare
19 it ourselves here. */
20@interface NSApplication(SDL_Missing_Methods)
21- (void)setAppleMenu:(NSMenu *)menu;
22@end
23
24/* Use this flag to determine whether we use SDLMain.nib or not */
25#define         SDL_USE_NIB_FILE        0
26
27/* Use this flag to determine whether we use CPS (docking) or not */
28#define         SDL_USE_CPS             1
29#ifdef SDL_USE_CPS
30/* Portions of CPS.h */
31typedef struct CPSProcessSerNum
32{
33        UInt32          lo;
34        UInt32          hi;
35} CPSProcessSerNum;
36
37extern OSErr    CPSGetCurrentProcess( CPSProcessSerNum *psn);
38extern OSErr    CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);
39extern OSErr    CPSSetFrontProcess( CPSProcessSerNum *psn);
40
41#endif /* SDL_USE_CPS */
42
43static int    gArgc;
44static char  **gArgv;
45static BOOL   gFinderLaunch;
46static BOOL   gCalledAppMainline = FALSE;
47
48static NSString *getApplicationName(void)
49{
50    NSDictionary *dict;
51    NSString *appName = 0;
52
53    /* Determine the application name */
54    dict = (NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle());
55    if (dict)
56        appName = [dict objectForKey: @"CFBundleName"];
57   
58    if (![appName length])
59        appName = [[NSProcessInfo processInfo] processName];
60
61    return appName;
62}
63
64#if SDL_USE_NIB_FILE
65/* A helper category for NSString */
66@interface NSString (ReplaceSubString)
67- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString;
68@end
69#endif
70
71@interface SDLApplication : NSApplication
72@end
73
74@implementation SDLApplication
75/* Invoked from the Quit menu item */
76- (void)terminate:(id)sender
77{
78    /* Post a SDL_QUIT event */
79    SDL_Event event;
80    event.type = SDL_QUIT;
81    SDL_PushEvent(&event);
82}
83@end
84
85/* The main class of the application, the application's delegate */
86@implementation SDLMain
87
88/* Set the working directory to the .app's parent directory */
89- (void) setupWorkingDirectory:(BOOL)shouldChdir
90{
91    if (shouldChdir)
92    {
93        char parentdir[MAXPATHLEN];
94                CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle());
95                CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url);
96                if (CFURLGetFileSystemRepresentation(url2, true, (UInt8 *)parentdir, MAXPATHLEN)) {
97                assert ( chdir (parentdir) == 0 );   /* chdir to the binary app's parent */
98                }
99                CFRelease(url);
100                CFRelease(url2);
101        }
102
103}
104
105#if SDL_USE_NIB_FILE
106
107/* Fix menu to contain the real app name instead of "SDL App" */
108- (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName
109{
110    NSRange aRange;
111    NSEnumerator *enumerator;
112    NSMenuItem *menuItem;
113
114    aRange = [[aMenu title] rangeOfString:@"SDL App"];
115    if (aRange.length != 0)
116        [aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]];
117
118    enumerator = [[aMenu itemArray] objectEnumerator];
119    while ((menuItem = [enumerator nextObject]))
120    {
121        aRange = [[menuItem title] rangeOfString:@"SDL App"];
122        if (aRange.length != 0)
123            [menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]];
124        if ([menuItem hasSubmenu])
125            [self fixMenu:[menuItem submenu] withAppName:appName];
126    }
127    [ aMenu sizeToFit ];
128}
129
130#else
131
132static void setApplicationMenu(void)
133{
134    /* warning: this code is very odd */
135    NSMenu *appleMenu;
136    NSMenuItem *menuItem;
137    NSString *title;
138    NSString *appName;
139   
140    appName = getApplicationName();
141    appleMenu = [[NSMenu alloc] initWithTitle:@""];
142   
143    /* Add menu items */
144    title = [@"About " stringByAppendingString:appName];
145    [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
146
147    [appleMenu addItem:[NSMenuItem separatorItem]];
148
149    title = [@"Hide " stringByAppendingString:appName];
150    [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
151
152    menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
153    [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
154
155    [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
156
157    [appleMenu addItem:[NSMenuItem separatorItem]];
158
159    title = [@"Quit " stringByAppendingString:appName];
160    [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
161
162   
163    /* Put menu into the menubar */
164    menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
165    [menuItem setSubmenu:appleMenu];
166    [[NSApp mainMenu] addItem:menuItem];
167
168    /* Tell the application object that this is now the application menu */
169    [NSApp setAppleMenu:appleMenu];
170
171    /* Finally give up our references to the objects */
172    [appleMenu release];
173    [menuItem release];
174}
175
176/* Create a window menu */
177static void setupWindowMenu(void)
178{
179    NSMenu      *windowMenu;
180    NSMenuItem  *windowMenuItem;
181    NSMenuItem  *menuItem;
182
183    windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
184   
185    /* "Minimize" item */
186    menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
187    [windowMenu addItem:menuItem];
188    [menuItem release];
189   
190    /* Put menu into the menubar */
191    windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
192    [windowMenuItem setSubmenu:windowMenu];
193    [[NSApp mainMenu] addItem:windowMenuItem];
194   
195    /* Tell the application object that this is now the window menu */
196    [NSApp setWindowsMenu:windowMenu];
197
198    /* Finally give up our references to the objects */
199    [windowMenu release];
200    [windowMenuItem release];
201}
202
203/* Replacement for NSApplicationMain */
204static void CustomApplicationMain (int argc, char **argv)
205{
206    NSAutoreleasePool   *pool = [[NSAutoreleasePool alloc] init];
207    SDLMain                             *sdlMain;
208
209    /* Ensure the application object is initialised */
210    [SDLApplication sharedApplication];
211   
212#ifdef SDL_USE_CPS
213    {
214        CPSProcessSerNum PSN;
215        /* Tell the dock about us */
216        if (!CPSGetCurrentProcess(&PSN))
217            if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103))
218                if (!CPSSetFrontProcess(&PSN))
219                    [SDLApplication sharedApplication];
220    }
221#endif /* SDL_USE_CPS */
222
223    /* Set up the menubar */
224    [NSApp setMainMenu:[[NSMenu alloc] init]];
225    setApplicationMenu();
226    setupWindowMenu();
227
228    /* Create SDLMain and make it the app delegate */
229    sdlMain = [[SDLMain alloc] init];
230    [NSApp setDelegate:sdlMain];
231   
232    /* Start the main event loop */
233    [NSApp run];
234   
235    [sdlMain release];
236    [pool release];
237}
238
239#endif
240
241
242/*
243 * Catch document open requests...this lets us notice files when the app
244 *  was launched by double-clicking a document, or when a document was
245 *  dragged/dropped on the app's icon. You need to have a
246 *  CFBundleDocumentsType section in your Info.plist to get this message,
247 *  apparently.
248 *
249 * Files are added to gArgv, so to the app, they'll look like command line
250 *  arguments. Previously, apps launched from the finder had nothing but
251 *  an argv[0].
252 *
253 * This message may be received multiple times to open several docs on launch.
254 *
255 * This message is ignored once the app's mainline has been called.
256 */
257- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
258{
259    const char *temparg;
260    size_t arglen;
261    char *arg;
262    char **newargv;
263
264    if (!gFinderLaunch)  /* MacOS is passing command line args. */
265        return FALSE;
266
267    if (gCalledAppMainline)  /* app has started, ignore this document. */
268        return FALSE;
269
270    temparg = [filename UTF8String];
271    arglen = SDL_strlen(temparg) + 1;
272    arg = (char *) SDL_malloc(arglen);
273    if (arg == NULL)
274        return FALSE;
275
276    newargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 2));
277    if (newargv == NULL)
278    {
279        SDL_free(arg);
280        return FALSE;
281    }
282    gArgv = newargv;
283
284    SDL_strlcpy(arg, temparg, arglen);
285    gArgv[gArgc++] = arg;
286    gArgv[gArgc] = NULL;
287    return TRUE;
288}
289
290
291/* Called when the internal event loop has just started running */
292- (void) applicationDidFinishLaunching: (NSNotification *) note
293{
294    int status;
295
296    /* Set the working directory to the .app's parent directory */
297    [self setupWorkingDirectory:gFinderLaunch];
298
299#if SDL_USE_NIB_FILE
300    /* Set the main menu to contain the real app name instead of "SDL App" */
301    [self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()];
302#endif
303
304    /* Hand off to main application code */
305    gCalledAppMainline = TRUE;
306    status = SDL_main (gArgc, gArgv);
307
308    /* We're done, thank you for playing */
309    exit(status);
310}
311@end
312
313
314@implementation NSString (ReplaceSubString)
315
316- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString
317{
318    unsigned int bufferSize;
319    unsigned int selfLen = [self length];
320    unsigned int aStringLen = [aString length];
321    unichar *buffer;
322    NSRange localRange;
323    NSString *result;
324
325    bufferSize = selfLen + aStringLen - aRange.length;
326    buffer = NSAllocateMemoryPages(bufferSize*sizeof(unichar));
327   
328    /* Get first part into buffer */
329    localRange.location = 0;
330    localRange.length = aRange.location;
331    [self getCharacters:buffer range:localRange];
332   
333    /* Get middle part into buffer */
334    localRange.location = 0;
335    localRange.length = aStringLen;
336    [aString getCharacters:(buffer+aRange.location) range:localRange];
337     
338    /* Get last part into buffer */
339    localRange.location = aRange.location + aRange.length;
340    localRange.length = selfLen - localRange.location;
341    [self getCharacters:(buffer+aRange.location+aStringLen) range:localRange];
342   
343    /* Build output string */
344    result = [NSString stringWithCharacters:buffer length:bufferSize];
345   
346    NSDeallocateMemoryPages(buffer, bufferSize);
347   
348    return result;
349}
350
351@end
352
353
354
355#ifdef main
356undef main
357#endif
358
359
360/* Main entry point to executable - should *not* be SDL_main! */
361int main (int argc, char **argv)
362{
363    /* Copy the arguments into a global variable */
364    /* This is passed if we are launched by double-clicking */
365    if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) {
366        gArgv = (char **) SDL_malloc(sizeof (char *) * 2);
367        gArgv[0] = argv[0];
368        gArgv[1] = NULL;
369        gArgc = 1;
370        gFinderLaunch = YES;
371    } else {
372        int i;
373        gArgc = argc;
374        gArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1));
375        for (i = 0; i <= argc; i++)
376            gArgv[i] = argv[i];
377        gFinderLaunch = NO;
378    }
379
380#if SDL_USE_NIB_FILE
381    [SDLApplication poseAsClass:[NSApplication class]];
382    NSApplicationMain (argc, argv);
383#else
384    CustomApplicationMain (argc, argv);
385#endif
386    return 0;
387}
Note: See TracBrowser for help on using the browser.