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