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