File: miscdialogs.py

package info (click to toggle)
treeline 3.1.5-1.1
  • links: PTS
  • area: main
  • in suites: trixie
  • size: 6,508 kB
  • sloc: python: 20,489; javascript: 998; makefile: 54
file content (1978 lines) | stat: -rw-r--r-- 78,207 bytes parent folder | download | duplicates (3)
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
#!/usr/bin/env python3

#******************************************************************************
# miscdialogs.py, provides classes for various control dialogs
#
# TreeLine, an information storage program
# Copyright (C) 2020, Douglas W. Bell
#
# This is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License, either Version 2 or any later
# version.  This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY.  See the included LICENSE file for details.
#******************************************************************************

import enum
import re
import sys
import operator
import collections
import datetime
import platform
import traceback
from PyQt5.QtCore import Qt, pyqtSignal, PYQT_VERSION_STR, qVersion
from PyQt5.QtGui import QFont, QKeySequence, QTextDocument, QTextOption
from PyQt5.QtWidgets import (QAbstractItemView, QApplication, QButtonGroup,
                             QCheckBox, QComboBox, QDialog, QGridLayout,
                             QGroupBox, QHBoxLayout, QLabel, QLineEdit,
                             QListWidget, QListWidgetItem, QMenu, QMessageBox,
                             QPlainTextEdit, QPushButton, QRadioButton,
                             QScrollArea, QSpinBox, QTabWidget, QTextEdit,
                             QTreeWidget, QTreeWidgetItem, QVBoxLayout,
                             QWidget)
import options
import printdialogs
import undo
import globalref
try:
    from __main__ import __version__
except ImportError:
    __version__ = ''


class RadioChoiceDialog(QDialog):
    """Dialog for choosing between a list of text items (radio buttons).

    Dialog title, group heading, button text and return text can be set.
    """
    def __init__(self, title, heading, choiceList, parent=None):
        """Create the radio choice dialog.

        Arguments:
            title -- the window title
            heading -- the groupbox text
            choiceList -- tuples of button text and return values
            parent -- the parent window
        """
        super().__init__(parent)
        self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint |
                            Qt.WindowCloseButtonHint)
        self.setWindowTitle(title)
        topLayout = QVBoxLayout(self)
        self.setLayout(topLayout)

        groupBox = QGroupBox(heading)
        topLayout.addWidget(groupBox)
        groupLayout = QVBoxLayout(groupBox)
        self.buttonGroup = QButtonGroup(self)
        for text, value in choiceList:
            if value != None:
                button = QRadioButton(text)
                button.returnValue = value
                groupLayout.addWidget(button)
                self.buttonGroup.addButton(button)
            else:  # add heading if no return value
                label = QLabel('<b>{0}:</b>'.format(text))
                groupLayout.addWidget(label)
        self.buttonGroup.buttons()[0].setChecked(True)

        ctrlLayout = QHBoxLayout()
        topLayout.addLayout(ctrlLayout)
        ctrlLayout.addStretch(0)
        okButton = QPushButton(_('&OK'))
        ctrlLayout.addWidget(okButton)
        okButton.clicked.connect(self.accept)
        cancelButton = QPushButton(_('&Cancel'))
        ctrlLayout.addWidget(cancelButton)
        cancelButton.clicked.connect(self.reject)
        groupBox.setFocus()

    def addLabelBox(self, heading, text):
        """Add a group box with text above the radio button group.

        Arguments:
            heading -- the groupbox text
            text - the label text
        """
        labelBox = QGroupBox(heading)
        self.layout().insertWidget(0, labelBox)
        labelLayout =  QVBoxLayout(labelBox)
        label = QLabel(text)
        labelLayout.addWidget(label)

    def selectedButton(self):
        """Return the value of the selected button.
        """
        return self.buttonGroup.checkedButton().returnValue


class FieldSelectDialog(QDialog):
    """Dialog for selecting a sequence from a list of field names.
    """
    def __init__(self, title, heading, fieldList, parent=None):
        """Create the field select dialog.

        Arguments:
            title -- the window title
            heading -- the groupbox text
            fieldList -- the list of field names to select
            parent -- the parent window
        """
        super().__init__(parent)
        self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint |
                            Qt.WindowCloseButtonHint)
        self.setWindowTitle(title)
        self.selectedFields = []
        topLayout = QVBoxLayout(self)
        self.setLayout(topLayout)
        groupBox = QGroupBox(heading)
        topLayout.addWidget(groupBox)
        groupLayout = QVBoxLayout(groupBox)

        self.listView = QTreeWidget()
        groupLayout.addWidget(self.listView)
        self.listView.setHeaderLabels(['#', _('Fields')])
        self.listView.setRootIsDecorated(False)
        self.listView.setSortingEnabled(False)
        self.listView.setSelectionMode(QAbstractItemView.MultiSelection)
        for field in fieldList:
            QTreeWidgetItem(self.listView, ['', field])
        self.listView.resizeColumnToContents(0)
        self.listView.resizeColumnToContents(1)
        self.listView.itemSelectionChanged.connect(self.updateSelectedFields)

        ctrlLayout = QHBoxLayout()
        topLayout.addLayout(ctrlLayout)
        ctrlLayout.addStretch(0)
        self.okButton = QPushButton(_('&OK'))
        ctrlLayout.addWidget(self.okButton)
        self.okButton.clicked.connect(self.accept)
        self.okButton.setEnabled(False)
        cancelButton = QPushButton(_('&Cancel'))
        ctrlLayout.addWidget(cancelButton)
        cancelButton.clicked.connect(self.reject)
        self.listView.setFocus()

    def updateSelectedFields(self):
        """Update the TreeView and the list of selected fields.
        """
        itemList = [self.listView.topLevelItem(i) for i in
                    range(self.listView.topLevelItemCount())]
        for item in itemList:
            if item.isSelected():
                if item.text(1) not in self.selectedFields:
                    self.selectedFields.append(item.text(1))
            elif item.text(1) in self.selectedFields:
                self.selectedFields.remove(item.text(1))
        for item in itemList:
            if item.isSelected():
                item.setText(0, str(self.selectedFields.index(item.text(1))
                                    + 1))
            else:
                item.setText(0, '')
        self.okButton.setEnabled(len(self.selectedFields))


class FilePropertiesDialog(QDialog):
    """Dialog for setting file parameters like compression and encryption.
    """
    def __init__(self, localControl, parent=None):
        """Create the file properties dialog.

        Arguments:
            localControl -- a reference to the file's local control
            parent -- the parent window
        """
        super().__init__(parent)
        self.localControl = localControl
        self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint |
                            Qt.WindowCloseButtonHint)
        self.setWindowTitle(_('File Properties'))
        topLayout = QVBoxLayout(self)
        self.setLayout(topLayout)

        groupBox = QGroupBox(_('File Storage'))
        topLayout.addWidget(groupBox)
        groupLayout = QVBoxLayout(groupBox)
        self.compressCheck = QCheckBox(_('&Use file compression'))
        self.compressCheck.setChecked(localControl.compressed)
        groupLayout.addWidget(self.compressCheck)
        self.encryptCheck = QCheckBox(_('Use file &encryption'))
        self.encryptCheck.setChecked(localControl.encrypted)
        groupLayout.addWidget(self.encryptCheck)

        groupBox = QGroupBox(_('Spell Check'))
        topLayout.addWidget(groupBox)
        groupLayout = QHBoxLayout(groupBox)
        label = QLabel(_('Language code or\ndictionary (optional)'))
        groupLayout.addWidget(label)
        self.spellCheckEdit = QLineEdit()
        self.spellCheckEdit.setText(self.localControl.spellCheckLang)
        groupLayout.addWidget(self.spellCheckEdit)

        groupBox = QGroupBox(_('Math Fields'))
        topLayout.addWidget(groupBox)
        groupLayout = QVBoxLayout(groupBox)
        self.zeroBlanks = QCheckBox(_('&Treat blank fields as zeros'))
        self.zeroBlanks.setChecked(localControl.structure.mathZeroBlanks)
        groupLayout.addWidget(self.zeroBlanks)

        ctrlLayout = QHBoxLayout()
        topLayout.addLayout(ctrlLayout)
        ctrlLayout.addStretch(0)
        okButton = QPushButton(_('&OK'))
        ctrlLayout.addWidget(okButton)
        okButton.clicked.connect(self.accept)
        cancelButton = QPushButton(_('&Cancel'))
        ctrlLayout.addWidget(cancelButton)
        cancelButton.clicked.connect(self.reject)

    def accept(self):
        """Store the results.
        """
        if (self.localControl.compressed != self.compressCheck.isChecked() or
            self.localControl.encrypted != self.encryptCheck.isChecked() or
            self.localControl.spellCheckLang != self.spellCheckEdit.text() or
            self.localControl.structure.mathZeroBlanks !=
            self.zeroBlanks.isChecked()):
            undo.ParamUndo(self.localControl.structure.undoList,
                           [(self.localControl, 'compressed'),
                            (self.localControl, 'encrypted'),
                            (self.localControl, 'spellCheckLang'),
                            (self.localControl.structure, 'mathZeroBlanks')])
            self.localControl.compressed = self.compressCheck.isChecked()
            self.localControl.encrypted = self.encryptCheck.isChecked()
            self.localControl.spellCheckLang = self.spellCheckEdit.text()
            self.localControl.structure.mathZeroBlanks = (self.zeroBlanks.
                                                          isChecked())
            super().accept()
        else:
            super().reject()


class PasswordDialog(QDialog):
    """Dialog for password entry and optional re-entry.
    """
    remember = True
    def __init__(self, retype=True, fileLabel='', parent=None):
        """Create the password dialog.

        Arguments:
            retype -- require a 2nd password entry if True
            fileLabel -- file name to show if given
            parent -- the parent window
        """
        super().__init__(parent)
        self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint |
                            Qt.WindowCloseButtonHint)
        self.setWindowTitle(_('Encrypted File Password'))
        self.password = ''
        topLayout = QVBoxLayout(self)
        self.setLayout(topLayout)
        if fileLabel:
            prompt = _('Type Password for "{0}":').format(fileLabel)
        else:
            prompt = _('Type Password:')
        self.editors = [self.addEditor(prompt, topLayout)]
        self.editors[0].setFocus()
        if retype:
            self.editors.append(self.addEditor(_('Re-Type Password:'),
                                               topLayout))
            self.editors[0].returnPressed.connect(self.editors[1].setFocus)
        self.editors[-1].returnPressed.connect(self.accept)
        self.rememberCheck = QCheckBox(_('Remember password during this '
                                               'session'))
        self.rememberCheck.setChecked(PasswordDialog.remember)
        topLayout.addWidget(self.rememberCheck)

        ctrlLayout = QHBoxLayout()
        topLayout.addLayout(ctrlLayout)
        ctrlLayout.addStretch(0)
        okButton = QPushButton(_('&OK'))
        okButton.setAutoDefault(False)
        ctrlLayout.addWidget(okButton)
        okButton.clicked.connect(self.accept)
        cancelButton = QPushButton(_('&Cancel'))
        cancelButton.setAutoDefault(False)
        ctrlLayout.addWidget(cancelButton)
        cancelButton.clicked.connect(self.reject)

    def addEditor(self, labelText, layout):
        """Add a password editor to this dialog and return it.

        Arguments:
            labelText -- the text for the label
            layout -- the layout to append it
        """
        label = QLabel(labelText)
        layout.addWidget(label)
        editor = QLineEdit()
        editor.setEchoMode(QLineEdit.Password)
        layout.addWidget(editor)
        return editor

    def accept(self):
        """Check for valid password and store the result.
        """
        self.password = self.editors[0].text()
        PasswordDialog.remember = self.rememberCheck.isChecked()
        if not self.password:
            QMessageBox.warning(self, 'TreeLine',
                                  _('Zero-length passwords are not permitted'))
        elif len(self.editors) > 1 and self.editors[1].text() != self.password:
             QMessageBox.warning(self, 'TreeLine',
                                       _('Re-typed password did not match'))
        else:
            super().accept()
        for editor in self.editors:
            editor.clear()
        self.editors[0].setFocus()


class TemplateFileItem:
    """Helper class to store template paths and info.
    """
    nameExp = re.compile(r'(\d+)([a-zA-Z]+?)_(.+)')
    def __init__(self, pathObj):
        """Initialize the path.

        Arguments:
            pathObj -- the full path object
        """
        self.pathObj = pathObj
        self.number = sys.maxsize
        self.name = ''
        self.displayName = ''
        self.langCode = ''
        if pathObj:
            self.name = pathObj.stem
            match = TemplateFileItem.nameExp.match(self.name)
            if match:
                num, self.langCode, self.name = match.groups()
                self.number = int(num)
            self.displayName = self.name.replace('_', ' ')

    def sortKey(self):
        """Return a key for sorting the items by number then name.
        """
        return (self.number, self.displayName)

    def __eq__(self, other):
        """Comparison to detect equivalent items.

        Arguments:
            other -- the TemplateFileItem to compare
        """
        return (self.displayName == other.displayName and
                self.langCode == other.langCode)

    def __hash__(self):
        """Return a hash code for use in sets and dictionaries.
        """
        return hash((self.langCode, self.displayName))


class TemplateFileDialog(QDialog):
    """Dialog for listing available template files.
    """
    def __init__(self, title, heading, searchPaths, addDefault=True,
                 parent=None):
        """Create the template dialog.

        Arguments:
            title -- the window title
            heading -- the groupbox text
            searchPaths -- list of path objects with available templates
            addDefault -- if True, add a default (no path) entry
            parent -- the parent window
        """
        super().__init__(parent)
        self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint |
                            Qt.WindowCloseButtonHint)
        self.setWindowTitle(title)
        self.templateItems = []
        if addDefault:
            item = TemplateFileItem(None)
            item.number = -1
            item.displayName = _('Default - Single Line Text')
            self.templateItems.append(item)

        topLayout = QVBoxLayout(self)
        self.setLayout(topLayout)
        groupBox = QGroupBox(heading)
        topLayout.addWidget(groupBox)
        boxLayout = QVBoxLayout(groupBox)
        self.listBox = QListWidget()
        boxLayout.addWidget(self.listBox)
        self.listBox.itemDoubleClicked.connect(self.accept)

        ctrlLayout = QHBoxLayout()
        topLayout.addLayout(ctrlLayout)
        ctrlLayout.addStretch(0)
        self.okButton = QPushButton(_('&OK'))
        ctrlLayout.addWidget(self.okButton)
        self.okButton.clicked.connect(self.accept)
        cancelButton = QPushButton(_('&Cancel'))
        ctrlLayout.addWidget(cancelButton)
        cancelButton.clicked.connect(self.reject)

        self.readTemplates(searchPaths)
        self.loadListBox()

    def readTemplates(self, searchPaths):
        """Read template file paths into the templateItems list.

        Arguments:
            searchPaths -- list of path objects with available templates
        """
        templateItems = set()
        for path in searchPaths:
            for templatePath in path.glob('*.trln'):
                templateItem = TemplateFileItem(templatePath)
                if templateItem not in templateItems:
                    templateItems.add(templateItem)
        availLang = set([item.langCode for item in templateItems])
        if len(availLang) > 1:
            lang = 'en'
            if globalref.lang[:2] in availLang:
                lang = globalref.lang[:2]
            templateItems = [item for item in templateItems if
                             item.langCode == lang or not item.langCode]
        self.templateItems.extend(list(templateItems))
        self.templateItems.sort(key = operator.methodcaller('sortKey'))

    def loadListBox(self):
        """Load the list box with items from the templateItems list.
        """
        self.listBox.clear()
        self.listBox.addItems([item.displayName for item in
                               self.templateItems])
        self.listBox.setCurrentRow(0)
        self.okButton.setEnabled(self.listBox.count() > 0)

    def selectedPath(self):
        """Return the path object from the selected item.
        """
        item = self.templateItems[self.listBox.currentRow()]
        return item.pathObj

    def selectedName(self):
        """Return the displayed name with underscores from the selected item.
        """
        item = self.templateItems[self.listBox.currentRow()]
        return item.name


class ExceptionDialog(QDialog):
    """Dialog for showing debug info from an unhandled exception.
    """
    def __init__(self, excType, value, tb, parent=None):
        """Initialize the exception dialog.

        Arguments:
            excType -- execption class
            value -- execption error text
            tb -- the traceback object
        """
        super().__init__(parent)
        self.setWindowFlags(Qt.Window | Qt.WindowStaysOnTopHint)
        self.setWindowTitle(_('TreeLine - Serious Error'))

        topLayout = QVBoxLayout(self)
        self.setLayout(topLayout)
        label = QLabel(_('A serious error has occurred.  TreeLine could be '
                         'in an unstable state.\n'
                         'Recommend saving any file changes under another '
                         'filename and restart TreeLine.\n\n'
                         'The debugging info shown below can be copied '
                         'and emailed to doug101@bellz.org along with\n'
                         'an explanation of the circumstances.\n'))
        topLayout.addWidget(label)
        textBox = QTextEdit()
        textBox.setReadOnly(True)
        pyVersion = '.'.join([repr(num) for num in sys.version_info[:3]])
        textLines = ['When:  {0}\n'.format(datetime.datetime.now().
                                           isoformat(' ')),
                     'TreeLine Version:  {0}\n'.format(__version__),
                     'Python Version:  {0}\n'.format(pyVersion),
                     'Qt Version:  {0}\n'.format(qVersion()),
                     'PyQt Version:  {0}\n'.format(PYQT_VERSION_STR),
                     'OS:  {0}\n'.format(platform.platform()), '\n']
        textLines.extend(traceback.format_exception(excType, value, tb))
        textBox.setPlainText(''.join(textLines))
        topLayout.addWidget(textBox)

        ctrlLayout = QHBoxLayout()
        topLayout.addLayout(ctrlLayout)
        ctrlLayout.addStretch(0)
        closeButton = QPushButton(_('&Close'))
        ctrlLayout.addWidget(closeButton)
        closeButton.clicked.connect(self.close)


FindScope = enum.IntEnum('FindScope', 'fullData titlesOnly')
FindType = enum.IntEnum('FindType', 'keyWords fullWords fullPhrase regExp')

class FindFilterDialog(QDialog):
    """Dialog for searching for text within tree titles and data.
    """
    dialogShown = pyqtSignal(bool)
    def __init__(self, isFilterDialog=False, parent=None):
        """Initialize the find dialog.

        Arguments:
            isFilterDialog -- True for filter dialog, False for find dialog
            parent -- the parent window
        """
        super().__init__(parent)
        self.isFilterDialog = isFilterDialog
        self.setAttribute(Qt.WA_QuitOnClose, False)
        self.setWindowFlags(Qt.Window | Qt.WindowStaysOnTopHint)

        topLayout = QVBoxLayout(self)
        self.setLayout(topLayout)

        textBox = QGroupBox(_('&Search Text'))
        topLayout.addWidget(textBox)
        textLayout = QVBoxLayout(textBox)
        self.textEntry = QLineEdit()
        textLayout.addWidget(self.textEntry)
        self.textEntry.textEdited.connect(self.updateAvail)

        horizLayout = QHBoxLayout()
        topLayout.addLayout(horizLayout)

        whatBox = QGroupBox(_('What to Search'))
        horizLayout.addWidget(whatBox)
        whatLayout = QVBoxLayout(whatBox)
        self.whatButtons = QButtonGroup(self)
        button = QRadioButton(_('Full &data'))
        self.whatButtons.addButton(button, FindScope.fullData)
        whatLayout.addWidget(button)
        button = QRadioButton(_('&Titles only'))
        self.whatButtons.addButton(button, FindScope.titlesOnly)
        whatLayout.addWidget(button)
        self.whatButtons.button(FindScope.fullData).setChecked(True)

        howBox = QGroupBox(_('How to Search'))
        horizLayout.addWidget(howBox)
        howLayout = QVBoxLayout(howBox)
        self.howButtons = QButtonGroup(self)
        button = QRadioButton(_('&Key words'))
        self.howButtons.addButton(button, FindType.keyWords)
        howLayout.addWidget(button)
        button = QRadioButton(_('Key full &words'))
        self.howButtons.addButton(button, FindType.fullWords)
        howLayout.addWidget(button)
        button = QRadioButton(_('F&ull phrase'))
        self.howButtons.addButton(button, FindType.fullPhrase)
        howLayout.addWidget(button)
        button = QRadioButton(_('&Regular expression'))
        self.howButtons.addButton(button, FindType.regExp)
        howLayout.addWidget(button)
        self.howButtons.button(FindType.keyWords).setChecked(True)

        ctrlLayout = QHBoxLayout()
        topLayout.addLayout(ctrlLayout)
        if not self.isFilterDialog:
            self.setWindowTitle(_('Find'))
            self.previousButton = QPushButton(_('Find &Previous'))
            ctrlLayout.addWidget(self.previousButton)
            self.previousButton.clicked.connect(self.findPrevious)
            self.nextButton = QPushButton(_('Find &Next'))
            self.nextButton.setDefault(True)
            ctrlLayout.addWidget(self.nextButton)
            self.nextButton.clicked.connect(self.findNext)
            self.resultLabel = QLabel()
            topLayout.addWidget(self.resultLabel)
        else:
            self.setWindowTitle(_('Filter'))
            self.filterButton = QPushButton(_('&Filter'))
            ctrlLayout.addWidget(self.filterButton)
            self.filterButton.clicked.connect(self.startFilter)
            self.endFilterButton = QPushButton(_('&End Filter'))
            ctrlLayout.addWidget(self.endFilterButton)
            self.endFilterButton.clicked.connect(self.endFilter)
        closeButton = QPushButton(_('&Close'))
        ctrlLayout.addWidget(closeButton)
        closeButton.clicked.connect(self.close)
        self.updateAvail('')

    def selectAllText(self):
        """Select all line edit text to prepare for a new entry.
        """
        self.textEntry.selectAll()
        self.textEntry.setFocus()

    def updateAvail(self, text='', fileChange=False):
        """Make find buttons available if search text exists.

        Arguments:
            text -- placeholder for signal text (not used)
            fileChange -- True if window changed while dialog open
        """
        hasEntry = len(self.textEntry.text().strip()) > 0
        if not self.isFilterDialog:
            self.previousButton.setEnabled(hasEntry)
            self.nextButton.setEnabled(hasEntry)
            self.resultLabel.setText('')
        else:
            window = globalref.mainControl.activeControl.activeWindow
            if fileChange and window.treeFilterView:
                filterView = window.treeFilterView
                self.textEntry.setText(filterView.filterStr)
                self.whatButtons.button(filterView.filterWhat).setChecked(True)
                self.howButtons.button(filterView.filterHow).setChecked(True)
            self.filterButton.setEnabled(hasEntry)
            self.endFilterButton.setEnabled(window.treeFilterView != None)

    def find(self, forward=True):
        """Find another match in the indicated direction.

        Arguments:
            forward -- next if True, previous if False
        """
        self.resultLabel.setText('')
        text = self.textEntry.text()
        titlesOnly = self.whatButtons.checkedId() == (FindScope.titlesOnly)
        control = globalref.mainControl.activeControl
        if self.howButtons.checkedId() == FindType.regExp:
            try:
                regExp = re.compile(text)
            except re.error:
                QMessageBox.warning(self, 'TreeLine',
                                    _('Error - invalid regular expression'))
                return
            result = control.findNodesByRegExp([regExp], titlesOnly, forward)
        elif self.howButtons.checkedId() == FindType.fullWords:
            regExpList = []
            for word in text.lower().split():
                regExpList.append(re.compile(r'(?i)\b{}\b'.
                                             format(re.escape(word))))
            result = control.findNodesByRegExp(regExpList, titlesOnly, forward)
        elif self.howButtons.checkedId() == FindType.keyWords:
            wordList = text.lower().split()
            result = control.findNodesByWords(wordList, titlesOnly, forward)
        else:         # full phrase
            wordList = [text.lower().strip()]
            result = control.findNodesByWords(wordList, titlesOnly, forward)
        if not result:
            self.resultLabel.setText(_('Search string "{0}" not found').
                                     format(text))

    def findPrevious(self):
        """Find the previous match.
        """
        self.find(False)

    def findNext(self):
        """Find the next match.
        """
        self.find(True)

    def startFilter(self):
        """Start filtering nodes.
        """
        if self.howButtons.checkedId() == FindType.regExp:
            try:
                re.compile(self.textEntry.text())
            except re.error:
                QMessageBox.warning(self, 'TreeLine',
                                       _('Error - invalid regular expression'))
                return
        filterView = (globalref.mainControl.activeControl.activeWindow.
                      filterView())
        filterView.filterWhat = self.whatButtons.checkedId()
        filterView.filterHow = self.howButtons.checkedId()
        filterView.filterStr = self.textEntry.text()
        filterView.updateContents()
        self.updateAvail()

    def endFilter(self):
        """Stop filtering nodes.
        """
        globalref.mainControl.activeControl.activeWindow.removeFilterView()
        self.updateAvail()

    def closeEvent(self, event):
        """Signal that the dialog is closing.

        Arguments:
            event -- the close event
        """
        self.dialogShown.emit(False)


FindReplaceType = enum.IntEnum('FindReplaceType', 'anyMatch fullWord regExp')

class FindReplaceDialog(QDialog):
    """Dialog for finding and replacing text in the node data.
    """
    dialogShown = pyqtSignal(bool)
    def __init__(self, parent=None):
        """Initialize the find and replace dialog.

        Arguments:
            parent -- the parent window
        """
        super().__init__(parent)
        self.setAttribute(Qt.WA_QuitOnClose, False)
        self.setWindowFlags(Qt.Window | Qt.WindowStaysOnTopHint)
        self.setWindowTitle(_('Find and Replace'))

        self.matchedSpot = None
        topLayout = QGridLayout(self)
        self.setLayout(topLayout)

        textBox = QGroupBox(_('&Search Text'))
        topLayout.addWidget(textBox, 0, 0)
        textLayout = QVBoxLayout(textBox)
        self.textEntry = QLineEdit()
        textLayout.addWidget(self.textEntry)
        self.textEntry.textEdited.connect(self.clearMatch)

        replaceBox = QGroupBox(_('Replacement &Text'))
        topLayout.addWidget(replaceBox, 0, 1)
        replaceLayout = QVBoxLayout(replaceBox)
        self.replaceEntry = QLineEdit()
        replaceLayout.addWidget(self.replaceEntry)

        howBox = QGroupBox(_('How to Search'))
        topLayout.addWidget(howBox, 1, 0, 2, 1)
        howLayout = QVBoxLayout(howBox)
        self.howButtons = QButtonGroup(self)
        button = QRadioButton(_('Any &match'))
        self.howButtons.addButton(button, FindReplaceType.anyMatch)
        howLayout.addWidget(button)
        button = QRadioButton(_('Full &words'))
        self.howButtons.addButton(button, FindReplaceType.fullWord)
        howLayout.addWidget(button)
        button = QRadioButton(_('Re&gular expression'))
        self.howButtons.addButton(button, FindReplaceType.regExp)
        howLayout.addWidget(button)
        self.howButtons.button(FindReplaceType.anyMatch).setChecked(True)
        self.howButtons.buttonClicked.connect(self.clearMatch)

        typeBox = QGroupBox(_('&Node Type'))
        topLayout.addWidget(typeBox, 1, 1)
        typeLayout = QVBoxLayout(typeBox)
        self.typeCombo = QComboBox()
        typeLayout.addWidget(self.typeCombo)
        self.typeCombo.currentIndexChanged.connect(self.loadFieldNames)

        fieldBox = QGroupBox(_('N&ode Fields'))
        topLayout.addWidget(fieldBox, 2, 1)
        fieldLayout = QVBoxLayout(fieldBox)
        self.fieldCombo = QComboBox()
        fieldLayout.addWidget(self.fieldCombo)
        self.fieldCombo.currentIndexChanged.connect(self.clearMatch)

        ctrlLayout = QHBoxLayout()
        topLayout.addLayout(ctrlLayout, 3, 0, 1, 2)
        self.previousButton = QPushButton(_('Find &Previous'))
        ctrlLayout.addWidget(self.previousButton)
        self.previousButton.clicked.connect(self.findPrevious)
        self.nextButton = QPushButton(_('&Find Next'))
        self.nextButton.setDefault(True)
        ctrlLayout.addWidget(self.nextButton)
        self.nextButton.clicked.connect(self.findNext)
        self.replaceButton = QPushButton(_('&Replace'))
        ctrlLayout.addWidget(self.replaceButton)
        self.replaceButton.clicked.connect(self.replace)
        self.replaceAllButton = QPushButton(_('Replace &All'))
        ctrlLayout.addWidget(self.replaceAllButton)
        self.replaceAllButton.clicked.connect(self.replaceAll)
        closeButton = QPushButton(_('&Close'))
        ctrlLayout.addWidget(closeButton)
        closeButton.clicked.connect(self.close)

        self.resultLabel = QLabel()
        topLayout.addWidget(self.resultLabel, 4, 0, 1, 2)
        self.loadTypeNames()
        self.updateAvail()

    def updateAvail(self):
        """Set find & replace buttons available if search text & matches exist.
        """
        hasEntry = (len(self.textEntry.text().strip()) > 0 or
                    self.howButtons.checkedId() == FindReplaceType.anyMatch)
        self.previousButton.setEnabled(hasEntry)
        self.nextButton.setEnabled(hasEntry)
        match = bool(self.matchedSpot and self.matchedSpot is
                     globalref.mainControl.activeControl.
                     currentSelectionModel().currentSpot())
        self.replaceButton.setEnabled(match)
        self.replaceAllButton.setEnabled(match)
        self.resultLabel.setText('')

    def clearMatch(self):
        """Remove reference to matched node if search criteria changes.
        """
        self.matchedSpot = None
        globalref.mainControl.activeControl.findReplaceSpotRef = (None, 0)
        self.updateAvail()

    def loadTypeNames(self):
        """Load format type names into combo box.
        """
        origTypeName = self.typeCombo.currentText()
        nodeFormats = globalref.mainControl.activeControl.structure.treeFormats
        self.typeCombo.blockSignals(True)
        self.typeCombo.clear()
        typeNames = nodeFormats.typeNames()
        self.typeCombo.addItems([_('[All Types]')] + typeNames)
        origPos = self.typeCombo.findText(origTypeName)
        if origPos >= 0:
            self.typeCombo.setCurrentIndex(origPos)
        self.typeCombo.blockSignals(False)
        self.loadFieldNames()

    def loadFieldNames(self):
        """Load field names into combo box.
        """
        origFieldName = self.fieldCombo.currentText()
        nodeFormats = globalref.mainControl.activeControl.structure.treeFormats
        typeName = self.typeCombo.currentText()
        fieldNames = []
        if typeName.startswith('['):
            for typeName in nodeFormats.typeNames():
                for fieldName in nodeFormats[typeName].fieldNames():
                    if fieldName not in fieldNames:
                        fieldNames.append(fieldName)
        else:
            fieldNames.extend(nodeFormats[typeName].fieldNames())
        self.fieldCombo.clear()
        self.fieldCombo.addItems([_('[All Fields]')] + fieldNames)
        origPos = self.fieldCombo.findText(origFieldName)
        if origPos >= 0:
            self.fieldCombo.setCurrentIndex(origPos)
        self.matchedSpot = None
        self.updateAvail()

    def findParameters(self):
        """Create search parameters based on the dialog settings.

        Return a tuple of searchText, regExpObj, typeName, and fieldName.
        """
        text = self.textEntry.text()
        searchText = ''
        regExpObj = None
        if self.howButtons.checkedId() == FindReplaceType.anyMatch:
            searchText = text.lower().strip()
        elif self.howButtons.checkedId() == FindReplaceType.fullWord:
            regExpObj = re.compile(r'(?i)\b{}\b'.format(re.escape(text)))
        else:
            regExpObj = re.compile(text)
        typeName = self.typeCombo.currentText()
        if typeName.startswith('['):
            typeName = ''
        fieldName = self.fieldCombo.currentText()
        if fieldName.startswith('['):
            fieldName = ''
        return (searchText, regExpObj, typeName, fieldName)

    def find(self, forward=True):
        """Find another match in the indicated direction.

        Arguments:
            forward -- next if True, previous if False
        """
        self.matchedSpot = None
        try:
            searchText, regExpObj, typeName, fieldName = self.findParameters()
        except re.error:
            QMessageBox.warning(self, 'TreeLine',
                                _('Error - invalid regular expression'))
            self.updateAvail()
            return
        control = globalref.mainControl.activeControl
        if control.findNodesForReplace(searchText, regExpObj, typeName,
                                       fieldName, forward):
            self.matchedSpot = control.currentSelectionModel().currentSpot()
            self.updateAvail()
        else:
            self.updateAvail()
            self.resultLabel.setText(_('Search text "{0}" not found').
                                     format(self.textEntry.text()))

    def findPrevious(self):
        """Find the previous match.
        """
        self.find(False)

    def findNext(self):
        """Find the next match.
        """
        self.find(True)

    def replace(self):
        """Replace the currently found text.
        """
        searchText, regExpObj, typeName, fieldName = self.findParameters()
        replaceText = self.replaceEntry.text()
        control = globalref.mainControl.activeControl
        if control.replaceInCurrentNode(searchText, regExpObj, typeName,
                                        fieldName, replaceText):
            self.find()
        else:
            QMessageBox.warning(self, 'TreeLine',
                                      _('Error - replacement failed'))
            self.matchedSpot = None
            self.updateAvail()

    def replaceAll(self):
        """Replace all text matches.
        """
        searchText, regExpObj, typeName, fieldName = self.findParameters()
        replaceText = self.replaceEntry.text()
        control = globalref.mainControl.activeControl
        qty = control.replaceAll(searchText, regExpObj, typeName, fieldName,
                                 replaceText)
        self.matchedSpot = None
        self.updateAvail()
        self.resultLabel.setText(_('Replaced {0} matches').format(qty))

    def closeEvent(self, event):
        """Signal that the dialog is closing.

        Arguments:
            event -- the close event
        """
        self.dialogShown.emit(False)


SortWhat = enum.IntEnum('SortWhat',
                        'fullTree selectBranch selectChildren selectSiblings')
SortMethod = enum.IntEnum('SortMethod', 'fieldSort titleSort')
SortDirection = enum.IntEnum('SortDirection', 'forward reverse')

class SortDialog(QDialog):
    """Dialog for defining sort operations.
    """
    dialogShown = pyqtSignal(bool)
    def __init__(self, parent=None):
        """Initialize the sort dialog.

        Arguments:
            parent -- the parent window
        """
        super().__init__(parent)
        self.setAttribute(Qt.WA_QuitOnClose, False)
        self.setWindowFlags(Qt.Window | Qt.WindowStaysOnTopHint)
        self.setWindowTitle(_('Sort Nodes'))

        topLayout = QVBoxLayout(self)
        self.setLayout(topLayout)
        horizLayout = QHBoxLayout()
        topLayout.addLayout(horizLayout)
        whatBox = QGroupBox(_('What to Sort'))
        horizLayout.addWidget(whatBox)
        whatLayout = QVBoxLayout(whatBox)
        self.whatButtons = QButtonGroup(self)
        button = QRadioButton(_('&Entire tree'))
        self.whatButtons.addButton(button, SortWhat.fullTree)
        whatLayout.addWidget(button)
        button = QRadioButton(_('Selected &branches'))
        self.whatButtons.addButton(button, SortWhat.selectBranch)
        whatLayout.addWidget(button)
        button = QRadioButton(_('Selection\'s childre&n'))
        self.whatButtons.addButton(button, SortWhat.selectChildren)
        whatLayout.addWidget(button)
        button = QRadioButton(_('Selection\'s &siblings'))
        self.whatButtons.addButton(button, SortWhat.selectSiblings)
        whatLayout.addWidget(button)
        self.whatButtons.button(SortWhat.fullTree).setChecked(True)

        vertLayout =  QVBoxLayout()
        horizLayout.addLayout(vertLayout)
        methodBox = QGroupBox(_('Sort Method'))
        vertLayout.addWidget(methodBox)
        methodLayout = QVBoxLayout(methodBox)
        self.methodButtons = QButtonGroup(self)
        button = QRadioButton(_('&Predefined Key Fields'))
        self.methodButtons.addButton(button, SortMethod.fieldSort)
        methodLayout.addWidget(button)
        button = QRadioButton(_('Node &Titles'))
        self.methodButtons.addButton(button, SortMethod.titleSort)
        methodLayout.addWidget(button)
        self.methodButtons.button(SortMethod.fieldSort).setChecked(True)

        directionBox = QGroupBox(_('Sort Direction'))
        vertLayout.addWidget(directionBox)
        directionLayout =  QVBoxLayout(directionBox)
        self.directionButtons = QButtonGroup(self)
        button = QRadioButton(_('&Forward'))
        self.directionButtons.addButton(button, SortDirection.forward)
        directionLayout.addWidget(button)
        button = QRadioButton(_('&Reverse'))
        self.directionButtons.addButton(button, SortDirection.reverse)
        directionLayout.addWidget(button)
        self.directionButtons.button(SortDirection.forward).setChecked(True)

        ctrlLayout = QHBoxLayout()
        topLayout.addLayout(ctrlLayout)
        ctrlLayout.addStretch()
        okButton = QPushButton(_('&OK'))
        ctrlLayout.addWidget(okButton)
        okButton.clicked.connect(self.sortAndClose)
        applyButton = QPushButton(_('&Apply'))
        ctrlLayout.addWidget(applyButton)
        applyButton.clicked.connect(self.sortNodes)
        closeButton = QPushButton(_('&Close'))
        ctrlLayout.addWidget(closeButton)
        closeButton.clicked.connect(self.close)
        self.updateCommandsAvail()

    def updateCommandsAvail(self):
        """Set what to sort options available based on tree selections.
        """
        selModel = globalref.mainControl.activeControl.currentSelectionModel()
        hasChild = False
        hasSibling = False
        for spot in selModel.selectedSpots():
            if spot.nodeRef.childList:
                hasChild = True
            if spot.parentSpot and len(spot.parentSpot.nodeRef.childList) > 1:
                hasSibling = True
        self.whatButtons.button(SortWhat.selectBranch).setEnabled(hasChild)
        self.whatButtons.button(SortWhat.selectChildren).setEnabled(hasChild)
        self.whatButtons.button(SortWhat.selectSiblings).setEnabled(hasSibling)
        if not self.whatButtons.checkedButton().isEnabled():
            self.whatButtons.button(SortWhat.fullTree).setChecked(True)

    def sortNodes(self):
        """Perform the sorting operation.
        """
        QApplication.setOverrideCursor(Qt.WaitCursor)
        control = globalref.mainControl.activeControl
        selSpots = control.currentSelectionModel().selectedSpots()
        if self.whatButtons.checkedId() == SortWhat.fullTree:
            selSpots = [control.structure.spotByNumber(0)]
        elif self.whatButtons.checkedId() == SortWhat.selectSiblings:
            selSpots = [spot.parentSpot for spot in selSpots]
        if self.whatButtons.checkedId() in (SortWhat.fullTree,
                                            SortWhat.selectBranch):
            rootSpots = selSpots[:]
            selSpots = []
            for root in rootSpots:
                for spot in root.spotDescendantGen():
                    if spot.nodeRef.childList:
                        selSpots.append(spot)
        undo.ChildListUndo(control.structure.undoList,
                           [spot.nodeRef for spot in selSpots])
        forward = self.directionButtons.checkedId() == SortDirection.forward
        if self.methodButtons.checkedId() == SortMethod.fieldSort:
            for spot in selSpots:
                spot.nodeRef.sortChildrenByField(False, forward)
            # reset temporary sort field storage
            for nodeFormat in control.structure.treeFormats.values():
                nodeFormat.sortFields = []
        else:
            for spot in selSpots:
                spot.nodeRef.sortChildrenByTitle(False, forward)
        control.updateAll()
        QApplication.restoreOverrideCursor()

    def sortAndClose(self):
        """Perform the sorting operation and close the dialog.
        """
        self.sortNodes()
        self.close()

    def closeEvent(self, event):
        """Signal that the dialog is closing.

        Arguments:
            event -- the close event
        """
        self.dialogShown.emit(False)


NumberingScope = enum.IntEnum('NumberingScope',
                              'fullTree selectBranch selectChildren')
NumberingNoField = enum.IntEnum('NumberingNoField',
                            'ignoreNoField restartAfterNoField reserveNoField')

class NumberingDialog(QDialog):
    """Dialog for updating node nuumbering fields.
    """
    dialogShown = pyqtSignal(bool)
    def __init__(self, parent=None):
        """Initialize the numbering dialog.

        Arguments:
            parent -- the parent window
        """
        super().__init__(parent)
        self.setAttribute(Qt.WA_QuitOnClose, False)
        self.setWindowFlags(Qt.Window | Qt.WindowStaysOnTopHint)
        self.setWindowTitle(_('Update Node Numbering'))

        topLayout = QVBoxLayout(self)
        self.setLayout(topLayout)
        whatBox = QGroupBox(_('What to Update'))
        topLayout.addWidget(whatBox)
        whatLayout = QVBoxLayout(whatBox)
        self.whatButtons = QButtonGroup(self)
        button = QRadioButton(_('&Entire tree'))
        self.whatButtons.addButton(button, NumberingScope.fullTree)
        whatLayout.addWidget(button)
        button = QRadioButton(_('Selected &branches'))
        self.whatButtons.addButton(button, NumberingScope.selectBranch)
        whatLayout.addWidget(button)
        button = QRadioButton(_('&Selection\'s children'))
        self.whatButtons.addButton(button, NumberingScope.selectChildren)
        whatLayout.addWidget(button)
        self.whatButtons.button(NumberingScope.fullTree).setChecked(True)

        rootBox = QGroupBox(_('Root Node'))
        topLayout.addWidget(rootBox)
        rootLayout = QVBoxLayout(rootBox)
        self.rootCheck = QCheckBox(_('Include top-level nodes'))
        rootLayout.addWidget(self.rootCheck)
        self.rootCheck.setChecked(True)

        noFieldBox = QGroupBox(_('Handling Nodes without Numbering '
                                       'Fields'))
        topLayout.addWidget(noFieldBox)
        noFieldLayout =  QVBoxLayout(noFieldBox)
        self.noFieldButtons = QButtonGroup(self)
        button = QRadioButton(_('&Ignore and skip'))
        self.noFieldButtons.addButton(button, NumberingNoField.ignoreNoField)
        noFieldLayout.addWidget(button)
        button = QRadioButton(_('&Restart numbers for next siblings'))
        self.noFieldButtons.addButton(button,
                                      NumberingNoField.restartAfterNoField)
        noFieldLayout.addWidget(button)
        button = QRadioButton(_('Reserve &numbers'))
        self.noFieldButtons.addButton(button, NumberingNoField.reserveNoField)
        noFieldLayout.addWidget(button)
        self.noFieldButtons.button(NumberingNoField.
                                   ignoreNoField).setChecked(True)

        ctrlLayout = QHBoxLayout()
        topLayout.addLayout(ctrlLayout)
        ctrlLayout.addStretch()
        okButton = QPushButton(_('&OK'))
        ctrlLayout.addWidget(okButton)
        okButton.clicked.connect(self.numberAndClose)
        applyButton = QPushButton(_('&Apply'))
        ctrlLayout.addWidget(applyButton)
        applyButton.clicked.connect(self.updateNumbering)
        closeButton = QPushButton(_('&Close'))
        ctrlLayout.addWidget(closeButton)
        closeButton.clicked.connect(self.close)
        self.updateCommandsAvail()

    def updateCommandsAvail(self):
        """Set branch numbering available based on tree selections.
        """
        selNodes = globalref.mainControl.activeControl.currentSelectionModel()
        hasChild = False
        for node in selNodes.selectedNodes():
            if node.childList:
                hasChild = True
        self.whatButtons.button(NumberingScope.
                                selectChildren).setEnabled(hasChild)
        if not self.whatButtons.checkedButton().isEnabled():
            self.whatButtons.button(NumberingScope.fullTree).setChecked(True)

    def checkForNumberingFields(self):
        """Check that the tree formats have numbering formats.

        Return a dict of numbering field names by node format name.
        If not found, warn user.
        """
        fieldDict = (globalref.mainControl.activeControl.structure.treeFormats.
                     numberingFieldDict())
        if not fieldDict:
            QMessageBox.warning(self, _('TreeLine Numbering'),
                             _('No numbering fields were found in data types'))
        return fieldDict

    def updateNumbering(self):
        """Perform the numbering update operation.
        """
        QApplication.setOverrideCursor(Qt.WaitCursor)
        fieldDict = self.checkForNumberingFields()
        if fieldDict:
            control = globalref.mainControl.activeControl
            selNodes = control.currentSelectionModel().selectedNodes()
            if (self.whatButtons.checkedId() == NumberingScope.fullTree or
                len(selNodes) == 0):
                selNodes = control.structure.childList
            undo.DataUndo(control.structure.undoList, selNodes, addBranch=True)
            reserveNums = (self.noFieldButtons.checkedId() ==
                           NumberingNoField.reserveNoField)
            restartSetting = (self.noFieldButtons.checkedId() ==
                              NumberingNoField.restartAfterNoField)
            includeRoot = self.rootCheck.isChecked()
            if self.whatButtons.checkedId() == NumberingScope.selectChildren:
                levelLimit = 2
            else:
                levelLimit = sys.maxsize
            startNum = [1]
            completedClones = set()
            for node in selNodes:
                node.updateNumbering(fieldDict, startNum, levelLimit,
                                     completedClones, includeRoot,
                                     reserveNums, restartSetting)
            control.updateAll()
        QApplication.restoreOverrideCursor()

    def numberAndClose(self):
        """Perform the numbering update operation and close the dialog.
        """
        self.updateNumbering()
        self.close()

    def closeEvent(self, event):
        """Signal that the dialog is closing.

        Arguments:
            event -- the close event
        """
        self.dialogShown.emit(False)


menuNames = collections.OrderedDict([(N_('File Menu'), _('File')),
                                     (N_('Edit Menu'), _('Edit')),
                                     (N_('Node Menu'), _('Node')),
                                     (N_('Data Menu'), _('Data')),
                                     (N_('Tools Menu'), _('Tools')),
                                     (N_('Format Menu'), _('Format')),
                                     (N_('View Menu'), _('View')),
                                     (N_('Window Menu'), _('Window')),
                                     (N_('Help Menu'), _('Help'))])

class CustomShortcutsDialog(QDialog):
    """Dialog for customizing keyboard commands.
    """
    def __init__(self, allActions, parent=None):
        """Create a shortcuts selection dialog.

        Arguments:
            allActions -- dict of all actions from a window
            parent -- the parent window
        """
        super().__init__(parent)
        self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint |
                            Qt.WindowCloseButtonHint)
        self.setWindowTitle(_('Keyboard Shortcuts'))
        topLayout = QVBoxLayout(self)
        self.setLayout(topLayout)
        scrollArea = QScrollArea()
        topLayout.addWidget(scrollArea)
        viewport = QWidget()
        viewLayout = QGridLayout(viewport)
        scrollArea.setWidget(viewport)
        scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scrollArea.setWidgetResizable(True)

        self.editors = []
        for i, keyOption in enumerate(globalref.keyboardOptions.values()):
            category = menuNames.get(keyOption.category, _('No menu'))
            try:
                action = allActions[keyOption.name]
            except KeyError:
                pass
            else:
                text = '{0} > {1}'.format(category, action.toolTip())
                label = QLabel(text)
                viewLayout.addWidget(label, i, 0)
                editor = KeyLineEdit(keyOption, action, self)
                viewLayout.addWidget(editor, i, 1)
                self.editors.append(editor)

        ctrlLayout = QHBoxLayout()
        topLayout.addLayout(ctrlLayout)
        restoreButton = QPushButton(_('&Restore Defaults'))
        ctrlLayout.addWidget(restoreButton)
        restoreButton.clicked.connect(self.restoreDefaults)
        ctrlLayout.addStretch(0)
        self.okButton = QPushButton(_('&OK'))
        ctrlLayout.addWidget(self.okButton)
        self.okButton.clicked.connect(self.accept)
        cancelButton = QPushButton(_('&Cancel'))
        ctrlLayout.addWidget(cancelButton)
        cancelButton.clicked.connect(self.reject)
        self.editors[0].setFocus()

    def restoreDefaults(self):
        """Restore all default keyboard shortcuts.
        """
        for editor in self.editors:
            editor.loadDefaultKey()

    def accept(self):
        """Save any changes to options and actions before closing.
        """
        modified = False
        for editor in self.editors:
            if editor.modified:
                editor.saveChange()
                modified = True
        if modified:
            globalref.keyboardOptions.writeFile()
        super().accept()


class KeyLineEdit(QLineEdit):
    """Line editor for keyboad sequence entry.
    """
    usedKeySet = set()
    blankText = ' ' * 8
    def __init__(self, keyOption, action, parent=None):
        """Create a key editor.

        Arguments:
            keyOption -- the KeyOptionItem for this editor
            action -- the action to update on changes
            parent -- the parent dialog
        """
        super().__init__(parent)
        self.keyOption = keyOption
        self.keyAction = action
        self.key = None
        self.modified = False
        self.setReadOnly(True)
        self.loadKey()

    def loadKey(self):
        """Load the initial key shortcut from the option.
        """
        key = self.keyOption.value
        if key:
            self.setKey(key)
        else:
            self.setText(KeyLineEdit.blankText)

    def loadDefaultKey(self):
        """Change to the default key shortcut from the option.

        Arguments:
            useDefault -- if True, load the default key
        """
        key = self.keyOption.defaultValue
        if key == self.key:
            return
        if key:
            self.setKey(key)
            self.modified = True
        else:
            self.clearKey(False)

    def setKey(self, key):
        """Set this editor to the given key and add to the used key set.

        Arguments:
            key - the QKeySequence to add
        """
        keyText = key.toString(QKeySequence.NativeText)
        self.setText(keyText)
        self.key = key
        KeyLineEdit.usedKeySet.add(keyText)

    def clearKey(self, staySelected=True):
        """Remove any existing key.
        """
        self.setText(KeyLineEdit.blankText)
        if staySelected:
            self.selectAll()
        if self.key:
            KeyLineEdit.usedKeySet.remove(self.key.toString(QKeySequence.
                                                            NativeText))
            self.key = None
            self.modified = True

    def saveChange(self):
        """Save any change to the option and action.
        """
        if self.modified:
            self.keyOption.setValue(self.key)
            if self.key:
                self.keyAction.setShortcut(self.key)
            else:
                self.keyAction.setShortcut(QKeySequence())

    def keyPressEvent(self, event):
        """Capture key strokes and update the editor if valid.

        Arguments:
            event -- the key press event
        """
        if event.key() in (Qt.Key_Shift, Qt.Key_Control,
                           Qt.Key_Meta, Qt.Key_Alt,
                           Qt.Key_AltGr, Qt.Key_CapsLock,
                           Qt.Key_NumLock, Qt.Key_ScrollLock,
                           Qt.Key_Pause, Qt.Key_Print,
                           Qt.Key_Cancel):
            event.ignore()
        elif event.key() in (Qt.Key_Backspace, Qt.Key_Escape):
            self.clearKey()
            event.accept()
        else:
            modifier = event.modifiers()
            if modifier & Qt.KeypadModifier:
                modifier = modifier ^ Qt.KeypadModifier
            key = QKeySequence(event.key() + int(modifier))
            if key != self.key:
                keyText = key.toString(QKeySequence.NativeText)
                if keyText not in KeyLineEdit.usedKeySet:
                    if self.key:
                        KeyLineEdit.usedKeySet.remove(self.key.
                                                   toString(QKeySequence.
                                                            NativeText))
                    self.setKey(key)
                    self.selectAll()
                    self.modified = True
                else:
                    text = _('Key {0} is already used').format(keyText)
                    QMessageBox.warning(self.parent(), 'TreeLine', text)
            event.accept()

    def contextMenuEvent(self, event):
        """Change to a context menu with a clear command.

        Arguments:
            event -- the menu event
        """
        menu = QMenu(self)
        menu.addAction(_('Clear &Key'), self.clearKey)
        menu.exec_(event.globalPos())

    def mousePressEvent(self, event):
        """Capture mouse clicks to avoid selection loss.

        Arguments:
            event -- the mouse event
        """
        event.accept()

    def mouseReleaseEvent(self, event):
        """Capture mouse clicks to avoid selection loss.

        Arguments:
            event -- the mouse event
        """
        event.accept()

    def mouseMoveEvent(self, event):
        """Capture mouse clicks to avoid selection loss.

        Arguments:
            event -- the mouse event
        """
        event.accept()

    def mouseDoubleClickEvent(self, event):
        """Capture mouse clicks to avoid selection loss.

        Arguments:
            event -- the mouse event
        """
        event.accept()

    def focusInEvent(self, event):
        """Select contents when focussed.

        Arguments:
            event -- the focus event
        """
        self.selectAll()
        super().focusInEvent(event)


class CustomToolbarDialog(QDialog):
    """Dialog for customizing toolbar buttons.
    """
    separatorString = _('--Separator--')
    def __init__(self, allActions, updateFunction, parent=None):
        """Create a toolbar buttons customization dialog.

        Arguments:
            allActions -- dict of all actions from a window
            updateFunction -- a function ref for updating window toolbars
            parent -- the parent window
        """
        super().__init__(parent)
        self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint |
                            Qt.WindowCloseButtonHint)
        self.setWindowTitle(_('Customize Toolbars'))
        self.allActions = allActions
        self.updateFunction = updateFunction
        self.availableCommands = []
        self.modified = False
        self.numToolbars = 0
        self.availableCommands = []
        self.toolbarLists = []

        topLayout = QVBoxLayout(self)
        self.setLayout(topLayout)
        gridLayout = QGridLayout()
        topLayout.addLayout(gridLayout)

        sizeBox = QGroupBox(_('Toolbar &Size'))
        gridLayout.addWidget(sizeBox, 0, 0, 1, 2)
        sizeLayout = QVBoxLayout(sizeBox)
        self.sizeCombo = QComboBox()
        sizeLayout.addWidget(self.sizeCombo)
        self.sizeCombo.addItems([_('Small Icons'), _('Large Icons')])
        self.sizeCombo.currentIndexChanged.connect(self.setModified)

        numberBox = QGroupBox(_('Toolbar Quantity'))
        gridLayout.addWidget(numberBox, 0, 2)
        numberLayout = QHBoxLayout(numberBox)
        self.quantitySpin = QSpinBox()
        numberLayout.addWidget(self.quantitySpin)
        self.quantitySpin.setRange(0, 20)
        numberlabel = QLabel(_('&Toolbars'))
        numberLayout.addWidget(numberlabel)
        numberlabel.setBuddy(self.quantitySpin)
        self.quantitySpin.valueChanged.connect(self.changeQuantity)

        availableBox = QGroupBox(_('A&vailable Commands'))
        gridLayout.addWidget(availableBox, 1, 0)
        availableLayout = QVBoxLayout(availableBox)
        menuCombo = QComboBox()
        availableLayout.addWidget(menuCombo)
        menuCombo.addItems([_(name) for name in menuNames.keys()])
        menuCombo.currentIndexChanged.connect(self.updateAvailableCommands)

        self.availableListWidget = QListWidget()
        availableLayout.addWidget(self.availableListWidget)

        buttonLayout = QVBoxLayout()
        gridLayout.addLayout(buttonLayout, 1, 1)
        self.addButton = QPushButton('>>')
        buttonLayout.addWidget(self.addButton)
        self.addButton.setMaximumWidth(self.addButton.sizeHint().height())
        self.addButton.clicked.connect(self.addTool)

        self.removeButton = QPushButton('<<')
        buttonLayout.addWidget(self.removeButton)
        self.removeButton.setMaximumWidth(self.removeButton.sizeHint().
                                          height())
        self.removeButton.clicked.connect(self.removeTool)

        toolbarBox = QGroupBox(_('Tool&bar Commands'))
        gridLayout.addWidget(toolbarBox, 1, 2)
        toolbarLayout = QVBoxLayout(toolbarBox)
        self.toolbarCombo = QComboBox()
        toolbarLayout.addWidget(self.toolbarCombo)
        self.toolbarCombo.currentIndexChanged.connect(self.
                                                      updateToolbarCommands)

        self.toolbarListWidget = QListWidget()
        toolbarLayout.addWidget(self.toolbarListWidget)
        self.toolbarListWidget.currentRowChanged.connect(self.
                                                         setButtonsAvailable)

        moveLayout = QHBoxLayout()
        toolbarLayout.addLayout(moveLayout)
        self.moveUpButton = QPushButton(_('Move &Up'))
        moveLayout.addWidget(self.moveUpButton)
        self.moveUpButton.clicked.connect(self.moveUp)
        self.moveDownButton = QPushButton(_('Move &Down'))
        moveLayout.addWidget(self.moveDownButton)
        self.moveDownButton.clicked.connect(self.moveDown)

        ctrlLayout = QHBoxLayout()
        topLayout.addLayout(ctrlLayout)
        restoreButton = QPushButton(_('&Restore Defaults'))
        ctrlLayout.addWidget(restoreButton)
        restoreButton.clicked.connect(self.restoreDefaults)
        ctrlLayout.addStretch()
        self.okButton = QPushButton(_('&OK'))
        ctrlLayout.addWidget(self.okButton)
        self.okButton.clicked.connect(self.accept)
        self.applyButton = QPushButton(_('&Apply'))
        ctrlLayout.addWidget(self.applyButton)
        self.applyButton.clicked.connect(self.applyChanges)
        self.applyButton.setEnabled(False)
        cancelButton = QPushButton(_('&Cancel'))
        ctrlLayout.addWidget(cancelButton)
        cancelButton.clicked.connect(self.reject)

        self.updateAvailableCommands(0)
        self.loadToolbars()

    def setModified(self):
        """Set modified flag and make apply button available.
        """
        self.modified = True
        self.applyButton.setEnabled(True)

    def setButtonsAvailable(self):
        """Enable or disable buttons based on toolbar list state.
        """
        toolbarNum = numCommands = commandNum = 0
        if self.numToolbars:
            toolbarNum = self.toolbarCombo.currentIndex()
            numCommands = len(self.toolbarLists[toolbarNum])
            if self.toolbarLists[toolbarNum]:
                commandNum = self.toolbarListWidget.currentRow()
        self.addButton.setEnabled(self.numToolbars > 0)
        self.removeButton.setEnabled(self.numToolbars and numCommands)
        self.moveUpButton.setEnabled(self.numToolbars and numCommands > 1 and
                                     commandNum > 0)
        self.moveDownButton.setEnabled(self.numToolbars and numCommands > 1 and
                                       commandNum < numCommands - 1)

    def loadToolbars(self, defaultOnly=False):
        """Load all toolbar data from options.

        Arguments:
            defaultOnly -- if True, load default settings
        """
        size = (globalref.toolbarOptions['ToolbarSize'] if not defaultOnly else
                globalref.toolbarOptions.getDefaultValue('ToolbarSize'))
        self.sizeCombo.blockSignals(True)
        if size < 24:
            self.sizeCombo.setCurrentIndex(0)
        else:
            self.sizeCombo.setCurrentIndex(1)
        self.sizeCombo.blockSignals(False)
        self.numToolbars = (globalref.toolbarOptions['ToolbarQuantity'] if not
                            defaultOnly else globalref.toolbarOptions.
                            getDefaultValue('ToolbarQuantity'))
        self.quantitySpin.blockSignals(True)
        self.quantitySpin.setValue(self.numToolbars)
        self.quantitySpin.blockSignals(False)
        self.toolbarLists = []
        commands = (globalref.toolbarOptions['ToolbarCommands'] if not
                    defaultOnly else globalref.toolbarOptions.
                    getDefaultValue('ToolbarCommands'))
        self.toolbarLists = [cmd.split(',') for cmd in commands]
        # account for toolbar quantity mismatch (should not happen)
        del self.toolbarLists[self.numToolbars:]
        while len(self.toolbarLists) < self.numToolbars:
            self.toolbarLists.append([])
        self.updateToolbarCombo()

    def updateToolbarCombo(self):
        """Fill combo with toolbar numbers for current quantity.
        """
        self.toolbarCombo.clear()
        if self.numToolbars:
            self.toolbarCombo.addItems(['Toolbar {0}'.format(num + 1) for
                                        num in range(self.numToolbars)])
        else:
            self.toolbarListWidget.clear()
            self.setButtonsAvailable()

    def updateAvailableCommands(self, menuNum):
        """Fill in available command list for given menu.

        Arguments:
            menuNum -- the index of the current menu selected
        """
        menuName = list(menuNames.keys())[menuNum]
        self.availableCommands = []
        self.availableListWidget.clear()
        for option in globalref.keyboardOptions.values():
            if option.category == menuName:
                action = self.allActions[option.name]
                icon = action.icon()
                if not icon.isNull():
                    self.availableCommands.append(option.name)
                    QListWidgetItem(icon, action.toolTip(),
                                          self.availableListWidget)
        QListWidgetItem(CustomToolbarDialog.separatorString,
                              self.availableListWidget)
        self.availableListWidget.setCurrentRow(0)

    def updateToolbarCommands(self, toolbarNum):
        """Fill in toolbar commands for given toolbar.

        Arguments:
            toolbarNum -- the number of the toolbar to update
        """
        self.toolbarListWidget.clear()
        if self.numToolbars == 0:
            return
        for command in self.toolbarLists[toolbarNum]:
            if command:
                action = self.allActions[command]
                QListWidgetItem(action.icon(), action.toolTip(),
                                      self.toolbarListWidget)
            else:  # separator
                QListWidgetItem(CustomToolbarDialog.separatorString,
                                      self.toolbarListWidget)
        if self.toolbarLists[toolbarNum]:
            self.toolbarListWidget.setCurrentRow(0)
        self.setButtonsAvailable()

    def changeQuantity(self, qty):
        """Change the toolbar quantity based on a spin box signal.

        Arguments:
            qty -- the new toolbar quantity
        """
        self.numToolbars = qty
        while qty > len(self.toolbarLists):
            self.toolbarLists.append([])
        self.updateToolbarCombo()
        self.setModified()

    def addTool(self):
        """Add the selected command to the current toolbar.
        """
        toolbarNum = self.toolbarCombo.currentIndex()
        try:
            command = self.availableCommands[self.availableListWidget.
                                             currentRow()]
            action = self.allActions[command]
            item = QListWidgetItem(action.icon(), action.toolTip())
        except IndexError:
            command = ''
            item = QListWidgetItem(CustomToolbarDialog.separatorString)
        if self.toolbarLists[toolbarNum]:
            pos = self.toolbarListWidget.currentRow() + 1
        else:
            pos = 0
        self.toolbarLists[toolbarNum].insert(pos, command)
        self.toolbarListWidget.insertItem(pos, item)
        self.toolbarListWidget.setCurrentRow(pos)
        self.toolbarListWidget.scrollToItem(item)
        self.setModified()

    def removeTool(self):
        """Remove the selected command from the current toolbar.
        """
        toolbarNum = self.toolbarCombo.currentIndex()
        pos = self.toolbarListWidget.currentRow()
        del self.toolbarLists[toolbarNum][pos]
        self.toolbarListWidget.takeItem(pos)
        if self.toolbarLists[toolbarNum]:
            if pos == len(self.toolbarLists[toolbarNum]):
                pos -= 1
            self.toolbarListWidget.setCurrentRow(pos)
        self.setModified()

    def moveUp(self):
        """Raise the selected command.
        """
        toolbarNum = self.toolbarCombo.currentIndex()
        pos = self.toolbarListWidget.currentRow()
        command = self.toolbarLists[toolbarNum].pop(pos)
        self.toolbarLists[toolbarNum].insert(pos - 1, command)
        item = self.toolbarListWidget.takeItem(pos)
        self.toolbarListWidget.insertItem(pos - 1, item)
        self.toolbarListWidget.setCurrentRow(pos - 1)
        self.toolbarListWidget.scrollToItem(item)
        self.setModified()

    def moveDown(self):
        """Lower the selected command.
        """
        toolbarNum = self.toolbarCombo.currentIndex()
        pos = self.toolbarListWidget.currentRow()
        command = self.toolbarLists[toolbarNum].pop(pos)
        self.toolbarLists[toolbarNum].insert(pos + 1, command)
        item = self.toolbarListWidget.takeItem(pos)
        self.toolbarListWidget.insertItem(pos + 1, item)
        self.toolbarListWidget.setCurrentRow(pos + 1)
        self.toolbarListWidget.scrollToItem(item)
        self.setModified()

    def restoreDefaults(self):
        """Restore all default toolbar settings.
        """
        self.loadToolbars(True)
        self.setModified()

    def applyChanges(self):
        """Apply any changes from the dialog.
        """
        size = 16 if self.sizeCombo.currentIndex() == 0 else 32
        globalref.toolbarOptions.changeValue('ToolbarSize', size)
        globalref.toolbarOptions.changeValue('ToolbarQuantity',
                                             self.numToolbars)
        del self.toolbarLists[self.numToolbars:]
        commands = [','.join(cmds) for cmds in self.toolbarLists]
        globalref.toolbarOptions.changeValue('ToolbarCommands', commands)
        globalref.toolbarOptions.writeFile()
        self.modified = False
        self.applyButton.setEnabled(False)
        self.updateFunction()

    def accept(self):
        """Apply changes and close the dialog.
        """
        if self.modified:
            self.applyChanges()
        super().accept()


class CustomFontData:
    """Class to store custom font settings.

    Acts as a stand-in for PrintData class in the font page of the dialog.
    """
    def __init__(self, fontOption, useAppDefault=True):
        """Initialize the font data.

        Arguments:
            fontOption -- the name of the font setting to retrieve
            useAppDefault -- use app default if true, o/w use sys default
        """
        self.fontOption = fontOption
        if useAppDefault:
            self.defaultFont = QTextDocument().defaultFont()
        else:
            self.defaultFont = QFont(globalref.mainControl.systemFont)
        self.useDefaultFont = True
        self.mainFont = QFont(self.defaultFont)
        fontName = globalref.miscOptions[self.fontOption]
        if fontName:
            self.mainFont.fromString(fontName)
            self.useDefaultFont = False

    def recordChanges(self):
        """Record the updated font info to the option settings.
        """
        if self.useDefaultFont:
            globalref.miscOptions.changeValue(self.fontOption, '')
        else:
            globalref.miscOptions.changeValue(self.fontOption,
                                              self.mainFont.toString())


class CustomFontDialog(QDialog):
    """Dialog for selecting custom fonts.

    Uses the print setup dialog's font page for the details.
    """
    updateRequired = pyqtSignal()
    def __init__(self, parent=None):
        """Create a font customization dialog.

        Arguments:
            parent -- the parent window
        """
        super().__init__(parent)
        self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint |
                            Qt.WindowCloseButtonHint)
        self.setWindowTitle(_('Customize Fonts'))

        topLayout = QVBoxLayout(self)
        self.setLayout(topLayout)
        self.tabs = QTabWidget()
        topLayout.addWidget(self.tabs)
        self.tabs.setUsesScrollButtons(False)
        self.tabs.currentChanged.connect(self.updateTabDefault)

        self.pages = []
        defaultLabel = _('&Use system default font')
        appFontPage = printdialogs.FontPage(CustomFontData('AppFont', False),
                                            defaultLabel)
        self.pages.append(appFontPage)
        self.tabs.addTab(appFontPage, _('App Default Font'))
        defaultLabel = _('&Use app default font')
        treeFontPage = printdialogs.FontPage(CustomFontData('TreeFont'),
                                             defaultLabel)
        self.pages.append(treeFontPage)
        self.tabs.addTab(treeFontPage, _('Tree View Font'))
        outputFontPage = printdialogs.FontPage(CustomFontData('OutputFont'),
                                               defaultLabel)
        self.pages.append(outputFontPage)
        self.tabs.addTab(outputFontPage, _('Output View Font'))
        editorFontPage = printdialogs.FontPage(CustomFontData('EditorFont'),
                                               defaultLabel)
        self.pages.append(editorFontPage)
        self.tabs.addTab(editorFontPage, _('Editor View Font'))

        ctrlLayout = QHBoxLayout()
        topLayout.addLayout(ctrlLayout)
        ctrlLayout.addStretch()
        self.okButton = QPushButton(_('&OK'))
        ctrlLayout.addWidget(self.okButton)
        self.okButton.clicked.connect(self.accept)
        self.applyButton = QPushButton(_('&Apply'))
        ctrlLayout.addWidget(self.applyButton)
        self.applyButton.clicked.connect(self.applyChanges)
        cancelButton = QPushButton(_('&Cancel'))
        ctrlLayout.addWidget(cancelButton)
        cancelButton.clicked.connect(self.reject)

    def updateTabDefault(self):
        """Update the default font on the newly shown page.
        """
        appFontWidget = self.tabs.widget(0)
        currentWidget = self.tabs.currentWidget()
        if appFontWidget is not currentWidget:
            if appFontWidget.defaultCheck.isChecked():
                defaultFont = QFont(globalref.mainControl.systemFont)
            else:
                defaultFont = appFontWidget.readFont()
            if defaultFont:
                currentWidget.printData.defaultFont = defaultFont
                if currentWidget.defaultCheck.isChecked():
                    currentWidget.printData.mainFont = QFont(defaultFont)
                    currentWidget.currentFont = (currentWidget.printData.
                                                 mainFont)
                    currentWidget.setFont(defaultFont)

    def applyChanges(self):
        """Apply any changes from the dialog.
        """
        modified = False
        for page in self.pages:
            if page.saveChanges():
                page.printData.recordChanges()
                modified = True
        if modified:
            globalref.miscOptions.writeFile()
            self.updateRequired.emit()

    def accept(self):
        """Apply changes and close the dialog.
        """
        self.applyChanges()
        super().accept()


class AboutDialog(QDialog):
    """Show program info in a text box.
    """
    def __init__(self, title, textLines, icon=None, parent=None):
        """Create the dialog.

        Arguments:
            title -- the window title text
            textLines -- a list of lines to show
            icon -- an icon to show if given
            parent -- the parent window
        """
        super().__init__(parent)
        self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint |
                            Qt.WindowCloseButtonHint)
        self.setWindowTitle(title)

        topLayout = QVBoxLayout(self)
        self.setLayout(topLayout)
        mainLayout = QHBoxLayout()
        topLayout.addLayout(mainLayout)
        iconLabel = QLabel()
        iconLabel.setPixmap(icon.pixmap(128, 128))
        mainLayout.addWidget(iconLabel)
        textBox = QPlainTextEdit()
        textBox.setReadOnly(True)
        textBox.setWordWrapMode(QTextOption.NoWrap)
        textBox.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        textBox.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        text = '\n'.join(textLines)
        textBox.setPlainText(text)
        size = textBox.fontMetrics().size(0, text)
        size.setHeight(size.height() + 10)
        size.setWidth(size.width() + 10)
        textBox.setMinimumSize(size)
        mainLayout.addWidget(textBox)

        ctrlLayout = QHBoxLayout()
        topLayout.addLayout(ctrlLayout)
        ctrlLayout.addStretch()
        okButton = QPushButton(_('&OK'))
        ctrlLayout.addWidget(okButton)
        okButton.clicked.connect(self.accept)