def testActivate(self): list = FreeCADGui.listWorkbenches() try: for i in list: FreeCADGui.activateWorkbench(i) FreeCADGui.updateGui() FreeCAD.Console.PrintLog("Active: " + FreeCADGui.activeWorkbench().name() + " Expected: " + i + "\n") FreeCADGui.updateGui() self.failUnless(FreeCADGui.activeWorkbench().name() == i, "Test on activating workbench failed") except Exception, e: self.failUnless( False, "Loading of workbench '%s' failed: %s" % (i, e.message))
def testHandler(self): import __main__ class UnitWorkbench(__main__.Workbench): MenuText = "Unittest" ToolTip = "Unittest" def Initialize(self): list = ["Test_Test"] self.appendToolbar("My Unittest", list) def GetClassName(self): return "Gui::PythonWorkbench" FreeCADGui.addWorkbench(UnitWorkbench()) list = FreeCADGui.listWorkbenches() self.failUnless( list.has_key("UnitWorkbench") == True, "Test on adding workbench handler failed") FreeCADGui.activateWorkbench("UnitWorkbench") FreeCADGui.updateGui() self.failUnless(FreeCADGui.activeWorkbench().name() == "UnitWorkbench", "Test on loading workbench 'Unittest' failed") FreeCADGui.removeWorkbench("UnitWorkbench") list = FreeCADGui.listWorkbenches() self.failUnless( list.has_key("UnitWorkbench") == False, "Test on removing workbench handler failed")
def Activated(self): s = FreeCADGui.Selection.getSelectionEx() try: ordered = FreeCADGui.activeWorkbench().Selection if ordered: s = ordered except AttributeError: pass sub = list() pts = list() typ = list() for obj in s: if obj.HasSubObjects: #FreeCAD.Console.PrintMessage("object has subobjects %s\n"%str(obj.SubElementNames)) for n in obj.SubElementNames: sub.append((obj.Object, [n])) for p in obj.PickedPoints: pts.append(p) if len(pts) == 0: pts = [FreeCAD.Vector(0, 0, 0), FreeCAD.Vector(1, 0, 0)] typ = [0, 0] else: typ = [1] * len(pts) self.makeFeature(sub, pts, typ)
def postStart(): "executes needed operations after loading a file" param = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Start") # switch workbench wb = param.GetString("AutoloadModule","") if wb: # don't switch workbenches if we are not in Start anymore if FreeCADGui.activeWorkbench() and (FreeCADGui.activeWorkbench().name() == "StartWorkbench"): FreeCADGui.activateWorkbench(wb) # close start tab cl = param.GetBool("closeStart",False) if cl: title = QtGui.QApplication.translate("Workbench","Start page") mw = FreeCADGui.getMainWindow() if mw: mdi = mw.findChild(QtGui.QMdiArea) if mdi: for mdichild in mdi.children(): for subw in mdichild.findChildren(QtGui.QMdiSubWindow): if subw.windowTitle() == title: subw.close()
def testActivate(self): list=FreeCADGui.listWorkbenches() for i in list: FreeCADGui.activateWorkbench(i) FreeCADGui.updateGui() FreeCAD.Console.PrintLog("Active: "+FreeCADGui.activeWorkbench().name()+ " Expected: "+i+"\n") FreeCADGui.updateGui() self.failUnless(FreeCADGui.activeWorkbench().name()==i, "Test on activating workbench failed")
def testActivate(self): list=FreeCADGui.listWorkbenches() try: for i in list: FreeCADGui.activateWorkbench(i) FreeCADGui.updateGui() FreeCAD.Console.PrintLog("Active: "+FreeCADGui.activeWorkbench().name()+ " Expected: "+i+"\n") FreeCADGui.updateGui() self.failUnless(FreeCADGui.activeWorkbench().name()==i, "Test on activating workbench failed") except Exception, e: self.failUnless(False, "Loading of workbench '%s' failed: %s" % (i, e.message))
def testActivate(self): list = FreeCADGui.listWorkbenches() for i in list: FreeCADGui.activateWorkbench(i) FreeCADGui.updateGui() FreeCAD.Console.PrintLog("Active: " + FreeCADGui.activeWorkbench().name() + " Expected: " + i + "\n") FreeCADGui.updateGui() self.failUnless(FreeCADGui.activeWorkbench().name() == i, "Test on activating workbench failed")
def testActivate(self): wbs=FreeCADGui.listWorkbenches() try: for i in wbs: FreeCADGui.activateWorkbench(i) FreeCADGui.updateGui() FreeCAD.Console.PrintLog("Active: "+FreeCADGui.activeWorkbench().name()+ " Expected: "+i+"\n") FreeCADGui.updateGui() self.assertEqual(FreeCADGui.activeWorkbench().name(), i, "Test on activating workbench {0} failed".format(i)) except Exception as e: self.fail("Loading of workbench '{0}' failed: {1}".format(i, e))
def localShortcuts(): """ Create a dictionary of available local shortcuts. """ currentLocal.clear() if Gui.activeWorkbench().MenuText: activeWB = Gui.activeWorkbench().MenuText else: activeWB = None if activeWB: index = paramGet.GetGroup(activeWB).GetString("IndexList") index = index.split(",") for i in index: try: command = (paramGet .GetGroup(activeWB) .GetGroup(i) .GetString("command") .decode("UTF-8")) except AttributeError: command = (paramGet .GetGroup(activeWB) .GetGroup(i) .GetString("command")) try: shortcut = (paramGet .GetGroup(activeWB) .GetGroup(i) .GetString("shortcut") .decode("UTF-8")) except AttributeError: shortcut = (paramGet .GetGroup(activeWB) .GetGroup(i) .GetString("shortcut")) if command and shortcut: currentLocal[command] = shortcut else: index.remove(i) paramGet.GetGroup(activeWB).RemGroup(i) string = ",".join(index) paramGet.GetGroup(activeWB).SetString("IndexList", string) else: pass
def doubleClicked(self, vobj): if FreeCADGui.activeWorkbench().name() != 'CfdWorkbench': FreeCADGui.activateWorkbench("CfdWorkbench") doc = FreeCADGui.getDocument(vobj.Object.Document) # it should be possible to find the AnalysisObject although it is not a documentObjectGroup if not FemGui.getActiveAnalysis(): analysis_obj = CfdTools.getParentAnalysisObject(self.Object) if analysis_obj: FemGui.setActiveAnalysis(analysis_obj) else: FreeCAD.Console.PrintError( 'No Active Analysis is detected from solver object in the active Document!\n' ) if not doc.getInEdit(): if FemGui.getActiveAnalysis().Document is FreeCAD.ActiveDocument: if self.Object in FemGui.getActiveAnalysis().Group: doc.setEdit(vobj.Object.Name) else: FreeCAD.Console.PrintError( 'Activate the analysis this solver belongs to!\n') else: FreeCAD.Console.PrintError( 'Active Analysis is not in active Document!\n') else: FreeCAD.Console.PrintError( 'Active Task Dialog found! Please close this one first!\n') return True
def doubleClicked(self, vobj): if not FemGui.getActiveAnalysis() == self.Object: if FreeCADGui.activeWorkbench().name() != "FemWorkbench": FreeCADGui.activateWorkbench("FemWorkbench") FemGui.setActiveAnalysis(self.Object) return True return True
def sig(): ''' compute a signature of a selection''' debug=False subs=[] wbn=Gui.activeWorkbench().name() for s in Gui.Selection.getSelectionEx(): if debug: print s print s.ObjectName print s.Object.__class__.__name__ print "Type Id",s.Object.TypeId print s.SubElementNames print s.SubObjects # sub= s.Object.__class__.__name__ sub= s.Object.TypeId.replace('::','.') if sub == 'Part.FeaturePython' or sub== 'App.DocumentObjectGroupPython' : try: tid = s.Object.Proxy.__module__ + '.' + s.Object.Proxy.__class__.__name__ if tid <>'': sub=tid except: pass k=[so.__class__.__name__ for so in s.SubObjects] sub += ":"+ ','.join(k) subs.append(sub) if subs==[]: subs=[":"] sss=wbn +'#' + '#'.join(subs) print "Look for SIGNATURE:\n"+sss+'--' return sss
def runme(): if PluginManager.toolbar >= 0: try: t = FreeCADGui.getMainWindow() wb = FreeCADGui.activeWorkbench() name = "TEST" try: name = wb.name() except: wbs = 'a' + str(wb) pat = r".*\.(.+) inst.*" import re m = re.match(pat, wbs) if m: name = m.group(1) import Part #FreeCAD.Console.PrintMessage("\n " +name) #FreeCAD.Console.PrintMessage(" gen ..") if name <> "NoneWorkbench": PluginManager.gentoolbars(name) #FreeCAD.Console.PrintMessage(" .. gened" ) except: sayexc("except 2") # PluginManager.gentoolbars("Robot") PluginManager.toolbar += 1 self = FreeCAD.Gui.getMainWindow() self.show()
def doubleClicked(self, vobj): # bug: still not working, always bring up FemWorkbench if FreeCADGui.activeWorkbench().name() != 'CfdWorkbench': FreeCADGui.activateWorkbench("CfdWorkbench") if not FemGui.getActiveAnalysis() == self.Object: FemGui.setActiveAnalysis(self.Object) return True
def selectorMenu(): """Selector button with menu.""" sMenu.clear() enabled = p.GetString("Enabled") partially = p.GetString("Partially") unchecked = p.GetString("Unchecked") position = p.GetString("Position") enabled = enabled.split(",") partially = partially.split(",") unchecked = unchecked.split(",") position = position.split(",") active = Gui.activeWorkbench().__class__.__name__ l = [] for i in partially: if i in actions: l.append(i) s = list(actions) s.sort() for i in s: if i not in l and i not in enabled and i not in unchecked: l.append(i) for i in l: sMenu.addAction(actions[i]) sMenuStatic.addAction(actions[i]) aMenu.setText(actions[active].text()) aMenu.setIcon(actions[active].icon())
def onWorkbench(): """Populate command panel on workbench activation.""" # Global panel mode if p.GetBool("Global", 0): workbench = "GlobalPanel" else: workbench = Gui.activeWorkbench().__class__.__name__ if layout: while not layout.isEmpty(): item = layout.takeAt(0) del item buttons = cpcmd.workbenchButtons(workbench) if p.GetString("Layout") == "Grid": columns = p.GetInt("ColumnNumber", 1) - 1 x = 0 y = 0 for btn in buttons: if y > columns: y = 0 x += 1 layout.addWidget(btn, x, y) y += 1 # Set spacing layout.setSpacing(p.GetInt("ButtonSpacing", 5)) else: for btn in buttons: layout.addWidget(btn) # Set spacing layout.setSpaceXY() layout.update()
def populateTop(): """Populate all top menus.""" # Global menu mode if p.GetBool("Global", 0): workbench = "GlobalPanel" else: workbench = Gui.activeWorkbench().__class__.__name__ for menu in mw.findChildren(QtGui.QMenu, "NaviCube_Menu"): commands = [] # User if p.GetGroup("User").GetGroup(workbench).GetString("default"): domain = ( p.GetGroup("User").GetGroup(workbench).GetString("default")) # System elif p.GetGroup("System").GetGroup(workbench).GetString("default"): domain = ( p.GetGroup("System").GetGroup(workbench).GetString("default")) # Global default else: domain = "CPMenu.System.GlobalPanel.GlobalDefault" group = cpc.findGroup(domain) if group: commands = cpc.splitIndex(group, "commands") commands = globalDefault(commands) addActions(menu, commands)
def doubleClicked(self, vobj): if FreeCADGui.activeWorkbench().name() != 'CfdOFWorkbench': FreeCADGui.activateWorkbench("CfdOFWorkbench") doc = FreeCADGui.getDocument(vobj.Object.Document) if not CfdTools.getActiveAnalysis(): analysis_obj = CfdTools.getParentAnalysisObject(self.Object) if analysis_obj: CfdTools.setActiveAnalysis(analysis_obj) else: FreeCAD.Console.PrintError( 'No Active Analysis detected from Solver object in the active Document\n' ) if not doc.getInEdit(): if CfdTools.getActiveAnalysis().Document is FreeCAD.ActiveDocument: if self.Object in CfdTools.getActiveAnalysis().Group: doc.setEdit(vobj.Object.Name) else: FreeCAD.Console.PrintError( 'Please activate the Analysis this solver belongs to.\n' ) else: FreeCAD.Console.PrintError( 'Active Analysis is not in active Document\n') else: FreeCAD.Console.PrintError('Task dialog already active\n') FreeCADGui.Control.showTaskView() return True
def selectWorkbench(self): Defaults = ['File', 'Workbench', 'Macro', 'View', 'Structure'] index = self._tabBar.currentIndex() tabName = self._tabBar.tabText(index) if tabName == 'FreeCAD': return FreeCADGui.activateWorkbench(self.actions[tabName]) workbench = FreeCADGui.activeWorkbench() for tbb in mw.findChildren(QtWidgets.QToolBar): tbb.hide() if self.Enabled[tabName]: return tab = self._tabs[index] for toolbar in workbench.listToolbars(): if toolbar in Defaults: continue section = tab.addSection(toolbar) TB = mw.findChildren(QtWidgets.QToolBar, toolbar) for button in TB[0].findChildren(QtWidgets.QToolButton): if button.text() == '': continue section.addButton(full=False, icon=button.icon(), title=button.text() + ' ', handler=button.defaultAction().triggered, shortcut=button.shortcut(), statusTip=button.statusTip(), menu=button.menu()) self.Enabled[tabName] = True
def Activated(self): s = FreeCADGui.Selection.getSelectionEx() try: ordered = FreeCADGui.activeWorkbench().Selection if ordered: s = ordered except AttributeError: pass source = self.parseSel(s) if not source: return False if not isinstance(source, list): obj = FreeCAD.ActiveDocument.addObject( "Part::FeaturePython", "Approximation_Surface") #add object to document Approximate(obj, source) ViewProviderApp(obj.ViewObject) #s.ViewObject.Visibility=False else: for s in source: obj = FreeCAD.ActiveDocument.addObject( "Part::FeaturePython", "Approximation_Curve") #add object to document Approximate(obj, s) ViewProviderApp(obj.ViewObject) s.ViewObject.Visibility = False FreeCAD.ActiveDocument.recompute()
def Activated(self): try: s = FreeCADGui.activeWorkbench().Selection except AttributeError: s = FreeCADGui.Selection.getSelectionEx() edges, param = self.parseSel(s) if len(edges) > 1: for j in range(int(len(edges) / 2)): i = j * 2 obj = FreeCAD.ActiveDocument.addObject( "Part::FeaturePython", "Blend Curve") #add object to document BlendCurveFP(obj, edges[i:i + 2]) BlendCurveVP(obj.ViewObject) obj.Parameter1 = self.normalizedParam(edges[i], param[i], True) obj.Parameter2 = self.normalizedParam(edges[i + 1], param[i + 1], True) obj.Continuity1 = "G1" obj.Continuity2 = "G1" obj.Output = "Single" ori1, ori2 = self.getOrientation(edges[i], param[i], edges[i + 1], param[i + 1]) obj.Scale1 = ori1 obj.Scale2 = ori2 FreeCAD.ActiveDocument.recompute()
def populateCBoxWb(): """Workbench selector combo box.""" wb = Gui.listWorkbenches() wbSort = list(wb) wbSort.sort() wbSort.reverse() cBoxWb.blockSignals(True) cBoxWb.clear() for i in wbSort: try: icon = cpc.wbIcon(wb[i].Icon) except AttributeError: icon = QtGui.QIcon(":/icons/freecad") mt = wb[i].MenuText cn = wb[i].__class__.__name__ cBoxWb.insertItem(0, icon, mt, cn) cBoxWb.insertSeparator(0) cBoxWb.insertItem(0, QtGui.QIcon(":/icons/freecad"), "Global panel", "GlobalPanel") if p.GetBool("Global", 0): cBoxWb.setCurrentIndex(cBoxWb.findData("GlobalPanel")) else: activeWb = Gui.activeWorkbench().__class__.__name__ cBoxWb.setCurrentIndex(cBoxWb.findData(activeWb)) cBoxWb.blockSignals(False)
def comboBox(): """Workbench selector combo box.""" cBox = QtGui.QComboBox() cBox.setMinimumWidth(220) listWB = Gui.listWorkbenches() listWBSorted = sorted(listWB) listWBSorted.reverse() for i in listWBSorted: try: icon = wbIcon(Gui.listWorkbenches()[i].Icon) except AttributeError: icon = QtGui.QIcon(":/icons/freecad") cBox.insertItem(0, icon, listWB[i].MenuText, listWB[i].__class__.__name__) cBox.insertSeparator(0) icon = QtGui.QIcon(":/icons/freecad") cBox.insertItem(0, icon, "Global shortcuts", "GlobalShortcuts") cBox.setCurrentIndex(0) activeWB = Gui.activeWorkbench().__class__.__name__ for count in range(cBox.count()): if cBox.itemData(count) == activeWB: cBox.setCurrentIndex(count) return cBox
def Activated(self): s = FreeCADGui.Selection.getSelectionEx() try: ordered = FreeCADGui.activeWorkbench().Selection if ordered: s = ordered except AttributeError: pass sub = list() pts = list() typ = list() for obj in s: if obj.HasSubObjects: #FreeCAD.Console.PrintMessage("object has subobjects %s\n"%str(obj.SubElementNames)) for n in obj.SubElementNames: sub.append((obj.Object,[n])) for p in obj.PickedPoints: pts.append(p) if len(pts) == 0: pts = [FreeCAD.Vector(0,0,0),FreeCAD.Vector(0.5,0,0),FreeCAD.Vector(1,0,0)] typ = [0,0,0] elif len(pts) == 1: pts.append(pts[0]+FreeCAD.Vector(0.5,0,0)) pts.append(pts[0]+FreeCAD.Vector(1,0,0)) typ = [1,0,0] else: typ = [1]*len(pts) self.makeFeature(sub,pts,typ)
def doubleClicked(self, vobj): if not FemGui.getActiveAnalysis() == self.Object: if FreeCADGui.activeWorkbench().name() != 'CfdWorkbench': FreeCADGui.activateWorkbench("CfdWorkbench") FemGui.setActiveAnalysis(self.Object) return True return True
def onWorkbench(): """Store subwindow and workbench info.""" if p.GetBool("Checked", True): win = mdi.activeSubWindow() wb = Gui.activeWorkbench().__class__.__name__ if win and wb: ids[id(win)] = wb
def runme(): if PluginManager.toolbar >= 0: try: t=FreeCADGui.getMainWindow() wb=FreeCADGui.activeWorkbench() name="TEST" try: name=wb.name() except: wbs='a'+ str(wb) pat=r".*\.(.+) inst.*" import re m = re.match(pat, wbs) if m: name=m.group(1) import Part #FreeCAD.Console.PrintMessage("\n " +name) #FreeCAD.Console.PrintMessage(" gen ..") if name <>"NoneWorkbench": PluginManager.gentoolbars(name) #FreeCAD.Console.PrintMessage(" .. gened" ) except: sayexc("except 2") # PluginManager.gentoolbars("Robot") PluginManager.toolbar +=1 self=FreeCAD.Gui.getMainWindow() self.show()
def setEdit(self, vobj, mode): self.wb_before_edit = Gui.activeWorkbench() Gui.activateWorkbench("DraftWorkbench") self.task = ShapeStringTaskPanelEdit(vobj) Gui.Control.showDialog(self.task) return True
def Activated(self): vd = [FreeCAD.Vector(0, 0, 0), FreeCAD.Vector(0, 0, 0)] try: sel = FreeCADGui.activeWorkbench().Selection vd = FreeCADGui.activeWorkbench().View_Directions except AttributeError: sel = FreeCADGui.Selection.getSelectionEx() if not len(sel) == 2: FreeCAD.Console.PrintError("Select 2 objects !\n") return for selobj in sel: selobj.Object.ViewObject.Visibility = False if len(vd) == 2 and vd[0].dot(vd[1]) < 0.999: d1, d2 = vd else: d1, d2 = [FreeCAD.Vector(0, 0, 0), FreeCAD.Vector(0, 0, 0)] self.makeCPCFeature(sel[0].Object, sel[1].Object, d1, d2)
def doubleClicked(self, vobj): if FreeCADGui.activeWorkbench().name() != 'FemWorkbench': FreeCADGui.activateWorkbench("FemWorkbench") doc = FreeCADGui.getDocument(vobj.Object.Document) if not doc.getInEdit(): doc.setEdit(vobj.Object.Name) else: FreeCAD.Console.PrintError('Active Task Dialog found! Please close this one first!\n') return True
def importFrd(filename,Analysis=None): m = readResult(filename); MeshObject = None if(len(m) > 0): import Fem if Analysis == None: AnalysisName = os.path.splitext(os.path.basename(filename))[0] AnalysisObject = FreeCAD.ActiveDocument.addObject('Fem::FemAnalysis','Analysis') AnalysisObject.Label = AnalysisName else: AnalysisObject = Analysis if(m.has_key('Tet10Elem') and m.has_key('Nodes') and not Analysis ): mesh = Fem.FemMesh() nds = m['Nodes'] for i in nds: n = nds[i] mesh.addNode(n[0],n[1],n[2],i) elms = m['Tet10Elem'] for i in elms: e = elms[i] mesh.addVolume([e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9]],i) if len(nds) > 0: MeshObject = FreeCAD.ActiveDocument.addObject('Fem::FemMeshObject','ResultMesh') MeshObject.FemMesh = mesh AnalysisObject.Member = AnalysisObject.Member + [MeshObject] if(m.has_key('Displacement')): disp = m['Displacement'] if len(disp)>0: o = FreeCAD.ActiveDocument.addObject('Fem::FemResultVector','Displacement') o.Values = disp.values() o.DataType = 'Displacement' o.ElementNumbers = disp.keys() if(MeshObject): o.Mesh = MeshObject AnalysisObject.Member = AnalysisObject.Member + [o] if(m.has_key('Stress')): stress = m['Stress'] if len(stress)>0: o = FreeCAD.ActiveDocument.addObject('Fem::FemResultValue','MisesStress') mstress = [] for i in stress.values(): # van mises stress (http://en.wikipedia.org/wiki/Von_Mises_yield_criterion) mstress.append( sqrt( pow( i[0] - i[1] ,2) + pow( i[1] - i[2] ,2) + pow( i[2] - i[0] ,2) + 6 * (pow(i[3],2)+pow(i[4],2)+pow(i[5],2) ) ) ) o.Values = mstress o.DataType = 'VanMisesStress' o.ElementNumbers = stress.keys() if(MeshObject): o.Mesh = MeshObject AnalysisObject.Member = AnalysisObject.Member + [o] if(FreeCAD.GuiUp): import FemGui, FreeCADGui if FreeCADGui.activeWorkbench().name() != 'FemWorkbench': FreeCADGui.activateWorkbench("FemWorkbench") FemGui.setActiveAnalysis(AnalysisObject)
def doubleClicked(self, vobj): if FreeCADGui.activeWorkbench().name() != 'CfdOFWorkbench': FreeCADGui.activateWorkbench("CfdOFWorkbench") gui_doc = FreeCADGui.getDocument(vobj.Object.Document) if not gui_doc.getInEdit(): gui_doc.setEdit(vobj.Object.Name) else: FreeCAD.Console.PrintError('Task dialog already open\n') return True
def onBtnSettingsDone(): """Return to general preferences.""" btnSettings.clearFocus() stack.setCurrentIndex(0) if p.GetBool("Global", 0): cBoxWb.setCurrentIndex(cBoxWb.findData("GlobalPanel")) else: activeWb = Gui.activeWorkbench().__class__.__name__ cBoxWb.setCurrentIndex(cBoxWb.findData(activeWb))
def onWorkbenchActivated(): """When workbench gets activated restore toolbar position.""" active = Gui.activeWorkbench().__class__.__name__ if active: pythonToolbars() onRestore(active) else: pass
def doubleClicked(self, vobj): if not FemGui.getActiveAnalysis() == self.Object: if FreeCADGui.activeWorkbench().name() != 'FemWorkbench': FreeCADGui.activateWorkbench("FemWorkbench") FemGui.setActiveAnalysis(self.Object) return True else: taskd = _JobControlTaskPanel(self.Object) FreeCADGui.Control.showDialog(taskd) return True
def slotCreatedObject(self, feature): ac = activeContainer() aw = Gui.activeWorkbench().GetClassName() #hack!! we delay call of addObject to fire from within onChanged, as doing it now #results in incorrect parenting of viewproviders. Yet it has to be done before recompute, o #therwise the recompute fails. #From there, another delayed call is registered - a call to advanceTip, which should be called after the new object is fully set up. self.addition_calls_queue.append( lambda self=self, feature=feature, ac=ac, aw=aw: self. appendToActiveContainer(feature, ac, aw))
def pythonToolbars(): """Manage Python based toolbars in Arch and Draft workbench.""" active = Gui.activeWorkbench().__class__.__name__ if active == "DraftWorkbench" or active == "ArchWorkbench": if hasattr(Gui, "draftToolBar"): Gui.draftToolBar.Activated() if hasattr(Gui, "Snapper"): Gui.Snapper.show() else: pass
def slotCreatedObject(self, feature): print("created object") ac = activeContainer() aw = Gui.activeWorkbench().GetClassName() #hack!! we delay call of addObject to fire from within onChanged, as doing it now #results in incorrect parenting of viewproviders. Yet it has to be done before recompute, o #therwise the recompute fails. #From there, another delayed call is registered - a call to advanceTip, which should be called after the new object is fully set up. self.addition_calls_queue.append( lambda self=self, feature=feature, ac=ac, aw=aw: self.appendToActiveContainer(feature, ac, aw) )
def comboBox(): """ Workbench selector combo box. """ cBox = QtGui.QComboBox() cBox.setMinimumWidth(220) listWB = Gui.listWorkbenches() listWBSorted = sorted(listWB) listWBSorted.reverse() for i in listWBSorted: if i in listWB: try: icon = wbIcon(Gui.listWorkbenches()[i].Icon) except AttributeError: icon = iconFreeCAD cBox.insertItem(0, icon, listWB[i].MenuText) cBox.insertSeparator(0) icon = iconFreeCAD cBox.insertItem(0, icon, "Global shortcuts") cBox.setCurrentIndex(0) activeWB = Gui.activeWorkbench().MenuText for count in range(cBox.count()): if cBox.itemText(count) == activeWB: cBox.setCurrentIndex(count) else: pass def onCurrentIndexChanged(): """ Activate workbench on selection. """ listWB = Gui.listWorkbenches() for i in listWB: if listWB[i].MenuText == cBox.currentText(): Gui.activateWorkbench(i) else: pass updateStats() updateTable() cBox.currentIndexChanged.connect(onCurrentIndexChanged) return cBox
def Activated(self): s = FreeCADGui.Selection.getSelectionEx() try: ordered = FreeCADGui.activeWorkbench().Selection if ordered: s = ordered except AttributeError: pass source = self.parseSel(s) if not source: return(False) obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Interpolation_Curve") #add object to document Interpolate(obj,source) ViewProviderInterpolate(obj.ViewObject) FreeCAD.ActiveDocument.recompute()
def IsActive(self): if 'PathWorkbench' == FreeCADGui.activeWorkbench().name(): if bool(FreeCADGui.Selection.getSelection()) is False: return False try: sel = FreeCADGui.Selection.getSelectionEx()[0] if sel.Object == self.obj and sel.SubElementNames == self.sub: return self.active self.obj = sel.Object self.sub = sel.SubElementNames if sel.SubObjects: self.active = self.formsPartOfALoop(sel.Object, sel.SubObjects[0], sel.SubElementNames) else: self.active = False return self.active except Exception as exc: PathLog.error(exc) traceback.print_exc(exc) return False return False
def testHandler(self): import __main__ class UnitWorkbench(__main__.Workbench): MenuText = "Unittest" ToolTip = "Unittest" def Initialize(self): list = ["Test_Test"] self.appendToolbar("My Unittest",list) def GetClassName(self): return "Gui::PythonWorkbench" FreeCADGui.addWorkbench(UnitWorkbench()) list=FreeCADGui.listWorkbenches() self.failUnless(list.has_key("UnitWorkbench")==True, "Test on adding workbench handler failed") FreeCADGui.activateWorkbench("UnitWorkbench") FreeCADGui.updateGui() self.failUnless(FreeCADGui.activeWorkbench().name()=="UnitWorkbench", "Test on loading workbench 'Unittest' failed") FreeCADGui.removeWorkbench("UnitWorkbench") list=FreeCADGui.listWorkbenches() self.failUnless(list.has_key("UnitWorkbench")==False, "Test on removing workbench handler failed")
def pythonToolbars(): """Manage Python based toolbars in Arch and Draft workbench.""" active = Gui.activeWorkbench().__class__.__name__ if active == "DraftWorkbench" or active == "ArchWorkbench": if hasattr(Gui, "draftToolBar"): try: Gui.draftToolBar.Activated() except: m = "Persistent toolbars: draftToolBar toolbar not managed.\n" App.Console.PrintMessage(m) if hasattr(Gui, "Snapper"): try: Gui.Snapper.show() except: m = "Persistent toolbars: Snapper toolbar not managed.\n" App.Console.PrintMessage(m) else: pass
def Activated(self): try: s = FreeCADGui.activeWorkbench().Selection except AttributeError: s = FreeCADGui.Selection.getSelectionEx() edges, param = self.parseSel(s) if len(edges) > 1: for j in range(int(len(edges)/2)): i = j*2 obj=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Blend Curve") #add object to document BlendCurveFP(obj,edges[i:i+2]) BlendCurveVP(obj.ViewObject) obj.Parameter1 = self.normalizedParam(edges[i], param[i], True) obj.Parameter2 = self.normalizedParam(edges[i+1], param[i+1], True) obj.Continuity1 = "G1" obj.Continuity2 = "G1" obj.Output = "Single" ori1, ori2 = self.getOrientation(edges[i], param[i], edges[i+1], param[i+1]) obj.Scale1 = ori1 obj.Scale2 = ori2 FreeCAD.ActiveDocument.recompute()
def Activated(self): edges = [] sel = FreeCADGui.Selection.getSelectionEx() try: ordered = FreeCADGui.activeWorkbench().Selection if ordered: sel = ordered except AttributeError: pass if sel == []: FreeCAD.Console.PrintError("Select the edges to join first !\n") for selobj in sel: if selobj.HasSubObjects: for i in range(len(selobj.SubObjects)): if isinstance(selobj.SubObjects[i], Part.Edge): edges.append((selobj.Object, selobj.SubElementNames[i])) else: self.makeJoinFeature(selobj.Object) selobj.Object.ViewObject.Visibility=False if edges: self.makeJoinFeature(edges)
def registerPlugin(self,name,method): t=FreeCADGui.getMainWindow() saye("register menubar") pp=t.menuBar() found=False w=FreeCADGui.activeWorkbench() pname='Plugins' for c in pp.children(): try: if c.title() == pname: found=c #c.hide() #found=False #break except: print c if not found: p=pp.addMenu(pname) saye("---------------------------yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy") saye("addmenu ..") say(p) else: p=found say("found 1") #p=self.Menu for c in p.actions(): if c.text() == name: p.removeAction(c) break; saye("create action "+name) plina =MyAction(name,t,method) a=p.addAction(plina) plina.triggered.connect(plina.run) #p.show() saye("menubar done")
def Activated(self): s = FreeCADGui.Selection.getSelectionEx() try: ordered = FreeCADGui.activeWorkbench().Selection if ordered: s = ordered except AttributeError: pass source = self.parseSel(s) if not source: return False if not isinstance(source,list): obj=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Approximation_Surface") #add object to document Approximate(obj,source) ViewProviderApp(obj.ViewObject) #s.ViewObject.Visibility=False else: for s in source: obj=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Approximation_Curve") #add object to document Approximate(obj,s) ViewProviderApp(obj.ViewObject) s.ViewObject.Visibility=False FreeCAD.ActiveDocument.recompute()
def runme(): if PluginManager.toolbar >= 0: try: t=FreeCADGui.getMainWindow() wb=FreeCADGui.activeWorkbench() name="TEST" try: name=wb.name() except: wbs='a'+ str(wb) pat=r".*\.(.+) inst.*" import re m = re.match(pat, wbs) if m: name=m.group(1) import Part PluginManager.gentoolbars(name) except: sayexc("except 2") PluginManager.gentoolbars("Robot") PluginManager.toolbar +=1 self=FreeCAD.Gui.getMainWindow() self.show()
def importFrd(filename, Analysis=None): m = readResult(filename) result_set_number = len(m['Results']) MeshObject = None if(len(m) > 0): import Fem if Analysis is None: AnalysisName = os.path.splitext(os.path.basename(filename))[0] AnalysisObject = FreeCAD.ActiveDocument.addObject('Fem::FemAnalysis', 'Analysis') AnalysisObject.Label = AnalysisName else: AnalysisObject = Analysis if 'Nodes' in m: positions = [] for k, v in m['Nodes'].iteritems(): positions.append(v) p_x_max, p_y_max, p_z_max = map(max, zip(*positions)) p_x_min, p_y_min, p_z_min = map(min, zip(*positions)) x_span = abs(p_x_max - p_x_min) y_span = abs(p_y_max - p_y_min) z_span = abs(p_z_max - p_z_min) span = max(x_span, y_span, z_span) if ('Tet10Elem' in m) and ('Nodes' in m) and (not Analysis): mesh = Fem.FemMesh() nds = m['Nodes'] for i in nds: n = nds[i] mesh.addNode(n[0], n[1], n[2], i) elms = m['Tet10Elem'] for i in elms: e = elms[i] mesh.addVolume([e[0], e[1], e[2], e[3], e[4], e[5], e[6], e[7], e[8], e[9]], i) if len(nds) > 0: MeshObject = FreeCAD.ActiveDocument.addObject('Fem::FemMeshObject', 'ResultMesh') MeshObject.FemMesh = mesh AnalysisObject.Member = AnalysisObject.Member + [MeshObject] for result_set in m['Results']: eigenmode_number = result_set['number'] if result_set_number > 1: results_name = 'Mode_' + str(eigenmode_number) + '_results' else: results_name = 'Results' results = FreeCAD.ActiveDocument.addObject('Fem::FemResultObject', results_name) disp = result_set['disp'] l = len(disp) displacement = [] for k, v in disp.iteritems(): displacement.append(v) x_max, y_max, z_max = map(max, zip(*displacement)) if result_set_number > 1: max_disp = max(x_max, y_max, z_max) # Allow for max displacement to be 0.1% of the span # FIXME - add to Preferences max_allowed_disp = 0.001 * span scale = max_allowed_disp / max_disp else: scale = 1.0 if len(disp) > 0: results.DisplacementVectors = map((lambda x: x * scale), disp.values()) results.ElementNumbers = disp.keys() if(MeshObject): results.Mesh = MeshObject stress = result_set['stress'] if len(stress) > 0: mstress = [] for i in stress.values(): mstress.append(calculate_von_mises(i)) if result_set_number > 1: results.StressValues = map((lambda x: x * scale), mstress) else: results.StressValues = mstress if (results.ElementNumbers != 0 and results.ElementNumbers != stress.keys()): print ("Inconsistent FEM results: element number for Stress doesn't equal element number for Displacement {} != {}" .format(results.ElementNumbers, len(results.StressValues))) results.ElementNumbers = stress.keys() x_min, y_min, z_min = map(min, zip(*displacement)) sum_list = map(sum, zip(*displacement)) x_avg, y_avg, z_avg = [i / l for i in sum_list] s_max = max(results.StressValues) s_min = min(results.StressValues) s_avg = sum(results.StressValues) / l disp_abs = [] for d in displacement: disp_abs.append(sqrt(pow(d[0], 2) + pow(d[1], 2) + pow(d[2], 2))) results.DisplacementLengths = disp_abs a_max = max(disp_abs) a_min = min(disp_abs) a_avg = sum(disp_abs) / l results.Stats = [x_min, x_avg, x_max, y_min, y_avg, y_max, z_min, z_avg, z_max, a_min, a_avg, a_max, s_min, s_avg, s_max] AnalysisObject.Member = AnalysisObject.Member + [results] if(FreeCAD.GuiUp): import FemGui import FreeCADGui if FreeCADGui.activeWorkbench().name() != 'FemWorkbench': FreeCADGui.activateWorkbench("FemWorkbench") FemGui.setActiveAnalysis(AnalysisObject)
def setUp(self): self.Active = FreeCADGui.activeWorkbench() FreeCAD.Console.PrintLog(FreeCADGui.activeWorkbench().name())
def onSave(): """Save current workbench toolbars position.""" tb = mw.findChildren(QtGui.QToolBar) active = Gui.activeWorkbench().__class__.__name__ p = App.ParamGet("User parameter:BaseApp/PersistentToolbars") group = p.GetGroup(active) top = [] left = [] right = [] bottom = [] for i in tb: if i.objectName() and i.isVisible() and not i.isFloating(): area = mw.toolBarArea(i) x = i.geometry().x() y = i.geometry().y() b = mw.toolBarBreak(i) n = i.objectName() if area == QtCore.Qt.ToolBarArea.TopToolBarArea: top.append([x, y, b, n]) elif area == QtCore.Qt.ToolBarArea.LeftToolBarArea: left.append([x, y, b, n]) elif area == QtCore.Qt.ToolBarArea.RightToolBarArea: right.append([-x, y, b, n]) elif area == QtCore.Qt.ToolBarArea.BottomToolBarArea: bottom.append([x, -y, b, n]) else: pass else: pass top = sorted(top, key=operator.itemgetter(1, 0)) left = sorted(left, key=operator.itemgetter(0, 1)) right = sorted(right, key=operator.itemgetter(0, 1)) bottom = sorted(bottom, key=operator.itemgetter(1, 0)) topSave = [] leftSave = [] rightSave = [] bottomSave = [] for i in top: if i[2] is True: topSave.append("Break") topSave.append(i[3]) else: topSave.append(i[3]) for i in left: if i[2] is True: leftSave.append("Break") leftSave.append(i[3]) else: leftSave.append(i[3]) for i in right: if i[2] is True: rightSave.append("Break") rightSave.append(i[3]) else: rightSave.append(i[3]) for i in bottom: if i[2] is True: bottomSave.append("Break") bottomSave.append(i[3]) else: bottomSave.append(i[3]) group.SetBool("Saved", 1) group.SetString("Top", ",".join(topSave)) group.SetString("Left", ",".join(leftSave)) group.SetString("Right", ",".join(rightSave)) group.SetString("Bottom", ",".join(bottomSave))
def onWorkbench(): """Update shortcuts on workbench activated.""" workbench = Gui.activeWorkbench().__class__.__name__ update(workbench)