e7d20ffef064d0fcffc00b03017c399c91e5061f
[pcsx_rearmed.git] / frontend / menu.c
1 /*
2  * (C) GraÅžvydas "notaz" Ignotas, 2010-2011
3  *
4  * This work is licensed under the terms of any of these licenses
5  * (at your option):
6  *  - GNU GPL, version 2 or later.
7  *  - GNU LGPL, version 2.1 or later.
8  * See the COPYING file in the top-level directory.
9  */
10
11 #include <stdio.h>
12 #include <string.h>
13 #include <errno.h>
14 #include <dlfcn.h>
15 #include <zlib.h>
16
17 #include "main.h"
18 #include "menu.h"
19 #include "config.h"
20 #include "plugin.h"
21 #include "plugin_lib.h"
22 #include "omap.h"
23 #include "common/plat.h"
24 #include "../libpcsxcore/misc.h"
25 #include "../libpcsxcore/psemu_plugin_defs.h"
26 #include "revision.h"
27
28 #define MENU_X2 1
29 #define array_size(x) (sizeof(x) / sizeof(x[0]))
30
31 typedef enum
32 {
33         MA_NONE = 1,
34         MA_MAIN_RESUME_GAME,
35         MA_MAIN_SAVE_STATE,
36         MA_MAIN_LOAD_STATE,
37         MA_MAIN_RESET_GAME,
38         MA_MAIN_LOAD_ROM,
39         MA_MAIN_RUN_BIOS,
40         MA_MAIN_CONTROLS,
41         MA_MAIN_CREDITS,
42         MA_MAIN_EXIT,
43         MA_CTRL_PLAYER1,
44         MA_CTRL_PLAYER2,
45         MA_CTRL_EMU,
46         MA_CTRL_DEV_FIRST,
47         MA_CTRL_DEV_NEXT,
48         MA_CTRL_DONE,
49         MA_OPT_SAVECFG,
50         MA_OPT_SAVECFG_GAME,
51         MA_OPT_CPU_CLOCKS,
52         MA_OPT_FILTERING,
53 } menu_id;
54
55 enum {
56         SCALE_1_1,
57         SCALE_4_3,
58         SCALE_FULLSCREEN,
59         SCALE_CUSTOM,
60 };
61
62 static int last_psx_w, last_psx_h, last_psx_bpp;
63 static int scaling, filter, state_slot, cpu_clock, cpu_clock_st;
64 static char rom_fname_reload[MAXPATHLEN];
65 static char last_selected_fname[MAXPATHLEN];
66 static int region, in_type_sel;
67 int g_opts;
68
69 // from softgpu plugin
70 extern int iUseDither;
71 extern int UseFrameSkip;
72 extern uint32_t dwActFixes;
73 extern float fFrameRateHz;
74 extern int dwFrameRateTicks;
75
76 // sound plugin
77 extern int iUseReverb;
78 extern int iUseInterpolation;
79 extern int iXAPitch;
80 extern int iSPUIRQWait;
81 extern int iUseTimer;
82
83 static const char *bioses[24];
84 static const char *gpu_plugins[16];
85 static const char *spu_plugins[16];
86 static int bios_sel, gpu_plugsel, spu_plugsel;
87
88
89 static int min(int x, int y) { return x < y ? x : y; }
90 static int max(int x, int y) { return x > y ? x : y; }
91
92 void emu_make_path(char *buff, const char *end, int size)
93 {
94         int pos, end_len;
95
96         end_len = strlen(end);
97         pos = plat_get_root_dir(buff, size);
98         strncpy(buff + pos, end, size - pos);
99         buff[size - 1] = 0;
100         if (pos + end_len > size - 1)
101                 printf("Warning: path truncated: %s\n", buff);
102 }
103
104 static int emu_check_save_file(int slot)
105 {
106         char fname[MAXPATHLEN];
107         int ret;
108
109         ret = get_state_filename(fname, sizeof(fname), slot);
110         if (ret != 0)
111                 return 0;
112
113         ret = CheckState(fname);
114         return ret == 0 ? 1 : 0;
115 }
116
117 static int emu_save_load_game(int load, int sram)
118 {
119         char fname[MAXPATHLEN];
120         int ret;
121
122         ret = get_state_filename(fname, sizeof(fname), state_slot);
123         if (ret != 0)
124                 return 0;
125
126         if (load) {
127                 ret = LoadState(fname);
128
129                 // reflect hle/bios mode from savestate
130                 if (Config.HLE)
131                         bios_sel = 0;
132                 else if (bios_sel == 0 && bioses[1] != NULL)
133                         // XXX: maybe find the right bios instead
134                         bios_sel = 1;
135         }
136         else
137                 ret = SaveState(fname);
138
139         return ret;
140 }
141
142 // propagate menu settings to the emu vars
143 static void menu_sync_config(void)
144 {
145         Config.PsxAuto = 1;
146         if (region > 0) {
147                 Config.PsxAuto = 0;
148                 Config.PsxType = region - 1;
149         }
150         in_type = in_type_sel ? PSE_PAD_TYPE_ANALOGPAD : PSE_PAD_TYPE_STANDARD;
151
152         pl_frame_interval = Config.PsxType ? 20000 : 16667;
153         // used by P.E.Op.S. frameskip code
154         fFrameRateHz = Config.PsxType ? 50.0f : 59.94f;
155         dwFrameRateTicks = (100000*100 / (unsigned long)(fFrameRateHz*100));
156 }
157
158 static void menu_set_defconfig(void)
159 {
160         g_opts = 0;
161         scaling = SCALE_4_3;
162
163         region = 0;
164         in_type_sel = 0;
165         Config.Xa = Config.Cdda = Config.Sio =
166         Config.SpuIrq = Config.RCntFix = Config.VSyncWA = 0;
167
168         iUseDither = 0;
169         UseFrameSkip = 1;
170         dwActFixes = 1<<7;
171
172         iUseReverb = 2;
173         iUseInterpolation = 1;
174         iXAPitch = iSPUIRQWait = 0;
175         iUseTimer = 2;
176
177         menu_sync_config();
178 }
179
180 #define CE_CONFIG_STR(val) \
181         { #val, 0, Config.val }
182
183 #define CE_CONFIG_VAL(val) \
184         { #val, sizeof(Config.val), &Config.val }
185
186 #define CE_STR(val) \
187         { #val, 0, val }
188
189 #define CE_INTVAL(val) \
190         { #val, sizeof(val), &val }
191
192 static const struct {
193         const char *name;
194         size_t len;
195         void *val;
196 } config_data[] = {
197         CE_CONFIG_STR(Bios),
198         CE_CONFIG_STR(Gpu),
199         CE_CONFIG_STR(Spu),
200 //      CE_CONFIG_STR(Cdr),
201         CE_CONFIG_VAL(Xa),
202         CE_CONFIG_VAL(Sio),
203         CE_CONFIG_VAL(Mdec),
204         CE_CONFIG_VAL(Cdda),
205         CE_CONFIG_VAL(Debug),
206         CE_CONFIG_VAL(PsxOut),
207         CE_CONFIG_VAL(SpuIrq),
208         CE_CONFIG_VAL(RCntFix),
209         CE_CONFIG_VAL(VSyncWA),
210         CE_CONFIG_VAL(Cpu),
211         CE_INTVAL(region),
212         CE_INTVAL(scaling),
213         CE_INTVAL(g_layer_x),
214         CE_INTVAL(g_layer_y),
215         CE_INTVAL(g_layer_w),
216         CE_INTVAL(g_layer_h),
217         CE_INTVAL(filter),
218         CE_INTVAL(state_slot),
219         CE_INTVAL(cpu_clock),
220         CE_INTVAL(g_opts),
221         CE_INTVAL(in_type_sel),
222         CE_INTVAL(iUseDither),
223         CE_INTVAL(UseFrameSkip),
224         CE_INTVAL(dwActFixes),
225         CE_INTVAL(iUseReverb),
226         CE_INTVAL(iUseInterpolation),
227         CE_INTVAL(iXAPitch),
228         CE_INTVAL(iSPUIRQWait),
229         CE_INTVAL(iUseTimer),
230 };
231
232 static char *get_cd_label(void)
233 {
234         static char trimlabel[33];
235         int j;
236
237         strncpy(trimlabel, CdromLabel, 32);
238         trimlabel[32] = 0;
239         for (j = 31; j >= 0; j--)
240                 if (trimlabel[j] == ' ')
241                         trimlabel[j] = 0;
242
243         return trimlabel;
244 }
245
246 static void make_cfg_fname(char *buf, size_t size, int is_game)
247 {
248         if (is_game)
249                 snprintf(buf, size, "." PCSX_DOT_DIR "cfg/%.32s-%.9s.cfg", get_cd_label(), CdromId);
250         else
251                 snprintf(buf, size, "." PCSX_DOT_DIR "%s", cfgfile_basename);
252 }
253
254 static void keys_write_all(FILE *f);
255
256 static int menu_write_config(int is_game)
257 {
258         char cfgfile[MAXPATHLEN];
259         FILE *f;
260         int i;
261
262         make_cfg_fname(cfgfile, sizeof(cfgfile), is_game);
263         f = fopen(cfgfile, "w");
264         if (f == NULL) {
265                 printf("menu_write_config: failed to open: %s\n", cfgfile);
266                 return -1;
267         }
268
269         for (i = 0; i < ARRAY_SIZE(config_data); i++) {
270                 fprintf(f, "%s = ", config_data[i].name);
271                 switch (config_data[i].len) {
272                 case 0:
273                         fprintf(f, "%s\n", (char *)config_data[i].val);
274                         break;
275                 case 1:
276                         fprintf(f, "%x\n", *(u8 *)config_data[i].val);
277                         break;
278                 case 2:
279                         fprintf(f, "%x\n", *(u16 *)config_data[i].val);
280                         break;
281                 case 4:
282                         fprintf(f, "%x\n", *(u32 *)config_data[i].val);
283                         break;
284                 default:
285                         printf("menu_write_config: unhandled len %d for %s\n",
286                                  config_data[i].len, config_data[i].name);
287                         break;
288                 }
289         }
290
291         if (!is_game)
292                 fprintf(f, "lastcdimg = %s\n", last_selected_fname);
293
294         keys_write_all(f);
295         fclose(f);
296
297         return 0;
298 }
299
300 static void parse_str_val(char *cval, const char *src)
301 {
302         char *tmp;
303         strncpy(cval, src, MAXPATHLEN);
304         cval[MAXPATHLEN - 1] = 0;
305         tmp = strchr(cval, '\n');
306         if (tmp == NULL)
307                 tmp = strchr(cval, '\r');
308         if (tmp != NULL)
309                 *tmp = 0;
310 }
311
312 static void keys_load_all(const char *cfg);
313
314 static int menu_load_config(int is_game)
315 {
316         char cfgfile[MAXPATHLEN];
317         int i, ret = -1;
318         long size;
319         char *cfg;
320         FILE *f;
321
322         make_cfg_fname(cfgfile, sizeof(cfgfile), is_game);
323         f = fopen(cfgfile, "r");
324         if (f == NULL) {
325                 printf("menu_load_config: failed to open: %s\n", cfgfile);
326                 return -1;
327         }
328
329         fseek(f, 0, SEEK_END);
330         size = ftell(f);
331         if (size <= 0) {
332                 printf("bad size %ld: %s\n", size, cfgfile);
333                 goto fail;
334         }
335
336         cfg = malloc(size + 1);
337         if (cfg == NULL)
338                 goto fail;
339
340         fseek(f, 0, SEEK_SET);
341         if (fread(cfg, 1, size, f) != size) {
342                 printf("failed to read: %s\n", cfgfile);
343                 goto fail_read;
344         }
345         cfg[size] = 0;
346
347         for (i = 0; i < ARRAY_SIZE(config_data); i++) {
348                 char *tmp, *tmp2;
349                 u32 val;
350
351                 tmp = strstr(cfg, config_data[i].name);
352                 if (tmp == NULL)
353                         continue;
354                 tmp += strlen(config_data[i].name);
355                 if (strncmp(tmp, " = ", 3) != 0)
356                         continue;
357                 tmp += 3;
358
359                 if (config_data[i].len == 0) {
360                         parse_str_val(config_data[i].val, tmp);
361                         continue;
362                 }
363
364                 tmp2 = NULL;
365                 val = strtoul(tmp, &tmp2, 16);
366                 if (tmp2 == NULL || tmp == tmp2)
367                         continue; // parse failed
368
369                 switch (config_data[i].len) {
370                 case 1:
371                         *(u8 *)config_data[i].val = val;
372                         break;
373                 case 2:
374                         *(u16 *)config_data[i].val = val;
375                         break;
376                 case 4:
377                         *(u32 *)config_data[i].val = val;
378                         break;
379                 default:
380                         printf("menu_load_config: unhandled len %d for %s\n",
381                                  config_data[i].len, config_data[i].name);
382                         break;
383                 }
384         }
385
386         if (!is_game) {
387                 char *tmp = strstr(cfg, "lastcdimg = ");
388                 if (tmp != NULL) {
389                         tmp += 12;
390                         parse_str_val(last_selected_fname, tmp);
391                 }
392         }
393
394         menu_sync_config();
395
396         // sync plugins
397         for (i = bios_sel = 0; bioses[i] != NULL; i++)
398                 if (strcmp(Config.Bios, bioses[i]) == 0)
399                         { bios_sel = i; break; }
400
401         for (i = gpu_plugsel = 0; gpu_plugins[i] != NULL; i++)
402                 if (strcmp(Config.Gpu, gpu_plugins[i]) == 0)
403                         { gpu_plugsel = i; break; }
404
405         for (i = spu_plugsel = 0; spu_plugins[i] != NULL; i++)
406                 if (strcmp(Config.Spu, spu_plugins[i]) == 0)
407                         { spu_plugsel = i; break; }
408
409         keys_load_all(cfg);
410         ret = 0;
411 fail_read:
412         free(cfg);
413 fail:
414         fclose(f);
415         return ret;
416 }
417
418 // rrrr rggg gggb bbbb
419 static unsigned short fname2color(const char *fname)
420 {
421         static const char *cdimg_exts[] = { ".bin", ".img", ".iso", ".cue", ".z", ".bz", ".znx", ".pbp" };
422         static const char *other_exts[] = { ".ccd", ".toc", ".mds", ".sub", ".table", ".index" };
423         const char *ext = strrchr(fname, '.');
424         int i;
425
426         if (ext == NULL)
427                 return 0xffff;
428         for (i = 0; i < array_size(cdimg_exts); i++)
429                 if (strcasecmp(ext, cdimg_exts[i]) == 0)
430                         return 0x7bff;
431         for (i = 0; i < array_size(other_exts); i++)
432                 if (strcasecmp(ext, other_exts[i]) == 0)
433                         return 0xa514;
434         return 0xffff;
435 }
436
437 static void draw_savestate_bg(int slot);
438
439 #define MENU_ALIGN_LEFT
440 #define menu_init menu_init_common
441 #include "common/menu.c"
442 #undef menu_init
443
444 // a bit of black magic here
445 static void draw_savestate_bg(int slot)
446 {
447         extern void bgr555_to_rgb565(void *dst, void *src, int bytes);
448         static const int psx_widths[8]  = { 256, 368, 320, 384, 512, 512, 640, 640 };
449         int x, y, w, h;
450         char fname[MAXPATHLEN];
451         GPUFreeze_t *gpu;
452         u16 *s, *d;
453         gzFile f;
454         int ret;
455         u32 tmp;
456
457         ret = get_state_filename(fname, sizeof(fname), slot);
458         if (ret != 0)
459                 return;
460
461         f = gzopen(fname, "rb");
462         if (f == NULL)
463                 return;
464
465         if (gzseek(f, 0x29933d, SEEK_SET) != 0x29933d) {
466                 fprintf(stderr, "gzseek failed\n");
467                 gzclose(f);
468                 return;
469         }
470
471         gpu = malloc(sizeof(*gpu));
472         if (gpu == NULL) {
473                 gzclose(f);
474                 return;
475         }
476
477         ret = gzread(f, gpu, sizeof(*gpu));
478         gzclose(f);
479         if (ret != sizeof(*gpu)) {
480                 fprintf(stderr, "gzread failed\n");
481                 goto out;
482         }
483
484         memcpy(g_menubg_ptr, g_menubg_src_ptr, g_menuscreen_w * g_menuscreen_h * 2);
485
486         if ((gpu->ulStatus & 0x800000) || (gpu->ulStatus & 0x200000))
487                 goto out; // disabled || 24bpp (NYET)
488
489         x = gpu->ulControl[5] & 0x3ff;
490         y = (gpu->ulControl[5] >> 10) & 0x1ff;
491         s = (u16 *)gpu->psxVRam + y * 1024 + (x & ~3);
492         w = psx_widths[(gpu->ulStatus >> 16) & 7];
493         tmp = gpu->ulControl[7];
494         h = ((tmp >> 10) & 0x3ff) - (tmp & 0x3ff);
495         if (gpu->ulStatus & 0x80000) // doubleheight
496                 h *= 2;
497
498         x = max(0, g_menuscreen_w - w) & ~3;
499         y = max(0, g_menuscreen_h / 2 - h / 2);
500         w = min(g_menuscreen_w, w);
501         h = min(g_menuscreen_h, h);
502         d = (u16 *)g_menubg_ptr + g_menuscreen_w * y + x;
503
504         for (; h > 0; h--, d += g_menuscreen_w, s += 1024)
505                 bgr555_to_rgb565(d, s, w * 2);
506
507 out:
508         free(gpu);
509 }
510
511 // ---------- pandora specific -----------
512
513 static const char pnd_script_base[] = "sudo -n /usr/pandora/scripts";
514 static char **pnd_filter_list;
515
516 static int get_cpu_clock(void)
517 {
518         FILE *f;
519         int ret = 0;
520         f = fopen("/proc/pandora/cpu_mhz_max", "r");
521         if (f) {
522                 fscanf(f, "%d", &ret);
523                 fclose(f);
524         }
525         return ret;
526 }
527
528 static void apply_cpu_clock(void)
529 {
530         char buf[128];
531
532         if (cpu_clock != 0 && cpu_clock != get_cpu_clock()) {
533                 snprintf(buf, sizeof(buf), "unset DISPLAY; echo y | %s/op_cpuspeed.sh %d",
534                          pnd_script_base, cpu_clock);
535                 system(buf);
536         }
537 }
538
539 static void apply_filter(int which)
540 {
541         static int old = -1;
542         char buf[128];
543         int i;
544
545         if (pnd_filter_list == NULL || which == old)
546                 return;
547
548         for (i = 0; i < which; i++)
549                 if (pnd_filter_list[i] == NULL)
550                         return;
551
552         if (pnd_filter_list[i] == NULL)
553                 return;
554
555         snprintf(buf, sizeof(buf), "%s/op_videofir.sh %s", pnd_script_base, pnd_filter_list[i]);
556         system(buf);
557         old = which;
558 }
559
560 static menu_entry e_menu_gfx_options[];
561
562 static void pnd_menu_init(void)
563 {
564         struct dirent *ent;
565         int i, count = 0;
566         char **mfilters;
567         char buff[64];
568         DIR *dir;
569
570         cpu_clock_st = cpu_clock = get_cpu_clock();
571
572         dir = opendir("/etc/pandora/conf/dss_fir");
573         if (dir == NULL) {
574                 perror("filter opendir");
575                 return;
576         }
577
578         while (1) {
579                 errno = 0;
580                 ent = readdir(dir);
581                 if (ent == NULL) {
582                         if (errno != 0)
583                                 perror("readdir");
584                         break;
585                 }
586
587                 if (ent->d_type != DT_REG && ent->d_type != DT_LNK)
588                         continue;
589
590                 count++;
591         }
592
593         if (count == 0)
594                 return;
595
596         mfilters = calloc(count + 1, sizeof(mfilters[0]));
597         if (mfilters == NULL)
598                 return;
599
600         rewinddir(dir);
601         for (i = 0; (ent = readdir(dir)); ) {
602                 size_t len;
603
604                 if (ent->d_type != DT_REG && ent->d_type != DT_LNK)
605                         continue;
606
607                 len = strlen(ent->d_name);
608
609                 // skip pre-HF5 extra files
610                 if (len >= 3 && strcmp(ent->d_name + len - 3, "_v3") == 0)
611                         continue;
612                 if (len >= 3 && strcmp(ent->d_name + len - 3, "_v5") == 0)
613                         continue;
614
615                 // have to cut "_up_h" for pre-HF5
616                 if (len > 5 && strcmp(ent->d_name + len - 5, "_up_h") == 0)
617                         len -= 5;
618
619                 if (len > sizeof(buff) - 1)
620                         continue;
621
622                 strncpy(buff, ent->d_name, len);
623                 buff[len] = 0;
624                 mfilters[i] = strdup(buff);
625                 if (mfilters[i] != NULL)
626                         i++;
627         }
628         closedir(dir);
629
630         i = me_id2offset(e_menu_gfx_options, MA_OPT_FILTERING);
631         e_menu_gfx_options[i].data = (void *)mfilters;
632         pnd_filter_list = mfilters;
633 }
634
635 void menu_finish(void)
636 {
637         cpu_clock = cpu_clock_st;
638         apply_cpu_clock();
639 }
640
641 // -------------- key config --------------
642
643 me_bind_action me_ctrl_actions[] =
644 {
645         { "UP      ", 1 << DKEY_UP},
646         { "DOWN    ", 1 << DKEY_DOWN },
647         { "LEFT    ", 1 << DKEY_LEFT },
648         { "RIGHT   ", 1 << DKEY_RIGHT },
649         { "TRIANGLE", 1 << DKEY_TRIANGLE },
650         { "CIRCLE  ", 1 << DKEY_CIRCLE },
651         { "CROSS   ", 1 << DKEY_CROSS },
652         { "SQUARE  ", 1 << DKEY_SQUARE },
653         { "L1      ", 1 << DKEY_L1 },
654         { "R1      ", 1 << DKEY_R1 },
655         { "L2      ", 1 << DKEY_L2 },
656         { "R2      ", 1 << DKEY_R2 },
657         { "L3      ", 1 << DKEY_L3 },
658         { "R3      ", 1 << DKEY_R3 },
659         { "START   ", 1 << DKEY_START },
660         { "SELECT  ", 1 << DKEY_SELECT },
661         { NULL,       0 }
662 };
663
664 me_bind_action emuctrl_actions[] =
665 {
666 /*
667         { "Load State       ", PEV_STATE_LOAD },
668         { "Save State       ", PEV_STATE_SAVE },
669         { "Prev Save Slot   ", PEV_SSLOT_PREV },
670         { "Next Save Slot   ", PEV_SSLOT_NEXT },
671 */
672         { "Enter Menu       ", PEV_MENU },
673         { NULL,                0 }
674 };
675
676 static char *mystrip(char *str)
677 {
678         int i, len;
679
680         len = strlen(str);
681         for (i = 0; i < len; i++)
682                 if (str[i] != ' ') break;
683         if (i > 0) memmove(str, str + i, len - i + 1);
684
685         len = strlen(str);
686         for (i = len - 1; i >= 0; i--)
687                 if (str[i] != ' ') break;
688         str[i+1] = 0;
689
690         return str;
691 }
692
693 static void get_line(char *d, size_t size, const char *s)
694 {
695         const char *pe;
696         size_t len;
697
698         for (pe = s; *pe != '\r' && *pe != '\n' && *pe != 0; pe++)
699                 ;
700         len = pe - s;
701         if (len > size - 1)
702                 len = size - 1;
703         strncpy(d, s, len);
704         d[len] = 0;
705
706         mystrip(d);
707 }
708
709 static void keys_write_all(FILE *f)
710 {
711         int d;
712
713         for (d = 0; d < IN_MAX_DEVS; d++)
714         {
715                 const int *binds = in_get_dev_binds(d);
716                 const char *name = in_get_dev_name(d, 0, 0);
717                 int k, count = 0;
718
719                 if (binds == NULL || name == NULL)
720                         continue;
721
722                 fprintf(f, "binddev = %s\n", name);
723                 in_get_config(d, IN_CFG_BIND_COUNT, &count);
724
725                 for (k = 0; k < count; k++)
726                 {
727                         int i, kbinds, mask;
728                         char act[32];
729
730                         act[0] = act[31] = 0;
731                         name = in_get_key_name(d, k);
732
733                         kbinds = binds[IN_BIND_OFFS(k, IN_BINDTYPE_PLAYER12)];
734                         for (i = 0; kbinds && i < ARRAY_SIZE(me_ctrl_actions) - 1; i++) {
735                                 mask = me_ctrl_actions[i].mask;
736                                 if (mask & kbinds) {
737                                         strncpy(act, me_ctrl_actions[i].name, 31);
738                                         fprintf(f, "bind %s = player1 %s\n", name, mystrip(act));
739                                         kbinds &= ~mask;
740                                 }
741                                 mask = me_ctrl_actions[i].mask << 16;
742                                 if (mask & kbinds) {
743                                         strncpy(act, me_ctrl_actions[i].name, 31);
744                                         fprintf(f, "bind %s = player2 %s\n", name, mystrip(act));
745                                         kbinds &= ~mask;
746                                 }
747                         }
748
749                         kbinds = binds[IN_BIND_OFFS(k, IN_BINDTYPE_EMU)];
750                         for (i = 0; kbinds && i < ARRAY_SIZE(emuctrl_actions) - 1; i++) {
751                                 mask = emuctrl_actions[i].mask;
752                                 if (mask & kbinds) {
753                                         strncpy(act, emuctrl_actions[i].name, 31);
754                                         fprintf(f, "bind %s = %s\n", name, mystrip(act));
755                                         kbinds &= ~mask;
756                                 }
757                         }
758                 }
759         }
760 }
761
762 static int parse_bind_val(const char *val, int *type)
763 {
764         int i;
765
766         *type = IN_BINDTYPE_NONE;
767         if (val[0] == 0)
768                 return 0;
769         
770         if (strncasecmp(val, "player", 6) == 0)
771         {
772                 int player, shift = 0;
773                 player = atoi(val + 6) - 1;
774
775                 if ((unsigned int)player > 1)
776                         return -1;
777                 if (player == 1)
778                         shift = 16;
779
780                 *type = IN_BINDTYPE_PLAYER12;
781                 for (i = 0; me_ctrl_actions[i].name != NULL; i++) {
782                         if (strncasecmp(me_ctrl_actions[i].name, val + 8, strlen(val + 8)) == 0)
783                                 return me_ctrl_actions[i].mask << shift;
784                 }
785         }
786         for (i = 0; emuctrl_actions[i].name != NULL; i++) {
787                 if (strncasecmp(emuctrl_actions[i].name, val, strlen(val)) == 0) {
788                         *type = IN_BINDTYPE_EMU;
789                         return emuctrl_actions[i].mask;
790                 }
791         }
792
793         return -1;
794 }
795
796 static void keys_load_all(const char *cfg)
797 {
798         char dev[256], key[128], *act;
799         const char *p;
800         int bind, bindtype;
801         int dev_id;
802
803         p = cfg;
804         while (p != NULL && (p = strstr(p, "binddev = ")) != NULL) {
805                 p += 10;
806
807                 get_line(dev, sizeof(dev), p);
808                 dev_id = in_config_parse_dev(dev);
809                 if (dev_id < 0) {
810                         printf("input: can't handle dev: %s\n", dev);
811                         continue;
812                 }
813
814                 in_unbind_all(dev_id, -1, -1);
815                 while ((p = strstr(p, "bind"))) {
816                         if (strncmp(p, "binddev = ", 10) == 0)
817                                 break;
818
819                         p += 4;
820                         if (*p != ' ') {
821                                 printf("input: parse error: %16s..\n", p);
822                                 continue;
823                         }
824
825                         get_line(key, sizeof(key), p);
826                         act = strchr(key, '=');
827                         if (act == NULL) {
828                                 printf("parse failed: %16s..\n", p);
829                                 continue;
830                         }
831                         *act = 0;
832                         act++;
833                         mystrip(key);
834                         mystrip(act);
835
836                         bind = parse_bind_val(act, &bindtype);
837                         if (bind != -1 && bind != 0) {
838                                 printf("bind #%d '%s' %08x (%s)\n", dev_id, key, bind, act);
839                                 in_config_bind_key(dev_id, key, bind, bindtype);
840                         }
841                         else
842                                 lprintf("config: unhandled action \"%s\"\n", act);
843                 }
844         }
845 }
846
847 static int key_config_loop_wrap(int id, int keys)
848 {
849         switch (id) {
850                 case MA_CTRL_PLAYER1:
851                         key_config_loop(me_ctrl_actions, array_size(me_ctrl_actions) - 1, 0);
852                         break;
853                 case MA_CTRL_PLAYER2:
854                         key_config_loop(me_ctrl_actions, array_size(me_ctrl_actions) - 1, 1);
855                         break;
856                 case MA_CTRL_EMU:
857                         key_config_loop(emuctrl_actions, array_size(emuctrl_actions) - 1, -1);
858                         break;
859                 default:
860                         break;
861         }
862         return 0;
863 }
864
865 static const char *mgn_dev_name(int id, int *offs)
866 {
867         const char *name = NULL;
868         static int it = 0;
869
870         if (id == MA_CTRL_DEV_FIRST)
871                 it = 0;
872
873         for (; it < IN_MAX_DEVS; it++) {
874                 name = in_get_dev_name(it, 1, 1);
875                 if (name != NULL)
876                         break;
877         }
878
879         it++;
880         return name;
881 }
882
883 static const char *mgn_saveloadcfg(int id, int *offs)
884 {
885         return "";
886 }
887
888 static int mh_savecfg(int id, int keys)
889 {
890         if (menu_write_config(id == MA_OPT_SAVECFG_GAME ? 1 : 0) == 0)
891                 me_update_msg("config saved");
892         else
893                 me_update_msg("failed to write config");
894
895         return 1;
896 }
897
898 static const char *men_in_type_sel[] = { "Standard (SCPH-1080)", "Analog (SCPH-1150)", NULL };
899
900 static menu_entry e_menu_keyconfig[] =
901 {
902         mee_handler_id("Player 1",          MA_CTRL_PLAYER1,    key_config_loop_wrap),
903         mee_handler_id("Player 2",          MA_CTRL_PLAYER2,    key_config_loop_wrap),
904         mee_handler_id("Emulator controls", MA_CTRL_EMU,        key_config_loop_wrap),
905         mee_label     (""),
906         mee_enum      ("Controller",        0, in_type_sel,     men_in_type_sel),
907         mee_cust_nosave("Save global config",       MA_OPT_SAVECFG,      mh_savecfg, mgn_saveloadcfg),
908         mee_cust_nosave("Save cfg for loaded game", MA_OPT_SAVECFG_GAME, mh_savecfg, mgn_saveloadcfg),
909         mee_label     (""),
910         mee_label     ("Input devices:"),
911         mee_label_mk  (MA_CTRL_DEV_FIRST, mgn_dev_name),
912         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
913         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
914         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
915         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
916         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
917         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
918         mee_end,
919 };
920
921 static int menu_loop_keyconfig(int id, int keys)
922 {
923         static int sel = 0;
924
925 //      me_enable(e_menu_keyconfig, MA_OPT_SAVECFG_GAME, ready_to_go && CdromId[0]);
926         me_loop(e_menu_keyconfig, &sel, NULL);
927         return 0;
928 }
929
930 // ------------ gfx options menu ------------
931
932 static const char *men_scaler[] = { "1x1", "scaled 4:3", "fullscreen", "custom", NULL };
933 static const char h_cscaler[]   = "Displays the scaler layer, you can resize it\n"
934                                   "using d-pad or move it using R+d-pad";
935 static const char *men_dummy[] = { NULL };
936
937 static int menu_loop_cscaler(int id, int keys)
938 {
939         unsigned int inp;
940
941         scaling = SCALE_CUSTOM;
942
943         omap_enable_layer(1);
944
945         for (;;)
946         {
947                 menu_draw_begin(0);
948                 memset(g_menuscreen_ptr, 4, g_menuscreen_w * g_menuscreen_h * 2);
949                 text_out16(2, 2, "%d,%d", g_layer_x, g_layer_y);
950                 text_out16(2, 480 - 18, "%dx%d | d-pad: resize, R+d-pad: move", g_layer_w, g_layer_h);
951                 menu_draw_end();
952
953                 inp = in_menu_wait(PBTN_UP|PBTN_DOWN|PBTN_LEFT|PBTN_RIGHT|PBTN_R|PBTN_MOK|PBTN_MBACK, 40);
954                 if (inp & PBTN_UP)    g_layer_y--;
955                 if (inp & PBTN_DOWN)  g_layer_y++;
956                 if (inp & PBTN_LEFT)  g_layer_x--;
957                 if (inp & PBTN_RIGHT) g_layer_x++;
958                 if (!(inp & PBTN_R)) {
959                         if (inp & PBTN_UP)    g_layer_h += 2;
960                         if (inp & PBTN_DOWN)  g_layer_h -= 2;
961                         if (inp & PBTN_LEFT)  g_layer_w += 2;
962                         if (inp & PBTN_RIGHT) g_layer_w -= 2;
963                 }
964                 if (inp & (PBTN_MOK|PBTN_MBACK))
965                         break;
966
967                 if (inp & (PBTN_UP|PBTN_DOWN|PBTN_LEFT|PBTN_RIGHT)) {
968                         if (g_layer_x < 0)   g_layer_x = 0;
969                         if (g_layer_x > 640) g_layer_x = 640;
970                         if (g_layer_y < 0)   g_layer_y = 0;
971                         if (g_layer_y > 420) g_layer_y = 420;
972                         if (g_layer_w < 160) g_layer_w = 160;
973                         if (g_layer_h < 60)  g_layer_h = 60;
974                         if (g_layer_x + g_layer_w > 800)
975                                 g_layer_w = 800 - g_layer_x;
976                         if (g_layer_y + g_layer_h > 480)
977                                 g_layer_h = 480 - g_layer_y;
978                         omap_enable_layer(1);
979                 }
980         }
981
982         omap_enable_layer(0);
983
984         return 0;
985 }
986
987 static menu_entry e_menu_gfx_options[] =
988 {
989         mee_enum      ("Scaler",                   0, scaling, men_scaler),
990         mee_enum      ("Filter",                   MA_OPT_FILTERING, filter, men_dummy),
991 //      mee_onoff     ("Vsync",                    0, vsync, 1),
992         mee_cust_h    ("Setup custom scaler",      0, menu_loop_cscaler, NULL, h_cscaler),
993         mee_end,
994 };
995
996 static int menu_loop_gfx_options(int id, int keys)
997 {
998         static int sel = 0;
999
1000         me_loop(e_menu_gfx_options, &sel, NULL);
1001
1002         return 0;
1003 }
1004
1005 // ------------ bios/plugins ------------
1006
1007 static const char *men_gpu_dithering[] = { "None", "Game dependant", "Always", NULL };
1008 static const char h_gpu_0[]            = "Needed for Chrono Cross";
1009 static const char h_gpu_1[]            = "Capcom fighting games";
1010 static const char h_gpu_2[]            = "Black screens in Lunar";
1011 static const char h_gpu_3[]            = "Compatibility mode";
1012 static const char h_gpu_6[]            = "Pandemonium 2";
1013 static const char h_gpu_7[]            = "Skip every second frame";
1014 static const char h_gpu_8[]            = "Needed by Dark Forces";
1015 static const char h_gpu_9[]            = "better g-colors, worse textures";
1016 static const char h_gpu_10[]           = "Toggle busy flags after drawing";
1017
1018 static menu_entry e_menu_plugin_gpu[] =
1019 {
1020         mee_enum      ("Dithering",                  0, iUseDither, men_gpu_dithering),
1021         mee_onoff_h   ("Odd/even bit hack",          0, dwActFixes, 1<<0, h_gpu_0),
1022         mee_onoff_h   ("Expand screen width",        0, dwActFixes, 1<<1, h_gpu_1),
1023         mee_onoff_h   ("Ignore brightness color",    0, dwActFixes, 1<<2, h_gpu_2),
1024         mee_onoff_h   ("Disable coordinate check",   0, dwActFixes, 1<<3, h_gpu_3),
1025         mee_onoff_h   ("Lazy screen update",         0, dwActFixes, 1<<6, h_gpu_6),
1026         mee_onoff_h   ("Old frame skipping",         0, dwActFixes, 1<<7, h_gpu_7),
1027         mee_onoff_h   ("Repeated flat tex triangles ",0,dwActFixes, 1<<8, h_gpu_8),
1028         mee_onoff_h   ("Draw quads with triangles",  0, dwActFixes, 1<<9, h_gpu_9),
1029         mee_onoff_h   ("Fake 'gpu busy' states",     0, dwActFixes, 1<<10, h_gpu_10),
1030         mee_end,
1031 };
1032
1033 static int menu_loop_plugin_gpu(int id, int keys)
1034 {
1035         static int sel = 0;
1036         me_loop(e_menu_plugin_gpu, &sel, NULL);
1037         return 0;
1038 }
1039
1040 static const char *men_spu_reverb[] = { "Off", "Fake", "On", NULL };
1041 static const char *men_spu_interp[] = { "None", "Simple", "Gaussian", "Cubic", NULL };
1042 static const char h_spu_irq_wait[]  = "Wait for CPU; only useful for some games, may cause glitches";
1043 static const char h_spu_thread[]    = "Run sound emulation in main thread (recommended)";
1044
1045 static menu_entry e_menu_plugin_spu[] =
1046 {
1047         mee_enum      ("Reverb",                    0, iUseReverb, men_spu_reverb),
1048         mee_enum      ("Interpolation",             0, iUseInterpolation, men_spu_interp),
1049         mee_onoff     ("Adjust XA pitch",           0, iXAPitch, 1),
1050         mee_onoff_h   ("SPU IRQ Wait",              0, iSPUIRQWait, 1, h_spu_irq_wait),
1051         mee_onoff_h   ("Sound in main thread",      0, iUseTimer, 2, h_spu_thread),
1052         mee_end,
1053 };
1054
1055 static int menu_loop_plugin_spu(int id, int keys)
1056 {
1057         static int sel = 0;
1058         me_loop(e_menu_plugin_spu, &sel, NULL);
1059         return 0;
1060 }
1061
1062 static const char h_bios[]       = "HLE is simulated BIOS. BIOS is saved in savestates.\n"
1063                                    "Must save config and reload the game\n"
1064                                    "for change to take effect";
1065 static const char h_plugin_xpu[] = "Must save config and reload the game\n"
1066                                    "for plugin change to take effect";
1067 static const char h_gpu[]        = "Configure built-in P.E.Op.S. SoftGL Driver V1.17";
1068 static const char h_spu[]        = "Configure built-in P.E.Op.S. Sound Driver V1.7";
1069
1070 static menu_entry e_menu_plugin_options[] =
1071 {
1072         mee_enum_h    ("BIOS",                          0, bios_sel, bioses, h_bios),
1073         mee_enum_h    ("GPU plugin",                    0, gpu_plugsel, gpu_plugins, h_plugin_xpu),
1074         mee_enum_h    ("SPU plugin",                    0, spu_plugsel, spu_plugins, h_plugin_xpu),
1075         mee_handler_h ("Configure built-in GPU plugin", menu_loop_plugin_gpu, h_gpu),
1076         mee_handler_h ("Configure built-in SPU plugin", menu_loop_plugin_spu, h_spu),
1077         mee_end,
1078 };
1079
1080 static menu_entry e_menu_main[];
1081
1082 static int menu_loop_plugin_options(int id, int keys)
1083 {
1084         static int sel = 0;
1085         me_loop(e_menu_plugin_options, &sel, NULL);
1086
1087         // sync BIOS/plugins
1088         snprintf(Config.Bios, sizeof(Config.Bios), "%s", bioses[bios_sel]);
1089         snprintf(Config.Gpu, sizeof(Config.Gpu), "%s", gpu_plugins[gpu_plugsel]);
1090         snprintf(Config.Spu, sizeof(Config.Spu), "%s", spu_plugins[spu_plugsel]);
1091         me_enable(e_menu_main, MA_MAIN_RUN_BIOS, bios_sel != 0);
1092
1093         return 0;
1094 }
1095
1096 // ------------ adv options menu ------------
1097
1098 static const char h_cfg_cpul[]   = "Shows CPU usage in %%";
1099 static const char h_cfg_fl[]     = "Frame Limiter keeps the game from running too fast";
1100 static const char h_cfg_xa[]     = "Disables XA sound, which can sometimes improve performance";
1101 static const char h_cfg_cdda[]   = "Disable CD Audio for a performance boost\n"
1102                                    "(proper .cue/.bin dump is needed otherwise)";
1103 static const char h_cfg_sio[]    = "This should be enabled for certain memcards/gamepads";
1104 static const char h_cfg_spuirq[] = "Compatibility tweak; should probably be left off";
1105 static const char h_cfg_rcnt1[]  = "Parasite Eve 2, Vandal Hearts 1/2 Fix";
1106 static const char h_cfg_rcnt2[]  = "InuYasha Sengoku Battle Fix";
1107 static const char h_cfg_nodrc[]  = "Disable dynamic recompiler and use interpreter\n"
1108                                    "Might be useful to overcome some dynarec bugs";
1109
1110 static menu_entry e_menu_adv_options[] =
1111 {
1112         mee_onoff_h   ("Show CPU load",          0, g_opts, OPT_SHOWCPU, h_cfg_cpul),
1113         mee_onoff_h   ("Disable Frame Limiter",  0, g_opts, OPT_NO_FRAMELIM, h_cfg_fl),
1114         mee_onoff_h   ("Disable XA Decoding",    0, Config.Xa, 1, h_cfg_xa),
1115         mee_onoff_h   ("Disable CD Audio",       0, Config.Cdda, 1, h_cfg_cdda),
1116         mee_onoff_h   ("SIO IRQ Always Enabled", 0, Config.Sio, 1, h_cfg_sio),
1117         mee_onoff_h   ("SPU IRQ Always Enabled", 0, Config.SpuIrq, 1, h_cfg_spuirq),
1118         mee_onoff_h   ("Rootcounter hack",       0, Config.RCntFix, 1, h_cfg_rcnt1),
1119         mee_onoff_h   ("Rootcounter hack 2",     0, Config.VSyncWA, 1, h_cfg_rcnt2),
1120         mee_onoff_h   ("Disable dynarec (slow!)",0, Config.Cpu, 1, h_cfg_nodrc),
1121         mee_end,
1122 };
1123
1124 static int menu_loop_adv_options(int id, int keys)
1125 {
1126         static int sel = 0;
1127         me_loop(e_menu_adv_options, &sel, NULL);
1128         return 0;
1129 }
1130
1131 // ------------ options menu ------------
1132
1133 static int mh_restore_defaults(int id, int keys)
1134 {
1135         menu_set_defconfig();
1136         me_update_msg("defaults restored");
1137         return 1;
1138 }
1139
1140 static const char *men_region[]       = { "Auto", "NTSC", "PAL", NULL };
1141 /*
1142 static const char *men_confirm_save[] = { "OFF", "writes", "loads", "both", NULL };
1143 static const char h_confirm_save[]    = "Ask for confirmation when overwriting save,\n"
1144                                         "loading state or both";
1145 */
1146 static const char h_restore_def[]     = "Switches back to default / recommended\n"
1147                                         "configuration";
1148
1149 static menu_entry e_menu_options[] =
1150 {
1151 //      mee_range     ("Save slot",                0, state_slot, 0, 9),
1152 //      mee_enum_h    ("Confirm savestate",        0, dummy, men_confirm_save, h_confirm_save),
1153         mee_onoff     ("Frameskip",                0, UseFrameSkip, 1),
1154         mee_onoff     ("Show FPS",                 0, g_opts, OPT_SHOWFPS),
1155         mee_enum      ("Region",                   0, region, men_region),
1156         mee_range     ("CPU clock",                MA_OPT_CPU_CLOCKS, cpu_clock, 20, 5000),
1157         mee_handler   ("[Display]",                menu_loop_gfx_options),
1158         mee_handler   ("[BIOS/Plugins]",           menu_loop_plugin_options),
1159         mee_handler   ("[Advanced]",               menu_loop_adv_options),
1160         mee_cust_nosave("Save global config",      MA_OPT_SAVECFG,      mh_savecfg, mgn_saveloadcfg),
1161         mee_cust_nosave("Save cfg for loaded game",MA_OPT_SAVECFG_GAME, mh_savecfg, mgn_saveloadcfg),
1162         mee_handler_h ("Restore default config",   mh_restore_defaults, h_restore_def),
1163         mee_end,
1164 };
1165
1166 static int menu_loop_options(int id, int keys)
1167 {
1168         static int sel = 0;
1169         int i;
1170
1171         i = me_id2offset(e_menu_options, MA_OPT_CPU_CLOCKS);
1172         e_menu_options[i].enabled = cpu_clock != 0 ? 1 : 0;
1173         me_enable(e_menu_options, MA_OPT_SAVECFG_GAME, ready_to_go && CdromId[0]);
1174
1175         me_loop(e_menu_options, &sel, NULL);
1176
1177         return 0;
1178 }
1179
1180 // ------------ debug menu ------------
1181
1182 static void draw_frame_debug(void)
1183 {
1184         smalltext_out16(4, 1, "build: "__DATE__ " " __TIME__ " " REV, 0xe7fc);
1185 }
1186
1187 static void debug_menu_loop(void)
1188 {
1189         int inp;
1190
1191         while (1)
1192         {
1193                 menu_draw_begin(1);
1194                 draw_frame_debug();
1195                 menu_draw_end();
1196
1197                 inp = in_menu_wait(PBTN_MOK|PBTN_MBACK|PBTN_MA2|PBTN_MA3|PBTN_L|PBTN_R |
1198                                         PBTN_UP|PBTN_DOWN|PBTN_LEFT|PBTN_RIGHT, 70);
1199                 if (inp & PBTN_MBACK)
1200                         return;
1201         }
1202 }
1203
1204 // ------------ main menu ------------
1205
1206 void OnFile_Exit();
1207
1208 static void draw_frame_main(void)
1209 {
1210         if (CdromId[0] != 0) {
1211                 char buff[64];
1212                 snprintf(buff, sizeof(buff), "%.32s/%.9s (running as %s)",
1213                          get_cd_label(), CdromId, Config.PsxType ? "PAL" : "NTSC");
1214                 smalltext_out16(4, 1, buff, 0x105f);
1215         }
1216 }
1217
1218 static void draw_frame_credits(void)
1219 {
1220         smalltext_out16(4, 1, "build: "__DATE__ " " __TIME__ " " REV, 0xe7fc);
1221 }
1222
1223 const char *plat_get_credits(void)
1224 {
1225         return  "PCSX-ReARMed\n\n"
1226                 "(C) 1999-2003 PCSX Team\n"
1227                 "(C) 2005-2009 PCSX-df Team\n"
1228                 "(C) 2009-2011 PCSX-Reloaded Team\n\n"
1229                 "GPU and SPU code by Pete Bernert\n"
1230                 "  and the P.E.Op.S. team\n"
1231                 "ARM recompiler (C) 2009-2011 Ari64\n"
1232                 "PCSX4ALL plugins by PCSX4ALL team\n"
1233                 "  Chui, Franxis, Unai\n\n"
1234                 "integration, optimization and\n"
1235                 "  frontend (C) 2010-2011 notaz\n";
1236 }
1237
1238 static int reset_game(void)
1239 {
1240         // sanity check
1241         if (bios_sel == 0 && !Config.HLE)
1242                 return -1;
1243
1244         ClosePlugins();
1245         OpenPlugins();
1246         SysReset();
1247         if (CheckCdrom() != -1) {
1248                 LoadCdrom();
1249         }
1250         return 0;
1251 }
1252
1253 static int run_bios(void)
1254 {
1255         if (bios_sel == 0)
1256                 return -1;
1257
1258         ready_to_go = 0;
1259         pl_fbdev_buf = NULL;
1260
1261         ClosePlugins();
1262         set_cd_image(NULL);
1263         LoadPlugins();
1264         NetOpened = 0;
1265         if (OpenPlugins() == -1) {
1266                 me_update_msg("failed to open plugins");
1267                 return -1;
1268         }
1269         plugin_call_rearmed_cbs();
1270
1271         CdromId[0] = '\0';
1272         CdromLabel[0] = '\0';
1273
1274         SysReset();
1275
1276         ready_to_go = 1;
1277         return 0;
1278 }
1279
1280 static int run_cd_image(const char *fname)
1281 {
1282         ready_to_go = 0;
1283         pl_fbdev_buf = NULL;
1284
1285         ClosePlugins();
1286         set_cd_image(fname);
1287         LoadPlugins();
1288         NetOpened = 0;
1289         if (OpenPlugins() == -1) {
1290                 me_update_msg("failed to open plugins");
1291                 return -1;
1292         }
1293         plugin_call_rearmed_cbs();
1294
1295         if (CheckCdrom() == -1) {
1296                 // Only check the CD if we are starting the console with a CD
1297                 ClosePlugins();
1298                 me_update_msg("unsupported/invalid CD image");
1299                 return -1;
1300         }
1301
1302         SysReset();
1303
1304         // Read main executable directly from CDRom and start it
1305         if (LoadCdrom() == -1) {
1306                 ClosePlugins();
1307                 me_update_msg("failed to load CD image");
1308                 return -1;
1309         }
1310
1311         ready_to_go = 1;
1312         return 0;
1313 }
1314
1315 static int romsel_run(void)
1316 {
1317         int prev_gpu, prev_spu;
1318         char *fname;
1319
1320         fname = menu_loop_romsel(last_selected_fname, sizeof(last_selected_fname));
1321         if (fname == NULL)
1322                 return -1;
1323
1324         printf("selected file: %s\n", fname);
1325
1326         if (run_cd_image(fname) != 0)
1327                 return -1;
1328
1329         prev_gpu = gpu_plugsel;
1330         prev_spu = spu_plugsel;
1331         if (menu_load_config(1) != 0)
1332                 menu_load_config(0);
1333
1334         // check for plugin changes, have to repeat
1335         // loading if game config changed plugins to reload them
1336         if (prev_gpu != gpu_plugsel || prev_spu != spu_plugsel) {
1337                 printf("plugin change detected, reloading plugins..\n");
1338                 if (run_cd_image(fname) != 0)
1339                         return -1;
1340         }
1341
1342         strcpy(last_selected_fname, rom_fname_reload);
1343         return 0;
1344 }
1345
1346 static int main_menu_handler(int id, int keys)
1347 {
1348         switch (id)
1349         {
1350         case MA_MAIN_RESUME_GAME:
1351                 if (ready_to_go)
1352                         return 1;
1353                 break;
1354         case MA_MAIN_SAVE_STATE:
1355                 if (ready_to_go)
1356                         return menu_loop_savestate(0);
1357                 break;
1358         case MA_MAIN_LOAD_STATE:
1359                 if (ready_to_go)
1360                         return menu_loop_savestate(1);
1361                 break;
1362         case MA_MAIN_RESET_GAME:
1363                 if (ready_to_go && reset_game() == 0)
1364                         return 1;
1365                 break;
1366         case MA_MAIN_LOAD_ROM:
1367                 if (romsel_run() == 0)
1368                         return 1;
1369                 break;
1370         case MA_MAIN_RUN_BIOS:
1371                 if (run_bios() == 0)
1372                         return 1;
1373                 break;
1374         case MA_MAIN_CREDITS:
1375                 draw_menu_credits(draw_frame_credits);
1376                 in_menu_wait(PBTN_MOK|PBTN_MBACK, 70);
1377                 break;
1378         case MA_MAIN_EXIT:
1379                 OnFile_Exit();
1380                 break;
1381         default:
1382                 lprintf("%s: something unknown selected\n", __FUNCTION__);
1383                 break;
1384         }
1385
1386         return 0;
1387 }
1388
1389 static menu_entry e_menu_main[] =
1390 {
1391         mee_label     (""),
1392         mee_label     (""),
1393         mee_handler_id("Resume game",        MA_MAIN_RESUME_GAME, main_menu_handler),
1394         mee_handler_id("Save State",         MA_MAIN_SAVE_STATE,  main_menu_handler),
1395         mee_handler_id("Load State",         MA_MAIN_LOAD_STATE,  main_menu_handler),
1396         mee_handler_id("Reset game",         MA_MAIN_RESET_GAME,  main_menu_handler),
1397         mee_handler_id("Load CD image",      MA_MAIN_LOAD_ROM,    main_menu_handler),
1398         mee_handler_id("Run BIOS",           MA_MAIN_RUN_BIOS,    main_menu_handler),
1399         mee_handler   ("Options",            menu_loop_options),
1400         mee_handler   ("Controls",           menu_loop_keyconfig),
1401         mee_handler_id("Credits",            MA_MAIN_CREDITS,     main_menu_handler),
1402         mee_handler_id("Exit",               MA_MAIN_EXIT,        main_menu_handler),
1403         mee_end,
1404 };
1405
1406 // ----------------------------
1407
1408 static void menu_leave_emu(void);
1409
1410 void menu_loop(void)
1411 {
1412         static int sel = 0;
1413
1414         menu_leave_emu();
1415
1416         me_enable(e_menu_main, MA_MAIN_RESUME_GAME, ready_to_go);
1417         me_enable(e_menu_main, MA_MAIN_SAVE_STATE,  ready_to_go && CdromId[0]);
1418         me_enable(e_menu_main, MA_MAIN_LOAD_STATE,  ready_to_go && CdromId[0]);
1419         me_enable(e_menu_main, MA_MAIN_RESET_GAME,  ready_to_go);
1420         me_enable(e_menu_main, MA_MAIN_RUN_BIOS, bios_sel != 0);
1421
1422         in_set_config_int(0, IN_CFG_BLOCKING, 1);
1423
1424         do {
1425                 me_loop(e_menu_main, &sel, draw_frame_main);
1426         } while (!ready_to_go);
1427
1428         /* wait until menu, ok, back is released */
1429         while (in_menu_wait_any(50) & (PBTN_MENU|PBTN_MOK|PBTN_MBACK))
1430                 ;
1431
1432         in_set_config_int(0, IN_CFG_BLOCKING, 0);
1433
1434         menu_prepare_emu();
1435 }
1436
1437 static void scan_bios_plugins(void)
1438 {
1439         char fname[MAXPATHLEN];
1440         struct dirent *ent;
1441         int bios_i, gpu_i, spu_i;
1442         char *p;
1443         DIR *dir;
1444
1445         bioses[0] = "HLE";
1446         gpu_plugins[0] = "builtin_gpu";
1447         spu_plugins[0] = "builtin_spu";
1448         bios_i = gpu_i = spu_i = 1;
1449
1450         snprintf(fname, sizeof(fname), "%s/", Config.BiosDir);
1451         dir = opendir(fname);
1452         if (dir == NULL) {
1453                 perror("scan_bios_plugins bios opendir");
1454                 goto do_plugins;
1455         }
1456
1457         while (1) {
1458                 struct stat st;
1459
1460                 errno = 0;
1461                 ent = readdir(dir);
1462                 if (ent == NULL) {
1463                         if (errno != 0)
1464                                 perror("readdir");
1465                         break;
1466                 }
1467
1468                 if (ent->d_type != DT_REG && ent->d_type != DT_LNK)
1469                         continue;
1470
1471                 snprintf(fname, sizeof(fname), "%s/%s", Config.BiosDir, ent->d_name);
1472                 if (stat(fname, &st) != 0 || st.st_size != 512*1024) {
1473                         printf("bad BIOS file: %s\n", ent->d_name);
1474                         continue;
1475                 }
1476
1477                 if (bios_i < ARRAY_SIZE(bioses) - 1) {
1478                         bioses[bios_i++] = strdup(ent->d_name);
1479                         continue;
1480                 }
1481
1482                 printf("too many BIOSes, dropping \"%s\"\n", ent->d_name);
1483         }
1484
1485         closedir(dir);
1486
1487 do_plugins:
1488         snprintf(fname, sizeof(fname), "%s/", Config.PluginsDir);
1489         dir = opendir(fname);
1490         if (dir == NULL) {
1491                 perror("scan_bios_plugins opendir");
1492                 return;
1493         }
1494
1495         while (1) {
1496                 void *h, *tmp;
1497
1498                 errno = 0;
1499                 ent = readdir(dir);
1500                 if (ent == NULL) {
1501                         if (errno != 0)
1502                                 perror("readdir");
1503                         break;
1504                 }
1505                 p = strstr(ent->d_name, ".so");
1506                 if (p == NULL)
1507                         continue;
1508
1509                 snprintf(fname, sizeof(fname), "%s/%s", Config.PluginsDir, ent->d_name);
1510                 h = dlopen(fname, RTLD_LAZY | RTLD_LOCAL);
1511                 if (h == NULL) {
1512                         fprintf(stderr, "%s\n", dlerror());
1513                         continue;
1514                 }
1515
1516                 // now what do we have here?
1517                 tmp = dlsym(h, "GPUinit");
1518                 if (tmp) {
1519                         dlclose(h);
1520                         if (gpu_i < ARRAY_SIZE(gpu_plugins) - 1)
1521                                 gpu_plugins[gpu_i++] = strdup(ent->d_name);
1522                         continue;
1523                 }
1524
1525                 tmp = dlsym(h, "SPUinit");
1526                 if (tmp) {
1527                         dlclose(h);
1528                         if (spu_i < ARRAY_SIZE(spu_plugins) - 1)
1529                                 spu_plugins[spu_i++] = strdup(ent->d_name);
1530                         continue;
1531                 }
1532
1533                 fprintf(stderr, "ignoring unidentified plugin: %s\n", fname);
1534                 dlclose(h);
1535         }
1536
1537         closedir(dir);
1538 }
1539
1540 void menu_init(void)
1541 {
1542         char buff[MAXPATHLEN];
1543
1544         strcpy(last_selected_fname, "/media");
1545
1546         scan_bios_plugins();
1547         pnd_menu_init();
1548         menu_init_common();
1549
1550         menu_set_defconfig();
1551         menu_load_config(0);
1552         last_psx_w = 320;
1553         last_psx_h = 240;
1554         last_psx_bpp = 16;
1555
1556         g_menubg_src_ptr = calloc(g_menuscreen_w * g_menuscreen_h * 2, 1);
1557         if (g_menubg_src_ptr == NULL)
1558                 exit(1);
1559         emu_make_path(buff, "skin/background.png", sizeof(buff));
1560         readpng(g_menubg_src_ptr, buff, READPNG_BG, g_menuscreen_w, g_menuscreen_h);
1561 }
1562
1563 void menu_notify_mode_change(int w, int h, int bpp)
1564 {
1565         last_psx_w = w;
1566         last_psx_h = h;
1567         last_psx_bpp = bpp;
1568
1569         if (scaling == SCALE_1_1) {
1570                 g_layer_x = 800/2 - w/2;  g_layer_y = 480/2 - h/2;
1571                 g_layer_w = w; g_layer_h = h;
1572         }
1573 }
1574
1575 static void menu_leave_emu(void)
1576 {
1577         if (GPU_close != NULL) {
1578                 int ret = GPU_close();
1579                 if (ret)
1580                         fprintf(stderr, "Warning: GPU_close returned %d\n", ret);
1581         }
1582
1583         memcpy(g_menubg_ptr, g_menubg_src_ptr, g_menuscreen_w * g_menuscreen_h * 2);
1584         if (pl_fbdev_buf != NULL && ready_to_go && last_psx_bpp == 16) {
1585                 int x = max(0, g_menuscreen_w - last_psx_w);
1586                 int y = max(0, g_menuscreen_h / 2 - last_psx_h / 2);
1587                 int w = min(g_menuscreen_w, last_psx_w);
1588                 int h = min(g_menuscreen_h, last_psx_h);
1589                 u16 *d = (u16 *)g_menubg_ptr + g_menuscreen_w * y + x;
1590                 u16 *s = pl_fbdev_buf;
1591
1592                 for (; h > 0; h--, d += g_menuscreen_w, s += last_psx_w)
1593                         menu_darken_bg(d, s, w, 0);
1594         }
1595
1596         if (ready_to_go)
1597                 cpu_clock = get_cpu_clock();
1598
1599         plat_video_menu_enter(ready_to_go);
1600 }
1601
1602 void menu_prepare_emu(void)
1603 {
1604         R3000Acpu *prev_cpu = psxCpu;
1605
1606         plat_video_menu_leave();
1607
1608         switch (scaling) {
1609         case SCALE_1_1:
1610                 menu_notify_mode_change(last_psx_w, last_psx_h, last_psx_bpp);
1611                 break;
1612         case SCALE_4_3:
1613                 g_layer_x = 80;  g_layer_y = 0;
1614                 g_layer_w = 640; g_layer_h = 480;
1615                 break;
1616         case SCALE_FULLSCREEN:
1617                 g_layer_x = 0;   g_layer_y = 0;
1618                 g_layer_w = 800; g_layer_h = 480;
1619                 break;
1620         case SCALE_CUSTOM:
1621                 break;
1622         }
1623         apply_filter(filter);
1624         apply_cpu_clock();
1625
1626         psxCpu = (Config.Cpu == CPU_INTERPRETER) ? &psxInt : &psxRec;
1627         if (psxCpu != prev_cpu)
1628                 // note that this does not really reset, just clears drc caches
1629                 psxCpu->Reset();
1630
1631         // core doesn't care about Config.Cdda changes,
1632         // so handle them manually here
1633         if (Config.Cdda)
1634                 CDR_stop();
1635
1636         menu_sync_config();
1637
1638         if (GPU_open != NULL) {
1639                 int ret = GPU_open(&gpuDisp, "PCSX", NULL);
1640                 if (ret)
1641                         fprintf(stderr, "Warning: GPU_open returned %d\n", ret);
1642         }
1643 }
1644
1645 void me_update_msg(const char *msg)
1646 {
1647         strncpy(menu_error_msg, msg, sizeof(menu_error_msg));
1648         menu_error_msg[sizeof(menu_error_msg) - 1] = 0;
1649
1650         menu_error_time = plat_get_ticks_ms();
1651         lprintf("msg: %s\n", menu_error_msg);
1652 }
1653