示例#1
0
class textApplication(object):
    def __init__(self):
        self.__command={}
        self.__applicationCommand={}
        # Application Command
        self.__applicationCommand['Open']=self.openFile
        self.__applicationCommand['Close']=self.closeFile
        self.__applicationCommand['New']=self.newDoc
        self.__applicationCommand['Documents']=self.showDocuments
        self.__applicationCommand['CreateStyle']=self.createStyle
        self.__applicationCommand['SetActive']=self.setActiveDoc
        self.__applicationCommand['GetActive']=self.getActiveDoc
        self.__applicationCommand['GetEnts']=self.getEnts
        self.__applicationCommand['Esc']=self.endApplication
        self.__applicationCommand['?']=self.printHelp
        self.__applicationCommand['Test']=self.featureTest
        self.__applicationCommand['ETest']=self.easyTest
        # Document Commandf
        self.__pyCadApplication=Application()
        for command in self.__pyCadApplication.getCommandList():
            self.__command[command]=self.performCommand

    def mainLoop(self):
        """
            mainLoop operation
        """
        while 1:
            imputstr=self.inputMsg("Insert a command (? for Help)")
            try:
                if imputstr in self.__command:
                    self.__command[imputstr](imputstr)
                elif imputstr in self.__applicationCommand:
                    self.__applicationCommand[imputstr]()
                else:
                    self.outputMsg("Wrong Command !!")
            except EntityMissing as err:
                self.outputMsg("Application Error %s "%str(err))
                
    def printHelp(self):            
        """
            print the command list
        """
        self.outputMsg("*****************************Drawing")
        for commandName in self.__command:
            self.outputMsg("Comand : %s "%str(commandName))
        self.outputMsg("**************************Application Command")
        for commandName in self.__applicationCommand:
            self.outputMsg("Comand : %s "%str(commandName))
    def getEnts(self):
        """
            get database entitys
        """
        try:
            type=self.inputMsg("Witch Type ?")
            if not type:
                type="ALL"
            startTime=time.clock()
            activeDoc=self.__pyCadApplication.ActiveDocument
            if activeDoc == None:
                self.outputMsg("No Object opened")
                return
                
            ents=activeDoc.getEntityFromType(type)
            endTime=time.clock()-startTime       
            self.printEntity(ents)
            self.outputMsg("Exec query get %s ent in %s s"%(str(len(ents)), str(endTime)))
            self.outputMsg("********************************")
        except:
            self.outputMsg("Unable To Perform the getEnts")   

        
    def printEntity(self, ents):
        """
            print a query result
        """
        i=0
        for e in ents:
            self.outputMsg("Entity Type %s id %s "%(str(e.eType),str(e.getId())))
            if i > 100:
                self.outputMsg("There are more then 100 entitys in the select so i stop printing")
                break
            i+=1
    def newDoc(self):
        """
            create a new document
        """
        try:
            self.__pyCadApplication.newDocument(None)
        except (IOError, EmptyFile):
            self.outputMsg("Unable To open the file %s"%str(filePath))
    
    def createStyle(self):        
        """
            create a new style object
        """
        styleName=self.inputMsg("Write style name")
        stl=Style(styleName)
        doc=self.__pyCadApplication.ActiveDocument
        doc.saveEntity(stl);
        
    def getActiveDoc(self):            
        """
            print the active document
        """ 
        try:
            doc=self.__pyCadApplication.ActiveDocument
            self.outputMsg("Active Document is %s"%str(doc.dbPath))
        except:
            self.outputMsg("Unable To Perform the getActiveDoc") 
   
    def setActiveDoc(self):
        """
            set the active docuement
        """
        try:
            lookIndex=self.inputMsg("Write the number of doc that you are looking for")
            i=0
            docs=self.__pyCadApplication.getDocuments()
            if len(docs)<int(lookIndex):
                self.outputMsg("No such a document")
                return
            for key in docs:
                if i == int(lookIndex):
                    self.__pyCadApplication.ActiveDocument=docs[key]
                    return
                i+=1
            else:
                self.outputMsg("Document not found") 
        except:
            self.outputMsg("Unable To Perform the setActiveDoc") 
            
    def showDocuments(self):
        """
            show The list of documents
        """
        try:
            self.outputMsg("Documents in the curret application")
            i=0
            for key in self.__pyCadApplication.getDocuments():
                self.outputMsg("%s File %s"%(str(i), str(key)))
                i+=1
            self.outputMsg("***********************************")
        except:
            self.outputMsg("Unable To Perform the GetDocuments")
    
    def closeFile(self):
        """
            close the active Document
        """
        try:
            acDoc=self.__pyCadApplication.getActiveDocuemnt()
            self.__pyCadApplication.closeDocument(acDoc.dbFile)
        except:
            self.outputMsg("Unable To close the active document")

    def openFile(self):
        """
            open a new document
        """
        try:
            filePath=self.inputMsg("File Path")
            self.__pyCadApplication.openDocument(filePath)
        except IOError:
            self.outputMsg("Unable To open the file %s"%str(filePath))

    def endApplication(self):
        """
            close the application
        """
        self.outputMsg("Bye")
        sys.exit(0)

    def performCommand(self,name):
        """
            Perform a Command
        """
        try:
            cmd_Key=str(name).upper()
            cObject=self.__pyCadApplication.getCommand(cmd_Key)
            for iv in cObject:
                exception,message=iv
                try:
                    raise exception(None)
                except ExcPoint:
                    cObject[iv]=self.imputPoint(message)                    
                except (ExcLenght, ExcAngle):
                    cObject[iv]=self.inputFloat(message)
                except (ExText):
                    cObject[iv]=self.inputMsg(message)
                except (ExEntity):
                    cObject[iv]=self.inputInt(message)
                except:
                    print("Bad error !!")
                    raise 
            else:
                cObject.applyCommand()
        except PyCadWrongCommand:
            self.outputMsg("Wrong Command")
            
    def featureTest(self):
        """
            this function make a basic test
        """
        self.outputMsg("Create a new document 1")
        doc1=self.__pyCadApplication.newDocument()
        self.outputMsg("Create a new document 2")
        doc2=self.__pyCadApplication.newDocument()
        self.outputMsg("Set Current p1")
        self.__pyCadApplication.ActiveDocument=doc1
        self.outputMsg("Create Point")
        self.performCommandRandomly("POINT")
        self.outputMsg("Create Segment")
        self.performCommandRandomly("SEGMENT")
        self.outputMsg("Create Arc")
        self.performCommandRandomly("ARC")
        self.__pyCadApplication.ActiveDocument=doc2
        self.outputMsg("Create Ellipse")
        self.performCommandRandomly("ELLIPSE")
        self.outputMsg("Create Polyline")
        self.performCommandRandomly("POLYLINE")
        self.outputMsg("Create ACLine")
        self.performCommandRandomly("ACLINE")
        
        self.outputMsg("Get Entitys for doc 1")
        self.__pyCadApplication.ActiveDocument=doc1
        activeDoc=self.__pyCadApplication.ActiveDocument
        ents=activeDoc.getEntityFromType("ALL")
        self.printEntity(ents)
        self.outputMsg("Get Entitys for doc 2")
        self.__pyCadApplication.ActiveDocument=doc2
        activeDoc=self.__pyCadApplication.ActiveDocument
        ents=activeDoc.getEntityFromType("ALL")
        self.printEntity(ents)
        # Working with styles
        self.outputMsg("Create NewStyle")
        stl=Style("NewStyle")
        self.outputMsg("Save in document")
        activeDoc.saveEntity(stl)
        activeDoc.setActiveStyle(name='NewStyle')
        self.outputMsg("Create Segment")
        self.performCommandRandomly("SEGMENT")
        self.outputMsg("Create Arc")
        self.performCommandRandomly("ARC")
        
        self.outputMsg("Create NewStyle1")
        stl1=Style("NewStyle1")
        self.__pyCadApplication.setApplicationStyle(stl1)
        stl11=self.__pyCadApplication.getApplicationStyle(name='NewStyle1')
        styleDic=stl11.getConstructionElements()
        styleDic[list(styleDic.keys())[0]].setStyleProp('entity_color',(255,215,000))
        self.__pyCadApplication.setApplicationStyle(stl11)
        activeDoc.saveEntity(stl11)
        self.outputMsg("Create Segment")
        self.performCommandRandomly("SEGMENT")
        self.outputMsg("Create Arc")
        self.performCommandRandomly("ARC")
        
        self.outputMsg("Create NewStyle2 ")
        stl1=Style("NewStyle2")
        stl12=activeDoc.saveEntity(stl1)
        styleDic=stl11.getConstructionElements()
        styleDic[list(styleDic.keys())[0]].setStyleProp('entity_color',(255,215,000))
        self.outputMsg("Update NewStyle2")
        activeDoc.saveEntity(stl12)
        self.outputMsg("Done")
        # Test  Geometrical chamfer ent
        self.GeotestChamfer()
        # Test Chamfer Command 
        self.testChamferCommand()
        
    def testGeoChamfer(self):    
        self.outputMsg("Test Chamfer")
        p1=Point(0.0, 0.0)
        p2=Point(10.0, 0.0)
        p3=Point(0.0, 10.0)
        s1=Segment(p1, p2)
        s2=Segment(p1, p3)
        cmf=Chamfer(s1, s2, 2.0, 2.0)
        cl=cmf.getLength()
        self.outputMsg("Chamfer Lengh %s"%str(cl))
        s1, s2, s3=cmf.getReletedComponent()
        if s3:
            for p in s3.getEndpoints():
                x, y=p.getCoords()
                self.outputMsg("P1 Cords %s,%s"%(str(x), str(y)))
        else:
            self.outputMsg("Chamfer segment in None")
    
    def testChamferCommand(self):
        """
            this function is usefoul for short test
            as soon it works copy the code into featureTest
        """
        newDoc=self.__pyCadApplication.newDocument()
        intPoint=Point(0.0, 0.0)
        
        s1=Segment(intPoint, Point(10.0, 0.0))
        s2=Segment(intPoint, Point(0.0, 10.0))
        
        ent1=newDoc.saveEntity(s1)
        ent2=newDoc.saveEntity(s2)
       
        cObject=self.__pyCadApplication.getCommand("CHAMFER")
        keys=list(cObject.keys())
        cObject[keys[0]]=ent1
        cObject[keys[1]]=ent2
        cObject[keys[2]]=2
        cObject[keys[3]]=2
        cObject[keys[4]]=None
        cObject[keys[5]]=None
        cObject.applyCommand()
    
    def easyTest(self):
        """
            this function is usefoul for short test
            as soon it works copy the code into featureTest
        """
        pass
        newDoc=self.__pyCadApplication.newDocument()
        intPoint=Point(2.0, 2.0)
        
        s1=Segment(intPoint, Point(10.0, 0.0))
        s2=Segment(intPoint, Point(0.0, 10.0))
        
        ent1=newDoc.saveEntity(s1)
        ent2=newDoc.saveEntity(s2)
       
        cObject=self.__pyCadApplication.getCommand("CHAMFER")
        keys=list(cObject.keys())
        cObject[keys[0]]=ent1
        cObject[keys[1]]=ent2
        cObject[keys[2]]=2
        cObject[keys[3]]=2
        cObject[keys[4]]=None
        cObject[keys[5]]=None
        cObject.applyCommand()
        
    def performCommandRandomly(self, commandName, andLoop=10):
        """
            set some random Value at the command imput
        """
        self.outputMsg("Start Command %s"%str(commandName))
        i=0
        cObject=self.__pyCadApplication.getCommand(commandName)
        for iv in cObject:
            exception,message=iv
            try:
                raise exception(None)
            except ExcPoint:
                self.outputMsg("Add Point")
                if i>=andLoop:
                    cObject[iv]=None
                else:
                    cObject[iv]=self.getRandomPoint()
            except (ExcLenght, ExcAngle):
                self.outputMsg("Add Lengh/Angle")
                cObject[iv]=100
            except:
                self.outputMsg("Bad error !!")
                raise 
            i+=1
        else:
            self.outputMsg("Apply Command")
            cObject.applyCommand()
            
            
    def getRandomPoint(self):
        """
            get e random point
        """
        x=random()*1000
        y=random()*1000
        #print("x is ", x, "y is ", y)
        return Point(x, y)

    def inputInt(self, msg):   
        """
            return an int from user
        """        
        value=self.inputMsg(msg)
        if value:
            return int(value)
        return None
        
    def inputFloat(self, msg):
        """
            return a float number
        """
        value=self.inputMsg(msg)
        if value:
            return float(value)
        return None
        
    def imputPoint(self, msg):
        """
            ask at the user to imput a point 
        """
        msg=msg + " x,y "
        value=self.inputMsg(msg)
        if value:
            coords=value.split(',')
            x=float(coords[0])
            y=float(coords[1])
            return Point(x, y)
        return None
        
    def outputMsg(self,msg):
        """
            print an output message
        """
        print("""<PythonCad> %s"""%(str(msg)))
        
    def inputMsg(self,msg):
        """
            print and ask for a value
        """
        msg="""<PythonCad> %s >>>"""%(str(msg))
        return input(msg)