frontend: overlay improvements
[pcsx_rearmed.git] / frontend / main.c
1 /*
2  * (C) notaz, 2010-2012
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 "plat.h"
24 #include "../libpcsxcore/misc.h"
25 #include "../libpcsxcore/cheat.h"
26 #include "../libpcsxcore/new_dynarec/new_dynarec.h"
27 #include "../plugins/cdrcimg/cdrcimg.h"
28 #include "revision.h"
29
30 #ifndef NO_FRONTEND
31 #include "libpicofe/input.h"
32 #include "libpicofe/plat.h"
33 #include "libpicofe/readpng.h"
34 #endif
35 #ifndef BOOT_MSG
36 #define BOOT_MSG "Booting up..."
37 #endif
38
39 // don't include debug.h - it breaks ARM build (R1 redefined)
40 void StartDebugger();
41 void StopDebugger();
42
43 // sound plugin
44 extern int iUseReverb;
45 extern int iUseInterpolation;
46 extern int iXAPitch;
47 extern int iVolume;
48
49 int ready_to_go;
50 unsigned long gpuDisp;
51 char cfgfile_basename[MAXPATHLEN];
52 int state_slot;
53 enum sched_action emu_action, emu_action_old;
54 char hud_msg[64];
55 int hud_new_msg;
56
57 static void toggle_fast_forward(int force_off);
58
59 static void make_path(char *buf, size_t size, const char *dir, const char *fname)
60 {
61         if (fname)
62                 snprintf(buf, size, ".%s%s", dir, fname);
63         else
64                 snprintf(buf, size, ".%s", dir);
65 }
66 #define MAKE_PATH(buf, dir, fname) \
67         make_path(buf, sizeof(buf), dir, fname)
68
69 static void create_profile_dir(const char *directory) {
70         char path[MAXPATHLEN];
71
72         MAKE_PATH(path, directory, NULL);
73         mkdir(path, S_IRWXU | S_IRWXG);
74 }
75
76 static void CheckSubDir() {
77         // make sure that ~/.pcsx exists
78         create_profile_dir(PCSX_DOT_DIR);
79
80         create_profile_dir(BIOS_DIR);
81         create_profile_dir(MEMCARD_DIR);
82         create_profile_dir(STATES_DIR);
83         create_profile_dir(PLUGINS_DIR);
84         create_profile_dir(PLUGINS_CFG_DIR);
85         create_profile_dir(CHEATS_DIR);
86         create_profile_dir(PATCHES_DIR);
87         create_profile_dir(PCSX_DOT_DIR "cfg");
88         create_profile_dir("/screenshots/");
89 }
90
91 static int get_gameid_filename(char *buf, int size, const char *fmt, int i) {
92         char trimlabel[33];
93         int j;
94
95         strncpy(trimlabel, CdromLabel, 32);
96         trimlabel[32] = 0;
97         for (j = 31; j >= 0; j--)
98                 if (trimlabel[j] == ' ')
99                         trimlabel[j] = 0;
100                 else
101                         continue;
102
103         snprintf(buf, size, fmt, trimlabel, CdromId, i);
104
105         return 0;
106 }
107
108 void set_cd_image(const char *fname)
109 {
110         const char *ext = NULL;
111         
112         if (fname != NULL)
113                 ext = strrchr(fname, '.');
114
115         if (ext && (
116             strcasecmp(ext, ".z") == 0 || strcasecmp(ext, ".bz") == 0 ||
117             strcasecmp(ext, ".znx") == 0 /*|| strcasecmp(ext, ".pbp") == 0*/)) {
118                 SetIsoFile(NULL);
119                 cdrcimg_set_fname(fname);
120                 strcpy(Config.Cdr, "builtin_cdrcimg");
121         } else {
122                 SetIsoFile(fname);
123                 strcpy(Config.Cdr, "builtin_cdr");
124         }
125 }
126
127 static void set_default_paths(void)
128 {
129         MAKE_PATH(Config.Mcd1, MEMCARD_DIR, "card1.mcd");
130         MAKE_PATH(Config.Mcd2, MEMCARD_DIR, "card2.mcd");
131         strcpy(Config.BiosDir, "bios");
132
133         strcpy(Config.PluginsDir, "plugins");
134         strcpy(Config.Gpu, "builtin_gpu");
135         strcpy(Config.Spu, "builtin_spu");
136         strcpy(Config.Cdr, "builtin_cdr");
137         strcpy(Config.Pad1, "builtin_pad");
138         strcpy(Config.Pad2, "builtin_pad");
139         strcpy(Config.Net, "Disabled");
140
141         snprintf(Config.PatchesDir, sizeof(Config.PatchesDir), "." PATCHES_DIR);
142 }
143
144 void emu_set_default_config(void)
145 {
146         // try to set sane config on which most games work
147         Config.Xa = Config.Cdda = Config.Sio =
148         Config.SpuIrq = Config.RCntFix = Config.VSyncWA = 0;
149         Config.CdrReschedule = 0;
150         Config.PsxAuto = 1;
151
152         pl_rearmed_cbs.gpu_neon.allow_interlace = 2; // auto
153         pl_rearmed_cbs.gpu_neon.enhancement_enable =
154         pl_rearmed_cbs.gpu_neon.enhancement_no_main = 0;
155         pl_rearmed_cbs.gpu_peops.iUseDither = 0;
156         pl_rearmed_cbs.gpu_peops.dwActFixes = 1<<7;
157         pl_rearmed_cbs.gpu_unai.abe_hack =
158         pl_rearmed_cbs.gpu_unai.no_light =
159         pl_rearmed_cbs.gpu_unai.no_blend = 0;
160         memset(&pl_rearmed_cbs.gpu_peopsgl, 0, sizeof(pl_rearmed_cbs.gpu_peopsgl));
161         pl_rearmed_cbs.gpu_peopsgl.iVRamSize = 64;
162         pl_rearmed_cbs.gpu_peopsgl.iTexGarbageCollection = 1;
163
164         iUseReverb = 2;
165         iUseInterpolation = 1;
166         iXAPitch = 0;
167         iVolume = 768;
168 #ifndef __ARM_ARCH_7A__ /* XXX */
169         iUseReverb = 0;
170         iUseInterpolation = 0;
171 #endif
172         new_dynarec_hacks = 0;
173         cycle_multiplier = 200;
174
175         in_type1 = PSE_PAD_TYPE_STANDARD;
176         in_type2 = PSE_PAD_TYPE_STANDARD;
177 }
178
179 static void check_memcards(void)
180 {
181         char buf[MAXPATHLEN];
182         FILE *f;
183         int i;
184
185         for (i = 1; i <= 9; i++) {
186                 snprintf(buf, sizeof(buf), ".%scard%d.mcd", MEMCARD_DIR, i);
187
188                 f = fopen(buf, "rb");
189                 if (f == NULL) {
190                         printf("Creating memcard: %s\n", buf);
191                         CreateMcd(buf);
192                 }
193                 else
194                         fclose(f);
195         }
196 }
197
198 void do_emu_action(void)
199 {
200         int ret;
201
202         emu_action_old = emu_action;
203
204         switch (emu_action) {
205         case SACTION_LOAD_STATE:
206                 ret = emu_load_state(state_slot);
207                 snprintf(hud_msg, sizeof(hud_msg), ret == 0 ? "LOADED" : "FAIL!");
208                 break;
209         case SACTION_SAVE_STATE:
210                 ret = emu_save_state(state_slot);
211                 snprintf(hud_msg, sizeof(hud_msg), ret == 0 ? "SAVED" : "FAIL!");
212                 break;
213 #ifndef NO_FRONTEND
214         case SACTION_ENTER_MENU:
215                 toggle_fast_forward(1);
216                 menu_loop();
217                 return;
218         case SACTION_NEXT_SSLOT:
219                 state_slot++;
220                 if (state_slot > 9)
221                         state_slot = 0;
222                 goto do_state_slot;
223         case SACTION_PREV_SSLOT:
224                 state_slot--;
225                 if (state_slot < 0)
226                         state_slot = 9;
227 do_state_slot:
228                 snprintf(hud_msg, sizeof(hud_msg), "STATE SLOT %d [%s]", state_slot,
229                         emu_check_state(state_slot) == 0 ? "USED" : "FREE");
230                 hud_new_msg = 3;
231                 printf("* %s\n", hud_msg);
232                 break;
233         case SACTION_TOGGLE_FSKIP:
234                 pl_rearmed_cbs.fskip_advice = 0;
235                 pl_rearmed_cbs.frameskip++;
236                 if (pl_rearmed_cbs.frameskip > 1)
237                         pl_rearmed_cbs.frameskip = -1;
238                 snprintf(hud_msg, sizeof(hud_msg), "FRAMESKIP: %s",
239                         pl_rearmed_cbs.frameskip == -1 ? "AUTO" :
240                         pl_rearmed_cbs.frameskip == 0 ? "OFF" : "1" );
241                 plugin_call_rearmed_cbs();
242                 break;
243         case SACTION_SWITCH_DISPMODE:
244                 pl_switch_dispmode();
245                 plugin_call_rearmed_cbs();
246                 if (GPU_open != NULL && GPU_close != NULL) {
247                         GPU_close();
248                         GPU_open(&gpuDisp, "PCSX", NULL);
249                 }
250                 break;
251         case SACTION_FAST_FORWARD:
252                 toggle_fast_forward(0);
253                 plugin_call_rearmed_cbs();
254                 break;
255         case SACTION_TOGGLE_FPS:
256                 if ((g_opts & (OPT_SHOWFPS|OPT_SHOWCPU))
257                     == (OPT_SHOWFPS|OPT_SHOWCPU))
258                         g_opts &= ~(OPT_SHOWFPS|OPT_SHOWCPU);
259                 else if (g_opts & OPT_SHOWFPS)
260                         g_opts |= OPT_SHOWCPU;
261                 else
262                         g_opts |= OPT_SHOWFPS;
263                 break;
264         case SACTION_TOGGLE_FULLSCREEN:
265                 g_fullscreen = !g_fullscreen;
266                 if (GPU_open != NULL && GPU_close != NULL) {
267                         GPU_close();
268                         GPU_open(&gpuDisp, "PCSX", NULL);
269                 }
270                 break;
271         case SACTION_SCREENSHOT:
272                 {
273                         char buf[MAXPATHLEN];
274                         void *scrbuf;
275                         int w, h, bpp;
276                         time_t t = time(NULL);
277                         struct tm *tb = localtime(&t);
278                         int ti = tb->tm_yday * 1000000 + tb->tm_hour * 10000 +
279                                 tb->tm_min * 100 + tb->tm_sec;
280
281                         scrbuf = pl_prepare_screenshot(&w, &h, &bpp);
282                         get_gameid_filename(buf, sizeof(buf),
283                                 "screenshots/%.32s-%.9s.%d.png", ti);
284                         ret = -1;
285                         if (scrbuf != 0 && bpp == 16)
286                                 ret = writepng(buf, scrbuf, w, h);
287                         if (ret == 0)
288                                 snprintf(hud_msg, sizeof(hud_msg), "SCREENSHOT TAKEN");
289                         break;
290                 }
291         case SACTION_VOLUME_UP:
292         case SACTION_VOLUME_DOWN:
293                 plat_target_step_volume(emu_action == SACTION_VOLUME_UP);
294                 return;
295         case SACTION_MINIMIZE:
296                 if (GPU_close != NULL)
297                         GPU_close();
298
299                 plat_minimize();
300
301                 if (GPU_open != NULL) {
302                         ret = GPU_open(&gpuDisp, "PCSX", NULL);
303                         if (ret)
304                                 fprintf(stderr, "GPU_open returned %d\n", ret);
305                 }
306                 return;
307 #endif
308         default:
309                 return;
310         }
311
312         hud_new_msg = 3;
313 }
314
315 static int cdidcmp(const char *id1, const char *id2)
316 {
317         while (*id1 != 0 && *id2 != 0) {
318                 if (*id1 == '_') { id1++; continue; }
319                 if (*id2 == '_') { id2++; continue; }
320                 if (*id1 != *id2)
321                         break;
322                 id1++;
323                 id2++;
324         }
325
326         return *id1 - *id2;
327 }
328
329 static void parse_cwcheat(void)
330 {
331         char line[256], buf[64], name[64], *p;
332         int newcheat = 1;
333         u32 a, v;
334         FILE *f;
335
336         f = fopen("cheatpops.db", "r");
337         if (f == NULL)
338                 return;
339
340         /* find the game */
341         while (fgets(line, sizeof(line), f)) {
342                 if (sscanf(line, "_S %63s", buf) != 1)
343                         continue;
344                 if (cdidcmp(buf, CdromId) == 0)
345                         break;
346         }
347
348         if (feof(f))
349                 goto out;
350
351         printf("cwcheat section found for %s\n", CdromId);
352         while (fgets(line, sizeof(line), f))
353         {
354                 p = line + strlen(line);
355                 for (p--; p >= line && (*p == '\r' || *p == '\n' || *p == ' '); p--)
356                         *p = 0;
357                 if (*p == 0 || *p == '#' || *p == ';')
358                         continue;
359
360                 if (strncmp(line, "_S", 2) == 0)
361                         break;
362                 if (strncmp(line, "_G", 2) == 0) {
363                         printf("  cwcheat game name: '%s'\n", line + 3);
364                         continue;
365                 }
366                 if (strncmp(line, "_C0", 3) == 0) {
367                         if (!newcheat && Cheats[NumCheats - 1].n == 0) {
368                                 printf("cheat '%s' failed to parse\n", name);
369                                 free(Cheats[NumCheats - 1].Descr);
370                                 NumCheats--;
371                         }
372                         snprintf(name, sizeof(name), "%s", line + 4);
373                         newcheat = 1;
374                         continue;
375                 }
376                 if (sscanf(line, "_L %x %x", &a, &v) != 2) {
377                         printf("line failed to parse: '%s'\n", line);
378                         continue;
379                 }
380
381                 if (newcheat) {
382                         if (NumCheats >= NumCheatsAllocated) {
383                                 NumCheatsAllocated += 16;
384                                 Cheats = realloc(Cheats, sizeof(Cheat) *
385                                                 NumCheatsAllocated);
386                                 if (Cheats == NULL)
387                                         break;
388                         }
389                         Cheats[NumCheats].Descr = strdup(name);
390                         Cheats[NumCheats].Enabled = 0;
391                         Cheats[NumCheats].WasEnabled = 0;
392                         Cheats[NumCheats].First = NumCodes;
393                         Cheats[NumCheats].n = 0;
394                         NumCheats++;
395                         newcheat = 0;
396                 }
397
398                 if (NumCodes >= NumCodesAllocated) {
399                         NumCodesAllocated += 16;
400                         CheatCodes = realloc(CheatCodes, sizeof(CheatCode) *
401                                 NumCodesAllocated);
402                         if (CheatCodes == NULL)
403                                 break;
404                 }
405                 CheatCodes[NumCodes].Addr = a;
406                 CheatCodes[NumCodes].Val = v;
407                 NumCodes++;
408                 Cheats[NumCheats - 1].n++;
409         }
410
411 out:
412         fclose(f);
413 }
414
415 void emu_on_new_cd(int show_hud_msg)
416 {
417         ClearAllCheats();
418         parse_cwcheat();
419
420         if (Config.HLE) {
421                 printf("note: running with HLE BIOS, expect compatibility problems\n");
422                 printf("----------------------------------------------------------\n");
423         }
424
425         if (show_hud_msg) {
426                 snprintf(hud_msg, sizeof(hud_msg), BOOT_MSG);
427                 hud_new_msg = 3;
428         }
429 }
430
431 int emu_core_preinit(void)
432 {
433         // what is the name of the config file?
434         // it may be redefined by -cfg on the command line
435         strcpy(cfgfile_basename, "pcsx.cfg");
436
437         emuLog = stdout;
438         SetIsoFile(NULL);
439
440         memset(&Config, 0, sizeof(Config));
441
442         set_default_paths();
443         emu_set_default_config();
444         strcpy(Config.Bios, "HLE");
445
446         return 0;
447 }
448
449 int emu_core_init(void)
450 {
451         CheckSubDir();
452         check_memcards();
453
454         if (EmuInit() == -1) {
455                 printf("PSX emulator couldn't be initialized.\n");
456                 return -1;
457         }
458
459         LoadMcds(Config.Mcd1, Config.Mcd2);
460
461         if (Config.Debug) {
462                 StartDebugger();
463         }
464
465         return 0;
466 }
467
468 #ifndef NO_FRONTEND
469 int main(int argc, char *argv[])
470 {
471         char file[MAXPATHLEN] = "";
472         char path[MAXPATHLEN];
473         const char *cdfile = NULL;
474         const char *loadst_f = NULL;
475         int psxout = 0;
476         int loadst = 0;
477         int i;
478
479         emu_core_preinit();
480
481         // read command line options
482         for (i = 1; i < argc; i++) {
483                      if (!strcmp(argv[i], "-psxout")) psxout = 1;
484                 else if (!strcmp(argv[i], "-load")) loadst = atol(argv[++i]);
485                 else if (!strcmp(argv[i], "-cfg")) {
486                         if (i+1 >= argc) break;
487                         strncpy(cfgfile_basename, argv[++i], MAXPATHLEN-100);   /* TODO buffer overruns */
488                         printf("Using config file %s.\n", cfgfile_basename);
489                 }
490                 else if (!strcmp(argv[i], "-cdfile")) {
491                         char isofilename[MAXPATHLEN];
492
493                         if (i+1 >= argc) break;
494                         strncpy(isofilename, argv[++i], MAXPATHLEN);
495                         if (isofilename[0] != '/') {
496                                 getcwd(path, MAXPATHLEN);
497                                 if (strlen(path) + strlen(isofilename) + 1 < MAXPATHLEN) {
498                                         strcat(path, "/");
499                                         strcat(path, isofilename);
500                                         strcpy(isofilename, path);
501                                 } else
502                                         isofilename[0] = 0;
503                         }
504
505                         cdfile = isofilename;
506                 }
507                 else if (!strcmp(argv[i], "-loadf")) {
508                         if (i+1 >= argc) break;
509                         loadst_f = argv[++i];
510                 }
511                 else if (!strcmp(argv[i], "-h") ||
512                          !strcmp(argv[i], "-help") ||
513                          !strcmp(argv[i], "--help")) {
514                          printf("PCSX-ReARMed " REV "\n");
515                          printf("%s\n", _(
516                                                         " pcsx [options] [file]\n"
517                                                         "\toptions:\n"
518                                                         "\t-cdfile FILE\tRuns a CD image file\n"
519                                                         "\t-cfg FILE\tLoads desired configuration file (default: ~/.pcsx/pcsx.cfg)\n"
520                                                         "\t-psxout\t\tEnable PSX output\n"
521                                                         "\t-load STATENUM\tLoads savestate STATENUM (1-5)\n"
522                                                         "\t-h -help\tDisplay this message\n"
523                                                         "\tfile\t\tLoads a PSX EXE file\n"));
524                          return 0;
525                 } else {
526                         strncpy(file, argv[i], MAXPATHLEN);
527                         if (file[0] != '/') {
528                                 getcwd(path, MAXPATHLEN);
529                                 if (strlen(path) + strlen(file) + 1 < MAXPATHLEN) {
530                                         strcat(path, "/");
531                                         strcat(path, file);
532                                         strcpy(file, path);
533                                 } else
534                                         file[0] = 0;
535                         }
536                 }
537         }
538
539         if (cdfile)
540                 set_cd_image(cdfile);
541
542         // frontend stuff
543         // init input but leave probing to platform code,
544         // they add input drivers and may need to modify them after probe
545         in_init();
546         pl_init();
547         plat_init();
548         menu_init(); // loads config
549
550         emu_core_init();
551
552         if (psxout)
553                 Config.PsxOut = 1;
554
555         if (LoadPlugins() == -1) {
556                 // FIXME: this recovery doesn't work, just delete bad config and bail out
557                 // SysMessage("could not load plugins, retrying with defaults\n");
558                 set_default_paths();
559                 snprintf(path, sizeof(path), "." PCSX_DOT_DIR "%s", cfgfile_basename);
560                 remove(path);
561                 SysMessage("Failed loading plugins!");
562                 return 1;
563         }
564         pcnt_hook_plugins();
565
566         if (OpenPlugins() == -1) {
567                 return 1;
568         }
569         plugin_call_rearmed_cbs();
570
571         CheckCdrom();
572         SysReset();
573
574         if (file[0] != '\0') {
575                 if (Load(file) != -1)
576                         ready_to_go = 1;
577         } else {
578                 if (cdfile) {
579                         if (LoadCdrom() == -1) {
580                                 ClosePlugins();
581                                 printf(_("Could not load CD-ROM!\n"));
582                                 return -1;
583                         }
584                         emu_on_new_cd(!loadst);
585                         ready_to_go = 1;
586                 }
587         }
588
589         if (ready_to_go) {
590                 menu_prepare_emu();
591
592                 // If a state has been specified, then load that
593                 if (loadst) {
594                         int ret = emu_load_state(loadst - 1);
595                         printf("%s state %d\n", ret ? "failed to load" : "loaded", loadst);
596                 }
597                 if (loadst_f) {
598                         int ret = LoadState(loadst_f);
599                         printf("%s state file: %s\n", ret ? "failed to load" : "loaded", loadst_f);
600                 }
601         }
602         else
603                 menu_loop();
604
605         pl_start_watchdog();
606
607         while (1)
608         {
609                 stop = 0;
610                 emu_action = SACTION_NONE;
611
612                 psxCpu->Execute();
613                 if (emu_action != SACTION_NONE)
614                         do_emu_action();
615         }
616
617         return 0;
618 }
619
620 static void toggle_fast_forward(int force_off)
621 {
622         static int fast_forward;
623         static int normal_g_opts;
624         static int normal_frameskip;
625         static int normal_enhancement_enable;
626
627         if (force_off && !fast_forward)
628                 return;
629
630         fast_forward = !fast_forward;
631         if (fast_forward) {
632                 normal_g_opts = g_opts;
633                 normal_frameskip = pl_rearmed_cbs.frameskip;
634                 normal_enhancement_enable =
635                         pl_rearmed_cbs.gpu_neon.enhancement_enable;
636
637                 g_opts |= OPT_NO_FRAMELIM;
638                 pl_rearmed_cbs.frameskip = 3;
639                 pl_rearmed_cbs.gpu_neon.enhancement_enable = 0;
640         } else {
641                 g_opts = normal_g_opts;
642                 pl_rearmed_cbs.frameskip = normal_frameskip;
643                 pl_rearmed_cbs.gpu_neon.enhancement_enable =
644                         normal_enhancement_enable;
645
646                 pl_timing_prepare(Config.PsxType);
647         }
648
649         if (!force_off)
650                 snprintf(hud_msg, sizeof(hud_msg), "FAST FORWARD %s",
651                         fast_forward ? "ON" : "OFF");
652 }
653 #endif
654
655 void SysRunGui() {
656         printf("SysRunGui\n");
657 }
658
659 static void dummy_lace()
660 {
661 }
662
663 void SysReset() {
664         // rearmed hack: EmuReset() runs some code when real BIOS is used,
665         // but we usually do reset from menu while GPU is not open yet,
666         // so we need to prevent updateLace() call..
667         void *real_lace = GPU_updateLace;
668         GPU_updateLace = dummy_lace;
669
670         // reset can run code, timing must be set
671         pl_timing_prepare(Config.PsxType);
672
673         EmuReset();
674
675         // hmh core forgets this
676         CDR_stop();
677
678         GPU_updateLace = real_lace;
679 }
680
681 void SysClose() {
682         EmuShutdown();
683         ReleasePlugins();
684
685         StopDebugger();
686
687         if (emuLog != NULL) fclose(emuLog);
688 }
689
690 void SysUpdate() {
691 }
692
693 void OnFile_Exit() {
694         printf("OnFile_Exit\n");
695         SysClose();
696 #ifndef NO_FRONTEND
697         menu_finish();
698         plat_finish();
699         exit(0);
700 #endif
701 }
702
703 int get_state_filename(char *buf, int size, int i) {
704         return get_gameid_filename(buf, size,
705                 "." STATES_DIR "%.32s-%.9s.%3.3d", i);
706 }
707
708 int emu_check_state(int slot)
709 {
710         char fname[MAXPATHLEN];
711         int ret;
712
713         ret = get_state_filename(fname, sizeof(fname), slot);
714         if (ret != 0)
715                 return ret;
716
717         return CheckState(fname);
718 }
719
720 int emu_save_state(int slot)
721 {
722         char fname[MAXPATHLEN];
723         int ret;
724
725         ret = get_state_filename(fname, sizeof(fname), slot);
726         if (ret != 0)
727                 return ret;
728
729         ret = SaveState(fname);
730 #ifndef __ARM_ARCH_7A__ /* XXX */
731         sync();
732 #endif
733         printf("* %s \"%s\" [%d]\n", ret == 0 ? "saved" : "failed to save", fname, slot);
734         return ret;
735 }
736
737 int emu_load_state(int slot)
738 {
739         char fname[MAXPATHLEN];
740         int ret;
741
742         hud_msg[0] = 0;
743
744         ret = get_state_filename(fname, sizeof(fname), slot);
745         if (ret != 0)
746                 return ret;
747
748         return LoadState(fname);
749 }
750
751 void SysPrintf(const char *fmt, ...) {
752         va_list list;
753         char msg[512];
754
755         va_start(list, fmt);
756         vsprintf(msg, fmt, list);
757         va_end(list);
758
759         fprintf(emuLog, "%s", msg);
760 }
761
762 void SysMessage(const char *fmt, ...) {
763         va_list list;
764         char msg[512];
765
766         va_start(list, fmt);
767         vsprintf(msg, fmt, list);
768         va_end(list);
769
770         if (msg[strlen(msg) - 1] == '\n')
771                 msg[strlen(msg) - 1] = 0;
772
773         fprintf(stderr, "%s\n", msg);
774 }
775
776 static void SignalExit(int sig) {
777         ClosePlugins();
778         OnFile_Exit();
779 }
780
781 #define PARSEPATH(dst, src) \
782         ptr = src + strlen(src); \
783         while (*ptr != '\\' && ptr != src) ptr--; \
784         if (ptr != src) { \
785                 strcpy(dst, ptr+1); \
786         }
787
788 static int _OpenPlugins(void) {
789         int ret;
790
791         signal(SIGINT, SignalExit);
792         signal(SIGPIPE, SignalExit);
793
794         GPU_clearDynarec(clearDynarec);
795
796         ret = CDR_open();
797         if (ret < 0) { SysMessage(_("Error opening CD-ROM plugin!")); return -1; }
798         ret = SPU_open();
799         if (ret < 0) { SysMessage(_("Error opening SPU plugin!")); return -1; }
800         SPU_registerCallback(SPUirq);
801         // pcsx-rearmed: we handle gpu elsewhere
802         //ret = GPU_open(&gpuDisp, "PCSX", NULL);
803         //if (ret < 0) { SysMessage(_("Error opening GPU plugin!")); return -1; }
804         ret = PAD1_open(&gpuDisp);
805         if (ret < 0) { SysMessage(_("Error opening Controller 1 plugin!")); return -1; }
806         ret = PAD2_open(&gpuDisp);
807         if (ret < 0) { SysMessage(_("Error opening Controller 2 plugin!")); return -1; }
808
809         if (Config.UseNet && !NetOpened) {
810                 netInfo info;
811                 char path[MAXPATHLEN];
812                 char dotdir[MAXPATHLEN];
813
814                 MAKE_PATH(dotdir, "/.pcsx/plugins/", NULL);
815
816                 strcpy(info.EmuName, "PCSX");
817                 strncpy(info.CdromID, CdromId, 9);
818                 strncpy(info.CdromLabel, CdromLabel, 9);
819                 info.psxMem = psxM;
820                 info.GPU_showScreenPic = GPU_showScreenPic;
821                 info.GPU_displayText = GPU_displayText;
822                 info.GPU_showScreenPic = GPU_showScreenPic;
823                 info.PAD_setSensitive = PAD1_setSensitive;
824                 sprintf(path, "%s%s", Config.BiosDir, Config.Bios);
825                 strcpy(info.BIOSpath, path);
826                 strcpy(info.MCD1path, Config.Mcd1);
827                 strcpy(info.MCD2path, Config.Mcd2);
828                 sprintf(path, "%s%s", dotdir, Config.Gpu);
829                 strcpy(info.GPUpath, path);
830                 sprintf(path, "%s%s", dotdir, Config.Spu);
831                 strcpy(info.SPUpath, path);
832                 sprintf(path, "%s%s", dotdir, Config.Cdr);
833                 strcpy(info.CDRpath, path);
834                 NET_setInfo(&info);
835
836                 ret = NET_open(&gpuDisp);
837                 if (ret < 0) {
838                         if (ret == -2) {
839                                 // -2 is returned when something in the info
840                                 // changed and needs to be synced
841                                 char *ptr;
842
843                                 PARSEPATH(Config.Bios, info.BIOSpath);
844                                 PARSEPATH(Config.Gpu,  info.GPUpath);
845                                 PARSEPATH(Config.Spu,  info.SPUpath);
846                                 PARSEPATH(Config.Cdr,  info.CDRpath);
847
848                                 strcpy(Config.Mcd1, info.MCD1path);
849                                 strcpy(Config.Mcd2, info.MCD2path);
850                                 return -2;
851                         } else {
852                                 Config.UseNet = FALSE;
853                         }
854                 } else {
855                         if (NET_queryPlayer() == 1) {
856                                 if (SendPcsxInfo() == -1) Config.UseNet = FALSE;
857                         } else {
858                                 if (RecvPcsxInfo() == -1) Config.UseNet = FALSE;
859                         }
860                 }
861                 NetOpened = TRUE;
862         } else if (Config.UseNet) {
863                 NET_resume();
864         }
865
866         return 0;
867 }
868
869 int OpenPlugins() {
870         int ret;
871
872         while ((ret = _OpenPlugins()) == -2) {
873                 ReleasePlugins();
874                 LoadMcds(Config.Mcd1, Config.Mcd2);
875                 if (LoadPlugins() == -1) return -1;
876         }
877         return ret;
878 }
879
880 void ClosePlugins() {
881         int ret;
882
883         signal(SIGINT, SIG_DFL);
884         signal(SIGPIPE, SIG_DFL);
885         ret = CDR_close();
886         if (ret < 0) { SysMessage(_("Error closing CD-ROM plugin!")); return; }
887         ret = SPU_close();
888         if (ret < 0) { SysMessage(_("Error closing SPU plugin!")); return; }
889         ret = PAD1_close();
890         if (ret < 0) { SysMessage(_("Error closing Controller 1 Plugin!")); return; }
891         ret = PAD2_close();
892         if (ret < 0) { SysMessage(_("Error closing Controller 2 plugin!")); return; }
893         // pcsx-rearmed: we handle gpu elsewhere
894         //ret = GPU_close();
895         //if (ret < 0) { SysMessage(_("Error closing GPU plugin!")); return; }
896
897         if (Config.UseNet) {
898                 NET_pause();
899         }
900 }
901
902 /* we hook statically linked plugins here */
903 static const char *builtin_plugins[] = {
904         "builtin_gpu", "builtin_spu", "builtin_cdr", "builtin_pad",
905         "builtin_cdrcimg",
906 };
907
908 static const int builtin_plugin_ids[] = {
909         PLUGIN_GPU, PLUGIN_SPU, PLUGIN_CDR, PLUGIN_PAD,
910         PLUGIN_CDRCIMG,
911 };
912
913 void *SysLoadLibrary(const char *lib) {
914         const char *tmp = strrchr(lib, '/');
915         void *ret;
916         int i;
917
918         printf("plugin: %s\n", lib);
919
920         if (tmp != NULL) {
921                 tmp++;
922                 for (i = 0; i < ARRAY_SIZE(builtin_plugins); i++)
923                         if (strcmp(tmp, builtin_plugins[i]) == 0)
924                                 return (void *)(long)(PLUGIN_DL_BASE + builtin_plugin_ids[i]);
925         }
926
927         ret = dlopen(lib, RTLD_NOW);
928         if (ret == NULL)
929                 fprintf(stderr, "dlopen: %s\n", dlerror());
930         return ret;
931 }
932
933 void *SysLoadSym(void *lib, const char *sym) {
934         unsigned int plugid = (unsigned int)(long)lib;
935
936         if (PLUGIN_DL_BASE <= plugid && plugid < PLUGIN_DL_BASE + ARRAY_SIZE(builtin_plugins))
937                 return plugin_link(plugid - PLUGIN_DL_BASE, sym);
938
939         return dlsym(lib, sym);
940 }
941
942 const char *SysLibError() {
943         return dlerror();
944 }
945
946 void SysCloseLibrary(void *lib) {
947         unsigned int plugid = (unsigned int)(long)lib;
948
949         if (PLUGIN_DL_BASE <= plugid && plugid < PLUGIN_DL_BASE + ARRAY_SIZE(builtin_plugins))
950                 return;
951
952         dlclose(lib);
953 }
954