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