e0f7c66ef4c5c7eccc85215d861cf2236e7efeda
[libpicofe.git] / common / menu_pico.c
1 #include <string.h>
2
3 #include "emu.h"
4 #include "menu_pico.h"
5
6 #include <version.h>
7 #include <revision.h>
8
9 #include <pico/pico.h>
10 #include <pico/patch.h>
11
12 // rrrr rggg gggb bbbb
13 static unsigned short fname2color(const char *fname)
14 {
15         const char *ext = fname + strlen(fname) - 3;
16         static const char *rom_exts[]   = { "zip", "bin", "smd", "gen", "iso", "cso", "cue" };
17         static const char *other_exts[] = { "gmv", "pat" };
18         int i;
19
20         if (ext < fname) ext = fname;
21         for (i = 0; i < array_size(rom_exts); i++)
22                 if (strcasecmp(ext, rom_exts[i]) == 0) return 0xbdff; // FIXME: mk defines
23         for (i = 0; i < array_size(other_exts); i++)
24                 if (strcasecmp(ext, other_exts[i]) == 0) return 0xaff5;
25         return 0xffff;
26 }
27
28 static const char *filter_exts[] = {
29         ".mp3", ".MP3", ".srm", ".brm", "s.gz", ".mds", "bcfg", ".txt", ".htm", "html",
30         ".jpg", ".gpe"
31 };
32
33 #include "menu.c"
34
35 /* platform specific options and handlers */
36 #if   defined(__GP2X__)
37 #include "../gp2x/menu.c"
38 #elif defined(PANDORA)
39 #include "../pandora/menu.c"
40 #else
41 #define MENU_OPTIONS_GFX
42 #define MENU_OPTIONS_ADV
43 #define menu_main_plat_draw NULL
44 #endif
45
46 static void menu_enter(int is_rom_loaded)
47 {
48         if (is_rom_loaded)
49         {
50                 // darken the active framebuffer
51                 menu_darken_bg(g_menubg_ptr, g_menubg_src_ptr, g_menuscreen_w * g_menuscreen_h, 1);
52         }
53         else
54         {
55                 char buff[256];
56
57                 // should really only happen once, on startup..
58                 emu_make_path(buff, "skin/background.png", sizeof(buff));
59                 if (readpng(g_menubg_ptr, buff, READPNG_BG, g_menuscreen_w, g_menuscreen_h) < 0)
60                         memset(g_menubg_ptr, 0, g_menuscreen_w * g_menuscreen_h * 2);
61         }
62
63         plat_video_menu_enter(is_rom_loaded);
64 }
65
66 static void draw_savestate_bg(int slot)
67 {
68         const char *fname;
69         void *tmp_state;
70
71         fname = emu_get_save_fname(1, 0, slot);
72         if (!fname)
73                 return;
74
75         tmp_state = PicoTmpStateSave();
76
77         PicoStateLoadGfx(fname);
78
79         /* do a frame and fetch menu bg */
80         pemu_forced_frame(0, 0);
81
82         menu_darken_bg(g_menubg_ptr, g_menubg_src_ptr, g_menuscreen_w * g_menuscreen_h, 1);
83
84         PicoTmpStateRestore(tmp_state);
85 }
86
87 // --------- loading ROM screen ----------
88
89 static int cdload_called = 0;
90
91 static void load_progress_cb(int percent)
92 {
93         int ln, len = percent * g_menuscreen_w / 100;
94         unsigned short *dst;
95
96         if (len > g_menuscreen_w)
97                 len = g_menuscreen_w;
98
99         menu_draw_begin(0);
100         dst = (unsigned short *)g_menuscreen_ptr + g_menuscreen_w * me_sfont_h * 2;
101         for (ln = me_sfont_h - 2; ln > 0; ln--, dst += g_menuscreen_w)
102                 memset(dst, 0xff, len * 2);
103         menu_draw_end();
104 }
105
106 static void cdload_progress_cb(const char *fname, int percent)
107 {
108         int ln, len = percent * g_menuscreen_w / 100;
109         unsigned short *dst;
110
111         menu_draw_begin(0);
112         dst = (unsigned short *)g_menuscreen_ptr + g_menuscreen_w * me_sfont_h * 2;
113         memset(dst, 0xff, g_menuscreen_w * (me_sfont_h - 2) * 2);
114
115         smalltext_out16(1, 3 * me_sfont_h, "Processing CD image / MP3s", 0xffff);
116         smalltext_out16(1, 4 * me_sfont_h, fname, 0xffff);
117         dst += g_menuscreen_w * me_sfont_h * 3;
118
119         if (len > g_menuscreen_w)
120                 len = g_menuscreen_w;
121
122         for (ln = (me_sfont_h - 2); ln > 0; ln--, dst += g_menuscreen_w)
123                 memset(dst, 0xff, len * 2);
124         menu_draw_end();
125
126         cdload_called = 1;
127 }
128
129 void menu_romload_prepare(const char *rom_name)
130 {
131         const char *p = rom_name + strlen(rom_name);
132         int i;
133
134         while (p > rom_name && *p != '/')
135                 p--;
136
137         /* fill all buffers, callbacks won't update in full */
138         for (i = 0; i < 3; i++) {
139                 menu_draw_begin(1);
140                 smalltext_out16(1, 1, "Loading", 0xffff);
141                 smalltext_out16(1, me_sfont_h, p, 0xffff);
142                 menu_draw_end();
143         }
144
145         PicoCartLoadProgressCB = load_progress_cb;
146         PicoCDLoadProgressCB = cdload_progress_cb;
147         cdload_called = 0;
148 }
149
150 void menu_romload_end(void)
151 {
152         PicoCartLoadProgressCB = NULL;
153         PicoCDLoadProgressCB = NULL;
154
155         menu_draw_begin(0);
156         smalltext_out16(1, (cdload_called ? 6 : 3) * me_sfont_h,
157                 "Starting emulation...", 0xffff);
158         menu_draw_end();
159 }
160
161 // ------------ patch/gg menu ------------
162
163 static void draw_patchlist(int sel)
164 {
165         int max_cnt, start, i, pos, active;
166
167         max_cnt = g_menuscreen_h / me_sfont_h;
168         start = max_cnt / 2 - sel;
169
170         menu_draw_begin(1);
171
172         for (i = 0; i < PicoPatchCount; i++) {
173                 pos = start + i;
174                 if (pos < 0) continue;
175                 if (pos >= max_cnt) break;
176                 active = PicoPatches[i].active;
177                 smalltext_out16(14,                pos * me_sfont_h, active ? "ON " : "OFF", active ? 0xfff6 : 0xffff);
178                 smalltext_out16(14 + me_sfont_w*4, pos * me_sfont_h, PicoPatches[i].name,    active ? 0xfff6 : 0xffff);
179         }
180         pos = start + i;
181         if (pos < max_cnt)
182                 smalltext_out16(14, pos * me_sfont_h, "done", 0xffff);
183
184         text_out16(5, max_cnt / 2 * me_sfont_h, ">");
185         menu_draw_end();
186 }
187
188 static void menu_loop_patches(void)
189 {
190         static int menu_sel = 0;
191         int inp;
192
193         for (;;)
194         {
195                 draw_patchlist(menu_sel);
196                 inp = in_menu_wait(PBTN_UP|PBTN_DOWN|PBTN_LEFT|PBTN_RIGHT|PBTN_L|PBTN_R|PBTN_MOK|PBTN_MBACK, 33);
197                 if (inp & PBTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = PicoPatchCount; }
198                 if (inp & PBTN_DOWN) { menu_sel++; if (menu_sel > PicoPatchCount) menu_sel = 0; }
199                 if (inp &(PBTN_LEFT|PBTN_L))  { menu_sel-=10; if (menu_sel < 0) menu_sel = 0; }
200                 if (inp &(PBTN_RIGHT|PBTN_R)) { menu_sel+=10; if (menu_sel > PicoPatchCount) menu_sel = PicoPatchCount; }
201                 if (inp & PBTN_MOK) { // action
202                         if (menu_sel < PicoPatchCount)
203                                 PicoPatches[menu_sel].active = !PicoPatches[menu_sel].active;
204                         else    break;
205                 }
206                 if (inp & PBTN_MBACK)
207                         break;
208         }
209 }
210
211 // -------------- key config --------------
212
213 // PicoPad[] format: MXYZ SACB RLDU
214 me_bind_action me_ctrl_actions[] =
215 {
216         { "UP     ", 0x0001 },
217         { "DOWN   ", 0x0002 },
218         { "LEFT   ", 0x0004 },
219         { "RIGHT  ", 0x0008 },
220         { "A      ", 0x0040 },
221         { "B      ", 0x0010 },
222         { "C      ", 0x0020 },
223         { "A turbo", 0x4000 },
224         { "B turbo", 0x1000 },
225         { "C turbo", 0x2000 },
226         { "START  ", 0x0080 },
227         { "MODE   ", 0x0800 },
228         { "X      ", 0x0400 },
229         { "Y      ", 0x0200 },
230         { "Z      ", 0x0100 },
231         { NULL,      0 },
232 };
233
234 me_bind_action emuctrl_actions[] =
235 {
236         { "Load State       ", PEV_STATE_LOAD },
237         { "Save State       ", PEV_STATE_SAVE },
238         { "Prev Save Slot   ", PEV_SSLOT_PREV },
239         { "Next Save Slot   ", PEV_SSLOT_NEXT },
240         { "Switch Renderer  ", PEV_SWITCH_RND },
241         { "Volume Down      ", PEV_VOL_DOWN },
242         { "Volume Up        ", PEV_VOL_UP },
243         { "Fast forward     ", PEV_FF },
244         { "Enter Menu       ", PEV_MENU },
245         { "Pico Next page   ", PEV_PICO_PNEXT },
246         { "Pico Prev page   ", PEV_PICO_PPREV },
247         { "Pico Switch input", PEV_PICO_SWINP },
248         { NULL,                0 }
249 };
250
251 static int key_config_loop_wrap(int id, int keys)
252 {
253         switch (id) {
254                 case MA_CTRL_PLAYER1:
255                         key_config_loop(me_ctrl_actions, array_size(me_ctrl_actions) - 1, 0);
256                         break;
257                 case MA_CTRL_PLAYER2:
258                         key_config_loop(me_ctrl_actions, array_size(me_ctrl_actions) - 1, 1);
259                         break;
260                 case MA_CTRL_EMU:
261                         key_config_loop(emuctrl_actions, array_size(emuctrl_actions) - 1, -1);
262                         break;
263                 default:
264                         break;
265         }
266         return 0;
267 }
268
269 static const char *mgn_dev_name(int id, int *offs)
270 {
271         const char *name = NULL;
272         static int it = 0;
273
274         if (id == MA_CTRL_DEV_FIRST)
275                 it = 0;
276
277         for (; it < IN_MAX_DEVS; it++) {
278                 name = in_get_dev_name(it, 1, 1);
279                 if (name != NULL)
280                         break;
281         }
282
283         it++;
284         return name;
285 }
286
287 static int mh_saveloadcfg(int id, int keys);
288 static const char *mgn_saveloadcfg(int id, int *offs);
289
290 static menu_entry e_menu_keyconfig[] =
291 {
292         mee_handler_id("Player 1",          MA_CTRL_PLAYER1,    key_config_loop_wrap),
293         mee_handler_id("Player 2",          MA_CTRL_PLAYER2,    key_config_loop_wrap),
294         mee_handler_id("Emulator controls", MA_CTRL_EMU,        key_config_loop_wrap),
295         mee_onoff     ("6 button pad",      MA_OPT_6BUTTON_PAD, PicoOpt, POPT_6BTN_PAD),
296         mee_range     ("Turbo rate",        MA_CTRL_TURBO_RATE, currentConfig.turbo_rate, 1, 30),
297         mee_range     ("Analog deadzone",   MA_CTRL_DEADZONE,   currentConfig.analog_deadzone, 1, 99),
298         mee_cust_nosave("Save global config",       MA_OPT_SAVECFG, mh_saveloadcfg, mgn_saveloadcfg),
299         mee_cust_nosave("Save cfg for loaded game", MA_OPT_SAVECFG_GAME, mh_saveloadcfg, mgn_saveloadcfg),
300         mee_label     (""),
301         mee_label     ("Input devices:"),
302         mee_label_mk  (MA_CTRL_DEV_FIRST, mgn_dev_name),
303         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
304         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
305         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
306         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
307         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
308         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
309         mee_end,
310 };
311
312 static int menu_loop_keyconfig(int id, int keys)
313 {
314         static int sel = 0;
315
316         me_enable(e_menu_keyconfig, MA_OPT_SAVECFG_GAME, rom_loaded);
317         me_loop(e_menu_keyconfig, &sel);
318         return 0;
319 }
320
321 // ------------ SCD options menu ------------
322
323 static const char *mgn_cdopt_ra(int id, int *offs)
324 {
325         *offs = -5;
326         if (PicoCDBuffers <= 0)
327                 return "     OFF";
328         sprintf(static_buff, "%5iK", PicoCDBuffers * 2);
329         return static_buff;
330 }
331
332 static int mh_cdopt_ra(int id, int keys)
333 {
334         if (keys & PBTN_LEFT) {
335                 PicoCDBuffers >>= 1;
336                 if (PicoCDBuffers < 2)
337                         PicoCDBuffers = 0;
338         } else {
339                 if (PicoCDBuffers <= 0)
340                         PicoCDBuffers = 1;
341                 PicoCDBuffers <<= 1;
342                 if (PicoCDBuffers > 8*1024)
343                         PicoCDBuffers = 8*1024; // 16M
344         }
345         return 0;
346 }
347
348 static const char h_cdleds[] = "Show power/CD LEDs of emulated console";
349 static const char h_cdda[]   = "Play audio tracks from mp3s/wavs/bins";
350 static const char h_cdpcm[]  = "Emulate PCM audio chip for effects/voices/music";
351 static const char h_srcart[] = "Emulate the save RAM cartridge accessory\n"
352                                 "most games don't need this";
353 static const char h_scfx[]   = "Emulate scale/rotate ASIC chip for graphics effects\n"
354                                 "disable to improve performance";
355 static const char h_bsync[]  = "More accurate mode for CPUs (needed for some games)\n"
356                                 "disable to improve performance";
357
358 static menu_entry e_menu_cd_options[] =
359 {
360         mee_onoff_h("CD LEDs",              MA_CDOPT_LEDS,          currentConfig.EmuOpt, EOPT_EN_CD_LEDS, h_cdleds),
361         mee_onoff_h("CDDA audio",           MA_CDOPT_CDDA,          PicoOpt, POPT_EN_MCD_CDDA, h_cdda),
362         mee_onoff_h("PCM audio",            MA_CDOPT_PCM,           PicoOpt, POPT_EN_MCD_PCM, h_cdpcm),
363         mee_cust   ("ReadAhead buffer",     MA_CDOPT_READAHEAD,     mh_cdopt_ra, mgn_cdopt_ra),
364         mee_onoff_h("SaveRAM cart",         MA_CDOPT_SAVERAM,       PicoOpt, POPT_EN_MCD_RAMCART, h_srcart),
365         mee_onoff_h("Scale/Rot. fx (slow)", MA_CDOPT_SCALEROT_CHIP, PicoOpt, POPT_EN_MCD_GFX, h_scfx),
366         mee_onoff_h("Better sync (slow)",   MA_CDOPT_BETTER_SYNC,   PicoOpt, POPT_EN_MCD_PSYNC, h_bsync),
367         mee_end,
368 };
369
370 static int menu_loop_cd_options(int id, int keys)
371 {
372         static int sel = 0;
373         me_loop(e_menu_cd_options, &sel);
374         return 0;
375 }
376
377 // ------------ 32X options menu ------------
378
379 #ifndef NO_32X
380
381 // convert from multiplier of VClk
382 static int mh_opt_sh2cycles(int id, int keys)
383 {
384         int *mul = (id == MA_32XOPT_MSH2_CYCLES) ? &p32x_msh2_multiplier : &p32x_ssh2_multiplier;
385
386         if (keys & (PBTN_LEFT|PBTN_RIGHT))
387                 *mul += (keys & PBTN_LEFT) ? -10 : 10;
388         if (keys & (PBTN_L|PBTN_R))
389                 *mul += (keys & PBTN_L) ? -100 : 100;
390
391         if (*mul < 1)
392                 *mul = 1;
393         else if (*mul > (10 << SH2_MULTI_SHIFT))
394                 *mul = 10 << SH2_MULTI_SHIFT;
395
396         return 0;
397 }
398
399 static const char *mgn_opt_sh2cycles(int id, int *offs)
400 {
401         int mul = (id == MA_32XOPT_MSH2_CYCLES) ? p32x_msh2_multiplier : p32x_ssh2_multiplier;
402         
403         sprintf(static_buff, "%d", 7670 * mul >> SH2_MULTI_SHIFT);
404         return static_buff;
405 }
406
407 static const char h_32x_enable[] = "Enable emulation of the 32X addon";
408 static const char h_pwm[]        = "Disabling may improve performance, but break sound";
409 static const char h_sh2cycles[]  = "Cycles/millisecond (similar to DOSBox)\n"
410                                    "lower values speed up emulation but break games\n"
411                                    "at least 11000 recommended for compatibility";
412
413 static menu_entry e_menu_32x_options[] =
414 {
415         mee_onoff_h   ("32X enabled",       MA_32XOPT_ENABLE_32X,  PicoOpt, POPT_EN_32X, h_32x_enable),
416         mee_enum      ("32X renderer",      MA_32XOPT_RENDERER,    currentConfig.renderer32x, renderer_names32x),
417         mee_onoff_h   ("PWM sound",         MA_32XOPT_PWM,         PicoOpt, POPT_EN_PWM, h_pwm),
418         mee_cust_h    ("Master SH2 cycles", MA_32XOPT_MSH2_CYCLES, mh_opt_sh2cycles, mgn_opt_sh2cycles, h_sh2cycles),
419         mee_cust_h    ("Slave SH2 cycles",  MA_32XOPT_SSH2_CYCLES, mh_opt_sh2cycles, mgn_opt_sh2cycles, h_sh2cycles),
420         mee_end,
421 };
422
423 static int menu_loop_32x_options(int id, int keys)
424 {
425         static int sel = 0;
426
427         me_enable(e_menu_32x_options, MA_32XOPT_RENDERER, renderer_names32x[0] != NULL);
428         me_loop(e_menu_32x_options, &sel);
429
430         return 0;
431 }
432
433 #endif
434
435 // ------------ adv options menu ------------
436
437 static menu_entry e_menu_adv_options[] =
438 {
439         mee_onoff     ("SRAM/BRAM saves",          MA_OPT_SRAM_STATES,    currentConfig.EmuOpt, EOPT_EN_SRAM),
440         mee_onoff     ("Disable sprite limit",     MA_OPT2_NO_SPRITE_LIM, PicoOpt, POPT_DIS_SPRITE_LIM),
441         mee_onoff     ("Emulate Z80",              MA_OPT2_ENABLE_Z80,    PicoOpt, POPT_EN_Z80),
442         mee_onoff     ("Emulate YM2612 (FM)",      MA_OPT2_ENABLE_YM2612, PicoOpt, POPT_EN_FM),
443         mee_onoff     ("Emulate SN76496 (PSG)",    MA_OPT2_ENABLE_SN76496,PicoOpt, POPT_EN_PSG),
444         mee_onoff     ("gzip savestates",          MA_OPT2_GZIP_STATES,   currentConfig.EmuOpt, EOPT_GZIP_SAVES),
445         mee_onoff     ("Don't save last used ROM", MA_OPT2_NO_LAST_ROM,   currentConfig.EmuOpt, EOPT_NO_AUTOSVCFG),
446         mee_onoff     ("Disable idle loop patching",MA_OPT2_NO_IDLE_LOOPS,PicoOpt, POPT_DIS_IDLE_DET),
447         mee_onoff     ("Disable frame limiter",    MA_OPT2_NO_FRAME_LIMIT,currentConfig.EmuOpt, EOPT_NO_FRMLIMIT),
448         MENU_OPTIONS_ADV
449         mee_end,
450 };
451
452 static int menu_loop_adv_options(int id, int keys)
453 {
454         static int sel = 0;
455         me_loop(e_menu_adv_options, &sel);
456         return 0;
457 }
458
459 // ------------ gfx options menu ------------
460
461 static menu_entry e_menu_gfx_options[] =
462 {
463         mee_enum("Renderer", MA_OPT_RENDERER, currentConfig.renderer, renderer_names),
464         MENU_OPTIONS_GFX
465         mee_end,
466 };
467
468 static int menu_loop_gfx_options(int id, int keys)
469 {
470         static int sel = 0;
471
472         me_enable(e_menu_gfx_options, MA_OPT_RENDERER, renderer_names[0] != NULL);
473         me_loop(e_menu_gfx_options, &sel);
474
475         return 0;
476 }
477
478 // ------------ options menu ------------
479
480 static menu_entry e_menu_options[];
481
482 static int sndrate_prevnext(int rate, int dir)
483 {
484         static const int rates[] = { 8000, 11025, 16000, 22050, 44100 };
485         int i;
486
487         for (i = 0; i < 5; i++)
488                 if (rates[i] == rate) break;
489
490         i += dir ? 1 : -1;
491         if (i > 4) {
492                 if (!(PicoOpt & POPT_EN_STEREO)) {
493                         PicoOpt |= POPT_EN_STEREO;
494                         return rates[0];
495                 }
496                 return rates[4];
497         }
498         if (i < 0) {
499                 if (PicoOpt & POPT_EN_STEREO) {
500                         PicoOpt &= ~POPT_EN_STEREO;
501                         return rates[4];
502                 }
503                 return rates[0];
504         }
505         return rates[i];
506 }
507
508 static void region_prevnext(int right)
509 {
510         // jp_ntsc=1, jp_pal=2, usa=4, eu=8
511         static const int rgn_orders[] = { 0x148, 0x184, 0x814, 0x418, 0x841, 0x481 };
512         int i;
513
514         if (right) {
515                 if (!PicoRegionOverride) {
516                         for (i = 0; i < 6; i++)
517                                 if (rgn_orders[i] == PicoAutoRgnOrder) break;
518                         if (i < 5) PicoAutoRgnOrder = rgn_orders[i+1];
519                         else PicoRegionOverride=1;
520                 }
521                 else
522                         PicoRegionOverride <<= 1;
523                 if (PicoRegionOverride > 8)
524                         PicoRegionOverride = 8;
525         } else {
526                 if (!PicoRegionOverride) {
527                         for (i = 0; i < 6; i++)
528                                 if (rgn_orders[i] == PicoAutoRgnOrder) break;
529                         if (i > 0) PicoAutoRgnOrder = rgn_orders[i-1];
530                 }
531                 else
532                         PicoRegionOverride >>= 1;
533         }
534 }
535
536 static int mh_opt_misc(int id, int keys)
537 {
538         switch (id) {
539         case MA_OPT_SOUND_QUALITY:
540                 PsndRate = sndrate_prevnext(PsndRate, keys & PBTN_RIGHT);
541                 break;
542         case MA_OPT_REGION:
543                 region_prevnext(keys & PBTN_RIGHT);
544                 break;
545         default:
546                 break;
547         }
548         return 0;
549 }
550
551 static int mh_saveloadcfg(int id, int keys)
552 {
553         int ret;
554
555         if (keys & (PBTN_LEFT|PBTN_RIGHT)) { // multi choice
556                 config_slot += (keys & PBTN_LEFT) ? -1 : 1;
557                 if (config_slot < 0) config_slot = 9;
558                 else if (config_slot > 9) config_slot = 0;
559                 me_enable(e_menu_options, MA_OPT_LOADCFG, config_slot != config_slot_current);
560                 return 0;
561         }
562
563         switch (id) {
564         case MA_OPT_SAVECFG:
565         case MA_OPT_SAVECFG_GAME:
566                 if (emu_write_config(id == MA_OPT_SAVECFG_GAME ? 1 : 0))
567                         me_update_msg("config saved");
568                 else
569                         me_update_msg("failed to write config");
570                 break;
571         case MA_OPT_LOADCFG:
572                 ret = emu_read_config(rom_fname_loaded, 1);
573                 if (!ret) ret = emu_read_config(NULL, 1);
574                 if (ret)  me_update_msg("config loaded");
575                 else      me_update_msg("failed to load config");
576                 break;
577         default:
578                 return 0;
579         }
580
581         return 1;
582 }
583
584 static int mh_restore_defaults(int id, int keys)
585 {
586         emu_set_defconfig();
587         me_update_msg("defaults restored");
588         return 1;
589 }
590
591 static const char *mgn_opt_fskip(int id, int *offs)
592 {
593         if (currentConfig.Frameskip < 0)
594                 return "Auto";
595         sprintf(static_buff, "%d", currentConfig.Frameskip);
596         return static_buff;
597 }
598
599 static const char *mgn_opt_sound(int id, int *offs)
600 {
601         const char *str2;
602         *offs = -8;
603         str2 = (PicoOpt & POPT_EN_STEREO) ? "stereo" : "mono";
604         sprintf(static_buff, "%5iHz %s", PsndRate, str2);
605         return static_buff;
606 }
607
608 static const char *mgn_opt_region(int id, int *offs)
609 {
610         static const char *names[] = { "Auto", "      Japan NTSC", "      Japan PAL", "      USA", "      Europe" };
611         static const char *names_short[] = { "", " JP", " JP", " US", " EU" };
612         int code = PicoRegionOverride;
613         int u, i = 0;
614
615         *offs = -6;
616         if (code) {
617                 code <<= 1;
618                 while ((code >>= 1)) i++;
619                 if (i > 4)
620                         return "unknown";
621                 return names[i];
622         } else {
623                 strcpy(static_buff, "Auto:");
624                 for (u = 0; u < 3; u++) {
625                         code = (PicoAutoRgnOrder >> u*4) & 0xf;
626                         for (i = 0; code; code >>= 1, i++)
627                                 ;
628                         strcat(static_buff, names_short[i]);
629                 }
630                 return static_buff;
631         }
632 }
633
634 static const char *mgn_saveloadcfg(int id, int *offs)
635 {
636         static_buff[0] = 0;
637         if (config_slot != 0)
638                 sprintf(static_buff, "[%i]", config_slot);
639         return static_buff;
640 }
641
642 static const char *men_confirm_save[] = { "OFF", "writes", "loads", "both", NULL };
643 static const char h_confirm_save[]    = "Ask for confirmation when overwriting save,\n"
644                                         "loading state or both";
645
646 static menu_entry e_menu_options[] =
647 {
648         mee_range     ("Save slot",                MA_OPT_SAVE_SLOT,     state_slot, 0, 9),
649         mee_range_cust("Frameskip",                MA_OPT_FRAMESKIP,     currentConfig.Frameskip, -1, 16, mgn_opt_fskip),
650         mee_cust      ("Region",                   MA_OPT_REGION,        mh_opt_misc, mgn_opt_region),
651         mee_onoff     ("Show FPS",                 MA_OPT_SHOW_FPS,      currentConfig.EmuOpt, EOPT_SHOW_FPS),
652         mee_onoff     ("Enable sound",             MA_OPT_ENABLE_SOUND,  currentConfig.EmuOpt, EOPT_EN_SOUND),
653         mee_cust      ("Sound Quality",            MA_OPT_SOUND_QUALITY, mh_opt_misc, mgn_opt_sound),
654         mee_enum_h    ("Confirm savestate",        MA_OPT_CONFIRM_STATES,currentConfig.confirm_save, men_confirm_save, h_confirm_save),
655         mee_range     ("",                         MA_OPT_CPU_CLOCKS,    currentConfig.CPUclock, 20, 1200),
656         mee_handler   ("[Display options]",        menu_loop_gfx_options),
657         mee_handler   ("[Sega/Mega CD options]",   menu_loop_cd_options),
658 #ifndef NO_32X
659         mee_handler   ("[32X options]",            menu_loop_32x_options),
660 #endif
661         mee_handler   ("[Advanced options]",       menu_loop_adv_options),
662         mee_cust_nosave("Save global config",      MA_OPT_SAVECFG, mh_saveloadcfg, mgn_saveloadcfg),
663         mee_cust_nosave("Save cfg for loaded game",MA_OPT_SAVECFG_GAME, mh_saveloadcfg, mgn_saveloadcfg),
664         mee_cust_nosave("Load cfg from profile",   MA_OPT_LOADCFG, mh_saveloadcfg, mgn_saveloadcfg),
665         mee_handler   ("Restore defaults",         mh_restore_defaults),
666         mee_end,
667 };
668
669 static int menu_loop_options(int id, int keys)
670 {
671         static int sel = 0;
672         int i;
673
674         i = me_id2offset(e_menu_options, MA_OPT_CPU_CLOCKS);
675         e_menu_options[i].enabled = e_menu_options[i].name[0] ? 1 : 0;
676         me_enable(e_menu_options, MA_OPT_SAVECFG_GAME, rom_loaded);
677         me_enable(e_menu_options, MA_OPT_LOADCFG, config_slot != config_slot_current);
678
679         me_loop(e_menu_options, &sel);
680
681         return 0;
682 }
683
684 // ------------ debug menu ------------
685
686 #include <pico/debug.h>
687
688 extern void SekStepM68k(void);
689
690 static void mplayer_loop(void)
691 {
692         pemu_sound_start();
693
694         while (1)
695         {
696                 PDebugZ80Frame();
697                 if (in_menu_wait_any(0) & PBTN_MA3)
698                         break;
699                 pemu_sound_wait();
700         }
701
702         pemu_sound_stop();
703 }
704
705 static void draw_text_debug(const char *str, int skip, int from)
706 {
707         const char *p;
708         int line;
709
710         p = str;
711         while (skip-- > 0)
712         {
713                 while (*p && *p != '\n')
714                         p++;
715                 if (*p == 0 || p[1] == 0)
716                         return;
717                 p++;
718         }
719
720         str = p;
721         for (line = from; line < g_menuscreen_h / me_sfont_h; line++)
722         {
723                 smalltext_out16(1, line * me_sfont_h, str, 0xffff);
724                 while (*p && *p != '\n')
725                         p++;
726                 if (*p == 0)
727                         break;
728                 p++; str = p;
729         }
730 }
731
732 #ifdef __GNUC__
733 #define COMPILER "gcc " __VERSION__
734 #else
735 #define COMPILER
736 #endif
737
738 static void draw_frame_debug(void)
739 {
740         char layer_str[48] = "layers:                   ";
741         if (PicoDrawMask & PDRAW_LAYERB_ON)      memcpy(layer_str +  8, "B", 1);
742         if (PicoDrawMask & PDRAW_LAYERA_ON)      memcpy(layer_str + 10, "A", 1);
743         if (PicoDrawMask & PDRAW_SPRITES_LOW_ON) memcpy(layer_str + 12, "spr_lo", 6);
744         if (PicoDrawMask & PDRAW_SPRITES_HI_ON)  memcpy(layer_str + 19, "spr_hi", 6);
745         if (PicoDrawMask & PDRAW_32X_ON)         memcpy(layer_str + 26, "32x", 4);
746
747         pemu_forced_frame(1, 0);
748         memcpy(g_menuscreen_ptr, g_menubg_src_ptr, g_menuscreen_w * g_menuscreen_h * 2);
749         smalltext_out16(4, 1, "build: r" REVISION "  "__DATE__ " " __TIME__ " " COMPILER, 0xffff);
750         smalltext_out16(4, g_menuscreen_h - me_sfont_h, layer_str, 0xffff);
751 }
752
753 static void debug_menu_loop(void)
754 {
755         int inp, mode = 0;
756         int spr_offs = 0, dumped = 0;
757         char *tmp;
758
759         while (1)
760         {
761                 menu_draw_begin(1);
762                 switch (mode)
763                 {
764                         case 0: tmp = PDebugMain();
765                                 plat_debug_cat(tmp);
766                                 draw_text_debug(tmp, 0, 0);
767                                 if (dumped) {
768                                         smalltext_out16(g_menuscreen_w - 6 * me_sfont_h,
769                                                 g_menuscreen_h - me_mfont_h, "dumped", 0xffff);
770                                         dumped = 0;
771                                 }
772                                 break;
773                         case 1: draw_frame_debug();
774                                 break;
775                         case 2: pemu_forced_frame(1, 0);
776                                 menu_darken_bg(g_menuscreen_ptr, g_menubg_src_ptr, g_menuscreen_w * g_menuscreen_h, 0);
777                                 PDebugShowSpriteStats((unsigned short *)g_menuscreen_ptr + (g_menuscreen_h/2 - 240/2)*g_menuscreen_w +
778                                         g_menuscreen_w/2 - 320/2, g_menuscreen_w);
779                                 break;
780                         case 3: memset(g_menuscreen_ptr, 0, g_menuscreen_w * g_menuscreen_h * 2);
781                                 PDebugShowPalette(g_menuscreen_ptr, g_menuscreen_w);
782                                 PDebugShowSprite((unsigned short *)g_menuscreen_ptr + g_menuscreen_w*120 + g_menuscreen_w/2 + 16,
783                                         g_menuscreen_w, spr_offs);
784                                 draw_text_debug(PDebugSpriteList(), spr_offs, 6);
785                                 break;
786                         case 4: tmp = PDebug32x();
787                                 draw_text_debug(tmp, 0, 0);
788                                 break;
789                 }
790                 menu_draw_end();
791
792                 inp = in_menu_wait(PBTN_MOK|PBTN_MBACK|PBTN_MA2|PBTN_MA3|PBTN_L|PBTN_R |
793                                         PBTN_UP|PBTN_DOWN|PBTN_LEFT|PBTN_RIGHT, 70);
794                 if (inp & PBTN_MBACK) return;
795                 if (inp & PBTN_L) { mode--; if (mode < 0) mode = 4; }
796                 if (inp & PBTN_R) { mode++; if (mode > 4) mode = 0; }
797                 switch (mode)
798                 {
799                         case 0:
800                                 if (inp & PBTN_MOK)
801                                         PDebugCPUStep();
802                                 if (inp & PBTN_MA3) {
803                                         while (inp & PBTN_MA3)
804                                                 inp = in_menu_wait_any(-1);
805                                         mplayer_loop();
806                                 }
807                                 if ((inp & (PBTN_MA2|PBTN_LEFT)) == (PBTN_MA2|PBTN_LEFT)) {
808                                         mkdir("dumps", 0777);
809                                         PDebugDumpMem();
810                                         while (inp & PBTN_MA2) inp = in_menu_wait_any(-1);
811                                         dumped = 1;
812                                 }
813                                 break;
814                         case 1:
815                                 if (inp & PBTN_LEFT)  PicoDrawMask ^= PDRAW_LAYERB_ON;
816                                 if (inp & PBTN_RIGHT) PicoDrawMask ^= PDRAW_LAYERA_ON;
817                                 if (inp & PBTN_DOWN)  PicoDrawMask ^= PDRAW_SPRITES_LOW_ON;
818                                 if (inp & PBTN_UP)    PicoDrawMask ^= PDRAW_SPRITES_HI_ON;
819                                 if (inp & PBTN_MA2)   PicoDrawMask ^= PDRAW_32X_ON;
820                                 if (inp & PBTN_MOK) {
821                                         PsndOut = NULL; // just in case
822                                         PicoSkipFrame = 1;
823                                         PicoFrame();
824                                         PicoSkipFrame = 0;
825                                         while (inp & PBTN_MOK) inp = in_menu_wait_any(-1);
826                                 }
827                                 break;
828                         case 3:
829                                 if (inp & PBTN_DOWN)  spr_offs++;
830                                 if (inp & PBTN_UP)    spr_offs--;
831                                 if (spr_offs < 0) spr_offs = 0;
832                                 break;
833                 }
834         }
835 }
836
837 // ------------ main menu ------------
838
839 static const char credits[] =
840         "PicoDrive v" VERSION " (c) notaz, 2006-2011\n\n\n"
841         "Credits:\n"
842         "fDave: Cyclone 68000 core,\n"
843         "      base code of PicoDrive\n"
844         "Reesy & FluBBa: DrZ80 core\n"
845         "MAME devs: YM2612 and SN76496 cores\n"
846         "Inder, ketchupgun: graphics\n"
847 #ifdef __GP2X__
848         "rlyeh and others: minimal SDK\n"
849         "Squidge: mmuhack\n"
850         "Dzz: ARM940 sample\n"
851 #endif
852         "\n"
853         "special thanks (for docs, ideas):\n"
854         " Charles MacDonald, Haze,\n"
855         " Stephane Dallongeville,\n"
856         " Lordus, Exophase, Rokas,\n"
857         " Nemesis, Tasco Deluxe";
858
859 static char *romsel_run(void)
860 {
861         char *ret, *sel_name;
862
863         sel_name = malloc(sizeof(rom_fname_loaded));
864         if (sel_name == NULL)
865                 return NULL;
866         strcpy(sel_name, rom_fname_loaded);
867
868         ret = menu_loop_romsel(sel_name, sizeof(rom_fname_loaded));
869         free(sel_name);
870         return ret;
871 }
872
873 static int main_menu_handler(int id, int keys)
874 {
875         char *ret_name;
876
877         switch (id)
878         {
879         case MA_MAIN_RESUME_GAME:
880                 if (rom_loaded)
881                         return 1;
882                 break;
883         case MA_MAIN_SAVE_STATE:
884                 if (rom_loaded)
885                         return menu_loop_savestate(0);
886                 break;
887         case MA_MAIN_LOAD_STATE:
888                 if (rom_loaded)
889                         return menu_loop_savestate(1);
890                 break;
891         case MA_MAIN_RESET_GAME:
892                 if (rom_loaded) {
893                         emu_reset_game();
894                         return 1;
895                 }
896                 break;
897         case MA_MAIN_LOAD_ROM:
898                 ret_name = romsel_run();
899                 if (ret_name != NULL) {
900                         lprintf("selected file: %s\n", ret_name);
901                         engineState = PGS_ReloadRom;
902                         return 1;
903                 }
904                 break;
905         case MA_MAIN_CREDITS:
906                 draw_menu_message(credits, NULL);
907                 in_menu_wait(PBTN_MOK|PBTN_MBACK, 70);
908                 break;
909         case MA_MAIN_EXIT:
910                 engineState = PGS_Quit;
911                 return 1;
912         case MA_MAIN_PATCHES:
913                 if (rom_loaded && PicoPatches) {
914                         menu_loop_patches();
915                         PicoPatchApply();
916                         me_update_msg("Patches applied");
917                 }
918                 break;
919         default:
920                 lprintf("%s: something unknown selected\n", __FUNCTION__);
921                 break;
922         }
923
924         return 0;
925 }
926
927 static menu_entry e_menu_main[] =
928 {
929         mee_label     ("PicoDrive " VERSION),
930         mee_label     (""),
931         mee_label     (""),
932         mee_label     (""),
933         mee_handler_id("Resume game",        MA_MAIN_RESUME_GAME, main_menu_handler),
934         mee_handler_id("Save State",         MA_MAIN_SAVE_STATE,  main_menu_handler),
935         mee_handler_id("Load State",         MA_MAIN_LOAD_STATE,  main_menu_handler),
936         mee_handler_id("Reset game",         MA_MAIN_RESET_GAME,  main_menu_handler),
937         mee_handler_id("Load new ROM/ISO",   MA_MAIN_LOAD_ROM,    main_menu_handler),
938         mee_handler   ("Change options",                          menu_loop_options),
939         mee_handler   ("Configure controls",                      menu_loop_keyconfig),
940         mee_handler_id("Credits",            MA_MAIN_CREDITS,     main_menu_handler),
941         mee_handler_id("Patches / GameGenie",MA_MAIN_PATCHES,     main_menu_handler),
942         mee_handler_id("Exit",               MA_MAIN_EXIT,        main_menu_handler),
943         mee_end,
944 };
945
946 void menu_loop(void)
947 {
948         static int sel = 0;
949
950         me_enable(e_menu_main, MA_MAIN_RESUME_GAME, rom_loaded);
951         me_enable(e_menu_main, MA_MAIN_SAVE_STATE,  rom_loaded);
952         me_enable(e_menu_main, MA_MAIN_LOAD_STATE,  rom_loaded);
953         me_enable(e_menu_main, MA_MAIN_RESET_GAME,  rom_loaded);
954         me_enable(e_menu_main, MA_MAIN_PATCHES, PicoPatches != NULL);
955
956         menu_enter(rom_loaded);
957         in_set_config_int(0, IN_CFG_BLOCKING, 1);
958         me_loop_d(e_menu_main, &sel, NULL, menu_main_plat_draw);
959
960         if (rom_loaded) {
961                 if (engineState == PGS_Menu)
962                         engineState = PGS_Running;
963                 /* wait until menu, ok, back is released */
964                 while (in_menu_wait_any(50) & (PBTN_MENU|PBTN_MOK|PBTN_MBACK))
965                         ;
966         }
967
968         in_set_config_int(0, IN_CFG_BLOCKING, 0);
969 }
970
971 // --------- CD tray close menu ----------
972
973 static int mh_tray_load_cd(int id, int keys)
974 {
975         char *ret_name;
976
977         ret_name = romsel_run();
978         if (ret_name == NULL)
979                 return 0;
980
981         engineState = PGS_RestartRun;
982         return emu_swap_cd(ret_name);
983 }
984
985 static int mh_tray_nothing(int id, int keys)
986 {
987         return 1;
988 }
989
990 static menu_entry e_menu_tray[] =
991 {
992         mee_label  ("The CD tray has opened."),
993         mee_label  (""),
994         mee_label  (""),
995         mee_handler("Load CD image",  mh_tray_load_cd),
996         mee_handler("Insert nothing", mh_tray_nothing),
997         mee_end,
998 };
999
1000 int menu_loop_tray(void)
1001 {
1002         int ret = 1, sel = 0;
1003
1004         menu_enter(rom_loaded);
1005
1006         in_set_config_int(0, IN_CFG_BLOCKING, 1);
1007         me_loop(e_menu_tray, &sel);
1008
1009         if (engineState != PGS_RestartRun) {
1010                 engineState = PGS_RestartRun;
1011                 ret = 0; /* no CD inserted */
1012         }
1013
1014         while (in_menu_wait_any(50) & (PBTN_MENU|PBTN_MOK|PBTN_MBACK));
1015         in_set_config_int(0, IN_CFG_BLOCKING, 0);
1016
1017         return ret;
1018 }
1019
1020 void me_update_msg(const char *msg)
1021 {
1022         strncpy(menu_error_msg, msg, sizeof(menu_error_msg));
1023         menu_error_msg[sizeof(menu_error_msg) - 1] = 0;
1024
1025         menu_error_time = plat_get_ticks_ms();
1026         lprintf("msg: %s\n", menu_error_msg);
1027 }
1028
1029 // ------------ util ------------
1030
1031 /* hidden options for config engine only */
1032 static menu_entry e_menu_hidden[] =
1033 {
1034         mee_onoff("Accurate sprites", MA_OPT_ACC_SPRITES, PicoOpt, 0x080),
1035         mee_end,
1036 };
1037
1038 static menu_entry *e_menu_table[] =
1039 {
1040         e_menu_options,
1041         e_menu_gfx_options,
1042         e_menu_adv_options,
1043         e_menu_cd_options,
1044 #ifndef NO_32X
1045         e_menu_32x_options,
1046 #endif
1047         e_menu_keyconfig,
1048         e_menu_hidden,
1049 };
1050
1051 static menu_entry *me_list_table = NULL;
1052 static menu_entry *me_list_i = NULL;
1053
1054 menu_entry *me_list_get_first(void)
1055 {
1056         me_list_table = me_list_i = e_menu_table[0];
1057         return me_list_i;
1058 }
1059
1060 menu_entry *me_list_get_next(void)
1061 {
1062         int i;
1063
1064         me_list_i++;
1065         if (me_list_i->name != NULL)
1066                 return me_list_i;
1067
1068         for (i = 0; i < array_size(e_menu_table); i++)
1069                 if (me_list_table == e_menu_table[i])
1070                         break;
1071
1072         if (i + 1 < array_size(e_menu_table))
1073                 me_list_table = me_list_i = e_menu_table[i + 1];
1074         else
1075                 me_list_table = me_list_i = NULL;
1076
1077         return me_list_i;
1078 }
1079