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