frontend cleanup
[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
16 #include "main.h"
17 #include "menu.h"
18 #include "config.h"
19 #include "plugin.h"
20 #include "plugin_lib.h"
21 #include "omap.h"
22 #include "common/plat.h"
23 #include "../libpcsxcore/misc.h"
24 #include "../libpcsxcore/new_dynarec/new_dynarec.h"
25 #include "revision.h"
26
27 #define MENU_X2 1
28 #define array_size(x) (sizeof(x) / sizeof(x[0]))
29
30 typedef enum
31 {
32         MA_NONE = 1,
33         MA_MAIN_RESUME_GAME,
34         MA_MAIN_SAVE_STATE,
35         MA_MAIN_LOAD_STATE,
36         MA_MAIN_RESET_GAME,
37         MA_MAIN_LOAD_ROM,
38         MA_MAIN_CONTROLS,
39         MA_MAIN_CREDITS,
40         MA_MAIN_EXIT,
41         MA_CTRL_PLAYER1,
42         MA_CTRL_PLAYER2,
43         MA_CTRL_EMU,
44         MA_CTRL_DEV_FIRST,
45         MA_CTRL_DEV_NEXT,
46         MA_CTRL_DONE,
47         MA_OPT_SAVECFG,
48         MA_OPT_SAVECFG_GAME,
49         MA_OPT_CPU_CLOCKS,
50         MA_OPT_FILTERING,
51 } menu_id;
52
53 enum {
54         SCALE_1_1,
55         SCALE_4_3,
56         SCALE_FULLSCREEN,
57         SCALE_CUSTOM,
58 };
59
60 static int last_psx_w, last_psx_h, last_psx_bpp;
61 static int scaling, filter, state_slot, cpu_clock, cpu_clock_st;
62 static char rom_fname_reload[MAXPATHLEN];
63 static char last_selected_fname[MAXPATHLEN];
64 int g_opts;
65
66 // from softgpu plugin
67 extern int iUseDither;
68 extern int UseFrameSkip;
69 extern int UseFrameLimit;
70 extern uint32_t dwActFixes;
71 extern float fFrameRateHz;
72 extern int dwFrameRateTicks;
73
74 // sound plugin
75 extern int iUseReverb;
76 extern int iUseInterpolation;
77 extern int iXAPitch;
78 extern int iSPUIRQWait;
79 extern int iUseTimer;
80
81 static const char *gpu_plugins[16];
82 static const char *spu_plugins[16];
83 static int gpu_plugsel, spu_plugsel;
84
85
86 static int min(int x, int y) { return x < y ? x : y; }
87 static int max(int x, int y) { return x > y ? x : y; }
88
89 void emu_make_path(char *buff, const char *end, int size)
90 {
91         int pos, end_len;
92
93         end_len = strlen(end);
94         pos = plat_get_root_dir(buff, size);
95         strncpy(buff + pos, end, size - pos);
96         buff[size - 1] = 0;
97         if (pos + end_len > size - 1)
98                 printf("Warning: path truncated: %s\n", buff);
99 }
100
101 static int emu_check_save_file(int slot)
102 {
103         char fname[MAXPATHLEN];
104         int ret;
105
106         ret = get_state_filename(fname, sizeof(fname), slot);
107         if (ret != 0)
108                 return 0;
109
110         ret = CheckState(fname);
111         return ret == 0 ? 1 : 0;
112 }
113
114 static int emu_save_load_game(int load, int sram)
115 {
116         char fname[MAXPATHLEN];
117         int ret;
118
119         ret = get_state_filename(fname, sizeof(fname), state_slot);
120         if (ret != 0)
121                 return 0;
122
123         if (load)
124                 ret = LoadState(fname);
125         else
126                 ret = SaveState(fname);
127
128         return ret;
129 }
130
131 static void draw_savestate_bg(int slot)
132 {
133 }
134
135 static void menu_set_defconfig(void)
136 {
137         scaling = SCALE_4_3;
138
139         Config.Xa = Config.Cdda = Config.Sio =
140         Config.SpuIrq = Config.RCntFix = Config.VSyncWA = 0;
141
142         iUseDither = UseFrameSkip = 0;
143         UseFrameLimit = 1;
144         dwActFixes = 1<<7;
145
146         iUseReverb = 2;
147         iUseInterpolation = 1;
148         iXAPitch = iSPUIRQWait = 0;
149         iUseTimer = 2;
150 }
151
152 #define CE_CONFIG_STR(val) \
153         { #val, 0, Config.val }
154
155 #define CE_CONFIG_VAL(val) \
156         { #val, sizeof(Config.val), &Config.val }
157
158 #define CE_STR(val) \
159         { #val, 0, val }
160
161 #define CE_INTVAL(val) \
162         { #val, sizeof(val), &val }
163
164 static const struct {
165         const char *name;
166         size_t len;
167         void *val;
168 } config_data[] = {
169         CE_CONFIG_STR(Bios),
170         CE_CONFIG_STR(Gpu),
171         CE_CONFIG_STR(Spu),
172         CE_CONFIG_STR(Cdr),
173         CE_CONFIG_VAL(Xa),
174         CE_CONFIG_VAL(Sio),
175         CE_CONFIG_VAL(Mdec),
176         CE_CONFIG_VAL(PsxAuto),
177         CE_CONFIG_VAL(Cdda),
178         CE_CONFIG_VAL(Debug),
179         CE_CONFIG_VAL(PsxOut),
180         CE_CONFIG_VAL(SpuIrq),
181         CE_CONFIG_VAL(RCntFix),
182         CE_CONFIG_VAL(VSyncWA),
183         CE_CONFIG_VAL(Cpu),
184         CE_CONFIG_VAL(PsxType),
185         CE_INTVAL(scaling),
186         CE_INTVAL(g_layer_x),
187         CE_INTVAL(g_layer_y),
188         CE_INTVAL(g_layer_w),
189         CE_INTVAL(g_layer_h),
190         CE_INTVAL(filter),
191         CE_INTVAL(state_slot),
192         CE_INTVAL(cpu_clock),
193         CE_INTVAL(g_opts),
194         CE_INTVAL(iUseDither),
195         CE_INTVAL(UseFrameSkip),
196         CE_INTVAL(UseFrameLimit),
197         CE_INTVAL(dwActFixes),
198         CE_INTVAL(iUseReverb),
199         CE_INTVAL(iUseInterpolation),
200         CE_INTVAL(iXAPitch),
201         CE_INTVAL(iSPUIRQWait),
202         CE_INTVAL(iUseTimer),
203 };
204
205 static void make_cfg_fname(char *buf, size_t size, int is_game)
206 {
207         char trimlabel[33];
208         int j;
209
210         strncpy(trimlabel, CdromLabel, 32);
211         trimlabel[32] = 0;
212         for (j = 31; j >= 0; j--)
213                 if (trimlabel[j] == ' ')
214                         trimlabel[j] = 0;
215
216         if (is_game)
217                 snprintf(buf, size, "." PCSX_DOT_DIR "cfg/%.32s-%.9s.cfg", trimlabel, CdromId);
218         else
219                 snprintf(buf, size, "." PCSX_DOT_DIR "%s", cfgfile_basename);
220 }
221
222 static int menu_write_config(int is_game)
223 {
224         char cfgfile[MAXPATHLEN];
225         FILE *f;
226         int i;
227
228         make_cfg_fname(cfgfile, sizeof(cfgfile), is_game);
229         f = fopen(cfgfile, "w");
230         if (f == NULL) {
231                 printf("menu_write_config: failed to open: %s\n", cfgfile);
232                 return -1;
233         }
234
235         for (i = 0; i < ARRAY_SIZE(config_data); i++) {
236                 fprintf(f, "%s = ", config_data[i].name);
237                 switch (config_data[i].len) {
238                 case 0:
239                         fprintf(f, "%s\n", (char *)config_data[i].val);
240                         break;
241                 case 1:
242                         fprintf(f, "%x\n", *(u8 *)config_data[i].val);
243                         break;
244                 case 2:
245                         fprintf(f, "%x\n", *(u16 *)config_data[i].val);
246                         break;
247                 case 4:
248                         fprintf(f, "%x\n", *(u32 *)config_data[i].val);
249                         break;
250                 default:
251                         printf("menu_write_config: unhandled len %d for %s\n",
252                                  config_data[i].len, config_data[i].name);
253                         break;
254                 }
255         }
256
257         if (!is_game)
258                 fprintf(f, "lastcdimg = %s\n", last_selected_fname);
259
260         fclose(f);
261         return 0;
262 }
263
264 static void parse_str_val(char *cval, const char *src)
265 {
266         char *tmp;
267         strncpy(cval, src, MAXPATHLEN);
268         cval[MAXPATHLEN - 1] = 0;
269         tmp = strchr(cval, '\n');
270         if (tmp == NULL)
271                 tmp = strchr(cval, '\r');
272         if (tmp != NULL)
273                 *tmp = 0;
274 }
275
276 static int menu_load_config(int is_game)
277 {
278         char cfgfile[MAXPATHLEN];
279         int i, ret = -1;
280         long size;
281         char *cfg;
282         FILE *f;
283
284         make_cfg_fname(cfgfile, sizeof(cfgfile), is_game);
285         f = fopen(cfgfile, "r");
286         if (f == NULL) {
287                 printf("menu_load_config: failed to open: %s\n", cfgfile);
288                 return -1;
289         }
290
291         fseek(f, 0, SEEK_END);
292         size = ftell(f);
293         if (size <= 0) {
294                 printf("bad size %ld: %s\n", size, cfgfile);
295                 goto fail;
296         }
297
298         cfg = malloc(size + 1);
299         if (cfg == NULL)
300                 goto fail;
301
302         fseek(f, 0, SEEK_SET);
303         if (fread(cfg, 1, size, f) != size) {
304                 printf("failed to read: %s\n", cfgfile);
305                 goto fail_read;
306         }
307         cfg[size] = 0;
308
309         for (i = 0; i < ARRAY_SIZE(config_data); i++) {
310                 char *tmp, *tmp2;
311                 u32 val;
312
313                 tmp = strstr(cfg, config_data[i].name);
314                 if (tmp == NULL)
315                         continue;
316                 tmp += strlen(config_data[i].name);
317                 if (strncmp(tmp, " = ", 3) != 0)
318                         continue;
319                 tmp += 3;
320
321                 if (config_data[i].len == 0) {
322                         parse_str_val(config_data[i].val, tmp);
323                         continue;
324                 }
325
326                 tmp2 = NULL;
327                 val = strtoul(tmp, &tmp2, 16);
328                 if (tmp2 == NULL || tmp == tmp2)
329                         continue; // parse failed
330
331                 switch (config_data[i].len) {
332                 case 1:
333                         *(u8 *)config_data[i].val = val;
334                         break;
335                 case 2:
336                         *(u16 *)config_data[i].val = val;
337                         break;
338                 case 4:
339                         *(u32 *)config_data[i].val = val;
340                         break;
341                 default:
342                         printf("menu_load_config: unhandled len %d for %s\n",
343                                  config_data[i].len, config_data[i].name);
344                         break;
345                 }
346         }
347
348         if (!is_game) {
349                 char *tmp = strstr(cfg, "lastcdimg = ");
350                 if (tmp != NULL) {
351                         tmp += 12;
352                         parse_str_val(last_selected_fname, tmp);
353                 }
354         }
355
356         // sync plugins
357         for (i = gpu_plugsel = 0; gpu_plugins[i] != NULL; i++)
358                 if (strcmp(Config.Gpu, gpu_plugins[i]) == 0)
359                         { gpu_plugsel = i; break; }
360
361         for (i = spu_plugsel = 0; spu_plugins[i] != NULL; i++)
362                 if (strcmp(Config.Spu, spu_plugins[i]) == 0)
363                         { spu_plugsel = i; break; }
364
365         ret = 0;
366 fail_read:
367         free(cfg);
368 fail:
369         fclose(f);
370         return ret;
371 }
372
373 // rrrr rggg gggb bbbb
374 static unsigned short fname2color(const char *fname)
375 {
376         static const char *cdimg_exts[] = { ".bin", ".img", ".iso", ".z", ".cue" };
377         static const char *other_exts[] = { ".ccd", ".toc", ".mds", ".sub", ".table" };
378         const char *ext = strrchr(fname, '.');
379         int i;
380
381         if (ext == NULL)
382                 return 0xffff;
383         for (i = 0; i < array_size(cdimg_exts); i++)
384                 if (strcasecmp(ext, cdimg_exts[i]) == 0)
385                         return 0x7bff;
386         for (i = 0; i < array_size(other_exts); i++)
387                 if (strcasecmp(ext, other_exts[i]) == 0)
388                         return 0xa514;
389         return 0xffff;
390 }
391
392 #define MENU_ALIGN_LEFT
393 #define menu_init menu_init_common
394 #include "common/menu.c"
395 #undef menu_init
396
397 // ---------- pandora specific -----------
398
399 static const char pnd_script_base[] = "sudo -n /usr/pandora/scripts";
400 static char **pnd_filter_list;
401
402 static int get_cpu_clock(void)
403 {
404         FILE *f;
405         int ret = 0;
406         f = fopen("/proc/pandora/cpu_mhz_max", "r");
407         if (f) {
408                 fscanf(f, "%d", &ret);
409                 fclose(f);
410         }
411         return ret;
412 }
413
414 static void apply_cpu_clock(void)
415 {
416         char buf[128];
417
418         if (cpu_clock != 0 && cpu_clock != get_cpu_clock()) {
419                 snprintf(buf, sizeof(buf), "unset DISPLAY; echo y | %s/op_cpuspeed.sh %d",
420                          pnd_script_base, cpu_clock);
421                 system(buf);
422         }
423 }
424
425 static void apply_filter(int which)
426 {
427         static int old = -1;
428         char buf[128];
429         int i;
430
431         if (pnd_filter_list == NULL || which == old)
432                 return;
433
434         for (i = 0; i < which; i++)
435                 if (pnd_filter_list[i] == NULL)
436                         return;
437
438         if (pnd_filter_list[i] == NULL)
439                 return;
440
441         snprintf(buf, sizeof(buf), "%s/op_videofir.sh %s", pnd_script_base, pnd_filter_list[i]);
442         system(buf);
443         old = which;
444 }
445
446 static menu_entry e_menu_gfx_options[];
447
448 static void pnd_menu_init(void)
449 {
450         struct dirent *ent;
451         int i, count = 0;
452         char **mfilters;
453         char buff[64], *p;
454         DIR *dir;
455
456         cpu_clock_st = cpu_clock = get_cpu_clock();
457
458         dir = opendir("/etc/pandora/conf/dss_fir");
459         if (dir == NULL) {
460                 perror("filter opendir");
461                 return;
462         }
463
464         while (1) {
465                 errno = 0;
466                 ent = readdir(dir);
467                 if (ent == NULL) {
468                         if (errno != 0)
469                                 perror("readdir");
470                         break;
471                 }
472                 p = strstr(ent->d_name, "_up");
473                 if (p != NULL && (p[3] == 0 || !strcmp(p + 3, "_h")))
474                         count++;
475         }
476
477         if (count == 0)
478                 return;
479
480         mfilters = calloc(count + 1, sizeof(mfilters[0]));
481         if (mfilters == NULL)
482                 return;
483
484         rewinddir(dir);
485         for (i = 0; (ent = readdir(dir)); ) {
486                 size_t len;
487
488                 p = strstr(ent->d_name, "_up");
489                 if (p == NULL || (p[3] != 0 && strcmp(p + 3, "_h")))
490                         continue;
491
492                 len = p - ent->d_name;
493                 if (len > sizeof(buff) - 1)
494                         continue;
495
496                 strncpy(buff, ent->d_name, len);
497                 buff[len] = 0;
498                 mfilters[i] = strdup(buff);
499                 if (mfilters[i] != NULL)
500                         i++;
501         }
502         closedir(dir);
503
504         i = me_id2offset(e_menu_gfx_options, MA_OPT_FILTERING);
505         e_menu_gfx_options[i].data = (void *)mfilters;
506         pnd_filter_list = mfilters;
507 }
508
509 void menu_finish(void)
510 {
511         cpu_clock = cpu_clock_st;
512         apply_cpu_clock();
513 }
514
515 // -------------- key config --------------
516
517 me_bind_action me_ctrl_actions[] =
518 {
519         { "UP      ", 1 << DKEY_UP},
520         { "DOWN    ", 1 << DKEY_DOWN },
521         { "LEFT    ", 1 << DKEY_LEFT },
522         { "RIGHT   ", 1 << DKEY_RIGHT },
523         { "TRIANGLE", 1 << DKEY_TRIANGLE },
524         { "CIRCLE  ", 1 << DKEY_CIRCLE },
525         { "CROSS   ", 1 << DKEY_CROSS },
526         { "SQUARE  ", 1 << DKEY_SQUARE },
527         { "L1      ", 1 << DKEY_L1 },
528         { "R1      ", 1 << DKEY_R1 },
529         { "L2      ", 1 << DKEY_L2 },
530         { "R2      ", 1 << DKEY_R2 },
531         { "START   ", 1 << DKEY_START },
532         { "SELECT  ", 1 << DKEY_SELECT },
533         { NULL,       0 }
534 };
535
536 me_bind_action emuctrl_actions[] =
537 {
538 /*
539         { "Load State       ", PEV_STATE_LOAD },
540         { "Save State       ", PEV_STATE_SAVE },
541         { "Prev Save Slot   ", PEV_SSLOT_PREV },
542         { "Next Save Slot   ", PEV_SSLOT_NEXT },
543 */
544         { "Enter Menu       ", PEV_MENU },
545         { NULL,                0 }
546 };
547
548 static int key_config_loop_wrap(int id, int keys)
549 {
550         switch (id) {
551                 case MA_CTRL_PLAYER1:
552                         key_config_loop(me_ctrl_actions, array_size(me_ctrl_actions) - 1, 0);
553                         break;
554                 case MA_CTRL_PLAYER2:
555                         key_config_loop(me_ctrl_actions, array_size(me_ctrl_actions) - 1, 1);
556                         break;
557                 case MA_CTRL_EMU:
558                         key_config_loop(emuctrl_actions, array_size(emuctrl_actions) - 1, -1);
559                         break;
560                 default:
561                         break;
562         }
563         return 0;
564 }
565
566 static const char *mgn_dev_name(int id, int *offs)
567 {
568         const char *name = NULL;
569         static int it = 0;
570
571         if (id == MA_CTRL_DEV_FIRST)
572                 it = 0;
573
574         for (; it < IN_MAX_DEVS; it++) {
575                 name = in_get_dev_name(it, 1, 1);
576                 if (name != NULL)
577                         break;
578         }
579
580         it++;
581         return name;
582 }
583
584 static const char *mgn_saveloadcfg(int id, int *offs)
585 {
586         return "";
587 }
588
589 static int mh_savecfg(int id, int keys)
590 {
591         if (menu_write_config(id == MA_OPT_SAVECFG_GAME ? 1 : 0) == 0)
592                 me_update_msg("config saved");
593         else
594                 me_update_msg("failed to write config");
595
596         return 1;
597 }
598
599 static menu_entry e_menu_keyconfig[] =
600 {
601         mee_handler_id("Player 1",          MA_CTRL_PLAYER1,    key_config_loop_wrap),
602         mee_handler_id("Player 2",          MA_CTRL_PLAYER2,    key_config_loop_wrap),
603         mee_handler_id("Emulator controls", MA_CTRL_EMU,        key_config_loop_wrap),
604 //      mee_cust_nosave("Save global config",       MA_OPT_SAVECFG, mh_savecfg, mgn_saveloadcfg),
605 //      mee_cust_nosave("Save cfg for loaded game", MA_OPT_SAVECFG_GAME, mh_savecfg, mgn_saveloadcfg),
606         mee_label     (""),
607         mee_label     ("Input devices:"),
608         mee_label_mk  (MA_CTRL_DEV_FIRST, mgn_dev_name),
609         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
610         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
611         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
612         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
613         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
614         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
615         mee_end,
616 };
617
618 static int menu_loop_keyconfig(int id, int keys)
619 {
620         static int sel = 0;
621
622 //      me_enable(e_menu_keyconfig, MA_OPT_SAVECFG_GAME, ready_to_go);
623         me_loop(e_menu_keyconfig, &sel, NULL);
624         return 0;
625 }
626
627 // ------------ gfx options menu ------------
628
629 static const char *men_scaler[] = { "1x1", "scaled 4:3", "fullscreen", "custom", NULL };
630 static const char h_cscaler[]   = "Displays the scaler layer, you can resize it\n"
631                                   "using d-pad or move it using R+d-pad";
632 static const char *men_dummy[] = { NULL };
633
634 static int menu_loop_cscaler(int id, int keys)
635 {
636         unsigned int inp;
637
638         scaling = SCALE_CUSTOM;
639
640         omap_enable_layer(1);
641
642         for (;;)
643         {
644                 menu_draw_begin(0);
645                 memset(g_menuscreen_ptr, 4, g_menuscreen_w * g_menuscreen_h * 2);
646                 text_out16(2, 2, "%d,%d", g_layer_x, g_layer_y);
647                 text_out16(2, 480 - 18, "%dx%d | d-pad: resize, R+d-pad: move", g_layer_w, g_layer_h);
648                 menu_draw_end();
649
650                 inp = in_menu_wait(PBTN_UP|PBTN_DOWN|PBTN_LEFT|PBTN_RIGHT|PBTN_R|PBTN_MOK|PBTN_MBACK, 40);
651                 if (inp & PBTN_UP)    g_layer_y--;
652                 if (inp & PBTN_DOWN)  g_layer_y++;
653                 if (inp & PBTN_LEFT)  g_layer_x--;
654                 if (inp & PBTN_RIGHT) g_layer_x++;
655                 if (!(inp & PBTN_R)) {
656                         if (inp & PBTN_UP)    g_layer_h += 2;
657                         if (inp & PBTN_DOWN)  g_layer_h -= 2;
658                         if (inp & PBTN_LEFT)  g_layer_w += 2;
659                         if (inp & PBTN_RIGHT) g_layer_w -= 2;
660                 }
661                 if (inp & (PBTN_MOK|PBTN_MBACK))
662                         break;
663
664                 if (inp & (PBTN_UP|PBTN_DOWN|PBTN_LEFT|PBTN_RIGHT)) {
665                         if (g_layer_x < 0)   g_layer_x = 0;
666                         if (g_layer_x > 640) g_layer_x = 640;
667                         if (g_layer_y < 0)   g_layer_y = 0;
668                         if (g_layer_y > 420) g_layer_y = 420;
669                         if (g_layer_w < 160) g_layer_w = 160;
670                         if (g_layer_h < 60)  g_layer_h = 60;
671                         if (g_layer_x + g_layer_w > 800)
672                                 g_layer_w = 800 - g_layer_x;
673                         if (g_layer_y + g_layer_h > 480)
674                                 g_layer_h = 480 - g_layer_y;
675                         omap_enable_layer(1);
676                 }
677         }
678
679         omap_enable_layer(0);
680
681         return 0;
682 }
683
684 static menu_entry e_menu_gfx_options[] =
685 {
686         mee_enum      ("Scaler",                   0, scaling, men_scaler),
687         mee_enum      ("Filter",                   MA_OPT_FILTERING, filter, men_dummy),
688 //      mee_onoff     ("Vsync",                    0, vsync, 1),
689         mee_cust_h    ("Setup custom scaler",      0, menu_loop_cscaler, NULL, h_cscaler),
690         mee_end,
691 };
692
693 static int menu_loop_gfx_options(int id, int keys)
694 {
695         static int sel = 0;
696
697         me_loop(e_menu_gfx_options, &sel, NULL);
698
699         return 0;
700 }
701
702 // ------------ bios/plugins ------------
703
704 static const char *men_gpu_dithering[] = { "None", "Game dependant", "Always", NULL };
705 static const char h_gpu_0[]            = "Needed for Chrono Cross";
706 static const char h_gpu_1[]            = "Capcom fighting games";
707 static const char h_gpu_2[]            = "Black screens in Lunar";
708 static const char h_gpu_3[]            = "Compatibility mode";
709 static const char h_gpu_6[]            = "Pandemonium 2";
710 static const char h_gpu_7[]            = "Skip every second frame";
711 static const char h_gpu_8[]            = "Needed by Dark Forces";
712 static const char h_gpu_9[]            = "better g-colors, worse textures";
713 static const char h_gpu_10[]           = "Toggle busy flags after drawing";
714
715 static menu_entry e_menu_plugin_gpu[] =
716 {
717         mee_enum      ("Dithering",                  0, iUseDither, men_gpu_dithering),
718         mee_onoff_h   ("Odd/even bit hack",          0, dwActFixes, 1<<0, h_gpu_0),
719         mee_onoff_h   ("Expand screen width",        0, dwActFixes, 1<<1, h_gpu_1),
720         mee_onoff_h   ("Ignore brightness color",    0, dwActFixes, 1<<2, h_gpu_2),
721         mee_onoff_h   ("Disable coordinate check",   0, dwActFixes, 1<<3, h_gpu_3),
722         mee_onoff_h   ("Lazy screen update",         0, dwActFixes, 1<<6, h_gpu_6),
723         mee_onoff_h   ("Old frame skipping",         0, dwActFixes, 1<<7, h_gpu_7),
724         mee_onoff_h   ("Repeated flat tex triangles ",0,dwActFixes, 1<<8, h_gpu_8),
725         mee_onoff_h   ("Draw quads with triangles",  0, dwActFixes, 1<<9, h_gpu_9),
726         mee_onoff_h   ("Fake 'gpu busy' states",     0, dwActFixes, 1<<10, h_gpu_10),
727         mee_end,
728 };
729
730 static int menu_loop_plugin_gpu(int id, int keys)
731 {
732         static int sel = 0;
733         me_loop(e_menu_plugin_gpu, &sel, NULL);
734         return 0;
735 }
736
737 static const char *men_spu_reverb[] = { "Off", "Fake", "On", NULL };
738 static const char *men_spu_interp[] = { "None", "Simple", "Gaussian", "Cubic", NULL };
739 static const char h_spu_irq_wait[]  = "Wait for CPU; only useful for some games, may cause glitches";
740 static const char h_spu_thread[]    = "Run sound emulation in separate thread";
741
742 static menu_entry e_menu_plugin_spu[] =
743 {
744         mee_enum      ("Reverb",                    0, iUseReverb, men_spu_reverb),
745         mee_enum      ("Interpolation",             0, iUseInterpolation, men_spu_interp),
746         mee_onoff     ("Adjust XA pitch",           0, iXAPitch, 1),
747         mee_onoff_h   ("SPU IRQ Wait",              0, iSPUIRQWait, 1, h_spu_irq_wait),
748         mee_onoff_h   ("Use sound thread",          0, iUseTimer, 1, h_spu_thread),
749         mee_end,
750 };
751
752 static int menu_loop_plugin_spu(int id, int keys)
753 {
754         static int sel = 0;
755         me_loop(e_menu_plugin_spu, &sel, NULL);
756         return 0;
757 }
758
759 static const char h_gpu[]        = "Configure built-in P.E.Op.S. SoftGL Driver V1.17";
760 static const char h_spu[]        = "Configure built-in P.E.Op.S. Sound Driver V1.7";
761 static const char h_plugin_xpu[] = "Must save config and reload the game\n"
762                                    "for plugin change to take effect";
763
764 static menu_entry e_menu_plugin_options[] =
765 {
766         mee_enum_h    ("GPU plugin",                    0, gpu_plugsel, gpu_plugins, h_plugin_xpu),
767         mee_enum_h    ("SPU plugin",                    0, spu_plugsel, spu_plugins, h_plugin_xpu),
768         mee_handler_h ("Configure built-in GPU plugin", menu_loop_plugin_gpu, h_gpu),
769         mee_handler_h ("Configure built-in SPU plugin", menu_loop_plugin_spu, h_spu),
770         mee_end,
771 };
772
773 static int menu_loop_plugin_options(int id, int keys)
774 {
775         static int sel = 0;
776         me_loop(e_menu_plugin_options, &sel, NULL);
777
778         // sync plugins
779         snprintf(Config.Gpu, sizeof(Config.Gpu), "%s", gpu_plugins[gpu_plugsel]);
780         snprintf(Config.Spu, sizeof(Config.Spu), "%s", spu_plugins[spu_plugsel]);
781
782         return 0;
783 }
784
785 // ------------ adv options menu ------------
786
787 static const char h_cfg_cpul[]   = "Shows CPU usage in %%";
788 static const char h_cfg_fl[]     = "Keeps the game from running too fast";
789 static const char h_cfg_xa[]     = "Disables XA sound, which can sometimes improve performance";
790 static const char h_cfg_cdda[]   = "Disable CD Audio for a performance boost\n"
791                                    "(proper .cue/.bin dump is needed otherwise)";
792 static const char h_cfg_sio[]    = "This should be enabled for certain memcards/gamepads";
793 static const char h_cfg_spuirq[] = "Compatibility tweak; should probably be left off";
794 static const char h_cfg_rcnt1[]  = "Parasite Eve 2, Vandal Hearts 1/2 Fix";
795 static const char h_cfg_rcnt2[]  = "InuYasha Sengoku Battle Fix";
796
797 static menu_entry e_menu_adv_options[] =
798 {
799         mee_onoff_h   ("Show CPU load",          0, g_opts, OPT_SHOWCPU, h_cfg_cpul),
800         mee_onoff_h   ("Frame Limiter",          0, UseFrameLimit, 1, h_cfg_fl),
801         mee_onoff_h   ("Disable XA Decoding",    0, Config.Xa, 1, h_cfg_xa),
802         mee_onoff_h   ("Disable CD Audio",       0, Config.Cdda, 1, h_cfg_cdda),
803         mee_onoff_h   ("SIO IRQ Always Enabled", 0, Config.Sio, 1, h_cfg_sio),
804         mee_onoff_h   ("SPU IRQ Always Enabled", 0, Config.SpuIrq, 1, h_cfg_spuirq),
805         mee_onoff_h   ("Rootcounter hack",       0, Config.RCntFix, 1, h_cfg_rcnt1),
806         mee_onoff_h   ("Rootcounter hack 2",     0, Config.VSyncWA, 1, h_cfg_rcnt2),
807         mee_end,
808 };
809
810 static int menu_loop_adv_options(int id, int keys)
811 {
812         static int sel = 0;
813         me_loop(e_menu_adv_options, &sel, NULL);
814         return 0;
815 }
816
817 // ------------ options menu ------------
818
819 static int mh_restore_defaults(int id, int keys)
820 {
821         menu_set_defconfig();
822         me_update_msg("defaults restored");
823         return 1;
824 }
825
826 static const char *men_region[]       = { "NTSC", "PAL", NULL };
827 /*
828 static const char *men_confirm_save[] = { "OFF", "writes", "loads", "both", NULL };
829 static const char h_confirm_save[]    = "Ask for confirmation when overwriting save,\n"
830                                         "loading state or both";
831 */
832 static const char h_restore_def[]     = "Switches back to default / recommended\n"
833                                         "configuration";
834
835 static menu_entry e_menu_options[] =
836 {
837 //      mee_range     ("Save slot",                0, state_slot, 0, 9),
838 //      mee_enum_h    ("Confirm savestate",        0, dummy, men_confirm_save, h_confirm_save),
839         mee_onoff     ("Frameskip",                0, UseFrameSkip, 1),
840         mee_onoff     ("Show FPS",                 0, g_opts, OPT_SHOWFPS),
841         mee_enum      ("Region",                   0, Config.PsxType, men_region),
842         mee_range     ("CPU clock",                MA_OPT_CPU_CLOCKS, cpu_clock, 20, 5000),
843         mee_handler   ("[Display]",                menu_loop_gfx_options),
844         mee_handler   ("[BIOS/Plugins]",           menu_loop_plugin_options),
845         mee_handler   ("[Advanced]",               menu_loop_adv_options),
846         mee_cust_nosave("Save global config",      MA_OPT_SAVECFG,      mh_savecfg, mgn_saveloadcfg),
847         mee_cust_nosave("Save cfg for loaded game",MA_OPT_SAVECFG_GAME, mh_savecfg, mgn_saveloadcfg),
848         mee_handler_h ("Restore default config",   mh_restore_defaults, h_restore_def),
849         mee_end,
850 };
851
852 static int menu_loop_options(int id, int keys)
853 {
854         static int sel = 0;
855         int i;
856
857         i = me_id2offset(e_menu_options, MA_OPT_CPU_CLOCKS);
858         e_menu_options[i].enabled = cpu_clock != 0 ? 1 : 0;
859         me_enable(e_menu_options, MA_OPT_SAVECFG_GAME, ready_to_go);
860
861         me_loop(e_menu_options, &sel, NULL);
862
863         return 0;
864 }
865
866 // ------------ debug menu ------------
867
868 static void draw_frame_debug(void)
869 {
870         smalltext_out16(4, 1, "build: "__DATE__ " " __TIME__ " " REV, 0xe7fc);
871 }
872
873 static void debug_menu_loop(void)
874 {
875         int inp;
876
877         while (1)
878         {
879                 menu_draw_begin(1);
880                 draw_frame_debug();
881                 menu_draw_end();
882
883                 inp = in_menu_wait(PBTN_MOK|PBTN_MBACK|PBTN_MA2|PBTN_MA3|PBTN_L|PBTN_R |
884                                         PBTN_UP|PBTN_DOWN|PBTN_LEFT|PBTN_RIGHT, 70);
885                 if (inp & PBTN_MBACK)
886                         return;
887         }
888 }
889
890 // ------------ main menu ------------
891
892 void OnFile_Exit();
893
894 const char *plat_get_credits(void)
895 {
896         return  "PCSX-ReARMed\n\n"
897                 "(C) 1999-2003 PCSX Team\n"
898                 "(C) 2005-2009 PCSX-df Team\n"
899                 "(C) 2009-2010 PCSX-Reloaded Team\n\n"
900                 "GPU and SPU code by Pete Bernert\n"
901                 "  and the P.E.Op.S. team\n"
902                 "ARM recompiler (C) 2009-2010 Ari64\n\n"
903                 "integration, optimization and\n"
904                 "  frontend (C) 2010-2011 notaz\n";
905 }
906
907 static int run_cd_image(const char *fname)
908 {
909         extern void set_cd_image(const char *fname);
910         ready_to_go = 0;
911         pl_fbdev_buf = NULL;
912
913         ClosePlugins();
914         set_cd_image(fname);
915         LoadPlugins();
916         NetOpened = 0;
917         if (OpenPlugins() == -1) {
918                 me_update_msg("failed to open plugins");
919                 return -1;
920         }
921         plugin_call_rearmed_cbs();
922
923         if (CheckCdrom() == -1) {
924                 // Only check the CD if we are starting the console with a CD
925                 ClosePlugins();
926                 me_update_msg("unsupported/invalid CD image");
927                 return -1;
928         }
929
930         SysReset();
931
932         // Read main executable directly from CDRom and start it
933         if (LoadCdrom() == -1) {
934                 ClosePlugins();
935                 me_update_msg("failed to load CD image");
936                 return -1;
937         }
938
939         ready_to_go = 1;
940         return 0;
941 }
942
943 static int romsel_run(void)
944 {
945         int prev_gpu, prev_spu;
946         char *fname;
947
948         fname = menu_loop_romsel(last_selected_fname, sizeof(last_selected_fname));
949         if (fname == NULL)
950                 return -1;
951
952         printf("selected file: %s\n", fname);
953
954         if (run_cd_image(fname) != 0)
955                 return -1;
956
957         prev_gpu = gpu_plugsel;
958         prev_spu = spu_plugsel;
959         if (menu_load_config(1) != 0)
960                 menu_load_config(0);
961
962         // check for plugin changes, have to repeat
963         // loading if game config changed plugins to reload them
964         if (prev_gpu != gpu_plugsel || prev_spu != spu_plugsel) {
965                 printf("plugin change detected, reloading plugins..\n");
966                 if (run_cd_image(fname) != 0)
967                         return -1;
968         }
969
970         strcpy(last_selected_fname, rom_fname_reload);
971         return 0;
972 }
973
974 static int main_menu_handler(int id, int keys)
975 {
976         switch (id)
977         {
978         case MA_MAIN_RESUME_GAME:
979                 if (ready_to_go)
980                         return 1;
981                 break;
982         case MA_MAIN_SAVE_STATE:
983                 if (ready_to_go)
984                         return menu_loop_savestate(0);
985                 break;
986         case MA_MAIN_LOAD_STATE:
987                 if (ready_to_go)
988                         return menu_loop_savestate(1);
989                 break;
990         case MA_MAIN_RESET_GAME:
991                 if (ready_to_go) {
992                         ClosePlugins();
993                         OpenPlugins();
994                         SysReset();
995                         if (CheckCdrom() != -1) {
996                                 LoadCdrom();
997                         }
998                         return 1;
999                 }
1000                 break;
1001         case MA_MAIN_LOAD_ROM:
1002                 if (romsel_run() == 0)
1003                         return 1;
1004                 break;
1005         case MA_MAIN_CREDITS:
1006                 draw_menu_credits(draw_frame_debug);
1007                 in_menu_wait(PBTN_MOK|PBTN_MBACK, 70);
1008                 break;
1009         case MA_MAIN_EXIT:
1010                 OnFile_Exit();
1011                 break;
1012         default:
1013                 lprintf("%s: something unknown selected\n", __FUNCTION__);
1014                 break;
1015         }
1016
1017         return 0;
1018 }
1019
1020 static menu_entry e_menu_main[] =
1021 {
1022         mee_label     (""),
1023         mee_label     (""),
1024         mee_handler_id("Resume game",        MA_MAIN_RESUME_GAME, main_menu_handler),
1025         mee_handler_id("Save State",         MA_MAIN_SAVE_STATE,  main_menu_handler),
1026         mee_handler_id("Load State",         MA_MAIN_LOAD_STATE,  main_menu_handler),
1027         mee_handler_id("Reset game",         MA_MAIN_RESET_GAME,  main_menu_handler),
1028         mee_handler_id("Load CD image",      MA_MAIN_LOAD_ROM,    main_menu_handler),
1029         mee_handler   ("Options",            menu_loop_options),
1030         mee_handler   ("Controls",           menu_loop_keyconfig),
1031         mee_handler_id("Credits",            MA_MAIN_CREDITS,     main_menu_handler),
1032         mee_handler_id("Exit",               MA_MAIN_EXIT,        main_menu_handler),
1033         mee_end,
1034 };
1035
1036 // ----------------------------
1037
1038 static void menu_leave_emu(void);
1039
1040 void menu_loop(void)
1041 {
1042         static int sel = 0;
1043
1044         menu_leave_emu();
1045
1046         me_enable(e_menu_main, MA_MAIN_RESUME_GAME, ready_to_go);
1047         me_enable(e_menu_main, MA_MAIN_SAVE_STATE,  ready_to_go);
1048         me_enable(e_menu_main, MA_MAIN_LOAD_STATE,  ready_to_go);
1049         me_enable(e_menu_main, MA_MAIN_RESET_GAME,  ready_to_go);
1050
1051 //      menu_enter(ready_to_go);
1052         in_set_config_int(0, IN_CFG_BLOCKING, 1);
1053
1054         do {
1055                 me_loop(e_menu_main, &sel, NULL);
1056         } while (!ready_to_go);
1057
1058         /* wait until menu, ok, back is released */
1059         while (in_menu_wait_any(50) & (PBTN_MENU|PBTN_MOK|PBTN_MBACK))
1060                 ;
1061
1062         in_set_config_int(0, IN_CFG_BLOCKING, 0);
1063
1064         menu_prepare_emu();
1065 }
1066
1067 static void scan_plugins(void)
1068 {
1069         char fname[MAXPATHLEN];
1070         struct dirent *ent;
1071         int gpu_i, spu_i;
1072         char *p;
1073         DIR *dir;
1074
1075         gpu_plugins[0] = "builtin_gpu";
1076         spu_plugins[0] = "builtin_spu";
1077         gpu_i = spu_i = 1;
1078
1079         snprintf(fname, sizeof(fname), "%s/", Config.PluginsDir);
1080         dir = opendir(fname);
1081         if (dir == NULL) {
1082                 perror("scan_plugins opendir");
1083                 return;
1084         }
1085
1086         while (1) {
1087                 void *h, *tmp;
1088
1089                 errno = 0;
1090                 ent = readdir(dir);
1091                 if (ent == NULL) {
1092                         if (errno != 0)
1093                                 perror("readdir");
1094                         break;
1095                 }
1096                 p = strstr(ent->d_name, ".so");
1097                 if (p == NULL)
1098                         continue;
1099
1100                 snprintf(fname, sizeof(fname), "%s/%s", Config.PluginsDir, ent->d_name);
1101                 h = dlopen(fname, RTLD_LAZY | RTLD_LOCAL);
1102                 if (h == NULL) {
1103                         fprintf(stderr, "%s\n", dlerror());
1104                         continue;
1105                 }
1106
1107                 // now what do we have here?
1108                 tmp = dlsym(h, "GPUinit");
1109                 if (tmp) {
1110                         dlclose(h);
1111                         if (gpu_i < ARRAY_SIZE(gpu_plugins) - 1)
1112                                 gpu_plugins[gpu_i++] = strdup(ent->d_name);
1113                         continue;
1114                 }
1115
1116                 tmp = dlsym(h, "SPUinit");
1117                 if (tmp) {
1118                         dlclose(h);
1119                         if (spu_i < ARRAY_SIZE(spu_plugins) - 1)
1120                                 spu_plugins[spu_i++] = strdup(ent->d_name);
1121                         continue;
1122                 }
1123
1124                 fprintf(stderr, "ignoring unidentified plugin: %s\n", fname);
1125                 dlclose(h);
1126         }
1127
1128         closedir(dir);
1129 }
1130
1131 void menu_init(void)
1132 {
1133         char buff[MAXPATHLEN];
1134
1135         strcpy(last_selected_fname, "/media");
1136
1137         scan_plugins();
1138         pnd_menu_init();
1139         menu_init_common();
1140
1141         menu_set_defconfig();
1142         menu_load_config(0);
1143         last_psx_w = 320;
1144         last_psx_h = 240;
1145         last_psx_bpp = 16;
1146
1147         g_menubg_src_ptr = calloc(g_menuscreen_w * g_menuscreen_h * 2, 1);
1148         if (g_menubg_src_ptr == NULL)
1149                 exit(1);
1150         emu_make_path(buff, "skin/background.png", sizeof(buff));
1151         readpng(g_menubg_src_ptr, buff, READPNG_BG, g_menuscreen_w, g_menuscreen_h);
1152 }
1153
1154 void menu_notify_mode_change(int w, int h, int bpp)
1155 {
1156         last_psx_w = w;
1157         last_psx_h = h;
1158         last_psx_bpp = bpp;
1159
1160         if (scaling == SCALE_1_1) {
1161                 g_layer_x = 800/2 - w/2;  g_layer_y = 480/2 - h/2;
1162                 g_layer_w = w; g_layer_h = h;
1163         }
1164 }
1165
1166 static void menu_leave_emu(void)
1167 {
1168         if (GPU_close != NULL) {
1169                 int ret = GPU_close();
1170                 if (ret)
1171                         fprintf(stderr, "Warning: GPU_close returned %d\n", ret);
1172         }
1173
1174         memcpy(g_menubg_ptr, g_menubg_src_ptr, g_menuscreen_w * g_menuscreen_h * 2);
1175         if (pl_fbdev_buf != NULL && ready_to_go && last_psx_bpp == 16) {
1176                 int x = max(0, g_menuscreen_w - last_psx_w);
1177                 int y = max(0, g_menuscreen_h / 2 - last_psx_h / 2);
1178                 int w = min(g_menuscreen_w, last_psx_w);
1179                 int h = min(g_menuscreen_h, last_psx_h);
1180                 u16 *d = (u16 *)g_menubg_ptr + g_menuscreen_w * y + x;
1181                 u16 *s = pl_fbdev_buf;
1182
1183                 for (; h > 0; h--, d += g_menuscreen_w, s += last_psx_w)
1184                         menu_darken_bg(d, s, w, 0);
1185         }
1186
1187         plat_video_menu_enter(ready_to_go);
1188 }
1189
1190 void menu_prepare_emu(void)
1191 {
1192         plat_video_menu_leave();
1193
1194         switch (scaling) {
1195         case SCALE_1_1:
1196                 menu_notify_mode_change(last_psx_w, last_psx_h, last_psx_bpp);
1197                 break;
1198         case SCALE_4_3:
1199                 g_layer_x = 80;  g_layer_y = 0;
1200                 g_layer_w = 640; g_layer_h = 480;
1201                 break;
1202         case SCALE_FULLSCREEN:
1203                 g_layer_x = 0;   g_layer_y = 0;
1204                 g_layer_w = 800; g_layer_h = 480;
1205                 break;
1206         case SCALE_CUSTOM:
1207                 break;
1208         }
1209         apply_filter(filter);
1210         apply_cpu_clock();
1211         stop = 0;
1212
1213         // core doesn't care about Config.Cdda changes,
1214         // so handle them manually here
1215         if (Config.Cdda)
1216                 CDR_stop();
1217
1218         // HACK to set up the frame limiter if softgpu is not used..
1219         if (gpu_plugsel != 0) {
1220                 fFrameRateHz = Config.PsxType ? 50.0f : 59.94f;
1221                 dwFrameRateTicks = (100000*100 / (unsigned long)(fFrameRateHz*100));
1222         }
1223
1224         if (GPU_open != NULL) {
1225                 int ret = GPU_open(&gpuDisp, "PCSX", NULL);
1226                 if (ret)
1227                         fprintf(stderr, "Warning: GPU_open returned %d\n", ret);
1228         }
1229 }
1230
1231 void me_update_msg(const char *msg)
1232 {
1233         strncpy(menu_error_msg, msg, sizeof(menu_error_msg));
1234         menu_error_msg[sizeof(menu_error_msg) - 1] = 0;
1235
1236         menu_error_time = plat_get_ticks_ms();
1237         lprintf("msg: %s\n", menu_error_msg);
1238 }
1239