31#import "OOJSFrameCallbacks.h"
46#if OOJS_QUICKJS && !defined(NDEBUG)
47#import "OOJavaScriptEngine.h"
50#if OOLITE_MAC_COCOA_UI
51#import "JAPersistentFileReference.h"
52#import "OOMacJoystickManager.h"
54#import <Sparkle/Sparkle.h>
57#elif (OOLITE_SDL && defined(OO_DEBUG_MONITOR_ENABLED))
63@interface GameController (OOPrivate)
65- (void)reportUnhandledStartupException:(NSException*)exception;
85 [
NSException raise:NSInternalInconsistencyException format:@"%s: expected only one GameController to exist at a time.", __PRETTY_FUNCTION__];
88 if ((
self = [super
init])) {
89 _finishedLaunching = NO;
96 ranrot_srand((uint32_t)[[NSDate date] timeIntervalSince1970]);
106#if OOLITE_MAC_COCOA_UI
107 [[[
NSWorkspace sharedWorkspace] notificationCenter] removeObserver:UNIVERSE];
114 [playerFileToLoad release];
115 [playerFileDirectory release];
116 [expansionPathsToInclude release];
126- (void)setGamePaused:(BOOL)value
133 [PLAYER doScriptEvent:OOJSID("gamePaused")];
138 [PLAYER doScriptEvent:OOJSID("gameResumed")];
142- (void)setEcoQoS:(BOOL)efficiencyModeRequested
145 if ([[NSUserDefaults standardUserDefaults] oo_boolForKey:
@"ecoqos" defaultValue:YES]) {
146 BOOL setEfficiencyMode = !!efficiencyModeRequested;
147 HANDLE currentProcess = GetCurrentProcess();
149 if (
EXPECT_NOT(!SetPriorityClass(currentProcess, setEfficiencyMode ? IDLE_PRIORITY_CLASS : NORMAL_PRIORITY_CLASS))) {
150 OOLog(
@"gameController.setEcoQos",
@"SetPriorityClass failed with error %lu", GetLastError());
153 PROCESS_POWER_THROTTLING_STATE powerThrottling;
154 RtlZeroMemory(&powerThrottling,
sizeof(powerThrottling));
155 powerThrottling.Version = PROCESS_POWER_THROTTLING_CURRENT_VERSION;
156 powerThrottling.ControlMask = PROCESS_POWER_THROTTLING_EXECUTION_SPEED;
157 powerThrottling.StateMask = setEfficiencyMode ? PROCESS_POWER_THROTTLING_EXECUTION_SPEED : 0;
158 if (
EXPECT_NOT(!SetProcessInformation(currentProcess, ProcessPowerThrottling, &powerThrottling,
sizeof(powerThrottling)))) {
159 OOLog(
@"gameController.setEcoQos",
@"SetProcessInformation failed with error %lu", GetLastError());
179#if OO_USE_FULLSCREEN_CONTROLLER
191 [
self setMouseInteractionMode:[PLAYER isMouseControlOn] ? MOUSE_MODE_FLIGHT_WITH_MOUSE_CONTROL : MOUSE_MODE_FLIGHT_NO_MOUSE_CONTROL];
194- (void)setMouseInteractionModeForUIWithMouseInteraction:(BOOL)interaction
196 [
self setMouseInteractionMode:interaction ? MOUSE_MODE_UI_SCREEN_WITH_INTERACTION : MOUSE_MODE_UI_SCREEN_NO_INTERACTION];
209 [UNIVERSE setGameView:gameView];
212- (void)applicationDidFinishLaunching:(NSNotification*)notification
214 NSAutoreleasePool* pool =
nil;
223#if OO_OXP_VERIFIER_ENABLED
235#if OOLITE_MAC_COCOA_UI
244 for (i = 0; i < [expansionPathsToInclude count]; i++) {
254 [[
Universe alloc] initWithGameView:gameView];
265 @catch (NSException* exception) {
270 OOLog(
@"startup.complete",
@"========== Loading complete in %.2f seconds. ==========", -[
_splashStart timeIntervalSinceNow]);
272#if OO_USE_FULLSCREEN_CONTROLLER
276 _finishedLaunching = YES;
281#if !OOLITE_MAC_COCOA_UI
288 return _finishedLaunching;
297 [UNIVERSE useGUILightSource:YES];
298 [UNIVERSE useGUILightSource:NO];
299 [PLAYER loadPlayerFromFile:playerFileToLoad asNew:NO];
305#if !OOLITE_MAC_COCOA_UI
317#if OOLITE_MAC_COCOA_UI
319- (void)performGameTick:(
id)sender
327- (void)performGameTick:(
id)sender
329 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
331 [gameView pollControls];
332 [
self doPerformGameTick];
345 delta_t = [
NSDate timeIntervalSinceReferenceDate] - last_timeInterval;
346 last_timeInterval += delta_t;
351 [UNIVERSE update:delta_t];
353 [UNIVERSE reinitAndShowDemo:YES];
360 @catch (
id exception) {
361 OOLog(
@"exception.backtrace",
@"%@", [exception callStackSymbols]);
368 @catch (
id exception) {
377 timer = [[
NSTimer timerWithTimeInterval:ti target:
self selector:@selector(performGameTick:) userInfo:nil repeats:YES] retain];
379 [[
NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
380#if OOLITE_MAC_COCOA_UI
381 [[
NSRunLoop currentRunLoop] addTimer:timer
382 forMode:NSEventTrackingRunLoopMode];
396#if OOLITE_MAC_COCOA_UI
402 [
gameView setVirtualJoystick:0.0:0.0];
405- (IBAction)showLogAction:sender
407 [[
NSWorkspace sharedWorkspace] openFile:[OOLogHandlerGetLogBasePath() stringByAppendingPathComponent:@"Previous.log"]];
410- (IBAction)showLogFolderAction:sender
412 [[
NSWorkspace sharedWorkspace] openFile:OOLogHandlerGetLogBasePath()];
418 id result = [[
NSUserDefaults standardUserDefaults] objectForKey:key];
419 if (expectedClass != Nil && ![result isKindOfClass:expectedClass])
427 [[
NSUserDefaults standardUserDefaults] setObject:value forKey:key];
435#define kSnapshotsDirRefKey @"snapshots-directory-reference"
436#define kSnapshotsDirNameKey @"snapshots-directory-name"
438- (NSURL*)snapshotsURLCreatingIfNeeded:(BOOL)create
443 NSString* name =
DESC(
@"snapshots-directory-name-mac");
445 if (snapshotDirDict !=
nil) {
446 url = JAURLFromPersistentFileReference(snapshotDirDict, kJAPersistentFileReferenceWithoutUI | kJAPersistentFileReferenceWithoutMounting, &stale);
448 NSString* existingName = [[
url path] lastPathComponent];
449 if ([existingName compare:name options:NSCaseInsensitiveSearch] != 0) {
452 if (originalOldName ==
nil || [existingName compare:originalOldName options:NSCaseInsensitiveSearch] != 0) {
458 Boolean inTrash =
false;
459 const UInt8* utfPath = (
const UInt8*)[[url path] UTF8String];
461 OSStatus err = DetermineIfPathIsEnclosedByFolder(kOnAppropriateDisk, kTrashFolderType, utfPath,
false, &inTrash);
463 if (err == noErr && inTrash ==
true)
469 NSString* path =
nil;
470 NSArray* searchPaths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
471 if ([searchPaths
count] > 0) {
472 path = [[
searchPaths objectAtIndex:0] stringByAppendingPathComponent:name];
474 url = [
NSURL fileURLWithPath:path];
480 if (![fmgr fileExistsAtPath:path]) {
481 [
fmgr oo_createDirectoryAtPath:path attributes:nil];
488 snapshotDirDict = JAPersistentFileReferenceFromURL(url);
489 if (snapshotDirDict !=
nil) {
500- (IBAction)showSnapshotsAction:sender
505- (IBAction)showAddOnsAction:sender
510 for (NSString* path in paths) {
511 if ([
self addOnsExistAtPath:path]) {
518 for (NSString* path in paths) {
519 if ([
self isDirectoryAtPath:path]) {
527 withIntermediateDirectories:YES
533- (BOOL)isDirectoryAtPath:(NSString*)path
539- (BOOL)addOnsExistAtPath:(NSString*)path
541 if (![
self isDirectoryAtPath:path])
544 NSWorkspace* workspace = NSWorkspace.sharedWorkspace;
545 for (NSString* subPath in [NSFileManager.defaultManager enumeratorAtPath:path]) {
546 subPath = [
path stringByAppendingPathComponent:subPath];
547 NSString* type = [
workspace typeOfFile:subPath error:NULL];
548 if ([workspace type:type conformsToType:
@"org.aegidian.oolite.expansion"])
555- (void)openPath:(NSString*)path
560- (BOOL)validateMenuItem:(NSMenuItem*)menuItem
562 SEL action = menuItem.action;
564 if (action ==
@selector(showLogAction:)) {
566 return ([[NSFileManager defaultManager] fileExistsAtPath:[
OOLogHandlerGetLogBasePath() stringByAppendingPathComponent:
@"Previous.log"]]);
569 if (action ==
@selector(showAddOnsAction:)) {
574 if (action ==
@selector(showSnapshotsAction:)) {
575 BOOL pathIsDirectory;
576 if (![[NSFileManager defaultManager] fileExistsAtPath:[
self snapshotsURLCreatingIfNeeded:NO].path isDirectory:&pathIsDirectory]) {
579 return pathIsDirectory;
582 if (action ==
@selector(toggleFullScreenAction:)) {
585 menuItem.title = NSLocalizedString(
@"Exit Full Screen", NULL);
587 menuItem.title = NSLocalizedString(
@"Enter Full Screen", NULL);
595- (NSMenu*)applicationDockMenu:(NSApplication*)sender
602- (NSURL*)snapshotsURLCreatingIfNeeded:(BOOL)create
604 NSURL* url = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingPathComponent:DESC(@"snapshots-directory-name")]];
607 NSString* path = [url path];
608 NSFileManager* fmgr = [NSFileManager defaultManager];
609 if (![fmgr fileExistsAtPath:path]) {
610 [fmgr oo_createDirectoryAtPath:path attributes:nil];
617#error Unknown environment!
620- (void)logProgress:(NSString*)message
625#if OOLITE_MAC_COCOA_UI
626 [splashProgressTextField setStringValue:message];
627 [splashProgressTextField display];
629 if ([message length] > 0) {
630 OOLog(
@"startup.progress",
@"===== [%.2f s] %@", -[
_splashStart timeIntervalSinceNow], message);
635#if OOLITE_MAC_COCOA_UI
636- (BOOL)debugMessageTrackingIsOn
638 return splashProgressTextField !=
nil;
641- (NSString*)debugMessageCurrentString
643 return [splashProgressTextField stringValue];
646- (BOOL)debugMessageTrackingIsOn
651- (NSString*)debugMessageCurrentString
657- (void)debugLogProgress:(NSString*)format, ...
660 va_start(args, format);
661 [
self debugLogProgress:format arguments:args];
665- (void)debugLogProgress:(NSString*)format arguments:(va_list)arguments
667 NSString* message = [[[NSString alloc] initWithFormat:format arguments:arguments] autorelease];
668 [
self logProgress:message];
671static NSMutableArray* sMessageStack;
673- (void)debugPushProgressMessage:(NSString*)format, ...
675 if ([
self debugMessageTrackingIsOn]) {
676 if (sMessageStack ==
nil)
677 sMessageStack = [[NSMutableArray alloc] init];
678 [sMessageStack addObject:[
self debugMessageCurrentString]];
681 va_start(args, format);
682 [
self debugLogProgress:format arguments:args];
689- (void)debugPopProgressMessage
693 if ([sMessageStack
count] > 0) {
694 NSString* message = [sMessageStack lastObject];
695 if ([message length] > 0)
696 [
self logProgress:message];
697 [sMessageStack removeLastObject];
707#if OOLITE_MAC_COCOA_UI
712 [gameWindow setAcceptsMouseMovedEvents:YES];
713 [gameWindow setContentView:gameView];
714 [gameWindow makeFirstResponder:gameView];
720#if OOLITE_MAC_COCOA_UI
725 NSString* path =
nil;
728 path = [[
NSBundle mainBundle] pathForResource:@"OoliteReadMe" ofType:@"pdf"];
730 PDFDocument* document = [[
PDFDocument alloc] initWithURL:[
NSURL fileURLWithPath:path]];
731 [helpView setDocument:document];
734 [helpView setBackgroundColor:[
NSColor whiteColor]];
738- (BOOL)application:(NSApplication*)theApplication openFile:(NSString*)filename
740 if ([[
filename pathExtension] isEqual:
@"oolite-save"]) {
745 if ([[
filename pathExtension] isEqualToString:
@"oxp"]) {
747 [[
NSFileManager defaultManager] fileExistsAtPath:filename isDirectory:&dir_test];
752 [expansionPathsToInclude addObject:filename];
759- (void)exitAppWithContext:(NSString*)context
763 [
NSApp terminate:
self];
766- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)sender
770 return NSTerminateNow;
774#include <SDL3/SDL_init.h>
776- (void)exitAppWithContext:(NSString*)context
778 OOLog(
@"exit.context",
@"Exiting: %@.", context);
779#if (OOLITE_SDL && defined(OO_DEBUG_MONITOR_ENABLED))
785 if (![gameView atDesktopResolution]) {
786 OOLog(
@"gameController.exitApp",
@"%@",
@"Restoring desktop resolution.");
787 ChangeDisplaySettingsEx(NULL, NULL, NULL, 0, NULL);
790 [[NSUserDefaults standardUserDefaults] synchronize];
791 OOLog(
@"gameController.exitApp",
@"%@",
@".GNUstepDefaults synchronized.");
792#if OOJS_QUICKJS && !defined(NDEBUG)
803#error Unknown environment!
811- (void)windowDidResize:(NSNotification*)aNotification
821- (void)setPlayerFileToLoad:(NSString*)filename
824 [playerFileToLoad autorelease];
826 if ([[[
filename pathExtension] lowercaseString] isEqual:
@"oolite-save"])
840 [playerFileDirectory retain];
846- (void)setPlayerFileDirectory:(NSString*)filename
849 [playerFileDirectory autorelease];
853 if ([[[
filename pathExtension] lowercaseString] isEqual:
@"oolite-save"]) {
854 filename = [filename stringByDeletingLastPathComponent];
858 [[
NSUserDefaults standardUserDefaults] setObject:filename forKey:@"save-directory"];
861- (void)reportUnhandledStartupException:(NSException*)exception
863 OOLog(
@"startup.exception",
@"***** Unhandled exception during startup: %@ (%@).", [exception name], [exception reason]);
865#if OOLITE_MAC_COCOA_UI
868 NSRunCriticalAlertPanel(
@"Oolite failed to start up, because an unhandled exception occurred.",
@"An exception of type %@ occurred. If this problem persists, please file a bug report.",
@"OK", NULL, NULL, [exception name]);
884#if OOLITE_MAC_COCOA_UI
888#define FEED_URL_BASE "http://www.oolite.org/updates/"
889#define TEST_RELEASE_FEED_NAME "oolite-mac-test-release-appcast.xml"
890#define DEPLOYMENT_FEED_NAME "oolite-mac-appcast.xml"
892#define TEST_RELEASE_FEED_URL (@FEED_URL_BASE TEST_RELEASE_FEED_NAME)
893#define DEPLOYMENT_FEED_URL (@FEED_URL_BASE DEPLOYMENT_FEED_NAME)
897#define DEFAULT_TEST_RELEASE 0
899#define DEFAULT_TEST_RELEASE 1
902 BOOL useTestReleases = [[NSUserDefaults standardUserDefaults] oo_boolForKey:@"use-test-release-updates"
903 defaultValue:DEFAULT_TEST_RELEASE];
905 SUUpdater* updater = [SUUpdater sharedUpdater];
906 [updater setFeedURL:[NSURL URLWithString:useTestReleases ? TEST_RELEASE_FEED_URL : DEPLOYMENT_FEED_URL]];
#define MINIMUM_GAME_TICK
static GameController * sSharedController
#define kSnapshotsDirNameKey
#define kSnapshotsDirRefKey
static void SetUpSparkle(void)
void OOJSFrameCallbacksInvoke(OOTimeDelta delta)
NSString * OOLogHandlerGetLogBasePath(void)
BOOL OOLogWillDisplayMessagesInClass(NSString *inMessageClass)
#define OOLogOutdentIf(class)
#define OOLog(class, format,...)
#define OOLogIndentIf(class)
void OOLoggingTerminate(void)
void OOLogSetDisplayMessagesInClass(NSString *inClass, BOOL inFlag)
NSString * OOStringFromMouseInteractionMode(OOMouseInteractionMode mode)
void setMouseInteractionMode:(OOMouseInteractionMode mode)
void setMouseInteractionModeForUIWithMouseInteraction:(BOOL interaction)
IBOutlet NSTextField * splashProgressTextField
static id GetPreference(NSString *key, Class expectedClass)
OOMouseInteractionMode mouseInteractionMode()
NSString * playerFileToLoad
BOOL suppressClangStuff()
GameController * sharedController()
NSMutableArray * expansionPathsToInclude
OOMouseInteractionMode _resumeMode
NSTimeInterval last_timeInterval
void recenterVirtualJoystick()
NSString * playerFileDirectory
void stopAnimationTimer()
void reportUnhandledStartupException:(NSException *exception)
void openPath:(NSString *path)
void logProgress:(NSString *message)
NSTimeInterval _animationTimerInterval
void exitAppWithContext:(NSString *context)
static void SetPreference(NSString *key, id value)
OOMouseInteractionMode _mouseMode
void setPlayerFileDirectory:(NSString *filename)
void setEcoQoS:(BOOL efficiencyModeRequested)
void setMouseInteractionModeForFlight()
void startAnimationTimer()
void setFullScreenMode:(BOOL value)
NSURL * snapshotsURLCreatingIfNeeded:(BOOL create)
IBOutlet MyOpenGLView * gameView
void loadPlayerIfRequired()
static void RemovePreference(NSString *key)
void setPlayerFileToLoad:(NSString *filename)
IBOutlet NSView * splashView
OOFullScreenController * _fullScreenController
IBOutlet NSMenu * dockMenu
void noteMouseInteractionModeChangedFrom:to:(OOMouseInteractionMode oldMode,[to] OOMouseInteractionMode newMode)
void setGameController:(GameController *controller)
void finishOngoingFlush()
OOCacheManager * sharedCache()
OODebugMonitor * sharedDebugMonitor()
void noteMouseInteractionModeChangedFrom:to:(OOMouseInteractionMode oldMode,[to] OOMouseInteractionMode newMode)
OOJavaScriptEngine * sharedEngine()
BOOL setStickHandlerClass:(Class aClass)
OOOXZManager * sharedManager()
OOOpenALController * sharedController()
void addExternalPath:(NSString *fileName)
NSArray * userRootPaths()
void ranrot_srand(uint32_t seed)