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