forked from Beherith/springrts_smf_compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathargparseui.py
848 lines (764 loc) · 35.1 KB
/
argparseui.py
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
##############################################################################
# This file is part of argparseui. #
# #
# argparseui is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# argparseui is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with argparseui. If not, see <http://www.gnu.org/licenses/>. #
##############################################################################
import textwrap
import argparse
import os
from PyQt4 import QtCore, QtGui
__VERSION__ = "0.0.4"
def comb(str1, str2):
if str1.count('|') == 2:
str1 = str1.partition('|')[2].rpartition('|')[0] + ' \t' + str1.partition('|')[0] + str1.rpartition('|')[2]
return str1 + str2
import re
try:
_find_unsafe = re.compile(r'[^\w@%+=:,./-]', re.ASCII).search
except:
_find_unsafe = re.compile(r'[^\w@%+=:,./-]').search
def quote(s):
"""Return a shell-escaped version of the string *s*."""
if not s:
return "''"
if _find_unsafe(s) is None:
return s
# use single quotes, and put single quotes into double quotes
# the string $'b is then quoted as '$'"'"'b'
return "'" + s.replace("'", "'\"'\"'") + "'"
SINGLE = {
'int' : 'an integer',
'float' : 'a floating point number',
'str' : 'a string',
'unicode' : 'a unicode string'
}
MULTIPLE = {
'int' : '%d integers',
'float' : '%d floating point numbers',
'str' : '%d strings',
'unicode' : '%d unicode strings'
}
_OR_MORE = {
'int' : ' or more integers',
'float' : ' or more floating point numbers',
'str' : ' or more strings',
'unicode' : ' or more unicode strings'
}
class ArgparseUi(QtGui.QDialog):
def __init__(self, parser, use_scrollbars=False, remove_defaults_from_helptext=False,
helptext_default=' [default=%(default)s]', use_save_load_button=False, window_title="Make your choice",
left_label_alignment=None, ok_button_handler=None, cancel_button_handler=None, dnts_button_handler = None, parent=None):
super(ArgparseUi, self).__init__(parent)
self.setWindowTitle(window_title)
self.parser = parser
self.use_scrollbars = use_scrollbars
self.remove_defaults_from_helptext = remove_defaults_from_helptext
self.helptext_default = helptext_default
self.use_save_load_button = use_save_load_button
self.ok_button_handler = ok_button_handler # function that takes two options: the ArgparseUi instance and "parsed options"
self.dnts_button_handler = dnts_button_handler # function that takes two options: the ArgparseUi instance and "parsed options"
self.cancel_button_handler= cancel_button_handler # function that takes one option: the ArgparseUi instance
self.commandLineArgumentCreators = []
self.filename = None
self.destToWidget = {}
self.mainLayout = QtGui.QVBoxLayout(self)
self.setLayout(self.mainLayout)
self.description = QtGui.QWidget(self)
self.descriptionLayout = QtGui.QVBoxLayout(self.description)
self.description.setLayout(self.descriptionLayout)
self.options = QtGui.QWidget(self)
self.optionsLayout = QtGui.QFormLayout(self.options)
if left_label_alignment is not None:
self.optionsLayout.setLabelAlignment(QtCore.Qt.AlignLeft if left_label_alignment else QtCore.Qt.AlignRight)
self.options.setLayout(self.optionsLayout)
self.buttons = QtGui.QWidget(self)
self.buttonsLayout = QtGui.QHBoxLayout(self.buttons)
self.buttons.setLayout(self.buttonsLayout)
self.epilog = QtGui.QWidget(self)
self.epilogLayout = QtGui.QVBoxLayout(self.epilog)
self.epilog.setLayout(self.epilogLayout)
if self.use_save_load_button:
self.LoadButton = self.addButton("Load options")
if self.use_save_load_button:
self.SaveButton = self.addButton("Save options")
self.SaveAsButton = self.addButton("Save options as")
self.OkButton = self.addButton("Compile")
self.OkButton.setToolTip("Start compilation/decompilation")
self.CancelButton= self.addButton("Cancel (exit)")
self.DNTSButton = self.addButton("Convert image to DDS (DNTS)")
self.DNTSButton.setToolTip("Choose any image and have NVDXT convert it to a DXT5 DDS file for inclusion in maps. TGA files get flipped")
self.buttonsLayout.addSpacerItem(QtGui.QSpacerItem(20, 1, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum))
self.OkButton.clicked.connect(self.onOk)
self.DNTSButton.clicked.connect(self.onDNTS)
self.CancelButton.clicked.connect(self.onCancel)
if self.use_save_load_button:
self.LoadButton.clicked.connect(self.onLoad)
self.SaveButton.clicked.connect(self.onSave)
self.SaveAsButton.clicked.connect(self.onSaveAs)
self.create_ui()
self.mainLayout.addWidget(self.description)
if self.use_scrollbars:
self.scrollableArea = QtGui.QScrollArea(self)
self.scrollableArea.setWidgetResizable(True)
self.scrollableArea.setEnabled(True)
self.scrollableArea.setFrameShape(QtGui.QFrame.NoFrame)
self.scrollableArea.setWidget(self.options)
self.mainLayout.addWidget(self.scrollableArea)
self.resize(self.sizeHint())
self.update()
self.updateGeometry()
else:
self.mainLayout.addWidget(self.options)
self.mainLayout.addWidget(self.epilog)
self.mainLayout.addWidget(self.buttons)
def addButton(self, label):
self.buttonsLayout.addSpacerItem(QtGui.QSpacerItem(20, 1, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum))
b = QtGui.QPushButton(label, self.buttons)
self.buttonsLayout.addWidget(b)
return b
def sizeHint(self):
"""
helps determining the initial size of the dialog when scrollbars are requested
"""
return QtCore.QSize(self.options.sizeHint().width(), self.options.sizeHint().height() + self.OkButton.sizeHint().height())
def create_ui(self):
"""
create a dialog with the options from the parser
and an ok and cancel button
"""
self.addDescription()
self.actionLookupTable = {
type(argparse._HelpAction(None)) : self.makeHelpActionEntry,
type(argparse._VersionAction(None)) : self.makeHelpActionEntry,
type(argparse._StoreAction(None,None,None)): self.makeStoreConstEntry,
type(argparse._StoreConstAction(None,None,None)): self.makeStoreConstEntry,
type(argparse._StoreTrueAction(None, None)): self.makeStoreConstEntry,
type(argparse._StoreFalseAction(None, None)): self.makeStoreConstEntry,
type(argparse._StoreAction(None, None)) : self.makeStoreActionEntry,
type(argparse._CountAction(None, None)) : self.makeCountActionEntry,
type(argparse._AppendAction(None,None)) : self.makeAppendActionEntry,
type(argparse._AppendConstAction(None, None, None)) : self.makeCountActionEntry
}
for a in self.parser._get_optional_actions():
try:
self.actionLookupTable[type(a)](a, optional=True)
#print ("Introspected type: {0}\n".format(a))
except KeyError:
print ("Unsupported type: {0}\n".format(a))
for a in self.parser._get_positional_actions():
try:
self.actionLookupTable[type(a)](a, optional=True)
#print ("Introspected type: {0}\n".format(a))
except KeyError:
print ("Unsupported type: {0}\n".format(a))
self.addEpilog()
def addDescription(self):
"""
add a description above the ui
"""
if self.parser.description is not None:
descr = self.parser.description
else:
descr = "<b>Choose which options to include, and define their value below</b>"
label = QtGui.QLabel(descr)
self.descriptionLayout.addWidget(label)
def addEpilog(self):
"""
add an epilog text underneath the ui
"""
if self.parser.epilog is not None:
descr = self.parser.epilog
else:
descr = "<b>This options dialog is auto-generated by argparseui {0}!</b>".format(__VERSION__)
label = QtGui.QLabel(descr)
self.epilogLayout.addWidget(label)
def makeHelpString(self, a):
"""
extract help string for argparse parser and for use in the dialog
"""
helpstring = ""
if a.help:
helpstring += self.makeOptionString(a) + (" " + a.help)
elif a.option_strings:
helpstring += (" " + self.makeOptionString(a))
else:
helpstring += "positional argument"
if self.remove_defaults_from_helptext:
helpstring = helpstring.replace(self.helptext_default, '')
return '\n'.join(textwrap.wrap(helpstring, 80))
def makeOptionString(self, a):
"""
extract option strings as defined in argparse parser for use in the dialog
"""
the_options = " ".join(a.option_strings)
return the_options
def extractTypename(self, a):
"""
given an argparse action, find out what datatype it expects
and return that as a string (used to create help text)
"""
rawtypename = "{0}".format(a.type)
if 'type' in rawtypename:
return rawtypename[7:-2]
elif 'class' in rawtypename:
return rawtypename[8:-2]
return rawtypename
def makeTypeHelp(self, a):
"""
synthesize a human-readable string to describe the expected datatype
"""
typehelp = "programming error"
if a.choices:
typehelp = "" # no need to explain as options are represented in a combo box
else:
rawtypename = self.extractTypename(a)
nargs = a.nargs
if rawtypename in ['int', 'float'] and a.default is not None:
typename = ""
elif rawtypename == 'None':
typename = ""
else:
try:
intargs = int(nargs)
except ValueError:
intargs = -1
except TypeError:
intargs = -1
if nargs == '1':
typename = SINGLE.get(rawtypename, rawtypename)
elif intargs > 0:
if rawtypename in MULTIPLE:
typename = MULTIPLE[rawtypename] % intargs
else:
typename = rawtypename
elif nargs == "*":
if rawtypename in _OR_MORE:
typename = "0" + _OR_MORE[rawtypename]
else:
typename = rawtypename
elif nargs == "+":
if rawtypename in _OR_MORE:
typename = "1" + _OR_MORE[rawtypename]
else:
typename = rawtypename
elif nargs == "?":
typename = SINGLE.get(rawtypename, rawtypename)
else:
typename = SINGLE.get(rawtypename, rawtypename)
typehelp = " [" + typename + "]" if typename else ""
return typehelp
def getValidator(self, a):
"""
return a validator for a QLineEdit
"""
validator = None
if not a.choices and a.nargs in [None, '1']:
rawtypename = self.extractTypename(a)
if rawtypename == 'int':
validator = QtGui.QIntValidator
elif rawtypename == 'float':
validator = QtGui.QDoubleValidator
return validator
def disableOnClick(self, widget):
"""
function that creates a function that can be
used to disable a given widget (used to generate
clicked handlers on-the-fly)
"""
def disable(state):
widget.setEnabled(state)
return disable
def makeHelpActionEntry(self, a, optional=True):
"""
do not add the help action in the dialog
since the dialog replaces the help action
"""
pass
def registerDisplayStateInfo(self, dest, list_of_widgets):
"""
registers backward dependency from option_string to widget;
used to update ui state when loading files
"""
for w in list_of_widgets:
if dest not in self.destToWidget:
self.destToWidget[dest] = []
self.destToWidget[dest].append(w)
def makeStoreConstEntry(self, a, optional=True):
"""
make a dialog entry for a StoreTrue action
(represented as a label)
"""
helpstring = self.makeHelpString(a)
rhslabel = QtGui.QLabel("", self.options)
#lhslabel = QtGui.QLabel("lhslabel", self.options)
include = QtGui.QCheckBox(comb(helpstring,''), self.options)
if a.default:
include.setChecked(True)
self.optionsLayout.addRow(include, rhslabel)
self.registerDisplayStateInfo(a.dest, [include])
self.commandLineArgumentCreators.append(self.createFunctionToMakeStoreConstEntryCommandLine(include, a))
self.registerDisplayStateInfo(a.dest, [include])
def createFunctionToMakeStoreConstEntryCommandLine(self, include_widget, a):
"""
function to create a function that generates a command line string,
specialized for one given option (these functions are generated on-the-fly
while building the ui)
"""
def to_command_line():
if type(include_widget) == QtGui.QCheckBox:
checked = include_widget.isChecked()
else:
checked = True
if checked:
return ["{0}".format(a.option_strings[0])]
else:
return []
return to_command_line
def makeStoreActionEntry(self, a, optional=True):
"""
make a dialog entry for a StoreAction entry
(represented as combo box or line edit, depending on
choices being defined or not
"""
helpstring = self.makeHelpString(a)
typehelp = self.makeTypeHelp(a)
validator = self.getValidator(a)
if a.choices:
combobox = QtGui.QComboBox(self.options)
for c in a.choices:
combobox.addItem("{0}".format(c))
if a.default is not None:
combobox.setCurrentIndex(combobox.findText("{0}".format(a.default)))
if optional:
include = QtGui.QCheckBox(comb(helpstring, typehelp), self.options)
enabled = a.default is not None
include.setChecked(enabled)
self.disableOnClick(combobox)(enabled)
include.clicked.connect(self.disableOnClick(combobox))
self.registerDisplayStateInfo(a.dest, [include])
else:
include = QtGui.QLabel(comb(helpstring, typehelp), self.options)
self.registerDisplayStateInfo(a.dest, [combobox])
self.commandLineArgumentCreators.append(self.createFunctionToMakeStoreEntryCommandLine(include, combobox, a))
self.optionsLayout.addRow(include, combobox)
else:
lineedit = QtGui.QLineEdit(self.options)
if a.default is not None:
lineedit.setText("{0}".format(a.default))
if validator is not None:
lineedit.setValidator(validator(self))
if optional:
include = QtGui.QCheckBox(comb(helpstring, typehelp), self.options)
enabled = a.default is not None
include.setChecked(enabled)
self.disableOnClick(lineedit)(enabled)
include.clicked.connect(self.disableOnClick(lineedit))
self.registerDisplayStateInfo(a.dest, [include])
else:
include = QtGui.QLabel(comb(helpstring, typehelp), self.options)
self.registerDisplayStateInfo(a.dest, [lineedit])
self.commandLineArgumentCreators.append(self.createFunctionToMakeStoreEntryCommandLine(include, lineedit, a))
#Yay for the following example of why I suck at OO concepts:
if a.type == str:
btn = self.addButton("Select file")
btn.lineedit = lineedit
btn.include = include
def openAFile():
filename = QtGui.QFileDialog.getOpenFileName()
if filename:
btn.lineedit.setText(filename)
btn.lineedit.setEnabled(True)
btn.include.setChecked(True)
btn.clickyclicky = openAFile
btn.clicked.connect(btn.clickyclicky)
hBox = QtGui.QHBoxLayout()
hBox.addWidget(lineedit)
hBox.addWidget(btn)
self.optionsLayout.addRow(include, hBox)
#self.optionsLayout.addRow(include, lineedit)
else:
self.optionsLayout.addRow(include, lineedit)
def createFunctionToMakeStoreEntryCommandLine(self, include_widget, value_widget, argument):
"""
function to create a function that generates a command line string,
specialized for one given option (these functions are generated on-the-fly
while building the ui)
"""
def to_command_line():
if type(include_widget) == QtGui.QCheckBox:
checked = include_widget.isChecked()
else:
checked = True
if checked:
if type(value_widget) == QtGui.QLineEdit:
if argument.option_strings:
if argument.nargs == "1" or argument.nargs is None:
return ["{0}".format(argument.option_strings[0]),
"{0}".format(value_widget.text())]
else:
cmd = ["{0}".format(argument.option_strings[0])]
cmd.extend(["{0}".format(l) for l in "{0}".format(value_widget.text()).strip().split(" ")])
return cmd
else:
return ["{0}".format(value_widget.text())]
elif type(value_widget) == QtGui.QComboBox:
if argument.option_strings:
return ["{0}".format(argument.option_strings[0]),
"{0}".format(value_widget.currentText())]
else:
return ["{0}".format(value_widget.currentText())]
else:
assert False # programming error
else:
return []
return to_command_line
def makeCountActionEntry(self, a, optional=True):
"""
add an entry for a counting action
(represented by a spinbox)
"""
helpstring = self.makeHelpString(a)
spinbox = QtGui.QSpinBox(self.options)
spinbox.setRange(0, 100)
spinbox.setValue(a.nargs)
if optional:
include = QtGui.QCheckBox(helpstring, self.options)
enabled = a.default is not None
include.setChecked(enabled)
self.disableOnClick(spinbox)(enabled)
include.clicked.connect(self.disableOnClick(spinbox))
self.registerDisplayStateInfo(a.dest, [include])
else:
include = QtGui.QLabel(helpstring, self.options)
self.registerDisplayStateInfo(a.dest, [spinbox])
self.commandLineArgumentCreators.append(self.createFunctionToMakeCountActionCommandLine(include, spinbox, a))
self.optionsLayout.addRow(include, spinbox)
def createFunctionToMakeCountActionCommandLine(self, include_widget, value_widget, argument):
"""
function to create a function that generates a command line string,
specialized for one given option (these functions are generated on-the-fly
while building the ui)
"""
def to_command_line():
if type(include_widget) == QtGui.QCheckBox:
checked = include_widget.isChecked()
else:
checked = True
if checked:
if type(value_widget) == QtGui.QSpinBox:
if argument.option_strings:
return [("{0}".format(argument.option_strings[0]))]*value_widget.value()
else:
assert False # programming error
else:
assert False # programming error
else:
return []
return to_command_line
def cleanupEmptyTableRows(self, tablewidget):
"""
function to create a function that cleans up the unused columns of a tablewidget,
specialized for one given option (these functions are generated on-the-fly
while building the ui)
"""
def cleanup(row, col):
data = []
tablewidget.blockSignals(True)
for c in range(tablewidget.columnCount()):
cellText = "{0}".format(tablewidget.item(0, c).text() if tablewidget.item(0, c) else "")
if cellText:
data.append(cellText)
tablewidget.setColumnCount(len(data)+1)
for c, d in enumerate(data):
tablewidget.setItem(0, c, QtGui.QTableWidgetItem(d))
tablewidget.setItem(0, len(data), QtGui.QTableWidgetItem(""))
tablewidget.blockSignals(False)
return cleanup
def makeAppendActionEntry(self, a, optional=True):
"""
creates a table widget for appending arguments into a list
"""
helpstring = self.makeHelpString(a)
tablewidget = QtGui.QTableWidget(1, 1, self.options)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(1)
sizePolicy.setVerticalStretch(1)
sizePolicy.setHeightForWidth(tablewidget.sizePolicy().hasHeightForWidth())
tablewidget.setSizePolicy(sizePolicy)
tablewidget.cellChanged.connect(self.cleanupEmptyTableRows(tablewidget))
tablewidget.verticalHeader().hide()
tablewidget.horizontalHeader().hide()
if a.default:
# add enough rows to hold default data + one empty row
cnt = tablewidget.columnCount()
needed = len(a.default)
if needed >= cnt:
for i in range(needed-cnt+1):
tablewidget.insertColumn(tablewidget.columnCount())
for column, d in enumerate(a.default):
tablewidget.setItem(0, column, QtGui.QTableWidgetItem(d))
if optional:
include = QtGui.QCheckBox(helpstring, self.options)
enabled = a.default is not None
include.setChecked(enabled)
self.disableOnClick(tablewidget)(enabled)
include.clicked.connect(self.disableOnClick(tablewidget))
self.registerDisplayStateInfo(a.dest, [include])
else:
include = QtGui.QLabel(helpstring, self.options)
self.registerDisplayStateInfo(a.dest, [tablewidget])
self.commandLineArgumentCreators.append(self.createFunctionToMakeAppendCommandLine(include, tablewidget, a))
self.optionsLayout.addRow(include, tablewidget)
def createFunctionToMakeAppendCommandLine(self, include_widget, tablewidget, argument):
"""
function to create a function that generates a command line string,
specialized for one given option (these functions are generated on-the-fly
while building the ui)
"""
def to_command_line():
data = []
if type(include_widget) == QtGui.QCheckBox:
checked = include_widget.isChecked()
else:
checked = True
if checked:
if type(tablewidget) == QtGui.QTableWidget:
if argument.option_strings:
for c in range(tablewidget.columnCount()):
cellText = "{0}".format(tablewidget.item(0, c).text() if tablewidget.item(0, c) else "")
if cellText:
data.extend([argument.option_strings[0], cellText])
else:
assert False # programming error
else:
assert False # programming error
else:
return []
return data
return to_command_line
def makeCommandLine(self):
"""
construct the command line from the ui state
"""
commandline = []
for c in self.commandLineArgumentCreators:
commandline.extend(c())
return commandline
def hasOne(self, list_of_possibilities, cmdline):
"""
True if an element of list_of_possibilities occurs in cmdline
"""
for p in list_of_possibilities:
if p in cmdline:
return True
return False
def validateMutualExclusiveOptions(self):
"""
check if mutex options specified
"""
cmdline = " ".join(self.makeCommandLine())
for m in self.parser._mutually_exclusive_groups:
foundOne = False
offending_options = []
for a in m._group_actions:
present = self.hasOne(a.option_strings, cmdline)
if present and foundOne:
offending_options.append(a.option_strings)
return False, offending_options
elif present:
offending_options.append(a.option_strings)
foundOne = True
return True, []
def onOk(self):
"""
handle ok button pressed
"""
validate, offensive_options = self.validateMutualExclusiveOptions()
if validate:
if self.ok_button_handler is None:
return
self.accept()
else:
self.ok_button_handler(self)
else:
mutexes = "\n".join([",".join(o) for o in offensive_options])
QtGui.QMessageBox.question(self, 'Validation error', "The following options are mutually exclusive:\n{0}".format(mutexes), QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
def onDNTS(self):
"""
handle DNTS button pressed
"""
filename = QtGui.QFileDialog.getOpenFileName() # has / as pathsep
if filename:
filename = str(filename)
outputfilename = filename.rpartition('/')[2].rpartition('.')[0]+'.dds'
flip = ''
if filename.lower.endswith('.tga'):
flip = " -flip"
nvdxtcommand = 'nvdxt.exe -file "%s" -dxt5 -Sinc -quality_highest -output "%s"'%(filename,outputfilename) + flip
print("DNTS Conversion:",nvdxtcommand)
os.system(nvdxtcommand)
print("Done")
def onCancel(self):
"""
handle cancel button pressed
"""
if self.cancel_button_handler is None:
self.reject()
else:
self.cancel_button_handler(self)
def resetAllWidgets(self, argparser):
helper = argparse.ArgumentParser(add_help=False, parents=[self.parser], fromfile_prefix_chars='@')
# make sure default values don't get enabled
for a in helper._get_optional_actions():
a.default = None
for a in helper._get_positional_actions():
a.default = None
# make sure all checkboxes that were already enabled are disabled first
for a in self.destToWidget:
for w in self.destToWidget[a]:
if type(w) == QtGui.QCheckBox:
w.setChecked(False)
w.clicked.emit(False)
elif type(w) == QtGui.QTableWidget:
w.setColumnCount(1)
w.setItem(0, 0, QtGui.QTableWidgetItem(""))
def onLoad(self):
"""
handle load button pressed
"""
filename = QtGui.QFileDialog.getOpenFileName()
if filename:
helper = argparse.ArgumentParser(add_help=False, parents=[self.parser], fromfile_prefix_chars='@')
self.resetAllWidgets(helper)
result = helper.parse_args(['@{0}'.format(filename)])
for a in helper._get_optional_actions():
self.copyActionValuesToUi(a,result)
for a in helper._get_positional_actions():
self.copyActionValuesToUi(a,result)
self.filename = filename
def copyActionValuesToUi(self, a, result):
"""
function to update ui after loading command line arguments from file
a = argparse action
result = argparse parse result
"""
if a.dest in self.destToWidget:
for w in self.destToWidget[a.dest]:
data = result.__getattribute__(a.dest)
if type(w) == QtGui.QCheckBox:
if data is not None:
if type(data) == bool:
w.setChecked(data)
w.clicked.emit(data)
else:
w.setChecked(True)
w.clicked.emit(True)
elif type(w) == QtGui.QLineEdit:
if data is not None:
if type(data) == type([]):
w.setText(" ".join(["{0}".format(d) for d in data]))
else:
w.setText("{0}".format(data))
elif type(w) == QtGui.QSpinBox:
if data is not None:
w.setValue(int("{0}".format(data)))
elif type(w) == QtGui.QComboBox:
if data is not None:
w.setCurrentIndex(w.findText("{0}".format(data)))
elif type(w) == QtGui.QTableWidget:
#clear existing defaults first
w.setColumnCount(1)
w.setItem(0, 0, QtGui.QTableWidgetItem(""))
cnt = w.columnCount()
if data is not None:
needed = len(data)
if needed >= cnt:
for i in range(needed-cnt+1):
w.insertColumn(w.columnCount())
for column, d in enumerate(data):
w.setItem(0, int("{0}".format(column)), QtGui.QTableWidgetItem(d))
def onSave(self):
"""
what to do when the save button is clicked
"""
if not self.filename:
self.onSaveAs()
else:
try:
with open(self.filename, "w") as f:
c = self.makeCommandLine()
for line in c:
f.write(line+"\n")
except IOError:
import os.path
QtGui.QMessageBox.critical(self,
"Critical",
"Couldn't write to file {0}".format(os.path.abspath(self.filename)))
def onSaveAs(self):
"""
what to do when the save as button is clicked
"""
filename = QtGui.QFileDialog.getSaveFileName()
if filename:
self.filename = filename
self.onSave()
def parse_args(self):
"""
method to ensure that the ui looks and feels identical to the argparse parser
"""
cmdline = self.makeCommandLine()
return self.parser.parse_args(cmdline)
if __name__ == "__main__":
import sys
from PyQt4 import QtGui
# EXPERIMENT USING BASIC PARSER
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--make-argument-true", help="optional boolean argument", action="store_true")
parser.add_argument("-o","--make-other-argument-true", help="optional boolean argument 2", action="store_true", default=True)
parser.add_argument("-n","--number", help="an optional number", type=int)
parser.add_argument("-r","--restricted-number", help="one of a few possible numbers", type=int, choices=[1,2,3], default=2)
parser.add_argument("-c", "--counting-argument", help="counting #occurrences", action="count")
parser.add_argument("-d", "--default-value-argument", help="default value argument with a very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very long description", type=float, default="3.14")
parser.add_argument("-a", "--append-args", help="append arguments to list", type=str, action="append", default=["dish", "dash"])
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
parser.add_argument('--foo', type=int, nargs='+')
parser.add_argument('--bar', type=int, nargs=2, metavar=('bar', 'baz'))
app = QtGui.QApplication(sys.argv)
a = ArgparseUi(parser, left_label_alignment=True, use_scrollbars=True, use_save_load_button=True)
a.show()
app.exec_()
print ("Ok" if a.result() == 1 else "Cancel")
if a.result() == 1: # Ok pressed
parsed_args = a.parse_args()
else:
parsed_args = None
print (parsed_args)
# EXPERIMENT USING PARENT PARSER
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument('--parent', type=int)
foo_parser = argparse.ArgumentParser(parents=[parent_parser])
foo_parser.add_argument('foo')
foo_parser.description = "Come on! Let's bar that foo!!"
foo_parser.epilog = "And this is how you bar a foo!"
a = ArgparseUi(foo_parser, use_scrollbars=False, use_save_load_button=True, window_title="Simple config")
a.show()
app.exec_()
print ("Ok" if a.result() == 1 else "Cancel")
if a.result() == 1: # Ok pressed
parsed_args = a.parse_args()
else:
parsed_args = None
print (parsed_args)