-
Notifications
You must be signed in to change notification settings - Fork 0
/
monkeyprintGui.py
3445 lines (2947 loc) · 136 KB
/
monkeyprintGui.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 pygtk
pygtk.require('2.0')
import gtk, gobject
#import gtkGLExtVTKRenderWindowInteractor
import monkeyprintModelViewer
import monkeyprintGuiHelper
import monkeyprintSerial
import monkeyprintPrintProcess
import monkeyprintSocketCommunication
import subprocess # Needed to call avrdude.
import vtk
import threading
import Queue
import time
import signal
import zmq
import os
################################################################################
# Define a class for standalone without main GUI. ##############################
################################################################################
# Inherit from projector display window.
class noGui(monkeyprintGuiHelper.projectorDisplay):
# Override init function. #################################################
def __init__(self, programSettings, modelCollection):
# Initialise base class gtk window.********************
monkeyprintGuiHelper.projectorDisplay.__init__(self, programSettings, modelCollection)
# Set function for window close event.
self.connect("delete-event", self.on_closing, None)
# Show the window.
self.show()
# Internalise parameters.******************************
self.modelCollection = modelCollection
self.programSettings = programSettings
# Create queues for inter-thread communication.********
# Queue for setting print progess bar.
self.queueSliceOut = Queue.Queue(maxsize=1)
self.queueSliceIn = Queue.Queue(maxsize=1)
# Queue for status infos displayed above the status bar.
self.queueStatus = Queue.Queue()
# Queue for console messages.
self.queueConsole = Queue.Queue()
# Queue list.
self.queues = [ self.queueSliceOut,
self.queueStatus ]
# Allow background threads.****************************
# Very important, otherwise threads will be
# blocked by gui main thread.
gtk.gdk.threads_init()
# Add thread listener functions to run every n ms.****
# Check if the slicer threads have finished.
# slicerListenerId = gobject.timeout_add(100, self.modelCollection.checkSlicerThreads)
# Update the progress bar, projector image and 3d view. during prints.
pollPrintQueuesId = gobject.timeout_add(50, self.pollPrintQueues)
# Create additional variables.*************************
# Flag to set during print process.
self.printFlag = True
self.programSettings['printOnRaspberry'].value = True
# Create the print window.
# self.projectorDisplay = monkeyprintGuiHelper.projectorDisplay(self.programSettings, self.modelCollection)
# Create the print process thread.
self.printProcess = monkeyprintPrintProcess.printProcess(self.modelCollection, self.programSettings, self.queueSliceOut, self.queueSliceIn, self.queueStatus, self.queueConsole)
# Start the print process.
self.printProcess.start()
# Start main loop.
self.main()
def pollPrintQueues(self):
# If slice number queue has slice number...
if self.queueSliceOut.qsize():
sliceNumber = self.queueSliceOut.get()
# Set slice view to given slice. If sliceNumber is -1 black is displayed.
#if self.projectorDisplay != None:
# self.projectorDisplay.updateImage(sliceNumber)
self.updateImage(sliceNumber)
# Set slice in queue to true as a signal to print process thread that it can start waiting.
self.queueSliceIn.put(True)
# If print info queue has info...
if self.queueStatus.qsize():
#self.progressBar.setText(self.queueStatus.get())
message = self.queueStatus.get()
if message == "destroy":
self.printFlag = False
del self.printProcess
gtk.main_quit()
self.destroy()
del self
return False
else:
return True
# Return true, otherwise function won't run again.
return True
def on_closing(self, widget, event, data):
# Get all threads.
runningThreads = threading.enumerate()
# End kill threads. Main gui thread is the first...
for i in range(len(runningThreads)):
if i != 0:
runningThreads[-1].join(timeout=10000) # Timeout in ms.
print "Slicer thread " + str(i) + " finished."
del runningThreads[-1]
# Save settings to file.
self.programSettings.saveFile()
# Terminate the gui.
gtk.main_quit()
return False # returning False makes "destroy-event" be signalled to the window
# Gui main function. ######################################################
def main(self):
# All PyGTK applications must have a gtk.main(). Control ends here
# and waits for an event to occur (like a key press or mouse event).
gtk.main()
################################################################################
# Define a class for the main GUI. #############################################
################################################################################
class gui(gtk.Window):
# Override init function. #################################################
def __init__(self, modelCollection, programSettings, console=None, filename=None, *args, **kwargs):
# ********************************************************************
# Initialise base class gtk window.***********************************
# ********************************************************************
gtk.Window.__init__(self, *args, **kwargs)
# Set function for window close event.
self.connect("delete-event", self.on_closing, None)
# Set window title.
self.set_title("Monkeyprint")
# Set maximized.
self.maximize()
# Show the window.
self.show()
# ********************************************************************
# Declare variables. *************************************************
# ********************************************************************
# Internalise parameters.
self.modelCollection = modelCollection
self.programSettings = programSettings
self.console = console
# Create queues for inter-thread communication.
# Queue for setting print progess bar.
self.queueSliceOut = Queue.Queue(maxsize=1)
self.queueSliceIn = Queue.Queue(maxsize=1)
# Queues for controlling the file transmission thread.
self.queueFileTransferIn = Queue.Queue(maxsize=1)
self.queueFileTransferOut = Queue.Queue(maxsize=1)
# Queue for print process commands.
# Queue for status infos displayed above the status bar.
self.queueStatus = Queue.Queue()
# Queue for commands sent to print process.
self.queueCommands = Queue.Queue(maxsize=1)
# Queue for console messages.
self.queueConsole = Queue.Queue()
# Is this running from Raspberry Pi or from PC?
self.runningOnRasPi = False
# TODO: Use this flag to combine this class and server class.
# Flag to set during print process.
self.printFlag = False
# Get current working directory and set paths.
self.cwd = os.getcwd()
self.programSettings['localMkpPath'].value = self.cwd + "/currentPrint.mkp"
# ********************************************************************
# Create print process. **********************************************
# ********************************************************************
# self.printProcess = monkeyprintPrintProcess.printProcess(self.modelCollection, self.programSettings, self.queueSliceOut, self.queueSliceIn, self.queueStatus, self.queueConsole)
#DO THIS LATER ON PRINT BUTTON PRESS!
# TODO: make specific for Pi or PC
# ********************************************************************
# Create communication socket to Raspberry Pi. ***********************
# ********************************************************************
# Create the socket and connect.
if self.runningOnRasPi:
self.socket = monkeyprintSocketCommunication.communicationSocket(port=self.programSettings['networkPortRaspi'].value, ip=None, queueCommands=self.queueCommands)
else:
self.socket = monkeyprintSocketCommunication.communicationSocket(port=self.programSettings['networkPortRaspi'].value, ip=self.programSettings['ipAddressRaspi'].value, queueStatus=self.queueStatus)
# Add socket listener and connection timeout methods to GTK event loop.
gobject.io_add_watch(self.socket.fileDescriptor, gobject.IO_IN, self.socket.callbackIOActivity, self.socket.socket)
if not self.runningOnRasPi:
# Connection poll.
gobject.timeout_add(500, self.socket.pollRasPiConnection)
# Connection timeout counter.
gobject.timeout_add(1000, self.socket.countdownRasPiConnection)
# ********************************************************************
# Allow background threads. ******************************************
# ********************************************************************
# Very important, otherwise threads will be
# blocked by gui main thread.
gtk.gdk.threads_init()
# ********************************************************************
# Add thread listener functions to run every n ms.********************
# ********************************************************************
# Check if the slicer threads have finished.
slicerListenerId = gobject.timeout_add(100, self.modelCollection.checkSlicerThreads)
# Update the progress bar, projector image and 3d view. during prints.
pollPrintQueuesId = gobject.timeout_add(50, self.pollPrintQueues)
# Request status info from raspberry pi.
# pollRasPiConnectionId = gobject.timeout_add(500, self.pollRasPiConnection)
# Request status info from slicer.
pollSlicerStatusId = gobject.timeout_add(100, self.pollSlicerStatus)
# TODO: combine this with slicerListener.
# ********************************************************************
# Create file transmission thread. ***********************************
# ********************************************************************
# Only if this is not running on Raspberry Pi.
if not self.runningOnRasPi:
ipFileClient = self.programSettings['ipAddressRaspi'].value
portFileClient = self.programSettings['fileTransmissionPortRaspi'].value
self.threadFileTransmission = monkeyprintSocketCommunication.fileSender(ip=ipFileClient, port=portFileClient, queueStatusIn=self.queueFileTransferIn, queueStatusOut=self.queueFileTransferOut)
self.threadFileTransmission.start()
# ********************************************************************
# Create the main GUI. ***********************************************
# ********************************************************************
# Create main box inside of window.
self.boxMain = gtk.VBox()
self.add(self.boxMain)
self.boxMain.show()
# Create menu bar and pack inside main box at top.
self.menuBar = self.createMenuBar()#menuBar(self.programSettings, self.on_closing)
self.boxMain.pack_start(self.menuBar, expand=False, fill=False)
self.menuBar.show()
# Create work area box and pack below menu bar.
self.boxWork = gtk.HBox()
self.boxMain.pack_start(self.boxWork)
self.boxWork.show()
# Create render box and pack inside work area box.
self.renderView = monkeyprintModelViewer.renderView(self.programSettings)
self.renderView.show()
self.boxWork.pack_start(self.renderView)#, expand=True, fill= True)
# Create settings box and pack right of render box.
self.boxSettings = self.createSettingsBox()
self.boxSettings.show()
self.boxWork.pack_start(self.boxSettings, expand=False, fill=False, padding = 5)
# Handle sigterm to shut down gracefully.
signal.signal(signal.SIGTERM, self.on_closing)
# Prepare...
# Print window.
self.projectorDisplay = None
# Set print progress values.
self.queueSliceOut.put(0)
self.queueStatus.put("idle:slice:0")
# Add print job load function to be called once on startup.
if filename != None:
printjobLoadFunctionId = gobject.idle_add(self.loadPrintjob, filename)
# *************************************************************************
# Gui main function. ******************************************************
# *************************************************************************
def main(self):
# All PyGTK applications must have a gtk.main(). Control ends here
# and waits for an event to occur (like a key press or mouse event).
gtk.main()
# *************************************************************************
# Override the close function. ********************************************
# *************************************************************************
def on_closing(self, widget, event, data):
# Check if a print is running.
if self.printFlag:
self.console.addLine('Monkeyprint cannot be closed')
self.console.addLine('during a print. Wait for')
self.console.addLine('the print to finish or cancel')
self.console.addLine('the print if you want to close.')
return True # returning True avoids it to signal "destroy-event"
else:
# Create a dialog window with yes/no buttons.
dialog = gtk.MessageDialog(self,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_QUESTION,
gtk.BUTTONS_YES_NO,
"Do you really want to quit?")
# Set the title.
dialog.set_title("Quit Monkeyprint?")
# Check the result and respond accordingly.
response = dialog.run()
dialog.destroy()
if response == gtk.RESPONSE_YES:
# Get all threads.
runningThreads = threading.enumerate()
# End kill threads. Main gui thread is the first...
for i in range(len(runningThreads)):
if i != 0:
runningThreads[-1].join(timeout=1000) # Timeout in ms.
print "Background thread " + str(i) + " finished."
del runningThreads[-1]
# Clean up files.
if os.path.isfile(self.programSettings['localMkpPath'].value):
os.remove(self.programSettings['localMkpPath'].value)
# Save settings to file.
self.programSettings.saveFile()
# Terminate the gui.
gtk.main_quit()
return False # returning False makes "destroy-event" be signalled to the window.
else:
return True # returning True avoids it to signal "destroy-event"
# *************************************************************************
# Function that checks if one of the slicer threads is running. ***********
# *************************************************************************
# This runs every 100 ms as a gobject timeout function.
def pollSlicerStatus(self):
if self.modelCollection != None:
self.buttonSaveSlices.set_sensitive(not self.modelCollection.slicerRunning())
return True
# *************************************************************************
# Function that updates all relevant GUI elements during prints. **********
# *************************************************************************
# This runs every 100 ms as a gobject timeout function.
# Updates 3d view and projector view. Also forwards status info.
def pollPrintQueues(self):
# Check the queues...
# If slice number queue has slice number...
if self.queueSliceOut.qsize():
# ... get it from the queue.
sliceNumber = self.queueSliceOut.get()
# If it's an actual slice number...
if sliceNumber >=0:
# Set 3d view to given slice.
self.modelCollection.updateAllSlices3d(sliceNumber)
self.renderView.render()
# Set slice view to given slice. If sliceNumber is -1 black is displayed.
# Only if not printing from raspberry. In this case the projector display will not exist.
if self.projectorDisplay != None:
self.projectorDisplay.updateImage(sliceNumber)
# Update slice preview in the gui.
self.sliceView.updateImage(sliceNumber)
# Signal to print process that slice image is set and exposure time can begin.
if self.queueSliceIn.empty():
self.queueSliceIn.put(True)
# If status queue has info...
if self.queueStatus.qsize():
# ... get the status.
message = self.queueStatus.get()
#print message
# Check if this is the destroy message for terminating the print window.
if message == "destroy":
# If running on Raspberry, destroy projector display and clean up files.
if self.runningOnRasPi:
print "Print process finished! Idling..."
self.printFlag = False
del self.printProcess
self.projectorDisplay.destroy()
del self.projectorDisplay
# Remove print file.
if os.path.isfile(self.localPath + self.localFilename):
os.remove(self.localPath + self.localFilename)
# If not running on Raspberry Pi, destroy projector display and reset GUI.
else:
self.buttonPrintStart.set_sensitive(True)
self.buttonPrintStop.set_sensitive(False)
self.modelCollection.updateAllSlices3d(0)
self.renderView.render()
self.progressBar.updateValue(0)
self.printFlag = False
del self.printProcess
self.projectorDisplay.destroy()
del self.projectorDisplay
else:
# If running on Raspberry forward the message to the socket connection.
if self.runningOnRasPi:
self.socket.sendMulti("status", message)
# If not, update the GUI.
else:
self.processStatusMessage(message)
# print message
# Poll the command queue.
# Only do this when running on Raspberry Pi.
# If command queue has info...
if self.queueCommands.qsize():
# ... get the command.
command = self.queueCommands.get()
self.processCommandMessage(command)
# If console queue has info...
if self.queueConsole.qsize():
if self.console != None:
self.console.addLine(self.queueConsole.get())
# Return true, otherwise function won't run again.
return True
# *************************************************************************
# Function to process output of commandQueue and control print process. ***
# *************************************************************************
def processCommandMessage(self, message):
# Only needed on Rasperry Pi.
#if self.runningOnRasPi:
# Split the string.
command, parameter = message.split(":")
if command == "start":
if self.printFlag:
pass
# TODO: Send error message.
#zmq_socket.send_multipart(["error", "Print running already."])
else:
# Start the print. Parameter is the file path in case of running from Pi.
self.printProcessStart(parameter)
elif command == "stop":
print "command: stop"
if self.printFlag:
self.printProcessStop()
#self.printProcess.stop()
elif command == "pause":
if self.printFlag:
self.printProcess.pause()
# *************************************************************************
# Function to process the output of statusQueue and update the GUI. *******
# *************************************************************************
def processStatusMessage(self, message):
# Split the string.
status, param, value = message.split(":")
# Check the status and retreive other data.
printFlag = True
if status == "slicing":
if param == "nSlices":
# Set number of slices for status bar.
self.progressBar.setLimit(int(value))
elif param == "slice":
# Set current slice in status bar.
currentSlice = int(value)
# TODO get current slice, this will work once slicer thread returns single slices.
if not self.queueSliceOut.qsize():
self.queueSliceOut.put(int(currentSlice))
self.progressBar.setText("Slicing.")
elif status == "preparing":
if param == "nSlices":
self.progressBar.setLimit(int(value))
if param == "homing":
self.progressBar.setText("Homing build platform.")
if param == "bubbles":
self.progressBar.setText("Removing bubbles.")
elif status == "printing":
if param == "nSlices":
# Set number of slices for status bar.
self.progressBar.setLimit(int(value))
if param == "slice":
# Set current slice in status bar.
self.progressBar.updateValue(int(value))
self.progressBar.setText("Printing slice " + value + ".")
if not self.queueSliceOut.qsize():
self.queueSliceOut.put(int(value))
elif status == "stopping":
self.progressBar.setText("Stopping print.")
elif status == "paused":
self.progressBar.setText("Print paused.")
elif status == "stopped":
if param == "slice":
self.progressBar.setText("Print stopped after " + value + " slices.")
else:
self.progressBar.setText("Print stopped.")
# Reset stop button to insensitive.
self.buttonPrintStart.set_sensitive(True)
self.buttonPrintStop.set_sensitive(False)
elif status == "idle":
if param == "slice":
self.progressBar.updateValue(int(value))
printFlag = False
self.progressBar.setText("Idle.")
self.printFlag = printFlag
# Create menu. ############################################################
def createMenuBar(self):
# Create the menu bar.
menuBar = gtk.MenuBar()
# Create file menu.
# That's the container for the file menu items that
# will pop up upon ckicking the file menu. Therefore, it
# does not have to be shown here.
fileMenu = gtk.Menu()
# Create file menu items.
self.menuItemOpen = gtk.MenuItem(label="Open project")
self.menuItemSave = gtk.MenuItem(label="Save project")
self.menuItemClose = gtk.MenuItem(label="Close project")
self.menuItemQuit = gtk.MenuItem(label="Quit")
# Set initial sensitivities.
self.menuItemSave.set_sensitive(False)
self.menuItemClose.set_sensitive(False)
# Add to menu.
fileMenu.append(self.menuItemOpen)
fileMenu.append(self.menuItemSave)
fileMenu.append(self.menuItemClose)
fileMenu.append(self.menuItemQuit)
# Connect menu items to callback signals.
self.menuItemOpen.connect("activate", self.callbackOpen)
self.menuItemSave.connect("activate", self.callbackSaveProject)
self.menuItemClose.connect("activate", self.callbackClose)
self.menuItemQuit.connect("activate", self.callbackQuit)
# Show the items.
self.menuItemOpen.show()
self.menuItemSave.show()
self.menuItemClose.show()
self.menuItemQuit.show()
# Create file menu (does not have to be shown).
optionsMenu = gtk.Menu()
# Create file menu items.
self.menuItemSettings = gtk.MenuItem(label="Settings")
self.menuItemFlash = gtk.MenuItem(label="Flash firmware")
self.menuItemManualControl = gtk.MenuItem(label="Manual control")
# Connect callbacks.
self.menuItemSettings.connect("activate", self.callbackSettings)
self.menuItemFlash.connect("activate", self.callbackFlash)
self.menuItemManualControl.connect("activate", self.callbackManualControl)
# Add to menu.
optionsMenu.append(self.menuItemSettings)
optionsMenu.append(self.menuItemFlash)
optionsMenu.append(self.menuItemManualControl)
# Show the items.
self.menuItemSettings.show()
self.menuItemFlash.show()
self.menuItemManualControl.show()
# Help menu.
helpMenu = gtk.Menu()
# Create file menu items.
self.menuItemDocu = gtk.MenuItem(label="Documentation")
self.menuItemAbout = gtk.MenuItem(label="About")
self.menuItemDocu.set_sensitive(False)
self.menuItemAbout.set_sensitive(False)
# Connect callbacks.
self.menuItemDocu.connect("activate", self.callbackSettings)
self.menuItemAbout.connect("activate", self.callbackSettings)
# Add to menu.
helpMenu.append(self.menuItemDocu)
helpMenu.append(self.menuItemAbout)
# Show the items.
self.menuItemDocu.show()
self.menuItemAbout.show()
# Create menu bar items.
# File menu.
menuItemFile = gtk.MenuItem(label="File")
menuItemFile.set_submenu(fileMenu)
menuBar.append(menuItemFile)
menuItemFile.show()
# Options menu.
menuItemOptions = gtk.MenuItem(label="Options")
menuItemOptions.set_submenu(optionsMenu)
menuBar.append(menuItemOptions)
menuItemOptions.show()
# Help menu.
menuItemHelp = gtk.MenuItem(label="Help")
menuItemHelp.set_submenu(helpMenu)
menuBar.append(menuItemHelp)
menuItemHelp.show()
# Return the menu.
return menuBar
def loadPrintjob(self, filename):
# Check if file is an mkp. If not...
if filename.lower()[-3:] != "mkp":
# ... display message and nothing more.
self.console.addLine("File \"" + filename + "\" is not a monkeyprint project file.")
else:
# Console message.
self.console.addLine("Loading project \"" + filename.split('/')[-1] + "\".")
# Save path for next use.
self.programSettings['currentFolder'].value = filename[:-len(filename.split('/')[-1])]
# Now that we have the new selection, we can delete the previously selected model.
# First, remove the actors from the render view.
self.renderView.removeActors(self.modelCollection.getAllActors())
# Then, load the project into the model collection:
self.modelCollection.loadProject(filename)
# Update the list view.
self.modelListView.update()
# Set menu item sensitivities.
self.menuItemSave.set_sensitive(True)
self.menuItemClose.set_sensitive(True)
# Hide the previous models bounding box.
# self.modelCollection.getCurrentModel().hideBox()
# Load the model into the model collection.
# self.modelCollection.add(filename, filepath)
# Add the filename to the list and set selected.
# self.add(filename, filename, filepath)
# Activate the remove button which was deactivated when there was no model.
# self.buttonRemove.set_sensitive(True)
# Add actor to render view.
self.renderView.addActors(self.modelCollection.getAllActors())
# Update 3d view.
self.renderView.render()
# Update menu to set sensitivities.
self.updateMenu()
# Update model list view to set sensitivities.
self.modelListView.setSensitive(remove=self.modelCollection.modelsLoaded())
# Update notebook to set sensitivities.
self.updateAllEntries(state=1)
self.notebook.set_current_page(0)
# Return false so this method will not be called again when
# called from gui idle functions stack.
return False
def callbackOpen(self, event):
self.console.addLine("Opening print job...")
# Open file chooser dialog."
filepath = ""
# File open dialog to retrive file name and file path.
dialog = gtk.FileChooserDialog("Load project", None, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
dialog.set_modal(True)
dialog.set_default_response(gtk.RESPONSE_OK)
dialog.set_current_folder(self.programSettings['currentFolder'].value)
# File filter for the dialog.
fileFilter = gtk.FileFilter()
fileFilter.set_name("Monkeyprint project files")
fileFilter.add_pattern("*.mkp")
dialog.add_filter(fileFilter)
# Run the dialog and return the file path.
response = dialog.run()
# Check the response.
# If OK was pressed...
if response == gtk.RESPONSE_OK:
filename = dialog.get_filename()
self.loadPrintjob(filename)
'''
# Check if file is an mkp. If not...
if filename.lower()[-3:] != "mkp":
# ... display message and nothing more.
self.console.addLine("File \"" + filename + "\" is not a monkeyprint project file.")
else:
self.loadPrintjob(filename)
# Console message.
self.console.addLine("Loading project \"" + filename.split('/')[-1] + "\".")
# Save path for next use.
self.programSettings['currentFolder'].value = filename[:-len(filename.split('/')[-1])]
# Now that we have the new selection, we can delete the previously selected model.
# First, remove the actors from the render view.
self.renderView.removeActors(self.modelCollection.getAllActors())
# Then, load the project into the model collection:
self.modelCollection.loadProject(filename)
# Update the list view.
self.modelListView.update()
# Set menu item sensitivities.
self.menuItemSave.set_sensitive(True)
self.menuItemClose.set_sensitive(True)
# Hide the previous models bounding box.
# self.modelCollection.getCurrentModel().hideBox()
# Load the model into the model collection.
# self.modelCollection.add(filename, filepath)
# Add the filename to the list and set selected.
# self.add(filename, filename, filepath)
# Activate the remove button which was deactivated when there was no model.
# self.buttonRemove.set_sensitive(True)
# Add actor to render view.
self.renderView.addActors(self.modelCollection.getAllActors())
# Update 3d view.
self.renderView.render()
# Update menu to set sensitivities.
self.updateMenu()
# Update model list view to set sensitivities.
self.modelListView.setSensitive(remove=self.modelCollection.modelsLoaded())
# Update notebook to set sensitivities.
self.updateAllEntries(state=1)
self.notebook.set_current_page(0)
'''
# Close dialog.
dialog.destroy()
# If cancel was pressed...
elif response == gtk.RESPONSE_CANCEL:
#... do nothing.
dialog.destroy()
def callbackSaveProject(self, event):
# Open file saver dialog.
# Open file chooser dialog."
filepath = ""
# File open dialog to retrive file name and file path.
dialog = gtk.FileChooserDialog("Save project", None, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK))
dialog.set_modal(True)
dialog.set_default_response(gtk.RESPONSE_OK)
dialog.set_current_folder(self.programSettings['currentFolder'].value)
# File filter for the dialog.
fileFilter = gtk.FileFilter()
fileFilter.set_name("Monkeyprint project files")
fileFilter.add_pattern("*.mkp")
dialog.add_filter(fileFilter)
# Run the dialog and return the file path.
response = dialog.run()
# Process response. If OK...
if response == gtk.RESPONSE_OK:
# ... get file name.
path = dialog.get_filename()
#... add *.mkp file extension if necessary.
if len(path) < 4 or path[-4:] != ".mkp":
path += ".mkp"
# Console message.
self.console.addLine("Saving project to \"" + path.split('/')[-1] + "\".")
# Save path without project name for next use.
self.programSettings['currentFolder'].value = path[:-len(path.split('/')[-1])]
# Save the model collection to the given location.
self.modelCollection.saveProject(path)
# Save the path for later.
dialog.destroy()
# If cancel was pressed...
elif response == gtk.RESPONSE_CANCEL:
#... do nothing.
dialog.destroy()
def callbackClose(self, event):
# Create a dialog window with yes/no buttons.
dialog = gtk.MessageDialog(self,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_QUESTION,
gtk.BUTTONS_YES_NO,
"Do you really want to close the current project?")
# Set the title.
dialog.set_title("Close project?")
# Check the result and respond accordingly.
response = dialog.run()
dialog.destroy()
if response == gtk.RESPONSE_YES:
self.console.addLine("Closing print job...")
# Remove all actors from view.
self.renderView.removeActors(self.modelCollection.getAllActors())
# Remove all models.
self.modelCollection.removeAll()
# Set menu item sensitivities.
# Update menu to set sensitivities.
self.updateMenu()
# Update model list view to set sensitivities.
self.modelListView.setSensitive(remove=self.modelCollection.modelsLoaded())
# Update notebook to set sensitivities.
self.updateAllEntries(state=0)
# Render.
self.renderView.render()
# else:
# return True # returning True avoids it to signal "destroy-event"
def callbackQuit(self, event):
self.on_closing(None, None, None)
def callbackSettings(self, event):
dialogSettings(self.programSettings, parentWindow=self)
def callbackFlash(self, event):
dialogFirmware(self.programSettings, parent=self)
def callbackManualControl(self, event):
dialogManualControl(self.programSettings, parent=self)
def callbackDocu(self, event):
pass
def callbackAbout(self, event):
pass
# Create the notebook.#####################################################
def createSettingsBox(self):
boxSettings = gtk.VBox()
# Create model management editor. ************************************
self.frameModels = gtk.Frame(label="Models")
boxSettings.pack_start(self.frameModels, padding = 5)
self.frameModels.show()
# Create model list view using the model list.
self.modelListView = modelListView(self.programSettings, self.modelCollection, self.renderView, self.updateAllEntries, self.console)
self.frameModels.add(self.modelListView)
self.modelListView.show()
# Create notebook. ***************************************************
self.notebook = monkeyprintGuiHelper.notebook()
boxSettings.pack_start(self.notebook)
self.notebook.show()
# Create model page, append to notebook and pass custom function.
self.createModelTab()
self.notebook.append_page(self.modelTab, gtk.Label('Models'))
self.notebook.set_custom_function(0, self.tabSwitchModelUpdate)
# Create supports page, append to notebook and pass custom function.
self.createSupportsTab()
self.notebook.append_page(self.supportsTab, gtk.Label('Supports'))
self.notebook.set_custom_function(1, self.tabSwitchSupportsUpdate)
# Add slicing page, append to notebook and pass custom function.
self.createSlicingTab()
self.notebook.append_page(self.slicingTab, gtk.Label('Slicing'))
self.notebook.set_custom_function(2, self.tabSwitchSlicesUpdate)
# Add print page.
self.createPrintTab()
self.notebook.append_page(self.printTab, gtk.Label('Print'))
self.notebook.set_custom_function(3, self.tabSwitchPrintUpdate)
# Set gui state. This controls which tabs are clickable.**************
# 0: Model modifications active.
# 1: Model modifications, supports and slicing active.
# 2: All active.
# Use setGuiState function to set the state. Do not set manually.
self.setGuiState(0)
# Create console for debug output.************************************
# Create frame.
self.frameConsole = gtk.Frame(label="Output log")
boxSettings.pack_start(self.frameConsole, padding=5)
self.frameConsole.show()
# Custom scrolled window.
self.consoleView = monkeyprintGuiHelper.consoleView(self.console)
self.frameConsole.add(self.consoleView)
# Return the box. ****************************************************
return boxSettings
# Create notebook pages. ##################################################
# Model page.
def createModelTab(self):
# Create tab box.
self.modelTab = gtk.VBox()
self.modelTab.show()
# Create model modification frame.
self.frameModifications = gtk.Frame(label="Model modifications")
self.modelTab.pack_start(self.frameModifications, expand=True, fill=True, padding=5)
self.frameModifications.show()
self.boxModelModifications = gtk.VBox()
self.frameModifications.add(self.boxModelModifications)
self.boxModelModifications.show()
self.entryScaling = monkeyprintGuiHelper.entry('scaling', modelCollection=self.modelCollection, customFunctions=[self.updateCurrentModel, self.renderView.render, self.updateAllEntries])
self.boxModelModifications.pack_start(self.entryScaling, expand=False, fill=False)
self.entryRotationX = monkeyprintGuiHelper.entry('rotationX', modelCollection=self.modelCollection, customFunctions=[self.updateCurrentModel, self.renderView.render, self.updateAllEntries])
self.boxModelModifications.pack_start(self.entryRotationX, expand=False, fill=False)
self.entryRotationY = monkeyprintGuiHelper.entry('rotationY', modelCollection=self.modelCollection, customFunctions=[self.updateCurrentModel, self.renderView.render, self.updateAllEntries])
self.boxModelModifications.pack_start(self.entryRotationY, expand=False, fill=False)
self.entryRotationZ = monkeyprintGuiHelper.entry('rotationZ', modelCollection=self.modelCollection, customFunctions=[self.updateCurrentModel, self.renderView.render, self.updateAllEntries])
self.boxModelModifications.pack_start(self.entryRotationZ, expand=False, fill=False)
self.entryPositionX = monkeyprintGuiHelper.entry('positionX', modelCollection=self.modelCollection, customFunctions=[self.updateCurrentModel, self.renderView.render, self.updateAllEntries])
self.boxModelModifications.pack_start(self.entryPositionX, expand=False, fill=False)
self.entryPositionY = monkeyprintGuiHelper.entry('positionY', modelCollection=self.modelCollection, customFunctions=[self.updateCurrentModel, self.renderView.render, self.updateAllEntries])
self.boxModelModifications.pack_start(self.entryPositionY, expand=False, fill=False)
self.entryBottomClearance = monkeyprintGuiHelper.entry('bottomClearance', modelCollection=self.modelCollection, customFunctions=[self.updateCurrentModel, self.renderView.render, self.updateAllEntries])
self.boxModelModifications.pack_start(self.entryBottomClearance, expand=False, fill=False)
# Supports page.
def createSupportsTab(self):
# Create tab box.
self.supportsTab = gtk.VBox()
self.supportsTab.show()
# Create support pattern frame.
self.frameSupportPattern = gtk.Frame(label="Support pattern")
self.supportsTab.pack_start(self.frameSupportPattern, expand=False, fill=False, padding=5)
self.frameSupportPattern.show()
self.boxSupportPattern = gtk.VBox()
self.frameSupportPattern.add(self.boxSupportPattern)
self.boxSupportPattern.show()
self.entryOverhangAngle = monkeyprintGuiHelper.entry('overhangAngle', modelCollection=self.modelCollection, customFunctions=[self.updateCurrentModel, self.renderView.render, self.updateAllEntries])