Apply the new ground_level method.
[crawl.git] / crawl-ref / source / SDLMain.m
blobba6bac43ca7c2e4730500eab3d396f7f93d6e70d
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>
5     Feel free to customize this file to suit your needs
6 */
8 #import "SDL.h"
9 #import "SDLMain.h"
10 #import <sys/param.h> /* for MAXPATHLEN */
11 #import <unistd.h>
13 /* For some reaon, Apple removed setAppleMenu from the headers in 10.4,
14  but the method still is there and works. To avoid warnings, we declare
15  it ourselves here. */
16 @interface NSApplication(SDL_Missing_Methods)
17 - (void)setAppleMenu:(NSMenu *)menu;
18 @end
20 /* Use this flag to determine whether we use SDLMain.nib or not */
21 #define         SDL_USE_NIB_FILE        0
23 /* Use this flag to determine whether we use CPS (docking) or not */
24 #define         SDL_USE_CPS             1
25 #ifdef SDL_USE_CPS
26 /* Portions of CPS.h */
27 typedef struct CPSProcessSerNum
29     UInt32      lo;
30     UInt32      hi;
31 } CPSProcessSerNum;
33 extern OSErr    CPSGetCurrentProcess(CPSProcessSerNum *psn);
34 extern OSErr    CPSEnableForegroundOperation(CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);
35 extern OSErr    CPSSetFrontProcess(CPSProcessSerNum *psn);
37 #endif /* SDL_USE_CPS */
39 static int    gArgc;
40 static char  **gArgv;
41 static BOOL   gFinderLaunch;
42 static BOOL   gCalledAppMainline = FALSE;
44 static NSString *getApplicationName(void)
46     NSDictionary *dict;
47     NSString *appName = 0;
49     /* Determine the application name */
50     dict = (NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle());
51     if (dict)
52         appName = [dict objectForKey: @"CFBundleName"];
54     if (![appName length])
55         appName = [[NSProcessInfo processInfo] processName];
57     return appName;
60 #if SDL_USE_NIB_FILE
61 /* A helper category for NSString */
62 @interface NSString (ReplaceSubString)
63 - (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString;
64 @end
65 #endif
67 @interface SDLApplication : NSApplication
68 @end
70 @implementation SDLApplication
71 /* Invoked from the Quit menu item */
72 - (void)terminate:(id)sender
74     /* Post a SDL_QUIT event */
75     SDL_Event event;
76     event.type = SDL_QUIT;
77     SDL_PushEvent(&event);
79 @end
81 /* The main class of the application, the application's delegate */
82 @implementation SDLMain
84 /* Set the working directory to the .app's parent directory */
85 - (void) setupWorkingDirectory:(BOOL)shouldChdir
87     if (shouldChdir)
88     {
89         char parentdir[MAXPATHLEN];
90         CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle());
91         CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url);
92         if (CFURLGetFileSystemRepresentation(url2, true, (UInt8 *)parentdir,
93                                              MAXPATHLEN))
94         {
95             assert (chdir (parentdir) == 0);   /* chdir to the binary app's parent */
96         }
97         CFRelease(url);
98         CFRelease(url2);
99     }
102 #if SDL_USE_NIB_FILE
104 /* Fix menu to contain the real app name instead of "SDL App" */
105 - (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName
107     NSRange aRange;
108     NSEnumerator *enumerator;
109     NSMenuItem *menuItem;
111     aRange = [[aMenu title] rangeOfString:@"SDL App"];
112     if (aRange.length != 0)
113         [aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]];
115     enumerator = [[aMenu itemArray] objectEnumerator];
116     while ((menuItem = [enumerator nextObject]))
117     {
118         aRange = [[menuItem title] rangeOfString:@"SDL App"];
119         if (aRange.length != 0)
120             [menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]];
121         if ([menuItem hasSubmenu])
122             [self fixMenu:[menuItem submenu] withAppName:appName];
123     }
124     [ aMenu sizeToFit ];
127 #else
129 static void setApplicationMenu(void)
131     /* warning: this code is very odd */
132     NSMenu *appleMenu;
133     NSMenuItem *menuItem;
134     NSString *title;
135     NSString *appName;
137     appName = getApplicationName();
138     appleMenu = [[NSMenu alloc] initWithTitle:@""];
140     /* Add menu items */
141     title = [@"About " stringByAppendingString:appName];
142     [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
144     [appleMenu addItem:[NSMenuItem separatorItem]];
146     title = [@"Hide " stringByAppendingString:appName];
147     [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
149     menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
150     [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
152     [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
154     [appleMenu addItem:[NSMenuItem separatorItem]];
156     title = [@"Quit " stringByAppendingString:appName];
157     [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
160     /* Put menu into the menubar */
161     menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
162     [menuItem setSubmenu:appleMenu];
163     [[NSApp mainMenu] addItem:menuItem];
165     /* Tell the application object that this is now the application menu */
166     [NSApp setAppleMenu:appleMenu];
168     /* Finally give up our references to the objects */
169     [appleMenu release];
170     [menuItem release];
173 /* Create a window menu */
174 static void setupWindowMenu(void)
176     NSMenu      *windowMenu;
177     NSMenuItem  *windowMenuItem;
178     NSMenuItem  *menuItem;
180     windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
182     /* "Minimize" item */
183     menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
184     [windowMenu addItem:menuItem];
185     [menuItem release];
187     /* Put menu into the menubar */
188     windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
189     [windowMenuItem setSubmenu:windowMenu];
190     [[NSApp mainMenu] addItem:windowMenuItem];
192     /* Tell the application object that this is now the window menu */
193     [NSApp setWindowsMenu:windowMenu];
195     /* Finally give up our references to the objects */
196     [windowMenu release];
197     [windowMenuItem release];
200 /* Replacement for NSApplicationMain */
201 static void CustomApplicationMain (int argc, char **argv)
203     NSAutoreleasePool   *pool = [[NSAutoreleasePool alloc] init];
204     SDLMain             *sdlMain;
206     /* Ensure the application object is initialised */
207     [SDLApplication sharedApplication];
209 #ifdef SDL_USE_CPS
210     {
211         CPSProcessSerNum PSN;
212         /* Tell the dock about us */
213         if (!CPSGetCurrentProcess(&PSN))
214             if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103))
215                 if (!CPSSetFrontProcess(&PSN))
216                     [SDLApplication sharedApplication];
217     }
218 #endif /* SDL_USE_CPS */
220     /* Set up the menubar */
221     [NSApp setMainMenu:[[NSMenu alloc] init]];
222     setApplicationMenu();
223     setupWindowMenu();
225     /* Create SDLMain and make it the app delegate */
226     sdlMain = [[SDLMain alloc] init];
227     [NSApp setDelegate:sdlMain];
229     /* Start the main event loop */
230     [NSApp run];
232     [sdlMain release];
233     [pool release];
236 #endif
240  * Catch document open requests...this lets us notice files when the app
241  *  was launched by double-clicking a document, or when a document was
242  *  dragged/dropped on the app's icon. You need to have a
243  *  CFBundleDocumentsType section in your Info.plist to get this message,
244  *  apparently.
246  * Files are added to gArgv, so to the app, they'll look like command line
247  *  arguments. Previously, apps launched from the finder had nothing but
248  *  an argv[0].
250  * This message may be received multiple times to open several docs on launch.
252  * This message is ignored once the app's mainline has been called.
253  */
254 - (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
256     const char *temparg;
257     size_t arglen;
258     char *arg;
259     char **newargv;
261     if (!gFinderLaunch)  /* MacOS is passing command line args. */
262         return FALSE;
264     if (gCalledAppMainline)  /* app has started, ignore this document. */
265         return FALSE;
267     temparg = [filename UTF8String];
268     arglen = SDL_strlen(temparg) + 1;
269     arg = (char *) SDL_malloc(arglen);
270     if (arg == NULL)
271         return FALSE;
273     newargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 2));
274     if (newargv == NULL)
275     {
276         SDL_free(arg);
277         return FALSE;
278     }
279     gArgv = newargv;
281     SDL_strlcpy(arg, temparg, arglen);
282     gArgv[gArgc++] = arg;
283     gArgv[gArgc] = NULL;
284     return TRUE;
288 /* Called when the internal event loop has just started running */
289 - (void) applicationDidFinishLaunching: (NSNotification *) note
291     int status;
293     /* Set the working directory to the .app's parent directory */
294     [self setupWorkingDirectory:gFinderLaunch];
296 #if SDL_USE_NIB_FILE
297     /* Set the main menu to contain the real app name instead of "SDL App" */
298     [self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()];
299 #endif
301     /* Hand off to main application code */
302     gCalledAppMainline = TRUE;
303     status = SDL_main (gArgc, gArgv);
305     /* We're done, thank you for playing */
306     exit(status);
308 @end
311 @implementation NSString (ReplaceSubString)
313 - (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString
315     unsigned int bufferSize;
316     unsigned int selfLen = [self length];
317     unsigned int aStringLen = [aString length];
318     unichar *buffer;
319     NSRange localRange;
320     NSString *result;
322     bufferSize = selfLen + aStringLen - aRange.length;
323     buffer = NSAllocateMemoryPages(bufferSize*sizeof(unichar));
325     /* Get first part into buffer */
326     localRange.location = 0;
327     localRange.length = aRange.location;
328     [self getCharacters:buffer range:localRange];
330     /* Get middle part into buffer */
331     localRange.location = 0;
332     localRange.length = aStringLen;
333     [aString getCharacters:(buffer+aRange.location) range:localRange];
335     /* Get last part into buffer */
336     localRange.location = aRange.location + aRange.length;
337     localRange.length = selfLen - localRange.location;
338     [self getCharacters:(buffer+aRange.location+aStringLen) range:localRange];
340     /* Build output string */
341     result = [NSString stringWithCharacters:buffer length:bufferSize];
343     NSDeallocateMemoryPages(buffer, bufferSize);
345     return result;
348 @end
352 #ifdef main
353 #  undef main
354 #endif
357 /* Main entry point to executable - should *not* be SDL_main! */
358 int main (int argc, char **argv)
360     /* Copy the arguments into a global variable */
361     /* This is passed if we are launched by double-clicking */
362     if (argc >= 2 && strncmp (argv[1], "-psn", 4) == 0)
363     {
364         gArgv = (char **) SDL_malloc(sizeof (char *) * 2);
365         gArgv[0] = argv[0];
366         gArgv[1] = NULL;
367         gArgc = 1;
368         gFinderLaunch = YES;
369     }
370     else
371     {
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     }
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;