chiark / gitweb /
Update on rotation tools, this breaks a lot of functionality, but is really needed.
[cura.git] / Cura / util / profile.py
1 from __future__ import absolute_import
2 from __future__ import division
3
4 import os, traceback, math, re, zlib, base64, time, sys, platform, glob, string, stat
5 import cPickle as pickle
6 if sys.version_info[0] < 3:
7         import ConfigParser
8 else:
9         import configparser as ConfigParser
10
11 from Cura.util import resources
12 from Cura.util import version
13
14 #########################################################
15 ## Default settings when none are found.
16 #########################################################
17
18 #Single place to store the defaults, so we have a consistent set of default settings.
19 profileDefaultSettings = {
20         'nozzle_size': '0.4',
21         'layer_height': '0.2',
22         'wall_thickness': '0.8',
23         'solid_layer_thickness': '0.6',
24         'fill_density': '20',
25         'skirt_line_count': '1',
26         'skirt_gap': '3.0',
27         'print_speed': '50',
28         'print_temperature': '220',
29         'print_bed_temperature': '70',
30         'support': 'None',
31         'filament_diameter': '2.89',
32         'filament_density': '1.00',
33         'retraction_min_travel': '5.0',
34         'retraction_enable': 'False',
35         'retraction_speed': '40.0',
36         'retraction_amount': '4.5',
37         'retraction_extra': '0.0',
38         'retract_on_jumps_only': 'True',
39         'travel_speed': '150',
40         'max_z_speed': '3.0',
41         'bottom_layer_speed': '20',
42         'cool_min_layer_time': '5',
43         'fan_enabled': 'True',
44         'fan_layer': '1',
45         'fan_speed': '100',
46         'fan_speed_max': '100',
47         'model_matrix': '1,0,0,0,1,0,0,0,1',
48         'extra_base_wall_thickness': '0.0',
49         'sequence': 'Loops > Perimeter > Infill',
50         'force_first_layer_sequence': 'True',
51         'infill_type': 'Line',
52         'solid_top': 'True',
53         'fill_overlap': '15',
54         'support_rate': '50',
55         'support_distance': '0.5',
56         'support_dual_extrusion': 'False',
57         'joris': 'False',
58         'enable_skin': 'False',
59         'enable_raft': 'False',
60         'cool_min_feedrate': '10',
61         'bridge_speed': '100',
62         'raft_margin': '5',
63         'raft_base_material_amount': '100',
64         'raft_interface_material_amount': '100',
65         'bottom_thickness': '0.3',
66         'hop_on_move': 'False',
67         'plugin_config': '',
68         'object_center_x': '-1',
69         'object_center_y': '-1',
70         
71         'gcode_extension': 'gcode',
72         'alternative_center': '',
73         'clear_z': '0.0',
74         'extruder': '0',
75 }
76 alterationDefault = {
77 #######################################################################################
78         'start.gcode': """;Sliced {filename} at: {day} {date} {time}
79 ;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
80 ;Print time: {print_time}
81 ;Filament used: {filament_amount}m {filament_weight}g
82 ;Filament cost: {filament_cost}
83 G21        ;metric values
84 G90        ;absolute positioning
85 M107       ;start with the fan off
86
87 G28 X0 Y0  ;move X/Y to min endstops
88 G28 Z0     ;move Z to min endstops
89 G92 X0 Y0 Z0 E0         ;reset software position to front/left/z=0.0
90
91 G1 Z15.0 F{max_z_speed} ;move the platform down 15mm
92
93 G92 E0                  ;zero the extruded length
94 G1 F200 E3              ;extrude 3mm of feed stock
95 G92 E0                  ;zero the extruded length again
96 G1 F{travel_speed}
97 """,
98 #######################################################################################
99         'end.gcode': """;End GCode
100 M104 S0                     ;extruder heater off
101 M140 S0                     ;heated bed heater off (if you have it)
102
103 G91                                    ;relative positioning
104 G1 E-1 F300                            ;retract the filament a bit before lifting the nozzle, to release some of the pressure
105 G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
106 G28 X0 Y0                              ;move X/Y to min endstops, so the head is out of the way
107
108 M84                         ;steppers off
109 G90                         ;absolute positioning
110 """,
111 #######################################################################################
112         'support_start.gcode': '',
113         'support_end.gcode': '',
114         'cool_start.gcode': '',
115         'cool_end.gcode': '',
116         'replace.csv': '',
117 #######################################################################################
118         'nextobject.gcode': """;Move to next object on the platform. clear_z is the minimal z height we need to make sure we do not hit any objects.
119 G92 E0
120
121 G91                                    ;relative positioning
122 G1 E-1 F300                            ;retract the filament a bit before lifting the nozzle, to release some of the pressure
123 G1 Z+0.5 E-5 F{travel_speed}           ;move Z up a bit and retract filament even more
124 G90                                    ;absolute positioning
125
126 G1 Z{clear_z} F{max_z_speed}
127 G92 E0
128 G1 X{object_center_x} Y{object_center_x} F{travel_speed}
129 G1 F200 E6
130 G92 E0
131 """,
132 #######################################################################################
133         'switchExtruder.gcode': """;Switch between the current extruder and the next extruder, when printing with multiple extruders.
134 G92 E0
135 G1 E-15 F5000
136 G92 E0
137 T{extruder}
138 G1 E15 F5000
139 G92 E0
140 """,
141 }
142 preferencesDefaultSettings = {
143         'startMode': 'Simple',
144         'lastFile': os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'resources', 'example', 'UltimakerRobot_support.stl')),
145         'machine_width': '205',
146         'machine_depth': '205',
147         'machine_height': '200',
148         'machine_type': 'unknown',
149         'machine_center_is_zero': 'False',
150         'ultimaker_extruder_upgrade': 'False',
151         'has_heated_bed': 'False',
152         'extruder_amount': '1',
153         'extruder_offset_x1': '-22.0',
154         'extruder_offset_y1': '0.0',
155         'extruder_offset_x2': '0.0',
156         'extruder_offset_y2': '0.0',
157         'extruder_offset_x3': '0.0',
158         'extruder_offset_y3': '0.0',
159         'filament_density': '1300',
160         'steps_per_e': '0',
161         'serial_port': 'AUTO',
162         'serial_port_auto': '',
163         'serial_baud': 'AUTO',
164         'serial_baud_auto': '',
165         'slicer': 'Cura (Skeinforge based)',
166         'save_profile': 'False',
167         'filament_cost_kg': '0',
168         'filament_cost_meter': '0',
169         'sdpath': '',
170         'sdshortnames': 'False',
171         'check_for_updates': 'True',
172
173         'planner_always_autoplace': 'True',
174         'extruder_head_size_min_x': '75.0',
175         'extruder_head_size_min_y': '18.0',
176         'extruder_head_size_max_x': '18.0',
177         'extruder_head_size_max_y': '35.0',
178         'extruder_head_size_height': '60.0',
179         
180         'model_colour': '#72CB30',
181         'model_colour2': '#CB3030',
182         'model_colour3': '#DDD93C',
183         'model_colour4': '#4550D3',
184 }
185
186 #########################################################
187 ## Profile and preferences functions
188 #########################################################
189
190 ## Profile functions
191 def getDefaultProfilePath():
192         if platform.system() == "Windows":
193                 basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
194                 #If we have a frozen python install, we need to step out of the library.zip
195                 if hasattr(sys, 'frozen'):
196                         basePath = os.path.normpath(os.path.join(basePath, ".."))
197         else:
198                 basePath = os.path.expanduser('~/.cura/%s' % version.getVersion(False))
199         if not os.path.isdir(basePath):
200                 os.makedirs(basePath)
201         return os.path.join(basePath, 'current_profile.ini')
202
203 def loadGlobalProfile(filename):
204         #Read a configuration file as global config
205         global globalProfileParser
206         globalProfileParser = ConfigParser.ConfigParser()
207         globalProfileParser.read(filename)
208
209 def resetGlobalProfile():
210         #Read a configuration file as global config
211         global globalProfileParser
212         globalProfileParser = ConfigParser.ConfigParser()
213
214         if getPreference('machine_type') == 'ultimaker':
215                 putProfileSetting('nozzle_size', '0.4')
216                 if getPreference('ultimaker_extruder_upgrade') == 'True':
217                         putProfileSetting('retraction_enable', 'True')
218         else:
219                 putProfileSetting('nozzle_size', '0.5')
220
221 def saveGlobalProfile(filename):
222         #Save the current profile to an ini file
223         globalProfileParser.write(open(filename, 'w'))
224
225 def loadGlobalProfileFromString(options):
226         global globalProfileParser
227         globalProfileParser = ConfigParser.ConfigParser()
228         globalProfileParser.add_section('profile')
229         globalProfileParser.add_section('alterations')
230         options = base64.b64decode(options)
231         options = zlib.decompress(options)
232         (profileOpts, alt) = options.split('\f', 1)
233         for option in profileOpts.split('\b'):
234                 if len(option) > 0:
235                         (key, value) = option.split('=', 1)
236                         globalProfileParser.set('profile', key, value)
237         for option in alt.split('\b'):
238                 if len(option) > 0:
239                         (key, value) = option.split('=', 1)
240                         globalProfileParser.set('alterations', key, value)
241
242 def getGlobalProfileString():
243         global globalProfileParser
244         if not globals().has_key('globalProfileParser'):
245                 loadGlobalProfile(getDefaultProfilePath())
246         
247         p = []
248         alt = []
249         tempDone = []
250         if globalProfileParser.has_section('profile'):
251                 for key in globalProfileParser.options('profile'):
252                         if key in tempOverride:
253                                 p.append(key + "=" + tempOverride[key])
254                                 tempDone.append(key)
255                         else:
256                                 p.append(key + "=" + globalProfileParser.get('profile', key))
257         if globalProfileParser.has_section('alterations'):
258                 for key in globalProfileParser.options('alterations'):
259                         if key in tempOverride:
260                                 p.append(key + "=" + tempOverride[key])
261                                 tempDone.append(key)
262                         else:
263                                 alt.append(key + "=" + globalProfileParser.get('alterations', key))
264         for key in tempOverride:
265                 if key not in tempDone:
266                         p.append(key + "=" + tempOverride[key])
267         ret = '\b'.join(p) + '\f' + '\b'.join(alt)
268         ret = base64.b64encode(zlib.compress(ret, 9))
269         return ret
270
271 def getProfileSetting(name):
272         if name in tempOverride:
273                 return unicode(tempOverride[name], "utf-8")
274         #Check if we have a configuration file loaded, else load the default.
275         if not globals().has_key('globalProfileParser'):
276                 loadGlobalProfile(getDefaultProfilePath())
277         if not globalProfileParser.has_option('profile', name):
278                 if name in profileDefaultSettings:
279                         default = profileDefaultSettings[name]
280                 else:
281                         print("Missing default setting for: '" + name + "'")
282                         profileDefaultSettings[name] = ''
283                         default = ''
284                 if not globalProfileParser.has_section('profile'):
285                         globalProfileParser.add_section('profile')
286                 globalProfileParser.set('profile', name, str(default))
287                 #print(name + " not found in profile, so using default: " + str(default))
288                 return default
289         return globalProfileParser.get('profile', name)
290
291 def getProfileSettingFloat(name):
292         try:
293                 setting = getProfileSetting(name).replace(',', '.')
294                 return float(eval(setting, {}, {}))
295         except (ValueError, SyntaxError, TypeError):
296                 return 0.0
297
298 def putProfileSetting(name, value):
299         #Check if we have a configuration file loaded, else load the default.
300         if not globals().has_key('globalProfileParser'):
301                 loadGlobalProfile(getDefaultProfilePath())
302         if not globalProfileParser.has_section('profile'):
303                 globalProfileParser.add_section('profile')
304         globalProfileParser.set('profile', name, str(value))
305
306 def isProfileSetting(name):
307         if name in profileDefaultSettings:
308                 return True
309         return False
310
311 ## Preferences functions
312 global globalPreferenceParser
313 globalPreferenceParser = None
314
315 def getPreferencePath():
316         if platform.system() == "Windows":
317                 basePath = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
318                 #If we have a frozen python install, we need to step out of the library.zip
319                 if hasattr(sys, 'frozen'):
320                         basePath = os.path.normpath(os.path.join(basePath, ".."))
321         else:
322                 basePath = os.path.expanduser('~/.cura/%s' % version.getVersion(False))
323         if not os.path.isdir(basePath):
324                 os.makedirs(basePath)
325         return os.path.join(basePath, 'preferences.ini')
326
327 def getPreferenceFloat(name):
328         try:
329                 setting = getPreference(name).replace(',', '.')
330                 return float(eval(setting, {}, {}))
331         except (ValueError, SyntaxError, TypeError):
332                 return 0.0
333
334 def getPreferenceColour(name):
335         colorString = getPreference(name)
336         return [float(int(colorString[1:3], 16)) / 255, float(int(colorString[3:5], 16)) / 255, float(int(colorString[5:7], 16)) / 255, 1.0]
337
338 def getPreference(name):
339         if name in tempOverride:
340                 return unicode(tempOverride[name])
341         global globalPreferenceParser
342         if globalPreferenceParser is None:
343                 globalPreferenceParser = ConfigParser.ConfigParser()
344                 globalPreferenceParser.read(getPreferencePath())
345         if not globalPreferenceParser.has_option('preference', name):
346                 if name in preferencesDefaultSettings:
347                         default = preferencesDefaultSettings[name]
348                 else:
349                         print("Missing default setting for: '" + name + "'")
350                         preferencesDefaultSettings[name] = ''
351                         default = ''
352                 if not globalPreferenceParser.has_section('preference'):
353                         globalPreferenceParser.add_section('preference')
354                 globalPreferenceParser.set('preference', name, str(default))
355                 #print(name + " not found in preferences, so using default: " + str(default))
356                 return default
357         return unicode(globalPreferenceParser.get('preference', name), "utf-8")
358
359 def putPreference(name, value):
360         #Check if we have a configuration file loaded, else load the default.
361         global globalPreferenceParser
362         if globalPreferenceParser == None:
363                 globalPreferenceParser = ConfigParser.ConfigParser()
364                 globalPreferenceParser.read(getPreferencePath())
365         if not globalPreferenceParser.has_section('preference'):
366                 globalPreferenceParser.add_section('preference')
367         globalPreferenceParser.set('preference', name, unicode(value).encode("utf-8"))
368         globalPreferenceParser.write(open(getPreferencePath(), 'w'))
369
370 def isPreference(name):
371         if name in preferencesDefaultSettings:
372                 return True
373         return False
374
375 ## Temp overrides for multi-extruder slicing and the project planner.
376 tempOverride = {}
377 def setTempOverride(name, value):
378         tempOverride[name] = unicode(value).encode("utf-8")
379 def clearTempOverride(name):
380         del tempOverride[name]
381 def resetTempOverride():
382         tempOverride.clear()
383
384 #########################################################
385 ## Utility functions to calculate common profile values
386 #########################################################
387 def calculateEdgeWidth():
388         wallThickness = getProfileSettingFloat('wall_thickness')
389         nozzleSize = getProfileSettingFloat('nozzle_size')
390         
391         if wallThickness < nozzleSize:
392                 return wallThickness
393
394         lineCount = int(wallThickness / nozzleSize + 0.0001)
395         lineWidth = wallThickness / lineCount
396         lineWidthAlt = wallThickness / (lineCount + 1)
397         if lineWidth > nozzleSize * 1.5:
398                 return lineWidthAlt
399         return lineWidth
400
401 def calculateLineCount():
402         wallThickness = getProfileSettingFloat('wall_thickness')
403         nozzleSize = getProfileSettingFloat('nozzle_size')
404         
405         if wallThickness < nozzleSize:
406                 return 1
407
408         lineCount = int(wallThickness / nozzleSize + 0.0001)
409         lineWidth = wallThickness / lineCount
410         lineWidthAlt = wallThickness / (lineCount + 1)
411         if lineWidth > nozzleSize * 1.5:
412                 return lineCount + 1
413         return lineCount
414
415 def calculateSolidLayerCount():
416         layerHeight = getProfileSettingFloat('layer_height')
417         solidThickness = getProfileSettingFloat('solid_layer_thickness')
418         return int(math.ceil(solidThickness / layerHeight - 0.0001))
419
420 def getMachineCenterCoords():
421         if getPreference('machine_center_is_zero') == 'True':
422                 return [0, 0]
423         return [getPreferenceFloat('machine_width') / 2, getPreferenceFloat('machine_depth') / 2]
424
425 def getObjectMatrix():
426         scale = getProfileSettingFloat('model_scale')
427         return map(lambda x: float(x) * scale, getProfileSetting('model_matrix').split(','))
428
429 #########################################################
430 ## Alteration file functions
431 #########################################################
432 def replaceTagMatch(m):
433         pre = m.group(1)
434         tag = m.group(2)
435         if tag == 'time':
436                 return pre + time.strftime('%H:%M:%S').encode('utf-8', 'replace')
437         if tag == 'date':
438                 return pre + time.strftime('%d %b %Y').encode('utf-8', 'replace')
439         if tag == 'day':
440                 return pre + time.strftime('%a').encode('utf-8', 'replace')
441         if tag == 'print_time':
442                 return pre + '#P_TIME#'
443         if tag == 'filament_amount':
444                 return pre + '#F_AMNT#'
445         if tag == 'filament_weight':
446                 return pre + '#F_WGHT#'
447         if tag == 'filament_cost':
448                 return pre + '#F_COST#'
449         if pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'max_z_speed', 'bottom_layer_speed', 'cool_min_feedrate']:
450                 f = getProfileSettingFloat(tag) * 60
451         elif isProfileSetting(tag):
452                 f = getProfileSettingFloat(tag)
453         elif isPreference(tag):
454                 f = getProfileSettingFloat(tag)
455         else:
456                 return '%s?%s?' % (pre, tag)
457         if (f % 1) == 0:
458                 return pre + str(int(f))
459         return pre + str(f)
460
461 def replaceGCodeTags(filename, gcodeInt):
462         f = open(filename, 'r+')
463         data = f.read(2048)
464         data = data.replace('#P_TIME#', ('%5d:%02d' % (int(gcodeInt.totalMoveTimeMinute / 60), int(gcodeInt.totalMoveTimeMinute % 60)))[-8:])
465         data = data.replace('#F_AMNT#', ('%8.2f' % (gcodeInt.extrusionAmount / 1000))[-8:])
466         data = data.replace('#F_WGHT#', ('%8.2f' % (gcodeInt.calculateWeight() * 1000))[-8:])
467         cost = gcodeInt.calculateCost()
468         if cost is None:
469                 cost = 'Unknown'
470         data = data.replace('#F_COST#', ('%8s' % (cost.split(' ')[0]))[-8:])
471         f.seek(0)
472         f.write(data)
473         f.close()
474
475 ### Get aleration raw contents. (Used internally in Cura)
476 def getAlterationFile(filename):
477         #Check if we have a configuration file loaded, else load the default.
478         if not globals().has_key('globalProfileParser'):
479                 loadGlobalProfile(getDefaultProfilePath())
480         
481         if not globalProfileParser.has_option('alterations', filename):
482                 if filename in alterationDefault:
483                         default = alterationDefault[filename]
484                 else:
485                         print("Missing default alteration for: '" + filename + "'")
486                         alterationDefault[filename] = ''
487                         default = ''
488                 if not globalProfileParser.has_section('alterations'):
489                         globalProfileParser.add_section('alterations')
490                 #print("Using default for: %s" % (filename))
491                 globalProfileParser.set('alterations', filename, default)
492         return unicode(globalProfileParser.get('alterations', filename), "utf-8")
493
494 def setAlterationFile(filename, value):
495         #Check if we have a configuration file loaded, else load the default.
496         if not globals().has_key('globalProfileParser'):
497                 loadGlobalProfile(getDefaultProfilePath())
498         if not globalProfileParser.has_section('alterations'):
499                 globalProfileParser.add_section('alterations')
500         globalProfileParser.set('alterations', filename, value.encode("utf-8"))
501         saveGlobalProfile(getDefaultProfilePath())
502
503 ### Get the alteration file for output. (Used by Skeinforge)
504 def getAlterationFileContents(filename):
505         prefix = ''
506         postfix = ''
507         alterationContents = getAlterationFile(filename)
508         if filename == 'start.gcode':
509                 #For the start code, hack the temperature and the steps per E value into it. So the temperature is reached before the start code extrusion.
510                 #We also set our steps per E here, if configured.
511                 eSteps = getPreferenceFloat('steps_per_e')
512                 if eSteps > 0:
513                         prefix += 'M92 E%f\n' % (eSteps)
514                 temp = getProfileSettingFloat('print_temperature')
515                 bedTemp = 0
516                 if getPreference('has_heated_bed') == 'True':
517                         bedTemp = getProfileSettingFloat('print_bed_temperature')
518                 
519                 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:
520                         prefix += 'M140 S%f\n' % (bedTemp)
521                 if temp > 0 and not '{print_temperature}' in alterationContents:
522                         prefix += 'M109 S%f\n' % (temp)
523                 if bedTemp > 0 and not '{print_bed_temperature}' in alterationContents:
524                         prefix += 'M190 S%f\n' % (bedTemp)
525         elif filename == 'end.gcode':
526                 #Append the profile string to the end of the GCode, so we can load it from the GCode file later.
527                 postfix = ';CURA_PROFILE_STRING:%s\n' % (getGlobalProfileString())
528         elif filename == 'replace.csv':
529                 #Always remove the extruder on/off M codes. These are no longer needed in 5D printing.
530                 prefix = 'M101\nM103\n'
531         elif filename == 'support_start.gcode' or filename == 'support_end.gcode':
532                 #Add support start/end code 
533                 if getProfileSetting('support_dual_extrusion') == 'True' and int(getPreference('extruder_amount')) > 1:
534                         if filename == 'support_start.gcode':
535                                 setTempOverride('extruder', '1')
536                         else:
537                                 setTempOverride('extruder', '0')
538                         alterationContents = getAlterationFileContents('switchExtruder.gcode')
539                         clearTempOverride('extruder')
540                 else:
541                         alterationContents = ''
542         return unicode(prefix + re.sub("(.)\{([^\}]*)\}", replaceTagMatch, alterationContents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
543
544 ###### PLUGIN #####
545
546 def getPluginConfig():
547         try:
548                 return pickle.loads(getProfileSetting('plugin_config'))
549         except:
550                 return []
551
552 def setPluginConfig(config):
553         putProfileSetting('plugin_config', pickle.dumps(config))
554
555 def getPluginBasePaths():
556         ret = []
557         if platform.system() != "Windows":
558                 ret.append(os.path.expanduser('~/.cura/plugins/'))
559         if platform.system() == "Darwin" and hasattr(sys, 'frozen'):
560                 ret.append(os.path.normpath(os.path.join(resources.resourceBasePath, "Cura/plugins")))
561         else:
562                 ret.append(os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'plugins')))
563         return ret
564
565 def getPluginList():
566         ret = []
567         for basePath in getPluginBasePaths():
568                 for filename in glob.glob(os.path.join(basePath, '*.py')):
569                         filename = os.path.basename(filename)
570                         if filename.startswith('_'):
571                                 continue
572                         with open(os.path.join(basePath, filename), "r") as f:
573                                 item = {'filename': filename, 'name': None, 'info': None, 'type': None, 'params': []}
574                                 for line in f:
575                                         line = line.strip()
576                                         if not line.startswith('#'):
577                                                 break
578                                         line = line[1:].split(':', 1)
579                                         if len(line) != 2:
580                                                 continue
581                                         if line[0].upper() == 'NAME':
582                                                 item['name'] = line[1].strip()
583                                         elif line[0].upper() == 'INFO':
584                                                 item['info'] = line[1].strip()
585                                         elif line[0].upper() == 'TYPE':
586                                                 item['type'] = line[1].strip()
587                                         elif line[0].upper() == 'DEPEND':
588                                                 pass
589                                         elif line[0].upper() == 'PARAM':
590                                                 m = re.match('([a-zA-Z]*)\(([a-zA-Z_]*)(?::([^\)]*))?\) +(.*)', line[1].strip())
591                                                 if m is not None:
592                                                         item['params'].append({'name': m.group(1), 'type': m.group(2), 'default': m.group(3), 'description': m.group(4)})
593                                         else:
594                                                 print "Unknown item in effect meta data: %s %s" % (line[0], line[1])
595                                 if item['name'] != None and item['type'] == 'postprocess':
596                                         ret.append(item)
597         return ret
598
599 def runPostProcessingPlugins(gcodefilename):
600         pluginConfigList = getPluginConfig()
601         pluginList = getPluginList()
602         
603         for pluginConfig in pluginConfigList:
604                 plugin = None
605                 for pluginTest in pluginList:
606                         if pluginTest['filename'] == pluginConfig['filename']:
607                                 plugin = pluginTest
608                 if plugin is None:
609                         continue
610                 
611                 pythonFile = None
612                 for basePath in getPluginBasePaths():
613                         testFilename = os.path.join(basePath, pluginConfig['filename'])
614                         if os.path.isfile(testFilename):
615                                 pythonFile = testFilename
616                 if pythonFile is None:
617                         continue
618                 
619                 locals = {'filename': gcodefilename}
620                 for param in plugin['params']:
621                         value = param['default']
622                         if param['name'] in pluginConfig['params']:
623                                 value = pluginConfig['params'][param['name']]
624                         
625                         if param['type'] == 'float':
626                                 try:
627                                         value = float(value)
628                                 except:
629                                         value = float(param['default'])
630                         
631                         locals[param['name']] = value
632                 try:
633                         execfile(pythonFile, locals)
634                 except:
635                         locationInfo = traceback.extract_tb(sys.exc_info()[2])[-1]
636                         return "%s: '%s' @ %s:%s:%d" % (str(sys.exc_info()[0].__name__), str(sys.exc_info()[1]), os.path.basename(locationInfo[0]), locationInfo[2], locationInfo[1])
637         return None
638
639 def getSDcardDrives():
640         drives = ['']
641         if platform.system() == "Windows":
642                 from ctypes import windll
643                 bitmask = windll.kernel32.GetLogicalDrives()
644                 for letter in string.uppercase:
645                         if bitmask & 1:
646                                 drives.append(letter + ':/')
647                         bitmask >>= 1
648         if platform.system() == "Darwin":
649                 drives = []
650                 for volume in glob.glob('/Volumes/*'):
651                         if stat.S_ISLNK(os.lstat(volume).st_mode):
652                                 continue
653                         drives.append(volume)
654         return drives