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