This file is indexed.

/usr/share/arista/arista-gtk is in arista 0.9.7-5.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
#! /usr/bin/python

"""
    Arista Desktop Transcoder (GTK+ client)
    =======================================
    An audio/video transcoder based on simple device profiles provided by
    presets. This is the GTK+ version.
    
    License
    -------
    Copyright 2008 - 2011 Daniel G. Taylor <dan@programmer-art.org>
    
    This file is part of Arista.

    Arista is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as 
    published by the Free Software Foundation, either version 2.1 of
    the License, or (at your option) any later version.

    Arista 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 Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with Arista.  If not, see
    <http://www.gnu.org/licenses/>.
"""

import gettext
import locale
import logging
import os
import re
import shutil
import sys
import threading
import time
import webbrowser

from optparse import OptionParser

import gobject
import gio
import gconf
import cairo
import gtk

# FIXME: Stupid hack, see the other fixme comment below!
if __name__ != "__main__":
    import gst

_log = logging.getLogger("arista-gtk")

try:
    import pynotify
    pynotify.init("icon-summary-body")
except ImportError:
    pynotify = None
    _log.info("Unable to import pynotify - desktop notifications disabled")

try:
    import webkit
except ImportError:
    webkit = None
    _log.info("Unable to import webkit - in-app documentation disabled")

import arista

_ = gettext.gettext

locale.setlocale(locale.LC_ALL, '')

CONFIG_PATH = "/apps/arista"

DEFAULT_CHECK_INPUTS = True
DEFAULT_SHOW_TOOLBAR = True
DEFAULT_SHOW_PREVIEW = True
DEFAULT_PREVIEW_FPS = 10
DEFAULT_OPEN_PATH = os.path.expanduser("~/Desktop")

RE_ENDS_NUM = re.compile(r'^.*(?P<number>[0-9]+)$')

def _new_combo_with_image(extra = []):
    """
        Create a new combo box with a list store of a pixbuf, a string, and any
        extra passed types.
        
        @type extra: list
        @param extra: Extra types to add to the gtk.ListStore
        @rtype: gtk.ComboBox
            @return: The newly created combo box
    """
    store = gtk.ListStore(gtk.gdk.Pixbuf, gobject.TYPE_STRING, *extra)
    combo = gtk.ComboBox(store)
    pixbuf_cell = gtk.CellRendererPixbuf()
    text_cell = gtk.CellRendererText()
    combo.pack_start(pixbuf_cell, False)
    combo.pack_start(text_cell, True)
    combo.add_attribute(pixbuf_cell, 'pixbuf', 0)
    combo.add_attribute(text_cell, 'text', 1)
    return combo

def _get_icon_pixbuf(uri, width, height):
    """
        Get a pixbuf from an item with an icon URI set.
        
        @type item: object
        @param item: An object with an icon attribute
        @type width: int
        @param width: The requested width of the pixbuf
        @type height: int
        @param height: The requested height of the pixbuf
        @rtype: gtk.Pixbuf or None
        @return: The pixbuf of the icon if it can be found
    """
    image = None
    theme = gtk.icon_theme_get_default()
    
    if not uri:
        return image
    
    if uri.startswith("file://"):
        try:
            path = arista.utils.get_path("presets", uri[7:])
        except IOError:
            path = ""
        
        if os.path.exists(path):
            image = gtk.gdk.pixbuf_new_from_file_at_size(path, width, height)
    elif uri.startswith("stock://"):
        image = theme.load_icon(uri[8:], gtk.ICON_SIZE_MENU, 0)
    else:
        raise ValueError(_("Unknown icon URI %(uri)s") % {
            "uri": uri
        })
    
    return image

def _get_filename_icon(filename):
    """
        Get the icon from a filename using GIO.
        
            >>> icon = _get_filename_icon("test.mp4")
            >>> if icon:
            >>>     # Do something here using icon.load_icon()
            >>>     ...
        
        @type filename: str
        @param filename: The name of the file whose icon to fetch
        @rtype: gtk.ThemedIcon or None
        @return: The requested unloaded icon or nothing if it cannot be found
    """
    theme = gtk.icon_theme_get_default()
    
    names = gio.content_type_get_icon(gio.content_type_guess(filename)).get_property("names")
    icon = theme.choose_icon(names, gtk.icon_size_lookup(gtk.ICON_SIZE_MENU)[0], 0)
    
    return icon

class LogoWidget(gtk.Widget):
    """
        A widget to show the Arista logo.
        
        See http://svn.gnome.org/viewvc/pygtk/trunk/examples/gtk/widget.py?view=markup
    """
    def __init__(self):
        gtk.Widget.__init__(self)
        
        # Load the logo overlay
        logo_path = arista.utils.get_path("ui", "logo.svg")
        self.pixbuf = gtk.gdk.pixbuf_new_from_file(logo_path)
    
    def do_realize(self):
        """
            Realize the widget. Setup the window.
        """
        self.set_flags(self.flags() | gtk.REALIZED)
        
        self.window = gtk.gdk.Window(
            self.get_parent_window(),
            width = self.allocation.width,
            height = self.allocation.height,
            window_type = gtk.gdk.WINDOW_CHILD,
            wclass = gtk.gdk.INPUT_OUTPUT,
            event_mask = self.get_events() | gtk.gdk.EXPOSURE_MASK | gtk.gdk.BUTTON_PRESS_MASK)
        
        self.window.set_user_data(self)
        
        self.style.attach(self.window)
        
        self.style.set_background(self.window, gtk.STATE_NORMAL)
        self.window.move_resize(*self.allocation)
        
        self.gc = self.style.fg_gc[gtk.STATE_NORMAL]
    
    def do_unrealize(self):
        """
            Destroy the window.
        """
        self.window.destroy()
    
    def do_size_request(self, requisition):
        """
            Request a minimum size.
        """
        requisition.width = self.pixbuf.get_width()
        requisition.height = self.pixbuf.get_height()
    
    def do_size_allocate(self, allocation):
        """
            Our size was allocated, save it!
        """
        self.allocation = allocation
        
        if self.flags() & gtk.REALIZED:
            self.window.move_resize(*allocation)
    
    def do_expose_event(self, event):
        """
            Draw the logo.
        """
        x, y, w, h = self.allocation
        
        cr = self.window.cairo_create()
        
        # Base the background color on a 50% luminosity version of the theme's
        # selected color (the color you usually see in progress bars, for
        # example) and make the gradient go from slightly lighter to slightly
        # darker.
        color = self.style.bg[gtk.STATE_SELECTED]
        r, g, b = color.red / 65535.0, color.green / 65535.0, \
                  color.blue / 65535.0
        avg = (r + g + b) / 3.0
        r, g, b = [i + 0.5 - avg for i in [r, g, b]]
        
        # Draw a gradient background
        gradient = cairo.LinearGradient(0, 0, 0, h)
        gradient.add_color_stop_rgb(0.0, r * 1.1, g * 1.1, b * 1.1)
        gradient.add_color_stop_rgb(1.0, r, g, b)
        
        cr.rectangle(0, 0, w, h)
        cr.set_source(gradient)
        cr.fill()
        
        # Draw block shadow area
        gradient = cairo.LinearGradient(1, (h / 2) + 5, 1, (h / 2) + 115)
        gradient.add_color_stop_rgba(0.0, r * 0.95, g * 0.95, b * 0.95, 0.0)
        gradient.add_color_stop_rgba(0.5, r * 0.95, g * 0.95, b * 0.95, 1.0)
        gradient.add_color_stop_rgba(0.6, r * 0.9, g * 0.9, b * 0.9, 1.0)
        gradient.add_color_stop_rgba(1.0, r * 0.9, g * 0.9, b * 0.9, 0.0)
        
        cr.rectangle(1, (h / 2) + 5, w - 2, 30)
        cr.rectangle(1, (h / 2) + 35 + 45, w - 2, 35)
        cr.set_source(gradient)
        cr.fill()
        
        # Draw a highlighted block
        cr.set_source_rgba(1.0, 1.0, 1.0, 0.13)
        cr.rectangle(1, (h / 2) + 35, w - 2, 45)
        cr.fill()
        
        # Draw a border around the highlighted block
        cr.rectangle(1, (h / 2) + 35, w - 2, 1)
        cr.rectangle(1, (h / 2) + 35 + 45 - 1, w - 2, 1)
        cr.fill()
        
        # Draw the outer border
        cr.set_source_rgba(0.0, 0.0, 0.0, 0.5)
        cr.set_line_width(1.0)
        cr.rectangle(0, 0, w, h)
        cr.stroke()
        
        # Draw the logo svg centered in the widget
        self.window.draw_pixbuf(self.gc, self.pixbuf, 0, 0,
                                (w / 2) - (self.pixbuf.get_width() / 2),
                                (h / 2) - (self.pixbuf.get_height() / 2))

gobject.type_register(LogoWidget)

class MainWindow(object):
    """
        Arista Main Window
        ==================
        The main transcoder window. Provides a method of selecting a source,
        output device, and preset for transcoding as well as managing the
        transcoding queue.
    """
    def __init__(self, runoptions):
        self.runoptions = runoptions
        
        ui_path = arista.utils.get_path("ui", "main.ui")
        
        # Load the GUI
        self.builder = gtk.Builder()
        self.builder.add_from_file(ui_path)
        self.builder.connect_signals(self)
        
        self.window = self.builder.get_object("main_window")
        self.menuitem_toolbar = self.builder.get_object("menuitem_toolbar")
        self.toolbar = self.builder.get_object("toolbar")
        self.toolbutton_remove = self.builder.get_object("toolbutton_remove")
        self.toolbutton_pause = self.builder.get_object("toolbutton_pause")
        self.hbox_progress = self.builder.get_object("hbox_progress")
        self.progress = self.builder.get_object("progressbar")
        self.button_pause = self.builder.get_object("button_pause")
        self.button_cancel = self.builder.get_object("button_cancel")
        self.preview = self.builder.get_object("video_preview")
        self.preview_frame = self.builder.get_object("preview_frame")
        
        self.logo = LogoWidget()
        self.logo.connect("button-press-event", self.logo_button_pressed)
        
        self.logo.drag_dest_set(gtk.DEST_DEFAULT_ALL, [('text/plain', 0, 0)], gtk.gdk.ACTION_COPY)
        self.logo.connect("drag-data-received", self.drag_data_received)
        
        self.preview.drag_dest_set(gtk.DEST_DEFAULT_ALL, [('text/plain', 0, 0)], gtk.gdk.ACTION_COPY)
        self.preview.connect("drag-data-received", self.drag_data_received)
        
        self.image_preview = gtk.Alignment(xscale = 1.0, yscale = 1.0)
        self.image_preview.set_padding(0, 5, 0, 0)
        self.image_preview.add(self.logo)
        self.builder.get_object("vbox_preview").pack_start(self.image_preview)
        
        self.add_dialog = None
        self.prefs_dialog = None
        self.about_dialog = None
        
        self.transcoder = None
        
        # Setup the transcoding queue and watch for events
        self.queue = arista.queue.TranscodeQueue()
        self.queue.connect("entry-discovered", self.on_queue_entry_discovered)
        self.queue.connect("entry-error", self.on_queue_entry_error)
        self.queue.connect("entry-complete", self.on_queue_entry_complete)
        
        # Setup configuration system
        client = gconf.client_get_default()
        
        client.add_dir(CONFIG_PATH, gconf.CLIENT_PRELOAD_NONE)
        
        # Update UI to reflect currently stored settings
        try:
            value = client.get_value(CONFIG_PATH + "/show_toolbar")
            if value:
                self.toolbar.show()
            else:
                self.toolbar.hide()
            self.menuitem_toolbar.set_active(value)
        except ValueError:
            if DEFAULT_SHOW_TOOLBAR:
                self.toolbar.show()
            else:
                self.toolbar.hide()
            self.menuitem_toolbar.set_active(DEFAULT_SHOW_TOOLBAR)
        
        client.notify_add(CONFIG_PATH + "/show_toolbar", 
                          self.on_gconf_show_toolbar)
        
        try:
            value = client.get_value(CONFIG_PATH + "/last_open_path")
            if value and os.path.exists(value):
                self.last_open_path = value
            else:
                self.last_open_path = DEFAULT_OPEN_PATH
        except ValueError:
            self.last_open_path = DEFAULT_OPEN_PATH
        
        # Show the interface!
        self.preview.hide()
        self.hbox_progress.hide()
        self.image_preview.show_all()
        self.window.show()
        
        # Are we using the simplified interface? Hide stuff!
        if self.runoptions.simple:
            self.builder.get_object("menubar").hide()
            self.toolbar.hide()
            self.window.resize(320, 240)
            self.window.set_position(gtk.WIN_POS_CENTER_ALWAYS)
            
            device = arista.presets.get()[self.runoptions.device]
        
            if not self.runoptions.preset:
                preset = device.presets[device.default]
            else:
                for (id, preset) in device.presets.items():
                    if preset.name == options.preset:
                        break
            
            outputs = []
            for fname in self.runoptions.files:
                output = arista.utils.generate_output_path(fname, preset,
                             to_be_created=outputs,
                             device_name=self.runoptions.device)
            
                outputs.append(output)
            
                opts = arista.transcoder.TranscoderOptions(fname, preset, output)
            
                self.queue.append(opts)
    
    def _get_preset_from_coords(self, x, y):
        """
            Get a preset from a set of widget-local coordinates on the logo
            widget. If a preset is clicked then the name is returned, otherwise
            None is returned.
        """
        # Get logo dimensions, pixbuf dimensions
        w, h = self.logo.allocation.width, self.logo.allocation.height
        lw, lh = self.logo.pixbuf.get_width(), self.logo.pixbuf.get_height()
        # Convert coordinates from widget-local to pixbuf-local
        lx = x - ((w - lw) / 2)
        ly = y - ((h - lh) / 2)
        
        # Find the preset that was clicked, if any
        preset = None
        
        if lx >= 50 and lx <= 93 and ly >= 155 and ly <= 195:
            preset = "DVD Player - DivX Home Theater"
        elif lx >= 104 and lx <= 153 and ly >= 154 and ly <= 195:
            preset = "Computer - WebM"
        elif lx >= 171 and lx <= 212 and ly >= 156 and ly <= 195:
            preset = "Computer - H.264"
        elif lx >= 229 and lx <= 260 and ly >= 153 and ly <= 195:
            preset = "Apple iOS - iPad"
        elif lx >= 276 and lx <= 298 and ly >= 157 and ly <= 195:
            preset = "Apple iOS - iPhone / iPod Touch"
        elif lx >= 316 and lx <= 336 and ly >= 156 and ly <= 195:
            preset = "Android - Nexus One / Desire"
        elif lx >= 352 and lx <= 399 and ly >= 168 and ly <= 193:
            preset = "Sony Playstation - PSP"
        
        return preset
    
    def drag_data_received(self, widget, context, x, y, selection, target_type, time):
        """
            Files were dragged and dropped into Arista. Add the first file or
            folder as the source and show the add dialog.
        """
        filenames = [f.strip()[7:] for f in selection.data.split("\n") if x]
        
        preset = None
        if widget == self.logo:
            preset = self._get_preset_from_coords(x, y)
        
        self.on_add(None, preset)
        self.add_dialog.set_source_to_path(filenames[0])
    
    def logo_button_pressed(self, widget, event):
        """
            Listen for button presses on the logo - if one of the preset icons
            is pressed then show the add icon with that preset selected.
        """
        
        # See which preset was clicked and launch the create dialog with the
        # given preset selected
        preset = self._get_preset_from_coords(event.x, event.y)
        if preset:
            self.on_add(None, preset)
    
    def on_quit(self, widget, *args):
        """
            Stop the transcoder and hopefully let it cleanup, then exit.
        """
        try:
            if self.transcoder:
                if self.transcoder.state in [gst.STATE_READY, gst.STATE_PAUSED]:
                    self.transcoder.start()
                    
                self.transcoder.pipe.send_event(gst.event_new_eos())
        except:
            pass
        
        self.window.hide()
        
        _log.debug(_("Cleaning up and flushing buffers..."))
        
        def waiting_to_quit():
            if not self.transcoder or self.transcoder.state == gst.STATE_NULL:
                gobject.idle_add(gtk.main_quit)
                return False
            else:
                return True
        
        gobject.idle_add(waiting_to_quit)
        
        return True
    
    def on_pause_toggled(self, widget):
        """
            Pause toolbar button clicked.
        """
        if widget.get_active():
            self.transcoder.pause()
        else:
            self.transcoder.start()
    
    def on_add(self, widget, selected_preset=None):
        """
            Add an item to the queue. This shows a file chooser dialog to 
            pick the output filename and then adds the item to the queue for
            transcoding.
        """
        if self.add_dialog:
            if self.add_dialog.window.get_property("visible"):
                self.add_dialog.window.present()
                if selected_preset:
                    self.add_dialog.select_preset(selected_preset)
                return
            else:
                self.add_dialog.window.destroy()
        
        self.add_dialog = AddDialog(self, selected_preset)
    
    def on_get_new(self, widget):
        """
            Go to the presets list page online and let the user download
            new presets!
        """
        webbrowser.open("http://www.transcoder.org/presets/")
    
    def stop_processing_entry(self, entry):
        """
            Stop processing an entry that is currently being processed. This
            sends an end-of-stream signal down the pipe, hides the preview,
            and makes sure the menu and toolbar is in the proper state.
            
            The item will remain in the queue for up to a few seconds as 
            GStreamer finishes flushing its buffers, then will be removed.
            If another item is in the queue it will start processing then.
        """
        entry.stop()
        
        if self.runoptions.simple and len(self.queue) == 1:
            # This is the last item in the simplified GUI, so we are done and
            # should exit as soon as possible!
            gobject.idle_add(gtk.main_quit)
            return
        
        # Hide live preview while we wait for the item to finish
        self.image_preview.show()
        self.preview.hide()
        self.hbox_progress.hide()
    
    def on_about(self, widget):
        """
            Show the about dialog.
        """
        AboutDialog()
    
    def on_prefs(self, widget):
        """
            Show the preferences dialog.
        """
        PrefsDialog()
    
    def on_show_toolbar_toggled(self, widget):
        """
            Update the GConf preference for showing or hiding the toolbar.
        """
        client = gconf.client_get_default()
        client.set_bool(CONFIG_PATH + "/show_toolbar", widget.get_active())
    
    def on_gconf_show_toolbar(self, client, connection, entry, args):
        """
            Show or hide the toolbar and set the menu item to reflect which
            has happened when the GConf preference has changed.
        """
        self.menuitem_toolbar.set_active(entry.get_value().get_bool())
        if entry.get_value().get_bool():
            self.toolbar.show()
        else:
            self.toolbar.hide()
    
    def on_queue_entry_discovered(self, queue, entry, info, is_media):
        """
            The queue entry has been discovered, see if it is a valid input
            file, if not show an error and remove it from the queue.
        """
        if not info.is_video and info.is_audio:
            _log.error(_("Input %(infile)s contains no valid streams!") % {
                "infile": entry.transcoder.infile,
            })
            
            gtk.gdk.threads_enter()
            
            msg = "The input file or device contains no audio or video " \
                  "streams and will be removed from the queue."
            
            dialog = gtk.MessageDialog(self.window,
                            gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                            type = gtk.MESSAGE_ERROR,
                            buttons = gtk.BUTTONS_OK,
                            message_format = msg)
            dialog.set_title(_("Error with input!"))
            dialog.run()
            dialog.destroy()
            gtk.gdk.threads_leave()
            self.on_queue_entry_complete(queue, entry)
        else:
            entry.transcoder.connect("pass-setup",
                                     self.on_queue_entry_pass_setup, entry)
    
    def on_queue_entry_pass_setup(self, transcoder, entry):
        """
            Called by the queue to start an entry. Setup the correct pass and
            start the transcoder after attaching to the video tee so that
            we can show a nice preview.
        """
        client = gconf.client_get_default()
        
        try:
            show_preview = client.get_value(CONFIG_PATH + "/show_preview")
        except ValueError:
            show_preview = DEFAULT_SHOW_PREVIEW
        
        try:
            fps = client.get_value(CONFIG_PATH + "/preview_fps")
        except ValueError:
            fps = DEFAULT_PREVIEW_FPS
        
        transcoder = entry.transcoder
        self.transcoder = transcoder
        gobject.timeout_add(500, self.on_status_update)
        
        if show_preview:
            element = transcoder.pipe.get_by_name("videotee")
            
            if element:
                pipe = gst.parse_launch("queue name=preview_source ! decodebin2 ! videoscale method=bilinear ! videorate ! ffmpegcolorspace ! video/x-raw-yuv, framerate=%d/1; video/x-raw-rgb, framerate=%d/1 ! autovideosink name=preview_sink" % (fps, fps))
                psink = pipe.get_by_name("preview_sink")
                psink.connect("element-added", self.on_preview_sink_element_added)
                transcoder.pipe.add(pipe)
                src = pipe.get_by_name("preview_source")
                gst.element_link_many(element, src)
                bus = transcoder.pipe.get_bus()
                bus.enable_sync_message_emission()
                bus.connect("sync-message::element", self.on_sync_msg)
                self.preview.show()
                self.image_preview.hide()
        
        self.hbox_progress.show()
    
    def on_queue_entry_error(self, queue, entry, error_str):
        """
            An entry in the queue has had an error. Update the queue model
            and inform the user.
        """
        entry.transcoder.stop()
        
        if pynotify and not entry.force_stopped:
            theme = gtk.icon_theme_get_default()
            icon_info = theme.lookup_icon("dialog-error", 64, 0)
            if icon_info:
                icon = icon_info.get_filename()
            else:
                icon = ""
            notice = pynotify.Notification(_("Error!"), _("Conversion of %(filename)s to %(device)s %(preset)s failed! Reason: %(reason)s") % {
                "filename": os.path.basename(entry.options.output_uri),
                "device": entry.options.preset.device,
                "preset": entry.options.preset.name,
                "reason": error_str,
            }, icon)
            notice.show()
        else:
            # TODO: Show a dialog or something for people with no notifications
            pass
        
        if self.runoptions.simple and len(self.queue) == 1:
            # This is the last item in the simplified GUI, so we are done and
            # should exit as soon as possible!
            gobject.idle_add(gtk.main_quit)
            return
        
        self.image_preview.show()
        self.preview.hide()
        self.hbox_progress.hide()
    
    def on_queue_entry_complete(self, queue, entry):
        """
            An entry in the queue is finished. Update the queue model.
        """
        if pynotify:
            try:
                icon = arista.utils.get_path("presets/" + entry.options.preset.device.icon[7:])
            except IOError:
                icon = ""
            
            notice = pynotify.Notification(_("Job done"), _("Conversion of %(filename)s to %(device)s %(preset)s %(action)s") % {
                "filename": os.path.basename(entry.options.output_uri),
                "device": entry.options.preset.device.name,
                "preset": entry.options.preset.name,
                "action": entry.force_stopped and _("canceled") or _("finished")
            }, icon)
            notice.show()
        
        if self.runoptions.simple and len(self.queue) == 1:
            # This is the last item in the simplified GUI, so we are done and
            # should exit as soon as possible!
            gobject.idle_add(gtk.main_quit)
            return
        
        self.image_preview.show()
        self.preview.hide()
        self.hbox_progress.hide()
    
    def on_preview_sink_element_added(self, autovideosink, element):
        """
            Since we let Gstreamer decide which video sink to use, whenever it
            has picked one set the sync attribute to false so that the
            transcoder runs as fast as possible.
        """
        try:
            # We don't want to play at the proper speed, just go as fast
            # as possible when encoding!
            element.set_property("sync", False)
        except: pass
    
    def on_sync_msg(self, bus, msg):
        """
            Prepare the preview drawing area so that the video preview is 
            rendered there.
        """
        if msg.structure is None:
            return
            
        msg_name = msg.structure.get_name()
        if msg_name == "prepare-xwindow-id":
            gtk.gdk.threads_enter()
            imagesink = msg.src
            imagesink.set_property("force-aspect-ratio", True)
            imagesink.set_xwindow_id(self.preview.window.xid)
            gtk.gdk.threads_leave()
    
    def on_status_update(self):
        """
            Update the status progress bar and text.
        """
        percent = 0.0
        state = self.transcoder.state
        
        if state != gst.STATE_PAUSED:
            try:
                percent, time_rem = self.transcoder.status
                
                if percent > 1.0:
                    percent = 1.0
                if percent < 0.0:
                    percent = 0.0
                
                pass_info = ""
                if self.transcoder.preset.pass_count > 1:
                    pass_info = "pass %(pass)d of %(total)d, " % {
                        "pass": self.transcoder.enc_pass + 1,
                        "total": self.transcoder.preset.pass_count,
                    }
                
                time_info = "%(time)s remaining" % {
                    "time": time_rem,
                }
                
                file_info = ""
                if len(self.queue) > 1:
                    file_info = ", %(files)d files left" % {
                        "files": len(self.queue)
                    }
                
                info_string = "Transcoding... (%(pass_info)s%(time_info)s%(file_info)s)" % {
                    "pass_info": pass_info,
                    "time_info": time_info,
                    "file_info": file_info,
                }
                
                gtk.gdk.threads_enter()
                
                if percent == 0.0:
                    self.progress.pulse()
                else:
                    self.progress.set_fraction(percent)
                
                self.progress.set_text(info_string)
                gtk.gdk.threads_leave()
            except arista.transcoder.TranscoderStatusException, e:
                _log.debug(str(e))
                self.progress.pulse()
        
        return percent < 1.0 and state != gst.STATE_NULL
    
    def on_cancel_clicked(self, widget):
        """
            The user clicked the stop button, so stop processing the entry.
        """
        if len(self.queue):
            self.stop_processing_entry(self.queue[0])
    
    def on_install_device(self, widget):
        dialog = gtk.FileChooserDialog(title=_("Choose Source File..."),
                        buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                                 gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT))
        dialog.set_property("local-only", False)
        dialog.set_current_folder(self.last_open_path)
        response = dialog.run()
        dialog.hide()
        if response == gtk.RESPONSE_ACCEPT:
            filename = dialog.get_filename()
            client = gconf.client_get_default()
            client.set_string(CONFIG_PATH + "/last_open_path",
                              os.path.dirname(filename))
            try:
                devices = arista.presets.extract(open(filename))
            except Exception, e:
                _log.error(str(e))
                dialog = gtk.MessageDialog(self.window, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE, message_format=_("Problem importing preset. This file does not appear to be a valid Arista preset!"))
                dialog.run()
                dialog.destroy()
                return
                
            arista.presets.reset()
            if pynotify:
                for device in devices:
                    try:
                        icon = arista.utils.get_path("presets", arista.presets.get()[device].icon[7:])
                    except:
                        icon = None
                        
                    notice = pynotify.Notification(_("Installation Successful"), _("Device preset %(name)s successfully installed.") % {
                        "name": arista.presets.get()[device].name,
                    }, icon)
                    notice.show()

class PrefsDialog(object):
    """
        Arista Preferences Dialog
        =========================
        A dialog to edit preferences and presets.
    """
    def __init__(self):
        ui_path = arista.utils.get_path("ui", "prefs.ui")
        
        # Load the interface definition file
        self.builder = gtk.Builder()
        self.builder.add_from_file(ui_path)
        
        # Shortcuts for accessing widgets
        self.window = self.builder.get_object("prefs_dialog")
        self.check_inputs = self.builder.get_object("check_inputs")
        self.check_show_live = self.builder.get_object("check_show_live")
        self.spin_live_fps = self.builder.get_object("spin_live_fps")
        
        # Setup configuration system
        client = gconf.client_get_default()
        
        client.add_dir(CONFIG_PATH, gconf.CLIENT_PRELOAD_NONE)
        
        # Update UI to reflect currently stored settings
        try:
            value = client.get_value(CONFIG_PATH + "/check_inputs")
            self.check_inputs.set_active(value)
        except ValueError:
            self.check_inputs.set_active(DEFAULT_CHECK_INPUTS)
        
        try:
            value = client.get_value(CONFIG_PATH + "/show_preview")
            self.check_show_live.set_active(value)
        except ValueError:
            self.check_show_live.set_active(DEFAULT_SHOW_PREVIEW)
        
        try:
            value = client.get_value(CONFIG_PATH + "/preview_fps")
            self.spin_live_fps.set_value(value)
        except ValueError:
            self.spin_live_fps.set_value(DEFAULT_PREVIEW_FPS)
        
        # Register handlers for when settings are changed
        client.notify_add(CONFIG_PATH + "/check_inputs", 
                          self.on_gconf_check_inputs)
        client.notify_add(CONFIG_PATH + "/show_preview", 
                          self.on_gconf_show_preview)
        client.notify_add(CONFIG_PATH + "/preview_fps", 
                          self.on_gconf_preview_fps)
        
        # Connect to signals defined in UI definition file
        self.builder.connect_signals(self)
        
        # Show the window and go!
        self.window.show_all()
    
    def on_close(self, widget, response):
        """
            Close was clicked, remove the window.
        """
        self.window.destroy()
    
    def on_check_inputs_toggled(self, widget):
        """
            Update GConf preference for checking DVD drives.
        """
        client = gconf.client_get_default()
        client.set_bool(CONFIG_PATH + "/check_inputs", widget.get_active())
    
    def on_check_show_live_toggled(self, widget):
        """
            Update GConf preference for showing a live preview during encoding.
        """
        client = gconf.client_get_default()
        client.set_bool(CONFIG_PATH + "/show_preview", widget.get_active())
    
    def on_fps_changed(self, widget):
        """
            Update GConf preference for the frames per second to show during
            the live preview. The higher the number the more CPU is diverted
            from encoding to displaying the video.
        """
        client = gconf.client_get_default()
        client.set_int(CONFIG_PATH + "/preview_fps", int(widget.get_value()))
    
    def on_gconf_check_inputs(self, client, connection, entry, args):
        """
            Update UI when the GConf preference for checking DVD drives has
            been modified.
        """
        self.check_inputs.set_active(entry.get_value().get_bool())
    
    def on_gconf_show_preview(self, client, connection, entry, args):
        """
            Update UI when the GConf preference for showing the live preview
            has been modified.
        """
        value = entry.get_value().get_bool()
        
        self.check_show_live.set_active(value)
        self.spin_live_fps.set_sensitive(value)
    
    def on_gconf_preview_fps(self, client, connection, entry, args):
        """
            Update UI when the GConf preference for the preview framerate has
            been modified.
        """
        self.spin_live_fps.set_value(entry.get_value().get_int())
    
    def on_reset_clicked(self, widget):
        dialog = gtk.MessageDialog(self.window, type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_YES_NO, message_format=_("Are you sure you want to reset your device presets? Doing so will permanently remove any modifications you have made to presets that ship with or share a short name with presets that ship with Arista!"))
        response = dialog.run()
        dialog.destroy()
        
        if response == gtk.RESPONSE_YES:
            # Reset all presets that ship with Arista to the factory default.
            # This does not touch user-made presets unless the shortname
            # matches one of the factory default preset shortnames.
            arista.presets.reset(overwrite=True, ignore_initial=True)

class PropertiesDialog(object):
    """
        Arista Source Properties Dialog
        ===============================
        A simple dialog to set properties for the input source, such as
        subtitles and deinterlacing.
    """
    def __init__(self, options):
        self.options = options
    
        ui_path = arista.utils.get_path("ui", "props.ui")
        
        self.builder = gtk.Builder()
        self.builder.add_from_file(ui_path)
        
        self.window = self.builder.get_object("props_dialog")
        self.subs = self.builder.get_object("filechooserbutton_subs")
        self.font = self.builder.get_object("fontbutton")
        self.deinterlace = self.builder.get_object("checkbutton_deinterlace")
        
        if options.subfile:
            self.subs.set_filename(options.subfile)
        
        if options.font:
            self.font.set_font_name(options.font)
        
        if options.deinterlace:
            self.deinterlace.set_active(options.deinterlace)
        
        self.builder.connect_signals(self)
        
        self.window.show_all()
    
    def on_close(self, widget, response):
        """
            Close was clicked, remove the window.
        """
        self.window.destroy()
    
    def on_subs_set(self, widget):
        """
            Set subtitle file.
        """
        self.options.subfile = widget.get_filename()
    
    def on_font_set(self, widget):
        """
            Set subtitle rendering font.
        """
        self.options.font = widget.get_font_name()
    
    def on_deinterlace(self, widget):
        """
            Toggle forced deinterlacing.
        """
        self.options.deinterlace = widget.get_active()

class AddDialog(object):
    """
        A dialog for creating new conversion jobs.
    """
    def __init__(self, parent, selected_preset=None):
        self.parent = parent
        self.selected_preset = selected_preset
        
        ui_path = arista.utils.get_path("ui", "add.ui")
        
        self.builder = gtk.Builder()
        self.builder.add_from_file(ui_path)
        
        self.window = self.builder.get_object("add_dialog")
        self.presets_view = self.builder.get_object("presets_view")
        self.entry_filter = self.builder.get_object("entry_filter")
        self.button_add = self.builder.get_object("button_add")
        self.button_destination = self.builder.get_object("button_destination")
        self.button_del = self.builder.get_object("button_del")
        self.button_info = self.builder.get_object("button_info")
        
        self.settings_frame = self.builder.get_object("settings_frame")
        
        self.presets_model = gtk.ListStore(gtk.gdk.Pixbuf,        # Image
                                           gobject.TYPE_STRING,   # Preset
                                           gobject.TYPE_PYOBJECT) # Data
        self.presets_model.set_sort_column_id(1, gtk.SORT_ASCENDING)
        
        self.presets_filter = self.presets_model.filter_new()
        self.presets_filter.set_visible_func(self._filter)
        
        self.presets_view.set_model(self.presets_filter)
        
        self.presets_view.get_selection().connect("changed", self.on_preset_changed)
        
        pixbuf_renderer = gtk.CellRendererPixbuf()
        preset_renderer = gtk.CellRendererText()
        
        column = gtk.TreeViewColumn(_("Device Preset"))
        column.pack_start(pixbuf_renderer, False)
        column.set_attributes(pixbuf_renderer, pixbuf = 0)
        column.pack_start(preset_renderer)
        column.set_attributes(preset_renderer, markup = 1)
        self.presets_view.append_column(column)
        
        self.source = None
        self.source_hbox = None
        self.finder = None
        self.finder_video_found = None
        self.finder_video_lost = None
        
        self.table = self.builder.get_object("settings_table")
        
        self.setup_source()
        
        gobject.idle_add(self.setup_devices)
        
        self.fileiter = None
        self.options = arista.transcoder.TranscoderOptions()
        
        # Setup configuration system
        client = gconf.client_get_default()
        
        client.add_dir(CONFIG_PATH, gconf.CLIENT_PRELOAD_NONE)
        
        try:
            value = client.get_value(CONFIG_PATH + "/last_open_path")
            if value and os.path.exists(value):
                self.last_open_path = value
            else:
                self.last_open_path = DEFAULT_OPEN_PATH
        except ValueError:
            self.last_open_path = DEFAULT_OPEN_PATH
        
        self.button_destination.set_current_folder(self.last_open_path)
        
        client.notify_add(CONFIG_PATH + "/last_open_path", 
                          self.on_gconf_last_open_path)
        client.notify_add(CONFIG_PATH + "/check_inputs", self.setup_source)
        
        self.source.show()
        
        self.builder.connect_signals(self)
        
        self.window.show_all()
    
    def setup_source(self, *args):
        """
            Setup the source widget. Creates a combo box or a file input button
            depending on the settings and available devices.
        """
        theme = gtk.icon_theme_get_default()
        size = gtk.icon_size_lookup(gtk.ICON_SIZE_MENU)[0]
        
        # Already exists? Remove it!
        if self.source:
            self.source_hbox.remove(self.source)
            self.source.destroy()
        
        if self.finder:
            if self.finder_disc_found is not None:
                self.finder.disconnect(self.finder_disc_found)
                self.finder_disc_found = None
            
            if self.finder_disc_lost is not None:
                self.finder.disconnect(self.finder_disc_lost)
                self.finder_disc_lost = None
        
        # Should we check for DVD drives?
        client = gconf.client_get_default()
        try:
            check_inputs = client.get_value(CONFIG_PATH + "/check_inputs")
        except ValueError:
            check_inputs = DEFAULT_CHECK_INPUTS
        
        if check_inputs:
            # Setup input source discovery
            # Adds DVD and V4L devices to the source combo box
            if not self.finder:
                self.finder = arista.inputs.InputFinder()
                
            if len(self.finder.drives) or len(self.finder.capture_devices):
                icon = gtk.stock_lookup(gtk.STOCK_CDROM)[0]
                self.source = _new_combo_with_image([gobject.TYPE_PYOBJECT])
                model = self.source.get_model()
                
                for block, drive in self.finder.drives.items():
                    iter = model.append()
                    model.set_value(iter, 0, theme.load_icon(icon, size, 0))
                    model.set_value(iter, 1, drive.nice_label)
                    model.set_value(iter, 2, ("dvd://" + block, drive.media))
                
                for device, capture in self.finder.capture_devices.items():
                    iter = model.append()
                    try:
                        model.set_value(iter, 0, theme.load_icon("camera-video",
                                                             size, 0))
                    except:
                        pass
                    model.set_value(iter, 1, capture.nice_label)
                    if capture.version == '1':
                        model.set_value(iter, 2, ("v4l://" + device, True))
                    elif capture.version == '2':
                        model.set_value(iter, 2, ("v4l2://" + device, True))
                    else:
                        _log.warning(_("Unknown V4L version %(version)s!") % {
                                       "version": capture.version,
                                    })
                        model.remove(iter)
                
                iter = model.append()
                icon = gtk.stock_lookup(gtk.STOCK_OPEN)[0]
                model.set_value(iter, 0, theme.load_icon(icon, size, 0))
                model.set_value(iter, 1, _("Choose File..."))
                
                iter = model.append()
                icon = gtk.stock_lookup(gtk.STOCK_OPEN)[0]
                model.set_value(iter, 0, theme.load_icon(icon, size, 0))
                model.set_value(iter, 1, _("Choose Directory..."))
                
                self.source.set_active(0)
                self.source.connect("changed", self.on_source_changed)
                
                # Watch for DVD discovery events
                self.finder_disc_found = self.finder.connect("disc-found",
                                                        self.on_disc_found)
                self.finder_disc_lost = self.finder.connect("disc-lost",
                                                        self.on_disc_lost)
            else:
                self.source = gtk.FileChooserButton(_("Choose File..."))
        else:
            self.source = gtk.FileChooserButton(_("Choose File..."))
        
        # Add properties button to set source properties like subtitles
        source_prop_image = gtk.Image()
        source_prop_image.set_from_stock(gtk.STOCK_PROPERTIES, 
                                         gtk.ICON_SIZE_MENU)
        source_properties = gtk.Button()
        source_properties.add(source_prop_image)
        source_properties.connect("clicked", self.on_source_properties)
        
        if not self.source_hbox:
            self.source_hbox = gtk.HBox()
            self.source_hbox.pack_end(source_properties, expand = False)
            self.table.attach(self.source_hbox, 1, 2, 0, 1, yoptions = gtk.FILL)
        
        self.source_hbox.pack_start(self.source)
        
        # Attach and show the source
        self.source_hbox.show_all()
    
    def setup_devices(self):
        """
            Setup the device presets view.
        """
        # Find plugins and sort them nicely
        # Adds output device profiles to the output device view
        model = self.presets_view.get_model().get_model()
        
        # Remove existing items
        model.clear()
        
        self.default_device = 0
        for x, (id, device) in enumerate(arista.presets.get().items()):
            for (preset_id, preset) in sorted(device.presets.items(), lambda x, y: cmp(x[1].name, y[1].name)):
                iter = self._add_device(model, device, preset)
                
                if id == "computer" and preset == device.default_preset:
                    self.default_device = iter
        
        self.presets_view.set_cursor(model.get_path(self.default_device))
        self.presets_view.scroll_to_cell(model.get_path(self.default_device))
        
        if self.selected_preset:
            self.select_preset(self.selected_preset)
    
    def _add_device(self, model, device, preset):
        iter = model.append()
        
        image = _get_icon_pixbuf(preset.icon or device.icon, 32, 32)
        
        if image:
            model.set_value(iter, 0, image)
        
        model.set_value(iter, 1, "<b>%s - %s</b>\nUp to %sx%s" % (device.name, preset.name, preset.vcodec.width[1], preset.vcodec.height[1]))
        model.set_value(iter, 2, (device, preset))
        
        return iter
    
    def _filter(self, model, iter):
        """
            Filter device presets view to show only presets that match the
            string typed into the filter text input box.
        """
        iter_value = model.get_value(iter, 2)
        
        if not iter_value:
            return False
        
        (device, preset) = iter_value
        search_text = self.entry_filter.get_text().lower().strip()
        
        strings = [device.name, device.description, preset.name, preset.vcodec.name, preset.acodec.name]
        
        for string in strings:
            if search_text in string.lower():
                return True
        
        return False
    
    def select_preset(self, name):
        """
            Select a named preset in the list. If it is not found then the
            selection is not updated.
        """
        for item in self.presets_model:
            if item[1].split("\n")[0].strip("</b>") == name:
                self.presets_view.set_cursor(item.path)
                self.presets_view.scroll_to_cell(item.path)
    
    def get_default_output_name(self, inname, outdir, preset):
        """
            Get the default recommended output filename given an input path
            and a dir/preset. The original extension is removed, then the new
            preset extension is added. If such a path already exists then
            numbers are added before the extension until a non-existing path
            is found to exist.
        """
        if "." in inname:
            default_out = os.path.join(outdir, os.path.basename(".".join(inname.split(".")[:-1]) + "." + preset.extension))
        else:
            default_out = os.path.join(outdir, os.path.basename(inname + "." + preset.extension))
        
        while os.path.exists(default_out):
            parts = default_out.split(".")
            name, ext = ".".join(parts[:-1]), parts[-1]
            
            result = RE_ENDS_NUM.search(name)
            if result:
                value = result.group("number")
                name = name[:-len(value)]
                number = int(value) + 1
            else:
                number = 1
                
            default_out = "%s%d.%s" % (name, number, ext)
        
        return default_out
    
    def on_filter_changed(self, widget):
        """
            Device presets view filter changed.
        """
        self.presets_filter.refilter()
    
    def on_preset_changed(self, selection):
        model, iter = selection.get_selected()
        
        if hasattr(self.source, "get_model"):
            smodel, siter = self.source.get_model(), self.source.get_active_iter()
            source = smodel.get_value(siter, 2)[1]
        else:
            source = self.source.get_filename()
        
        self.button_del.set_sensitive(bool(iter))
        self.button_info.set_sensitive(bool(iter))
        self.button_add.set_sensitive(bool(iter and source))
    
    def on_disc_found(self, finder, device, label):
        """
            A video DVD has been found, update the source combo box!
        """
        model = self.source.get_model()
        for pos, item in enumerate(model):
            if item[2] and item[2][0].endswith(device.path):
                model[pos] = (item[0], device.nice_label, (item[2][0], True))
                break
        
        # Update UI sensitivity of various buttons
        self.on_preset_changed(self.presets_view.get_selection())
    
    def on_disc_lost(self, finder, device, label):
        """
            A video DVD has been removed, update the source combo box!
        """
        model = self.source.get_model()
        for pos, item in enumerate(model):
            if item[2] and item[2][0].endswith(device.path):
                model[pos] = (item[0], device.nice_label, (item[2][0], False))
                break
        
        # Update UI sensitivity of various buttons
        self.on_preset_changed(self.presets_view.get_selection())
    
    def on_gconf_last_open_path(self, client, connection, entry, args):
        """
            Change the default location of the open dialog when choosing a 
            new file or folder to transcode.
        """
        path = entry.get_value().get_string()
        if os.path.exists(path):
            self.last_open_path = path
        else:
            self.last_open_path = DEFAULT_OPEN_PATH
        
        self.button_destination.set_current_folder(self.last_open_path)
    
    def on_source_changed(self, widget):
        """
            The source combo box or file chooser button has changed, update!
        """
        theme = gtk.icon_theme_get_default()
        size = gtk.ICON_SIZE_MENU
        width, height = gtk.icon_size_lookup(size)
        
        iter = widget.get_active_iter()
        model = widget.get_model()
        item = model.get_value(iter, 1)
        if item == _("Choose File..."):
            dialog = gtk.FileChooserDialog(title=_("Choose Source File..."),
                        buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                                 gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT))
            dialog.set_property("local-only", False)
            dialog.set_current_folder(self.last_open_path)
            response = dialog.run()
            dialog.hide()
            filename = None
            if response == gtk.RESPONSE_ACCEPT:
                if self.fileiter:
                    model.remove(self.fileiter)
                filename = dialog.get_filename()
                client = gconf.client_get_default()
                client.set_string(CONFIG_PATH + "/last_open_path",
                                  os.path.dirname(filename))
                self.set_source_to_path(filename)
            else:
                if self.fileiter:
                    pos = widget.get_active()
                    widget.set_active(pos - 1)
                else:
                    widget.set_active(0)

        elif item == _("Choose Directory..."):
            dialog = gtk.FileChooserDialog(title=_("Choose Source Directory..."),
                        action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
                        buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                                 gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT))
            dialog.set_property("local-only", False)
            dialog.set_current_folder(self.last_open_path)
            response = dialog.run()
            dialog.hide()
            if response == gtk.RESPONSE_ACCEPT:
                if self.fileiter:
                    model.remove(self.fileiter)
                directory = dialog.get_current_folder()
                client = gconf.client_get_default()
                client.set_string(CONFIG_PATH + "/last_open_path", directory)
                self.set_source_to_path(directory)
            else:
                if self.fileiter:
                    pos = widget.get_active()
                    widget.set_active(pos - 2)
                else:
                    widget.set_active(0)
        
        # Simulate preset being changed to update UI sensitivity to clicks
        self.on_preset_changed(self.presets_view.get_selection())
    
    def set_source_to_path(self, path):
        """
            Set the source selector widget to a path.
        """
        if not hasattr(self.source, "get_model"):
            # Source is not a combo box
            self.source.set_filename(path)
            return
        
        size = gtk.ICON_SIZE_MENU
        width, height = gtk.icon_size_lookup(size)
        
        model = self.source.get_model()
        pos = self.source.get_active()
        newiter = model.insert(pos)
        
        # Reset the custom input options
        self.options.reset()
        
        if os.path.isdir(path):
            icon = icon = _get_icon_pixbuf("stock://gtk-directory", width, height)
        else:
            icon = _get_filename_icon(path)
            if icon:
                icon = icon.load_icon()
            
            # Find a subtitle file with same filename
            subfilename = path[0:path.rfind(".")]+".srt" 
            if os.path.exists(subfilename):
                self.options.subfile = subfilename
        
        if icon:
             model.set_value(newiter, 0, icon)
        
        basename = os.path.basename(path.rstrip("/"))
        if len(basename) > 25:
            basename = basename[:22] + "..."
        model.set_value(newiter, 1, basename)
        model.set_value(newiter, 2, (path, True))
        
        self.fileiter = newiter
        self.source.set_active(pos)
    
    def on_source_properties(self, widget):
        """
            Show source properties dialog so user can set things like
            subtitles, forcing deinterlacing, etc.
        """
        dialog = PropertiesDialog(self.options)
        dialog.window.run()
        dialog.window.destroy()
    
    def on_destination_changed(self, widget):
        pass
    
    def on_cancel(self, widget):
        self.window.destroy()
    
    def on_add(self, widget):
        model, iter = self.presets_view.get_selection().get_selected()
        
        device, preset = model.get_value(iter, 2)
        
        can_encode = preset.check_elements(self.on_preset_ready)
    
    def on_preset_ready(self, preset, can_encode):
        """
            Called when a preset is ready to be encoded after checking for
            (and optionally installing) required GStreamer elements.
        """
        if not can_encode:
            gtk.gdk.threads_enter()
            dialog = gtk.MessageDialog(self.window, type = gtk.MESSAGE_ERROR, buttons = gtk.BUTTONS_OK, message_format = _("Cannot add conversion to queue because of missing elements!"))
            dialog.run()
            dialog.destroy()
            gtk.gdk.threads_leave()
            return
        
        gtk.gdk.threads_enter()
        if isinstance(self.source, gtk.ComboBox):
            iter = self.source.get_active_iter()
            model = self.source.get_model()
            inpath = model.get_value(iter, 2)[0]
            inname = os.path.basename(inpath)
        else:
            inpath = self.source.get_filename()
            inname = os.path.basename(inpath)
        
        filenames = []
        outdir = self.button_destination.get_current_folder()
        
        if not os.path.isdir(inpath):
            filenames.append((inpath, self.get_default_output_name(inpath, outdir, preset)))
        else:
            for root, dirs, files in os.walk(inpath):
                for fname in files:
                    full_path = os.path.join(root, fname)
                    filenames.append((full_path, self.get_default_output_name(full_path, outdir, preset)))
        
        for inpath, outpath in filenames:
            # Setup the transcode job options
            self.options.uri = inpath
            self.options.preset = preset
            self.options.output_uri = outpath
            
            self.parent.queue.append(self.options)
            
            # Reset options for next item, but copy relevant data
            options = arista.transcoder.TranscoderOptions()
            options.subfile = self.options.subfile
            options.font = self.options.font
            options.deinterlace = self.options.deinterlace
            self.options = options
        
        self.window.destroy()
        
        gtk.gdk.threads_leave()
    
    def on_new_clicked(self, widget):
        """
            Create a new device preset.
        """
        devices = arista.presets.get()
        shortname = "new"
        count = 1
        
        # Get a unique name not overwriting another device
        while shortname in devices:
            shortname = "new" + str(count)
            count += 1
        
        # Create a new device and preset
        device = arista.presets.Device.from_json("""
            {
                "make": "Generic", 
                "model": "New Device", 
                "description": "", 
                "author": {
                    "name": "", 
                    "email": ""
                }, 
                "version": "1.0", 
                "icon": "", 
                "default": "", 
                "presets": [
                    {
                        "name": "New Preset", 
                        "container": "mp4mux", 
                        "extension": "mp4",  
                        "vcodec": {
                            "passes": [
                                "pass=pass=qual quantizer=21 me=umh subme=6 ref=3 threads=0"
                            ], 
                            "container": "mp4mux", 
                            "name": "x264enc", 
                            "height": [
                                240, 
                                1080
                            ], 
                            "width": [
                                320, 
                                1920
                            ], 
                            "rate": [
                                1,
                                30
                            ]
                        }, 
                        "acodec": {
                            "passes": [
                                "bitrate=192000"
                            ], 
                            "container": "mp4mux", 
                            "name": "faac", 
                            "depth": [
                                8, 
                                24
                            ], 
                            "channels": [
                                1, 
                                6
                            ], 
                            "width": [
                                8, 
                                24
                            ], 
                            "rate": [
                                8000, 
                                96000
                            ]
                        }
                    }
                ]
            }
        """)
        
        device.filename = arista.utils.get_write_path("presets", shortname + ".json")
        
        devices[shortname] = device
        
        model = self.presets_model
        
        self.entry_filter.set_text("")
        iter = self._add_device(model, device, device.presets.values()[0])
        self.presets_view.set_cursor(model.get_path(iter))
        self.presets_view.scroll_to_cell(model.get_path(iter))
        
        self.on_info_clicked(self.presets_view)
    
    def on_delete_clicked(self, widget):
        """
            Delete a device preset. Asks the user if she is really sure before
            actually doing so.
        """
        model, iter = self.presets_view.get_selection().get_selected()
        device, preset = model.get_value(iter, 2)
        
        dialog = gtk.MessageDialog(self.window, type=gtk.MESSAGE_WARNING, buttons=gtk.BUTTONS_YES_NO, message_format="Are you sure you want to delete the %(preset)s preset?" % { "preset": device.name + " - " + preset.name })
        response = dialog.run()
        dialog.destroy()
        
        if response == gtk.RESPONSE_YES:
            devices = arista.presets.get()
            name = ".".join(os.path.basename(device.filename).split(".")[:-1])
            
            if len(device.presets) == 1:
                # This was the only preset, so delete the file
                del devices[name]
                
                if os.access(device.filename, os.W_OK):
                    os.unlink(device.filename)
            else:
                del device.presets[preset.name]
                if not os.access(device.filename, os.W_OK):
                    device.filename = arista.utils.get_write_path("presets", os.path.basename(device.filename))
                
                device.save()
            
            self.presets_model.remove(model.convert_iter_to_child_iter(iter))
    
    def on_info_clicked(self, widget):
        """
            Display an edit dialog allowing you to view info about and manage
            device presets.
        """
        model, iter = self.presets_view.get_selection().get_selected()
        
        device, preset = model.get_value(iter, 2)
        
        dialog = PresetDialog(preset)
        
        dialog.connect("changed", self.preset_changed, "text", model.convert_iter_to_child_iter(iter))
        dialog.connect("icon-changed", self.preset_changed, "icon", model.convert_iter_to_child_iter(iter))
    
    def preset_changed(self, dialog, type, iter):
        model = self.presets_view.get_model().get_model()
        device, preset = dialog.preset.device, dialog.preset
        
        # Update
        if type == "icon":
            model.set_value(iter, 0, _get_icon_pixbuf(preset.icon or device.icon, 32, 32))
        elif type == "text":
            model.set_value(iter, 1, "<b>%s - %s</b>\nUp to %sx%s" % (device.name, preset.name, preset.vcodec.width[1], preset.vcodec.height[1]))

class PresetDialog(gobject.GObject):
    """
        Arista Preset Dialog
        ====================
        A dialog for viewing and editing preset properties.
    """
    __gsignals__ =  {
        "changed": (gobject.SIGNAL_RUN_FIRST, None, ()),
        "icon-changed": (gobject.SIGNAL_RUN_FIRST, None, ()),
    }
    
    CONTAINER_LIST = ["WebM", "MP4", "MOV", "AVI", "MPEG PS", "MPEG TS", "DVD (VOB)", "Matroska", "Ogg", "FLV"]
    MUXER_TO_CONTAINER = {
        "webmmux": 0,
        "ffmux_webm": 0,
        "mp4mux": 1,
        "ffmux_mp4": 1,
        "qtmux": 2,
        "ffmux_mov": 2,
        "avimux": 3,
        "ffmux_avi": 3,
        "mpegpsmux": 4,
        "mpegtsmux": 5,
        "ffmux_mpegts": 5,
        "ffmux_vob": 6,
        "ffmux_dvd": 6,
        "matroskamux": 7,
        "ffmux_matroska": 7,
        "oggmux": 8,
        "ffmux_ogg": 8,
        "flvmux": 9,
        "ffmux_flv": 9,
    }
    CONTAINER_TO_MUXER = {
        "WebM": "webmmux",
        "MP4": "mp4mux",
        "MOV": "qtmux",
        "AVI": "avimux",
        "MPEG PS": "mpegpsmux",
        "MPEG TS": "mpegtsmux",
        "DVD (VOB)": "ffmux_dvd",
        "Matroska": "matroskamux",
        "Ogg": "oggmux",
        "FLV": "flvmux",
    }
    ENCODER_TO_VCODEC = {
        "vp8enc": "VP8",
        "x264enc": "H.264 / AVC",
        "xvidenc": "MPEG4 / DivX / XviD",
        "mpeg2enc": "MPEG2",
        "theoraenc": "Theora",
        "ffenc_flv": "FLV / Spark / H.263",
    }
    VCODEC_TO_ENCODER = {
        "VP8": "vp8enc",
        "H.264 / AVC": "x264enc",
        "MPEG4 / DivX / XviD": "xvidenc",
        "MPEG2": "mpeg2enc",
        "Theora": "theoraenc",
        "FLV / Spark / H.263": "ffenc_flv",
    }
    ENCODER_TO_ACODEC = {
        "faac": "AAC",
        "lame": "MP3",
        "vorbisenc": "Vorbis",
        "ffenc_ac3": "AC-3",
        "flacenc": "FLAC",
        "twolame": "MP2",
    }
    ACODEC_TO_ENCODER = {
        "Vorbis": "vorbisenc",
        "AAC": "faac",
        "MP3": "lame",
        "AC-3": "ffenc_ac3",
        "FLAC": "flacenc",
        "MP2": "twolame",
    }
    EFFECT_LIST = ["None", "Rotate clockwise", "Rotate counter-clockwise", "Flip vertical", "Flip horizontal"]
    EFFECT_TO_ELEMENTS = {
        "None": "",
        "Rotate clockwise": "videoflip method=clockwise",
        "Rotate counter-clockwise": "videoflip method=counterclockwise",
        "Flip vertical": "videoflip method=vertical-flip",
        "Flip horizontal": "videoflip method=horizontal-flip",
    }
    ELEMENTS_TO_EFFECT = {
        "": 0,
        "videoflip method=clockwise": 1,
        "videoflip method=1": 1,
        "videoflip method=counterclockwise": 2,
        "videoflip method=3": 2,
        "videoflip method=vertical-flip": 3,
        "videoflip method=5": 3,
        "videoflip method=horizontal-flip": 4,
        "videoflip method=4": 4,
    }
    
    def __init__(self, preset):
        gobject.GObject.__init__(self)
        ui_path = arista.utils.get_path("ui", "preset.ui")
        
        self.builder = gtk.Builder()
        self.builder.add_from_file(ui_path)
        
        self.window = self.builder.get_object("preset_dialog")
        
        self.image = self.builder.get_object("image_icon")
        self.short_name = self.builder.get_object("entry_short_name")
        self.description = self.builder.get_object("entry_description")
        self.make = self.builder.get_object("entry_make")
        self.model = self.builder.get_object("entry_model")
        self.preset_name = self.builder.get_object("entry_preset")
        self.author_name = self.builder.get_object("entry_author_name")
        self.author_email = self.builder.get_object("entry_author_email")
        self.version = self.builder.get_object("entry_version")
        self.container = self.builder.get_object("combo_container")
        self.extension = self.builder.get_object("entry_extension")
        
        self.video_codec = self.builder.get_object("combo_video_codec")
        self.video_options = self.builder.get_object("entry_video_options")
        self.width_min = self.builder.get_object("spin_width_min")
        self.width_max = self.builder.get_object("spin_width_max")
        self.height_min = self.builder.get_object("spin_height_min")
        self.height_max = self.builder.get_object("spin_height_max")
        self.framerate_min = self.builder.get_object("spin_framerate_min")
        self.framerate_max = self.builder.get_object("spin_framerate_max")
        self.effect = self.builder.get_object("combo_effect")
        
        self.audio_codec = self.builder.get_object("combo_audio_codec")
        self.audio_options = self.builder.get_object("entry_audio_options")
        self.channels_min = self.builder.get_object("spin_channels_min")
        self.channels_max = self.builder.get_object("spin_channels_max")
        
        # Set general values
        if preset.icon or preset.device.icon:
            width, height = gtk.icon_size_lookup(gtk.ICON_SIZE_DIALOG)
            image = _get_icon_pixbuf(preset.icon or preset.device.icon, width, height)
            
            if image:
                self.image.set_from_pixbuf(image)
        
        self.short_name.set_text(".".join(os.path.basename(preset.device.filename).split(".")[:-1]))
        self.description.set_text(preset.description or preset.device.description)
        self.make.set_text(preset.device.make)
        self.model.set_text(preset.device.model)
        self.preset_name.set_text(preset.name)
        self.author_name.set_text(preset.author.name or preset.device.author.name)
        self.author_email.set_text(preset.author.email or preset.device.author.email)
        self.version.set_text(preset.version or preset.device.version)
        self.extension.set_text(preset.extension or preset.device.extension)
        
        # Setup list models for combo boxes
        cstore = gtk.ListStore(gobject.TYPE_STRING)
        self.container.set_model(cstore)
        text_cell = gtk.CellRendererText()
        self.container.pack_start(text_cell, True)
        self.container.add_attribute(text_cell, 'text', 0)
        
        # Setup possible containers
        for attr in self.CONTAINER_LIST:
            iter = cstore.append()
            cstore.set_value(iter, 0, attr)
        
        vstore = gtk.ListStore(gobject.TYPE_STRING)
        self.video_codec.set_model(vstore)
        text_cell = gtk.CellRendererText()
        self.video_codec.pack_start(text_cell, True)
        self.video_codec.add_attribute(text_cell, 'text', 0)
        
        astore = gtk.ListStore(gobject.TYPE_STRING)
        self.audio_codec.set_model(astore)
        text_cell = gtk.CellRendererText()
        self.audio_codec.pack_start(text_cell, True)
        self.audio_codec.add_attribute(text_cell, 'text', 0)
        
        # Set active container
        self.container.set_active(self.MUXER_TO_CONTAINER.get(preset.container, 0))
        
        # Update codec combos to show valid codecs for selected container
        self.update_codecs(self.CONTAINER_LIST[self.MUXER_TO_CONTAINER[preset.container]])
        
        for widget, codec in [(self.video_codec, self.ENCODER_TO_VCODEC[preset.vcodec.name]), (self.audio_codec, self.ENCODER_TO_ACODEC[preset.acodec.name])]:
            for i, row in enumerate(widget.get_model()):
                if row[0] == codec:
                    widget.set_active(i)
        
        # Set codec values
        self.video_options.set_text(";".join(preset.vcodec.passes))
        self.width_min.set_value(preset.vcodec.width[0])
        self.width_max.set_value(preset.vcodec.width[1])
        self.height_min.set_value(preset.vcodec.height[0])
        self.height_max.set_value(preset.vcodec.height[1])
        self.framerate_min.set_value(preset.vcodec.rate[0])
        self.framerate_max.set_value(preset.vcodec.rate[1])
        
        self.audio_options.set_text(";".join(preset.acodec.passes))
        self.channels_min.set_value(preset.acodec.channels[0])
        self.channels_max.set_value(preset.acodec.channels[1])
        
        # Setup effects
        estore = gtk.ListStore(gobject.TYPE_STRING)
        self.effect.set_model(estore)
        text_cell = gtk.CellRendererText()
        self.effect.pack_start(text_cell, True)
        self.effect.add_attribute(text_cell, 'text', 0)
        
        for attr in self.EFFECT_LIST:
            iter = estore.append()
            estore.set_value(iter, 0, attr)
        
        effect = self.ELEMENTS_TO_EFFECT.get(preset.vcodec.transform, 5)
        # Handle custom effects we don't recognize
        if effect == 5:
            iter = estore.append()
            estore.set_value(iter, 0, "Custom")
            self.effect.set_sensitive(False)
        self.effect.set_active(effect)
        
        self.builder.connect_signals(self)
        
        self.preset = preset
        
        self.window.show_all()
    
    def on_destroy(self, widget):
        _log.debug(_("Saving preset to disk..."))
        self.preset.device.save()
    
    def on_close_clicked(self, widget):
        self.window.destroy()
    
    def on_export_clicked(self, widget):
        if len(self.preset.device.presets) > 1:
            dialog = gtk.MessageDialog(self.window, buttons=gtk.BUTTONS_YES_NO, message_format=_("You are about to export %(count)d presets with the short name '%(shortname)s'. If you want to only export %(name)s then please first change the short name. Do you want to continue?") % {
                "count": len(self.preset.device.presets),
                "shortname": self.preset.device.short_name,
                "name": self.preset.device.name + " - " + self.preset.name
            })
            response = dialog.run()
            dialog.destroy()
            if response == gtk.RESPONSE_NO:
                return
        
        dialog = gtk.FileChooserDialog(title=_("Export Preset"),
                    action=gtk.FILE_CHOOSER_ACTION_SAVE,
                    buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                             gtk.STOCK_SAVE, gtk.RESPONSE_ACCEPT))
        dialog.set_property("local-only", False)
        filter = gtk.FileFilter()
        filter.set_name("Arista Presets")
        filter.add_pattern("*.bz2")
        dialog.set_filter(filter)
        dialog.set_current_folder(os.path.expanduser(os.path.join("~", "Desktop")))
        dialog.set_current_name(self.preset.device.short_name + ".tar.bz2")
        response = dialog.run()
        dialog.hide()
        if response == gtk.RESPONSE_ACCEPT:
            filename = dialog.get_filename()
            if not filename.endswith(".tar.bz2"):
                filename += ".tar.bz2"
            self.preset.device.export(filename)
            dialog.destroy()
            if len(self.preset.device.presets) > 1:
                msg = _("Export of '%(shortname)s' with %(count)d presets complete.") % {
                    "shortname": self.preset.device.short_name,
                    "count": len(self.preset.device.presets),
                }
            else:
                msg = _("Export of '%(name)s' complete.") % {
                    "name": self.preset.device.name + " - " + self.preset.name
                }
            dialog = gtk.MessageDialog(self.window, buttons=gtk.BUTTONS_OK, message_format=msg)
            dialog.run()
            dialog.destroy()
    
    def on_icon_clicked(self, widget):
        # Let user select new image, copy to presets folder, possibly rename
        client = gconf.client_get_default()
        dialog = gtk.FileChooserDialog(title=_("Choose Preset Icon..."),
                    buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                             gtk.STOCK_OPEN, gtk.RESPONSE_ACCEPT))
        dialog.set_property("local-only", False)
        dialog.set_current_folder(os.path.expanduser(os.path.join("~", "Pictures")))
        filter = gtk.FileFilter()
        filter.set_name("Image Files")
        filter.add_pattern("*.png")
        filter.add_pattern("*.svg")
        dialog.set_filter(filter)
        response = dialog.run()
        dialog.hide()
        if response == gtk.RESPONSE_ACCEPT:
            filename = dialog.get_filename()
            ext = filename.split(".")[-1]
            output = arista.utils.get_write_path("presets", self.preset.slug + "." + ext)
            shutil.copy(filename, output)
            self.preset.icon = "file://" + self.preset.slug + "." + ext
            width, height = gtk.icon_size_lookup(gtk.ICON_SIZE_DIALOG)
            image = _get_icon_pixbuf(self.preset.icon, width, height)
            self.image.set_from_pixbuf(image)
            
            self.emit("icon-changed")
    
    def on_shortname_changed(self, widget, arg):
        # Change the filename, update icon filename if present, etc
        # This can actually be used to group multiple presets into a single
        # file. Hopefully that's not too confusing.
        old_name = ".".join(os.path.basename(self.preset.device.filename).split(".")[:-1])
        new_name = widget.get_text()
        if new_name:
            old_filename = self.preset.device.filename
            devices = arista.presets.get()
            
            if new_name in devices:
                # We are moving this preset into an existing device
                devices[new_name].presets[self.preset.name] = self.preset
            else:
                # We are creating a new device file
                devices[new_name] = arista.presets.Device(**{
                    "make": devices[old_name].make,
                    "model": devices[old_name].model,
                    "description": devices[old_name].description,
                    "author": arista.presets.Author(**{
                        "name": devices[old_name].author.name,
                        "email": devices[old_name].author.email,
                    }),
                    "version": devices[old_name].version,
                    "presets": {
                        self.preset.name: self.preset,
                    },
                    "icon": devices[old_name].icon,
                    "default": self.preset.name,
                })
                devices[new_name].filename = arista.utils.get_write_path("presets", new_name + ".json")
            
            self.preset.device = devices[new_name]
            self.make.set_text(self.preset.device.make)
            self.model.set_text(self.preset.device.model)
            
            if len(devices[old_name].presets) == 1:
                # This was the only preset, so delete the file
                del devices[old_name]
                
                if os.access(old_filename, os.W_OK):
                    os.unlink(old_filename)
            else:
                del devices[old_name].presets[self.preset.name]
                if not os.access(old_filename, os.W_OK):
                    devices[old_name].filename = arista.utils.get_write_path("presets", os.path.basename(old_filename))
                
                devices[old_name].save()
    
    def on_description_changed(self, widget):
        self.preset.description = widget.get_text()
    
    def on_make_changed(self, widget):
        self.preset.device.make = widget.get_text()
        
        self.emit("changed")
    
    def on_model_changed(self, widget):
        self.preset.device.model = widget.get_text()
        
        self.emit("changed")
    
    def on_name_changed(self, widget, arg):
        # Update device presets dictionary
        old_name = self.preset.name
        new_name = widget.get_text()
        if new_name:
            # Update default if needed
            if self.preset.device.default == old_name:
                self.preset.device.default = new_name
            # Update presets map
            del self.preset.device.presets[old_name]
            self.preset.device.presets[new_name] = self.preset
            # Set name on preset itself
            self.preset.name = new_name
            
            self.emit("changed")
    
    def on_author_name_changed(self, widget):
        self.preset.author.name = widget.get_text()
    
    def on_author_email_changed(self, widget):
        self.preset.author.email = widget.get_text()
    
    def on_version_changed(self, widget):
        self.preset.version = widget.get_text()
    
    def on_container_changed(self, widget):
        iter = self.container.get_active_iter()
        container = self.container.get_model().get_value(iter, 0)
        
        self.preset.container = self.CONTAINER_TO_MUXER[container]
        
        self.update_codecs(container)
        
        self.extension.set_text({
            "MPEG PS": "mpg",
            "MPEG TS": "ts",
            "DVD (VOB)": "vob",
            "Matroska": "mkv"
        }.get(container, container.lower()))
    
    def update_codecs(self, container):
        vcodecs = {
            "WebM": ["VP8"],
            "MP4": ["H.264 / AVC", "MPEG4 / DivX / XviD"],
            "MOV": ["H.264 / AVC", "MPEG4 / DivX / XviD"],
            "AVI": ["H.264 / AVC", "MPEG4 / DivX / XviD", "VP8"],
            "MPEG PS": ["H.264 / AVC", "MPEG4 / DivX / XviD", "MPEG2"],
            "MPEG TS": ["H.264 / AVC", "MPEG4 / DivX / XviD", "MPEG2"],
            "DVD (VOB)": ["MPEG2"],
            "Matroska": ["H.264 / AVC", "MPEG4 / DivX / XviD", "MPEG2", "VP8", "Theora"],
            "Ogg": ["Theora"],
            "FLV": ["H.264 / AVC", "FLV / Spark / H.263"],
        }.get(container, ["No known codecs"])
        
        acodecs = {
            "WebM": ["Vorbis"],
            "MP4": ["AAC", "MP3"],
            "MOV": ["AAC", "MP3"],
            "AVI": ["AAC", "MP3", "Vorbis"],
            "MPEG PS": ["AAC", "MP3"],
            "MPEG TS": ["AAC", "MP3"],
            "DVD (VOB)": ["MP2", "AC-3"],
            "Matroska": ["AAC", "MP3", "Vorbis", "FLAC"],
            "Ogg": ["Vorbis", "FLAC"],
            "FLV": ["MP3"],
        }.get(container, ["No known codecs"])
        
        for widget, codecs in [(self.video_codec, vcodecs), (self.audio_codec, acodecs)]:
            iter = widget.get_active_iter()
            model = widget.get_model()
            selected = iter and model.get_value(iter, 0) or ""
            new_selected = 0
            model.clear()
            
            for i, codec in enumerate(codecs):
                iter = model.append()
                model.set_value(iter, 0, codec)
                if codec == selected:
                    new_selected = i
                    
            widget.set_active(new_selected)
    
    def on_extension_changed(self, widget):
        self.preset.extension = widget.get_text()
    
    def on_vcodec_changed(self, widget):
        iter = self.video_codec.get_active_iter()
        vcodec = iter and self.video_codec.get_model().get_value(iter, 0) or None
        
        if vcodec and self.ENCODER_TO_VCODEC[self.preset.vcodec.name] != vcodec:
            self.preset.vcodec.name = self.VCODEC_TO_ENCODER[vcodec]
            self.video_options.set_text({
                "VP8": "quality=6 threads=%(threads)s speed=2",
                "H.264 / AVC": "pass=qual quantizer=21 me=umh subme=6 ref=3 threads=0",
                "MPEG4 / DivX / XviD": "pass=quant quantizer=5 max-bframes=2 trellis=true",
                "MPEG2": "format=3 quantisation=5",
                "FLV / Spark / H.263": "bitrate=512000",
            }.get(vcodec, ""))
    
    def on_video_options_changed(self, widget):
        self.preset.vcodec.passes = widget.get_text().split(";")
    
    def on_width_min_changed(self, widget):
        value = int(widget.get_value())
        self.preset.vcodec.width[0] = value
        
        if self.width_max.get_value() < value:
            self.width_max.set_value(value)
    
    def on_width_max_changed(self, widget):
        value = int(widget.get_value())
        self.preset.vcodec.width[1] = value
        
        if self.width_min.get_value() > value:
            self.width_min.set_value(value)
        
        self.emit("changed")
    
    def on_height_min_changed(self, widget):
        value = int(widget.get_value())
        self.preset.vcodec.height[0] = value
        
        if self.height_max.get_value() < value:
            self.height_max.set_value(value)
    
    def on_height_max_changed(self, widget):
        value = int(widget.get_value())
        self.preset.vcodec.height[1] = value
        
        if self.height_min.get_value() > value:
            self.height_min.set_value(value)
        
        self.emit("changed")
    
    def on_framerate_min_changed(self, widget):
        value = widget.get_value()
        self.preset.vcodec.rate[0] = value
        
        if self.framerate_max.get_value() < value:
            self.framerate_max.set_value(value)
    
    def on_framerate_max_changed(self, widget):
        value = widget.get_value()
        self.preset.vcodec.framerate[1] = value
        
        if self.framerate_min.get_value() > value:
            self.framerate_min.set_value(value)
    
    def on_effect_changed(self, widget):
        iter = self.effect.get_active_iter()
        effect = iter and self.effect.get_model().get_value(iter, 0) or None
        
        if effect:
            self.preset.vcodec.transform = self.EFFECT_TO_ELEMENTS[effect]
    
    def on_acodec_changed(self, widget):
        iter = self.audio_codec.get_active_iter()
        acodec = iter and self.audio_codec.get_model().get_value(iter, 0) or None
        
        if acodec and self.ENCODER_TO_ACODEC[self.preset.acodec.name] != acodec:
            self.preset.acodec.name = self.ACODEC_TO_ENCODER[acodec]
            self.audio_options.set_text({
                "Vorbis": "quality=0.5",
                "AAC": "profile=4 bitrate=128000",
                "MP3": "vbr=new vbr-quality=4",
                "FLAC": "quality=6",
                "MP2": "bitrate=192",
                "AC-3": "bitrate=128000",
            }.get(acodec, ""))
    
    def on_audio_options_changed(self, widget):
        self.preset.acodec.passes = widget.get_text().split(";")
    
    def on_channels_min_changed(self, widget):
        value = widget.get_value()
        self.preset.acodec.channels[0] = value
        
        if self.channels_max.get_value() < value:
            self.channels_max.set_value(value)
    
    def on_channels_max_changed(self, widget):
        value = widget.get_value()
        self.preset.acodec.channels[1] = value
        
        if self.channels_min.get_value() > value:
            self.channels_min.set_value(value)
    
    def on_vcodec_help_clicked(self, widget):
        iter = self.video_codec.get_active_iter()
        vcodec = iter and self.video_codec.get_model().get_value(iter, 0) or None
        self.on_codec_help(vcodec)
    
    def on_acodec_help_clicked(self, widget):
        iter = self.audio_codec.get_active_iter()
        acodec = iter and self.audio_codec.get_model().get_value(iter, 0) or None
        self.on_codec_help(acodec)
    
    def on_codec_help(self, codec):
        try:
            html_path = arista.utils.get_path("help", "%s.html" % codec.split(" ")[0].lower())
        except IOError:
            html_path = arista.utils.get_path("help", "404.html")
        
        html_path = "file://" + html_path
        
        if webkit:
            CodecHelpDialog(html_path)
        else:
            webbrowser.open(html_path)

gobject.type_register(PresetDialog)

class CodecHelpDialog(object):
    """
        Arista Codec Help Dialog
        ========================
        A dialog showing various options for codecs.
    """
    def __init__(self, html_path):
        ui_path = arista.utils.get_path("ui", "codec.ui")
        
        self.builder = gtk.Builder()
        self.builder.add_from_file(ui_path)
        
        self.window = self.builder.get_object("codec_dialog")
        
        # Add web view to dialog
        scrolled_window = self.builder.get_object("scrolledwindow")
        self.webkit = webkit.WebView()
        scrolled_window.add(self.webkit)
        
        # Load documentation for specific codec
        self.webkit.load_uri(html_path)
        
        self.builder.connect_signals(self)
        
        self.window.show_all()
    
    def on_close(self, widget):
        self.window.destroy()

class AboutDialog(object):
    """
        Arista About Dialog
        ===================
        A simple about dialog.
    """
    def __init__(self):
        ui_path = arista.utils.get_path("ui", "about.ui")
        
        self.builder = gtk.Builder()
        self.builder.add_from_file(ui_path)
        
        self.window = self.builder.get_object("about_dialog")
        
        self.builder.connect_signals(self)
        
        self.window.show_all()
    
    def on_close(self, widget, response):
        """
            Close was clicked, remove the window.
        """
        self.window.destroy()

if __name__ == "__main__":
    parser = OptionParser(usage = _("%prog [options] [file1 file2 file3 ...]"),
                          version = _("Arista Transcoder GUI " + \
                                      arista.__version__))
    parser.add_option("-v", "--verbose", dest = "verbose",
                      action = "store_true", default = False,
                      help = _("Show verbose (debug) output"))
    parser.add_option("-p", "--preset", dest = "preset", default = None,
                      help = _("Preset to encode to [default]"))
    parser.add_option("-d", "--device", dest = "device", default = "computer",
                      help = _("Device to encode to [computer]"))
    parser.add_option("-s", "--simple", dest = "simple", action = "store_true",
                      default = False, help = _("Simple UI"))
    
    options, args = parser.parse_args()
    
    options.files = args
    
    logging.basicConfig(level = options.verbose and logging.DEBUG \
                        or logging.INFO, format = "%(name)s [%(lineno)d]: " \
                        "%(levelname)s %(message)s")
    
    # FIXME: OMGWTFBBQ gstreamer hijacks sys.argv unless we import AFTER we use
    # the optionparser stuff above...
    # This seems to be fixed http://bugzilla.gnome.org/show_bug.cgi?id=425847
    # but in my testing it is NOT. Leaving hacks for now.
    import gst
    import gst.pbutils
    
    arista.init()
    
    lc_path = arista.utils.get_path("locale", default = "")
    if lc_path:
        if hasattr(gettext, "bindtextdomain"):
            gettext.bindtextdomain("arista", lc_path)
        if hasattr(locale, "bindtextdomain"):
            locale.bindtextdomain("arista", lc_path)
    
    if hasattr(gettext, "bind_textdomain_codeset"):
        gettext.bind_textdomain_codeset("arista", "UTF-8")
    if hasattr(locale, "bind_textdomain_codeset"):
        locale.bind_textdomain_codeset("arista", "UTF-8")
    
    if hasattr(gettext, "textdomain"):
        gettext.textdomain("arista")
    if hasattr(locale, "textdomain"):
        locale.textdomain("arista")
    
    gtk.gdk.threads_init()
    
    # Set the default icon for all windows
    icon_path = arista.utils.get_path("ui", "icon.svg")
    gtk.window_set_default_icon_from_file(icon_path)
    
    main = MainWindow(options)
    
    # Renice by default to sort of background transcoding
    if hasattr(os, "nice"):
        _log.debug("Increasing niceness by 5...")
        os.nice(5)
    
    gtk.main()