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