frontend/input: make it more modular
[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 "../libpcsxcore/misc.h"
24 #include "../libpcsxcore/new_dynarec/new_dynarec.h"
25 #include "../plugins/cdrcimg/cdrcimg.h"
26 #include "common/plat.h"
27 #include "common/readpng.h"
28 #include "common/input.h"
29 #include "linux/in_evdev.h"
30
31 // don't include debug.h - it breaks ARM build (R1 redefined)
32 void StartDebugger();
33 void StopDebugger();
34
35 int ready_to_go;
36 unsigned long gpuDisp;
37 char cfgfile_basename[MAXPATHLEN];
38 int state_slot;
39 enum sched_action emu_action, emu_action_old;
40 char hud_msg[64];
41 int hud_new_msg;
42
43 static void make_path(char *buf, size_t size, const char *dir, const char *fname)
44 {
45         if (fname)
46                 snprintf(buf, size, ".%s%s", dir, fname);
47         else
48                 snprintf(buf, size, ".%s", dir);
49 }
50 #define MAKE_PATH(buf, dir, fname) \
51         make_path(buf, sizeof(buf), dir, fname)
52
53 static void create_profile_dir(const char *directory) {
54         char path[MAXPATHLEN];
55
56         MAKE_PATH(path, directory, NULL);
57         mkdir(path, S_IRWXU | S_IRWXG);
58 }
59
60 static void CheckSubDir() {
61         // make sure that ~/.pcsx exists
62         create_profile_dir(PCSX_DOT_DIR);
63
64         create_profile_dir(BIOS_DIR);
65         create_profile_dir(MEMCARD_DIR);
66         create_profile_dir(STATES_DIR);
67         create_profile_dir(PLUGINS_DIR);
68         create_profile_dir(PLUGINS_CFG_DIR);
69         create_profile_dir(CHEATS_DIR);
70         create_profile_dir(PATCHES_DIR);
71         create_profile_dir(PCSX_DOT_DIR "cfg");
72         create_profile_dir("/screenshots/");
73 }
74
75 static int get_gameid_filename(char *buf, int size, const char *fmt, int i) {
76         char trimlabel[33];
77         int j;
78
79         strncpy(trimlabel, CdromLabel, 32);
80         trimlabel[32] = 0;
81         for (j = 31; j >= 0; j--)
82                 if (trimlabel[j] == ' ')
83                         trimlabel[j] = 0;
84                 else
85                         continue;
86
87         snprintf(buf, size, fmt, trimlabel, CdromId, i);
88
89         return 0;
90 }
91
92 void set_cd_image(const char *fname)
93 {
94         const char *ext = NULL;
95         
96         if (fname != NULL)
97                 ext = strrchr(fname, '.');
98
99         if (ext && (
100             strcasecmp(ext, ".z") == 0 || strcasecmp(ext, ".bz") == 0 ||
101             strcasecmp(ext, ".znx") == 0 /*|| strcasecmp(ext, ".pbp") == 0*/)) {
102                 SetIsoFile(NULL);
103                 cdrcimg_set_fname(fname);
104                 strcpy(Config.Cdr, "builtin_cdrcimg");
105         } else {
106                 SetIsoFile(fname);
107                 strcpy(Config.Cdr, "builtin_cdr");
108         }
109 }
110
111 static void set_default_paths(void)
112 {
113         MAKE_PATH(Config.Mcd1, MEMCARD_DIR, "card1.mcd");
114         MAKE_PATH(Config.Mcd2, MEMCARD_DIR, "card2.mcd");
115         strcpy(Config.BiosDir, "bios");
116
117         strcpy(Config.PluginsDir, "plugins");
118         strcpy(Config.Gpu, "builtin_gpu");
119         strcpy(Config.Spu, "builtin_spu");
120         strcpy(Config.Cdr, "builtin_cdr");
121         strcpy(Config.Pad1, "builtin_pad");
122         strcpy(Config.Pad2, "builtin_pad");
123         strcpy(Config.Net, "Disabled");
124 #if defined(__arm__) && !defined(__ARM_ARCH_7A__) /* XXX */
125         strcpy(Config.Gpu, "gpuPCSX4ALL.so");
126 #endif
127         Config.PsxAuto = 1;
128
129         snprintf(Config.PatchesDir, sizeof(Config.PatchesDir), "." PATCHES_DIR);
130 }
131
132 static void check_memcards(void)
133 {
134         char buf[MAXPATHLEN];
135         FILE *f;
136         int i;
137
138         for (i = 1; i <= 9; i++) {
139                 snprintf(buf, sizeof(buf), ".%scard%d.mcd", MEMCARD_DIR, i);
140
141                 f = fopen(buf, "rb");
142                 if (f == NULL) {
143                         printf("Creating memcard: %s\n", buf);
144                         CreateMcd(buf);
145                 }
146                 else
147                         fclose(f);
148         }
149 }
150
151 void do_emu_action(void)
152 {
153         char buf[MAXPATHLEN];
154         int ret;
155
156         emu_action_old = emu_action;
157
158         switch (emu_action) {
159         case SACTION_ENTER_MENU:
160                 menu_loop();
161                 return;
162         case SACTION_LOAD_STATE:
163                 ret = emu_load_state(state_slot);
164                 snprintf(hud_msg, sizeof(hud_msg), ret == 0 ? "LOADED" : "FAIL!");
165                 break;
166         case SACTION_SAVE_STATE:
167                 ret = emu_save_state(state_slot);
168                 snprintf(hud_msg, sizeof(hud_msg), ret == 0 ? "SAVED" : "FAIL!");
169                 break;
170         case SACTION_NEXT_SSLOT:
171                 state_slot++;
172                 if (state_slot > 9)
173                         state_slot = 0;
174                 goto do_state_slot;
175         case SACTION_PREV_SSLOT:
176                 state_slot--;
177                 if (state_slot < 0)
178                         state_slot = 9;
179                 goto do_state_slot;
180         case SACTION_TOGGLE_FSKIP:
181                 pl_rearmed_cbs.fskip_advice = 0;
182                 pl_rearmed_cbs.frameskip++;
183                 if (pl_rearmed_cbs.frameskip > 1)
184                         pl_rearmed_cbs.frameskip = -1;
185                 snprintf(hud_msg, sizeof(hud_msg), "FRAMESKIP: %s",
186                         pl_rearmed_cbs.frameskip == -1 ? "AUTO" :
187                         pl_rearmed_cbs.frameskip == 0 ? "OFF" : "1" );
188                 plugin_call_rearmed_cbs();
189                 break;
190         case SACTION_SCREENSHOT:
191                 {
192                         void *scrbuf;
193                         int w, h, bpp;
194                         time_t t = time(NULL);
195                         struct tm *tb = localtime(&t);
196                         int ti = tb->tm_yday * 1000000 + tb->tm_hour * 10000 +
197                                 tb->tm_min * 100 + tb->tm_sec;
198
199                         scrbuf = pl_prepare_screenshot(&w, &h, &bpp);
200                         get_gameid_filename(buf, sizeof(buf),
201                                 "screenshots/%.32s-%.9s.%d.png", ti);
202                         ret = -1;
203                         if (scrbuf != 0 && bpp == 16)
204                                 ret = writepng(buf, scrbuf, w, h);
205                         if (ret == 0)
206                                 snprintf(hud_msg, sizeof(hud_msg), "SCREENSHOT TAKEN");
207                         break;
208                 }
209         default:
210                 return;
211         }
212         hud_new_msg = 3;
213         return;
214
215 do_state_slot:
216         snprintf(hud_msg, sizeof(hud_msg), "STATE SLOT %d [%s]", state_slot,
217                 emu_check_state(state_slot) == 0 ? "USED" : "FREE");
218         hud_new_msg = 3;
219         printf("* %s\n", hud_msg);
220 }
221
222 int main(int argc, char *argv[])
223 {
224         // what is the name of the config file?
225         // it may be redefined by -cfg on the command line
226         strcpy(cfgfile_basename, "pcsx.cfg");
227
228         emuLog = stdout;
229         SetIsoFile(NULL);
230
231         memset(&Config, 0, sizeof(Config));
232
233         CheckSubDir();
234         set_default_paths();
235         check_memcards();
236         strcpy(Config.Bios, "HLE");
237
238 #ifdef MAEMO
239         extern int maemo_main(int argc, char **argv);
240         return maemo_main(argc, argv);
241 #else
242         char file[MAXPATHLEN] = "";
243         char path[MAXPATHLEN];
244         const char *cdfile = NULL;
245         const char *loadst_f = NULL;
246         int psxout = 0;
247         int loadst = 0;
248         int i;
249
250         // read command line options
251         for (i = 1; i < argc; i++) {
252                      if (!strcmp(argv[i], "-psxout")) psxout = 1;
253                 else if (!strcmp(argv[i], "-load")) loadst = atol(argv[++i]);
254                 else if (!strcmp(argv[i], "-cfg")) {
255                         if (i+1 >= argc) break;
256                         strncpy(cfgfile_basename, argv[++i], MAXPATHLEN-100);   /* TODO buffer overruns */
257                         printf("Using config file %s.\n", cfgfile_basename);
258                 }
259                 else if (!strcmp(argv[i], "-cdfile")) {
260                         char isofilename[MAXPATHLEN];
261
262                         if (i+1 >= argc) break;
263                         strncpy(isofilename, argv[++i], MAXPATHLEN);
264                         if (isofilename[0] != '/') {
265                                 getcwd(path, MAXPATHLEN);
266                                 if (strlen(path) + strlen(isofilename) + 1 < MAXPATHLEN) {
267                                         strcat(path, "/");
268                                         strcat(path, isofilename);
269                                         strcpy(isofilename, path);
270                                 } else
271                                         isofilename[0] = 0;
272                         }
273
274                         cdfile = isofilename;
275                 }
276                 else if (!strcmp(argv[i], "-loadf")) {
277                         if (i+1 >= argc) break;
278                         loadst_f = argv[++i];
279                 }
280                 else if (!strcmp(argv[i], "-h") ||
281                          !strcmp(argv[i], "-help") ||
282                          !strcmp(argv[i], "--help")) {
283                          printf(PACKAGE_NAME " " PACKAGE_VERSION "\n");
284                          printf("%s\n", _(
285                                                         " pcsx [options] [file]\n"
286                                                         "\toptions:\n"
287                                                         "\t-cdfile FILE\tRuns a CD image file\n"
288                                                         "\t-nogui\t\tDon't open the GTK GUI\n"
289                                                         "\t-cfg FILE\tLoads desired configuration file (default: ~/.pcsx/pcsx.cfg)\n"
290                                                         "\t-psxout\t\tEnable PSX output\n"
291                                                         "\t-load STATENUM\tLoads savestate STATENUM (1-5)\n"
292                                                         "\t-h -help\tDisplay this message\n"
293                                                         "\tfile\t\tLoads file\n"));
294                          return 0;
295                 } else {
296                         strncpy(file, argv[i], MAXPATHLEN);
297                         if (file[0] != '/') {
298                                 getcwd(path, MAXPATHLEN);
299                                 if (strlen(path) + strlen(file) + 1 < MAXPATHLEN) {
300                                         strcat(path, "/");
301                                         strcat(path, file);
302                                         strcpy(file, path);
303                                 } else
304                                         file[0] = 0;
305                         }
306                 }
307         }
308
309         if (cdfile)
310                 set_cd_image(cdfile);
311
312         if (SysInit() == -1)
313                 return 1;
314
315         // frontend stuff
316         in_init();
317         in_evdev_init();
318         //in_probe();
319         plat_init();
320         menu_init(); // loads config
321         pl_init();
322
323         if (psxout)
324                 Config.PsxOut = 1;
325
326         if (LoadPlugins() == -1) {
327                 // FIXME: this recovery doesn't work, just delete bad config and bail out
328                 // SysMessage("could not load plugins, retrying with defaults\n");
329                 set_default_paths();
330                 snprintf(path, sizeof(path), "." PCSX_DOT_DIR "%s", cfgfile_basename);
331                 remove(path);
332                 SysMessage("Failed loading plugins!");
333                 return 1;
334         }
335         pcnt_hook_plugins();
336
337         if (OpenPlugins() == -1) {
338                 return 1;
339         }
340         plugin_call_rearmed_cbs();
341
342         CheckCdrom();
343         SysReset();
344
345         if (file[0] != '\0') {
346                 if (Load(file) != -1)
347                         ready_to_go = 1;
348         } else {
349                 if (cdfile) {
350                         if (LoadCdrom() == -1) {
351                                 ClosePlugins();
352                                 printf(_("Could not load CD-ROM!\n"));
353                                 return -1;
354                         }
355                         ready_to_go = 1;
356                 }
357         }
358
359         if (ready_to_go) {
360                 menu_prepare_emu();
361
362                 // If a state has been specified, then load that
363                 if (loadst) {
364                         int ret = emu_load_state(loadst - 1);
365                         printf("%s state %d\n", ret ? "failed to load" : "loaded", loadst);
366                 }
367                 if (loadst_f) {
368                         int ret = LoadState(loadst_f);
369                         printf("%s state file: %s\n", ret ? "failed to load" : "loaded", loadst_f);
370                 }
371         }
372         else
373                 menu_loop();
374
375         pl_start_watchdog();
376
377         while (1)
378         {
379                 stop = 0;
380                 emu_action = SACTION_NONE;
381
382                 psxCpu->Execute();
383                 if (emu_action != SACTION_NONE)
384                         do_emu_action();
385         }
386
387         return 0;
388 #endif
389 }
390
391 int SysInit() {
392         if (EmuInit() == -1) {
393                 printf("PSX emulator couldn't be initialized.\n");
394                 return -1;
395         }
396
397         LoadMcds(Config.Mcd1, Config.Mcd2);
398
399         if (Config.Debug) {
400                 StartDebugger();
401         }
402
403         return 0;
404 }
405
406 void SysRunGui() {
407         printf("SysRunGui\n");
408 }
409
410 void StartGui() {
411         printf("StartGui\n");
412 }
413
414 static void dummy_lace()
415 {
416 }
417
418 void SysReset() {
419         // rearmed hack: EmuReset() runs some code when real BIOS is used,
420         // but we usually do reset from menu while GPU is not open yet,
421         // so we need to prevent updateLace() call..
422         void *real_lace = GPU_updateLace;
423         GPU_updateLace = dummy_lace;
424
425         EmuReset();
426
427         // hmh core forgets this
428         CDR_stop();
429
430         GPU_updateLace = real_lace;
431 }
432
433 void SysClose() {
434         EmuShutdown();
435         ReleasePlugins();
436
437         StopDebugger();
438
439         if (emuLog != NULL) fclose(emuLog);
440 }
441
442 void SysUpdate() {
443 }
444
445 void OnFile_Exit() {
446         printf("OnFile_Exit\n");
447 #ifndef MAEMO
448         menu_finish();
449 #endif
450         SysClose();
451         plat_finish();
452         exit(0);
453 }
454
455 int get_state_filename(char *buf, int size, int i) {
456         return get_gameid_filename(buf, size,
457                 "." STATES_DIR "%.32s-%.9s.%3.3d", i);
458 }
459
460 int emu_check_state(int slot)
461 {
462         char fname[MAXPATHLEN];
463         int ret;
464
465         ret = get_state_filename(fname, sizeof(fname), slot);
466         if (ret != 0)
467                 return ret;
468
469         return CheckState(fname);
470 }
471
472 int emu_save_state(int slot)
473 {
474         char fname[MAXPATHLEN];
475         int ret;
476
477         ret = get_state_filename(fname, sizeof(fname), slot);
478         if (ret != 0)
479                 return ret;
480
481         ret = SaveState(fname);
482         printf("* %s \"%s\" [%d]\n", ret == 0 ? "saved" : "failed to save", fname, slot);
483         return ret;
484 }
485
486 int emu_load_state(int slot)
487 {
488         char fname[MAXPATHLEN];
489         int ret;
490
491         ret = get_state_filename(fname, sizeof(fname), slot);
492         if (ret != 0)
493                 return ret;
494
495         return LoadState(fname);
496 }
497
498 void SysPrintf(const char *fmt, ...) {
499         va_list list;
500         char msg[512];
501
502         va_start(list, fmt);
503         vsprintf(msg, fmt, list);
504         va_end(list);
505
506         fprintf(emuLog, "%s", msg);
507 }
508
509 void SysMessage(const char *fmt, ...) {
510         va_list list;
511         char msg[512];
512
513         va_start(list, fmt);
514         vsprintf(msg, fmt, list);
515         va_end(list);
516
517         if (msg[strlen(msg) - 1] == '\n')
518                 msg[strlen(msg) - 1] = 0;
519
520         fprintf(stderr, "%s\n", msg);
521 }
522
523 static void SignalExit(int sig) {
524         ClosePlugins();
525         OnFile_Exit();
526 }
527
528 #define PARSEPATH(dst, src) \
529         ptr = src + strlen(src); \
530         while (*ptr != '\\' && ptr != src) ptr--; \
531         if (ptr != src) { \
532                 strcpy(dst, ptr+1); \
533         }
534
535 static int _OpenPlugins(void) {
536         int ret;
537
538         signal(SIGINT, SignalExit);
539         signal(SIGPIPE, SignalExit);
540
541         GPU_clearDynarec(clearDynarec);
542
543         ret = CDR_open();
544         if (ret < 0) { SysMessage(_("Error opening CD-ROM plugin!")); return -1; }
545         ret = SPU_open();
546         if (ret < 0) { SysMessage(_("Error opening SPU plugin!")); return -1; }
547         SPU_registerCallback(SPUirq);
548         // pcsx-rearmed: we handle gpu elsewhere
549         //ret = GPU_open(&gpuDisp, "PCSX", NULL);
550         //if (ret < 0) { SysMessage(_("Error opening GPU plugin!")); return -1; }
551         ret = PAD1_open(&gpuDisp);
552         if (ret < 0) { SysMessage(_("Error opening Controller 1 plugin!")); return -1; }
553         ret = PAD2_open(&gpuDisp);
554         if (ret < 0) { SysMessage(_("Error opening Controller 2 plugin!")); return -1; }
555
556         if (Config.UseNet && !NetOpened) {
557                 netInfo info;
558                 char path[MAXPATHLEN];
559                 char dotdir[MAXPATHLEN];
560
561                 MAKE_PATH(dotdir, "/.pcsx/plugins/", NULL);
562
563                 strcpy(info.EmuName, "PCSX " PACKAGE_VERSION);
564                 strncpy(info.CdromID, CdromId, 9);
565                 strncpy(info.CdromLabel, CdromLabel, 9);
566                 info.psxMem = psxM;
567                 info.GPU_showScreenPic = GPU_showScreenPic;
568                 info.GPU_displayText = GPU_displayText;
569                 info.GPU_showScreenPic = GPU_showScreenPic;
570                 info.PAD_setSensitive = PAD1_setSensitive;
571                 sprintf(path, "%s%s", Config.BiosDir, Config.Bios);
572                 strcpy(info.BIOSpath, path);
573                 strcpy(info.MCD1path, Config.Mcd1);
574                 strcpy(info.MCD2path, Config.Mcd2);
575                 sprintf(path, "%s%s", dotdir, Config.Gpu);
576                 strcpy(info.GPUpath, path);
577                 sprintf(path, "%s%s", dotdir, Config.Spu);
578                 strcpy(info.SPUpath, path);
579                 sprintf(path, "%s%s", dotdir, Config.Cdr);
580                 strcpy(info.CDRpath, path);
581                 NET_setInfo(&info);
582
583                 ret = NET_open(&gpuDisp);
584                 if (ret < 0) {
585                         if (ret == -2) {
586                                 // -2 is returned when something in the info
587                                 // changed and needs to be synced
588                                 char *ptr;
589
590                                 PARSEPATH(Config.Bios, info.BIOSpath);
591                                 PARSEPATH(Config.Gpu,  info.GPUpath);
592                                 PARSEPATH(Config.Spu,  info.SPUpath);
593                                 PARSEPATH(Config.Cdr,  info.CDRpath);
594
595                                 strcpy(Config.Mcd1, info.MCD1path);
596                                 strcpy(Config.Mcd2, info.MCD2path);
597                                 return -2;
598                         } else {
599                                 Config.UseNet = FALSE;
600                         }
601                 } else {
602                         if (NET_queryPlayer() == 1) {
603                                 if (SendPcsxInfo() == -1) Config.UseNet = FALSE;
604                         } else {
605                                 if (RecvPcsxInfo() == -1) Config.UseNet = FALSE;
606                         }
607                 }
608                 NetOpened = TRUE;
609         } else if (Config.UseNet) {
610                 NET_resume();
611         }
612
613         return 0;
614 }
615
616 int OpenPlugins() {
617         int ret;
618
619         while ((ret = _OpenPlugins()) == -2) {
620                 ReleasePlugins();
621                 LoadMcds(Config.Mcd1, Config.Mcd2);
622                 if (LoadPlugins() == -1) return -1;
623         }
624         return ret;
625 }
626
627 void ClosePlugins() {
628         int ret;
629
630         signal(SIGINT, SIG_DFL);
631         signal(SIGPIPE, SIG_DFL);
632         ret = CDR_close();
633         if (ret < 0) { SysMessage(_("Error closing CD-ROM plugin!")); return; }
634         ret = SPU_close();
635         if (ret < 0) { SysMessage(_("Error closing SPU plugin!")); return; }
636         ret = PAD1_close();
637         if (ret < 0) { SysMessage(_("Error closing Controller 1 Plugin!")); return; }
638         ret = PAD2_close();
639         if (ret < 0) { SysMessage(_("Error closing Controller 2 plugin!")); return; }
640         // pcsx-rearmed: we handle gpu elsewhere
641         //ret = GPU_close();
642         //if (ret < 0) { SysMessage(_("Error closing GPU plugin!")); return; }
643
644         if (Config.UseNet) {
645                 NET_pause();
646         }
647 }
648
649 /* we hook statically linked plugins here */
650 static const char *builtin_plugins[] = {
651         "builtin_gpu", "builtin_spu", "builtin_cdr", "builtin_pad",
652         "builtin_cdrcimg",
653 };
654
655 static const int builtin_plugin_ids[] = {
656         PLUGIN_GPU, PLUGIN_SPU, PLUGIN_CDR, PLUGIN_PAD,
657         PLUGIN_CDRCIMG,
658 };
659
660 void *SysLoadLibrary(const char *lib) {
661         const char *tmp = strrchr(lib, '/');
662         void *ret;
663         int i;
664
665         printf("plugin: %s\n", lib);
666
667         if (tmp != NULL) {
668                 tmp++;
669                 for (i = 0; i < ARRAY_SIZE(builtin_plugins); i++)
670                         if (strcmp(tmp, builtin_plugins[i]) == 0)
671                                 return (void *)(long)(PLUGIN_DL_BASE + builtin_plugin_ids[i]);
672         }
673
674 #if defined(__x86_64__) || defined(__i386__)
675         // convenience hack
676         char name[MAXPATHLEN];
677         snprintf(name, sizeof(name), "%s.x86", lib);
678         lib = name;
679 #endif
680
681         ret = dlopen(lib, RTLD_NOW);
682         if (ret == NULL)
683                 fprintf(stderr, "dlopen: %s\n", dlerror());
684         return ret;
685 }
686
687 void *SysLoadSym(void *lib, const char *sym) {
688         unsigned int plugid = (unsigned int)(long)lib;
689
690         if (PLUGIN_DL_BASE <= plugid && plugid < PLUGIN_DL_BASE + ARRAY_SIZE(builtin_plugins))
691                 return plugin_link(plugid - PLUGIN_DL_BASE, sym);
692
693         return dlsym(lib, sym);
694 }
695
696 const char *SysLibError() {
697         return dlerror();
698 }
699
700 void SysCloseLibrary(void *lib) {
701         unsigned int plugid = (unsigned int)(long)lib;
702
703         if (PLUGIN_DL_BASE <= plugid && plugid < PLUGIN_DL_BASE + ARRAY_SIZE(builtin_plugins))
704                 return;
705
706         dlclose(lib);
707 }
708