-
Notifications
You must be signed in to change notification settings - Fork 0
/
pack_nuke_gui.py
1067 lines (877 loc) · 38.5 KB
/
pack_nuke_gui.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
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
# This Python file uses the following encoding: utf-8
import csv
import datetime
from functools import partial
import json
import logging
import os
from pathlib import Path
import platform
import re
import shutil
import subprocess
import sys
import time
from typing import Any, List, Dict, Union
from PySide6 import QtWidgets, QtCore, QtGui
from ui_pack_nuke import *
from ui_images_rc import *
import pprint
class TreeItem:
"""A Json item corresponding to a line in QTreeView"""
def __init__(self, parent: "TreeItem" = None):
self._parent = parent
self._key = ""
self._value = ""
self._value_type = None
self._children = []
def appendChild(self, item: "TreeItem"):
"""Add item as a child"""
self._children.append(item)
def child(self, row: int) -> "TreeItem":
"""Return the child of the current item from the given row"""
return self._children[row]
def parent(self) -> "TreeItem":
"""Return the parent of the current item"""
return self._parent
def childCount(self) -> int:
"""Return the number of children of the current item"""
return len(self._children)
def row(self) -> int:
"""Return the row where the current item occupies in the parent"""
return self._parent._children.index(self) if self._parent else 0
@property
def key(self) -> str:
"""Return the key name"""
return self._key
@key.setter
def key(self, key: str):
"""Set key name of the current item"""
self._key = key
@property
def value(self) -> str:
"""Return the value name of the current item"""
return self._value
@value.setter
def value(self, value: str):
"""Set value name of the current item"""
self._value = value
@property
def value_type(self):
"""Return the python type of the item's value."""
return self._value_type
@value_type.setter
def value_type(self, value):
"""Set the python type of the item's value."""
self._value_type = value
@classmethod
def load(
cls, value: Union[List, Dict], parent: "TreeItem" = None, sort=True
) -> "TreeItem":
"""Create a 'root' TreeItem from a nested list or a nested dictonary
Examples:
with open("file.json") as file:
data = json.dump(file)
root = TreeItem.load(data)
This method is a recursive function that calls itself.
Returns:
TreeItem: TreeItem
"""
rootItem = TreeItem(parent)
rootItem.key = "root"
if isinstance(value, dict):
items = sorted(value.items()) if sort else value.items()
for key, value in items:
child = cls.load(value, rootItem)
child.key = key
child.value_type = type(value)
rootItem.appendChild(child)
elif isinstance(value, list):
for index, value in enumerate(value):
child = cls.load(value, rootItem)
child.key = index
child.value_type = type(value)
rootItem.appendChild(child)
else:
rootItem.value = value
rootItem.value_type = type(value)
return rootItem
class JsonModel(QtCore.QAbstractItemModel):
""" An editable model of Json data """
def __init__(self, parent: QObject = None):
super().__init__(parent)
self._rootItem = TreeItem()
self._headers = ("key", "value")
def clear(self):
""" Clear data from the model """
self.load({})
def load(self, document: dict):
"""Load model from a nested dictionary returned by json.loads()
Arguments:
document (dict): JSON-compatible dictionary
"""
assert isinstance(
document, (dict, list, tuple)
), "`document` must be of dict, list or tuple, " f"not {type(document)}"
self.beginResetModel()
self._rootItem = TreeItem.load(document)
self._rootItem.value_type = type(document)
self.endResetModel()
return True
def data(self, index: QtCore.QModelIndex, role: QtCore.Qt.ItemDataRole) -> Any:
"""Override from QAbstractItemModel
Return data from a json item according index and role
"""
if not index.isValid():
return None
item = index.internalPointer()
if role == QtCore.Qt.DisplayRole:
if index.column() == 0:
return item.key
if index.column() == 1:
return item.value
elif role == QtCore.Qt.EditRole:
if index.column() == 1:
return item.value
def setData(self, index: QtCore.QModelIndex, value: Any, role: QtCore.Qt.ItemDataRole):
"""Override from QAbstractItemModel
Set json item according index and role
Args:
index (QModelIndex)
value (Any)
role (Qt.ItemDataRole)
"""
if role == QtCore.Qt.EditRole:
if index.column() == 1:
item = index.internalPointer()
item.value = str(value)
self.dataChanged.emit(index, index, [QtCore.Qt.EditRole])
return True
return False
def headerData(
self, section: int, orientation: QtCore.Qt.Orientation, role: QtCore.Qt.ItemDataRole
):
"""Override from QAbstractItemModel
For the JsonModel, it returns only data for columns (orientation = Horizontal)
"""
if role != QtCore.Qt.DisplayRole:
return None
if orientation == QtCore.Qt.Horizontal:
return self._headers[section]
def index(self, row: int, column: int, parent=QtCore.QModelIndex()) -> QtCore.QModelIndex:
"""Override from QAbstractItemModel
Return index according row, column and parent
"""
if not self.hasIndex(row, column, parent):
return QtCore.QModelIndex()
if not parent.isValid():
parentItem = self._rootItem
else:
parentItem = parent.internalPointer()
childItem = parentItem.child(row)
if childItem:
return self.createIndex(row, column, childItem)
else:
return QtCore.QModelIndex()
def parent(self, index: QtCore.QModelIndex) -> QtCore.QModelIndex:
"""Override from QAbstractItemModel
Return parent index of index
"""
if not index.isValid():
return QtCore.QModelIndex()
childItem = index.internalPointer()
parentItem = childItem.parent()
if parentItem == self._rootItem:
return QtCore.QModelIndex()
return self.createIndex(parentItem.row(), 0, parentItem)
def rowCount(self, parent=QtCore.QModelIndex()):
"""Override from QAbstractItemModel
Return row count from parent index
"""
if parent.column() > 0:
return 0
if not parent.isValid():
parentItem = self._rootItem
else:
parentItem = parent.internalPointer()
return parentItem.childCount()
def columnCount(self, parent=QtCore.QModelIndex()):
"""Override from QAbstractItemModel
Return column number. For the model, it always return 2 columns
"""
return 2
def flags(self, index: QtCore.QModelIndex) -> QtCore.Qt.ItemFlags:
"""Override from QAbstractItemModel
Return flags of index
"""
flags = super(JsonModel, self).flags(index)
if index.column() == 1:
return QtCore.Qt.ItemIsEditable | flags
else:
return flags
def to_json(self, item=None):
if item is None:
item = self._rootItem
nchild = item.childCount()
if item.value_type is dict:
document = {}
for i in range(nchild):
ch = item.child(i)
document[ch.key] = self.to_json(ch)
return document
elif item.value_type == list:
document = []
for i in range(nchild):
ch = item.child(i)
document.append(self.to_json(ch))
return document
else:
return item.value
class MainWindow(QtWidgets.QMainWindow, Ui_pack_gui):
def __init__(self, parent = None):
super().__init__()
self.place_list = None
self.ui = Ui_pack_gui()
self.ui.setupUi(self)
ui_images_rc.qInitResources()
#self.resize(1400, 300)
# data structs
self.found_versions = None
self.filtered_versions = None
# from the gui
self.search_root = None
self.search_contains = None
self.search_for = None
self.search_version_regex = None
self.regex_compiled = None
self.versions_get_first = None
self.versions_first = None
self.versions_get_last = None
self.versions_last = None
self.settings_file = None
self.settings_json = {}
self.place_source_default = None
self.column_titles = ['Path', 'Tokens', 'Open', 'Select']
self.user_stopped = False
self.place_list = []
self.place_source = ''
self.place_target = ''
self.anatomy = {}
if getattr(sys, 'frozen', False):
# If the application is run as a bundle, the PyInstaller bootloader
# extends the sys module by a flag frozen=True and sets the app
# path into variable _MEIPASS'.
#self.application_path = sys._MEIPASS.replace('\\', '/')
self.application_path = os.path.dirname(
sys.executable).replace('\\', '/')
else:
self.application_path = os.path.dirname(
os.path.abspath(__file__)).replace('\\', '/')
# settings
prefs_pth = self.application_path + '/settings.ini'
print('-> init prefs')
print('-> prefs: ' + prefs_pth)
self.settings = QtCore.QSettings(prefs_pth, QtCore.QSettings.IniFormat)
self.settings.setFallbacksEnabled(False) # File only
try:
self.settings_read()
except:
print('-> Failed to read preferences.')
try:
self.settings_set_defaults()
self.settings_write()
self.settings_read()
except:
print('-> Failed to write preferences.')
# signals
# path
self.ui.search_root.textChanged.connect(self.search_changed)
self.ui.search_root_browse.clicked.connect(self.get_folder)
# search
self.ui.search_contains.textChanged.connect(self.search_changed)
self.ui.search_for.textChanged.connect(self.search_changed)
# versions
self.ui.search_version_regex.textChanged.connect(self.versions_changed)
self.ui.versions_get_first.clicked.connect(self.versions_changed)
self.ui.versions_get_last.clicked.connect(self.versions_changed)
self.ui.versions_first.valueChanged.connect(self.versions_changed)
self.ui.versions_last.valueChanged.connect(self.versions_changed)
# mark all/none
self.ui.mark_all.clicked.connect(self.select_all)
self.ui.mark_none.clicked.connect(self.select_none)
# places change
self.ui.place_source.currentIndexChanged.connect(self.place_change)
self.ui.place_target.currentIndexChanged.connect(self.place_change)
# job name
self.ui.job_name.textChanged.connect(self._validate_job_name)
# job folder browse
self.ui.job_folder_browse.clicked.connect(self.get_job_folder)
# settings json path
self.ui.settings_file.textChanged.connect(self.display_json)
# go
self.ui.deadline.clicked.connect(self.go)
# quit
exit = QtGui.QAction(self)
self.stop_short = QtGui.QShortcut(QtGui.QKeySequence('Ctrl+.'), self)
self.stop_short.activated.connect(self.user_stop)
# show settings json
self.model = JsonModel()
self.ui.settings.setModel(self.model)
self.display_json()
def settings_set_defaults(self):
self.settings.setValue('search_root', 'C:/projects/ProjectMeridian')
self.settings.setValue('search_contains', '/work/comp/')
self.settings.setValue('search_for', '*_comp_v???.nk')
self.settings.setValue('search_version_regex', '.*_v(\d{3}).nk')
self.settings.setValue('versions_get_first', False)
self.settings.setValue('versions_first', 1)
self.settings.setValue('versions_get_last', True)
self.settings.setValue('versions_last', 1)
self.settings.setValue('settings_file', '')
self.settings.setValue('place_source_default', 'studio')
def settings_write(self):
"""
Write display settings to file
"""
self.settings.setValue('search_root', self.ui.search_root.displayText())
self.settings.setValue('search_contains', self.ui.search_contains.displayText())
self.settings.setValue('search_for', self.ui.search_for.displayText())
self.settings.setValue('search_version_regex', self.ui.search_version_regex.displayText())
self.settings.setValue('versions_get_first', int(self.ui.versions_get_first.isChecked()))
self.settings.setValue('versions_first', int(self.ui.versions_first.value()))
self.settings.setValue('versions_get_last', int(self.ui.versions_get_last.isChecked()))
self.settings.setValue('versions_last', int(self.ui.versions_last.value()))
self.settings.setValue('settings_file', self.ui.settings_file.displayText())
self.settings.setValue('place_source_default', self.ui.place_source_default.displayText())
def settings_read(self):
"""
Read settings from file
"""
self.ui.search_root.blockSignals(True)
self.ui.search_root.setText(self.settings.value('search_root'))
self.ui.search_root.blockSignals(False)
self.search_root = str(self.ui.search_root.displayText()).replace('\\', '/')
self.ui.search_contains.blockSignals(True)
self.ui.search_contains.setText(self.settings.value('search_contains'))
self.ui.search_contains.blockSignals(False)
self.search_contains = str(self.ui.search_contains.displayText()).replace('\\', '/')
self.ui.search_for.blockSignals(True)
self.ui.search_for.setText(self.settings.value('search_for'))
self.ui.search_for.blockSignals(False)
self.search_for = str(self.ui.search_for.displayText()).replace('\\', '/')
self.ui.search_version_regex.blockSignals(True)
self.ui.search_version_regex.setText(self.settings.value('search_version_regex'))
self.ui.search_version_regex.blockSignals(False)
self.search_version_regex = str(self.ui.search_version_regex.displayText())
self.ui.versions_get_first.blockSignals(True)
self.ui.versions_get_first.setChecked(int(self.settings.value('versions_get_first')))
self.ui.versions_get_first.blockSignals(False)
self.versions_get_first = int(self.ui.versions_get_first.isChecked())
self.ui.versions_first.blockSignals(True)
self.ui.versions_first.setValue(int(self.settings.value('versions_first')))
self.ui.versions_first.blockSignals(False)
self.versions_first = int(self.ui.versions_first.value())
self.ui.versions_get_last.blockSignals(True)
self.ui.versions_get_last.setChecked(int(self.settings.value('versions_get_last')))
self.ui.versions_get_last.blockSignals(False)
self.versions_get_last = int(self.ui.versions_get_last.isChecked())
self.ui.versions_last.blockSignals(True)
self.ui.versions_last.setValue(int(self.settings.value('versions_last')))
self.ui.versions_last.blockSignals(False)
self.versions_last = int(self.ui.versions_last.value())
self.ui.settings_file.blockSignals(True)
self.ui.settings_file.setText(self.settings.value('settings_file'))
self.ui.settings_file.blockSignals(False)
self.settings_file = str(self.ui.settings_file.toPlainText())
self.ui.place_source_default.blockSignals(True)
self.ui.place_source_default.setText(self.settings.value('place_source_default'))
self.ui.place_source_default.blockSignals(False)
self.place_source_default = str(self.ui.place_source_default.toPlainText())
def closeEvent(self, event):
self.settings_write()
event.accept()
def get_folder(self):
file_name = QtWidgets.QFileDialog.getExistingDirectory(
self,
"Select Starting Folder",
str(self.ui.search_root.displayText())
)
fldr = os.path.realpath(file_name).replace('\\', '/')
self.ui.search_root.setText(fldr)
self.search_changed()
def get_job_folder(self):
file_name = QtWidgets.QFileDialog.getExistingDirectory(
self,
"Select Job Folder",
str(self.ui.job_folder.displayText())
)
self.ui.job_folder.setText(os.path.realpath(file_name).replace('\\', '/'))
def _get_search_gui(self):
self.search_root = str(self.ui.search_root.displayText()).replace('\\', '/')
self.search_contains = str(self.ui.search_contains.displayText()).replace('\\', '/')
self.search_for = str(self.ui.search_for.displayText()).replace('\\', '/')
self.search_version_regex = str(self.ui.search_version_regex.displayText())
self.versions_get_first = int(self.ui.versions_get_first.isChecked())
self.versions_first = int(self.ui.versions_first.value())
self.versions_get_last = int(self.ui.versions_get_last.isChecked())
self.versions_last = int(self.ui.versions_last.value())
def search_changed(self):
self._get_search_gui()
# get versions
self.find_versions()
self.filter_versions()
self.display_table()
def versions_changed(self):
self._get_search_gui()
# get versions
self.filter_versions()
self.display_table()
def explore_shot_from_table(self, row, column):
self.explore(self.filtered_versions[row]['full'])
def explore(self, path):
platform = 'win'
if sys.platform.startswith('darwin'):
platform = 'mac'
elif str(os.name).startswith('posix'):
platform = 'nix'
if path and path != '' and os.path.exists(path):
if platform == 'win':
if os.path.isdir(path):
path = path + '/'
subprocess.Popen('explorer /root, \"' + path.replace('/', '\\') + '\"')
if platform == 'mac':
subprocess.call(['open', "-R", path])
if platform == 'nix':
subprocess.call(('xdg-open', path))
def find_versions(self):
lst = {}
for path in Path(self.search_root).rglob(self.search_for):
_pth = str(path).replace('\\', '/')
if self.search_contains in _pth:
try:
_split = _pth.split('/')
if _split:
_last = str(_split[-1])
_start = str('/'.join(_split[:-1]))
if lst.get(_start):
# add to the list of subfolders
lst[_start].append(_last)
else:
# first subfolder
lst[_start] = [_last]
except:
pass
# sort versions
for k, v in lst.items():
vs = sorted(v)
lst[k] = vs
self.found_versions = lst
def match_regex(self, filter, source, ):
"""
Checks if the filter matches the source by regex
"""
result = None
try:
_re = re.compile(filter['search'])
except:
return None
if filter['replace'] and filter['replace'] != '':
try:
result = _re.match(source).expand(filter['replace'])
except:
return None
else:
m = re.search(filter['search'], source)
if m is not None:
try:
result = m.group(1)
except:
result = m.group(0)
if result is not None:
if filter['lowercase']:
result = result.lower()
if filter['uppercase']:
result = result.upper()
return result
def get_script_path_tags(self, full_path):
if self.settings_json is None:
return {}
place_source = self.ui.place_source.currentText()
if not self.settings_json['places'][place_source]['use_script_path_tags']:
return {}
tags_list = self.settings_json['places'][place_source]['script_path_tags']
if tags_list is None or len(tags_list) == 0:
return {}
full_path = full_path.replace('\\', '/')
file_name = os.path.basename(full_path)
tokens = {}
for one_filter in tags_list:
match = None
if one_filter['source'] == 'File Name':
match = self.match_regex(one_filter, source=file_name)
elif one_filter['source'] == 'File Path':
match = self.match_regex(one_filter, source=full_path)
if match is not None:
tokens[one_filter['name']] = match
return tokens
def filter_versions(self):
"""
This assumes the versions of the Nuke script are in one folder
"""
self.filtered_versions = []
try:
self.regex_compiled = re.compile(self.search_version_regex)
regex_valid = True
except re.error:
regex_valid = False
logger.error("Version Regex Error")
return
if self.found_versions is not None:
for one_path, file_list in self.found_versions.items():
one_folder = []
for one_file in file_list:
my_dict = {}
m = self.regex_compiled.search(one_file)
if m:
try:
# if user made a group
version = m.group(1)
# get merged anatomy and script_path_tags pairs
tokens = self.get_script_path_tags(one_path + '/' + one_file)
t = ''
for k, v in tokens.items():
t += f"{k}:{v};"
for k, v in self.anatomy.items():
t += f"{k}:{v};"
my_dict = {
'path': one_path,
'file': one_file,
'version': version,
'full': one_path + '/' + one_file,
'apply': True,
'tokens': t
}
one_folder.append(my_dict)
except:
pass
#sort folder
folder_sorted = sorted(one_folder, key=lambda i: i['version'])
max_versions = len(folder_sorted)
if bool(self.versions_get_first):
_first = self.versions_first
if max_versions < self.versions_first:
_first = max_versions
for i in range(0, _first):
self.filtered_versions.append(folder_sorted[i])
if bool(self.versions_get_last):
_last = self.versions_last
if max_versions < self.versions_last:
_last = max_versions
for i in range(-1 * _last, 0):
self.filtered_versions.append(folder_sorted[i])
if not bool(self.versions_get_first) and (not bool(self.versions_get_last)):
# add all
for one in folder_sorted:
self.filtered_versions.append(one)
def _select_all_none(self, is_selected=True):
for one_row in self.filtered_versions:
one_row['apply'] = is_selected
self.display_table()
def select_all(self):
self._select_all_none(True)
def select_none(self):
self._select_all_none(False)
def handle_apply(self, row, column):
_apply = bool(self.filtered_versions[row]['apply'])
if _apply:
self.filtered_versions[row]['apply'] = False
else:
self.filtered_versions[row]['apply'] = True
#self.display_table()
def my_time(self):
"""
Used for timestamping packages
Stores UTC time, and adds UTC offset for user comfort
Offset assumes plus sign, unless - present
"""
# get utc time YYMMDD-HHMM_
utc = datetime.datetime.now(datetime.timezone.utc).strftime('%y%m%d_%H%M_')
# get utc to local time offset, this is just for user
offset = datetime.datetime.now(datetime.timezone.utc).astimezone().strftime('%z').replace('+', '')
return utc + offset
def _fill_job_path(self):
class Default(dict):
def __missing__(self, key):
return key
if self.settings_json is None or self.settings_json == {}:
return None
if self.place_list is None or self.place_list == []:
return None
place_source = self.ui.place_source.currentText()
place_target = self.ui.place_target.currentText()
self.settings_json['places'][place_source]['is_source'] = True
self.settings_json['places'][place_source]['is_target'] = False
self.settings_json['places'][place_target]['is_source'] = False
self.settings_json['places'][place_target]['is_target'] = True
self.anatomy = {
'timestamp': self.my_time(),
'place_source': place_source,
'place_target': place_target,
}
self.anatomy.update(self.settings_json['places'][place_source]['anatomy'])
# job root
self.ui.job_folder.setText(self.settings_json['job']['job_root'].format_map(Default(self.anatomy)).replace("\\", "/"))
# job folder
self.ui.job_name.setText(self.settings_json['job']['job_name_default'].format_map(Default(self.anatomy)).replace("\\", "/"))
def _validate_job_name(self):
if not re.match(self.ui.job_template.displayText(), self.ui.job_name.displayText()):
logger.error("Make sure job name matches convention.")
return False
else:
logger.info("Job name matches convention.")
return True
def place_change(self):
place_source = self.ui.place_source.currentText()
place_target = self.ui.place_target.currentText()
if place_source == place_target:
logging.error("Source and target places have to be different")
else:
self._fill_job_path()
def display_json(self):
self.settings_file = str(self.ui.settings_file.displayText()).replace('\\', '/')
if self.settings_file is not None and self.settings_file != '':
if Path(self.settings_file).is_file():
with open(self.settings_file) as settings_file:
self.settings_json = json.load(settings_file)
self.model.load(self.settings_json)
self.ui.settings.show()
self.ui.settings.header().setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
#self.ui.settings.setAlternatingRowColors(True)
if self.settings_json is not None and self.settings_json != {}:
self.ui.job_template.setText(self.settings_json['job']['job_name_check'])
self.ui.job_template.setText(self.settings_json['job']['job_name_check'])
self.place_list = list(self.settings_json['places'].keys())
if len(self.place_list) >= 2:
self.ui.place_source.blockSignals(True)
self.ui.place_source.clear()
self.ui.place_source.addItems(self.place_list)
self.ui.place_target.blockSignals(True)
self.ui.place_target.clear()
self.ui.place_target.addItems(self.place_list)
try:
preferred_source = self.ui.place_source_default.displayText()
if preferred_source in self.place_list:
i = self.place_list.index(preferred_source)
self.ui.place_source.setCurrentIndex(i)
# set target to close place that is not source
if i == 0:
self.ui.place_target.setCurrentIndex(1)
else:
self.ui.place_target.setCurrentIndex(0)
else:
self.ui.place_source.setCurrentIndex(0)
self.ui.place_target.setCurrentIndex(1)
except:
logger.error("Failed to set places dropbox")
self.ui.place_source.blockSignals(False)
self.ui.place_target.blockSignals(False)
self._fill_job_path()
else:
logger.error(f"Found {len(self.place_list)} places defined in settings json. At least two are required.")
def display_table(self):
# display table
self.ui.tableWidget.clear()
self.ui.tableWidget.setColumnCount(0)
self.ui.tableWidget.setRowCount(0)
if self.filtered_versions and self.column_titles:
self.ui.tableWidget.setSortingEnabled(False)
self.ui.tableWidget.setColumnCount(len(self.column_titles))
self.ui.tableWidget.setHorizontalHeaderLabels(self.column_titles)
self.ui.tableWidget.setRowCount(len(self.filtered_versions))
for row, line in enumerate(self.filtered_versions):
# set row color by check list
color = 'white'
# for every column in a row
for column_number, one_column in enumerate(self.column_titles):
my_title = str(one_column).lstrip().rstrip().lower()
if my_title == 'open':
btn = QtWidgets.QPushButton('Open', self)
btn.setIcon(QtGui.QIcon(":/images/system-search.png"))
index = QtCore.QPersistentModelIndex(self.ui.tableWidget.model().index(row, column_number))
# partial instead of lambda!
btn.clicked.connect(partial(self.explore_shot_from_table, index.row(), index.column()))
self.ui.tableWidget.setCellWidget(row, column_number, btn)
elif my_title == 'select':
chbx = QtWidgets.QCheckBox('Select ', self)
chbx.setChecked(line['apply'])
index = QtCore.QPersistentModelIndex(self.ui.tableWidget.model().index(row, column_number))
# partial instead of lambda!
chbx.clicked.connect(partial(self.handle_apply, index.row(), index.column()))
self.ui.tableWidget.setCellWidget(row, column_number, chbx)
elif my_title == 'path':
self.ui.tableWidget.setItem(row, column_number,
QtWidgets.QTableWidgetItem(
str(line['full'])))
elif my_title == 'tokens':
self.ui.tableWidget.setItem(row, column_number,
QtWidgets.QTableWidgetItem(
str(line['tokens'])))
else:
logging.error("Can't display table row")
# colorize cell
itm = self.ui.tableWidget.item(row, column_number)
if itm:
if color == 'green':
itm.setBackground(QtGui.QColor('darkgreen'))
elif color == 'orange':
itm.setBackground(QtGui.QColor('sienna'))
elif color == 'red':
itm.setBackground(QtGui.QColor('maroon'))
elif color == 'purple':
itm.setBackground(QtGui.QColor('purple'))
else:
# white
itm.setBackground(QtGui.QColor("#4d4d4d"))
self.ui.tableWidget.setSortingEnabled(True)
self.ui.tableWidget.resizeColumnsToContents()
self.ui.tableWidget.resizeRowsToContents()
def apply(self, nuke_file):
pass
def external_execute(self, args):
kwargs = {
"stdout": subprocess.PIPE,
"stderr": subprocess.PIPE,
}
if platform.system().lower() == "windows":
kwargs["creationflags"] = (
subprocess.CREATE_NEW_PROCESS_GROUP
| getattr(subprocess, "DETACHED_PROCESS", 0)
| getattr(subprocess, "CREATE_NO_WINDOW", 0)
)
popen = subprocess.Popen(args, **kwargs)
popen_stdout, popen_stderr = popen.communicate()
if popen_stdout:
pass
if popen_stderr:
pass
def go(self):
def make_dir(dir):
try:
os.makedirs(dir)
except OSError:
pass
return os.path.isdir(dir)
_job_path = self.ui.job_folder.displayText() + '/' + self.ui.job_name.displayText()
self.settings_json['job']['path'] = _job_path
self.settings_json['job']['name'] = self.ui.job_name.displayText()
self.settings_json['job']['timestamp'] = self.anatomy['timestamp']
r = make_dir(_job_path)
if not r:
logging.error(f"Can't create directory {_job_path}")
pack_dir = _job_path + '/_pack_nuke'
r = make_dir(pack_dir)
if not r:
logging.error(f"Can't create directory {pack_dir}")
# Write CSV file with all Nuke scripts
_csv = pack_dir + '/nuke_files.csv'
titles = ['Id', 'Name', 'Full Path', 'Tokens', 'Package', 'Source', 'Target']
total = 0
selected_versions = []
with open(_csv, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(titles)
for one in self.filtered_versions:
if one['apply']:
id = str(total).zfill(4) + '_' + one['file'].rstrip('.nk')
one_row = [
id,
one['file'],
one['full'],
one['tokens'],
self.ui.job_name.displayText(),
self.ui.place_source.currentText(),
self.ui.place_target.currentText(),
]
writer.writerow(one_row)
selected_versions.append(one_row)
total += 1
_set = pack_dir + '/settings.json'
with open(_set, 'w') as json_file:
json.dump(self.settings_json, json_file)
# now send selected versions to deadline
nuke_exe = self.settings_json['nuke'].get(platform.system())
if nuke_exe is None or not os.path.exists(nuke_exe):
logging.error(f"Can't find Nuke executable: {nuke_exe}")
deadline_exe = self.settings_json['deadline'].get(platform.system())
if deadline_exe is None or not os.path.exists(deadline_exe):
logging.error(f"Can't find Deadline executable: {deadline_exe}")
deadline_py = self.settings_json['deadline_python'].get(platform.system())
if deadline_py is None or not os.path.exists(deadline_py):
logging.error(f"Can't find Deadline python file: {deadline_py}")
_params = self.settings_json['deadline_job']
params_1 = [
deadline_exe,
'-SubmitCommandLineJob',
'-executable',
nuke_exe,
'-pool',
_params['pool'],