File: Dialogs.py

package info (click to toggle)
fofix-dfsg 3.121-2
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 27,016 kB
  • ctags: 4,131
  • sloc: python: 44,002; makefile: 99; perl: 42; sh: 39
file content (5606 lines) | stat: -rwxr-xr-x 233,502 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
#####################################################################
# -*- coding: iso-8859-1 -*-                                        #
#                                                                   #
# Frets on Fire                                                     #
# Copyright (C) 2006 Sami Ky�stil�                                  #
#               2008 myfingershurt                                  #
#               2008 Glorandwarf                                    #
#               2008 ShiekOdaSandz                                  #
#               2008 QQStarS                                        #
#               2008 Blazingamer                                    #
#               2008 evilynux <evilynux@gmail.com>                  #
#                                                                   #
# This program is free software; you can redistribute it and/or     #
# modify it under the terms of the GNU General Public License       #
# as published by the Free Software Foundation; either version 2    #
# of the License, or (at your option) any later version.            #
#                                                                   #
# This program is distributed in the hope that it will be useful,   #
# but WITHOUT ANY WARRANTY; without even the implied warranty of    #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the     #
# GNU General Public License for more details.                      #
#                                                                   #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software       #
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,        #
# MA  02110-1301, USA.                                              #
#####################################################################

"""A bunch of dialog functions for interacting with the user."""

import pygame
from OpenGL.GL import *
from OpenGL.GLU import *
import math
import os
import fnmatch
import string
import time

from View import Layer, BackgroundLayer
from Input import KeyListener
from Camera import Camera
from Mesh import Mesh
from Menu import Menu
from Language import _
from Texture import Texture
from Player import GUITARTYPES, DRUMTYPES, MICTYPES
import Theme
import Log
import Song
import Data
import Player
import Guitar
import random
from Shader import shaders

#myfingershurt: drums :)
import Drum

#stump: vocals
import Microphone

# evilynux - MFH-Alarian Mod credits
from Credits import Credits

import Config
import Settings

#MFH - for cd/song list
from Svg import ImgDrawing, SvgContext

#MFH - for loading phrases
def wrapCenteredText(font, pos, text, rightMargin = 1.0, scale = 0.002, visibility = 0.0, linespace = 1.0, allowshadowoffset = False, shadowoffset = (.0022, .0005)):
  """
  Wrap a piece of text inside given margins.
  
  @param pos:         (x, y) tuple, x defines the centerline
  @param text:        Text to wrap
  @param rightMargin: Right margin
  @param scale:       Text scale
  @param visibility:  Visibility factor [0..1], 0 is fully visible
  """
  
  
  x, y = pos

  #MFH: rewriting WrapCenteredText function to properly wrap lines in a centered fashion around a defined centerline (x)
  #space = font.getStringSize(" ", scale = scale)[0]
  #startXpos = x - (rightMargin-x) #for a symmetrical text wrapping
  #x = startXpos
  sentence = ""
  for n, word in enumerate(text.split(" ")):
    w, h = font.getStringSize(sentence + " " + word, scale = scale)
    if x + (w/2) > rightMargin or word == "\n":
      w, h = font.getStringSize(sentence, scale = scale)
      #x = startXpos
      glPushMatrix()
      glRotate(visibility * (n + 1) * -45, 0, 0, 1)
      if allowshadowoffset == True:
        font.render(sentence, (x - (w/2), y + visibility * n), scale = scale, shadowoffset = shadowoffset)
      else:
        font.render(sentence, (x - (w/2), y + visibility * n), scale = scale)
      glPopMatrix()
      sentence = word
      y += h * linespace
    else:
      if sentence == "" or sentence == "\n":
        sentence = word
      else:
        sentence = sentence + " " + word
  else:
    w, h = font.getStringSize(sentence, scale = scale)
    glPushMatrix()
    glRotate(visibility * (n + 1) * -45, 0, 0, 1)
    if allowshadowoffset == True:
      font.render(sentence, (x - (w/2), y + visibility * n), scale = scale, shadowoffset = shadowoffset)
    else:
      font.render(sentence, (x - (w/2), y + visibility * n), scale = scale)
    glPopMatrix()
    y += h * linespace
  
    #if word == "\n":
    #  continue
    #x += w + space
  return (x, y)

  #space = font.getStringSize(" ", scale = scale)[0]
  #startXpos = x - (rightMargin-x) #for a symmetrical text wrapping
  #x = startXpos
  #for n, word in enumerate(text.split(" ")):
  #  w, h = font.getStringSize(word, scale = scale)
  #  if x + w > rightMargin*1.11 or word == "\n":
  #    x = startXpos
  #    y += h*.5 # Worldrave - Modified spacing between lines
  #  if word == "\n":
  #    continue
  #  glPushMatrix()
  #  glRotate(visibility * (n + 1) * -45, 0, 0, 1)
  #  font.render(word, (x, y + visibility * n), scale = scale)
  #  glPopMatrix()
  #  x += w + space
  #return (x - space, y)


def wrapText(font, pos, text, rightMargin = 0.9, scale = 0.002, visibility = 0.0):
  """
  Wrap a piece of text inside given margins.
  
  @param pos:         (x, y) tuple, x defines the left margin
  @param text:        Text to wrap
  @param rightMargin: Right margin
  @param scale:       Text scale
  @param visibility:  Visibility factor [0..1], 0 is fully visible
  """
  x, y = pos
  w = h = 0
  space = font.getStringSize(" ", scale = scale)[0]

  # evilynux - No longer requires "\n" to be in between spaces
  for n, sentence in enumerate(text.split("\n")):
    y += h
    x = pos[0]
    if n == 0:
      y = pos[1]
    for n, word in enumerate(sentence.strip().split(" ")):
      w, h = font.getStringSize(word, scale = scale)
      if x + w > rightMargin:
        x = pos[0]
        y += h
      glPushMatrix()
      glRotate(visibility * (n + 1) * -45, 0, 0, 1)
      font.render(word, (x, y + visibility * n), scale = scale)
      glPopMatrix()
      x += w + space
  return (x - space, y)

def fadeScreen(v):
  """
  Fade the screen to a dark color to make whatever is on top easier to read.
  
  @param v: Visibility factor [0..1], 0 is fully visible
  """
  glEnable(GL_BLEND)
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
  glEnable(GL_COLOR_MATERIAL)

  glBegin(GL_TRIANGLE_STRIP)
  glColor4f(0, 0, 0, .3 - v * .3)
  glVertex2f(0, 0)
  glColor4f(0, 0, 0, .3 - v * .3)
  glVertex2f(1, 0)
  glColor4f(0, 0, 0, .9 - v * .9)
  glVertex2f(0, 1)
  glColor4f(0, 0, 0, .9 - v * .9)
  glVertex2f(1, 1)
  glEnd()
  

class GetText(Layer, KeyListener):
  """Text input layer."""
  def __init__(self, engine, prompt = "", text = ""):
    self.text = text
    self.prompt = prompt
    self.engine = engine
    self.time = 0
    self.accepted = False

    self.logClassInits = self.engine.config.get("game", "log_class_inits")
    if self.logClassInits == 1:
      Log.debug("GetText class init (Dialogs.py)...")
    
    self.sfxVolume    = self.engine.config.get("audio", "SFX_volume")

    self.drumHighScoreNav = self.engine.config.get("game", "drum_navigation")  #MFH
    
    
    
  def shown(self):
    self.engine.input.addKeyListener(self, priority = True)
    self.engine.input.enableKeyRepeat()
    
  def hidden(self):
    self.engine.input.removeKeyListener(self)
    self.engine.input.disableKeyRepeat()
    
  def keyPressed(self, key, unicode):
    self.time = 0
    c = self.engine.input.controls.getMapping(key)
    
    #if (c in Player.KEY1S or key == pygame.K_RETURN) and not self.accepted:
    #if (c in Player.KEY1S or key == pygame.K_RETURN or c in Player.DRUM4S) and not self.accepted:   #MFH - adding support for green drum "OK"
    if key == pygame.K_BACKSPACE and not self.accepted:
      self.text = self.text[:-1]
    elif unicode and ord(unicode) > 31 and not self.accepted:
      self.text += unicode
    elif key == pygame.K_LSHIFT or key == pygame.K_RSHIFT:
      return True
    elif (c in Player.menuYes or key == pygame.K_RETURN) and not self.accepted:   #MFH - adding support for green drum "OK"
      self.engine.view.popLayer(self)
      self.accepted = True
      if c in Player.key1s:
        self.engine.data.acceptSound.setVolume(self.sfxVolume)  #MFH
        self.engine.data.acceptSound.play()
    elif (c in Player.menuNo or key == pygame.K_ESCAPE) and not self.accepted:
      self.text = ""
      self.engine.view.popLayer(self)
      self.accepted = True
      if c in Player.key2s:
        self.engine.data.cancelSound.setVolume(self.sfxVolume)  #MFH
        self.engine.data.cancelSound.play()
    elif c in Player.key4s and not self.accepted:
      self.text = self.text[:-1]
      if c in Player.key4s:
        self.engine.data.cancelSound.setVolume(self.sfxVolume)  #MFH
        self.engine.data.cancelSound.play()
    elif c in Player.key3s and not self.accepted:
      self.text += self.text[len(self.text) - 1]
      self.engine.data.acceptSound.setVolume(self.sfxVolume)  #MFH
      self.engine.data.acceptSound.play()
    elif c in Player.action1s and not self.accepted:
      if len(self.text) == 0:
        self.text = "A"
        return True
      letter = self.text[len(self.text)-1]
      letterNum = ord(letter)
      if letterNum == ord('A'):
        letterNum = ord(' ')
      elif letterNum == ord(' '):
        letterNum = ord('_')
      elif letterNum == ord('_'):
        letterNum = ord('-')
      elif letterNum == ord('-'):
        letterNum = ord('9')
      elif letterNum == ord('0'):
        letterNum = ord('z')
      elif letterNum == ord('a'):
        letterNum = ord('Z')        
      else:
        letterNum -= 1
      self.text = self.text[:-1] + chr(letterNum)
      self.engine.data.selectSound.setVolume(self.sfxVolume)  #MFH
      self.engine.data.selectSound.play()
    elif c in Player.action2s and not self.accepted:
      if len(self.text) == 0:
        self.text = "A"
        return True
      letter = self.text[len(self.text)-1]
      letterNum = ord(letter)
      if letterNum == ord('Z'):
        letterNum = ord('a')
      elif letterNum == ord('z'):
        letterNum = ord('0')
      elif letterNum == ord('9'):
        letterNum = ord('-')
      elif letterNum == ord('-'):
        letterNum = ord('_')
      elif letterNum == ord('_'):
        letterNum = ord(' ')
      elif letterNum == ord(' '):
        letterNum = ord('A')
      else:
        letterNum += 1
      self.text = self.text[:-1] + chr(letterNum)
      self.engine.data.selectSound.setVolume(self.sfxVolume)  #MFH
      self.engine.data.selectSound.play()
    return True
    
  def run(self, ticks):
    self.time += ticks / 50.0
  
  def render(self, visibility, topMost):
    self.engine.view.setViewport(1,0)
    self.engine.view.setOrthogonalProjection(normalize = True)
    font = self.engine.data.font
    
    try:
      v = (1 - visibility) ** 2
      
      fadeScreen(v)
      Theme.setBaseColor(1 - v)

      if (self.time % 10) < 5 and visibility > .9:
        cursor = "|"
      else:
        cursor = ""

      pos = wrapText(font, (.1, .33 - v), self.prompt)

      Theme.setSelectedColor(1 - v)
      
      if self.text is not None:
        pos = wrapText(font, (.1, (pos[1] + v) + .08 + v / 4), self.text)
        font.render(cursor, pos)
      
    finally:
      self.engine.view.resetProjection()

class GetKey(Layer, KeyListener):
  """Key choosing layer."""
  def __init__(self, engine, prompt = "", key = None, noKey = False, specialKeyList = []):
    self.key = key
    self.prompt = prompt
    self.engine = engine
    self.time = 0
    self.accepted  = False
    self.noKey     = noKey
    self.toggleEsc = False
    self.escTimer  = 1000
    self.specialKeyList = specialKeyList

    self.logClassInits = self.engine.config.get("game", "log_class_inits")
    if self.logClassInits == 1:
      Log.debug("GetKey class init (Dialogs.py)...")
    
  def shown(self):
    self.engine.input.addKeyListener(self, priority = True)
    
  def hidden(self):
    self.engine.input.removeKeyListener(self)
    
  def keyPressed(self, key, unicode):
    if key == pygame.K_ESCAPE and not self.accepted:
      self.toggleEsc = True
    elif not self.accepted and key not in self.specialKeyList:
      self.key = key
      self.engine.view.popLayer(self)
      self.accepted = True
    return True
  
  def keyReleased(self, key):
    if key == pygame.K_ESCAPE and self.toggleEsc:
      if key in self.specialKeyList:
        self.escTimer = 1000
        self.toggleEsc = False
      else:
        self.key = key
        self.engine.view.popLayer(self)
        self.accepted = True
    
  def run(self, ticks):
    self.time += ticks / 50.0
    if self.toggleEsc:
      self.escTimer -= ticks
      if self.escTimer < 0:
        self.key = None
        self.engine.view.popLayer(self)
        self.accepted = True
  
  def render(self, visibility, topMost):
    self.engine.view.setViewport(1,0)
    self.engine.view.setOrthogonalProjection(normalize = True)
    font = self.engine.data.font
    
    try:
      v = (1 - visibility) ** 2
      
      fadeScreen(v)
      Theme.setBaseColor(1 - v)

      pos = wrapText(font, (.1, .33 - v), self.prompt)

      Theme.setSelectedColor(1 - v)

      if self.key is not None:
        text = pygame.key.name(self.key).capitalize()
        pos = wrapText(font, (.1, (pos[1] + v) + .08 + v / 4), text)
      
    finally:
      self.engine.view.resetProjection()

class LoadingScreen(Layer, KeyListener):
  """Loading screen layer."""
  def __init__(self, engine, condition, text, allowCancel = False):
    self.engine       = engine
    self.text         = text
    self.condition    = condition
    self.ready        = False
    self.allowCancel  = allowCancel
    self.time         = 0.0

    self.logClassInits = self.engine.config.get("game", "log_class_inits")
    if self.logClassInits == 1:
      Log.debug("LoadingScreen class init (Dialogs.py)...")

    self.loadingx = Theme.loadingX
    self.loadingy = Theme.loadingY
    self.allowtext = self.engine.config.get("game", "lphrases")    

    #Get theme
    themename = self.engine.data.themeLabel
    self.theme = self.engine.data.theme

  def shown(self):
    self.engine.input.addKeyListener(self, priority = True)

  def keyPressed(self, key, unicode):
    c = self.engine.input.controls.getMapping(key)
    if self.allowCancel and c in Player.menuNo:
      self.engine.view.popLayer(self)
    return True
    
  def hidden(self):
    self.engine.input.removeKeyListener(self)

  def run(self, ticks):
    self.time += ticks / 50.0
    if not self.ready and self.condition():
      self.engine.view.popLayer(self)
      self.ready = True
  
  def render(self, visibility, topMost):
    self.engine.view.setViewport(1,0)
    self.engine.view.setOrthogonalProjection(normalize = True)
    #font = self.engine.data.font
    font = self.engine.data.loadingFont

    if not font:
      return

    try:
      v = (1 - visibility) ** 2
      fadeScreen(v)

      w, h = self.engine.view.geometry[2:4]
      
      #MFH - auto-scaling of loading screen
      #Volshebnyi - fit to screen applied
      self.engine.drawImage(self.engine.data.loadingImage, scale = (1.0,-1.0), coord = (w/2,h/2), stretched = 3)

      Theme.setBaseColor(1 - v)
      w, h = font.getStringSize(self.text)

      if self.loadingx != None:
        if self.loadingy != None:
          x = self.loadingx - w / 2
          y = self.loadingy - h / 2 + v * .5
        else:
          x = self.loadingx - w / 2
          y = .6 - h / 2 + v * .5
      elif self.loadingy != None:
        x = .5 - w / 2
        y = .6 - h / 2 + v * .5
      else:
        x = .5 - w / 2
        y = .6 - h / 2 + v * .5

      if self.allowtext:
        if self.theme == 1:
          font.render(self.text, (x, y), shadowoffset = (Theme.shadowoffsetx, Theme.shadowoffsety))     
        else:
          font.render(self.text, (x, y))
    finally:
      self.engine.view.resetProjection()

class MessageScreen(Layer, KeyListener):
  """Message screen layer."""
  def __init__(self, engine, text, prompt = _("<OK>")):
    self.engine = engine
    self.text = text
    self.time = 0.0
    self.prompt = prompt

    self.logClassInits = self.engine.config.get("game", "log_class_inits")
    if self.logClassInits == 1:
      Log.debug("MessageScreen class init (Dialogs.py)...")
    

  def shown(self):
    self.engine.input.addKeyListener(self, priority = True)

  def keyPressed(self, key, unicode):
    c = self.engine.input.controls.getMapping(key)
    if c in (Player.menuYes + Player.menuNo) or key in [pygame.K_RETURN, pygame.K_ESCAPE, pygame.K_LCTRL, pygame.K_RCTRL]:
      self.engine.view.popLayer(self)
    return True
    
  def hidden(self):
    self.engine.input.removeKeyListener(self)

  def run(self, ticks):
    self.time += ticks / 50.0
  
  def render(self, visibility, topMost):
    self.engine.view.setViewport(1,0)
    self.engine.view.setOrthogonalProjection(normalize = True)
    font = self.engine.data.font

    if not font:
      return
    
    try:
      v = (1 - visibility) ** 2
      fadeScreen(v)

      x = .1
      y = .3 + v * 2
      Theme.setBaseColor(1 - v)
      pos = wrapText(font, (x, y), self.text, visibility = v)

      w, h = font.getStringSize(self.prompt, scale = 0.001)
      x = .5 - w / 2
      y = pos[1] + 3 * h + v * 2
      Theme.setSelectedColor(1 - v)
      font.render(self.prompt, (x, y), scale = 0.001)
      
    finally:
      self.engine.view.resetProjection()
      
class SongChooser(Layer, KeyListener):
  """Song choosing layer."""
  def __init__(self, engine, prompt = "", selectedSong = None, selectedLibrary = None):
    self.prompt         = prompt
    self.engine         = engine
    
    self.logClassInits = self.engine.config.get("game", "log_class_inits")
    if self.logClassInits == 1:
      Log.debug("SongChooser class init (Dialogs.py)...")

    #MFH - retrieve game parameters:
    self.gamePlayers = self.engine.config.get("game", "players")
    self.gameMode1p = self.engine.config.get("game","game_mode")
    self.gameMode2p = self.engine.config.get("game","multiplayer_mode")
    if self.gameMode1p == 2:
      self.careerMode = True
    else:
      self.careerMode = False
    
    self.drumNav = self.engine.config.get("game", "drum_navigation")  #MFH
    
    
    self.career_title_color = Theme.hexToColor(Theme.career_title_colorVar)
    self.song_name_text_color = Theme.hexToColor(Theme.song_name_text_colorVar)
    self.song_name_selected_color = Theme.hexToColor(Theme.song_name_selected_colorVar)
    self.artist_text_color = Theme.hexToColor(Theme.artist_text_colorVar)
    self.artist_selected_color = Theme.hexToColor(Theme.artist_selected_colorVar)
    self.library_text_color = Theme.hexToColor(Theme.library_text_colorVar)
    self.library_selected_color = Theme.hexToColor(Theme.library_selected_colorVar)
    self.songlist_score_color = Theme.hexToColor(Theme.songlist_score_colorVar)
    self.songlistcd_score_color = Theme.hexToColor(Theme.songlistcd_score_colorVar)
    
    self.song_rb2_name_color = Theme.hexToColor(Theme.song_rb2_name_colorVar)
    self.song_rb2_name_selected_color = Theme.hexToColor(Theme.song_rb2_name_selected_colorVar)
    self.song_rb2_diff_color = Theme.hexToColor(Theme.song_rb2_diff_colorVar)
    self.song_rb2_artist_color = Theme.hexToColor(Theme.song_rb2_artist_colorVar)

    self.scrolling = 0
    self.delay     = 0
    self.rate      = 0
    self.scroller  = [0, self.scrollUp, self.scrollDown]

    self.listRotation = self.engine.config.get("game", "songlistrotation")
    self.songCoverType = self.engine.config.get("game", "songcovertype")
    self.listingMode = engine.config.get("game","song_listing_mode")
    self.songIcons = engine.config.get("game", "song_icons")
    self.preLoadSongLabels = engine.config.get("game", "preload_labels")
    
    Log.debug("Songlist artist colors: " + str(self.artist_text_color) + " / " + str(self.artist_selected_color))

    self.NilShowNextScore = engine.config.get("songlist",  "nil_show_next_score")   #MFH



    #MFH
    try:
      self.song_cd_xpos = Theme.song_cd_Xpos
      Log.debug("song_cd_xpos found: " + str(self.song_cd_xpos))
    except Exception, e:
      Log.warn("Unable to load Theme song_cd_xpos: %s" % e) 
      self.song_cd_xpos = None

    try:
      self.song_cdscore_xpos = Theme.song_cdscore_Xpos
      Log.debug("song_cdscore_xpos found: " + str(self.song_cdscore_xpos))
    except Exception, e:
      Log.warn("Unable to load Theme song_cdscore_xpos: %s" % e) 
      self.song_cdscore_xpos = None

    try:
      self.song_list_xpos = Theme.song_list_Xpos
      Log.debug("song_list_xpos found: " + str(self.song_list_xpos))
    except Exception, e:
      Log.warn("Unable to load Theme song_list_xpos: %s" % e) 
      self.song_list_xpos = None

    try:
      self.song_listscore_xpos = Theme.song_listscore_Xpos
      Log.debug("song_listscore_xpos found: " + str(self.song_listscore_xpos))
    except Exception, e:
      Log.warn("Unable to load Theme song_listscore_xpos: %s" % e) 
      self.song_listscore_xpos = None

    try:
      self.song_listcd_cd_xpos = Theme.song_listcd_cd_Xpos
      Log.debug("song_listcd_cd_xpos found: " + str(self.song_listcd_cd_xpos))
    except Exception, e:
      Log.warn("Unable to load Theme song_listcd_cd_xpos: %s" % e) 
      self.song_listcd_cd_xpos = None

    try:
      self.song_listcd_cd_ypos = Theme.song_listcd_cd_Ypos
      Log.debug("song_listcd_cd_ypos found: " + str(self.song_listcd_cd_ypos))
    except Exception, e:
      Log.warn("Unable to load Theme song_listcd_cd_ypos: %s" % e) 
      self.song_listcd_cd_ypos = None

    try:
      self.song_listcd_score_xpos = Theme.song_listcd_score_Xpos
      Log.debug("song_listcd_score_xpos found: " + str(self.song_listcd_score_xpos))
    except Exception, e:
      Log.warn("Unable to load Theme song_listcd_score_xpos: %s" % e) 
      self.song_listcd_score_xpos = None

    try:
      self.song_listcd_score_ypos = Theme.song_listcd_score_Ypos
      Log.debug("song_listcd_score_ypos found: " + str(self.song_listcd_score_ypos))
    except Exception, e:
      Log.warn("Unable to load Theme song_listcd_score_ypos: %s" % e) 
      self.song_listcd_score_ypos = None

    try:
      self.song_listcd_list_xpos = Theme.song_listcd_list_Xpos
      Log.debug("song_listcd_list_xpos found: " + str(self.song_listcd_list_xpos))
    except Exception, e:
      Log.warn("Unable to load Theme song_listcd_list_xpos: %s" % e) 
      self.song_listcd_list_xpos = None


    #pre-determine these values and just replace them with these variables in the render function:

    #Blazingamer CD X position fix
    if self.song_cd_xpos == None:
      self.song_cd_xpos = 0.0
    elif self.song_cd_xpos > 5:
      self.song_cd_xpos = 5.0
    elif self.song_cd_xpos < 0:
      self.song_cd_xpos = 0.0


    if self.song_cdscore_xpos == None:
      self.song_cdscore_xpos = 0.6

    if self.song_list_xpos == None:
      self.song_list_xpos = 0.15

    if self.song_listscore_xpos == None:
      self.song_listscore_xpos = 0.8
      
    #Qstick - List/CD mode element positions
    if self.song_listcd_cd_xpos == None:
      self.song_listcd_cd_xpos = .75
  
    if self.song_listcd_cd_ypos == None:
      self.song_listcd_cd_ypos = .6
      
    if self.song_listcd_score_xpos == None:
      self.song_listcd_score_xpos = 0.6

    if self.song_listcd_score_ypos == None:
      self.song_listcd_score_ypos = 0.5
      
    if self.song_listcd_list_xpos == None:
      self.song_listcd_list_xpos = .1
    

    
    self.time           = 0
    self.lastTime       = 0
    self.accepted       = False
    self.selectedIndex  = 0
    self.camera         = Camera()
    self.cassetteHeight = .8
    self.cassetteWidth  = 4.0
    self.libraryHeight  = 1.2
    self.libraryWidth   = 4.0

    self.titleHeight    = 2.4
    self.titleWidth     = 4.0

    self.itemAngles     = None
    self.itemLabels     = None
    self.selectedOffset = 0.0
    self.cameraOffset   = 0.0
    self.selectedItem   = None
    self.song           = None
    self.songCountdown  = 1024
    self.songLoader     = None
    self.initialItem    = selectedSong
    self.library        = os.path.join(self.engine.config.get("game", "base_library"), selectedLibrary)
    self.searchText     = ""
    self.searching      = False
    
    self.halfTime = 0

    #RF-mod
    self.previewDisabled  = self.engine.config.get("audio", "disable_preview")
    self.sortOrder        = self.engine.config.get("game", "sort_order")
    self.rotationDisabled = self.engine.config.get("performance", "disable_librotation")
    self.spinnyDisabled   = self.engine.config.get("game", "disable_spinny")

    self.sortorder = engine.config.get("game", "sort_order")
    self.sortdirection = engine.config.get("game", "sort_direction")

    self.sfxVolume    = self.engine.config.get("audio", "SFX_volume")
    self.engine.data.selectSound.setVolume(self.sfxVolume)

    #Get Theme
    themename = self.engine.data.themeLabel
    self.theme = self.engine.data.theme

    
    self.display = self.engine.config.get("coffee", "song_display_mode")
    if self.display == 4:
      if Theme.songListDisplay != None:
        self.display = Theme.songListDisplay
      else:
        self.display = 1

    self.tut = self.engine.config.get("game", "tut")

    self.songback = Theme.songback
    self.filepathenable = self.engine.config.get("coffee", "songfilepath")

    temp = self.engine.config.get("game", "search_key")
    
    if temp != "None":
      self.searchKey = ord(temp[0])
    else:
      self.searchKey = ord('/')
    
    # Use the default library if this one doesn't exist
    if not self.library or not os.path.isdir(self.engine.resource.fileName(self.library)):
      self.library = Song.DEFAULT_LIBRARY
    if self.tut == True:
      self.library = self.engine.tutorialFolder

    self.loadCollection()


    #MFH configurable default instrument display with 5th / orange fret
    #   need to keep track of the instrument number and instrument name
    self.instrument = Song.parts[self.engine.config.get("game", "songlist_instrument")]

    if self.display == 0:
      self.engine.resource.load(self, "cassette",     lambda: Mesh(self.engine.resource.fileName("cassette.dae")), synch = True)
      self.engine.resource.load(self, "label",        lambda: Mesh(self.engine.resource.fileName("label.dae")), synch = True)
      self.engine.resource.load(self, "libraryMesh",  lambda: Mesh(self.engine.resource.fileName("library.dae")), synch = True)
      self.engine.resource.load(self, "libraryLabel", lambda: Mesh(self.engine.resource.fileName("library_label.dae")), synch = True)
      self.engine.loadImgDrawing(self, "background",  os.path.join("themes",themename,"menu","songchoosepaper.png"))
    elif self.display == 1:

      try:
        self.engine.loadImgDrawing(self, "background",  os.path.join("themes",themename,"menu","songchooseback.png"))
      except IOError:
        self.background = None
      self.engine.loadImgDrawing(self, "paper",       os.path.join("themes",themename,"menu","songchoosepaper.png"))
      self.engine.loadImgDrawing(self, "selected",    os.path.join("themes",themename,"menu","selected.png"))
      self.scoreTimer = 0

      # evilynux - configurable default highscores difficulty display
      self.diff = Song.difficulties[self.engine.config.get("game", "songlist_difficulty")]
    elif self.display == 2:
      self.engine.resource.load(self, "cassette",     lambda: Mesh(self.engine.resource.fileName("cassette.dae")), synch = True)
      self.engine.resource.load(self, "label",        lambda: Mesh(self.engine.resource.fileName("label.dae")), synch = True)
      self.engine.resource.load(self, "libraryMesh",  lambda: Mesh(self.engine.resource.fileName("library.dae")), synch = True)
      self.engine.resource.load(self, "libraryLabel", lambda: Mesh(self.engine.resource.fileName("library_label.dae")), synch = True)
      try:
        self.engine.loadImgDrawing(self, "background",       os.path.join("themes",themename,"menu","songchooselistcd.png"))
      except IOError:
        self.engine.loadImgDrawing(self, "background",       os.path.join("themes",themename,"menu","songchoosepaper.png"))
      try:
        self.engine.loadImgDrawing(self, "selectedlistcd",    os.path.join("themes",themename,"menu","selectedlistcd.png"))
      except IOError:
        self.engine.loadImgDrawing(self, "selected",    os.path.join("themes",themename,"menu","selected.png"))
        self.selectedlistcd = None
    elif self.display == 3:
      try:
        self.engine.loadImgDrawing(self, "background",  os.path.join("themes",themename,"menu","songchooserb2.png"))
      except IOError:
        self.background = None
        self.engine.loadImgDrawing(self, "background",       os.path.join("themes",themename,"menu","songchoosepaper.png"))
      try:
        self.engine.loadImgDrawing(self, "selected",    os.path.join("themes",themename,"menu","selectedrb2.png"))
      except IOError:
        self.engine.loadImgDrawing(self, "selected",    os.path.join("themes",themename,"menu","selected.png"))
      try:
        self.engine.loadImgDrawing(self, "tierbg",    os.path.join("themes",themename,"menu","tier.png"))
      except IOError:
        self.tierbg = None
      try:
        self.engine.loadImgDrawing(self, "emptyLabel",    os.path.join("themes",themename,"menu","emptylabel.png"))
      except IOError:
        self.emptyLabel = None
      try:
        self.engine.loadImgDrawing(self, "lockedLabel",    os.path.join("themes",themename,"menu","lockedlabel.png"))
      except IOError:
        self.lockedLabel = self.emptyLabel
      try:
        self.engine.loadImgDrawing(self, "diffimg1",    os.path.join("themes",themename,"menu","diff1.png"))
        self.engine.loadImgDrawing(self, "diffimg2",    os.path.join("themes",themename,"menu","diff2.png"))
        self.engine.loadImgDrawing(self, "diffimg3",    os.path.join("themes",themename,"menu","diff3.png"))
      except IOError:
        self.diffimg1 = self.engine.data.star3
        self.diffimg2 = self.engine.data.star4
        self.diffimg3 = self.engine.data.starPerfect
        
      #song icon loading
      if self.songIcons:
        self.itemIcons = []
        self.itemIconNames = []
        iconFolder = engine.resource.fileName(os.path.join("themes",themename,"menu","icon"))
        if os.path.exists(iconFolder):
          for filename in os.listdir(iconFolder):
            if os.path.splitext(filename)[1].lower() == ".png":
              
              thisfile = self.engine.resource.fileName("themes",themename,"menu","icon",filename)
              if os.path.exists(thisfile):
                self.itemIcons.append(ImgDrawing(self.engine.data.svg, thisfile))
                self.itemIconNames.append(os.path.splitext(filename)[0])
             
  
        
      self.scoreTimer = 0

      # evilynux - configurable default highscores difficulty display
      self.diff = Song.difficulties[self.engine.config.get("game", "songlist_difficulty")]
        
      #if self.rotationDisabled:
      #  item = self.items[self.selectedIndex]
      #  Log.debug(os.path.join(self.library, item.songName,    "label.png"))
      #  try:
      #    if isinstance(item, Song.SongInfo):
      #      
      #      self.engine.loadImgDrawing(self, "currentlabel", os.path.join(self.library, item.songName,    "label.png"))
      #    elif isinstance(item, Song.LibraryInfo):
      #      self.engine.loadImgDrawing(self, "currentlabel", os.path.join(item.libraryName,    "label.png"))
      #    else:
      #      self.currentlabel = None
      #  except IOError:
      #    self.currentlabel = None


      
    # evilynux - Shall we show hit% and note streak?
    self.extraStats = self.engine.config.get("game", "songlist_extra_stats")
    #myfingershurt: adding yellow fret preview again
    self.playSong = False

#worldrave - Use setlistguidebuttons image if it exists.
    try:
      self.engine.loadImgDrawing(self, "setlistguidebuttons", os.path.join("themes",themename,"menu","setlistguidebuttons.png"))
    except IOError:
      self.setlistguidebuttons = None

#racer: preview graphic
    try:
      self.engine.loadImgDrawing(self, "preview",  os.path.join("themes",themename,"menu","preview.png"))
    except IOError:
      self.preview = None

#racer: highscores are changed by fret
    self.highScoreChange = False
    self.highScoreType = self.engine.config.get("game", "HSMovement")

    self.instrumentChange = False   #MFH

  def loadCollection(self):
    Log.debug("Dialogs.loadCollection() function call...")
    self.loaded = False
    #showLoadingScreen(self.engine, lambda: self.loaded, text = _("Browsing Collection..."))
    self.splash = showLoadingSplashScreen(self.engine, _("Browsing Collection..."))
    self.loadStartTime = time.time()
    
    # evilynux - Has to be synchronous so we don't return with an empty library list!
    self.engine.resource.load(self, "libraries", lambda: Song.getAvailableLibraries(self.engine, self.library), onLoad = self.libraryListLoaded, synch = True)

    #showLoadingScreen(self.engine, lambda: self.loaded, text = _("Browsing Collection..."))

    

  def libraryListLoaded(self, libraries):
    Log.debug("Dialogs.libraryListLoaded() function call...")
    #self.engine.resource.load(self, "songs",     lambda: Song.getAvailableSongs(self.engine, self.library), onLoad = self.songListLoaded)
    self.engine.resource.load(self, "songs",     lambda: Song.getAvailableSongsAndTitles(self.engine, self.library, progressCallback=self.progressCallback), onLoad = self.songListLoaded, synch = True) # evilynux - Less BlackSOD[?]

  def progressCallback(self, percent):
    if time.time() - self.loadStartTime > 7:
      changeLoadingSplashScreenText(self.engine, self.splash, _("Browsing Collection...") + ' (%d%%)' % (percent*100))

  def isInt(self, possibleInt):
    try:
      #MFH - remove any leading zeros (for songs with 01. or 02. for example)        
      splitName = possibleInt.split("0",1)
      while splitName[0] == "":
        splitName = possibleInt.split("0",1)
        if len(splitName) > 1:
          if splitName[0] == "":
            possibleInt = splitName[1]
      if str(int(possibleInt)) == str(possibleInt):
        #Log.debug("Dialogs.isInt: " + str(possibleInt) + " = TRUE")
        return True
      else:
        #Log.debug("Dialogs.isInt: " + str(possibleInt) + " = FALSE")
        return False
    except Exception, e:
      return False
      #Log.debug("Dialogs.isInt: " + str(possibleInt) + " = FALSE, exception: " + str(e) )
      
  def removeSongOrderPrefixFromItem(self, item):
    if not item.name.startswith("."):
      splitName = item.name.split(".",1)
      #Log.debug("Dialogs.songListLoaded: Separating song name from prefix: " + str(splitName) )
      if self.isInt(splitName[0]) and len(splitName) > 1:
        item.name = splitName[1]
        #while len(splitName) > 1: #now remove any remaining leading spaces
        splitName[0] = ""
        while splitName[0] == "":
          splitName = item.name.split(" ",1)
          if len(splitName) > 1:
            if splitName[0] == "":
              item.name = splitName[1]
              #Log.debug("Dialogs.songListLoaded: Removing song name prefix, new name = " + splitName[1])
    else:
      Log.debug("Song name starting with a period filtered from prefix removal logic: " + item.name)



  def songListLoaded(self, songs):
    if self.songLoader:
      self.songLoader.cancel() # evilynux - cancel() became stop() - akedrou: when?
    self.selectedIndex = 0
    if self.display != 4:
      #MFH: Here, scan self.songs for a SongInfo followed by a TitleInfo.  Insert a BlankSpaceInfo object in between them. (one will already be in front of a CareerResetterInfo)
      addingBlankSpaces = True
      foundEndOfCareerYet = False
      while addingBlankSpaces:
        lastObjectWasASong = False
        for i, item in enumerate(self.songs):
          if isinstance(item, Song.SongInfo):
            lastObjectWasASong = True
          elif isinstance(item, Song.TitleInfo):
            if lastObjectWasASong:
              self.songs.insert(i, Song.BlankSpaceInfo())
              Log.debug("Dialogs.py: Inserted blank space in self.songs list before " + item.getName())
              break   #now that the self.songs list has changed, we must re-enumerate and look for the next place to insert a space
            lastObjectWasASong = False
          elif isinstance(item, Song.BlankSpaceInfo):
            if item.name == _("End of Career") and not foundEndOfCareerYet:   #also want to insert a blank space after the end of career marker
              self.songs.insert(i, Song.BlankSpaceInfo())   #insert a blank space before End of Career
              self.songs.insert(i+2, Song.BlankSpaceInfo())   #...and after End of Career (which is now shifted up one index)
              foundEndOfCareerYet = True
              Log.debug("Dialogs.py: Inserted blank space in self.songs list after " + item.getName())
              break   #now that the self.songs list has changed, we must re-enumerate and look for the next place to insert a space
            lastObjectWasASong = False
          else:
            lastObjectWasASong = False
        else:   #executed after the for loop finishes
          addingBlankSpaces = False   #finished adding blank spaces, exit while loop
          Log.debug("Dialogs.py: Finished inserting blank spaces in self.songs.")
  
      #MFH: Second scan through songlist items to remove any resulting double blank spaces
      removingBlankSpaces = True
      foundEndOfCareerYet = False
      while removingBlankSpaces:
        lastObjectWasASpace = False
        for i, item in enumerate(self.songs):
          if isinstance(item, Song.BlankSpaceInfo) and item.name == "":
            if lastObjectWasASpace:
              #self.songs.remove(i)
              del self.songs[i]
              break
            
            lastObjectWasASpace = True
          else:
            lastObjectWasASpace = False
        else:   #executed after the for loop finishes
          removingBlankSpaces = False   #finished adding blank spaces, exit while loop
          Log.debug("Dialogs.py: Finished filtering doubled blank spaces in self.songs.")

    if self.listingMode == 0 or self.careerMode:
      self.items         = self.libraries + self.songs
    else:
      self.items         = self.songs

    if self.items == []:    #MFH: Catch when there ain't a damn thing in the current folder - back out!
      if self.library != Song.DEFAULT_LIBRARY:
        hideLoadingSplashScreen(self.engine, self.splash)
        self.splash = None
        self.initialItem = self.library
        self.library     = os.path.dirname(self.library)
        self.selectedItem = None
        self.loadCollection()
        return


    #Log.debug("Dialogs.songListLoaded: self.items = " + str(self.items))
    Log.debug("Dialogs.songListLoaded.")

    self.itemAngles    = [0.0] * len(self.items)
    self.itemLabels    = [None] * len(self.items)
    self.loaded        = True
    self.searchText    = ""
    self.searching     = False
    
    if self.display != 1:
      if self.preLoadSongLabels:
        for i in range(0,len(self.items)):
          self.loadItemLabel(i)
    
    if self.initialItem is not None:
      for i, item in enumerate(self.items):
        if isinstance(item, Song.SongInfo) and self.initialItem == item.songName:
          self.selectedIndex =  i
          break
        elif isinstance(item, Song.LibraryInfo) and self.initialItem == item.libraryName:
          self.selectedIndex =  i
          break

    #MFH
    self.tiersArePresent = False
    self.indentString = "   "

    #MFH: filter out song name prefixes "1." "2." etc 
    #   but -- also must NOT get stuck here on ellipsises (such as RBDLC - Metallica - ...And Justice For All)
    for i, item in enumerate(self.items):
      if isinstance(item, Song.SongInfo):


        self.removeSongOrderPrefixFromItem(item)
#-        if not item.name.startswith("."):
#-          splitName = item.name.split(".",1)
#-          #Log.debug("Dialogs.songListLoaded: Separating song name from prefix: " + str(splitName) )
#-          if self.isInt(splitName[0]) and len(splitName) > 1:
#-            item.name = splitName[1]
#-            #while len(splitName) > 1: #now remove any remaining leading spaces
#-            splitName[0] = ""
#-            while splitName[0] == "":
#-              splitName = item.name.split(" ",1)
#-              if len(splitName) > 1:
#-                if splitName[0] == "":
#-                  item.name = splitName[1]
#-                  #Log.debug("Dialogs.songListLoaded: Removing song name prefix, new name = " + splitName[1])
#-        else:
#-          Log.debug("Song name starting with a period filtered from prefix removal logic: " + item.name)

      elif isinstance(item, Song.TitleInfo) or isinstance(item, Song.SortTitleInfo):
        self.tiersArePresent = True 

    # if the first item is a title, start on the second one
    #FIXME: potential infinite loop if there are only titles
    
    #else:
    #if self.items != []:
      while isinstance(self.items[self.selectedIndex], Song.TitleInfo):
        self.selectedIndex = (self.selectedIndex + 1) % len(self.items)
    # Load labels for libraries right away
    #if self.items != []:
      self.updateSelection()

    hideLoadingSplashScreen(self.engine, self.splash)
    self.splash = None

    
  def shown(self):
    self.engine.input.addKeyListener(self) #, priority = True
    
  def hidden(self):
    if self.songLoader:
      self.songLoader.cancel() # evilynux - cancel() became stop() - akedrou: when?
    if self.song:
      self.song.fadeout(1000)
      self.song = None
    self.engine.input.removeKeyListener(self)

      
  def getSelectedSong(self):
    if isinstance(self.selectedItem, Song.SongInfo):
      return self.selectedItem.songName

  def getSelectedItem(self):
    return self.selectedItem


  def getSelectedLibrary(self):
    return self.library

  def getItems(self):
    return self.items
  
  def loadItemLabel(self, i):
    # Load the item label if it isn't yet loaded
    themename = self.engine.data.themeLabel
    item = self.items[i]
    if self.itemLabels[i] is None:
      if isinstance(item, Song.SongInfo):
        if (item.getLocked()):
          self.itemLabels[i] = "Locked"
          return
        elif self.songCoverType:
          label = self.engine.resource.fileName(item.libraryNam, item.songName,    "label.png")
        else:
          label = self.engine.resource.fileName(item.libraryNam, item.songName,    "album.png")

      elif isinstance(item, Song.LibraryInfo):
        label = self.engine.resource.fileName(item.libraryName, "label.png")
      elif isinstance(item, Song.CareerResetterInfo):
        label = self.engine.resource.fileName("themes",themename,"menu","resetlabel.png")
      elif isinstance(item, Song.RandomSongInfo):
        label = self.engine.resource.fileName("themes",themename,"menu","random.png")
      else:
        return
      if os.path.exists(label):
        #MFH - load as 2D drawing and not a texture when in CD/List mode:
        if self.display == 2 and not self.listRotation:
          #self.engine.loadImgDrawing(self, "itemLabels[i]",  label)
          self.itemLabels[i] = ImgDrawing(self.engine.data.svg, label)
        elif self.display == 3:
          self.itemLabels[i] = ImgDrawing(self.engine.data.svg, label)
        else:
          self.itemLabels[i] = Texture(label)
      else:
        if self.display == 3:
          self.itemLabels[i] = "Empty"

  def updateSelection(self):
  
    self.selectedItem  = self.items[self.selectedIndex]
    self.songCountdown = 1024

    #myfingershurt: only if CD list
    if self.display != 1:
      if self.selectedIndex > 1:
        self.loadItemLabel(self.selectedIndex - 1)
      self.loadItemLabel(self.selectedIndex)
      if self.selectedIndex < len(self.items) - 1:
        self.loadItemLabel(self.selectedIndex + 1)
    
  def keyPressed(self, key, unicode): #racer: drum nav.
    if not self.items or self.accepted:
      return

    self.lastTime = self.time
    c = self.engine.input.controls.getMapping(key)
    if self.searching == True and unicode and ord(unicode) > 31 and not self.accepted:
      self.searchText += unicode
      self.doSearch()
    elif self.searching == False and ((key >= ord('a') and key <= ord('z')) or (key >= ord('A') and key <= ord('Z')) or (key >= ord('0') and key <= ord('9'))):
      k1 = unicode
      k2 = k1.capitalize()
      found = 0
      
      for i in range(len(self.items)):
        if self.sortOrder == 1:
          if not self.items[i].artist:
            continue
          if self.items[i].artist[0] == k1 or self.items[i].artist[0] == k2:
            found = 1
            break
        else:
          if not self.items[i].name:
            continue
          if self.items[i].name[0] == k1 or self.items[i].name[0] == k2:
            found = 1
            break
      if found == 1 and self.selectedIndex != i:
        self.selectedIndex = i
        self.updateSelection() 
    elif (c in Player.menuYes and not c in Player.starts) or key == pygame.K_RETURN:
      self.scrolling = 0
      if self.matchesSearch(self.selectedItem):
        # evilynux - "song" might be in the process of being created by a song preview,
        #            stopping the songLoader is safer.
        if self.songLoader:
          self.songLoader.cancel()
        #if not self.song: #MFH - play the sound immediately, THEN process.
        self.engine.data.acceptSound.setVolume(self.sfxVolume)  #MFH
        self.engine.data.acceptSound.play()
        if isinstance(self.selectedItem, Song.LibraryInfo):
          self.library = self.selectedItem.libraryName
          self.initialItem = None
          Log.debug("New library selected: " + str(self.library) )
          self.loadCollection()
        elif isinstance(self.selectedItem, Song.SongInfo) and not self.selectedItem.getLocked():
        #else:
          
          if self.listingMode == 1 and self.careerMode == False:
            self.library = self.selectedItem.libraryNam
          #blazingamer - stops preview from playing outside of songchooser
          self.hidden()
          self.engine.view.popLayer(self)
          self.accepted = True

        elif isinstance(self.selectedItem, Song.RandomSongInfo):
          while 1:
            self.selectedItem = self.items[random.randint(0,len(self.items)-1)]
            if isinstance(self.selectedItem, Song.SongInfo) and not self.selectedItem.getLocked():
              break
          
          if self.listingMode == 1 and self.careerMode == False:
            self.library = self.selectedItem.libraryNam

          #blazingamer - stops preview from playing outside of songchooser
          self.hidden()       
          self.engine.view.popLayer(self)
          self.accepted = True
        elif isinstance(self.selectedItem, Song.CareerResetterInfo):  #MFH - here's where to actually reset careers
          self.engine.view.popLayer(self)
          while 1:
            isYouSure = chooseItem(self.engine, [_("No"),_("Yes")], _("Are you sure you want to reset this entire career?") )
            if isYouSure:
              if isYouSure == _("Yes"):
                splash = showLoadingSplashScreen(self.engine, _("Resetting career..."))
                for i, item in enumerate(self.items):
                  if isinstance(item, Song.SongInfo) and item.completed:
                    item.completed = False
                    item.save()
                self.loadCollection()
                hideLoadingSplashScreen(self.engine, splash)
                splash = None
              break
            else:
              break  
          self.engine.view.pushLayer(self)
          
    elif c in Player.kills and self.engine.config.get("game", "whammy_changes_sort_order"):
        orderings = self.engine.config.getOptions("game", "sort_order")[1]
        self.sortOrder += 1
        #if self.sortOrder > len(orderings):
        if self.sortOrder >= len(orderings):  #MFH - must not allow this to go over the max!
          self.sortOrder = 0
        self.engine.config.set("game", "sort_order", self.sortOrder)
        if self.songLoader:
          self.songLoader.cancel()
        if self.song:
          self.song.fadeout(1000)
        self.selectedItem = None
        self.loadCollection()

        
    elif c in Player.menuNo:
      # evilynux - "song" might be in the process of being created,
      #            stopping the songLoader is safer.
      if self.songLoader:
        self.songLoader.cancel()
      #if not self.song:
      self.engine.data.cancelSound.setVolume(self.sfxVolume)  #MFH
      self.engine.data.cancelSound.play()
      if self.library != Song.DEFAULT_LIBRARY and self.tut == False and (self.listingMode == 0 or self.careerMode):
        self.initialItem = self.library
        self.library     = os.path.dirname(self.library)
        if self.song:
          self.song.fadeout(1000)
        self.selectedItem = None
        self.loadCollection()
        #blazingamer - stops preview from playing outside of songchooser
        self.song = None
        self.songLoader = None
        if self.library == os.path.join("..", self.engine.config.get("game", "base_library")):
          self.selectedItem = None
          #blazingamer - stops preview from playing outside of songchooser
          self.hidden()
          self.engine.view.popLayer(self)
          self.accepted = True
      else:
        self.selectedItem = None
        #blazingamer - stops preview from playing outside of songchooser
        self.hidden()
        self.engine.view.popLayer(self)
        self.accepted = True


    # left + right to quickly skip to the item after the next title
    elif c in Player.lefts or key == pygame.K_LEFT:
      #if self.tiersArePresent or self.careerMode: # if there are no titles, we'll have an infinite loop = bad
      if self.tiersArePresent: # if there are no titles, we'll have an infinite loop = bad
        self.selectedIndex = (self.selectedIndex - 1) % len(self.items)   #MFH - nudge it up one count.
        if isinstance(self.items[self.selectedIndex], Song.TitleInfo) or isinstance(self.items[self.selectedIndex], Song.SortTitleInfo):  #MFH - if we just found a title, we need to go once more to ensure we're goin back a title:
          self.selectedIndex = (self.selectedIndex - 1) % len(self.items)
        while not ( isinstance(self.items[self.selectedIndex], Song.TitleInfo) or isinstance(self.items[self.selectedIndex], Song.CareerResetterInfo) or isinstance(self.items[self.selectedIndex], Song.SortTitleInfo) ):
          self.selectedIndex = (self.selectedIndex - 1) % len(self.items)
        while 1:
          if isinstance(self.items[self.selectedIndex], Song.CareerResetterInfo):
            break
          self.selectedIndex = (self.selectedIndex + 1) % len(self.items)
          if self.matchesSearch(self.items[self.selectedIndex]) and not isinstance(self.items[self.selectedIndex], Song.TitleInfo) and not isinstance(self.items[self.selectedIndex], Song.SortTitleInfo):
            break
        self.updateSelection()
    
    elif c in Player.rights or key == pygame.K_RIGHT:
      #if self.tiersArePresent or self.careerMode: # if there are no titles, we'll have an infinite loop = bad
      if self.tiersArePresent: # if there are no titles, we'll have an infinite loop = bad
        self.selectedIndex = (self.selectedIndex + 1) % len(self.items) #MFH - nudge it down one count to get things started.
        while not ( isinstance(self.items[self.selectedIndex], Song.TitleInfo) or isinstance(self.items[self.selectedIndex], Song.CareerResetterInfo) or isinstance(self.items[self.selectedIndex], Song.SortTitleInfo) ):
          self.selectedIndex = (self.selectedIndex + 1) % len(self.items)
        while 1:
          if isinstance(self.items[self.selectedIndex], Song.CareerResetterInfo):
            break
          self.selectedIndex = (self.selectedIndex + 1) % len(self.items)
          if self.matchesSearch(self.items[self.selectedIndex]) and not isinstance(self.items[self.selectedIndex], Song.TitleInfo) and not isinstance(self.items[self.selectedIndex], Song.SortTitleInfo):
            break
        self.updateSelection()
    

        
    #myfingershurt: adding yellow fret preview again
    elif c in Player.key3s or key == pygame.K_F3:
      self.playSong = True

    #racer: highscores change on fret hit
    elif c in Player.key4s:
      self.highScoreChange = True

    #MFH - instrument change on 5th fret
    #elif c in Player.KEY5S or (c in Player.DRUM3S and self.drumNav):
    elif c in Player.key5s:   #MFH can't use drum3, that's for down
      self.instrumentChange = True


    elif c in Player.menuUp or key == pygame.K_UP:
      self.scrolling = 1
      self.delay = self.engine.scrollDelay
      self.scrollUp()
    elif c in Player.menuDown or key == pygame.K_DOWN:
      self.scrolling = 2
      self.delay = self.engine.scrollDelay
      self.scrollDown()
    elif key == pygame.K_BACKSPACE and not self.accepted:
      self.searchText = self.searchText[:-1]
      if self.searchText == "":
        self.searching = False
    elif key == self.searchKey:
      if self.searching == False:
        self.searching = True
      else:
        self.searching == False
    return True
  
  def keyReleased(self, key):
    self.scrolling = 0
    if not self.items or self.accepted:
      return
    return True
  
  def scrollUp(self):
    self.engine.data.selectSound.play()
    if self.matchesSearch(self.items[self.selectedIndex]):
      while 1:
        #self.selectedIndex = (self.selectedIndex - 1) % len(self.items)
        # evilynux - Skip blank lines and Tier names
        currentIndex = self.selectedIndex
        while 1:
          currentIndex = (currentIndex - 1) % len(self.items)
          if isinstance(self.items[currentIndex], Song.SongInfo) or \
              isinstance(self.items[currentIndex], Song.CareerResetterInfo) or \
              isinstance(self.items[currentIndex], Song.LibraryInfo) or \
              isinstance(self.items[currentIndex], Song.RandomSongInfo) or \
              (self.display == 0 and isinstance(self.items[currentIndex], Song.TitleInfo)):
            break
        self.selectedIndex = currentIndex
        if self.matchesSearch(self.items[self.selectedIndex]):
        #if self.matchesSearch(self.items[self.selectedIndex]) and not isinstance(self.items[self.selectedIndex], Song.TitleInfo):
          break
    self.updateSelection()
  
  def scrollDown(self):
    self.engine.data.selectSound.play()
    if self.matchesSearch(self.items[self.selectedIndex]):
      while 1:
        #self.selectedIndex = (self.selectedIndex + 1) % len(self.items)
        # evilynux - Skip blank lines and Tier names
        currentIndex = self.selectedIndex
        while 1:
          currentIndex = (currentIndex + 1) % len(self.items)
          if isinstance(self.items[currentIndex], Song.SongInfo) or \
              isinstance(self.items[currentIndex], Song.CareerResetterInfo) or \
             isinstance(self.items[currentIndex], Song.LibraryInfo) or \
             isinstance(self.items[currentIndex], Song.RandomSongInfo) or \
             (self.display == 0 and isinstance(self.items[currentIndex], Song.TitleInfo)):
            break
        self.selectedIndex = currentIndex
      
        if self.matchesSearch(self.items[self.selectedIndex]):
        #if self.matchesSearch(self.items[self.selectedIndex]) and not isinstance(self.items[self.selectedIndex], Song.TitleInfo):
          break
    self.updateSelection()

  def matchesSearch(self, item):
    if not self.searchText:
      return True
    if isinstance(item, Song.SongInfo):
      if self.searchText.lower() in item.name.lower() or self.searchText.lower() in item.artist.lower():
        return True
    elif isinstance(item, Song.LibraryInfo):
      if self.searchText.lower() in item.name.lower():
        return True
    return False

  def doSearch(self):
    if not self.searchText:
      return
      
    for i, item in enumerate(self.items):
      if self.matchesSearch(item):
          self.selectedIndex =  i
          self.updateSelection()
          break

  def songLoaded(self, song):
    self.songLoader = None

    if self.song:
      self.song.stop()
    
    song.crowdVolume = 0
    song.activeAudioTracks = [Song.GUITAR_TRACK, Song.RHYTHM_TRACK, Song.DRUM_TRACK]
    song.setAllTrackVolumes(1)
    song.play()
    self.song = song
  
  def songCanceled(self):
    self.songLoader = None
    if self.song:
      self.song.stop()
    self.song = None

  def playSelectedSong(self):
    song = self.getSelectedSong()
    if not song:
      return
    
    songItem = self.getSelectedItem()
    
    #MFH - check for career mode, and song's unlocked status before playing
    #Need to check if song is locked; not completed (then current songs can be previewable)
    if self.careerMode and songItem.getLocked():
      if self.song:
        self.song.fadeout(1000)
      return
    
    # evilynux - Stop already playing song if any
    if self.songLoader:
      try:
        self.songLoader.cancel()
      except:
        self.songLoader = None

    self.songLoader = self.engine.resource.load(self, None, lambda: Song.loadSong(self.engine, song, playbackOnly = True, library = self.library), synch = False, onLoad = self.songLoaded, onCancel = self.songCanceled) #Blazingamer - asynchronous preview loading allows "Loading Preview..." to correctly disappear.

  def run(self, ticks):
    self.time += ticks / 50.0


    if self.previewDisabled:
      #myfingershurt: adding yellow fret preview again, and making it compatible with the auto-preview setting
      if self.playSong == True:
        self.playSelectedSong()
        self.playSong = False
    elif self.songCountdown > 0:
      self.songCountdown -= ticks
      if self.songCountdown <= 0:
        self.playSelectedSong()
    
    if self.scrolling > 0:
      self.delay -= ticks
      self.rate += ticks
      if self.delay <= 0 and self.rate >= self.engine.scrollRate:
        self.rate = 0
        self.scroller[self.scrolling]()

    d = self.cameraOffset - self.selectedOffset
    self.cameraOffset -= d * ticks / 192.0
    
    for i in range(len(self.itemAngles)):
      if i == self.selectedIndex:
        self.itemAngles[i] = min(90, self.itemAngles[i] + ticks / 2.0)
      else:
        self.itemAngles[i] = max(0,  self.itemAngles[i] - ticks / 2.0)
    
  def renderCassette(self, color, label):
    if not self.cassette:
      return

    if color:
      glColor3f(*color)

    glEnable(GL_COLOR_MATERIAL)
    if self.display == 2:
      glRotate(90, 0, 0, 1)
      if self.listRotation:
        glRotate(((self.time - self.lastTime) * 2 % 360) - 90, 1, 0, 0)
    
    self.cassette.render("Mesh_001")
    glColor3f(.1, .1, .1)
    self.cassette.render("Mesh")
    
    if isinstance(label, str): #locked
      return
    # Draw the label if there is one
    if label is not None:
      glEnable(GL_TEXTURE_2D)
      label.bind()
      glColor3f(1, 1, 1)
      glMatrixMode(GL_TEXTURE)
      glScalef(1, -1, 1)
      glMatrixMode(GL_MODELVIEW)
      self.label.render("Mesh_001")
      glMatrixMode(GL_TEXTURE)
      glLoadIdentity()
      glMatrixMode(GL_MODELVIEW)
      glDisable(GL_TEXTURE_2D)
      
    
    
    if shaders.enable("cd"):
      self.cassette.render("Mesh_001")
      shaders.disable()
  
  def renderLibrary(self, color, label):
    if not self.libraryMesh:
      return

    if color:
      glColor3f(*color)

    glEnable(GL_NORMALIZE)
    glEnable(GL_COLOR_MATERIAL)
    if self.display == 2:
      glRotate(-180, 0, 1, 0)
      glRotate(-90, 0, 0, 1)
      if self.listRotation:
        glRotate(((self.time - self.lastTime) * 4 % 360) - 90, 1, 0, 0)
    self.libraryMesh.render("Mesh_001")
    glColor3f(.1, .1, .1)
    self.libraryMesh.render("Mesh")

    # Draw the label if there is one
    if label is not None:
      glEnable(GL_TEXTURE_2D)
      label.bind()
      glColor3f(1, 1, 1)
      glMatrixMode(GL_TEXTURE)
      glScalef(1, -1, 1)
      glMatrixMode(GL_MODELVIEW)
      self.libraryLabel.render()
      glMatrixMode(GL_TEXTURE)
      glLoadIdentity()
      glMatrixMode(GL_MODELVIEW)
      glDisable(GL_TEXTURE_2D)
    glDisable(GL_NORMALIZE)

#MFH - need to render titles (with new function so future expansion can include title labels):
  def renderTitle(self, color, label):
    if not self.libraryMesh:
      return

    if color:
      glColor3f(*color)

    glEnable(GL_NORMALIZE)
    glEnable(GL_COLOR_MATERIAL)
    self.libraryMesh.render("Mesh_001")
    glColor3f(.1, .1, .1)
    self.libraryMesh.render("Mesh")

    # Draw the label if there is one
    if label is not None:
      glEnable(GL_TEXTURE_2D)
      label.bind()
      glColor3f(1, 1, 1)
      glMatrixMode(GL_TEXTURE)
      glScalef(1, -1, 1)
      glMatrixMode(GL_MODELVIEW)
      self.libraryLabel.render()
      glMatrixMode(GL_TEXTURE)
      glLoadIdentity()
      glMatrixMode(GL_MODELVIEW)
      glDisable(GL_TEXTURE_2D)
    glDisable(GL_NORMALIZE)


#MFH - need to render the Career Resetter (with new function so future expansion can include a label):
  def renderCareerResetter(self, color, label):
    if not self.libraryMesh:
      return

    if color:
      glColor3f(*color)

    glEnable(GL_NORMALIZE)
    glEnable(GL_COLOR_MATERIAL)
    self.libraryMesh.render("Mesh_001")
    glColor3f(.1, .1, .1)
    self.libraryMesh.render("Mesh")

    # Draw the label if there is one
    if label is not None:
      glEnable(GL_TEXTURE_2D)
      label.bind()
      glColor3f(1, 1, 1)
      glMatrixMode(GL_TEXTURE)
      glScalef(1, -1, 1)
      glMatrixMode(GL_MODELVIEW)
      self.libraryLabel.render()
      glMatrixMode(GL_TEXTURE)
      glLoadIdentity()
      glMatrixMode(GL_MODELVIEW)
      glDisable(GL_TEXTURE_2D)
    glDisable(GL_NORMALIZE)


  
  def render(self, visibility, topMost):
    if self.items != []:
      v = (1 - visibility) ** 2
  
      # render the background
      t = self.time / 100
      
      self.engine.view.setViewport(1,0)
      w, h = self.engine.view.geometry[2:4]
      screenw = w
      screenh = h
      r = .5
  
      if self.display != 1: #
        #MFH - auto background image scaling
        imgwidth = self.background.width1()
        wfactor = 640.000/imgwidth
        self.engine.drawImage(self.background, scale = (wfactor,-wfactor), coord = (w/2,h/2))
      else:
        imgwidth = self.paper.width1()
        wfactor = 640.000/imgwidth
        imgheight = self.paper.height1()
        if self.background != None:
          self.engine.drawImage(self.background, scale = (.5,-.5), coord = (w/2,h/2))
        else:
          self.background = None
  
        if self.songback:
        # evilynux - Fixed, there's a two song offset and two lines should be skipped
          if self.selectedIndex == 0 or self.selectedIndex == 1:      #worldrave - Paper no longer moves up when user moves up to select '(Random)' song option. 
            y = 0
          else:
            y = h*(self.selectedIndex-2)*2/16.06  #worldrave - Tweaked the number so the image doesn't move off sync more and more as the paper moves down.
          
          papercoord = (w/2,(h - (w*(imgheight/imgwidth))/2) + y)
        else:
          papercoord = (w/2,h/2)

        self.engine.drawImage(self.paper, scale = (wfactor,-wfactor), coord = papercoord)
  
        #worldrave - Displays 'setlistguidebuttons.png' image, also added theme.ini control over X+Y position, as well as scaling X+Y control. 
      if self.setlistguidebuttons != None:
        self.engine.drawImage(self.setlistguidebuttons, scale = (Theme.setlistguidebuttonsscaleX,-Theme.setlistguidebuttonsscaleY), coord = (w*Theme.setlistguidebuttonsposX, h*Theme.setlistguidebuttonsposY))

        #racer: render preview graphic    worldrave - Added theme.ini control over X+Y position, as well as scaling X+Y control.
      if self.previewDisabled == True and self.preview != None:
        self.engine.drawImage(self.preview, scale = (Theme.setlistpreviewbuttonscaleX,-Theme.setlistpreviewbuttonscaleY), coord = (w*Theme.setlistpreviewbuttonposX, h*Theme.setlistpreviewbuttonposY))
      else:
        self.preview = None
  
  
  
    
  
      #MFH - initializing these local variables so no "undefined" crashes result
      text = ""  
      notesTotal = 0    
      notesHit = 0
      noteStreak = 0

      if self.instrumentChange:
        self.instrumentChange = False
        self.instrument = Song.parts[Song.SORT_PART[(Song.PART_SORT[self.instrument.id]+1)%len(Song.parts)]] # or do you want to order this properly?
        self.engine.config.set("game", "songlist_instrument", self.instrument.id)
        if self.sortOrder == 7:
            if self.songLoader:
              self.songLoader.cancel()
            if self.song:
              self.song.fadeout(1000)
            self.selectedItem = None
            self.loadCollection()
  
      if self.display == 0: #CDs Mode
      # render the item list
        try:      
          glMatrixMode(GL_PROJECTION)
          glPushMatrix()
  
          #myfingershurt: indentation was screwy here
          glLoadIdentity()
          gluPerspective(60, self.engine.view.aspectRatio, 0.1, 1000)
          glMatrixMode(GL_MODELVIEW)
          glLoadIdentity()
              
          glEnable(GL_DEPTH_TEST)
          glDisable(GL_CULL_FACE)
          glDepthMask(1)
              
          offset = 10 * (v ** 2)
          
          #self.camera.origin = (-10 + offset, -self.cameraOffset, 4   + offset)
          #self.camera.target = (  0 + offset, -self.cameraOffset, 2.5 + offset)
  
          #Blazingamer's CD X position fix        
          self.camera.origin = (-10 + offset, -self.cameraOffset, 4   - self.song_cd_xpos + offset)
          self.camera.target = (  0 + offset, -self.cameraOffset, 2.5 - self.song_cd_xpos + offset)
  
          
          self.camera.apply()
              
          y = 0.0
          for i, item in enumerate(self.items):
  
            if not self.matchesSearch(item):
              continue
          
            c = math.sin(self.itemAngles[i] * math.pi / 180)
          
            if isinstance(item, Song.SongInfo):
              h = c * self.cassetteWidth + (1 - c) * self.cassetteHeight
            elif isinstance(item, Song.LibraryInfo):
              h = c * self.libraryWidth + (1 - c) * self.libraryHeight
            elif isinstance(item, Song.TitleInfo):
              h = c * self.titleWidth + (1 - c) * self.titleHeight
            elif isinstance(item, Song.CareerResetterInfo):
              h = c * self.titleWidth + (1 - c) * self.titleHeight
            elif isinstance(item, Song.RandomSongInfo):
              h = c * self.titleWidth + (1 - c) * self.titleHeight
            elif isinstance(item, Song.BlankSpaceInfo):
              h = c * self.titleWidth + (1 - c) * self.titleHeight
  
  
          
            d = (y + h * .5 + self.camera.origin[1]) / (4 * (self.camera.target[2] - self.camera.origin[2]))
    
            if i == self.selectedIndex:
              self.selectedOffset = y + h / 2
              Theme.setSelectedColor()
            else:
              Theme.setBaseColor()
            
            #MFH - I think this is where CD songs are positioned --- Nope!
            glTranslatef(0, -h / 2, 0)
            #glTranslatef(self.song_cd_xpos, -h / 2, 0)
            
          
            glPushMatrix()
            if abs(d) < 1.2:
              if isinstance(item, Song.SongInfo):
                glRotate(self.itemAngles[i], 0, 0, 1)
                self.renderCassette(item.cassetteColor, self.itemLabels[i])
              elif isinstance(item, Song.LibraryInfo):
                #myfingershurt: cd cases are backwards
                glRotate(-self.itemAngles[i], 0, 1, 0)    #spin 90 degrees around y axis
                glRotate(-self.itemAngles[i], 0, 1, 0)    #spin 90 degrees around y axis again, now case is corrected
                glRotate(-self.itemAngles[i], 0, 0, 1)    #bring cd case up for viewing
                if i == self.selectedIndex and self.rotationDisabled == False:
                  glRotate(((self.time - self.lastTime) * 4 % 360) - 90, 1, 0, 0)
                self.renderLibrary(item.color, self.itemLabels[i])
              elif isinstance(item, Song.TitleInfo):
                #myfingershurt: cd cases are backwards
                glRotate(-self.itemAngles[i], 0, 0.5, 0)    #spin 90 degrees around y axis
                glRotate(-self.itemAngles[i], 0, 0.5, 0)    #spin 90 degrees around y axis again, now case is corrected
                glRotate(-self.itemAngles[i], 0, 0, 0.5)    #bring cd case up for viewing
                if i == self.selectedIndex and self.rotationDisabled == False:
                  glRotate(((self.time - self.lastTime) * 4 % 360) - 90, 1, 0, 0)
                self.renderTitle(item.color, self.itemLabels[i])
              elif isinstance(item, Song.CareerResetterInfo):
                #myfingershurt: cd cases are backwards
                glRotate(-self.itemAngles[i], 0, 0.5, 0)    #spin 90 degrees around y axis
                glRotate(-self.itemAngles[i], 0, 0.5, 0)    #spin 90 degrees around y axis again, now case is corrected
                glRotate(-self.itemAngles[i], 0, 0, 0.5)    #bring cd case up for viewing
                if i == self.selectedIndex and self.rotationDisabled == False:
                  glRotate(((self.time - self.lastTime) * 4 % 360) - 90, 1, 0, 0)
                self.renderCareerResetter(item.color, self.itemLabels[i])
              elif isinstance(item, Song.RandomSongInfo):
                #myfingershurt: cd cases are backwards
                glRotate(self.itemAngles[i], 0, 0, 1)
                self.renderCareerResetter(item.color, self.itemLabels[i])
  
  
            glPopMatrix()
          
            glTranslatef(0, -h / 2, 0)
            y += h
          glDisable(GL_DEPTH_TEST)
          glDisable(GL_CULL_FACE)
          glDepthMask(0)
        
        finally:
          glMatrixMode(GL_PROJECTION)
          glPopMatrix()
          glMatrixMode(GL_MODELVIEW)
      
        # render the song info
        self.engine.view.setOrthogonalProjection(normalize = True)
        font = self.engine.data.font
        # evilynux - GH theme? Use not-outlined font. Beware, RbMFH doesn't have any lfont!
        if self.theme == 0 or self.theme == 1:
          lfont = self.engine.data.lfont
        else:
          lfont = font
      
        try:
          glEnable(GL_BLEND)
          glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
          glEnable(GL_COLOR_MATERIAL)
          Theme.setBaseColor(1 - v)
  
          if self.searchText:
            text = _("Filter: %s") % (self.searchText) + "|"
            if not self.matchesSearch(self.items[self.selectedIndex]):
              text += " (%s)" % _("Not found")
            font.render(text, (.05, .7 + v), scale = 0.001)
          elif self.songLoader:
            font.render(_("Loading Preview..."), (.05, .7 + v), scale = 0.001)
  
          #x = .6
          x = self.song_cdscore_xpos
          y = .15
          font.render(self.prompt, (x, .05 - v))
  
          Theme.setSelectedColor(1 - v)
  
          c1,c2,c3 = self.song_name_selected_color
          glColor3f(c1,c2,c3)
          
          item  = self.items[self.selectedIndex]
  
          if self.matchesSearch(item):
            angle = self.itemAngles[self.selectedIndex]
            f = ((90.0 - angle) / 90.0) ** 2
  
            cText = item.name
            if (isinstance(item, Song.SongInfo) and item.getLocked()):
              cText = _("-- Locked --")
  
            # evilynux - Use font w/o outline
            pos = wrapText(lfont, (x, y), cText, visibility = f, scale = 0.0016)
  
            if isinstance(item, Song.SongInfo):
              Theme.setBaseColor(1 - v)
  
              c1,c2,c3 = self.artist_selected_color
              glColor3f(c1,c2,c3)
              
              if not item.year == "":
                yeartag = ", "+item.year
              else:
                yeartag = ""
              
              cText = item.artist + yeartag
              if (item.getLocked()):
                cText = "" # avoid giving away artist of locked song
              
              # evilynux - Use font w/o outline
              pos = wrapText(lfont, (x, pos[1] + font.getHeight() * 0.0016), cText, visibility = f, scale = 0.0016)
  
              if item.count:
                Theme.setSelectedColor(1 - v)
  
                c1,c2,c3 = self.song_name_selected_color
                glColor3f(c1,c2,c3)
  
                count = int(item.count)
                if count == 1: 
                  text = _("Played %d time") % count
                else:
                  text = _("Played %d times") % count
  
                if item.getLocked():
                  text = item.getUnlockText()
                elif self.careerMode and not item.completed:
                  text = _("Play To Advance.")
                # evilynux - small text, use font w/o outline, else unreadable
                pos = wrapText(lfont, (x, pos[1] + font.getHeight() * 0.0016), text, visibility = f, scale = 0.001)
              else:
                if item.getLocked():
                  text = item.getUnlockText()
                elif self.careerMode and not item.completed:
                  text = _("Play To Advance.")
                # evilynux - small text, use font w/o outline, else unreadable
                pos = wrapText(lfont, (x, pos[1] + font.getHeight() * 0.0016), text, visibility = f, scale = 0.001)
  
              Theme.setSelectedColor(1 - v)
  
              c1,c2,c3 = self.songlistcd_score_color
              glColor3f(c1,c2,c3)
  
              scale = 0.0011
              w, h = font.getStringSize(self.prompt, scale = scale)
              
              #x = .6
              x = self.song_cdscore_xpos
              y = .5 + f / 2.0
              try:
                difficulties = item.partDifficulties[self.instrument.id]
              except KeyError:
                difficulties = []
              if len(difficulties) > 3:
                y = .42 + f / 2.0
              elif len(difficulties) == 0:
                score, stars, name = "---", 0, "---"
              
              #for p in item.parts:    #MFH - look at selected instrument!
              #  if str(p) == self.instrument:
              for d in difficulties:
                scores = item.getHighscores(d, part = self.instrument)
                #scores = item.getHighscoresWithPartString(d, part = self.instrument)
                
                if scores:
                  score, stars, name, scoreExt = scores[0]
                  try:
                    notesHit, notesTotal, noteStreak, modVersion, handicap, handicapLong, originalScore = scoreExt
                  except ValueError:
                    notesHit, notesTotal, noteStreak, modVersion, oldScores1, oldScores2 = scoreExt
                    handicap = 0
                    handicapLong = "None"
                    originalScore = score
                else:
                  score, stars, name = "---", 0, "---"
                Theme.setBaseColor(1 - v)
                font.render(Song.difficulties[d.id].text,     (x, y),           scale = scale) # akedrou: This is absolute nonsense, but needed for translation because of caching!

                starscale = 0.02
                stary = 1.0 - y/self.engine.data.fontScreenBottom
                self.engine.drawStarScore(screenw, screenh, x+.01, stary-2*h, stars, starscale, hqStar = True) #volshebnyi

#-                # evilynux - Fixed star size following Font render bugfix
#-                if stars == 7: #akedrou
#-                  glColor3f(0, .5, 1) #should be customizable
#-                  font.render(unicode(Data.STAR2 * 5), (x, y + h), scale = scale * 1.8)
#-                elif stars == 6 and self.theme == 2:    #gold stars in RB songlist
#-                  glColor3f(1, 1, 0)  
#-                  font.render(unicode(Data.STAR2 * 5), (x, y + h), scale = scale * 1.8)
#-                elif stars == 6:
#-                  glColor3f(0, 1, 0)  
#-                  font.render(unicode(Data.STAR2 * 5), (x, y + h), scale = scale * 1.8)
#-                else:
#-                  font.render(unicode(Data.STAR2 * stars + Data.STAR1 * (5 - stars)), (x, y + h), scale = scale * 1.8)


                Theme.setSelectedColor(1 - v)
                # evilynux - Also use hit%/noteStreak SongList option
                if scores:
                  if self.extraStats:
                    if notesTotal != 0:
                      score = "%s %.1f%%" % (score, (float(notesHit) / notesTotal) * 100.0)
                    if noteStreak != 0:
                      score = "%s (%d)" % (score, noteStreak)
                font.render(unicode(score), (x + .15, y),     scale = scale)
                font.render(name,       (x + .15, y + h),     scale = scale)
                y += 2 * h + f / 4.0
            elif isinstance(item, Song.LibraryInfo):
              Theme.setBaseColor(1 - v)
  
              c1,c2,c3 = self.library_selected_color
              glColor3f(c1,c2,c3)
  
              if item.songCount == 1:
                songCount = _("One Song In This Setlist")
              else:
                songCount = _("%d Songs In This Setlist") % item.songCount
              if item.songCount > 0:
                wrapText(font, (x, pos[1] + 3 * font.getHeight() * 0.0016), songCount, visibility = f, scale = 0.0016)
  
            elif isinstance(item, Song.CareerResetterInfo):
              Theme.setBaseColor(1 - v)
  
              c1,c2,c3 = self.career_title_color
              glColor3f(c1,c2,c3)
  
              careerResetText = _("Reset this entire career")
              wrapText(font, (x, pos[1] + 3 * font.getHeight() * 0.0016), careerResetText, visibility = f, scale = 0.0016)
  
            elif isinstance(item, Song.RandomSongInfo):
              Theme.setBaseColor(1 - v)
  
              c1,c2,c3 = self.song_name_selected_color
              glColor3f(c1,c2,c3)
  
              careerResetText = ""
              wrapText(font, (x, pos[1] + 3 * font.getHeight() * 0.0016), careerResetText, visibility = f, scale = 0.0016)
  
          #MFH CD list
          text = self.instrument.text
          scale = 0.00250
          #glColor3f(1, 1, 1)
          c1,c2,c3 = self.song_name_selected_color
          glColor3f(c1,c2,c3)
          w, h = font.getStringSize(text, scale=scale)
          font.render(text, (0.95-w, 0.000), scale=scale)
  
  
  
  
        finally:
          self.engine.view.resetProjection()
          nuttin = True
      

          
      elif self.display == 1:   #MFH - song List display
        if self.theme == 0 or self.theme == 1:
          # render the song info
          self.engine.view.setOrthogonalProjection(normalize = True)
          font = self.engine.data.songListFont
          lfont = self.engine.data.songListFont
          sfont = self.engine.data.shadowfont
          #font = self.engine.data.font
          #lfont = self.engine.data.lfont
        
          try:
            glEnable(GL_BLEND)
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
            glEnable(GL_COLOR_MATERIAL)
            Theme.setBaseColor(0)
  
            for i, item in enumerate(self.items):
              maxIndex = i
  
            #MFH - TODO - add logic for special 4-item songlist to prevent jumping up and down
            if self.selectedIndex < 5 and maxIndex < 5:
              pos = self.selectedIndex - self.selectedIndex, self.selectedIndex + (5-self.selectedIndex)
              y = h*(.63-(.125*self.selectedIndex))
            elif self.selectedIndex == 0:#Selection is first item in list
              pos = (self.selectedIndex, self.selectedIndex +5)
              y = h*0.63
            elif self.selectedIndex == 1:#Second item in list
              pos = (self.selectedIndex-1, self.selectedIndex+4)
              y = h*0.5
            elif self.selectedIndex == maxIndex-1:#Second to last item in list
              pos = (self.selectedIndex-3, self.selectedIndex+2)
              y = h*0.26
            elif self.selectedIndex == maxIndex and not self.selectedIndex == 2:#Last in list and not third item
              pos = (self.selectedIndex-4, self.selectedIndex+1)
              y = h*0.13
            else:
              pos = (self.selectedIndex-2, self.selectedIndex+3)#Any other item than above
              y = h*0.38
  
            #Render the selection grahics
            wfactor = self.selected.widthf(pixelw = 635.000)
            self.engine.drawImage(self.selected, scale = (wfactor,-wfactor), coord = (w/2.1, y-h*.01))
  
            #Render current library path
            glColor4f(1,1,1,1)
            text = self.library
            w, h = font.getStringSize(text)
  
            if self.searchText:
              text = _("Filter: %s") % (self.searchText) + "|"
              if not self.matchesSearch(self.items[self.selectedIndex]):
                text += " (%s)" % _("Not found")
              font.render(text, (.05, .7 + v), scale = 0.001)
            elif self.songLoader:
              font.render(_("Loading Preview..."), (.05, .7 + v), scale = 0.001)
  
  
            if self.filepathenable:
              font.render(text, (self.song_list_xpos, .19))
  
  
            #Render song list items
            glColor4f(1,1,1,1)
            for i, item in enumerate(self.items):
              if i >= pos[0] and i < pos[1]:
  
                if isinstance(item, Song.SongInfo):
                  c1,c2,c3 = self.song_name_selected_color
                  glColor3f(c1,c2,c3)
                  if i == self.selectedIndex:
                    if item.getLocked():
                      text = item.getUnlockText()
                    elif self.careerMode and not item.completed:
                      text = _("Play To Advance.")
                    elif self.gameMode1p == 1: #evilynux - Practice mode
                      text = _("Practice")
                    elif item.count:
                      count = int(item.count)
                      if count == 1: 
                        text = _("Played Once")
                      else:
                        text = _("Played %d times.") % count
                    else:
                      text = _("Quickplay")
                elif isinstance(item, Song.LibraryInfo):
                  c1,c2,c3 = self.library_selected_color
                  glColor3f(c1,c2,c3)
                  if i == self.selectedIndex:
                    if item.songCount == 1:
                      text = _("There Is 1 Song In This Setlist")
                    elif item.songCount > 1:
                      text = _("There are %d songs in this folder") % (item.songCount)
                    else:
                      text = ""
  
                elif isinstance(item, Song.TitleInfo):
                  text = _("Tier")
                  c1,c2,c3 = self.career_title_color
                  glColor3f(c1,c2,c3)
  
                elif isinstance(item, Song.CareerResetterInfo):
                  text = _("Reset this entire career")
                  c1,c2,c3 = self.career_title_color
                  glColor3f(c1,c2,c3)
                elif isinstance(item, Song.RandomSongInfo):
                  text = _("Random Song")
                  c1,c2,c3 = self.career_title_color
                  glColor3f(c1,c2,c3)
  
  
                if i == self.selectedIndex:
                  font.render(text, (self.song_list_xpos, .15))
  
                
                if i == self.selectedIndex:
                  glColor4f(.7,.5,.25,1)
                  if isinstance(item, Song.SongInfo) or isinstance(item, Song.RandomSongInfo):
                    c1,c2,c3 = self.song_name_selected_color
                    glColor3f(c1,c2,c3)
                  if isinstance(item, Song.LibraryInfo):
                    c1,c2,c3 = self.library_selected_color
                    glColor3f(c1,c2,c3)
                  if isinstance(item, Song.TitleInfo) or isinstance(item, Song.CareerResetterInfo) or isinstance(item, Song.BlankSpaceInfo):
                    c1,c2,c3 = self.career_title_color
                    glColor3f(c1,c2,c3)
                else:
                  glColor4f(0,0,0,1)
                  if isinstance(item, Song.SongInfo) or isinstance(item, Song.RandomSongInfo):
                    c1,c2,c3 = self.song_name_text_color
                    glColor3f(c1,c2,c3)
                  if isinstance(item, Song.LibraryInfo):
                    c1,c2,c3 = self.library_text_color
                    glColor3f(c1,c2,c3)
                  if isinstance(item, Song.TitleInfo) or isinstance(item, Song.CareerResetterInfo) or isinstance(item, Song.BlankSpaceInfo):
                    c1,c2,c3 = self.career_title_color
                    glColor3f(c1,c2,c3)
                    
                text = item.name
                
                if isinstance(item, Song.SongInfo) and item.getLocked():
                  text = _("-- Locked --")
                
                if isinstance(item, Song.SongInfo): #MFH - add indentation when tier sorting
                  if self.tiersArePresent:
                    text = self.indentString + text
                
                # evilynux - Force uppercase display for Career titles
                if isinstance(item, Song.TitleInfo) or isinstance(item, Song.CareerResetterInfo) or isinstance(item, Song.BlankSpaceInfo):
                  text = string.upper(text)
  
                # evilynux - automatically scale song name
                scale = font.scaleText(text, maxwidth = 0.440)
                w, h = font.getStringSize(text, scale = scale)

                if i == self.selectedIndex:
                  sfont.render(text, (self.song_list_xpos, .0925*(i+1)-pos[0]*.0925+.15), scale = scale)
                else:
                  lfont.render(text, (self.song_list_xpos, .0925*(i+1)-pos[0]*.0925+.15), scale = scale)


                #MFH - Song list score / info display:
                if isinstance(item, Song.SongInfo) and not item.getLocked():
                  if self.scoreTimer == 0 and self.highScoreType == 0: #racer: regular-style highscore movement
                    self.diff = Song.difficulties[(self.diff.id-1)%len(Song.difficulties)]
                    
  
                  #racer: score can be changed by fret button:
                  #MFH - and now they will be remembered as well
                  if self.highScoreChange == True and self.highScoreType == 1:
                    self.diff = Song.difficulties[(self.diff.id-1)%len(Song.difficulties)]
                    self.engine.config.set("game", "songlist_difficulty", self.diff.id)
                    self.highScoreChange = False

                  scale = 0.0009
                  text = self.diff.text
                  w, h = font.getStringSize(text, scale=scale)
                  # evilynux - score color
                  c1,c2,c3 = self.songlist_score_color
                  glColor3f(c1,c2,c3)
                  # evilynux - tweaked position to fit hit% and note streak
                  if self.extraStats:
                    lfont.render(text, (self.song_listscore_xpos-w-.02, .0925*(i+1)-pos[0]*.0925+.1575-h/2), scale=scale)
                  else:
                    lfont.render(text, (self.song_listscore_xpos-w-.02, .0925*(i+1)-pos[0]*.0925+.2-h/2), scale=scale)
                  if not item.frets == "":
                    suffix = ", ("+item.frets+")"
                  else:
                    suffix = ""
  
                  if not item.year == "":
                    yeartag = ", "+item.year
                  else:
                    yeartag = ""
  
  
                  scale = .0014
                  glColor4f(.25,.5,1,1)
  
                  if i == self.selectedIndex:
                    c1,c2,c3 = self.artist_selected_color
                  else:
                    c1,c2,c3 = self.artist_text_color
                  glColor3f(c1,c2,c3)
  
                  # evilynux - Force uppercase display for artist name
                  text = string.upper(item.artist)+suffix+yeartag
                  
                  # evilynux - automatically scale artist name and year
                  scale = font.scaleText(text, maxwidth = 0.440, scale = scale)
                  if scale > .0014:
                    scale = .0014
                  w, h = font.getStringSize(text, scale = scale)

                  lfont.render(text, (self.song_list_xpos+.05, .0925*(i+1)-pos[0]*.0925+.2), scale=scale)
  
                  score = _("Nil")
                  stars = 0
                  name = ""

                  try:
                    difficulties = item.partDifficulties[self.instrument.id]
                  except KeyError:
                    difficulties = []
                  for d in difficulties:
                    if d.id == self.diff.id:
                      scores = item.getHighscores(d, part = self.instrument)
                      if scores:
                        score, stars, name, scoreExt = scores[0]
                        try:
                          notesHit, notesTotal, noteStreak, modVersion, handicap, handicapLong, originalScore = scoreExt
                        except ValueError:
                          notesHit, notesTotal, noteStreak, modVersion, oldScores1, oldScores2 = scoreExt
                          handicap = 0
                          handicapLong = "None"
                          originalScore = score
                      else:
                        score, stars, name = 0, 0, "---"
                  
                  if score == _("Nil") and self.NilShowNextScore:   #MFH
                    for d in difficulties:   #MFH - just take the first valid difficulty you can find and display it.
                      scores = item.getHighscores(d, part = self.instrument)
                      if scores:
                        score, stars, name, scoreExt = scores[0]
                        try:
                          notesHit, notesTotal, noteStreak, modVersion, handicap, handicapLong, originalScore = scoreExt
                        except ValueError:
                          notesHit, notesTotal, noteStreak, modVersion, oldScores1, oldScores2 = scoreExt
                          handicap = 0
                          handicapLong = "None"
                          originalScore = score
                        break
                      else:
                        score, stars, name = 0, 0, "---"
                    else:
                      score, stars, name = _("Nil"), 0, "---"
                      
                  
                  


                  starx = self.song_listscore_xpos+.01
                  if self.extraStats:
                    stary = .0925*(i+1)-pos[0]*.0925+.1825-0.034
                  else:
                    stary = .0925*(i+1)-pos[0]*.0925+.2-0.034
                  #stary = 0.5
                  starscale = 0.03
                  stary = 1.0 - (stary / self.engine.data.fontScreenBottom)
                  self.engine.drawStarScore(screenw, screenh, starx, stary - h/2, stars, starscale, horiz_spacing = 1.0, hqStar = True) #MFH

                  scale = 0.0014
                  # evilynux - score color
                  c1,c2,c3 = self.songlist_score_color
                  glColor3f(c1,c2,c3)
                  # evilynux - hit% and note streak only if enabled
                  if self.extraStats:
                    if score is not _("Nil") and score > 0 and notesTotal != 0:
                      text = "%.1f%% (%d)" % ((float(notesHit) / notesTotal) * 100.0, noteStreak)
                      w, h = font.getStringSize(text, scale=scale)
                      lfont.render(text, (self.song_listscore_xpos+.1-w, .0925*(i+1)-pos[0]*.0925+.1725), scale=scale)
  
                  text = str(score)
                  w, h = font.getStringSize(text, scale=scale)
                  if score > 0 and score!=_("Nil"): #QQstarS: score >0 that have the back color
                    # evilynux - No more outline
                    lfont.render(text, (self.song_listscore_xpos+.1-w, .0925*(i+1)-pos[0]*.0925+.2), scale=scale*1.28)
                  else: #QQstarS: 
                    lfont.render(text, (self.song_listscore_xpos+.1-w, .0925*(i+1)-pos[0]*.0925+.2), scale=scale*1.28)
  
                  if self.scoreTimer < 1000:
                    self.scoreTimer += 1
                  else:
                    self.scoreTimer = 0
              
          finally:
          #  self.engine.view.resetProjection()
            nuttin = True
        
        elif self.theme == 2: # RbMFH
          # render the song info
          self.engine.view.setOrthogonalProjection(normalize = True)
          #font = self.engine.data.font
          font = self.engine.data.songListFont
        
          try:
            glEnable(GL_BLEND)
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
            glEnable(GL_COLOR_MATERIAL)
            Theme.setBaseColor(0)
  
            for i, item in enumerate(self.items):
              maxIndex = i
            if self.selectedIndex < 5 and maxIndex < 5:
              pos = self.selectedIndex - self.selectedIndex, self.selectedIndex + (5-self.selectedIndex)
              y = h*(.63-(.125*self.selectedIndex))
            elif self.selectedIndex == 0:
              pos = (self.selectedIndex, self.selectedIndex +5)
              y = h*0.63
            elif self.selectedIndex == 1:
              pos = (self.selectedIndex-1, self.selectedIndex+4)
              y = h*0.5
            elif self.selectedIndex == maxIndex-1:
              pos = (self.selectedIndex-3, self.selectedIndex+2)
              y = h*0.26
            elif self.selectedIndex == maxIndex and not self.selectedIndex == 2:
              pos = (self.selectedIndex-4, self.selectedIndex+1)
              y = h*0.13
            else:
              pos = (self.selectedIndex-2, self.selectedIndex+3)
              y = h*0.38

            self.engine.drawImage(self.selected, scale = (1,-1), coord = (w/2.1, y-h*.01))
  
            glColor4f(1,1,1,1)
            text = self.library
            w, h = font.getStringSize(text)
            if self.filepathenable:
              font.render(text, (self.song_list_xpos, .19))
            
            if self.searchText:
              text = _("Filter: %s") % (self.searchText) + "|"
              if not self.matchesSearch(self.items[self.selectedIndex]):
                text += " (%s)" % _("Not found")
              font.render(text, (.05, .7 + v), scale = 0.001)
            elif self.songLoader:
              font.render(_("Loading Preview..."), (.05, .7 + v), scale = 0.001)

            #Render song list items  
            for i, item in enumerate(self.items):
              if i >= pos[0] and i <= pos[1]:
  
                if isinstance(item, Song.SongInfo):
                  c1,c2,c3 = self.song_name_selected_color
                  glColor3f(c1,c2,c3)
                  if i == self.selectedIndex:
                    if item.getLocked():
                      text = item.getUnlockText()
                    elif self.careerMode and not item.completed:
                      text = _("Play To Advance")
                    elif self.gameMode1p == 1: #evilynux - Practice mode
                      text = _("Practice")
                    elif item.count:
                      count = int(item.count)
                      if count == 1: 
                        text = _("Played Once")
                      else:
                        text = _("Played %d times.") % count
                    else:
                      text = _("Quickplay")
                elif isinstance(item, Song.LibraryInfo):
                  c1,c2,c3 = self.library_selected_color
                  glColor3f(c1,c2,c3)
                  if i == self.selectedIndex:
                    if item.songCount == 1:
                      text = _("There Is 1 Song In This Setlist.")
                    elif item.songCount > 1:
                      text = _("There Are %d Songs In This Setlist.") % (item.songCount)
                    else:
                      text = ""
                elif isinstance(item, Song.TitleInfo):
                  text = _("Tier")
                  c1,c2,c3 = self.career_title_color
                  glColor3f(c1,c2,c3)
                elif isinstance(item, Song.CareerResetterInfo):
                  text = _("Reset this entire career")
                  c1,c2,c3 = self.career_title_color
                  glColor3f(c1,c2,c3)
                elif isinstance(item, Song.RandomSongInfo):
                  text = _("Random Song")
                  c1,c2,c3 = self.career_title_color
                  glColor3f(c1,c2,c3)
  
                if i == self.selectedIndex:
                  w, h = font.getStringSize(text)
                  font.render(text, (.5-w/2, .15))
                
                if i == self.selectedIndex:
                  glColor4f(.7,.5,.25,1)
                  if isinstance(item, Song.SongInfo) or isinstance(item, Song.RandomSongInfo):
                    c1,c2,c3 = self.song_name_selected_color
                    glColor3f(c1,c2,c3)
                  if isinstance(item, Song.LibraryInfo):
                    c1,c2,c3 = self.library_selected_color
                    glColor3f(c1,c2,c3)
                  if isinstance(item, Song.TitleInfo) or isinstance(item, Song.CareerResetterInfo) or isinstance(item, Song.BlankSpaceInfo):
                    c1,c2,c3 = self.career_title_color
                    glColor3f(c1,c2,c3)
                else:
                  glColor4f(0,0,0,1)
                  if isinstance(item, Song.SongInfo):
                    c1,c2,c3 = self.song_name_text_color
                    glColor3f(c1,c2,c3)
                  if isinstance(item, Song.RandomSongInfo):
                    c1,c2,c3 = self.song_name_text_color
                    glColor3f(c1,c2,c3)
                  if isinstance(item, Song.LibraryInfo):
                    c1,c2,c3 = self.library_text_color
                    glColor3f(c1,c2,c3)
                  if isinstance(item, Song.TitleInfo) or isinstance(item, Song.CareerResetterInfo) or isinstance(item, Song.BlankSpaceInfo):
                    c1,c2,c3 = self.career_title_color
                    glColor3f(c1,c2,c3)
                text = item.name
  
                if isinstance(item, Song.SongInfo) and item.getLocked():
                  text = _("-- Locked --")
  
                if isinstance(item, Song.SongInfo): #MFH - add indentation when tier sorting
                  if self.tiersArePresent:
                    text = self.indentString + text
  
                # evilynux/blazingamer - Force uppercase display
                if isinstance(item, Song.TitleInfo) or isinstance(item, Song.CareerResetterInfo) or isinstance(item, Song.BlankSpaceInfo):
                  text = string.upper(text)
  
                # evilynux - automatically scale song name
                scale = font.scaleText(text, maxwidth = 0.64)
                w, h = font.getStringSize(text, scale = scale)

                font.render(text, (self.song_list_xpos, .0935*(i+1)-pos[0]*.0935+.15), scale = scale)
  
                if isinstance(item, Song.SongInfo) and not item.getLocked():
                  if self.scoreTimer == 0 and self.highScoreType == 0: #racer: regular-style highscore movement
                    self.diff = Song.difficulties[(self.diff.id-1)%len(Song.difficulties)]
  
                  #racer: score can be changed by fret button:
                  #MFH - and now they will be remembered as well
                  if self.highScoreChange == True and self.highScoreType == 1:
                    self.diff = Song.difficulties[(self.diff.id-1)%len(Song.difficulties)]
                    self.engine.config.set("game", "songlist_difficulty", self.diff.id)
                    self.highScoreChange = False
  
                  score = _("Nil")
                  stars = 0
                  name = ""

                  try:
                    difficulties = item.partDifficulties[self.instrument.id]
                  except KeyError:
                    difficulties = []
                  for d in difficulties:
                    if d.id == self.diff.id:
                      scores = item.getHighscores(d, part = self.instrument)
                      if scores:
                        score, stars, name, scoreExt = scores[0]
                        try:
                          notesHit, notesTotal, noteStreak, modVersion, handicap, handicapLong, originalScore = scoreExt
                        except ValueError:
                          notesHit, notesTotal, noteStreak, modVersion, oldScores1, oldScores2 = scoreExt
                          handicap = 0
                          handicapLong = "None"
                          originalScore = score
                      else:
                        score, stars, name = 0, 0, "---"
                  
                  if score == _("Nil") and self.NilShowNextScore:   #MFH
                    for d in item.difficulties:   #MFH - just take the first valid difficulty you can find and display it.
                      scores = item.getHighscores(d, part = self.instrument)
                      if scores:
                        score, stars, name, scoreExt = scores[0]
                        try:
                          notesHit, notesTotal, noteStreak, modVersion, handicap, handicapLong, originalScore = scoreExt
                        except ValueError:
                          notesHit, notesTotal, noteStreak, modVersion, oldScores1, oldScores2 = scoreExt
                          handicap = 0
                          handicapLong = "None"
                          originalScore = score
                        break
                      else:
                        score, stars, name = 0, 0, "---"
                    else:
                      score, stars, name = _("Nil"), 0, "---"

                  scale = 0.0009
                  text = self.diff.text
                  w, h = font.getStringSize(text, scale=scale)
                  # evilynux - score color
                  c1,c2,c3 = self.songlist_score_color
                  glColor3f(c1,c2,c3)
                  if self.extraStats:
                    # evilynux - tweaked position to fit hit% and note streak
                    font.render(text, (self.song_listscore_xpos-w-.025, .0935*(i+1)-pos[0]*.0935+.185-h/2), scale=scale)
                  else:
                    font.render(text, (self.song_listscore_xpos-w-.025, .0935*(i+1)-pos[0]*.0935+.2-h/2), scale=scale)
                  
                  if not item.frets == "":
                    suffix = ", ("+item.frets+")"
                  else:
                    suffix = ""
                  
                  if not item.year == "":
                    yeartag = ", "+item.year
                  else:
                    yeartag = ""
                  
                    
                  scale = .0014
                  glColor4f(.25,.5,1,1)
  
                  if i == self.selectedIndex:
                    c1,c2,c3 = self.artist_selected_color
                  else:
                    c1,c2,c3 = self.artist_text_color
                  glColor3f(c1,c2,c3)
  
                  # evilynux - Force uppercase display for artist name
                  text = string.upper(item.artist)+suffix+yeartag
  
                  # evilynux - automatically scale artist name and year
                  scale = font.scaleText(text, maxwidth = 0.554, scale = scale)
                  if scale > .0014:
                    scale = .0014
                  w, h = font.getStringSize(text, scale = scale)

                  font.render(text, (self.song_list_xpos+.05, .0935*(i+1)-pos[0]*.0935+.2), scale=scale)
  
                  starx = self.song_listscore_xpos+.005
                  if self.extraStats:
                    stary = .0935*(i+1)-pos[0]*.0935+.1705
                  else:
                    stary = .0935*(i+1)-pos[0]*.0935+.2-0.0145
                  #stary = 0.5
                  starscale = 0.02
                  stary = 1.0 - (stary / self.engine.data.fontScreenBottom)
                  if i < pos[1]:
                    self.engine.drawStarScore(screenw, screenh, starx, stary, stars, starscale) #MFH

  
                  scale = 0.0014
                  # evilynux - score color
                  c1,c2,c3 = self.songlist_score_color
                  glColor3f(c1,c2,c3)
                  #evilynux - hit% and note streak if enabled
                  if self.extraStats:
                    if score is not _("Nil") and score > 0 and notesTotal != 0:
                      text = "%.1f%% (%d)" % ((float(notesHit) / notesTotal) * 100.0, noteStreak)
                      # evilynux - changed positions a little for nice note streak integration
                      w, h = font.getStringSize(text, scale=scale)
                      font.render(text, (self.song_listscore_xpos+.11-w, .0935*(i+1)-pos[0]*.0935+.1825), scale=scale)
  
                  text = str(score)
                  w, h = font.getStringSize(text, scale=scale)
  
                  # evilynux - changed positions a little for nice note streak integration
                  font.render(text, (self.song_listscore_xpos+.11-w, .0935*(i+1)-pos[0]*.0935+.205), scale=scale)
  
                  if self.scoreTimer < 1000:
                    self.scoreTimer += 1
                  else:
                    self.scoreTimer = 0
        
        
              
          finally:
          #  self.engine.view.resetProjection()
            nuttin = True
        
        #MFH - after songlist / CD and theme conditionals - common executions
        text = self.instrument.text
        scale = 0.00250
        glColor3f(1, 1, 1)
        w, h = font.getStringSize(text, scale=scale)
        font.render(text, (0.85-w, 0.10), scale=scale)
        self.engine.view.resetProjection()

      elif self.display == 2:   #Qstick/Blazingamer - Combo CD/List
        item  = self.items[self.selectedIndex]
        i = self.selectedIndex
        if not self.listRotation:
          if self.itemLabels[i]:
            imgwidth = self.itemLabels[i].width1()
            wfactor = 214.000/imgwidth
            self.engine.drawImage(self.itemLabels[i], scale = (wfactor,-wfactor),
                                  coord = (self.song_listcd_cd_xpos * w,self.song_listcd_cd_ypos*h))
        else:
          try:
            glMatrixMode(GL_PROJECTION)
            glPushMatrix()
            
            #myfingershurt: indentation was screwy here
            glLoadIdentity()
            gluPerspective(60, self.engine.view.aspectRatio, 0.1, 1000)
            glMatrixMode(GL_MODELVIEW)
            glLoadIdentity()
                
            glEnable(GL_DEPTH_TEST)
            glDisable(GL_CULL_FACE)
            glDepthMask(1)
                
            offset = 10 * (v ** 2)
            self.camera.origin = (-9,(5.196/self.engine.view.aspectRatio) - (5.196*2/self.engine.view.aspectRatio)*self.song_listcd_cd_ypos,(5.196*self.engine.view.aspectRatio)-(5.196*2*self.engine.view.aspectRatio)*self.song_listcd_cd_xpos)
            self.camera.target = ( 0,(5.196/self.engine.view.aspectRatio) - (5.196*2/self.engine.view.aspectRatio)*self.song_listcd_cd_ypos,(5.196*self.engine.view.aspectRatio)-(5.196*2*self.engine.view.aspectRatio)*self.song_listcd_cd_xpos)
            self.camera.apply()
                
            y = 0.0

            

            glPushMatrix()
            if isinstance(item, Song.SongInfo):
              if self.songCoverType:
                self.renderCassette(item.cassetteColor, self.itemLabels[i])
              else:
                self.renderLibrary(item.cassetteColor, self.itemLabels[i])
            elif isinstance(item, Song.LibraryInfo):
              self.renderLibrary(item.color, self.itemLabels[i])
            glPopMatrix()
            
            glTranslatef(0, -h / 2, 0)
            y += h

            glDisable(GL_DEPTH_TEST)
            glDisable(GL_CULL_FACE)
            glDepthMask(0)
          
          finally:
            glMatrixMode(GL_PROJECTION)
            glPopMatrix()
            glMatrixMode(GL_MODELVIEW)
          # render the song info
        self.engine.view.setOrthogonalProjection(normalize = True)
        font = self.engine.data.songListFont
        
        try:
          glEnable(GL_BLEND)
          glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
          glEnable(GL_COLOR_MATERIAL)
          Theme.setBaseColor(0)
          
          
          
          for i, item in enumerate(self.items):
            maxIndex = i
          if self.selectedIndex < 7 and maxIndex < 7:
            pos = self.selectedIndex - self.selectedIndex, self.selectedIndex + (7-self.selectedIndex)
            y = h*(.87-(.1*self.selectedIndex))
          elif self.selectedIndex == 0:#Selection is first item in list
            pos = (self.selectedIndex, self.selectedIndex +7)
            y = h*0.87
          elif self.selectedIndex == 1:#Second item in list
            pos = (self.selectedIndex-1, self.selectedIndex+6)
            y = h*0.77
          elif self.selectedIndex == 2:#Second item in list
            pos = (self.selectedIndex-2, self.selectedIndex+5)
            y = h*0.67
          elif self.selectedIndex == maxIndex-2:
            pos = (self.selectedIndex-4, self.selectedIndex+3)
            y = h*0.47
          elif self.selectedIndex == maxIndex-1:#Second to last item in list
            pos = (self.selectedIndex-5, self.selectedIndex+2)
            y = h*0.37
          elif self.selectedIndex == maxIndex and not self.selectedIndex == 1:#Third to Last in list and not third item
            pos = (self.selectedIndex-6, self.selectedIndex+1)
            y = h*0.27
          else:
            pos = (self.selectedIndex-3, self.selectedIndex+4)#Any other item than above
            y = h*0.57

          if self.theme == 0 or self.theme == 1:
            lfont = self.engine.data.songListFont
            sfont = self.engine.data.shadowfont
            
            glColor4f(1,1,1,1)
            text = self.library
            w, h = font.getStringSize(text)
            if self.filepathenable:
              font.render(text, (.05, .01))
            
            if self.searchText:
              text = _("Filter: %s") % (self.searchText) + "|"
              if not self.matchesSearch(self.items[self.selectedIndex]):
                text += " (%s)" % _("Not found")
              font.render(text, (.05, .7 + v), scale = 0.001)
            elif self.songLoader:
              font.render(_("Loading Preview..."), (.05, .7 + v), scale = 0.001)
              
            for i, item in enumerate(self.items):
              if i >= pos[0] and i <= pos[1]:
  
                if isinstance(item, Song.SongInfo):
                  c1,c2,c3 = self.song_name_selected_color
                  glColor3f(c1,c2,c3)
                  if i == self.selectedIndex:
                    if item.getLocked():
                      text = item.getUnlockText()
                    elif self.careerMode and not item.completed:
                      text = _("Play To Advance")
                    elif self.gameMode1p == 1: #evilynux - Practice mode
                      text = _("Practice")
                    elif item.count:
                      count = int(item.count)
                      if count == 1: 
                        text = _("Played Once")
                      else:
                        text = _("Played %d times.") % count
                    else:
                      text = _("Quickplay")
                elif isinstance(item, Song.LibraryInfo):
                  c1,c2,c3 = self.library_selected_color
                  glColor3f(c1,c2,c3)
                  if i == self.selectedIndex:
                    if item.songCount == 1:
                      text = _("There Is 1 Song In This Setlist.")
                    elif item.songCount > 1:
                      text = _("There Are %d Songs In This Setlist.") % (item.songCount)
                    else:
                      text = ""
                elif isinstance(item, Song.TitleInfo):
                  text = _("Tier")
                  c1,c2,c3 = self.career_title_color
                  glColor3f(c1,c2,c3)
                elif isinstance(item, Song.CareerResetterInfo):
                  text = _("Reset this entire career")
                  c1,c2,c3 = self.career_title_color
                  glColor3f(c1,c2,c3)
                elif isinstance(item, Song.RandomSongInfo):
                  text = _("Random Song")
                  c1,c2,c3 = self.career_title_color
                  glColor3f(c1,c2,c3)
                
                if i == self.selectedIndex:
                  w, h = font.getStringSize(text)
                  font.render(text, (self.song_listcd_score_xpos, .085), scale = 0.0012)
                
                if i == self.selectedIndex:
                  glColor4f(.7,.5,.25,1)
                  if isinstance(item, Song.SongInfo) or isinstance(item, Song.RandomSongInfo):
                    c1,c2,c3 = self.song_name_selected_color
                    glColor3f(c1,c2,c3)
                  if isinstance(item, Song.LibraryInfo):
                    c1,c2,c3 = self.library_selected_color
                    glColor3f(c1,c2,c3)
                  if isinstance(item, Song.TitleInfo) or isinstance(item, Song.CareerResetterInfo) or isinstance(item, Song.BlankSpaceInfo):
                    c1,c2,c3 = self.career_title_color
                    glColor3f(c1,c2,c3)
                else:
                  glColor4f(0,0,0,1)
                  if isinstance(item, Song.SongInfo) or isinstance(item, Song.RandomSongInfo):
                    c1,c2,c3 = self.song_name_text_color
                    glColor3f(c1,c2,c3)
                  if isinstance(item, Song.LibraryInfo):
                    c1,c2,c3 = self.library_text_color
                    glColor3f(c1,c2,c3)
                  if isinstance(item, Song.TitleInfo) or isinstance(item, Song.CareerResetterInfo) or isinstance(item, Song.BlankSpaceInfo):
                    c1,c2,c3 = self.career_title_color
                    glColor3f(c1,c2,c3)

                text = item.name
                
                if isinstance(item, Song.SongInfo) and item.getLocked():
                  text = _("-- Locked --")
                  
                if isinstance(item, Song.SongInfo): #MFH - add indentation when tier sorting
                  if self.tiersArePresent:
                    text = self.indentString + text
  
                # evilynux - Force uppercase display for Career titles
                if isinstance(item, Song.TitleInfo):
                  text = string.upper(text)
                  
                if isinstance(item, Song.CareerResetterInfo):
                  text = string.upper(text)
  
                if isinstance(item, Song.BlankSpaceInfo):
                  text = string.upper(text)
                  
                scale = font.scaleText(text, maxwidth = 0.45)
                w, h = font.getStringSize(text, scale = scale)
                
                if i == self.selectedIndex:
                  sfont.render(text, (self.song_listcd_list_xpos, .09*(i+1)-pos[0]*.09), scale = scale) #add theme option for song_listCD_xpos
                else:
                  lfont.render(text, (self.song_listcd_list_xpos, .09*(i+1)-pos[0]*.09), scale = scale) #add theme option for song_listCD_xpos
                  
                angle = self.itemAngles[self.selectedIndex]
                f = ((90.0 - angle) / 90.0) ** 2
                
                if isinstance(item, Song.SongInfo) and not item.getLocked():
                  if not item.frets == "":
                    suffix = ", ("+item.frets+")"
                  else:
                    suffix = ""
                  
                  if not item.year == "":
                    yeartag = ", "+item.year
                  else:
                    yeartag = ""
                  
                  scale = .0014
                  glColor4f(.25,.5,1,1)
  
                  if i == self.selectedIndex:
                    c1,c2,c3 = self.artist_selected_color
                  else:
                    c1,c2,c3 = self.artist_text_color
                  glColor3f(c1,c2,c3)
  
                  # evilynux - Force uppercase display for artist name
                  text = string.upper(item.artist)+suffix+yeartag
  
                  # evilynux - automatically scale artist name and year
                  scale = font.scaleText(text, maxwidth = 0.4, scale = scale)
                  w, h = font.getStringSize(text, scale = scale)

                  lfont.render(text, (self.song_listcd_list_xpos + .05, .09*(i+1)-pos[0]*.09+.05), scale=scale)
            
                
                item  = self.items[self.selectedIndex]
                if self.matchesSearch(item):
                  if isinstance(item, Song.SongInfo):
                    angle = self.itemAngles[self.selectedIndex]
                    f = ((90.0 - angle) / 90.0) ** 2

                    
                    c1,c2,c3 = self.songlistcd_score_color
                    glColor3f(c1,c2,c3)
      
                    scale = 0.0013
                    w, h = font.getStringSize(self.prompt, scale = scale)
                    x = self.song_listcd_score_xpos
                    y = self.song_listcd_score_ypos + f / 2.0
                    try:
                      difficulties = item.partDifficulties[self.instrument.id]
                    except KeyError:
                      difficulties = []
                      score, stars, name = "---", 0, "---"
                    if len(difficulties) > 3:
                      y = self.song_listcd_score_ypos + f / 2.0
                    
                    #new
                    for d in difficulties:
                      #scores =  item.getHighscoresWithPartString(d, part = self.instrument)
                      scores =  item.getHighscores(d, part = self.instrument)
                      if scores:
                        score, stars, name, scoreExt = scores[0]
                        try:
                          notesHit, notesTotal, noteStreak, modVersion, handicap, handicapLong, originalScore = scoreExt
                        except ValueError:
                          notesHit, notesTotal, noteStreak, modVersion, oldScores1, oldScores2 = scoreExt
                          handicap = 0
                          handicapLong = "None"
                          originalScore = score
                      else:
                        score, stars, name = "---", 0, "---"
                      #Theme.setBaseColor(1 - v)
                      lfont.render(Song.difficulties[d.id].text,     (x, y),           scale = scale) # akedrou: This is absolute nonsense, but needed for translation because of caching!

                      starscale = 0.02
                      stary = 1.0 - (y / self.engine.data.fontScreenBottom) - h
                      self.engine.drawStarScore(screenw, screenh, x+.01, stary-h, stars, starscale) #MFH

#-                      if stars == 6 and self.theme == 2:
#-                        glColor3f(1, 1, 0)  
#-                        lfont.render(unicode(Data.STAR2 * (stars -1)), (x, y + h), scale = scale * 1.8)
#-                      elif stars == 6:
#-                        glColor3f(0, 1, 0)  
#-                        lfont.render(unicode(Data.STAR2 * (stars -1)), (x, y + h), scale = scale * 1.8)
#-                      else:
#-                        lfont.render(unicode(Data.STAR2 * stars + Data.STAR1 * (5 - stars)), (x, y + h), scale = scale * 1.8)
#-                      #Theme.setSelectedColor(1 - v)
                      
                                      

                      c1,c2,c3 = self.songlistcd_score_color
                      glColor3f(c1,c2,c3)
                      if scores:
                        if self.extraStats:
                          if notesTotal != 0:
                            score = "%s %.1f%%" % (score, (float(notesHit) / notesTotal) * 100.0)
                          if noteStreak != 0:
                            score = "%s (%d)" % (score, noteStreak)
                      lfont.render(unicode(score), (x + .15, y),     scale = scale)
                      lfont.render(name,       (x + .15, y + h),     scale = scale)
                      y += 2 * h + f / 4.0
            
          elif self.theme == 2:
            if self.selectedlistcd == None:
              imgwidth = self.selected.width1()
              self.engine.drawImage(self.selected, scale = (.64, -1.05), coord = (self.song_listcd_list_xpos * w + (imgwidth*.64/2), y*1.2-h*.215))
            else:
              self.engine.drawImage(self.selectedlistcd, scale = (1,-1), coord =(self.song_listcd_list_xpos * w + (imgwidth/2), y*1.2-h*.215))
            
            glColor4f(1,1,1,1)
            text = self.library
            w, h = font.getStringSize(text)
            if self.filepathenable:
              font.render(text, (.05, .01))
            
            if self.searchText:
              text = _("Filter: %s") % (self.searchText) + "|"
              if not self.matchesSearch(self.items[self.selectedIndex]):
                text += " (%s)" % _("Not found")
              font.render(text, (.05, .7 + v), scale = 0.001)
            elif self.songLoader:
              font.render(_("Loading Preview..."), (.05, .7 + v), scale = 0.001)
              
            x = self.song_cdscore_xpos #Add theme.ini option for song_cdlistscore_xpos
            font.render(self.prompt, (self.song_listcd_score_xpos, .05-v))
            
            for i, item in enumerate(self.items):
              if i >= pos[0] and i <= pos[1]:
  
                if isinstance(item, Song.SongInfo):
                  c1,c2,c3 = self.song_name_selected_color
                  glColor3f(c1,c2,c3)
                  if i == self.selectedIndex:
                    if item.getLocked():
                      text = item.getUnlockText()
                    elif self.careerMode and not item.completed:
                      text = _("Play To Advance")
                    elif self.gameMode1p == 1: #evilynux - Practice mode
                      text = _("Practice")
                    elif item.count:
                      count = int(item.count)
                      if count == 1: 
                        text = _("Played Once")
                      else:
                        text = _("Played %d times.") % count
                    else:
                      text = _("Quickplay")
                elif isinstance(item, Song.LibraryInfo):
                  c1,c2,c3 = self.library_selected_color
                  glColor3f(c1,c2,c3)
                  if i == self.selectedIndex:
                    if item.songCount == 1:
                      text = _("There Is 1 Song In This Setlist.")
                    elif item.songCount > 1:
                      text = _("There Are %d Songs In This Setlist.") % (item.songCount)
                    else:
                      text = ""
                elif isinstance(item, Song.TitleInfo):
                  text = _("Tier")
                  c1,c2,c3 = self.career_title_color
                  glColor3f(c1,c2,c3)
                elif isinstance(item, Song.CareerResetterInfo):
                  text = _("Reset this entire career")
                  c1,c2,c3 = self.career_title_color
                  glColor3f(c1,c2,c3)
                elif isinstance(item, Song.RandomSongInfo):
                  text = _("Random Song")
                  c1,c2,c3 = self.career_title_color
                  glColor3f(c1,c2,c3)
                
                if i == self.selectedIndex:
                  w, h = font.getStringSize(text)
                  font.render(text, (self.song_listcd_score_xpos, .085), scale = 0.0012)
                
                if i == self.selectedIndex:
                  glColor4f(.7,.5,.25,1)
                  if isinstance(item, Song.SongInfo) or isinstance(item, Song.RandomSongInfo):
                    c1,c2,c3 = self.song_name_selected_color
                    glColor3f(c1,c2,c3)
                  if isinstance(item, Song.LibraryInfo):
                    c1,c2,c3 = self.library_selected_color
                    glColor3f(c1,c2,c3)
                  if isinstance(item, Song.TitleInfo) or isinstance(item, Song.BlankSpaceInfo) or isinstance(item, Song.CareerResetterInfo):
                    c1,c2,c3 = self.career_title_color
                    glColor3f(c1,c2,c3)
                else:
                  glColor4f(0,0,0,1)
                  if isinstance(item, Song.SongInfo) or isinstance(item, Song.RandomSongInfo):
                    c1,c2,c3 = self.song_name_text_color
                    glColor3f(c1,c2,c3)
                  if isinstance(item, Song.LibraryInfo):
                    c1,c2,c3 = self.library_text_color
                    glColor3f(c1,c2,c3)
                  if isinstance(item, Song.TitleInfo) or isinstance(item, Song.CareerResetterInfo) or isinstance(item, Song.BlankSpaceInfo):
                    c1,c2,c3 = self.career_title_color
                    glColor3f(c1,c2,c3)
                    
                text = item.name
                
                if isinstance(item, Song.SongInfo) and item.getLocked():
                  text = _("-- Locked --")
                  
                if isinstance(item, Song.SongInfo): #MFH - add indentation when tier sorting
                  if self.tiersArePresent:
                    text = self.indentString + text
  
                # evilynux - Force uppercase display for Career titles
                if isinstance(item, Song.TitleInfo):
                  text = string.upper(text)
                  
                if isinstance(item, Song.CareerResetterInfo):
                  text = string.upper(text)
  
                if isinstance(item, Song.BlankSpaceInfo):
                  text = string.upper(text)
                  
                scale = font.scaleText(text, maxwidth = 0.45)
                w, h = font.getStringSize(text, scale = scale)

                font.render(text, (self.song_listcd_list_xpos, .09*(i+1)-pos[0]*.09), scale = scale) #add theme option for song_listCD_xpos
                
                if isinstance(item, Song.SongInfo) and not item.getLocked():
                  if not item.frets == "":
                    suffix = ", ("+item.frets+")"
                  else:
                    suffix = ""
                  
                  if not item.year == "":
                    yeartag = ", "+item.year
                  else:
                    yeartag = ""
                  
                  scale = .0014
                  glColor4f(.25,.5,1,1)
  
                  if i == self.selectedIndex:
                    c1,c2,c3 = self.artist_selected_color
                  else:
                    c1,c2,c3 = self.artist_text_color
                  glColor3f(c1,c2,c3)
  
                  # evilynux - Force uppercase display for artist name
                  text = string.upper(item.artist)+suffix+yeartag
  
                  # evilynux - automatically scale artist name and year
                  scale = font.scaleText(text, maxwidth = 0.4, scale = scale)
                  w, h = font.getStringSize(text, scale = scale)

                  font.render(text, (self.song_listcd_list_xpos + .05, .09*(i+1)-pos[0]*.09+.05), scale=scale) #add theme song_listCD_Xpos
            
                
                item  = self.items[self.selectedIndex]
                if self.matchesSearch(item):
                  if isinstance(item, Song.SongInfo):
                    angle = self.itemAngles[self.selectedIndex]
                    f = ((90.0 - angle) / 90.0) ** 2
        
                    Theme.setSelectedColor(1 - v)
                    
                    c1,c2,c3 = self.songlistcd_score_color
                    glColor3f(c1,c2,c3)
      
                    scale = 0.0013
                    w, h = font.getStringSize(self.prompt, scale = scale)
                    x = self.song_listcd_score_xpos
                    y = self.song_listcd_score_ypos + f / 2.0
                    try:
                      difficulties = item.partDifficulties[self.instrument.id]
                    except KeyError:
                      difficulties = []
                      score, stars, name = "---", 0, "---"
                    if len(difficulties) > 3:
                      y = self.song_listcd_score_ypos + f / 2.0
                    
                    #new
                    for d in difficulties:
                      #scores =  item.getHighscoresWithPartString(d, part = self.instrument)
                      scores =  item.getHighscores(d, part = self.instrument)
                      if scores:
                        score, stars, name, scoreExt = scores[0]
                        try:
                          notesHit, notesTotal, noteStreak, modVersion, handicap, handicapLong, originalScore = scoreExt
                        except ValueError:
                          notesHit, notesTotal, noteStreak, modVersion, oldScores1, oldScores2 = scoreExt
                          handicap = 0
                          handicapLong = "None"
                          originalScore = score
                      else:
                        score, stars, name = "---", 0, "---"
                      
                      font.render(Song.difficulties[d.id].text,     (x, y),           scale = scale) # akedrou: This is absolute nonsense, but needed for translation because of caching!
                      

                      starscale = 0.02
                      starx = x + starscale/2
                      stary = 1.0 - (y / self.engine.data.fontScreenBottom) - h - starscale
                      self.engine.drawStarScore(screenw, screenh, starx, stary, stars, starscale) #MFH

#-                      if stars == 7 and self.theme == 2:
#-                        glColor3f(.6, .6, .75)  
#-                        font.render(unicode(Data.STAR2 * (stars -1)), (x, y + h), scale = scale * 1.8)
#-                      elif stars == 7:
#-                        glColor3f(0, .75, 1)  
#-                        font.render(unicode(Data.STAR2 * (stars -1)), (x, y + h), scale = scale * 1.8)
#-                      if stars == 6 and self.theme == 2:
#-                        glColor3f(1, 1, 0)  
#-                        font.render(unicode(Data.STAR2 * (stars -1)), (x, y + h), scale = scale * 1.8)
#-                      elif stars == 6:
#-                        glColor3f(0, 1, 0)  
#-                        font.render(unicode(Data.STAR2 * (stars -1)), (x, y + h), scale = scale * 1.8)
#-                      else:
#-                        font.render(unicode(Data.STAR2 * stars + Data.STAR1 * (5 - stars)), (x, y + h), scale = scale * 1.8)
#-                      #Theme.setSelectedColor(1 - v)
                      
                                      
                      c1,c2,c3 = self.songlistcd_score_color
                      glColor3f(c1,c2,c3)
                      if scores:
                        if self.extraStats:
                          if notesTotal != 0:
                            score = "%s %.1f%%" % (score, (float(notesHit) / notesTotal) * 100.0)
                          if noteStreak != 0:
                            score = "%s (%d)" % (score, noteStreak)
                      font.render(unicode(score), (x + .15, y),     scale = scale)
                      font.render(name,       (x + .15, y + h),     scale = scale)
                      y += 2 * h + f / 4.0
              
        finally:
          text = self.instrument.text
          scale = 0.00250
          glColor3f(1, 1, 1)
          w, h = font.getStringSize(text, scale=scale)
          font.render(text, (0.95-w, 0.000), scale=scale)
          self.engine.view.resetProjection()
          nuttin = True

          
      elif self.display == 3:   #Qstick - rb2 Mode
        item  = self.items[self.selectedIndex]
        i = self.selectedIndex
        if self.itemLabels[i] == "Empty":   #added so that emptylabel.png is only loaded once and not on every empty song
          if self.emptyLabel != None:
            imgwidth = self.emptyLabel.width1()
            wfactor = 155.000/imgwidth
            self.engine.drawImage(self.emptyLabel, scale = (wfactor,-wfactor), coord = (.21*w,.59*h))
        elif self.itemLabels[i] == "Locked":   #added so that emptylabel.png is only loaded once and not on every empty song
          if self.lockedLabel != None:
            imgwidth = self.lockedLabel.width1()
            wfactor = 155.000/imgwidth
            self.engine.drawImage(self.lockedLabel, scale = (wfactor,-wfactor), coord = (.21*w,.59*h))
        elif self.itemLabels[i]:
          imgwidth = self.itemLabels[i].width1()
          wfactor = 155.000/imgwidth
          self.engine.drawImage(self.itemLabels[i], scale = (wfactor,-wfactor), coord = (.21*w,.59*h))

        self.engine.view.setOrthogonalProjection(normalize = True)
        font = self.engine.data.songListFont
        
        try:
          glEnable(GL_BLEND)
          glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
          glEnable(GL_COLOR_MATERIAL)
          Theme.setBaseColor(0)
          
          
          for i, item in enumerate(self.items):
            maxIndex = i
          if self.selectedIndex < 11 and maxIndex < 11:
            pos = self.selectedIndex - self.selectedIndex, self.selectedIndex + (11-self.selectedIndex)
            y = h*(.7825-(.0459*self.selectedIndex))
          elif self.selectedIndex == 0:#Selection is first item in list
            pos = (self.selectedIndex, self.selectedIndex +11)
            y = h*0.7825
          elif self.selectedIndex == 1:#Second item in list
            pos = (self.selectedIndex-1, self.selectedIndex+10)
            y = h*0.7365
          elif self.selectedIndex == 2:#Second item in list
            pos = (self.selectedIndex-2, self.selectedIndex+9)
            y = h*0.6909
          elif self.selectedIndex == 3:
            pos = (self.selectedIndex-3, self.selectedIndex+8)
            y = h*0.6447
          elif self.selectedIndex == 4:
            pos = (self.selectedIndex-4, self.selectedIndex+7)
            y = h*0.5988
          elif self.selectedIndex == 5:
            pos = (self.selectedIndex-5, self.selectedIndex+6)
            y = h*0.5529
          elif self.selectedIndex == maxIndex-4:
            pos = (self.selectedIndex-7, self.selectedIndex+4)
            y = h*0.4611
          elif self.selectedIndex == maxIndex-3:
            pos = (self.selectedIndex-8, self.selectedIndex+3)
            y = h*0.4152
          elif self.selectedIndex == maxIndex-2:
            pos = (self.selectedIndex-9, self.selectedIndex+2)
            y = h*0.3693
          elif self.selectedIndex == maxIndex-1:#Second to last item in list
            pos = (self.selectedIndex-10, self.selectedIndex+1)
            y = h*0.3234
          elif self.selectedIndex == maxIndex and not self.selectedIndex == 2:#Third to Last in list and not third item
            pos = (self.selectedIndex-11, self.selectedIndex)
            y = h*0.2775
          else:
            pos = (self.selectedIndex-6, self.selectedIndex+5)#Any other item than above
            y = h*0.507
            
            
          if self.tierbg != None:
            imgwidth = self.tierbg.width1()
            imgheight = self.tierbg.height1()
            wfactor = 381.1/imgwidth
            hfactor = 24.000/imgheight
          for i, item in enumerate(self.items):
            if i >= pos[0] and i <= pos[1]:
              if isinstance(item, Song.TitleInfo) or isinstance(item, Song.SortTitleInfo):
                if self.tierbg != None:
                  w, h, = self.engine.view.geometry[2:4]
                  self.engine.drawImage(self.tierbg, scale = (wfactor,-hfactor), coord = (w/1.587, h-((0.055*h)*(i+1)-pos[0]*(0.055*h))-(0.219*h)))


          imgwidth = self.selected.width1()
          imgheight = self.selected.height1()
          wfactor = 381.5/imgwidth
          hfactor = 36.000/imgheight

          self.engine.drawImage(self.selected, scale = (wfactor,-hfactor), coord = (w/1.587, y*1.2-h*.213))
          
          
          if self.diffimg1 != None:
            imgwidth = self.diffimg3.width1()
            imgheight = self.diffimg3.height1()
            wfactor1 = 13.0/imgwidth

          c1,c2,c3 = self.song_rb2_diff_color
          glColor3f(c1,c2,c3)
          
          font.render(_("DIFFICULTY"), (.095, .5325), scale = 0.0018)
          scale = 0.0014
          text = _("BAND")
          w, h = font.getStringSize(text, scale = scale)
          font.render(text, (.17 - w, .5585), scale = scale)
          text = _("GUITAR")
          w, h = font.getStringSize(text, scale = scale)
          font.render(text, (.17 - w, .5835), scale = scale)
          text = _("DRUM")
          w, h = font.getStringSize(text, scale = scale)
          font.render(text, (.17 - w, .6085), scale = scale)
          text = _("BASS")
          w, h = font.getStringSize(text, scale = scale)
          font.render(text, (.17 - w, .6335), scale = scale)
          text = _("VOCALS")
          w, h = font.getStringSize(text, scale = scale)
          font.render(text, (.17 - w, .6585), scale = scale)

          #Add support for lead and rhythm diff          

          #Qstick - Sorting Text
          text = _("SORTING:") + "     "
          if self.sortOrder == 0: #title
            text = text + _("ALPHABETICALLY BY TITLE")
          elif self.sortOrder == 1: #artist
            text = text + _("ALPHABETICALLY BY ARTIST")
          elif self.sortOrder == 2: #timesplayed
            text = text + _("BY PLAY COUNT")
          elif self.sortOrder == 3: #album
            text = text + _("ALPHABETICALLY BY ALBUM")
          elif self.sortOrder == 4: #genre
            text = text + _("ALPHABETICALLY BY GENRE")
          elif self.sortOrder == 5: #year
            text = text + _("BY YEAR")
          elif self.sortOrder == 6: #Band Difficulty
            text = text + _("BY BAND DIFFICULTY")
          elif self.sortOrder == 7: #Band Difficulty
            text = text + _("BY INSTRUMENT DIFFICULTY")
          else:
            text = text + _("BY SONG COLLECTION")
            
          font.render(text, (.13, .152), scale = 0.0017)

          if self.searchText:
            text = _("Filter: %s") % (self.searchText) + "|"
            if not self.matchesSearch(self.items[self.selectedIndex]):
              text += " (%s)" % _("Not found")
            font.render(text, (.05, .7 + v), scale = 0.001)
          elif self.songLoader:
            font.render(_("Loading Preview..."), (.05, .7 + v), scale = 0.001)
          
          for i, item in enumerate(self.items):
            if i >= pos[0] and i <= pos[1]:

              if isinstance(item, Song.SongInfo):
                if self.songIcons:    
                  if item.icon != "":
                    iconNum = None
                    try:
                      iconNum = self.itemIconNames.index(item.icon)
                      imgwidth = self.itemIcons[iconNum].width1()
                      wfactor = 23.000/imgwidth
                      w, h, = self.engine.view.geometry[2:4]
                      self.engine.drawImage(self.itemIcons[iconNum], scale = (wfactor,-wfactor), coord = (w/2.86, h-((0.055*h)*(i+1)-pos[0]*(0.055*h))-(0.219*h)))
                    except ValueError:
                      iconNum = -1
                
                c1,c2,c3 = self.song_name_selected_color
                glColor3f(c1,c2,c3)
                if i == self.selectedIndex:
                  if item.getLocked():
                    text = item.getUnlockText()
                  elif self.careerMode and not item.completed:
                    text = _("Play To Advance")
                  elif self.gameMode1p == 1: #evilynux - Practice mode
                    text = _("Practice")
                  elif item.count:
                    count = int(item.count)
                    if count == 1: 
                      text = _("Played Once")
                    else:
                      text = _("Played %d times.") % count
                  else:
                    text = _("Quickplay")
              elif isinstance(item, Song.LibraryInfo):
                c1,c2,c3 = self.library_selected_color
                glColor3f(c1,c2,c3)
                if i == self.selectedIndex:
                  if item.songCount == 1:
                    text = _("There Is 1 Song In This Setlist.")
                  elif item.songCount > 1:
                    text = _("There Are %d Songs In This Setlist.") % (item.songCount)
                  else:
                    text = ""
              elif isinstance(item, Song.TitleInfo) or isinstance(item, Song.SortTitleInfo):
                text = _("Tier")
                c1,c2,c3 = self.career_title_color
                glColor3f(c1,c2,c3)
                

              elif isinstance(item, Song.CareerResetterInfo):
                text = _("Reset this entire career")
                c1,c2,c3 = self.career_title_color
                glColor3f(c1,c2,c3)
                
              elif isinstance(item, Song.RandomSongInfo):
                text = _("Random Song")
                c1,c2,c3 = self.career_title_color
                glColor3f(c1,c2,c3)
              
              if i == self.selectedIndex:
                w, h = font.getStringSize(text, scale = 0.0012)
                font.render(text, (0.92-w, .13), scale = 0.0012)
              
              maxwidth = .45
              if i == self.selectedIndex:
                glColor4f(.7,.5,.25,1)
                if isinstance(item, Song.SongInfo) or isinstance(item, Song.LibraryInfo) or isinstance(item, Song.RandomSongInfo):
                  c1,c2,c3 = self.song_rb2_name_selected_color
                  glColor3f(c1,c2,c3)
                if isinstance(item, Song.TitleInfo) or isinstance(item, Song.SortTitleInfo) or isinstance(item, Song.CareerResetterInfo) or isinstance(item, Song.BlankSpaceInfo):
                  c1,c2,c3 = self.career_title_color
                  glColor3f(c1,c2,c3)
              else:
                glColor4f(0,0,0,1)
                if isinstance(item, Song.SongInfo) or isinstance(item, Song.LibraryInfo):
                  c1,c2,c3 = self.song_rb2_name_color
                  glColor3f(c1,c2,c3)
                if isinstance(item, Song.TitleInfo) or isinstance(item, Song.SortTitleInfo) or isinstance(item, Song.CareerResetterInfo) or isinstance(item, Song.BlankSpaceInfo):
                  c1,c2,c3 = self.career_title_color
                  glColor3f(c1,c2,c3)
                if isinstance(item, Song.RandomSongInfo):
                  c1,c2,c3 = self.song_name_text_color
                  glColor3f(c1,c2,c3)
              
              text = item.name
              
              if isinstance(item, Song.SongInfo) and item.getLocked():
                text = _("-- Locked --")
                
              if isinstance(item, Song.SongInfo): #MFH - add indentation when tier sorting
                if self.tiersArePresent or self.songIcons:
                  text = self.indentString + text
                

              # evilynux - Force uppercase display for Career titles
              if isinstance(item, Song.TitleInfo) or isinstance(item, Song.SortTitleInfo):
                maxwidth = .55
                
              if isinstance(item, Song.TitleInfo) or isinstance(item, Song.SortTitleInfo) or isinstance(item, Song.CareerResetterInfo) or isinstance(item, Song.BlankSpaceInfo):
                text = string.upper(text)
                
              scale = .0015
              w, h = font.getStringSize(text, scale = scale)

              while w > maxwidth:
                tlength = len(text) - 4
                text = text[:tlength] + "..."
                w, h = font.getStringSize(text, scale = scale)
                if w < .45:
                  break
                
                
              font.render(text, (.35, .0413*(i+1)-pos[0]*.0413+.15), scale = scale) #add theme option for song_listCD_xpos

              if isinstance(item, Song.SongInfo):
                if self.scoreTimer == 0 and self.highScoreType == 0: #racer: regular-style highscore movement
                  self.diff = Song.difficulties[(self.diff.id-1)%len(Song.difficulties)]
                
                #racer: score can be changed by fret button:
                #MFH - and now they will be remembered as well
                if self.highScoreChange == True and self.highScoreType == 1:
                  self.diff = Song.difficulties[(self.diff.id-1)%len(Song.difficulties)]
                  self.engine.config.set("game", "songlist_difficulty", self.diff.id)
                  self.highScoreChange = False

                if not (item.getLocked()):
                  score = _("Nil")
                  stars = 0
                  name = ""

                  try:
                    difficulties = item.partDifficulties[self.instrument.id]
                  except KeyError:
                    difficulties = []
                  for d in difficulties:
                    if d.id == self.diff.id:
                      scores = item.getHighscores(d, part = self.instrument)
                      if scores:
                        score, stars, name, scoreExt = scores[0]
                        try:
                          notesHit, notesTotal, noteStreak, modVersion, handicap, handicapLong, originalScore = scoreExt
                        except ValueError:
                          notesHit, notesTotal, noteStreak, modVersion, oldScores1, oldScores2 = scoreExt
                          handicap = 0
                          handicapLong = "None"
                          originalScore = score
                      else:
                        score, stars, name = 0, 0, "---"
                  
                  if score == _("Nil") and self.NilShowNextScore:   #MFH
                    for d in difficulties:   #MFH - just take the first valid difficulty you can find and display it.
                      scores = item.getHighscores(d, part = self.instrument)
                      if scores:
                        score, stars, name, scoreExt = scores[0]
                        try:
                          notesHit, notesTotal, noteStreak, modVersion, handicap, handicapLong, originalScore = scoreExt
                        except ValueError:
                          notesHit, notesTotal, noteStreak, modVersion, oldScores1, oldScores2 = scoreExt
                          handicap = 0
                          handicapLong = "None"
                          originalScore = score
                        break
                      else:
                        score, stars, name = 0, 0, "---"
  
                  scale = 0.0014
                  #evilynux - hit% and note streak if enabled
                  if self.extraStats:
                    scale = 0.0009
                    if score is not _("Nil") and score > 0 and notesTotal != 0:
                      text = "%.1f%% (%d)" % ((float(notesHit) / notesTotal) * 100.0, noteStreak)
                      w, h = font.getStringSize(text, scale=scale)
                      font.render(text, (.92-w, .0413*(i+1)-pos[0]*.0413+.163), scale=scale)
                        
                  text = str(score)
                  w, h = font.getStringSize(text, scale=scale)
                  
                  font.render(text, (.92-w, .0413*(i+1)-pos[0]*.0413+.15), scale=scale)
  
                  if self.scoreTimer < 1000:
                    self.scoreTimer += 1
                  else:
                    self.scoreTimer = 0
                    
                  if i == self.selectedIndex:
                    text = item.artist
                    if (item.getLocked()):
                      text = "" # avoid giving away artist of locked song
  
                    scale = 0.0015
                    w, h = font.getStringSize(text, scale=scale)
                    
                    while w > .21:
                      tlength = len(text) - 4
                      text = text[:tlength] + "..."
                      w, h = font.getStringSize(text, scale = scale)
                      if w < .22:
                        break
                      
                    c1,c2,c3 = self.song_rb2_artist_color
                    glColor3f(c1,c2,c3)
                    
                    text = string.upper(text)
                    font.render(text, (.095, .44), scale = scale)
                    
                    albumtag = item.album
                      
                    albumtag = string.upper(albumtag)
                    w, h = font.getStringSize(albumtag, scale=scale)
                    
                    while w > .21:
                      tlength = len(albumtag) - 4
                      albumtag = albumtag[:tlength] + "..."
                      w, h = font.getStringSize(albumtag, scale = scale)
                      if w < .22:
                        break                    
  
                    font.render(albumtag, (.095, .47), scale = 0.0015)
                    
                    genretag = item.genre
                    font.render(genretag, (.095, .49), scale = 0.0015)                                
  
                    yeartag = item.year           
                    font.render(yeartag, (.095, .51), scale = 0.0015)

                 
                    for i in range(5):
                      glColor3f(1, 1, 1) 
                      if i == 0:
                        diff = item.diffSong
                      elif i == 1:
                        diff = item.diffGuitar
                      elif i == 2:
                        diff = item.diffDrums
                      elif i == 3:
                        diff = item.diffBass
                      elif i == 4:
                        diff = item.diffVocals
                      if self.diffimg1 == None:
                        if diff == -1:
                          font.render("N/A", (.18, .5585 + i*.025), scale = 0.0014)
                        elif diff == 6:
                          glColor3f(1, 1, 0)  
                          font.render(str(Data.STAR2 * (diff -1)), (.18, 0.5685 + i*.025), scale = 0.003)
                        else:
                          font.render(str(Data.STAR2 * diff + Data.STAR1 * (5 - diff)), (.18, 0.5685 + i*.025), scale = 0.003)
                      else:
                        w, h, = self.engine.view.geometry[2:4]
                        if diff == -1:
                          font.render("N/A", (.18, .5585 + i*.025), scale = 0.0014)
                        elif diff == 6:
                          for k in range(0,5):
                            self.engine.drawImage(self.diffimg3, scale = (wfactor1,-wfactor1), coord = ((.19+.03*k)*w, (0.2354-.0333*i)*h))
                        else:
                          for k in range(0,diff):
                            self.engine.drawImage(self.diffimg2, scale = (wfactor1,-wfactor1), coord = ((.19+.03*k)*w, (0.2354-.0333*i)*h))
                          for k in range(0, 5-diff):
                            self.engine.drawImage(self.diffimg1, scale = (wfactor1,-wfactor1), coord = ((.31-.03*k)*w, (0.2354-.0333*i)*h))
           
        finally:
          text = self.instrument.text + " - " + self.diff.text
          scale = 0.0017
          glColor3f(1, 1, 1)
          w, h = font.getStringSize(text, scale=scale)
          font.render(text, (0.92-w, 0.152), scale=scale)
          self.engine.view.resetProjection()
          nuttin = True
          
class FileChooser(BackgroundLayer, KeyListener):
  """File choosing layer."""
  def __init__(self, engine, masks, path, prompt = "", dirSelect = False):
    self.masks          = masks
    self.path           = path
    self.prompt         = prompt
    self.engine         = engine
    self.accepted       = False
    self.selectedFile   = None
    self.time           = 0.0
    self.menu           = None

    self.logClassInits = self.engine.config.get("game", "log_class_inits")
    if self.logClassInits == 1:
      Log.debug("FileChooser class init (Dialogs.py)...")
    

    self.dirSelect      = dirSelect
    self.spinnyDisabled = self.engine.config.get("game", "disable_spinny")

    #Get theme
    themename = self.engine.data.themeLabel
    #now theme determination logic is only in data.py:
    self.theme = self.engine.data.theme

   #MFH - added simple black background to place in front of Options background, behind Neck BG, for transparent neck displays
    try:
      self.engine.loadImgDrawing(self, "neckBlackBack", ("neckblackback.png"))
    except IOError:
      self.neckBlackBack = None


    self.engine.loadImgDrawing(self, "background", os.path.join("themes",themename,"editor.png"))
    
  def _getFileCallback(self, fileName):
    return lambda: self.chooseFile(fileName)

  def _getFileText(self, fileName):
    f = os.path.join(self.path, fileName)
    if fileName == "..":
      return _("[Parent Folder]")
    if self.dirSelect == True:
      for mask in self.masks:
        if fnmatch.fnmatch(fileName, mask):
          return _("[Accept Folder]")
    if os.path.isdir(f):
      return _("%s [Folder]") % fileName
    return fileName

  def getFiles(self):
    files = [".."]
    for fn in os.listdir(self.path):
      if fn.startswith("."): continue
      f = os.path.join(self.path, fn)
      for mask in self.masks:
        if fnmatch.fnmatch(fn, mask):
          break
      else:
        if not os.path.isdir(f):
          continue
      files.append(fn)
    files.sort()
    if self.dirSelect == True and (fnmatch.fnmatch(self.path, self.masks[0])):
      files.insert(0, self.path)
    return files

  def getDisks(self):
    import win32file, string
    driveLetters=[]
    for drive in string.letters[len(string.letters) / 2:]:
      if win32file.GetDriveType(drive + ":") == win32file.DRIVE_FIXED:
        driveLetters.append(drive + ":\\")
    return driveLetters
  
  def updateFiles(self):
    if self.menu:
      self.engine.view.popLayer(self.menu)

    if self.path == "toplevel" and os.name != "nt":
      self.path = "/"
      
    if self.path == "toplevel":
      self.menu = Menu(self.engine, choices = [(self._getFileText(f), self._getFileCallback(f)) for f in self.getDisks()], onClose = self.close, onCancel = self.cancel)
    else:
      self.menu = Menu(self.engine, choices = [(self._getFileText(f), self._getFileCallback(f)) for f in self.getFiles()], onClose = self.close, onCancel = self.cancel)
    self.engine.view.pushLayer(self.menu)

  def chooseFile(self, fileName):
    if self.dirSelect == True:
      for mask in self.masks:
        if fnmatch.fnmatch(fileName, mask):
          self.selectedFile = fileName
          accepted = True
          self.engine.view.popLayer(self.menu)
          self.engine.view.popLayer(self)
          self.menu = None
          return

    if self.path == "toplevel":
      self.path = ""
    path = os.path.abspath(os.path.join(self.path, fileName))

    if os.path.isdir(path):

      if path == self.path and fileName == "..":
        self.path = "toplevel"
      else:
        self.path = path
      self.updateFiles()
      return
    self.selectedFile = path
    accepted = True
    self.engine.view.popLayer(self.menu)
    self.engine.view.popLayer(self)
    self.menu = None
    
  def cancel(self):
    self.accepted = True
    self.engine.view.popLayer(self)

  def close(self):
    if not self.menu:
      self.accepted = True
      self.engine.view.popLayer(self)
    
  def shown(self):
    self.updateFiles()
    
  def getSelectedFile(self):
    return self.selectedFile
  
  def run(self, ticks):
    self.time += ticks / 50.0
    
  def render(self, visibility, topMost):
    v = (1 - visibility) ** 2

    # render the background

    t = self.time / 100
    self.engine.view.setViewport(1,0)
    w, h, = self.engine.view.geometry[2:4]
    r = .5

    #MFH - draw neck black BG in for transparent areas (covers options BG):
    if self.neckBlackBack != None:
      #MFH - auto background scaling 
      imgwidth = self.neckBlackBack.width1()
      wfactor = 640.000/imgwidth
      self.engine.drawImage(self.neckBlackBack, scale = (wfactor,-wfactor), coord = (w/2,h/2))


    #MFH - auto background scaling 
    imgwidth = self.background.width1()
    wfactor = 640.000/imgwidth
    self.engine.drawImage(self.background, scale = (wfactor,-wfactor), coord = (w/2,h/2))


      
    self.engine.view.setOrthogonalProjection(normalize = True)
    font = self.engine.data.font
    
    try:
      glEnable(GL_BLEND)
      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
      glEnable(GL_COLOR_MATERIAL)
      Theme.setBaseColor(1 - v)
      wrapText(font, (.1, .05 - v), self.prompt)
    finally:
      self.engine.view.resetProjection()

#==============================================================
#MFH - on-demand Neck Select menu
class NeckChooser(Layer, KeyListener):
  """Item menu layer."""
  def __init__(self, engine, selected = None, prompt = _("Yellow (#3) / Blue (#4) to change, Green (#1) to confirm:"), player = "default", owner = None):
    self.prompt   = prompt
    self.prompt_x = Theme.neck_prompt_x
    self.prompt_y = Theme.neck_prompt_y
    self.engine   = engine
    self.player   = player
    self.owner    = owner

    self.logClassInits = self.engine.config.get("game", "log_class_inits")
    if self.logClassInits == 1:
      Log.debug("%s NeckChooser class init (Dialogs.py)..." % (self.player))
    
    splash = showLoadingSplashScreen(self.engine, _("Loading necks..."))

    self.neck = []
    self.necks = ["2none", "none"]
    self.maxNeck = 0
    
    defaultNeck = self.engine.config.get("game", "default_neck")
    self.selectedNeck = 0
    for i, name in enumerate(Player.playername):
      if name == player:
        playerNeck = Player.playerpref[i][6]
        if playerNeck == "":
          playerNeck = defaultNeck
        break
    else:
      playerNeck = defaultNeck

    # evilynux - improved loading logic to support arbitrary filenames
    #          - os.listdir is not guaranteed to return a sorted list, so sort it!
    neckfiles = os.listdir(self.engine.resource.fileName("necks"))
    neckfiles.sort()

    for i in neckfiles:   #MFH - first go through and find the random neck
      if ( str(i) == "randomneck.png"  or str(i) == "Neck_0.png" ):    #MFH 
        randomNeck = i
        #exists = 1
        
        try:
          neckImage = engine.loadImgDrawing(self, "neck"+str(i), os.path.join("necks",str(i)))
          # evilynux - Warning, Thumbs.db won't fail at engine.loadImgDrawing
  
        except IOError:
          exists = 0
          break

        if neckImage is None:
          exists = 0
        else:
          exists = 1
  
        if exists == 1:
          self.neck.append(str(i)[:-4]) # evilynux - filename w/o extension
          self.necks.append(neckImage)


    for i in neckfiles:
      # evilynux - Special cases, ignore these...
      #if( str(i) == "overdriveneck.png" or str(i)[-4:] != ".png" ):
      #exists = 1
      #if( str(i) == "overdriveneck.png" or not i.endswith(".png") ):
      if( str(i) == "overdriveneck.png" or str(i) == "randomneck.png"  or str(i) == "Neck_0.png" or str(i)[-4:] != ".png" ):    #MFH 
        exists = 0
        continue
      try:
        neckImage = engine.loadImgDrawing(self, "neck"+str(i), os.path.join("necks",str(i)))
        # evilynux - Warning, Thumbs.db won't fail at engine.loadImgDrawing

      except IOError:
        exists = 0
        break
      else:
        # evilynux - Warning, pseudo valid images like Thumbs.db won't fail - we need to catch those bastards
        if neckImage is None:
         exists = 0
        else:
         exists = 1

      if exists == 1:
        self.neck.append(str(i)[:-4]) # evilynux - filename w/o extension
        self.necks.append(neckImage)
        self.maxNeck += 1
    self.maxNeck -= 1 # evilynux - confusing, but there's an offset of -1
    Config.define("player",   "neck",  str,  0,  text = _("Neck"), options = self.neck)
    
    for i, neck in enumerate(self.neck):
      if neck == playerNeck:
        self.selectedNeck = i
        break
    else:
      for i, neck in enumerate(self.neck):
        if neck == defaultNeck:
          self.selectedNeck = i
      else:
        self.selectedNeck = 0

    self.necks.append("none")
    self.necks.append("2none")
    
    self.accepted       = False
    self.time           = 0.0
    

    #Get theme
    self.themename = self.engine.data.themeLabel
    self.theme = self.engine.data.theme

   #MFH - added simple black background to place in front of Options background, behind Neck BG, for transparent neck displays
    try:
      self.engine.loadImgDrawing(self, "neckBlackBack", ("neckblackback.png"))
    except IOError:
      self.neckBlackBack = None

   
   
    self.engine.loadImgDrawing(self, "neckBG", os.path.join("themes",self.themename,"menu","neckchoosebg.png"))
    self.engine.loadImgDrawing(self, "neckSelect", os.path.join("themes",self.themename,"menu","neckchooseselect.png"))

    # ready... hide the splash screen
    hideLoadingSplashScreen(self.engine, splash)
    splash = None
    
  def shown(self):
    self.engine.input.addKeyListener(self, priority = True)
  
  def hidden(self):
    self.engine.input.removeKeyListener(self)
    
  def chooseNeck(self):
    #self.selectedNeck = neck
    if self.player == "default":
      self.engine.config.set("game","default_neck",self.neck[self.selectedNeck])
    if self.owner: #rather hard-coded...
      if self.player != "default":
        self.owner.neck  = self.neck[self.selectedNeck]
    self.engine.view.popLayer(self)
    
  def cancel(self):
    self.accepted = False
    self.engine.view.popLayer(self)
  
  def keyPressed(self, key, unicode):
    c = self.engine.input.controls.getMapping(key)
    if c in Player.key1s or key == pygame.K_RETURN:
      self.chooseNeck()
    elif c in Player.key2s + Player.cancels or key == pygame.K_ESCAPE:
      self.cancel()
    elif c in Player.key3s + Player.ups + Player.action1s + Player.lefts or key == pygame.K_UP or key == pygame.K_LEFT:
      self.selectedNeck -= 1
      if self.selectedNeck < 0:
        self.selectedNeck = len(self.neck) - 1
    elif c in Player.key4s + Player.downs + Player.action2s + Player.rights or key == pygame.K_DOWN or key == pygame.K_RIGHT:
      self.selectedNeck += 1
      if self.selectedNeck >= len(self.neck):
        self.selectedNeck = 0
    return True
  
  def keyReleased(self, key):
    return
  
  def getSelectedNeck(self):
    return self.selectedNeck
  
  def run(self, ticks):
    self.time += ticks / 50.0
    
  def render(self, visibility, topMost):
   v = (1 - visibility) ** 2
   # render the background
   t = self.time / 100
   self.engine.view.setViewport(1,0)
   w, h, = self.engine.view.geometry[2:4]
   r = .5


   #MFH - draw neck black BG in for transparent necks (covers options BG):
   if self.neckBlackBack != None:
     #MFH - auto background scaling
     imgwidth = self.neckBlackBack.width1()
     wfactor = 640.000/imgwidth
     self.engine.drawImage(self.neckBlackBack, scale = (wfactor,-wfactor), coord = (w/2,h/2))

   currentNeck = self.necks[int(self.selectedNeck)+2]
   lastNeck1 = self.necks[int(self.selectedNeck)]
   if lastNeck1 == "none":
     lastNeck1 = self.necks[self.maxNeck+2]
   elif lastNeck1 == "2none":
     lastNeck1 = self.necks[self.maxNeck+1]
   lastNeck = self.necks[int(self.selectedNeck)+1]
   if lastNeck == "none":
     lastNeck = self.necks[self.maxNeck+2]

   nextNeck = self.necks[int(self.selectedNeck)+3]
   if nextNeck == "none":
     nextNeck = self.necks[2]
     
   nextNeck1 = self.necks[int(self.selectedNeck)+4]
   if nextNeck1 == "none":
     nextNeck1 = self.necks[2]
   elif nextNeck1 == "2none":
     nextNeck1 = self.necks[3]

   if self.theme == 2:
     self.x1 = w*0.067
     self.x2 = w*0.187
     self.x3 = w*0.307
     self.x4 = w*0.427
     self.x5 = w*0.547
     self.x6 = w*0.296
     self.y1 = h*0.420
     self.y2 = h*0.420
     self.y3 = h*0.420
     self.y4 = h*0.420
     self.y5 = h*0.420
     self.y6 = h*0.420
     self.wfac = 192.000
     self.wfac2 = 62.000  
   else:
     self.x1 = w*0.05
     self.x2 = w*0.175
     self.x3 = w*0.296
     self.x4 = w*0.42
     self.x5 = w*0.539
     self.x6 = w*0.296
     self.y1 = h*0.420
     self.y2 = h*0.554
     self.y3 = h*0.415
     self.y4 = h*0.554
     self.y5 = h*0.402
     self.y6 = h*0.423
     self.wfac = 187.000
     self.wfac2 = 64.000



   wfactor = currentNeck.widthf(pixelw = self.wfac)
   if self.theme != 2:
     neckcoord = (w/1.31,h/2)
   else:
     neckcoord = (w/1.22,h/2)
   self.engine.drawImage(currentNeck, scale = (-wfactor,wfactor), coord = neckcoord)
   

   wfactor = lastNeck1.widthf(pixelw = self.wfac2)
   self.engine.drawImage(lastNeck1, scale = (-wfactor,wfactor), coord = (self.x1,self.y1))
   wfactor = lastNeck.widthf(pixelw = self.wfac2)
   self.engine.drawImage(lastNeck, scale = (-wfactor,wfactor), coord = (self.x2,self.y2))
   wfactor = currentNeck.widthf(pixelw = self.wfac2)
   self.engine.drawImage(currentNeck, scale = (-wfactor,wfactor), coord = (self.x3,self.y3))
   wfactor = nextNeck.widthf(pixelw = self.wfac2)
   self.engine.drawImage(nextNeck, scale = (-wfactor,wfactor), coord = (self.x4,self.y4))   
   wfactor = nextNeck1.widthf(pixelw = self.wfac2)
   self.engine.drawImage(nextNeck1, scale = (-wfactor,wfactor), coord = (self.x5,self.y5))
   
   if self.selectedNeck:
     self.engine.drawImage(self.neckSelect, scale = (-1,1), coord = (self.x6, self.y6))

   #MFH - draw neck BG on top of necks
   #MFH - auto background scaling
   imgwidth = self.neckBG.width1()
   wfactor = 640.000/imgwidth
   self.engine.drawImage(self.neckBG, scale = (wfactor,-wfactor), coord = (w/2,h/2))

  
   self.engine.view.setOrthogonalProjection(normalize = True)
   font = self.engine.data.font
   
   try:
     glEnable(GL_BLEND)
     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
     glEnable(GL_COLOR_MATERIAL)
     Theme.setBaseColor(1 - v)
     wrapText(font, (self.prompt_x, self.prompt_y - v), self.prompt)
   finally:
     self.engine.view.resetProjection()
   #==============================================================

    
    
class AvatarChooser(Layer, KeyListener):
  """Avatar choosing layer"""
  def __init__(self, engine):
    self.engine   = engine

    self.logClassInits = self.engine.config.get("game", "log_class_inits")
    if self.logClassInits == 1:
      Log.debug("AvatarChooser class init (Dialogs.py)...")
    
    splash = showLoadingSplashScreen(self.engine, _("Loading avatars..."))
    
    #Get theme
    self.themename = self.engine.data.themeLabel
    self.theme = self.engine.data.theme
    
    self.avatar = []
    self.avatars = []
    self.maxAv = 0
    self.themeAvs = 0
    
    self.selectedAv = 0
    
    self.scrolling = 0
    self.delay     = 0
    self.rate      = 0
    self.scroller  = [0, self.scrollUp, self.scrollDown]

    # evilynux - improved loading logic to support arbitrary filenames
    #          - os.listdir is not guaranteed to return a sorted list, so sort it!
    avatarfiles = os.listdir(self.engine.resource.fileName("avatars"))
    avatarfiles.sort()
    
    themeavatarfiles = []
    if os.path.exists(self.engine.resource.fileName(os.path.join("themes",self.themename,"avatars"))):
      themeavatarfiles = os.listdir(self.engine.resource.fileName(os.path.join("themes",self.themename,"avatars")))
    themeavatarfiles.sort()
    
    for i in themeavatarfiles:
      if str(i).lower()[-4:] != ".png":
        continue
      try:
        image = engine.loadImgDrawing(self, "av"+str(i), os.path.join("themes",self.themename,"avatars",str(i)))

      except IOError:
        exists = 0
        break
      else:
        # evilynux - Warning, pseudo valid images like Thumbs.db won't fail - we need to catch those bastards
        if image is None:
         exists = 0
        else:
         exists = 1

      if exists == 1:
        self.avatar.append(str(i)[:-4]) # evilynux - filename w/o extension
        self.avatars.append(image)
        self.maxAv += 1
    self.themeAvs = len(self.avatars)
    for i in avatarfiles:
      if str(i).lower()[-4:] != ".png":
        continue
      try:
        image = engine.loadImgDrawing(self, "av"+str(i), os.path.join("avatars",str(i)))

      except IOError:
        exists = 0
        break
      else:
        # evilynux - Warning, pseudo valid images like Thumbs.db won't fail - we need to catch those bastards
        if image is None:
         exists = 0
        else:
         exists = 1

      if exists == 1:
        self.avatar.append(str(i)[:-4]) # evilynux - filename w/o extension
        self.avatars.append(image)
        self.maxAv += 1
    Log.debug("%d Theme Avatars found; %d total." % (self.themeAvs, len(self.avatars)))
    self.avScale = []
    for avatar in self.avatars:
      imgheight = avatar.height1()
      imgwidth  = avatar.width1()
      hFactor = 110.00/imgheight
      wFactor = 178.00/imgwidth
      self.avScale.append(min(hFactor, wFactor))
    self.maxAv -= 1 # evilynux - confusing, but there's an offset of -1
    
    self.accepted       = False
    self.time           = 0.0
    self.dist           = 1.0
    

    #MFH - added simple black background to place in front of Options background, behind Neck BG, for transparent neck displays
    try:
      self.engine.loadImgDrawing(self, "avFrame", os.path.join("themes",self.themename,"lobby","avatarframe.png"))
    except IOError:
      self.avFrame = None
    
    try:
      self.engine.loadImgDrawing(self, "avSelFrame", os.path.join("themes",self.themename,"lobby","avatarselectframe.png"))
    except IOError:
      self.avSelFrame = self.avFrame
    
    try:
      self.engine.loadImgDrawing(self, "avBigFrame", os.path.join("themes",self.themename,"lobby","avatarmainframe.png"))
    except IOError:
      self.avBigFrame = self.avFrame
    
    try:
      self.engine.loadImgDrawing(self, "avText", os.path.join("themes",self.themename,"lobby","avatartext.png"))
    except IOError:
      self.avText = None
    
    self.avFrameScale = None
    if self.avFrame:
      imgheight = self.avFrame.height1()
      imgwidth  = self.avFrame.width1()
      hFactor = 110.00/imgheight
      wFactor = 178.00/imgwidth
      self.avFrameScale = (wFactor, -hFactor)
    
    self.avSelFrameScale = None
    if self.avSelFrame:
      imgheight = self.avSelFrame.height1()
      imgwidth  = self.avSelFrame.width1()
      hFactor = 110.00/imgheight
      wFactor = 178.00/imgwidth
      self.avSelFrameScale = (wFactor, -hFactor)
    
    self.avBigFrameScale = None
    if self.avBigFrame:
      imgheight = self.avBigFrame.height1()
      imgwidth  = self.avBigFrame.width1()
      hFactor = 110.00/imgheight
      wFactor = 178.00/imgwidth
      self.avBigFrameScale = (wFactor, -hFactor)
    
    self.avatarText = _("Select Your Avatar:")
    
    try:
      self.engine.loadImgDrawing(self, "background", os.path.join("themes",self.themename,"lobby","avatarbg.png"))
    except IOError:
      self.background = None

    hideLoadingSplashScreen(self.engine, splash)
    splash = None
    
  def shown(self):
    self.engine.input.addKeyListener(self, priority = True)
  
  def hidden(self):
    self.engine.input.removeKeyListener(self)
    
  def cancel(self):
    self.accepted = False
    self.engine.view.popLayer(self)
  
  def keyPressed(self, key, unicode):
    c = self.engine.input.controls.getMapping(key)
    if c in Player.key1s or key == pygame.K_RETURN:
      self.accepted = True
      self.engine.data.acceptSound.play()
      self.engine.view.popLayer(self)
    elif c in Player.key2s + Player.cancels or key == pygame.K_ESCAPE:
      self.engine.data.cancelSound.play()
      self.cancel()
    elif c in Player.key3s + Player.ups + Player.action1s + Player.lefts or key == pygame.K_UP or key == pygame.K_LEFT:
      self.scrolling = 1
      self.delay = self.engine.scrollDelay
      self.scrollUp()
    elif c in Player.key4s + Player.downs + Player.action2s + Player.rights or key == pygame.K_DOWN or key == pygame.K_RIGHT:
      self.scrolling = 2
      self.delay = self.engine.scrollDelay
      self.scrollDown()
    return True
    
  def scrollUp(self):
    self.engine.data.selectSound.play()
    self.selectedAv -= 1
    if self.selectedAv < 0:
      self.selectedAv = len(self.avatars) - 1
  
  def scrollDown(self):
    self.engine.data.selectSound.play()
    self.selectedAv += 1
    if self.selectedAv >= len(self.avatars):
      self.selectedAv = 0
    
  def keyReleased(self, key):
    self.scrolling = 0
  
  def getAvatar(self):
    if self.accepted:
      t = self.selectedAv < self.themeAvs and os.path.join("themes",self.themename,"avatars",self.avatar[self.selectedAv]+".png") or os.path.join("avatars",self.avatar[self.selectedAv]+".png")
      return t
    else:
      return None
  
  def run(self, ticks):
    self.time += ticks / 50.0
    if self.dist > 0:
      self.dist -= ticks / 750.0
      if self.dist < 0:
        self.dist = 0
    if self.scrolling > 0:
      self.delay -= ticks
      self.rate += ticks
      if self.delay <= 0 and self.rate >= self.engine.scrollRate:
        self.rate = 0
        self.scroller[self.scrolling]()
    
  def render(self, visibility, topMost):
    v = (1 - visibility) ** 2
    t = self.time / 100
    self.engine.view.setViewport(1,0)
    self.engine.view.setOrthogonalProjection(normalize = True)
    w, h, = self.engine.view.geometry[2:4]
    
    try:
      if self.background:
        wFactor = 640.000/self.background.width1()
        self.engine.drawImage(self.background, scale = (wFactor, -wFactor), coord = (w/2,h/2))
      else:
        fadeScreen(v)
      Theme.setBaseColor(1 - v)
      if len(self.avatars) > 1:
        lastAv2i  = (int(self.selectedAv)-2) % len(self.avatars)
        lastAvi   = (int(self.selectedAv)-1) % len(self.avatars)
        nextAvi   = (int(self.selectedAv)+1) % len(self.avatars)
        nextAv2i  = (int(self.selectedAv)+2) % len(self.avatars)
      else:
        lastAv2i  = 0
        lastAvi   = 0
        nextAvi   = 0
        nextAv2i  = 0
      lastAv2   = self.avatars[lastAv2i]
      lastAv    = self.avatars[lastAvi]
      currentAv = self.avatars[int(self.selectedAv)]
      nextAv    = self.avatars[nextAvi]
      nextAv2   = self.avatars[nextAv2i]
      
      self.x1 = w*(0.07-self.dist/2)
      self.x2 = w*(0.17-self.dist/2)
      self.x3 = w*(0.24-self.dist/2)
      self.x4 = w*(0.17-self.dist/2)
      self.x5 = w*(0.07-self.dist/2)
      self.y1 = h*(0.75+Theme.avatarSelectWheelY)
      self.y2 = h*(0.68+Theme.avatarSelectWheelY)
      self.y3 = h*(0.5+Theme.avatarSelectWheelY)
      self.y4 = h*(0.32+Theme.avatarSelectWheelY)
      self.y5 = h*(0.25+Theme.avatarSelectWheelY)
      bigCoord = (w*(Theme.avatarSelectAvX+self.dist),h*Theme.avatarSelectAvY)
      
      if self.avBigFrame:
        self.engine.drawImage(self.avFrame, scale = (self.avBigFrameScale[0]*1.75,self.avBigFrameScale[1]*1.75), coord = bigCoord)
      self.engine.drawImage(currentAv, scale = (self.avScale[self.selectedAv]*1.75,-self.avScale[self.selectedAv]*1.75), coord = bigCoord)
      
      if self.avFrame:
        self.engine.drawImage(self.avFrame, scale = self.avFrameScale, coord = (self.x1,self.y1))
      self.engine.drawImage(lastAv2, scale = (self.avScale[lastAv2i],-self.avScale[lastAv2i]), coord = (self.x1,self.y1))
      if self.avFrame:
        self.engine.drawImage(self.avFrame, scale = self.avFrameScale, coord = (self.x2,self.y2))
      self.engine.drawImage(lastAv, scale = (self.avScale[lastAvi], -self.avScale[lastAvi]), coord = (self.x2,self.y2))
      if self.avFrame:
        self.engine.drawImage(self.avFrame, scale = self.avFrameScale, coord = (self.x5,self.y5))
      self.engine.drawImage(nextAv2, scale = (self.avScale[nextAv2i],-self.avScale[nextAv2i]), coord = (self.x5,self.y5))
      if self.avFrame:
        self.engine.drawImage(self.avFrame, scale = self.avFrameScale, coord = (self.x4,self.y4))
      self.engine.drawImage(nextAv, scale = (self.avScale[nextAvi],-self.avScale[nextAvi]), coord = (self.x4,self.y4))   
      if self.avSelFrame:
        self.engine.drawImage(self.avSelFrame, scale = self.avSelFrameScale, coord = (self.x3,self.y3))
      self.engine.drawImage(currentAv, scale = (self.avScale[int(self.selectedAv)],-self.avScale[int(self.selectedAv)]), coord = (self.x3,self.y3))
      
      try:
        font = self.engine.data.fontDict[Theme.avatarSelectFont]
      except:
        font = self.engine.data.font
      if self.avText:
        self.engine.drawImage(self.avText, scale = (Theme.avatarSelectTextScale, -Theme.avatarSelectTextScale), coord = (Theme.avatarSelectTextX, Theme.avatarSelectTextY - v))
      else:
        font.render(self.avatarText, (Theme.avatarSelectTextX, Theme.avatarSelectTextY - v), scale = Theme.avatarSelectTextScale)
    finally:
      self.engine.view.resetProjection()
    #==============================================================

class ItemChooser(BackgroundLayer, KeyListener):
  """Item menu layer."""
  def __init__(self, engine, items, selected = None, prompt = "", pos = None):    #MFH
    self.prompt         = prompt
    self.engine         = engine
    
    self.logClassInits = self.engine.config.get("game", "log_class_inits")
    if self.logClassInits == 1:
      Log.debug("ItemChooser class init (Dialogs.py)...")
    
    self.accepted       = False
    self.selectedItem   = None
    self.time           = 0.0

    self.font = self.engine.data.streakFont2
    self.promptScale = 0.002
    self.promptWidth, self.promptHeight = self.font.getStringSize(self.prompt, scale=self.promptScale)
    widthOfSpace, heightOfSpace = self.font.getStringSize(" ", scale=self.promptScale)

    if pos: #MFH
      self.songSelectSubmenuOffsetLines = Theme.songSelectSubmenuOffsetLines
      self.songSelectSubmenuOffsetSpaces = Theme.songSelectSubmenuOffsetSpaces
      self.posX, self.posY = pos
      wrapX, wrapY = wrapText(self.font, (self.posX, self.posY), self.prompt, scale = self.promptScale)
      #self.posY += self.promptHeight*2
      #self.posX -= self.promptWidth/2
      #self.menu = Menu(self.engine, choices = [(c, self._callbackForItem(c)) for c in items], onClose = self.close, onCancel = self.cancel, font = self.engine.data.streakFont2, pos = (self.posX + widthOfSpace*2, wrapY + self.promptHeight*2) )
      self.menu = Menu(self.engine, choices = [(c, self._callbackForItem(c)) for c in items], onClose = self.close, onCancel = self.cancel, font = self.engine.data.streakFont2, pos = (self.posX + widthOfSpace*(self.songSelectSubmenuOffsetSpaces+1), wrapY + self.promptHeight*(self.songSelectSubmenuOffsetLines+1)) )
    else:
      self.posX = .1    #MFH - default
      self.posY = .05   #MFH - default
      self.menu = Menu(self.engine, choices = [(c, self._callbackForItem(c)) for c in items], onClose = self.close, onCancel = self.cancel, font = self.engine.data.streakFont2)
    self.spinnyDisabled = self.engine.config.get("game", "disable_spinny")
    
    if selected and selected in items:
      self.menu.selectItem(items.index(selected))

    #Get theme
    themename = self.engine.data.themeLabel
    self.theme = self.engine.data.theme
    self.engine.loadImgDrawing(self, "background", os.path.join("themes",themename,"editor.png"))
    
  def _callbackForItem(self, item):
    def cb():
      self.chooseItem(item)
    return cb
    
  def chooseItem(self, item):
    self.selectedItem = item
    accepted = True
    self.engine.view.popLayer(self.menu)
    self.engine.view.popLayer(self)
    
  def cancel(self):
    self.accepted = True
    self.engine.view.popLayer(self)

  def close(self):
    self.accepted = True
    self.engine.view.popLayer(self)
    
  def shown(self):
    self.engine.view.pushLayer(self.menu)
    
  def getSelectedItem(self):
    return self.selectedItem
  
  def run(self, ticks):
    self.time += ticks / 50.0
    
  def render(self, visibility, topMost):
    v = (1 - visibility) ** 2

    # render the background
    t = self.time / 100
    self.engine.view.setViewport(1,0)
    w, h, = self.engine.view.geometry[2:4]
    r = .5

    #MFH - auto background scaling 
    imgwidth = self.background.width1()
    wfactor = 640.000/imgwidth
    self.engine.drawImage(self.background, scale = (wfactor,-wfactor), coord = (w/2,h/2))

      
    self.engine.view.setOrthogonalProjection(normalize = True)
    
    
    try:
      glEnable(GL_BLEND)
      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
      glEnable(GL_COLOR_MATERIAL)
      Theme.setBaseColor(1 - v)
      #wrapText(self.font, (.1, .05 - v), self.prompt)
      wrapText(self.font, (self.posX, self.posY - v), self.prompt, scale = self.promptScale)
    finally:
      self.engine.view.resetProjection()
      
class ControlActivator(Layer, KeyListener):
  def __init__(self, engine, players, maxplayers = None, allowGuitar = True, allowDrum = True, allowMic = False):
    self.engine     = engine
    self.minPlayers = players
    if maxplayers:
      maxallowed = self.engine.config.get("performance", "max_players")
      if maxplayers > maxallowed or maxplayers == -1:
        self.maxPlayers = maxallowed
      else:
        self.maxPlayers = maxplayers
    else:
      self.maxPlayers = players
    self.time       = 0.0
    self.controls   = self.engine.input.controls.controls[:] #make a copy
    self.ready      = False
    
    if self.engine.cmdPlay == 2:
      if self.engine.cmdPart is not None:
        if self.engine.cmdPart == 4:
          allowGuitar = False
          allowMic    = False
        elif self.engine.cmdPart == 5:
          allowGuitar = False
          allowDrum   = False
        else:
          allowDrum   = False
          allowMic    = False
    
    self.selectedItems  = []
    self.blockedItems   = []
    self.selectedIndex  = 0
    self.playerNum      = 0
    self.confirmPlayers = 0
    self.delay          = 0
    self.delayedIndex   = 0
    self.fader          = 0
    self.fadeDir        = True
    self.allowed        = [True for i in self.controls]
    
    for i, control in enumerate(self.engine.input.controls.controls):
      if self.engine.input.controls.type[i] in GUITARTYPES and not allowGuitar:
        self.allowed[i] = False
      elif self.engine.input.controls.type[i] in DRUMTYPES and not allowDrum:
        self.allowed[i] = False
      elif self.engine.input.controls.type[i] in MICTYPES and not allowMic:
        self.allowed[i] = False
    
    self.tsReady = _("Press Start to Begin!")
    self.tsInfo  = _("Use the keyboard to select or just play some notes!")
    
    sfxVolume = self.engine.config.get("audio", "SFX_volume")
    self.engine.data.selectSound.setVolume(sfxVolume)
    self.engine.data.acceptSound.setVolume(sfxVolume)  #MFH
    self.engine.data.cancelSound.setVolume(sfxVolume)
    
    self.controlNum = 0
    for i, control in enumerate(self.engine.input.controls.controls):
      self.controlNum += 1
      if control == "None":
        self.controls[i] = _("No Controller")
        self.blockedItems.append(i)
        self.controlNum -= 1
      elif self.allowed[i] == False:
        self.controls[i] = _("Disabled Controller")
        self.blockedItems.append(i)
        self.controlNum -= 1
      elif control == "defaultg":
        self.controls[i] = _("Default Guitar")
      elif control == "defaultd":
        self.controls[i] = _("Default Drums")
      elif control == "defaultm":
        self.controls[i] = _("Default Microphone")
    
    themename = self.engine.data.themeLabel
    while self.selectedIndex in self.blockedItems:
      self.selectedIndex += 1
      if self.selectedIndex > 3:
        self.selectedIndex = 0
        break
    try:
      self.engine.loadImgDrawing(self, "background", os.path.join("themes", themename, "lobby", "controlbg.png"))
      self.bgScale = 640.000/self.background.width1()
    except IOError:
      self.background = None
    try:
      self.engine.loadImgDrawing(self, "readyImage", os.path.join("themes", themename, "lobby", "ready.png"))
      self.readyScale = 640.000/self.readyImage.width1()
    except IOError:
      self.readyImage = None
    try:
      self.engine.loadImgDrawing(self, "selected", os.path.join("themes", themename, "lobby", "select.png"))
    except IOError:
      self.selected = None
    
    self.selectX = Theme.controlActivateSelectX
    self.controlSelectX = Theme.controlActivateX
    self.controlPartX   = Theme.controlActivatePartX
    self.selectY = Theme.controlActivateY
    self.selectScale = Theme.controlActivateScale
    self.selectSpace = Theme.controlActivateSpace
    self.partBig = Theme.controlCheckPartMult
    self.checkX = Theme.controlCheckX
    self.checkY = Theme.controlCheckY
    self.checkYText = Theme.controlCheckTextY
    self.checkScale = Theme.controlCheckScale
    self.checkSpace = Theme.controlCheckSpace
    
    self.partSize = Theme.controlActivatePartSize
    try:
      self.engine.loadImgDrawing(self, "guitar", os.path.join("themes", themename, "guitar.png"))
      self.guitarScale = self.partSize/self.guitar.width1()
    except IOError:
      self.engine.loadImgDrawing(self, "guitar", "guitar.png")
      self.guitarScale = self.partSize/self.guitar.width1()
    try:
      self.engine.loadImgDrawing(self, "bass", os.path.join("themes", themename, "bass.png"))
      self.bassScale = self.partSize/self.bass.width1()
    except IOError:
      self.engine.loadImgDrawing(self, "bass", "bass.png")
      self.bassScale = self.partSize/self.bass.width1()
    try:
      self.engine.loadImgDrawing(self, "drum", os.path.join("themes", themename, "drum.png"))
      self.drumScale = self.partSize/self.drum.width1()
    except IOError:
      self.engine.loadImgDrawing(self, "drum", "drum.png")
      self.drumScale = self.partSize/self.drum.width1()
    try:
      self.engine.loadImgDrawing(self, "mic", os.path.join("themes", themename, "mic.png"))
      self.micScale = self.partSize/self.mic.width1()
    except IOError:
      self.engine.loadImgDrawing(self, "mic", "mic.png")
      self.micScale = self.partSize/self.mic.width1()
  
  def shown(self):
    if self.controlNum < self.minPlayers:
      self.confirmPlayers = 0
      if self.controlNum == 1:
        plural = _("controller")
      else:
        plural = _("controllers")
      showMessage(self.engine, _("You only have %d %s defined. You need at least %d for this mode.") % (self.controlNum, plural, self.minPlayers))
      self.engine.view.popLayer(self)
    else:
      self.engine.input.addKeyListener(self, priority = True)
  
  def hidden(self):
    self.engine.input.removeKeyListener(self)
  
  def confirm(self):
    self.engine.data.acceptSound.play()
    self.engine.input.activeGameControls = self.selectedItems
    self.engine.input.pluginControls()
    self.confirmPlayers = self.playerNum
    self.engine.view.popLayer(self)
    self.engine.input.removeKeyListener(self)
  
  def getPlayers(self):
    return self.confirmPlayers
  
  def delaySelect(self, num):
    if self.engine.input.controls.type[num] == 5:
      return
    self.engine.data.selectSound.play()
    self.delay = 500
    self.delayedIndex  = num
    self.selectedIndex = num
  
  def selectControl(self, num):
    if num in self.selectedItems or self.playerNum >= self.maxPlayers:
      return
    self.engine.data.acceptSound.play()
    self.playerNum += 1
    self.selectedItems.append(num)
    self.blockedItems.append(num)
    self.blockedItems.sort()
    if self.playerNum >= self.minPlayers:
      self.ready = True
    self.selectedIndex += 1
    self.delay = 0
    catch = 0
    while self.selectedIndex in self.blockedItems:
      self.selectedIndex += 1
      catch += 1
      if self.selectedIndex > 3:
        self.selectedIndex = 0
      if catch > 4:
        self.confirm()
        break
    else:
      if self.selectedIndex > 3:
        for i in range(4):
          if i in self.blockedItems:
            continue
          self.selectedIndex = i
          break
  
  def keyPressed(self, key, unicode):
    c = self.engine.input.controls.getMapping(key)
    if key == pygame.K_RETURN:
      if (self.ready and self.playerNum >= self.maxPlayers) or (self.playerNum >= self.minPlayers and self.blockedItems == [0,1,2,3]):
        self.confirm()
      else:
        self.delay = 0
        self.selectControl(self.selectedIndex)
      return True
    if c in Player.menuYes and self.ready:
      self.confirm()
      return True
    if c in Player.menuNo or key == pygame.K_ESCAPE:
      self.engine.data.cancelSound.play()
      if len(self.selectedItems) > 0:
        self.delay = 0
        self.selectedIndex = 0
        self.blockedItems.remove(self.selectedItems.pop())
        self.playerNum = len(self.selectedItems)
        if self.playerNum < self.minPlayers and self.ready:
          self.ready = False
      else:
        self.playerNum = 0
        self.engine.view.popLayer(self)
        self.engine.input.removeKeyListener(self)
      return True
    elif c in Player.ups + Player.rights or key == pygame.K_UP or key == pygame.K_RIGHT:
      self.engine.data.selectSound.play()
      self.selectedIndex -= 1
      self.delay = 0
      catch = 0
      while self.selectedIndex in self.blockedItems:
        self.selectedIndex -= 1
        catch += 1
        if self.selectedIndex < 0:
          self.selectedIndex = 3
        if catch > 4:
          self.confirm()
          break
      else:
        if self.selectedIndex < 0:
          a = range(4)
          a.reverse()
          for i in a:
            if i in self.blockedItems:
              continue
            self.selectedIndex = i
            break
    elif c in Player.downs + Player.lefts or key == pygame.K_DOWN or key == pygame.K_LEFT:
      self.engine.data.selectSound.play()
      self.selectedIndex += 1
      self.delay = 0
      catch = 0
      while self.selectedIndex in self.blockedItems:
        self.selectedIndex += 1
        catch += 1
        if self.selectedIndex > 3:
          self.selectedIndex = 0
        if catch > 4:
          break
      else:
        if self.selectedIndex > 3:
          for i in range(4):
            if i in self.blockedItems:
              continue
            self.selectedIndex = i
            break
    if c in Player.ups + Player.downs + Player.lefts + Player.rights + Player.cancels + Player.stars + [None]:
      pass
    elif c in Player.starts or key == pygame.K_LCTRL or ((c in Player.key1s or key == pygame.K_RETURN) and self.ready):
      if self.ready:
        self.confirm()
        return True
    elif c in Player.CONTROL1:
      if not 0 in self.selectedItems:
        self.delaySelect(0)
        return True
    elif c in Player.CONTROL2:
      if not 1 in self.selectedItems:
        self.delaySelect(1)
        return True
    elif c in Player.CONTROL3:
      if not 2 in self.selectedItems:
        self.delaySelect(2)
        return True
    elif c in Player.CONTROL4:
      if not 3 in self.selectedItems:
        self.delaySelect(3)
        return True
    return True
  
  def keyReleased(self, key):
    pass
  
  def run(self, ticks):
    self.time += ticks/50.0
    if self.delay > 0:
      self.delay -= ticks
      if self.delay <= 0:
        self.selectControl(self.selectedIndex)
    if self.ready and self.fadeDir:
      self.fader += ticks/1000.0
      if self.fader > 1:
        self.fader = 1
        self.fadeDir = False
    elif self.ready:
      self.fader -= ticks/1000.0
      if self.fader < 0.2:
        self.fader = 0.2
        self.fadeDir = True
  
  def render(self, visibility, topMost):
    try:
      font = self.engine.data.fontDict[Theme.controlActivateFont]
      descFont = self.engine.data.fontDict[Theme.controlDescriptionFont]
      checkFont = self.engine.data.fontDict[Theme.controlCheckFont]
    except KeyError:
      font = self.engine.data.loadingFont
      descFont = self.engine.data.font
      checkFont = self.engine.data.font
    bigFont = self.engine.data.bigFont
    self.engine.view.setOrthogonalProjection(normalize = True)
    w, h = self.engine.view.geometry[2:4]
    v = (1-visibility)**2
    try:
      if self.background:
        self.engine.drawImage(self.background, scale = (self.bgScale,-self.bgScale), coord = (w/2,h/2))
      Theme.setBaseColor(1-v)
      wText, hText = descFont.getStringSize(self.tsInfo, scale = Theme.controlDescriptionScale)
      descFont.render(self.tsInfo, (Theme.controlDescriptionX-wText/2, Theme.controlDescriptionY), scale = Theme.controlDescriptionScale)
      for i, control in enumerate(self.controls):
        if self.selectedIndex == i:
          if self.selected:
            Theme.setBaseColor(1-v)
            self.engine.drawImage(self.selected, scale = (.5,-.5), coord = (w*self.selectX,h*(1-(self.selectY+self.selectSpace*i)/self.engine.data.fontScreenBottom)))
          else:
            Theme.setSelectedColor(1-v)
        elif i in self.blockedItems:
          glColor3f(.3, .3, .3)
        else:
          Theme.setBaseColor(1-v)
        wText, hText = font.getStringSize(control, scale = self.selectScale)
        font.render(control, (self.controlSelectX-wText, self.selectY-(hText/2)+self.selectSpace*i), scale = self.selectScale)
        color = (1, 1, 1, 1)
        if i in self.blockedItems:
          color = (.3, .3, .3, 1)
        if self.engine.input.controls.type[i] in GUITARTYPES:
          self.engine.drawImage(self.guitar, scale = (self.guitarScale, -self.guitarScale), coord = (w*self.controlPartX-(self.partSize*1.1), h*(1-(self.selectY+self.selectSpace*i)/self.engine.data.fontScreenBottom)), color = color)
          self.engine.drawImage(self.bass, scale = (self.bassScale, -self.bassScale), coord = (w*self.controlPartX+(self.partSize*1.1), h*(1-(self.selectY+self.selectSpace*i)/self.engine.data.fontScreenBottom)), color = color)
        elif self.engine.input.controls.type[i] in DRUMTYPES:
          self.engine.drawImage(self.drum, scale = (self.drumScale, -self.drumScale), coord = (w*self.controlPartX, h*(1-(self.selectY+self.selectSpace*i)/self.engine.data.fontScreenBottom)), color = color)
        elif self.engine.input.controls.type[i] in MICTYPES:
          self.engine.drawImage(self.mic, scale = (self.micScale, -self.micScale), coord = (w*self.controlPartX, h*(1-(self.selectY+self.selectSpace*i)/self.engine.data.fontScreenBottom)), color = color)
      Theme.setBaseColor(1-v)
      for j, i in enumerate(self.selectedItems):
        if self.engine.input.controls.type[i] in GUITARTYPES:
          self.engine.drawImage(self.guitar, scale = (self.guitarScale*self.partBig, -self.guitarScale*self.partBig), coord = (w*(self.checkX+self.checkSpace*j)-(self.partSize*self.partBig*1.1), h*self.checkY))
          self.engine.drawImage(self.bass, scale = (self.bassScale*self.partBig, -self.bassScale*self.partBig), coord = (w*(self.checkX+self.checkSpace*j)+(self.partSize*self.partBig*1.1), h*self.checkY))
        elif self.engine.input.controls.type[i] in DRUMTYPES:
          self.engine.drawImage(self.drum, scale = (self.drumScale*self.partBig, -self.drumScale*self.partBig), coord = (w*(self.checkX+self.checkSpace*j), h*self.checkY))
        elif self.engine.input.controls.type[i] in MICTYPES:
          self.engine.drawImage(self.mic, scale = (self.micScale*self.partBig, -self.micScale*self.partBig), coord = (w*(self.checkX+self.checkSpace*j), h*self.checkY))
        wText, hText = checkFont.getStringSize(self.controls[i], scale = self.checkScale)
        checkFont.render(self.controls[i], ((self.checkX+self.checkSpace*j)-wText/2, self.checkYText*self.engine.data.fontScreenBottom), scale = self.checkScale)
      if self.ready:
        if self.readyImage:
          self.engine.drawImage(self.readyImage, scale = (self.readyScale, -self.readyScale), coord = (w*.5, h*.5), color = (1, 1, 1, self.fader))
        else:
          Theme.setBaseColor(self.fader)
          wText, hText = bigFont.getStringSize(self.tsReady, scale = .001)
          bigFont.render(self.tsReady, (.5-wText/2, .3), scale = .001)
    finally:
      self.engine.view.resetProjection()

class BpmEstimator(Layer, KeyListener):
  """Beats per minute value estimation layer."""
  def __init__(self, engine, song, prompt = ""):
    self.prompt         = prompt
    self.engine         = engine

    self.logClassInits = self.engine.config.get("game", "log_class_inits")
    if self.logClassInits == 1:
      Log.debug("BpmEstimator class init (Dialogs.py)...")

    self.song           = song
    self.accepted       = False
    self.bpm            = None
    self.time           = 0.0
    self.beats          = []
    
    
  def shown(self):
    self.engine.input.addKeyListener(self, priority = True)
    self.song.play()
  
  def hidden(self):
    self.engine.input.removeKeyListener(self)
    self.song.fadeout(1000)
    
  def keyPressed(self, key, unicode):
    if self.accepted:
      return True
      
    c = self.engine.input.controls.getMapping(key)
    if key == pygame.K_SPACE:
      self.beats.append(self.time)
      if len(self.beats) > 12:
        diffs = [self.beats[i + 1] - self.beats[i] for i in range(len(self.beats) - 1)]
        self.bpm = 60000.0 / (sum(diffs) / float(len(diffs)))
        self.beats = self.beats[-12:]
    elif c in Player.cancels + Player.key2s:
      self.engine.view.popLayer(self)
      self.accepted = True
      self.bpm      = None
    elif c in Player.key1s or key == pygame.K_RETURN:
      self.engine.view.popLayer(self)
      self.accepted = True
      
    return True
  
  def run(self, ticks):
    self.time += ticks
    
  def render(self, visibility, topMost):
    v = (1 - visibility) ** 2
    
    self.engine.view.setViewport(1,0)
    self.engine.view.setOrthogonalProjection(normalize = True)
    font = self.engine.data.font
    
    fadeScreen(v)
          
    try:
      glEnable(GL_BLEND)
      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
      glEnable(GL_COLOR_MATERIAL)
      Theme.setBaseColor(1 - v)
      wrapText(font, (.1, .2 - v), self.prompt)
      
      if self.bpm is not None:
        Theme.setSelectedColor(1 - v)
        wrapText(font, (.1, .5 + v),  _("%.2f beats per minute") % (self.bpm))
    finally:
      self.engine.view.resetProjection()
      
class KeyTester(Layer, KeyListener):
  """Keyboard configuration testing layer."""
  def __init__(self, engine, control, prompt = ""):
    self.prompt         = prompt
    self.engine         = engine
    
    self.logClassInits = self.engine.config.get("game", "log_class_inits")
    if self.logClassInits == 1:
      Log.debug("KeyTester class init (Dialogs.py)...")
    
    
    self.accepted       = False
    self.time           = 0.0
    self.controls       = self.engine.input.controls
    self.controlNum     = control
    self.keyList        = Player.CONTROLS[control]
    self.type           = self.controls.type[control]
    self.analogKillMode = self.controls.analogKill[control]
    self.analogSPMode   = self.controls.analogSP[control]
    self.analogSPThresh = self.controls.analogSPThresh[control]
    self.analogSPSense  = self.controls.analogSPSense[control]
    self.analogDrumMode = self.controls.analogDrum[control]
    self.analogSlideMode = self.controls.analogSlide[control]
    
    if self.type < 2 or self.type == 4:
      self.fretColors     = Theme.fretColors
      self.names          = [_("Left"), _("Right"), _("Up"), _("Down"), _("Start"), \
                             _("Select"), _("Fret #1"), _("Solo #1"), _("Fret #2"), _("Solo #2"), \
                             _("Fret #3"), _("Solo #3"), _("Fret #4"), _("Solo #4"), _("Fret #5"), \
                             _("Solo #5"), _("Pick!"), _("Pick!"), _("Starpower!"), _("Whammy")]
    elif self.type == 2:
      colors              = Theme.fretColors
      self.fretColors     = [colors[1], colors[2], colors[3], colors[0]]
      self.bassColor      = colors[4]
      self.names          = [_("Left"), _("Right"), _("Up"), _("Down"), _("Start"), \
                             _("Select"), _("Drum #1"), None, _("Drum #2"), None, \
                             _("Drum #3"), None, None, None, _("Drum #4"), \
                             None, _("Bass Drum"), None, _("Starpower!"), _("None")]
    elif self.type == 5:
      self.names          = [_("Left"), _("Right"), _("Up"), _("Down"), _("Start"), \
                             _("Select"), None, None, None, None, \
                             None, None, None, None, None, \
                             None, None, None, _("Starpower!"), None]
    else:
      colors              = Theme.fretColors
      self.fretColors     = [colors[1], colors[2], colors[3], colors[4], colors[0]]
      self.bassColor      = Theme.bassColor
      self.names          = [_("Left"), _("Right"), _("Up"), _("Down"), _("Start"), \
                             _("Select"), _("Drum #1"), None, _("Cymbal #2"), None, \
                             _("Drum #3"), None, _("Cymbal #4"), None, _("Drum #5"), \
                             None, _("Bass Drum"), None, _("Starpower!"), _("None")]
      
    self.tsFret  = _("Fret")
    self.tsSolo  = _("Solo")
    self.tsDrum  = _("Drum")
    self.tsSlide = _("Slide~")
    
    self.engine.loadImgDrawing(self, "arrow", "arrow.png")
    self.engine.loadImgDrawing(self, "circle", "test.png")
    self.engine.loadImgDrawing(self, "analogBar", "analog.png")
    self.engine.loadImgDrawing(self, "analogBox", "analogback.png")
    self.engine.loadImgDrawing(self, "analogThresh", "analogthresh.png")
    self.analogBoxScale = 1.0/6.0
    self.analogBarScale = 1.0/6.0
    self.analogThreshScale = 5.000/self.analogThresh.width1()
    
    #evilynux - Get killswitch mode (analog or digital?)
    # If analog, get and show attenuation. Most code taken from GuitarScene.
    self.isKillAnalog = False
    self.isSPAnalog = False
    self.isSlideAnalog = False
    self.areDrumsAnalog = False
    self.whichJoyKill = 0
    self.whichAxisKill = 0
    self.whichJoyStar = 0
    self.whichAxisStar = 0
    self.whichJoySlide = 0
    self.whichAxisSlide = 0
    self.whichJoyDrum1 = 0
    self.whichAxisDrum1 = 0
    self.whichJoyDrum2 = 0
    self.whichAxisDrum2 = 0
    self.whichJoyDrum3 = 0
    self.whichAxisDrum3 = 0
    self.whichJoyDrum4 = 0
    self.whichAxisDrum4 = 0
    self.whichJoyDrum5 = 0
    self.whichAxisDrum5 = 0
    self.whammy = 0
    self.starpower = 0
    self.slideActive = -1
    self.midFret = False

    if len(self.engine.input.joysticks) != 0 and self.type < 2 or self.type == 4:
      if self.analogKillMode > 0:
        KillKeyCode = self.controls.getReverseMapping(self.keyList[Player.KILL])
        self.isKillAnalog, self.whichJoyKill, self.whichAxisKill = self.engine.input.getWhammyAxis(KillKeyCode)
      if self.analogSPMode > 0:
        StarKeyCode = self.controls.getReverseMapping(self.keyList[Player.STAR])
        self.isSPAnalog, self.whichJoyStar, self.whichAxisStar = self.engine.input.getWhammyAxis(StarKeyCode)
      if self.type == 4:
        SlideKeyCode = self.controls.getReverseMapping(self.keyList[Player.KEY1A])
        self.isSlideAnalog, self.whichJoySlide, self.whichAxisSlide = self.engine.input.getWhammyAxis(SlideKeyCode)
    
  def shown(self):
    if self.type == 5:
      self.mic = Microphone.Microphone(self.engine, self.controlNum)
      self.mic.start()
    self.engine.input.addKeyListener(self, priority = True)
  
  def hidden(self):
    if hasattr(self, 'mic'):
      self.mic.stop()
      del self.mic
    self.engine.input.removeKeyListener(self)
    
  def keyPressed(self, key, unicode):
    if self.accepted:
      return True
    if key == pygame.K_ESCAPE:
      self.engine.view.popLayer(self)
      self.accepted = True
      return True
    c = self.engine.input.controls.getMapping(key)
    self.controls.keyPressed(key)
    if self.type > 1 and self.type not in (4, 5):
      if c == self.keyList[Player.DRUM1]:
        self.engine.data.T1DrumSound.play()
      elif c == self.keyList[Player.DRUM2]:
        if self.type == 2:
          self.engine.data.T2DrumSound.play()
        else:
          self.engine.data.CDrumSound.play()
      elif c == self.keyList[Player.DRUM3]:
        if self.type == 2:
          self.engine.data.T3DrumSound.play()
        else:
          self.engine.data.T2DrumSound.play()
      elif c == self.keyList[Player.DRUM4]:
        self.engine.data.CDrumSound.play()
      elif c == self.keyList[Player.DRUM5]:
        if self.type == 2:
          self.engine.data.CDrumSound.play()
        else:
          self.engine.data.T3DrumSound.play()
    return True

  def keyReleased(self, key):
    self.controls.keyReleased(key)
  
  def run(self, ticks):
    self.time += ticks
    if self.isSPAnalog:
      if self.starpower > (self.analogSPThresh/100.0):
        if self.starDelay == 0 and not self.starpowerActive:
          self.starDelay = (10-self.analogSPSense)*25
        else:
          self.starDelay -= ticks
          if self.starDelay <= 0:
            self.starpowerActive = True
      else:
        self.starpowerActive = False
        self.starDelay = 0
    
  def render(self, visibility, topMost):
    v = (1 - visibility) ** 2
    
    self.engine.view.setViewport(1,0)
    self.engine.view.setOrthogonalProjection(normalize = True)
    font = self.engine.data.font
    w, h = self.engine.view.geometry[2:4]
    
    if self.controls.getState(self.keyList[Player.UP]):
      if self.controls.getState(self.keyList[Player.LEFT]):
        rotateArrow = math.pi/4
      elif self.controls.getState(self.keyList[Player.RIGHT]):
        rotateArrow = -math.pi/4
      else:
        rotateArrow = 0.0
    elif self.controls.getState(self.keyList[Player.DOWN]):
      if self.controls.getState(self.keyList[Player.LEFT]):
        rotateArrow = 3*math.pi/4
      elif self.controls.getState(self.keyList[Player.RIGHT]):
        rotateArrow = -3*math.pi/4
      else:
        rotateArrow = math.pi
    elif self.controls.getState(self.keyList[Player.LEFT]):
      rotateArrow = math.pi/2
    elif self.controls.getState(self.keyList[Player.RIGHT]):
      rotateArrow = -math.pi/2
    else:
      rotateArrow = None
    
    fadeScreen(v)
          
    try:
      glEnable(GL_BLEND)
      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
      glEnable(GL_COLOR_MATERIAL)
      Theme.setBaseColor(1 - v)
      wrapText(font, (.1, .2 - v), self.prompt)
      
      self.engine.drawImage(self.circle, scale = (.5, -.5), coord = (w*.5,h*.6))
      if rotateArrow is not None:
        self.engine.drawImage(self.arrow,  scale = (.5, -.5), coord = (w*.5,h*.6), rot = rotateArrow)

      if self.type != 5:
        #akedrou - analog starpower, analog slider
        text = self.names[Player.STAR]
        wText, hText = font.getStringSize(text)

        if self.isSlideAnalog:
          if self.analogSlideMode == 1:  #Inverted mode
            slideVal = -(self.engine.input.joysticks[self.whichJoySlide].get_axis(self.whichAxisSlide)+1.0)/2.0
          else:  #Default
            slideVal = (self.engine.input.joysticks[self.whichJoySlide].get_axis(self.whichAxisSlide)+1.0)/2.0
          if slideVal > 0.9 or slideVal < 0.01:
            self.slideActive = 4
            self.midFret = False
          elif slideVal > 0.77:
            self.slideActive = 4
            self.midFret = True
          elif slideVal > 0.68:
            self.slideActive = 3
            self.midFret = False
          elif slideVal > 0.60:
            self.slideActive = 3
            self.midFret = True
          elif slideVal > 0.54:
            self.slideActive = 2
            self.midFret = False
          elif slideVal > 0.43:
            self.slideActive = -1
            self.midFret = False
          elif slideVal > 0.34:
            self.slideActive = 2
            self.midFret = True
          elif slideVal > 0.28:
            self.slideActive = 1
            self.midFret = False
          elif slideVal > 0.16:
            self.slideActive = 1
            self.midFret = True
          else:
            self.slideActive = 0
            self.midFret = False

        if self.isSPAnalog:
          starThresh = (self.analogSPThresh/100.0)*(w/6.0)-(w/12.0)
          self.engine.drawImage(self.analogThresh, scale = (self.analogThreshScale, -self.analogThreshScale), coord = ((w*.25)+starThresh, h*.3))
          #(0.0 at level, -1 upright; 1 upside down)
          self.starpower = abs(self.engine.input.joysticks[self.whichJoyStar].get_axis(self.whichAxisStar))

        if self.starpower > 0:
          if self.starpowerActive:
            Theme.setSelectedColor(1 - v)
          else:
            glColor3f(.4, .4, .4)
          font.render(text, (.25-wText/2, .45 + v))
          starC = (1-self.starpower)*.5*w*self.analogBarScale
          self.engine.drawImage(self.analogBar, scale = (self.analogBarScale*self.starpower, -self.analogBarScale), coord = ((w*.25)-starC, h*.3), rect = (0, self.starpower, 0, 1), stretched = 11)
          self.engine.drawImage(self.analogBox, scale = (self.analogBoxScale, -self.analogBoxScale), coord = (w*.25, h*.3), stretched = 11)
        else:
          if self.controls.getState(self.keyList[Player.STAR]):
            Theme.setSelectedColor(1 - v)
          else:
            glColor3f(.4, .4, .4)
          font.render(text, (.25-wText/2, .45 + v))
        
      if self.controls.getState(self.keyList[Player.CANCEL]):
        glColor3f(.6, 0, 0)
      else:
        glColor3f(.4, .4, .4)
      text = self.names[5]
      wText, hText = font.getStringSize(text)
      font.render(text, (.333-wText/2, .28 + v))
      
      if self.controls.getState(self.keyList[Player.START]):
        glColor3f(0, .6, 0)
      else:
        glColor3f(.4, .4, .4)
      text = self.names[4]
      wText, hText = font.getStringSize(text)
      font.render(text, (.667-wText/2, .28 + v))
      
      if self.type < 2 or self.type == 4:
        
        if self.type == 0:
          for i in range(5):
            if self.controls.getState(self.keyList[(2*i)+Player.KEY1]):
              glColor3f(*self.fretColors[i%5])
              text = self.tsFret
            elif self.controls.getState(self.keyList[(2*i)+1+Player.KEY1]):
              glColor3f(*self.fretColors[i%5])
              text = self.tsSolo
            else:
              glColor3f(.4, .4, .4)
              text = self.tsFret
            text = "%s #%d" % (text, (i + 1))
            wText, hText = font.getStringSize(text)
            font.render(text, ((.2 + .15 * i)-wText/2, .4 + v))
        else:
          for i in range(5):
            if self.slideActive == i or (self.midFret and self.slideActive == i + 1) or (self.controls.getState(self.keyList[Player.KEY1A]) and self.type == 1):
              text = self.tsSolo
            else:
              text = self.tsFret
            if self.controls.getState(self.keyList[(2*i)+Player.KEY1]) or self.slideActive == i or (self.midFret and self.slideActive == i + 1):
              glColor3f(*self.fretColors[i%5])
            else:
              glColor3f(.4, .4, .4)
            text = "%s #%d" % (text, (i + 1))
            wText, hText = font.getStringSize(text)
            font.render(text, ((.2 + .15 * i)-wText/2, .4 + v))
            if self.midFret and self.slideActive == i:
              Theme.setSelectedColor(1 - v)
              text = self.tsSlide
              wText, hText = font.getStringSize(text)
              font.render(text, ((.125 + .15 * i)-wText/2, .35 + v))

        #evilynux - Compute analog killswitch value
        wText, hText = font.getStringSize(self.names[Player.KILL])
        if self.isKillAnalog:
          if self.analogKillMode == 2:  #XBOX mode: (1.0 at rest, -1.0 fully depressed)
            self.whammy = 1.0 - ((self.engine.input.joysticks[self.whichJoyKill].get_axis(self.whichAxisKill)+1.0) / 2.0)

          elif self.analogKillMode == 3:  #XBOX Inverted mode: (-1.0 at rest, 1.0 fully depressed)
            self.whammy = (self.engine.input.joysticks[self.whichJoyKill].get_axis(self.whichAxisKill)+1.0) / 2.0 
        
          else: #PS2 mode: (0.0 at rest, fluctuates between 1.0 and -1.0 when pressed)
            self.whammy = abs(self.engine.input.joysticks[self.whichJoyKill].get_axis(self.whichAxisKill))

        #evilynux - analog killswitch rendering
        if self.whammy > 0:
          if self.whammy > 0.1:
            Theme.setSelectedColor(1 - v)
          else:
            glColor3f(.4, .4, .4)
          font.render(self.names[Player.KILL], (.75-wText/2, .45 + v))
          whammyC = (1-self.whammy)*.5*w*self.analogBarScale
          self.engine.drawImage(self.analogBar, scale = (self.analogBarScale*self.whammy, -self.analogBarScale), coord = (w*.75-whammyC, h*.3), rect = (0, self.whammy, 0, 1), stretched = 11)
        else:
          if self.controls.getState(self.keyList[Player.KILL]):
            Theme.setSelectedColor(1 - v)
          else:
            glColor3f(.4, .4, .4)
          font.render(self.names[Player.KILL], (.75-wText/2, .45 + v))
        
        self.engine.drawImage(self.analogBox, scale = (self.analogBoxScale, -self.analogBoxScale), coord = (w*.75, h*.3), stretched = 11)
        if self.controls.getState(self.keyList[Player.ACTION1]) or self.controls.getState(self.keyList[Player.ACTION2]):
          Theme.setSelectedColor(1 - v)
        else:
          glColor3f(.4, .4, .4)
        wText, hText = font.getStringSize(self.names[Player.ACTION1])
        font.render(self.names[Player.ACTION1], (.5-wText/2, .55 + v))

      elif self.type == 5:
        Theme.setBaseColor(1 - v)
        font.render(_('Level:'), (.3, .4 + v))
        font.render(_('Note:'), (.3, .6 + v))

        peakvol = self.mic.getPeak()
        if peakvol < -5.0:
          colorval = min(1.0, .4 + max(0.0, (peakvol+30.0) * .6 / 25.0))
          glColor3f(colorval, colorval, colorval)
        else:
          glColor3f(1.0, max(0.0, min(1.0, (peakvol/-5.0))), max(0.0, min(1.0, (peakvol/-5.0))))
        font.render('%5.3f dB' % peakvol, (.55, .4 + v))

        if self.mic.getTap():
          Theme.setBaseColor(1 - v)
        else:
          glColor3f(.4, .4, .4)
        font.render(_('Tap'), (.55, .5 + v))

        semitones = self.mic.getSemitones()
        if semitones is None:
          glColor3f(.4, .4, .4)
          font.render(_('None'), (.55, .6 + v))
        else:
          Theme.setBaseColor(1 - v)
          font.render(Microphone.getNoteName(semitones), (.55, .6 + v))
        
        f = self.mic.getFormants()
        if f[0] is not None:
          Theme.setBaseColor(1 - v)
          font.render("%.2f Hz" % f[0], (.45, .65 + v))
        else:
          glColor3f(.4, .4, .4)
          font.render("None", (.45, .65 + v))
        if f[1] is not None:
          Theme.setBaseColor(1 - v)
          font.render("%.2f Hz" % f[1], (.65, .65 + v))
        else:
          glColor3f(.4, .4, .4)
          font.render("None", (.65, .65 + v))

      elif self.type > 1:
        if self.type == 2:
          drumList = [self.keyList[Player.DRUM1], self.keyList[Player.DRUM1A], self.keyList[Player.DRUM2], self.keyList[Player.DRUM2A], \
                      self.keyList[Player.DRUM3], self.keyList[Player.DRUM3A], self.keyList[Player.DRUM5], self.keyList[Player.DRUM5A]]
          for i in range(4):
            if self.controls.getState(drumList[(2*i)]) or self.controls.getState(drumList[(2*i)+1]):
              glColor3f(*self.fretColors[i%5])
            else:
              glColor3f(.4, .4, .4)
            text = self.tsDrum
            text = "%s #%d" % (text, (i + 1))
            wText, hText = font.getStringSize(text)
            font.render(text, ((.2 + .2 * i)-wText/2, .4 + v))
        else:
          drumList = [self.keyList[Player.DRUM1], self.keyList[Player.DRUM1A], self.keyList[Player.DRUM2], self.keyList[Player.DRUM2A], \
                      self.keyList[Player.DRUM3], self.keyList[Player.DRUM3A], self.keyList[Player.DRUM4], self.keyList[Player.DRUM4A], \
                      self.keyList[Player.DRUM5], self.keyList[Player.DRUM5A]]
          for i in range(5):
            if self.controls.getState(drumList[(2*i)]) or self.controls.getState(drumList[(2*i)+1]):
              glColor3f(*self.fretColors[i%5])
            else:
              glColor3f(.4, .4, .4)
            text = self.tsDrum
            text = "%s #%d" % (text, (i + 1))
            wText, hText = font.getStringSize(text)
            font.render(text, ((.2 + .15 * i)-wText/2, .4 + v))
  
        if self.controls.getState(self.keyList[Player.DRUMBASS]) or self.controls.getState(self.keyList[Player.DRUMBASSA]):
          glColor3f(*self.bassColor)
        else:
          glColor3f(.4, .4, .4)
        wText, hText = font.getStringSize(self.names[Player.DRUMBASS])
        font.render(self.names[Player.DRUMBASS], (.5-wText/2, .5 + v))
        
    finally:
      self.engine.view.resetProjection()
      
def _runDialog(engine, dialog):
  """Run a dialog in a sub event loop until it is finished."""
  if not engine.running:
    return
  
  engine.view.pushLayer(dialog)

  while engine.running and dialog in engine.view.layers:
    engine.run()

def getText(engine, prompt, text = ""):
  """
  Get a string of text from the user.
  
  @param engine:  Game engine
  @param prompt:  Prompt shown to the user
  @param text:    Default text
  """
  d = GetText(engine, prompt, text)
  _runDialog(engine, d)
  return d.text

def getKey(engine, prompt, key = None, specialKeyList = []):
  """
  Ask the user to choose a key.
  
  @param engine:          Game engine
  @param prompt:          Prompt shown to the user
  @param key:             Default key
  @param specialKeyList:  A list of keys that are ineligible.
  """
  d = GetKey(engine, prompt, key, specialKeyList = specialKeyList)
  _runDialog(engine, d)
  return d.key

def chooseSong(engine, prompt = _("Choose a Song"), selectedSong = None, selectedLibrary = None):
  """
  Ask the user to select a song.
  
  @param engine:           Game engine
  @param prompt:           Prompt shown to the user
  @param selectedSong:     Name of song to select initially
  @param selectedLibrary:  Name of the library where to search for the songs or None for the default library

  @returns a (library, song) pair
  """
  d = SongChooser(engine, prompt, selectedLibrary = selectedLibrary, selectedSong = selectedSong)

  if d.getItems() == []:
    return (None, None)
  else:
    _runDialog(engine, d)
  return (d.getSelectedLibrary(), d.getSelectedSong())
  
def chooseFile(engine, masks = ["*.*"], path = ".", prompt = _("Choose a File"), dirSelect = False):
  """
  Ask the user to select a file.
  
  @param engine:  Game engine
  @param masks:   List of glob masks for files that are acceptable
  @param path:    Initial path
  @param prompt:  Prompt shown to the user
  """
  d = FileChooser(engine, masks, path, prompt, dirSelect)
  _runDialog(engine, d)
  return d.getSelectedFile()
  
def chooseItem(engine, items, prompt = "", selected = None, pos = None):   #MFH
  """
  Ask the user to choose one item from a list.
  
  @param engine:    Game engine
  @param items:     List of items
  @param prompt:    Prompt shown to the user
  @param selected:  Item selected by default
  @param pos:       Position tuple (x,y) for placing the menu
  """
  d = ItemChooser(engine, items, prompt = prompt, selected = selected, pos = pos)
  _runDialog(engine, d)
  return d.getSelectedItem()

def activateControllers(engine, players = 1, maxplayers = None, allowGuitar = True, allowDrum = True, allowMic = False):
  """
  Ask the user to select the active controllers for the game session.
  
  @param engine:    Game engine
  @type players:    int
  @param players:   The maximum number of players.
  """
  d = ControlActivator(engine, players, maxplayers, allowGuitar, allowDrum, allowMic)
  _runDialog(engine, d)
  return d.getPlayers()

#MFH - on-demand Neck Chooser
def chooseNeck(engine, player = "default"):
  """
  Ask the user to choose their in-game neck.
  
  @param engine:    Game engine
  @type  player:    str
  @param player:    The active player
  """
  d = NeckChooser(engine, player = player)
  _runDialog(engine, d)
  return d.getSelectedNeck()

def chooseAvatar(engine):
  """
  Have the user select an avatar.
  
  @param engine:   Game engine
  """
  d = AvatarChooser(engine)
  _runDialog(engine, d)
  return d.getAvatar()

# evilynux - Show creadits
def showCredits(engine):
  d = Credits(engine)
  _runDialog(engine, d)
  
def testKeys(engine, control, prompt = _("Play with the keys and press Escape when you're done.")):
  """
  Have the user test the current keyboard configuration.
  
  @param engine:  Game engine
  @param prompt:  Prompt shown to the user
  """
  if engine.input.controls.type[control] == 5 and not Microphone.supported:
    showMessage(engine, 'A required module for microphone support is missing.')
  else:
    d = KeyTester(engine, control, prompt = prompt)
    _runDialog(engine, d)

def showLoadingScreen(engine, condition, text = _("Loading..."), allowCancel = False):
  """
  Show a loading screen until a condition is met.
  
  @param engine:      Game engine
  @param condition:   A function that will be polled until it returns a true value
  @param text:        Text shown to the user
  @type  allowCancel: bool
  @param allowCancel: Can the loading be canceled
  @return:            True if the condition was met, Fales if the loading was canceled.
  """
  
  # poll the condition first for some time
  n = 0
  while n < 32:
    n += 1
    if condition():
      return True
    engine.run()

  d = LoadingScreen(engine, condition, text, allowCancel)
  _runDialog(engine, d)
  return d.ready

def showMessage(engine, text):
  """
  Show a message to the user.
  
  @param engine:  Game engine
  @param text:    Message text
  """
  Log.notice("%s" % text)
  d = MessageScreen(engine, text)
  _runDialog(engine, d)

def estimateBpm(engine, song, prompt):
  """
  Ask the user to estimate the beats per minute value of a song.
  
  @param engine:  Game engine
  @param song:    Song instance
  @param prompt:  Prompt shown to the user
  """
  d = BpmEstimator(engine, song, prompt)
  _runDialog(engine, d)
  return d.bpm
  
#=======================================================================
# glorandwarf: added derived class LoadingSplashScreen

class LoadingSplashScreen(Layer, KeyListener):
  """Loading splash screen layer"""
  def __init__(self, engine, text):
    self.engine       = engine
    self.text         = text
    self.time         = 0.0
    self.loadingx = Theme.loadingX
    self.loadingy = Theme.loadingY  
    self.textColor = Theme.loadingColor
    self.allowtext = self.engine.config.get("game", "lphrases") 
    self.fScale = Theme.loadingFScale
    self.rMargin = Theme.loadingRMargin
    self.lspacing = Theme.loadingLSpacing

    self.logClassInits = self.engine.config.get("game", "log_class_inits")
    if self.logClassInits == 1:
      Log.debug("LoadingSplashScreen class init (Dialogs.py)...")

    #Get theme
    themename = self.engine.data.themeLabel
    self.theme = self.engine.data.theme

  def shown(self):
    self.engine.input.addKeyListener(self, priority = True)

  def keyPressed(self, key, unicode):
    return True
    
  def hidden(self):
    self.engine.input.removeKeyListener(self)

  def run(self, ticks):
    self.time += ticks / 50.0
  
  def render(self, visibility, topMost):
    self.engine.view.setViewport(1,0)
    self.engine.view.setOrthogonalProjection(normalize = True)
    font = self.engine.data.loadingFont   #MFH - new font support

    if not font:
      return

    try:
      v = (1 - visibility) ** 2
      fadeScreen(v)
      w, h = self.engine.view.geometry[2:4]
      self.engine.drawImage(self.engine.data.loadingImage, scale = (1.0,-1.0), coord = (w/2,h/2), stretched = 3)
      
      Theme.setBaseColor(1 - v)
      w, h = font.getStringSize(self.text, scale=self.fScale)
      
      x = self.loadingx
      y = self.loadingy - h / 2 + v * .5
      
      #akedrou - support for Loading Text Color
      c1,c2,c3 = self.textColor
      glColor3f(c1,c2,c3)
      
      # evilynux - Made text about 2 times smaller (as requested by worldrave)
      if self.allowtext:
        if self.theme == 1:
          wrapCenteredText(font, (x,y), self.text, scale = self.fScale, rightMargin = self.rMargin, linespace = self.lspacing, allowshadowoffset = True, shadowoffset = (Theme.shadowoffsetx, Theme.shadowoffsety))
        else:
          wrapCenteredText(font, (x,y), self.text, scale = self.fScale, rightMargin = self.rMargin, linespace = self.lspacing)
            
    finally:
      self.engine.view.resetProjection()
    
def showLoadingSplashScreen(engine, text = _("Loading...")):
  splash = LoadingSplashScreen(engine, text)
  engine.view.pushLayer(splash)
  engine.run()
  return splash

def changeLoadingSplashScreenText(engine, splash, text=_("Loading...")):
  splash.text = text
  engine.run()

def hideLoadingSplashScreen(engine, splash):
  engine.view.popLayer(splash)

def isInt(possibleInt):
  try:
    #MFH - remove any leading zeros (for songs with 01. or 02. for example)        
    splitName = possibleInt.split("0",1)
    while splitName[0] == "":
      splitName = possibleInt.split("0",1)
      if len(splitName) > 1:
        if splitName[0] == "":
          possibleInt = splitName[1]
    if str(int(possibleInt)) == str(possibleInt):
      #Log.debug("Dialogs.isInt: " + str(possibleInt) + " = TRUE")
      return True
    else:
      #Log.debug("Dialogs.isInt: " + str(possibleInt) + " = FALSE")
      return False
  except Exception, e:
    return False
    #Log.debug("Dialogs.isInt: " + str(possibleInt) + " = FALSE, exception: " + str(e) )


def removeSongOrderPrefixFromName(name):
  if not name.startswith("."):
    splitName = name.split(".",1)
    #Log.debug("Dialogs.songListLoaded: Separating song name from prefix: " + str(splitName) )
    if isInt(splitName[0]) and len(splitName) > 1:
      name = splitName[1]
      #while len(splitName) > 1: #now remove any remaining leading spaces
      splitName[0] = ""
      while splitName[0] == "":
        splitName = name.split(" ",1)
        if len(splitName) > 1:
          if splitName[0] == "":
            name = splitName[1]
            #Log.debug("Dialogs.songListLoaded: Removing song name prefix, new name = " + splitName[1])
  #else:
  #  Log.debug("Song name starting with a period filtered from prefix removal logic: " + name)
  return name