def importDB(fn=None): """Import a _post.py database and select it as the current.""" if fn is None: types = utils.fileDescription('postproc') fn = askFilename(pf.cfg['workdir'],types) if fn: chdir(fn) size = os.stat(fn).st_size if size > 1000000 and ask(""" BEWARE!!! The size of this file is very large: %s bytes It is unlikely that I will be able to process this file. I strongly recommend you to cancel the operation now. """ % size,["Continue","Cancel"]) != "Continue": return # import the results DB play(fn) ### check whether the import succeeded name = FeResult._name_ db = pf.PF[name] if not isinstance(db,FeResult): warning("!Something went wrong during the import of the database %s" % fn) return ### ok: select the DB selection.set([name]) selectDB(db)
def showImage(): """Display an image file.""" global viewer fn = draw.askFilename(filter=utils.fileDescription('img')) if fn: viewer = ImageViewer(pf.app, fn) viewer.show()
def openScript(fn=None,exist=True,create=False): """Open a pyFormex script and set it as the current script. If no filename is specified, a file selection dialog is started to select an existing script, or allow to create a new file if exist is False. If the file exists and is a pyFormex script, it is set ready to execute. If create is True, a default pyFormex script template will be written to the file, overwriting the contents if the file existed. Then, the script is loaded into the editor. We encourage the use of createScript() to create new scripts and leave openScript() to open existing scripts. """ if fn is None: cur = GD.cfg.get('curfile',GD.cfg.get('workdir','.')) typ = utils.fileDescription('pyformex') fn = widgets.FileSelection(cur,typ,exist=exist).getFilename() if fn: if create: if not exist and os.path.exists(fn) and not draw.ack("The file %s already exists.\n Are you sure you want to overwrite it?" % fn): return None template = GD.cfg['scripttemplate'] if (os.path.exists(template)): shutil.copyfile(template,fn) GD.cfg['workdir'] = os.path.dirname(fn) GD.GUI.setcurfile(fn) GD.GUI.history.add(fn) if create: editScript(fn) return fn
def readSelection(select=True,draw=True,multi=True): """Read a Formex (or list) from asked file name(s). If select is True (default), this becomes the current selection. If select and draw are True (default), the selection is drawn. """ types = utils.fileDescription(['pgf','all']) fn = askFilename(GD.cfg['workdir'],types,multi=multi) if fn: if not multi: fn = [ fn ] chdir(fn[0]) res = ODict() GD.GUI.setBusy() for f in fn: res.update(readGeomFile(f)) GD.GUI.setBusy(False) export(res) if select: oknames = [ k for k in res if isinstance(res[k],Formex) ] selection.set(oknames) GD.message("Set Formex selection to %s" % oknames) if draw: selection.draw() return fn
def importGeometry(select=True,draw=True,ftype=None): """Read geometry from file. If select is True (default), the imported geometry becomes the current selection. If select and draw are True (default), the selection is drawn. """ if ftype is None: ftype = ['pgf','pyf','surface','off','stl','gts','smesh','neu','all'] else: ftype = [ftype] types = utils.fileDescription(ftype) cur = pf.cfg['workdir'] fn = askFilename(cur=cur,filter=types) if fn: message("Reading geometry file %s" % fn) res = readGeometry(fn) export(res) #selection.readFromFile(fn) print res.keys() if select: selection.set(res.keys()) if draw: selection.draw() zoomAll()
def showImage(): """Display an image file.""" global viewer fn = draw.askFilename(filter=utils.fileDescription('img')) if fn: viewer = ImageViewer(pf.app,fn) viewer.show()
def showImage(): """Display an image file.""" global viewer fn = draw.askFilename(filter=utils.fileDescription('img'),multi=False,exist=True) if fn: viewer = ImageViewer(GD.app,fn) viewer.show()
def writeGeometry(): """Write geometry to file.""" drawable.ask() if drawable.check(): filter = utils.fileDescription(['pgf','all']) cur = GD.cfg['workdir'] fn = askNewFilename(cur=cur,filter=filter) if fn: drawable.writeToFile(fn)
def convertGeometryFile(): """Convert pyFormex geometry file to latest format.""" filter = utils.fileDescription(['pgf','all']) cur = pf.cfg['workdir'] fn = askFilename(cur=cur,filter=filter) if fn: from geomfile import GeometryFile message("Converting geometry file %s to version %s" % (fn,GeometryFile._version_)) GeometryFile(fn).rewrite()
def convertGeometryFile(): """Convert pyFormex geometry file to latest format.""" filter = utils.fileDescription(['pgf', 'all']) cur = pf.cfg['workdir'] fn = askFilename(cur=cur, filter=filter) if fn: from geomfile import GeometryFile message("Converting geometry file %s to version %s" % (fn, GeometryFile._version_)) GeometryFile(fn).rewrite()
def saveIcon(): """Save an image as icon. This will show the Save Image dialog, with the multisave mode off and asking for an icon file name. Then save the current rendering to that file. """ ## We should create a specialized input dialog, asking also for the size fn = draw.askFilename(filter=utils.fileDescription('icon')) if fn: image.saveIcon(fn,size=32)
def saveIcon(): """Save an image as icon. This will show the Save Image dialog, with the multisave mode off and asking for an icon file name. Then save the current rendering to that file. """ ## We should create a specialized input dialog, asking also for the size fn = draw.askNewFilename(filter=utils.fileDescription('icon')) if fn: image.saveIcon(fn, size=32)
def readGeometry(): """Read geometry from file.""" filter = utils.fileDescription(['pgf','all']) cur = GD.cfg['workdir'] fn = askFilename(cur=cur,filter=filter) if fn: drawable.readFromFile(fn) drawable.draw() zoomAll() print drawable.names
def importFlavia(fn=None): """Import a flavia file and select it as the current results. Flavia files are the postprocessing format used by GiD pre- and postprocessor, and can also be written by the FE program calix. There usually are two files named 'BASE.flavia.msh' and 'BASE.flavia.res' which hold the FE mesh and results, respectively. This functions asks the user to select a flavia file (either mesh or results), will then read both the mesh and corrseponding results files, and store the results in a FeResult instance, which will be set as the current results database for the postprocessing menu. """ from plugins.flavia import readFlavia if fn is None: types = [utils.fileDescription('flavia'), utils.fileDescription('all')] fn = askFilename(pf.cfg['workdir'], types) if fn: chdir(fn) if fn.endswith('.msh'): meshfile = fn resfile = utils.changeExt(fn, 'res') else: resfile = fn meshfile = utils.changeExt(fn, 'msh') db = readFlavia(meshfile, resfile) if not isinstance(db, FeResult): warning( "!Something went wrong during the import of the flavia database %s" % fn) return ### ok: export and select the DB name = os.path.splitext(os.path.basename(fn))[0].replace('.flavia', '') export({name: db}) db.printSteps() print(db.R) print(db.datasize) selection.set([name]) selectDB(db)
def openProject(fn=None,exist=False,access=['wr','rw','w','r'],default=None): """Open a (new or old) Project file. A dialog is presented to ask the user for a Project file name and the access modalities. The parameters help in setting sensible defaults for the user and in delimiting his options. Depending on he results of the dialog, either a new project is created or an old one is opened, or nothing is done. If a project is opened, it is returned, else the return value is None. Parameters: - `fn`: filename: if specified, the Project file dialog will start with the specified file, otherwise it will start in the current directory. - `exist`: boolean: if False (default), the user can create new project files as well as open existing ones. Use exist=True or :func:`openExistingProject` to only accept existing project files. - `access`: a list of :class:`Project` access modes to be presented to the user. - `default`: the access mode that is presented as default to the user. If not specified, the first option of `access` will be the default. """ if type(access) == str: access = [access] cur = fn if fn else '.' typ = utils.fileDescription(['pyf','all']) res = widgets.ProjectSelection(cur,typ,exist=exist,access=access,default=default,convert=True).getResult() if not res: return fn = res.fn if not fn.endswith('.pyf'): fn += '.pyf' access = res.acc compression = res.cpr convert = res.cvt signature = pf.fullVersion() # OK, we have all data, now create/open the project pf.message("Opening project %s" % fn) pf.GUI.setBusy() # loading may take a while try: proj = project.Project(fn,access=access,convert=convert,signature=signature,compression=compression) if proj.signature != signature: pf.warning("The project was written with %s, while you are now running %s. If the latter is the newer one, this should probably not cause any problems. Saving is always done in the current format of the running version. Save your project and this message will be avoided on the next reopening." % (proj.signature,signature)) except: proj = None raise finally: pf.GUI.setBusy(False) proj.hits = 0 pf.debug("START COUNTING HITS",pf.DEBUG.PROJECT) return proj
def writeGeometry(): """Write geometry to file.""" drawable.ask() if drawable.check(): filter = utils.fileDescription(['pgf','all']) cur = pf.cfg['workdir'] fn = askNewFilename(cur=cur,filter=filter) if fn: if not fn.endswith('.pgf'): fn.append('.pgf') message("Writing geometry file %s" % fn) drawable.writeToFile(fn)
def importFlavia(fn=None): """Import a flavia file and select it as the current results. Flavia files are the postprocessing format used by GiD pre- and postprocessor, and can also be written by the FE program calix. There usually are two files named 'BASE.flavia.msh' and 'BASE.flavia.res' which hold the FE mesh and results, respectively. This functions asks the user to select a flavia file (either mesh or results), will then read both the mesh and corrseponding results files, and store the results in a FeResult instance, which will be set as the current results database for the postprocessing menu. """ from plugins.flavia import readFlavia if fn is None: types = [ utils.fileDescription('flavia'), utils.fileDescription('all') ] fn = askFilename(pf.cfg['workdir'],types) if fn: chdir(fn) if fn.endswith('.msh'): meshfile = fn resfile = utils.changeExt(fn,'res') else: resfile = fn meshfile = utils.changeExt(fn,'msh') db = readFlavia(meshfile,resfile) if not isinstance(db,FeResult): warning("!Something went wrong during the import of the flavia database %s" % fn) return ### ok: export and select the DB name = os.path.splitext(os.path.basename(fn))[0].replace('.flavia','') export({name:db}) db.printSteps() print db.R print db.datasize selection.set([name]) selectDB(db)
def exportGeometry(types=['pgf','all'],shortlines=False): """Write geometry to file.""" drawable.ask() if not drawable.check(): return filter = utils.fileDescription(types) cur = pf.cfg['workdir'] fn = askNewFilename(cur=cur,filter=filter) if fn: message("Writing geometry file %s" % fn) res = writeGeometry(drawable.odict(),fn,shortlines=shortlines) pf.message("Contents: %s" % res)
def writeSelection(): """Writes the currently selected Formices to a Geometry File.""" F = selection.check() if F: types = utils.fileDescription(['pgf','all']) name = selection.names[0] fn = askNewFilename(os.path.join(GD.cfg['workdir'],"%s.pgf" % name), filter=types) if fn: if not (fn.endswith('.pgf') or fn.endswith('.formex')): fn += '.pgf' GD.message("Creating pyFormex Geometry File '%s'" % fn) chdir(fn) selection.writeToFile(fn) GD.message("Contents: %s" % selection.names)
def exportGeometry(types=['pgf', 'all'], sep=' ', shortlines=False): """Write geometry to file.""" selection.ask() if not selection.check(): return filter = utils.fileDescription(types) cur = pf.cfg['workdir'] fn = askNewFilename(cur=cur, filter=filter) if fn: message("Writing geometry file %s" % fn) res = writeGeometry(selection.odict(), fn, sep=sep, shortlines=shortlines) pf.message("Contents: %s" % res)
def exportPGF(): """Export the current scene to PGF""" from plugins.webgl import WebGL types = utils.fileDescription(['pgf','all']) fn = draw.askNewFilename(pf.cfg['workdir'],types) if fn: pf.GUI.setBusy() pf.message("Exporting current scene to %s" % fn) fn = os.path.basename(fn) if not fn.endswith('.pgf'): fn += '.pgf' name = utils.projectName(fn) W = WebGL(name) W.addScene() res = W.exportPGF(fn,sep='') pf.message("Contents: %s" % res) pf.GUI.setBusy(False)
def exportPGF(): """Export the current scene to PGF""" from plugins.webgl import WebGL types = utils.fileDescription(['pgf', 'all']) fn = draw.askNewFilename(pf.cfg['workdir'], types) if fn: pf.GUI.setBusy() pf.message("Exporting current scene to %s" % fn) fn = os.path.basename(fn) if not fn.endswith('.pgf'): fn += '.pgf' name = utils.projectName(fn) W = WebGL(name) W.addScene() res = W.exportPGF(fn, sep='') pf.message("Contents: %s" % res) pf.GUI.setBusy(False)
def exportWebGL(): """Export the current scene to WebGL""" from plugins.webgl import WebGL types = [utils.fileDescription('html')] fn = draw.askNewFilename(pf.cfg['workdir'], types) if fn: pf.message("Exporting current scene to %s" % fn) pf.GUI.setBusy() fn = os.path.basename(fn) name = utils.projectName(fn) W = WebGL(name) W.addScene() fn = W.export(title="%s WebGL model" % name, createdby=50) pf.GUI.setBusy(False) if draw.ack("Show the scene in your browser?"): fn = os.path.join(os.getcwd(), fn) print(fn) from gui.helpMenu import help help('file:%s' % fn)
def importDB(self,fn=None): if fn is None: types = utils.fileDescription('postproc') fn = askFilename(GD.cfg['workdir'],types,exist=True) if fn: chdir(fn) ### ### Warning for obsolete feature ### Will be removed in version 0.8 if fn.endswith('_post.py'): ans = ask("The '_post.py' extension for postprocessing databases is obsolete and should be avoided. Use the '.post' extension instead.\n\nDo you want to rename the database now?",['Keep','Rename','Cancel']) if ans == 'Cancel': return elif ans == 'Rename': newfn = fn.replace('_post.py','.post') while os.path.exists(newfn): newfn = newfn.replace('.post','_1.post') os.rename(fn,newfn) fn = newfn size = os.stat(fn).st_size if size > 1000000 and ask(""" BEWARE!!! The size of this file is very large: %s bytes It is unlikely that I will be able to process this file. I strongly recommend you to cancel the operation now. """ % size,["Continue","Cancel"]) != "Continue": return project = os.path.basename(os.path.splitext(fn)[0]) #### Currenty, the postabq always uses the global 'DB' ##DB = FeResult() export({'DB':self.DB}) play(fn) #### We export it under the project name export({project:GD.PF['DB']}) #### and delete the 'DB' name del GD.PF['DB'] ### now select the DB self.setDB(GD.PF[project],project) GD.message(self.DB.about['heading']) self.DB.printSteps()
def exportWebGL(): """Export the current scene to WebGL""" from plugins.webgl import WebGL types = [ utils.fileDescription('html') ] fn = draw.askNewFilename(pf.cfg['workdir'],types) if fn: pf.message("Exporting current scene to %s" % fn) pf.GUI.setBusy() fn = os.path.basename(fn) name = utils.projectName(fn) W = WebGL(name) W.addScene() fn = W.export(title="%s WebGL model"%name,createdby=50) pf.GUI.setBusy(False) if draw.ack("Show the scene in your browser?"): fn = os.path.join(os.getcwd(),fn) print(fn) from gui.helpMenu import help help('file:%s' % fn)
def importCalculix(fn=None): """Import a CalculiX results file and select it as the current results. CalculiX result files are the .dat files resulting from a run of the ccx program with an .inp file as input. This function will need both files and supposes that the names are the same except for the extension. If no file name is specified, the user is asked to select one (either the .inp or .dat file), will then read both the mesh and corresponding results files, and store the results in a FeResult instance, which will be set as the current results database for the postprocessing menu. """ from plugins import ccxdat from fileread import readInpFile #from plugins.fe import Model if fn is None: types = [utils.fileDescription('ccx')] fn = askFilename(pf.cfg['workdir'], types) if fn: chdir(fn) if fn.endswith('.inp'): meshfile = fn resfile = utils.changeExt(fn, 'dat') else: resfile = fn meshfile = utils.changeExt(fn, 'inp') parts = readInpFile(meshfile) print(type(parts)) print(parts.keys()) meshes = parts.values()[0] print(type(meshes)) #fem = Model(meshes=meshes,fuse=False) DB = ccxdat.createResultDB(meshes) ngp = 8 ccxdat.readResults(resfile, DB, DB.nnodes, DB.nelems, ngp) DB.printSteps() name = 'FeResult-%s' % meshfile[:-4] export({name: DB}) selection.set([name]) selectDB(DB)
def importCalculix(fn=None): """Import a CalculiX results file and select it as the current results. CalculiX result files are the .dat files resulting from a run of the ccx program with an .inp file as input. This function will need both files and supposes that the names are the same except for the extension. If no file name is specified, the user is asked to select one (either the .inp or .dat file), will then read both the mesh and corresponding results files, and store the results in a FeResult instance, which will be set as the current results database for the postprocessing menu. """ from plugins import ccxdat from fileread import readInpFile #from plugins.fe import Model if fn is None: types = [ utils.fileDescription('ccx') ] fn = askFilename(pf.cfg['workdir'],types) if fn: chdir(fn) if fn.endswith('.inp'): meshfile = fn resfile = utils.changeExt(fn,'dat') else: resfile = fn meshfile = utils.changeExt(fn,'inp') parts = readInpFile(meshfile) print(type(parts)) print(parts.keys()) meshes = parts.values()[0] print(type(meshes)) #fem = Model(meshes=meshes,fuse=False) DB = ccxdat.createResultDB(meshes) ngp = 8 ccxdat.readResults(resfile,DB,DB.nnodes,DB.nelems,ngp) DB.printSteps() name = 'FeResult-%s' % meshfile[:-4] export({name:DB}) selection.set([name]) selectDB(DB)
def importGeometry(select=True, draw=True, ftype=None): """Read geometry from file. If select is True (default), the imported geometry becomes the current selection. If select and draw are True (default), the selection is drawn. """ if ftype is None: ftype = [ 'pgf', 'pyf', 'surface', 'off', 'stl', 'gts', 'smesh', 'neu', 'inp', 'all' ] elif type(ftype) is list: pass else: ftype = [ftype] types = utils.fileDescription(ftype) cur = pf.cfg['workdir'] fn = askFilename(cur=cur, filter=types) if fn: message("Reading geometry file %s" % fn) res = readGeometry(fn) export(res) #selection.readFromFile(fn) print("Items read: %s" % ["%s(%s)" % (k, res[k].__class__.__name__) for k in res]) if select: print("SET SELECTION") selection.set(res.keys()) #print(selection.names) surface_menu.selection.set([ n for n in selection.names if isinstance(named(n), TriSurface) ]) #print(surface_menu.selection.names) if draw: print("DRAW SELECTION") selection.draw() zoomAll()
def openScript(fn=None, exist=True, create=False): """Open a pyFormex script and set it as the current script. If no filename is specified, a file selection dialog is started to select an existing script, or allow to create a new file if exist is False. If the file exists and is a pyFormex script, it is set ready to execute. If create is True, a default pyFormex script template will be written to the file, overwriting the contents if the file existed. Then, the script is loaded into the editor. We encourage the use of createScript() to create new scripts and leave openScript() to open existing scripts. """ if fn is None: cur = pf.cfg['curfile'] if cur is None: cur = pf.cfg['workdir'] if cur is None: cur = '.' typ = utils.fileDescription('pyformex') fn = widgets.FileSelection(cur, typ, exist=exist).getFilename() if fn: if create: if not exist and os.path.exists(fn) and not draw.ack( "The file %s already exists.\n Are you sure you want to overwrite it?" % fn): return None template = pf.cfg['scripttemplate'] if (os.path.exists(template)): shutil.copyfile(template, fn) updateSettings({'workdir': os.path.dirname(fn)}, save=True) pf.GUI.setcurfile(fn) pf.GUI.scripthistory.add(fn) if create: draw.editFile(fn) return fn
def importDB(fn=None): """Import a _post.py database and select it as the current.""" if fn is None: types = utils.fileDescription('postproc') fn = askFilename(pf.cfg['workdir'], types) if fn: chdir(fn) sizeM = round(os.stat(fn).st_size * 1.e-6) if sizeM > 10.0 and ask( """ BEWARE!!! The size of this file is very large: %.1fMB. It is unlikely that I will be able to process this file. I strongly recommend you to cancel the operation now. """ % sizeM, ["Continue", "Cancel"]) != "Continue": return # import the results DB pf.GUI.setBusy(True) runScript(fn) pf.GUI.setBusy(False) ### check whether the import succeeded name = FeResult._name_ db = pf.PF[name] if not isinstance(db, FeResult): warning( "!Something went wrong during the import of the database %s" % fn) return ### ok: select the DB selection.set([name]) selectDB(db)
def openProject(fn=None, exist=False, access=['wr', 'rw', 'w', 'r'], default=None): """Open a (new or old) Project file. A dialog is presented to ask the user for a Project file name and the access modalities. The parameters help in setting sensible defaults for the user and in delimiting his options. Depending on he results of the dialog, either a new project is created or an old one is opened, or nothing is done. If a project is opened, it is returned, else the return value is None. Parameters: - `fn`: filename: if specified, the Project file dialog will start with the specified file, otherwise it will start in the current directory. - `exist`: boolean: if False (default), the user can create new project files as well as open existing ones. Use exist=True or :func:`openExistingProject` to only accept existing project files. - `access`: a list of :class:`Project` access modes to be presented to the user. - `default`: the access mode that is presented as default to the user. If not specified, the first option of `access` will be the default. """ if type(access) == str: access = [access] cur = fn if fn else '.' typ = utils.fileDescription(['pyf', 'all']) res = widgets.ProjectSelection(cur, typ, exist=exist, access=access, default=default, convert=True).getResult() if not res: return fn = res.fn if not fn.endswith('.pyf'): fn += '.pyf' access = res.acc compression = res.cpr convert = res.cvt signature = pf.fullVersion() # OK, we have all data, now create/open the project pf.message("Opening project %s" % fn) pf.GUI.setBusy() # loading may take a while try: proj = project.Project(fn, access=access, convert=convert, signature=signature, compression=compression) if proj.signature != signature: pf.warning( "The project was written with %s, while you are now running %s. If the latter is the newer one, this should probably not cause any problems. Saving is always done in the current format of the running version. Save your project and this message will be avoided on the next reopening." % (proj.signature, signature)) except: proj = None raise finally: pf.GUI.setBusy(False) proj.hits = 0 pf.debug("START COUNTING HITS", pf.DEBUG.PROJECT) return proj
def createProject(create=True,compression=0,addGlobals=None): """Open a file selection dialog and let the user select a project. The default will let the user create new project files as well as open existing ones. Use create=False or the convenience function openProject to only accept existing project files. If a compression level (1..9) is given, the contents will be compressed, resulting in much smaller project files at the cost of Only one pyFormex project can be open at any time. The open project owns all the global data created and exported by any script. If addGlobals is None, the user is asked whether the current globals should be added to the project. Set True or False to force or reject the adding without asking. """ global the_project # ask filename from user if the_project is None: cur = GD.cfg.get('workdir','.') else: options = ['Cancel','Close without saving','Save and Close'] ans = draw.ask("Another project is still open. Shall I close it first?", options) if ans == 'Cancel': return if ans == options[2]: the_project.save() cur = the_project.filename typ = utils.fileDescription(['pyf','all']) res = widgets.ProjectSelection(cur,typ,exist=not create).getResult() if res is None: # user canceled return fn = res.fn if not fn.endswith('.pyf'): fn += '.pyf' legacy = res.leg ignoresig = res.sig compression = res.cpr #print(fn,legacy,compression) if create and os.path.exists(fn): res = draw.ask("The project file '%s' already exists\nShall I delete the contents or add to it?" % fn,['Delete','Add','Cancel']) if res == 'Cancel': return if res == 'Add': create = False GD.message("Opening project %s" % fn) if GD.PF: GD.message("Exported symbols: %s" % GD.PF.keys()) if addGlobals is None: res = draw.ask("pyFormex already contains exported symbols.\nShall I delete them or add them to your project?",['Delete','Add','Cancel']) if res == 'Cancel': # ESCAPE FROM CREATING THE PROJECT return addGlobals = res == 'Add' # OK, we have all data, now create/open the project GD.cfg['workdir'] = os.path.dirname(fn) sig = GD.Version[:GD.Version.rfind('-')] if ignoresig: sig = '' # Loading the project make take a long while; attent user GD.GUI.setBusy() try: the_project = project.Project(fn,create=create,signature=sig,compression=compression,legacy=legacy) if GD.PF and addGlobals: the_project.update(GD.PF) finally: GD.GUI.setBusy(False) GD.PF = the_project GD.GUI.setcurproj(fn) GD.message("Project contents: %s" % the_project.keys()) if hasattr(the_project,'autofile') and draw.ack("The project has an autofile attribute: %s\nShall I execute this script?" % the_project.autofile): processArgs([the_project.autofile])
def create_menu(): """Create the plugin menu.""" from dxf_menu import importDxf _init_() MenuData = [ ( "&Import ", [ (utils.fileDescription('pgf'), importPgf), (utils.fileDescription('surface'), importSurface), (utils.fileDescription('tetgen'), importTetgen), ("Abaqus/Calculix FE model (*.inp)", importInp), ("All known geometry formats", importAny), ("Abaqus .inp", [ ("&Convert Abaqus .inp file", readInp), ("&Import Converted Abaqus Model", importModel), ]), # ("AutoCAD .dxf",[ # ("&Import .dxf or .dxftext",importDxf), # ("&Load DXF plugin menu",loadDxfMenu), # ]), ('&Upgrade pyFormex Geometry File', convertGeometryFile, dict( tooltip= "Convert a pyFormex Geometry File (.pgf) to the latest format, overwriting the file." )), ]), ("&Export ", [ (utils.fileDescription('pgf'), exportPgf), ("pyFormex Geometry File (binary)", exportPgfBinary), ("pyFormex Geometry File with short lines", exportPgfShortlines), ("Object File Format (.off)", exportOff), ]), ("&Select ", [ ('Any', set_selection), ('Formex', set_selection, { 'data': 'formex' }), ('Mesh', set_selection, { 'data': 'mesh' }), ('TriSurface', set_selection, { 'data': 'surface' }), ('PolyLine', set_selection, { 'data': 'polyline' }), ('Curve', set_selection, { 'data': 'curve' }), ('NurbsCurve', set_selection, { 'data': 'nurbs' }), ]), ("&Draw Selection", selection.draw), ("&Forget Selection", selection.forget), ("---", None), ("Print &Information ", [ ('&Bounding Box', selection.printbbox), ('&Type and Size', printDataSize), ]), ("Set &Attributes ", setAttributes), ("&Annotations ", [ ("&Names", selection.toggleNames, dict(checkable=True)), ("&Elem Numbers", selection.toggleNumbers, dict(checkable=True)), ("&Node Numbers", selection.toggleNodeNumbers, dict(checkable=True, checked=selection.hasNodeNumbers())), ("&Free Edges", selection.toggleFreeEdges, dict(checkable=True, checked=selection.hasFreeEdges())), ("&Node Marks", selection.toggleNodes, dict(checkable=True, checked=selection.hasNodeMarks())), ('&Toggle Bbox', selection.toggleBbox, dict(checkable=True)), ('&Toggle Shrink Mode', shrink, dict(checkable=True)), ("&Toggle Numbers On Top", toggleNumbersOntop), ]), ("---", None), ( "&Convert", [ ("To &Formex", toFormex), ("To &Mesh", toMesh), ("To &TriSurface", toSurface), ## ("To &PolyLine",toPolyLine), ## ("To &BezierSpline",toBezierSpline), ## ("To &NurbsCurve",toNurbsCurve), ]), ("&Property Numbers", [ ("&Set", selection.setProp), ("&Delete", selection.delProp), ("&Split", splitProp), ]), ("&Create Object", [ ('&Grid', createGrid), ('&Rectangle', createRectangle), ('&Cylinder, Cone, Truncated Cone', createCylinder), ('&Circle, Sector, Cone', createCone), ('&Sphere', createSphere), ]), ## ("&Shrink",shrink), ## ("&Bbox", ## [('&Show Bbox Planes',showBbox), ## ('&Remove Bbox Planes',removeBbox), ## ]), ## ("&Transform", ## [("&Scale Selection",scaleSelection), ## ("&Scale non-uniformly",scale3Selection), ## ("&Translate",translateSelection), ## ("&Center",centerSelection), ## ("&Rotate",rotateSelection), ## ("&Rotate Around",rotateAround), ## ("&Roll Axes",rollAxes), ## ]), ## ("&Clip/Cut", ## [("&Clip",clipSelection), ## ("&Cut With Plane",cutSelection), ## ]), ## ("&Undo Last Changes",selection.undoChanges), ("---", None), ("Show &Principal Axes", showPrincipal), ("Rotate to &Principal Axes", rotatePrincipal), ("Transform to &Principal Axes", transformPrincipal), ## ("---",None), ## ("&Concatenate Selection",concatenateSelection), ## ("&Partition Selection",partitionSelection), ## ("&Create Parts",createParts), ## ("&Sectionize Selection",sectionizeSelection), ## ("---",None), ## ("&Fly",fly), ("Mesh", [ ("&Reverse mesh elements", reverseMesh), ("&Convert element type", convertMesh), ("&Subdivide", subdivideMesh), ("&Compact", compactMesh), ("&Fuse nodes", fuseMesh), ("&Remove degenerate", removeDegenerate), ("&Renumber nodes", [ ("In element order", renumberMesh), ("In random order", renumberMeshRandom), ("In frontal order", renumberMeshFront), ]), ("&Get border mesh", getBorderMesh), ("&Peel off border", peelOffMesh), ]), ("---", None), ("&Reload menu", reload_menu), ("&Close", close_menu), ] M = menu.Menu(_menu, items=MenuData, parent=pf.GUI.menu, before='help') ## if not utils.hasExternal('dxfparser'): ## I = M.item("&Import ").item("AutoCAD .dxf") ## I.setEnabled(False) return M
def createProject(create=True,compression=0,addGlobals=None,makeDefault=True): """Open a file selection dialog and let the user select a project. The default will let the user create new project files as well as open existing ones. Use create=False or the convenience function openProject to only accept existing project files. If a compression level (1..9) is given, the contents will be compressed, resulting in much smaller project files at the cost of Only one pyFormex project can be open at any time. The open project owns all the global data created and exported by any script. If makeDefault is True, an already open project will be closed and the opened project becomes the current project. If makeDefault is False, the project data are imported into GD.PF and the current project does not change. This means that if a project was open, the imported data will be added to it. If addGlobals is None, the user is asked whether the current globals should be added to the project. Set True or False to force or reject the adding without asking. """ global the_project # ask filename from user if the_project is None: cur = GD.cfg.get('workdir','.') else: if makeDefault: options = ['Cancel','Close without saving','Save and Close'] ans = draw.ask("Another project is still open. Shall I close it first?", options) if ans == 'Cancel': return if ans == options[2]: the_project.save() cur = the_project.filename typ = utils.fileDescription(['pyf','all']) res = widgets.ProjectSelection(cur,typ,exist=not create).getResult() if res is None: # user canceled return fn = res.fn if not fn.endswith('.pyf'): fn += '.pyf' legacy = res.leg ignoresig = res.sig compression = res.cpr #print(fn,legacy,compression) if create and os.path.exists(fn): res = draw.ask("The project file '%s' already exists\nShall I delete the contents or add to it?" % fn,['Delete','Add','Cancel']) if res == 'Cancel': return if res == 'Add': create = False GD.message("Opening project %s" % fn) if GD.PF: GD.message("Exported symbols: %s" % GD.PF.keys()) if addGlobals is None: res = draw.ask("pyFormex already contains exported symbols.\nShall I delete them or add them to your project?",['Delete','Add','Cancel']) if res == 'Cancel': # ESCAPE FROM CREATING THE PROJECT return addGlobals = res == 'Add' # OK, we have all data, now create/open the project updateSettings({'workdir':os.path.dirname(fn)},save=True) sig = GD.Version[:GD.Version.rfind('-')] if ignoresig: sig = '' proj = _open_project(fn,create,sig,compression,legacy) GD.message("Project contents: %s" % proj.keys()) if hasattr(proj,'_autoscript_'): _ignore = "Ignore it!" _show = "Show it" _edit = "Load it in the editor" _exec = "Execute it" res = draw.ask("There is an autoscript stored inside the project.\nIf you received this project file from an untrusted source, you should probably not execute it.",[_ignore,_show,_edit,_exec]) if res == _show: res = draw.showText(proj._autoscript_)#,actions=[_ignore,_edit,_show]) return if res == _exec: draw.playScript(proj._autoscript_) elif res == _edit: fn = "_autoscript_.py" draw.checkWorkdir() f = file(fn,'w') f.write(proj._autoscript_) f.close() openScript(fn) editScript(fn) if hasattr(proj,'autofile') and draw.ack("The project has an autofile attribute: %s\nShall I execute this script?" % proj.autofile): processArgs([proj.autofile]) if makeDefault: the_project = proj if GD.PF and addGlobals: the_project.update(GD.PF) GD.PF = the_project GD.GUI.setcurproj(fn) else: # Just import the data into current project GD.PF.update(proj) GD.message("Exported symbols: %s" % GD.PF.keys())