Пример #1
0
def getInstance():

    try:
        return FreeCAD.PF
    except:
        pass
    try:
        INITIALIZE()
    except:
        pass

    if 0:
        from PyFlow.App import PyFlow
        instance = PyFlow.instance(None, "standalone")
    else:
        from nodeeditor.freecad_pyflowapp import FreeCADPyFlow
        sayl("---------get FreeCADPyFlow-------------------")
        instance = FreeCADPyFlow.instance(None, "standalone")
        say(instance)

    t = instance.windowTitle()
    if not t.startswith("FreeCAD NodeEditor"):
        instance.setWindowTitle("FreeCAD NodeEditor v0.35 @ " +
                                instance.windowTitle())
        #instance.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)

    FreeCAD.PF = instance

    from PyFlow import (INITIALIZE, GET_PACKAGES)

    from PyFlow.Core import (GraphBase, PinBase, NodeBase, GraphManager)
    sayl("create instance")
    return instance
Пример #2
0
 def save(self, *args, **kwargs):
     try:
         data = {
             "name": self.nameEntry.text(),
             "color_count": int(self.colorEntry.text()),
             "mono_count": int(self.monoEntry.text()),
         }
         if self.depthPresent.isChecked():
             data.update({
                 "depth":
                 True,
                 "left_fov_deg":
                 float(self.leftfovEntry.text()),
                 "right_fov_deg":
                 float(self.rightfovEntry.text()),
                 "rgb_fov_deg":
                 float(self.rgbfovEntry.text()),
                 "left_to_right_distance_cm":
                 float(self.lrdistanceEntry.text()),
                 "left_to_rgb_distance_cm":
                 float(self.lrgbdistanceEntry.text()),
             })
         append_to_json(
             data,
             Path(__file__).parent.parent / Path('custom_devices.json'))
         self.close()
         INITIALIZE()
         self.instance.getRegisteredTools(['NodeBoxTool'])[0].refresh()
     except Exception as e:
         QMessageBox.warning(self, "Warning", str(e))
Пример #3
0
    def instance(parent=None):
        if PyFlow.appInstance is not None:
            return PyFlow.appInstance

        settings = ConfigManager().getSettings("APP_STATE")

        instance = PyFlow(parent)
        REGISTER_TOOL("PyFlowBase", LoggerTool)
        a = GET_TOOLS()["PyFlowBase"][0]()
        a.setAppInstance(instance)
        instance.registerToolInstance(a)
        instance.addDockWidget(a.defaultDockArea(), a)
        a.setAppInstance(instance)
        a.onShow()

        try:
            extraPackagePaths = []
            extraPathsString = ConfigManager().getPrefsValue(
                "PREFS", "General/ExtraPackageDirs")
            if extraPathsString is not None:
                extraPathsString = extraPathsString.rstrip(";")
                extraPathsRaw = extraPathsString.split(";")
                for rawPath in extraPathsRaw:
                    if os.path.exists(rawPath):
                        extraPackagePaths.append(os.path.normpath(rawPath))
            INITIALIZE(additionalPackageLocations=extraPackagePaths)
        except Exception as e:
            QMessageBox.critical(None, "Fatal error", str(e))
            return

        instance.startMainLoop()

        # populate tools
        canvas = instance.getCanvas()
        toolbar = instance.getToolbar()

        geo = settings.value('Editor/geometry')
        if geo is not None:
            instance.restoreGeometry(geo)
        state = settings.value('Editor/state')
        if state is not None:
            instance.restoreState(state)
        settings.beginGroup("Tools")
        for packageName, registeredToolSet in GET_TOOLS().items():
            for ToolClass in registeredToolSet:
                if issubclass(ToolClass, ShelfTool):
                    ToolInstance = ToolClass()
                    # prevent to be garbage collected
                    instance.registerToolInstance(ToolInstance)
                    ToolInstance.setAppInstance(instance)
                    action = QAction(instance)
                    action.setIcon(ToolInstance.getIcon())
                    action.setText(ToolInstance.name())
                    action.setToolTip(ToolInstance.toolTip())
                    action.setObjectName(ToolInstance.name())
                    action.triggered.connect(ToolInstance.do)
                    # check if context menu data available
                    menuBuilder = ToolInstance.contextMenuBuilder()
                    if menuBuilder:
                        menuGenerator = ContextMenuGenerator(menuBuilder)
                        menu = menuGenerator.generate()
                        action.setMenu(menu)
                    toolbar.addAction(action)

                    # step to ShelfTools/ToolName group and pass settings inside
                    settings.beginGroup("ShelfTools")
                    settings.beginGroup(ToolClass.name())
                    ToolInstance.restoreState(settings)
                    settings.endGroup()
                    settings.endGroup()

                if issubclass(ToolClass, DockTool):
                    menus = instance.menuBar.findChildren(QMenu)
                    pluginsMenuAction = [
                        m for m in menus if m.title() == "Plugins"
                    ][0].menuAction()
                    toolsMenu = getOrCreateMenu(instance.menuBar, "Tools")
                    instance.menuBar.insertMenu(pluginsMenuAction, toolsMenu)
                    packageSubMenu = getOrCreateMenu(toolsMenu, packageName)
                    toolsMenu.addMenu(packageSubMenu)
                    showToolAction = packageSubMenu.addAction(ToolClass.name())
                    icon = ToolClass.getIcon()
                    if icon:
                        showToolAction.setIcon(icon)
                    showToolAction.triggered.connect(
                        lambda pkgName=packageName, toolName=ToolClass.name(
                        ): instance.invokeDockToolByName(pkgName, toolName))

                    settings.beginGroup("DockTools")
                    childGroups = settings.childGroups()
                    for dockToolGroupName in childGroups:
                        # This dock tool data been saved on last shutdown
                        settings.beginGroup(dockToolGroupName)
                        if dockToolGroupName in [
                                t.uniqueName() for t in instance._tools
                        ]:
                            continue
                        toolName = dockToolGroupName.split("::")[0]
                        instance.invokeDockToolByName(packageName, toolName,
                                                      settings)
                        settings.endGroup()
                    settings.endGroup()

        PyFlow.appInstance = instance
        EditorHistory().saveState("New file")

        for name, package in GET_PACKAGES().items():
            prefsWidgets = package.PrefsWidgets()
            if prefsWidgets is not None:
                for categoryName, widgetClass in prefsWidgets.items():
                    PreferencesWindow().addCategory(categoryName,
                                                    widgetClass())
                PreferencesWindow().selectByName("General")

        return instance
Пример #4
0
    def instance(parent=None, software=""):
        assert (
            software != ""
        ), "Invalid arguments. Please pass you software name as second argument!"

        instance = PyFlow(parent)
        settings = ConfigManager().getSettings("APP_STATE")
        instance.currentSoftware = software
        SessionDescriptor().software = instance.currentSoftware

        if software == "standalone":
            editableStyleSheet(instance)

        try:
            extraPackagePaths = []
            extraPathsString = ConfigManager().getPrefsValue(
                "PREFS", "General/ExtraPackageDirs")
            if extraPathsString is not None:
                extraPathsString = extraPathsString.rstrip(";")
                extraPathsRaw = extraPathsString.split(";")
                for rawPath in extraPathsRaw:
                    if os.path.exists(rawPath):
                        extraPackagePaths.append(os.path.normpath(rawPath))
            INITIALIZE(additionalPackageLocations=extraPackagePaths,
                       software=software)
        except Exception as e:
            QMessageBox.critical(None, "Fatal error", str(e))
            return

        instance.startMainLoop()

        # populate tools
        canvas = instance.getCanvas()
        toolbar = instance.getToolbar()

        # populate menus
        instance.populateMenu()

        geo = settings.value('Editor/geometry')
        if geo is not None:
            instance.restoreGeometry(geo)
        state = settings.value('Editor/state')
        if state is not None:
            instance.restoreState(state)
        settings.beginGroup("Tools")
        for packageName, registeredToolSet in GET_TOOLS().items():
            for ToolClass in registeredToolSet:
                if issubclass(ToolClass, ShelfTool):
                    ToolInstance = ToolClass()
                    # prevent to be garbage collected
                    instance.registerToolInstance(ToolInstance)
                    ToolInstance.setAppInstance(instance)
                    action = QAction(instance)
                    action.setIcon(ToolInstance.getIcon())
                    action.setText(ToolInstance.name())
                    action.setToolTip(ToolInstance.toolTip())
                    action.setObjectName(ToolInstance.name())
                    action.triggered.connect(ToolInstance.do)
                    # check if context menu data available
                    menuBuilder = ToolInstance.contextMenuBuilder()
                    if menuBuilder:
                        menuGenerator = ContextMenuGenerator(menuBuilder)
                        menu = menuGenerator.generate()
                        action.setMenu(menu)
                    toolbar.addAction(action)

                    # step to ShelfTools/ToolName group and pass settings inside
                    settings.beginGroup("ShelfTools")
                    settings.beginGroup(ToolClass.name())
                    ToolInstance.restoreState(settings)
                    settings.endGroup()
                    settings.endGroup()

                if issubclass(ToolClass, DockTool):
                    menus = instance.menuBar.findChildren(QMenu)
                    pluginsMenuAction = [
                        m for m in menus if m.title() == "Plugins"
                    ][0].menuAction()
                    toolsMenu = getOrCreateMenu(instance.menuBar, "Tools")
                    instance.menuBar.insertMenu(pluginsMenuAction, toolsMenu)
                    packageSubMenu = getOrCreateMenu(toolsMenu, packageName)
                    toolsMenu.addMenu(packageSubMenu)
                    showToolAction = packageSubMenu.addAction(ToolClass.name())
                    icon = ToolClass.getIcon()
                    if icon:
                        showToolAction.setIcon(icon)
                    showToolAction.triggered.connect(
                        lambda pkgName=packageName, toolName=ToolClass.name(
                        ): instance.invokeDockToolByName(pkgName, toolName))

                    settings.beginGroup("DockTools")
                    childGroups = settings.childGroups()
                    for dockToolGroupName in childGroups:
                        # This dock tool data been saved on last shutdown
                        settings.beginGroup(dockToolGroupName)
                        if dockToolGroupName in [
                                t.uniqueName() for t in instance._tools
                        ]:
                            settings.endGroup()
                            continue
                        toolName = dockToolGroupName.split("::")[0]
                        instance.invokeDockToolByName(packageName, toolName,
                                                      settings)
                        settings.endGroup()
                    settings.endGroup()

        PyFlow.appInstance = instance
        EditorHistory().saveState("New file")

        for name, package in GET_PACKAGES().items():
            prefsWidgets = package.PrefsWidgets()
            if prefsWidgets is not None:
                for categoryName, widgetClass in prefsWidgets.items():
                    PreferencesWindow().addCategory(categoryName,
                                                    widgetClass())
                PreferencesWindow().selectByName("General")

        if ConfigManager().loadedDefaults:
            QMessageBox.information(
                None, "First-time tips",
                "Welcome to DepthAI GUI. To use this tool efficiently, please do the following:\n\n1. Maximize the window\n2. Enable NodeBox widget (Tools > PyFlowBase > NodeBox)\n3. Enable Properties widget (Tools > PyFlowBase > Properties)\n\nHave fun!"
            )
        return instance
Пример #5
0
def run(filePath):
    app = QApplication(sys.argv)
    app.setStyle(QStyleFactory.create("plastique"))
    app.setStyleSheet(editableStyleSheet().getStyleSheet())

    msg = QMessageBox()
    msg.setWindowIcon(QtGui.QIcon(":/LogoBpApp.png"))
    msg.setIcon(QMessageBox.Critical)

    if os.path.exists(filePath):
        with open(filePath, 'r') as f:
            data = json.load(f)

        # Window to display inputs
        prop = QDialog()
        prop.setLayout(QVBoxLayout())
        prop.setWindowTitle(filePath)
        prop.setWindowIcon(QtGui.QIcon(":/LogoBpApp.png"))

        # Initalize packages
        try:
            INITIALIZE()
            man = GraphManager()
            man.deserialize(data)
            grph = man.findRootGraph()
            inputs = grph.getNodesByClassName("graphInputs")

            # If no GraphInput Nodes Exit propgram
            if len(inputs) > 0:
                for inp in inputs:
                    uiNode = getUINodeInstance(inp)
                    uiNodeJsonTemplate = inp.serialize()
                    uiNodeJsonTemplate["wrapper"] = inp.wrapperJsonData
                    uiNode.postCreate(uiNodeJsonTemplate)
                    cat = uiNode.createOutputWidgets(prop.layout(), inp.name)
                    prop.show()

                def programLoop():
                    while True:
                        man.Tick(deltaTime=0.02)
                        time.sleep(0.02)
                        if man.terminationRequested:
                            break

                t = threading.Thread(target=programLoop)
                t.start()

                def quitEvent():
                    man.terminationRequested = True
                    t.join()

                app.aboutToQuit.connect(quitEvent)
            else:
                msg.setInformativeText(filePath)
                msg.setDetailedText(
                    "The file doesn't containt graphInputs nodes")
                msg.setWindowTitle("PyFlow Ui Graph Parser")
                msg.setStandardButtons(QMessageBox.Ok)
                msg.show()

        except Exception as e:
            msg.setText("Error reading Graph")
            msg.setInformativeText(filePath)
            msg.setDetailedText(str(e))
            msg.setWindowTitle("PyFlow Ui Graph Parser")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.show()

    else:
        msg.setText("File Not Found")
        msg.setInformativeText(filePath)
        msg.setWindowTitle("PyFlow Ui Graph Parser")
        msg.setStandardButtons(QMessageBox.Ok)
        msg.show()

    try:
        sys.exit(app.exec_())
    except Exception as e:
        print(e)
Пример #6
0
    def instance(parent=None):
        instance = PyFlow(parent)
        instance.startMainLoop()
        INITIALIZE()

        # create app folder in documents
        # random string used for cases when multiple instances of app are running in the same time
        prefs = QtCore.QSettings(ConfigManager().PREFERENCES_CONFIG_PATH,
                                 QtCore.QSettings.IniFormat)
        tempDirPath = prefs.value("Preferences/General/TempFilesDir")
        if tempDirPath == None:
            tempDirPath = "/tmp/pyflow"
        if tempDirPath[-1:] in ('/', '\\'):
            tempDirPath = tempDirPath[:-1]
        instance.currentTempDir = "{0}_{1}".format(tempDirPath,
                                                   generateRandomString())

        if not os.path.exists(instance.currentTempDir):
            os.makedirs(instance.currentTempDir)

        # populate tools
        canvas = instance.getCanvas()
        toolbar = instance.getToolbar()

        settings = QtCore.QSettings(ConfigManager().APP_SETTINGS_PATH,
                                    QtCore.QSettings.IniFormat)
        geo = settings.value('Editor/geometry')
        if geo is not None:
            instance.restoreGeometry(geo)
        state = settings.value('Editor/state')
        if state is not None:
            instance.restoreState(state)
        settings.beginGroup("Tools")
        for packageName, registeredToolSet in GET_TOOLS().items():
            for ToolClass in registeredToolSet:
                if issubclass(ToolClass, ShelfTool):
                    ToolInstance = ToolClass()
                    # prevent to be garbage collected
                    instance.registerToolInstance(ToolInstance)
                    ToolInstance.setCanvas(canvas)
                    action = QAction(instance)
                    action.setIcon(ToolInstance.getIcon())
                    action.setText(ToolInstance.name())
                    action.setToolTip(ToolInstance.toolTip())
                    action.setObjectName(ToolInstance.name())
                    action.triggered.connect(ToolInstance.do)
                    # check if context menu data available
                    menuBuilder = ToolInstance.contextMenuBuilder()
                    if menuBuilder:
                        menuGenerator = ContextMenuGenerator(menuBuilder)
                        menu = menuGenerator.generate()
                        action.setMenu(menu)
                    toolbar.addAction(action)

                    # step to ShelfTools/ToolName group and pass settings inside
                    settings.beginGroup("ShelfTools")
                    settings.beginGroup(ToolClass.name())
                    ToolInstance.restoreState(settings)
                    settings.endGroup()
                    settings.endGroup()

                if issubclass(ToolClass, DockTool):
                    menus = instance.menuBar.findChildren(QMenu)
                    helpMenuAction = [m for m in menus
                                      if m.title() == "Help"][0].menuAction()
                    toolsMenu = getOrCreateMenu(instance.menuBar, "Tools")
                    instance.menuBar.insertMenu(helpMenuAction, toolsMenu)
                    packageSubMenu = getOrCreateMenu(toolsMenu, packageName)
                    toolsMenu.addMenu(packageSubMenu)
                    showToolAction = packageSubMenu.addAction(ToolClass.name())
                    icon = ToolClass.getIcon()
                    if icon:
                        showToolAction.setIcon(icon)
                    showToolAction.triggered.connect(
                        lambda pkgName=packageName, toolName=ToolClass.name(
                        ): instance.invokeDockToolByName(pkgName, toolName))

                    settings.beginGroup("DockTools")
                    childGroups = settings.childGroups()
                    for dockToolGroupName in childGroups:
                        # This dock tool data been saved on last shutdown
                        settings.beginGroup(dockToolGroupName)
                        if dockToolGroupName in [
                                t.uniqueName() for t in instance._tools
                        ]:
                            continue
                        toolName = dockToolGroupName.split("::")[0]
                        ToolInstance = instance.invokeDockToolByName(
                            packageName, toolName, settings)
                        settings.endGroup()
                    settings.endGroup()

        return instance
Пример #7
0
        fpath = savepath

    if not fpath == '':
        with open(fpath, 'r') as f:
            data = json.load(f)
        # Window to display Inputs
        prop = QDialog()
        prop.setLayout(QVBoxLayout())
        prop.setWindowTitle(fpath)
        prop.setWindowIcon(QtGui.QIcon(":/LogoBpApp.png"))
        msg = QMessageBox()
        msg.setWindowIcon(QtGui.QIcon(":/LogoBpApp.png"))
        msg.setIcon(QMessageBox.Critical)
        # Initalize Packages
        try:
            INITIALIZE()
            man = GraphManager()
            man.deserialize(data)
            grph = man.findRootGraph()
            inputs = grph.getNodesByClassName("graphInputs")
            # If no GraphInput Nodes Exit propgram
            if len(inputs) > 0:
                for inp in inputs:
                    uiNode = getUINodeInstance(inp)
                    uiNodeJsonTemplate = inp.serialize()
                    uiNodeJsonTemplate["wrapper"] = inp.wrapperJsonData
                    uiNode.postCreate(uiNodeJsonTemplate)
                    cat = uiNode.createOutputWidgets(prop.layout(), inp.name)
                    prop.show()
            else:
                msg.setInformativeText(fpath)
def main():
    parser = argparse.ArgumentParser(description="PyFlow CLI")
    parser.add_argument("-m",
                        "--mode",
                        type=str,
                        default="edit",
                        choices=["edit", "run", "runui"])
    parser.add_argument("-f",
                        "--filePath",
                        type=str,
                        default="untitled.pygraph")
    parser.add_argument("--version",
                        action="version",
                        version=str(currentVersion()))
    parsedArguments, unknown = parser.parse_known_args(sys.argv[1:])

    filePath = parsedArguments.filePath

    if not filePath.endswith(".pygraph"):
        filePath += ".pygraph"

    if parsedArguments.mode == "edit":
        app = QApplication(sys.argv)

        instance = PyFlow.instance(software="standalone")
        if instance is not None:
            app.setActiveWindow(instance)
            instance.show()
            if os.path.exists(filePath):
                with open(filePath, 'r') as f:
                    data = json.load(f)
                    instance.loadFromData(data)
                    instance.currentFileName = filePath

            try:
                sys.exit(app.exec_())
            except Exception as e:
                print(e)

    if parsedArguments.mode == "run":
        data = None
        if not os.path.exists(filePath):
            print("No such file. {}".format(filePath))
            return
        with open(filePath, 'r') as f:
            data = json.load(f)
        getGraphArguments(data, parser)
        parsedArguments = parser.parse_args()

        # load updated data
        INITIALIZE()
        GM = GraphManagerSingleton().get()
        GM.deserialize(data)

        # fake main loop
        def programLoop():
            while True:
                GM.Tick(deltaTime=0.02)
                time.sleep(0.02)
                if GM.terminationRequested:
                    break

        # call graph inputs nodes
        root = GM.findRootGraph()
        graphInputNodes = root.getNodesList(classNameFilters=["graphInputs"])
        evalFunctions = []
        for graphInput in graphInputNodes:
            # update data
            for outPin in graphInput.outputs.values():
                if outPin.isExec():
                    evalFunctions.append(outPin.call)
                if hasattr(parsedArguments, outPin.name):
                    cliValue = getattr(parsedArguments, outPin.name)
                    if cliValue is not None:
                        outPin.setData(cliValue)

        for foo in evalFunctions:
            foo()

        loopThread = threading.Thread(target=programLoop)
        loopThread.start()
        loopThread.join()

    if parsedArguments.mode == "runui":
        graphUiParser.run(filePath)
Пример #9
0
    def instance(parent=None):
        instance = PyFlow(parent)
        instance.startMainLoop()
        INITIALIZE()

        # populate tools
        canvas = instance.getCanvas()
        toolbar = instance.getToolbar()

        settings = QtCore.QSettings(SETTINGS_PATH, QtCore.QSettings.IniFormat)
        instance.restoreGeometry(settings.value('Editor/geometry'))
        instance.restoreState(settings.value('Editor/state'))
        settings.beginGroup("Tools")
        for packageName, registeredToolSet in GET_TOOLS().items():
            for ToolClass in registeredToolSet:
                if issubclass(ToolClass, ShelfTool):
                    ToolInstance = ToolClass()
                    # prevent to be garbage collected
                    instance.registerToolInstance(ToolInstance)
                    ToolInstance.setCanvas(canvas)
                    action = QAction(instance)
                    action.setIcon(ToolInstance.getIcon())
                    action.setText(ToolInstance.name())
                    action.setToolTip(ToolInstance.toolTip())
                    action.setObjectName(ToolInstance.name())
                    action.triggered.connect(ToolInstance.do)
                    # check if context menu data available
                    menuBuilder = ToolInstance.contextMenuBuilder()
                    if menuBuilder:
                        menuGenerator = ContextMenuGenerator(menuBuilder)
                        menu = menuGenerator.generate()
                        action.setMenu(menu)
                    toolbar.addAction(action)

                    # step to ShelfTools/ToolName group and pass settings inside
                    settings.beginGroup("ShelfTools")
                    settings.beginGroup(ToolClass.name())
                    ToolInstance.restoreState(settings)
                    settings.endGroup()
                    settings.endGroup()

                if issubclass(ToolClass, DockTool):
                    menus = instance.menuBar.findChildren(QMenu)
                    helpMenuAction = [m for m in menus
                                      if m.title() == "Help"][0].menuAction()
                    toolsMenu = getOrCreateMenu(instance.menuBar, "Tools")
                    instance.menuBar.insertMenu(helpMenuAction, toolsMenu)
                    packageSubMenu = getOrCreateMenu(toolsMenu, packageName)
                    toolsMenu.addMenu(packageSubMenu)
                    showToolAction = packageSubMenu.addAction(ToolClass.name())
                    icon = ToolClass.getIcon()
                    if icon:
                        showToolAction.setIcon(icon)
                    showToolAction.triggered.connect(
                        lambda pkgName=packageName, toolName=ToolClass.name(
                        ): instance.invokeDockToolByName(pkgName, toolName))

                    settings.beginGroup("DockTools")
                    childGroups = settings.childGroups()
                    for dockToolGroupName in childGroups:
                        # This dock tool data been saved on last shutdown
                        settings.beginGroup(dockToolGroupName)
                        if dockToolGroupName in [
                                t.uniqueName() for t in instance._tools
                        ]:
                            continue
                        toolName = dockToolGroupName.split("::")[0]
                        ToolInstance = instance.invokeDockToolByName(
                            packageName, toolName, settings)
                        settings.endGroup()
                    settings.endGroup()
        return instance