1 from __future__ import absolute_import
4 import wx, sys, os, shutil, math, threading, subprocess, time, re
6 from gui import taskbar
7 from util import profile
8 from util import sliceRun
9 from util import exporer
10 from util import gcodeInterpreter
12 class sliceProgessPanel(wx.Panel):
13 def __init__(self, mainWindow, parent, filelist):
14 wx.Panel.__init__(self, parent, -1)
15 self.mainWindow = mainWindow
16 self.filelist = filelist
19 box = wx.StaticBox(self, -1, filelist[0])
20 self.sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
22 mainSizer = wx.BoxSizer(wx.VERTICAL)
23 mainSizer.Add(self.sizer, 0, flag=wx.EXPAND)
25 self.statusText = wx.StaticText(self, -1, "Starting...")
26 self.progressGauge = wx.Gauge(self, -1)
27 self.progressGauge.SetRange(10000 * len(filelist))
28 self.abortButton = wx.Button(self, -1, "X", style=wx.BU_EXACTFIT)
29 self.sizer.Add(self.statusText, 2, flag=wx.ALIGN_CENTER )
30 self.sizer.Add(self.progressGauge, 2)
31 self.sizer.Add(self.abortButton, 0)
33 self.Bind(wx.EVT_BUTTON, self.OnAbort, self.abortButton)
35 self.SetSizer(mainSizer)
36 self.prevStep = 'start'
37 self.totalDoneFactor = 0.0
38 self.startTime = time.time()
39 if profile.getPreference('save_profile') == 'True':
40 profile.saveGlobalProfile(self.filelist[0][: self.filelist[0].rfind('.')] + "_profile.ini")
42 for filename in self.filelist:
43 idx = self.filelist.index(filename)
46 profile.setTempOverride('fan_enabled', 'False')
47 profile.setTempOverride('skirt_line_count', '0')
48 profile.setTempOverride('machine_center_x', profile.getProfileSettingFloat('machine_center_x') - profile.getPreferenceFloat('extruder_offset_x%d' % (idx)))
49 profile.setTempOverride('machine_center_y', profile.getProfileSettingFloat('machine_center_y') - profile.getPreferenceFloat('extruder_offset_y%d' % (idx)))
50 profile.setTempOverride('alternative_center', self.filelist[0])
51 if len(self.filelist) > 1:
52 profile.setTempOverride('add_start_end_gcode', 'False')
53 profile.setTempOverride('gcode_extension', 'multi_extrude_tmp')
54 cmdList.append(sliceRun.getSliceCommand(filename))
55 profile.resetTempOverride()
56 self.thread = WorkerThread(self, filelist, cmdList)
60 self.mainWindow.removeSliceProgress(self)
64 def OnShowGCode(self, e):
65 self.mainWindow.preview3d.loadModelFiles(self.filelist)
66 self.mainWindow.preview3d.setViewMode("GCode")
68 def OnShowLog(self, e):
69 LogWindow('\n'.join(self.progressLog))
71 def OnOpenFileLocation(self, e):
72 exporer.openExporer(sliceRun.getExportFilename(self.filelist[0]))
74 def OnCopyToSD(self, e):
75 exportFilename = sliceRun.getExportFilename(self.filelist[0])
76 filename = os.path.basename(exportFilename)
77 if profile.getPreference('sdshortnames') == 'True':
78 filename = sliceRun.getShortFilename(filename)
79 shutil.copy(exportFilename, os.path.join(profile.getPreference('sdpath'), filename))
81 def OnSliceDone(self, result):
82 self.progressGauge.Destroy()
83 self.abortButton.Destroy()
84 self.progressLog = result.progressLog
85 self.logButton = wx.Button(self, -1, "Show Log")
86 self.abortButton = wx.Button(self, -1, "X", style=wx.BU_EXACTFIT)
87 self.Bind(wx.EVT_BUTTON, self.OnShowLog, self.logButton)
88 self.Bind(wx.EVT_BUTTON, self.OnAbort, self.abortButton)
89 self.sizer.Add(self.logButton, 0)
90 if result.returnCode == 0:
91 status = "Ready: Filament: %.2fm %.2fg" % (result.gcode.extrusionAmount / 1000, result.gcode.calculateWeight() * 1000)
92 status += " Print time: %02d:%02d" % (int(result.gcode.totalMoveTimeMinute / 60), int(result.gcode.totalMoveTimeMinute % 60))
93 cost = result.gcode.calculateCost()
95 status += " Cost: %s" % (cost)
96 self.statusText.SetLabel(status)
97 if exporer.hasExporer():
98 self.openFileLocationButton = wx.Button(self, -1, "Open file location")
99 self.Bind(wx.EVT_BUTTON, self.OnOpenFileLocation, self.openFileLocationButton)
100 self.sizer.Add(self.openFileLocationButton, 0)
101 if profile.getPreference('sdpath') != '':
102 self.copyToSDButton = wx.Button(self, -1, "To SDCard")
103 self.Bind(wx.EVT_BUTTON, self.OnCopyToSD, self.copyToSDButton)
104 self.sizer.Add(self.copyToSDButton, 0)
105 self.showButton = wx.Button(self, -1, "Show result")
106 self.Bind(wx.EVT_BUTTON, self.OnShowGCode, self.showButton)
107 self.sizer.Add(self.showButton, 0)
109 self.statusText.SetLabel("Something went wrong during slicing!")
110 self.sizer.Add(self.abortButton, 0)
114 if self.mainWindow.preview3d.loadReModelFiles(self.filelist):
115 self.mainWindow.preview3d.setViewMode("GCode")
116 taskbar.setBusy(self.GetParent(), False)
118 def SetProgress(self, stepName, layer, maxLayer):
119 if self.prevStep != stepName:
120 self.totalDoneFactor += sliceRun.sliceStepTimeFactor[self.prevStep]
121 newTime = time.time()
122 #print "#####" + str(newTime-self.startTime) + " " + self.prevStep + " -> " + stepName
123 self.startTime = newTime
124 self.prevStep = stepName
126 progresValue = ((self.totalDoneFactor + sliceRun.sliceStepTimeFactor[stepName] * layer / maxLayer) / sliceRun.totalRunTimeFactor) * 10000
127 self.progressGauge.SetValue(int(progresValue))
128 taskbar.setProgress(self.GetParent(), int(progresValue), self.progressGauge.GetRange())
129 self.statusText.SetLabel("Preparing: processing %s [%d/%d]" % (stepName, layer, maxLayer))
131 class WorkerThread(threading.Thread):
132 def __init__(self, notifyWindow, filelist, cmdList):
133 threading.Thread.__init__(self)
134 self.filelist = filelist
135 self.notifyWindow = notifyWindow
136 self.cmdList = cmdList
141 p = sliceRun.startSliceCommandProcess(self.cmdList[self.fileIdx])
142 line = p.stdout.readline()
143 self.progressLog = []
145 while(len(line) > 0):
147 if line[0:9] == "Progress[" and line[-1:] == "]":
148 progress = line[9:-1].split(":")
149 if len(progress) > 2:
150 maxValue = int(progress[2])
151 wx.CallAfter(self.notifyWindow.SetProgress, progress[0], int(progress[1]), maxValue)
153 self.progressLog.append(line)
154 wx.CallAfter(self.notifyWindow.statusText.SetLabel, line)
155 if self.notifyWindow.abort:
157 wx.CallAfter(self.notifyWindow.statusText.SetLabel, "Aborted by user.")
159 line = p.stdout.readline()
160 self.returnCode = p.wait()
162 if self.fileIdx == len(self.cmdList):
163 if len(self.filelist) > 1:
164 self._stitchMultiExtruder()
165 gcodeFilename = sliceRun.getExportFilename(self.filelist[0])
166 gcodefile = open(gcodeFilename, "a")
167 for logLine in self.progressLog:
168 if logLine.startswith('Model error('):
169 gcodefile.write(';%s\n' % (logLine))
171 ret = profile.runPostProcessingPlugins(gcodeFilename)
173 self.progressLog.append(ret)
174 self.gcode = gcodeInterpreter.gcode()
175 self.gcode.load(gcodeFilename)
176 profile.replaceGCodeTags(gcodeFilename, self.gcode)
177 wx.CallAfter(self.notifyWindow.OnSliceDone, self)
181 def _stitchMultiExtruder(self):
183 resultFile = open(sliceRun.getExportFilename(self.filelist[0]), "w")
184 resultFile.write(';TYPE:CUSTOM\n')
185 resultFile.write(profile.getAlterationFileContents('start.gcode'))
186 for filename in self.filelist:
187 if os.path.isfile(sliceRun.getExportFilename(filename, 'multi_extrude_tmp')):
188 files.append(open(sliceRun.getExportFilename(filename, 'multi_extrude_tmp'), "r"))
193 resultFile.write('T%d\n' % (currentExtruder))
202 if line.startswith(';LAYER:'):
205 lastZ = float(re.search('Z([^\s]+)', line).group(1))
207 nextExtruder = files.index(f)
208 resultFile.write(';LAYER:%d\n' % (layerNr))
209 resultFile.write(';EXTRUDER:%d\n' % (nextExtruder))
210 if nextExtruder != currentExtruder:
211 resultFile.write(';TYPE:CUSTOM\n')
212 profile.setTempOverride('extruder', nextExtruder)
213 resultFile.write(profile.getAlterationFileContents('switchExtruder.gcode'))
214 profile.resetTempOverride()
215 currentExtruder = nextExtruder
217 resultFile.write(line)
221 for filename in self.filelist:
222 os.remove(sliceRun.getExportFilename(filename, 'multi_extrude_tmp'))
223 resultFile.write(';TYPE:CUSTOM\n')
224 resultFile.write(profile.getAlterationFileContents('end.gcode'))
227 class LogWindow(wx.Frame):
228 def __init__(self, logText):
229 super(LogWindow, self).__init__(None, title="Slice log")
230 self.textBox = wx.TextCtrl(self, -1, logText, style=wx.TE_MULTILINE|wx.TE_DONTWRAP|wx.TE_READONLY)
231 self.SetSize((400,300))