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