chiark / gitweb /
Move SF into its own directory, to seperate SF and Cura. Rename newui to gui.
[cura.git] / Cura / cura_sf / fabmetheus_utilities / archive.py
1 """
2 Boolean geometry utilities.
3
4 """
5
6 from __future__ import absolute_import
7 #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.
8 import __init__
9
10 import os
11 import sys
12 import traceback
13
14
15 __author__ = 'Enrique Perez (perez_enrique@yahoo.com)'
16 __credits__ = 'Art of Illusion <http://www.artofillusion.org/>'
17 __date__ = '$Date: 2008/02/05 $'
18 __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
19
20
21 globalTemporarySettingsPath = os.path.join(os.path.expanduser('~'), '.skeinforge_pypy')
22
23
24 def addToNamePathDictionary(directoryPath, namePathDictionary):
25         'Add to the name path dictionary.'
26         pluginFileNames = getPluginFileNamesFromDirectoryPath(directoryPath)
27         for pluginFileName in pluginFileNames:
28                 namePathDictionary[pluginFileName.replace('_', '')] = os.path.join(directoryPath, pluginFileName)
29
30 def getAbsoluteFolderPath(filePath, folderName=''):
31         'Get the absolute folder path.'
32         absoluteFolderPath = os.path.dirname(os.path.abspath(filePath))
33         if folderName == '':
34                 return absoluteFolderPath
35         return os.path.join(absoluteFolderPath, folderName)
36
37 def getAbsoluteFrozenFolderPath(filePath, folderName=''):
38         'Get the absolute frozen folder path.'
39         if hasattr(sys, 'frozen'):
40                 if '.py' in filePath:
41                         filePath = ''.join(filePath.rpartition('\\')[: 2])
42                 filePath = os.path.join(filePath, 'skeinforge_application')
43         return getAbsoluteFolderPath(filePath, folderName)
44
45 def getAnalyzePluginsDirectoryPath(subName=''):
46         'Get the analyze plugins directory path.'
47         return getJoinedPath(getSkeinforgePluginsPath('analyze_plugins'), subName)
48
49 def getCraftPluginsDirectoryPath(subName=''):
50         'Get the craft plugins directory path.'
51         return getJoinedPath(getSkeinforgePluginsPath('craft_plugins'), subName)
52
53 def getDocumentationPath(subName=''):
54         'Get the documentation file path.'
55         return getJoinedPath(getFabmetheusPath('documentation'), subName)
56
57 def getElementsPath(subName=''):
58         'Get the evaluate_elements directory path.'
59         return getJoinedPath(getGeometryUtilitiesPath('evaluate_elements'), subName)
60
61 def getEndsWithList(word, wordEndings):
62         'Determine if the word ends with a list.'
63         for wordEnding in wordEndings:
64                 if word.endswith(wordEnding):
65                         return True
66         return False
67
68 def getFabmetheusPath(subName=''):
69         'Get the fabmetheus directory path.'
70         fabmetheusFile = None
71         if hasattr(sys, 'frozen'):
72                 fabmetheusFile = unicode(sys.executable, sys.getfilesystemencoding())
73         else:
74                 fabmetheusFile = os.path.dirname(os.path.abspath(__file__))
75         return getJoinedPath(os.path.dirname(fabmetheusFile), subName)
76
77 def getFabmetheusToolsPath(subName=''):
78         'Get the fabmetheus tools directory path.'
79         return getJoinedPath(getFabmetheusUtilitiesPath('fabmetheus_tools'), subName)
80
81 def getFabmetheusUtilitiesPath(subName=''):
82         'Get the fabmetheus utilities directory path.'
83         return getJoinedPath(getFabmetheusPath('fabmetheus_utilities'), subName)
84
85 def getFileNamesByFilePaths(pluginFilePaths):
86         'Get the file names of the plugins by the file paths.'
87         fileNames = []
88         for pluginFilePath in pluginFilePaths:
89                 pluginBasename = os.path.basename(pluginFilePath)
90                 pluginBasename = getUntilDot(pluginBasename)
91                 fileNames.append(pluginBasename)
92         return fileNames
93
94 def getFilePaths(fileInDirectory=''):
95         'Get the file paths in the directory of the file in directory.'
96         directoryName = os.getcwd()
97         if fileInDirectory != '':
98                 directoryName = os.path.dirname(fileInDirectory)
99         return getFilePathsByDirectory(directoryName)
100
101 def getFilePathsByDirectory(directoryName):
102         'Get the file paths in the directory of the file in directory.'
103         absoluteDirectoryPath = os.path.abspath(directoryName)
104         directory = os.listdir(directoryName)
105         filePaths = []
106         for fileName in directory:
107                 filePaths.append(os.path.join(absoluteDirectoryPath, fileName))
108         return filePaths
109
110 def getFilePathsRecursively(fileInDirectory=''):
111         'Get the file paths in the directory of the file in directory.'
112         filePaths = getFilePaths(fileInDirectory)
113         filePathsRecursively = filePaths[:]
114         for filePath in filePaths:
115                 if os.path.isdir(filePath):
116                         directory = os.listdir(filePath)
117                         if len(directory) > 0:
118                                 filePathsRecursively += getFilePathsRecursively(os.path.join(filePath, directory[0]))
119         return filePathsRecursively
120
121 def getFilePathWithUnderscoredBasename(fileName, suffix):
122         'Get the file path with all spaces in the basename replaced with underscores.'
123         suffixFileName = getUntilDot(fileName) + suffix
124         suffixDirectoryName = os.path.dirname(suffixFileName)
125         suffixReplacedBaseName = os.path.basename(suffixFileName).replace(' ', '_')
126         return os.path.join(suffixDirectoryName, suffixReplacedBaseName)
127
128 def getFilesWithFileTypesWithoutWords(fileTypes, words = [], fileInDirectory=''):
129         'Get files which have a given file type, but with do not contain a word in a list.'
130         filesWithFileTypes = []
131         for filePath in getFilePaths(fileInDirectory):
132                 for fileType in fileTypes:
133                         if isFileWithFileTypeWithoutWords(fileType, filePath, words):
134                                 filesWithFileTypes.append(filePath)
135         filesWithFileTypes.sort()
136         return filesWithFileTypes
137
138 def getFilesWithFileTypesWithoutWordsRecursively(fileTypes, words = [], fileInDirectory=''):
139         'Get files recursively which have a given file type, but with do not contain a word in a list.'
140         filesWithFileTypesRecursively = []
141         for filePath in getFilePathsRecursively(fileInDirectory):
142                 for fileType in fileTypes:
143                         if isFileWithFileTypeWithoutWords(fileType, filePath, words):
144                                 filesWithFileTypesRecursively.append(filePath)
145         filesWithFileTypesRecursively.sort()
146         return filesWithFileTypesRecursively
147
148 def getFilesWithFileTypeWithoutWords(fileType, words = [], fileInDirectory=''):
149         'Get files which have a given file type, but with do not contain a word in a list.'
150         filesWithFileType = []
151         for filePath in getFilePaths(fileInDirectory):
152                 if isFileWithFileTypeWithoutWords(fileType, filePath, words):
153                         filesWithFileType.append(filePath)
154         filesWithFileType.sort()
155         return filesWithFileType
156
157 def getFileText(fileName, printWarning=True, readMode='r'):
158         'Get the entire text of a file.'
159         try:
160                 file = open(fileName, readMode)
161                 fileText = file.read()
162                 file.close()
163                 return fileText
164         except IOError:
165                 if printWarning:
166                         print('The file ' + fileName + ' does not exist.')
167         return ''
168
169 def getFileTextInFileDirectory(fileInDirectory, fileName, readMode='r'):
170         'Get the entire text of a file in the directory of the file in directory.'
171         absoluteFilePathInFileDirectory = os.path.join(os.path.dirname(fileInDirectory), fileName)
172         return getFileText(absoluteFilePathInFileDirectory, True, readMode)
173
174 def getFundamentalsPath(subName=''):
175         'Get the evaluate_fundamentals directory path.'
176         return getJoinedPath(getGeometryUtilitiesPath('evaluate_fundamentals'), subName)
177
178 def getGeometryDictionary(folderName):
179         'Get to the geometry name path dictionary.'
180         geometryDictionary={}
181         geometryDirectory = getGeometryPath()
182         addToNamePathDictionary(os.path.join(geometryDirectory, folderName), geometryDictionary)
183         geometryPluginsDirectory = getFabmetheusUtilitiesPath('geometry_plugins')
184         addToNamePathDictionary(os.path.join(geometryPluginsDirectory, folderName), geometryDictionary)
185         return geometryDictionary
186
187 def getGeometryPath(subName=''):
188         'Get the geometry directory path.'
189         return getJoinedPath(getFabmetheusUtilitiesPath('geometry'), subName)
190
191 def getGeometryToolsPath(subName=''):
192         'Get the geometry tools directory path.'
193         return getJoinedPath(getGeometryPath('geometry_tools'), subName)
194
195 def getGeometryUtilitiesPath(subName=''):
196         'Get the geometry_utilities directory path.'
197         return getJoinedPath(getGeometryPath('geometry_utilities'), subName)
198
199 def getInterpretPluginsPath(subName=''):
200         'Get the interpret plugins directory path.'
201         return getJoinedPath(getFabmetheusToolsPath('interpret_plugins'), subName)
202
203 def getJoinedPath(path, subName=''):
204         'Get the joined file path.'
205         if subName == '':
206                 return path
207         return os.path.join(path, subName)
208
209 def getModuleWithDirectoryPath(directoryPath, fileName):
210         'Get the module from the fileName and folder name.'
211         if fileName == '':
212                 print('The file name in getModule in archive was empty.')
213                 return None
214         originalSystemPath = sys.path[:]
215         try:
216                 sys.path.insert(0, directoryPath)
217                 folderPluginsModule = __import__(fileName)
218                 sys.path = originalSystemPath
219                 return folderPluginsModule
220         except:
221                 sys.path = originalSystemPath
222                 print('')
223                 print('Exception traceback in getModuleWithDirectoryPath in archive:')
224                 traceback.print_exc(file=sys.stdout)
225                 print('')
226                 print('That error means; could not import a module with the fileName ' + fileName)
227                 print('and an absolute directory name of ' + directoryPath)
228                 print('')
229         return None
230
231 def getModuleWithPath(path):
232         'Get the module from the path.'
233         return getModuleWithDirectoryPath(os.path.dirname(path), os.path.basename(path))
234
235 def getPluginFileNamesFromDirectoryPath(directoryPath):
236         'Get the file names of the python plugins in the directory path.'
237         fileInDirectory = os.path.join(directoryPath, '__init__.py')
238         return getFileNamesByFilePaths(getPythonFileNamesExceptInit(fileInDirectory))
239
240 def getProfilesPath(subName=''):
241         'Get the profiles directory path, which is the settings directory joined with profiles.'
242         return getJoinedPath(getSettingsPath('profiles'), subName)
243
244 def getPythonDirectoryNames(directoryName):
245         'Get the python directories.'
246         pythonDirectoryNames = []
247         directory = os.listdir(directoryName)
248         for fileName in directory:
249                 subdirectoryName = os.path.join(directoryName, fileName)
250                 if os.path.isdir(subdirectoryName):
251                         if os.path.isfile(os.path.join(subdirectoryName, '__init__.py')):
252                                 pythonDirectoryNames.append(subdirectoryName)
253         return pythonDirectoryNames
254
255 def getPythonDirectoryNamesRecursively(directoryName=''):
256         'Get the python directories recursively.'
257         recursivePythonDirectoryNames = []
258         if directoryName == '':
259                 directoryName = os.getcwd()
260         if os.path.isfile(os.path.join(directoryName, '__init__.py')):
261                 recursivePythonDirectoryNames.append(directoryName)
262                 pythonDirectoryNames = getPythonDirectoryNames(directoryName)
263                 for pythonDirectoryName in pythonDirectoryNames:
264                         recursivePythonDirectoryNames += getPythonDirectoryNamesRecursively(pythonDirectoryName)
265         else:
266                 return []
267         return recursivePythonDirectoryNames
268
269 def getPythonFileNamesExceptInit(fileInDirectory=''):
270         'Get the python fileNames of the directory which the fileInDirectory is in, except for the __init__.py file.'
271         pythonFileNamesExceptInit = getFilesWithFileTypeWithoutWords('py', ['__init__.py'], fileInDirectory)
272         pythonFileNamesExceptInit.sort()
273         return pythonFileNamesExceptInit
274
275 def getPythonFileNamesExceptInitRecursively(directoryName=''):
276         'Get the python fileNames of the directory recursively, except for the __init__.py files.'
277         pythonDirectoryNames = getPythonDirectoryNamesRecursively(directoryName)
278         pythonFileNamesExceptInitRecursively = []
279         for pythonDirectoryName in pythonDirectoryNames:
280                 pythonFileNamesExceptInitRecursively += getPythonFileNamesExceptInit(os.path.join(pythonDirectoryName, '__init__.py'))
281         pythonFileNamesExceptInitRecursively.sort()
282         return pythonFileNamesExceptInitRecursively
283
284 def getSettingsPath(subName=''):
285         'Get the settings directory path, which is the home directory joined with .skeinforge.'
286         global globalTemporarySettingsPath
287         return getJoinedPath(globalTemporarySettingsPath, subName)
288
289 def getSkeinforgePath(subName=''):
290         'Get the skeinforge directory path.'
291         return getJoinedPath(getFabmetheusPath('skeinforge_application'), subName)
292
293 def getSkeinforgePluginsPath(subName=''):
294         'Get the skeinforge plugins directory path.'
295         return getJoinedPath(getSkeinforgePath('skeinforge_plugins'), subName)
296
297 def getSummarizedFileName(fileName):
298         'Get the fileName basename if the file is in the current working directory, otherwise return the original full name.'
299         if os.getcwd() == os.path.dirname(fileName):
300                 return os.path.basename(fileName)
301         return fileName
302
303 def getTemplatesPath(subName=''):
304         'Get the templates directory path.'
305         return getJoinedPath(getFabmetheusUtilitiesPath('templates'), subName)
306
307 def getTextIfEmpty(fileName, text):
308         'Get the text from a file if it the text is empty.'
309         if text != '':
310                 return text
311         return getFileText(fileName)
312
313 def getTextLines(text):
314         'Get the all the lines of text of a text.'
315         if '\r' in text:
316                 text = text.replace('\r', '\n').replace('\n\n', '\n')
317         textLines = text.split('\n')
318         if len(textLines) == 1:
319                 if textLines[0] == '':
320                         return []
321         return textLines
322
323 def getUntilDot(text):
324         'Get the text until the last dot, if any.'
325         dotIndex = text.rfind('.')
326         if dotIndex < 0:
327                 return text
328         return text[: dotIndex]
329
330 def getVersionFileName():
331         'Get the file name of the version date.getFabmetheusUtilitiesPath(subName='')'
332         return getFabmetheusUtilitiesPath('version.txt')
333
334 def isFileWithFileTypeWithoutWords(fileType, fileName, words):
335         'Determine if file has a given file type, but with does not contain a word in a list.'
336         fileName = os.path.basename(fileName)
337         fileTypeDot = '.' + fileType
338         if not fileName.endswith(fileTypeDot):
339                 return False
340         for word in words:
341                 if fileName.find(word) >= 0:
342                         return False
343         return True
344
345 def makeDirectory(directoryPath):
346         'Make a directory if it does not already exist.'
347         if os.path.isdir(directoryPath):
348                 return
349         try:
350                 print('The following directory was made:')
351                 print(os.path.abspath(directoryPath))
352                 os.makedirs(directoryPath)
353         except OSError:
354                 print('Skeinforge can not make the directory %s so give it read/write permission for that directory and the containing directory.' % directoryPath)
355
356 def removeBackupFilesByType(fileType):
357         'Remove backup files by type.'
358         backupFilePaths = getFilesWithFileTypesWithoutWordsRecursively([fileType + '~'])
359         for backupFilePath in backupFilePaths:
360                 os.remove(backupFilePath)
361
362 def removeBackupFilesByTypes(fileTypes):
363         'Remove backup files by types.'
364         for fileType in fileTypes:
365                 removeBackupFilesByType(fileType)
366
367 def writeFileMessageEnd(end, fileName, fileText, message):
368         'Write to a fileName with a suffix and print a message.'
369         suffixFileName = getUntilDot(fileName) + end
370         writeFileText(suffixFileName, fileText)
371         print(message + getSummarizedFileName(suffixFileName))
372
373 def writeFileText(fileName, fileText, writeMode='w+'):
374         'Write a text to a file.'
375         try:
376                 file = open(fileName, writeMode)
377                 file.write(fileText)
378                 file.close()
379         except IOError:
380                 print('The file ' + fileName + ' can not be written to.')