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