/usr/lib/python3/dist-packages/audiotools/ui.py is in audiotools 3.1.1-1+b1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | # Audio Tools, a module and set of tools for manipulating audio data
# Copyright (C) 2007-2015 Brian Langenberger
# 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 module for reusable GUI widgets"""
import audiotools
from audiotools import PY3, PY2
if PY3:
raw_input = input
try:
import urwid
if urwid.version.VERSION < (1, 0, 0):
raise ImportError()
def Screen():
from urwid.raw_display import Screen as __Screen__
return __Screen__()
AVAILABLE = True
class DownEdit(urwid.Edit):
"""a subclass of urwid.Edit which performs a down-arrow keypress
when the enter key is pressed,
typically for moving to the next element in a form"""
def __init__(self, *args, **kwargs):
urwid.Edit.__init__(self, *args, **kwargs)
self.__key_map__ = {"enter": "down"}
def keypress(self, size, key):
if key == "ctrl k":
self.set_edit_text(u"")
else:
return urwid.Edit.keypress(self, size,
self.__key_map__.get(key, key))
class DownIntEdit(urwid.IntEdit):
"""a subclass of urwid.IntEdit which performs a down-arrow keypress
when the enter key is pressed,
typically for moving to the next element in a form"""
def __init__(self, *args, **kwargs):
urwid.IntEdit.__init__(self, *args, **kwargs)
self.__key_map__ = {"enter": "down"}
def keypress(self, size, key):
if key == "ctrl k":
self.set_edit_text(u"0")
else:
return urwid.Edit.keypress(self, size,
self.__key_map__.get(key, key))
class DownCheckBox(urwid.CheckBox):
"""a subclass of urwid.CheckBox which performs a down-arrow keypress
when the enter key is pressed,
typically for moving to the next element in a form"""
def keypress(self, size, key):
if key == "enter":
return urwid.CheckBox.keypress(self, size, "down")
else:
return urwid.CheckBox.keypress(self, size, key)
class FocusFrame(urwid.Frame):
"""a special Frame widget which performs callbacks on focus changes"""
def __init__(self, *args, **kwargs):
urwid.Frame.__init__(self, *args, **kwargs)
self.focus_callback = None
self.focus_callback_arg = None
def set_focus_callback(self, callback, user_arg=None):
"""callback(widget, focus_part[, user_arg])
called when focus is set"""
self.focus_callback = callback
self.focus_callback_arg = user_arg
def set_focus(self, part):
urwid.Frame.set_focus(self, part)
if self.focus_callback is not None:
if self.focus_callback_arg is not None:
self.focus_callback(self, part, self.focus_callback_arg)
else:
self.focus_callback(self, part)
def get_focus(widget):
# something to smooth out the differences between Urwid versions
if hasattr(widget, "get_focus") and callable(widget.get_focus):
return widget.get_focus()
else:
return widget.focus_part
class OutputFiller(urwid.Frame):
"""a class for selecting MetaData and populating output parameters
for multiple input tracks"""
def __init__(self,
track_labels,
metadata_choices,
input_filenames,
output_directory,
format_string,
output_class,
quality,
completion_label=u"Apply"):
"""track_labels is a list of unicode strings, one per track
metadata_choices[c][t]
is a MetaData object for choice number "c" and track number "t"
all choices must have the same number of tracks
input_filenames is a list of Filename objects for input files
the number of input files must equal the number of metadata objects
in each metadata choice
output_directory is a string of the default output dir
format_string is a format string
output_class is the default AudioFile-compatible class
quality is a string of the default output quality to use
"""
self.__cancelled__ = True
# a few debug type checks
for label in track_labels:
assert(isinstance(label, str if PY3 else unicode))
assert(isinstance(output_directory, str))
assert(isinstance(format_string, str))
assert(isinstance(quality, str))
# ensure label count equals path count
assert(len(track_labels) == len(input_filenames))
# ensure there's at least one set of choices
assert(len(metadata_choices) > 0)
# ensure file path count is equal to metadata track count
assert(len(metadata_choices[0]) == len(input_filenames))
# ensure input filenames are Filename objects
for f in input_filenames:
assert(isinstance(f, audiotools.Filename))
from audiotools.text import LAB_CANCEL_BUTTON
# setup status bars for output messages
self.metadata_status = urwid.Text(u"")
self.options_status = urwid.Text(u"")
# setup a widget for populating metadata fields
self.metadata = MetaDataFiller(track_labels,
metadata_choices,
self.metadata_status)
# setup a widget for populating output parameters
self.options = OutputOptions(
output_dir=output_directory,
format_string=format_string,
audio_class=output_class,
quality=quality,
input_filenames=input_filenames,
metadatas=[None for t in input_filenames])
# finish initialization
self.wizard = Wizard([self.metadata,
self.options],
urwid.Button(LAB_CANCEL_BUTTON,
on_press=self.exit),
urwid.Button(completion_label,
on_press=self.complete),
self.page_changed)
urwid.Frame.__init__(self,
body=self.wizard,
footer=self.metadata_status)
def page_changed(self, new_page):
if new_page is self.metadata:
self.set_footer(self.metadata_status)
elif new_page is self.options:
self.options.set_metadatas(
list(self.metadata.populated_metadata()))
self.set_footer(self.options_status)
def exit(self, button):
self.__cancelled__ = True
raise urwid.ExitMainLoop()
def complete(self, button):
if self.options.has_collisions:
from audiotools.text import ERR_OUTPUT_OUTPUTS_ARE_INPUT
self.options_status.set_text(ERR_OUTPUT_OUTPUTS_ARE_INPUT)
elif self.options.has_duplicates:
from audiotools.text import ERR_OUTPUT_DUPLICATE_NAME
self.options_status.set_text(ERR_OUTPUT_DUPLICATE_NAME)
elif self.options.has_errors:
from audiotools.text import ERR_OUTPUT_INVALID_FORMAT
self.options_status.set_text(ERR_OUTPUT_INVALID_FORMAT)
else:
self.__cancelled__ = False
raise urwid.ExitMainLoop()
def cancelled(self):
"""returns True if the widget was cancelled,
False if exited normally"""
return self.__cancelled__
def handle_text(self, i):
if self.get_footer() is self.metadata_status:
if i == 'f1':
self.metadata.select_previous_item()
elif i == 'f2':
self.metadata.select_next_item()
def output_tracks(self):
"""yields (output_class,
output_filename,
output_quality,
output_metadata) tuple for each input audio file
output_metadata is a newly created MetaData object"""
# Note that output_tracks() creates new MetaData objects
# while process_output_options() reuses inputted MetaData objects.
# This is because we don't want to modify MetaData objects
# in the event they're being used elsewhere.
(audiofile_class,
quality,
output_filenames) = self.options.selected_options()
for (metadata,
output_filename) in zip(self.metadata.populated_metadata(),
output_filenames):
yield (audiofile_class,
output_filename,
quality,
metadata)
class SingleOutputFiller(urwid.Frame):
"""a class for selecting MetaData and populating output parameters
for a single input track"""
def __init__(self,
track_label,
metadata_choices,
input_filenames,
output_file,
output_class,
quality,
completion_label=u"Apply"):
"""track_label is a unicode string
metadata_choices is a list of MetaData objects,
one per possible metadata choice to apply
input_filenames is a list or set of Filename objects
output_file is a string of the default output filename
output_class is the default AudioFile-compatible class
quality is a string of the default output quality to use"""
# a few debut type checks
assert(isinstance(track_label, str if PY3 else unicode))
assert(isinstance(output_file, str))
assert(isinstance(quality, str))
assert(isinstance(completion_label, str if PY3 else unicode))
self.input_filenames = input_filenames
self.__cancelled__ = True
# ensure there's at least one choice
assert(len(metadata_choices) > 0)
# ensure input file is a Filename object
for f in input_filenames:
assert(isinstance(f, audiotools.Filename))
from audiotools.text import (LAB_CANCEL_BUTTON,
LAB_OUTPUT_OPTIONS)
# setup status bar for output messages
self.status = urwid.Text(u"")
# setup a widget for cancel/finish buttons
output_buttons = urwid.Filler(
urwid.Columns(
widget_list=[
('weight', 1, urwid.Button(LAB_CANCEL_BUTTON,
on_press=self.exit)),
('weight', 2, urwid.Button(completion_label,
on_press=self.complete))],
dividechars=3,
focus_column=1))
# setup a widget for populating output parameters
self.options = SingleOutputOptions(
output_filename=output_file,
audio_class=output_class,
quality=quality)
# combine metadata and output options into single widget
self.metadata = MetaDataFiller(
track_labels=[track_label],
metadata_choices=[[m] for m in metadata_choices],
status=self.status)
body = urwid.Pile(
[("weight", 1, self.metadata),
("fixed", 5, urwid.LineBox(self.options,
title=LAB_OUTPUT_OPTIONS)),
("fixed", 1, output_buttons)])
# finish initialization
urwid.Frame.__init__(self,
body=body,
footer=self.status)
def exit(self, button):
self.__cancelled__ = True
raise urwid.ExitMainLoop()
def complete(self, button):
output_filename = self.options.selected_options()[2]
# ensure output filename isn't same as input filename
if output_filename in self.input_filenames:
from audiotools.text import ERR_OUTPUT_IS_INPUT
self.status.set_text(
ERR_OUTPUT_IS_INPUT % (output_filename,))
else:
self.__cancelled__ = False
raise urwid.ExitMainLoop()
def cancelled(self):
return self.__cancelled__
def handle_text(self, i):
if i == 'esc':
self.exit(None)
elif i == 'f1':
self.metadata.select_previous_item()
elif i == 'f2':
self.metadata.select_next_item()
def output_track(self):
"""returns (output_class,
output_filename,
output_quality,
output_metadata)
output_metadata is a newly created MetaData object"""
(output_class,
output_quality,
output_filename) = self.options.selected_options()
return (output_class,
output_filename,
output_quality,
list(self.metadata.populated_metadata())[0])
class MetaDataFiller(urwid.Pile):
"""a class for selecting the MetaData to apply to tracks"""
def __init__(self, track_labels, metadata_choices, status):
"""track_labels is a list of unicode strings, one per track
metadata_choices[c][t]
is a MetaData object for choice number "c" and track number "t"
this widget allows the user to populate a set of MetaData objects
which can be applied to tracks
status is an urwid.Text object
"""
# a few debug type checks
for label in track_labels:
assert(isinstance(label, str if PY3 else unicode))
# there must be at least one choice
assert(len(metadata_choices) > 0)
# all choices must have at least 1 track
assert(min(map(len, metadata_choices)) > 0)
# and all choices must have the same number of tracks
assert(len(set(map(len, metadata_choices))) == 1)
from audiotools.text import (LAB_SELECT_BEST_MATCH,
LAB_TRACK_METADATA,
LAB_KEY_NEXT,
LAB_KEY_PREVIOUS)
self.metadata_choices = metadata_choices
self.status = status
# setup a MetaDataEditor for each possible match
self.edit_matches = [
MetaDataEditor(
[(i, label, track) for (i, (track, label)) in
enumerate(zip(choice, track_labels))],
on_swivel_change=self.swiveled)
for choice in metadata_choices]
self.selected_match = self.edit_matches[0]
# place selector at top only if there's more than one match
if len(metadata_choices) > 1:
# setup radio button for each possible match
matches = []
radios = [urwid.RadioButton(matches,
(choice[0].album_name
if (choice[0].album_name
is not None)
else u""),
on_state_change=self.select_match,
user_data=i)
for (i, choice) in enumerate(metadata_choices)]
for radio in radios:
radio._label.set_wrap_mode(urwid.CLIP)
# put radio buttons in pretty container
select_match = urwid.LineBox(urwid.ListBox(radios))
if hasattr(select_match, "set_title"):
select_match.set_title(LAB_SELECT_BEST_MATCH)
widgets = [("fixed",
len(metadata_choices) + 2,
select_match)]
else:
widgets = []
self.track_metadata = urwid.Frame(body=self.edit_matches[0])
widgets.append(("weight", 1,
urwid.LineBox(self.track_metadata,
title=LAB_TRACK_METADATA)))
urwid.Pile.__init__(self, widgets)
def select_match(self, radio, selected, match):
if selected:
self.selected_match = self.edit_matches[match]
self.track_metadata.set_body(self.selected_match)
def swiveled(self, radio_button, selected, swivel):
if selected:
from .text import (LAB_KEY_NEXT,
LAB_KEY_PREVIOUS)
keys = []
if radio_button.previous_radio_button() is not None:
keys.extend([('key', u"F1"),
LAB_KEY_PREVIOUS % (swivel.swivel_type)])
if radio_button.next_radio_button() is not None:
if len(keys) > 0:
keys.append(u" ")
keys.extend([('key', u"F2"),
LAB_KEY_NEXT % (swivel.swivel_type)])
if len(keys) > 0:
self.status.set_text(keys)
else:
self.status.set_text(u"")
def select_previous_item(self):
"""selects the previous item (track or field)
if possible"""
self.selected_match.select_previous_item()
def select_next_item(self):
"""selects the next item (track or field)
if possible"""
self.selected_match.select_next_item()
def populated_metadata(self):
"""yields a new, populated MetaData object per track,
depending on the current selection and its values."""
for (track_id, metadata) in self.selected_match.metadata():
yield metadata
class MetaDataEditor(urwid.Frame):
"""a class for editing MetaData values for a set of tracks"""
def __init__(self, tracks,
on_text_change=None,
on_swivel_change=None):
"""tracks is a list of (id, label, MetaData) tuples
in the order they are to be displayed
where id is some unique hashable ID value
label is a unicode string
and MetaData is an audiotools.MetaData-compatible object or None
on_text_change is a callback for when any text field is modified
on_swivel_change is a callback for when
tracks and fields are swapped
"""
for (id, label, metadata) in tracks:
assert(isinstance(label, str if PY3 else unicode))
# a list of track IDs in the order they appear
self.track_ids = []
# a list of (track_id, label) tuples
# in the order they should appear
track_labels = []
# the order metadata fields should appear
field_labels = [(attr, audiotools.MetaData.FIELD_NAMES[attr])
for attr in audiotools.MetaData.FIELD_ORDER]
# a dict of track_id->TrackMetaData values
self.metadata_edits = {}
# determine the base metadata all others should be linked against
base_metadata = {}
for (track_id, track_label, metadata) in tracks:
self.track_ids.append(track_id)
for (attr, value) in (metadata if metadata is not None
else audiotools.MetaData()).fields():
base_metadata.setdefault(attr, set()).add(value)
base_metadata = BaseMetaData(
metadata=audiotools.MetaData(
**{field: list(values)[0]
for (field, values) in base_metadata.items()
if (len(values) == 1)}),
on_change=on_text_change)
# populate the track_labels and metadata_edits lookup tables
for (track_id, track_label, metadata) in tracks:
if track_id not in self.metadata_edits:
track_labels.append((track_id, track_label))
self.metadata_edits[track_id] = TrackMetaData(
metadata=(metadata if metadata is not None
else audiotools.MetaData()),
base_metadata=base_metadata,
on_change=on_text_change)
else:
# no_duplicates via open_files should filter this case
raise ValueError("same track ID cannot appear twice")
swivel_radios = []
track_radios_order = []
track_radios = {}
field_radios_order = []
field_radios = {}
# generate radio buttons for track labels
for (track_id, track_label) in track_labels:
radio = OrderedRadioButton(ordered_group=track_radios_order,
group=swivel_radios,
label=('label', track_label),
state=False)
swivel = Swivel(
swivel_type=u"track",
left_top_widget=urwid.Text(('label', 'fields')),
left_alignment='fixed',
left_width=4 + max(len(label) for _,label in field_labels),
left_radios=field_radios,
left_ids=[field_id for (field_id, label) in field_labels],
right_top_widget=urwid.Text(('label', track_label),
wrap=urwid.CLIP),
right_alignment='weight',
right_width=1,
right_widgets=[getattr(self.metadata_edits[track_id],
field_id)
for (field_id, label) in field_labels])
radio._label.set_wrap_mode(urwid.CLIP)
urwid.connect_signal(radio,
'change',
self.activate_swivel,
swivel)
if on_swivel_change is not None:
urwid.connect_signal(radio,
'change',
on_swivel_change,
swivel)
track_radios[track_id] = radio
# generate radio buttons for metadata labels
for (field_id, field_label) in field_labels:
radio = OrderedRadioButton(ordered_group=field_radios_order,
group=swivel_radios,
label=('label', field_label),
state=False)
swivel = Swivel(
swivel_type=u"field",
left_top_widget=urwid.Text(('label', u'files')),
left_alignment='weight',
left_width=1,
left_radios=track_radios,
left_ids=[track_id for (track_id, track)
in track_labels],
right_top_widget=urwid.Text(('label', field_label)),
right_alignment='weight',
right_width=2,
right_widgets=[getattr(self.metadata_edits[track_id],
field_id)
for (track_id, track) in track_labels])
radio._label.set_align_mode('right')
urwid.connect_signal(radio,
'change',
self.activate_swivel,
swivel)
if on_swivel_change is not None:
urwid.connect_signal(radio,
'change',
on_swivel_change,
swivel)
field_radios[field_id] = radio
urwid.Frame.__init__(
self,
header=urwid.Columns(
[("fixed", 1, urwid.Text(u"")),
("weight", 1, urwid.Text(u""))]),
body=urwid.ListBox([]))
if len(self.metadata_edits) != 1:
# if more than one track, select track_name radio button
field_radios["track_name"].set_state(True)
else:
# if only one track, select that track's radio button
track_radios[track_labels[0][0]].set_state(True)
def activate_swivel(self, radio_button, selected, swivel):
if selected:
self.selected_radio = radio_button
# add new entries according to swivel's values
self.set_body(
urwid.ListBox(
[urwid.Columns([(swivel.left_alignment,
swivel.left_width,
left_widget),
(swivel.right_alignment,
swivel.right_width,
right_widget)])
for (left_widget,
right_widget) in swivel.rows()]))
# update header with swivel's values
self.set_header(
urwid.Columns(
[(swivel.left_alignment,
swivel.left_width,
urwid.Text(u"")),
(swivel.right_alignment,
swivel.right_width,
LinkedWidgetHeader(swivel.right_top_widget))]))
else:
pass
def select_previous_item(self):
previous_radio = self.selected_radio.previous_radio_button()
if previous_radio is not None:
previous_radio.set_state(True)
def select_next_item(self):
next_radio = self.selected_radio.next_radio_button()
if next_radio is not None:
next_radio.set_state(True)
def metadata(self):
"""yields a (track_id, MetaData) tuple
per edited metadata track
MetaData objects are newly created"""
for track_id in self.track_ids:
yield (track_id,
self.metadata_edits[track_id].edited_metadata())
class OrderedRadioButton(urwid.RadioButton):
def __init__(self, ordered_group, group, label,
state='first True', on_state_change=None, user_data=None):
urwid.RadioButton.__init__(self,
group,
label,
state,
on_state_change,
user_data)
ordered_group.append(self)
self.ordered_group = ordered_group
def previous_radio_button(self):
for (current_radio,
previous_radio) in zip(self.ordered_group,
[None] + self.ordered_group):
if current_radio is self:
return previous_radio
else:
return None
def next_radio_button(self):
for (current_radio,
next_radio) in zip(self.ordered_group,
self.ordered_group[1:] + [None]):
if current_radio is self:
return next_radio
else:
return None
class LinkedWidgetHeader(urwid.Columns):
def __init__(self, widget):
urwid.Columns.__init__(self,
[("fixed", 3, urwid.Text(u" ")),
("weight", 1, widget),
("fixed", 4, urwid.Text(u""))])
class LinkedWidgetDivider(urwid.Columns):
def __init__(self):
urwid.Columns.__init__(
self,
[("fixed", 3, urwid.Text(u"\u2500\u2534\u2500")),
("weight", 1, urwid.Divider(u"\u2500")),
("fixed", 4, urwid.Text(u"\u2500" * 4))])
class LinkedWidgets(urwid.Columns):
def __init__(self, checkbox_group, linked_widget, unlinked_widget,
initially_linked):
"""linked_widget is shown when the linking checkbox is checked
otherwise unlinked_widget is shown"""
self.linked_widget = linked_widget
self.unlinked_widget = unlinked_widget
self.checkbox_group = checkbox_group
self.checkbox = urwid.CheckBox(u"",
state=initially_linked,
on_state_change=self.swap_link)
self.checkbox_group.append(self.checkbox)
urwid.Columns.__init__(
self,
[("fixed", 3, urwid.Text(u" : ")),
("weight", 1,
linked_widget if initially_linked else unlinked_widget),
("fixed", 4, self.checkbox)])
def swap_link(self, checkbox, linked):
if linked:
# if nothing else linked in this checkbox group,
# set linked text to whatever the last unlinked text as
if ({cb.get_state() for cb in self.checkbox_group
if (cb is not checkbox)} == {False}):
if (hasattr(self.linked_widget, "set_edit_text") and
hasattr(self.unlinked_widget, "get_edit_text")):
self.linked_widget.set_edit_text(
self.unlinked_widget.get_edit_text())
elif (hasattr(self.linked_widget, "set_state") and
hasattr(self.unlinked_widget, "get_state")):
self.linked_widget.set_state(
self.unlinked_widget.get_state())
self.widget_list[1] = self.linked_widget
self.set_focus(2)
else:
# set unlinked text to whatever the last linked text was
if (hasattr(self.unlinked_widget, "set_edit_text") and
hasattr(self.linked_widget, "get_edit_text")):
self.unlinked_widget.set_edit_text(
self.linked_widget.get_edit_text())
elif (hasattr(self.unlinked_widget, "set_state") and
hasattr(self.linked_widget, "get_state")):
self.unlinked_widget.set_state(
self.linked_widget.get_state())
self.widget_list[1] = self.unlinked_widget
self.set_focus(2)
def value(self):
if self.checkbox.get_state():
widget = self.linked_widget
else:
widget = self.unlinked_widget
if type(widget) is DownIntEdit:
if len(widget.edit_text) > 0:
return widget.value()
else:
return None
elif type(widget) is DownEdit:
if len(widget.get_edit_text()) > 0:
return widget.get_edit_text()
else:
return None
elif type(widget) is DownCheckBox:
if widget.get_state():
return True
else:
return None
else:
return None
class BaseMetaData(object):
def __init__(self, metadata, on_change=None):
"""metadata is a MetaData object
on_change is a callback for when the text field is modified"""
self.metadata = metadata
self.checkbox_groups = {}
for field, field_type in metadata.FIELD_TYPES.items():
if field_type is type(u""):
value = getattr(metadata, field)
widget = DownEdit(edit_text=value if value is not None
else u"")
elif field_type is int:
value = getattr(metadata, field)
widget = DownIntEdit(default=value if value is not None
else None)
elif field_type is bool:
value = getattr(metadata, field)
widget = DownCheckBox(u"",
state=value if value is not None
else False)
if on_change is not None:
urwid.connect_signal(widget, 'change', on_change)
setattr(self, field, widget)
self.checkbox_groups[field] = []
class TrackMetaData(object):
NEVER_LINK = {"track_name", "track_number", "ISRC"}
def __init__(self, metadata, base_metadata, on_change=None):
"""metadata is a MetaData object
base_metadata is a BaseMetaData object to link against
on_change is a callback for when the text field is modified"""
for field, field_type in metadata.FIELD_TYPES.items():
if field_type is type(u""):
value = getattr(metadata, field)
widget = DownEdit(edit_text=value if value is not None
else u"")
elif field_type is int:
value = getattr(metadata, field)
widget = DownIntEdit(default=value if value is not None
else None)
elif field_type is bool:
value = getattr(metadata, field)
widget = DownCheckBox(u"",
state=value if value is not None
else False)
if on_change is not None:
urwid.connect_signal(widget, 'change', on_change)
linked_widget = LinkedWidgets(
checkbox_group=base_metadata.checkbox_groups[field],
linked_widget=getattr(base_metadata, field),
unlinked_widget=widget,
initially_linked=((field not in self.NEVER_LINK) and
(getattr(metadata,
field) ==
getattr(base_metadata.metadata,
field))))
setattr(self, field, linked_widget)
def edited_metadata(self):
"""returns a new MetaData object of the track's
current value based on its widgets' values"""
return audiotools.MetaData(
**{attr: value for (attr, value) in
[(attr, getattr(self, attr).value())
for attr in audiotools.MetaData.FIELDS]
if value is not None})
class Swivel(object):
"""this is a container for the objects of a swiveling operation"""
def __init__(self, swivel_type,
left_top_widget,
left_alignment,
left_width,
left_radios,
left_ids,
right_top_widget,
right_alignment,
right_width,
right_widgets):
assert(len(left_ids) == len(right_widgets))
self.swivel_type = swivel_type
self.left_top_widget = left_top_widget
self.left_alignment = left_alignment
self.left_width = left_width
self.left_radios = left_radios
self.left_ids = left_ids
self.right_top_widget = right_top_widget
self.right_alignment = right_alignment
self.right_width = right_width
self.right_widgets = right_widgets
def rows(self):
for (left_id, right_widget) in zip(self.left_ids,
self.right_widgets):
yield (self.left_radios[left_id], right_widget)
def tab_complete(path):
"""given a partially-completed directory path string
returns a path string completed as far as possible
"""
import os.path
(base, remainder) = os.path.split(path)
if os.path.isdir(base):
try:
candidate_dirs = [d for d in os.listdir(base)
if (d.startswith(remainder) and
os.path.isdir(os.path.join(base, d)))]
if len(candidate_dirs) == 0:
# no possible matches to tab complete
return path
elif len(candidate_dirs) == 1:
# one possible match to tab complete
return os.path.join(base, candidate_dirs[0]) + os.sep
else:
# multiple possible matches to tab complete
# so complete as much as possible
return os.path.join(base,
os.path.commonprefix(candidate_dirs))
except OSError:
# unable to read base dir to complete the rest
return path
else:
# base doesn't exist,
# so we don't know how to complete the rest
return path
def tab_complete_file(path):
"""given a partially-completed file path string
returns a path string completed as far as possible"""
import os.path
(base, remainder) = os.path.split(path)
if os.path.isdir(base):
try:
candidates = [f for f in os.listdir(base)
if f.startswith(remainder)]
if len(candidates) == 0:
# no possible matches to tab complete
return path
elif len(candidates) == 1:
# one possible match to tab complete
path = os.path.join(base, candidates[0])
if os.path.isdir(path):
return path + os.sep
else:
return path
else:
# multiple possible matches to tab complete
# so complete as much as possible
return os.path.join(base,
os.path.commonprefix(candidates))
except OSError:
# unable to read base dir to complete the rest
return path
else:
# base doesn't exist,
# so we don't know how to complete the rest
return path
def pop_directory(path):
"""given a path string,
returns a new path string with one directory removed if possible"""
import os.path
base = os.path.split(path.rstrip(os.sep))[0]
if base == '':
return base
elif not base.endswith(os.sep):
return base + os.sep
else:
return base
def split_at_cursor(edit):
"""returns a (prefix, suffix) unicode pair
of text before and after the urwid.Edit widget's cursor"""
return (edit.get_edit_text()[0:edit.edit_pos],
edit.get_edit_text()[edit.edit_pos:])
class SelectButtons(urwid.Pile):
def __init__(self, widget_list, focus_item=None, cancelled=None):
"""cancelled is a callback which is called
when the esc key is pressed
it takes no arguments"""
urwid.Pile.__init__(self, widget_list, focus_item)
self.cancelled = cancelled
def keypress(self, size, key):
key = urwid.Pile.keypress(self, size, key)
if (key == "esc") and (self.cancelled is not None):
self.cancelled()
return
else:
return key
class BottomLineBox(urwid.LineBox):
"""a LineBox that places its title at the bottom instead of the top"""
def __init__(self, original_widget, title="",
tlcorner=u"\u250c", tline=u"\u2500", lline=u"\u2502",
trcorner=u"\u2510", blcorner=u"\u2514", rline=u"\u2502",
bline=u"\u2500", brcorner=u"\u2518"):
tline, bline = urwid.Divider(tline), urwid.Divider(bline)
lline, rline = urwid.SolidFill(lline), urwid.SolidFill(rline)
tlcorner, trcorner = urwid.Text(tlcorner), urwid.Text(trcorner)
blcorner, brcorner = urwid.Text(blcorner), urwid.Text(brcorner)
self.title_widget = urwid.Text(self.format_title(title))
self.tline_widget = urwid.Columns(
[tline, ('flow', self.title_widget), tline])
top = urwid.Columns(
[('fixed', 1, tlcorner), bline, ('fixed', 1, trcorner)])
middle = urwid.Columns(
[('fixed', 1, lline), original_widget, ('fixed', 1, rline)],
box_columns=[0, 2],
focus_column=1)
bottom = urwid.Columns(
[('fixed', 1, blcorner),
self.tline_widget,
('fixed', 1, brcorner)])
pile = urwid.Pile(
[('flow', top), middle, ('flow', bottom)], focus_item=1)
urwid.WidgetDecoration.__init__(self, original_widget)
urwid.WidgetWrap.__init__(self, pile)
class SelectOneDialog(urwid.WidgetWrap):
signals = ['close']
def __init__(self, select_one, items, selected_value,
label=None):
self.select_one = select_one
self.items = items
selected_button = 0
buttons = []
for (i, (l, value)) in enumerate(items):
buttons.append(urwid.Button(label=l,
on_press=self.select_button,
user_data=(l, value)))
if value == selected_value:
selected_button = i
pile = SelectButtons(buttons,
selected_button,
lambda: self._emit("close"))
fill = urwid.Filler(pile)
if label is not None:
linebox = urwid.LineBox(fill, title=label)
else:
linebox = urwid.LineBox(fill)
self.__super.__init__(linebox)
def select_button(self, button, label_value):
(label, value) = label_value
self.select_one.make_selection(label, value)
self._emit("close")
class SelectOne(urwid.PopUpLauncher):
def __init__(self, items, selected_value=None, on_change=None,
user_data=None, label=None):
"""items is a list of (unicode, value) tuples
where value can be any sort of object
selected_value is a selected object
on_change is a callback which takes a new selected object
which is called as on_change(new_value, [user_data])
label is a unicode label string for the selection box"""
self.__select_button__ = urwid.Button(u"")
self.__super.__init__(self.__select_button__)
urwid.connect_signal(
self.original_widget,
'click',
lambda button: self.open_pop_up())
assert(len(items) > 0)
self.__items__ = items
self.__selected_value__ = None # set by make_selection, below
self.__on_change__ = None
self.__user_data__ = None
self.__label__ = label
if selected_value is not None:
try:
(label, value) = [pair for pair in items
if pair[1] == selected_value][0]
except IndexError:
(label, value) = items[0]
else:
(label, value) = items[0]
self.make_selection(label, value)
self.__on_change__ = on_change
self.__user_data__ = user_data
def create_pop_up(self):
pop_up = SelectOneDialog(self,
self.__items__,
self.__selected_value__,
self.__label__)
urwid.connect_signal(
pop_up,
'close',
lambda button: self.close_pop_up())
return pop_up
def get_pop_up_parameters(self):
return {'left': 0,
'top': 1,
'overlay_width': max([4 + len(i[0]) for i in
self.__items__]) + 2,
'overlay_height': len(self.__items__) + 2}
def make_selection(self, label, value):
self.__select_button__.set_label(label)
self.__selected_value__ = value
if self.__on_change__ is not None:
if self.__user_data__ is not None:
self.__on_change__(value, self.__user_data__)
else:
self.__on_change__(value)
def selection(self):
return self.__selected_value__
def set_items(self, items, selected_value):
self.__items__ = items
self.make_selection([label for (label, value) in items if
value is selected_value][0],
selected_value)
class SelectDirectory(urwid.Columns):
def __init__(self, initial_directory, on_change=None, user_data=None):
self.edit = EditDirectory(initial_directory)
urwid.Columns.__init__(self,
[('weight', 1, self.edit),
('fixed', 10, BrowseDirectory(self.edit))])
if on_change is not None:
urwid.connect_signal(self.edit,
'change',
on_change,
user_data)
def set_directory(self, directory):
# FIXME - allow this to be assigned externally
raise NotImplementedError()
def get_directory(self):
return self.edit.get_directory()
class EditDirectory(urwid.Edit):
def __init__(self, initial_directory):
"""initial_directory is a plain string
in the default filesystem encoding
this directory has username expanded
and is converted to the absolute path"""
import os.path
FS_ENCODING = audiotools.FS_ENCODING
urwid.Edit.__init__(
self,
edit_text=audiotools.Filename(
initial_directory).expanduser().abspath().__unicode__(),
wrap='clip',
allow_tab=False)
def keypress(self, size, key):
key = urwid.Edit.keypress(self, size, key)
FS_ENCODING = audiotools.FS_ENCODING
import os.path
if key == 'tab':
# only tab complete stuff before cursor
(prefix, suffix) = split_at_cursor(self)
new_prefix = tab_complete(
str(audiotools.Filename.from_unicode(
prefix).expanduser().abspath()))
if PY2:
new_prefix = new_prefix.decode(FS_ENCODING)
self.set_edit_text(new_prefix + suffix)
self.set_edit_pos(len(new_prefix))
elif key == 'ctrl w':
# only delete stuff before cursor
(prefix, suffix) = split_at_cursor(self)
new_prefix = pop_directory(
str(audiotools.Filename.from_unicode(
prefix).expanduser().abspath()))
if PY2:
new_prefix = new_prefix.decode(FS_ENCODING)
self.set_edit_text(new_prefix + suffix)
self.set_edit_pos(len(new_prefix))
elif key == 'ctrl k':
# delete entire line
self.set_edit_text(u"")
self.set_edit_pos(0)
else:
return key
def set_directory(self, directory):
"""directory is a plain directory string to set"""
assert(isinstance(directory, str))
if PY2:
directory = directory.decode(audiotools.FS_ENCODING)
self.set_edit_text(directory)
self.set_edit_pos(len(directory))
def get_directory(self):
"""returns selected directory as a plain string"""
directory = self.get_edit_text()
if PY2:
directory = directory.encode(audiotools.FS_ENCODING)
return directory
class BrowseDirectory(urwid.PopUpLauncher):
def __init__(self, edit_directory):
"""edit_directory is an EditDirectory object"""
from audiotools.text import LAB_BROWSE_BUTTON
self.__super.__init__(
urwid.Button(LAB_BROWSE_BUTTON,
on_press=lambda button: self.open_pop_up()))
self.edit_directory = edit_directory
def create_pop_up(self):
pop_up = BrowseDirectoryDialog(self.edit_directory)
urwid.connect_signal(pop_up, "close",
lambda button: self.close_pop_up())
return pop_up
def get_pop_up_parameters(self):
# FIXME - make these values dynamic
# based on edit_directory's location
return {'left': 0,
'top': 1,
'overlay_width': 70,
'overlay_height': 20}
class BrowseDirectoryDialog(urwid.WidgetWrap):
signals = ['close']
def __init__(self, edit_directory):
"""edit_directory is an EditDirectory object"""
from audiotools.text import (LAB_KEY_SELECT,
LAB_KEY_TOGGLE_OPEN,
LAB_KEY_CANCEL,
LAB_CHOOSE_DIRECTORY)
browser = DirectoryBrowser(
edit_directory.get_directory(),
directory_selected=self.select_directory,
cancelled=lambda: self._emit("close"))
frame = urwid.LineBox(urwid.Frame(
body=browser,
footer=urwid.Text([('key', 'enter'),
LAB_KEY_SELECT,
u" ",
('key', 'space'),
LAB_KEY_TOGGLE_OPEN,
u" ",
('key', 'esc'),
LAB_KEY_CANCEL])),
title=LAB_CHOOSE_DIRECTORY)
self.__super.__init__(frame)
self.edit_directory = edit_directory
def select_directory(self, selected_directory):
self.edit_directory.set_directory(selected_directory)
self._emit("close")
class DirectoryBrowser(urwid.TreeListBox):
def __init__(self, initial_directory,
directory_selected=None,
cancelled=None):
import os
import os.path
def path_iter(path):
if path == os.sep:
yield path
else:
path = path.rstrip(os.sep)
if len(path) > 0:
(head, tail) = os.path.split(path)
for part in path_iter(head):
yield part
yield tail
else:
return
topnode = DirectoryNode(os.sep)
for path_part in path_iter(
os.path.abspath(
os.path.expanduser(initial_directory))):
try:
if path_part == "/":
node = topnode
else:
node = node.get_child_node(path_part)
widget = node.get_widget()
widget.expanded = True
widget.update_expanded_icon()
except urwid.treetools.TreeWidgetError:
break
urwid.TreeListBox.__init__(self, urwid.TreeWalker(topnode))
self.set_focus(node)
self.directory_selected = directory_selected
self.cancelled = cancelled
def selected_directory(self):
import os
import os.path
def focused_nodes():
(widget, node) = self.get_focus()
while not node.is_root():
yield node.get_key()
node = node.get_parent()
else:
yield os.sep
return os.path.join(*reversed(list(focused_nodes()))) + os.sep
def unhandled_input(self, size, input):
input = urwid.TreeListBox.unhandled_input(self, size, input)
if input == 'enter':
if self.directory_selected is not None:
self.directory_selected(self.selected_directory())
else:
return input
elif input == 'esc':
if self.cancelled is not None:
self.cancelled()
else:
return input
else:
return input
class DirectoryWidget(urwid.TreeWidget):
indent_cols = 1
def __init__(self, node):
self.__super.__init__(node)
self.expanded = False
self.update_expanded_icon()
def keypress(self, size, key):
key = urwid.TreeWidget.keypress(self, size, key)
if key == " ":
self.expanded = not self.expanded
self.update_expanded_icon()
else:
return key
def get_display_text(self):
node = self.get_node()
if node.get_depth() == 0:
return "/"
else:
return node.get_key()
class ErrorWidget(urwid.TreeWidget):
indent_cols = 1
def get_display_text(self):
return ('error', u"(error/permission denied)")
class ErrorNode(urwid.TreeNode):
def load_widget(self):
return ErrorWidget(self)
class DirectoryNode(urwid.ParentNode):
def __init__(self, path, parent=None):
import os
import os.path
if path == os.sep:
urwid.ParentNode.__init__(self,
value=path,
key=None,
parent=parent,
depth=0)
else:
urwid.ParentNode.__init__(self,
value=path,
key=os.path.basename(path),
parent=parent,
depth=path.count(os.sep))
def load_parent(self):
import os.path
(parentname, myname) = os.path.split(self.get_value())
parent = DirectoryNode(parentname)
parent.set_child_node(self.get_key(), self)
return parent
def load_child_keys(self):
import os.path
dirs = []
try:
path = self.get_value()
for d in sorted(os.listdir(path)):
if ((not d.startswith(".")) and
os.path.isdir(
os.path.join(path, d))):
dirs.append(d)
except OSError as e:
depth = self.get_depth() + 1
self._children[None] = ErrorNode(self, parent=self, key=None,
depth=depth)
return [None]
return dirs
def load_child_node(self, key):
"""Return a DirectoryNode"""
import os.path
index = self.get_child_index(key)
path = os.path.join(self.get_value(), key)
return DirectoryNode(path, parent=self)
def load_widget(self):
return DirectoryWidget(self)
class EditFilename(urwid.Edit):
def __init__(self, initial_filename):
"""initial_filename is a plain string
in the default filesystem encoding
this filename has username expanded
and is converted to the absolute path"""
import os.path
FS_ENCODING = audiotools.FS_ENCODING
urwid.Edit.__init__(
self,
edit_text=audiotools.Filename(
initial_filename).expanduser().abspath().__unicode__(),
wrap="clip",
allow_tab=False)
def keypress(self, size, key):
key = urwid.Edit.keypress(self, size, key)
import os.path
FS_ENCODING = audiotools.FS_ENCODING
if key == 'tab':
# only tab complete stuff before cursor
(prefix, suffix) = split_at_cursor(self)
new_prefix = tab_complete(
str(audiotools.Filename.from_unicode(
prefix).expanduser().abspath()))
if PY2:
new_prefix = new_prefix.decode(FS_ENCODING)
self.set_edit_text(new_prefix + suffix)
self.set_edit_pos(len(new_prefix))
elif key == 'ctrl w':
# only delete stuff before cursor
(prefix, suffix) = split_at_cursor(self)
new_prefix = pop_directory(
str(audiotools.Filename.from_unicode(
prefix).expanduser().abspath()))
if PY2:
new_prefix = new_prefix.decode(FS_ENCODING)
self.set_edit_text(new_prefix + suffix)
self.set_edit_pos(len(new_prefix))
elif key == 'ctrl k':
# delete entire line
self.set_edit_text(u"")
self.set_edit_pos(0)
else:
return key
def set_filename(self, filename):
"""filename is a string to set"""
assert(isinstance(filename, str))
if PY2:
filename = filename.decode(audiotools.FS_ENCODING)
self.set_edit_text(filename)
self.set_edit_pos(len(filename))
def get_filename(self):
"""returns selected filename as a string"""
filename = self.get_edit_text()
if PY2:
filename = filename.encode(audiotools.FS_ENCODING)
return filename
class BrowseFields(urwid.PopUpLauncher):
def __init__(self, output_format):
"""output_format is an Edit object"""
from audiotools.text import LAB_FIELDS_BUTTON
self.__super.__init__(
urwid.Button(LAB_FIELDS_BUTTON,
on_press=lambda button: self.open_pop_up()))
self.output_format = output_format
def create_pop_up(self):
pop_up = BrowseFieldsDialog(self.output_format)
urwid.connect_signal(pop_up, "close",
lambda button: self.close_pop_up())
return pop_up
def get_pop_up_parameters(self):
return {
'left': 0,
'top': 1,
'overlay_width': (max([len(label) + 4
for (string, label) in
audiotools.FORMAT_FIELDS.values()]) +
2),
'overlay_height': len(audiotools.FORMAT_FIELDS.values()) + 2}
class BrowseFieldsDialog(urwid.WidgetWrap):
signals = ['close']
def __init__(self, output_format):
from audiotools.text import (LAB_KEY_CANCEL,
LAB_KEY_CLEAR_FORMAT,
LAB_ADD_FIELD)
self.__super.__init__(
urwid.LineBox(
urwid.Frame(body=FieldsList(output_format, self.close),
footer=urwid.Text([('key', 'del'),
LAB_KEY_CLEAR_FORMAT,
u" ",
('key', 'esc'),
LAB_KEY_CANCEL])),
title=LAB_ADD_FIELD))
def close(self):
self._emit("close")
class FieldsList(urwid.ListBox):
def __init__(self, output_format, close):
urwid.ListBox.__init__(
self,
[urwid.Button(label,
on_press=self.select_field,
user_data=(output_format, string))
for (string, label) in
[audiotools.FORMAT_FIELDS[field] for field in
audiotools.FORMAT_FIELD_ORDER]])
self.output_format = output_format
self.close = close
def select_field(self, button, field_value):
(field, value) = field_value
field.insert_text(value)
self.close()
def cancel(self):
self.close()
def keypress(self, size, input):
input = urwid.ListBox.keypress(self, size, input)
if input == 'esc':
self.cancel()
elif input == 'delete':
self.output_format.set_edit_text(u"")
else:
return input
class OutputOptions(urwid.Pile):
"""a widget for selecting the typical set of output options
for multiple input files: --dir, --format, --type, --quality"""
def __init__(self,
output_dir,
format_string,
audio_class,
quality,
input_filenames,
metadatas,
extra_widgets=None):
"""
| field | value | meaning |
|-----------------+------------+----------------------------------|
| output_dir | string | default output directory |
| format_string | string | format string to use for files |
| audio_class | AudioFile | audio class of output files |
| quality | string | quality level of output |
| input_filenames | [Filename] | Filename objects for input files |
| metadatas | [MetaData] | MetaData objects for input files |
note that the length of input_filenames
must equal length of metadatas
"""
# a few debug type checks
assert(isinstance(output_dir, str))
assert(isinstance(format_string, str))
assert(isinstance(quality, str))
assert(len(input_filenames) == len(metadatas))
for f in input_filenames:
assert(isinstance(f, audiotools.Filename))
from audiotools.text import (ERR_INVALID_FILENAME_FORMAT,
LAB_OPTIONS_FILENAME_FORMAT,
LAB_OUTPUT_OPTIONS,
LAB_OPTIONS_OUTPUT_DIRECTORY,
LAB_OPTIONS_AUDIO_CLASS,
LAB_OPTIONS_AUDIO_QUALITY,
LAB_OPTIONS_OUTPUT_FILES,
LAB_OPTIONS_OUTPUT_FILES_1)
self.input_filenames = input_filenames
self.metadatas = metadatas
self.selected_class = audio_class
self.selected_quality = quality
self.has_collisions = False # if input files same as output
self.has_duplicates = False # if any track names are duplicates
self.has_errors = False # if format string is invalid
self.output_format = urwid.Edit(
edit_text=(format_string if PY3 else
format_string.decode('utf-8')),
wrap='clip')
urwid.connect_signal(self.output_format,
'change',
self.format_changed)
self.browse_fields = BrowseFields(self.output_format)
self.output_directory = SelectDirectory(output_dir,
self.directory_changed)
self.output_tracks_frame = urwid.Frame(
body=urwid.Filler(urwid.Text(u"")))
output_tracks_frame_linebox = urwid.LineBox(
self.output_tracks_frame,
title=(LAB_OPTIONS_OUTPUT_FILES if
(len(input_filenames) != 1) else
LAB_OPTIONS_OUTPUT_FILES_1))
self.output_tracks = [urwid.Text(u"") for path in input_filenames]
self.output_tracks_list = urwid.ListBox(self.output_tracks)
self.invalid_output_format = urwid.Filler(
urwid.Text(ERR_INVALID_FILENAME_FORMAT,
align="center"))
self.output_quality = SelectOne(
items=[(u"N/A", "")],
label=LAB_OPTIONS_AUDIO_QUALITY)
self.output_type = SelectOne(
items=sorted([(u"%s - %s" % (t.NAME, t.DESCRIPTION), t)
for t in audiotools.AVAILABLE_TYPES
if t.supports_from_pcm()],
key=lambda pair: pair[0]),
selected_value=audio_class,
on_change=self.select_type,
label=LAB_OPTIONS_AUDIO_CLASS)
self.select_type(audio_class, quality)
header = urwid.Pile(
[urwid.Columns([('fixed', 10,
urwid.Text(('label',
u"%s : " %
(LAB_OPTIONS_OUTPUT_DIRECTORY)),
align="right")),
('weight', 1, self.output_directory)]),
urwid.Columns([('fixed', 10,
urwid.Text(('label',
u"%s : " %
(LAB_OPTIONS_FILENAME_FORMAT)),
align="right")),
('weight', 1, self.output_format),
('fixed', 10, self.browse_fields)]),
urwid.Columns([('fixed', 10,
urwid.Text(('label',
u"%s : " %
(LAB_OPTIONS_AUDIO_CLASS)),
align="right")),
('weight', 1, self.output_type)]),
urwid.Columns([('fixed', 10,
urwid.Text(('label',
u"%s : " %
(LAB_OPTIONS_AUDIO_QUALITY)),
align="right")),
('weight', 1, self.output_quality)])])
widgets = [('fixed', 6,
urwid.Filler(urwid.LineBox(
header,
title=LAB_OUTPUT_OPTIONS))),
('weight', 1, output_tracks_frame_linebox)]
if extra_widgets is not None:
widgets.extend(extra_widgets)
urwid.Pile.__init__(self, widgets)
self.update_tracks()
def select_type(self, audio_class, default_quality=None):
self.selected_class = audio_class
if len(audio_class.COMPRESSION_MODES) < 2:
# one audio quality for selected type
try:
quality = audio_class.COMPRESSION_MODES[0]
except IndexError:
# this shouldn't happen, but just in case
quality = ""
self.output_quality.set_items([(u"N/A", quality)], quality)
else:
# two or more audio qualities for selected type
qualities = audio_class.COMPRESSION_MODES
if default_quality is not None:
default = [q for q in qualities if
q == default_quality][0]
else:
default = [q for q in qualities if
q == audio_class.DEFAULT_COMPRESSION][0]
self.output_quality.set_items(
[(u"%s" % (q,) if q not in
audio_class.COMPRESSION_DESCRIPTIONS else
u"%s - %s" % (q,
audio_class.COMPRESSION_DESCRIPTIONS[q]),
q)
for q in qualities],
default)
self.update_tracks()
def directory_changed(self, widget, new_value):
if PY3:
output_directory = new_value
else:
output_directory = new_value.encode(audiotools.FS_ENCODING)
self.update_tracks(output_directory=output_directory)
def format_changed(self, widget, new_value):
if PY3:
filename_format = new_value
else:
filename_format = new_value.encode("UTF-8", "replace")
self.update_tracks(filename_format=filename_format)
def update_tracks(self, output_directory=None, filename_format=None):
FS_ENCODING = audiotools.FS_ENCODING
import os.path
# get the output directory
if output_directory is None:
output_directory = self.output_directory.get_directory()
# get selected audio format
audio_class = self.selected_class
# get current filename format
if filename_format is None:
output_format_text = self.output_format.get_edit_text()
if PY3:
filename_format = output_format_text
else:
filename_format = output_format_text.encode('utf-8')
try:
# generate list of Filename objects
# from paths, metadatas and format
# with selected output directory prepended
self.output_filenames = [
audiotools.Filename(
os.path.join(output_directory,
audio_class.track_name(str(filename),
metadata,
filename_format)))
for (filename,
metadata) in zip(self.input_filenames,
self.metadatas)]
# check for duplicates in output/input files
# (don't care if input files are duplicated)
input_filenames = {f for f in self.input_filenames
if f.disk_file()}
output_filenames = set()
collisions = set()
self.has_collisions = False
self.has_duplicates = False
for path in self.output_filenames:
if path in input_filenames:
collisions.add(path)
self.has_collisions = True
elif path in output_filenames:
collisions.add(path)
self.has_duplicates = True
else:
output_filenames.add(path)
# and populate output files list
for (filename, track) in zip(self.output_filenames,
self.output_tracks):
if filename not in collisions:
track.set_text(filename.__unicode__())
else:
track.set_text(("duplicate",
filename.__unicode__()))
if ((self.output_tracks_frame.get_body() is not
self.output_tracks_list)):
self.output_tracks_frame.set_body(
self.output_tracks_list)
self.has_errors = False
except (audiotools.UnsupportedTracknameField,
audiotools.InvalidFilenameFormat):
# if there's an error calling track_name,
# populate files list with an error message
if ((self.output_tracks_frame.get_body() is not
self.invalid_output_format)):
self.output_tracks_frame.set_body(
self.invalid_output_format)
self.has_errors = True
def selected_options(self):
"""returns (AudioFile class, quality string, [output Filename])
based on selected options in the UI"""
import os.path
return (self.selected_class,
self.output_quality.selection(),
[f.expanduser() for f in self.output_filenames])
def set_metadatas(self, metadatas):
"""metadatas is a list of MetaData objects
(some of which may be None)"""
if len(metadatas) != len(self.metadatas):
raise ValueError("new metadatas must have same count as old")
self.metadatas = metadatas
self.update_tracks()
class SingleOutputOptions(urwid.ListBox):
"""a widget for selecting the typical set of output options
for a single input file: --output, --type, --quality"""
def __init__(self,
output_filename,
audio_class,
quality):
"""
| field | value | meaning |
|-----------------+-----------+----------------------------|
| output_filename | string | default output filename |
| audio_class | AudioFile | audio class of output file |
| quality | string | quality level of output |
"""
# FIXME - add support for directory selector
# FIXME - add support for field populator
from audiotools.text import (LAB_OPTIONS_OUTPUT,
LAB_OPTIONS_AUDIO_CLASS,
LAB_OPTIONS_AUDIO_QUALITY)
assert(isinstance(output_filename, str))
assert(isinstance(quality, str))
self.output_filename = EditFilename(
initial_filename=output_filename)
self.output_quality = SelectOne(
items=[(u"N/A", "")],
label=LAB_OPTIONS_AUDIO_QUALITY)
self.output_type = SelectOne(
items=sorted([(u"%s - %s" % (t.NAME, t.DESCRIPTION), t)
for t in audiotools.AVAILABLE_TYPES
if t.supports_from_pcm()],
key=lambda pair: pair[0]),
selected_value=audio_class,
on_change=self.select_type,
label=LAB_OPTIONS_AUDIO_CLASS)
self.select_type(audio_class, quality)
filename_widget = urwid.Columns(
[('fixed', 10, urwid.Text(('label',
u"%s : " %
(LAB_OPTIONS_OUTPUT)),
align="right")),
('weight', 1, self.output_filename)])
class_widget = urwid.Columns(
[('fixed', 10,
urwid.Text(('label',
u"%s : " %
(LAB_OPTIONS_AUDIO_CLASS)),
align="right")),
('weight', 1, self.output_type)])
quality_widget = urwid.Columns(
[('fixed', 10,
urwid.Text(('label',
u"%s : " %
(LAB_OPTIONS_AUDIO_QUALITY)),
align="right")),
('weight', 1, self.output_quality)])
urwid.ListBox.__init__(self, [filename_widget,
class_widget,
quality_widget])
def set_metadata(self, metadata):
"""setting metadata allows output field to be populated
by metadata fields"""
pass # FIXME
def select_type(self, audio_class, default_quality=None):
self.selected_class = audio_class
if len(audio_class.COMPRESSION_MODES) < 2:
# one audio quality for selected type
try:
quality = audio_class.COMPRESSION_MODES[0]
except IndexError:
# this shouldn't happen, but just in case
quality = ""
self.output_quality.set_items([(u"N/A", quality)], quality)
else:
# two or more audio qualities for selected type
qualities = audio_class.COMPRESSION_MODES
if default_quality is not None:
default = [q for q in qualities if
q == default_quality][0]
else:
default = [q for q in qualities if
q == audio_class.DEFAULT_COMPRESSION][0]
self.output_quality.set_items(
[(u"%s" % (q,) if q not in
audio_class.COMPRESSION_DESCRIPTIONS else
u"%s - %s" % (q,
audio_class.COMPRESSION_DESCRIPTIONS[q]),
q)
for q in qualities],
default)
def selected_options(self):
"""returns (AudioFile class, quality string, output Filename)
based on selected options in the UI"""
return (self.selected_class,
self.output_quality.selection(),
audiotools.Filename(self.output_filename.get_filename()))
class Wizard(urwid.Frame):
def __init__(self, pages, cancel_button, completion_button,
page_changed=None):
"""pages is a list of widgets
cancel_button and completion_button are Button objects
to be placed at either end of the set of pages
page_changed(new_page) is an optional callback
when the current page is changed"""
assert(len(pages) > 0)
from audiotools.text import (LAB_PREVIOUS_BUTTON,
LAB_NEXT_BUTTON)
self.__body_pages__ = []
for (i, widget) in enumerate(pages):
if i == 0:
previous_button = cancel_button
else:
previous_button = urwid.Button(
LAB_PREVIOUS_BUTTON,
on_press=self.set_page,
user_data=(i - 1,
pages[i - 1],
page_changed))
if i == (len(pages) - 1):
next_button = completion_button
else:
next_button = urwid.Button(
LAB_NEXT_BUTTON,
on_press=self.set_page,
user_data=(i + 1,
pages[i + 1],
page_changed))
metadata_buttons = urwid.Filler(
urwid.Columns(widget_list=[('weight', 1, previous_button),
('weight', 2, next_button)],
dividechars=3,
focus_column=1))
self.__body_pages__.append(urwid.Pile(
[("weight", 1, widget),
("fixed", 1, metadata_buttons)],
focus_item=1))
urwid.Frame.__init__(self, body=self.__body_pages__[0])
def set_page(self, button, user_data):
(page_widget_index, base_widget, page_changed) = user_data
self.set_body(self.__body_pages__[page_widget_index])
if page_changed is not None:
page_changed(base_widget)
class MappedButton(urwid.Button):
def __init__(self, label, on_press=None, user_data=None,
key_map={}):
urwid.Button.__init__(self, label=label,
on_press=on_press,
user_data=user_data)
self.__key_map__ = key_map
def keypress(self, size, key):
return urwid.Button.keypress(self,
size,
self.__key_map__.get(key, key))
class MappedRadioButton(urwid.RadioButton):
def __init__(self, group, label, state='first True',
on_state_change=None, user_data=None,
key_map={}):
urwid.RadioButton.__init__(self, group=group,
label=label,
state=state,
on_state_change=on_state_change,
user_data=user_data)
self.__key_map__ = key_map
def keypress(self, size, key):
return urwid.RadioButton.keypress(self,
size,
self.__key_map__.get(key, key))
class AudioProgressBar(urwid.ProgressBar):
def __init__(self, normal, complete, sample_rate, current=0, done=100,
satt=None):
urwid.ProgressBar.__init__(self,
normal=normal,
complete=complete,
current=current,
done=done,
satt=satt)
self.sample_rate = sample_rate
def get_text(self):
from audiotools.text import LAB_TRACK_LENGTH
try:
return LAB_TRACK_LENGTH % \
((self.current // self.sample_rate) // 60,
(self.current // self.sample_rate) % 60)
except ZeroDivisionError:
return LAB_TRACK_LENGTH % (0, 0)
class VolumeControl(urwid.ProgressBar):
def __init__(self, get_volume, volume_delta, change_volume):
"""get_volume is a function that returns the current volume
volume_delta is the delta as a float
change_volume is a function that takes a delta
and returns the new volume"""
urwid.ProgressBar.__init__(self,
normal="volume normal",
complete="volume complete",
current=0.0,
done=1.0)
self.get_volume = get_volume
self.volume_delta = volume_delta
self.change_volume = change_volume
self.set_completion(self.get_volume())
def update(self):
self.set_completion(self.get_volume())
def get_text(self):
from audiotools.text import LAB_VOLUME
return u"%s : %s" % (LAB_VOLUME, urwid.ProgressBar.get_text(self))
def selectable(self):
return True
def get_cursor_coords(self, size):
return (0, 0)
def keypress(self, size, key):
if (key == 'left') and (self.decrease_volume is not None):
self.decrease_volume()
elif (key == 'right') and (self.increase_volume is not None):
self.increase_volume()
else:
return key
def render(self, size, focus=False):
c = urwid.ProgressBar.render(self, size, focus)
if focus:
# create a new canvas so we can add a cursor
c = urwid.CompositeCanvas(c)
c.cursor = self.get_cursor_coords(size)
return c
def decrease_volume(self):
self.update_volume(-self.volume_delta)
def increase_volume(self):
self.update_volume(self.volume_delta)
def update_volume(self, delta):
self.set_completion(self.change_volume(delta))
class AdjustOutput(urwid.PopUpLauncher):
def __init__(self, player, volume_control):
from audiotools.text import LAB_ADJUST_OUTPUT
self.__output_button__ = urwid.Button(LAB_ADJUST_OUTPUT)
self.__super.__init__(self.__output_button__)
urwid.connect_signal(
self.original_widget,
'click',
lambda button: self.open_pop_up())
self.player = player
self.volume_control = volume_control
self.outputs = []
def create_pop_up(self):
from audiotools.player import available_outputs
self.outputs = list(available_outputs())
pop_up = AdjustOutputDialog(self.player,
self.volume_control,
self.outputs)
urwid.connect_signal(
pop_up,
'close',
lambda button: self.close_pop_up())
return pop_up
def get_pop_up_parameters(self):
return {'left': 0,
'top': 1,
'overlay_width': 50,
'overlay_height': len(self.outputs) + 4}
class AdjustOutputWidget(urwid.Pile):
def __init__(self, player, volume_control, outputs,
closed_callback=None):
from audiotools.text import (LAB_DECREASE_VOLUME,
LAB_INCREASE_VOLUME,
LAB_KEY_DONE)
self.player = player
self.closed_callback = closed_callback
self.volume_control = volume_control
current_output_name = player.current_output_name()
output_group = []
urwid.Pile.__init__(
self,
[self.volume_control] +
[urwid.RadioButton(group=output_group,
label=o.description(),
state=current_output_name == o.NAME,
on_state_change=self.change_output,
user_data=o) for o in outputs] +
[urwid.Text([('key', u" \u2190 "),
LAB_DECREASE_VOLUME,
u" ",
('key', u" \u2192 "),
LAB_INCREASE_VOLUME,
u" ",
('key', 'esc'), LAB_KEY_DONE])])
def keypress(self, size, key):
key = urwid.Pile.keypress(self, size, key)
if key == 'esc':
if self.closed_callback is not None:
self.closed_callback()
else:
return key
def change_output(self, radio_button, new_state, new_output):
if new_state:
self.player.set_output(new_output)
self.volume_control.update()
class AdjustOutputDialog(urwid.WidgetWrap):
signals = ['close']
def __init__(self, player, volume_control, outputs):
from audiotools.text import LAB_OUTPUT_OPTIONS
close_button = urwid.Button(u"done")
pile = AdjustOutputWidget(
player,
volume_control,
outputs,
closed_callback=lambda: self._emit("close"))
self.__super.__init__(urwid.LineBox(urwid.Filler(pile),
title=LAB_OUTPUT_OPTIONS))
class PlayerGUI(urwid.Frame):
def __init__(self, player, tracks, track_len):
"""player is a Player-compatible object
tracks is a list of (track_name, seconds_length, user_data) tuples
where "track_name" is a unicode string
to place in the radio buttons
"seconds_length" is the length of the track in seconds
and "user_data" is forwarded to calls to select_track()
track_len is the length of all tracks in seconds"""
from audiotools.text import (LAB_PLAY_BUTTON,
METADATA_TRACK_NAME,
METADATA_ARTIST_NAME,
METADATA_ALBUM_NAME,
LAB_PLAY_TRACK,
LAB_PREVIOUS_BUTTON,
LAB_NEXT_BUTTON,
LAB_PLAY_STATUS,
LAB_PLAY_STATUS_1,
LAB_ALBUM_NUMBER)
self.player = player
self.track_name = urwid.Text(u"")
self.album_name = urwid.Text(u"")
self.artist_name = urwid.Text(u"")
self.tracknum = urwid.Text(u"")
self.albumnum_label = urwid.Text(u"")
self.albumnum = urwid.Text(u"")
self.play_pause_button = MappedButton(LAB_PLAY_BUTTON,
on_press=self.play_pause,
key_map={'tab': 'right'})
self.progress = AudioProgressBar(normal='pg normal',
complete='pg complete',
sample_rate=0,
current=0,
done=100)
self.volume_control = VolumeControl(player.get_volume,
0.01,
player.change_volume)
label_width = max([len(audiotools.output_text(s))
for s in [METADATA_TRACK_NAME,
METADATA_ARTIST_NAME,
METADATA_ALBUM_NAME,
LAB_PLAY_TRACK]]) + 3
track_name_widget = urwid.Columns(
[('fixed',
label_width,
urwid.Text(('label',
u"%s : " % (METADATA_TRACK_NAME)),
align='right')),
('weight', 1, self.track_name)])
artist_name_widget = urwid.Columns(
[('fixed',
label_width,
urwid.Text(('label',
u"%s : " % (METADATA_ARTIST_NAME)),
align='right')),
('weight', 1, self.artist_name)])
album_name_widget = urwid.Columns(
[('fixed',
label_width,
urwid.Text(('label',
u"%s : " % (METADATA_ALBUM_NAME)),
align='right')),
('weight', 1, self.album_name)])
track_number_widget = urwid.Columns(
[('fixed',
label_width,
urwid.Text(('label',
u"%s : " % (LAB_PLAY_TRACK)),
align='right')),
('weight', 1, self.tracknum)])
album_number_widget = urwid.Columns(
[('fixed',
len(LAB_ALBUM_NUMBER) + 3,
self.albumnum_label),
('weight', 1, self.albumnum)])
track_album_number = urwid.Columns(
[('weight', 1, track_number_widget),
('weight', 1, album_number_widget)])
header = urwid.Pile([track_name_widget,
artist_name_widget,
album_name_widget,
track_album_number,
self.progress])
controls = urwid.Columns(
[("fixed", 10, urwid.Divider(u" ")),
("weight", 1,
urwid.Divider(u" ")),
("fixed", 9,
MappedButton(LAB_PREVIOUS_BUTTON,
on_press=self.previous_track,
key_map={"tab": "right"})),
("fixed", 9,
self.play_pause_button),
("fixed", 9,
MappedButton(LAB_NEXT_BUTTON,
on_press=self.next_track,
key_map={"tab": "down"})),
("weight", 1,
urwid.Divider(u" ")),
("fixed", 10,
AdjustOutput(self.player, self.volume_control))],
dividechars=2,
focus_column=3)
self.track_group = []
self.track_list_widget = urwid.ListBox(
[urwid.Columns(
[("weight",
1,
MappedRadioButton(group=self.track_group,
label=track_label,
user_data=user_data,
on_state_change=self.select_track,
key_map={'tab': 'down'})),
("fixed",
6,
urwid.Text(u"%2.1d:%2.2d" %
(seconds_length // 60,
seconds_length % 60),
align="right"))])
for (track_label, seconds_length, user_data) in tracks])
status = ((LAB_PLAY_STATUS if (len(tracks) > 1) else
LAB_PLAY_STATUS_1) % {"count": len(tracks),
"min": int(track_len) // 60,
"sec": int(track_len) % 60})
body = urwid.Pile(
[("fixed", 1,
urwid.Filler(controls)),
("weight", 1,
BottomLineBox(self.track_list_widget,
title=status))])
urwid.Frame.__init__(
self,
body=body,
header=urwid.LineBox(header))
def select_track(self, radio_button, new_state, user_data,
auto_play=True):
# to be implemented by subclasses
raise NotImplementedError()
def next_track(self, user_data=None):
track_index = [g.state for g in self.track_group].index(True)
try:
self.track_group[track_index + 1].set_state(True)
self.track_list_widget.set_focus(track_index + 1, "above")
except IndexError:
if len(self.track_group):
self.track_group[0].set_state(True)
self.track_list_widget.set_focus(0, "above")
self.player.stop()
def previous_track(self, user_data=None):
track_index = [g.state for g in self.track_group].index(True)
try:
if track_index == 0:
raise IndexError()
else:
self.track_group[track_index - 1].set_state(True)
self.track_list_widget.set_focus(track_index - 1, "below")
except IndexError:
pass
def update_metadata(self, track_name=None,
album_name=None,
artist_name=None,
track_number=None,
track_total=None,
album_number=None,
album_total=None,
pcm_frames=0,
channels=0,
sample_rate=0,
bits_per_sample=0):
"""updates metadata fields with new values
for when a new track is opened"""
from audiotools.text import (LAB_X_OF_Y,
LAB_TRACK_LENGTH,
LAB_ALBUM_NUMBER)
self.track_name.set_text(track_name if
track_name is not None
else u"")
self.album_name.set_text(album_name if
album_name is not None
else u"")
self.artist_name.set_text(artist_name if
artist_name is not None
else u"")
if track_number is not None:
if track_total is not None:
self.tracknum.set_text(LAB_X_OF_Y %
(track_number,
track_total))
else:
self.tracknum.set_text(u"%d" % (track_number,))
else:
self.tracknum.set_text(u"")
if album_number is not None:
if album_total is not None:
self.albumnum_label.set_text(('label',
LAB_ALBUM_NUMBER + u" : "))
self.albumnum.set_text(LAB_X_OF_Y %
(album_number,
album_total))
else:
self.albumnum_label.set_text(('label',
LAB_ALBUM_NUMBER + u" : "))
self.albumnum.set_text(u"%d" % (album_number,))
else:
self.albumnum_label.set_text(u"")
self.albumnum.set_text(u"")
try:
seconds_length = pcm_frames // sample_rate
except ZeroDivisionError:
seconds_length = 0
self.progress.current = 0
self.progress.done = max(pcm_frames, 1)
self.progress.sample_rate = sample_rate
def update_status(self):
from audiotools.text import (LAB_PLAY_BUTTON,
LAB_PAUSE_BUTTON)
from audiotools.player import PLAYER_PLAYING
self.progress.set_completion(self.player.progress()[0])
self.volume_control.update()
if self.player.state() == PLAYER_PLAYING:
self.play_pause_button.set_label(LAB_PAUSE_BUTTON)
else:
self.play_pause_button.set_label(LAB_PLAY_BUTTON)
def play_pause(self, user_data):
from audiotools.player import PLAYER_STOPPED
if self.player.state() == PLAYER_STOPPED:
self.player.play()
else:
# there's a race condition here where the player's state
# may go from playing to stopped, in which case
# this will do nothing and the state will stay stopped
self.player.toggle_play_pause()
self.update_status()
def stop(self):
self.player.stop()
self.update_status()
def handle_text(self, i):
if (i == 'esc') or (i == 'q') or (i == 'Q'):
self.perform_exit()
elif (i == 'n') or (i == 'N'):
self.next_track()
elif (i == 'p') or (i == 'P'):
self.previous_track()
elif (i == 's') or (i == 'S'):
self.stop()
def perform_exit(self, *args):
self.player.close()
raise urwid.ExitMainLoop()
def timer(main_loop, playergui):
import time
playergui.update_status()
main_loop.set_alarm_at(tm=time.time() + 0.25,
callback=timer,
user_data=playergui)
def style():
"""returns a list of widget style tuples
for use with urwid.MainLoop"""
return [('key', 'white', 'dark blue'),
('label', 'default,bold', 'default'),
('modified', 'default,bold', 'default', ''),
('duplicate', 'light red', 'default'),
('error', 'light red,bold', 'default'),
('pg normal', 'white', 'black', 'standout'),
('pg complete', 'white', 'dark blue'),
('pg smooth', 'dark blue', 'black'),
('volume normal', 'white', 'black'),
('volume complete', 'white', 'dark blue')]
except ImportError:
AVAILABLE = False
def show_available_formats(msg):
"""given a Messenger object,
display all the available file formats"""
from audiotools import output_table, output_text
from audiotools.text import (LAB_AVAILABLE_FORMATS,
LAB_OUTPUT_TYPE,
LAB_OUTPUT_TYPE_DESCRIPTION)
msg.output(LAB_AVAILABLE_FORMATS)
msg.output(u"")
table = output_table()
row = table.row()
row.add_column(LAB_OUTPUT_TYPE, "right")
row.add_column(u" ")
row.add_column(LAB_OUTPUT_TYPE_DESCRIPTION)
table.divider_row([u"-", u" ", u"-"])
for name in sorted(audiotools.TYPE_MAP.keys()):
row = table.row()
row.add_column(
output_text(u"%s" % (name),
style=("underline" if
(name == audiotools.DEFAULT_TYPE)
else None)),
"right")
row.add_column(u" : ")
row.add_column(audiotools.TYPE_MAP[name].DESCRIPTION)
for row in table.format(msg.output_isatty()):
msg.output(row)
def show_available_qualities(msg, audiotype):
"""given a Messenger object and AudioFile class,
display all available quality types for that format"""
from audiotools import output_table, output_text
from audiotools.text import (LAB_AVAILABLE_COMPRESSION_TYPES,
LAB_OUTPUT_QUALITY_DESCRIPTION,
LAB_OUTPUT_QUALITY,
ERR_NO_COMPRESSION_MODES)
if len(audiotype.COMPRESSION_MODES) > 1:
msg.info(LAB_AVAILABLE_COMPRESSION_TYPES % (audiotype.NAME))
msg.info(u"")
table = audiotools.output_table()
row = table.row()
row.add_column(LAB_OUTPUT_QUALITY, "right")
row.add_column(u" ")
row.add_column(LAB_OUTPUT_QUALITY_DESCRIPTION)
table.divider_row([u"-", u" ", u"-"])
for mode in audiotype.COMPRESSION_MODES:
row = table.row()
row.add_column(
output_text(u"%s" % (mode),
style=("underline" if
(mode == audiotools.__default_quality__(
audiotype.NAME))
else None)),
"right")
if mode in audiotype.COMPRESSION_DESCRIPTIONS:
row.add_column(u" : ")
row.add_column(audiotype.COMPRESSION_DESCRIPTIONS[mode])
else:
row.add_column(u"")
row.add_column(u"")
for row in table.format(msg.info_isatty()):
msg.info(row)
else:
msg.info(ERR_NO_COMPRESSION_MODES % (audiotype.NAME))
def select_metadata(metadata_choices, msg, use_default=False):
"""queries the user for the best matching metadata to use
returns a list of MetaData objects for the selected choice"""
# there must be at least one choice
assert(len(metadata_choices) > 0)
# all choices must have at least 1 track
assert(min(map(len, metadata_choices)) > 0)
# and all choices must have the same number of tracks
assert(len(set(map(len, metadata_choices))) == 1)
if (len(metadata_choices) == 1) or use_default:
return metadata_choices[0]
else:
choice = None
while choice not in range(0, len(metadata_choices)):
from audiotools.text import (LAB_SELECT_BEST_MATCH)
for (i, choice) in enumerate(metadata_choices):
msg.output(u"%d) %s" % (i + 1, choice[0].album_name))
try:
choice = int(raw_input(u"%s (1-%d) : " %
(LAB_SELECT_BEST_MATCH,
len(metadata_choices)))) - 1
except ValueError:
choice = None
return metadata_choices[choice]
def process_output_options(metadata_choices,
input_filenames,
output_directory,
format_string,
output_class,
quality,
msg,
use_default=False):
"""metadata_choices[c][t]
is a MetaData object for choice number "c" and track number "t"
all choices must have the same number of tracks
input_filenames is a list of Filename objects for input files
the number of input files must equal the number of metadata objects
in each metadata choice
output_directory is a string of the default output dir
format_string is a UTF-8 encoded format string, or None
output_class is the default AudioFile-compatible class
quality is a string of the default output quality to use
msg is a Messenger object
this may take user input from the prompt to select a MetaData choice
after which it yields (output_class,
output_filename,
output_quality,
output_metadata) tuple for each input file
output_metadata is a reference to an object in metadata_choices
may raise UnsupportedTracknameField or InvalidFilenameFormat
if the given format_string is invalid
may raise DuplicateOutputFile
if the same output file is generated more than once
may raise OutputFileIsInput
if an output file is the same as one of the given input_filenames"""
# there must be at least one choice
assert(len(metadata_choices) > 0)
# ensure input filename count is equal to metadata track count
assert(len(metadata_choices[0]) == len(input_filenames))
import os.path
selected_metadata = select_metadata(metadata_choices, msg, use_default)
# ensure no output paths overwrite input paths
# and that all output paths are distinct
__input__ = {f for f in input_filenames if f.disk_file()}
__output__ = set()
output_filenames = []
for (input_filename, metadata) in zip(input_filenames, selected_metadata):
output_filename = audiotools.Filename(
os.path.join(output_directory,
output_class.track_name(str(input_filename),
metadata,
format_string)))
if output_filename in __input__:
raise audiotools.OutputFileIsInput(output_filename)
elif output_filename in __output__:
raise audiotools.DuplicateOutputFile(output_filename)
else:
__output__.add(output_filename)
output_filenames.append(output_filename)
for (output_filename, metadata) in zip(output_filenames,
selected_metadata):
yield (output_class,
output_filename,
quality,
metadata)
class PlayerTTY(object):
OUTPUT_FORMAT = (u"%(track_number)d/%(track_total)d " +
u"[%(sent_minutes)d:%(sent_seconds)2.2d / " +
u"%(total_minutes)d:%(total_seconds)2.2d] " +
u"%(channels)dch %(sample_rate)s " +
u"%(bits_per_sample)d-bit")
def __init__(self, player):
self.player = player
self.track_number = 0
self.track_total = 0
self.channels = 0
self.sample_rate = 0
self.bits_per_sample = 0
self.playing_finished = False
def previous_track(self):
# implement this in subclass
# to call set_metadata() and have the player open the previous track
raise NotImplementedError()
def next_track(self):
# implement this in subclass
# to call set_metadata() and have the player open the next track
# set playing_finished to True when all tracks have been exhausted
raise NotImplementedError()
def set_metadata(self, track_number,
track_total,
channels,
sample_rate,
bits_per_sample):
self.track_number = track_number
self.track_total = track_total
self.channels = channels
self.sample_rate = sample_rate
self.bits_per_sample = bits_per_sample
def toggle_play_pause(self):
self.player.toggle_play_pause()
def stop(self):
self.player.stop()
def run(self, msg, stdin):
"""msg is a Messenger object
stdin is a file object for keyboard input
returns 0 on a successful exit, 1 if there's an error"""
import os
import tty
import termios
import select
try:
original_terminal_settings = termios.tcgetattr(0)
except termios.error:
from audiotools.text import (ERR_TERMIOS_ERROR,
ERR_TERMIOS_SUGGESTION)
msg.error(ERR_TERMIOS_ERROR)
msg.info(ERR_TERMIOS_SUGGESTION)
return 1
output_line_len = 0
self.next_track()
try:
tty.setcbreak(stdin.fileno())
try:
while not self.playing_finished:
(frames_sent, frames_total) = self.progress()
output_line = self.progress_line(frames_sent, frames_total)
msg.ansi_clearline()
if len(output_line) > output_line_len:
output_line_len = len(output_line)
msg.partial_output(output_line)
else:
msg.partial_output(output_line +
(u" " * (output_line_len -
len(output_line))))
(r_list, w_list, x_list) = select.select([stdin.fileno()],
[], [], 1)
if len(r_list) > 0:
char = os.read(stdin.fileno(), 1)
if (((char == b'q') or
(char == b'Q') or
(char == b'\x1B'))):
self.playing_finished = True
elif char == b' ':
self.toggle_play_pause()
elif ((char == b'n') or
(char == b'N')):
self.next_track()
elif ((char == b'p') or
(char == b'P')):
self.previous_track()
elif ((char == b's') or
(char == b'S')):
self.stop()
else:
pass
except KeyboardInterrupt:
pass
msg.ansi_clearline()
self.player.close()
return 0
finally:
termios.tcsetattr(0, termios.TCSADRAIN, original_terminal_settings)
def progress(self):
return self.player.progress()
def progress_line(self, frames_sent, frames_total):
return (self.OUTPUT_FORMAT %
{"track_number": self.track_number,
"track_total": self.track_total,
"sent_minutes": (frames_sent // self.sample_rate) // 60,
"sent_seconds": (frames_sent // self.sample_rate) % 60,
"total_minutes": (frames_total // self.sample_rate) // 60,
"total_seconds": (frames_total // self.sample_rate) % 60,
"channels": self.channels,
"sample_rate": audiotools.khz(self.sample_rate),
"bits_per_sample": self.bits_per_sample})
def not_available_message(msg):
"""prints a message about lack of Urwid availability
to a Messenger object"""
from audiotools.text import (ERR_URWID_REQUIRED,
ERR_GET_URWID1,
ERR_GET_URWID2)
msg.error(ERR_URWID_REQUIRED)
msg.output(ERR_GET_URWID1)
msg.output(ERR_GET_URWID2)
def xargs_suggestion(args):
"""converts arguments to xargs-compatible suggestion
and returns unicode string"""
import os.path
# All command-line arguments start with "-"
# but not everything that starts with "-" is a command-line argument.
# However, since this is just a suggestion,
# users can be expected to figure it out.
return (u"xargs sh -c '%s %s \"%%@\" < /dev/tty'" %
(os.path.basename(args[0]).decode('utf-8'),
" ".join([arg.decode('utf-8') for arg in args[1:]
if arg.startswith("-")])))
|