def __init__(self, slicedModel): self.slicedModel = slicedModel self.turnFanOnAtBeginning = config.getboolean(name, 'turn.on.fan.at.beginning') self.turnFanOffAtEnding = config.getboolean(name, 'turn.off.fan.at.end') self.nameOfCoolStartFile = config.get(name, 'cool.start.file') self.nameOfCoolEndFile = config.get(name, 'cool.end.file') self.coolStrategyName = config.get(name, 'strategy') self.coolStrategyPath = config.get(name, 'strategy.path') self.absoluteCoolStartFilePath = os.path.join('alterations', self.nameOfCoolStartFile) self.absoluteCoolEndFilePath = os.path.join('alterations', self.nameOfCoolEndFile) self.coolStartLines = archive.getTextLines(archive.getFileText(self.absoluteCoolEndFilePath, printWarning=False)) self.coolEndLines = archive.getTextLines(archive.getFileText(self.absoluteCoolEndFilePath, printWarning=False))
def __init__(self, slicedModel): self.slicedModel = slicedModel self.boundaryLayers = [] self.supportLayers = [] self.debug = config.getboolean(configSection, 'debug') self.supportLocation = config.get(configSection, 'location') self.supportMinimumAngle = config.getfloat(configSection, 'min.angle') self.minimumSupportRatio = math.tan( math.radians(self.supportMinimumAngle)) self.supportCrossHatchNthLayer = config.getint( configSection, 'crosshatch.every.nth.layer') self.supportFeedRate = config.getfloat('speed', 'feed.rate.support') self.supportFlowRateRatio = config.getfloat('speed', 'flow.rate.support.ratio') self.raftAdditionalMarginOverLengthPercent = config.getfloat( configSection, 'extension.percent') self.raftMargin = config.getfloat(configSection, 'extension.distance') self.infillOverhangOverExtrusionWidth = config.getfloat( configSection, 'infill.overhang.ratio') self.supportStartFile = config.get(configSection, 'support.start.file') self.supportEndFile = config.get(configSection, 'support.end.file') self.absoluteSupportStartFilePath = os.path.join( 'alterations', self.supportStartFile) self.absoluteSupportEndFilePath = os.path.join('alterations', self.supportEndFile) self.supportStartLines = archive.getTextLines( archive.getFileText(self.absoluteSupportStartFilePath, printWarning=False)) self.supportEndLines = archive.getTextLines( archive.getFileText(self.absoluteSupportEndFilePath, printWarning=False)) self.extrusionWidth = config.getfloat('carve', 'extrusion.width') self.supportGapOverPerimeterExtrusionWidth = config.getfloat( configSection, 'gap.over.perimeter.extrusion.width.ratio') self.supportOutset = self.extrusionWidth * self.supportGapOverPerimeterExtrusionWidth self.interfaceInfillDensity = config.getfloat( configSection, 'interface.infill.density') self.interfaceLayerThicknessRatio = config.getfloat( configSection, 'interface.layer.thickness.ratio') interfaceExtrusionWidth = self.extrusionWidth * self.interfaceLayerThicknessRatio self.interfaceStep = interfaceExtrusionWidth / self.interfaceInfillDensity self.cornerMinimum = self.slicedModel.carvingCornerMinimum self.cornerMaximum = self.slicedModel.carvingCornerMaximum self.cornerMinimumComplex = self.cornerMinimum.dropAxis() self.cornerMaximumComplex = self.cornerMaximum.dropAxis()
def getHeightGrid(fileName): 'Get heightGrid by fileName.' if 'models/' not in fileName: print('Warning, models/ was not in the absolute file path, so for security nothing will be done for:') print(fileName) print('The heightmap tool can only read a file which has models/ in the file path.') print('To import the file, move the file into a folder called model/ or a subfolder which is inside the model folder tree.') return pgmText = archive.getFileText(fileName) textLines = archive.getTextLines(pgmText) format = textLines[0].lower() sizeWords = textLines[2].split() numberOfColumns = int(sizeWords[0]) numberOfRows = int(sizeWords[1]) heights = [] if format == 'p1': addHeightsByBitmap(heights, textLines) elif format == 'p2': addHeightsByGraymap(heights, textLines) else: print('Warning, the file format was not recognized for:') print(fileName) print('Heightmap can only read the Netpbm Portable bitmap format and the Netpbm Portable graymap format.') print('The Netpbm formats are described at:') print('http://en.wikipedia.org/wiki/Netpbm_format') return [] heightGrid = [] heightIndex = 0 for rowIndex in xrange(numberOfRows): row = [] heightGrid.append(row) for columnIndex in xrange(numberOfColumns): row.append(heights[heightIndex]) heightIndex += 1 return heightGrid
def addInitializationToOutput(self): "Add initialization gcode to the output." self.addFromUpperLowerFile( self.prefaceRepository.nameOfStartFile.value ) # Add a start file if it exists. self.distanceFeedRate.addTagBracketedLine('creation', 'skeinforge') # GCode formatted comment absoluteFilePathUntilDot = os.path.abspath( __file__ )[ : os.path.abspath( __file__ ).rfind('.') ] if absoluteFilePathUntilDot == '/home/enrique/Desktop/backup/babbleold/script/reprap/fabmetheus/skeinforge_application/skeinforge_plugins/craft_plugins/preface': #is this script on Enrique's computer? archive.writeFileText( archive.getVersionFileName(), date.today().isoformat().replace('-', '.')[ 2 : ] ) versionText = archive.getFileText( archive.getVersionFileName() ) self.distanceFeedRate.addTagBracketedLine('version', versionText ) # GCode formatted comment self.distanceFeedRate.addLine('(<extruderInitialization>)') # GCode formatted comment if self.prefaceRepository.setPositioningToAbsolute.value: self.distanceFeedRate.addLine('G90') # Set positioning to absolute. if self.prefaceRepository.setUnitsToMillimeters.value: self.distanceFeedRate.addLine('G21') # Set units to millimeters. if self.prefaceRepository.startAtHome.value: self.distanceFeedRate.addLine('G28') # Start at home. if self.prefaceRepository.turnExtruderOffAtStartUp.value: self.distanceFeedRate.addLine('M103') # Turn extruder off. craftTypeName = skeinforge_profile.getCraftTypeName() self.distanceFeedRate.addTagBracketedLine('craftTypeName', craftTypeName ) self.distanceFeedRate.addTagBracketedLine('decimalPlacesCarried', self.distanceFeedRate.decimalPlacesCarried ) layerThickness = float( self.svgReader.sliceDictionary['layerThickness'] ) self.distanceFeedRate.addTagBracketedLine('layerThickness', self.distanceFeedRate.getRounded( layerThickness ) ) if self.prefaceRepository.meta.value: self.distanceFeedRate.addTagBracketedLine('meta', self.prefaceRepository.meta.value ) perimeterWidth = float( self.svgReader.sliceDictionary['perimeterWidth'] ) self.distanceFeedRate.addTagBracketedLine('perimeterWidth', self.distanceFeedRate.getRounded( perimeterWidth ) ) self.distanceFeedRate.addTagBracketedLine('profileName', skeinforge_profile.getProfileName( craftTypeName ) ) self.distanceFeedRate.addTagBracketedLine('procedureDone', self.svgReader.sliceDictionary['procedureDone'] ) self.distanceFeedRate.addTagBracketedLine('procedureDone', 'preface') self.distanceFeedRate.addLine('(</extruderInitialization>)') # Initialization is finished, extrusion is starting. self.distanceFeedRate.addLine('(<extrusion>)') # Initialization is finished, extrusion is starting.
def writeOutput(fileName, fileNamePenultimate, fileNameSuffix, filePenultimateWritten, gcodeText=""): "Write a commented gcode file for a skeinforge gcode file, if 'Write Commented File for Skeinforge Chain' is selected." repository = settings.getReadRepository(CommentRepository()) if gcodeText == "": gcodeText = archive.getFileText(fileNameSuffix) if repository.activateComment.value: getWindowAnalyzeFileGivenText(fileNameSuffix, gcodeText)
def getChainText( fileName, procedure ): "Get a crafted shape file." text = '' if fileName.endswith('.gcode') or fileName.endswith('.svg'): text = archive.getFileText(fileName) procedures = getProcedures( procedure, text ) return getChainTextFromProcedures( fileName, procedures, text )
def getGcodeFileText(fileName, gcodeText): 'Get the gcode text from a file if it the gcode text is empty and if the file is a gcode file.' if gcodeText != '': return gcodeText if fileName.endswith('.gcode'): return archive.getFileText(fileName) return ''
def writeOutput(fileName, fileNamePenultimate, fileNameSuffix, filePenultimateWritten, gcodeText=''): "Write a commented gcode file for a skeinforge gcode file, if 'Write Commented File for Skeinforge Chain' is selected." repository = settings.getReadRepository( CommentRepository() ) if gcodeText == '': gcodeText = archive.getFileText( fileNameSuffix ) if repository.activateComment.value: getWindowAnalyzeFileGivenText( fileNameSuffix, gcodeText )
def __init__(self): "Set the default settings, execute title & settings fileName." skeinforge_profile.addListsToCraftTypeRepository("skeinforge_application.skeinforge.html", self) self.fileNameInput = settings.FileNameInput().getFromFileName( fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), "Open File for Skeinforge", self, "" ) self.profileType = settings.MenuButtonDisplay().getFromName("Profile Type: ", self) self.profileSelection = settings.MenuButtonDisplay().getFromName("Profile Selection: ", self) addToProfileMenu(self.profileSelection, self.profileType, self) settings.LabelDisplay().getFromName("Search:", self) reprapSearch = settings.HelpPage().getFromNameAfterHTTP( "members.axion.net/~enrique/search_reprap.html", "Reprap", self ) skeinforgeSearch = settings.HelpPage().getFromNameAfterHTTP( "members.axion.net/~enrique/search_skeinforge.html", "Skeinforge", self ) skeinforgeSearch.column += 2 webSearch = settings.HelpPage().getFromNameAfterHTTP("members.axion.net/~enrique/search_web.html", "Web", self) webSearch.column += 4 versionText = archive.getFileText(archive.getVersionFileName()) self.version = settings.LabelDisplay().getFromName("Version: " + versionText, self) settings.LabelDisplay().getFromName("", self) importantFileNames = ["craft", "profile"] getRadioPluginsAddPluginGroupFrame( archive.getSkeinforgePluginsPath(), importantFileNames, getPluginFileNames(), self ) self.executeTitle = "Skeinforge"
def addInitializationToOutput(self): "Add initialization gcode to the output." self.addFromUpperLowerFile(self.repository.nameOfStartFile.value) # Add a start file if it exists. self.distanceFeedRate.addTagBracketedLine('creation', 'skeinforge') # GCode formatted comment absoluteFilePathUntilDot = os.path.abspath(__file__)[: os.path.abspath(__file__).rfind('.')] if absoluteFilePathUntilDot == '/home/enrique/Desktop/backup/babbleold/script/reprap/fabmetheus/skeinforge_application/skeinforge_plugins/craft_plugins/preface': #is this script on Enrique's computer? archive.writeFileText(archive.getVersionFileName(), date.today().isoformat().replace('-', '.')[2 :]) versionText = archive.getFileText(archive.getVersionFileName()) self.distanceFeedRate.addTagBracketedLine('version', versionText) # GCode formatted comment self.distanceFeedRate.addLine('(<extruderInitialization>)') # GCode formatted comment if self.repository.setPositioningToAbsolute.value: self.distanceFeedRate.addLine('G90 ;set positioning to absolute') # Set positioning to absolute. if self.repository.setUnitsToMillimeters.value: self.distanceFeedRate.addLine('G21 ;set units to millimeters') # Set units to millimeters. if self.repository.startAtHome.value: self.distanceFeedRate.addLine('G28 ;start at home') # Start at home. if self.repository.turnExtruderOffAtStartUp.value: self.distanceFeedRate.addLine('M103') # Turn extruder off. craftTypeName = skeinforge_profile.getCraftTypeName() self.distanceFeedRate.addTagBracketedLine('craftTypeName', craftTypeName) self.distanceFeedRate.addTagBracketedLine('decimalPlacesCarried', self.distanceFeedRate.decimalPlacesCarried) layerThickness = float(self.svgReader.sliceDictionary['layerThickness']) self.distanceFeedRate.addTagRoundedLine('layerThickness', layerThickness) if self.repository.meta.value: self.distanceFeedRate.addTagBracketedLine('meta', self.repository.meta.value) perimeterWidth = float(self.svgReader.sliceDictionary['perimeterWidth']) self.distanceFeedRate.addTagRoundedLine('perimeterWidth', perimeterWidth) self.distanceFeedRate.addTagBracketedLine('profileName', skeinforge_profile.getProfileName(craftTypeName)) procedureNames = self.svgReader.sliceDictionary['procedureName'].replace(',', ' ').split() for procedureName in procedureNames: self.distanceFeedRate.addTagBracketedLine('procedureName', procedureName) self.distanceFeedRate.addTagBracketedLine('procedureName', 'preface') self.distanceFeedRate.addLine('(</extruderInitialization>)') # Initialization is finished, extrusion is starting. self.distanceFeedRate.addLine('(<crafting>)') # Initialization is finished, crafting is starting.
def writeOutput(fileName, fileNameSuffix, gcodeText=''): "Write statistics for a skeinforge gcode file, if 'Write Statistics File for Skeinforge Chain' is selected." repository = settings.getReadRepository(StatisticRepository()) if gcodeText == '': gcodeText = archive.getFileText(fileNameSuffix) if repository.activateStatistic.value: getWindowAnalyzeFileGivenText(fileNameSuffix, gcodeText, repository)
def getReplacedSVGTemplate(self, fileName, procedureName, rotatedLoopLayers, xmlElement=None): 'Get the lines of text from the layer_template.svg file.' self.extent = self.cornerMaximum - self.cornerMinimum svgTemplateText = archive.getFileText(archive.getTemplatesPath('layer_template.svg')) self.xmlParser = XMLSimpleReader( fileName, None, svgTemplateText ) self.svgElement = self.xmlParser.getRoot() svgElementDictionary = self.svgElement.attributeDictionary self.sliceDictionary = getSliceDictionary(self.svgElement) self.controlBoxHeight = float(self.sliceDictionary['controlBoxHeight']) self.controlBoxWidth = float(self.sliceDictionary['controlBoxWidth']) self.margin = float(self.sliceDictionary['margin']) self.marginTop = float(self.sliceDictionary['marginTop']) self.textHeight = float(self.sliceDictionary['textHeight']) self.unitScale = float(self.sliceDictionary['unitScale']) svgMinWidth = float(self.sliceDictionary['svgMinWidth']) self.controlBoxHeightMargin = self.controlBoxHeight + self.marginTop if not self.addLayerTemplateToSVG: self.svgElement.getXMLElementByID('layerTextTemplate').removeFromIDNameParent() del self.svgElement.getXMLElementByID('sliceElementTemplate').attributeDictionary['transform'] self.graphicsXMLElement = self.svgElement.getXMLElementByID('sliceElementTemplate') self.graphicsXMLElement.attributeDictionary['id'] = 'z:' self.addRotatedLoopLayersToOutput(rotatedLoopLayers) self.setMetadataNoscriptElement('layerThickness', 'Layer Thickness: ', self.layerThickness) self.setMetadataNoscriptElement('maxX', 'X: ', self.cornerMaximum.x) self.setMetadataNoscriptElement('minX', 'X: ', self.cornerMinimum.x) self.setMetadataNoscriptElement('maxY', 'Y: ', self.cornerMaximum.y) self.setMetadataNoscriptElement('minY', 'Y: ', self.cornerMinimum.y) self.setMetadataNoscriptElement('maxZ', 'Z: ', self.cornerMaximum.z) self.setMetadataNoscriptElement('minZ', 'Z: ', self.cornerMinimum.z) self.textHeight = float( self.sliceDictionary['textHeight'] ) controlTop = len(rotatedLoopLayers) * (self.margin + self.extent.y * self.unitScale + self.textHeight) + self.marginTop + self.textHeight self.svgElement.getFirstChildWithClassName('title').text = os.path.basename(fileName) + ' - Slice Layers' svgElementDictionary['height'] = '%spx' % self.getRounded(max(controlTop, self.controlBoxHeightMargin)) width = max(self.extent.x * self.unitScale, svgMinWidth) svgElementDictionary['width'] = '%spx' % self.getRounded( width ) self.sliceDictionary['decimalPlacesCarried'] = str( self.decimalPlacesCarried ) if self.perimeterWidth != None: self.sliceDictionary['perimeterWidth'] = self.getRounded( self.perimeterWidth ) self.sliceDictionary['yAxisPointingUpward'] = 'true' self.sliceDictionary['procedureName'] = procedureName self.setDimensionTexts('dimX', 'X: ' + self.getRounded(self.extent.x)) self.setDimensionTexts('dimY', 'Y: ' + self.getRounded(self.extent.y)) self.setDimensionTexts('dimZ', 'Z: ' + self.getRounded(self.extent.z)) self.setTexts('numberOfLayers', 'Number of Layers: %s' % len(rotatedLoopLayers)) volume = 0.0 for rotatedLoopLayer in rotatedLoopLayers: volume += euclidean.getAreaLoops(rotatedLoopLayer.loops) volume *= 0.001 self.setTexts('volume', 'Volume: %s cm3' % self.getRounded(volume)) if not self.addLayerTemplateToSVG: self.svgElement.getFirstChildWithClassName('script').removeFromIDNameParent() self.svgElement.getXMLElementByID('isoControlBox').removeFromIDNameParent() self.svgElement.getXMLElementByID('layerControlBox').removeFromIDNameParent() self.svgElement.getXMLElementByID('scrollControlBox').removeFromIDNameParent() self.graphicsXMLElement.removeFromIDNameParent() self.addOriginalAsComment(xmlElement) output = cStringIO.StringIO() output.write(self.xmlParser.beforeRoot) self.svgElement.addXML(0, output) return xml_simple_writer.getBeforeRootOutput(self.xmlParser)
def __init__(self): "Set the default settings, execute title & settings fileName." skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_utilities.skeinforge_help.html', self) announcementsText = '- Announcements - ' announcementsLabel = settings.LabelDisplay().getFromName(announcementsText, self ) announcementsLabel.columnspan = 6 settings.LabelDisplay().getFromName('Fabmetheus Blog, Announcements & Questions:', self ) settings.HelpPage().getFromNameAfterHTTP('fabmetheus.blogspot.com/', 'Fabmetheus Blog', self ) settings.LabelSeparator().getFromRepository(self) settings.LabelDisplay().getFromName('- Documentation -', self ) settings.LabelDisplay().getFromName('Local Documentation Table of Contents: ', self ) settings.HelpPage().getFromNameSubName('Contents', self, 'contents.html') settings.LabelDisplay().getFromName('Wiki Manual with Pictures & Charts: ', self ) settings.HelpPage().getFromNameAfterHTTP('fabmetheus.crsndoo.com/wiki/index.php/Skeinforge', 'Wiki Manual', self ) settings.LabelDisplay().getFromName('Skeinforge Overview: ', self ) settings.HelpPage().getFromNameSubName('Skeinforge Overview', self, 'skeinforge_application.skeinforge.html') settings.LabelSeparator().getFromRepository(self) settings.LabelDisplay().getFromName('- Search -', self ) settings.LabelDisplay().getFromName('Reprap Search:', self ) settings.HelpPage().getFromNameAfterHTTP('members.axion.net/~enrique/search_reprap.html', 'Reprap Search', self ) settings.LabelDisplay().getFromName('Skeinforge Search:', self ) settings.HelpPage().getFromNameAfterHTTP('members.axion.net/~enrique/search_skeinforge.html', 'Skeinforge Search', self ) settings.LabelDisplay().getFromName('Web Search:', self ) settings.HelpPage().getFromNameAfterHTTP('members.axion.net/~enrique/search_web.html', 'Web Search', self ) settings.LabelSeparator().getFromRepository(self) settings.LabelDisplay().getFromName('- Troubleshooting -', self ) settings.LabelDisplay().getFromName('Skeinforge Forum:', self) settings.HelpPage().getFromNameAfterHTTP('forums.reprap.org/list.php?154', ' Skeinforge Forum ', self ) settings.LabelSeparator().getFromRepository(self) self.version = settings.LabelDisplay().getFromName('Version: ' + archive.getFileText(archive.getVersionFileName()), self) self.wikiManualPrimary = settings.BooleanSetting().getFromValue('Wiki Manual Primary', self, True ) self.wikiManualPrimary.setUpdateFunction( self.save )
def getChainText( fileName, procedure ): "Get a crafted shape file." text='' if fileName.endswith('.gcode') or fileName.endswith('.svg'): text = archive.getFileText(fileName) procedures = getProcedures( procedure, text ) return getChainTextFromProcedures( fileName, procedures, text )
def __init__(self): "Set the default settings, execute title & settings fileName." settings.addListsToRepository('skeinforge_application.skeinforge.html', None, self) self.fileNameInput = settings.FileNameInput().getFromFileName( fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Skeinforge', self, '') self.profileType = settings.MenuButtonDisplay().getFromName( 'Profile Type: ', self) self.profileSelection = settings.MenuButtonDisplay().getFromName( 'Profile Selection: ', self) addToProfileMenu(self.profileSelection, self.profileType, self) settings.LabelDisplay().getFromName('Search:', self) reprapSearch = settings.HelpPage().getFromNameAfterHTTP( 'members.axion.net/~enrique/search_reprap.html', 'Reprap', self) skeinforgeSearch = settings.HelpPage().getFromNameAfterHTTP( 'members.axion.net/~enrique/search_skeinforge.html', 'Skeinforge', self) skeinforgeSearch.column += 2 webSearch = settings.HelpPage().getFromNameAfterHTTP( 'members.axion.net/~enrique/search_web.html', 'Web', self) webSearch.column += 4 versionText = archive.getFileText(archive.getVersionFileName()) self.version = settings.LabelDisplay().getFromName( 'Version: ' + versionText, self) settings.LabelDisplay().getFromName('', self) importantFileNames = ['craft', 'profile'] getRadioPluginsAddPluginGroupFrame(getPluginsDirectoryPath(), importantFileNames, getPluginFileNames(), self) self.executeTitle = 'Skeinforge'
def writeOutput(fileName, fileNamePenultimate, fileNameSuffix, filePenultimateWritten, gcodeText=''): """Write statistics for a skeinforge gcode file, if 'Write Statistics File for Skeinforge Chain' is selected.""" repository = settings.getReadRepository( StatisticRepository() ) if gcodeText == '': gcodeText = archive.getFileText( fileNameSuffix ) if repository.activateStatistic.value: getWindowAnalyzeFileGivenText( fileNameSuffix, gcodeText, repository )
def __init__(self): 'Set the default settings, execute title & settings fileName.' skeinforge_profile.addListsToCraftTypeRepository( 'skeinforge_application.skeinforge.html', self) self.fileNameInput = settings.FileNameInput().getFromFileName( fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Skeinforge', self, '') self.profileType = settings.MenuButtonDisplay().getFromName( 'Profile Type: ', self) self.profileSelection = settings.MenuButtonDisplay().getFromName( 'Profile Selection: ', self) addToProfileMenu(self.profileSelection, self.profileType, self) settings.LabelDisplay().getFromName('Search:', self) reprapSearch = settings.HelpPage().getFromNameAfterHTTP( 'github.com/ahmetcemturan/SFACT', 'SFACT Update', self) skeinforgeSearch = settings.HelpPage().getFromNameAfterHTTP( 'www.reprapfordummies.net/index.php/softwaresection/44-gcode-generators/49-sfact-homepage', 'SFACT Help', self) skeinforgeSearch.column += 6 webSearch = settings.HelpPage().getFromNameAfterHTTP( 'www.reprap.org', 'Reprap', self) webSearch.column += 4 versionText = archive.getFileText(archive.getVersionFileName()) self.version = settings.LabelDisplay().getFromName( 'Version: ' + versionText, self) settings.LabelDisplay().getFromName('', self) importantFileNames = ['craft', 'profile'] getRadioPluginsAddPluginGroupFrame(archive.getSkeinforgePluginsPath(), importantFileNames, getPluginFileNames(), self) self.executeTitle = 'Skeinforge'
def processXMLElement(xmlElement): "Process the xml element." fileName = evaluate.getEvaluatedValue('file', xmlElement) if fileName == None: return parserFileName = xmlElement.getRoot().parser.fileName absoluteFileName = archive.getAbsoluteFolderPath(parserFileName, fileName) xmlText = '' if fileName.endswith('.xml'): xmlText = archive.getFileText(absoluteFileName) else: xmlText = getXMLFromCarvingFileName(absoluteFileName) if xmlText == '': print( 'The file %s could not be found in the folder which the fabmetheus xml file is in.' % fileName) return if '_importname' in xmlElement.attributeDictionary: xmlElement.importName = xmlElement.attributeDictionary['_importname'] else: xmlElement.importName = archive.getUntilDot(fileName) xmlElement.attributeDictionary['_importname'] = xmlElement.importName XMLSimpleReader(parserFileName, xmlElement, xmlText) originalChildren = xmlElement.children[:] xmlElement.children = [] for child in originalChildren: for subchild in child.children: subchild.setParentAddToChildren(xmlElement) for attributeDictionaryKey in child.attributeDictionary.keys(): if attributeDictionaryKey != 'version': xmlElement.attributeDictionary[ attributeDictionaryKey] = child.attributeDictionary[ attributeDictionaryKey] group.processShape(group.Group, xmlElement)
def processXMLElement(xmlElement): "Process the xml element." fileName = evaluate.getEvaluatedValue('file', xmlElement ) if fileName == None: return parserFileName = xmlElement.getRoot().parser.fileName absoluteFileName = archive.getAbsoluteFolderPath( parserFileName, fileName ) xmlText = '' if fileName.endswith('.xml'): xmlText = archive.getFileText( absoluteFileName ) else: xmlText = getXMLFromCarvingFileName( absoluteFileName ) if xmlText == '': print('The file %s could not be found in the folder which the fabmetheus xml file is in.' % fileName ) return if '_importname' in xmlElement.attributeDictionary: xmlElement.importName = xmlElement.attributeDictionary['_importname'] else: xmlElement.importName = archive.getUntilDot(fileName) xmlElement.attributeDictionary['_importname'] = xmlElement.importName XMLSimpleReader( parserFileName, xmlElement, xmlText ) originalChildren = xmlElement.children[:] xmlElement.children = [] for child in originalChildren: for subchild in child.children: subchild.setParentAddToChildren(xmlElement) for attributeDictionaryKey in child.attributeDictionary.keys(): if attributeDictionaryKey != 'version': xmlElement.attributeDictionary[attributeDictionaryKey] = child.attributeDictionary[attributeDictionaryKey] group.processShape( group.Group, xmlElement)
def getReplaceableExportGcode(self, nameOfReplaceFile, replaceableExportGcode): 'Get text with strings replaced according to replace.csv file.' fullReplaceFilePath = os.path.join('alterations', nameOfReplaceFile) if self.nameOfReplaceFile == '' or not os.path.exists( fullReplaceFilePath): return replaceableExportGcode fullReplaceText = archive.getFileText(fullReplaceFilePath) replaceLines = archive.getTextLines(fullReplaceText) if len(replaceLines) < 1: return replaceableExportGcode for replaceLine in replaceLines: splitLine = replaceLine.replace('\\n', '\t').split('\t') if len(splitLine) > 0: replaceableExportGcode = replaceableExportGcode.replace( splitLine[0], '\n'.join(splitLine[1:])) output = StringIO() for line in archive.getTextLines(replaceableExportGcode): if line != '': output.write(line + '\n') return output.getvalue()
def addInitializationToOutput(self): """Add initialization gcode to the output.""" self.addFromUpperLowerFile(self.repository.nameOfStartFile.value) # Add a start file if it exists. self.distanceFeedRate.addTagBracketedLine('creation', 'skeinforge') # GCode formatted comment absoluteFilePathUntilDot = os.path.abspath(__file__)[: os.path.abspath(__file__).rfind('.')] if absoluteFilePathUntilDot == '/home/enrique/Desktop/backup/babbleold/script/reprap/fabmetheus/skeinforge_application/skeinforge_plugins/craft_plugins/preface': #is this script on Enrique's computer? archive.writeFileText(archive.getVersionFileName(), date.today().isoformat().replace('-', '.')[2 :]) versionText = archive.getFileText(archive.getVersionFileName()) self.distanceFeedRate.addTagBracketedLine('version', versionText) # GCode formatted comment self.distanceFeedRate.addLine('(<extruderInitialization>)') # GCode formatted comment if self.repository.setPositioningToAbsolute.value: self.distanceFeedRate.addLine('G90 ;set positioning to absolute') # Set positioning to absolute. if self.repository.setUnitsToMillimeters.value: self.distanceFeedRate.addLine('G21 ;set units to millimeters') # Set units to millimeters. if self.repository.startAtHome.value: self.distanceFeedRate.addLine('G28 ;start at home') # Start at home. if self.repository.resetExtruder.value: self.distanceFeedRate.addLine('G92 E0 ;reset extruder distance') # Start at home. craftTypeName = skeinforge_profile.getCraftTypeName() self.distanceFeedRate.addTagBracketedLine('craftTypeName', craftTypeName) self.distanceFeedRate.addTagBracketedLine('decimalPlacesCarried', self.distanceFeedRate.decimalPlacesCarried) extrusionHeight = float(self.svgReader.sliceDictionary['extrusionHeight']) self.distanceFeedRate.addTagRoundedLine('extrusionHeight', extrusionHeight) if self.repository.meta.value: self.distanceFeedRate.addTagBracketedLine('meta', self.repository.meta.value) extrusionWidth = float(self.svgReader.sliceDictionary['extrusionWidth']) self.distanceFeedRate.addTagRoundedLine('extrusionWidth', extrusionWidth) self.distanceFeedRate.addTagBracketedLine('profileName', skeinforge_profile.getProfileName(craftTypeName)) procedureNames = self.svgReader.sliceDictionary['procedureName'].replace(',', ' ').split() for procedureName in procedureNames: self.distanceFeedRate.addTagBracketedLine('procedureName', procedureName) self.distanceFeedRate.addTagBracketedLine('procedureName', 'preface') self.distanceFeedRate.addLine('(</extruderInitialization>)') # Initialization is finished, extrusion is starting. self.distanceFeedRate.addLine('(<crafting>)') # Initialization is finished, crafting is starting.
def getGcodeFileText(fileName, gcodeText): "Get the gcode text from a file if it the gcode text is empty and if the file is a gcode file." if gcodeText != "": return gcodeText if fileName.endswith(".gcode"): return archive.getFileText(fileName) return ""
def readWriteNavigationHelp(documentDirectoryPath, transferredFileNameIndex, transferredFileNames): 'Read the hypertext help documents, and add the navigation lines to them.' fileName = os.path.basename(transferredFileNames[transferredFileNameIndex]) print('readWriteNavigationHelp ' + fileName) filePath = os.path.join(documentDirectoryPath, fileName) fileText = archive.getFileText(filePath) fileText = getNavigationHypertext(fileText, transferredFileNameIndex, transferredFileNames) archive.writeFileText(filePath, fileText)
def getReplacedSVGTemplate(self, fileName, loopLayers, procedureName, elementNode=None): 'Get the lines of text from the layer_template.svg file.' self.extent = self.cornerMaximum - self.cornerMinimum svgTemplateText = archive.getFileText(archive.getTemplatesPath('layer_template.svg')) documentNode = DocumentNode(fileName, svgTemplateText) self.svgElement = documentNode.getDocumentElement() svgElementDictionary = self.svgElement.attributes self.sliceDictionary = getSliceDictionary(self.svgElement) self.controlBoxHeight = float(self.sliceDictionary['controlBoxHeight']) self.controlBoxWidth = float(self.sliceDictionary['controlBoxWidth']) self.margin = float(self.sliceDictionary['margin']) self.marginTop = float(self.sliceDictionary['marginTop']) self.textHeight = float(self.sliceDictionary['textHeight']) self.unitScale = float(self.sliceDictionary['unitScale']) svgMinWidth = float(self.sliceDictionary['svgMinWidth']) self.controlBoxHeightMargin = self.controlBoxHeight + self.marginTop if not self.addLayerTemplateToSVG: self.svgElement.getElementNodeByID('layerTextTemplate').removeFromIDNameParent() del self.svgElement.getElementNodeByID('sliceElementTemplate').attributes['transform'] self.graphicsElementNode = self.svgElement.getElementNodeByID('sliceElementTemplate') self.graphicsElementNode.attributes['id'] = 'z:' self.addLoopLayersToOutput(loopLayers) self.setMetadataNoscriptElement('layerThickness', 'Layer Thickness: ', self.layerThickness) self.setMetadataNoscriptElement('maxX', 'X: ', self.cornerMaximum.x) self.setMetadataNoscriptElement('minX', 'X: ', self.cornerMinimum.x) self.setMetadataNoscriptElement('maxY', 'Y: ', self.cornerMaximum.y) self.setMetadataNoscriptElement('minY', 'Y: ', self.cornerMinimum.y) self.setMetadataNoscriptElement('maxZ', 'Z: ', self.cornerMaximum.z) self.setMetadataNoscriptElement('minZ', 'Z: ', self.cornerMinimum.z) self.textHeight = float( self.sliceDictionary['textHeight'] ) controlTop = len(loopLayers) * (self.margin + self.extent.y * self.unitScale + self.textHeight) + self.marginTop + self.textHeight self.svgElement.getFirstChildByLocalName('title').setTextContent(os.path.basename(fileName) + ' - Slice Layers') svgElementDictionary['height'] = '%spx' % self.getRounded(max(controlTop, self.controlBoxHeightMargin)) width = max(self.extent.x * self.unitScale, svgMinWidth) svgElementDictionary['width'] = '%spx' % self.getRounded( width ) self.sliceDictionary['decimalPlacesCarried'] = str( self.decimalPlacesCarried ) if self.perimeterWidth != None: self.sliceDictionary['perimeterWidth'] = self.getRounded( self.perimeterWidth ) self.sliceDictionary['yAxisPointingUpward'] = 'true' self.sliceDictionary['procedureName'] = procedureName self.setDimensionTexts('dimX', 'X: ' + self.getRounded(self.extent.x)) self.setDimensionTexts('dimY', 'Y: ' + self.getRounded(self.extent.y)) self.setDimensionTexts('dimZ', 'Z: ' + self.getRounded(self.extent.z)) self.setTexts('numberOfLayers', 'Number of Layers: %s' % len(loopLayers)) volume = 0.0 for loopLayer in loopLayers: volume += euclidean.getAreaLoops(loopLayer.loops) volume *= 0.001 * self.layerThickness self.setTexts('volume', 'Volume: %s cm3' % self.getRounded(volume)) if not self.addLayerTemplateToSVG: self.svgElement.getFirstChildByLocalName('script').removeFromIDNameParent() self.svgElement.getElementNodeByID('isoControlBox').removeFromIDNameParent() self.svgElement.getElementNodeByID('layerControlBox').removeFromIDNameParent() self.svgElement.getElementNodeByID('scrollControlBox').removeFromIDNameParent() self.graphicsElementNode.removeFromIDNameParent() self.addOriginalAsComment(elementNode) return documentNode.__repr__()
def __init__(self): "Set the default settings, execute title & settings fileName." skeinforge_profile.addListsToCraftTypeRepository( 'skeinforge_application.skeinforge_utilities.skeinforge_help.html', self) announcementsText = '- Announcements - ' announcementsLabel = settings.LabelDisplay().getFromName( announcementsText, self) announcementsLabel.columnspan = 6 settings.LabelDisplay().getFromName( 'Fabmetheus Blog, Announcements & Questions:', self) settings.HelpPage().getFromNameAfterHTTP('fabmetheus.blogspot.com/', 'Fabmetheus Blog', self) settings.LabelSeparator().getFromRepository(self) settings.LabelDisplay().getFromName('- Documentation -', self) settings.LabelDisplay().getFromName( 'Local Documentation Table of Contents: ', self) settings.HelpPage().getFromNameSubName('Contents', self, 'contents.html') settings.LabelDisplay().getFromName( 'Wiki Manual with Pictures & Charts: ', self) settings.HelpPage().getFromNameAfterHTTP( 'fabmetheus.crsndoo.com/wiki/index.php/Skeinforge', 'Wiki Manual', self) settings.LabelDisplay().getFromName('Skeinforge Overview: ', self) settings.HelpPage().getFromNameSubName( 'Skeinforge Overview', self, 'skeinforge_application.skeinforge.html') settings.LabelSeparator().getFromRepository(self) settings.LabelDisplay().getFromName('SFACT FAQs:', self) settings.HelpPage().getFromNameAfterHTTP( 'http://titanpad.com/XTUJXiNHmd', ' SFACT FAQs ', self) settings.LabelSeparator().getFromRepository(self) settings.LabelDisplay().getFromName('- Search -', self) settings.LabelDisplay().getFromName('Reprap Search:', self) settings.HelpPage().getFromNameAfterHTTP( 'members.axion.net/~enrique/search_reprap.html', 'Reprap Search', self) settings.LabelDisplay().getFromName('Skeinforge Search:', self) settings.HelpPage().getFromNameAfterHTTP( 'members.axion.net/~enrique/search_skeinforge.html', 'Skeinforge Search', self) settings.LabelDisplay().getFromName('Web Search:', self) settings.HelpPage().getFromNameAfterHTTP( 'members.axion.net/~enrique/search_web.html', 'Web Search', self) settings.LabelSeparator().getFromRepository(self) settings.LabelDisplay().getFromName('- Troubleshooting -', self) settings.LabelDisplay().getFromName('Skeinforge Forum:', self) settings.HelpPage().getFromNameAfterHTTP( 'forums.reprap.org/list.php?154', ' Skeinforge Forum ', self) settings.LabelSeparator().getFromRepository(self) self.version = settings.LabelDisplay().getFromName( 'Version: ' + archive.getFileText(archive.getVersionFileName()), self) self.wikiManualPrimary = settings.BooleanSetting().getFromValue( 'Wiki Manual Primary', self, True) self.wikiManualPrimary.setUpdateFunction(self.save)
def getCarving(fileName=''): "Get the triangle mesh for the obj file." if fileName == '': return None objText = archive.getFileText(fileName, True, 'rb') if objText == '': return None triangleMesh = triangle_mesh.TriangleMesh() addFacesGivenText(objText, triangleMesh) return triangleMesh
def processXMLElementByDerivation(derivation, xmlElement): 'Process the xml element by derivation.' if derivation == None: derivation = ImportDerivation(xmlElement) if derivation.fileName == None: return parserFileName = xmlElement.getParser().fileName absoluteFileName = archive.getAbsoluteFolderPath(parserFileName, derivation.fileName) if 'models/' not in absoluteFileName: print( 'Warning, models/ was not in the absolute file path, so for security nothing will be done for:' ) print(xmlElement) print('For which the absolute file path is:') print(absoluteFileName) print( 'The import tool can only read a file which has models/ in the file path.' ) print( 'To import the file, move the file into a folder called model/ or a subfolder which is inside the model folder tree.' ) return xmlText = '' if derivation.fileName.endswith('.xml'): xmlText = archive.getFileText(absoluteFileName) else: xmlText = getXMLFromCarvingFileName(absoluteFileName) print('The import tool is opening the file:') print(absoluteFileName) if xmlText == '': print( 'The file %s could not be found by processXMLElement in import.' % derivation.fileName) return if derivation.importName == None: xmlElement.importName = archive.getUntilDot(derivation.fileName) if derivation.basename: xmlElement.importName = os.path.basename(xmlElement.importName) xmlElement.attributeDictionary['_importName'] = xmlElement.importName else: xmlElement.importName = derivation.importName importXMLElement = xml_simple_reader.XMLElement() xml_simple_reader.XMLSimpleReader(parserFileName, importXMLElement, xmlText) for child in importXMLElement.children: child.copyXMLChildren('', xmlElement) evaluate.removeIdentifiersFromDictionary(child.attributeDictionary) xmlElement.attributeDictionary.update(child.attributeDictionary) if derivation.overwriteRoot: xmlElement.getRoot().attributeDictionary.update( child.attributeDictionary) xmlElement.className = 'group' evaluate.processArchivable(group.Group, xmlElement)
def getCarving(fileName=''): "Get the carving for the xml file." xmlText = archive.getFileText(fileName) if xmlText == '': return None xmlParser = DocumentNode(fileName, xmlText) lowerLocalName = xmlParser.getDocumentElement().getNodeName().lower() pluginModule = archive.getModuleWithDirectoryPath( getPluginsDirectoryPath(), lowerLocalName ) if pluginModule == None: return None return pluginModule.getCarvingFromParser( xmlParser )
def getSnippetsByFileName(fileName, functionName): 'Get the function signature snippets by the file name.' fileText = archive.getFileText(fileName) snippets = [] functionStart = functionName[:functionName.find('(') + 1] tokenEnd = getTokenEnd(0, fileText, functionStart) while tokenEnd != -1: snippet = Snippet(tokenEnd, fileText) snippets.append(snippet) tokenEnd = getTokenEnd(snippet.characterIndex, fileText, functionStart) return snippets
def getCarving(fileName=''): "Get the carving for the xml file." xmlText = archive.getFileText(fileName) if xmlText == '': return None xmlParser = XMLSimpleReader( fileName, None, xmlText ) lowerClassName = xmlParser.getRoot().className.lower() pluginModule = archive.getModuleWithDirectoryPath( getPluginsDirectoryPath(), lowerClassName ) if pluginModule == None: return None return pluginModule.getCarvingFromParser( xmlParser )
def getSnippetsByFileName(fileName, functionName): 'Get the function signature snippets by the file name.' fileText = archive.getFileText(fileName) snippets = [] functionStart = functionName[: functionName.find('(') + 1] tokenEnd = getTokenEnd(0, fileText, functionStart) while tokenEnd != -1: snippet = Snippet(tokenEnd, fileText) snippets.append(snippet) tokenEnd = getTokenEnd(snippet.characterIndex, fileText, functionStart) return snippets
def getCarving(fileName=""): "Get the carving for the csv file." csvText = archive.getFileText(fileName) if csvText == "": return None csvParser = CSVSimpleParser(fileName, None, csvText) lowerLocalName = csvParser.getDocumentElement().getNodeName().lower() pluginModule = archive.getModuleWithDirectoryPath(getPluginsDirectoryPath(), lowerLocalName) if pluginModule == None: return None return pluginModule.getCarvingFromParser(csvParser)
def getCarving(fileName=''): "Get the carving for the csv file." csvText = archive.getFileText(fileName) if csvText == '': return None csvParser = CSVSimpleParser( fileName, None, csvText ) lowerClassName = csvParser.getRoot().className.lower() pluginModule = archive.getModuleWithDirectoryPath( getPluginsDirectoryPath(), lowerClassName ) if pluginModule == None: return None return pluginModule.getCarvingFromParser( csvParser )
def processXMLElement(xmlElement): 'Process the xml element.' fileName = evaluate.getEvaluatedValue('file', xmlElement) if fileName == None: return parserFileName = xmlElement.getRoot().parser.fileName absoluteFileName = archive.getAbsoluteFolderPath(parserFileName, fileName) absoluteFileName = os.path.abspath(absoluteFileName) if 'models/' not in absoluteFileName: print( 'Warning, models/ was not in the absolute file path, so for security nothing will be done for:' ) print(xmlElement) print('For which the absolute file path is:') print(absoluteFileName) print( 'The import tool can only read a file which has models/ in the file path.' ) print( 'To import the file, move the file into a folder called model/ or a subfolder which is inside the model folder tree.' ) return xmlText = '' if fileName.endswith('.xml'): xmlText = archive.getFileText(absoluteFileName) else: xmlText = getXMLFromCarvingFileName(absoluteFileName) print('The import tool is opening the file:') print(absoluteFileName) if xmlText == '': print( 'The file %s could not be found by processXMLElement in import.' % fileName) return if '_importName' in xmlElement.attributeDictionary: xmlElement.importName = xmlElement.attributeDictionary['_importName'] else: xmlElement.importName = archive.getUntilDot(fileName) if evaluate.getEvaluatedBooleanDefault(True, 'basename', xmlElement): xmlElement.importName = os.path.basename(xmlElement.importName) xmlElement.attributeDictionary['_importName'] = xmlElement.importName importXMLElement = xml_simple_reader.XMLElement() xml_simple_reader.XMLSimpleReader(parserFileName, importXMLElement, xmlText) for child in importXMLElement.children: child.copyXMLChildren('', xmlElement) euclidean.removeElementsFromDictionary(child.attributeDictionary, ['id', 'name']) xmlElement.attributeDictionary.update(child.attributeDictionary) if evaluate.getEvaluatedBooleanDefault(False, 'overwriteRoot', xmlElement): xmlElement.getRoot().attributeDictionary.update( child.attributeDictionary) group.processShape(group.Group, xmlElement)
def getCarving(fileName=''): "Get the carving for the csv file." csvText = archive.getFileText(fileName) if csvText == '': return None csvParser = CSVSimpleParser(fileName, None, csvText) lowerLocalName = csvParser.getDocumentElement().getNodeName().lower() pluginModule = archive.getModuleWithDirectoryPath( getPluginsDirectoryPath(), lowerLocalName) if pluginModule is None: return None return pluginModule.getCarvingFromParser(csvParser)
def readWriteDeleteHypertextHelp(documentDirectoryPath, hypertextFileIndex, hypertextFiles, transferredFileNames): 'Read the pydoc hypertext help documents, write them in the documentation folder then delete the originals.' fileName = os.path.basename(hypertextFiles[hypertextFileIndex]) print('readWriteDeleteHypertextHelp ' + fileName) filePath = os.path.join(documentDirectoryPath, fileName) fileText = archive.getFileText(fileName) fileText = getWrappedHypertext(fileText, hypertextFileIndex, hypertextFiles) if fileText.find('This page is in the table of contents.') > - 1: fileText = fileText.replace('This page is in the table of contents.', '') transferredFileNames.append(fileName) archive.writeFileText(filePath, fileText) os.remove(fileName)
def processXMLElementByDerivation(derivation, xmlElement): """Process the xml element by derivation.""" if derivation is None: derivation = ImportDerivation(xmlElement) if derivation.fileName is None: return parserFileName = xmlElement.getParser().fileName absoluteFileName = archive.getAbsoluteFolderPath(parserFileName, derivation.fileName) if 'models/' not in absoluteFileName: print( 'Warning, models/ was not in the absolute file path, so for security nothing will be done for:' ) print(xmlElement) print('For which the absolute file path is:') print(absoluteFileName) print( 'The import tool can only read a file which has models/ in the file path.' ) print( 'To import the file, move the file into a folder called model/ or a subfolder which is inside the model folder tree.' ) return xmlText = '' if derivation.fileName.endswith('.xml'): xmlText = archive.getFileText(absoluteFileName) else: xmlText = getXMLFromCarvingFileName(absoluteFileName) print('The import tool is opening the file:') print(absoluteFileName) if xmlText == '': print('The file %s could not be found by processXMLElement in import.' % derivation.fileName) return if derivation.importName is None: xmlElement.importName = archive.getUntilDot(derivation.fileName) if derivation.basename: xmlElement.importName = os.path.basename(xmlElement.importName) xmlElement.attributeDictionary['_importName'] = xmlElement.importName else: xmlElement.importName = derivation.importName importXMLElement = xml_simple_reader.XMLElement() xml_simple_reader.XMLSimpleReader(parserFileName, importXMLElement, xmlText) for child in importXMLElement.children: child.copyXMLChildren('', xmlElement) evaluate.removeIdentifiersFromDictionary(child.attributeDictionary) xmlElement.attributeDictionary.update(child.attributeDictionary) if derivation.overwriteRoot: xmlElement.getRoot().attributeDictionary.update( child.attributeDictionary) xmlElement.className = 'group' evaluate.processArchivable(group.Group, xmlElement)
def addInitializationToOutput(self): "Add initialization gcode to the output." self.addFromUpperLowerFile(self.repository.nameOfStartFile.value) # Add a start file if it exists. self.distanceFeedRate.addTagBracketedLine('creation', 'skeinforge') # GCode formatted comment # absoluteFilePathUntilDot = os.path.abspath(__file__)[: os.path.abspath(__file__).rfind('.')] # if absoluteFilePathUntilDot == '/home/enrique/Desktop/backup/babbleold/script/reprap/fabmetheus/skeinforge_application/skeinforge_plugins/craft_plugins/preface': #is this script on Enrique's computer? # archive.writeFileText(archive.getVersionFileName(), date.today().isoformat().replace('-', '.')[2 :]) versionText = archive.getFileText(archive.getVersionFileName()) self.distanceFeedRate.addTagBracketedLine('version', versionText) # GCode formatted comment self.distanceFeedRate.addLine('(<extruderInitialization>)') # GCode formatted comment if self.repository.setPositioningToAbsolute.value: self.distanceFeedRate.addLine('G90 ;set positioning to absolute') # Set positioning to absolute. if self.repository.setUnitsToMillimeters.value: self.distanceFeedRate.addLine('G21 ;set units to millimeters') # Set units to millimeters. if self.repository.startAtHome.value: self.distanceFeedRate.addLine('G28 ;start at home') # Start at home. if self.repository.resetExtruder.value: self.distanceFeedRate.addLine('G92 E0 ;reset extruder distance') # Start at home. # if self.repository.turnExtruderOffAtStartUp.value: # self.distanceFeedRate.addLine('M103') # Turn extruder off. craftTypeName = skeinforge_profile.getCraftTypeName() self.distanceFeedRate.addTagBracketedLine('craftTypeName', craftTypeName) self.distanceFeedRate.addTagBracketedLine('decimalPlacesCarried', self.distanceFeedRate.decimalPlacesCarried) layerThickness = float(self.svgReader.sliceDictionary['layerThickness']) self.distanceFeedRate.addTagRoundedLine('layerThickness', layerThickness) if self.repository.meta.value: self.distanceFeedRate.addTagBracketedLine('meta', self.repository.meta.value) if self.repository.extraLineOne.value: self.distanceFeedRate.addLine( self.repository.extraLineOne.value) if self.repository.extraLineTwo.value: self.distanceFeedRate.addLine( self.repository.extraLineTwo.value) if self.repository.extraLineThree.value: self.distanceFeedRate.addLine( self.repository.extraLineThree.value) if self.repository.extraLineFour.value: self.distanceFeedRate.addLine( self.repository.extraLineFour.value) if self.repository.extraLineFive.value: self.distanceFeedRate.addLine( self.repository.extraLineFive.value) perimeterWidth = float(self.svgReader.sliceDictionary['perimeterWidth']) self.distanceFeedRate.addTagRoundedLine('perimeterWidth', perimeterWidth) self.distanceFeedRate.addTagBracketedLine('profileName', skeinforge_profile.getProfileName(craftTypeName)) self.distanceFeedRate.addLine('(<settings>)') pluginFileNames = skeinforge_craft.getPluginFileNames() for pluginFileName in pluginFileNames: self.addToolSettingLines(pluginFileName) self.distanceFeedRate.addLine('(</settings>)') self.distanceFeedRate.addTagBracketedLine('timeStampPreface', strftime('%Y%m%d_%H%M%S')) procedureNames = self.svgReader.sliceDictionary['procedureName'].replace(',', ' ').split() for procedureName in procedureNames: self.distanceFeedRate.addTagBracketedLine('procedureName', procedureName) self.distanceFeedRate.addTagBracketedLine('procedureName', 'preface') self.distanceFeedRate.addLine('(</extruderInitialization>)') # Initialization is finished, extrusion is starting. self.distanceFeedRate.addLine('(<crafting>)') # Initialization is finished, crafting is starting.
def getFunctionsWithStringByFileName(fileName, searchString): 'Get the functions with the search string in the file.' fileText = archive.getFileText(fileName) functions = [] lines = archive.getTextLines(fileText) for line in lines: lineStripped = line.strip() # if lineStripped.startswith('def ') and searchString in lineStripped and '=' in lineStripped: if lineStripped.startswith('def ') and searchString in lineStripped: if '(self, ' not in lineStripped or lineStripped.count(',') > 1: functions.append(lineStripped[len('def '):].strip()) functions.sort() return functions
def getFunctionsWithStringByFileName(fileName, searchString): 'Get the functions with the search string in the file.' fileText = archive.getFileText(fileName) functions = [] lines = archive.getTextLines(fileText) for line in lines: lineStripped = line.strip() # if lineStripped.startswith('def ') and searchString in lineStripped and '=' in lineStripped: if lineStripped.startswith('def ') and searchString in lineStripped: if '(self, ' not in lineStripped or lineStripped.count(',') > 1: functions.append(lineStripped[len('def ') :].strip()) functions.sort() return functions
def __init__(self, fontFamily): "Initialize." self.fontFamily = fontFamily self.glyphDictionary = {} self.glyphElementNodeDictionary = {} self.missingGlyph = None fileName = os.path.join(getFontsDirectoryPath(), fontFamily + '.svg') documentElement = DocumentNode(fileName, archive.getFileText(fileName)).getDocumentElement() self.fontElementNode = documentElement.getFirstChildByLocalName('defs').getFirstChildByLocalName('font') self.fontFaceElementNode = self.fontElementNode.getFirstChildByLocalName('font-face') self.unitsPerEM = float(self.fontFaceElementNode.attributes['units-per-em']) glyphElementNodes = self.fontElementNode.getChildElementsByLocalName('glyph') for glyphElementNode in glyphElementNodes: self.glyphElementNodeDictionary[glyphElementNode.attributes['unicode']] = glyphElementNode
def addInitializationToOutput(self): "Add initialization gcode to the output." self.distanceFeedRate.addTagBracketedLine("format", "skeinforge gcode") absoluteFilePathUntilDot = archive.getUntilDot(archive.getCraftPluginsDirectoryPath("preface.py")) dateTodayString = date.today().isoformat().replace("-", ".")[2:] if ( absoluteFilePathUntilDot == "/home/enrique/Desktop/backup/babbleold/script/reprap/fabmetheus/skeinforge_application/skeinforge_plugins/craft_plugins/preface" ): # is this script on Enrique's computer? archive.writeFileText(archive.getVersionFileName(), dateTodayString) versionText = archive.getFileText(archive.getVersionFileName()) self.distanceFeedRate.addTagBracketedLine("version", versionText) dateTimeTuple = datetime.now().timetuple() created = dateTodayString + "|%s:%s" % (dateTimeTuple[3], dateTimeTuple[4]) self.distanceFeedRate.addTagBracketedLine("created", created) self.distanceFeedRate.addLine("(<extruderInitialization>)") if self.repository.setPositioningToAbsolute.value: self.distanceFeedRate.addLine("G90 ;set positioning to absolute") # Set positioning to absolute. if self.repository.setUnitsToMillimeters.value: self.distanceFeedRate.addLine("G21 ;set units to millimeters") # Set units to millimeters. if self.repository.startAtHome.value: self.distanceFeedRate.addLine("G28 ;start at home") # Start at home. if self.repository.turnExtruderOffAtStartUp.value: self.distanceFeedRate.addLine("M103") # Turn extruder off. craftTypeName = skeinforge_profile.getCraftTypeName() self.distanceFeedRate.addTagBracketedLine("craftTypeName", craftTypeName) self.distanceFeedRate.addTagBracketedLine("decimalPlacesCarried", self.distanceFeedRate.decimalPlacesCarried) layerHeight = float(self.svgReader.sliceDictionary["layerHeight"]) self.distanceFeedRate.addTagRoundedLine("layerThickness", layerHeight) self.distanceFeedRate.addTagRoundedLine("layerHeight", layerHeight) if self.repository.meta.value: self.distanceFeedRate.addTagBracketedLine("meta", self.repository.meta.value) edgeWidth = float(self.svgReader.sliceDictionary["edgeWidth"]) self.distanceFeedRate.addTagRoundedLine("edgeWidth", edgeWidth) self.distanceFeedRate.addTagRoundedLine("perimeterWidth", edgeWidth) self.distanceFeedRate.addTagBracketedLine("profileName", skeinforge_profile.getProfileName(craftTypeName)) self.distanceFeedRate.addLine("(<settings>)") pluginFileNames = skeinforge_craft.getPluginFileNames() for pluginFileName in pluginFileNames: self.addToolSettingLines(pluginFileName) self.distanceFeedRate.addLine("(</settings>)") self.distanceFeedRate.addTagBracketedLine("timeStampPreface", strftime("%Y%m%d_%H%M%S")) procedureNames = self.svgReader.sliceDictionary["procedureName"].replace(",", " ").split() for procedureName in procedureNames: self.distanceFeedRate.addTagBracketedProcedure(procedureName) self.distanceFeedRate.addTagBracketedProcedure("preface") self.distanceFeedRate.addLine( "(</extruderInitialization>)" ) # Initialization is finished, extrusion is starting. self.distanceFeedRate.addLine("(<crafting>)") # Initialization is finished, crafting is starting.
def __init__(self, fontFamily): "Initialize." self.fontFamily = fontFamily self.glyphDictionary = {} self.glyphXMLElementDictionary = {} self.missingGlyph = None fileName = os.path.join(getFontsDirectoryPath(), fontFamily + '.svg') self.xmlParser = XMLSimpleReader(fileName, None, archive.getFileText(fileName)) self.fontXMLElement = self.xmlParser.getRoot().getFirstChildWithClassName('defs').getFirstChildWithClassName('font') self.fontFaceXMLElement = self.fontXMLElement.getFirstChildWithClassName('font-face') self.unitsPerEM = float(self.fontFaceXMLElement.attributeDictionary['units-per-em']) glyphXMLElements = self.fontXMLElement.getChildrenWithClassName('glyph') for glyphXMLElement in glyphXMLElements: self.glyphXMLElementDictionary[glyphXMLElement.attributeDictionary['unicode']] = glyphXMLElement
def __init__(self, slicedModel): self.slicedModel = slicedModel self.boundaryLayers = [] self.supportLayers = [] self.debug = config.getboolean(configSection, 'debug') self.supportLocation = config.get(configSection, 'location') self.supportMinimumAngle = config.getfloat(configSection, 'min.angle') self.minimumSupportRatio = math.tan(math.radians(self.supportMinimumAngle)) self.supportCrossHatchNthLayer = config.getint(configSection, 'crosshatch.every.nth.layer') self.supportFeedRate = config.getfloat('speed', 'feed.rate.support') self.supportFlowRateRatio = config.getfloat('speed', 'flow.rate.support.ratio') self.raftAdditionalMarginOverLengthPercent = config.getfloat(configSection, 'extension.percent') self.raftMargin = config.getfloat(configSection, 'extension.distance') self.infillOverhangOverExtrusionWidth = config.getfloat(configSection, 'infill.overhang.ratio') self.supportStartFile = config.get(configSection, 'support.start.file') self.supportEndFile = config.get(configSection, 'support.end.file') self.absoluteSupportStartFilePath = os.path.join('alterations', self.supportStartFile) self.absoluteSupportEndFilePath = os.path.join('alterations', self.supportEndFile) self.supportStartLines = archive.getTextLines(archive.getFileText(self.absoluteSupportStartFilePath, printWarning=False)) self.supportEndLines = archive.getTextLines(archive.getFileText(self.absoluteSupportEndFilePath, printWarning=False)) self.extrusionWidth = config.getfloat('carve', 'extrusion.width') self.supportGapOverPerimeterExtrusionWidth = config.getfloat(configSection, 'gap.over.perimeter.extrusion.width.ratio') self.supportOutset = self.extrusionWidth * self.supportGapOverPerimeterExtrusionWidth self.interfaceInfillDensity = config.getfloat(configSection, 'interface.infill.density') self.interfaceLayerThicknessRatio = config.getfloat(configSection, 'interface.layer.thickness.ratio') interfaceExtrusionWidth = self.extrusionWidth * self.interfaceLayerThicknessRatio self.interfaceStep = interfaceExtrusionWidth / self.interfaceInfillDensity self.cornerMinimum = self.slicedModel.carvingCornerMinimum self.cornerMaximum = self.slicedModel.carvingCornerMaximum self.cornerMinimumComplex = self.cornerMinimum.dropAxis() self.cornerMaximumComplex = self.cornerMaximum.dropAxis()
def execute(self): "Export the canvas as an svg file." svgFileName = archive.getFilePathWithUnderscoredBasename( self.fileName, self.suffix ) boundingBox = self.canvas.bbox( settings.Tkinter.ALL ) # tuple (w, n, e, s) self.boxW = boundingBox[0] self.boxN = boundingBox[1] boxWidth = boundingBox[2] - self.boxW boxHeight = boundingBox[3] - self.boxN print('Exported svg file saved as ' + svgFileName ) svgTemplateText = archive.getFileText(archive.getTemplatesPath('canvas_template.svg')) output = cStringIO.StringIO() lines = archive.getTextLines( svgTemplateText ) firstWordTable = {} firstWordTable['height="999px"'] = ' height="%spx"' % int( round( boxHeight ) ) firstWordTable['<!--replaceLineWith_coloredLines-->'] = self.getCanvasLinesOutput() firstWordTable['replaceLineWithTitle'] = archive.getSummarizedFileName( self.fileName ) firstWordTable['width="999px"'] = ' width="%spx"' % int( round( boxWidth ) ) for line in lines: parseLineReplace( firstWordTable, line, output ) archive.writeFileText( svgFileName, output.getvalue() ) fileExtension = self.fileExtension.value svgViewer = self.svgViewer.value if svgViewer == '': return if svgViewer == 'webbrowser': settings.openWebPage( svgFileName ) return svgFilePath = '"' + os.path.normpath( svgFileName ) + '"' # " to send in file name with spaces shellCommand = svgViewer + ' ' + svgFilePath print('') if fileExtension == '': print('Sending the shell command:') print(shellCommand) commandResult = os.system(shellCommand) if commandResult != 0: print('It may be that the system could not find the %s program.' % svgViewer ) print('If so, try installing the %s program or look for another svg viewer, like Netscape which can be found at:' % svgViewer ) print('http://www.netscape.org/') return convertedFileName = archive.getFilePathWithUnderscoredBasename( svgFilePath, '.' + fileExtension + '"') shellCommand += ' ' + convertedFileName print('Sending the shell command:') print(shellCommand) commandResult = os.system(shellCommand) if commandResult != 0: print('The %s program could not convert the svg to the %s file format.' % ( svgViewer, fileExtension ) ) print('Try installing the %s program or look for another one, like Image Magick which can be found at:' % svgViewer ) print('http://www.imagemagick.org/script/index.php')
def execute(self): """Export the canvas as an svg file.""" svgFileName = archive.getFilePathWithUnderscoredBasename( self.fileName, self.suffix ) boundingBox = self.canvas.bbox( settings.Tkinter.ALL ) # tuple (w, n, e, s) self.boxW = boundingBox[0] self.boxN = boundingBox[1] boxWidth = boundingBox[2] - self.boxW boxHeight = boundingBox[3] - self.boxN print('Exported svg file saved as ' + svgFileName ) svgTemplateText = archive.getFileText(archive.getTemplatesPath('canvas_template.svg')) output = cStringIO.StringIO() lines = archive.getTextLines( svgTemplateText ) firstWordTable = {} firstWordTable['height="999px"'] = ' height="%spx"' % int( round( boxHeight ) ) firstWordTable['<!--replaceLineWith_coloredLines-->'] = self.getCanvasLinesOutput() firstWordTable['replaceLineWithTitle'] = archive.getSummarizedFileName( self.fileName ) firstWordTable['width="999px"'] = ' width="%spx"' % int( round( boxWidth ) ) for line in lines: parseLineReplace( firstWordTable, line, output ) archive.writeFileText( svgFileName, output.getvalue() ) fileExtension = self.fileExtension.value svgViewer = self.svgViewer.value if svgViewer == '': return if svgViewer == 'webbrowser': settings.openWebPage( svgFileName ) return svgFilePath = '"' + os.path.normpath( svgFileName ) + '"' # " to send in file name with spaces shellCommand = svgViewer + ' ' + svgFilePath print('') if fileExtension == '': print('Sending the shell command:') print(shellCommand) commandResult = os.system(shellCommand) if commandResult != 0: print('It may be that the system could not find the %s program.' % svgViewer ) print('If so, try installing the %s program or look for another svg viewer, like Netscape which can be found at:' % svgViewer ) print('http://www.netscape.org/') return convertedFileName = archive.getFilePathWithUnderscoredBasename( svgFilePath, '.' + fileExtension + '"') shellCommand += ' ' + convertedFileName print('Sending the shell command:') print(shellCommand) commandResult = os.system(shellCommand) if commandResult != 0: print('The %s program could not convert the svg to the %s file format.' % ( svgViewer, fileExtension ) ) print('Try installing the %s program or look for another one, like Image Magick which can be found at:' % svgViewer ) print('http://www.imagemagick.org/script/index.php')
def processElementNodeByDerivation(derivation, elementNode): 'Process the xml element by derivation.' if derivation == None: derivation = ImportDerivation(elementNode) if derivation.fileName == None: return parserFileName = elementNode.getOwnerDocument().fileName absoluteFileName = archive.getAbsoluteFolderPath(parserFileName, derivation.fileName) if 'models/' not in absoluteFileName: print( 'Warning, models/ was not in the absolute file path, so for security nothing will be done for:' ) print(elementNode) print('For which the absolute file path is:') print(absoluteFileName) print( 'The import tool can only read a file which has models/ in the file path.' ) print( 'To import the file, move the file into a folder called model/ or a subfolder which is inside the model folder tree.' ) return xmlText = '' if derivation.fileName.endswith('.xml'): xmlText = archive.getFileText(absoluteFileName) else: xmlText = getXMLFromCarvingFileName(absoluteFileName) print('The import tool is opening the file:') print(absoluteFileName) if xmlText == '': print( 'The file %s could not be found by processElementNode in import.' % derivation.fileName) return if derivation.importName == None: elementNode.attributes['_importName'] = archive.getUntilDot( derivation.fileName) if derivation.basename: elementNode.attributes['_importName'] = os.path.basename( elementNode.attributes['_importName']) xml_simple_reader.createAppendByText(elementNode, xmlText) if derivation.appendDocumentElement: appendAttributes(elementNode, elementNode.getDocumentElement()) if derivation.appendElement: appendAttributes(elementNode, elementNode) elementNode.localName = 'group' evaluate.processArchivable(group.Group, elementNode)
def getCarving(fileName=''): "Get the triangle mesh for the stl file." if fileName == '': return None stlData = archive.getFileText(fileName, True, 'rb') if stlData == '': return None triangleMesh = triangle_mesh.TriangleMesh() vertexIndexTable = {} numberOfVertexStrings = stlData.count('vertex') requiredVertexStringsForText = max( 2, len( stlData ) / 8000 ) if numberOfVertexStrings > requiredVertexStringsForText: addFacesGivenText( stlData, triangleMesh, vertexIndexTable ) else: # A binary stl should never start with the word "solid". Because this error is common the file is been parsed as binary regardless. addFacesGivenBinary( stlData, triangleMesh, vertexIndexTable ) return triangleMesh
def getFunctionLists(fileName): 'Get the function lists in the file.' fileText = archive.getFileText(fileName) functionList = [] functionLists = [functionList] lines = archive.getTextLines(fileText) for line in lines: lineStripped = line.strip() if lineStripped.startswith('def '): bracketIndex = lineStripped.find('(') if bracketIndex > -1: lineStripped = lineStripped[:bracketIndex] functionList.append(lineStripped) elif line.startswith('class'): functionList = [] functionLists.append(functionList) return functionLists