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