-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathmonkeyprintGuiHelper.py
2088 lines (1672 loc) · 69.5 KB
/
monkeyprintGuiHelper.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
# -*- coding: latin-1 -*-
#
# Copyright (c) 2015-2016 Paul Bomke
# Distributed under the GNU GPL v2.
#
# This file is part of monkeyprint.
#
# monkeyprint 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.
#
# monkeyprint 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 have received a copy of the GNU General Public License
# along with monkeyprint. If not, see <http://www.gnu.org/licenses/>.
import PyQt4
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt
import sys
import time
import os.path
import shutil
import numpy
import random
from PIL import Image
import inspect # Provides methdos to check arguments of a function.
import monkeyprintImageHandling as imageHandling
import monkeyprintPrintProcess
import Queue, threading, subprocess
import re
import cv2
# Main window class that overrides the close event to show an "Are you sure?" box.
class mainWindow(QtGui.QMainWindow):
def __init__(self, app):
QtGui.QMainWindow.__init__(self)
self.app = app
def closeEvent(self, event):
if self.app.printRunning:
result = QtGui.QMessageBox.information( self,
"Nope",
"You cannot exit while a print is running.",
QtGui.QMessageBox.Ok)
else:
result = QtGui.QMessageBox.question( self,
"Confirm Exit...",
"Are you sure you want to exit ?",
QtGui.QMessageBox.Yes| QtGui.QMessageBox.No)
if result == QtGui.QMessageBox.Yes:
self.app.closeNicely()
event.accept()
else:
event.ignore()
# Button convenience class.
class button(QtGui.QPushButton):
def __init__(self, label, callback):
# Call super class init function.
QtGui.QPushButton.__init__(self, label)
# Internalise values.
self.callback = callback
self.label = label
# Set label.
self.setText(label)
# Set callback.
QtCore.QObject.connect(self, QtCore.SIGNAL("clicked()"), self.callback)
# Check button convenience class.
class checkbox(QtGui.QCheckBox):
def __init__(self, label, callback, initialState=False):
# Call super class init function.
QtGui.QCheckBox.__init__(self, label)
# Internalise values.
self.callback = callback
# Set label.
self.setText(label)
# Set state.
self.setChecked(initialState)
# Set callback.
self.stateChanged.connect(self.callbackInternal)
#QtCore.QObject.connect(self, QtCore.SIGNAL("clicked()"), functools.partial(self.callback, self))
def callbackInternal(self):
self.callback(self.isChecked())
# A toggle button class with a label on the left. ##############################
# Will call custom functions passed as input. Label and default value are
# taken from settings object.
# There are two possibilities: if a model collection is supplied, this is a
# toggle button for a model specific setting. If no model collection has been
# supplied, this is a general setting.
class toggleButton(QtGui.QCheckBox):
# Override init function.
def __init__(self, string, settings=None, modelCollection=None, customFunctions=None, displayString=None):
# Internalise params.
self.string = string
self.modelCollection = modelCollection
self.customFunctions = customFunctions
# Get settings object if model collection was supplied.
if self.modelCollection != None:
self.settings = self.modelCollection.getCurrentModel().settings
elif settings != None:
self.settings = settings
# Create the label string.
if displayString != None:
self.labelString = displayString+self.settings[string].unit
elif self.settings[self.string].name != None:
self.labelString = self.settings[self.string].name + self.settings[string].unit
else:
self.labelString = string+self.settings[string].unit
# Create toggle button.
# Call super class init funtion.
QtGui.QCheckBox.__init__(self, self.labelString)
self.show()
# Set toggle state according to setting.
self.setChecked(self.settings[string].getValue())
# Connect to callback function.
self.stateChanged.connect(self.callbackToggleChanged)
def callbackToggleChanged(self, data=None):
# Set value.
self.settings[self.string].setValue(self.isChecked())
# Call the custom functions specified for the setting.
if self.customFunctions != None:
for function in self.customFunctions:
function()
# Update the toggle state if current model has changed.
def update(self):
# If this is a model setting...
if self.modelCollection != None:
self.set_active(self.modelCollection.getCurrentModel().settings[self.string].getValue())
else:
self.set_active(self.settings[self.string].getValue())
## Update the toggle state if current model has changed.
#def update(self):
# self.set_active(self.settings[self.string].getValue())
# A text entry including a label on the left. ##################################
# Will call a function passed to it on input. Label, default value and
# callback function are taken from the settings object.
class entry(QtGui.QWidget):
# Override init function.
def __init__(self, string, settings=None, modelCollection=None, customFunctions=None, width=None, displayString=None):
# Call super class init function.
QtGui.QWidget.__init__(self)
box = QtGui.QHBoxLayout()
box.setContentsMargins(0,0,0,0)
box.setSpacing(0)
box.setAlignment(QtCore.Qt.AlignLeft)
self.setLayout(box)
# Internalise params.
self.string = string
self.modelCollection = modelCollection
# Get settings of default model which is the only model during GUI creation.
if modelCollection != None:
#self.modelCollection = modelCollection
self.settings = modelCollection.getCurrentModel().settings
# If settings are provided instead of a model collection this is a
# printer settings entry.
elif settings != None:
self.settings = settings
else:
print "WARNING: either model collection or settings object must be passed."
self.customFunctions = customFunctions
# Create the label string.
if displayString != None:
self.labelString = displayString+self.settings[string].unit
elif self.settings[self.string].name != None:
self.labelString = self.settings[self.string].name + self.settings[string].unit
else:
self.labelString = string+self.settings[string].unit
# Transform into QString to handle special chars better.
self.labelString = QtCore.QString.fromUtf8(self.labelString)
# Make label.
self.label = QtGui.QLabel(self.labelString)
box.addWidget(self.label, 0, QtCore.Qt.AlignVCenter and QtCore.Qt.AlignLeft)
box.addStretch(1)
# Make text entry.
self.entry = QtGui.QLineEdit()
self.setColor(False)
box.addWidget(self.entry, 0, Qt.AlignVCenter)
if width == None:
self.entry.setFixedWidth(60)
else:
self.entry.setFixedWidth(width)
# Set entry text.
self.entry.setText(str(self.settings[string].getValue()))
# Set callback connected to Enter key and focus leave.
self.entry.editingFinished.connect(self.entryCallback)
# Create timer to turn green fields to white again.
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.timerTimeout)
# Return the current settings object.
# This is needed because one entry can work on different settings
# objects depending on which model is currently selected.
# That's of course only for the case the entry works on a model collection.
def updateCurrentSettings(self):
if self.modelCollection != None:
self.settings = self.modelCollection.getCurrentModel().settings
def timerTimeout(self):
self.entry.setText(str(self.settings[self.string].getValue()))
self.setColor('black')
self.timer.stop()
def setColor(self, color):
if color == 'red':
self.entry.setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(255,0,0)")
elif color == 'black':
self.entry.setStyleSheet("color: rgb(0, 0, 0); background-color: rgb(255,255,255)")
elif color == 'grey':
self.entry.setStyleSheet("color: rgb(127, 127, 127); background-color: rgb(255,255,255)")
elif color == 'green':
self.entry.setStyleSheet("color: rgb(0, 0, 0); background-color: rgb(80,230,80)")
elif color == 'yellow':
self.entry.setStyleSheet("color: rgb(0, 0, 0); background-color: rgb(230,230,0)")
def entryCallback(self):
# Update the current settings object.
self.updateCurrentSettings()
# Check which type we are expecting.
valueTypeExpected = self.settings[self.string].getType()
# Check if that type has been entered.
entryText = str(self.entry.text())
valueTypeFound = None
# Try if it can be cast into a number...
try:
# If cast to int == cast to float, it's an int.
# If not, it's a float.
if int(float(entryText)) == float(entryText):
valueTypeFound = int
print "Found int."
# Turn into float if we expect one,
# this is for the case where an int (e.g. 1)
# has been entered (instead of e.g. 1.0).
if valueTypeExpected == float:
valueTypeFound = float
else:
valueTypeFound = float
print "Found float"
# ... if not, it must be a path or nothing.
except ValueError:
# Check if path chars are present.
if len(re.findall(r'[a-zA-Z\/\.]', entryText)) > 0:
valueTypeFound = str
print "Found string."
if valueTypeExpected != valueTypeFound:
self.setColor('red')
self.timer.start(500)
else:
# Cast value string to expected type.
newValue = valueTypeExpected(self.entry.text())
# Check if the value has changed.
if self.settings[self.string].getValue() != newValue:
# CHeck if the value is within limits.
if self.settings[self.string].getLimits()[0] <= newValue and self.settings[self.string].getLimits()[1] >= newValue:
self.setColor('green')
self.timer.start(100)
else:
self.setColor('yellow')
self.timer.start(100)
self.settings[self.string].setValue(newValue)
# Set the entry text in case the setting was changed by settings object.
self.entry.setText(str(valueTypeExpected(self.settings[self.string].getValue())))
# Call the custom functions specified for the setting.
if self.customFunctions != None:
for function in self.customFunctions:
function()
# Override setEnabled method to act on entry box.
def setEnabled(self, active):
self.entry.setEnabled(active)
if active:
self.setColor('black')
else:
self.setColor('grey')
# Update the value in the text field if current model has changed.
def update(self):
# Update the current settings object.
self.updateCurrentSettings()
# If this is a model setting...
self.entry.setText(str(self.settings[self.string].getValue()))
#*******************************************************************************
# String class that emits a signal on content changes. *************************
#*******************************************************************************
class consoleText(QtCore.QObject):
changed = QtCore.pyqtSignal()
# Init function.
def __init__(self, numberOfLines=100):
QtCore.QObject.__init__(self)
self.text = QtCore.QString()
self.numberOfLines = numberOfLines
self.mutex = threading.Lock()
# Add text method with auto line break.
def addLine(self, string):
# Wait for other threads using this method to finish.
self.mutex.acquire()
# Cast to normal string, QString strangely misbehaves.
text = str(self.text)
# Split into list of line stings.
lines = text.split('\n')
# If number of lines reached, delete first lines.
if self.numberOfLines != None and len(lines) >= self.numberOfLines:
newText = ''
for i in range(len(lines)-self.numberOfLines, len(lines)):
newText = newText + '\n' + lines[i]
text = newText
# Add new string as new line.
text = text + '\n' + string
# Put back into QString.
self.text = QtCore.QString(text)
# Emit the signal that updates the text view.
self.changed.emit()
# Allow other threads to use this method.
self.mutex.release()
# Add a string without line break.
def addString(self, string):
self.mutex.acquire()
self.text += string
self.changed.emit()
self.mutex.release()
#*******************************************************************************
# Creates a view for the model list including add and remove buttons.
#*******************************************************************************
class modelTableView(QtGui.QWidget):
def __init__(self, settings, modelCollection, console, guiParent):
#Init the base class
#QtGui.QWidget.__init__(self)
super(modelTableView, self).__init__()
self.settings = settings
self.modelCollection = modelCollection
self.console = console
self.guiParent = guiParent
self.box = QtGui.QVBoxLayout()
self.box.setSpacing(0)
self.box.setContentsMargins(0,0,0,0)
self.setLayout(self.box)
self.tableView = QtGui.QTableView()
# Select whole rows instead of individual cells.
self.tableView.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
# Set single selection mode.
self.tableView.setSelectionMode(1)
# Hide the cell grid.
self.tableView.setShowGrid(False)
# Hide the vertical headers.
self.tableView.verticalHeader().hide()
# Set the row height.
self.tableView.verticalHeader().setDefaultSectionSize(20)
# Hide the grey dottet line of the item in focus.
# This will disable focussing, so no keyboard events can be processed.
self.tableView.setFocusPolicy(QtCore.Qt.NoFocus)
# Prevent the header font from being made bold if a row is selected.
self.tableView.horizontalHeader().setHighlightSections(False)
# Expand last column to fit view.
self.tableView.horizontalHeader().setStretchLastSection(True)
# Auto-stretch columns to fit contents.
self.tableView.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)
self.box.addWidget(self.tableView)
self.boxButtons = QtGui.QHBoxLayout()
self.boxButtons.setSpacing(0)
self.boxButtons.setContentsMargins(0,0,0,0)
self.box.addLayout(self.boxButtons)
self.buttonAdd = QtGui.QPushButton("Add")
self.buttonAdd.clicked.connect(self.callbackButtonAdd)
self.boxButtons.addWidget(self.buttonAdd)
self.buttonRemove = QtGui.QPushButton("Remove")
self.buttonRemove.clicked.connect(self.callbackButtonRemove)
self.boxButtons.addWidget(self.buttonRemove)
self.buttonRemove.setEnabled(False)
# Create the model table model.
self.modelList = modelTableModel([], 2) # Create table model with empty list, and two visible columns.
# Create a dummy row, otherwise tableView does not accept the modelTableModel.
self.modelList.insertRows(['foo', 20, 'bar', 'hoo', True], position=len(self.modelList.tableData), rows=1)
self.tableView.setModel(self.modelList)
# Delete the dummy row.
self.modelList.removeRows(0,1)
# Connect selection changed event.
# NOTE: this has to happen *after* setting the model.
self.tableView.selectionModel().selectionChanged.connect(self.callbackSelectionChanged)
# Connect data changed event.
self.modelList.dataChanged.connect(self.callbackDataChanged)
# Set up timer to poll slicer progress and update model progress bars.
# TODO: providing an update function to model collection might be
# better than polling like this.
self.timerSlicerProgress = QtCore.QTimer()
self.timerSlicerProgress.timeout.connect(self.updateSlicerProgress)
self.timerSlicerProgress.start(100)
# Method to add a new model.
def callbackButtonAdd(self):
# Open a file chooser dialog.
fileChooser = QtGui.QFileDialog()
fileChooser.setFileMode(QtGui.QFileDialog.AnyFile)
fileChooser.setFilter("Stl files (*.stl)")
fileChooser.setWindowTitle("Select model file")
fileChooser.setDirectory(self.settings['currentFolder'].getValue())
filenames = QtCore.QStringList()
# exec_ returns true if OK, false if Cancel was clicked.
if fileChooser.exec_():
filepath = str(fileChooser.selectedFiles()[0])
# Check if file is an stl. If yes, load.
if filepath.lower()[-3:] != "stl":
if self.console:
self.console.addLine("File \"" + filepath + "\" is not an stl file.")
else:
# Get filename without path.
filenameStlParts = filepath.split('/')
filename = filenameStlParts[-1]
if self.console:
self.console.addLine("Loading file \"" + filename + "\".")
# Save path for next use.
self.settings['currentFolder'].setValue(filepath[:-len(filenameStlParts[-1])])
# Hide the previous models bounding box.
self.modelCollection.getCurrentModel().hideBox()
# Load the model into the model collection. Returns id for the new model.
modelId = self.modelCollection.add(filename, filepath)
# Add to Qt model list.
# Add to table model.
self.modelList.insertRows([modelId, 0, modelId, filepath, True], position=len(self.modelList.tableData), rows=1)
# Set new row selected and scroll there.
self.tableView.selectRow(len(self.modelList.tableData)-1)
self.tableView.scrollToBottom()
# Activate the remove button which was deactivated when there was no model.
self.buttonRemove.setEnabled(True)
# Add actor to render view.
self.guiParent.renderView.addActors(self.modelCollection.getCurrentModel().getAllActors())
# Update 3d view.
self.guiParent.renderView.render()
# Make supports and slice tab available if this is the first model.
if len(self.modelList.tableData)< 2:
self.guiParent.setGuiState(state=1)
def callbackButtonRemove(self):
# Get selected row. We have single select mode, so only one (the first) will be selected.
removeIndex = self.tableView.selectionModel().selectedRows()[0]
# Find out which row to select after the current selection has been deleted.
currentIndex = removeIndex
# Select the next model in the list before deleting the current one.
# If current selection at end of list but not the last element...
if currentIndex == len(self.modelList.tableData) - 1 and len(self.modelList.tableData) > 1:
# ... select the previous item.
currentIndex -= 1
self.tableView.selectRow(currentIndex)
# If current selection is somewhere in the middle...
elif currentIndex < len(self.modelList.tableData) - 1 and len(self.modelList.tableData) > 1:
# ... selected the next item.
currentIndex += 1
self.tableView.selectRow(currentIndex)
# If current selection is the last element remaining...
elif len(self.modelList.tableData) == 1:
# ... set the default model as current model.
self.modelCollection.setCurrentModelId("default")
# Deactivate the remove button.
self.buttonRemove.setEnabled(False)
# Update the gui.
self.guiParent.setGuiState(state=0)
# Now that we have the new selection, we can delete the previously selected model.
# Remove model from model collection.
# First, use model index to get model id.
# Beware that indices are of type QModelIndex.
modelId = self.modelList.tableData[removeIndex.row()][2]
# Remove all render actors.
self.guiParent.renderView.removeActors(self.modelCollection.getModel(modelId).getActor())
self.guiParent.renderView.removeActors(self.modelCollection.getModel(modelId).getBoxActor())
self.guiParent.renderView.removeActors(self.modelCollection.getModel(modelId).getBoxTextActor())
self.guiParent.renderView.removeActors(self.modelCollection.getModel(modelId).getAllActors())
# Remove the model.
self.modelCollection.remove(modelId)
# Update 3d view.
self.guiParent.renderView.render()
# Update the slider.
#???
# Now, remove from QT table model.
# Turn into persistent indices which keep track of index shifts as
# items get removed from the model.
# This is only needed for removing multiple indices (which we don't do, but what the heck...)
persistentIndices = [QtCore.QPersistentModelIndex(index) for index in self.tableView.selectionModel().selectedRows()]
for index in persistentIndices:
self.modelList.removeRow(index.row())
def removeAll(self):
# TODO: handle this in model collection!
self.modelList.clear()
# Act if data in the model has changed.
# This is mostly for setting model's active status.
def callbackDataChanged(self, index):
# Check if the data in the model enable column has changed.
if self.modelList.checkBoxChanged:
print "Changed toggle in row " + str(index.row())
# Reset the checkbox change flag.
self.modelList.checkBoxChanged = False
# Set model status accordingly.
# If table data shows False in activation column...
if self.modelList.tableData[index.row()][-1]:
print "Activating model " + self.modelList.tableData[index.row()][2]
self.modelCollection[self.modelList.tableData[index.row()][2]].setActive(True)
self.tableView.selectionModel().setCurrentIndex(index, QtGui.QItemSelectionModel.Rows)
#self.modelCollection.setCurrentModelId(self.modelList.tableData[index.row()][2])
# Update model.
self.modelCollection.getCurrentModel().updateModel()
self.modelCollection.getCurrentModel().updateSupports()
self.modelCollection.updateSliceStack()
#self.renderView.render()
# If table data shows True in activation column...
else:
# TODO: CHECK IF THERE'S NO ACTIVE MODEL ANY MORE!
print "Deactivating model " + self.modelList.tableData[index.row()][2]
self.modelCollection[self.modelList.tableData[index.row()][2]].setActive(False)
self.modelCollection.updateSliceStack()
# Call gui update function to change actor visibilities.
self.guiParent.updateAllEntries(render=True)
self.guiParent.updateSlider()
def updateSlicerProgress(self):
# Get slicer status list from model collection.
slicerProgress = []
for modelId in self.modelCollection:
if modelId != "default":
slicerProgress.append(self.modelCollection[modelId].getSlicerProgress())
self.modelList.updateSlicerProgress(slicerProgress)
def callbackSelectionChanged(self):
# Hide the previous models bounding box actor.
self.modelCollection.getCurrentModel().hideBox()
# Get index list of selected items.
selectedIndices = self.tableView.selectionModel().selectedRows()
# If nothing selected...
if len(selectedIndices) == 0:
# ... set the default model as current model.
self.modelCollection.setCurrentModelId("default")
# If there is a selection...
else:
# ... set the corresponding model active.
# Use only the first index as we use single selection mode.
self.modelCollection.setCurrentModelId(self.modelList.tableData[selectedIndices[0].row()][2])
# Show bounding box.
self.modelCollection.getCurrentModel().showBox()
# Update GUI.
self.guiParent.renderView.render()
self.guiParent.updateAllEntries()
# Disable buttons so models can only be loaded in first tab.
def setButtonsSensitive(self, load=True, remove=True):
self.buttonAdd.setEnabled(load)
self.buttonRemove.setEnabled(remove)
#*******************************************************************************
# Create a table model for the model container including add and remove methods.
#*******************************************************************************
# Custom table model.
# Data carries the following columns:
# Model name, slicer status, model ID, stl path, model acitve flag.
class modelTableModel(QtCore.QAbstractTableModel):
def __init__(self, tableData, numDispCols, parent = None, *args):
QtCore.QAbstractTableModel.__init__(self, parent, *args)
self.tableData = tableData
self.numDispCols = numDispCols
self.checkBoxChanged = False
# This will be called by the view to determine the number of rows to show.
def rowCount(self, parent):
return len(self.tableData)
# This will be called by the view to determine the number of columns to show.
# We only want to show a certain number of columns, starting from 0 and
# ending at numDispCols
def columnCount(self, parent):
if len(self.tableData) > 0:
if self.numDispCols <= len(self.tableData[0]):
return self.numDispCols
else:
return len(self.tableData[0])
else:
return 0
# This gets called by the view to get the data at the given index.
# Based on the row and column number retrieved from the index, we
# assign different roles the the returned data. This predicts how the data
# is shown. The view will request all roles and if the requested one matches
# the one we want to show for the given index, we'll return it.
# DisplayRole will show the data, all other roles will modify the display.
def data(self, index, role):
# Return nothing if index is invalid.
if not index.isValid():
return QtCore.QVariant()
# Get row and column.
row = index.row()
column = index.column()
# Return the data.
if role == Qt.DisplayRole:
if column == 0:
return QtCore.QVariant(self.tableData[index.row()][index.column()])
elif column == 1:
return QtCore.QVariant(str(self.tableData[index.row()][index.column()]) + " %")
# If user starts editing the cell by double clicking it, also return the data.
# Otherwise cell will be empty once editing is started.
if role == Qt.EditRole:
return QtCore.QVariant(self.tableData[index.row()][index.column()])
# Return the picture for slicer status bar if the view asks for a
# decoration role.
elif role == Qt.DecorationRole:
if column == 1:
# Bar size.
barWidth = 50
barHeight =10
# Set the color depending on the slicer status.
# Small: red, medium: yellow, high: green.
if self.tableData[row][1] < barWidth * (100./barWidth) * 0.1:
color = 0xFF0000
elif self.tableData[row][1] > barWidth * (100./barWidth) * 0.95:
color = 0x64FF00
else:
color = 0xFFC800
# Create image.
img = QtGui.QImage(barWidth, barHeight, QtGui.QImage.Format_RGB888)
img.fill(0xFFFFFF)
for h in range(barHeight):
for w in range(barWidth):
if w*(100./barWidth) < self.tableData[row][1]:
img.setPixel(w,h,color)
'''
# DOES NOT WORK.
# That's because the bardata array
# will be deleted after the data() method has returned.
# The memory of the img will be overwritten and result in
# noise.
barWidth = 50
barHeight =6
# Create a numpy array of 100 x 1 pixels.
barData = numpy.ones((barHeight,barWidth,3), dtype = numpy.uint8)*255
# Set the color depending on the slicer status.
# Small: red, medium: yellow, high: green.
if self.tableData[row][1] < barWidth * (100./barWidth) * 0.1:
color = [255,255,0]#0xFFFF00
elif self.tableData[row][1] > barWidth * (100./barWidth) * 0.95:
color = [100,255,0]#0x80FF00
else:
color = [255,200,0]#0x00D0FF
# Loop through image columns and set pixel color.
barData = numpy.swapaxes(barData,0,1)
for i in range(barData.shape[0]):
if i*(100./barWidth) < self.tableData[row][1]:
barData[i] = color
barData = numpy.swapaxes(barData,0,1)
print barData
# Convert to image.
img = QtGui.QImage(barData.DeepCopy(), barData.shape[1], barData.shape[0], barData.strides[0], QtGui.QImage.Format_RGB888)
'''
return img
# Add a check box to all rows in column 1.
# Set the checkbox state depending on the data in column 3.
elif role == Qt.CheckStateRole:
if column == 0:
#print self.tableData[row][3]
if self.tableData[row][4]:
return Qt.Checked
else:
return Qt.Unchecked
# Return tooltip.
elif role == Qt.ToolTipRole:
if column == 0:
return "Use the check box to enable or disable this model.\nDouble click to rename."
else:
return "Current slicer status."
# Return alignment.
elif role == Qt.TextAlignmentRole:
#print column
if column == 1:
return Qt.AlignRight + Qt.AlignVCenter
else:
return Qt.AlignLeft + Qt.AlignVCenter
'''
# Return background color.
elif role == Qt.BackgroundRole:
if column == 1:
red = QtGui.QBrush(Qt.red);
return red;
'''
# If none of the conditions is met, return nothing.
return QtCore.QVariant()
# Provide header strings for the horizontal headers.
# Vertical headers are empty.
# Role works the same as in data().
def headerData(self, section, orientation, role):
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
if section == 0:
return QtCore.QString("Model")
elif section == 1:
return QtCore.QString("Slicer status")
# This is called once user editing of a cell has been completed.
# The value is the new data that has to be manually set to the
# tableData within the setData method.
def setData(self, index, value, role=Qt.EditRole):
row = index.row()
column = index.column()
if role == Qt.EditRole:
self.tableData[row][column] = value
elif role == Qt.CheckStateRole:
self.checkBoxChanged = True
if value == Qt.Checked:
self.tableData[row][4] = Qt.Checked
elif value == Qt.Unchecked:
self.tableData[row][4] = Qt.Unchecked
# Emit the data changed signal to let possible other views that
# didn't do the editing know about the changed data.
self.dataChanged.emit(index, index)
return True
# This will be called by the view to determine if the cell that
# has been clicked is enabled, editable, checkable, selectable and so on.
def flags(self, index):
# Get row and column.
row = index.row()
column = index.column()
if column < 1:
return Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable ;
else:
return Qt.ItemIsEnabled | Qt.ItemIsSelectable
# This is called for inserting a row.
# Position: where to insert, rows: how many to insert,
# parent: who will be parent in a tree view?
# beginInsertRows(index, first, last) tells the views where data is inserted.
# index is for hierarchical data, so we pass an empty QModelIndex, that
# points to the root index.
def insertRows(self, data, position, rows, parent=QtCore.QModelIndex()):
self.beginInsertRows(parent, position, position+rows-1)
for i in range(rows):
if len(data) == 5:
self.tableData.insert(position, data)
self.endInsertRows()
return True
# This is called for removing a row.
# Position: where to insert, rows: how many to insert,
# parent: who will be parent in a tree view?
def removeRows(self, position, rows, parent=QtCore.QModelIndex()):
self.beginRemoveRows(parent, position, position+rows-1)
for i in range(rows):
# Remove method takes a value, not and index.
# So get the value first...
value = self.tableData[position]
#... and remove it.
self.tableData.remove(value)
self.endRemoveRows()
return True
# Delete all the data.
#TODO: leave "default" model in table data upon clearing?
#def clearData(self):
# if len(self.tableData) != 0:
# self.beginRemoveRows(QModelIndex(), 0, len(self.tableData) - 1)
# self.tableData = []
# self.endRemoveRows()
# Provide a new value for the slicer status of a given row.
# Slicer status is in column 1.
def updateSlicerProgress(self, slicerProgress):
# Set the data.
if len(self.tableData) == len(slicerProgress):
for row in range(len(self.tableData)):
self.tableData[row][1] = slicerProgress[row]
# Create index for the changed cell.
index = self.createIndex(row, 1)
# Emit data changed signal to update all views since we changed the data manually.
self.dataChanged.emit(index, index)
#*******************************************************************************
# Creates a text viewer that automatically updates if the referenced string is
# emitting a changed signal.
#*******************************************************************************
class consoleView(QtGui.QVBoxLayout):
# Override init function.
def __init__(self, textBuffer):
QtGui.QVBoxLayout.__init__(self)
# Internalise.
self.textBuffer = textBuffer
# Connect to text buffers changed signal.
# First, make a slot function.
@QtCore.pyqtSlot()
def textChanged():
self.update()
# Then, we connect the slot to the changed signal of the text buffer.
self.textBuffer.changed.connect(textChanged)
# Create box for content.
self.frame = QtGui.QGroupBox("Output log")
self.addWidget(self.frame)
self.box = QtGui.QVBoxLayout()
self.frame.setLayout(self.box)
self.textBrowser = QtGui.QTextBrowser()
self.box.addWidget(self.textBrowser)
self.update()
def update(self):
self.textBrowser.clear()
self.textBrowser.append(self.textBuffer.text)
#*******************************************************************************
# Creates a notebook for the settings tabs.
#*******************************************************************************
class notebook(QtGui.QTabWidget):
# Override init.
def __init__(self, customFunctions=None):
# Call super class init function.
QtGui.QTabWidget.__init__(self)
# Create custom function list to add to.
self.customFunctions = []
# Connect the page switch signal to a custom event handler.
# Tab sensitivity checking is done there.
self.connect(self, QtCore.SIGNAL("currentChanged(int)"), self.callbackPageSwitch)
self.setStyleSheet("QTabBar.tab { min-width: 100px; }")
# Function to set tab sensitivity for a given page.
'''
def setTabEnabled(self, page, sens):
# If given page exists...
if self.get_nth_page(page) != None:
# ... set the tab labels' sensititvity according to input.
self.get_tab_label(self.get_nth_page(page)).set_sensitive(sens)
'''
# Function to retrieve sensitivity for a given page.
def getTabEnabled(self, page):
if page < self.count():
return self.isTabEnabled(page)
# Set custom function.
def setCustomFunction(self, page, fcn):
# Add the function to the list at the index specified by page.
# If page > list length, add at end and fill with Nones.
listIndexMax = len(self.customFunctions)-1
# If the function will be placed for a page that is
# beyond the function list index...
if page > listIndexMax and page < self.count():
# ... append empty lists until just before page index...
for i in range((page-1)-listIndexMax):
self.customFunctions.append([])
# ... and append page specific function.
self.customFunctions.append([fcn])
# If the function is placed in an existing list item...
elif page <= listIndexMax and page < self.count():
# ... append it.
if self.customFunctions[page] == []:
self.customFunctions[page] == [fcn]
else:
self.customFunctions[page].append(fcn)
# Get current page.
def getCurrentPage(self):
return self.currentIndex()
# Set current page.
def setCurrentPage(self, page):
self.setCurrentIndex(page)
# Define tab change actions.
# Tab change event. The actual tab change will commence at the end of this function.
# Callback takes four mysterious arguments (parent, notebook, page, page index?).
# Last argument is the current tab index.
def callbackPageSwitch(self, page):
# Handle tab sensitivity.
# If the switch was made to an insensitive tab (the requested pageIndex)...
if self.getTabEnabled(page)==False:
# ... change to previously selected tab.
page = self.getCurrentPage() # Current page still points to the old page.
# Stop the event handling to stay on current page.
self.stop_emission("switch-page")
# Run the custom function corresponding to the current page index.
if len(self.customFunctions) > page and self.customFunctions[page] != []:
for customFunction in self.customFunctions[page]:
customFunction()