15e2be40e2419ac44b51364dfa14e7976592bb00
[pcsx_rearmed.git] / frontend / main.c
1 /*
2  * (C) notaz, 2010
3  *
4  * This work is licensed under the terms of the GNU GPLv2 or later.
5  * See the COPYING file in the top-level directory.
6  */
7
8 #include <stdio.h>
9 #include <string.h>
10 #include <stdarg.h>
11 #include <dlfcn.h>
12 #include <sys/stat.h>
13 #include <sys/types.h>
14 #include <unistd.h>
15
16 #include "plugin.h"
17 #include "pcnt.h"
18 #include "menu.h"
19 #include "../gui/Linux.h"
20 #include "../libpcsxcore/misc.h"
21 #include "../plugins/cdrcimg/cdrcimg.h"
22 #include "common/plat.h"
23 #include "common/input.h"
24
25 int ready_to_go;
26 int UseGui;
27 static char *(*real_getenv)(const char *name);
28
29 static void make_path(char *buf, size_t size, const char *dir, const char *fname)
30 {
31         if (fname)
32                 snprintf(buf, size, ".%s%s", dir, fname);
33         else
34                 snprintf(buf, size, ".%s", dir);
35 }
36 #define MAKE_PATH(buf, dir, fname) \
37         make_path(buf, sizeof(buf), dir, fname)
38
39 static void create_profile_dir(const char *directory) {
40         char path[MAXPATHLEN];
41
42         MAKE_PATH(path, directory, NULL);
43         mkdir(path, S_IRWXU | S_IRWXG);
44 }
45
46 static void CheckSubDir() {
47         // make sure that ~/.pcsx exists
48         create_profile_dir(PCSX_DOT_DIR);
49
50         create_profile_dir(BIOS_DIR);
51         create_profile_dir(MEMCARD_DIR);
52         create_profile_dir(STATES_DIR);
53         create_profile_dir(PLUGINS_DIR);
54         create_profile_dir(PLUGINS_CFG_DIR);
55         create_profile_dir(CHEATS_DIR);
56         create_profile_dir(PATCHES_DIR);
57         create_profile_dir(PCSX_DOT_DIR "cfg");
58 }
59
60 void set_cd_image(const char *fname)
61 {
62         const char *ext;
63         int len;
64         
65         len = strlen(fname);
66         ext = fname;
67         if (len > 2)
68                 ext = fname + len - 2;
69
70         if (strcasecmp(ext, ".z") == 0) {
71                 SetIsoFile(NULL);
72                 cdrcimg_set_fname(fname);
73                 strcpy(Config.Cdr, "builtin_cdrcimg");
74         } else {
75                 SetIsoFile(fname);
76                 strcpy(Config.Cdr, "builtin_cdr");
77         }
78 }
79
80 int main(int argc, char *argv[])
81 {
82         char file[MAXPATHLEN] = "";
83         char path[MAXPATHLEN];
84         const char *cdfile = NULL;
85         int loadst = 0;
86         void *tmp;
87         int i;
88
89         tmp = dlopen("/lib/libdl.so.2", RTLD_LAZY);
90         if (tmp == NULL)
91                 tmp = dlopen("/lib32/libdl.so.2", RTLD_LAZY);
92         if (tmp != NULL)
93                 real_getenv = dlsym(tmp, "getenv");
94         if (real_getenv == NULL) {
95                 fprintf(stderr, "%s\n", dlerror());
96                 return 1;
97         }
98         dlclose(tmp);
99
100         // what is the name of the config file?
101         // it may be redefined by -cfg on the command line
102         strcpy(cfgfile_basename, "pcsx.cfg");
103
104         emuLog = stdout;
105         SetIsoFile(NULL);
106
107         // read command line options
108         for (i = 1; i < argc; i++) {
109                      if (!strcmp(argv[i], "-psxout")) Config.PsxOut = 1;
110                 else if (!strcmp(argv[i], "-load")) loadst = atol(argv[++i]);
111                 else if (!strcmp(argv[i], "-cfg")) {
112                         if (i+1 >= argc) break;
113                         strncpy(cfgfile_basename, argv[++i], MAXPATHLEN-100);   /* TODO buffer overruns */
114                         printf("Using config file %s.\n", cfgfile_basename);
115                 }
116                 else if (!strcmp(argv[i], "-cdfile")) {
117                         char isofilename[MAXPATHLEN];
118
119                         if (i+1 >= argc) break;
120                         strncpy(isofilename, argv[++i], MAXPATHLEN);
121                         if (isofilename[0] != '/') {
122                                 getcwd(path, MAXPATHLEN);
123                                 if (strlen(path) + strlen(isofilename) + 1 < MAXPATHLEN) {
124                                         strcat(path, "/");
125                                         strcat(path, isofilename);
126                                         strcpy(isofilename, path);
127                                 } else
128                                         isofilename[0] = 0;
129                         }
130
131                         cdfile = isofilename;
132                 }
133                 else if (!strcmp(argv[i], "-h") ||
134                          !strcmp(argv[i], "-help") ||
135                          !strcmp(argv[i], "--help")) {
136                          printf(PACKAGE_NAME " " PACKAGE_VERSION "\n");
137                          printf("%s\n", _(
138                                                         " pcsx [options] [file]\n"
139                                                         "\toptions:\n"
140                                                         "\t-cdfile FILE\tRuns a CD image file\n"
141                                                         "\t-nogui\t\tDon't open the GTK GUI\n"
142                                                         "\t-cfg FILE\tLoads desired configuration file (default: ~/.pcsx/pcsx.cfg)\n"
143                                                         "\t-psxout\t\tEnable PSX output\n"
144                                                         "\t-load STATENUM\tLoads savestate STATENUM (1-5)\n"
145                                                         "\t-h -help\tDisplay this message\n"
146                                                         "\tfile\t\tLoads file\n"));
147                          return 0;
148                 } else {
149                         strncpy(file, argv[i], MAXPATHLEN);
150                         if (file[0] != '/') {
151                                 getcwd(path, MAXPATHLEN);
152                                 if (strlen(path) + strlen(file) + 1 < MAXPATHLEN) {
153                                         strcat(path, "/");
154                                         strcat(path, file);
155                                         strcpy(file, path);
156                                 } else
157                                         file[0] = 0;
158                         }
159                 }
160         }
161
162         memset(&Config, 0, sizeof(PcsxConfig));
163         strcpy(Config.Net, "Disabled");
164
165         CheckSubDir();
166 //      ScanAllPlugins();
167
168         MAKE_PATH(Config.Mcd1, MEMCARD_DIR, "card1.mcd");
169         MAKE_PATH(Config.Mcd2, MEMCARD_DIR, "card2.mcd");
170         strcpy(Config.Bios, "HLE");
171         strcpy(Config.BiosDir, "./");
172
173         strcpy(Config.PluginsDir, "plugins");
174         strcpy(Config.Gpu, "builtin_gpu");
175         strcpy(Config.Spu, "builtin_spu");
176         strcpy(Config.Cdr, "builtin_cdr");
177         strcpy(Config.Pad1, "builtin_pad");
178         strcpy(Config.Pad2, "builtin_pad");
179         Config.PsxAuto = 1;
180
181         snprintf(Config.PatchesDir, sizeof(Config.PatchesDir), "." PATCHES_DIR);
182 /*
183         // switch to plugin dotdir
184         // this lets plugins work without modification!
185         gchar *plugin_default_dir = g_build_filename(getenv("HOME"), PLUGINS_DIR, NULL);
186         chdir(plugin_default_dir);
187         g_free(plugin_default_dir);
188 */
189
190         if (cdfile)
191                 set_cd_image(cdfile);
192
193         if (SysInit() == -1)
194                 return 1;
195
196         // frontend stuff
197         in_init();
198         in_probe();
199         plat_init();
200         menu_init();
201
202         if (LoadPlugins() == -1) {
203                 SysMessage("Failed loading plugins!");
204                 return 1;
205         }
206         pcnt_hook_plugins();
207
208         if (OpenPlugins() == -1) {
209                 return 1;
210         }
211
212         SysReset();
213         CheckCdrom();
214
215         if (file[0] != '\0') {
216                 if (Load(file) != -1)
217                         ready_to_go = 1;
218         } else {
219                 if (cdfile) {
220                         if (LoadCdrom() == -1) {
221                                 ClosePlugins();
222                                 printf(_("Could not load CD-ROM!\n"));
223                                 return -1;
224                         }
225                         ready_to_go = 1;
226                 }
227         }
228
229         // If a state has been specified, then load that
230         if (loadst) {
231                 StatesC = loadst - 1;
232                 char *state_filename = get_state_filename(StatesC);
233                 int ret = LoadState(state_filename);
234                 printf("%s state %s\n", ret ? "failed to load" : "loaded", state_filename);
235                 free(state_filename);
236         }
237
238         if (ready_to_go)
239                 menu_prepare_emu();
240         else
241                 menu_loop();
242
243         while (1)
244         {
245                 psxCpu->Execute();
246                 menu_loop();
247         }
248
249         return 0;
250 }
251
252 int SysInit() {
253         if (EmuInit() == -1) {
254                 printf("PSX emulator couldn't be initialized.\n");
255                 return -1;
256         }
257
258         LoadMcds(Config.Mcd1, Config.Mcd2);     /* TODO Do we need to have this here, or in the calling main() function?? */
259
260         if (Config.Debug) {
261                 StartDebugger();
262         }
263
264         return 0;
265 }
266
267 void SysRunGui() {
268         printf("SysRunGui\n");
269 }
270
271 void StartGui() {
272         printf("StartGui\n");
273 }
274
275 void SysReset() {
276         EmuReset();
277
278         // hmh core forgets this
279         CDR_stop();
280 }
281
282 void SysClose() {
283         EmuShutdown();
284         ReleasePlugins();
285
286         StopDebugger();
287
288         if (emuLog != NULL) fclose(emuLog);
289 }
290
291 void SysUpdate() {
292         PADhandleKey(PAD1_keypressed());
293         PADhandleKey(PAD2_keypressed());
294 }
295
296 void UpdateMenuSlots() {
297 }
298
299 void OnFile_Exit() {
300         printf("OnFile_Exit\n");
301         plat_finish();
302         SysClose();
303         exit(0);
304 }
305
306 void state_save(gchar *state_filename) {
307         char Text[MAXPATHLEN + 20];
308
309         GPU_updateLace();
310
311         if (SaveState(state_filename) == 0)
312                 sprintf(Text, _("Saved state %s."), state_filename);
313         else
314                 sprintf(Text, _("Error saving state %s!"), state_filename);
315
316         GPU_displayText(Text);
317 }
318
319 void state_load(gchar *state_filename) {
320         int ret;
321         char Text[MAXPATHLEN + 20];
322         FILE *fp;
323
324         // check if the state file actually exists
325         fp = fopen(state_filename, "rb");
326         if (fp == NULL) {
327                 // file does not exist
328                 return;
329         }
330
331         fclose(fp);
332
333         ret = CheckState(state_filename);
334
335         if (ret == 0) {
336                 SysReset();
337                 ret = LoadState(state_filename);
338         }
339
340         if (ret == 0) {
341                 // Check the CD-ROM is valid
342                 if (CheckCdrom() == -1) {
343                         ClosePlugins();
344                         SysRunGui();
345                         return;
346                 }
347
348                 sprintf(Text, _("Loaded state %s."), state_filename);
349         } else {
350                 sprintf(Text, _("Error loading state %s!"), state_filename);
351         }
352         GPU_displayText(Text);
353 }
354
355 char *get_state_filename(int i) {
356         char SStateFile[256];
357         char trimlabel[33];
358         int j;
359
360         strncpy(trimlabel, CdromLabel, 32);
361         trimlabel[32] = 0;
362         for (j = 31; j >= 0; j--)
363                 if (trimlabel[j] == ' ')
364                         trimlabel[j] = 0;
365                 else
366                         continue;
367
368         snprintf(SStateFile, sizeof(SStateFile), "." STATES_DIR "%.32s-%.9s.%3.3d",
369                 trimlabel, CdromId, i);
370
371         return strdup(SStateFile);
372 }
373
374 void SysPrintf(const char *fmt, ...) {
375         va_list list;
376         char msg[512];
377
378         va_start(list, fmt);
379         vsprintf(msg, fmt, list);
380         va_end(list);
381
382         fprintf(emuLog, "%s", msg);
383 }
384
385 void SysMessage(const char *fmt, ...) {
386         va_list list;
387         char msg[512];
388
389         va_start(list, fmt);
390         vsprintf(msg, fmt, list);
391         va_end(list);
392
393         if (msg[strlen(msg) - 1] == '\n')
394                 msg[strlen(msg) - 1] = 0;
395
396         fprintf(stderr, "%s\n", msg);
397 }
398
399 #if 1
400 /* this is to avoid having to hack every plugin to stop using $HOME */
401 char *getenv(const char *name)
402 {
403         static char ret[8] = ".";
404
405         if (name && strcmp(name, "HOME") == 0 &&
406                         ((int)name >> 28) == 0) // HACK: let libs find home
407                 return ret;
408
409         return real_getenv(name);
410 }
411 #endif
412
413 /* we hook statically linked plugins here */
414 static const char *builtin_plugins[] = {
415         "builtin_gpu", "builtin_spu", "builtin_cdr", "builtin_pad",
416         "builtin_cdrcimg",
417 };
418
419 static const int builtin_plugin_ids[] = {
420         PLUGIN_GPU, PLUGIN_SPU, PLUGIN_CDR, PLUGIN_PAD,
421         PLUGIN_CDRCIMG,
422 };
423
424 void *SysLoadLibrary(const char *lib) {
425         const char *tmp = strrchr(lib, '/');
426         int i;
427
428         printf("dlopen %s\n", lib);
429         if (tmp != NULL) {
430                 tmp++;
431                 for (i = 0; i < ARRAY_SIZE(builtin_plugins); i++)
432                         if (strcmp(tmp, builtin_plugins[i]) == 0)
433                                 return (void *)(long)(PLUGIN_DL_BASE + builtin_plugin_ids[i]);
434         }
435
436 #if defined(__x86_64__) || defined(__i386__)
437         // convenience hack
438         char name[MAXPATHLEN];
439         snprintf(name, sizeof(name), "%s.x86", lib);
440         lib = name;
441 #endif
442
443         return dlopen(lib, RTLD_NOW);
444 }
445
446 void *SysLoadSym(void *lib, const char *sym) {
447         unsigned int plugid = (unsigned int)(long)lib;
448
449         if (PLUGIN_DL_BASE <= plugid && plugid < PLUGIN_DL_BASE + ARRAY_SIZE(builtin_plugins))
450                 return plugin_link(plugid - PLUGIN_DL_BASE, sym);
451
452         return dlsym(lib, sym);
453 }
454
455 const char *SysLibError() {
456         return dlerror();
457 }
458
459 void SysCloseLibrary(void *lib) {
460         unsigned int plugid = (unsigned int)(long)lib;
461
462         if (PLUGIN_DL_BASE <= plugid && plugid < PLUGIN_DL_BASE + ARRAY_SIZE(builtin_plugins))
463                 return;
464
465         dlclose(lib);
466 }
467
468