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