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