Python FreeCADGui.runCommand() Examples

The following are 17 code examples of FreeCADGui.runCommand(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module FreeCADGui , or try the search function .
Example #1
Source File: gui.py    From FreeCAD_assembly3 with GNU General Public License v3.0 6 votes vote down vote up
def Activated(cls):
        moveInfo = AsmCmdMove._moveInfo
        if not moveInfo:
            return
        info = moveInfo.ElementInfo
        if info.Subname:
            subs = moveInfo.SelSubname[:-len(info.Subname)]
        else:
            subs = moveInfo.SelSubname
        subs = subs.split('.')
        if isinstance(info.Part,tuple):
            part = info.Part[0]
            vis = part.isElementVisible(str(info.Part[1]))
            part.setElementVisible(str(info.Part[1]),not vis)
        else:
            from .assembly import resolveAssembly
            partGroup = resolveAssembly(info.Parent).getPartGroup()
            vis = partGroup.isElementVisible(info.Part.Name)
            partGroup.setElementVisible(info.Part.Name,not vis)

        FreeCADGui.Selection.clearSelection()
        FreeCADGui.Selection.addSelection(moveInfo.SelObj,'.'.join(subs))
        FreeCADGui.runCommand('Std_TreeSelection')
        if vis:
            FreeCADGui.runCommand('Std_TreeCollapse') 
Example #2
Source File: CountersunkHoles.py    From FreeCAD_FastenersWB with GNU General Public License v2.0 5 votes vote down vote up
def setEdit(self,vobj,mode=0):
    #FreeCADGui.runCommand("Draft_Edit")
    Gui.Control.showDialog(FSTaskFilletDialog(self.Object))
    return True 
Example #3
Source File: viewProviderProxy.py    From FreeCAD_assembly2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
def execute( self ):
        try:
            FreeCADGui.runCommand( self.Freecad_cmd )
        except:
            FreeCAD.Console.PrintError( traceback.format_exc() ) 
Example #4
Source File: insertLinkCmd.py    From FreeCAD_Assembly4 with GNU Lesser General Public License v2.1 5 votes vote down vote up
def onCreateLink(self):
        # parse the selected items 
        # TODO : there should only be 1
        selectedPart = []
        for selected in self.partList.selectedIndexes():
            # get the selected part
            selectedPart = self.allParts[ selected.row() ]

        # get the name of the link (as it should appear in the tree)
        linkName = self.linkNameInput.text()
        # only create link if there is a Part object and a name
        if self.asmModel and selectedPart and linkName:
            # create the App::Link with the user-provided name
            createdLink = self.activeDoc.getObject('Model').newObject( 'App::Link', linkName )
            # assign the user-selected selectedPart to it
            createdLink.LinkedObject = selectedPart
            # If the name was already chosen, and a UID was generated:
            if createdLink.Name != linkName:
                # we try to set the label to the chosen name
                createdLink.Label = linkName
            # update the link
            createdLink.recompute()
            
            # close the dialog UI...
            self.close()

            # ... and launch the placement of the inserted part
            Gui.Selection.clearSelection()
            Gui.Selection.addSelection( self.activeDoc.Name, 'Model', createdLink.Name+'.' )
            Gui.runCommand( 'Asm4_placeLink' )

        # if still open, close the dialog UI
        self.close() 
Example #5
Source File: FastenersLib.py    From FreeCAD_Assembly4 with GNU Lesser General Public License v2.1 5 votes vote down vote up
def Activated(self):
        # check that the Fasteners WB has been loaded before:
        if not 'FSChangeParams' in Gui.listCommands():
            Gui.activateWorkbench('FastenersWorkbench')
            Gui.activateWorkbench('Assembly4Workbench')
        # check that we have selected a Fastener from the Fastener WB
        selection = getSelectionFS()
        if selection == None:
            return
        Gui.runCommand('FSChangeParams') 
Example #6
Source File: FastenersLib.py    From FreeCAD_Assembly4 with GNU Lesser General Public License v2.1 5 votes vote down vote up
def Activated(self):
        # check that the Fasteners WB has been loaded before:
        if not 'FSChangeParams' in Gui.listCommands():
            Gui.activateWorkbench('FastenersWorkbench')
            Gui.activateWorkbench('Assembly4Workbench')
        # check that we have somewhere to put our stuff
        self.asmDoc = App.ActiveDocument
        part = self.getPart()
        if part :
            newFastener = App.ActiveDocument.addObject("Part::FeaturePython",self.FStype)
            newFastener.ViewObject.ShapeColor = self.FScolor
            if self.FStype == 'Screw':
                FS.FSScrewObject( newFastener, 'ISO4762', None )
            elif self.FStype == 'Nut':
                FS.FSScrewObject( newFastener, 'ISO4032', None )
            elif self.FStype == 'Washer':
                FS.FSScrewObject( newFastener, 'ISO7089', None )
            elif self.FStype == 'ThreadedRod':
                FS.FSThreadedRodObject( newFastener, None )
            # make the Proxy and stuff
            newFastener.Label = newFastener.Proxy.itemText
            FS.FSViewProviderTree(newFastener.ViewObject)
            # add Asm4 properties if necessary
            Asm4.makeAsmProperties( newFastener, reset=True )
            # add it to the Part 
            part.addObject( newFastener )
            # hide "offset" and "invert" properties to avoid confusion as they are not used in Asm4
            if hasattr( newFastener, 'offset' ):
                newFastener.setPropertyStatus('offset', 'Hidden')
            if hasattr( newFastener, 'invert' ):
                newFastener.setPropertyStatus('invert', 'Hidden')
            newFastener.recompute()
            # ... and select it
            Gui.Selection.clearSelection()
            Gui.Selection.addSelection( newFastener )
            Gui.runCommand('FSChangeParams')
            #Gui.runCommand( 'Asm4_placeFastener' ) 
Example #7
Source File: a2p_viewProviderProxies.py    From A2plus with GNU Lesser General Public License v2.1 5 votes vote down vote up
def doubleClicked(self,vobj):
        FreeCADGui.activateWorkbench('A2plusWorkbench')
        FreeCADGui.runCommand("a2p_EditConstraintCommand") 
Example #8
Source File: a2p_viewProviderProxies.py    From A2plus with GNU Lesser General Public License v2.1 5 votes vote down vote up
def doubleClicked(self,vobj):
        FreeCADGui.activateWorkbench('A2plusWorkbench')
        FreeCADGui.runCommand("a2p_EditConstraintCommand")
                
#WF: next 3 methods not required 
Example #9
Source File: a2p_viewProviderProxies.py    From A2plus with GNU Lesser General Public License v2.1 5 votes vote down vote up
def execute( self ):
        try:
            FreeCADGui.runCommand( self.Freecad_cmd )
        except:
            FreeCAD.Console.PrintError( traceback.format_exc() )


#============================================================================== 
Example #10
Source File: Commands.py    From NodeEditor with MIT License 5 votes vote down vote up
def shutdown():
    '''fast stop of freecad test environ'''
    try:
        FreeCAD.closeDocument("Unnamed")
    except:
        pass
    try:
        FreeCAD.closeDocument("graph")
    except:
        pass

    FreeCADGui.runCommand("Std_Quit") 
Example #11
Source File: gui.py    From FreeCAD_assembly3 with GNU General Public License v3.0 5 votes vote down vote up
def Activated(cls):
        from .assembly import isTypeOf, AsmElement, AsmElementLink
        sels = FreeCADGui.Selection.getSelectionEx('',0,True)
        if not sels:
            return
        if not sels[0].SubElementNames:
            FreeCADGui.runCommand('Std_LinkSelectLinkedFinal')
            return
        subname = sels[0].SubElementNames[0]
        obj = sels[0].Object.getSubObject(subname,retType=1)
        if not isTypeOf(obj,(AsmElementLink,AsmElement)):
            FreeCADGui.runCommand('Std_LinkSelectLinkedFinal')
            return

        while True:
            linked = obj.LinkedObject
            if isinstance(linked,tuple):
                subname = linked[1]
                linked = linked[0]
            else:
                subname = ''
            obj = linked.getSubObject(subname,retType=1)
            if not isTypeOf(obj,AsmElement):
                break

        obj = obj.getLinkedObject(True)

        import Part
        subname = Part.splitSubname(subname)[-1]

        FreeCADGui.Selection.pushSelStack()
        FreeCADGui.Selection.clearSelection()
        FreeCADGui.Selection.addSelection(obj,subname)
        FreeCADGui.Selection.pushSelStack()
        FreeCADGui.runCommand('Std_TreeSelection') 
Example #12
Source File: assembly.py    From FreeCAD_assembly3 with GNU General Public License v3.0 5 votes vote down vote up
def make(sels=None,name=None, undo=True):
        info = AsmPlainGroup.getSelection(sels)
        doc = info.Parent.Document
        if undo:
            FreeCAD.setActiveTransaction('Assembly create group')
        try:
            if not name:
                name = 'Group'
            obj = doc.addObject('App::DocumentObjectGroupPython',name)
            AsmPlainGroup(obj,info.Parent)
            ViewProviderAsmPlainGroup(obj.ViewObject)
            group = info.Group.Group
            indices = [ group.index(o) for o in info.Objects ]
            indices.sort()
            child = group[indices[0]]
            group = [ o for o in info.Group.Group
                        if o not in info.Objects ]
            group.insert(indices[0],obj)

            notouch = indices[-1] == indices[0]+len(indices)-1
            editGroup(info.Group,group,notouch)
            obj.purgeTouched()
            editGroup(obj,info.Objects,notouch)

            if undo:
                FreeCAD.closeActiveTransaction()

            FreeCADGui.Selection.clearSelection()
            FreeCADGui.Selection.addSelection(info.SelObj,'{}{}.{}.'.format(
                info.SelSubname,obj.Name,child.Name))
            FreeCADGui.runCommand('Std_TreeSelection')
            return obj
        except Exception:
            if undo:
                FreeCAD.closeActiveTransaction(True)
            raise 
Example #13
Source File: assembly.py    From FreeCAD_assembly3 with GNU General Public License v3.0 5 votes vote down vote up
def gotoRelationOfConstraint(obj,subname):
        sobj = obj.getSubObject(subname,1)
        if not isTypeOf(sobj,AsmConstraint):
            return
        subname = flattenLastSubname(obj,subname)
        sub = Part.splitSubname(subname)[0].split('.')
        sub = sub[:-1]
        sub[-2] = '3'
        sub[-1] = ''
        sub = '.'.join(sub)
        subs = []
        relationGroup = sobj.Proxy.getAssembly().getRelationGroup(True)
        for relation in relationGroup.Proxy.getRelations().values():
            for o in relation.Group:
                if isTypeOf(o,AsmRelation):
                    found = False
                    for child in o.Group:
                        if child == sobj:
                            subs.append('{}{}.{}.{}.'.format(
                                sub,relation.Name,o.Name,child.Name))
                            found = True
                            break
                    if found:
                        continue
                elif o == sobj:
                    subs.append('{}{}.{}.'.format(sub,relation.Name,o.Name))

        if subs:
            FreeCADGui.Selection.pushSelStack()
            FreeCADGui.Selection.clearSelection()
            FreeCADGui.Selection.addSelection(obj,subs)
            FreeCADGui.Selection.pushSelStack()
            FreeCADGui.runCommand('Std_TreeSelection') 
Example #14
Source File: assembly.py    From FreeCAD_assembly3 with GNU General Public License v3.0 4 votes vote down vote up
def make(typeid,sel=None,name='Constraint',undo=True):
        if not sel:
            sel = AsmConstraint.getSelection(typeid)
        assembly = resolveAssembly(sel.Assembly)
        if sel.Constraint:
            if undo:
                FreeCAD.setActiveTransaction('Assembly change constraint')
            cstr = sel.Constraint
        else:
            if undo:
                FreeCAD.setActiveTransaction('Assembly create constraint')
            constraints = assembly.getConstraintGroup()
            cstr = constraints.Document.addObject("App::FeaturePython",
                    name,AsmConstraint(constraints),None,True)
            ViewProviderAsmConstraint(cstr.ViewObject)
            constraints.setLink({-1:cstr})
            Constraint.setTypeID(cstr,typeid)
            cstr.Label = Constraint.getTypeName(cstr)

        try:
            for e in sel.Elements:
                AsmElementLink.make(AsmElementLink.MakeInfo(cstr,*e))
            logger.catchDebug('init constraint', Constraint.init,cstr)

            if gui.AsmCmdManager.AutoElementVis:
                cstr.setPropertyStatus('VisibilityList','-Immutable')
                cstr.VisibilityList = [False]*len(flattenGroup(cstr))
                cstr.setPropertyStatus('VisibilityList','Immutable')

            cstr.Proxy._initializing = False

            if Constraint.canMultiply(cstr):
                cstr.recompute(True)

            if undo:
                FreeCAD.closeActiveTransaction()
                undo = False

            if sel.SelObject:
                FreeCADGui.Selection.pushSelStack()
                FreeCADGui.Selection.clearSelection()
                if sel.SelSubname:
                    subname = sel.SelSubname
                else:
                    subname = ''
                subname += assembly.getConstraintGroup().Name + \
                        '.' + cstr.Name + '.'
                FreeCADGui.Selection.addSelection(sel.SelObject,subname)
                FreeCADGui.Selection.pushSelStack()
                FreeCADGui.runCommand('Std_TreeSelection')
            return cstr

        except Exception as e:
            logger.debug('failed to make constraint: {}',e)
            if undo:
                FreeCAD.closeActiveTransaction(True)
            raise 
Example #15
Source File: dev.py    From NodeEditor with MIT License 4 votes vote down vote up
def run_FreeCAD_bakery(self):

    workspace=self.getData("Workspace")
    name=self.getData("name")
    shape=self.getPinObject('Shape_in')
    s=shape

    l=FreeCAD.listDocuments()
    if workspace=='' or workspace=='None':
        try:
            w=l['Unnamed']
        except:
            w=FreeCAD.newDocument("Unnamed")
            FreeCADGui.runCommand("Std_TileWindows")
    else:
        if workspace in l.keys():
            w=l[workspace]
        else:
            w=FreeCAD.newDocument(workspace)

            #Std_CascadeWindows
            FreeCADGui.runCommand("Std_ViewDimetric")
            FreeCADGui.runCommand("Std_ViewFitAll")
            FreeCADGui.runCommand("Std_TileWindows")

    #s=store.store().get(shape)

    f=w.getObject(name)
    #say("AB",time.time()-timeA)
    if 1 or f == None:
        f = w.addObject('Part::Feature', name)
    if s  !=  None:
    #    say("AC",time.time()-timeA)
        f.Shape=s
    #    say("AD",time.time()-timeA)
    #say("shape",s);say("name",name)
    #say("A",time.time()-timeA)
    w.recompute()
    #say("B",time.time()-timeA)
    if 1:
        color=(random.random(),random.random(),1.)
        f.ViewObject.ShapeColor = color
        f.ViewObject.LineColor = color
        f.ViewObject.PointColor = color

    #f.ViewObject.Transparency = transparency

    #say("E",time.time()-timeA) 
Example #16
Source File: newDatumCmd.py    From FreeCAD_Assembly4 with GNU Lesser General Public License v2.1 4 votes vote down vote up
def Activated(self):
        # check that we have somewhere to put our stuff
        selectedObj = self.checkSelection()
        
        # check whether we have selected a container
        if selectedObj.TypeId in self.containers:
            parentContainer = selectedObj
        # if a datum object is selected we try to find the parent container
        elif selectedObj.TypeId in self.datumTypes:
            parent = selectedObj.getParentGeoFeatureGroup()
            if parent.TypeId in self.containers:
                parentContainer = parent
        # something went wrong
        else:
            Asm4.warningBox("I can't create a "+self.datumType+" with the current selections")
            
        # check whether there is already a similar datum, and increment the instance number 
        # instanceNum = 1
        #while App.ActiveDocument.getObject( self.datumName+'_'+str(instanceNum) ):
        #    instanceNum += 1
        #datumName = self.datumName+'_'+str(instanceNum)
        if parentContainer:
            # input dialog to ask the user the name of the Sketch:
            proposedName = Asm4.nextInstance( self.datumName, startAtOne=True )
            text,ok = QtGui.QInputDialog.getText(None,'Create new '+self.datumName,
                    'Enter '+self.datumName+' name :'+' '*40, text = proposedName)
            if ok and text:
                # App.activeDocument().getObject('Model').newObject( 'Sketcher::SketchObject', text )
                createdDatum = parentContainer.newObject( self.datumType, text )
                # automatic resizing of datum Plane sucks, so we set it to manual
                if self.datumType=='PartDesign::Plane':
                    createdDatum.ResizeMode = 'Manual'
                    createdDatum.Length = 100
                    createdDatum.Width = 100
                # if color or transparency is specified for this datum type
                if self.datumColor:
                    Gui.ActiveDocument.getObject(createdDatum.Name).ShapeColor = self.datumColor
                if self.datumAlpha:
                    Gui.ActiveDocument.getObject(createdDatum.Name).Transparency = self.datumAlpha
                # highlight the created datum object
                Gui.Selection.clearSelection()
                Gui.Selection.addSelection( App.ActiveDocument.Name, parentContainer.Name, createdDatum.Name+'.' )
                #Gui.runCommand('Part_EditAttachment') 
Example #17
Source File: assembly.py    From FreeCAD_assembly3 with GNU General Public License v3.0 4 votes vote down vote up
def make(info=None,name=None, tp=0, undo=True):
        if not info:
            info = AsmWorkPlane.getSelection()
        doc = info.PartGroup.Document
        if undo:
            FreeCAD.setActiveTransaction('Assembly create workplane')
        try:
            logger.debug('make {}',tp)
            if tp == 3:
                obj = Assembly.addOrigin(info.PartGroup,name)
            else:
                if tp==1:
                    pla = FreeCAD.Placement(info.Placement.Base,
                        FreeCAD.Rotation(FreeCAD.Vector(0,1,0),-90))
                elif tp==2:
                    pla = FreeCAD.Placement(info.Placement.Base,
                        FreeCAD.Rotation(FreeCAD.Vector(1,0,0),90))
                else:
                    pla = info.Placement

                if tp == 4:
                    if not name:
                        name = 'Placement'
                    obj = doc.addObject('App::Placement',name)
                elif not name:
                    name = 'Workplane'
                    obj = doc.addObject('Part::FeaturePython',name)
                    AsmWorkPlane(obj)
                    ViewProviderAsmWorkPlane(obj.ViewObject)
                    if utils.isVertex(info.Shape):
                        obj.Length = obj.Width = 0
                    elif utils.isLinearEdge(info.Shape):
                        if info.BoundBox.isValid():
                            obj.Length = info.BoundBox.DiagonalLength
                        obj.Width = 0
                        pla = FreeCAD.Placement(pla.Base,pla.Rotation.multiply(
                            FreeCAD.Rotation(FreeCAD.Vector(0,1,0),90)))
                    elif info.BoundBox.isValid():
                        obj.Length = obj.Width = info.BoundBox.DiagonalLength

                obj.Placement = pla

                obj.recompute(True)
                info.PartGroup.setLink({-1:obj})

            if undo:
                FreeCAD.closeActiveTransaction()

            FreeCADGui.Selection.clearSelection()
            FreeCADGui.Selection.addSelection(info.SelObj,
                info.SelSubname + info.PartGroup.Name + '.' + obj.Name + '.')
            FreeCADGui.runCommand('Std_TreeSelection')
            FreeCADGui.Selection.setVisible(True)
            return obj
        except Exception:
            if undo:
                FreeCAD.closeActiveTransaction(True)
            raise