86628ca08338a8d22977324b93f929802c42f097
[libpicofe.git] / psp / menu.c
1 // (c) Copyright 2006,2007 notaz, All rights reserved.
2 // Free for non-commercial use.
3
4 // For commercial use, separate licencing terms must be obtained.
5
6 // don't like to use loads of #ifdefs, so duplicating GP2X code
7 // horribly instead
8
9 #include <string.h>
10 #include <stdlib.h>
11 #include <wchar.h>
12 #include <unistd.h>
13 #include <sys/syslimits.h> // PATH_MAX
14
15 #include <pspdisplay.h>
16 #include <pspgu.h>
17 #include <pspiofilemgr.h>
18 #include <psputils.h>
19
20 #include "psp.h"
21 #include "emu.h"
22 #include "menu.h"
23 #include "mp3.h"
24 #include "../common/menu.h"
25 #include "../common/emu.h"
26 #include "../common/readpng.h"
27 #include "../common/lprintf.h"
28 #include "version.h"
29
30 #include <Pico/PicoInt.h>
31 #include <Pico/Patch.h>
32 #include <zlib/zlib.h>
33
34
35 #define pspKeyUnkn "???"
36 static const char * const pspKeyNames[] = {
37         "SELECT",   pspKeyUnkn, pspKeyUnkn, "START",    "UP",       "RIGHT",     "DOWN",     "LEFT",
38         "L",        "R",        pspKeyUnkn, pspKeyUnkn, "TRIANGLE", "CIRCLE",    "X",        "SQUARE",
39         "HOME",     "HOLD",     "WLAN_UP",  "REMOTE",   "VOLUP",    "VOLDOWN",   "SCREEN",   "NOTE",
40         pspKeyUnkn, pspKeyUnkn, pspKeyUnkn, pspKeyUnkn, "NUB UP",   "NUB RIGHT", "NUB DOWN", "NUB LEFT" // fake
41 };
42
43 static unsigned short bg_buffer[480*272] __attribute__((aligned(16)));
44 #define menu_screen psp_screen
45
46 static void menu_darken_bg(void *dst, const void *src, int pixels, int darker);
47 static void menu_prepare_bg(int use_game_bg, int use_fg);
48
49
50 static unsigned int inp_prev = 0;
51
52 static unsigned long wait_for_input(unsigned int interesting, int is_key_config)
53 {
54         unsigned int ret;
55         static int repeats = 0, wait = 50;
56         int release = 0, count, i;
57
58         if (!is_key_config)
59                 interesting |= (interesting & 0xf0) << 24; // also use analog
60
61         if (repeats == 2 || repeats == 4) wait /= 2;
62         if (repeats == 6) wait = 15;
63
64         for (i = 0; i < 6 && inp_prev == psp_pad_read(1); i++) {
65                 if (i == 0) repeats++;
66                 psp_msleep(wait);
67         }
68
69         for (count = 0; !((ret = psp_pad_read(1)) & interesting) && count < 100; count++) {
70                 psp_msleep(50);
71                 release = 1;
72         }
73
74         if (release || ret != inp_prev) {
75                 repeats = 0;
76                 wait = 50;
77         }
78         inp_prev = ret;
79
80         if (!is_key_config)
81                 ret |= (ret & 0xf0000000) >> 24; // use analog as d-pad
82
83         // we don't need diagonals in menus
84         if ((ret&BTN_UP)   && (ret&BTN_LEFT))  ret &= ~BTN_LEFT;
85         if ((ret&BTN_UP)   && (ret&BTN_RIGHT)) ret &= ~BTN_RIGHT;
86         if ((ret&BTN_DOWN) && (ret&BTN_LEFT))  ret &= ~BTN_LEFT;
87         if ((ret&BTN_DOWN) && (ret&BTN_RIGHT)) ret &= ~BTN_RIGHT;
88
89         return ret;
90 }
91
92 static void menu_draw_begin(void)
93 {
94         // short *src = (short *)bg_buffer, *dst = (short *)menu_screen;
95         // int i;
96
97         // for (i = 272; i >= 0; i--, dst += 512, src += 480)
98         //      memcpy32((int *)dst, (int *)src, 480*2/4);
99
100         sceGuSync(0,0); // sync with prev
101         sceGuStart(GU_DIRECT, guCmdList);
102         sceGuCopyImage(GU_PSM_5650, 0, 0, 480, 272, 480, bg_buffer, 0, 0, 512, menu_screen);
103         sceGuFinish();
104         sceGuSync(0,0);
105 }
106
107
108 static void menu_draw_end(void)
109 {
110         psp_video_flip(1);
111 }
112
113
114 // --------- loading ROM screen ----------
115
116 static int lcdr_line = 0;
117
118 static void load_progress_cb(int percent)
119 {
120         int ln, len = percent * 480 / 100;
121         unsigned short *dst;
122
123         //sceDisplayWaitVblankStart();
124
125         dst = (unsigned short *)menu_screen + 512*10*lcdr_line;
126
127         if (len > 480) len = 480;
128         for (ln = 8; ln > 0; ln--, dst += 512)
129                 memset(dst, 0xff, len*2);
130 }
131
132 static void cdload_progress_cb(int percent)
133 {
134         int ln, len = percent * 480 / 100;
135         unsigned short *dst;
136
137         if (lcdr_line <= 2) {
138                 lcdr_line++;
139                 smalltext_out16(1, lcdr_line++ * 10, "Processing CD image / MP3s", 0xffff);
140                 smalltext_out16_lim(1, lcdr_line++ * 10, romFileName, 0xffff, 80);
141         }
142
143         dst = (unsigned short *)menu_screen + 512*10*lcdr_line;
144
145         if (len > 480) len = 480;
146         for (ln = 8; ln > 0; ln--, dst += 512)
147                 memset(dst, 0xff, len*2);
148 }
149
150 void menu_romload_prepare(const char *rom_name)
151 {
152         const char *p = rom_name + strlen(rom_name);
153         while (p > rom_name && *p != '/') p--;
154
155         psp_video_switch_to_single();
156         if (rom_data) menu_draw_begin();
157         else memset32(psp_screen, 0, 512*272*2/4);
158
159         smalltext_out16(1, 1, "Loading", 0xffff);
160         smalltext_out16_lim(1, 10, p, 0xffff, 80);
161         PicoCartLoadProgressCB = load_progress_cb;
162         PicoCDLoadProgressCB = cdload_progress_cb;
163         lcdr_line = 2;
164 }
165
166 void menu_romload_end(void)
167 {
168         PicoCartLoadProgressCB = PicoCDLoadProgressCB = NULL;
169         smalltext_out16(1, ++lcdr_line*10, "Starting emulation...", 0xffff);
170 }
171
172 // -------------- ROM selector --------------
173
174 // SceIoDirent
175 #define DT_DIR FIO_SO_IFDIR
176 #define DT_REG FIO_SO_IFREG
177
178 struct my_dirent
179 {
180         unsigned char d_type;
181         char d_name[255];
182 };
183
184 // bbbb bggg gggr rrrr
185 static unsigned short file2color(const char *fname)
186 {
187         const char *ext = fname + strlen(fname) - 3;
188         static const char *rom_exts[]   = { "zip", "bin", "smd", "gen", "iso" };
189         static const char *other_exts[] = { "gmv", "pat" };
190         int i;
191
192         if (ext < fname) ext = fname;
193         for (i = 0; i < sizeof(rom_exts)/sizeof(rom_exts[0]); i++)
194                 if (strcasecmp(ext, rom_exts[i]) == 0) return 0xfdf7;
195         for (i = 0; i < sizeof(other_exts)/sizeof(other_exts[0]); i++)
196                 if (strcasecmp(ext, other_exts[i]) == 0) return 0xaff5;
197         return 0xffff;
198 }
199
200 static void draw_dirlist(char *curdir, struct my_dirent **namelist, int n, int sel)
201 {
202         int start, i, pos;
203
204         start = 13 - sel;
205         n--; // exclude current dir (".")
206
207         menu_draw_begin();
208
209         if (rom_data == NULL) {
210 //              menu_darken_bg(menu_screen, menu_screen, 321*240, 0);
211         }
212
213         menu_darken_bg((char *)menu_screen + 512*129*2, (char *)menu_screen + 512*129*2, 512*10, 0);
214
215         if (start - 2 >= 0)
216                 smalltext_out16_lim(14, (start - 2)*10, curdir, 0xffff, 53-2);
217         for (i = 0; i < n; i++) {
218                 pos = start + i;
219                 if (pos < 0)  continue;
220                 if (pos > 26) break;
221                 if (namelist[i+1]->d_type & DT_DIR) {
222                         smalltext_out16_lim(14,   pos*10, "/", 0xd7ff, 1);
223                         smalltext_out16_lim(14+6, pos*10, namelist[i+1]->d_name, 0xd7ff, 80-3);
224                 } else {
225                         unsigned short color = file2color(namelist[i+1]->d_name);
226                         smalltext_out16_lim(14,   pos*10, namelist[i+1]->d_name, color, 80-2);
227                 }
228         }
229         text_out16(5, 130, ">");
230         menu_draw_end();
231 }
232
233 static int scandir_cmp(const void *p1, const void *p2)
234 {
235         struct my_dirent **d1 = (struct my_dirent **)p1, **d2 = (struct my_dirent **)p2;
236         if ((*d1)->d_type == (*d2)->d_type) return strcasecmp((*d1)->d_name, (*d2)->d_name);
237         if ((*d1)->d_type & DT_DIR) return -1; // put before
238         if ((*d2)->d_type & DT_DIR) return  1;
239         return strcasecmp((*d1)->d_name, (*d2)->d_name);
240 }
241
242 static char *filter_exts[] = {
243         ".mp3", ".srm", ".brm", "s.gz", ".mds", "bcfg", ".txt", ".htm", "html",
244         ".jpg", ".cue", ".pbp"
245 };
246
247 static int scandir_filter(const struct my_dirent *ent)
248 {
249         const char *p;
250         int i;
251
252         if (ent == NULL || ent->d_name == NULL) return 0;
253         if (strlen(ent->d_name) < 5) return 1;
254
255         p = ent->d_name + strlen(ent->d_name) - 4;
256
257         for (i = 0; i < sizeof(filter_exts)/sizeof(filter_exts[0]); i++)
258         {
259                 if (strcasecmp(p, filter_exts[i]) == 0) return 0;
260         }
261
262         return 1;
263 }
264
265 static int my_scandir(const char *dir, struct my_dirent ***namelist_out,
266                 int(*filter)(const struct my_dirent *),
267                 int(*compar)(const void *, const void *))
268 {
269         int ret = -1, dir_uid = -1, name_alloc = 4, name_count = 0;
270         struct my_dirent **namelist = NULL, *ent;
271         SceIoDirent sce_ent;
272
273         namelist = malloc(sizeof(*namelist) * name_alloc);
274         if (namelist == NULL) { lprintf("%s:%i: OOM\n", __FILE__, __LINE__); goto fail; }
275
276         // try to read first..
277         dir_uid = sceIoDopen(dir);
278         if (dir_uid >= 0)
279         {
280                 /* it is very important to clear SceIoDirent to be passed to sceIoDread(), */
281                 /* or else it may crash, probably misinterpreting something in it. */
282                 memset(&sce_ent, 0, sizeof(sce_ent));
283                 ret = sceIoDread(dir_uid, &sce_ent);
284                 if (ret < 0)
285                 {
286                         lprintf("sceIoDread(\"%s\") failed with %i\n", dir, ret);
287                         goto fail;
288                 }
289         }
290         else
291                 lprintf("sceIoDopen(\"%s\") failed with %i\n", dir, dir_uid);
292
293         while (ret > 0)
294         {
295                 ent = malloc(sizeof(*ent));
296                 if (ent == NULL) { lprintf("%s:%i: OOM\n", __FILE__, __LINE__); goto fail; }
297                 ent->d_type = sce_ent.d_stat.st_attr;
298                 strncpy(ent->d_name, sce_ent.d_name, sizeof(ent->d_name));
299                 ent->d_name[sizeof(ent->d_name)-1] = 0;
300                 if (filter == NULL || filter(ent))
301                      namelist[name_count++] = ent;
302                 else free(ent);
303
304                 if (name_count >= name_alloc)
305                 {
306                         void *tmp;
307                         name_alloc *= 2;
308                         tmp = realloc(namelist, sizeof(*namelist) * name_alloc);
309                         if (tmp == NULL) { lprintf("%s:%i: OOM\n", __FILE__, __LINE__); goto fail; }
310                         namelist = tmp;
311                 }
312
313                 memset(&sce_ent, 0, sizeof(sce_ent));
314                 ret = sceIoDread(dir_uid, &sce_ent);
315         }
316
317         // sort
318         if (compar != NULL && name_count > 3) qsort(&namelist[2], name_count - 2, sizeof(namelist[0]), compar);
319
320         // all done.
321         ret = name_count;
322         *namelist_out = namelist;
323         goto end;
324
325 fail:
326         if (namelist != NULL)
327         {
328                 while (name_count--)
329                         free(namelist[name_count]);
330                 free(namelist);
331         }
332 end:
333         if (dir_uid >= 0) sceIoDclose(dir_uid);
334         return ret;
335 }
336
337
338 static char *romsel_loop(char *curr_path)
339 {
340         struct my_dirent **namelist;
341         int n, iret, sel = 0;
342         unsigned long inp = 0;
343         char *ret = NULL, *fname = NULL;
344         SceIoStat cpstat;
345
346         // is this a dir or a full path?
347         memset(&cpstat, 0, sizeof(cpstat));
348         iret = sceIoGetstat(curr_path, &cpstat);
349         if (iret >= 0 && (cpstat.st_attr & FIO_SO_IFREG)) { // file
350                 char *p;
351                 for (p = curr_path + strlen(curr_path) - 1; p > curr_path && *p != '/'; p--);
352                 *p = 0;
353                 fname = p+1;
354         }
355         else if (iret >= 0 && (cpstat.st_attr & FIO_SO_IFDIR)); // dir
356         else strcpy(curr_path, "ms0:/"); // something else
357
358         n = my_scandir(curr_path, &namelist, scandir_filter, scandir_cmp);
359         if (n < 0) {
360                 // try root..
361                 n = my_scandir("ms0:/", &namelist, scandir_filter, scandir_cmp);
362                 if (n < 0) {
363                         // oops, we failed
364                         lprintf("scandir failed, dir: "); lprintf(curr_path); lprintf("\n");
365                         return NULL;
366                 }
367         }
368
369         // try to find sel
370         if (fname != NULL) {
371                 int i;
372                 for (i = 1; i < n; i++) {
373                         if (strcmp(namelist[i]->d_name, fname) == 0) {
374                                 sel = i - 1;
375                                 break;
376                         }
377                 }
378         }
379
380         for (;;)
381         {
382                 draw_dirlist(curr_path, namelist, n, sel);
383                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_L|BTN_R|BTN_X|BTN_CIRCLE, 0);
384                 if(inp & BTN_UP  )  { sel--;   if (sel < 0)   sel = n-2; }
385                 if(inp & BTN_DOWN)  { sel++;   if (sel > n-2) sel = 0; }
386                 if(inp & BTN_LEFT)  { sel-=10; if (sel < 0)   sel = 0; }
387                 if(inp & BTN_L)     { sel-=24; if (sel < 0)   sel = 0; }
388                 if(inp & BTN_RIGHT) { sel+=10; if (sel > n-2) sel = n-2; }
389                 if(inp & BTN_R)     { sel+=24; if (sel > n-2) sel = n-2; }
390                 if(inp & BTN_CIRCLE) { // enter dir/select
391                         if (namelist[sel+1]->d_type & DT_REG) {
392                                 strcpy(romFileName, curr_path);
393                                 strcat(romFileName, "/");
394                                 strcat(romFileName, namelist[sel+1]->d_name);
395                                 ret = romFileName;
396                                 break;
397                         } else if (namelist[sel+1]->d_type & DT_DIR) {
398                                 int newlen = strlen(curr_path) + strlen(namelist[sel+1]->d_name) + 2;
399                                 char *p, *newdir = malloc(newlen);
400                                 if (strcmp(namelist[sel+1]->d_name, "..") == 0) {
401                                         char *start = curr_path;
402                                         p = start + strlen(start) - 1;
403                                         while (*p == '/' && p > start) p--;
404                                         while (*p != '/' && *p != ':' && p > start) p--;
405                                         if (p <= start || *p == ':' || p[-1] == ':') strcpy(newdir, "ms0:/");
406                                         else { strncpy(newdir, start, p-start); newdir[p-start] = 0; }
407                                 } else {
408                                         strcpy(newdir, curr_path);
409                                         p = newdir + strlen(newdir) - 1;
410                                         while (*p == '/' && p >= newdir) *p-- = 0;
411                                         strcat(newdir, "/");
412                                         strcat(newdir, namelist[sel+1]->d_name);
413                                 }
414                                 ret = romsel_loop(newdir);
415                                 free(newdir);
416                                 break;
417                         }
418                 }
419                 if(inp & BTN_X) break; // cancel
420         }
421
422         if (n > 0) {
423                 while(n--) free(namelist[n]);
424                 free(namelist);
425         }
426
427         return ret;
428 }
429
430 // ------------ debug menu ------------
431
432 char *debugString(void);
433
434 static void draw_debug(void)
435 {
436         char *p, *str = debugString();
437         int len, line;
438
439         menu_draw_begin();
440
441         p = str;
442         for (line = 0; line < 24; line++)
443         {
444                 while (*p && *p != '\n') p++;
445                 len = p - str;
446                 if (len > 55) len = 55;
447                 smalltext_out16_lim(1, line*10, str, 0xffff, len);
448                 if (*p == 0) break;
449                 p++; str = p;
450         }
451         menu_draw_end();
452 }
453
454 static void debug_menu_loop(void)
455 {
456         draw_debug();
457         wait_for_input(BTN_X|BTN_CIRCLE, 0);
458 }
459
460 // ------------ patch/gg menu ------------
461
462 static void draw_patchlist(int sel)
463 {
464         int start, i, pos, active;
465
466         start = 13 - sel;
467
468         menu_draw_begin();
469
470         for (i = 0; i < PicoPatchCount; i++) {
471                 pos = start + i;
472                 if (pos < 0)  continue;
473                 if (pos > 26) break;
474                 active = PicoPatches[i].active;
475                 smalltext_out16_lim(14,     pos*10, active ? "ON " : "OFF", active ? 0xfff6 : 0xffff, 3);
476                 smalltext_out16_lim(14+6*4, pos*10, PicoPatches[i].name, active ? 0xfff6 : 0xffff, 53-6);
477         }
478         pos = start + i;
479         if (pos < 27) smalltext_out16_lim(14, pos*10, "done", 0xffff, 4);
480
481         text_out16(5, 130, ">");
482         menu_draw_end();
483 }
484
485
486 static void patches_menu_loop(void)
487 {
488         int menu_sel = 0;
489         unsigned long inp = 0;
490
491         for(;;)
492         {
493                 draw_patchlist(menu_sel);
494                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_L|BTN_R|BTN_X|BTN_CIRCLE, 0);
495                 if(inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = PicoPatchCount; }
496                 if(inp & BTN_DOWN) { menu_sel++; if (menu_sel > PicoPatchCount) menu_sel = 0; }
497                 if(inp &(BTN_LEFT|BTN_L))  { menu_sel-=10; if (menu_sel < 0) menu_sel = 0; }
498                 if(inp &(BTN_RIGHT|BTN_R)) { menu_sel+=10; if (menu_sel > PicoPatchCount) menu_sel = PicoPatchCount; }
499                 if(inp & BTN_CIRCLE) { // action
500                         if (menu_sel < PicoPatchCount)
501                                 PicoPatches[menu_sel].active = !PicoPatches[menu_sel].active;
502                         else    return;
503                 }
504                 if(inp & BTN_X) return;
505         }
506
507 }
508
509 // ------------ savestate loader ------------
510
511 static int state_slot_flags = 0;
512
513 static void state_check_slots(void)
514 {
515         int slot;
516
517         state_slot_flags = 0;
518
519         for (slot = 0; slot < 10; slot++)
520         {
521                 if (emu_checkSaveFile(slot))
522                 {
523                         state_slot_flags |= 1 << slot;
524                 }
525         }
526 }
527
528 static void *get_oldstate_for_preview(void)
529 {
530         unsigned char *ptr = malloc(sizeof(Pico.vram) + sizeof(Pico.cram) + sizeof(Pico.vsram) + sizeof(Pico.video));
531         if (ptr == NULL) return NULL;
532
533         memcpy(ptr, Pico.vram, sizeof(Pico.vram));
534         memcpy(ptr + sizeof(Pico.vram), Pico.cram, sizeof(Pico.cram));
535         memcpy(ptr + sizeof(Pico.vram) + sizeof(Pico.cram), Pico.vsram, sizeof(Pico.vsram));
536         memcpy(ptr + sizeof(Pico.vram) + sizeof(Pico.cram) + sizeof(Pico.vsram), &Pico.video, sizeof(Pico.video));
537         return ptr;
538 }
539
540 static void restore_oldstate(void *ptrx)
541 {
542         unsigned char *ptr = ptrx;
543         memcpy(Pico.vram,  ptr,  sizeof(Pico.vram));
544         memcpy(Pico.cram,  ptr + sizeof(Pico.vram), sizeof(Pico.cram));
545         memcpy(Pico.vsram, ptr + sizeof(Pico.vram) + sizeof(Pico.cram), sizeof(Pico.vsram));
546         memcpy(&Pico.video,ptr + sizeof(Pico.vram) + sizeof(Pico.cram) + sizeof(Pico.vsram), sizeof(Pico.video));
547         free(ptrx);
548 }
549
550 static void draw_savestate_bg(int slot)
551 {
552         void *file, *oldstate;
553         char *fname;
554
555         fname = emu_GetSaveFName(1, 0, slot);
556         if (!fname) return;
557
558         oldstate = get_oldstate_for_preview();
559         if (oldstate == NULL) return;
560
561         if (strcmp(fname + strlen(fname) - 3, ".gz") == 0) {
562                 file = gzopen(fname, "rb");
563                 emu_setSaveStateCbs(1);
564         } else {
565                 file = fopen(fname, "rb");
566                 emu_setSaveStateCbs(0);
567         }
568
569         if (file) {
570                 if (PicoMCD & 1) {
571                         PicoCdLoadStateGfx(file);
572                 } else {
573                         areaSeek(file, 0x10020, SEEK_SET);  // skip header and RAM in state file
574                         areaRead(Pico.vram, 1, sizeof(Pico.vram), file);
575                         areaSeek(file, 0x2000, SEEK_CUR);
576                         areaRead(Pico.cram, 1, sizeof(Pico.cram), file);
577                         areaRead(Pico.vsram, 1, sizeof(Pico.vsram), file);
578                         areaSeek(file, 0x221a0, SEEK_SET);
579                         areaRead(&Pico.video, 1, sizeof(Pico.video), file);
580                 }
581                 areaClose(file);
582         }
583
584         emu_forcedFrame();
585         menu_prepare_bg(1, 0);
586
587         restore_oldstate(oldstate);
588 }
589
590 static void draw_savestate_menu(int menu_sel, int is_loading)
591 {
592         int tl_x = 80+25, tl_y = 16+60, y, i;
593
594         if (state_slot_flags & (1 << menu_sel))
595                 draw_savestate_bg(menu_sel);
596         menu_draw_begin();
597
598         text_out16(tl_x, 16+30, is_loading ? "Load state" : "Save state");
599
600         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 108);
601
602         /* draw all 10 slots */
603         y = tl_y;
604         for (i = 0; i < 10; i++, y+=10)
605         {
606                 text_out16(tl_x, y, "SLOT %i (%s)", i, (state_slot_flags & (1 << i)) ? "USED" : "free");
607         }
608         text_out16(tl_x, y, "back");
609
610         menu_draw_end();
611 }
612
613 static int savestate_menu_loop(int is_loading)
614 {
615         static int menu_sel = 10;
616         int menu_sel_max = 10;
617         unsigned long inp = 0;
618
619         state_check_slots();
620
621         for(;;)
622         {
623                 draw_savestate_menu(menu_sel, is_loading);
624                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_X|BTN_CIRCLE, 0);
625                 if(inp & BTN_UP  ) {
626                         do {
627                                 menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max;
628                         } while (!(state_slot_flags & (1 << menu_sel)) && menu_sel != menu_sel_max && is_loading);
629                 }
630                 if(inp & BTN_DOWN) {
631                         do {
632                                 menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0;
633                         } while (!(state_slot_flags & (1 << menu_sel)) && menu_sel != menu_sel_max && is_loading);
634                 }
635                 if(inp & BTN_CIRCLE) { // save/load
636                         if (menu_sel < 10) {
637                                 state_slot = menu_sel;
638                                 PicoStateProgressCB = emu_msg_cb; /* also suitable for menu */
639                                 if (emu_SaveLoadGame(is_loading, 0)) {
640                                         strcpy(menuErrorMsg, is_loading ? "Load failed" : "Save failed");
641                                         return 1;
642                                 }
643                                 return 0;
644                         } else  return 1;
645                 }
646                 if(inp & BTN_X) return 1;
647         }
648 }
649
650 // -------------- key config --------------
651
652 static char *action_binds(int player_idx, int action_mask)
653 {
654         static char strkeys[32*5];
655         int i;
656
657         strkeys[0] = 0;
658         for (i = 0; i < 32; i++) // i is key index
659         {
660                 if (currentConfig.KeyBinds[i] & action_mask)
661                 {
662                         if (player_idx >= 0 && ((currentConfig.KeyBinds[i] >> 16) & 3) != player_idx) continue;
663                         if (strkeys[0]) {
664                                 strcat(strkeys, i >= 28 ? ", " : " + "); // nub "buttons" don't create combos
665                                 strcat(strkeys, pspKeyNames[i]);
666                                 break;
667                         }
668                         else strcpy(strkeys, pspKeyNames[i]);
669                 }
670         }
671
672         return strkeys;
673 }
674
675 static void unbind_action(int action)
676 {
677         int i;
678
679         for (i = 0; i < 32; i++)
680                 currentConfig.KeyBinds[i] &= ~action;
681 }
682
683 static int count_bound_keys(int action, int pl_idx)
684 {
685         int i, keys = 0;
686
687         for (i = 0; i < 32; i++)
688         {
689                 if (pl_idx >= 0 && (currentConfig.KeyBinds[i]&0x30000) != (pl_idx<<16)) continue;
690                 if (currentConfig.KeyBinds[i] & action) keys++;
691         }
692
693         return keys;
694 }
695
696 typedef struct { char *name; int mask; } bind_action_t;
697
698 static void draw_key_config(const bind_action_t *opts, int opt_cnt, int player_idx, int sel)
699 {
700         int x, y, tl_y = 16+40, i;
701
702         menu_draw_begin();
703         if (player_idx >= 0) {
704                 text_out16(80+80, 16+20, "Player %i controls", player_idx + 1);
705                 x = 80+80;
706         } else {
707                 text_out16(80+80, 16+20, "Emulator controls");
708                 x = 80+40;
709         }
710
711         menu_draw_selection(x - 16, tl_y + sel*10, (player_idx >= 0) ? 66 : 130);
712
713         y = tl_y;
714         for (i = 0; i < opt_cnt; i++, y+=10)
715                 text_out16(x, y, "%s : %s", opts[i].name, action_binds(player_idx, opts[i].mask));
716
717         text_out16(x, y, "Done");
718
719         if (sel < opt_cnt) {
720                 text_out16(80+30, 220, "Press a button to bind/unbind");
721                 text_out16(80+30, 230, "Use SELECT to clear");
722                 text_out16(80+30, 240, "To bind UP/DOWN, hold SELECT");
723                 text_out16(80+30, 250, "Select \"Done\" to exit");
724         } else {
725                 text_out16(80+30, 230, "Use Options -> Save cfg");
726                 text_out16(80+30, 240, "to save controls");
727                 text_out16(80+30, 250, "Press X or O to exit");
728         }
729         menu_draw_end();
730 }
731
732 static void key_config_loop(const bind_action_t *opts, int opt_cnt, int player_idx)
733 {
734         int sel = 0, menu_sel_max = opt_cnt, prev_select = 0, i;
735         unsigned long inp = 0;
736
737         for (;;)
738         {
739                 draw_key_config(opts, opt_cnt, player_idx, sel);
740                 inp = wait_for_input(CONFIGURABLE_KEYS|BTN_SELECT, 1);
741                 if (!(inp & BTN_SELECT)) {
742                         prev_select = 0;
743                         if(inp & BTN_UP  ) { sel--; if (sel < 0) sel = menu_sel_max; continue; }
744                         if(inp & BTN_DOWN) { sel++; if (sel > menu_sel_max) sel = 0; continue; }
745                 }
746                 if (sel >= opt_cnt) {
747                         if (inp & (BTN_X|BTN_CIRCLE)) break;
748                         else continue;
749                 }
750                 // if we are here, we want to bind/unbind something
751                 if ((inp & BTN_SELECT) && !prev_select)
752                         unbind_action(opts[sel].mask);
753                 prev_select = inp & BTN_SELECT;
754                 inp &= CONFIGURABLE_KEYS;
755                 inp &= ~BTN_SELECT;
756                 for (i = 0; i < 32; i++)
757                         if (inp & (1 << i)) {
758                                 if (count_bound_keys(opts[sel].mask, player_idx) >= 2)
759                                      currentConfig.KeyBinds[i] &= ~opts[sel].mask; // allow to unbind only
760                                 else currentConfig.KeyBinds[i] ^=  opts[sel].mask;
761                                 if (player_idx >= 0 && (currentConfig.KeyBinds[i] & opts[sel].mask)) {
762                                         currentConfig.KeyBinds[i] &= ~(3 << 16);
763                                         currentConfig.KeyBinds[i] |= player_idx << 16;
764                                 }
765                         }
766         }
767 }
768
769 static void draw_kc_sel(int menu_sel)
770 {
771         int tl_x = 80+25+40, tl_y = 16+60, y;
772
773         y = tl_y;
774         menu_draw_begin();
775         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 138);
776
777         text_out16(tl_x, y,       "Player 1");
778         text_out16(tl_x, (y+=10), "Player 2");
779         text_out16(tl_x, (y+=10), "Emulator controls");
780         text_out16(tl_x, (y+=10), "Done");
781
782         menu_draw_end();
783 }
784
785
786 // PicoPad[] format: MXYZ SACB RLDU
787 static bind_action_t ctrl_actions[] =
788 {
789         { "UP     ", 0x001 },
790         { "DOWN   ", 0x002 },
791         { "LEFT   ", 0x004 },
792         { "RIGHT  ", 0x008 },
793         { "A      ", 0x040 },
794         { "B      ", 0x010 },
795         { "C      ", 0x020 },
796         { "START  ", 0x080 },
797         { "MODE   ", 0x800 },
798         { "X      ", 0x400 },
799         { "Y      ", 0x200 },
800         { "Z      ", 0x100 },
801 };
802
803 // player2_flag, ?, ?, ?, ?, ?, ?, menu
804 // "NEXT SAVE SLOT", "PREV SAVE SLOT", "SWITCH RENDERER", "SAVE STATE",
805 // "LOAD STATE", "VOLUME UP", "VOLUME DOWN", "DONE"
806 static bind_action_t emuctrl_actions[] =
807 {
808         { "Load State     ", 1<<28 },
809         { "Save State     ", 1<<27 },
810         { "Prev Save Slot ", 1<<25 },
811         { "Next Save Slot ", 1<<24 },
812         { "Switch Renderer", 1<<26 },
813 };
814
815 static void kc_sel_loop(void)
816 {
817         int menu_sel = 3, menu_sel_max = 3;
818         unsigned long inp = 0;
819         int is_6button = currentConfig.PicoOpt & 0x020;
820
821         while (1)
822         {
823                 draw_kc_sel(menu_sel);
824                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_X|BTN_CIRCLE, 0);
825                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
826                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
827                 if (inp & BTN_CIRCLE) {
828                         switch (menu_sel) {
829                                 case 0: key_config_loop(ctrl_actions, is_6button ? 12 : 8, 0); return;
830                                 case 1: key_config_loop(ctrl_actions, is_6button ? 12 : 8, 1); return;
831                                 case 2: key_config_loop(emuctrl_actions,
832                                                 sizeof(emuctrl_actions)/sizeof(emuctrl_actions[0]), -1); return;
833                                 case 3: if (rom_data == NULL) emu_WriteConfig(0); return;
834                                 default: return;
835                         }
836                 }
837                 if (inp & BTN_X) return;
838         }
839 }
840
841
842 // --------- sega/mega cd options ----------
843
844 menu_entry cdopt_entries[] =
845 {
846         { NULL,                        MB_NONE,  MA_CDOPT_TESTBIOS_USA, NULL, 0, 0, 0, 1 },
847         { NULL,                        MB_NONE,  MA_CDOPT_TESTBIOS_EUR, NULL, 0, 0, 0, 1 },
848         { NULL,                        MB_NONE,  MA_CDOPT_TESTBIOS_JAP, NULL, 0, 0, 0, 1 },
849         { "CD LEDs",                   MB_ONOFF, MA_CDOPT_LEDS,         &currentConfig.EmuOpt,  0x0400, 0, 0, 1 },
850         { "CDDA audio (using mp3s)",   MB_ONOFF, MA_CDOPT_CDDA,         &currentConfig.PicoOpt, 0x0800, 0, 0, 1 },
851         { "PCM audio",                 MB_ONOFF, MA_CDOPT_PCM,          &currentConfig.PicoOpt, 0x0400, 0, 0, 1 },
852         { NULL,                        MB_NONE,  MA_CDOPT_READAHEAD,    NULL, 0, 0, 0, 1 },
853         { "SaveRAM cart",              MB_ONOFF, MA_CDOPT_SAVERAM,      &currentConfig.PicoOpt, 0x8000, 0, 0, 1 },
854         { "Scale/Rot. fx (slow)",      MB_ONOFF, MA_CDOPT_SCALEROT_CHIP,&currentConfig.PicoOpt, 0x1000, 0, 0, 1 },
855         { "Better sync (slow)",        MB_ONOFF, MA_CDOPT_BETTER_SYNC,  &currentConfig.PicoOpt, 0x2000, 0, 0, 1 },
856         { "done",                      MB_NONE,  MA_CDOPT_DONE,         NULL, 0, 0, 0, 1 },
857 };
858
859 #define CDOPT_ENTRY_COUNT (sizeof(cdopt_entries) / sizeof(cdopt_entries[0]))
860
861
862 struct bios_names_t
863 {
864         char us[32], eu[32], jp[32];
865 };
866
867 static void menu_cdopt_cust_draw(const menu_entry *entry, int x, int y, void *param)
868 {
869         struct bios_names_t *bios_names = param;
870         char ra_buff[16];
871
872         switch (entry->id)
873         {
874                 case MA_CDOPT_TESTBIOS_USA: text_out16(x, y, "USA BIOS:     %s", bios_names->us); break;
875                 case MA_CDOPT_TESTBIOS_EUR: text_out16(x, y, "EUR BIOS:     %s", bios_names->eu); break;
876                 case MA_CDOPT_TESTBIOS_JAP: text_out16(x, y, "JAP BIOS:     %s", bios_names->jp); break;
877                 case MA_CDOPT_READAHEAD:
878                         if (PicoCDBuffers > 1) sprintf(ra_buff, "%5iK", PicoCDBuffers * 2);
879                         else strcpy(ra_buff, "     OFF");
880                         text_out16(x, y, "ReadAhead buffer      %s", ra_buff);
881                         break;
882                 default:break;
883         }
884 }
885
886 static void draw_cd_menu_options(int menu_sel, struct bios_names_t *bios_names)
887 {
888         int tl_x = 80+25, tl_y = 16+60;
889         menu_id selected_id;
890         char ra_buff[16];
891
892         if (PicoCDBuffers > 1) sprintf(ra_buff, "%5iK", PicoCDBuffers * 2);
893         else strcpy(ra_buff, "     OFF");
894
895         menu_draw_begin();
896
897         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 246);
898
899         me_draw(cdopt_entries, CDOPT_ENTRY_COUNT, tl_x, tl_y, menu_cdopt_cust_draw, bios_names);
900
901         selected_id = me_index2id(cdopt_entries, CDOPT_ENTRY_COUNT, menu_sel);
902         if ((selected_id == MA_CDOPT_TESTBIOS_USA && strcmp(bios_names->us, "NOT FOUND")) ||
903                 (selected_id == MA_CDOPT_TESTBIOS_EUR && strcmp(bios_names->eu, "NOT FOUND")) ||
904                 (selected_id == MA_CDOPT_TESTBIOS_JAP && strcmp(bios_names->jp, "NOT FOUND")))
905                         text_out16(tl_x, 250, "Press start to test selected BIOS");
906
907         menu_draw_end();
908 }
909
910 static void cd_menu_loop_options(void)
911 {
912         static int menu_sel = 0;
913         int menu_sel_max = 10;
914         unsigned long inp = 0;
915         struct bios_names_t bios_names;
916         menu_id selected_id;
917         char *bios, *p;
918
919         if (emu_findBios(4, &bios)) { // US
920                 for (p = bios+strlen(bios)-1; p > bios && *p != '/'; p--);
921                 if (*p == '/') p++;
922                 strncpy(bios_names.us, p, sizeof(bios_names.us)); bios_names.us[sizeof(bios_names.us)-1] = 0;
923         } else  strcpy(bios_names.us, "NOT FOUND");
924
925         if (emu_findBios(8, &bios)) { // EU
926                 for (p = bios+strlen(bios)-1; p > bios && *p != '/'; p--);
927                 if (*p == '/') p++;
928                 strncpy(bios_names.eu, p, sizeof(bios_names.eu)); bios_names.eu[sizeof(bios_names.eu)-1] = 0;
929         } else  strcpy(bios_names.eu, "NOT FOUND");
930
931         if (emu_findBios(1, &bios)) { // JP
932                 for (p = bios+strlen(bios)-1; p > bios && *p != '/'; p--);
933                 if (*p == '/') p++;
934                 strncpy(bios_names.jp, p, sizeof(bios_names.jp)); bios_names.jp[sizeof(bios_names.jp)-1] = 0;
935         } else  strcpy(bios_names.jp, "NOT FOUND");
936
937         menuErrorMsg[0] = 0;
938
939         for (;;)
940         {
941                 draw_cd_menu_options(menu_sel, &bios_names);
942                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_X|BTN_CIRCLE, 0);
943                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
944                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
945                 selected_id = me_index2id(cdopt_entries, CDOPT_ENTRY_COUNT, menu_sel);
946                 if (inp & (BTN_LEFT|BTN_RIGHT)) { // multi choise
947                         if (!me_process(cdopt_entries, CDOPT_ENTRY_COUNT, selected_id, (inp&BTN_RIGHT) ? 1 : 0) &&
948                             selected_id == MA_CDOPT_READAHEAD) {
949                                 if (inp & BTN_LEFT) {
950                                         PicoCDBuffers >>= 1;
951                                         if (PicoCDBuffers < 64) PicoCDBuffers = 0;
952                                 } else {
953                                         if (PicoCDBuffers < 64) PicoCDBuffers = 64;
954                                         else PicoCDBuffers <<= 1;
955                                         if (PicoCDBuffers > 8*1024) PicoCDBuffers = 8*1024; // 16M
956                                 }
957                         }
958                 }
959                 if (inp & BTN_CIRCLE) { // toggleable options
960                         if (!me_process(cdopt_entries, CDOPT_ENTRY_COUNT, selected_id, 1) &&
961                             selected_id == MA_CDOPT_DONE) {
962                                 return;
963                         }
964                         switch (selected_id) { // BIOS testers
965                                 case MA_CDOPT_TESTBIOS_USA:
966                                         if (emu_findBios(4, &bios)) { // test US
967                                                 strcpy(romFileName, bios);
968                                                 engineState = PGS_ReloadRom;
969                                                 return;
970                                         }
971                                         break;
972                                 case MA_CDOPT_TESTBIOS_EUR:
973                                         if (emu_findBios(8, &bios)) { // test EU
974                                                 strcpy(romFileName, bios);
975                                                 engineState = PGS_ReloadRom;
976                                                 return;
977                                         }
978                                         break;
979                                 case MA_CDOPT_TESTBIOS_JAP:
980                                         if (emu_findBios(1, &bios)) { // test JP
981                                                 strcpy(romFileName, bios);
982                                                 engineState = PGS_ReloadRom;
983                                                 return;
984                                         }
985                                         break;
986                                 default:
987                                         break;
988                         }
989                 }
990                 if (inp & BTN_X) return;
991         }
992 }
993
994 // --------- display options ----------
995
996 menu_entry opt3_entries[] =
997 {
998         { NULL,                        MB_NONE,  MA_OPT3_SCALE,         NULL, 0, 0, 0, 1 },
999         { NULL,                        MB_NONE,  MA_OPT3_HSCALE32,      NULL, 0, 0, 0, 1 },
1000         { NULL,                        MB_NONE,  MA_OPT3_HSCALE40,      NULL, 0, 0, 0, 1 },
1001         { NULL,                        MB_ONOFF, MA_OPT3_FILTERING,     &currentConfig.scaling, 1, 0, 0, 1 },
1002         { NULL,                        MB_NONE,  MA_OPT3_VSYNC,         NULL, 0, 0, 0, 1 },
1003         { "Set to unscaled centered",  MB_NONE,  MA_OPT3_PRES_NOSCALE,  NULL, 0, 0, 0, 1 },
1004         { "Set to fullscreen",         MB_NONE,  MA_OPT3_PRES_FULLSCR,  NULL, 0, 0, 0, 1 },
1005         { "done",                      MB_NONE,  MA_OPT3_DONE,          NULL, 0, 0, 0, 1 },
1006 };
1007
1008 #define OPT3_ENTRY_COUNT (sizeof(opt3_entries) / sizeof(opt3_entries[0]))
1009
1010
1011 static void menu_opt3_cust_draw(const menu_entry *entry, int x, int y, void *param)
1012 {
1013         switch (entry->id)
1014         {
1015                 case MA_OPT3_SCALE:
1016                         text_out16(x, y, "Scale factor:                      %.2f", currentConfig.scale);
1017                         break;
1018                 case MA_OPT3_HSCALE32:
1019                         text_out16(x, y, "Hor. scale (for low res. games):   %.2f", currentConfig.hscale32);
1020                         break;
1021                 case MA_OPT3_HSCALE40:
1022                         text_out16(x, y, "Hor. scale (for hi res. games):    %.2f", currentConfig.hscale40);
1023                         break;
1024                 case MA_OPT3_FILTERING:
1025                         text_out16(x, y, "Bilinear filtering                 %s", currentConfig.scaling?"ON":"OFF");
1026                         break;
1027                 case MA_OPT3_VSYNC: {
1028                         char *val = "    never";
1029                         if (currentConfig.EmuOpt & 0x2000)
1030                                 val = (currentConfig.EmuOpt & 0x10000) ? "sometimes" : "   always";
1031                         text_out16(x, y, "Wait for vsync (slow)         %s", val);
1032                         break;
1033                 }
1034                 default: break;
1035         }
1036 }
1037
1038 static void menu_opt3_preview(int is_32col)
1039 {
1040         void *oldstate = NULL;
1041
1042         if (rom_data == NULL || ((Pico.video.reg[12]&1)^1) != is_32col)
1043         {
1044                 extern char bgdatac32_start[], bgdatac40_start[];
1045                 extern int bgdatac32_size, bgdatac40_size;
1046                 void *bgdata = is_32col ? bgdatac32_start : bgdatac40_start;
1047                 unsigned long insize = is_32col ? bgdatac32_size : bgdatac40_size, outsize = 65856;
1048                 int ret;
1049                 ret = uncompress((Bytef *)bg_buffer, &outsize, bgdata, insize);
1050                 if (ret == 0)
1051                 {
1052                         if (rom_data != NULL) oldstate = get_oldstate_for_preview();
1053                         memcpy(Pico.vram,  bg_buffer, sizeof(Pico.vram));
1054                         memcpy(Pico.cram,  (char *)bg_buffer + 0x10000, 0x40*2);
1055                         memcpy(Pico.vsram, (char *)bg_buffer + 0x10080, 0x40*2);
1056                         memcpy(&Pico.video,(char *)bg_buffer + 0x10100, 0x40);
1057                 }
1058                 else
1059                         lprintf("uncompress returned %i\n", ret);
1060         }
1061
1062         memset32(psp_screen, 0, 512*272*2/4);
1063         emu_forcedFrame();
1064         menu_prepare_bg(1, 0);
1065
1066         if (oldstate) restore_oldstate(oldstate);
1067 }
1068
1069 static void draw_dispmenu_options(int menu_sel)
1070 {
1071         int tl_x = 80, tl_y = 16+50;
1072
1073         menu_draw_begin();
1074
1075         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 316);
1076
1077         me_draw(opt3_entries, OPT3_ENTRY_COUNT, tl_x, tl_y, menu_opt3_cust_draw, NULL);
1078
1079         menu_draw_end();
1080 }
1081
1082 static void dispmenu_loop_options(void)
1083 {
1084         static int menu_sel = 0;
1085         int menu_sel_max, is_32col = (Pico.video.reg[12]&1)^1;
1086         unsigned long inp = 0;
1087         menu_id selected_id;
1088
1089         menu_sel_max = me_count_enabled(opt3_entries, OPT3_ENTRY_COUNT) - 1;
1090
1091         for (;;)
1092         {
1093                 draw_dispmenu_options(menu_sel);
1094                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_X|BTN_CIRCLE, 0);
1095                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
1096                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
1097                 selected_id = me_index2id(opt3_entries, OPT3_ENTRY_COUNT, menu_sel);
1098                 if (selected_id == MA_OPT3_HSCALE40 &&  is_32col) { is_32col = 0; menu_opt3_preview(is_32col); }
1099                 if (selected_id == MA_OPT3_HSCALE32 && !is_32col) { is_32col = 1; menu_opt3_preview(is_32col); }
1100
1101                 if (inp & (BTN_LEFT|BTN_RIGHT)) // multi choise
1102                 {
1103                         float *setting = NULL;
1104                         int tmp;
1105                         me_process(opt3_entries, OPT3_ENTRY_COUNT, selected_id, (inp&BTN_RIGHT) ? 1 : 0);
1106                         switch (selected_id) {
1107                                 case MA_OPT3_SCALE:    setting = &currentConfig.scale; break;
1108                                 case MA_OPT3_HSCALE40: setting = &currentConfig.hscale40; is_32col = 0; break;
1109                                 case MA_OPT3_HSCALE32: setting = &currentConfig.hscale32; is_32col = 1; break;
1110                                 case MA_OPT3_FILTERING:menu_opt3_preview(is_32col); break;
1111                                 case MA_OPT3_VSYNC:    tmp = ((currentConfig.EmuOpt>>13)&1) | ((currentConfig.EmuOpt>>15)&2);
1112                                         tmp = (inp & BTN_LEFT) ? (tmp>>1) : ((tmp<<1)|1);
1113                                         if (tmp > 3) tmp = 3;
1114                                         currentConfig.EmuOpt &= ~0x12000;
1115                                         currentConfig.EmuOpt |= ((tmp&2)<<15) | ((tmp&1)<<13);
1116                                         break;
1117                                 default: break;
1118                         }
1119                         if (setting != NULL) {
1120                                 while ((inp = psp_pad_read(0)) & (BTN_LEFT|BTN_RIGHT)) {
1121                                         *setting += (inp & BTN_LEFT) ? -0.01 : 0.01;
1122                                         menu_opt3_preview(is_32col);
1123                                         draw_dispmenu_options(menu_sel); // will wait vsync
1124                                 }
1125                         }
1126                 }
1127                 if (inp & BTN_CIRCLE) { // toggleable options
1128                         me_process(opt3_entries, OPT3_ENTRY_COUNT, selected_id, 1);
1129                         switch (selected_id) {
1130                                 case MA_OPT3_DONE:
1131                                         return;
1132                                 case MA_OPT3_PRES_NOSCALE:
1133                                         currentConfig.scale = currentConfig.hscale40 = currentConfig.hscale32 = 1.0;
1134                                         menu_opt3_preview(is_32col);
1135                                         break;
1136                                 case MA_OPT3_PRES_FULLSCR:
1137                                         currentConfig.scale = 1.20;
1138                                         currentConfig.hscale40 = 1.25;
1139                                         currentConfig.hscale32 = 1.56;
1140                                         menu_opt3_preview(is_32col);
1141                                         break;
1142                                 case MA_OPT3_FILTERING:
1143                                         menu_opt3_preview(is_32col);
1144                                         break;
1145                                 default: break;
1146                         }
1147                 }
1148                 if (inp & BTN_X) return;
1149         }
1150 }
1151
1152
1153 // --------- advanced options ----------
1154
1155 menu_entry opt2_entries[] =
1156 {
1157         { "Emulate Z80",               MB_ONOFF, MA_OPT2_ENABLE_Z80,    &currentConfig.PicoOpt,0x00004, 0, 0, 1 },
1158         { "Emulate YM2612 (FM)",       MB_ONOFF, MA_OPT2_ENABLE_YM2612, &currentConfig.PicoOpt,0x00001, 0, 0, 1 },
1159         { "Emulate SN76496 (PSG)",     MB_ONOFF, MA_OPT2_ENABLE_SN76496,&currentConfig.PicoOpt,0x00002, 0, 0, 1 },
1160         { "gzip savestates",           MB_ONOFF, MA_OPT2_GZIP_STATES,   &currentConfig.EmuOpt, 0x00008, 0, 0, 1 },
1161         { "Don't save last used ROM",  MB_ONOFF, MA_OPT2_NO_LAST_ROM,   &currentConfig.EmuOpt, 0x00020, 0, 0, 1 },
1162         { "Status line in main menu",  MB_ONOFF, MA_OPT2_STATUS_LINE,   &currentConfig.EmuOpt, 0x20000, 0, 0, 1 },
1163         { "done",                      MB_NONE,  MA_OPT2_DONE,          NULL, 0, 0, 0, 1 },
1164 };
1165
1166 #define OPT2_ENTRY_COUNT (sizeof(opt2_entries) / sizeof(opt2_entries[0]))
1167
1168
1169 static void draw_amenu_options(int menu_sel)
1170 {
1171         int tl_x = 80+25, tl_y = 16+50;
1172
1173         menu_draw_begin();
1174
1175         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 252);
1176
1177         me_draw(opt2_entries, OPT2_ENTRY_COUNT, tl_x, tl_y, NULL, NULL);
1178
1179         menu_draw_end();
1180 }
1181
1182 static void amenu_loop_options(void)
1183 {
1184         static int menu_sel = 0;
1185         int menu_sel_max;
1186         unsigned long inp = 0;
1187         menu_id selected_id;
1188
1189         menu_sel_max = me_count_enabled(opt2_entries, OPT2_ENTRY_COUNT) - 1;
1190
1191         for(;;)
1192         {
1193                 draw_amenu_options(menu_sel);
1194                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_X|BTN_CIRCLE, 0);
1195                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
1196                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
1197                 selected_id = me_index2id(opt2_entries, OPT2_ENTRY_COUNT, menu_sel);
1198                 if (inp & (BTN_LEFT|BTN_RIGHT)) { // multi choise
1199                         if (!me_process(opt2_entries, OPT2_ENTRY_COUNT, selected_id, (inp&BTN_RIGHT) ? 1 : 0) &&
1200                             selected_id == MA_OPT2_GAMMA) {
1201                                 // TODO?
1202                         }
1203                 }
1204                 if (inp & BTN_CIRCLE) { // toggleable options
1205                         if (!me_process(opt2_entries, OPT2_ENTRY_COUNT, selected_id, 1) &&
1206                             selected_id == MA_OPT2_DONE) {
1207                                 return;
1208                         }
1209                 }
1210                 if (inp & BTN_X) return;
1211         }
1212 }
1213
1214 // -------------- options --------------
1215
1216
1217 menu_entry opt_entries[] =
1218 {
1219         { NULL,                        MB_NONE,  MA_OPT_RENDERER,      NULL, 0, 0, 0, 1 },
1220         { "Accurate timing (slower)",  MB_ONOFF, MA_OPT_ACC_TIMING,    &currentConfig.PicoOpt, 0x0040, 0, 0, 1 },
1221         { "Accurate sprites (slower)", MB_ONOFF, MA_OPT_ACC_SPRITES,   &currentConfig.PicoOpt, 0x0080, 0, 0, 1 },
1222         { "Show FPS",                  MB_ONOFF, MA_OPT_SHOW_FPS,      &currentConfig.EmuOpt,  0x0002, 0, 0, 1 },
1223         { NULL,                        MB_RANGE, MA_OPT_FRAMESKIP,     &currentConfig.Frameskip, 0, -1, 16, 1 },
1224         { "Enable sound",              MB_ONOFF, MA_OPT_ENABLE_SOUND,  &currentConfig.EmuOpt,  0x0004, 0, 0, 1 },
1225         { NULL,                        MB_NONE,  MA_OPT_SOUND_QUALITY, NULL, 0, 0, 0, 1 },
1226         { "6 button pad",              MB_ONOFF, MA_OPT_6BUTTON_PAD,   &currentConfig.PicoOpt, 0x0020, 0, 0, 1 },
1227         { NULL,                        MB_NONE,  MA_OPT_REGION,        NULL, 0, 0, 0, 1 },
1228         { "Use SRAM/BRAM savestates",  MB_ONOFF, MA_OPT_SRAM_STATES,   &currentConfig.EmuOpt,  0x0001, 0, 0, 1 },
1229         { NULL,                        MB_NONE,  MA_OPT_CONFIRM_STATES,NULL, 0, 0, 0, 1 },
1230         { "Save slot",                 MB_RANGE, MA_OPT_SAVE_SLOT,     &state_slot, 0, 0, 9, 1 },
1231         { NULL,                        MB_NONE,  MA_OPT_CPU_CLOCKS,    NULL, 0, 0, 0, 1 },
1232         { "[Display options]",         MB_NONE,  MA_OPT_DISP_OPTS,     NULL, 0, 0, 0, 1 },
1233         { "[Sega/Mega CD options]",    MB_NONE,  MA_OPT_SCD_OPTS,      NULL, 0, 0, 0, 1 },
1234         { "[Advanced options]",        MB_NONE,  MA_OPT_ADV_OPTS,      NULL, 0, 0, 0, 1 },
1235         { NULL,                        MB_NONE,  MA_OPT_SAVECFG,       NULL, 0, 0, 0, 1 },
1236         { "Save cfg for current game only",MB_NONE,MA_OPT_SAVECFG_GAME,NULL, 0, 0, 0, 1 },
1237         { NULL,                        MB_NONE,  MA_OPT_LOADCFG,       NULL, 0, 0, 0, 1 },
1238 };
1239
1240 #define OPT_ENTRY_COUNT (sizeof(opt_entries) / sizeof(opt_entries[0]))
1241
1242
1243 static const char *region_name(unsigned int code)
1244 {
1245         static const char *names[] = { "Auto", "      Japan NTSC", "      Japan PAL", "      USA", "      Europe" };
1246         static const char *names_short[] = { "", " JP", " JP", " US", " EU" };
1247         int u, i = 0;
1248         if (code) {
1249                 code <<= 1;
1250                 while((code >>= 1)) i++;
1251                 if (i > 4) return "unknown";
1252                 return names[i];
1253         } else {
1254                 static char name[24];
1255                 strcpy(name, "Auto:");
1256                 for (u = 0; u < 3; u++) {
1257                         i = 0; code = ((PicoAutoRgnOrder >> u*4) & 0xf) << 1;
1258                         while((code >>= 1)) i++;
1259                         strcat(name, names_short[i]);
1260                 }
1261                 return name;
1262         }
1263 }
1264
1265
1266 static void menu_opt_cust_draw(const menu_entry *entry, int x, int y, void *param)
1267 {
1268         char *str, str24[24];
1269
1270         switch (entry->id)
1271         {
1272                 case MA_OPT_RENDERER:
1273                         if (currentConfig.PicoOpt&0x10)
1274                                 str = "fast";
1275                         else if (currentConfig.EmuOpt&0x80)
1276                                 str = "accurate";
1277                         else
1278                                 str = " 8bit accurate"; // n/a
1279                         text_out16(x, y, "Renderer:                  %s", str);
1280                         break;
1281                 case MA_OPT_FRAMESKIP:
1282                         if (currentConfig.Frameskip < 0)
1283                              strcpy(str24, "Auto");
1284                         else sprintf(str24, "%i", currentConfig.Frameskip);
1285                         text_out16(x, y, "Frameskip                  %s", str24);
1286                         break;
1287                 case MA_OPT_SOUND_QUALITY:
1288                         str = (currentConfig.PicoOpt&0x08)?"stereo":"mono";
1289                         text_out16(x, y, "Sound Quality:     %5iHz %s", currentConfig.PsndRate, str);
1290                         break;
1291                 case MA_OPT_REGION:
1292                         text_out16(x, y, "Region:              %s", region_name(currentConfig.PicoRegion));
1293                         break;
1294                 case MA_OPT_CONFIRM_STATES:
1295                         switch ((currentConfig.EmuOpt >> 9) & 5) {
1296                                 default: str = "OFF";    break;
1297                                 case 1:  str = "writes"; break;
1298                                 case 4:  str = "loads";  break;
1299                                 case 5:  str = "both";   break;
1300                         }
1301                         text_out16(x, y, "Confirm savestate          %s", str);
1302                         break;
1303                 case MA_OPT_CPU_CLOCKS:
1304                         text_out16(x, y, "CPU/bus clock       %3i/%3iMHz", currentConfig.CPUclock, currentConfig.CPUclock/2);
1305                         break;
1306                 case MA_OPT_SAVECFG:
1307                         str24[0] = 0;
1308                         if (config_slot != 0) sprintf(str24, " (profile: %i)", config_slot);
1309                         text_out16(x, y, "Save cfg as default%s", str24);
1310                         break;
1311                 case MA_OPT_LOADCFG:
1312                         text_out16(x, y, "Load cfg from profile %i", config_slot);
1313                         break;
1314                 default:
1315                         lprintf("%s: unimplemented (%i)\n", __FUNCTION__, entry->id);
1316                         break;
1317         }
1318 }
1319
1320
1321 static void draw_menu_options(int menu_sel)
1322 {
1323         int tl_x = 80+25, tl_y = 16+24;
1324
1325         menu_draw_begin();
1326
1327         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 284);
1328
1329         me_draw(opt_entries, OPT_ENTRY_COUNT, tl_x, tl_y, menu_opt_cust_draw, NULL);
1330
1331         menu_draw_end();
1332 }
1333
1334 static int sndrate_prevnext(int rate, int dir)
1335 {
1336         int i, rates[] = { 11025, 22050, 44100 };
1337
1338         for (i = 0; i < 5; i++)
1339                 if (rates[i] == rate) break;
1340
1341         i += dir ? 1 : -1;
1342         if (i > 2) return dir ? 44100 : 22050;
1343         if (i < 0) return dir ? 22050 : 11025;
1344         return rates[i];
1345 }
1346
1347 static void region_prevnext(int right)
1348 {
1349         // jp_ntsc=1, jp_pal=2, usa=4, eu=8
1350         static int rgn_orders[] = { 0x148, 0x184, 0x814, 0x418, 0x841, 0x481 };
1351         int i;
1352         if (right) {
1353                 if (!currentConfig.PicoRegion) {
1354                         for (i = 0; i < 6; i++)
1355                                 if (rgn_orders[i] == PicoAutoRgnOrder) break;
1356                         if (i < 5) PicoAutoRgnOrder = rgn_orders[i+1];
1357                         else currentConfig.PicoRegion=1;
1358                 }
1359                 else currentConfig.PicoRegion<<=1;
1360                 if (currentConfig.PicoRegion > 8) currentConfig.PicoRegion = 8;
1361         } else {
1362                 if (!currentConfig.PicoRegion) {
1363                         for (i = 0; i < 6; i++)
1364                                 if (rgn_orders[i] == PicoAutoRgnOrder) break;
1365                         if (i > 0) PicoAutoRgnOrder = rgn_orders[i-1];
1366                 }
1367                 else currentConfig.PicoRegion>>=1;
1368         }
1369 }
1370
1371 static void menu_options_save(void)
1372 {
1373         PicoOpt = currentConfig.PicoOpt;
1374         PsndRate = currentConfig.PsndRate;
1375         PicoRegionOverride = currentConfig.PicoRegion;
1376         if (!(PicoOpt & 0x20)) {
1377                 // unbind XYZ MODE, just in case
1378                 unbind_action(0xf00);
1379         }
1380 }
1381
1382 static int menu_loop_options(void)
1383 {
1384         static int menu_sel = 0;
1385         int menu_sel_max, ret;
1386         unsigned long inp = 0;
1387         menu_id selected_id;
1388
1389         currentConfig.PicoOpt = PicoOpt;
1390         currentConfig.PsndRate = PsndRate;
1391         currentConfig.PicoRegion = PicoRegionOverride;
1392
1393         me_enable(opt_entries, OPT_ENTRY_COUNT, MA_OPT_SAVECFG_GAME, rom_data != NULL);
1394         me_enable(opt_entries, OPT_ENTRY_COUNT, MA_OPT_LOADCFG, config_slot != config_slot_current);
1395         menu_sel_max = me_count_enabled(opt_entries, OPT_ENTRY_COUNT) - 1;
1396         if (menu_sel > menu_sel_max) menu_sel = menu_sel_max;
1397
1398         while (1)
1399         {
1400                 draw_menu_options(menu_sel);
1401                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_X|BTN_CIRCLE, 0);
1402                 if (inp & BTN_UP  ) { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
1403                 if (inp & BTN_DOWN) { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
1404                 selected_id = me_index2id(opt_entries, OPT_ENTRY_COUNT, menu_sel);
1405                 if (inp & (BTN_LEFT|BTN_RIGHT)) { // multi choise
1406                         if (!me_process(opt_entries, OPT_ENTRY_COUNT, selected_id, (inp&BTN_RIGHT) ? 1 : 0)) {
1407                                 switch (selected_id) {
1408                                         case MA_OPT_RENDERER:
1409                                                 if ((currentConfig.PicoOpt&0x10) || !(currentConfig.EmuOpt &0x80)) {
1410                                                         currentConfig.PicoOpt&= ~0x10;
1411                                                         currentConfig.EmuOpt |=  0x80;
1412                                                 } else {
1413                                                         currentConfig.PicoOpt|=  0x10;
1414                                                         currentConfig.EmuOpt &= ~0x80;
1415                                                 }
1416                                                 break;
1417                                         case MA_OPT_SOUND_QUALITY:
1418                                                 currentConfig.PsndRate = sndrate_prevnext(currentConfig.PsndRate, inp & BTN_RIGHT);
1419                                                 break;
1420                                         case MA_OPT_REGION:
1421                                                 region_prevnext(inp & BTN_RIGHT);
1422                                                 break;
1423                                         case MA_OPT_CONFIRM_STATES: {
1424                                                          int n = ((currentConfig.EmuOpt>>9)&1) | ((currentConfig.EmuOpt>>10)&2);
1425                                                          n += (inp & BTN_LEFT) ? -1 : 1;
1426                                                          if (n < 0) n = 0; else if (n > 3) n = 3;
1427                                                          n |= n << 1; n &= ~2;
1428                                                          currentConfig.EmuOpt &= ~0xa00;
1429                                                          currentConfig.EmuOpt |= n << 9;
1430                                                          break;
1431                                                  }
1432                                         case MA_OPT_SAVE_SLOT:
1433                                                  if (inp & BTN_RIGHT) {
1434                                                          state_slot++; if (state_slot > 9) state_slot = 0;
1435                                                  } else {state_slot--; if (state_slot < 0) state_slot = 9;
1436                                                  }
1437                                                  break;
1438                                         case MA_OPT_CPU_CLOCKS:
1439                                                  while ((inp = psp_pad_read(0)) & (BTN_LEFT|BTN_RIGHT)) {
1440                                                          currentConfig.CPUclock += (inp & BTN_LEFT) ? -1 : 1;
1441                                                          if (currentConfig.CPUclock <  19) currentConfig.CPUclock = 19;
1442                                                          if (currentConfig.CPUclock > 333) currentConfig.CPUclock = 333;
1443                                                          draw_menu_options(menu_sel); // will wait vsync
1444                                                  }
1445                                                  break;
1446                                         case MA_OPT_SAVECFG:
1447                                         case MA_OPT_SAVECFG_GAME:
1448                                         case MA_OPT_LOADCFG:
1449                                                  config_slot += (inp&BTN_RIGHT) ? 1 : -1;
1450                                                  if (config_slot > 9) config_slot = 0;
1451                                                  if (config_slot < 0) config_slot = 9;
1452                                                  me_enable(opt_entries, OPT_ENTRY_COUNT, MA_OPT_LOADCFG, config_slot != config_slot_current);
1453                                                  menu_sel_max = me_count_enabled(opt_entries, OPT_ENTRY_COUNT) - 1;
1454                                                  if (menu_sel > menu_sel_max) menu_sel = menu_sel_max;
1455                                                  break;
1456                                         default:
1457                                                 //lprintf("%s: something unknown selected (%i)\n", __FUNCTION__, selected_id);
1458                                                 break;
1459                                 }
1460                         }
1461                 }
1462                 if (inp & BTN_CIRCLE) {
1463                         if (!me_process(opt_entries, OPT_ENTRY_COUNT, selected_id, 1))
1464                         {
1465                                 switch (selected_id)
1466                                 {
1467                                         case MA_OPT_DISP_OPTS:
1468                                                 dispmenu_loop_options();
1469                                                 break;
1470                                         case MA_OPT_SCD_OPTS:
1471                                                 cd_menu_loop_options();
1472                                                 if (engineState == PGS_ReloadRom)
1473                                                         return 0; // test BIOS
1474                                                 break;
1475                                         case MA_OPT_ADV_OPTS:
1476                                                 amenu_loop_options();
1477                                                 break;
1478                                         case MA_OPT_SAVECFG: // done (update and write)
1479                                                 menu_options_save();
1480                                                 if (emu_WriteConfig(0)) strcpy(menuErrorMsg, "config saved");
1481                                                 else strcpy(menuErrorMsg, "failed to write config");
1482                                                 return 1;
1483                                         case MA_OPT_SAVECFG_GAME: // done (update and write for current game)
1484                                                 menu_options_save();
1485                                                 if (emu_WriteConfig(1)) strcpy(menuErrorMsg, "config saved");
1486                                                 else strcpy(menuErrorMsg, "failed to write config");
1487                                                 return 1;
1488                                         case MA_OPT_LOADCFG:
1489                                                 ret = emu_ReadConfig(1, 1);
1490                                                 if (!ret) ret = emu_ReadConfig(0, 1);
1491                                                 if (ret)  strcpy(menuErrorMsg, "config loaded");
1492                                                 else      strcpy(menuErrorMsg, "failed to load config");
1493                                                 return 1;
1494                                         default:
1495                                                 //lprintf("%s: something unknown selected (%i)\n", __FUNCTION__, selected_id);
1496                                                 break;
1497                                 }
1498                         }
1499                 }
1500                 if(inp & BTN_X) {
1501                         menu_options_save();
1502                         return 0;  // done (update, no write)
1503                 }
1504         }
1505 }
1506
1507 // -------------- credits --------------
1508
1509 static void draw_menu_credits(void)
1510 {
1511         int tl_x = 80+15, tl_y = 16+64, y;
1512         menu_draw_begin();
1513
1514         text_out16(tl_x, 16+20, "PicoDrive v" VERSION " (c) notaz, 2006,2007");
1515
1516         y = tl_y;
1517         text_out16(tl_x, y, "Credits:");
1518         text_out16(tl_x, (y+=10), "fDave: base code of PicoDrive");
1519         text_out16(tl_x, (y+=10), "Chui: Fame/C");
1520         text_out16(tl_x, (y+=10), "NJ: CZ80");
1521         text_out16(tl_x, (y+=10), "MAME devs: YM2612 and SN76496 cores");
1522         text_out16(tl_x, (y+=10), "Stephane Dallongeville:");
1523         text_out16(tl_x, (y+=10), "    Gens code, base of Fame/C, CZ80");
1524         text_out16(tl_x, (y+=10), "Charles MacDonald: Genesis hw docs");
1525         text_out16(tl_x, (y+=10), "Haze: Genesis hw info");
1526         text_out16(tl_x, (y+=10), "ps2dev.org people: PSP SDK/code");
1527         text_out16(tl_x, (y+=10), "ketchupgun: skin design");
1528
1529         menu_draw_end();
1530 }
1531
1532
1533 // -------------- root menu --------------
1534
1535 menu_entry main_entries[] =
1536 {
1537         { "Resume game",        MB_NONE, MA_MAIN_RESUME_GAME, NULL, 0, 0, 0, 0 },
1538         { "Save State",         MB_NONE, MA_MAIN_SAVE_STATE,  NULL, 0, 0, 0, 0 },
1539         { "Load State",         MB_NONE, MA_MAIN_LOAD_STATE,  NULL, 0, 0, 0, 0 },
1540         { "Reset game",         MB_NONE, MA_MAIN_RESET_GAME,  NULL, 0, 0, 0, 0 },
1541         { "Load new ROM/ISO",   MB_NONE, MA_MAIN_LOAD_ROM,    NULL, 0, 0, 0, 1 },
1542         { "Change options",     MB_NONE, MA_MAIN_OPTIONS,     NULL, 0, 0, 0, 1 },
1543         { "Configure controls", MB_NONE, MA_MAIN_CONTROLS,    NULL, 0, 0, 0, 1 },
1544         { "Credits",            MB_NONE, MA_MAIN_CREDITS,     NULL, 0, 0, 0, 1 },
1545         { "Patches / GameGenie",MB_NONE, MA_MAIN_PATCHES,     NULL, 0, 0, 0, 0 },
1546         { "Exit",               MB_NONE, MA_MAIN_EXIT,        NULL, 0, 0, 0, 1 }
1547 };
1548
1549 #define MAIN_ENTRY_COUNT (sizeof(main_entries) / sizeof(main_entries[0]))
1550
1551 static void draw_menu_root(int menu_sel)
1552 {
1553         const int tl_x = 86+70, tl_y = 16+70;
1554         char *stat = NULL;
1555
1556         menu_draw_begin();
1557
1558         if ((currentConfig.EmuOpt&0x20000) && (stat = psp_get_status_line()))
1559                 text_out16(287, 12, "%s", stat);
1560
1561         text_out16(tl_x, 48, "PicoDrive v" VERSION);
1562
1563         menu_draw_selection(tl_x - 16, tl_y + menu_sel*10, 146);
1564
1565         me_draw(main_entries, MAIN_ENTRY_COUNT, tl_x, tl_y, NULL, NULL);
1566
1567         // error
1568         if (menuErrorMsg[0])
1569                 text_out16(10, 252, menuErrorMsg);
1570         menu_draw_end();
1571 }
1572
1573
1574 static void menu_loop_root(void)
1575 {
1576         static int menu_sel = 0;
1577         int ret, menu_sel_max;
1578         unsigned long inp = 0;
1579
1580         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_RESUME_GAME, rom_data != NULL);
1581         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_SAVE_STATE,  rom_data != NULL);
1582         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_LOAD_STATE,  rom_data != NULL);
1583         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_RESET_GAME,  rom_data != NULL);
1584         me_enable(main_entries, MAIN_ENTRY_COUNT, MA_MAIN_PATCHES,     PicoPatches != NULL);
1585
1586         menu_sel_max = me_count_enabled(main_entries, MAIN_ENTRY_COUNT) - 1;
1587         if (menu_sel > menu_sel_max) menu_sel = menu_sel_max;
1588
1589         // mp3 errors?
1590         if (mp3_last_error != 0) {
1591                 if (mp3_last_error == -1)
1592                      sprintf(menuErrorMsg, "Unsupported mp3 format, use 44kHz stereo");
1593                 else sprintf(menuErrorMsg, "mp3 init failed, code %08x", mp3_last_error);
1594                 mp3_last_error = 0;
1595         }
1596
1597         /* make sure action buttons are not pressed on entering menu */
1598         draw_menu_root(menu_sel);
1599
1600         while (psp_pad_read(1) & (BTN_X|BTN_CIRCLE|BTN_SELECT)) psp_msleep(50);
1601
1602         for (;;)
1603         {
1604                 draw_menu_root(menu_sel);
1605                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_X|BTN_CIRCLE|BTN_SELECT|BTN_L|BTN_R, 0);
1606                 if(inp & BTN_UP  )  { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
1607                 if(inp & BTN_DOWN)  { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
1608                 if((inp & (BTN_L|BTN_R)) == (BTN_L|BTN_R)) debug_menu_loop();
1609                 if( inp & (BTN_SELECT|BTN_X)) {
1610                         if (rom_data) {
1611                                 while (psp_pad_read(1) & (BTN_SELECT|BTN_X)) psp_msleep(50); // wait until released
1612                                 engineState = PGS_Running;
1613                                 break;
1614                         }
1615                 }
1616                 if(inp & BTN_CIRCLE)  {
1617                         menuErrorMsg[0] = 0; // clear error msg
1618                         switch (me_index2id(main_entries, MAIN_ENTRY_COUNT, menu_sel))
1619                         {
1620                                 case MA_MAIN_RESUME_GAME:
1621                                         if (rom_data) {
1622                                                 while (psp_pad_read(1) & BTN_CIRCLE) psp_msleep(50);
1623                                                 engineState = PGS_Running;
1624                                                 return;
1625                                         }
1626                                         break;
1627                                 case MA_MAIN_SAVE_STATE:
1628                                         if (rom_data) {
1629                                                 if(savestate_menu_loop(0))
1630                                                         continue;
1631                                                 engineState = PGS_Running;
1632                                                 return;
1633                                         }
1634                                         break;
1635                                 case MA_MAIN_LOAD_STATE:
1636                                         if (rom_data) {
1637                                                 if(savestate_menu_loop(1))
1638                                                         continue;
1639                                                 engineState = PGS_Running;
1640                                                 return;
1641                                         }
1642                                         break;
1643                                 case MA_MAIN_RESET_GAME:
1644                                         if (rom_data) {
1645                                                 emu_ResetGame();
1646                                                 engineState = PGS_Running;
1647                                                 return;
1648                                         }
1649                                         break;
1650                                 case MA_MAIN_LOAD_ROM:
1651                                 {
1652                                         char curr_path[PATH_MAX], *selfname;
1653                                         FILE *tstf;
1654                                         if ( (tstf = fopen(currentConfig.lastRomFile, "rb")) )
1655                                         {
1656                                                 fclose(tstf);
1657                                                 strcpy(curr_path, currentConfig.lastRomFile);
1658                                         }
1659                                         else
1660                                                 getcwd(curr_path, PATH_MAX);
1661                                         selfname = romsel_loop(curr_path);
1662                                         if (selfname) {
1663                                                 lprintf("selected file: %s\n", selfname);
1664                                                 engineState = PGS_ReloadRom;
1665                                                 return;
1666                                         }
1667                                         break;
1668                                 }
1669                                 case MA_MAIN_OPTIONS:
1670                                         ret = menu_loop_options();
1671                                         if (ret == 1) continue; // status update
1672                                         if (engineState == PGS_ReloadRom)
1673                                                 return; // BIOS test
1674                                         break;
1675                                 case MA_MAIN_CONTROLS:
1676                                         kc_sel_loop();
1677                                         break;
1678                                 case MA_MAIN_CREDITS:
1679                                         draw_menu_credits();
1680                                         psp_msleep(500);
1681                                         inp = 0;
1682                                         while (!(inp & (BTN_X|BTN_CIRCLE)))
1683                                                 inp = wait_for_input(BTN_X|BTN_CIRCLE, 0);
1684                                         break;
1685                                 case MA_MAIN_EXIT:
1686                                         engineState = PGS_Quit;
1687                                         return;
1688                                 case MA_MAIN_PATCHES:
1689                                         if (rom_data && PicoPatches) {
1690                                                 patches_menu_loop();
1691                                                 PicoPatchApply();
1692                                                 strcpy(menuErrorMsg, "Patches applied");
1693                                                 continue;
1694                                         }
1695                                         break;
1696                                 default:
1697                                         lprintf("%s: something unknown selected\n", __FUNCTION__);
1698                                         break;
1699                         }
1700                 }
1701         }
1702 }
1703
1704 // warning: alignment
1705 static void menu_darken_bg(void *dst, const void *src, int pixels, int darker)
1706 {
1707         unsigned int *dest = dst;
1708         const unsigned int *srce = src;
1709         pixels /= 2;
1710         if (darker)
1711         {
1712                 while (pixels--)
1713                 {
1714                         unsigned int p = *srce++;
1715                         *dest++ = ((p&0xf79ef79e)>>1) - ((p&0xc618c618)>>3);
1716                 }
1717         }
1718         else
1719         {
1720                 while (pixels--)
1721                 {
1722                         unsigned int p = *srce++;
1723                         *dest++ = (p&0xf79ef79e)>>1;
1724                 }
1725         }
1726 }
1727
1728 static void menu_prepare_bg(int use_game_bg, int use_fg)
1729 {
1730         if (use_game_bg)
1731         {
1732                 // darken the active framebuffer
1733                 unsigned short *dst = bg_buffer;
1734                 unsigned short *src = use_fg ? psp_video_get_active_fb() : psp_screen;
1735                 int i;
1736                 for (i = 272; i > 0; i--, dst += 480, src += 512)
1737                         menu_darken_bg(dst, src, 480, 1);
1738                 //memset32((int *)(bg_buffer + 480*264), 0, 480*8*2/4);
1739         }
1740         else
1741         {
1742                 // should really only happen once, on startup..
1743                 memset32((int *)(void *)bg_buffer, 0, sizeof(bg_buffer)/4);
1744                 readpng(bg_buffer, "skin/background.png", READPNG_BG);
1745         }
1746         sceKernelDcacheWritebackAll();
1747 }
1748
1749 static void menu_gfx_prepare(void)
1750 {
1751         menu_prepare_bg(rom_data != NULL, 1);
1752
1753         menu_draw_begin();
1754         menu_draw_end();
1755 }
1756
1757
1758 void menu_loop(void)
1759 {
1760         menu_gfx_prepare();
1761
1762         menu_loop_root();
1763
1764         menuErrorMsg[0] = 0;
1765 }
1766
1767
1768 // --------- CD tray close menu ----------
1769
1770 static void draw_menu_tray(int menu_sel)
1771 {
1772         int tl_x = 70, tl_y = 90, y;
1773
1774         menu_draw_begin();
1775
1776         text_out16(tl_x, 20, "The unit is about to");
1777         text_out16(tl_x, 30, "close the CD tray.");
1778
1779         y = tl_y;
1780         text_out16(tl_x, y,       "Load new CD image");
1781         text_out16(tl_x, (y+=10), "Insert nothing");
1782
1783         // draw cursor
1784         text_out16(tl_x - 16, tl_y + menu_sel*10, ">");
1785         // error
1786         if (menuErrorMsg[0]) text_out16(5, 226, menuErrorMsg);
1787         menu_draw_end();
1788 }
1789
1790
1791 int menu_loop_tray(void)
1792 {
1793         int menu_sel = 0, menu_sel_max = 1;
1794         unsigned long inp = 0;
1795         char curr_path[PATH_MAX], *selfname;
1796         FILE *tstf;
1797
1798         menu_gfx_prepare();
1799
1800         if ( (tstf = fopen(currentConfig.lastRomFile, "rb")) )
1801         {
1802                 fclose(tstf);
1803                 strcpy(curr_path, currentConfig.lastRomFile);
1804         }
1805         else
1806         {
1807                 getcwd(curr_path, PATH_MAX);
1808         }
1809
1810         /* make sure action buttons are not pressed on entering menu */
1811         draw_menu_tray(menu_sel);
1812         while (psp_pad_read(1) & BTN_CIRCLE) psp_msleep(50);
1813
1814         for (;;)
1815         {
1816                 draw_menu_tray(menu_sel);
1817                 inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_X, 0);
1818                 if(inp & BTN_UP  )  { menu_sel--; if (menu_sel < 0) menu_sel = menu_sel_max; }
1819                 if(inp & BTN_DOWN)  { menu_sel++; if (menu_sel > menu_sel_max) menu_sel = 0; }
1820                 if(inp & BTN_CIRCLE)  {
1821                         switch (menu_sel) {
1822                                 case 0: // select image
1823                                         selfname = romsel_loop(curr_path);
1824                                         if (selfname) {
1825                                                 int ret = -1, cd_type;
1826                                                 cd_type = emu_cdCheck(NULL);
1827                                                 if (cd_type > 0)
1828                                                         ret = Insert_CD(romFileName, cd_type == 2);
1829                                                 if (ret != 0) {
1830                                                         sprintf(menuErrorMsg, "Load failed, invalid CD image?");
1831                                                         lprintf("%s\n", menuErrorMsg);
1832                                                         continue;
1833                                                 }
1834                                                 engineState = PGS_RestartRun;
1835                                                 return 1;
1836                                         }
1837                                         break;
1838                                 case 1: // insert nothing
1839                                         engineState = PGS_RestartRun;
1840                                         return 0;
1841                         }
1842                 }
1843                 menuErrorMsg[0] = 0; // clear error msg
1844         }
1845 }
1846
1847