File: midicontrols.py

package info (click to toggle)
idjc 0.8.17-1
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 9,628 kB
  • sloc: python: 20,415; ansic: 15,941; sh: 4,869; makefile: 189; sed: 16
file content (2284 lines) | stat: -rw-r--r-- 84,779 bytes parent folder | download
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
#   midicontrols.py: MIDI and hotkey controls for IDJC
#   Copyright (C) 2010 Andrew Clover (and@doxdesk.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 in the file entitled COPYING.
#   If not, see <http://www.gnu.org/licenses/>.

from __future__ import print_function

import sys
import re
import os.path
import time
import collections
import gettext
import functools

import gobject
import gtk
import pango
import dbus
import dbus.service

from idjc import FGlobs, PGlobs
from .gtkstuff import threadslock
from .gtkstuff import timeout_add, source_remove
from .prelims import ProfileManager
from .tooltips import set_tip


_ = gettext.translation(FGlobs.package_name, FGlobs.localedir,
                                                        fallback=True).gettext

PM = ProfileManager()


control_methods= {
    # TC: Control method. Please keep it as Target:Action.
    'c_tips': _('Tooltips enable'),
    # TC: Control method. Please keep it as Target:Action.
    'c_sdjmix': _('DJ-mix monitor'),
    # TC: Control method. Please keep it as Target:Action.
    'l_panpre': _('Panning load from presets'),
    # TC: Control method. Please keep it as Target:Action.
    'p_pp': _('Player play/pause'),
    # TC: Control method. Please keep it as Target:Action.
    'p_stop': _('Player stop'),
    # TC: Control method. Please keep it as Target:Action.
    'p_advance': _('Player advance'),
    # TC: Control method. Please keep it as Target:Action.
    'p_prev': _('Player play previous'),
    # TC: Control method. Please keep it as Target:Action.
    'p_next': _('Player play next'),
    # TC: Control method. Please keep it as Target:Action.
    'p_sfire': _('Player play selected from start'),
    # TC: Control method. Please keep it as Target:Action.
    'p_sprev': _('Player select previous'),
    # TC: Control method. Please keep it as Target:Action.
    'p_snext': _('Player select next'),
    # TC: Control method. Please keep it as Target:Action.
    'p_stream': _('Player stream output enable'),
    # TC: Control method. Please keep it as Target:Action.
    'p_listen': _('Player DJ output enable'),
    # TC: Control method. Please keep it as Target:Action.
    'p_prep': _('Player DJ-only switch'),
    # TC: Control method. Please keep it as Target:Action.
    'p_vol': _('Player set volume'),
    # TC: Control method. Please keep it as Target:Action.
    'p_gain': _('Player set gain'),
    # TC: Control method. Please keep it as Target:Action.
    'p_pan': _('Player set balance'),
    # TC: Control method. Please keep it as Target:Action.
    'p_pitch': _('Player set pitchbend'),

    # TC: Control method. Please keep it as Target:Action.
    'p_tag': _('Playlist edit tags'),
    # TC: Control method. Please keep it as Target:Action.
    'p_istop': _('Playlist insert stop'),
    # TC: Control method. Please keep it as Target:Action.
    'p_istop2': _('Playlist insert stop 2'),
    # TC: Control method. Please keep it as Target:Action.
    'p_ianno': _('Playlist insert announce'),
    # TC: Control method. Please keep it as Target:Action.
    'p_itrans': _('Playlist insert transfer'),
    # TC: Control method. Please keep it as Target:Action.
    'p_ifade': _('Playlist insert crossfade'),
    # TC: Control method. Please keep it as Target:Action.
    'p_ipitch': _('Playlist insert pitchunbend'),
    # TC: Control method. Please keep it as Target:Action.
    'p_igotop': _('Playlist insert jump to top'),

    # TC: Control method. Please keep it as Target:Action.
    'x_fade': _('Players set crossfade'),
    # TC: Control method. Please keep it as Target:Action.
    'x_pass': _('Players pass crossfade'),
    # TC: Control method. Please keep it as Target:Action.
    'x_focus': _('Players set focus'),
    # TC: Control method. Please keep it as Target:Action.
    'x_pitch': _('Players show pitchbend'),
    # TC: Control method. Please keep it as Target:Action.
    'x_advance': _('Players advance'),

    # TC: Control method. Please keep it as Target:Action.
    'm_on': _('Channel output enable'),
    # TC: Control method. Please keep it as Target:Action.
    'm_vol': _('Channel set volume'),
    # TC: Control method. Please keep it as Target:Action.
    'm_gain': _('Channel set gain'),
    # TC: Control method. Please keep it as Target:Action.
    'm_pan': _('Channel set balance'),

    # TC: Control method. Please keep it as Target:Action.
    'v_on': _('VoIP output enable'),
    # TC: Control method. Please keep it as Target:Action.
    'v_prep': _('VoIP DJ-only switch'),
    # TC: Control method. Please keep it as Target:Action.
    'v_vol': _('VoIP set volume'),
    # TC: Control method. Please keep it as Target:Action.
    'v_mixback': _('VoIP set mixback'),
    # TC: Control method. Please keep it as Target:Action.
    'v_gain': _('VoIP set gain'),
    # TC: Control method. Please keep it as Target:Action.
    'v_pan': _('VoIP set balance'),

    # TC: Control method. Please keep it as Target:Action.
    'k_fire': _('Effect play from start'),

    # TC: Control method. Please keep it as Target:Action.
    'b_stop': _('Effects stop many'),
    # TC: Control method. Please keep it as Target:Action.
    'b_vol1': _('Effects set volume'),
    # TC: Control method. Please keep it as Target:Action.
    'b_vol2': _('Effects set headroom'),

    # TC: Control method. Please keep it as Target:Action.
    's_on': _('Stream set connected'),

    # TC: Control method. Please keep it as Target:Action.
    'r_on': _('Recorder set recording'),
}

control_targets= {
    'p': _('Player'),
    'm': _('Channel'),
    'k': _('Effect'),
    's': _('Stream'),
    'r': _('Recorder'),
    'l': _('Setting')
}

control_targets_players= (
    _('Left player'),
    _('Right player'),
    _('Background player'),
    _('Focused player'),
    _('Fadered player')
)

control_targets_effects_bank= (
    _('Effects bank 1'),
    _('Effects bank 2'),
    _('All effects')
)


class Binding(tuple):
    """Immutable value type representing an input bound to an action.

    An input is a MIDI event or keyboard movement. (Possibly others in future?)
    An action is a method of the Controls object, together with how to apply
    input to it, and, for some methods, a target integer specifying which
    player/channel/etc the method should be aimed at.

    A Binding is represented in string form in the 'controls' prefs file as
    one 'input:action' pair per line. There may be multiple bindings of the
    same input or the same action. An 'input' string looks like one of:

        Cc.nn   - MIDI control, channel 'c', control number 'nn'
        Nc.nn   - MIDI note, channel 'c', note id 'nn'
        Pc     - MIDI pitch wheel, channel 'c'
        Kmm.nnnn - Keypress, modifier-state 'm', keyval 'nnnn'

    All numbers are hex. This format is also used to send MIDI event data from
    the mixer to the idjcgui, with trailing ':vv' to set the value (0-127).

    An action string looks like:

        Mmethod.target.value

    Where method is the name of a method in the Controls object, target is
    the object index to apply it to where needed (eg. 0=left player for 'p_'
    methods), and the mode M is one of:

        D - mirror each input level change. For faders and held buttons.
            value may be 127, or -127 for inverted control (hold to set 0)
        P - call on input level high. For one-shot and toggle buttons.
            value is currently ignored.
        S - on input level high, set to specific value
            value is the value to set, from 0..127
        A - on input level high, alter value. For keyboard-controlled faders.
            value is the delta to add to current value, from -127..127

    Value is a signed decimal number. Example:

        C0.0F:Pp_stop.0.7F

    Binds the action 'Player 1 stop' to MIDI control number 15 on channel 0.
    """
    source= property(lambda self: self[0])
    channel= property(lambda self: self[1])
    control= property(lambda self: self[2])
    mode= property(lambda self: self[3])
    method= property(lambda self: self[4])
    target= property(lambda self: self[5])
    value= property(lambda self: self[6])

    # Possible source and mode values, in the order they should be listed in
    # the UI
    #
    SOURCES=(
        SOURCE_CONTROL,
        SOURCE_NOTE,
        SOURCE_PITCHWHEEL,
        SOURCE_KEYBOARD,
    )= 'cnpk'

    MODES=(
        MODE_DIRECT,
        MODE_PULSE,
        MODE_SET,
        MODE_ALTER
    )= 'dpsa'

    _default= [SOURCE_KEYBOARD, 0, 0x31, MODE_PULSE, 'p_pp', 0, 127]

    def __new__(cls, binding= None,
        source= None, channel= None, control= None,
        mode= None, method= None, target= None, value= None
    ):
        """New binding from copying old one, parsing from string, or new values
        """
        if binding is None:
            binding= list(cls._default)
        elif isinstance(binding, tuple):
            binding= list(binding)

        # Parse from string. Can also parse an input string alone
        #
        elif isinstance(binding, (str, unicode)):
            input_part, _, action_part= binding.partition(':')
            binding= list(cls._default)
            s= input_part[:1]
            if s not in Binding.SOURCES:
                raise ValueError('Unknown binding source %r' % input_part[0])
            binding[0]= s
            ch, _, inp= input_part[1:].partition('.')
            binding[1]= int(ch, 16)
            binding[2]= int(inp, 16)
            m= action_part[:1]
            if m not in Binding.MODES:
                raise ValueError('Unknown mode %r' % m)
            binding[3]= m
            parts= action_part[1:].split('.', 3)
            if len(parts)!=3:
                raise ValueError('Malformed control string %r' % action_part)
            if parts[0] not in Binding.METHODS:
                raise ValueError('Unknown method %r' % parts[0])
            binding[4]= parts[0]
            binding[5]= int(parts[1], 16)
            binding[6]= int(parts[2])
        else:
            raise ValueError('Expected string or Binding, not %r' % binding)

        # Override particular properties
        #
        if source is not None: binding[0]= source
        if channel is not None: binding[1]= channel
        if control is not None: binding[2]= control
        if mode is not None: binding[3]= mode
        if method is not None: binding[4]= method
        if target is not None: binding[5]= target
        if value is not None: binding[6]= value
        return tuple.__new__(cls, binding)

    def __str__(self):
        # Back to string
        #
        return '%s%x.%x:%s%s.%x.%d' % (self.source, self.channel, self.control,
                                self.mode, self.method, self.target, self.value)


    def __repr__(self):
        return 'Binding(%r)' % str(self)

    @property
    def input_str(self):
        """Get user-facing representation of channel and control
        """
        if self.source==Binding.SOURCE_KEYBOARD:
            return '%s%s' % (self.channel_str, self.control_str.title())
        elif self.source==Binding.SOURCE_PITCHWHEEL:
            return self.channel_str
        else:
            return '%s: %s' % (self.channel_str, self.control_str)

    @property
    def channel_str(self):
        """Get user-facing representation of channel value (shifting for keys)
        """
        if self.source==Binding.SOURCE_KEYBOARD:
            return Binding.modifier_to_str(self.channel)
        else:
            return str(self.channel)
        return ''

    @property
    def control_str(self):
        """Get user-facing representation of control value (key, note, ...)
        """
        if self.source==Binding.SOURCE_KEYBOARD:
            return Binding.key_to_str(self.control)
        elif self.source==Binding.SOURCE_NOTE:
            return Binding.note_to_str(self.control)
        elif self.source==Binding.SOURCE_CONTROL:
            return str(self.control)
        return ''

    @property
    def action_str(self):
        """Get user-facing representation of action/mode/value
        """
        return control_methods[self.method]
        
    @property
    def modifier_str(self):
        """Get user-facing representation of interaction type and value
        """
        if self.mode==Binding.MODE_DIRECT:
            if self.value<0:
                return ' (-)'
            elif getattr(Controls, self.method).action_modes[0] != \
                                                            Binding.MODE_DIRECT:
                return ' (+)'
        elif self.mode==Binding.MODE_SET:
            return ' (%d)' % self.value
        elif self.mode==Binding.MODE_ALTER:
            if self.value>=0:
                return ' (+%d)' % self.value
            else:
                return ' (%d)' % self.value
        elif self.mode==Binding.MODE_PULSE:
            if self.value<0x40:
                return ' (1-)'
        return ''

    @property
    def target_str(self):
        """Get user-facing representation of the target for this method
        """
        group= self.method[0]
        if group=='p':
            return control_targets_players[self.target]
        if group=='b':
            return control_targets_effects_bank[self.target]
        if group in control_targets:
            return '%s %d' % (control_targets[group], self.target+1)
        return ''

    # Display helpers used by the _str methods and also SpinButtons

    # Keys, with fallback names for unmapped keyvals
    #
    @staticmethod
    def key_to_str(k):
        name= gtk.gdk.keyval_name(k)
        if name is None:
            return '<%04X>' % k
        return name

    @staticmethod
    def str_to_key(s):
        s= s.strip()
        if s.startswith('<') and s.endswith('>') and len(s)==6:
            return int(s[1:-1], 16)

        # Try to find a name for a keyval using different case variants.
        # Unfortunately the case needed by keyval_from_name does not usually
        # match the case produced by keyval_name. Argh.
        #
        # Luckily it's not essential that this is completely right, as it's
        # only needed for bumping the 'key' spinbutton, which will rarely be
        # done.
        #
        if s.lower()=='backspace':
            # TC: The name of the backspace key.
            s= _('BackSpace')
        n= gtk.gdk.keyval_from_name(s)
        if n==0:
            n= gtk.gdk.keyval_from_name(s.lower())
        if n==0:
            n= gtk.gdk.keyval_from_name(s.title())
        if n==0:
            n= gtk.gdk.keyval_from_name(s[:1].upper()+s[1:].lower())
        return n

    # Note names. Convert to/from MIDI note/octave format.
    #
    NOTES= u'C,C#,D,D#,E,F,F#,G,G#,A,A#,B'.replace(u'#', u'\u266F').split(',')

    @staticmethod
    def note_to_str(n):
        return '%s%d' % (Binding.NOTES[n%12], n//12-1)

    @staticmethod
    def str_to_note(s):
        m= re.match(u'^([A-G](?:\u266F?))(-1|\d)$', s.replace(' ', '').replace(
                                                    u'#', u'\u266F').upper())
        if m is None:
            raise ValueError('Invalid note')
        n= Binding.NOTES.index(m.group(1))
        n+= int(m.group(2))*12+12
        if not 0<=n<128:
            raise ValueError('Octave out of range')
        return n

    # Shifting keys. Convert to/from short textual forms, with symbols rather
    # than the verbose names that accelgroup_name uses.
    #
    # Also convert to/from an ordinal form where the bits are reordered to fit
    # a simple 0..127 range, for easy use in a SpinButton.
    #
    MODIFIERS= (
        (gtk.gdk.SHIFT_MASK, u'\u21D1'),
        (gtk.gdk.CONTROL_MASK, u'^'),
        (gtk.gdk.MOD1_MASK, u'\u2020'), # alt/option
        (gtk.gdk.MOD5_MASK, u'\u2021'), # altgr/option
        (gtk.gdk.META_MASK, u'\u25C6'),
        (gtk.gdk.SUPER_MASK, u'\u2318'), # win/command
        (gtk.gdk.HYPER_MASK, u'\u25CF'),
    )
    MODIFIERS_MASK= sum(m for m, c in MODIFIERS)

    @staticmethod
    def modifier_to_str(m):
        return ''.join(c for mask, c in Binding.MODIFIERS if m & mask != 0)

    @staticmethod
    def str_to_modifier(s):
        return sum(mask for mask, c in Binding.MODIFIERS if c in s)

    @staticmethod
    def modifier_to_ord(m):
        return sum(1 << i for i, (mask, c) in enumerate(
                                        Binding.MODIFIERS) if m & mask != 0)

    @staticmethod
    def ord_to_modifier(b):
        return sum(mask for i, (mask, c) in enumerate(
                                        Binding.MODIFIERS) if b & (1 <<i ) !=0)


    METHOD_GROUPS= []
    METHODS= []

# Decorator for control method type annotation. Method names will be stored in
# order in Binding.METHODS; the given modes will be added as a function
# property so the binding editor can read what modes to offer.
#
def action_method(*modes):
    def wrap(fn):
        fn.action_modes= modes
        Binding.METHODS.append(fn.func_name)
        group= fn.func_name[0]
        if group not in Binding.METHOD_GROUPS:
            Binding.METHOD_GROUPS.append(group)
        return fn
    return wrap


dbusify = functools.partial(dbus.service.method, dbus_interface=PGlobs.dbus_bus_basename)


# Controls ___________________________________________________________________


class RepeatCache(collections.MutableSet):
    """A smart keyboard repeat cache -- implements time to live.

    Downstrokes are logged along with the time. Additional downstrokes
    refresh the TTL value for the key. This is done through checking the
    cached Binding before the TTL has run out, otherwise the cached
    entry is removed.

    The __contains__ method runs the TTL cache purge.
    """
    
    @property
    def ttl(self):
        """Time To Live.
        
        The duration a keystroke is valid in the absence of repeats.""" 
        return self._ttl
    @ttl.setter
    def ttl(self, ttl):
        assert(isinstance(ttl, (float, int)))
        self._ttl = ttl
    
    def __init__(self, ttl=0.8):
        self.ttl = ttl
        self._cache = {}
    
    def __len__(self):
        return len(self._cache)
        
    def __iter__(self):
        return iter(self._cache)

    def __contains__(self, key):
        if key in self._cache:
            if self._cache[key] < time.time():
                del self._cache[key]
                return False
            else:
                self._cache[key] = time.time() + self._ttl
                return True
        else:
            return False
            
    def add(self, key):
        self._cache[key] = time.time() + self._ttl
            
    def discard(self, key):
        if key in self._cache:
            del self._cache[key]


class Controls(dbus.service.Object):
    """Dispatch and implementation of input events to action methods.
    """
    # List of controls set up, empty by default. Mapping of input ID to list
    # of associated control commands, each (control_id, n, mode, v)
    #
    settings= {}

    def __init__(self, owner):
        dbus.service.Object.__init__(self, PM.dbus_bus_name, PGlobs.dbus_objects_basename + "/controls")
        self.owner= owner
        self.learner= None
        self.editing= None
        self.lookup= {}
        self.highlights= {}
        self.repeat_cache= RepeatCache()

        # Default minimal set of bindings, if not overridden by prefs file
        # This matches the hotkeys previously built into IDJC
        #
        self.bindings= [
            Binding('k0.ffbe:pk_fire.0.127'), # F-key effects
            Binding('k0.ffbf:pk_fire.1.127'),
            Binding('k0.ffc0:pk_fire.2.127'),
            Binding('k0.ffc1:pk_fire.3.127'),
            Binding('k0.ffc2:pk_fire.4.127'),
            Binding('k0.ffc3:pk_fire.5.127'),
            Binding('k0.ffc4:pk_fire.6.127'),
            Binding('k0.ffc5:pk_fire.7.127'),
            Binding('k0.ffc6:pk_fire.8.127'),
            Binding('k0.ffc7:pk_fire.9.127'),
            Binding('k0.ffc8:pk_fire.a.127'),
            Binding('k0.ffc9:pk_fire.b.127'),
            Binding('k0.ff1b:pb_stop.2.127'), # Esc stop effects
            Binding('k0.31:sx_fade.b.0'), # 1-2 xfader sides
            Binding('k0.32:sx_fade.b.127'),
            Binding('k0.63:px_pass.0.127'), # C, pass xfader
            Binding('k0.6d:pm_on.0.127'), # M, first channel toggle
            Binding('k0.76:pv_on.0.127'), # V, VoIP toggle
            Binding('k0.70:pv_prep.0.127'), # P, VoIP prefade
            Binding('k0.ff08:pp_stop.3.127'), # backspace, stop focused player
            Binding('k0.2f:pp_advance.4.127'), # slash, advance xfaded player
            Binding('k0.74:pp_tag.3.127'), # playlist editing keys
            Binding('k0.73:pp_istop.3.127'),
            Binding('k0.75:pp_ianno.3.127'),
            Binding('k0.61:pp_itrans.3.127'),
            Binding('k0.66:pp_ifade.3.127'),
            Binding('k0.6e:pp_ipitch.3.127'),
            Binding('k4.72:pr_on.0.127'),
            Binding('k4.73:ps_on.0.127'),
            Binding('k0.69:pc_tips.0.127'), # Tooltips shown
        ]
        self.update_lookup()

    def save_prefs(self, where=None):
        """Store bindings list to prefs file
        """
        fp= open((where or PM.basedir) / 'controls', 'w')
        for binding in self.bindings:
            fp.write(str(binding)+'\n')
        fp.close()

    def load_prefs(self):
        """Reload bindings list from prefs file
        """
        cpn = PM.basedir / 'controls'
        if os.path.isfile(cpn):
            fp= open(cpn)
            self.bindings= []
            for line in fp:
                line= line.strip()
                if line!='' and not line.startswith('#'):
                    try:
                        self.bindings.append(Binding(line))
                    except ValueError as e:
                        print('Warning: controls prefs file '
                              'contained unreadable binding %r' % line,
                              file=sys.stderr)
            fp.close()
            self.update_lookup()

    def update_lookup(self):
        """Bindings list has changed, rebuild input lookup
        """
        self.lookup= {}
        for binding in self.bindings:
            self.lookup.setdefault(
                            str(binding).split(':', 1)[0], []).append(binding)

    def input(self, input, iv):
        """Dispatch incoming input to all bindings associated with it
        """
        # If a BindingEditor is open in learning mode, inform it of the input
        # instead of doing anything with it.
        #
        if self.learner is not None:
            self.learner.learn(input)
            return

        # Handle input value according to the action mode and pass value with
        # is-delta flag to action methods.
        #
        for binding in self.lookup.get(input, []):
            isd= False
            v= iv
            if binding.mode==Binding.MODE_DIRECT:
                if binding.value<0:
                    v= 0x7F-v
            else:
                if binding.mode==Binding.MODE_PULSE:
                    if v>=0x40:
                        if binding in self.repeat_cache:
                            continue
                        else:
                            self.repeat_cache.add(binding)
                    else:
                        self.repeat_cache.discard(binding)

                    if binding.value<=0x40:
                        v= (~v)&0x7F # Act upon release.
                if v<0x40:
                    continue
                if binding.mode in (Binding.MODE_SET, Binding.MODE_ALTER):
                    v= binding.value
                if binding.mode in (Binding.MODE_PULSE, Binding.MODE_ALTER):
                    isd= True
            # Binding is to be highlighted in the user interface.
            self.highlights[binding]= (3, True)
            getattr(self, binding.method)(binding.target, v, isd)

    def input_key(self, event):
        """Convert incoming key events into input signals
        """
        # Ignore modifier keypresses, suppress keyboard repeat,
        # and include only relevant modifier flags.
        #
        if not(0xFFE1<=event.keyval<0xFFEF or 0xFE01<=event.keyval<0xFE35):
            state= event.state&Binding.MODIFIERS_MASK
            v= 0x7F if event.type==gtk.gdk.KEY_PRESS else 0
            self.input('k%x.%x' % (state, event.keyval), v)

    # Utility for p_ control methods
    #
    def _get_player(self, n):
        main = self.owner

        if n==3:
            if main.player_nb.get_current_page() == 1:
                if main.jingles.interlude.treeview.is_focus():
                    n = 2
                else:
                    return None
            elif main.player_left.treeview.is_focus():
                n= 0
            elif main.player_right.treeview.is_focus():
                n=1
            else:
                return None
        elif n==4:
            if main.crossfade.get_value()<50:
                n= 0
            else:
                n= 1

        return (main.player_left, main.player_right, main.jingles.interlude)[n]

    # Control implementations. The @action_method decorator records all control
    # methods in order, so the order they are defined in this code dictates the
    # order they'll appear in in the UI.

    # Miscellaneous
    #
    @action_method(Binding.MODE_PULSE, Binding.MODE_SET)
    def c_tips(self, n, v, isd):
        control= self.owner.prefs_window.enable_tooltips
        if isd:
            v= 0 if control.get_active() else 127
        control.set_active(v>=64)
        
    @dbusify(in_signature='b')
    def set_enable_tooltips(self, enabled):
        self.owner.prefs_window.enable_tooltips.set_active(enabled)
        
    @dbusify(out_signature='b')
    def get_enable_tooltips(self):
        return self.owner.prefs_window.enable_tooltips.get_active()

    @action_method(Binding.MODE_PULSE, Binding.MODE_DIRECT)
    def c_sdjmix(self, n, v, isd):
        active= not self.owner.listen_dj.get_active() if isd else v>=0x40
        if active:
            self.owner.listen_dj.set_active(True)
        else:
            self.owner.listen_stream.set_active(True)

    @dbusify()
    def set_listen_dj_mix(self):
        self.owner.listen_dj.set_active(True)
        
    @dbusify(out_signature='b')
    def get_listen_dj_mix(self):
        return self.owner.listen_dj.get_active()

    @dbusify()
    def set_listen_stream_mix(self):
        self.owner.listen_stream.set_active(True)

    @dbusify(out_signature='b')
    def get_listen_stream_mix(self):
        return self.owner.listen_stream.get_active()

    # Panning presets
    #
    @action_method(Binding.MODE_PULSE)
    def l_panpre(self, n, v, isd):
        self.owner.pan_preset_chooser.load_preset(n)

    @dbusify(in_signature='u')
    def panning_presets_load(self, n):
        self.l_panpre(n, 0, 0)

    # Player
    #
    @action_method(Binding.MODE_PULSE, Binding.MODE_DIRECT)
    def p_pp(self, n, v, isd):
        player= self._get_player(n)
        if player is None: return
        is_playing= player.is_playing
        if not is_playing and (isd or v >= 0x40):
            player.play.set_active(True)
        if is_playing if isd else (player.is_paused == (v >= 0x40)):
            player.pause.set_active(not player.pause.get_active())

    @dbusify(in_signature='ubb')
    def player_playpause(self, index, play, toggle):
        self.p_pp(index, 127 if play else 0, toggle)


    @action_method(Binding.MODE_PULSE)
    def p_stop(self, n, v, isd):
        player= self._get_player(n)
        if player is None: return
        player.stop.clicked()

    @dbusify(in_signature='u')
    def player_stop(self, index):
        self.p_stop(index, 0, 0)


    @action_method(Binding.MODE_PULSE)
    def p_advance(self, n, v, isd):
        player= self._get_player(n)
        if player is None: return
        player.advance()
        
    @dbusify(in_signature='u')
    def player_advance(self, index):
        self.p_advance(index, 0, 0)
        

    @action_method(Binding.MODE_PULSE)
    def p_prev(self, n, v, isd):
        player= self._get_player(n)
        if player is None: return
        player.prev.clicked()
        
    @dbusify(in_signature='u')
    def player_previous(self, index):
        self.p_prev(index, 0, 0)


    @action_method(Binding.MODE_PULSE)
    def p_next(self, n, v, isd):
        player= self._get_player(n)
        if player is None: return
        player.next.clicked()

    @dbusify(in_signature='u')
    def player_next(self, index):
        self.p_next(index, 0, 0)


    @action_method(Binding.MODE_PULSE)
    def p_sprev(self, n, v, isd):
        player= self._get_player(n)
        if player is None: return
        treeview_selectprevious(player.treeview)

    @dbusify(in_signature='u')
    def player_select_previous(self, index):
        self.p_sprev(index, 0, 0)
        

    @action_method(Binding.MODE_PULSE)
    def p_snext(self, n, v, isd):
        player= self._get_player(n)
        if player is None: return
        treeview_selectnext(player.treeview)
        
    @dbusify(in_signature='u')
    def player_select_next(self, index):
        self.p_snext(index, 0, 0)


    @action_method(Binding.MODE_PULSE)
    def p_sfire(self, n, v, isd):
        player= self._get_player(n)
        if player is None: return
        player.cb_doubleclick(player.treeview, None, None, None)

    @dbusify(in_signature='u')
    def player_play_selected(self, index):
        self.p_sfire(index, 0, 0)


    @action_method(Binding.MODE_PULSE, Binding.MODE_DIRECT, Binding.MODE_SET)
    def p_stream(self, n, v, isd):
        player= self._get_player(n)
        if player is None: return
        active= not player.stream.get_active() if isd else v>=0x40
        player.stream.set_active(active)

    @dbusify(in_signature='ubb')
    def player_set_streammix(self, index, value, toggle):
        self.p_stream(index, 127 if value else 0, toggle)


    @action_method(Binding.MODE_PULSE, Binding.MODE_DIRECT, Binding.MODE_SET)
    def p_listen(self, n, v, isd):
        player= self._get_player(n)
        if player is None: return
        active= not player.listen.get_active() if isd else v>=0x40
        player.listen.set_active(active)

    @dbusify(in_signature='ubb')
    def player_set_djmix(self, index, value, toggle):
        self.p_listen(index, 127 if value else 0, toggle)


    @action_method(Binding.MODE_PULSE, Binding.MODE_DIRECT, Binding.MODE_SET)
    def p_prep(self, n, v, isd):
        player= self._get_player(n)
        if player is None: return
        if player not in (self.owner.player_left, self.owner.player_right):
            print("player unsupported for this binding")
            return
        other= self.owner.player_left if player is self.owner.player_right \
                                                else self.owner.player_right
        prep= player.stream.get_active() if isd else v>=0x40
        player.stream.set_active(not prep)
        other.listen.set_active(not prep)
        if prep:
            player.listen.set_active(True)
            self.owner.listen_dj.set_active(True)
        else:
            # This is questionable. I like to listen to the Stream output not
            # DJ, so reset to Stream mode after pre-ing. This may not suit
            # everyone. Maybe there should be a different action for preview
            # without returning to stream listening. The alternative would be
            # to try to remember which output was being listened to previously,
            # but that would introduce invisible state not present in the
            # normal UI, making the behaviour unpredictable.
            #
            self.owner.listen_stream.set_active(True)

    @action_method(Binding.MODE_DIRECT, Binding.MODE_SET, Binding.MODE_ALTER)
    def p_vol(self, n, v, isd):
        player= self._get_player(n)
        if player is None: return
        if player.playername in ("left", "right"):
            deckadj= self.owner.deck2adj if player is self.owner.player_right \
                                                        else self.owner.deckadj
        elif player.playername == "interlude":
            deckadj = self.owner.jingles.ivol_adj
        cross= deckadj.get_value()+v if isd else v
        deckadj.set_value(cross)
        
    @dbusify(in_signature='uib')
    def player_set_volume(self, index, value, delta):
        self.p_vol(index, value, delta)


    #@action_method(Binding.MODE_DIRECT, Binding.MODE_SET, Binding.MODE_ALTER)
    #def p_gain(self, n, v, isd):
    #   player= self._get_player(n)
    #   if player is None: return
    #   pass # XXX

    #@action_method(Binding.MODE_DIRECT, Binding.MODE_SET, Binding.MODE_ALTER)
    #def p_pan(self, n, v, isd):
    #   player= self._get_player(n)
    #   if player is None: return
    #   pass # XXX

    @action_method(Binding.MODE_DIRECT, Binding.MODE_SET, Binding.MODE_ALTER)
    def p_pitch(self, n, v, isd):
        player= self._get_player(n)
        if player is None: return
        speed= player.pbspeedbar.get_value()+v if isd else v
        player.pbspeedbar.set_value(speed)

    @dbusify(in_signature='uib')
    def player_set_pitch(self, index, value, delta):
        self.p_pitch(index, value, delta)


    # Playlist methods, to reproduce previous idjcmedia shortcuts
    #
    @action_method(Binding.MODE_PULSE)
    def p_tag(self, n, v, isd): #t
        player= self._get_player(n)
        if player is None: return
        player.menu_model, player.menu_iter= \
                                player.treeview.get_selection().get_selected()
        player.menuitem_response(None, 'MetaTag')

    @action_method(Binding.MODE_PULSE)
    def p_istop(self, n, v, isd): #s
        player= self._get_player(n)
        if player is None: return
        player.menu_model, player.menu_iter= \
                                player.treeview.get_selection().get_selected()
        player.menuitem_response(None, 'Stop Control')

    @dbusify(in_signature='u')
    def playlist_insert_stop_control(self, index):
        self.p_istop(index, 0, 0)

    @action_method(Binding.MODE_PULSE)
    def p_istop2(self, n, v, isd): #s
        player= self._get_player(n)
        if player is None: return
        player.menu_model, player.menu_iter= \
                                player.treeview.get_selection().get_selected()
        player.menuitem_response(None, 'Stop Control 2')

    @dbusify(in_signature='u')
    def playlist_insert_stop_control_2(self, index):
        self.p_istop2(index, 0, 0)

    @action_method(Binding.MODE_PULSE)
    def p_ianno(self, n, v, isd): #u
        player= self._get_player(n)
        if player is None: return
        player.menu_model, player.menu_iter= \
                                player.treeview.get_selection().get_selected()
        player.menuitem_response(None, 'Announcement Control')

    @action_method(Binding.MODE_PULSE)
    def p_itrans(self, n, v, isd): #a
        player= self._get_player(n)
        if player is None: return
        player.menu_model, player.menu_iter= \
                                player.treeview.get_selection().get_selected()
        player.menuitem_response(None, 'Transfer Control')

    @dbusify(in_signature='u')
    def playlist_insert_transfer_control(self, index):
        self.p_itrans(index, 0, 0)

    @action_method(Binding.MODE_PULSE)
    def p_ifade(self, n, v, isd): #f
        player= self._get_player(n)
        if player is None: return
        player.menu_model, player.menu_iter= \
                                player.treeview.get_selection().get_selected()
        player.menuitem_response(None, 'Crossfade Control')

    @dbusify(in_signature='u')
    def playlist_insert_crossfade_control(self, index):
        self.p_ifade(index, 0, 0)


    @action_method(Binding.MODE_PULSE)
    def p_ipitch(self, n, v, isd): #n
        player= self._get_player(n)
        if player is None: return
        player.menu_model, player.menu_iter= \
                                player.treeview.get_selection().get_selected()
        player.menuitem_response(None, 'Normal Speed Control')

    @dbusify(in_signature='u')
    def playlist_insert_normal_speed_control(self, index):
        self.p_ipitch(index, 0, 0)


    @action_method(Binding.MODE_PULSE)
    def p_igotop(self, n, v, isd):
        player= self._get_player(n)
        if player is None: return
        player.menu_model, player.menu_iter= \
                                player.treeview.get_selection().get_selected()
        player.menuitem_response(None, 'Jump To Top Control')

    @dbusify(in_signature='u')
    def playlist_insert_jump_to_top_control(self, index):
        self.p_igotop(index, 0, 0)


    @dbusify(in_signature='us')
    def playlist_insert_pathname(self, index, pathname):
        player = self._get_player(index)
        if player is None: return
        model, iter = player.treeview.get_selection().get_selected()
        row = player.get_media_metadata(pathname)
        if row:
            model.insert_after(iter, row)
            self.player_select_next(index)
        
    @dbusify()
    def playlist_clear(self, index):
        player = self._get_player(index)
        if player is None: return
        player.liststore.clear()


    # Both players
    #
    @action_method(Binding.MODE_DIRECT, Binding.MODE_SET, Binding.MODE_ALTER)
    def x_fade(self, n, v, isd):
        v= v/127.0*100
        cross= self.owner.crossadj.get_value()+v if isd else v
        self.owner.crossadj.set_value(cross)
        
    @dbusify(in_signature='ib')
    def crossfade_set(self, value, delta):
        self.x_fade(0, value, delta) 


    @action_method(Binding.MODE_PULSE)
    def x_advance(self, n, v, isd):
        self.owner.advance.clicked()
        
    @dbusify()
    def playlist_advance(self):
        self.x_advance(0, 0, 0)    


    @action_method(Binding.MODE_PULSE)
    def x_pass(self, n, v, isd):
        self.owner.passbutton.clicked()

    @dbusify()
    def crossfade_pass(self):
        self.x_pass(0, 0, 0)


    @action_method(Binding.MODE_PULSE, Binding.MODE_DIRECT, Binding.MODE_SET)
    def x_pitch(self, n, v, isd):
        checkbox= self.owner.prefs_window.speed_variance
        checkbox.set_active(not checkbox.get_active() if isd else v>=0x40)

    @dbusify(in_signature='bb')
    def pitch_enable(self, value, toggle):
        self.x_pitch(0, 127 if value else 0, toggle)


    @action_method(Binding.MODE_PULSE, Binding.MODE_DIRECT, Binding.MODE_SET)
    def x_focus(self, n, v, isd):
        if isd:
           if self.owner.player_left.treeview.is_focus():
              player = self.owner.player_right
           else:
              player = self.owner.player_left
        else:
           player= self.owner.player_right if v>=0x40 else \
                                                        self.owner.player_left
        player.treeview.grab_focus()

    @dbusify(in_signature='ub')
    def main_player_focus(self, index, toggle):
        self.x_focus(0, 127 if index else 0, toggle)


    # Channel
    #
    @action_method(Binding.MODE_PULSE, Binding.MODE_DIRECT, Binding.MODE_SET)
    def m_on(self, n, v, isd):
       
        button = self.owner.mic_opener.get_opener_button(n)
        if button is not None:
            s = not button.get_active() if isd else v>=0x40
            button.set_active(s)

    @dbusify(in_signature='ubb')
    def channel_open(self, index, value, toggle):
        self.m_on(index, 127 if value else 0, toggle)

        
    @action_method(Binding.MODE_DIRECT, Binding.MODE_SET, Binding.MODE_ALTER)
    def m_vol(self, n, v, isd):
        agc = getattr(self.owner.prefs_window, 'mic_control_%d'%n)
        vol = agc.valuesdict[agc.commandname+'_gain'].get_adjustment()
        if isd:
            v += vol.props.value
        else:
            v = v / 127.0 * (vol.props.upper - vol.props.lower) + vol.props.lower
        vol.set_value(v)

    @dbusify(in_signature='uib')
    def channel_gain(self, index, value, delta):
        self.m_vol(index, value, delta)


    #@action_method(Binding.MODE_DIRECT, Binding.MODE_SET, Binding.MODE_ALTER)
    #def m_gain(self, n, v, isd):
    #   pass # XXX

    @action_method(Binding.MODE_DIRECT, Binding.MODE_SET, Binding.MODE_ALTER)
    def m_pan(self, n, v, isd):
        agc= getattr(self.owner.prefs_window, 'mic_control_%d'%n)
        pan= agc.valuesdict[agc.commandname+'_pan']
        v= v/127.0*100
        v= pan.get_value()+v if isd else v
        pan.set_value(v)

    @dbusify(in_signature='uib')
    def channel_pan(self, index, value, delta):
        self.m_pan(index, value, delta)


    # VoIP
    #
    @action_method(Binding.MODE_PULSE, Binding.MODE_DIRECT, Binding.MODE_SET)
    def v_on(self, n, v, isd):
        phone= self.owner.greenphone
        s= not phone.get_active() if isd else v>=0x40
        phone.set_active(s)

    @dbusify(in_signature='bb')
    def voip_mode_public(self, value, toggle):
        self.v_on(0, 127 if value else 0, toggle)


    @action_method(Binding.MODE_PULSE, Binding.MODE_DIRECT, Binding.MODE_SET)
    def v_prep(self, n, v, isd):
        phone= self.owner.redphone
        s= not phone.get_active() if isd else v>=0x40
        phone.set_active(s)

    @dbusify(in_signature='bb')
    def voip_mode_private(self, value, toggle):
        self.v_prep(0, 127 if value else 0, toggle)


    @action_method(Binding.MODE_DIRECT, Binding.MODE_SET, Binding.MODE_ALTER)
    def v_vol(self, n, v, isd):
        vol = self.owner.voipgainadj.get_value() + v if isd else v
        self.owner.voipgainadj.set_value(vol)

    @dbusify(in_signature='ib')
    def voip_set_gain(self, value, delta):
        self.v_vol(0, value, delta)


    @action_method(Binding.MODE_DIRECT, Binding.MODE_SET, Binding.MODE_ALTER)
    def v_mixback(self, n, v, isd):
       vol = self.owner.mixbackadj.get_value() + v if isd else v
       self.owner.mixbackadj.set_value(vol)

    @dbusify(in_signature='ib')
    def voip_set_mixback_level(self, value, delta):
        self.v_mixback(0, value, delta)
    

    #@action_method(Binding.MODE_DIRECT, Binding.MODE_SET, Binding.MODE_ALTER)
    #def v_gain(self, n, v, isd):
    #   pass # XXX

    #@action_method(Binding.MODE_DIRECT, Binding.MODE_SET, Binding.MODE_ALTER)
    #def v_pan(self, n, v, isd):
    #   pass # XXX

    # One jingle
    #
    @action_method(Binding.MODE_PULSE)
    def k_fire(self, n, v, isd):
        self.owner.jingles.all_effects[n].trigger.clicked()

    @dbusify(in_signature='u')
    def effect_trigger(self, index):
        self.k_fire(index, 0, 0)


    # Jingles player in general
    #
    @action_method(Binding.MODE_PULSE)
    def b_stop(self, n, v, isd):
        if n < 2:
            self.owner.jingles.effect_banks[n].stop()
        else:
            banks = self.owner.jingles.effect_banks
            banks[0].stop()
            if len(banks) > 1:
                banks[1].stop()

    @dbusify(in_signature='bb')
    def effect_bank_stop(self, first, second):
        if first or second:
            self.b_stop(2 if first and second else (0, 1)[second], 0, 0)


    @action_method(Binding.MODE_DIRECT, Binding.MODE_SET, Binding.MODE_ALTER)
    def b_vol1(self, n, v, isd):
        if n < 2:
            fader= self.owner.jingles.jvol_adj[n]
            vol= fader.get_value()+v if isd else v
            fader.set_value(vol)
        else:
            self.b_vol1(0, v, isd)
            self.b_vol1(1, v, isd)

    @dbusify(in_signature='uib')
    def effect_bank_gain(self, index, value, delta):
        self.b_vol1(index, value, delta)


    @action_method(Binding.MODE_DIRECT, Binding.MODE_SET, Binding.MODE_ALTER)
    def b_vol2(self, n, v, isd):
        if n < 2:
            fader= self.owner.jingles.jmute_adj[n]
            vol= fader.get_value()+v if isd else v
            fader.set_value(vol)
        else:
            self.b_vol2(0, v, isd)
            self.b_vol2(1, v, isd)

    @dbusify(in_signature='uib')
    def effect_bank_headroom(self, index, value, delta):
        self.b_vol2(index, value, delta)


    # Stream connection
    #
    @action_method(Binding.MODE_PULSE, Binding.MODE_DIRECT, Binding.MODE_SET)
    def s_on(self, n, v, isd):
        connect= self.owner.server_window.streamtabframe.tabs[n].server_connect
        s= not connect.get_active() if isd else v>=0x40
        connect.set_active(s)

    @dbusify(in_signature='ubb')
    def stream_set_connected(self, index, value, toggle):
        self.s_on(index, 127 if value else 0, toggle)


    # Recorder
    #
    @action_method(Binding.MODE_PULSE, Binding.MODE_DIRECT, Binding.MODE_SET)
    def r_on(self, n, v, isd):
        buttons= self.owner.server_window.recordtabframe.tabs[n].record_buttons
        s= not buttons.record_button.get_active() if isd else v>=0x40
        if s:
            buttons.record_button.set_active(s)
        else:
            buttons.stop_button.clicked()

    @dbusify(in_signature='ubb')
    def recorder_set_recording(self, index, value, toggle):
        self.r_on(index, 127 if value else 0, toggle)


# Generic GTK utilities ______________________________________________________

# TreeView move selection up/down with wrapping
#
def treeview_selectprevious(treeview):
    selection= treeview.get_selection()
    model, siter= selection.get_selected()
    iter= model.get_iter_first()
    if iter is not None:
        while True:
            niter= model.iter_next(iter)
            if niter is None or siter is not None and \
                                model.get_path(niter)==model.get_path(siter):
                break
            iter= niter
        selection.select_iter(iter)
        treeview.scroll_to_cell(model.get_path(iter), None, False)

def treeview_selectnext(treeview):
    selection= treeview.get_selection()
    model, siter= selection.get_selected()
    iter= model.get_iter_first()
    if iter is not None:
        if siter is not None:
            siter= model.iter_next(siter)
            if siter is not None:
                iter= siter
        selection.select_iter(iter)
        treeview.scroll_to_cell(model.get_path(iter), None, False)

# Simple value+text-based combo box with optional icon
#
class LookupComboBox(gtk.ComboBox):
   def __init__(self, values, texts, icons= None):
      self._values = values
      if icons is not None:
          model = gtk.ListStore(str, bool, gtk.gdk.Pixbuf)
      else:
          model = gtk.ListStore(str, bool)
      for valuei, value in enumerate(values):
         if icons is not None:
            model.append((texts[value], True, icons[value]))
         else:
            model.append((texts[value], True))
      gtk.ComboBox.__init__(self, model)

      if icons is not None:
         cricon= gtk.CellRendererPixbuf()
         self.pack_start(cricon, False)
         self.set_attributes(cricon, pixbuf= 2)
      crtext= gtk.CellRendererText()
      self.pack_start(crtext, False)
      self.set_attributes(crtext, text= 0, sensitive= 1)

   def get_value(self):
      active = self.get_active()
      if active==-1:
         active= 0
      return self._values[active]
   def set_value(self, value):
      self.set_active(self._values.index(value))

# Combo box with simple 1-level grouping and insensitive group headings
#
class GroupedComboBox(gtk.ComboBox):
    def __init__(self, groups, groupnames, values, valuenames, valuegroups):
        self._values= values
        self._lookup= {}
        model= gtk.TreeStore(int, str, bool)
        group_rows= {}
        for group in groups:
            group_rows[group]= model.append(
                                        None, [-1, groupnames[group], False])
        for i in range(len(values)):
            iter= model.append(group_rows[valuegroups[i]], 
                                            [i, valuenames[values[i]], True])
            self._lookup[values[i]]= model.get_path(iter)
        gtk.ComboBox.__init__(self, model)

        cr= gtk.CellRendererText()
        self.pack_start(cr, True)
        self.set_attributes(cr, text= 1, sensitive= 2)
        
    def get_value(self):
        iter= self.get_active_iter()
        if iter is None:
            return self._values[0]
        i= self.get_model().get_value(iter, 0)
        if i==-1:
            return self._values[0]
        return self._values[i]

    def set_value(self, value):
        self.set_active_iter(self.get_model().get_iter(self._lookup[value]))

# Horrible hack to make the text of a SpinButton customisable. If the
# adjustment property is set to a subclass of CustomAdjustment, the display
# text will be customisable through the read_input and write_output method
# of that Adjustment. (With a plain Adjustment, works like normal SpinButton.)
#
# Normally customisation is impossible because the 'input' signal needs an
# output written to its gpointer argument, which is not accessible via PyGTK.
# Try to do the pointer write using ctypes, if available. Otherwise fall back
# to working like a standard ComboBox.
#
try:
    import ctypes
except ImportError:
    ctypes= None

class CustomSpinButton(gtk.SpinButton):
    def __init__(self, adjustment, climb_rate= 0.0, digits= 0):
        gtk.SpinButton.__init__(self, adjustment, climb_rate, digits)
        self._value = adjustment.get_value()
        self._iscustom = ctypes is not None
        if self._iscustom:
            self.connect('input', self._on_input)
            self.connect('output', self._on_output)

    def _on_input(self, _, ptr):
        if not repr(ptr).startswith('<gpointer at 0x'):
            self._iscustom= False
        if not self._iscustom or not isinstance(self.get_adjustment(),
                                                            CustomAdjustment):
            return False
        try:
            value= self.get_adjustment().read_input(self.get_text())
        except ValueError:
            value= self._value
        addr= int(repr(ptr)[15:-1], 16)
        ctypes.c_double.from_address(addr).value= float(value) # danger!
        return True

    def _on_output(self, _):
        if not self._iscustom or not isinstance(self.get_adjustment(),
                                                            CustomAdjustment):
            return False
        adj= self.get_adjustment()
        self.set_text(adj.write_output(adj.get_value()))
        return True

    def set_adjustment(self, adjustment):
        v= self.get_adjustment().get_value()
        gtk.SpinButton.set_adjustment(self, adjustment)
        if v!=adjustment.get_value():
            adjustment.set_value(v)
        else:
            adjustment.emit('value-changed')

class CustomAdjustment(gtk.Adjustment):
    def read_input(self, text):
        return float(text)
    def write_output(self, value):
        if int(value)==value:
            value= int(value)
        return str(value)


# Binding editor popup _______________________________________________________

class BindingEditor(gtk.Dialog):
    binding_values= {
        # TC: binding editor, action pane, third row, heading text.
        'd': _('Use value'), 
        # TC: binding editor, action pane, third row, heading text.
        'p': _('Act if'), 
        # TC: binding editor, action pane, third row, heading text.
        's': _('Set to'),
        # TC: binding editor, action pane, third row, heading text.
        'a': _('Adjust by'),
    }

    binding_controls= {
        # TC: binding editor, input pane, fourth row, heading text.
        'c': _('Control'),
        # TC: binding editor, input pane, fourth row, heading text.
        'n': _('Note'),
        # TC: binding editor, input pane, fourth row, heading text.
        'p': _('Control'),
        # TC: binding editor, input pane, fourth row, heading text.
        'k': _('Key'),
    }
   
    control_method_groups= {
        # TC: binding editor, action pane, first row, toplevel menu.
        'c': _('Miscellaneous'),
        # TC: binding editor, action pane, first row, toplevel menu.
        'p': _('Player'),
        # TC: binding editor, action pane, first row, toplevel menu.
        'x': _('Both players'),
        # TC: binding editor, action pane, first row, toplevel menu.
        'l': _('Quick panning'),
        # TC: binding editor, action pane, first row, toplevel menu.
        'm': _('Channel'),
        # TC: binding editor, action pane, first row, toplevel menu.
        'v': _('VoIP channel'),
        # TC: binding editor, action pane, first row, toplevel menu.
        'k': _('Single effect'),
        # TC: binding editor, action pane, first row, toplevel menu.
        'b': _('Effects bank'),
        # TC: binding editor, action pane, first row, toplevel menu.
        's': _('Stream'),
        # TC: binding editor, action pane, first row, toplevel menu.
        'r': _('Stream recorder'),
    }   
   
    control_modes= {
        # TC: binding editor, action pane, second row, dropdown text.
        'd': _('Direct fader/held button'),
        # TC: binding editor, action pane, second row, dropdown text.
        'p': _('One-shot/toggle button'),
        # TC: binding editor, action pane, second row, dropdown text.
        's': _('Set value'),
        # TC: binding editor, action pane, second row, dropdown text.
        'a': _('Alter value')
    }  

    control_sources= {
        # TC: binding editor, input pane, second row, dropdown text.
        'c': _('MIDI control'),
        # TC: binding editor, input pane, second row, dropdown text.
        'n': _('MIDI note'),
        # TC: binding editor, input pane, second row, dropdown text.
        'p': _('MIDI pitch-wheel'),
        # TC: binding editor, input pane, second row, dropdown text.
        'k': _('Keyboard press'),
        # TC: binding editor, input pane, second row, dropdown text.
        'x': _('XChat command')
    }
   
   
    def __init__(self, owner):
        self.owner= owner
        gtk.Dialog.__init__(self,
            # TC: Dialog window title text.
            # TC: User is expected to edit a control binding.
            _('Edit control binding'), owner.owner.owner.prefs_window.window,
            gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_NO_SEPARATOR | 
            gtk.DIALOG_MODAL, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
            gtk.STOCK_OK, gtk.RESPONSE_OK))

        gtk.Dialog.set_resizable(self, False)
        owner.owner.owner.window_group.add_window(self)
        self.connect('delete_event', self.on_delete)
        self.connect('close', self.on_close)
        self.connect("key-press-event", self.on_key)

        # Input editing
        #
        # TC: After clicking this button the binding editor will be listening
        # TC: for a key press or midi control surface input.
        self.learn_button= gtk.ToggleButton(_('Listen for input...'))
        self.learn_button.connect('toggled', self.on_learn_toggled)
        self.learn_timer= None

        self.source_field= LookupComboBox(Binding.SOURCES,
                                self.control_sources, self.owner.source_icons)
        self.source_field.connect('changed', self.on_source_changed)
        # TC: The input source.
        self.source_label= gtk.Label(_('Source'))

        # TC: The midi channel.
        self.channel_label= gtk.Label(_('Channel'))
        self.channel_field= ModifierSpinButton(ChannelAdjustment())

        self.control_label= gtk.Label(self.binding_controls['c'])
        self.control_field= CustomSpinButton(gtk.Adjustment(0, 0, 127, 1))

        # Control editing
        #
        self.method_field= GroupedComboBox(
            Binding.METHOD_GROUPS, self.control_method_groups,
            Binding.METHODS, control_methods,
            [m[0] for m in Binding.METHODS]
        )
        self.method_field.connect('changed', self.on_method_changed)

        # TC: The manner in which the input is interpreted.
        self.mode_label= gtk.Label(_('Interaction'))
        self.mode_field= LookupComboBox(Binding.MODES, self.control_modes)
        self.mode_field.connect('changed', self.on_mode_changed)

        # TC: The effect of the control can be directed upon a specific target.
        # TC: e.g. On target [Left player]
        self.target_label= gtk.Label(_('On target'))
        self.target_field= CustomSpinButton(TargetAdjustment('p'))

        self.value_label= gtk.Label(self.binding_values[Binding.MODE_SET])
        self.value_field_scale= ValueSnapHScale(0, -127, 127)
        dummy= ValueSnapHScale(0, -127, 127)
        # TC: Checkbutton text.
        # TC: Use reverse scale and invert the meaning of button presses.
        self.value_field_invert= gtk.CheckButton(_('Reversed'))
        self.value_field_pulse_noinvert= gtk.RadioButton(None, _('Pressed'))
        self.value_field_pulse_inverted=gtk.RadioButton(
                                self.value_field_pulse_noinvert, _('Released'))

        # Layout
        #
        for label in (self.source_label, self.channel_label, self.control_label,
                        self.mode_label, self.target_label, self.value_label):
            label.set_width_chars(10)
            label.set_alignment(0, 0.5)

        sg= gtk.SizeGroup(gtk.SIZE_GROUP_VERTICAL)

        row0, row1, row2, row3= gtk.HBox(spacing= 4), gtk.HBox(spacing= 4), \
                                gtk.HBox(spacing= 4), gtk.HBox(spacing= 4)
        row0.pack_start(self.learn_button)
        row1.pack_start(self.source_label, False, False)
        row1.pack_start(self.source_field)
        row2.pack_start(self.channel_label, False, False)
        row2.pack_start(self.channel_field)
        row3.pack_start(self.control_label, False, False)
        row3.pack_start(self.control_field)
        sg.add_widget(row2)

        input_pane= gtk.VBox(homogeneous= True, spacing= 2)
        input_pane.set_border_width(8)
        input_pane.pack_start(row0, False, False)
        input_pane.pack_start(row1, False, False)
        input_pane.pack_start(row2, False, False)
        input_pane.pack_start(row3, False, False)
        input_pane.show_all()

        input_frame= gtk.Frame(" %s " % _('Input'))
        input_frame.set_border_width(4)
        input_frame.add(input_pane)
        input_pane.show()
        set_tip(input_pane, _("The first half of a binding is the input which "
        "comes in the form of the press of a keyboard key or an event from a "
        "midi device.\n\nInput selection can be done manually or with the help"
        " of the '%s' option." % _("Listen for input...")))

        self.value_field_pulsebox= gtk.HBox()
        self.value_field_pulsebox.pack_start(self.value_field_pulse_noinvert)
        self.value_field_pulsebox.pack_start(self.value_field_pulse_inverted)
        self.value_field_pulsebox.foreach(gtk.Widget.show)

        sg.add_widget(self.value_field_scale)
        sg.add_widget(self.value_field_invert)
        sg.add_widget(self.value_field_pulsebox)
        sg.add_widget(dummy)
        dummy.show()

        row0, row1, row2, row3= gtk.HBox(spacing= 4), gtk.HBox(spacing= 4), \
                                gtk.HBox(spacing= 4), gtk.HBox(spacing= 4)
        row0.pack_start(self.method_field)
        row1.pack_start(self.mode_label, False, False)
        row1.pack_start(self.mode_field)
        row2.pack_start(self.value_label, False, False)
        row2.pack_start(self.value_field_scale)
        row2.pack_start(self.value_field_invert)
        row2.pack_start(self.value_field_pulsebox)
        row3.pack_start(self.target_label, False, False)
        row3.pack_start(self.target_field)

        action_pane= gtk.VBox(homogeneous= True, spacing= 2)
        action_pane.set_border_width(8)
        action_pane.pack_start(row0, False, False)
        action_pane.pack_start(row1, False, False)
        action_pane.pack_start(row2, False, False)
        action_pane.pack_start(row3, False, False)
        action_pane.show_all()

        action_frame= gtk.Frame(" %s " % _('Action'))
        action_frame.set_border_width(4)
        action_frame.add(action_pane)
        action_pane.show()
        # TC: %s is the translation of 'Action'.
        set_tip(action_pane, _("The '%s' pane determines how the input is "
                                "handled, and to what effect." % _("Action")))

        hbox= gtk.HBox(True, spacing= 4)
        hbox.pack_start(input_frame)
        hbox.pack_start(action_frame)
        hbox.show_all()
        self.get_content_area().pack_start(hbox)
        hbox.show()

    def set_binding(self, binding):
        self.learn_button.set_active(False)
        self.source_field.set_value(binding.source)
        self.channel_field.set_value(binding.channel)
        self.control_field.set_value(binding.control)
        self.method_field.set_value(binding.method)
        self.mode_field.set_value(binding.mode)
        self.target_field.set_value(binding.target)
        self.value_field_scale.set_value(binding.value)
        self.value_field_invert.set_active(binding.value < 64)
        self.value_field_pulse_noinvert.set_active(binding.value>=64)
        self.value_field_pulse_inverted.set_active(binding.value<64)

    def get_binding(self):
        mode= self.mode_field.get_value()
        if mode==Binding.MODE_DIRECT:
            value= -127 if self.value_field_invert.get_active() else 127
        elif mode==Binding.MODE_PULSE:
            value= 127 if self.value_field_pulse_noinvert.get_active() else 0
        else:
            value= int(self.value_field_scale.get_value())
        return Binding(
            source= self.source_field.get_value(),
            channel= int(self.channel_field.get_value()),
            control= int(self.control_field.get_value()),
            mode= mode,
            method= self.method_field.get_value(),
            target= int(self.target_field.get_value()),
            value= value
        )

    def on_delete(self, *args):
        self.on_close()
        return True
    def on_close(self, *args):
        self.learn_button.set_active(False)

    def on_key(self, _, event):
        if self.learn_button.get_active():
            self.owner.owner.input_key(event)
            return True
        return False

    # Learn mode, take inputs and set the input fields from them
    #
    def on_learn_toggled(self, *args):
        if self.learn_button.get_active():
            self.learn_button.set_label(_('Listening for input'))
            self.owner.owner.learner= self
        else:
            # TC: Button text. If pressed triggers 'Listening for input' mode.
            self.learn_button.set_label(_('Listen for input...'))
            self.owner.owner.learner= None

    def learn(self, input):
        binding= Binding(input+':dp_pp.0.0')
        self.source_field.set_value(binding.source)
        self.channel_field.set_value(binding.channel)
        self.control_field.set_value(binding.control)
        self.learn_button.set_active(False)

    # Update dependent controls
    #
    def on_source_changed(self, *args):
        s= self.source_field.get_value()

        if s==Binding.SOURCE_KEYBOARD:
            # TC: Refers to key modifiers including Ctrl, Alt, Shift, ....
            self.channel_label.set_text(_('Shifting'))
            self.channel_field.set_adjustment(ModifierAdjustment())
        else:
            # TC: Specifically, the numerical midi channel.
            self.channel_label.set_text(_('Channel'))
            self.channel_field.set_adjustment(ChannelAdjustment())

        self.control_label.set_text(self.binding_controls[s])
        if s==Binding.SOURCE_KEYBOARD:
            self.control_field.set_adjustment(KeyAdjustment())
        elif s==Binding.SOURCE_NOTE:
            self.control_field.set_adjustment(NoteAdjustment())
        else:
            self.control_field.set_adjustment(gtk.Adjustment(0, 0, 127, 1))
        self.control_label.set_sensitive(s!=Binding.SOURCE_PITCHWHEEL)
        self.control_field.set_sensitive(s!=Binding.SOURCE_PITCHWHEEL)

    def on_method_changed(self, *args):
        method= self.method_field.get_value()
        modes= getattr(Controls, method).action_modes
        model= self.mode_field.get_model()
        iter= model.get_iter_first()
        i= 0
        while iter is not None:
            model.set_value(iter, 1, Binding.MODES[i] in modes)
            iter= model.iter_next(iter)
            i+= 1
        self.mode_field.set_value(modes[0])

        group= method[:1]
        if group=='p':
            self.target_field.set_adjustment(PlayerAdjustment())
        elif group=='b':
            self.target_field.set_adjustment(EffectsBankAdjustment())
        elif group in 'mksrl':
            self.target_field.set_adjustment(TargetAdjustment(group))
        else:
            self.target_field.set_adjustment(SingularAdjustment())
        self.target_field.update()
        
        # Snap state may need altering.
        self.snap_needed = 'p' in modes and 'a' not in modes
        if bool(self.value_field_scale.snap) != self.snap_needed:
            self.mode_field.emit("changed")

    def on_mode_changed(self, *args):
        mode= self.mode_field.get_value()
        self.value_label.set_text(self.binding_values[mode])

        self.value_field_pulsebox.hide()
        self.value_field_scale.hide()
        self.value_field_invert.hide()
        
        if mode==Binding.MODE_DIRECT:
            self.value_field_invert.set_active(False)
            self.value_field_invert.show()
        elif mode==Binding.MODE_PULSE:
            self.value_field_pulsebox.show()
        else:
           # Find the adjustment limits.
           if mode==Binding.MODE_SET:
               min, max = 0, 127
           else:
               min, max = -127, 127
           val= min + (max - min + 1) // 2
           snap= val if self.snap_needed else None
           self.value_field_scale.set_range(val, min, max, snap)
           self.value_field_scale.show()

# A Compound HScale widget that supports snapping.
#
class ValueSnapHScale(gtk.HBox):
    can_mark= all(hasattr(gtk.Scale, x) for x in ('add_mark', 'clear_marks'))
    
    def __init__(self, *args, **kwds):
        gtk.HBox.__init__(self)
        self.set_spacing(2)
        self.label= gtk.Label() 
        self.label.set_width_chars(4)
        self.label.set_alignment(1.0, 0.5)
        self.pack_start(self.label, False)
        self.hscale= gtk.HScale()
        self.hscale.connect('change-value', self.on_change_value)
        self.hscale.connect('value-changed', self.on_value_changed)
        # We draw our own value so we can control the alignment.
        self.hscale.set_draw_value(False)
        self.pack_start(self.hscale)
        self.foreach(gtk.Widget.show)
        if args:
            self.set_range(*args, **kwds)
        else:
            self.label.set_text("0")
            self.snap= None

    def set_range(self, val, lower, upper, snap=None):
        # Here snap also doubles as the boundary value.
        self.snap= snap
        if snap is not None:
            policy= gtk.UPDATE_DISCONTINUOUS
            adj= gtk.Adjustment(
                    val, lower, upper + snap - 1, snap * 2, snap * 2, snap-1)
            adj.connect('notify::value', self.on_value_do_snap, lower, upper)
        else:
            policy= gtk.UPDATE_CONTINUOUS
            adj= gtk.Adjustment(val, lower, upper, 1, 6)
        if self.can_mark:
            self.hscale.clear_marks()
            if not self.snap:
                mark= lower + (upper - lower + 1) // 2
                self.hscale.add_mark(mark, gtk.POS_BOTTOM, None)
        self.hscale.set_adjustment(adj)
        self.hscale.set_update_policy(policy)
        adj.props.value= val
        self.hscale.emit('value-changed')

    def on_change_value(self, range, scroll, _val):
        if self.snap:
            props= range.get_adjustment().props
            value= props.upper - props.page_size if \
                                range.get_value() >= self.snap else props.lower
            self.label.set_text(str(int(value)))

    def on_value_changed(self, range):
        self.label.set_text(str(int(range.get_value())))

    def on_value_do_snap(self, adj, _val, lower, upper):
        val= upper if adj.props.value >= self.snap else lower
        if adj.props.value != val:
            adj.props.value= val
        if val==lower:
            self.snap= lower + (upper - lower) // 4
        else:
            self.snap= lower + (upper - lower) * 3 // 4

    def __getattr__(self, name):
        return getattr(self.hscale, name)

# Extended adjustments for custom SpinButtons
#
class ChannelAdjustment(CustomAdjustment):
    def __init__(self, value= 0):
        CustomAdjustment.__init__(self, value, 0, 15, 1)
    def read_input(self, text):
        return int(text)-1
    def write_output(self, value):
        return str(int(value+1))
class ModifierAdjustment(CustomAdjustment):
    def __init__(self, value= 0):
        CustomAdjustment.__init__(self, value, 0, 127, 1)
    def read_input(self, text):
        return Binding.modifier_to_ord(Binding.str_to_modifier(text))
    def write_output(self, value):
        return Binding.modifier_to_str(Binding.ord_to_modifier(int(value)))

class NoteAdjustment(CustomAdjustment):
    def __init__(self, value= 0):
        CustomAdjustment.__init__(self, value, 0, 127, 1)
    def read_input(self, text):
        return Binding.str_to_note(text)
    def write_output(self, value):
        return Binding.note_to_str(int(value))
class KeyAdjustment(CustomAdjustment):
    def __init__(self, value= 0):
        CustomAdjustment.__init__(self, value, 0, 0xFFFF, 1)
    def read_input(self, text):
        return Binding.str_to_key(text)
    def write_output(self, value):
        return Binding.key_to_str(int(value))

class PlayerAdjustment(CustomAdjustment):
    def __init__(self, value= 0):
        CustomAdjustment.__init__(self, value, 0, 4, 1)
    def read_input(self, text):
        return control_targets_players.index(text)
    def write_output(self, value):
        return control_targets_players[max(min(int(value), 4), 0)]
class EffectsBankAdjustment(CustomAdjustment):
    def __init__(self, value= 0):
        CustomAdjustment.__init__(self, value, 0, 2, 1)
    def read_input(self, text):
        return control_targets_effects_bank.index(text)
    def write_output(self, value):
        return control_targets_effects_bank[max(min(int(value), 2), 0)]
class TargetAdjustment(CustomAdjustment):
    def __init__(self, group, value= 0):
        CustomAdjustment.__init__(self, value, 0, {
                        'p': 3, 'm': 11, 'k': 23, 's': 8, 'r': 3, 'l': 8}
                                                                    [group], 1)
        self._group= group
    def read_input(self, text):
        return int(text.rsplit(' ', 1)[-1])-1
    def write_output(self, value):
        return '%s %d' % (control_targets[self._group], value+1)
class SingularAdjustment(CustomAdjustment):
    def __init__(self, value= 0):
        CustomAdjustment.__init__(self)
    def read_input(self, text):
        return 0.0
    def write_output(self, value):
        return _('Singular control')
        
# SpinButton that can translate its underlying adjustment values to GTK shift
# key modifier flags, when a ModifierAdjustment is used.
#
class ModifierSpinButton(CustomSpinButton):
    def get_value(self):
        value= CustomSpinButton.get_value(self)
        if isinstance(self.get_adjustment(), ModifierAdjustment):
            value= Binding.ord_to_modifier(int(value))
        return value
    def set_value(self, value):
        if isinstance(self.get_adjustment(), ModifierAdjustment):
            value= Binding.modifier_to_ord(int(value))
        CustomSpinButton.set_value(self, value)


# Main UI binding list tab ___________________________________________________

class ControlsUI(gtk.VBox):
    """Controls main config interface, displayed in a tab by IDJCmixprefs
    """
    tooltip_coords = (0, 0)
    
    def __init__(self, owner):
        gtk.VBox.__init__(self, spacing= 4)
        self.owner= owner

        self.source_icons= {}
        for ct in Binding.SOURCES:
            self.source_icons[ct]= gtk.gdk.pixbuf_new_from_file(
                        PGlobs.themedir / ('control_' + ct + ".png"))
        self.editor= BindingEditor(self)
        self.editor.connect('response', self.on_editor_response)
        self.editing= None

        # Control list
        #
        # TC: Tree column heading for Inputs e.g. Backspace, F1, S.
        column_input= gtk.TreeViewColumn(_('Input'))
        column_input.set_expand(True)
        cricon= gtk.CellRendererPixbuf()
        crtext= gtk.CellRendererText()
        crtext.props.ellipsize= pango.ELLIPSIZE_END
        column_input.pack_start(cricon, False)
        column_input.pack_start(crtext, True)
        column_input.set_attributes(cricon, pixbuf= 3, cell_background= 8)
        column_input.set_attributes(crtext, text= 4)
        column_input.set_sort_column_id(0)
        craction= gtk.CellRendererText()
        crmodifier= gtk.CellRendererText()
        crmodifier.props.xalign= 1.0
        # TC: Tree column heading for actions e.g. Player stop.
        column_action= gtk.TreeViewColumn(_('Action'))
        column_action.pack_start(craction, True)
        column_action.pack_start(crmodifier, False)
        column_action.set_attributes(craction, text= 5)
        column_action.set_attributes(crmodifier, text= 6)
        column_action.set_sort_column_id(1)
        column_action.set_sizing(gtk.TREE_VIEW_COLUMN_AUTOSIZE)
        # TC: Tree column heading for targets e.g. Channel 1, Stream 2
        column_target= gtk.TreeViewColumn(
                                _('Target'), gtk.CellRendererText(), text= 7)
        column_target.set_sort_column_id(2)

        model= BindingListModel(self)
        model_sort= gtk.TreeModelSort(model)
        model_sort.set_sort_column_id(2, gtk.SORT_ASCENDING)
        self.tree= gtk.TreeView(model_sort)
        self.tree.connect('realize', model.on_realize, column_input, model_sort)
        self.tree.connect('cursor-changed', self.on_cursor_changed)
        self.tree.connect('key-press-event', self.on_tree_key)
        self.tree.connect('query-tooltip', self.on_tooltip_query)
        model.connect('row-deleted', self.on_cursor_changed)
        self.tree.append_column(column_input)
        self.tree.append_column(column_action)
        self.tree.append_column(column_target)
        self.tree.set_headers_visible(True)
        self.tree.set_rules_hint(True)
        self.tree.set_enable_search(False)
        self.tree.set_has_tooltip(True)

        # New/Edit/Remove buttons
        #
        # TC: User to create a new input binding.
        self.new_button= gtk.Button(stock=gtk.STOCK_NEW)
        # TC: User to remove an input binding.
        self.remove_button= gtk.Button(stock=gtk.STOCK_DELETE)
        # TC: User to modify an existing input binding.
        self.edit_button= gtk.Button(stock=gtk.STOCK_EDIT)
        self.new_button.connect('clicked', self.on_new)
        self.remove_button.connect('clicked', self.on_remove)
        self.edit_button.connect('clicked', self.on_edit)
        self.tree.connect('row-activated', self.on_edit)

        # Layout
        #
        buttons= gtk.HButtonBox()
        buttons.set_spacing(8)
        buttons.set_layout(gtk.BUTTONBOX_END)
        buttons.pack_start(self.edit_button, False, False)
        buttons.pack_start(self.remove_button, False, False)
        buttons.pack_start(self.new_button, False, False)
        buttons.show_all()
        self.on_cursor_changed()

        self.set_border_width(4)
        scroll= gtk.ScrolledWindow()
        scroll.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
        scroll.add(self.tree)
        self.pack_start(scroll, True, True)
        self.pack_start(buttons, False, False)
        self.show_all()

    # Dynamic tooltip generation
    #
    def on_tooltip_query(self, tv, x, y, kb_mode, tooltip):
        if (x, y) != self.tooltip_coords:
            self.tooltip_coords = (x, y)
        elif None not in (x, y) and \
                    self.owner.owner.prefs_window.enable_tooltips.get_active():
            path = tv.get_path_at_pos(
                                *tv.convert_widget_to_bin_window_coords(x, y))
            if path is not None:
                row = tv.get_model()[path[0]]
                hbox = gtk.HBox()
                hbox.set_spacing(3)
                hbox.pack_start(gtk.image_new_from_pixbuf(row[3].copy()), False)
                hbox.pack_start(gtk.Label(row[4]), False)
                hbox.pack_start(gtk.Label("  " + row[5] + row[6]), False)
                if row[7]:
                    hbox.pack_start(gtk.Label("  " + row[7]), False)
                hbox.show_all()
                tooltip.set_custom(hbox)
                return True

    # Tree interaction
    #
    def on_cursor_changed(self, *args):
        isselected= self.tree.get_selection().count_selected_rows()!=0
        self.edit_button.set_sensitive(isselected)
        self.remove_button.set_sensitive(isselected)

    def on_tree_key(self, tree, event, *args):
        if event.keyval==0xFFFF: # GDK_Delete
            self.on_remove()

    # Button presses
    #
    def on_remove(self, *args):
        model_sort, iter_sort= self.tree.get_selection().get_selected()
        model= model_sort.get_model()
        if iter_sort is None:
            return
        iter= model_sort.convert_iter_to_child_iter(None, iter_sort)
        binding= self.owner.bindings[model.get_path(iter)[0]]

        if binding is self.editing:
            self.editor.learnbutton.set_active(False)
            self.editor.hide()
            self.editing= None
        niter= model.iter_next(iter)
        if niter is None:
            treeview_selectprevious(self.tree)
        else:
            treeview_selectnext(self.tree)
        model.remove(iter)
        self.on_cursor_changed()

    def on_new(self, *args):
        model_sort, iter_sort= self.tree.get_selection().get_selected()
        model= model_sort.get_model()
        if iter_sort is not None:
            iter= model_sort.convert_iter_to_child_iter(None, iter_sort)
            binding= self.owner.bindings[model.get_path(iter)[0]]
        else:
            binding= Binding()

        self.editing= None
        self.editor.set_binding(binding)
        self.editor.show()

    def on_edit(self, *args):
        model_sort, iter_sort= self.tree.get_selection().get_selected()
        if iter_sort is None:
            return
        model= model_sort.get_model()
        iter= model_sort.convert_iter_to_child_iter(None, iter_sort)

        self.editing= iter
        self.editor.set_binding(self.owner.bindings[model.get_path(iter)[0]])
        self.editor.show()

    def on_editor_response(self, _, response):
        if response==gtk.RESPONSE_OK:
            model= self.tree.get_model().get_model()
            binding= self.editor.get_binding()
            if self.editing==None:
                path= model.append(binding)
            else:
                path= model.replace(self.editing, binding)
            path_sort= self.tree.get_model().convert_child_path_to_path(path)
            self.tree.get_selection().select_path(path_sort)
            self.tree.scroll_to_cell(path_sort, None, False)
            self.on_cursor_changed()
        self.editor.hide()


class BindingListModel(gtk.GenericTreeModel):
    """TreeModel mapping the list of Bindings in Controls to a TreeView
    """
    def __init__(self, owner):
        gtk.GenericTreeModel.__init__(self)
        self.owner= owner
        self.bindings= owner.owner.bindings
        self.highlights= owner.owner.highlights
        
    def on_realize(self, tree, column0, model_sort):
        source= timeout_add(100, self.cb_highlights, tree, column0, model_sort)
        tree.connect_object('destroy', source_remove, source)
        
    @threadslock
    def cb_highlights(self, tree, column0, model_sort):
        d= self.highlights
        if d:
            for rowref, (count, is_new) in d.items():
                # Highlights counter is reduced.
                if count < 1:
                    del d[rowref]
                else:
                    d[rowref]= (count - 1, False)
                # TreeView area invalidation to trigger a redraw.
                if is_new or rowref not in d:
                    try:
                        path= self.on_get_path(rowref)
                    except ValueError:
                        # User craftily deleted the entry during highlighting.
                        pass
                    else:
                        path= model_sort.convert_child_path_to_path(path)
                        area= tree.get_background_area(path, column0)
                        tree.get_bin_window().invalidate_rect(area, False)
        return True

    def on_get_flags(self):
        return gtk.TREE_MODEL_LIST_ONLY|gtk.TREE_MODEL_ITERS_PERSIST
    def on_get_n_columns(self):
        return len(BindingListModel.column_types)
    def on_get_column_type(self, index):
        return BindingListModel.column_types[index]
    def has_default_sort_func(self):
        return False

    # Pure-list iteration
    #
    def on_get_iter(self, path):
        return self.bindings[path[0]] if self.bindings else None
    def on_get_path(self, rowref):
        return (self.bindings.index(rowref),)
    def on_iter_next(self, rowref):
        i= self.bindings.index(rowref)+1
        if i>=len(self.bindings):
            return None
        return self.bindings[i]
    def on_iter_children(self, rowref):
        if rowref is None and len(self.bindings)>=1:
            return self.bindings[0]
        return None
    def on_iter_has_child(self, rowref):
        return False
    def on_iter_n_children(self, rowref):
        if rowref is None:
            return len(self.bindings)
        return 0
    def on_iter_nth_child(self, rowref, i):
        if rowref is None and i<len(self.bindings):
            return self.bindings[i]
        return None
    def on_iter_parent(self, child):
        return None

    # Make column data from binding objects
    #
    column_types= [str, str, str, gtk.gdk.Pixbuf, str, str, str, str, str]
    def on_get_value(self, binding, i):
        if i<3: # invisible sort columns
            inputix= '%02x.%02x.%04x' % (Binding.SOURCES.index(binding.source),
                                            binding.channel, binding.control)
            methodix= '%02x' % Binding.METHODS.index(binding.method)
            targetix= '%02x.%02x' % (Binding.METHOD_GROUPS.index(
                                            binding.method[0]), binding.target)
            return ':'.join(((inputix, methodix, targetix),
            (methodix, targetix, inputix), (targetix, methodix, inputix))[i])

        elif i==3: # icon column
            return self.owner.source_icons[binding.source]
        elif i==4: # input channel/control column
            return binding.input_str
        elif i==5: # method column
            return binding.action_str
        elif i==6: # mode/value column
            return binding.modifier_str
        elif i==7: # target column
            return binding.target_str
        elif i==8: # background color column
            return "red" if binding in self.highlights else None

    # Alteration
    #
    def remove(self, iter):
        path= self.get_path(iter)
        del self.bindings[path[0]]
        self.row_deleted(path)
        self.owner.owner.update_lookup()
    def append(self, binding):
        path= (len(self.bindings),)
        self.bindings.append(binding)
        iter= self.get_iter(path)
        self.row_inserted(path, iter)
        self.owner.owner.update_lookup()
        return path
    def replace(self, iter, binding):
        path= self.get_path(iter)
        del self.bindings[path[0]]
        self.row_deleted(path)
        self.bindings.insert(path[0], binding)
        iter= self.get_iter(path)
        self.row_inserted(path, iter)
        self.owner.owner.update_lookup()
        return path