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