Esempio n. 1
0
    def Activated(self):
        # Grab our code editor so we can interact with it
        cqCodePane = Shared.getActiveCodePane()

        # If there is no script to check, ignore this command
        if cqCodePane is None:
            FreeCAD.Console.PrintMessage("There is no script to validate.")
            return

        # Clear the old render before re-rendering
        Shared.clearActiveDocument()

        scriptText = cqCodePane.toPlainText().encode('utf-8')

        if ("show_object(" not in scriptText and "# show_object(" in scriptText and "#show_boject(" in scriptText) or ("debug(" not in scriptText and "# debug(" in scriptText and "#debug(" in scriptText):
            FreeCAD.Console.PrintError("Script did not call show_object or debug, no output available. Script must be CQGI compliant to get build output, variable editing and validation.\r\n")
            return

        # A repreentation of the CQ script with all the metadata attached
        cqModel = cqgi.parse(scriptText)

        # Allows us to present parameters to users later that they can alter
        parameters = cqModel.metadata.parameters

        Shared.populateParameterEditor(parameters)
Esempio n. 2
0
    def Activated(self):
        mw = FreeCADGui.getMainWindow()

        # Grab our code editor so we can interact with it
        cqCodePane = Shared.getActiveCodePane()

        # If there's nothing open in the code pane, we don't need to close it
        if cqCodePane is None or len(cqCodePane.file.path) == 0:
            return

        # Check to see if we need to save the script
        if cqCodePane.dirty:
            reply = QtGui.QMessageBox.question(cqCodePane, "Save CadQuery Script", "Save script before closing?",
                                               QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Cancel)

            if reply == QtGui.QMessageBox.Cancel:
                return

            if reply == QtGui.QMessageBox.Yes:
                # If we've got a file name already save it there, otherwise give a save-as dialog
                if len(cqCodePane.file.path) == 0:
                    filename = QtGui.QFileDialog.getSaveFileName(mw, mw.tr("Save CadQuery Script As"), "/home/",
                                                                 mw.tr("CadQuery Files (*.py)"))
                else:
                    filename = cqCodePane.file.path

                # Make sure we got a valid file name
                if filename is not None:
                    ExportCQ.save(filename)

        Shared.closeActiveCodeWindow()
Esempio n. 3
0
    def Activated(self):
        # Grab our code editor so we can interact with it
        cqCodePane = Shared.getActiveCodePane()

        # If there are no windows open there is nothing to save
        if cqCodePane == None:
            FreeCAD.Console.PrintError("Nothing to save.\r\n")
            return

        # If the code pane doesn't have a filename, we need to present the save as dialog
        if len(cqCodePane.file.path) == 0 or os.path.basename(cqCodePane.file.path) == 'script_template.py' \
                or os.path.split(cqCodePane.file.path)[-2].endswith('Examples'):
            FreeCAD.Console.PrintError(
                "You cannot save over a blank file, example file or template file.\r\n"
            )

            CadQuerySaveAsScript().Activated()

            return

        # Rely on our export library to help us save the file
        ExportCQ.save()

        # Execute the script if the user has asked for it
        if Settings.execute_on_save:
            CadQueryExecuteScript().Activated()
Esempio n. 4
0
    def Activated(self):
        # So we can open the save-as dialog
        mw = FreeCADGui.getMainWindow()
        cqCodePane = Shared.getActiveCodePane()

        if cqCodePane == None:
            FreeCAD.Console.PrintError("Nothing to save.\r\n")
            return

        # Try to keep track of the previous path used to open as a convenience to the user
        if self.previousPath is None:
            self.previousPath = "/home/"

        filename = QtGui.QFileDialog.getSaveFileName(mw, mw.tr("Save CadQuery Script As"), self.previousPath,
                                                     mw.tr("CadQuery Files (*.py)"))

        self.previousPath = filename[0]

        # Make sure the user didn't click cancel
        if filename[0]:
            # Close the 3D view for the original script if it's open
            try:
                docname = os.path.splitext(os.path.basename(cqCodePane.file.path))[0]
                FreeCAD.closeDocument(docname)
            except:
                # Assume that there was no 3D view to close
                pass

            # Change the name of our script window's tab
            Shared.setActiveWindowTitle(os.path.basename(filename[0]))

            # Save the file before closing the original and the re-rendering the new one
            ExportCQ.save(filename[0])
            CadQueryExecuteScript().Activated()
Esempio n. 5
0
    def Activated(self):
        # Grab our code editor so we can interact with it
        cqCodePane = Shared.getActiveCodePane()

        # If there are no windows open there is nothing to save
        if cqCodePane == None:
            FreeCAD.Console.PrintError("Nothing to save.\r\n")
            return

        # If the code pane doesn't have a filename, we need to present the save as dialog
        if len(cqCodePane.get_path()) == 0 or os.path.basename(cqCodePane.get_path()) == 'script_template.py' \
                or os.path.split(cqCodePane.get_path())[0].endswith('FreeCAD'):
            FreeCAD.Console.PrintError(
                "You cannot save over a blank file, example file or template file.\r\n"
            )

            CadQuerySaveAsScript().Activated()

            return

        # Rely on our export library to help us save the file
        ExportCQ.save()

        # Execute the script if the user has asked for it
        if FreeCAD.ParamGet(
                "User parameter:BaseApp/Preferences/Mod/cadquery-freecad-module"
        ).GetBool("executeOnSave"):
            CadQueryExecuteScript().Activated()
    def Activated(self):
        mw = FreeCADGui.getMainWindow()

        # Grab our code editor so we can interact with it
        cqCodePane = Shared.getActiveCodePane()

        # If there's nothing open in the code pane, we don't need to close it
        if cqCodePane is None or len(cqCodePane.get_path()) == 0:
            return

        # Check to see if we need to save the script
        if cqCodePane.is_dirty():
            reply = QtGui.QMessageBox.question(cqCodePane, "Save CadQuery Script", "Save script before closing?",
                                               QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Cancel)

            if reply == QtGui.QMessageBox.Cancel:
                return

            if reply == QtGui.QMessageBox.Yes:
                # If we've got a file name already save it there, otherwise give a save-as dialog
                if len(cqCodePane.get_path()) == 0:
                    filename = QtGui.QFileDialog.getSaveFileName(mw, mw.tr("Save CadQuery Script As"), "/home/",
                                                                 mw.tr("CadQuery Files (*.py)"))
                else:
                    filename = cqCodePane.get_path()

                # Make sure we got a valid file name
                if filename is not None:
                    ExportCQ.save(filename)

        Shared.closeActiveCodeWindow()
    def Activated(self):
        # Grab our code editor so we can interact with it
        cqCodePane = Shared.getActiveCodePane()

        # If there is no script to check, ignore this command
        if cqCodePane is None:
            FreeCAD.Console.PrintMessage("There is no script to validate.")
            return

        # Clear the old render before re-rendering
        Shared.clearActiveDocument()

        scriptText = cqCodePane.toPlainText().encode('utf-8')

        if (b"show_object(" not in scriptText) and  (b"debug(" not in scriptText):
            FreeCAD.Console.PrintError("Script did not call show_object or debug, no output available. Script must be CQGI compliant to get build output, variable editing and validation.\r\n")
            return

        # A repreentation of the CQ script with all the metadata attached
        cqModel = cqgi.parse(scriptText)

        # Allows us to present parameters to users later that they can alter
        parameters = cqModel.metadata.parameters

        Shared.populateParameterEditor(parameters)
    def Activated(self):
        # So we can open the save-as dialog
        mw = FreeCADGui.getMainWindow()
        cqCodePane = Shared.getActiveCodePane()

        if cqCodePane == None:
            FreeCAD.Console.PrintError("Nothing to save.\r\n")
            return

        # Try to keep track of the previous path used to open as a convenience to the user
        if self.previousPath is None:
            self.previousPath = "/home/"

        filename = QtGui.QFileDialog.getSaveFileName(mw, mw.tr("Save CadQuery Script As"), self.previousPath,
                                                     mw.tr("CadQuery Files (*.py)"))

        self.previousPath = filename[0]

        # Make sure the user didn't click cancel
        if filename[0]:
            # Close the 3D view for the original script if it's open
            try:
                docname = os.path.splitext(os.path.basename(cqCodePane.get_path()))[0]
                FreeCAD.closeDocument(docname)
            except:
                # Assume that there was no 3D view to close
                pass

            # Change the name of our script window's tab
            Shared.setActiveWindowTitle(os.path.basename(filename[0]))

            # Save the file before closing the original and the re-rendering the new one
            ExportCQ.save(filename[0])
            CadQueryExecuteScript().Activated()
Esempio n. 9
0
def show(cqObject, rgba=(204, 204, 204, 0.0)):
    import FreeCAD
    from random import random
    import os, tempfile
    import Shared

    #Convert our rgba values
    r = rgba[0] / 255.0
    g = rgba[1] / 255.0
    b = rgba[2] / 255.0
    a = int(rgba[3] * 100.0)

    # Grab our code editor so we can interact with it
    cqCodePane = Shared.getActiveCodePane()

    if cqCodePane != None:
        # Save our code to a tempfile and render it
        tempFile = tempfile.NamedTemporaryFile(delete=False)
        tempFile.write(cqCodePane.toPlainText().encode('utf-8'))
        tempFile.close()

        docname = os.path.splitext(os.path.basename(cqCodePane.file.path))[0]

        # Make sure we replace any troublesome characters
        for ch in ['&', '#', '.', '$', '%', ',', ' ']:
            if ch in docname:
                docname = docname.replace(ch, "")

        # Translate dashes so that they can be safetly used since theyare common
        if '-' in docname:
            docname = docname.replace('-', "__")

        # If the matching 3D view has been closed, we need to open a new one
        try:
            FreeCAD.getDocument(docname)
        except NameError:
            # FreeCAD.Console.PrintError("Could not find the model document or invalid characters were used in the filename.\r\n")

            FreeCAD.newDocument(docname)

    ad = FreeCAD.activeDocument()

    # If we've got a blank shape name, we have to create a random ID
    if not cqObject.val().label:
        #Generate a random name for this shape in case we are doing multiple shapes
        newName = "Shape" + str(random())
    else:
        # We're going to trust the user to keep labels unique between shapes
        newName = cqObject.val().label

    #Set up the feature in the tree so we can manipulate its properties
    newFeature = ad.addObject("Part::Feature", newName)

    #Change our shape's properties accordingly
    newFeature.ViewObject.ShapeColor = (r, g, b)
    newFeature.ViewObject.Transparency = a
    newFeature.Shape = cqObject.toFreecad()

    ad.recompute()
Esempio n. 10
0
def save(filename=None):
    """
    Allows us to save the CQ script file to disk.
    :param filename: The path and file name to save to. If not provided we try to pull it from the code pane itself
    """

    #Grab our code editor so we can interact with it
    cqCodePane = Shared.getActiveCodePane()

    cqCodePane.save(filename)

    msg = QtGui.QApplication.translate(
            "cqCodeWidget",
            "Saved ",
            None)
    FreeCAD.Console.PrintMessage(msg + cqCodePane.get_path() + "\r\n")
Esempio n. 11
0
def save(filename=None):
    """
    Allows us to save the CQ script file to disk.
    :param filename: The path and file name to save to. If not provided we try to pull it from the code pane itself
    """

    #Grab our code editor so we can interact with it
    cqCodePane = Shared.getActiveCodePane()

    #If we weren't provided a file name, we need to find it from the text field
    if filename is None:
        cqCodePane.file.save()
    else:
        cqCodePane.file.save(filename)

    msg = QtGui.QApplication.translate("cqCodeWidget", "Saved ", None)
    FreeCAD.Console.PrintMessage(msg + cqCodePane.file.path + "\r\n")
Esempio n. 12
0
    def Activated(self):
        # Grab our code editor so we can interact with it
        cqCodePane = Shared.getActiveCodePane()

        # Clear the old render before re-rendering
        Shared.clearActiveDocument()

        # Save our code to a tempfile and render it
        tempFile = tempfile.NamedTemporaryFile(delete=False)
        tempFile.write(cqCodePane.toPlainText().encode('utf-8'))
        tempFile.close()

        # Set some environment variables that may help the user
        os.environ["MYSCRIPT_FULL_PATH"] = cqCodePane.file.path
        os.environ["MYSCRIPT_DIR"] = os.path.dirname(
            os.path.abspath(cqCodePane.file.path))

        # We import this way because using execfile() causes non-standard script execution in some situations
        imp.load_source('temp_module', tempFile.name)

        msg = QtGui.QApplication.translate("cqCodeWidget", "Executed ", None,
                                           QtGui.QApplication.UnicodeUTF8)
        FreeCAD.Console.PrintMessage(msg + cqCodePane.file.path + "\r\n")
Esempio n. 13
0
    def Activated(self):
        # Grab our code editor so we can interact with it
        cqCodePane = Shared.getActiveCodePane()

        # If there are no windows open there is nothing to save
        if cqCodePane == None:
            FreeCAD.Console.PrintError("Nothing to save.\r\n")
            return

        # If the code pane doesn't have a filename, we need to present the save as dialog
        if len(cqCodePane.get_path()) == 0 or os.path.basename(cqCodePane.get_path()) == 'script_template.py' \
                or os.path.split(cqCodePane.get_path())[0].endswith('FreeCAD'):
            FreeCAD.Console.PrintError("You cannot save over a blank file, example file or template file.\r\n")

            CadQuerySaveAsScript().Activated()

            return

        # Rely on our export library to help us save the file
        ExportCQ.save()

        # Execute the script if the user has asked for it
        if FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/cadquery-freecad-module").GetBool("executeOnSave"):
            CadQueryExecuteScript().Activated()
Esempio n. 14
0
    def Activated(self):
        # Grab our code editor so we can interact with it
        cqCodePane = Shared.getActiveCodePane()

        # Clear the old render before re-rendering
        Shared.clearActiveDocument()

        scriptText = cqCodePane.toPlainText().encode('utf-8')

        # Check to see if we are executig a CQGI compliant script
        if ("show_object(" in scriptText and "# show_object(" not in scriptText and "#show_boject(" not in scriptText) or ("debug(" in scriptText and "# debug(" not in scriptText and "#debug(" not in scriptText):
            FreeCAD.Console.PrintMessage("Executing CQGI-compliant script.\r\n")

            # A repreentation of the CQ script with all the metadata attached
            cqModel = cqgi.parse(scriptText)

            # Allows us to present parameters to users later that they can alter
            parameters = cqModel.metadata.parameters
            build_parameters = {}

            # Collect the build parameters from the Parameters Editor view, if they exist
            mw = FreeCADGui.getMainWindow()

            # Tracks whether or not we have already added the variables editor
            isPresent = False

            # If the widget is open, we need to close it
            dockWidgets = mw.findChildren(QtGui.QDockWidget)
            for widget in dockWidgets:
                if widget.objectName() == "cqVarsEditor":
                    # Toggle the visibility of the widget
                    if not widget.visibleRegion().isEmpty():
                        # Find all of the controls that will have parameter values in them
                        valueControls = mw.findChildren(QtGui.QLineEdit)
                        for valueControl in valueControls:
                            objectName = valueControl.objectName()

                            # We only want text fields that will have parameter values in them
                            if objectName != None and objectName != '' and objectName.find('pcontrol_') >= 0:
                                # Associate the value in the text field with the variable name in the script
                                build_parameters[objectName.replace('pcontrol_', '')] = valueControl.text()

            build_result = cqModel.build(build_parameters=build_parameters)

            if Settings.report_execute_time:
                FreeCAD.Console.PrintMessage("Script executed in " + str(build_result.buildTime) + " seconds\r\n")

            # Make sure that the build was successful
            if build_result.success:
                # Display all the results that the user requested
                for result in build_result.results:
                    # Apply options to the show function if any were provided
                    if result.options and result.options["rgba"]:
                        show(result.shape, result.options["rgba"])
                    else:
                        show(result.shape)

                for debugObj in build_result.debugObjects:
                    # Mark this as a debug object
                    debugObj.shape.val().label = "Debug" + str(random())

                    # Apply options to the show function if any were provided
                    if debugObj.options and debugObj.options["rgba"]:
                        show(debugObj.shape, debugObj.options["rgba"])
                    else:
                        show(debugObj.shape, (255, 0, 0, 0.80))
            else:
                FreeCAD.Console.PrintError("Error executing CQGI-compliant script. " + str(build_result.exception) + "\r\n")
        else:
            # Save our code to a tempfile and render it
            tempFile = tempfile.NamedTemporaryFile(delete=False)
            tempFile.write(scriptText)
            tempFile.close()

            # Set some environment variables that may help the user
            os.environ["MYSCRIPT_FULL_PATH"] = cqCodePane.file.path
            os.environ["MYSCRIPT_DIR"] = os.path.dirname(os.path.abspath(cqCodePane.file.path))

            # We import this way because using execfile() causes non-standard script execution in some situations
            with revert_sys_modules():
                imp.load_source('temp_module', tempFile.name)

        msg = QtGui.QApplication.translate(
            "cqCodeWidget",
            "Executed ",
            None)
        FreeCAD.Console.PrintMessage(msg + cqCodePane.file.path + "\r\n")
Esempio n. 15
0
    def Activated(self):
        # Grab our code editor so we can interact with it
        cqCodePane = Shared.getActiveCodePane()

        # Clear the old render before re-rendering
        Shared.clearActiveDocument()

        scriptText = cqCodePane.toPlainText().encode('utf-8')

        # Check to see if we are executig a CQGI compliant script
        if b"show_object(" in scriptText or b"debug(" in scriptText:
            FreeCAD.Console.PrintMessage("Executing CQGI-compliant script.\r\n")

            # A repreentation of the CQ script with all the metadata attached
            cqModel = cqgi.parse(scriptText)

            # Allows us to present parameters to users later that they can alter
            parameters = cqModel.metadata.parameters
            build_parameters = {}

            # Collect the build parameters from the Parameters Editor view, if they exist
            mw = FreeCADGui.getMainWindow()

            # Tracks whether or not we have already added the variables editor
            isPresent = False

            # If the widget is open, we need to close it
            dockWidgets = mw.findChildren(QtGui.QDockWidget)
            for widget in dockWidgets:
                if widget.objectName() == "cqVarsEditor":
                    # Toggle the visibility of the widget
                    if not widget.visibleRegion().isEmpty():
                        # Find all of the controls that will have parameter values in them
                        valueControls = mw.findChildren(QtGui.QLineEdit)
                        for valueControl in valueControls:
                            objectName = valueControl.objectName()

                            # We only want text fields that will have parameter values in them
                            if objectName != None and objectName != '' and objectName.find('pcontrol_') >= 0:
                                # Associate the value in the text field with the variable name in the script
                                build_parameters[objectName.replace('pcontrol_', '')] = valueControl.text()

            build_result = cqModel.build(build_parameters=build_parameters)

            # if Settings.report_execute_time:
            #     FreeCAD.Console.PrintMessage("Script executed in " + str(build_result.buildTime) + " seconds\r\n")

            # Make sure that the build was successful
            if build_result.success:
                # Display all the results that the user requested
                for result in build_result.results:
                    # Apply options to the show function if any were provided
                    if result.options and result.options["rgba"]:
                        show(result.shape, result.options["rgba"])
                    else:
                        show(result.shape)

                for debugObj in build_result.debugObjects:
                    # Mark this as a debug object
                    debugObj.shape.val().label = "Debug" + str(random())

                    # Apply options to the show function if any were provided
                    if debugObj.options and debugObj.options["rgba"]:
                        show(debugObj.shape, debugObj.options["rgba"])
                    else:
                        show(debugObj.shape, (255, 0, 0, 0.80))
            else:
                FreeCAD.Console.PrintError("Error executing CQGI-compliant script. " + str(build_result.exception) + "\r\n")
        else:
            # Save our code to a tempfile and render it
            tempFile = tempfile.NamedTemporaryFile(delete=False)
            tempFile.write(scriptText)
            tempFile.close()

            # Set some environment variables that may help the user
            os.environ["MYSCRIPT_FULL_PATH"] = cqCodePane.get_path()
            os.environ["MYSCRIPT_DIR"] = os.path.dirname(os.path.abspath(cqCodePane.get_path()))

            # We import this way because using execfile() causes non-standard script execution in some situations
            with revert_sys_modules():
                imp.load_source('__cq_freecad_module__', tempFile.name)

        msg = QtGui.QApplication.translate(
            "cqCodeWidget",
            "Executed ",
            None)
        FreeCAD.Console.PrintMessage(msg + cqCodePane.get_path() + "\r\n")