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