chiark / gitweb /
b575a171092b796d5d3b6a4948e0859cb0caad99
[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 util import profile
8 from util import sliceRun
9 from util import exporer
10 from util import gcodeInterpreter
11
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
17                 self.abort = False
18                 
19                 box = wx.StaticBox(self, -1, filelist[0])
20                 self.sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
21
22                 mainSizer = wx.BoxSizer(wx.VERTICAL) 
23                 mainSizer.Add(self.sizer, 0, flag=wx.EXPAND)
24
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)
32
33                 self.Bind(wx.EVT_BUTTON, self.OnAbort, self.abortButton)
34
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")
41                 cmdList = []
42                 for filename in self.filelist:
43                         idx = self.filelist.index(filename)
44                         #print filename, idx
45                         if idx > 0:
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)
57         
58         def OnAbort(self, e):
59                 if self.abort:
60                         self.mainWindow.removeSliceProgress(self)
61                 else:
62                         self.abort = True
63         
64         def OnShowGCode(self, e):
65                 self.mainWindow.preview3d.loadModelFiles(self.filelist)
66                 self.mainWindow.preview3d.setViewMode("GCode")
67         
68         def OnShowLog(self, e):
69                 LogWindow('\n'.join(self.progressLog))
70         
71         def OnOpenFileLocation(self, e):
72                 exporer.openExporer(sliceRun.getExportFilename(self.filelist[0]))
73         
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))
80         
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()
94                         if cost != False:
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)
108                 else:
109                         self.statusText.SetLabel("Something went wrong during slicing!")
110                 self.sizer.Add(self.abortButton, 0)
111                 self.sizer.Layout()
112                 self.Layout()
113                 self.abort = True
114                 if self.mainWindow.preview3d.loadReModelFiles(self.filelist):
115                         self.mainWindow.preview3d.setViewMode("GCode")
116                 taskbar.setBusy(self.GetParent(), False)
117         
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
125                 
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))
130
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
137                 self.fileIdx = 0
138                 self.start()
139
140         def run(self):
141                 p = sliceRun.startSliceCommandProcess(self.cmdList[self.fileIdx])
142                 line = p.stdout.readline()
143                 self.progressLog = []
144                 maxValue = 1
145                 while(len(line) > 0):
146                         line = line.rstrip()
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)
152                         else:
153                                 self.progressLog.append(line)
154                                 wx.CallAfter(self.notifyWindow.statusText.SetLabel, line)
155                         if self.notifyWindow.abort:
156                                 p.terminate()
157                                 wx.CallAfter(self.notifyWindow.statusText.SetLabel, "Aborted by user.")
158                                 return
159                         line = p.stdout.readline()
160                 self.returnCode = p.wait()
161                 self.fileIdx += 1
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))
170                         gcodefile.close()
171                         ret = profile.runPostProcessingPlugins(gcodeFilename)
172                         if ret != None:
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)
178                 else:
179                         self.run()
180         
181         def _stitchMultiExtruder(self):
182                 files = []
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"))
189                         else:
190                                 return
191                 
192                 currentExtruder = 0
193                 resultFile.write('T%d\n' % (currentExtruder))
194                 layerNr = -1
195                 hasLine = True
196                 while hasLine:
197                         hasLine = False
198                         for f in files:
199                                 layerHasLine = False
200                                 for line in f:
201                                         hasLine = True
202                                         if line.startswith(';LAYER:'):
203                                                 break
204                                         if 'Z' in line:
205                                                 lastZ = float(re.search('Z([^\s]+)', line).group(1))
206                                         if not layerHasLine:
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
216                                                 layerHasLine = True
217                                         resultFile.write(line)
218                         layerNr += 1
219                 for f in files:
220                         f.close()
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'))
225                 resultFile.close()
226
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))
232                 self.Centre()
233                 self.Show(True)
234