Debian Codegraph @

sdl/osx/xcode/SDLMain.m

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