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