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

    # Deffered importing: We can only import the kraken modules after the
    # plugin has loaded, as it configures the python import paths on load.
    from kraken.core.objects.rig import Rig
    from kraken import plugins

    if rigFilePath == "" and si.Interactive is True:

        fileBrowser = XSIUIToolkit.FileBrowser
        fileBrowser.DialogTitle = "Select a Kraken Rig File"
        fileBrowser.InitialDirectory = si.ActiveProject3.Path
        fileBrowser.Filter = "Kraken Rig (*.krg)|*.krg||"
        fileBrowser.ShowOpen()

        fileName = fileBrowser.FilePathName
        if fileName != "":
            rigFilePath = fileName
        else:
            log("User Cancelled.", 4)
            return False

    elif rigFilePath == "" and si.Interactive is False:
        log("No rig file path specified in batch mode!", 2)
        return False

    guideRig = Rig()
    guideRig.loadRigDefinitionFile(rigFilePath)
    rigBuildData = guideRig.getRigBuildData()

    rig = Rig()
    rig.loadRigDefinition(rigBuildData)
    rig.setName(guideRig.getName().replace('_guide', ''))

    builtRig = None
    progressBar = None
    try:

        progressBar = XSIUIToolkit.ProgressBar
        progressBar.Caption = "Building Kraken Rig: " + rig.getName()
        progressBar.CancelEnabled = False
        progressBar.Visible = True

        builder = plugins.getBuilder()
        builtRig = builder.build(rig)

    finally:
        if progressBar is not None:
            progressBar.Visible = False

    return builtRig
Пример #2
0
def BuildKrakenRig_Execute(rigFilePath):

    # Deffered importing: We can only import the kraken modules after the
    # plugin has loaded, as it configures the python import paths on load.
    from kraken.core.objects.rig import Rig
    from kraken import plugins

    if rigFilePath == "" and si.Interactive is True:

        fileBrowser = XSIUIToolkit.FileBrowser
        fileBrowser.DialogTitle = "Select a Kraken Rig File"
        fileBrowser.InitialDirectory = si.ActiveProject3.Path
        fileBrowser.Filter = "Kraken Rig (*.krg)|*.krg||"
        fileBrowser.ShowOpen()

        fileName = fileBrowser.FilePathName
        if fileName != "":
             rigFilePath = fileName
        else:
            log("User Cancelled.", 4)
            return False

    elif rigFilePath == "" and si.Interactive is False:
        log("No rig file path specified in batch mode!", 2)
        return False

    guideRig = Rig()
    guideRig.loadRigDefinitionFile(rigFilePath)
    rigBuildData = guideRig.getRigBuildData()

    rig = Rig()
    rig.loadRigDefinition(rigBuildData)
    rig.setName(guideRig.getName().replace('_guide', ''))

    builtRig = None
    progressBar = None
    try:

        progressBar = XSIUIToolkit.ProgressBar
        progressBar.Caption = "Building Kraken Rig: " + rig.getName()
        progressBar.CancelEnabled = False
        progressBar.Visible = True

        builder = plugins.getBuilder()
        builtRig = builder.build(rig)

    finally:
        if progressBar is not None:
            progressBar.Visible = False

    return builtRig
Пример #3
0
def main():

    os.environ['KRAKEN_DCC'] = 'KL'

    options, args = argOpts()

    ks = KrakenSystem.getInstance()
    numConfigs = len(ks.registeredConfigs)

    if options.config:
        directory, file = os.path.split(options.config)
        filebase, ext = os.path.splitext(file)
        sys.path = [directory] + sys.path  # prepend
        exec("import " + filebase)

        if len(ks.registeredConfigs) > numConfigs:
            configName = next(reversed(ks.registeredConfigs))
            print ("Using config %s from %s" % (configName, options.config))
            ks.getConfigClass(configName).makeCurrent()

        else:
            print ("Failed to use config in %s" % options.config)
            exit()

    guideRig = Rig()
    guideRig.loadRigDefinitionFile(args[0])

    rig = Rig()
    rig.loadRigDefinition(guideRig.getRigBuildData())

    builder = plugins.getBuilder()
    builder.setOutputFolder(args[1])

    config = builder.getConfig()

    config.setMetaData('RigTitle', os.path.split(args[0])[1].partition('.')[0])
    if options.constants:
        config.setMetaData('UseRigConstants', True)
    if options.numframes:
        config.setMetaData('ProfilingFrames', options.numframes)
    if options.logfile:
        config.setMetaData('ProfilingLogFile', options.logfile)

    builder.build(rig)
Пример #4
0
def main():

    options, args = argOpts()

    ks = KrakenSystem.getInstance()
    numConfigs = len(ks.registeredConfigs)

    if options.config:
        directory, file = os.path.split(options.config)
        filebase, ext = os.path.splitext(file)
        sys.path = [directory] + sys.path  # prepend
        exec("import " + filebase)

        if len(ks.registeredConfigs) > numConfigs:
            configName = next(reversed(ks.registeredConfigs))
            print("Using config %s from %s" % (configName, options.config))
            ks.getConfigClass(configName).makeCurrent()

        else:
            print("Failed to use config in %s" % options.config)
            exit()

    guideRig = Rig()
    guideRig.loadRigDefinitionFile(args[0])

    rig = Rig()
    rig.loadRigDefinition(guideRig.getRigBuildData())

    builder = plugins.getBuilder()
    builder.setOutputFolder(args[1])

    config = builder.getConfig()

    config.setMetaData('RigTitle', os.path.split(args[0])[1].partition('.')[0])
    if options.constants:
        config.setMetaData('UseRigConstants', True)
    if options.numframes:
        config.setMetaData('ProfilingFrames', options.numframes)
    if options.logfile:
        config.setMetaData('ProfilingLogFile', options.logfile)
    if options.extensionname:
        config.setMetaData('RigTitle', options.extensionname)

    builder.build(rig)
Пример #5
0
def BuildKrakenGuide_Execute(rigFilePath):

    if rigFilePath == "" and si.Interactive is True:

        fileBrowser = XSIUIToolkit.FileBrowser
        fileBrowser.DialogTitle = "Select a Kraken Rig File"
        fileBrowser.InitialDirectory = si.ActiveProject3.Path
        fileBrowser.Filter = "Kraken Rig (*.krg)|*.krg||"
        fileBrowser.ShowOpen()

        fileName = fileBrowser.FilePathName
        if fileName != "":
            rigFilePath = fileName
        else:
            log("User Cancelled.", 4)
            return False

    elif rigFilePath == "" and si.Interactive is False:
        log("No rig file path specified in batch mode!", 2)
        return False

    guideRig = Rig()
    guideRig.loadRigDefinitionFile(rigFilePath)

    builtRig = None
    progressBar = None
    try:

        progressBar = XSIUIToolkit.ProgressBar
        progressBar.Caption = "Building Kraken Guide: " + guideRig.getName()
        progressBar.CancelEnabled = False
        progressBar.Visible = True

        builder = plugins.getBuilder()
        builtRig = builder.build(guideRig)

    finally:
        if progressBar is not None:
            progressBar.Visible = False

    return builtRig
Пример #6
0
import json
import os

from kraken import plugins
from kraken.core.objects.rig import Rig
from kraken_examples.bob_guide_data import bob_guide_data
from kraken.core.profiler import Profiler
from kraken.helpers.utility_methods import logHierarchy


Profiler.getInstance().push("bob_build")

bobGuideRig = Rig("char_bob")
bobGuideRig.loadRigDefinition(bob_guide_data)

bobGuideRig.writeRigDefinitionFile('bob_guide.krg')

bobGuideRig2 = Rig()
bobGuideRig2.loadRigDefinitionFile('bob_guide.krg')

logHierarchy(bobGuideRig2)

os.remove('bob_guide.krg')
Пример #7
0
class KGraphViewWidget(GraphViewWidget):

    rigNameChanged = QtCore.Signal()
    rigLoaded = QtCore.Signal(object)

    def __init__(self, parent=None):

        # constructors of base classes
        super(KGraphViewWidget, self).__init__(parent)

        self._builder = None
        self._guideBuilder = None

        graphView = KGraphView(parent=self)
        graphView.nodeAdded.connect(self.__onNodeAdded)
        graphView.nodeRemoved.connect(self.__onNodeRemoved)
        graphView.beginConnectionManipulation.connect(self.__onBeginConnectionManipulation)
        graphView.endConnectionManipulation.connect(self.__onEndConnectionManipulationSignal)
        graphView.connectionAdded.connect(self.__onConnectionAdded)
        graphView.connectionRemoved.connect(self.__onConnectionRemoved)

        graphView.selectionChanged.connect(self.__onSelectionChanged)
        graphView.endSelectionMoved.connect(self.__onSelectionMoved)

        graphView.beginDeleteSelection.connect(self.__onBeginDeleteSelection)
        graphView.endDeleteSelection.connect(self.__onEndDeleteSelection)

        self.setGraphView(graphView)

        # =========================================
        # Setup hotkeys for the following actions.
        # =========================================

        undoShortcut = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_Z), self)
        undoShortcut.activated.connect(self.undo)

        redoShortcut = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_Y), self)
        redoShortcut.activated.connect(self.redo)

        openContextualNodeListShortcut = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Tab), self)
        openContextualNodeListShortcut.activated.connect(self.openContextualNodeList)

        self.newRigPreset()


    # ============
    # Rig Methods
    # ============
    def editRigName(self):
        dialog = QtGui.QInputDialog(self)
        dialog.setObjectName('RigNameDialog')
        text, ok = dialog.getText(self, 'Edit Rig Name', 'New Rig Name', text=self.guideRig.getName())

        if ok is True:
            self.setGuideRigName(text)

    def setGuideRigName(self, text):
        if text.endswith('_guide') is True:
            text = text.replace('_guide', '')

        self.guideRig.setName(text)
        self.rigNameChanged.emit()

    def newRigPreset(self):
        try:
            self.guideRig = Rig()
            self.getGraphView().displayGraph(self.guideRig)
            self.setGuideRigName('MyRig')

            self.openedFile = None

            self.window().setWindowTitle('Kraken Editor')

            logger.inform("New Rig Created")
        except:
            logger.exception("Error Creating New Rig")

    def saveRig(self, saveAs=False):
        """Saves the current rig to disc.

        Args:
            saveAs (Boolean): Determines if this was a save as call or just a normal save.

        Returns:
            String: Path to the saved file.

        """

        try:
            self.window().setCursor(QtCore.Qt.WaitCursor)

            filePath = self.openedFile

            if saveAs is True or not filePath or not os.path.isdir(os.path.dirname(filePath)):

                settings = self.window().getSettings()
                settings.beginGroup('Files')
                lastFilePath = settings.value("lastFilePath", os.path.join(GetKrakenPath(), self.guideRig.getName()))
                settings.endGroup()

                filePathDir = os.path.dirname(lastFilePath)

                if not os.path.isdir(filePathDir):
                    filePathDir = GetKrakenPath()

                fileDialog = QtGui.QFileDialog(self)
                fileDialog.setOption(QtGui.QFileDialog.DontUseNativeDialog, on=True)
                fileDialog.setWindowTitle('Save Rig Preset As')
                fileDialog.setDirectory(os.path.abspath(filePathDir))
                fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
                fileDialog.setNameFilter('Kraken Rig (*.krg)')
                fileDialog.setDefaultSuffix('krg')

                if fileDialog.exec_() == QtGui.QFileDialog.Accepted:
                    filePath = fileDialog.selectedFiles()[0]
                else:
                    return False

            self.synchGuideRig()

            # Backdrop Meta Data
            graphView = self.getGraphView()
            backdropNodes = graphView.getNodesOfType('KBackdrop')
            backdropData = [x.getData() for x in backdropNodes]

            # Add Meta Data to rig
            self.guideRig.setMetaData('backdrops', backdropData)

            # Write rig file
            try:
                self.guideRig.writeRigDefinitionFile(filePath)
                settings = self.window().getSettings()
                settings.beginGroup('Files')
                settings.setValue("lastFilePath", filePath)
                settings.endGroup()
                self.openedFile = filePath

                logger.inform('Saved Rig file: ' + filePath)

            except:
                logger.exception('Error Saving Rig File')
                return False

            return filePath

        finally:
            self.window().setCursor(QtCore.Qt.ArrowCursor)

    def saveAsRigPreset(self):
        """Opens a dialogue window to save the current rig as a different file."""

        filePath = self.saveRig(saveAs=True)
        if filePath is not False:
            self.window().setWindowTitle('Kraken Editor - ' + filePath + '[*]')

        self.rigLoaded.emit(self.openedFile)

    def saveRigPreset(self):

        if self.openedFile is None or not os.path.exists(self.openedFile):
            self.saveAsRigPreset()

        else:
            self.saveRig(saveAs=False)
            self.rigLoaded.emit(self.openedFile)

    def openRigPreset(self):

        try:
            self.window().setCursor(QtCore.Qt.WaitCursor)

            settings = self.window().getSettings()
            settings.beginGroup('Files')
            lastFilePath = settings.value("lastFilePath", os.path.join(GetKrakenPath(), self.guideRig.getName()))
            settings.endGroup()

            if not lastFilePath:
                lastFilePath = GetKrakenPath()

            fileDialog = QtGui.QFileDialog(self)
            fileDialog.setOption(QtGui.QFileDialog.DontUseNativeDialog, on=True)
            fileDialog.setWindowTitle('Open Rig Preset')
            fileDialog.setDirectory(os.path.dirname(os.path.abspath(lastFilePath)))
            fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptOpen)
            fileDialog.setNameFilter('Kraken Rig (*.krg)')

            if fileDialog.exec_() == QtGui.QFileDialog.Accepted:
                filePath = fileDialog.selectedFiles()[0]
                self.loadRigPreset(filePath)

        finally:
            self.window().setCursor(QtCore.Qt.ArrowCursor)

    def loadRigPreset(self, filePath):

        if not os.path.exists(filePath):
            logger.warn("File '" + filePath + "' does not exist!")
            return

        self.guideRig = Rig()
        self.guideRig.loadRigDefinitionFile(filePath)
        self.setGuideRigName(self.guideRig.getName())  # Remove "_guide" from end of name
        self.graphView.displayGraph(self.guideRig)

        settings = self.window().getSettings()
        settings.beginGroup('Files')
        settings.setValue("lastFilePath", filePath)
        settings.endGroup()

        self.openedFile = filePath
        self.window().setWindowTitle('Kraken Editor - ' + filePath + '[*]')
        logger.inform('Loaded Rig file: ' + filePath)

        self.rigLoaded.emit(filePath)

    def buildGuideRig(self):

        try:
            logger.info('Building Guide')
            self.window().setCursor(QtCore.Qt.WaitCursor)

            # self.window().statusBar().showMessage('Building Guide')

            initConfigIndex = self.window().krakenMenu.configsWidget.currentIndex()


            # Append "_guide" to rig name when building guide
            if self.guideRig.getName().endswith('_guide') is False:
                self.guideRig.setName(self.guideRig.getName() + '_guide')

            if self.window().preferences.getPreferenceValue('delete_existing_rigs'):
                if self._guideBuilder:
                    self._guideBuilder.deleteBuildElements()

            self._guideBuilder = plugins.getBuilder()
            self._guideBuilder.build(self.guideRig)

            logger.inform('Guide Rig Build Success')

            self.window().krakenMenu.setCurrentConfig(initConfigIndex)

        except:
            logger.exception('Error Building')

        finally:
            self.window().setCursor(QtCore.Qt.ArrowCursor)

    def synchGuideRig(self):
        synchronizer = plugins.getSynchronizer()

        # Guide is always  built with "_guide" need this so synchronizer not confused with real Rig nodes
        if self.guideRig.getName().endswith('_guide') is False:
            self.guideRig.setName(self.guideRig.getName() + '_guide')

        synchronizer.setTarget(self.guideRig)
        synchronizer.sync()

    def buildRig(self):

        try:
            self.window().setCursor(QtCore.Qt.WaitCursor)

            self.window().statusBar.showMessage('Building Rig')

            initConfigIndex = self.window().krakenMenu.configsWidget.currentIndex()

            self.synchGuideRig()

            rigBuildData = self.guideRig.getRigBuildData()
            rig = Rig()
            rig.loadRigDefinition(rigBuildData)

            rig.setName(rig.getName().replace('_guide', ''))

            if self.window().preferences.getPreferenceValue('delete_existing_rigs'):
                if self._builder:
                    self._builder.deleteBuildElements()

            self._builder = plugins.getBuilder()
            self._builder.build(rig)

            logger.inform('Rig Build Success')

            self.window().krakenMenu.setCurrentConfig(initConfigIndex)

        except Exception as e:
            logger.exception('Error Building')

        finally:
            self.window().setCursor(QtCore.Qt.ArrowCursor)

    # ==========
    # Shortcuts
    # ==========
    def copy(self):
        graphView = self.getGraphView()
        pos = graphView.getSelectedNodesCentroid()
        graphView.copySettings(pos)

    def paste(self):
        graphView = self.getGraphView()
        clipboardData = self.graphView.getClipboardData()

        pos = clipboardData['copyPos'] + QtCore.QPoint(20, 20)
        graphView.pasteSettings(pos, mirrored=False, createConnectionsToExistingNodes=True)

    def pasteUnconnected(self):
        graphView = self.getGraphView()
        clipboardData = self.graphView.getClipboardData()

        pos = clipboardData['copyPos'] + QtCore.QPoint(20, 20)
        graphView.pasteSettings(pos, mirrored=False, createConnectionsToExistingNodes=False)

    def pasteMirrored(self):
        graphView = self.getGraphView()
        clipboardData = self.graphView.getClipboardData()

        pos = clipboardData['copyPos'] + QtCore.QPoint(20, 20)
        graphView.pasteSettings(pos, mirrored=True, createConnectionsToExistingNodes=False)

    def pasteMirroredConnected(self):
        graphView = self.getGraphView()
        clipboardData = self.graphView.getClipboardData()

        pos = clipboardData['copyPos'] + QtCore.QPoint(20, 20)
        graphView.pasteSettings(pos, mirrored=True, createConnectionsToExistingNodes=True)

    def undo(self):
        UndoRedoManager.getInstance().undo()

    def redo(self):
        UndoRedoManager.getInstance().redo()

    def openContextualNodeList(self):
        pos = self.mapFromGlobal(QtGui.QCursor.pos())

        contextualNodeList = ContextualNodeList(self)

        scenepos = self.graphView.mapToScene(pos)
        contextualNodeList.showAtPos(pos, scenepos, self.graphView)

    # ==============
    # Other Methods
    # ==============
    def addBackdrop(self, name='Backdrop'):
        """Adds a backdrop node to the graph.

        Args:
            name (str): Name of the backdrop node.

        Returns:
            Node: Backdrop node that was created.

        """

        graphView = self.getGraphView()

        initName = name
        suffix = 1
        collision = True
        while collision:

            collision = graphView.hasNode(name)
            if not collision:
                break

            result = re.split(r"(\d+)$", initName, 1)
            if len(result) > 1:
                initName = result[0]
                suffix = int(result[1])

            name = initName + str(suffix).zfill(2)
            suffix += 1

        backdropNode = KBackdrop(graphView, name)
        graphView.addNode(backdropNode)

        graphView.selectNode(backdropNode, clearSelection=True)

        return backdropNode

    # ===============
    # Signal Handlers
    # ===============
    def __onNodeAdded(self, node):
        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.AddNodeCommand(self.graphView, self.guideRig, node)
            UndoRedoManager.getInstance().addCommand(command)

    def __onNodeRemoved(self, node):

        if type(node).__name__ != 'KBackdrop':
            node.getComponent().detach()

        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.RemoveNodeCommand(self.graphView, self.guideRig, node)
            UndoRedoManager.getInstance().addCommand(command)

    def __onBeginConnectionManipulation(self):
        UndoRedoManager.getInstance().openBracket('Connect Ports')

    def __onEndConnectionManipulationSignal(self):
        UndoRedoManager.getInstance().closeBracket()

    def __onConnectionAdded(self, connection):
        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.ConnectionAddedCommand(self.graphView, self.guideRig, connection)
            UndoRedoManager.getInstance().addCommand(command)

    def __onConnectionRemoved(self, connection):
        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.ConnectionRemovedCommand(self.graphView, self.guideRig, connection)
            UndoRedoManager.getInstance().addCommand(command)

    def __onSelectionChanged(self, deselectedNodes, selectedNodes):
        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.SelectionChangeCommand(self.graphView, deselectedNodes, selectedNodes)
            UndoRedoManager.getInstance().addCommand(command)

    def __onSelectionMoved(self, nodes, delta):
        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.NodesMoveCommand(self.graphView, nodes, delta)
            UndoRedoManager.getInstance().addCommand(command)

    def __onBeginDeleteSelection(self):
        UndoRedoManager.getInstance().openBracket('Delete Nodes')

    def __onEndDeleteSelection(self):
        UndoRedoManager.getInstance().closeBracket()
Пример #8
0
import os
import sys

os.environ['KRAKEN_DCC'] = 'Canvas'

args = sys.argv[1:]
if len(args) != 2:
    print "\nPlease provide the rig file to convert and the target folder as command line arguments."
    exit(1)

from kraken import plugins
from kraken.core.objects.locator import Locator
from kraken.core.objects.rig import Rig

guideRig = Rig()
guideRig.loadRigDefinitionFile(args[0])

rig = Rig()
rig.loadRigDefinition(guideRig.getRigBuildData())

builder = plugins.getBuilder()
builder.setOutputFolder(args[1])

config = builder.getConfig()
config.setExplicitNaming(True)

config.setMetaData('RigTitle', os.path.split(args[0])[1].partition('.')[0])
config.setMetaData('SetupDebugDrawing', True)
config.setMetaData('CollapseComponents', False)
config.setMetaData('AddCollectJointsNode', True)
Пример #9
0
class KGraphViewWidget(GraphViewWidget):

    rigNameChanged = QtCore.Signal()
    rigLoaded = QtCore.Signal(object)

    def __init__(self, parent=None):

        # constructors of base classes
        super(KGraphViewWidget, self).__init__(parent)


        graphView = KGraphView(parent=self)
        graphView.nodeAdded.connect(self.__onNodeAdded)
        graphView.nodeRemoved.connect(self.__onNodeRemoved)
        graphView.beginConnectionManipulation.connect(self.__onBeginConnectionManipulation)
        graphView.endConnectionManipulation.connect(self.__onEndConnectionManipulationSignal)
        graphView.connectionAdded.connect(self.__onConnectionAdded)
        graphView.connectionRemoved.connect(self.__onConnectionRemoved)

        graphView.selectionChanged.connect(self.__onSelectionChanged)
        graphView.endSelectionMoved.connect(self.__onSelectionMoved)

        graphView.beginDeleteSelection.connect(self.__onBeginDeleteSelection)
        graphView.endDeleteSelection.connect(self.__onEndDeleteSelection)

        self.setGraphView(graphView)

        #########################
        ## Setup hotkeys for the following actions.

        undoShortcut = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_Z), self)
        undoShortcut.activated.connect(self.undo)

        redoShortcut = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_Y), self)
        redoShortcut.activated.connect(self.redo)

        openContextualNodeListShortcut = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Tab), self)
        openContextualNodeListShortcut.activated.connect(self.openContextualNodeList)

        self.newRigPreset()


    # ============
    # Rig Methods
    # ============
    def editRigName(self):
        dialog = QtGui.QInputDialog(self)
        dialog.setObjectName('RigNameDialog')
        text, ok = dialog.getText(self, 'Edit Rig Name', 'New Rig Name', text=self.guideRig.getName())

        if ok is True:
            self.setRigName(text)


    def setRigName(self, text):
        self.guideRig.setName(text)
        self.rigNameChanged.emit()


    def newRigPreset(self):
        self.guideRig = Rig()
        self.getGraphView().displayGraph(self.guideRig)
        self.setRigName('MyRig')

        self.openedFile = None

        self.window().setWindowTitle('Kraken Editor')


    def saveRig(self, saveAs=False):
        """Saves the current rig to disc.

        Args:
            saveAs (Boolean): Determines if this was a save as call or just a normal save.

        Returns:
            String: Path to the saved file.

        """

        try:
            self.window().setCursor(QtCore.Qt.WaitCursor)

            if self.openedFile is None:
                filePath = GetKrakenPath()
            else:
                settings = self.window().getSettings()
                settings.beginGroup('Files')
                filePath = settings.value("lastFilePath", os.path.join(GetKrakenPath(), self.guideRig.getName()))
                settings.endGroup()

            if saveAs is True:

                fileDialog = QtGui.QFileDialog(self)
                fileDialog.setOption(QtGui.QFileDialog.DontUseNativeDialog, on=True)
                fileDialog.setWindowTitle('Save Rig Preset As')
                fileDialog.setDirectory(os.path.abspath(filePath))
                fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
                fileDialog.setNameFilter('Kraken Rig (*.krg)')
                fileDialog.setDefaultSuffix('krg')

                if fileDialog.exec_() == QtGui.QFileDialog.Accepted:
                    filePath = fileDialog.selectedFiles()[0]
                else:
                    return False

            self.synchGuideRig()

            # Backdrop Meta Data
            graphView = self.getGraphView()
            backdropNodes = graphView.getNodesOfType('KBackdrop')
            backdropData = [x.getData() for x in backdropNodes]

            # Add Meta Data to rig
            self.guideRig.setMetaData('backdrops', backdropData)

            # Write rig file
            self.guideRig.writeRigDefinitionFile(filePath)

            settings = self.window().getSettings()
            settings.beginGroup('Files')
            settings.setValue("lastFilePath", filePath)
            settings.endGroup()

            self.openedFile = filePath

            self.reportMessage('Saved Rig file: ' + filePath, level='information')

            return filePath

        finally:
            self.window().setCursor(QtCore.Qt.ArrowCursor)


    def saveAsRigPreset(self):
        """Opens a dialogue window to save the current rig as a different file."""

        filePath = self.saveRig(saveAs=True)
        if filePath is not False:
            self.window().setWindowTitle('Kraken Editor - ' + filePath + '[*]')


    def saveRigPreset(self):

        if self.openedFile is None or not os.path.exists(self.openedFile):
            self.saveRig(saveAs=True)

        else:
            self.saveRig(saveAs=False)


    def openRigPreset(self):

        try:
            self.window().setCursor(QtCore.Qt.WaitCursor)

            settings = self.window().getSettings()
            settings.beginGroup('Files')
            lastFilePath = settings.value("lastFilePath", os.path.join(GetKrakenPath(), self.guideRig.getName()))
            settings.endGroup()

            fileDialog = QtGui.QFileDialog(self)
            fileDialog.setOption(QtGui.QFileDialog.DontUseNativeDialog, on=True)
            fileDialog.setWindowTitle('Open Rig Preset')
            fileDialog.setDirectory(os.path.dirname(os.path.abspath(lastFilePath)))
            fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptOpen)
            fileDialog.setNameFilter('Kraken Rig (*.krg)')

            if fileDialog.exec_() == QtGui.QFileDialog.Accepted:
                filePath = fileDialog.selectedFiles()[0]
                self.loadRigPreset(filePath)

        finally:
            self.window().setCursor(QtCore.Qt.ArrowCursor)

    def loadRigPreset(self, filePath):
        self.guideRig = Rig()
        self.guideRig.loadRigDefinitionFile(filePath)

        self.graphView.displayGraph(self.guideRig)

        settings = self.window().getSettings()
        settings.beginGroup('Files')
        settings.setValue("lastFilePath", filePath)
        settings.endGroup()

        self.openedFile = filePath
        self.window().setWindowTitle('Kraken Editor - ' + filePath + '[*]')
        self.reportMessage('Loaded Rig file: ' + filePath, level='information')

        self.rigLoaded.emit(filePath)

    def buildGuideRig(self):

        try:
            self.window().statusBar().showMessage('Building Guide')

            initConfigIndex = self.window().krakenMenu.configsWidget.currentIndex()

            builder = plugins.getBuilder()

            if self.guideRig.getName().endswith('_guide') is False:
                self.guideRig.setName(self.guideRig.getName() + '_guide')

            builder.build(self.guideRig)

            self.window().krakenMenu.setCurrentConfig(initConfigIndex)

        except Exception as e:
            # Add the callstak to the log
            callstack = traceback.format_exc()
            print callstack
            self.reportMessage('Error Building', level='error', exception=e)


    def synchGuideRig(self):
        synchronizer = plugins.getSynchronizer()
        synchronizer.setTarget(self.guideRig)
        synchronizer.sync()


    def buildRig(self):

        try:
            self.window().statusBar().showMessage('Building Rig')

            initConfigIndex = self.window().krakenMenu.configsWidget.currentIndex()

            self.synchGuideRig()

            rigBuildData = self.guideRig.getRigBuildData()
            rig = Rig()
            rig.loadRigDefinition(rigBuildData)

            rig.setName(rig.getName().replace('_guide', ''))

            builder = plugins.getBuilder()
            builder.build(rig)

            self.window().krakenMenu.setCurrentConfig(initConfigIndex)

        except Exception as e:
            # Add the callstak to the log
            callstack = traceback.format_exc()
            print callstack
            self.reportMessage('Error Building', level='error', exception=e)

    # ==========
    # Shortcuts
    # ==========
    def copy(self):
        graphView = self.getGraphView()
        pos = graphView.getSelectedNodesCentroid()
        graphView.copySettings(pos)


    def paste(self):
        graphView = self.getGraphView()
        clipboardData = self.graphView.getClipboardData()

        pos = clipboardData['copyPos'] + QtCore.QPoint(20, 20)
        graphView.pasteSettings(pos, mirrored=False, createConnectionsToExistingNodes=True)


    def pasteUnconnected(self):
        graphView = self.getGraphView()
        clipboardData = self.graphView.getClipboardData()

        pos = clipboardData['copyPos'] + QtCore.QPoint(20, 20)
        graphView.pasteSettings(pos, mirrored=False, createConnectionsToExistingNodes=False)


    def pasteMirrored(self):
        graphView = self.getGraphView()
        clipboardData = self.graphView.getClipboardData()

        pos = clipboardData['copyPos'] + QtCore.QPoint(20, 20)
        graphView.pasteSettings(pos, mirrored=True, createConnectionsToExistingNodes=False)


    def pasteMirroredConnected(self):
        graphView = self.getGraphView()
        clipboardData = self.graphView.getClipboardData()

        pos = clipboardData['copyPos'] + QtCore.QPoint(20, 20)
        graphView.pasteSettings(pos, mirrored=True, createConnectionsToExistingNodes=True)


    def undo(self):
        UndoRedoManager.getInstance().undo()

    def redo(self):
        UndoRedoManager.getInstance().redo()


    def openContextualNodeList(self):
        pos = self.mapFromGlobal(QtGui.QCursor.pos());

        contextualNodeList = ContextualNodeList(self)

        scenepos = self.graphView.mapToScene(pos)
        contextualNodeList.showAtPos(pos, scenepos, self.graphView)


    # ==============
    # Other Methods
    # ==============
    def addBackdrop(self, name='Backdrop'):
        """Adds a backdrop node to the graph.

        Args:
            name (str): Name of the backdrop node.

        Returns:
            Node: Backdrop node that was created.

        """

        graphView = self.getGraphView()

        initName = name
        suffix = 1
        collision = True
        while collision:

            collision = graphView.hasNode(name)
            if not collision:
                break

            result = re.split(r"(\d+)$", initName, 1)
            if len(result) > 1:
                initName = result[0]
                suffix = int(result[1])

            name = initName + str(suffix).zfill(2)
            suffix += 1

        backdropNode = KBackdrop(graphView, name)
        graphView.addNode(backdropNode)

        graphView.selectNode(backdropNode, clearSelection=True)

        return backdropNode

    # ==================
    # Message Reporting
    # ==================
    def reportMessage(self, message, level='error', exception=None):
        """Shows an error message in the status bar.

        Args:
            message (str): Message to display to the user.

        """

        statusBar = self.window().statusBar()

        if exception is not None:
            fullMessage = level[0].upper() + level[1:] + ": " + message + '; ' + ', '.join([x for x in exception.args])
        else:
            fullMessage = level[0].upper() + level[1:] + ": " + message

        messageLabel = QtGui.QLabel(fullMessage)

        print fullMessage

        messageColors = {
            'information': '#009900',
            'warning': '#CC3300',
            'error': '#AA0000'
        }

        if level not in messageColors.keys():
            level = 'error'

        messageLabel.setStyleSheet("QLabel { border-radius: 3px; background-color: " + messageColors[level] + "}")

        def addMessage():
            self.window().statusBar().clearMessage()

            statusBar.addWidget(messageLabel, 1)
            statusBar.repaint()

            timer.start()

        def endMessage():
            timer.stop()
            statusBar.removeWidget(messageLabel)
            statusBar.repaint()

            self.window().statusBar().showMessage('Ready', 2000)

        timer = QtCore.QTimer()
        timer.setInterval(3500)
        timer.timeout.connect(endMessage)

        addMessage()


    # ===============
    # Signal Handlers
    # ===============
    def __onNodeAdded(self, node):
        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.AddNodeCommand(self.graphView, self.guideRig, node)
            UndoRedoManager.getInstance().addCommand(command)


    def __onNodeRemoved(self, node):

        if type(node).__name__ != 'KBackdrop':
            node.getComponent().detach()

        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.RemoveNodeCommand(self.graphView, self.guideRig, node)
            UndoRedoManager.getInstance().addCommand(command)


    def __onBeginConnectionManipulation(self):
        UndoRedoManager.getInstance().openBracket('Connect Ports')


    def __onEndConnectionManipulationSignal(self):
        UndoRedoManager.getInstance().closeBracket()


    def __onConnectionAdded(self, connection):
        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.ConnectionAddedCommand(self.graphView, self.guideRig, connection)
            UndoRedoManager.getInstance().addCommand(command)


    def __onConnectionRemoved(self, connection):
        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.ConnectionRemovedCommand(self.graphView, self.guideRig, connection)
            UndoRedoManager.getInstance().addCommand(command)


    def __onSelectionChanged(self, deselectedNodes, selectedNodes):
        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.SelectionChangeCommand(self.graphView, deselectedNodes, selectedNodes)
            UndoRedoManager.getInstance().addCommand(command)


    def __onSelectionMoved(self, nodes, delta):
        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.NodesMoveCommand(self.graphView, nodes, delta)
            UndoRedoManager.getInstance().addCommand(command)


    def __onBeginDeleteSelection(self):
        UndoRedoManager.getInstance().openBracket('Delete Nodes')


    def __onEndDeleteSelection(self):
        UndoRedoManager.getInstance().closeBracket()
Пример #10
0
class KGraphViewWidget(GraphViewWidget):

    rigNameChanged = QtCore.Signal()

    def __init__(self, parent=None):

        # constructors of base classes
        super(KGraphViewWidget, self).__init__(parent)

        graphView = KGraphView(parent=self)
        graphView.nodeAdded.connect(self.__onNodeAdded)
        graphView.nodeRemoved.connect(self.__onNodeRemoved)
        graphView.beginConnectionManipulation.connect(
            self.__onBeginConnectionManipulation)
        graphView.endConnectionManipulation.connect(
            self.__onEndConnectionManipulationSignal)
        graphView.connectionAdded.connect(self.__onConnectionAdded)
        graphView.connectionRemoved.connect(self.__onConnectionRemoved)

        graphView.selectionChanged.connect(self.__onSelectionChanged)
        graphView.endSelectionMoved.connect(self.__onSelectionMoved)

        graphView.beginDeleteSelection.connect(self.__onBeginDeleteSelection)
        graphView.endDeleteSelection.connect(self.__onEndDeleteSelection)

        self.setGraphView(graphView)

        #########################
        ## Setup hotkeys for the following actions.

        undoShortcut = QtGui.QShortcut(
            QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_Z), self)
        undoShortcut.activated.connect(self.undo)

        redoShortcut = QtGui.QShortcut(
            QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_Y), self)
        redoShortcut.activated.connect(self.redo)

        openContextualNodeListShortcut = QtGui.QShortcut(
            QtGui.QKeySequence(QtCore.Qt.Key_QuoteLeft), self)
        openContextualNodeListShortcut.activated.connect(
            self.openContextualNodeList)

        self.newRigPreset()

    def editRigName(self):
        dialog = QtGui.QInputDialog(self)
        dialog.setObjectName('RigNameDialog')
        text, ok = dialog.getText(self,
                                  'Edit Rig Name',
                                  'New Rig Name',
                                  text=self.guideRig.getName())

        if ok is True:
            self.setRigName(text)

    def setRigName(self, text):
        self.guideRig.setName(text)
        self.rigNameChanged.emit()

    def newRigPreset(self):
        # TODO: clean the rig from the scene if it has been built.
        self.guideRig = Rig()
        self.getGraphView().displayGraph(self.guideRig)
        self.setRigName('MyRig')

    def saveRigPreset(self):
        settings = self.window().getSettings()
        settings.beginGroup('Files')
        lastFilePath = settings.value(
            "lastFilePath",
            os.path.join(GetKrakenPath(), self.guideRig.getName()))
        settings.endGroup()
        (filePath,
         filter) = QtGui.QFileDialog.getSaveFileName(self, 'Save Rig Preset',
                                                     lastFilePath,
                                                     'Kraken Rig (*.krg)')
        if len(filePath) > 0:
            self.synchGuideRig()
            self.guideRig.writeRigDefinitionFile(filePath)

            settings.beginGroup('Files')
            lastFilePath = settings.setValue("lastFilePath", filePath)
            settings.endGroup()

    def loadRigPreset(self):
        settings = self.window().getSettings()
        settings.beginGroup('Files')
        lastFilePath = settings.value(
            "lastFilePath",
            os.path.join(GetKrakenPath(), self.guideRig.getName()))
        settings.endGroup()
        (filePath,
         filter) = QtGui.QFileDialog.getOpenFileName(self, 'Load Rig Preset',
                                                     lastFilePath,
                                                     'Kraken Rig (*.krg)')
        if len(filePath) > 0:
            self.guideRig = Rig()
            self.guideRig.loadRigDefinitionFile(filePath)
            self.graphView.displayGraph(self.guideRig)
            # self.nameWidget.setText( self.guideRig.getName() )

            settings.beginGroup('Files')
            lastFilePath = settings.setValue("lastFilePath", filePath)
            settings.endGroup()

    def buildGuideRig(self):

        try:
            self.window().statusBar().showMessage('Building Guide')

            builder = plugins.getBuilder()

            if self.guideRig.getName().endswith('_guide') is False:
                self.guideRig.setName(self.guideRig.getName() + '_guide')

            builder.build(self.guideRig)

        except Exception as e:
            print traceback.format_exc()

            statusBar = self.window().statusBar()
            warningLabel = QtGui.QLabel('Error Building: ' +
                                        ', '.join([x for x in e.args]))
            warningLabel.setMaximumWidth(200)
            warningLabel.setStyleSheet(
                "QLabel { border-radius: 3px; background-color: #AA0000}")

            def addWarning():
                self.window().statusBar().clearMessage()

                statusBar.addWidget(warningLabel, 1)
                statusBar.repaint()

                timer.start()

            def endWarning():
                timer.stop()
                statusBar.removeWidget(warningLabel)
                statusBar.repaint()

                self.window().statusBar().showMessage('Ready', 2000)

            timer = QtCore.QTimer()
            timer.setInterval(2000)
            timer.timeout.connect(endWarning)

            addWarning()

    def synchGuideRig(self):
        synchronizer = plugins.getSynchronizer()
        synchronizer.setTarget(self.guideRig)
        synchronizer.sync()

    def buildRig(self):

        try:
            self.window().statusBar().showMessage('Building Rig')

            self.synchGuideRig()

            rigBuildData = self.guideRig.getRigBuildData()
            rig = Rig()
            rig.loadRigDefinition(rigBuildData)

            rig.setName(rig.getName().replace('_guide', ''))

            builder = plugins.getBuilder()
            builder.build(rig)

        except Exception as e:
            print traceback.format_exc()

            statusBar = self.window().statusBar()
            warningLabel = QtGui.QLabel('Error Building: ' +
                                        ', '.join([x for x in e.args]))
            warningLabel.setMaximumWidth(200)
            warningLabel.setStyleSheet(
                "QLabel { border-radius: 3px; background-color: #AA0000}")

            def addWarning():
                self.window().statusBar().clearMessage()

                statusBar.addWidget(warningLabel, 1)
                statusBar.repaint()

                timer.start()

            def endWarning():
                timer.stop()
                statusBar.removeWidget(warningLabel)
                statusBar.repaint()

                self.window().statusBar().showMessage('Ready', 2000)

            timer = QtCore.QTimer()
            timer.setInterval(2000)
            timer.timeout.connect(endWarning)

            addWarning()

    # =========
    # Shortcuts
    # =========
    def copy(self):
        graphView = self.getGraphView()
        pos = graphView.getSelectedNodesCentroid()
        graphView.copySettings(pos)

    def paste(self):
        graphView = self.getGraphView()
        clipboardData = self.graphView.getClipboardData()

        pos = clipboardData['copyPos'] + QtCore.QPoint(20, 20)
        graphView.pasteSettings(pos,
                                mirrored=False,
                                createConnectionsToExistingNodes=True)

    def pasteUnconnected(self):
        graphView = self.getGraphView()
        clipboardData = self.graphView.getClipboardData()

        pos = clipboardData['copyPos'] + QtCore.QPoint(20, 20)
        graphView.pasteSettings(pos,
                                mirrored=False,
                                createConnectionsToExistingNodes=False)

    def pasteMirrored(self):
        graphView = self.getGraphView()
        clipboardData = self.graphView.getClipboardData()

        pos = clipboardData['copyPos'] + QtCore.QPoint(20, 20)
        graphView.pasteSettings(pos,
                                mirrored=True,
                                createConnectionsToExistingNodes=False)

    def pasteMirroredConnected(self):
        graphView = self.getGraphView()
        clipboardData = self.graphView.getClipboardData()

        pos = clipboardData['copyPos'] + QtCore.QPoint(20, 20)
        graphView.pasteSettings(pos,
                                mirrored=True,
                                createConnectionsToExistingNodes=True)

    def undo(self):
        UndoRedoManager.getInstance().undo()

    def redo(self):
        UndoRedoManager.getInstance().redo()

    def openContextualNodeList(self):
        pos = self.mapFromGlobal(QtGui.QCursor.pos())

        contextualNodeList = ContextualNodeList(self)

        scenepos = self.graphView.mapToScene(pos)
        contextualNodeList.showAtPos(pos, scenepos, self.graphView)

    # ===============
    # Signal Handlers
    # ===============

    def __onNodeAdded(self, node):
        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.AddNodeCommand(self.graphView,
                                                    self.guideRig, node)
            UndoRedoManager.getInstance().addCommand(command)

    def __onNodeRemoved(self, node):
        node.getComponent().detach()

        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.RemoveNodeCommand(self.graphView,
                                                       self.guideRig, node)
            UndoRedoManager.getInstance().addCommand(command)

    def __onBeginConnectionManipulation(self):
        UndoRedoManager.getInstance().openBracket('Connect Ports')

    def __onEndConnectionManipulationSignal(self):
        UndoRedoManager.getInstance().closeBracket()

    def __onConnectionAdded(self, connection):
        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.ConnectionAddedCommand(
                self.graphView, self.guideRig, connection)
            UndoRedoManager.getInstance().addCommand(command)

    def __onConnectionRemoved(self, connection):
        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.ConnectionRemovedCommand(
                self.graphView, self.guideRig, connection)
            UndoRedoManager.getInstance().addCommand(command)

    def __onSelectionChanged(self, deselectedNodes, selectedNodes):
        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.SelectionChangeCommand(
                self.graphView, deselectedNodes, selectedNodes)
            UndoRedoManager.getInstance().addCommand(command)

    def __onSelectionMoved(self, nodes, delta):
        for node in nodes:
            node.pushGraphPosToComponent()

        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.NodesMoveCommand(self.graphView, nodes,
                                                      delta)
            UndoRedoManager.getInstance().addCommand(command)

    def __onBeginDeleteSelection(self):
        UndoRedoManager.getInstance().openBracket('Delete Nodes')

    def __onEndDeleteSelection(self):
        UndoRedoManager.getInstance().closeBracket()
Пример #11
0
class KGraphViewWidget(GraphViewWidget):

    rigNameChanged = QtCore.Signal()

    def __init__(self, parent=None):

        # constructors of base classes
        super(KGraphViewWidget, self).__init__(parent)


        graphView = KGraphView(parent=self)
        graphView.nodeAdded.connect(self.__onNodeAdded)
        graphView.nodeRemoved.connect(self.__onNodeRemoved)
        graphView.beginConnectionManipulation.connect(self.__onBeginConnectionManipulation)
        graphView.endConnectionManipulation.connect(self.__onEndConnectionManipulationSignal)
        graphView.connectionAdded.connect(self.__onConnectionAdded)
        graphView.connectionRemoved.connect(self.__onConnectionRemoved)

        graphView.selectionChanged.connect(self.__onSelectionChanged)
        graphView.endSelectionMoved.connect(self.__onSelectionMoved)

        graphView.beginDeleteSelection.connect(self.__onBeginDeleteSelection)
        graphView.endDeleteSelection.connect(self.__onEndDeleteSelection)

        self.setGraphView(graphView)

        #########################
        ## Setup hotkeys for the following actions.

        undoShortcut = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_Z), self)
        undoShortcut.activated.connect(self.undo)

        redoShortcut = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_Y), self)
        redoShortcut.activated.connect(self.redo)

        openContextualNodeListShortcut = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_QuoteLeft), self)
        openContextualNodeListShortcut.activated.connect(self.openContextualNodeList)

        self.newRigPreset()


    def editRigName(self):
        dialog = QtGui.QInputDialog(self)
        dialog.setObjectName('RigNameDialog')
        text, ok = dialog.getText(self, 'Edit Rig Name', 'New Rig Name', text=self.guideRig.getName())

        if ok is True:
            self.setRigName(text)


    def setRigName(self, text):
        self.guideRig.setName(text)
        self.rigNameChanged.emit()


    def newRigPreset(self):
        # TODO: clean the rig from the scene if it has been built.
        self.guideRig = Rig()
        self.getGraphView().displayGraph(self.guideRig)
        self.setRigName('MyRig')


    def saveRigPreset(self):
        settings = self.window().getSettings()
        settings.beginGroup('Files')
        lastFilePath = settings.value("lastFilePath", os.path.join(GetKrakenPath(), self.guideRig.getName() ))
        settings.endGroup()
        (filePath, filter) = QtGui.QFileDialog.getSaveFileName(self, 'Save Rig Preset', lastFilePath, 'Kraken Rig (*.krg)')
        if len(filePath) > 0:
            self.synchGuideRig()
            self.guideRig.writeRigDefinitionFile(filePath)

            settings.beginGroup('Files')
            lastFilePath = settings.setValue("lastFilePath", filePath)
            settings.endGroup()


    def loadRigPreset(self):
        settings = self.window().getSettings()
        settings.beginGroup('Files')
        lastFilePath = settings.value("lastFilePath", os.path.join(GetKrakenPath(), self.guideRig.getName() ))
        settings.endGroup()
        (filePath, filter) = QtGui.QFileDialog.getOpenFileName(self, 'Load Rig Preset', lastFilePath, 'Kraken Rig (*.krg)')
        if len(filePath) > 0:
            self.guideRig = Rig()
            self.guideRig.loadRigDefinitionFile(filePath)
            self.graphView.displayGraph( self.guideRig )
            # self.nameWidget.setText( self.guideRig.getName() )

            settings.beginGroup('Files')
            lastFilePath = settings.setValue("lastFilePath", filePath)
            settings.endGroup()


    def buildGuideRig(self):

        try:
            self.window().statusBar().showMessage('Building Guide')

            builder = plugins.getBuilder()

            if self.guideRig.getName().endswith('_guide') is False:
                self.guideRig.setName(self.guideRig.getName() + '_guide')

            builder.build(self.guideRig)

        except Exception as e:
            print traceback.format_exc()

            statusBar = self.window().statusBar()
            warningLabel = QtGui.QLabel('Error Building: ' + ', '.join([x for x in e.args]))
            warningLabel.setMaximumWidth(200)
            warningLabel.setStyleSheet("QLabel { border-radius: 3px; background-color: #AA0000}")

            def addWarning():
                self.window().statusBar().clearMessage()

                statusBar.addWidget(warningLabel, 1)
                statusBar.repaint()

                timer.start()

            def endWarning():
                timer.stop()
                statusBar.removeWidget(warningLabel)
                statusBar.repaint()

                self.window().statusBar().showMessage('Ready', 2000)

            timer = QtCore.QTimer()
            timer.setInterval(2000)
            timer.timeout.connect(endWarning)

            addWarning()


    def synchGuideRig(self):
        synchronizer = plugins.getSynchronizer()
        synchronizer.setTarget(self.guideRig)
        synchronizer.sync()


    def buildRig(self):

        try:
            self.window().statusBar().showMessage('Building Rig')

            self.synchGuideRig()

            rigBuildData = self.guideRig.getRigBuildData()
            rig = Rig()
            rig.loadRigDefinition(rigBuildData)

            rig.setName(rig.getName().replace('_guide', ''))

            builder = plugins.getBuilder()
            builder.build(rig)

        except Exception as e:
            print traceback.format_exc()

            statusBar = self.window().statusBar()
            warningLabel = QtGui.QLabel('Error Building: ' + ', '.join([x for x in e.args]))
            warningLabel.setMaximumWidth(200)
            warningLabel.setStyleSheet("QLabel { border-radius: 3px; background-color: #AA0000}")

            def addWarning():
                self.window().statusBar().clearMessage()

                statusBar.addWidget(warningLabel, 1)
                statusBar.repaint()

                timer.start()

            def endWarning():
                timer.stop()
                statusBar.removeWidget(warningLabel)
                statusBar.repaint()

                self.window().statusBar().showMessage('Ready', 2000)

            timer = QtCore.QTimer()
            timer.setInterval(2000)
            timer.timeout.connect(endWarning)

            addWarning()

    # =========
    # Shortcuts
    # =========
    def copy(self):
        graphView = self.getGraphView()
        pos = graphView.getSelectedNodesCentroid()
        graphView.copySettings(pos)


    def paste(self):
        graphView = self.getGraphView()
        clipboardData = self.graphView.getClipboardData()

        pos = clipboardData['copyPos'] + QtCore.QPoint(20, 20)
        graphView.pasteSettings(pos, mirrored=False, createConnectionsToExistingNodes=True)


    def pasteUnconnected(self):
        graphView = self.getGraphView()
        clipboardData = self.graphView.getClipboardData()

        pos = clipboardData['copyPos'] + QtCore.QPoint(20, 20)
        graphView.pasteSettings(pos, mirrored=False, createConnectionsToExistingNodes=False)


    def pasteMirrored(self):
        graphView = self.getGraphView()
        clipboardData = self.graphView.getClipboardData()

        pos = clipboardData['copyPos'] + QtCore.QPoint(20, 20)
        graphView.pasteSettings(pos, mirrored=True, createConnectionsToExistingNodes=False)


    def pasteMirroredConnected(self):
        graphView = self.getGraphView()
        clipboardData = self.graphView.getClipboardData()

        pos = clipboardData['copyPos'] + QtCore.QPoint(20, 20)
        graphView.pasteSettings(pos, mirrored=True, createConnectionsToExistingNodes=True)


    def undo(self):
        UndoRedoManager.getInstance().undo()

    def redo(self):
        UndoRedoManager.getInstance().redo()


    def openContextualNodeList(self):
        pos = self.mapFromGlobal(QtGui.QCursor.pos());

        contextualNodeList = ContextualNodeList(self)

        scenepos = self.graphView.mapToScene(pos)
        contextualNodeList.showAtPos(pos, scenepos, self.graphView)

    # ===============
    # Signal Handlers
    # ===============

    def __onNodeAdded(self, node):
        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.AddNodeCommand(self.graphView, self.guideRig, node)
            UndoRedoManager.getInstance().addCommand(command)


    def __onNodeRemoved(self, node):
        node.getComponent().detach()

        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.RemoveNodeCommand(self.graphView, self.guideRig, node)
            UndoRedoManager.getInstance().addCommand(command)


    def __onBeginConnectionManipulation(self):
        UndoRedoManager.getInstance().openBracket('Connect Ports')


    def __onEndConnectionManipulationSignal(self):
        UndoRedoManager.getInstance().closeBracket()


    def __onConnectionAdded(self, connection):
        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.ConnectionAddedCommand(self.graphView, self.guideRig, connection)
            UndoRedoManager.getInstance().addCommand(command)


    def __onConnectionRemoved(self, connection):
        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.ConnectionRemovedCommand(self.graphView, self.guideRig, connection)
            UndoRedoManager.getInstance().addCommand(command)


    def __onSelectionChanged(self, deselectedNodes, selectedNodes):
        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.SelectionChangeCommand(self.graphView, deselectedNodes, selectedNodes)
            UndoRedoManager.getInstance().addCommand(command)


    def __onSelectionMoved(self, nodes, delta):
        for node in nodes:
            node.pushGraphPosToComponent()

        if not UndoRedoManager.getInstance().isUndoingOrRedoing():
            command = graph_commands.NodesMoveCommand(self.graphView, nodes, delta)
            UndoRedoManager.getInstance().addCommand(command)


    def __onBeginDeleteSelection(self):
        UndoRedoManager.getInstance().openBracket('Delete Nodes')


    def __onEndDeleteSelection(self):
        UndoRedoManager.getInstance().closeBracket()