frontend cleanup
[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
17 #include "main.h"
18 #include "plugin.h"
19 #include "pcnt.h"
20 #include "menu.h"
21 #include "../libpcsxcore/misc.h"
22 #include "../plugins/cdrcimg/cdrcimg.h"
23 #include "common/plat.h"
24 #include "common/input.h"
25
26 int ready_to_go;
27 unsigned long gpuDisp;
28 char cfgfile_basename[MAXPATHLEN];
29 static char *(*real_getenv)(const char *name);
30
31 static void make_path(char *buf, size_t size, const char *dir, const char *fname)
32 {
33         if (fname)
34                 snprintf(buf, size, ".%s%s", dir, fname);
35         else
36                 snprintf(buf, size, ".%s", dir);
37 }
38 #define MAKE_PATH(buf, dir, fname) \
39         make_path(buf, sizeof(buf), dir, fname)
40
41 static void create_profile_dir(const char *directory) {
42         char path[MAXPATHLEN];
43
44         MAKE_PATH(path, directory, NULL);
45         mkdir(path, S_IRWXU | S_IRWXG);
46 }
47
48 static void CheckSubDir() {
49         // make sure that ~/.pcsx exists
50         create_profile_dir(PCSX_DOT_DIR);
51
52         create_profile_dir(BIOS_DIR);
53         create_profile_dir(MEMCARD_DIR);
54         create_profile_dir(STATES_DIR);
55         create_profile_dir(PLUGINS_DIR);
56         create_profile_dir(PLUGINS_CFG_DIR);
57         create_profile_dir(CHEATS_DIR);
58         create_profile_dir(PATCHES_DIR);
59         create_profile_dir(PCSX_DOT_DIR "cfg");
60 }
61
62 void set_cd_image(const char *fname)
63 {
64         const char *ext;
65         int len;
66         
67         len = strlen(fname);
68         ext = fname;
69         if (len > 2)
70                 ext = fname + len - 2;
71
72         if (strcasecmp(ext, ".z") == 0) {
73                 SetIsoFile(NULL);
74                 cdrcimg_set_fname(fname);
75                 strcpy(Config.Cdr, "builtin_cdrcimg");
76         } else {
77                 SetIsoFile(fname);
78                 strcpy(Config.Cdr, "builtin_cdr");
79         }
80 }
81
82 int main(int argc, char *argv[])
83 {
84         char file[MAXPATHLEN] = "";
85         char path[MAXPATHLEN];
86         const char *cdfile = NULL;
87         int loadst = 0;
88         void *tmp;
89         int i;
90
91         tmp = dlopen("/lib/libdl.so.2", RTLD_LAZY);
92         if (tmp == NULL)
93                 tmp = dlopen("/lib32/libdl.so.2", RTLD_LAZY);
94         if (tmp != NULL)
95                 real_getenv = dlsym(tmp, "getenv");
96         if (real_getenv == NULL) {
97                 fprintf(stderr, "%s\n", dlerror());
98                 return 1;
99         }
100         dlclose(tmp);
101
102         // what is the name of the config file?
103         // it may be redefined by -cfg on the command line
104         strcpy(cfgfile_basename, "pcsx.cfg");
105
106         emuLog = stdout;
107         SetIsoFile(NULL);
108
109         // read command line options
110         for (i = 1; i < argc; i++) {
111                      if (!strcmp(argv[i], "-psxout")) Config.PsxOut = 1;
112                 else if (!strcmp(argv[i], "-load")) loadst = atol(argv[++i]);
113                 else if (!strcmp(argv[i], "-cfg")) {
114                         if (i+1 >= argc) break;
115                         strncpy(cfgfile_basename, argv[++i], MAXPATHLEN-100);   /* TODO buffer overruns */
116                         printf("Using config file %s.\n", cfgfile_basename);
117                 }
118                 else if (!strcmp(argv[i], "-cdfile")) {
119                         char isofilename[MAXPATHLEN];
120
121                         if (i+1 >= argc) break;
122                         strncpy(isofilename, argv[++i], MAXPATHLEN);
123                         if (isofilename[0] != '/') {
124                                 getcwd(path, MAXPATHLEN);
125                                 if (strlen(path) + strlen(isofilename) + 1 < MAXPATHLEN) {
126                                         strcat(path, "/");
127                                         strcat(path, isofilename);
128                                         strcpy(isofilename, path);
129                                 } else
130                                         isofilename[0] = 0;
131                         }
132
133                         cdfile = isofilename;
134                 }
135                 else if (!strcmp(argv[i], "-h") ||
136                          !strcmp(argv[i], "-help") ||
137                          !strcmp(argv[i], "--help")) {
138                          printf(PACKAGE_NAME " " PACKAGE_VERSION "\n");
139                          printf("%s\n", _(
140                                                         " pcsx [options] [file]\n"
141                                                         "\toptions:\n"
142                                                         "\t-cdfile FILE\tRuns a CD image file\n"
143                                                         "\t-nogui\t\tDon't open the GTK GUI\n"
144                                                         "\t-cfg FILE\tLoads desired configuration file (default: ~/.pcsx/pcsx.cfg)\n"
145                                                         "\t-psxout\t\tEnable PSX output\n"
146                                                         "\t-load STATENUM\tLoads savestate STATENUM (1-5)\n"
147                                                         "\t-h -help\tDisplay this message\n"
148                                                         "\tfile\t\tLoads file\n"));
149                          return 0;
150                 } else {
151                         strncpy(file, argv[i], MAXPATHLEN);
152                         if (file[0] != '/') {
153                                 getcwd(path, MAXPATHLEN);
154                                 if (strlen(path) + strlen(file) + 1 < MAXPATHLEN) {
155                                         strcat(path, "/");
156                                         strcat(path, file);
157                                         strcpy(file, path);
158                                 } else
159                                         file[0] = 0;
160                         }
161                 }
162         }
163
164         memset(&Config, 0, sizeof(PcsxConfig));
165         strcpy(Config.Net, "Disabled");
166
167         CheckSubDir();
168
169         MAKE_PATH(Config.Mcd1, MEMCARD_DIR, "card1.mcd");
170         MAKE_PATH(Config.Mcd2, MEMCARD_DIR, "card2.mcd");
171         strcpy(Config.Bios, "HLE");
172         strcpy(Config.BiosDir, "./");
173
174         strcpy(Config.PluginsDir, "plugins");
175         strcpy(Config.Gpu, "builtin_gpu");
176         strcpy(Config.Spu, "builtin_spu");
177         strcpy(Config.Cdr, "builtin_cdr");
178         strcpy(Config.Pad1, "builtin_pad");
179         strcpy(Config.Pad2, "builtin_pad");
180         Config.PsxAuto = 1;
181
182         snprintf(Config.PatchesDir, sizeof(Config.PatchesDir), "." PATCHES_DIR);
183 /*
184         // switch to plugin dotdir
185         // this lets plugins work without modification!
186         gchar *plugin_default_dir = g_build_filename(getenv("HOME"), PLUGINS_DIR, NULL);
187         chdir(plugin_default_dir);
188         g_free(plugin_default_dir);
189 */
190
191         if (cdfile)
192                 set_cd_image(cdfile);
193
194         if (SysInit() == -1)
195                 return 1;
196
197         // frontend stuff
198         in_init();
199         in_probe();
200         plat_init();
201         menu_init();
202
203         if (LoadPlugins() == -1) {
204                 SysMessage("Failed loading plugins!");
205                 return 1;
206         }
207         pcnt_hook_plugins();
208
209         if (OpenPlugins() == -1) {
210                 return 1;
211         }
212         plugin_call_rearmed_cbs();
213
214         CheckCdrom();
215         SysReset();
216
217         if (file[0] != '\0') {
218                 if (Load(file) != -1)
219                         ready_to_go = 1;
220         } else {
221                 if (cdfile) {
222                         if (LoadCdrom() == -1) {
223                                 ClosePlugins();
224                                 printf(_("Could not load CD-ROM!\n"));
225                                 return -1;
226                         }
227                         ready_to_go = 1;
228                 }
229         }
230
231         // If a state has been specified, then load that
232         if (loadst) {
233                 char state_filename[MAXPATHLEN];
234                 int ret = get_state_filename(state_filename, sizeof(state_filename), loadst - 1);
235                 if (ret == 0)
236                         ret = LoadState(state_filename);
237                 printf("%s state %s\n", ret ? "failed to load" : "loaded", state_filename);
238         }
239
240         if (ready_to_go)
241                 menu_prepare_emu();
242         else
243                 menu_loop();
244
245         while (1)
246         {
247                 psxCpu->Execute();
248                 menu_loop();
249         }
250
251         return 0;
252 }
253
254 int SysInit() {
255         if (EmuInit() == -1) {
256                 printf("PSX emulator couldn't be initialized.\n");
257                 return -1;
258         }
259
260         LoadMcds(Config.Mcd1, Config.Mcd2);     /* TODO Do we need to have this here, or in the calling main() function?? */
261
262         if (Config.Debug) {
263                 StartDebugger();
264         }
265
266         return 0;
267 }
268
269 void SysRunGui() {
270         printf("SysRunGui\n");
271 }
272
273 void StartGui() {
274         printf("StartGui\n");
275 }
276
277 void SysReset() {
278         EmuReset();
279
280         // hmh core forgets this
281         CDR_stop();
282 }
283
284 void SysClose() {
285         EmuShutdown();
286         ReleasePlugins();
287
288         StopDebugger();
289
290         if (emuLog != NULL) fclose(emuLog);
291 }
292
293 void SysUpdate() {
294 }
295
296 void OnFile_Exit() {
297         printf("OnFile_Exit\n");
298         menu_finish();
299         plat_finish();
300         SysClose();
301         exit(0);
302 }
303
304 int get_state_filename(char *buf, int size, int i) {
305         char trimlabel[33];
306         int j;
307
308         strncpy(trimlabel, CdromLabel, 32);
309         trimlabel[32] = 0;
310         for (j = 31; j >= 0; j--)
311                 if (trimlabel[j] == ' ')
312                         trimlabel[j] = 0;
313                 else
314                         continue;
315
316         snprintf(buf, size, "." STATES_DIR "%.32s-%.9s.%3.3d",
317                 trimlabel, CdromId, i);
318
319         return 0;
320 }
321
322 void SysPrintf(const char *fmt, ...) {
323         va_list list;
324         char msg[512];
325
326         va_start(list, fmt);
327         vsprintf(msg, fmt, list);
328         va_end(list);
329
330         fprintf(emuLog, "%s", msg);
331 }
332
333 void SysMessage(const char *fmt, ...) {
334         va_list list;
335         char msg[512];
336
337         va_start(list, fmt);
338         vsprintf(msg, fmt, list);
339         va_end(list);
340
341         if (msg[strlen(msg) - 1] == '\n')
342                 msg[strlen(msg) - 1] = 0;
343
344         fprintf(stderr, "%s\n", msg);
345 }
346
347 static void SignalExit(int sig) {
348         ClosePlugins();
349         OnFile_Exit();
350 }
351
352 #define PARSEPATH(dst, src) \
353         ptr = src + strlen(src); \
354         while (*ptr != '\\' && ptr != src) ptr--; \
355         if (ptr != src) { \
356                 strcpy(dst, ptr+1); \
357         }
358
359 static int _OpenPlugins(void) {
360         int ret;
361
362         signal(SIGINT, SignalExit);
363         signal(SIGPIPE, SignalExit);
364
365         GPU_clearDynarec(clearDynarec);
366
367         ret = CDR_open();
368         if (ret < 0) { SysMessage(_("Error opening CD-ROM plugin!")); return -1; }
369         ret = SPU_open();
370         if (ret < 0) { SysMessage(_("Error opening SPU plugin!")); return -1; }
371         SPU_registerCallback(SPUirq);
372         // pcsx-rearmed: we handle gpu elsewhere
373         //ret = GPU_open(&gpuDisp, "PCSX", NULL);
374         //if (ret < 0) { SysMessage(_("Error opening GPU plugin!")); return -1; }
375         ret = PAD1_open(&gpuDisp);
376         if (ret < 0) { SysMessage(_("Error opening Controller 1 plugin!")); return -1; }
377         ret = PAD2_open(&gpuDisp);
378         if (ret < 0) { SysMessage(_("Error opening Controller 2 plugin!")); return -1; }
379
380         if (Config.UseNet && !NetOpened) {
381                 netInfo info;
382                 char path[MAXPATHLEN];
383                 char dotdir[MAXPATHLEN];
384
385                 MAKE_PATH(dotdir, "/.pcsx/plugins/", NULL);
386
387                 strcpy(info.EmuName, "PCSX " PACKAGE_VERSION);
388                 strncpy(info.CdromID, CdromId, 9);
389                 strncpy(info.CdromLabel, CdromLabel, 9);
390                 info.psxMem = psxM;
391                 info.GPU_showScreenPic = GPU_showScreenPic;
392                 info.GPU_displayText = GPU_displayText;
393                 info.GPU_showScreenPic = GPU_showScreenPic;
394                 info.PAD_setSensitive = PAD1_setSensitive;
395                 sprintf(path, "%s%s", Config.BiosDir, Config.Bios);
396                 strcpy(info.BIOSpath, path);
397                 strcpy(info.MCD1path, Config.Mcd1);
398                 strcpy(info.MCD2path, Config.Mcd2);
399                 sprintf(path, "%s%s", dotdir, Config.Gpu);
400                 strcpy(info.GPUpath, path);
401                 sprintf(path, "%s%s", dotdir, Config.Spu);
402                 strcpy(info.SPUpath, path);
403                 sprintf(path, "%s%s", dotdir, Config.Cdr);
404                 strcpy(info.CDRpath, path);
405                 NET_setInfo(&info);
406
407                 ret = NET_open(&gpuDisp);
408                 if (ret < 0) {
409                         if (ret == -2) {
410                                 // -2 is returned when something in the info
411                                 // changed and needs to be synced
412                                 char *ptr;
413
414                                 PARSEPATH(Config.Bios, info.BIOSpath);
415                                 PARSEPATH(Config.Gpu,  info.GPUpath);
416                                 PARSEPATH(Config.Spu,  info.SPUpath);
417                                 PARSEPATH(Config.Cdr,  info.CDRpath);
418
419                                 strcpy(Config.Mcd1, info.MCD1path);
420                                 strcpy(Config.Mcd2, info.MCD2path);
421                                 return -2;
422                         } else {
423                                 Config.UseNet = FALSE;
424                         }
425                 } else {
426                         if (NET_queryPlayer() == 1) {
427                                 if (SendPcsxInfo() == -1) Config.UseNet = FALSE;
428                         } else {
429                                 if (RecvPcsxInfo() == -1) Config.UseNet = FALSE;
430                         }
431                 }
432                 NetOpened = TRUE;
433         } else if (Config.UseNet) {
434                 NET_resume();
435         }
436
437         return 0;
438 }
439
440 int OpenPlugins() {
441         int ret;
442
443         while ((ret = _OpenPlugins()) == -2) {
444                 ReleasePlugins();
445                 LoadMcds(Config.Mcd1, Config.Mcd2);
446                 if (LoadPlugins() == -1) return -1;
447         }
448         return ret;
449 }
450
451 void ClosePlugins() {
452         int ret;
453
454         signal(SIGINT, SIG_DFL);
455         signal(SIGPIPE, SIG_DFL);
456         ret = CDR_close();
457         if (ret < 0) { SysMessage(_("Error closing CD-ROM plugin!")); return; }
458         ret = SPU_close();
459         if (ret < 0) { SysMessage(_("Error closing SPU plugin!")); return; }
460         ret = PAD1_close();
461         if (ret < 0) { SysMessage(_("Error closing Controller 1 Plugin!")); return; }
462         ret = PAD2_close();
463         if (ret < 0) { SysMessage(_("Error closing Controller 2 plugin!")); return; }
464         // pcsx-rearmed: we handle gpu elsewhere
465         //ret = GPU_close();
466         //if (ret < 0) { SysMessage(_("Error closing GPU plugin!")); return; }
467
468         if (Config.UseNet) {
469                 NET_pause();
470         }
471 }
472
473 #if 1
474 /* this is to avoid having to hack every plugin to stop using $HOME */
475 char *getenv(const char *name)
476 {
477         static char ret[8] = ".";
478
479         if (name && strcmp(name, "HOME") == 0 &&
480                         ((int)name >> 28) == 0) // HACK: let libs find home
481                 return ret;
482
483         return real_getenv(name);
484 }
485 #endif
486
487 /* we hook statically linked plugins here */
488 static const char *builtin_plugins[] = {
489         "builtin_gpu", "builtin_spu", "builtin_cdr", "builtin_pad",
490         "builtin_cdrcimg",
491 };
492
493 static const int builtin_plugin_ids[] = {
494         PLUGIN_GPU, PLUGIN_SPU, PLUGIN_CDR, PLUGIN_PAD,
495         PLUGIN_CDRCIMG,
496 };
497
498 void *SysLoadLibrary(const char *lib) {
499         const char *tmp = strrchr(lib, '/');
500         void *ret;
501         int i;
502
503         printf("plugin: %s\n", lib);
504
505         if (tmp != NULL) {
506                 tmp++;
507                 for (i = 0; i < ARRAY_SIZE(builtin_plugins); i++)
508                         if (strcmp(tmp, builtin_plugins[i]) == 0)
509                                 return (void *)(long)(PLUGIN_DL_BASE + builtin_plugin_ids[i]);
510         }
511
512 #if defined(__x86_64__) || defined(__i386__)
513         // convenience hack
514         char name[MAXPATHLEN];
515         snprintf(name, sizeof(name), "%s.x86", lib);
516         lib = name;
517 #endif
518
519         ret = dlopen(lib, RTLD_NOW);
520         if (ret == NULL)
521                 fprintf(stderr, "dlopen: %s\n", dlerror());
522         return ret;
523 }
524
525 void *SysLoadSym(void *lib, const char *sym) {
526         unsigned int plugid = (unsigned int)(long)lib;
527
528         if (PLUGIN_DL_BASE <= plugid && plugid < PLUGIN_DL_BASE + ARRAY_SIZE(builtin_plugins))
529                 return plugin_link(plugid - PLUGIN_DL_BASE, sym);
530
531         return dlsym(lib, sym);
532 }
533
534 const char *SysLibError() {
535         return dlerror();
536 }
537
538 void SysCloseLibrary(void *lib) {
539         unsigned int plugid = (unsigned int)(long)lib;
540
541         if (PLUGIN_DL_BASE <= plugid && plugid < PLUGIN_DL_BASE + ARRAY_SIZE(builtin_plugins))
542                 return;
543
544         dlclose(lib);
545 }
546