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