<commit_before>#***************************************************************************
#*                                                                         *
#*   Copyright (c) 2012 <NAME> <<EMAIL>>       *
#*                                                                         *
#*   This program is free software; you can redistribute it and/or modify  *
#*   it under the terms of the GNU Lesser General Public License (LGPL)    *
#*   as published by the Free Software Foundation; either version 2 of     *
#*   the License, or (at your option) any later version.                   *
#*   for detail see the LICENCE text file.                                 *
#*                                                                         *
#*   This program is distributed in the hope that it will be useful,       *
#*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
#*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
#*   GNU Library General Public License for more details.                  *
#*                                                                         *
#*   You should have received a copy of the GNU Library General Public     *
#*   License along with this program; if not, write to the Free Software   *
#*   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
#*   USA                                                                   *
#*                                                                         *
#***************************************************************************

__title__="FreeCAD OpenSCAD Workbench - Utility Fuctions"
__author__ = "<NAME>"
__url__ = ["http://www.freecadweb.org"]

'''
This Script includes various pyhton helper functions that are shared across
the module
'''

def translate(context,text):
    "convenience function for Qt translator"
    from PySide import QtGui
    return QtGui.QApplication.translate(context, text, None, \
        QtGui.QApplication.UnicodeUTF8)

class OpenSCADError(Exception):
    def __init__(self,value):
        self.value= value
    #def __repr__(self):
    #    return self.msg
    def __str__(self):
        return repr(self.value)

def searchforopenscadexe():
    import os,sys,subprocess
    if sys.platform == 'win32':
        testpaths = [os.path.join(os.environ.get('Programfiles(x86)','C:'),\
            'OpenSCAD\\openscad.exe')]
        if 'ProgramW6432' in os.environ:
            testpaths.append(os.path.join(os.environ.get('ProgramW6432','C:')\
                ,'OpenSCAD\\openscad.exe'))
        for testpath in testpaths:
            if os.path.isfile(testpath):
                return testpath
    else: #unix
        p1=subprocess.Popen(['which','openscad'],stdout=subprocess.PIPE)
        if p1.wait() == 0:
            opath=p1.stdout.read().split('\n')[0]
            return opath

def workaroundforissue128needed():
    '''sets the import path depending on the OpenSCAD Verion
    for versions <= 2012.06.23 to the current working dir
    for versions above to the inputfile dir
    see https://github.com/openscad/openscad/issues/128'''
    vdate=getopenscadversion().split(' ')[2].split('.')
    year,mon=int(vdate[0]),int(vdate[1])
    return (year<2012 or (year==2012 and (mon <6 or (mon == 6 and \
        (len(vdate)<3 or int(vdate[2]) <=23)))))
    #ifdate=int(vdate[0])+(int(vdate[1])-1)/12.0
    #if len(vdate)>2:
    #    fdate+=int((vdate[2])-1)/12.0/31.0
    #return fdate < 2012.4759

def getopenscadversion(osfilename=None):
    import os,subprocess,time
    if not osfilename:
        import FreeCAD
        osfilename = FreeCAD.ParamGet(\
            "User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
            GetString('openscadexecutable')
    if osfilename and os.path.isfile(osfilename):
        p=subprocess.Popen([osfilename,'-v'],\
            stdout=subprocess.PIPE,universal_newlines=True)
        p.wait()
        return p.stdout.read().strip()

def newtempfilename():
    import os,time
    formatstr='fc-%05d-%06d-%06d'
    count = 0
    while True:
        count+=1
        yield formatstr % (os.getpid(),int(time.time()*100) % 1000000,count)

tempfilenamegen=newtempfilename()

def callopenscad(inputfilename,outputfilename=None,outputext='csg',keepname=False):
    '''call the open scad binary
    returns the filename of the result (or None),
    please delete the file afterwards'''
    import FreeCAD,os,subprocess,tempfile,time
    def check_output2(*args,**kwargs):
        kwargs.update({'stdout':subprocess.PIPE})
        p=subprocess.Popen(*args,**kwargs)
        stdoutd,stderrd = p.communicate()
        if p.returncode != 0:
            raise OpenSCADError('%s\n' % stdoutd.strip())
            #raise Exception,'stdout %s\n stderr%s' %(stdoutd,stderrd)
        if stdoutd.strip():
            FreeCAD.Console.PrintMessage(stdoutd+u'\n')
            return stdoutd

    osfilename = FreeCAD.ParamGet(\
        "User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
        GetString('openscadexecutable')
    if osfilename and os.path.isfile(osfilename):
        if not outputfilename:
            dir1=tempfile.gettempdir()
            if keepname:
                outputfilename=os.path.join(dir1,'%s.%s' % (os.path.split(\
                    inputfilename)[1].rsplit('.',1)[0],outputext))
            else:
                outputfilename=os.path.join(dir1,'%s.%s' % \
                    (tempfilenamegen.next(),outputext))
        check_output2([osfilename,'-o',outputfilename, inputfilename],\
            stderr=subprocess.STDOUT)
        return outputfilename

def callopenscadstring(scadstr,outputext='csg'):
    '''create a tempfile and call the open scad binary
    returns the filename of the result (or None),
    please delete the file afterwards'''
    import os,tempfile,time
    dir1=tempfile.gettempdir()
    inputfilename=os.path.join(dir1,'%s.scad' % tempfilenamegen.next())
    inputfile = open(inputfilename,'w')
    inputfile.write(scadstr)
    inputfile.close()
    outputfilename = callopenscad(inputfilename,outputext=outputext,\
        keepname=True)
    os.unlink(inputfilename)
    return outputfilename

def reverseimporttypes():
    '''allows to search for supported filetypes by module'''

    def getsetfromdict(dict1,index):<commit_msg>OpenSCAD binary gives version info on stderr in never versions<commit_after>#***************************************************************************
#*                                                                         *
#*   Copyright (c) 2012 <NAME> <<EMAIL>>       *
#*                                                                         *
#*   This program is free software; you can redistribute it and/or modify  *
#*   it under the terms of the GNU Lesser General Public License (LGPL)    *
#*   as published by the Free Software Foundation; either version 2 of     *
#*   the License, or (at your option) any later version.                   *
#*   for detail see the LICENCE text file.                                 *
#*                                                                         *
#*   This program is distributed in the hope that it will be useful,       *
#*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
#*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
#*   GNU Library General Public License for more details.                  *
#*                                                                         *
#*   You should have received a copy of the GNU Library General Public     *
#*   License along with this program; if not, write to the Free Software   *
#*   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
#*   USA                                                                   *
#*                                                                         *
#***************************************************************************

__title__="FreeCAD OpenSCAD Workbench - Utility Fuctions"
__author__ = "<NAME>"
__url__ = ["http://www.freecadweb.org"]

'''
This Script includes various pyhton helper functions that are shared across
the module
'''

def translate(context,text):
    "convenience function for Qt translator"
    from PySide import QtGui
    return QtGui.QApplication.translate(context, text, None, \
        QtGui.QApplication.UnicodeUTF8)

class OpenSCADError(Exception):
    def __init__(self,value):
        self.value= value
    #def __repr__(self):
    #    return self.msg
    def __str__(self):
        return repr(self.value)

def searchforopenscadexe():
    import os,sys,subprocess
    if sys.platform == 'win32':
        testpaths = [os.path.join(os.environ.get('Programfiles(x86)','C:'),\
            'OpenSCAD\\openscad.exe')]
        if 'ProgramW6432' in os.environ:
            testpaths.append(os.path.join(os.environ.get('ProgramW6432','C:')\
                ,'OpenSCAD\\openscad.exe'))
        for testpath in testpaths:
            if os.path.isfile(testpath):
                return testpath
    else: #unix
        p1=subprocess.Popen(['which','openscad'],stdout=subprocess.PIPE)
        if p1.wait() == 0:
            opath=p1.stdout.read().split('\n')[0]
            return opath

def workaroundforissue128needed():
    '''sets the import path depending on the OpenSCAD Verion
    for versions <= 2012.06.23 to the current working dir
    for versions above to the inputfile dir
    see https://github.com/openscad/openscad/issues/128'''
    vdate=getopenscadversion().split(' ')[2].split('.')
    year,mon=int(vdate[0]),int(vdate[1])
    return (year<2012 or (year==2012 and (mon <6 or (mon == 6 and \
        (len(vdate)<3 or int(vdate[2]) <=23)))))
    #ifdate=int(vdate[0])+(int(vdate[1])-1)/12.0
    #if len(vdate)>2:
    #    fdate+=int((vdate[2])-1)/12.0/31.0
    #return fdate < 2012.4759

def getopenscadversion(osfilename=None):
    import os,subprocess,time
    if not osfilename:
        import FreeCAD
        osfilename = FreeCAD.ParamGet(\
            "User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
            GetString('openscadexecutable')
    if osfilename and os.path.isfile(osfilename):
        p=subprocess.Popen([osfilename,'-v'],\
            stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True)
        p.wait()
        stdout=p.stdout.read().strip()
        stderr=p.stderr.read().strip()
        return (stdout or stderr)

def newtempfilename():
    import os,time
    formatstr='fc-%05d-%06d-%06d'
    count = 0
    while True:
        count+=1
        yield formatstr % (os.getpid(),int(time.time()*100) % 1000000,count)

tempfilenamegen=newtempfilename()

def callopenscad(inputfilename,outputfilename=None,outputext='csg',keepname=False):
    '''call the open scad binary
    returns the filename of the result (or None),
    please delete the file afterwards'''
    import FreeCAD,os,subprocess,tempfile,time
    def check_output2(*args,**kwargs):
        kwargs.update({'stdout':subprocess.PIPE,'stderr':subprocess.PIPE})
        p=subprocess.Popen(*args,**kwargs)
        stdoutd,stderrd = p.communicate()
        if p.returncode != 0:
            raise OpenSCADError('%s %s\n' % (stdoutd.strip(),stderr.strip()))
            #raise Exception,'stdout %s\n stderr%s' %(stdoutd,stderrd)
        if stderrd.strip():
            FreeCAD.Console.PrintWarning(stderrd+u'\n')
        if stdoutd.strip():
            FreeCAD.Console.PrintMessage(stdoutd+u'\n')
            return stdoutd

    osfilename = FreeCAD.ParamGet(\
        "User parameter:BaseApp/Preferences/Mod/OpenSCAD").\
        GetString('openscadexecutable')
    if osfilename and os.path.isfile(osfilename):
        if not outputfilename:
            dir1=tempfile.gettempdir()
            if keepname:
                outputfilename=os.path.join(dir1,'%s.%s' % (os.path.split(\
                    inputfilename)[1].rsplit('.',1)[0],outputext))
            else:
                outputfilename=os.path.join(dir1,'%s.%s' % \
                    (tempfilenamegen.next(),outputext))
        check_output2([osfilename,'-o',outputfilename, inputfilename])
        return outputfilename

def callopenscadstring(scadstr,outputext='csg'):
    '''create a tempfile and call the open scad binary
    returns the filename of the result (or None),
    please delete the file afterwards'''
    import os,tempfile,time
    dir1=tempfile.gettempdir()
    inputfilename=os.path.join(dir1,'%s.scad' % tempfilenamegen.next())
    inputfile = open(inputfilename,'w')
    inputfile.write(scadstr)
    inputfile.close()
    outputfilename = callopenscad(inputfilename,outputext=outputext,\
        keepname=True)
    os.unlink(inputfilename)
    return outputfilename

def reverseimporttypes():
    '''allows to search for supported filetypes by module'''

    def getsetfromdict(dict1,index):
{'fraction_non_alphanumeric': 0.1373050965790086, 'fraction_numerical': 0.018772787215887054, 'mean_word_length': 2.304793642655729, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 13, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 36, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1536710', 'n_tokens_mistral': 3809, 'n_tokens_neox': 3577, 'n_words': 869}