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