aboutsummaryrefslogtreecommitdiffstats
path: root/lvc/ui/widgets.py
blob: 66f34b393a61f0580a915672c4b1c559ba5818d7 (plain)
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
import os
import sys

import copy
import tempfile
import urllib
import urlparse

from lvc.converter import ConverterInfo
from lvc.video import VideoFile
from lvc.resources import image_path
from lvc.utils import size_string, round_even, convert_path_for_subprocess
from lvc import openfiles

from lvc.widgets import (initialize, idle_add, mainloop_start, mainloop_stop,
                         attach_menubar, reveal_file, get_conversion_directory)

from lvc.widgets import menus
from lvc.widgets import widgetset
from lvc.widgets import cellpack
from lvc.widgets import widgetconst
from lvc.widgets import widgetutil
from lvc.widgets import app

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

try:
    import lvc
except ImportError:
    lvc_path = os.path.join(os.path.dirname(__file__), '..', '..')
    sys.path.append(lvc_path)
    import lvc

BUTTON_FONT = widgetutil.font_scale_from_osx_points(15.0)
LARGE_FONT = widgetutil.font_scale_from_osx_points(13.0)
SMALL_FONT = widgetutil.font_scale_from_osx_points(10.0)

DEFAULT_FONT = "Helvetica"

CONVERT_TO_FONT = "Gill Sans Light"
CONVERT_TO_FONTSIZE = widgetutil.font_scale_from_osx_points(14.0)

SETTINGS_FONT = "Gill Sans Light"
SETTINGS_FONTSIZE = widgetutil.font_scale_from_osx_points(13.0)

CONVERT_NOW_FONT = "Gill Sans Light"
CONVERT_NOW_FONTSIZE = widgetutil.font_scale_from_osx_points(18.0)

DND_FONT = "Gill Sans Light"
DND_LARGE_FONTSIZE = widgetutil.font_scale_from_osx_points(13.0)
DND_SMALL_FONTSIZE = widgetutil.font_scale_from_osx_points(12.0)

ITEM_TITLE_FONT = "Futura Medium"
ITEM_TITLE_FONTSIZE = widgetutil.font_scale_from_osx_points(13.0)

ITEM_ICONS_FONT = "Century Gothic"
ITEM_ICONS_FONTSIZE = widgetutil.font_scale_from_osx_points(10.0)

GRADIENT_TOP = widgetutil.css_to_color('#585f63')
GRADIENT_BOTTOM = widgetutil.css_to_color('#383d40')

DRAG_AREA = widgetutil.css_to_color('#2b2e31')

TEXT_DISABLED = widgetutil.css_to_color('#333333')
TEXT_ACTIVE = widgetutil.css_to_color('#ffffff')
TEXT_CLICKED = widgetutil.css_to_color('#cccccc')
TEXT_INFO = widgetutil.css_to_color('#808080')
TEXT_COLOR = widgetutil.css_to_color('#ffffff')
TEXT_SHADOW = widgetutil.css_to_color('#000000')

TABLE_WIDTH, TABLE_HEIGHT = 470, 87


class CustomLabel(widgetset.Background):
    def __init__(self, text=''):
        widgetset.Background.__init__(self)
        self.text = text
        self.font = DEFAULT_FONT
        self.font_scale = LARGE_FONT
        self.color = TEXT_COLOR

    def set_text(self, text):
        self.text = text
        self.invalidate_size_request()

    def set_color(self, color):
        self.color = color
        self.queue_redraw()

    def set_font(self, font, font_scale):
        self.font = font
        self.font_scale = font_scale
        self.invalidate_size_request()

    def textbox(self, layout_manager):
        layout_manager.set_text_color(self.color)
        layout_manager.set_font(self.font_scale, family=self.font)
        font = layout_manager.set_font(self.font_scale, family=self.font)
        return layout_manager.textbox(self.text)

    def draw(self, context, layout_manager):
        layout_manager.set_text_color(self.color)
        layout_manager.set_font(LARGE_FONT, family=self.font)
        textbox = self.textbox(layout_manager)
        size = textbox.get_size()
        textbox.draw(context, 0, (context.height - size[1]) // 2,
                     context.width, context.height)

    def size_request(self, layout_manager):
        return self.textbox(layout_manager).get_size()


class WebStyleButton(widgetset.CustomButton):
    def __init__(self):
        super(WebStyleButton, self).__init__()
        self.set_cursor(widgetconst.CURSOR_POINTING_HAND)
        self.text = ''
        self.font = DEFAULT_FONT
        self.font_scale = LARGE_FONT

    def set_text(self, text):
        self.text = text
        self.invalidate_size_request()

    def set_font(self, font, font_scale):
        self.font = font
        self.font_scale = font_scale
        self.invalidate_size_request()

    def textbox(self, layout_manager):
        return layout_manager.textbox(self.text, underline=True)

    def size_request(self, layout_manager):
        textbox = self.textbox(layout_manager)
        return textbox.get_size()

    def draw(self, context, layout_manager):
        layout_manager.set_text_color(TEXT_COLOR)
        layout_manager.set_font(self.font_scale, family=self.font)
        textbox = self.textbox(layout_manager)
        size = textbox.get_size()
        textbox.draw(context, 0, (context.height - size[1]) // 2,
                     context.width, context.height)


class FileDropTarget(widgetset.SolidBackground):

    dropoff_on = widgetset.ImageDisplay(widgetset.Image(
        image_path("dropoff-icon-on.png")))
    dropoff_off = widgetset.ImageDisplay(widgetset.Image(
        image_path("dropoff-icon-off.png")))
    dropoff_small_on = widgetset.ImageDisplay(widgetset.Image(
        image_path("dropoff-icon-small-on.png")))
    dropoff_small_off = widgetset.ImageDisplay(widgetset.Image(
        image_path("dropoff-icon-small-off.png")))

    def __init__(self):
        super(FileDropTarget, self).__init__()
        self.set_background_color(DRAG_AREA)
        self.alignment = widgetset.Alignment(
            xscale=0.0, yscale=0.5,
            xalign=0.5, yalign=0.5,
            top_pad=10, right_pad=40,
            bottom_pad=10, left_pad=40)
        self.add(self.alignment)

        self.widgets = {
            False: self.build_large_widgets(),
            True: self.build_small_widgets()
            }

        self.normal, self.drag = self.widgets[False]
        self.alignment.add(self.normal)

        self.in_drag = False
        self.small = False

    def build_large_widgets(self):
        height = 40  # arbitrary, but the same for both
        normal = widgetset.VBox(spacing=20)
        normal.pack_start(widgetutil.align_center(self.dropoff_off,
                                                  top_pad=60))
        label = CustomLabel("Drag videos here or")
        label.set_color(TEXT_COLOR)
        label.set_font(DND_FONT, DND_LARGE_FONTSIZE)
        hbox = widgetset.HBox(spacing=4)
        hbox.pack_start(widgetutil.align_middle(label))

        cfb = WebStyleButton()
        cfb.set_font(DND_FONT, DND_LARGE_FONTSIZE)
        cfb.set_text('Choose Files...')

        cfb.connect('clicked', self.choose_file)
        hbox.pack_start(widgetutil.align_middle(cfb))
        hbox.set_size_request(-1, height)
        normal.pack_start(hbox)

        drag = widgetset.VBox(spacing=20)
        drag.pack_start(widgetutil.align_center(self.dropoff_on,
                                                top_pad=60))
        hbox = widgetset.HBox(spacing=4)
        hbox.pack_start(widgetutil.align_center(
            widgetset.Label("Release button to drop off",
                            color=TEXT_COLOR)))
        hbox.set_size_request(-1, height)
        drag.pack_start(hbox)
        return normal, drag

    def build_small_widgets(self):
        height = 40  # arbitrary, but the same for both
        normal = widgetset.HBox(spacing=4)
        normal.pack_start(widgetutil.align_middle(self.dropoff_small_off,
                                                  right_pad=7))
        drag_label = CustomLabel('Drag more videos here or')
        drag_label.set_font(DND_FONT, DND_SMALL_FONTSIZE)
        drag_label.set_color(TEXT_COLOR)
        normal.pack_start(widgetutil.align_middle(drag_label))
        cfb = WebStyleButton()
        cfb.set_text('Choose Files...')
        cfb.set_font(DND_FONT, DND_SMALL_FONTSIZE)
        cfb.connect('clicked', self.choose_file)
        normal.pack_start(cfb)
        normal.set_size_request(-1, height)

        drop_label = CustomLabel('Release button to drop off')
        drop_label.set_font(DND_FONT, DND_SMALL_FONTSIZE)
        drop_label.set_color(TEXT_COLOR)
        drag = widgetset.HBox(spacing=10)
        drag.pack_start(widgetutil.align_middle(self.dropoff_small_on))
        drag.pack_start(widgetutil.align_middle(drop_label))
        drag.set_size_request(-1, height)

        return normal, drag

    def set_small(self, small):
        if small != self.small:
            self.small = small
            self.normal, self.drag = self.widgets[small]
            self.set_in_drag(self.in_drag, force=True)

    def set_in_drag(self, in_drag, force=False):
        if force or in_drag != self.in_drag:
            self.in_drag = in_drag
            if in_drag:
                self.alignment.set_child(self.drag)
            else:
                self.alignment.set_child(self.normal)
            self.queue_redraw()

    def choose_file(self, widget):
        app.widgetapp.choose_file()

BUTTON_BACKGROUND = widgetutil.ThreeImageSurface('settings-base')


class SettingsButton(widgetset.CustomButton):

    arrow_on = widgetset.ImageSurface(widgetset.Image(
        image_path('arrow-down-on.png')))
    arrow_off = widgetset.ImageSurface(widgetset.Image(
        image_path('arrow-down-off.png')))

    def __init__(self, name):
        super(SettingsButton, self).__init__()
        if name != 'settings':
            self.name = name.title()
        else:
            self.name = None
        self.selected = False
        if name != 'format':
            self.surface_on = widgetset.ImageSurface(widgetset.Image(
                image_path('%s-icon-on.png' % name)))
            self.surface_off = widgetset.ImageSurface(widgetset.Image(
                image_path('%s-icon-off.png' % name)))
            if self.surface_on.height != self.surface_off.height:
                raise ValueError('invalid surface: height mismatch')
            self.image_padding = self.calc_image_padding(name)
        else:
            self.surface_on = self.surface_off = None

    def calc_image_padding(self, name):
        """Add some padding to the bottom of our image icon.  This can be used
        to fine tune where it gets placed.

        :returns: padding in as a (top, right, bottom, left) tuple
        """

        # NOTE: we vertically center the images, so in order to move it X
        # pickels up, we need X*2 pixels of bottom padding
        if name == 'android':
            return (0, 0, 2, 0)
        elif name in ('apple', 'other'):
            return (0, 0, 4, 0)
        else:
            return (0, 0, 0, 0)

    def textbox(self, layout_manager):
        layout_manager.set_font(SETTINGS_FONTSIZE, family=SETTINGS_FONT)
        return layout_manager.textbox(self.name)

    def size_request(self, layout_manager):
        hbox = self.build_hbox(layout_manager)
        size = hbox.get_size()
        height = max(BUTTON_BACKGROUND.height, size[1])
        return int(size[0]) + 2, int(height) + 2  # padding

    def build_hbox(self, layout_manager):
        hbox = cellpack.HBox(spacing=5)
        if self.selected:
            image = self.surface_on
            arrow = self.arrow_on
            layout_manager.set_text_color(TEXT_ACTIVE)
        else:
            image = self.surface_off
            arrow = self.arrow_off
            layout_manager.set_text_color(TEXT_DISABLED)
        if image:
            padding = cellpack.Padding(image, *self.image_padding)
            hbox.pack(cellpack.Alignment(padding, xscale=0, yscale=0,
                                         yalign=0.5))
        if self.name:
            vbox = cellpack.VBox()
            textbox = self.textbox(layout_manager)
            vbox.pack(textbox)
            vbox.pack_space(1)
            hbox.pack(cellpack.Alignment(vbox, yscale=0, yalign=0.5),
                      expand=True)
        a = cellpack.Alignment(arrow, xscale=0, yscale=0, yalign=0.5)
        hbox.pack(cellpack.Padding(a, left=5, right=12))
        alignment = cellpack.Padding(hbox, left=5)
        return alignment

    def draw(self, context, layout_manager):
        BUTTON_BACKGROUND.draw(context, 1, 1, context.width - 2)
        alignment = self.build_hbox(layout_manager)
        padding = cellpack.Padding(alignment, top=1, right=3, bottom=1, left=3)
        padding.render_layout(context)

    def set_selected(self, selected):
        self.selected = selected
        self.queue_redraw()


class OptionMenuBackground(widgetset.Background):
    def __init__(self):
        widgetset.Background.__init__(self)
        self.surface = widgetutil.ThreeImageSurface('settings-depth')

    def set_child(self, child):
        widgetset.Background.set_child(self, child)
        # re-create the image surface and scale it as it needs to cover
        # the whole of the height of the child
        _, h = child.get_size_request()
        self.surface = widgetutil.ThreeImageSurface('settings-depth', height=h)
        self.invalidate_size_request()

    def size_request(self, layout_manager):
        return -1, self.surface.height

    def draw(self, context, layout_manager):
        child_width = self.child.get_size_request()[0]
        self.surface.draw(context, 0, 0, child_width)


class BottomBackground(widgetset.Background):

    def draw(self, context, layout_manager):
        gradient = widgetset.Gradient(0, 0, 0, context.height)
        gradient.set_start_color(GRADIENT_TOP)
        gradient.set_end_color(GRADIENT_BOTTOM)
        context.rectangle(0, 0, context.width, context.height)
        context.gradient_fill(gradient)


class LabeledNumberEntry(widgetset.HBox):

    def __init__(self, label):
        super(LabeledNumberEntry, self).__init__(spacing=5)
        self.label = widgetset.Label(label, color=TEXT_COLOR)
        self.label.set_size(widgetconst.SIZE_SMALL)
        self.entry = widgetset.NumberEntry()
        self.entry.set_size_request(50, 20)
        self.pack_start(self.label)
        self.pack_start(self.entry)
        self.entry.connect('focus-out', lambda x: self.emit('focus-out'))

    def get_text(self):
        return self.entry.get_text()

    def set_text(self, text):
        self.entry.set_text(text)

    def get_value(self):
        try:
            return int(self.entry.get_text())
        except ValueError:
            return None


class CustomOptions(widgetset.Background):

    background = widgetset.ImageSurface(widgetset.Image(
        image_path('settings-dropdown-bottom-bg.png')))

    def __init__(self):
        super(CustomOptions, self).__init__()
        self.create_signal('setting-changed')
        self.reset()

    def reset(self):
        self.options = {
            'destination': None,
            'custom-size': False,
            'width': None,
            'height': None,
            'custom-aspect': False,
            'aspect-ratio': 4.0/3.0,
            'dont-upsize': True
        }

        self.top = self.create_top()
        self.top.set_size_request(390, 50)
        self.left = self.create_left()
        self.left.set_size_request(212, 70)
        self.right = self.create_right()
        self.right.set_size_request(178, 70)
        vbox = widgetset.VBox()
        vbox.pack_start(self.top)
        hbox = widgetset.HBox()
        hbox.pack_start(self.left)
        hbox.pack_start(self.right)
        vbox.pack_start(hbox)

        self.box = widgetutil.align_left(vbox)

        if self.child:
            self.set_child(self.box)

    def create_top(self):
        hbox = widgetset.HBox(spacing=0)
        path_label = WebStyleButton()
        path_label.set_text('Show output folder')
        path_label.set_font(DEFAULT_FONT, widgetconst.SIZE_SMALL)
        path_label.connect('clicked', self.on_path_label_clicked)
        create_thumbnails = widgetset.Checkbox('Create Thumbnails',
                                               color=TEXT_COLOR)
        create_thumbnails.set_size(widgetconst.SIZE_SMALL)
        create_thumbnails.connect('toggled',
                                  self.on_create_thumbnails_changed)

        hbox.pack_start(widgetutil.align(path_label, xalign=0.5), expand=True)
        hbox.pack_start(widgetutil.align(create_thumbnails, xalign=0.5),
                        expand=True)
        # XXX: disabled until we can figure out how to do this properly.
        # button = widgetset.Button('...')
        # button.connect('clicked', self.on_destination_clicked)
        # reset = widgetset.Button('Reset')
        # reset.connect('clicked', self.on_destination_reset)
        # hbox.pack_start(button)
        # hbox.pack_start(reset)
        return widgetutil.align(hbox, xscale=1.0, yalign=0.5)

    def _get_save_to_path(self):
        if self.options['destination'] is None:
            return get_conversion_directory()
        else:
            return self.options['destination']

    def on_path_label_clicked(self, label):
        save_path = self._get_save_to_path()
        save_path = convert_path_for_subprocess(save_path)
        openfiles.reveal_folder(save_path)

    def create_left(self):
        self.custom_size = widgetset.Checkbox('Custom Size', color=TEXT_COLOR)
        self.custom_size.set_size(widgetconst.SIZE_SMALL)
        self.custom_size.connect('toggled', self.on_custom_size_changed)

        dont_upsize = widgetset.Checkbox('Don\'t Upsize', color=TEXT_COLOR)
        dont_upsize.set_checked(self.options['dont-upsize'])
        dont_upsize.set_size(widgetconst.SIZE_SMALL)
        dont_upsize.connect('toggled', self.on_dont_upsize_changed)

        bottom = widgetset.HBox(spacing=5)
        self.width_widget = LabeledNumberEntry('Width')
        self.width_widget.connect('focus-out', self.on_width_changed)
        self.width_widget.entry.connect('activate',
                                        self.on_width_changed)
        self.width_widget.disable()
        self.height_widget = LabeledNumberEntry('Height')
        self.height_widget.connect('focus-out', self.on_height_changed)
        self.height_widget.entry.connect('activate',
                                         self.on_height_changed)
        self.height_widget.disable()
        bottom.pack_start(self.width_widget)
        bottom.pack_start(self.height_widget)

        hbox = widgetset.HBox(spacing=5)
        hbox.pack_start(self.custom_size)
        hbox.pack_start(dont_upsize)

        vbox = widgetset.VBox(spacing=5)
        vbox.pack_start(widgetutil.align_left(hbox, left_pad=10))
        vbox.pack_start(widgetutil.align_center(bottom))
        return widgetutil.align_middle(vbox)

    def create_right(self):
        aspect = widgetset.Checkbox('Custom Aspect Ratio', color=TEXT_COLOR)
        aspect.set_size(widgetconst.SIZE_SMALL)
        aspect.connect('toggled', self.on_aspect_changed)
        self.aspect_widget = aspect
        self.button_group = widgetset.RadioButtonGroup()
        b1 = widgetset.RadioButton('4:3', self.button_group, color=TEXT_COLOR)
        b2 = widgetset.RadioButton('3:2', self.button_group, color=TEXT_COLOR)
        b3 = widgetset.RadioButton('16:9', self.button_group, color=TEXT_COLOR)
        b1.set_selected()
        b1.set_size(widgetconst.SIZE_SMALL)
        b2.set_size(widgetconst.SIZE_SMALL)
        b3.set_size(widgetconst.SIZE_SMALL)
        self.aspect_map = dict()
        self.aspect_map[b1] = (4, 3)
        self.aspect_map[b2] = (3, 2)
        self.aspect_map[b3] = (16, 9)
        hbox = widgetset.HBox(spacing=5)
        # Because the custom size starts off as disabled, so should aspect
        # ratio as aspect ratio is dependent on a custom size set.
        self.aspect_widget.disable()
        for button in self.button_group.get_buttons():
            button.disable()
            button.set_size(widgetconst.SIZE_SMALL)
            hbox.pack_start(button)
            button.connect('clicked', self.on_aspect_size_changed)

        vbox = widgetset.VBox()
        vbox.pack_start(widgetutil.align_center(aspect))
        vbox.pack_start(widgetutil.align_center(hbox))
        return widgetutil.align_middle(vbox)

    def draw(self, context, layout_manager):
        self.background.draw(context, 0, 0, self.background.width,
                             self.background.height)

    def enable_custom_size(self):
        self.custom_size.enable()

    def disable_custom_size(self):
        self.custom_size.disable()
        self.custom_size.set_checked(False)

    def update_setting(self, setting, value):
        self.options[setting] = value
        if setting in ('width', 'height'):
            if value is not None:
                widget_text = str(value)
            else:
                widget_text = ''
            if setting == 'width':
                self.width_widget.set_text(widget_text)
            elif setting == 'height':
                self.height_widget.set_text(widget_text)

    def do_setting_changed(self, setting, value):
        logging.info('setting-changed: %s -> %s', setting, value)

    def _change_setting(self, setting, value):
        """Handles setting changes in response to widget changes."""

        self.options[setting] = value
        self.emit('setting-changed', setting, value)

    def force_width_to_aspect_ratio(self):
        aspect_ratio = self.options['aspect-ratio']
        width = self.width_widget.get_text()
        height = self.height_widget.get_text()
        if not height:
            return
        new_width = round_even(float(height) * aspect_ratio)
        if new_width != width:
            self.update_setting('width', new_width)
            self.emit('setting-changed', 'width', new_width)

    def force_height_to_aspect_ratio(self):
        aspect_ratio = self.options['aspect-ratio']
        width = self.width_widget.get_text()
        height = self.height_widget.get_text()
        if not width:
            return
        new_height = round_even(float(width) / aspect_ratio)
        if new_height != height:
            self.update_setting('height', new_height)
            self.emit('setting-changed', 'height', new_height)

    def show(self):
        self.set_child(self.box)
        self.set_size_request(self.background.width,
                              self.background.height + 28)
        self.queue_redraw()

    def hide(self):
        self.remove()
        self.set_size_request(0, 0)
        self.queue_redraw()

    def toggle(self):
        if self.child:
            self.hide()
        else:
            self.show()

    # signal handlers
    def on_destination_clicked(self, widget):
        dialog = widgetset.DirectorySelectDialog('Destination Directory')
        r = dialog.run()
        if r == 0:  # picked a directory
            self._change_setting('destination', directory)

    def on_destination_reset(self, widget):
        self._change_setting('destination', None)

    def on_dont_upsize_changed(self, widget):
        self._change_setting('dont-upsize', widget.get_checked())

    def on_custom_size_changed(self, widget):
        self._change_setting('custom-size', widget.get_checked())
        if widget.get_checked():
            self.width_widget.enable()
            self.height_widget.enable()
            self.aspect_widget.enable()
            self.on_aspect_changed(self.aspect_widget)
        else:
            self.width_widget.disable()
            self.height_widget.disable()
            self.aspect_widget.disable()
            self.on_aspect_changed(self.aspect_widget)
            for button in self.button_group.get_buttons():
                button.disable()

    def on_create_thumbnails_changed(self, widget):
        self._change_setting('create-thumbnails', widget.get_checked())

    def on_width_changed(self, widget):
        self._change_setting('width', self.width_widget.get_value())
        if self.options['custom-aspect']:
            self.force_height_to_aspect_ratio()

    def on_height_changed(self, widget):
        self._change_setting('height', self.height_widget.get_value())
        if self.options['custom-aspect']:
            self.force_width_to_aspect_ratio()

    def on_aspect_changed(self, widget):
        self._change_setting('custom-aspect', widget.get_checked())
        if widget.get_checked():
            self.force_height_to_aspect_ratio()
            for button in self.button_group.get_buttons():
                button.enable()
        else:
            for button in self.button_group.get_buttons():
                button.disable()

    def on_aspect_size_changed(self, widget):
        if self.options['custom-aspect']:
            width_ratio, height_ratio = [float(v) for v in
                                         self.aspect_map[widget]]
            ratio = width_ratio / height_ratio
            self._change_setting('aspect-ratio', ratio)
            self.force_height_to_aspect_ratio()

EMPTY_CONVERTER = ConverterInfo("")


class ConversionModel(widgetset.TableModel):
    def __init__(self):
        super(ConversionModel, self).__init__(
            'text',  # filename
            'numeric',  # output_size
            'text',  # converter
            'text',  # status
            'numeric',  # duration
            'numeric',  # progress
            'numeric',  # eta,
            'object',  # image
            'object',  # the actual conversion
            )
        self.conversion_to_iter = {}
        self.thumbnail_to_image = {None: widgetset.Image(
            image_path('audio.png'))}

    def conversions(self):
        return iter(self.conversion_to_iter)

    def all_conversions_done(self):
        has_conversions = any(self.conversions())
        all_done = ((set(c.status for c in self.conversions()) -
                     set(['canceled', 'finished', 'failed'])) == set())
        return all_done and has_conversions

    def get_image(self, path):
        if path not in self.thumbnail_to_image:
            try:
                image = widgetset.Image(path)
            except ValueError:
                image = self.thumbnail_to_image[None]
            self.thumbnail_to_image[path] = image
        return self.thumbnail_to_image[path]

    def update_conversion(self, conversion):
        try:
            output_size = os.stat(conversion.output).st_size
        except OSError:
            output_size = 0

        def complete():
            # needs to do it on the update_conversion() from app object
            # which calls model_changed() and redraws for us
            app.widgetapp.update_conversion(conversion)

        values = (conversion.video.filename,
                  output_size,
                  conversion.converter.name,
                  conversion.status,
                  conversion.duration or 0,
                  conversion.progress or 0,
                  conversion.eta or 0,
                  self.get_image(conversion.video.get_thumbnail(complete,
                                                                90, 70)),
                  conversion)
        iter_ = self.conversion_to_iter.get(conversion)
        if iter_ is None:
            self.conversion_to_iter[conversion] = self.append(*values)
        else:
            self.update(iter_, *values)

    def remove(self, iter_):
        conversion = self[iter_][-1]
        del self.conversion_to_iter[conversion]

        # XXX If we add/remove too quickly, we could still be processing
        # thumbnails and this may return null, and the self.thumbnail_to_image
        # dictionary may get out of sync
        def complete(path):
            logging.info('calling completion handler for get_thumbnail on '
                         'removal')

        thumbnail_path = conversion.video.get_thumbnail(complete, 90, 70)
        if thumbnail_path:
            del self.thumbnail_to_image[thumbnail_path]
        return super(ConversionModel, self).remove(iter_)


class IconWithText(cellpack.HBox):

    def __init__(self, icon, textbox):
        super(IconWithText, self).__init__(spacing=5)
        self.pack(cellpack.Alignment(icon, yalign=0.5, xscale=0, yscale=0))
        self.pack(textbox)


class ConversionCellRenderer(widgetset.CustomCellRenderer):

    IGNORE_PADDING = True

    clear = widgetset.ImageSurface(widgetset.Image(
        image_path("clear-icon.png")))
    converted_to = widgetset.ImageSurface(widgetset.Image(
        image_path("converted_to-icon.png")))
    queued = widgetset.ImageSurface(widgetset.Image(
        image_path("queued-icon.png")))
    showfile = widgetset.ImageSurface(widgetset.Image(
        image_path("showfile-icon.png")))
    show_ffmpeg = widgetset.ImageSurface(widgetset.Image(
        image_path("error-icon.png")))
    progressbar_base = widgetset.ImageSurface(widgetset.Image(
        image_path("progressbar-base.png")))
    delete_on = widgetset.ImageSurface(widgetset.Image(
        image_path("item-delete-button-on.png")))
    delete_off = widgetset.ImageSurface(widgetset.Image(
        image_path("item-delete-button-off.png")))
    error = widgetset.ImageSurface(widgetset.Image(
        image_path("item-error.png")))
    completed = widgetset.ImageSurface(widgetset.Image(
        image_path("item-completed.png")))

    def __init__(self):
        super(ConversionCellRenderer, self).__init__()
        self.alignment = None

    def get_size(self, style, layout_manager):
        return TABLE_WIDTH, TABLE_HEIGHT

    def render(self, context, layout_manager, selected, hotspot, hover):
        left_right = cellpack.HBox()
        top_bottom = cellpack.VBox()
        left_right.pack(self.layout_left(layout_manager))
        left_right.pack(top_bottom, expand=True)
        layout_manager.set_text_color(TEXT_COLOR)
        layout_manager.set_font(ITEM_TITLE_FONTSIZE, bold=True,
                                family=ITEM_TITLE_FONT)
        title = layout_manager.textbox(os.path.basename(self.input))
        title.set_wrap_style('truncated-char')
        alignment = cellpack.Padding(cellpack.TruncatedTextLine(title),
                                     top=25)
        top_bottom.pack(alignment)
        layout_manager.set_font(ITEM_ICONS_FONTSIZE, family=ITEM_ICONS_FONT)

        bottom = self.layout_bottom(layout_manager, hotspot)
        if bottom is not None:
            top_bottom.pack(bottom)
        left_right.pack(self.layout_right(layout_manager, hotspot))

        alignment = cellpack.Alignment(left_right, yscale=0, yalign=0.5)
        self.alignment = alignment

        background = cellpack.Background(alignment)
        background.set_callback(self.draw_background)
        background.render_layout(context)

    @staticmethod
    def draw_background(context, x, y, width, height):
        # draw main background
        gradient = widgetset.Gradient(x, y, x, height)
        gradient.set_start_color(GRADIENT_TOP)
        gradient.set_end_color(GRADIENT_BOTTOM)
        context.rectangle(x, y, width, height)
        context.gradient_fill(gradient)
        # draw bottom line
        context.set_line_width(1)
        context.set_color((0, 0, 0))
        context.move_to(0, height-0.5)
        context.line_to(context.width, height-0.5)
        context.stroke()

    def draw_progressbar(self, context, x, y, _, height, width):
        # We're only drawing a certain amount of width, not however much we're
        # allocated.  So, we ignore the passed-in width and just use what we
        # set in layout_bottom.
        widgetutil.circular_rect(context, x, y, width-1, height-1)
        context.set_color((1, 1, 1))
        context.fill()

    def layout_left(self, layout_manager):
        surface = widgetset.ImageSurface(self.thumbnail)
        return cellpack.Padding(surface, 10, 10, 10, 10)

    def layout_right(self, layout_manager, hotspot):
        alignment_kwargs = dict(
            xalign=0.5,
            xscale=0,
            yalign=0.5,
            yscale=0,
            min_width=80)
        if self.status == 'finished':
            return cellpack.Alignment(self.completed, **alignment_kwargs)
        elif self.status in ('canceled', 'failed'):
            return cellpack.Alignment(self.error, **alignment_kwargs)
        else:
            if hotspot == 'cancel':
                image = self.delete_on
            else:
                image = self.delete_off
            return cellpack.Alignment(cellpack.Hotspot('cancel',
                                                       image),
                                      **alignment_kwargs)

    def layout_bottom(self, layout_manager, hotspot):
        layout_manager.set_text_color(TEXT_COLOR)
        if self.status in ('converting', 'staging'):
            box = cellpack.HBox(spacing=5)
            stack = cellpack.Stack()
            stack.pack(cellpack.Alignment(self.progressbar_base,
                                          yalign=0.5,
                                          xscale=0, yscale=0))
            percent = self.progress / self.duration
            width = max(int(percent * self.progressbar_base.width),
                        5)
            stack.pack(cellpack.DrawingArea(
                width, self.progressbar_base.height,
                self.draw_progressbar, width))
            box.pack(cellpack.Alignment(stack,
                                        yalign=0.5,
                                        xscale=0, yscale=0))
            textbox = layout_manager.textbox("%d%%" % (
                100 * percent))
            box.pack(textbox)
            return box
        elif self.status == 'initialized':  # queued
            vbox = cellpack.VBox()
            vbox.pack_space(2)
            vbox.pack(IconWithText(self.queued,
                                   layout_manager.textbox("Queued")))
            return vbox
        elif self.status in ('finished', 'failed', 'canceled'):
            vbox = cellpack.VBox(spacing=5)
            vbox.pack_space(4)
            top = cellpack.HBox(spacing=5)
            if self.status == 'finished':
                if hotspot == 'show-file':
                    layout_manager.set_text_color(TEXT_CLICKED)
                top.pack(cellpack.Hotspot('show-file', IconWithText(
                    self.showfile,
                    layout_manager.textbox('Show File',
                                           underline=True))))
            elif self.status in ('failed', 'canceled'):
                color = TEXT_CLICKED if hotspot == 'show-log' else TEXT_COLOR
                layout_manager.set_text_color(color)
                # XXX Missing grey error icon
                if self.status == 'failed':
                    text = 'Error - Show FFmpeg Output'
                else:
                    text = 'Canceled - Show FFmpeg Output'
                top.pack(cellpack.Hotspot('show-log', IconWithText(
                    self.show_ffmpeg,
                    layout_manager.textbox(text, underline=True))))
            color = TEXT_CLICKED if hotspot == 'clear' else TEXT_COLOR
            layout_manager.set_text_color(color)
            top.pack(cellpack.Hotspot('clear', IconWithText(
                self.showfile,
                layout_manager.textbox('Clear', underline=True))))
            vbox.pack(top)
            if self.status == 'finished':
                layout_manager.set_text_color(TEXT_INFO)
                vbox.pack(IconWithText(
                    self.converted_to,
                    layout_manager.textbox("Converted to %s" % (
                        size_string(self.output_size)))))
            return vbox

    def hotspot_test(self, style, layout_manager, x, y, width, height):
        if self.alignment is None:
            return
        hotspot_info = self.alignment.find_hotspot(x, y, width, height)
        if hotspot_info:
            return hotspot_info[0]


class ConvertButton(widgetset.CustomButton):
    off = widgetset.ImageSurface(widgetset.Image(
        image_path("convert-button-off.png")))
    clear = widgetset.ImageSurface(widgetset.Image(
        image_path("convert-button-off.png")))
    on = widgetset.ImageSurface(widgetset.Image(
        image_path("convert-button-on.png")))
    stop = widgetset.ImageSurface(widgetset.Image(
        image_path("convert-button-stop.png")))

    def __init__(self):
        super(ConvertButton, self).__init__()
        self.hidden = False
        self.set_off()

    def set_on(self):
        self.label = 'Convert to %s' % app.widgetapp.current_converter.name
        self.image = self.on
        self.set_cursor(widgetconst.CURSOR_POINTING_HAND)
        self.queue_redraw()

    def set_clear(self):
        self.label = 'Clear and Start Over'
        self.image = self.clear
        self.set_cursor(widgetconst.CURSOR_POINTING_HAND)
        self.queue_redraw()

    def set_off(self):
        self.label = 'Convert Now'
        self.image = self.off
        self.set_cursor(widgetconst.CURSOR_NORMAL)
        self.queue_redraw()

    def set_stop(self):
        self.label = 'Stop All Conversions'
        self.image = self.stop
        self.set_cursor(widgetconst.CURSOR_POINTING_HAND)
        self.queue_redraw()

    def hide(self):
        self.hidden = True
        self.invalidate_size_request()
        self.queue_redraw()

    def show(self):
        self.hidden = False
        self.invalidate_size_request()
        self.queue_redraw()

    def size_request(self, layout_manager):
        if self.hidden:
            return 0, 0
        return self.off.width, self.off.height

    def draw(self, context, layout_manager):
        if self.hidden:
            return
        self.image.draw(context, 0, 0, self.image.width, self.image.height)
        layout_manager.set_font(CONVERT_NOW_FONTSIZE, family=CONVERT_NOW_FONT)
        if self.image == self.off:
            layout_manager.set_text_shadow(widgetutil.Shadow(TEXT_SHADOW,
                                                             0.5, (-1, -1), 0))
            layout_manager.set_text_color(TEXT_DISABLED)
        else:
            layout_manager.set_text_shadow(widgetutil.Shadow(TEXT_SHADOW,
                                                             0.5, (1, 1), 0))
            layout_manager.set_text_color(TEXT_ACTIVE)
        textbox = layout_manager.textbox(self.label)
        alignment = cellpack.Alignment(textbox, xalign=0.5, xscale=0.0,
                                       yalign=0.5, yscale=0)
        alignment.render_layout(context)


# XXX do we want to export this for general purpose use?
class TextDialog(widgetset.Dialog):
    def __init__(self, title, description, window):
        widgetset.Dialog.__init__(self, title, description)
        self.set_transient_for(window)
        self.add_button('OK')
        self.textbox = widgetset.MultilineTextEntry()
        self.textbox.set_editable(False)
        scroller = widgetset.Scroller(False, True)
        scroller.set_has_borders(True)
        scroller.add(self.textbox)
        scroller.set_size_request(400, 500)
        self.set_extra_widget(scroller)

    def set_text(self, text):
        self.textbox.set_text(text)


class Application(lvc.Application):
    def __init__(self, simultaneous=None):
        lvc.Application.__init__(self, simultaneous)
        self.create_signal('window-shown')
        self.sent_window_shown = False

    def startup(self):
        if self.started:
            return

        self.current_converter = EMPTY_CONVERTER

        lvc.Application.startup(self)

        self.menu_manager = menus.MenuManager()
        self.menu_manager.setup_menubar(self.menubar)

        self.window = widgetset.Window("Libre Video Converter")
        self.window.connect('on-shown', self.on_window_shown)
        self.window.connect('will-close', self.destroy)

        # # table on top
        self.model = ConversionModel()
        self.table = widgetset.TableView(self.model)
        self.table.draws_selection = False
        self.table.set_row_spacing(0)
        self.table.enable_album_view_focus_hack()
        self.table.set_fixed_height(True)
        self.table.set_grid_lines(False, False)
        self.table.set_show_headers(False)

        c = widgetset.TableColumn("Data", ConversionCellRenderer(),
                                  **dict((n, v) for (v, n) in enumerate((
                                      'input', 'output_size', 'converter',
                                      'status', 'duration', 'progress',
                                      'eta', 'thumbnail', 'conversion'))))
        c.set_min_width(TABLE_WIDTH)
        self.table.add_column(c)
        self.table.connect('hotspot-clicked', self.hotspot_clicked)

        # bottom buttons
        converter_types = ('apple', 'android', 'other', 'format')
        converters = {}
        for c in self.converter_manager.list_converters():
            media_type = c.media_type
            if media_type not in converter_types:
                media_type = 'others'
            brand = self.converter_manager.converter_to_brand(c)
            # None = top level.  Otherwise tack on the brand name.
            if brand is None:
                converters.setdefault(media_type, set()).add(c)
            else:
                converters.setdefault(media_type, set()).add(brand)

        self.menus = []

        self.button_bar = widgetset.HBox()
        buttons = widgetset.HBox()

        for type_ in converter_types:
            options = []
            more_devices = None
            for c in converters[type_]:
                if isinstance(c, str):
                    rconverters = self.converter_manager.brand_to_converters(c)
                    values = []
                    for r in rconverters:
                        values.append((r.name, r.identifier))
                    # yuck
                    if c == 'More Devices':
                        more_devices = (c, values)
                    else:
                        options.append((c, values))
                else:
                    options.append((c.name, c.identifier))
            # Don't sort if formats..
            self.sort_converter_menu(type_, options)
            if more_devices:
                options.append(more_devices)
            menu = SettingsButton(type_)
            menu.connect('clicked', self.show_options_menu, options)
            self.menus.append(menu)
            buttons.pack_start(menu)
        omb = OptionMenuBackground()
        omb.set_child(widgetutil.pad(buttons, top=2, bottom=2,
                                     left=2, right=2))
        self.button_bar.pack_start(omb)

        self.settings_button = SettingsButton('settings')
        omb = OptionMenuBackground()
        omb.set_child(widgetutil.pad(self.settings_button, top=2,
                                     bottom=2, left=2, right=2))
        self.button_bar.pack_end(omb)

        self.drop_target = FileDropTarget()
        self.drop_target.set_size_request(-1, 70)

        # # finish up
        vbox = widgetset.VBox()
        self.vbox = vbox

        # add menubars, if we're not on windows
        if sys.platform != 'win32':
            attach_menubar()

        self.scroller = widgetset.Scroller(False, True)
        self.scroller.set_size_request(0, 0)
        self.scroller.set_background_color(DRAG_AREA)
        self.scroller.add(self.table)
        vbox.pack_start(self.scroller)
        vbox.pack_start(self.drop_target, expand=True)

        bottom = BottomBackground()
        bottom_box = widgetset.VBox()
        self.convert_label = CustomLabel('Convert to')
        self.convert_label.set_font(CONVERT_TO_FONT, CONVERT_TO_FONTSIZE)
        self.convert_label.set_color(TEXT_COLOR)
        bottom_box.pack_start(widgetutil.align_left(self.convert_label,
                                                    top_pad=10,
                                                    bottom_pad=10))
        bottom_box.pack_start(self.button_bar)

        self.options = CustomOptions()
        self.options.connect('setting-changed', self.on_setting_changed)
        self.settings_button.connect('clicked', self.on_settings_toggle)
        bottom_box.pack_start(widgetutil.align_right(self.options,
                                                     right_pad=5))

        self.convert_button = ConvertButton()
        self.convert_button.connect('clicked', self.convert)

        bottom_box.pack_start(widgetutil.align(self.convert_button,
                                               xalign=0.5, yalign=0.5,
                                               top_pad=50, bottom_pad=50))
        bottom.set_child(widgetutil.pad(bottom_box, left=20, right=20))
        vbox.pack_start(bottom)
        self.window.set_content_widget(vbox)

        idle_add(self.conversion_manager.check_notifications, 1)

        self.window.connect('file-drag-motion', self.drag_motion)
        self.window.connect('file-drag-received', self.drag_data_received)
        self.window.connect('file-drag-leave', self.drag_finished)
        self.window.accept_file_drag(True)

        self.window.center()
        self.window.show()
        self.update_table_size()

    def sort_converter_menu(self, menu_type, options):
        """Sort a list of converter options for the menus

        :param menu_type: type of the menu
        :param options: list of (name, menu) tuples, where menu is either a
        ConverterInfo or list of ConverterInfos.
        """
        if menu_type == 'format':
            order = ['Audio', 'Video', 'Ingest Formats', 'Same Format']
            options.sort(key=lambda (name, menu): order.index(name))
        else:
            options.sort()

    def drag_finished(self, widget):
        self.drop_target.set_in_drag(False)

    def drag_motion(self, widget):
        self.drop_target.set_in_drag(True)

    def drag_data_received(self, widget, values):
        for uri in values:
            parsed = urlparse.urlparse(uri)
            if parsed.scheme == 'file':
                pathname = urllib.url2pathname(parsed.path)
                self.file_activated(widget, pathname)

    def on_window_shown(self, window):
        # only emit window-shown once, even if our window gets shown, hidden,
        # and shown again
        if not self.sent_window_shown:
            self.emit("window-shown")
            self.sent_window_shown = True

    def destroy(self, widget):
        for conversion in self.conversion_manager.in_progress.copy():
            conversion.stop()
        mainloop_stop()

    def run(self):
        mainloop_start()

    def choose_file(self):
        dialog = widgetset.FileOpenDialog('Choose Files...')
        dialog.set_select_multiple(True)
        if dialog.run() == 0:  # success
            for filename in dialog.get_filenames():
                self.file_activated(None, filename)
        dialog.destroy()

    def about(self):
        dialog = widgetset.AboutDialog()
        dialog.set_transient_for(self.window)
        try:
            dialog.run()
        finally:
            dialog.destroy()

    def quit(self):
        self.window.close()

    def _generate_suboptions_menu(self, widget, options):
        submenu = []
        for option, id_ in options:
            def callback(x, i):
                return self.on_select_converter(widget, options[i][1])
            # callback = lambda x, i: self.on_select_converter(widget,
            #                                                  options[i][1])
            value = (option, callback)
            submenu.append(value)
        return submenu

    def show_options_menu(self, widget, options):
        optionlist = []
        identifiers = dict()
        for option, submenu in options:
            if isinstance(submenu, list):
                callback = self._generate_suboptions_menu(widget, submenu)
            else:
                def callback(x, i):
                    return self.on_select_converter(widget, options[i][1])
                # callback = lambda x, i: self.on_select_converter(widget,
                #                                                  options[i][1])
            value = (option, callback)
            optionlist.append(value)
        menu = widgetset.ContextMenu(optionlist)
        menu.popup()

    def update_convert_button(self):
        can_cancel = False
        can_start = False
        has_conversions = any(self.model.conversions())
        all_done = self.model.all_conversions_done()
        for c in self.model.conversions():
            if c.status == 'converting':
                can_cancel = True
                break
            elif c.status == 'initialized':
                can_start = True
        # if there are no conversions ... these can't be set
        if not has_conversions:
            for m in self.menus:
                m.set_selected(False)
            self.settings_button.set_selected(False)
        self.convert_label.set_color(TEXT_DISABLED)
        # Set the colors - all are enabled if all conversions complete, or
        # if we have conversions conversions but the converter has not yet
        # been set.
        # the converter has not been set.
        if ((self.current_converter is EMPTY_CONVERTER and has_conversions) or
                all_done):
            for m in self.menus:
                m.set_selected(True)
            self.settings_button.set_selected(True)
        if self.current_converter is EMPTY_CONVERTER:
            self.convert_label.set_text('Convert to')
        elif can_cancel:
            target = self.current_converter.name
            self.convert_label.set_text('Converting to %s' % target)
        elif can_start:
            target = self.current_converter.name
            self.convert_label.set_text('Will convert to %s' % target)
            self.convert_label.set_color(TEXT_ACTIVE)
        if all_done:
            self.convert_button.set_clear()
        elif (self.current_converter is EMPTY_CONVERTER or not
              (can_cancel or can_start)):
            self.convert_button.set_off()
        elif (self.current_converter is not EMPTY_CONVERTER and
              self.options.options['custom-size'] and
              (not self.options.options['width'] or
               not self.options.options['height'])):
            self.convert_button.set_off()
        else:
            self.convert_button.set_on()
        if can_cancel:
            self.convert_button.set_stop()
            self.button_bar.disable()
        else:
            if has_conversions:
                self.button_bar.enable()
            else:
                self.button_bar.disable()

    def file_activated(self, widget, filename):
        filename = os.path.realpath(filename)
        for c in self.model.conversions():
            if c.video.filename == filename:
                logger.info('ignoring duplicate: %r', filename)
                return
        # XXX disabled - don't want to allow individualized file outputs
        # since the workflow isn't entirely clear for now.
        # if self.options.options['destination'] is None:
        #     try:
        #         tempfile.TemporaryFile(dir=os.path.dirname(filename))
        #     except EnvironmentError:
        #         # can't write to the destination directory; ask for a new one
        #         self.options.on_destination_clicked(None)
        try:
            vf = VideoFile(filename)
        except ValueError:
            logging.info('invalid file %r, cannot parse', filename,
                         exc_info=True)
            return
        c = self.conversion_manager.get_conversion(
            vf,
            self.current_converter,
            output_dir=self.options.options['destination'])
        c.listen(self.update_conversion)
        if self.conversion_manager.running:
            # start running automatically if a conversion is already in
            # progress
            self.conversion_manager.run_conversion(c)
        self.update_conversion(c)
        self.update_table_size()

    def on_select_converter(self, widget, identifier):
        self.current_converter = self.converter_manager.get_by_id(identifier)
        self.options.reset()

        self.converter_changed(widget)

    def converter_changed(self, widget):
        if hasattr(self, '_doing_conversion_change'):
            return
        self._doing_conversion_change = True

        # If all conversions are done, then change the status of them back
        # to 'initialized'.
        #
        # XXX TODO: what happens if the state is 'failed'?  Should we reset?
        all_done = self.model.all_conversions_done()
        if all_done:
            for c in self.model.conversions():
                c.status = 'initialized'

        if self.current_converter is not EMPTY_CONVERTER:
            self.convert_label.set_text(
                'Will convert to %s' % self.current_converter.name)
        else:
            self.convert_label.set_text('Convert to')

        if not self.current_converter.audio_only:
            self.options.enable_custom_size()
            self.options.update_setting('width',
                                        self.current_converter.width)
            self.options.update_setting('height',
                                        self.current_converter.height)
        else:
            self.options.disable_custom_size()

        for c in self.model.conversions():
            if c.status == 'initialized':
                c.set_converter(self.current_converter)
                self.model.update_conversion(c)

        # We likely either reset the status or we've changed the conversion
        # output so let's just reload the table model.
        self.table.model_changed()

        self.update_convert_button()

        widget.set_selected(True)
        for menu in self.menus:
            if menu is not widget:
                menu.set_selected(False)

        del self._doing_conversion_change

    def convert(self, widget):
        self.convert_button.disable()
        if not self.conversion_manager.running:
            if self.current_converter is not EMPTY_CONVERTER:
                valid_resolution = True
                if (self.options.options['custom-size'] and
                        not (self.options.options['width'] and
                             self.options.options['height'])):
                            valid_resolution = False
                if valid_resolution:
                    for conversion in self.model.conversions():
                        if conversion.status == 'initialized':
                            self.conversion_manager.run_conversion(conversion)
                self.button_bar.disable()
                # all done: no conversion job should be running at this point
                all_done = self.model.all_conversions_done()
                if all_done:
                    # take stuff off one by one from the list
                    # until we have none!
                    # might not be very efficient.
                    iter_ = self.model.first_iter()
                    while iter_ is not None:
                        conversion = self.model[iter_][-1]
                        if conversion.status in ('finished',
                                                 'failed',
                                                 'canceled',
                                                 'initialized'):
                            try:
                                self.conversion_manager.remove(conversion)
                            except ValueError:
                                pass
                        iter_ = self.model.remove(iter_)
                    self.update_table_size()
        else:
            for conversion in self.model.conversions():
                conversion.stop()
                self.update_conversion(conversion)
            self.conversion_manager.running = False
        self.update_convert_button()
        self.convert_button.enable()

    def update_conversion(self, conversion):
        self.model.update_conversion(conversion)
        self.update_table_size()

    def update_table_size(self):
        conversions = len(self.model)
        total_height = 380
        if not conversions:
            self.scroller.set_size_request(-1, 0)
            self.drop_target.set_small(False)
            self.drop_target.set_size_request(-1, total_height)
        else:
            height = min(TABLE_HEIGHT * conversions, 320)
            self.scroller.set_size_request(-1, height)
            self.drop_target.set_small(True)
            self.drop_target.set_size_request(-1, total_height - height)
        self.update_convert_button()
        self.table.model_changed()

    def hotspot_clicked(self, widget, name, iter_):
        conversion = self.model[iter_][-1]
        if name == 'show-file':
            reveal_file(conversion.output)
        elif name == 'clear':
            self.model.remove(iter_)
            self.update_table_size()
        elif name == 'show-log':
            lines = ''.join(conversion.lines)
            d = TextDialog('Log', '', self.window)
            d.set_text(lines)
            try:
                d.run()
            finally:
                d.destroy()
        elif name == 'cancel':
            if conversion.status == 'initialized':
                self.model.remove(iter_)
                try:
                    self.conversion_manager.remove(conversion)
                except ValueError:
                    pass
                self.update_table_size()
            else:
                conversion.stop()
                self.update_conversion(conversion)

    def on_settings_toggle(self, widget):
        if not self.options.child:
            # hidden, going to show
            self.convert_button.hide()
        self.options.toggle()
        if not self.options.child:
            # was shown, not hidden
            self.convert_button.show()

    def on_setting_changed(self, widget, setting, value):
        if setting == 'destination':
            for c in self.model.conversions():
                if c.status == 'initialized':
                    if value is None:
                        c.output_dir = os.path.dirname(c.video.filename)
                    else:
                        c.output_dir = value
                    # update final path
                    c.set_converter(self.current_converter)
            return
        elif setting == 'dont-upsize':
            setattr(self.current_converter, 'dont_upsize', value)
            return

        if (self.current_converter.identifier != 'custom' and
                setting != 'create-thumbnails'):
            if hasattr(self.current_converter, 'simple'):
                self.current_converter = self.current_converter.simple(
                    self.current_converter.name)
            else:
                if self.current_converter is EMPTY_CONVERTER:
                    self.current_converter = copy.copy(
                        self.converter_manager.get_by_id('sameformat'))
                else:
                    self.current_converter = copy.copy(self.current_converter)
            # If the current converter name is resize only, then we don't
            # want to call it a custom conversion.
            if self.current_converter.identifier != 'sameformat':
                self.current_converter.name = 'Custom'
            self.current_converter.width = self.options.options['width']
            self.current_converter.height = self.options.options['height']
            self.converter_changed(self.menus[-1])  # formats menu
        if setting in ('width', 'height'):
            setattr(self.current_converter, setting, value)
        elif setting == 'custom-size':
            if not value:
                self.current_converter.old_size = (
                    self.current_converter.width,
                    self.current_converter.height)
                self.current_converter.width = None
                self.current_converter.height = None
            elif hasattr(self.current_converter, 'old_size'):
                old_size = self.current_converter.old_size
                (self.current_converter.width,
                 self.current_converter.height) = old_size
        elif setting == 'create-thumbnails':
            self.conversion_manager.create_thumbnails = bool(value)

if __name__ == "__main__":
    sys.dont_write_bytecode = True
    app.widgetapp = Application()
    initialize(app.widgetapp)