]> git.xonotic.org Git - xonotic/darkplaces.git/blob - SDLMain.m
Upgrade doxygen version, add better implementations, sidebar added (#20)
[xonotic/darkplaces.git] / SDLMain.m
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
8 #include <SDL.h>
9
10 #if SDL_MAJOR_VERSION == 1
11
12 #include "SDLMain.h"
13 #include <sys/param.h> /* for MAXPATHLEN */
14 #include <unistd.h>
15
16 /* For some reaon, Apple removed setAppleMenu from the headers in 10.4,
17  but the method still is there and works. To avoid warnings, we declare
18  it ourselves here. */
19 @interface NSApplication(SDL_Missing_Methods)
20 - (void)setAppleMenu:(NSMenu *)menu;
21 @end
22
23 /* Use this flag to determine whether we use SDLMain.nib or not */
24 #define         SDL_USE_NIB_FILE        0
25
26 /* Use this flag to determine whether we use CPS (docking) or not */
27 #define         SDL_USE_CPS             1
28 #ifdef SDL_USE_CPS
29 /* Portions of CPS.h */
30 typedef struct CPSProcessSerNum
31 {
32         UInt32          lo;
33         UInt32          hi;
34 } CPSProcessSerNum;
35
36 extern OSErr    CPSGetCurrentProcess( CPSProcessSerNum *psn);
37 extern OSErr    CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);
38 extern OSErr    CPSSetFrontProcess( CPSProcessSerNum *psn);
39
40 #endif /* SDL_USE_CPS */
41
42 static int    gArgc;
43 static char  **gArgv;
44 static BOOL   gFinderLaunch;
45 static BOOL   gCalledAppMainline = FALSE;
46
47 static NSString *getApplicationName(void)
48 {
49     const NSDictionary *dict;
50     NSString *appName = 0;
51
52     /* Determine the application name */
53     dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle());
54     if (dict)
55         appName = [dict objectForKey: @"CFBundleName"];
56     
57     if (![appName length])
58         appName = [[NSProcessInfo processInfo] processName];
59
60     return appName;
61 }
62
63 #if SDL_USE_NIB_FILE
64 /* A helper category for NSString */
65 @interface NSString (ReplaceSubString)
66 - (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString;
67 @end
68 #endif
69
70 @interface NSApplication (SDLApplication)
71 @end
72
73 @implementation NSApplication (SDLApplication)
74 /* Invoked from the Quit menu item */
75 - (void)terminate:(id)sender
76 {
77     /* Post a SDL_QUIT event */
78     SDL_Event event;
79     event.type = SDL_QUIT;
80     SDL_PushEvent(&event);
81 }
82 @end
83
84 /* The main class of the application, the application's delegate */
85 @implementation SDLMain
86
87 /* Set the working directory to the .app's parent directory */
88 - (void) setupWorkingDirectory:(BOOL)shouldChdir
89 {
90     if (shouldChdir)
91     {
92         char parentdir[MAXPATHLEN];
93         CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle());
94         CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url);
95         if (CFURLGetFileSystemRepresentation(url2, 1, (UInt8 *)parentdir, MAXPATHLEN)) {
96             chdir(parentdir);   /* chdir to the binary app's parent */
97         }
98         CFRelease(url);
99         CFRelease(url2);
100     }
101 }
102
103 #if SDL_USE_NIB_FILE
104
105 /* Fix menu to contain the real app name instead of "SDL App" */
106 - (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName
107 {
108     NSRange aRange;
109     NSEnumerator *enumerator;
110     NSMenuItem *menuItem;
111
112     aRange = [[aMenu title] rangeOfString:@"SDL App"];
113     if (aRange.length != 0)
114         [aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]];
115
116     enumerator = [[aMenu itemArray] objectEnumerator];
117     while ((menuItem = [enumerator nextObject]))
118     {
119         aRange = [[menuItem title] rangeOfString:@"SDL App"];
120         if (aRange.length != 0)
121             [menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]];
122         if ([menuItem hasSubmenu])
123             [self fixMenu:[menuItem submenu] withAppName:appName];
124     }
125 }
126
127 #else
128
129 static void setApplicationMenu(void)
130 {
131     /* warning: this code is very odd */
132     NSMenu *appleMenu;
133     NSMenuItem *menuItem;
134     NSString *title;
135     NSString *appName;
136     
137     appName = getApplicationName();
138     appleMenu = [[NSMenu alloc] initWithTitle:@""];
139     
140     /* Add menu items */
141     title = [@"About " stringByAppendingString:appName];
142     [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
143
144     [appleMenu addItem:[NSMenuItem separatorItem]];
145
146     title = [@"Hide " stringByAppendingString:appName];
147     [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
148
149     menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
150     [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
151
152     [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
153
154     [appleMenu addItem:[NSMenuItem separatorItem]];
155
156     title = [@"Quit " stringByAppendingString:appName];
157     [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
158
159     
160     /* Put menu into the menubar */
161     menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
162     [menuItem setSubmenu:appleMenu];
163     [[NSApp mainMenu] addItem:menuItem];
164
165     /* Tell the application object that this is now the application menu */
166     [NSApp setAppleMenu:appleMenu];
167
168     /* Finally give up our references to the objects */
169     [appleMenu release];
170     [menuItem release];
171 }
172
173 /* Create a window menu */
174 static void setupWindowMenu(void)
175 {
176     NSMenu      *windowMenu;
177     NSMenuItem  *windowMenuItem;
178     NSMenuItem  *menuItem;
179
180     windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
181     
182     /* "Minimize" item */
183     menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
184     [windowMenu addItem:menuItem];
185     [menuItem release];
186     
187     /* Put menu into the menubar */
188     windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
189     [windowMenuItem setSubmenu:windowMenu];
190     [[NSApp mainMenu] addItem:windowMenuItem];
191     
192     /* Tell the application object that this is now the window menu */
193     [NSApp setWindowsMenu:windowMenu];
194
195     /* Finally give up our references to the objects */
196     [windowMenu release];
197     [windowMenuItem release];
198 }
199
200 /* Replacement for NSApplicationMain */
201 static void CustomApplicationMain (int argc, char **argv)
202 {
203     NSAutoreleasePool   *pool = [[NSAutoreleasePool alloc] init];
204     SDLMain                             *sdlMain;
205
206     /* Ensure the application object is initialised */
207     [NSApplication sharedApplication];
208     
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                     [NSApplication sharedApplication];
217     }
218 #endif /* SDL_USE_CPS */
219
220     /* Set up the menubar */
221     [NSApp setMainMenu:[[NSMenu alloc] init]];
222     setApplicationMenu();
223     setupWindowMenu();
224
225     /* Create SDLMain and make it the app delegate */
226     sdlMain = [[SDLMain alloc] init];
227     [NSApp setDelegate:sdlMain];
228     
229     /* Start the main event loop */
230     [NSApp run];
231     
232     [sdlMain release];
233     [pool release];
234 }
235
236 #endif
237
238
239 /*
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.
245  *
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].
249  *
250  * This message may be received multiple times to open several docs on launch.
251  *
252  * This message is ignored once the app's mainline has been called.
253  */
254 - (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
255 {
256     const char *temparg;
257     size_t arglen;
258     char *arg;
259     char **newargv;
260
261     if (!gFinderLaunch)  /* MacOS is passing command line args. */
262         return FALSE;
263
264     if (gCalledAppMainline)  /* app has started, ignore this document. */
265         return FALSE;
266
267     temparg = [filename UTF8String];
268     arglen = SDL_strlen(temparg) + 1;
269     arg = (char *) SDL_malloc(arglen);
270     if (arg == NULL)
271         return FALSE;
272
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;
280
281     SDL_strlcpy(arg, temparg, arglen);
282     gArgv[gArgc++] = arg;
283     gArgv[gArgc] = NULL;
284     return TRUE;
285 }
286
287
288 /* Called when the internal event loop has just started running */
289 - (void) applicationDidFinishLaunching: (NSNotification *) note
290 {
291     int status;
292
293     /* Set the working directory to the .app's parent directory */
294     [self setupWorkingDirectory:gFinderLaunch];
295
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
300
301     /* Hand off to main application code */
302     gCalledAppMainline = TRUE;
303     status = SDL_main (gArgc, gArgv);
304
305     /* We're done, thank you for playing */
306     exit(status);
307 }
308 @end
309
310
311 @implementation NSString (ReplaceSubString)
312
313 - (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString
314 {
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;
321
322     bufferSize = selfLen + aStringLen - aRange.length;
323     buffer = (unichar *)NSAllocateMemoryPages(bufferSize*sizeof(unichar));
324     
325     /* Get first part into buffer */
326     localRange.location = 0;
327     localRange.length = aRange.location;
328     [self getCharacters:buffer range:localRange];
329     
330     /* Get middle part into buffer */
331     localRange.location = 0;
332     localRange.length = aStringLen;
333     [aString getCharacters:(buffer+aRange.location) range:localRange];
334      
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];
339     
340     /* Build output string */
341     result = [NSString stringWithCharacters:buffer length:bufferSize];
342     
343     NSDeallocateMemoryPages(buffer, bufferSize);
344     
345     return result;
346 }
347
348 @end
349
350
351
352 #ifdef main
353 #  undef main
354 #endif
355
356
357 /* Main entry point to executable - should *not* be SDL_main! */
358 int main (int argc, char **argv)
359 {
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         gArgv = (char **) SDL_malloc(sizeof (char *) * 2);
364         gArgv[0] = argv[0];
365         gArgv[1] = NULL;
366         gArgc = 1;
367         gFinderLaunch = YES;
368     } else {
369         int i;
370         gArgc = argc;
371         gArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1));
372         for (i = 0; i <= argc; i++)
373             gArgv[i] = argv[i];
374         gFinderLaunch = NO;
375     }
376
377 #if SDL_USE_NIB_FILE
378     NSApplicationMain (argc, argv);
379 #else
380     CustomApplicationMain (argc, argv);
381 #endif
382     return 0;
383 }
384
385 #endif