9f245409c6ec1324d6c9e6a658c33c3cdac09181
[pcsx_rearmed.git] / frontend / main.c
1 /*
2  * (C) notaz, 2010-2011
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 #include <signal.h>
16
17 #include "main.h"
18 #include "plugin.h"
19 #include "plugin_lib.h"
20 #include "pcnt.h"
21 #include "menu.h"
22 #include "../libpcsxcore/misc.h"
23 #include "../plugins/cdrcimg/cdrcimg.h"
24 #include "common/plat.h"
25 #include "common/input.h"
26
27 int ready_to_go;
28 unsigned long gpuDisp;
29 char cfgfile_basename[MAXPATHLEN];
30 static char *(*real_getenv)(const char *name);
31
32 static void make_path(char *buf, size_t size, const char *dir, const char *fname)
33 {
34         if (fname)
35                 snprintf(buf, size, ".%s%s", dir, fname);
36         else
37                 snprintf(buf, size, ".%s", dir);
38 }
39 #define MAKE_PATH(buf, dir, fname) \
40         make_path(buf, sizeof(buf), dir, fname)
41
42 static void create_profile_dir(const char *directory) {
43         char path[MAXPATHLEN];
44
45         MAKE_PATH(path, directory, NULL);
46         mkdir(path, S_IRWXU | S_IRWXG);
47 }
48
49 static void CheckSubDir() {
50         // make sure that ~/.pcsx exists
51         create_profile_dir(PCSX_DOT_DIR);
52
53         create_profile_dir(BIOS_DIR);
54         create_profile_dir(MEMCARD_DIR);
55         create_profile_dir(STATES_DIR);
56         create_profile_dir(PLUGINS_DIR);
57         create_profile_dir(PLUGINS_CFG_DIR);
58         create_profile_dir(CHEATS_DIR);
59         create_profile_dir(PATCHES_DIR);
60         create_profile_dir(PCSX_DOT_DIR "cfg");
61 }
62
63 void set_cd_image(const char *fname)
64 {
65         const char *ext = NULL;
66         
67         if (fname != NULL)
68                 ext = strrchr(fname, '.');
69
70         if (ext && (
71             strcasecmp(ext, ".z") == 0 || strcasecmp(ext, ".bz") == 0 ||
72             strcasecmp(ext, ".znx") == 0 || strcasecmp(ext, ".pbp") == 0)) {
73                 SetIsoFile(NULL);
74                 cdrcimg_set_fname(fname);
75                 strcpy(Config.Cdr, "builtin_cdrcimg");
76         } else {
77                 SetIsoFile(fname);
78                 strcpy(Config.Cdr, "builtin_cdr");
79         }
80 }
81
82 static void set_default_paths(void)
83 {
84         MAKE_PATH(Config.Mcd1, MEMCARD_DIR, "card1.mcd");
85         MAKE_PATH(Config.Mcd2, MEMCARD_DIR, "card2.mcd");
86         strcpy(Config.BiosDir, "bios");
87
88         strcpy(Config.PluginsDir, "plugins");
89         strcpy(Config.Gpu, "builtin_gpu");
90         strcpy(Config.Spu, "builtin_spu");
91         strcpy(Config.Cdr, "builtin_cdr");
92         strcpy(Config.Pad1, "builtin_pad");
93         strcpy(Config.Pad2, "builtin_pad");
94         strcpy(Config.Net, "Disabled");
95         Config.PsxAuto = 1;
96
97         snprintf(Config.PatchesDir, sizeof(Config.PatchesDir), "." PATCHES_DIR);
98 }
99
100 int main(int argc, char *argv[])
101 {
102         char file[MAXPATHLEN] = "";
103         char path[MAXPATHLEN];
104         const char *cdfile = NULL;
105         int loadst = 0;
106         void *tmp;
107         int i;
108
109         tmp = dlopen("/lib/libdl.so.2", RTLD_LAZY);
110         if (tmp == NULL)
111                 tmp = dlopen("/lib32/libdl.so.2", RTLD_LAZY);
112         if (tmp != NULL)
113                 real_getenv = dlsym(tmp, "getenv");
114         if (real_getenv == NULL) {
115                 fprintf(stderr, "%s\n", dlerror());
116                 return 1;
117         }
118         dlclose(tmp);
119
120         // what is the name of the config file?
121         // it may be redefined by -cfg on the command line
122         strcpy(cfgfile_basename, "pcsx.cfg");
123
124         emuLog = stdout;
125         SetIsoFile(NULL);
126
127         // read command line options
128         for (i = 1; i < argc; i++) {
129                      if (!strcmp(argv[i], "-psxout")) Config.PsxOut = 1;
130                 else if (!strcmp(argv[i], "-load")) loadst = atol(argv[++i]);
131                 else if (!strcmp(argv[i], "-cfg")) {
132                         if (i+1 >= argc) break;
133                         strncpy(cfgfile_basename, argv[++i], MAXPATHLEN-100);   /* TODO buffer overruns */
134                         printf("Using config file %s.\n", cfgfile_basename);
135                 }
136                 else if (!strcmp(argv[i], "-cdfile")) {
137                         char isofilename[MAXPATHLEN];
138
139                         if (i+1 >= argc) break;
140                         strncpy(isofilename, argv[++i], MAXPATHLEN);
141                         if (isofilename[0] != '/') {
142                                 getcwd(path, MAXPATHLEN);
143                                 if (strlen(path) + strlen(isofilename) + 1 < MAXPATHLEN) {
144                                         strcat(path, "/");
145                                         strcat(path, isofilename);
146                                         strcpy(isofilename, path);
147                                 } else
148                                         isofilename[0] = 0;
149                         }
150
151                         cdfile = isofilename;
152                 }
153                 else if (!strcmp(argv[i], "-h") ||
154                          !strcmp(argv[i], "-help") ||
155                          !strcmp(argv[i], "--help")) {
156                          printf(PACKAGE_NAME " " PACKAGE_VERSION "\n");
157                          printf("%s\n", _(
158                                                         " pcsx [options] [file]\n"
159                                                         "\toptions:\n"
160                                                         "\t-cdfile FILE\tRuns a CD image file\n"
161                                                         "\t-nogui\t\tDon't open the GTK GUI\n"
162                                                         "\t-cfg FILE\tLoads desired configuration file (default: ~/.pcsx/pcsx.cfg)\n"
163                                                         "\t-psxout\t\tEnable PSX output\n"
164                                                         "\t-load STATENUM\tLoads savestate STATENUM (1-5)\n"
165                                                         "\t-h -help\tDisplay this message\n"
166                                                         "\tfile\t\tLoads file\n"));
167                          return 0;
168                 } else {
169                         strncpy(file, argv[i], MAXPATHLEN);
170                         if (file[0] != '/') {
171                                 getcwd(path, MAXPATHLEN);
172                                 if (strlen(path) + strlen(file) + 1 < MAXPATHLEN) {
173                                         strcat(path, "/");
174                                         strcat(path, file);
175                                         strcpy(file, path);
176                                 } else
177                                         file[0] = 0;
178                         }
179                 }
180         }
181
182         memset(&Config, 0, sizeof(PcsxConfig));
183
184         CheckSubDir();
185         set_default_paths();
186         strcpy(Config.Bios, "HLE");
187
188         if (cdfile)
189                 set_cd_image(cdfile);
190
191         if (SysInit() == -1)
192                 return 1;
193
194         // frontend stuff
195         in_init();
196         in_probe();
197         plat_init();
198         menu_init();
199
200         if (LoadPlugins() == -1) {
201                 // FIXME: this recovery doesn't work, just delete bad config and bail out
202                 // SysMessage("could not load plugins, retrying with defaults\n");
203                 set_default_paths();
204                 snprintf(path, sizeof(path), "." PCSX_DOT_DIR "%s", cfgfile_basename);
205                 remove(path);
206                 SysMessage("Failed loading plugins!");
207                 return 1;
208         }
209         pcnt_hook_plugins();
210
211         if (OpenPlugins() == -1) {
212                 return 1;
213         }
214         plugin_call_rearmed_cbs();
215
216         CheckCdrom();
217         SysReset();
218
219         if (file[0] != '\0') {
220                 if (Load(file) != -1)
221                         ready_to_go = 1;
222         } else {
223                 if (cdfile) {
224                         if (LoadCdrom() == -1) {
225                                 ClosePlugins();
226                                 printf(_("Could not load CD-ROM!\n"));
227                                 return -1;
228                         }
229                         ready_to_go = 1;
230                 }
231         }
232
233         // If a state has been specified, then load that
234         if (loadst) {
235                 char state_filename[MAXPATHLEN];
236                 int ret = get_state_filename(state_filename, sizeof(state_filename), loadst - 1);
237                 if (ret == 0)
238                         ret = LoadState(state_filename);
239                 printf("%s state %s\n", ret ? "failed to load" : "loaded", state_filename);
240         }
241
242         if (ready_to_go)
243                 menu_prepare_emu();
244         else
245                 menu_loop();
246
247         pl_start_watchdog();
248
249         while (1)
250         {
251                 psxCpu->Execute();
252                 menu_loop();
253         }
254
255         return 0;
256 }
257
258 int SysInit() {
259         if (EmuInit() == -1) {
260                 printf("PSX emulator couldn't be initialized.\n");
261                 return -1;
262         }
263
264         LoadMcds(Config.Mcd1, Config.Mcd2);     /* TODO Do we need to have this here, or in the calling main() function?? */
265
266         if (Config.Debug) {
267                 StartDebugger();
268         }
269
270         return 0;
271 }
272
273 void SysRunGui() {
274         printf("SysRunGui\n");
275 }
276
277 void StartGui() {
278         printf("StartGui\n");
279 }
280
281 static void dummy_lace()
282 {
283 }
284
285 void SysReset() {
286         // rearmed hack: EmuReset() runs some code when real BIOS is used,
287         // but we usually do reset from menu while GPU is not open yet,
288         // so we need to prevent updateLace() call..
289         void *real_lace = GPU_updateLace;
290         GPU_updateLace = dummy_lace;
291
292         EmuReset();
293
294         // hmh core forgets this
295         CDR_stop();
296
297         GPU_updateLace = real_lace;
298 }
299
300 void SysClose() {
301         EmuShutdown();
302         ReleasePlugins();
303
304         StopDebugger();
305
306         if (emuLog != NULL) fclose(emuLog);
307 }
308
309 void SysUpdate() {
310 }
311
312 void OnFile_Exit() {
313         printf("OnFile_Exit\n");
314         menu_finish();
315         plat_finish();
316         SysClose();
317         exit(0);
318 }
319
320 int get_state_filename(char *buf, int size, int i) {
321         char trimlabel[33];
322         int j;
323
324         strncpy(trimlabel, CdromLabel, 32);
325         trimlabel[32] = 0;
326         for (j = 31; j >= 0; j--)
327                 if (trimlabel[j] == ' ')
328                         trimlabel[j] = 0;
329                 else
330                         continue;
331
332         snprintf(buf, size, "." STATES_DIR "%.32s-%.9s.%3.3d",
333                 trimlabel, CdromId, i);
334
335         return 0;
336 }
337
338 void SysPrintf(const char *fmt, ...) {
339         va_list list;
340         char msg[512];
341
342         va_start(list, fmt);
343         vsprintf(msg, fmt, list);
344         va_end(list);
345
346         fprintf(emuLog, "%s", msg);
347 }
348
349 void SysMessage(const char *fmt, ...) {
350         va_list list;
351         char msg[512];
352
353         va_start(list, fmt);
354         vsprintf(msg, fmt, list);
355         va_end(list);
356
357         if (msg[strlen(msg) - 1] == '\n')
358                 msg[strlen(msg) - 1] = 0;
359
360         fprintf(stderr, "%s\n", msg);
361 }
362
363 static void SignalExit(int sig) {
364         ClosePlugins();
365         OnFile_Exit();
366 }
367
368 #define PARSEPATH(dst, src) \
369         ptr = src + strlen(src); \
370         while (*ptr != '\\' && ptr != src) ptr--; \
371         if (ptr != src) { \
372                 strcpy(dst, ptr+1); \
373         }
374
375 static int _OpenPlugins(void) {
376         int ret;
377
378         signal(SIGINT, SignalExit);
379         signal(SIGPIPE, SignalExit);
380
381         GPU_clearDynarec(clearDynarec);
382
383         ret = CDR_open();
384         if (ret < 0) { SysMessage(_("Error opening CD-ROM plugin!")); return -1; }
385         ret = SPU_open();
386         if (ret < 0) { SysMessage(_("Error opening SPU plugin!")); return -1; }
387         SPU_registerCallback(SPUirq);
388         // pcsx-rearmed: we handle gpu elsewhere
389         //ret = GPU_open(&gpuDisp, "PCSX", NULL);
390         //if (ret < 0) { SysMessage(_("Error opening GPU plugin!")); return -1; }
391         ret = PAD1_open(&gpuDisp);
392         if (ret < 0) { SysMessage(_("Error opening Controller 1 plugin!")); return -1; }
393         ret = PAD2_open(&gpuDisp);
394         if (ret < 0) { SysMessage(_("Error opening Controller 2 plugin!")); return -1; }
395
396         if (Config.UseNet && !NetOpened) {
397                 netInfo info;
398                 char path[MAXPATHLEN];
399                 char dotdir[MAXPATHLEN];
400
401                 MAKE_PATH(dotdir, "/.pcsx/plugins/", NULL);
402
403                 strcpy(info.EmuName, "PCSX " PACKAGE_VERSION);
404                 strncpy(info.CdromID, CdromId, 9);
405                 strncpy(info.CdromLabel, CdromLabel, 9);
406                 info.psxMem = psxM;
407                 info.GPU_showScreenPic = GPU_showScreenPic;
408                 info.GPU_displayText = GPU_displayText;
409                 info.GPU_showScreenPic = GPU_showScreenPic;
410                 info.PAD_setSensitive = PAD1_setSensitive;
411                 sprintf(path, "%s%s", Config.BiosDir, Config.Bios);
412                 strcpy(info.BIOSpath, path);
413                 strcpy(info.MCD1path, Config.Mcd1);
414                 strcpy(info.MCD2path, Config.Mcd2);
415                 sprintf(path, "%s%s", dotdir, Config.Gpu);
416                 strcpy(info.GPUpath, path);
417                 sprintf(path, "%s%s", dotdir, Config.Spu);
418                 strcpy(info.SPUpath, path);
419                 sprintf(path, "%s%s", dotdir, Config.Cdr);
420                 strcpy(info.CDRpath, path);
421                 NET_setInfo(&info);
422
423                 ret = NET_open(&gpuDisp);
424                 if (ret < 0) {
425                         if (ret == -2) {
426                                 // -2 is returned when something in the info
427                                 // changed and needs to be synced
428                                 char *ptr;
429
430                                 PARSEPATH(Config.Bios, info.BIOSpath);
431                                 PARSEPATH(Config.Gpu,  info.GPUpath);
432                                 PARSEPATH(Config.Spu,  info.SPUpath);
433                                 PARSEPATH(Config.Cdr,  info.CDRpath);
434
435                                 strcpy(Config.Mcd1, info.MCD1path);
436                                 strcpy(Config.Mcd2, info.MCD2path);
437                                 return -2;
438                         } else {
439                                 Config.UseNet = FALSE;
440                         }
441                 } else {
442                         if (NET_queryPlayer() == 1) {
443                                 if (SendPcsxInfo() == -1) Config.UseNet = FALSE;
444                         } else {
445                                 if (RecvPcsxInfo() == -1) Config.UseNet = FALSE;
446                         }
447                 }
448                 NetOpened = TRUE;
449         } else if (Config.UseNet) {
450                 NET_resume();
451         }
452
453         return 0;
454 }
455
456 int OpenPlugins() {
457         int ret;
458
459         while ((ret = _OpenPlugins()) == -2) {
460                 ReleasePlugins();
461                 LoadMcds(Config.Mcd1, Config.Mcd2);
462                 if (LoadPlugins() == -1) return -1;
463         }
464         return ret;
465 }
466
467 void ClosePlugins() {
468         int ret;
469
470         signal(SIGINT, SIG_DFL);
471         signal(SIGPIPE, SIG_DFL);
472         ret = CDR_close();
473         if (ret < 0) { SysMessage(_("Error closing CD-ROM plugin!")); return; }
474         ret = SPU_close();
475         if (ret < 0) { SysMessage(_("Error closing SPU plugin!")); return; }
476         ret = PAD1_close();
477         if (ret < 0) { SysMessage(_("Error closing Controller 1 Plugin!")); return; }
478         ret = PAD2_close();
479         if (ret < 0) { SysMessage(_("Error closing Controller 2 plugin!")); return; }
480         // pcsx-rearmed: we handle gpu elsewhere
481         //ret = GPU_close();
482         //if (ret < 0) { SysMessage(_("Error closing GPU plugin!")); return; }
483
484         if (Config.UseNet) {
485                 NET_pause();
486         }
487 }
488
489 #if 1
490 /* this is to avoid having to hack every plugin to stop using $HOME */
491 char *getenv(const char *name)
492 {
493         static char ret[8] = ".";
494
495         if (name && strcmp(name, "HOME") == 0 &&
496                         ((int)name >> 28) == 0) // HACK: let libs find home
497                 return ret;
498
499         return real_getenv(name);
500 }
501 #endif
502
503 /* we hook statically linked plugins here */
504 static const char *builtin_plugins[] = {
505         "builtin_gpu", "builtin_spu", "builtin_cdr", "builtin_pad",
506         "builtin_cdrcimg",
507 };
508
509 static const int builtin_plugin_ids[] = {
510         PLUGIN_GPU, PLUGIN_SPU, PLUGIN_CDR, PLUGIN_PAD,
511         PLUGIN_CDRCIMG,
512 };
513
514 void *SysLoadLibrary(const char *lib) {
515         const char *tmp = strrchr(lib, '/');
516         void *ret;
517         int i;
518
519         printf("plugin: %s\n", lib);
520
521         if (tmp != NULL) {
522                 tmp++;
523                 for (i = 0; i < ARRAY_SIZE(builtin_plugins); i++)
524                         if (strcmp(tmp, builtin_plugins[i]) == 0)
525                                 return (void *)(long)(PLUGIN_DL_BASE + builtin_plugin_ids[i]);
526         }
527
528 #if defined(__x86_64__) || defined(__i386__)
529         // convenience hack
530         char name[MAXPATHLEN];
531         snprintf(name, sizeof(name), "%s.x86", lib);
532         lib = name;
533 #endif
534
535         ret = dlopen(lib, RTLD_NOW);
536         if (ret == NULL)
537                 fprintf(stderr, "dlopen: %s\n", dlerror());
538         return ret;
539 }
540
541 void *SysLoadSym(void *lib, const char *sym) {
542         unsigned int plugid = (unsigned int)(long)lib;
543
544         if (PLUGIN_DL_BASE <= plugid && plugid < PLUGIN_DL_BASE + ARRAY_SIZE(builtin_plugins))
545                 return plugin_link(plugid - PLUGIN_DL_BASE, sym);
546
547         return dlsym(lib, sym);
548 }
549
550 const char *SysLibError() {
551         return dlerror();
552 }
553
554 void SysCloseLibrary(void *lib) {
555         unsigned int plugid = (unsigned int)(long)lib;
556
557         if (PLUGIN_DL_BASE <= plugid && plugid < PLUGIN_DL_BASE + ARRAY_SIZE(builtin_plugins))
558                 return;
559
560         dlclose(lib);
561 }
562