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