chiark / gitweb /
1500a59d42e7394f74e32f652dc606064b3a6ab2
[cura.git] / Cura / gui / sliceProgessPanel.py
1 from __future__ import absolute_import
2 import __init__
3
4 import wx, sys, os, shutil, math, threading, subprocess, time, re
5
6 from gui import taskbar
7 from gui import preferencesDialog
8 from util import profile
9 from util import sliceRun
10 from util import exporer
11 from util import gcodeInterpreter
12
13 class sliceProgessPanel(wx.Panel):
14         def __init__(self, mainWindow, parent, filelist):
15                 wx.Panel.__init__(self, parent, -1)
16                 self.mainWindow = mainWindow
17                 self.filelist = filelist
18                 self.abort = False
19                 
20                 box = wx.StaticBox(self, -1, filelist[0])
21                 self.sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
22
23                 mainSizer = wx.BoxSizer(wx.VERTICAL) 
24                 mainSizer.Add(self.sizer, 0, flag=wx.EXPAND)
25
26                 self.statusText = wx.StaticText(self, -1, "Starting...")
27                 self.progressGauge = wx.Gauge(self, -1)
28                 self.progressGauge.SetRange(10000 * len(filelist))
29                 self.abortButton = wx.Button(self, -1, "X", style=wx.BU_EXACTFIT)
30                 self.sizer.Add(self.statusText, 2, flag=wx.ALIGN_CENTER )
31                 self.sizer.Add(self.progressGauge, 2)
32                 self.sizer.Add(self.abortButton, 0)
33
34                 self.Bind(wx.EVT_BUTTON, self.OnAbort, self.abortButton)
35
36                 self.SetSizer(mainSizer)
37                 self.prevStep = 'start'
38                 self.totalDoneFactor = 0.0
39                 self.startTime = time.time()
40                 if profile.getPreference('save_profile') == 'True':
41                         profile.saveGlobalProfile(self.filelist[0][: self.filelist[0].rfind('.')] + "_profile.ini")
42                 cmdList = []
43                 for filename in self.filelist:
44                         idx = self.filelist.index(filename)
45                         #print filename, idx
46                         if idx > 0:
47                                 profile.setTempOverride('fan_enabled', 'False')
48                                 profile.setTempOverride('skirt_line_count', '0')
49                                 profile.setTempOverride('machine_center_x', profile.getProfileSettingFloat('machine_center_x') - profile.getPreferenceFloat('extruder_offset_x%d' % (idx)))
50                                 profile.setTempOverride('machine_center_y', profile.getProfileSettingFloat('machine_center_y') - profile.getPreferenceFloat('extruder_offset_y%d' % (idx)))
51                                 profile.setTempOverride('alternative_center', self.filelist[0])
52                         if len(self.filelist) > 1:
53                                 profile.setTempOverride('add_start_end_gcode', 'False')
54                                 profile.setTempOverride('gcode_extension', 'multi_extrude_tmp')
55                         cmdList.append(sliceRun.getSliceCommand(filename))
56                 profile.resetTempOverride()
57                 self.thread = WorkerThread(self, filelist, cmdList)
58         
59         def OnAbort(self, e):
60                 if self.abort:
61                         self.mainWindow.removeSliceProgress(self)
62                 else:
63                         self.abort = True
64         
65         def OnShowGCode(self, e):
66                 self.mainWindow.preview3d.loadModelFiles(self.filelist)
67                 self.mainWindow.preview3d.setViewMode("GCode")
68         
69         def OnShowLog(self, e):
70                 LogWindow('\n'.join(self.progressLog))
71         
72         def OnOpenFileLocation(self, e):
73                 exporer.openExporer(sliceRun.getExportFilename(self.filelist[0]))
74         
75         def OnCopyToSD(self, e):
76                 if profile.getPreference('sdpath') == '':
77                         wx.MessageBox("You need to configure your SD card drive first before you can copy files to it.\nOpening the preferences now.", 'No SD card drive.', wx.OK | wx.ICON_INFORMATION)
78                         prefDialog = preferencesDialog.preferencesDialog(self.GetParent())
79                         prefDialog.Centre()
80                         prefDialog.Show(True)
81                         if profile.getPreference('sdpath') == '':
82                                 print "No path set"
83                                 return
84                 exportFilename = sliceRun.getExportFilename(self.filelist[0])
85                 filename = os.path.basename(exportFilename)
86                 if profile.getPreference('sdshortnames') == 'True':
87                         filename = sliceRun.getShortFilename(filename)
88                 shutil.copy(exportFilename, os.path.join(profile.getPreference('sdpath'), filename))
89         
90         def OnSliceDone(self, result):
91                 self.progressGauge.Destroy()
92                 self.abortButton.Destroy()
93                 self.progressLog = result.progressLog
94                 self.logButton = wx.Button(self, -1, "Show Log")
95                 self.abortButton = wx.Button(self, -1, "X", style=wx.BU_EXACTFIT)
96                 self.Bind(wx.EVT_BUTTON, self.OnShowLog, self.logButton)
97                 self.Bind(wx.EVT_BUTTON, self.OnAbort, self.abortButton)
98                 self.sizer.Add(self.logButton, 0)
99                 if result.returnCode == 0:
100                         status = "Ready: Filament: %.2fm %.2fg" % (result.gcode.extrusionAmount / 1000, result.gcode.calculateWeight() * 1000)
101                         status += " Print time: %02d:%02d" % (int(result.gcode.totalMoveTimeMinute / 60), int(result.gcode.totalMoveTimeMinute % 60))
102                         cost = result.gcode.calculateCost()
103                         if cost != False:
104                                 status += " Cost: %s" % (cost)
105                         self.statusText.SetLabel(status)
106                         if exporer.hasExporer():
107                                 self.openFileLocationButton = wx.Button(self, -1, "Open file location")
108                                 self.Bind(wx.EVT_BUTTON, self.OnOpenFileLocation, self.openFileLocationButton)
109                                 self.sizer.Add(self.openFileLocationButton, 0)
110                         if len(profile.getSDcardDrives()) > 0:
111                                 self.copyToSDButton = wx.Button(self, -1, "Copy to SDCard")
112                                 self.Bind(wx.EVT_BUTTON, self.OnCopyToSD, self.copyToSDButton)
113                                 self.sizer.Add(self.copyToSDButton, 0)
114                         self.showButton = wx.Button(self, -1, "Show result")
115                         self.Bind(wx.EVT_BUTTON, self.OnShowGCode, self.showButton)
116                         self.sizer.Add(self.showButton, 0)
117                 else:
118                         self.statusText.SetLabel("Something went wrong during slicing!")
119                 self.sizer.Add(self.abortButton, 0)
120                 self.sizer.Layout()
121                 self.Layout()
122                 self.abort = True
123                 if self.mainWindow.preview3d.loadReModelFiles(self.filelist):
124                         self.mainWindow.preview3d.setViewMode("GCode")
125                 taskbar.setBusy(self.GetParent(), False)
126         
127         def SetProgress(self, stepName, layer, maxLayer):
128                 if self.prevStep != stepName:
129                         self.totalDoneFactor += sliceRun.sliceStepTimeFactor[self.prevStep]
130                         newTime = time.time()
131                         #print "#####" + str(newTime-self.startTime) + " " + self.prevStep + " -> " + stepName
132                         self.startTime = newTime
133                         self.prevStep = stepName
134                 
135                 progresValue = ((self.totalDoneFactor + sliceRun.sliceStepTimeFactor[stepName] * layer / maxLayer) / sliceRun.totalRunTimeFactor) * 10000
136                 self.progressGauge.SetValue(int(progresValue))
137                 taskbar.setProgress(self.GetParent(), int(progresValue), self.progressGauge.GetRange())
138                 self.statusText.SetLabel("Preparing: processing %s [%d/%d]" % (stepName, layer, maxLayer))
139
140 class WorkerThread(threading.Thread):
141         def __init__(self, notifyWindow, filelist, cmdList):
142                 threading.Thread.__init__(self)
143                 self.filelist = filelist
144                 self.notifyWindow = notifyWindow
145                 self.cmdList = cmdList
146                 self.fileIdx = 0
147                 self.start()
148
149         def run(self):
150                 p = sliceRun.startSliceCommandProcess(self.cmdList[self.fileIdx])
151                 line = p.stdout.readline()
152                 self.progressLog = []
153                 maxValue = 1
154                 while(len(line) > 0):
155                         line = line.rstrip()
156                         if line[0:9] == "Progress[" and line[-1:] == "]":
157                                 progress = line[9:-1].split(":")
158                                 if len(progress) > 2:
159                                         maxValue = int(progress[2])
160                                 wx.CallAfter(self.notifyWindow.SetProgress, progress[0], int(progress[1]), maxValue)
161                         else:
162                                 self.progressLog.append(line)
163                                 wx.CallAfter(self.notifyWindow.statusText.SetLabel, line)
164                         if self.notifyWindow.abort:
165                                 p.terminate()
166                                 wx.CallAfter(self.notifyWindow.statusText.SetLabel, "Aborted by user.")
167                                 return
168                         line = p.stdout.readline()
169                 self.returnCode = p.wait()
170                 self.fileIdx += 1
171                 if self.fileIdx == len(self.cmdList):
172                         if len(self.filelist) > 1:
173                                 self._stitchMultiExtruder()
174                         gcodeFilename = sliceRun.getExportFilename(self.filelist[0])
175                         gcodefile = open(gcodeFilename, "a")
176                         for logLine in self.progressLog:
177                                 if logLine.startswith('Model error('):
178                                         gcodefile.write(';%s\n' % (logLine))
179                         gcodefile.close()
180                         wx.CallAfter(self.notifyWindow.statusText.SetLabel, "Running plugins")
181                         ret = profile.runPostProcessingPlugins(gcodeFilename)
182                         if ret != None:
183                                 self.progressLog.append(ret)
184                         self.gcode = gcodeInterpreter.gcode()
185                         self.gcode.load(gcodeFilename)
186                         profile.replaceGCodeTags(gcodeFilename, self.gcode)
187                         wx.CallAfter(self.notifyWindow.OnSliceDone, self)
188                 else:
189                         self.run()
190         
191         def _stitchMultiExtruder(self):
192                 files = []
193                 resultFile = open(sliceRun.getExportFilename(self.filelist[0]), "w")
194                 resultFile.write(';TYPE:CUSTOM\n')
195                 resultFile.write(profile.getAlterationFileContents('start.gcode'))
196                 for filename in self.filelist:
197                         if os.path.isfile(sliceRun.getExportFilename(filename, 'multi_extrude_tmp')):
198                                 files.append(open(sliceRun.getExportFilename(filename, 'multi_extrude_tmp'), "r"))
199                         else:
200                                 return
201                 
202                 currentExtruder = 0
203                 resultFile.write('T%d\n' % (currentExtruder))
204                 layerNr = -1
205                 hasLine = True
206                 while hasLine:
207                         hasLine = False
208                         for f in files:
209                                 layerHasLine = False
210                                 for line in f:
211                                         hasLine = True
212                                         if line.startswith(';LAYER:'):
213                                                 break
214                                         if 'Z' in line:
215                                                 lastZ = float(re.search('Z([^\s]+)', line).group(1))
216                                         if not layerHasLine:
217                                                 nextExtruder = files.index(f)
218                                                 resultFile.write(';LAYER:%d\n' % (layerNr))
219                                                 resultFile.write(';EXTRUDER:%d\n' % (nextExtruder))
220                                                 if nextExtruder != currentExtruder:
221                                                         resultFile.write(';TYPE:CUSTOM\n')
222                                                         profile.setTempOverride('extruder', nextExtruder)
223                                                         resultFile.write(profile.getAlterationFileContents('switchExtruder.gcode'))
224                                                         profile.resetTempOverride()
225                                                         currentExtruder = nextExtruder
226                                                 layerHasLine = True
227                                         resultFile.write(line)
228                         layerNr += 1
229                 for f in files:
230                         f.close()
231                 for filename in self.filelist:
232                         os.remove(sliceRun.getExportFilename(filename, 'multi_extrude_tmp'))
233                 resultFile.write(';TYPE:CUSTOM\n')
234                 resultFile.write(profile.getAlterationFileContents('end.gcode'))
235                 resultFile.close()
236
237 class LogWindow(wx.Frame):
238         def __init__(self, logText):
239                 super(LogWindow, self).__init__(None, title="Slice log")
240                 self.textBox = wx.TextCtrl(self, -1, logText, style=wx.TE_MULTILINE|wx.TE_DONTWRAP|wx.TE_READONLY)
241                 self.SetSize((400,300))
242                 self.Centre()
243                 self.Show(True)
244