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