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