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