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