SDLMain.m 13 KB

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