1 from __future__ import absolute_import
4 import wx, sys, os, shutil, math, threading, subprocess, time, re
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
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
20 box = wx.StaticBox(self, -1, filelist[0])
21 self.sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
23 mainSizer = wx.BoxSizer(wx.VERTICAL)
24 mainSizer.Add(self.sizer, 0, flag=wx.EXPAND)
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)
34 self.Bind(wx.EVT_BUTTON, self.OnAbort, self.abortButton)
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")
43 for filename in self.filelist:
44 idx = self.filelist.index(filename)
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)
61 self.mainWindow.removeSliceProgress(self)
65 def OnShowGCode(self, e):
66 self.mainWindow.preview3d.loadModelFiles(self.filelist)
67 self.mainWindow.preview3d.setViewMode("GCode")
69 def OnShowLog(self, e):
70 LogWindow('\n'.join(self.progressLog))
72 def OnOpenFileLocation(self, e):
73 exporer.openExporer(sliceRun.getExportFilename(self.filelist[0]))
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())
81 if profile.getPreference('sdpath') == '':
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))
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()
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)
118 self.statusText.SetLabel("Something went wrong during slicing!")
119 self.sizer.Add(self.abortButton, 0)
123 if self.mainWindow.preview3d.loadReModelFiles(self.filelist):
124 self.mainWindow.preview3d.setViewMode("GCode")
125 taskbar.setBusy(self.GetParent(), False)
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
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))
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
150 p = sliceRun.startSliceCommandProcess(self.cmdList[self.fileIdx])
151 line = p.stdout.readline()
152 self.progressLog = []
154 while(len(line) > 0):
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)
162 self.progressLog.append(line)
163 wx.CallAfter(self.notifyWindow.statusText.SetLabel, line)
164 if self.notifyWindow.abort:
166 wx.CallAfter(self.notifyWindow.statusText.SetLabel, "Aborted by user.")
168 line = p.stdout.readline()
169 self.returnCode = p.wait()
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))
180 wx.CallAfter(self.notifyWindow.statusText.SetLabel, "Running plugins")
181 ret = profile.runPostProcessingPlugins(gcodeFilename)
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)
191 def _stitchMultiExtruder(self):
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"))
203 resultFile.write('T%d\n' % (currentExtruder))
212 if line.startswith(';LAYER:'):
215 lastZ = float(re.search('Z([^\s]+)', line).group(1))
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
227 resultFile.write(line)
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'))
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))