SDLMain.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. Feel free to customize this file to suit your needs
  5. */
  6. #include "SDL.h"
  7. #include "SDLMain.h"
  8. #include <sys/param.h> /* for MAXPATHLEN */
  9. #include <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. const NSDictionary *dict;
  38. NSString *appName = 0;
  39. /* Determine the application name */
  40. dict = (const 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. // ADDED SO IT DOESN'T BEEP BECAUSE WE ENABLE SDL_ENABLEAPPEVENTS
  65. - (void)sendEvent:(NSEvent *)anEvent
  66. {
  67. if( NSKeyDown == [anEvent type] || NSKeyUp == [anEvent type] ) {
  68. if( [anEvent modifierFlags] & NSCommandKeyMask )
  69. [super sendEvent: anEvent];
  70. } else
  71. [super sendEvent: anEvent];
  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. - (void) setupWorkingDirectory:(BOOL)shouldChdir
  78. {
  79. if (shouldChdir)
  80. {
  81. char parentdir[MAXPATHLEN];
  82. CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle());
  83. CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url);
  84. if (CFURLGetFileSystemRepresentation(url2, 1, (UInt8 *)parentdir, MAXPATHLEN)) {
  85. chdir(parentdir); /* chdir to the binary app's parent */
  86. }
  87. CFRelease(url);
  88. CFRelease(url2);
  89. }
  90. }
  91. #if SDL_USE_NIB_FILE
  92. /* Fix menu to contain the real app name instead of "SDL App" */
  93. - (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName
  94. {
  95. NSRange aRange;
  96. NSEnumerator *enumerator;
  97. NSMenuItem *menuItem;
  98. aRange = [[aMenu title] rangeOfString:@"SDL App"];
  99. if (aRange.length != 0)
  100. [aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]];
  101. enumerator = [[aMenu itemArray] objectEnumerator];
  102. while ((menuItem = [enumerator nextObject]))
  103. {
  104. aRange = [[menuItem title] rangeOfString:@"SDL App"];
  105. if (aRange.length != 0)
  106. [menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]];
  107. if ([menuItem hasSubmenu])
  108. [self fixMenu:[menuItem submenu] withAppName:appName];
  109. }
  110. [ aMenu sizeToFit ];
  111. }
  112. #else
  113. static void setApplicationMenu(void)
  114. {
  115. /* warning: this code is very odd */
  116. NSMenu *appleMenu;
  117. NSMenuItem *menuItem;
  118. NSString *title;
  119. NSString *appName;
  120. appName = getApplicationName();
  121. appleMenu = [[NSMenu alloc] initWithTitle:@""];
  122. /* Add menu items */
  123. title = [@"About " stringByAppendingString:appName];
  124. [appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
  125. [appleMenu addItem:[NSMenuItem separatorItem]];
  126. title = [@"Hide " stringByAppendingString:appName];
  127. [appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
  128. menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
  129. [menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
  130. [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
  131. [appleMenu addItem:[NSMenuItem separatorItem]];
  132. title = [@"Quit " stringByAppendingString:appName];
  133. [appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
  134. /* Put menu into the menubar */
  135. menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
  136. [menuItem setSubmenu:appleMenu];
  137. [[NSApp mainMenu] addItem:menuItem];
  138. /* Tell the application object that this is now the application menu */
  139. [NSApp setAppleMenu:appleMenu];
  140. /* Finally give up our references to the objects */
  141. [appleMenu release];
  142. [menuItem release];
  143. }
  144. /* Create a window menu */
  145. static void setupWindowMenu(void)
  146. {
  147. NSMenu *windowMenu;
  148. NSMenuItem *windowMenuItem;
  149. NSMenuItem *menuItem;
  150. windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
  151. /* "Minimize" item */
  152. menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
  153. [windowMenu addItem:menuItem];
  154. [menuItem release];
  155. /* Put menu into the menubar */
  156. windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
  157. [windowMenuItem setSubmenu:windowMenu];
  158. [[NSApp mainMenu] addItem:windowMenuItem];
  159. /* Tell the application object that this is now the window menu */
  160. [NSApp setWindowsMenu:windowMenu];
  161. /* Finally give up our references to the objects */
  162. [windowMenu release];
  163. [windowMenuItem release];
  164. }
  165. /* Replacement for NSApplicationMain */
  166. static void CustomApplicationMain (int argc, char **argv)
  167. {
  168. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  169. SDLMain *sdlMain;
  170. /* Ensure the application object is initialised */
  171. [SDLApplication sharedApplication];
  172. #ifdef SDL_USE_CPS
  173. {
  174. CPSProcessSerNum PSN;
  175. /* Tell the dock about us */
  176. if (!CPSGetCurrentProcess(&PSN))
  177. if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103))
  178. if (!CPSSetFrontProcess(&PSN))
  179. [SDLApplication sharedApplication];
  180. }
  181. #endif /* SDL_USE_CPS */
  182. /* Set up the menubar */
  183. [NSApp setMainMenu:[[NSMenu alloc] init]];
  184. setApplicationMenu();
  185. setupWindowMenu();
  186. /* Create SDLMain and make it the app delegate */
  187. sdlMain = [[SDLMain alloc] init];
  188. [NSApp setDelegate:sdlMain];
  189. /* Start the main event loop */
  190. [NSApp run];
  191. [sdlMain release];
  192. [pool release];
  193. }
  194. #endif
  195. /*
  196. * Catch document open requests...this lets us notice files when the app
  197. * was launched by double-clicking a document, or when a document was
  198. * dragged/dropped on the app's icon. You need to have a
  199. * CFBundleDocumentsType section in your Info.plist to get this message,
  200. * apparently.
  201. *
  202. * Files are added to gArgv, so to the app, they'll look like command line
  203. * arguments. Previously, apps launched from the finder had nothing but
  204. * an argv[0].
  205. *
  206. * This message may be received multiple times to open several docs on launch.
  207. *
  208. * This message is ignored once the app's mainline has been called.
  209. */
  210. - (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
  211. {
  212. const char *temparg;
  213. size_t arglen;
  214. char *arg;
  215. char **newargv;
  216. if (!gFinderLaunch) /* MacOS is passing command line args. */
  217. return FALSE;
  218. if (gCalledAppMainline) /* app has started, ignore this document. */
  219. return FALSE;
  220. temparg = [filename UTF8String];
  221. arglen = SDL_strlen(temparg) + 1;
  222. arg = (char *) SDL_malloc(arglen);
  223. if (arg == NULL)
  224. return FALSE;
  225. newargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 2));
  226. if (newargv == NULL)
  227. {
  228. SDL_free(arg);
  229. return FALSE;
  230. }
  231. gArgv = newargv;
  232. SDL_strlcpy(arg, temparg, arglen);
  233. gArgv[gArgc++] = arg;
  234. gArgv[gArgc] = NULL;
  235. return TRUE;
  236. }
  237. /* Called when the internal event loop has just started running */
  238. - (void) applicationDidFinishLaunching: (NSNotification *) note
  239. {
  240. int status;
  241. /* Set the working directory to the .app's parent directory */
  242. [self setupWorkingDirectory:gFinderLaunch];
  243. #if SDL_USE_NIB_FILE
  244. /* Set the main menu to contain the real app name instead of "SDL App" */
  245. [self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()];
  246. #endif
  247. /* Hand off to main application code */
  248. gCalledAppMainline = TRUE;
  249. status = SDL_main (gArgc, gArgv);
  250. /* We're done, thank you for playing */
  251. exit(status);
  252. }
  253. @end
  254. @implementation NSString (ReplaceSubString)
  255. - (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString
  256. {
  257. unsigned int bufferSize;
  258. unsigned int selfLen = [self length];
  259. unsigned int aStringLen = [aString length];
  260. unichar *buffer;
  261. NSRange localRange;
  262. NSString *result;
  263. bufferSize = selfLen + aStringLen - aRange.length;
  264. buffer = (unichar *)NSAllocateMemoryPages(bufferSize*sizeof(unichar));
  265. /* Get first part into buffer */
  266. localRange.location = 0;
  267. localRange.length = aRange.location;
  268. [self getCharacters:buffer range:localRange];
  269. /* Get middle part into buffer */
  270. localRange.location = 0;
  271. localRange.length = aStringLen;
  272. [aString getCharacters:(buffer+aRange.location) range:localRange];
  273. /* Get last part into buffer */
  274. localRange.location = aRange.location + aRange.length;
  275. localRange.length = selfLen - localRange.location;
  276. [self getCharacters:(buffer+aRange.location+aStringLen) range:localRange];
  277. /* Build output string */
  278. result = [NSString stringWithCharacters:buffer length:bufferSize];
  279. NSDeallocateMemoryPages(buffer, bufferSize);
  280. return result;
  281. }
  282. @end
  283. #ifdef main
  284. # undef main
  285. #endif
  286. /* Main entry point to executable - should *not* be SDL_main! */
  287. int main (int argc, char **argv)
  288. {
  289. /* Copy the arguments into a global variable */
  290. /* This is passed if we are launched by double-clicking */
  291. if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) {
  292. gArgv = (char **) SDL_malloc(sizeof (char *) * 2);
  293. gArgv[0] = argv[0];
  294. gArgv[1] = NULL;
  295. gArgc = 1;
  296. gFinderLaunch = YES;
  297. } else {
  298. int i;
  299. gArgc = argc;
  300. gArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1));
  301. for (i = 0; i <= argc; i++)
  302. gArgv[i] = argv[i];
  303. gFinderLaunch = NO;
  304. }
  305. #if SDL_USE_NIB_FILE
  306. [SDLApplication poseAsClass:[NSApplication class]];
  307. NSApplicationMain (argc, argv);
  308. #else
  309. CustomApplicationMain (argc, argv);
  310. #endif
  311. return 0;
  312. }