File: main.m

package info (click to toggle)
pcsxr 1.9.94-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 10,500 kB
  • ctags: 16,110
  • sloc: ansic: 117,276; objc: 8,159; cpp: 1,140; makefile: 316; asm: 145; pascal: 30; sh: 20
file content (286 lines) | stat: -rw-r--r-- 7,091 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
//
//  main.m
//
//  Created by Gil Pedersen on Fri Jun 06 2003.
//  Copyright (c) 2003 SoftWorkz. All rights reserved.
//

#import <Cocoa/Cocoa.h>
#import "EmuThread.h"
#import "PcsxrController.h"
#import "ConfigurationController.h"
#include <dlfcn.h>
//#import <sys/param.h>
#import <unistd.h>
#include "psxcommon.h"
#include "sio.h"
#include <IOKit/pwr_mgt/IOPMLib.h>
#import "hotkeys.h"

static inline void RunOnMainThreadSync(dispatch_block_t block)
{
	if ([NSThread isMainThread]) {
		block();
	} else {
		dispatch_sync(dispatch_get_main_queue(), block);
	}
}

static BOOL sysInited = NO;
//#define EMU_LOG
static IOPMAssertionID powerAssertion = kIOPMNullAssertionID;

void PADhandleKey(int key);

int main(int argc, const char *argv[])
{
    if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) {
        char parentdir[MAXPATHLEN];
        char *c;

        strlcpy ( parentdir, argv[0], sizeof(parentdir) );
        c = (char*) parentdir;

        while (*c != '\0')     /* go to end */
               c++;

        while (*c != '/')      /* back up to parent */
               c--;

        *c++ = '\0';           /* cut off last part (binary name) */

        assert ( chdir (parentdir) == 0 );   /* chdir to the binary app's parent */
        assert ( chdir ("../../../") == 0 ); /* chdir to the .app's parent */
    } else {
		for (int i = 1; i < argc; i++) {
			//All the other option will be handled in the app delegate's awakeFromNib
			if (!strcasecmp("--help", argv[i])) {
				fprintf(stdout, "%s\n", argv[0]);
				ShowHelpAndExit(stdout, EXIT_SUCCESS);
			}
		}
	}

    strcpy(Config.BiosDir,    "Bios/");
    strcpy(Config.PatchesDir, "Patches/");

    // Setup the X11 window
    if (getenv("DISPLAY") == NULL)
        setenv("DISPLAY", ":0.0", 0); // Default to first local display

    return NSApplicationMain(argc, argv);
}

int SysInit()
{
	if (!sysInited) {
#ifdef EMU_LOG
#ifndef LOG_STDOUT
		NSFileManager *manager = [NSFileManager defaultManager];
		NSURL *supportURL = [manager URLForDirectory:NSLibraryDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:NULL];
		NSURL *logFolderURL = [supportURL URLByAppendingPathComponent:@"Logs/PCSXR"];
		if (![logFolderURL checkResourceIsReachableAndReturnError:NULL])
			[manager createDirectoryAtPath:[logFolderURL path] withIntermediateDirectories:YES attributes:nil error:NULL];
		//We use the log extension so that OS X's console app can open it by default.
		NSURL *logFileURL = [logFolderURL URLByAppendingPathComponent:@"emuLog.log"];
		
		emuLog = fopen([[logFileURL path] fileSystemRepresentation],"wb");
#else
		emuLog = stdout;
#endif
		setvbuf(emuLog, NULL, _IONBF, 0);
#endif
		
		if (EmuInit() != 0)
			return -1;
		
		sysInited = YES;
	}
	
	if (LoadPlugins() == -1) {
		return -1;
	}
	
	LoadMcds(Config.Mcd1, Config.Mcd2);
	
	IOReturn success = IOPMAssertionCreateWithName(kIOPMAssertionTypePreventUserIdleDisplaySleep, kIOPMAssertionLevelOn, CFSTR("PSX Emu Running"), &powerAssertion);
	if (success != kIOReturnSuccess) {
		NSLog(@"Unable to stop sleep, error code %d", success);
	}
	
	attachHotkeys();
	
	return 0;
}

void SysReset()
{
	[EmuThread resetNow];
	//EmuReset();
}

#ifdef EMU_LOG
#ifndef LOG_STDOUT
static inline NSDateFormatter* debugDateFormatter()
{
	static NSDateFormatter* theFormatter = nil;
	if (theFormatter == nil) {
		theFormatter = [[NSDateFormatter alloc] init];
		[theFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss:SSS"];
	}
	return theFormatter;
}
#endif
#endif

static void AddStringToLogList(const char *themsg)
{
	static NSMutableString *theStr;
	NSRange newlineRange, fullLineRange;
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		theStr = [[NSMutableString alloc] init];
	});
	[theStr appendString:@(themsg)];
	while ((newlineRange = [theStr rangeOfString:@"\n"]).location != NSNotFound) {
		NSString *tmpStr = [theStr substringToIndex:newlineRange.location];
		if (tmpStr && ![tmpStr isEqualToString:@""]) {
			NSLog(@"%@", tmpStr);
		}
		fullLineRange.location = 0;
		fullLineRange.length = newlineRange.location + newlineRange.length;
		fullLineRange = [theStr rangeOfComposedCharacterSequencesForRange:fullLineRange];
		[theStr deleteCharactersInRange:fullLineRange];
	}
}

void SysPrintf(const char *fmt, ...)
{
	va_list list;
	char *msg = calloc(sizeof(char), 512);
	
	va_start(list, fmt);
	vsnprintf(msg, 512, fmt, list);
	va_end(list);
		
	RunOnMainThreadSync(^{
		if (Config.PsxOut) AddStringToLogList(msg);
#ifdef EMU_LOG
#ifndef LOG_STDOUT
		if (emuLog) fprintf(emuLog, "%s", msg);
#endif
#endif
	});
	free(msg);
}

void SysMessage(const char *fmt, ...)
{
	va_list list;
	NSString *locFmtString = NSLocalizedString(@(fmt), nil);
	
	va_start(list, fmt);
	NSString *msg = [[NSString alloc] initWithFormat:locFmtString arguments:list];
	va_end(list);
	
	NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: msg};
	
	RunOnMainThreadSync(^{
		[NSApp presentError:[NSError errorWithDomain:@"Unknown Domain" code:-1 userInfo:userInfo]];
	});
}

void *SysLoadLibrary(const char *lib)
{
	NSBundle *bundle = [[NSBundle alloc] initWithPath:[[NSFileManager defaultManager] stringWithFileSystemRepresentation:lib length:strlen(lib)]];
	if (bundle != nil) {
		return dlopen([[bundle executablePath] fileSystemRepresentation], RTLD_LAZY /*RTLD_NOW*/);
	}
	return dlopen(lib, RTLD_LAZY);
}

void *SysLoadSym(void *lib, const char *sym)
{
	return dlsym(lib, sym);
}

const char *SysLibError()
{
#ifdef DEBUG
	const char *theErr = dlerror();
	if (theErr) {
		NSLog(@"Error loading binary: %s.", theErr);
	}
	return theErr;
#else
	return dlerror();
#endif
}

void SysCloseLibrary(void *lib) {
	//dlclose(lib);
}

// Called periodically from the emu thread
void SysUpdate()
{
#if 0
	PADhandleKey(PAD1_keypressed() & 0xffffffff);
	PADhandleKey(PAD2_keypressed() & 0xffffffff);
#else
	PAD1_keypressed();
	PAD2_keypressed();
#endif
	[emuThread handleEvents];
}

// Returns to the Gui
void SysRunGui()
{
	if (powerAssertion != kIOPMNullAssertionID) {
		IOPMAssertionRelease(powerAssertion);
		powerAssertion = kIOPMNullAssertionID;
	}
}

// Close mem and plugins
void SysClose()
{
	EmuShutdown();
	ReleasePlugins();
	
	if (powerAssertion != kIOPMNullAssertionID) {
		IOPMAssertionRelease(powerAssertion);
		powerAssertion = kIOPMNullAssertionID;
	}
	
	if (emuLog != NULL) {
		fclose(emuLog);
		emuLog = NULL;
	}
	
	sysInited = NO;
	detachHotkeys();
	
	if (((PcsxrController *)[NSApp delegate]).endAtEmuClose) {
		[NSApp stop:nil];
	}
	
	//Tell the memory card manager that the memory cards changed.
	//The number three tells the mem card manager to update both cards 1 and 2.
	[[NSNotificationCenter defaultCenter] postNotificationName:memChangeNotifier object:nil userInfo:@{memCardChangeNumberKey: @3}];
}

void OnFile_Exit()
{
    SysClose();
	[NSApp stop:nil];
}

char* Pcsxr_locale_text(char* toloc)
{
	NSBundle *mainBundle = [NSBundle mainBundle];
	NSString *origString = @(toloc), *transString = nil;
	transString = [mainBundle localizedStringForKey:origString value:@"" table:nil];
	return (char*)[transString UTF8String];
}