def _runserver(handshake_port):
    sock = zmq.Context().socket(zmq.REP)
    appport = sock.bind_to_random_port('tcp://127.0.0.1')

    handshakesock = zmq.Context().socket(zmq.REQ)
    handshakesock.connect('tcp://127.0.0.1:%s' % handshake_port)
    handshakesock.send(str(appport))
    handshakesock.recv() # acknowledgement
    handshakesock.close()

    while True:
        recved = sock.recv()
        func, arg = json.loads(recved)
        try:
            code = mayaserver.SUCCESS
            response = None
            if func == 'exec':
                executeInMainThreadWithResult(_exec, arg)
            elif func == 'eval':
                response = executeInMainThreadWithResult(
                    _eval, arg)
            else:
                code =  mayaserver.INVALID_METHOD
                response = func
            pickled = json.dumps([code, response])
        except Exception:
            pickled = json.dumps([
                mayaserver.UNHANDLED_ERROR,
                ''.join(traceback.format_exc())])
        sock.send(pickled)
示例#2
0
    def set_collection(self, new_contents):
        current = set(self._Internal_Collection)
        incoming = set(new_contents)
        reordered = sum([x == y for x, y in zip(new_contents, self._Internal_Collection)])
        additions = incoming.difference(current)
        deletions = current.difference(incoming)

        def safe_create_gui():
            for d in deletions:
                del(self._Public_Collecton[d])
            for a in additions:
                templated = self.Conversion(a)
                self._Public_Collecton[a] = templated.Widget
                self.WidgetCreated(templated)

        utils.executeInMainThreadWithResult(safe_create_gui)

        self._Internal_Collection = new_contents

        if len(additions) + len(deletions):
            self.CollectionChanged(collection=self.Contents)
        else:
            if reordered:
                self.CollectionChanged(sorted=True, collection=self.Contents)
            else:
                self.CollectionChanged(why="idontknow")
示例#3
0
def _runserver(handshake_port):
    sock = zmq.Context().socket(zmq.REP)
    appport = sock.bind_to_random_port('tcp://127.0.0.1')

    handshakesock = zmq.Context().socket(zmq.REQ)
    handshakesock.connect('tcp://127.0.0.1:%s' % handshake_port)
    handshakesock.send(str(appport))
    handshakesock.recv()  # acknowledgement
    handshakesock.close()

    while True:
        recved = sock.recv()
        func, arg = json.loads(recved)
        try:
            code = mayaserver.SUCCESS
            response = None
            if func == 'exec':
                executeInMainThreadWithResult(_exec, arg)
            elif func == 'eval':
                response = executeInMainThreadWithResult(_eval, arg)
            else:
                code = mayaserver.INVALID_METHOD
                response = func
            pickled = json.dumps([code, response])
        except Exception:
            pickled = json.dumps(
                [mayaserver.UNHANDLED_ERROR, ''.join(traceback.format_exc())])
        sock.send(pickled)
 def _mainLoop():
     self.event.wait(self.interval)
     if not self.event.isSet():
         if executeInMainThreadWithResult:
             executeInMainThreadWithResult(self.function, *self.args,
                                           **self.kwargs)
         else:
             self.function(*self.args, **self.kwargs)
示例#5
0
def process_update(data):
    """
    Process incoming data, run this in the Maya main thread
    :param data:
    :return:
    """

    try:
        maya_utils.executeInMainThreadWithResult(function_to_process, data)
    except Exception as e:
        cmds.error("Debug Server, Exception processing Function: {}".format(e))
示例#6
0
    def on_identify_dcc(self, client):
        """!
        On Identify Dcc Action
        @param client SocketClient: Client Connection
        """
        exec_name = sys.executable.rsplit('\\', 1)[1]
        exec_name = exec_name.split('.')[0]

        data = "name = cmds.file(q=True, sn=True).split('/')[-1]\nname = name if len(name)>0 else 'unsaved'\nprint(json.dumps({'filename': name, 'exec_name': '" + exec_name + "'}, sort_keys=True, indent=4))"
        maya_utils.executeInMainThreadWithResult(self.function_to_process,
                                                 data, client)
 def _mainLoop():
     self.event.wait(self.interval)
     if not self.event.isSet():
         if mu.executeInMainThreadWithResult:
             try:
                 mu.executeInMainThreadWithResult(
                     self.function, *self.args, **self.kwargs)
             except Exception as e:
                 print '\n\texecuteInMainThreadWithResult cases error: "%s"' % e.message
                 print '\n\tstop thread!'
                 self.stop()
         else:
             self.function(*self.args, **self.kwargs)
示例#8
0
    def process_update(self, data, client):
        """!
        Process incoming data, run this in the Maya main thread
        @param data Json: Received Data
        @param client SocketClient: Client Connection
        """

        try:
            maya_utils.executeInMainThreadWithResult(self.function_to_process,
                                                     data, client)
        except Exception as e:
            cmds.error(
                "Maya Server, Exception processing Function: {}".format(e))
示例#9
0
def processDataInMaya(data):
    """
    This function is designed to be passed as the 'processFunc' arg of
    the mayaServer function.  It is mainly a try\except wrapper around the
    executeWingCode.main() function.

    data : string : The data passed from wing.  Currently this is 'python' or 'mel'.
    """
    try:
        # If we don't evaluate in maya.util.executeInMainThreadWithResult(),
        # Maya can crash, and that's no good.
        mu.executeInMainThreadWithResult(executeWingCode.main, data)
    except Exception, e:
        om.MGlobal.displayError("Encountered exception: %s"%e)
 def Doit(self, *args):
     self._tranDVBG = []
     mc.currentUnit(t="pal")  #设置帧率
     mc.playbackOptions(min=1, ast=1, max=25, aet=25)
     self._TranValue = float(mc.textFieldGrp(self._textFG, tx=True, q=True))
     if (self._TranValue > 0.01) & (self._TranValue <= 100.0):
         if self._dateFileName and self._dateFileName[-4::] == ".txt":
             if self._tranFileName:
                 self.GetMoveList()
                 #print self._tranDVBG
             mu.executeInMainThreadWithResult(self.CreateAni)
         else:
             mc.confirmDialog(title=u"提示", message=u'请选择采集数据的txt文件!')
     else:
         mc.confirmDialog(title=u"提示", message=u'输入的间距值在0到10之前!\n请重新输入')
示例#11
0
def sendAlembic(target_clientID, sender, tabTarget):
    
    result = mUtils.executeInMainThreadWithResult(_exportAlembic)
    if not result:
        return False
    
    fileName = result[0]
    filePath = result[1]
    frameRange = result[2]
    
    with open(filePath, 'rb') as f:
        data = f.read()
        
    outData = {}
    outData["TYPE"] = "alembic_cache"
    outData["NAME"] = fileName
    outData["FRAME_RANGE"] = frameRange
    outData["DATA"] = data
    
    try:   
        os.remove(filePath)
    except:
        pass
    
    result = _sendData(target_clientID, sender, outData, "alembic", tabTarget)
    
    return result
示例#12
0
def sendObjMesh(target_clientID, sender, tabTarget):
    
    meshOut = {}
    meshOut["MESH_TYPE"] = ".obj"
    
    meshName, objtmp = mUtils.executeInMainThreadWithResult(_exportObj)
    
    if not meshName:
        return False
    
    if not objtmp:
        return False

    with open(objtmp, 'rb') as f:
        meshOut["MESH_DATA"] = f.read()
    
    try:   
        os.remove(objtmp)
    except:
        pass
    
    meshOut["MESH_TYPE"] = ".obj"
    meshOut["MESH_NAME"] = meshName
    
    result = _sendData(target_clientID, sender, meshOut, "mesh", tabTarget)
    
    return result
示例#13
0
def processCommandsInMaya(MayaCmd):
    try:
        res = mu.executeInMainThreadWithResult(MayaCmd)
        print('result:%s'%res)
        return res
    except Exception as e:
        om.MGlobal.displayError('Encountered exception: %s' %e)
示例#14
0
def sendAlembic(target_clientID, sender, tabTarget):

    result = mUtils.executeInMainThreadWithResult(_exportAlembic)
    if not result:
        return False

    fileName = result[0]
    filePath = result[1]
    frameRange = result[2]

    with open(filePath, 'rb') as f:
        data = f.read()

    outData = {}
    outData["TYPE"] = "alembic_cache"
    outData["NAME"] = fileName
    outData["FRAME_RANGE"] = frameRange
    outData["DATA"] = data

    try:
        os.remove(filePath)
    except:
        pass

    result = _sendData(target_clientID, sender, outData, "alembic", tabTarget)

    return result
示例#15
0
def sendObjMesh(target_clientID, sender, tabTarget):

    meshOut = {}
    meshOut["MESH_TYPE"] = ".obj"

    meshName, objtmp = mUtils.executeInMainThreadWithResult(_exportObj)

    if not meshName:
        return False

    if not objtmp:
        return False

    with open(objtmp, 'rb') as f:
        meshOut["MESH_DATA"] = f.read()

    try:
        os.remove(objtmp)
    except:
        pass

    meshOut["MESH_TYPE"] = ".obj"
    meshOut["MESH_NAME"] = meshName

    result = _sendData(target_clientID, sender, meshOut, "mesh", tabTarget)

    return result
示例#16
0
def createAlembic(data, sender = "", settings=None):
    
    name = data["NAME"]
    binary = data["DATA"]

    abcFile = fetchMyReceivedFilesFolder() + os.sep + name + ".abc"
    abcFile = incrementFile(abcFile)

    with open(abcFile, 'wb') as f:
        f.write(binary)
        
    try:
        mUtils.executeInMainThreadWithResult(lambda: cmds.AbcImport(fetchMyReceivedFilesFolder() + os.sep + name + ".abc"))
        return True
    except AttributeError:
        print("ERROR: ALEMBIC PLUGIN NOT LOADED")
        return False
示例#17
0
def archive(mayaFile, todo, settings):
    comment = todo["label"]
    amp = settings.get("AMPArchive.active", False)
    if amp and mayaFile:
        if Mutils.executeInMainThreadWithResult(lambda: AMPArchive().archive(mayaFile, comment)):
            print "Checking file into AMP."
        else:
            print "Couldn't check in file to AMP."
示例#18
0
    def handle(self):
        # Called to handle each connection request

        try:
            # if we are echoing output, we hold on to the first request
            # and poll the socket for pending command messages.
            # Otherwise, we just block on the socket.
            if self.server.echoOutput:
                self.request.settimeout(1.5)
            while not self.server.die:
                # check for pending command messages
                if self.server.echoOutput:
                    while not self.server.commandMessageQueue.empty():
                        self.wfile.write(
                            self.server.commandMessageQueue.get() +
                            self.resp_term)
                # set self.data to be the incoming message
                try:
                    self.data = self.receiveData()
                except socket.timeout:
                    continue
                if self.data is None:
                    break
                # check if we need to display the security warning
                # posting the dialog also has to be done in the gui thread
                if self.server.securityWarning:
                    utils.executeInMainThreadWithResult(
                        self.postSecurityWarning)
                    if self.dialog_result is False:
                        self.wfile.write(maya.stringTable[
                            'y_CommandPort.kExecutionDeniedByMaya'] +
                                         self.resp_term)
                        return
                    elif self.dialog_result is True:
                        self.server.securityWarning = False

                # execute the message
                response = utils.executeInMainThreadWithResult(
                    self._languageExecute)

                # write the command responses to the client
                self.wfile.write(response)
        except socket.error:
            # a socket exception is a normal way to terminate the connection
            pass
 def copyMap(self):
     #generate authorStr and uuid
     _uuidList = []
     for i in range(0, self.count):
         uuid = mu.executeInMainThreadWithResult(self.doInMain, i)
         _uuidList.append(uuid[0])
         self.progress.emit(i + 1)
     self.uuidList.emit(_uuidList)
     self.finished.emit()
示例#20
0
def createAlembic(data, sender="", settings=None):

    name = data["NAME"]
    binary = data["DATA"]

    abcFile = fetchMyReceivedFilesFolder() + os.sep + name + ".abc"
    abcFile = incrementFile(abcFile)

    with open(abcFile, 'wb') as f:
        f.write(binary)

    try:
        mUtils.executeInMainThreadWithResult(lambda: cmds.AbcImport(
            fetchMyReceivedFilesFolder() + os.sep + name + ".abc"))
        return True
    except AttributeError:
        print("ERROR: ALEMBIC PLUGIN NOT LOADED")
        return False
示例#21
0
 def runArchive(s, todo, filename):
     if s.data.get(s.settingName, False) and _version_:
         path = os.path.realpath(filename)
         if path and os.path.isfile(path):
             comment = todo.label
             if Mutils.executeInMainThreadWithResult(lambda: AMPArchive().archive(mayaFile, comment)):
                 print "Checking file into AMP."
             else:
                 print "Couldn't check in file to AMP."
示例#22
0
def createOtl(data, sender="", settings=None):

    nodeType = data["OTL_TYPE"]
    subOtlLibs = data["OTL_ALL_LIBS"]

    libPath = None
    otlToAdd = None

    # Check otl libs
    if subOtlLibs:

        for e in subOtlLibs:
            libName = e[0]
            libData = e[1]

            otlLibToInstall = str(fetchMyReceivedFilesFolder() +
                                  os.sep).replace("\\", "/") + libName

            with open(otlLibToInstall, 'wb') as f:
                f.write(libData)

            libs = mel.eval('houdiniAsset -listAssets "' + otlLibToInstall +
                            '"')
            if libs:
                for lib in libs:
                    if nodeType in str(lib):
                        libPath = otlLibToInstall
                        otlToAdd = lib

    if libPath and otlToAdd:
        melcmd = 'houdiniAsset -loadAsset "' + libPath + '" "' + otlToAdd + '"'

        try:
            mUtils.executeInMainThreadWithResult(lambda: mel.eval(melcmd))
            return True
        except Exception as e:
            print str(e)
            return False

    else:
        print("ERROR: Incoming object is not a valid digital asset")
        return None
示例#23
0
def sendData():
    cmds.progressWindow(isInterruptable=1)
    ser = serial.Serial(serialPort, baudRate, timeout=0.5)
    while 1:
        if cmds.progressWindow(query=1, isCancelled=1):
            ser.close()
            break
        data = utils.executeInMainThreadWithResult(getCurrentData)
        ser.write("<" + data + ">")
        time.sleep(sendRate)
    cmds.progressWindow(endProgress=1)
示例#24
0
def createOtl(data, sender="", settings=None):
        
    
    nodeType = data["OTL_TYPE"]
    subOtlLibs = data["OTL_ALL_LIBS"]
    
    libPath = None
    otlToAdd = None
    
    # Check otl libs
    if subOtlLibs:
        
        for e in subOtlLibs:
            libName = e[0]
            libData = e[1]
            
            otlLibToInstall = str(fetchMyReceivedFilesFolder() + os.sep).replace("\\","/") + libName
            
            with open(otlLibToInstall, 'wb') as f:
                f.write(libData)
                
            libs = mel.eval('houdiniAsset -listAssets "' + otlLibToInstall + '"')
            if libs:
                for lib in libs:
                    if nodeType in str(lib):
                        libPath = otlLibToInstall
                        otlToAdd = lib
    
    if libPath and otlToAdd:
        melcmd = 'houdiniAsset -loadAsset "' + libPath + '" "' + otlToAdd + '"'
        
        try:
            mUtils.executeInMainThreadWithResult(lambda: mel.eval(melcmd))
            return True
        except Exception as e:
            print str(e)
            return False

    else:
        print("ERROR: Incoming object is not a valid digital asset")
        return None
示例#25
0
def createMesh(data, sender="", settings=None):
    
    meshType = data["MESH_TYPE"]    
    if meshType != ".obj":
        print("ERROR: Mesh type not supported (" + meshType + ")")
        return False
    
    meshName = data["MESH_NAME"]
    meshData = data["MESH_DATA"]
    
    obj = fetchMyReceivedFilesFolder() + os.sep + meshName + meshType
    obj = incrementFile(obj)
    with open(obj, 'wb') as f:
        f.write(meshData)
    
    try:
        mUtils.executeInMainThreadWithResult(lambda: cmds.file(obj,i=True,dns=True))
        return True
    except Exception as e:
        print str(e)
        return False
示例#26
0
    def _routeMessageImpl(self, data):

        result = None
        if data.kind == DataKindEnum.MEL_SCRIPT:
            result = mu.executeInMainThreadWithResult(runMelExec, data.payload['script'])
        elif data.kind == DataKindEnum.PYTHON_SCRIPT:
            result = mu.executeInMainThreadWithResult(
                runPythonExec,
                data.payload['script'],
                data.payload['kwargs'])
        elif data.kind == DataKindEnum.MAYA_COMMAND:
            result = mu.executeInMainThreadWithResult(
                self._executeMayaCommand,
                data.payload)
        elif data.kind == DataKindEnum.MAYA_COMMAND_BATCH:
            result = mu.executeInMainThreadWithResult(
                self._executeMayaCommandBatch,
                data.payload)
        elif data.kind == DataKindEnum.COMMAND:
            result = mu.executeInMainThreadWithResult(
                self._executeCommand,
                data.payload)
        elif data.kind == DataKindEnum.PYTHON_SCRIPT_FILE:
            result = mu.executeInMainThreadWithResult(
                self._runPythonFile,
                data.payload)

        if result:
            if isinstance(result, NimbleResponseData):
                return result
            return self._createReply(data.kind, result)

        return None
def get_input(connection, qImage, size, progress_bar):
    #load qImage handling different input types
    connection_type = pm.objectType(connection)
    if connection_type == "file":
        #get file path
        texture_file = connection.fileTextureName.get()
        qImage.load(texture_file)
        #scale to size
        qImage = mu.executeInMainThreadWithResult(scale_down, qImage, size)
        #get repeat UV values from 2DPlacement node
        repeatU = connection.repeatU.get()
        repeatV = connection.repeatV.get()
        print(repeatU, size, repeatV)
        print("Scale started...")
        #scale QImage to be repeated according to repeat UV values
        qImage = mu.executeInMainThreadWithResult(scale_tile, qImage, repeatU,
                                                  repeatV)
        #qImage.save(Coat.project_dir + "/sourceimages/test.png", "PNG",-1)
        update_progress(progress_bar)
        print("Scale end")
        return [qImage, texture_file]
    if connection_type == "ramp":
        #make ramp
        make_ramp(connection, qImage)
        #get repeat UV values from 2DPlacement node
        repeatU = connection.repeatU.get()
        repeatV = connection.repeatV.get()
        print("Scale started...")
        #scale QImage to be repeated according to repeat UV values
        qImage = mu.executeInMainThreadWithResult(scale_tile, qImage, repeatU,
                                                  repeatV)
        update_progress(progress_bar)
        print("Scale end")
        return [qImage, connection]
    if connection_type == "colorConstant":
        #get color
        color = connection.inColor.get()
        qImage.fill(
            QtGui.QColor(color[0] * 255, color[1] * 255, color[2] * 255))
        return [qImage, str(color)]
示例#28
0
    def handle(self):
        # Called to handle each connection request

        try:
            # if we are echoing output, we hold on to the first request
            # and poll the socket and for pending command messages.
            # Otherwise, we just block on the socket.
            if self.server.echoOutput:
                self.request.settimeout(1.5)
            while not self.server.die:
                # check for pending command messages
                if self.server.echoOutput:
                    while not self.server.commandMessageQueue.empty():
                        self.wfile.write(self.server.commandMessageQueue.get() + self.resp_term)
                # set self.data to be the incoming message
                try:
                    self.data = self.recieveData()
                except socket.timeout:
                    continue
                if self.data is None: 
                    break
                # check if we need to display the security warning
                # posting the dialog also has to be done in the gui thread
                if self.server.securityWarning:
                    utils.executeInMainThreadWithResult(self.postSecurityWarning)
                    if self.dialog_result is False:
                        self.wfile.write(maya.stringTable['y_CommandPort.kExecutionDeniedByMaya' ] + self.resp_term)
                        return
                    elif self.dialog_result is True:
                        self.server.securityWarning = False

                # execute the message
                response = utils.executeInMainThreadWithResult(self._languageExecute)

                # write the command responses to the client
                self.wfile.write(response)
        except socket.error:
            # a socket exception is a normal way to terminate the connection
            pass
示例#29
0
def createMesh(data, sender="", settings=None):

    meshType = data["MESH_TYPE"]
    if meshType != ".obj":
        print("ERROR: Mesh type not supported (" + meshType + ")")
        return False

    meshName = data["MESH_NAME"]
    meshData = data["MESH_DATA"]

    obj = fetchMyReceivedFilesFolder() + os.sep + meshName + meshType
    obj = incrementFile(obj)
    with open(obj, 'wb') as f:
        f.write(meshData)

    try:
        mUtils.executeInMainThreadWithResult(
            lambda: cmds.file(obj, i=True, dns=True))
        return True
    except Exception as e:
        print str(e)
        return False
示例#30
0
    def readInput(self):
        '''
        Get the input from the UI class and start the timer or screenshot/playblast commands

        '''

        # get Values from UI
        everyFrame, everyTime_dropdwn = self.getEveryTimer()
        stopStyle, stopFrames = self.getStopStyle()
        renderStyle = self.getRenderStyle()

        # check if the output directory is set and the camera is selected
        if self.checkSaveLocation(
        ) and UI.assignCam_dropdwn.currentText() != 'none':

            # check if we need to enable the timer.
            # renderStyle == 1 is Log every x sec/min/hour
            if renderStyle == 1:

                # create new timer
                timerVal = threading.Timer(everyFrame, self.readInput)

                # check if: it is OK to start the timer or if we need to stop it and
                # if the number of frames in after x frames is more or equal than 3.
                if (stopStyle == 0 and (everyFrame >= 3) and
                    (self.currentFrame >= stopFrames)
                    ) or not self.renderActive:
                    self.startTimer(False, timerVal)
                else:
                    self.startTimer(True, timerVal)

            if renderStyle == 0 or (renderStyle == 1 and self.renderActive):
                # execute the render command / playblast in the mainThread in Maya.
                ut.executeInMainThreadWithResult(self.renderScreen)

            if not self.renderActive or renderStyle == 0:
                self.autoPackFrames(UI.exportPack_dropdwn.currentText(),
                                    UI.exportFps_edit.text())
示例#31
0
 def makeTx(self, texture):
     cmd = 'maketx';
     cmd += ' -o "' + os.path.splitext(texture)[0] + '.tx"'
     
     # Custom options
     ctrlPath = '|'.join([self.txManager.window, 'groupBox_2', 'lineEdit']);
     cmd += ' '+utils.executeInMainThreadWithResult(cmds.textField, ctrlPath, query=True, text=True);
     
     cmd += ' "'+texture+'"'
     #print cmd
     if os.name == 'nt':
         proc = subprocess.Popen(cmd, creationflags=subprocess.SW_HIDE, shell=True)
     else:
         proc = subprocess.Popen(cmd, shell=True)
     return proc.wait()
示例#32
0
def serverHandler(request):
    def mainThreadHandler(request):
        try:
            launch(**request)
            return {'result': 'success'}
        except Exception as e:
            import traceback
            traceback.print_exc()
            #return {'result':'exception','exception': str(e)base64.b64encode(pickle.dumps(e, pickle.HIGHEST_PROTOCOL)).encode("utf-8"),'stackTrace':traceback.format_exc()}
            return {
                'result': 'exception',
                'exception': str(e),
                'stackTrace': traceback.format_exc()
            }

    from maya.utils import executeInMainThreadWithResult
    result = executeInMainThreadWithResult(mainThreadHandler, request)
    return result
示例#33
0
    def processRequest(cls, data):
        result = None
        if data.kind == DataKindEnum.MEL_SCRIPT:
            result = mu.executeInMainThreadWithResult(runMelExec, data.payload["script"])
        elif data.kind == DataKindEnum.PYTHON_SCRIPT:
            result = mu.executeInMainThreadWithResult(runPythonExec, data.payload["script"], data.payload["kwargs"])
        elif data.kind == DataKindEnum.MAYA_COMMAND:
            result = mu.executeInMainThreadWithResult(cls._executeMayaCommand, data.payload)
        elif data.kind == DataKindEnum.MAYA_COMMAND_BATCH:
            result = mu.executeInMainThreadWithResult(cls._executeMayaCommandBatch, data.payload)
        elif data.kind == DataKindEnum.COMMAND:
            result = mu.executeInMainThreadWithResult(cls._executeCommand, data.payload)
        elif data.kind == DataKindEnum.PYTHON_SCRIPT_FILE:
            result = mu.executeInMainThreadWithResult(cls._runPythonFile, data.payload)
        elif data.kind == DataKindEnum.PYTHON_IMPORT:
            result = mu.executeInMainThreadWithResult(cls.runPythonImport, data.payload)

        if result:
            if isinstance(result, NimbleResponseData):
                return result
            return cls.createReply(data.kind, result)

        return None
    def run(self):
        #Create an input socket on an open port
        HOSTin = ''                 # Symbolic name meaning all available interfaces
        PORTin = self.get_open_port()              # Arbitrary non-privileged port
        self.sockIn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sockIn.bind((HOSTin, PORTin))
        self.sockIn.listen(1)
        repo = CallDeadlineCommand(["-GetRepositoryRoot"]).rstrip()
        
        #in the main thread get a screen shot
        screenshot = utils.executeInMainThreadWithResult(self.getScreenshot)
        info = screenshot.split("=")
        #if the screenshot exists then continue else create the failed message and return
        draftPath = repo+os.sep+"draft"
        if len(info) == 1:
            utils.executeInMainThreadWithResult(self.failedScreenshot)
            return
        
        deadlineCommand = GetDeadlineCommand()
        deadlineBin = os.path.dirname( deadlineCommand )
        
        if platform.system() == "Linux":
            if not deadlineBin == "":
                newLDPath = os.path.join(deadlineBin,"python","lib")+os.pathsep+draftPath
                if "LD_LIBRARY_PATH" in os.environ:
                    newLDPath = newLDPath + os.pathsep + os.environ["LD_LIBRARY_PATH"]
                os.environ["LD_LIBRARY_PATH"] = newLDPath
        elif platform.system() == "Darwin":
            if not deadlineBin == "":
                draftPath = os.path.join(draftPath,"Mac")
                newDYLDPath = os.path.join(deadlineBin,"python","lib")+os.pathsep+draftPath
                if "DYLD_LIBRARY_PATH" in os.environ:
                    newDYLDPath = newDYLDPath + os.pathsep + os.environ["DYLD_LIBRARY_PATH"]

                os.environ["DYLD_LIBRARY_PATH"] = newDYLDPath
            
        #Get deadlinecommand to execute a script and pass in a screenshot and the port to connect to.
        CallDeadlineCommand(["-executescript",repo+os.sep+"submission"+os.sep+"Jigsaw"+os.sep+"Jigsaw.py",str(PORTin),info[1]], False, False)
        
        conn, addr = self.sockIn.accept()
        #wait to receive the a message with the port in which to connect to for outgoing messages
        data = recvData(conn)
        if not data:
            #If we do not get one return
            conn.close()
            return
        HostOut = 'localhost'
        PORTout = int(data)
        self.sockOut = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sockOut.connect((HostOut, PORTout))
        #constantly listen 
        while 1:
            data = recvData(conn)
            #if we do not get data then exit
            if not data:
                break
            #otherwise split the data on =
            command = str(data).split("=")
            #if we got the command exit then break out of the loop
            if command[0].lower() == "exit":
                break
            #if we were told to get the screenshot then retrieve a screenshot and send it to the jigsaw ui
            elif command[0].lower() == "getscreenshot":
                screenshot = utils.executeInMainThreadWithResult(self.getScreenshot)
                if(not screenshot):
                    cmds.confirmDialog(title="No Background", message="Unable to get background. Make sure that the viewport is selected.");
                    self.closeJigsaw()
                else:
                    self.sockOut.sendall(screenshot+"\n")
            #When we are told to fit the region
            elif command[0].lower() == "getselected":
                mode = 0#Vertex
                padding = 0 #percentage based padding
                if len(command)>1:
                    arguments=command[1].split(";")
                    arguments[0].split()
                    if arguments[0].lower() == "tight":
                        mode = 0#vertex
                    elif arguments[0].lower() == "loose":
                        mode = 1#boundingbox
                    padding = float(arguments[1])
                regions = self.getSelectedBoundingRegion(mode, padding)
                regionMessage = ""
                for region in regions:
                    if not regionMessage == "":
                        regionMessage+=";"
                    first = True
                    for val in region:
                        if not first:
                            regionMessage+=","
                        regionMessage += str(val)
                        first = False
                self.sockOut.sendall("create="+regionMessage+"\n")
            #when told to save the regions save them to the scene
            elif command[0].lower() == "saveregions":
                if not len(command)>1:
                    utils.executeInMainThreadWithResult(self.saveRegions, "")
                else:
                    utils.executeInMainThreadWithResult(self.saveRegions, command[1])
            #when told to load the regions send the regions back to Jigsaw 
            elif command[0].lower() == "loadregions":
                self.sockOut.sendall("loadregions="+utils.executeInMainThreadWithResult(self.loadRegions)+"\n")
            
        conn.close()
        try:
            os.remove(self.tempFile)
        except:
            pass
def add_coat(blend_material, coat_number, size, res_colorQImage,
             res_bumpQImage, res_opacityQImage, progress_bar):
    #initialize coat
    current_coat = Coat(blend_material, coat_number, size)
    coat_material = current_coat.get_material()
    print("coat " + str(coat_number) + " --------------")
    print("name: " + coat_material[0])
    #get color or file and store in coat colorQImage
    if coat_material:
        is_supported = get_color_or_inputs(coat_material[0], current_coat,
                                           size, progress_bar)
        #warn and skip layer if material type is not supported
        if (is_supported == False):
            warning_msg("Material type on coat " + str(coat_number) + " (" +
                        coat_material[0] +
                        ") is not supported.\nSkipping layer")
            return True
        if (is_supported == None):  #slot_material is blend
            return False  #exit current add_coat
        else:
            #get matte
            matte = pm.listConnections(blend_material + '.blend_amount_' +
                                       str(coat_number))
            if (matte):
                get_input_connection_by_type(matte[0], current_coat, size,
                                             "matte", progress_bar)
                #check transparency and bump
                is_coat_transparent = current_coat.get_isTransparent()
                coat_has_bump = current_coat.get_hasBump()
                #fill opacity map
                if (is_coat_transparent):
                    #if transparent fill with 50% gray
                    current_coat.get_opacityQImage().fill(
                        QtGui.QColor(128, 128, 128))
                else:
                    #if not transparent fill with white
                    current_coat.get_opacityQImage().fill(
                        QtGui.QColor(255, 255, 255))
                if (not coat_has_bump):
                    #if coat doesn't have bump, fill with 50% gray fo height map or neutral blue for normal map
                    if (Coat.bump_is_normal):
                        current_coat.get_bumpQImage().fill(
                            QtGui.QColor(128, 128, 255))
                    else:
                        current_coat.get_bumpQImage().fill(
                            QtGui.QColor(128, 128, 128))

                matteQImage = current_coat.get_matteQImage()
                '''#repeat matte tile if matte repeat uv is not the same as color tile
                if(matteTile.width(),current_coat.get_colorQImage().width()):
                    matteQImage =  QtGui.QImage(size, size, QtGui.QImage.Format_RGB32)
                    mu.executeInMainThreadWithResult( comp_coat_base, matteTile, matteQImage)
                else:
                    matteQImage = current_coat.get_matteQImage()'''

                #matteQImage.save(Coat.project_dir + "/sourceimages/" + blend_material + "_matte_"+str(coat_number)+".png", "PNG",-1)
                #mask coat color, bump and opacity with coat matte
                print("set matte on coat...")
                mu.executeInMainThreadWithResult(
                    set_alpha, current_coat.get_colorQImage(), matteQImage)
                mu.executeInMainThreadWithResult(set_alpha,
                                                 current_coat.get_bumpQImage(),
                                                 matteQImage)
                mu.executeInMainThreadWithResult(
                    set_alpha, current_coat.get_opacityQImage(), matteQImage)
                #composite coat over base image
                update_progress(progress_bar)
                mu.executeInMainThreadWithResult(
                    comp_coat_base, current_coat.get_colorQImage(),
                    res_colorQImage)
                mu.executeInMainThreadWithResult(comp_coat_base,
                                                 current_coat.get_bumpQImage(),
                                                 res_bumpQImage)
                mu.executeInMainThreadWithResult(
                    comp_coat_base, current_coat.get_opacityQImage(),
                    res_opacityQImage)
                update_progress(progress_bar)
                return True
            else:
                #if coat doesn't have matte warn and don't add to texture
                warning_msg("Coat " + str(coat_number) + " (" + current_coat +
                            ") has no matte.\nSkipping layer")
                print("matte: Has no matte")
                return True
    def getSelectedBoundingRegion(self, mode=False, padding = 0.0):
        # get current render width and height settings
        renderHeight = cmds.getAttr('defaultResolution.height')
        renderWidth = cmds.getAttr('defaultResolution.width')
        
        widthMultiplier = renderWidth/(self.usingWidth+0.0)
        heightMultiplier = renderHeight/(self.usingHeight+0.0)
        
        gates = utils.executeInMainThreadWithResult( self.setGates, [False,False] )
        
        # get the active viewport
        activeView = OpenMayaUI.M3dView.active3dView()

        # define python api pointers to get data from api class
        xPtrInit = OpenMaya.MScriptUtil()
        yPtrInit = OpenMaya.MScriptUtil()
        widthPtrInit = OpenMaya.MScriptUtil()
        heightPtrInit = OpenMaya.MScriptUtil()

        xPtr = xPtrInit.asUintPtr()
        yPtr = yPtrInit.asUintPtr()
        widthPtr = widthPtrInit.asUintPtr()
        heightPtr = heightPtrInit.asUintPtr()

        # retreive viewport width and height
        activeView.viewport(xPtr, yPtr, widthPtr, heightPtr)
        viewX = xPtrInit.getUint( xPtr )
        viewY = yPtrInit.getUint( yPtr )
        viewWidth = widthPtrInit.getUint( widthPtr )
        viewHeight = heightPtrInit.getUint( heightPtr )
        
        # determine aspect ratio of render size
        # then determine what the viewport renderable height is
        aspectRatio = float(renderHeight) / float(renderWidth)
        heightDiff = 0  # actual viewport renderable pixels
        heightClip = 0	# area of user viewport not renderable

        # get the active selection
        selection = OpenMaya.MSelectionList()
        OpenMaya.MGlobal.getActiveSelectionList( selection )
        iterSel = OpenMaya.MItSelectionList(selection, OpenMaya.MFn.kMesh)

        # loop through the selected nodes
        boundingBoxes = []
        while not iterSel.isDone():
            # bounding box vars
            minX = 0
            maxX = 0
            minY = 0
            maxY = 0

            iterGeoNum = 0
            
            if mode == 0:#by vertex
                dagPath = OpenMaya.MDagPath()
                iterSel.getDagPath( dagPath )
                iterGeo = OpenMaya.MItGeometry( dagPath )

                # iterate through vertex positions
                # check each vertex position and get its x, y cordinate in the viewport
                # generate the minimum x and y position and the max x and y position
                
                while not iterGeo.isDone():
                    vertexMPoint = iterGeo.position(OpenMaya.MSpace.kWorld)
                    xPosShortPtrInit = OpenMaya.MScriptUtil()
                    yPosShortPtrInit = OpenMaya.MScriptUtil()
                    xPosShortPtr = xPosShortPtrInit.asShortPtr()
                    yPosShortPtr = yPosShortPtrInit.asShortPtr()

                    activeView.worldToView(vertexMPoint, xPosShortPtr, yPosShortPtr)

                    xPos = xPosShortPtrInit.getShort(xPosShortPtr)
                    yPos = yPosShortPtrInit.getShort(yPosShortPtr)
                    if iterGeoNum == 0:
                        minX = xPos
                        minY = yPos

                    if xPos < minX: minX = xPos
                    if xPos > maxX: maxX = xPos
                    if yPos < minY: minY = yPos
                    if yPos > maxY: maxY = yPos
                    
                    iterGeoNum = iterGeoNum + 1
                    iterGeo.next()
            elif mode == 1: #by boundingbox
                objNames = []
                iterSel.getStrings(objNames)
                
                for name in objNames:
                    bbox = cmds.exactWorldBoundingBox(name)
                    XVals = [bbox[0],bbox[3]]
                    YVals = [bbox[1],bbox[4]]
                    ZVals = [bbox[2],bbox[5]]
                    #print bbox
                
                    for x in XVals:
                        for y in YVals:
                            for z in ZVals:
                                point = OpenMaya.MPoint(x,y,z)
                                xPosShortPtrInit = OpenMaya.MScriptUtil()
                                yPosShortPtrInit = OpenMaya.MScriptUtil()
                                xPosShortPtr = xPosShortPtrInit.asShortPtr()
                                yPosShortPtr = yPosShortPtrInit.asShortPtr()
                                
                                activeView.worldToView(point, xPosShortPtr, yPosShortPtr)

                                xPos = xPosShortPtrInit.getShort(xPosShortPtr)
                                yPos = yPosShortPtrInit.getShort(yPosShortPtr)
                                if iterGeoNum == 0:
                                    minX = xPos
                                    minY = yPos

                                if xPos < minX: minX = xPos
                                if xPos > maxX: maxX = xPos
                                if yPos < minY: minY = yPos
                                if yPos > maxY: maxY = yPos
                                iterGeoNum = iterGeoNum + 1
            # move on to next selected node
            iterSel.next()
            
            # the renderWindowCheckAndRenderRegion arguments are ymax, xmin, ymin, xmax		
            # convert the min max values to scalars between 0 and 1
            minXScalar = 0
            maxXScalar = 0
            minYScalar = 0
            maxYScalar = 0
            
            filmFit = ""
            filmFit =  utils.executeInMainThreadWithResult( self.getFilmFit )
            if filmFit == "horizontal":
                renderableHeight = viewWidth * aspectRatio
                heightDiff = viewHeight - renderableHeight
                heightClip = heightDiff / 2
                
                minXScalar = float(minX)/float(viewWidth)
                maxXScalar = float(maxX)/float(viewWidth)
                    
                if(renderWidth > renderHeight or heightDiff < 0 ):
                    minYScalar = ( float( minY ) - heightClip ) / float( renderableHeight )
                    maxYScalar = ( float( maxY ) - heightClip ) / float( renderableHeight )
                    
                else:
                    minYScalar = ( float( minY ) + heightClip ) / float( renderableHeight )
                    maxYScalar = ( float( maxY ) + heightClip ) / float( renderableHeight )
                    
            elif filmFit == "vertical":
                renderableWidth = viewHeight / aspectRatio
                widthDiff = viewWidth - renderableWidth
                widthClip = widthDiff / 2
                
                minYScalar = float(minY)/float(viewHeight)
                maxYScalar = float(maxY)/float(viewHeight)
                
                if( renderHeight > renderWidth or widthDiff < 0  ):
                    minXScalar = ( float( minX ) - widthClip ) / float( renderableWidth )
                    maxXScalar = ( float( maxX ) - widthClip ) / float( renderableWidth )
                else:
                    minXScalar = ( float( minX ) + widthClip ) / float( renderableWidth )
                    maxXScalar = ( float( maxX ) + widthClip ) / float( renderableWidth )               
            

            # define viewport pixel based bounding box and scalar bounding box
            # scalar is the only one useful for rendering a region
            
            padding = max(padding,0.0)
            
            x = minXScalar*renderWidth
            y = renderHeight - maxYScalar*renderHeight
            #y = renderHeight-(renderWidth*maxYScalar+0.5)
            width = (maxXScalar-minXScalar)*renderWidth+1.5
            height = renderHeight*(maxYScalar-minYScalar)+1.5
                        
            xPadding = int(((width*padding)/200)+0.5)
            yPadding = int(((height*padding)/200)+0.5)
            
            x1 = int((x-xPadding)/widthMultiplier+0.5)
            y1 = int((y-yPadding)/heightMultiplier+0.5)
            x2 = int((width+xPadding*2)/widthMultiplier+0.5)
            y2 = int((height+yPadding*2)/heightMultiplier+0.5)
            
            boundingBoxFinalRegion = [ x1, y1, x2, y2 ]
            boundingBoxes.append(boundingBoxFinalRegion)
            
            print("Added Bounding Box")
        
        print("Done Select Bounding Region")
        
        utils.executeInMainThreadWithResult( self.setGates, gates )
        
        return boundingBoxes
示例#37
0
from PySide.QtCore import *
from PySide.QtGui import *
from MayaApp.MainWindow import MainWindow
import maya.OpenMayaUI as mui
from maya import utils
import sip

def getMayaWindow():
   '''
   Get the maya main window as a QMainWindow instance
   '''
   ptr = mui.MQtUtil.mainWindow()
   return sip.wrapinstance(long(ptr), QWidget)

def go():
    window = MainWindow(getMayaWindow())
    window.show()

utils.executeInMainThreadWithResult(go)
示例#38
0
def recording():
	global obarray
	global bodypart_names
	global NAME
	global data
	global frame
	# points to index in the message [data]
	index_pointer = 24
	# points to index in the object array [objectarray]
	array_pointer = 0
	# points to index in the segmentbox array [segmentbox]
	segmentbox_pointer = 0
	# keep track of the float cycles
	cycle_counter = 1
	
	# timestamp
	# time_byte1 = data[12]
	# time_byte2 = data[13]
	# time_byte3 = data[14]
	# time_byte4 = data[15]
	
	# time = time_byte1+time_byte2+time_byte3+time_byte4
	# time = struct.unpack('>i', time)
	
	
	
	objid = None
	# 4 bytes will be unpacked to one single precision type (float) #
	byte1 = None 
	byte2 = None
	byte3 = None 
	byte4 = None
	# floatcontainer1-6 are xyz translation and xyz rotation #
	fcon1 = None #x tran
	fcon2 = None #y tran
	fcon3 = None #z tran
	fcon4 = None #x rot
	fcon5 = None #y rot
	fcon6 = None #z rot
	#array that holds segment parts
	segmentbox = [objid, fcon1, fcon2, fcon3, fcon4, fcon5, fcon6]
	
	# validate euler message #
	if len(data) == 668:
		#print("valid")
		
		# Beginning of the post-processing round #
		while index_pointer < 668: 
				# object segment ID calculation #
				byte1 = data[index_pointer] #first round 24
				index_pointer += 1
				byte2 = data[index_pointer]
				index_pointer += 1
				byte3 = data[index_pointer]
				index_pointer += 1
				byte4 = data[index_pointer] #first round 27
				index_pointer += 1
				#print(byte1,byte2,byte3,byte4);
				#byte1 = struct.pack('B', byte1)
				#byte2 = struct.pack('B', byte2)
				#byte3 = struct.pack('B', byte3)
				#byte4 = struct.pack('B', byte4)
				
				segmentbox[segmentbox_pointer] = byte1+byte2+byte3+byte4
				#print(byte1,byte2,byte3,byte4);
				segmentbox[segmentbox_pointer] = struct.unpack('>i', segmentbox[segmentbox_pointer])
				#print("Current ID: ", segmentbox[segmentbox_pointer]);

				# place ID in 'item.ID'
				obarray[array_pointer].ID = segmentbox[segmentbox_pointer][0] 
				# point to next part of the segment
				segmentbox_pointer += 1 
				
				# end of segment ID calculation #
				
				# Beginning of the 'float cycles' #
				for cycle in range(6):
				
					#print(index_pointer)
					byte1 = data[index_pointer]
					index_pointer += 1
					byte2 = data[index_pointer]
					index_pointer += 1
					byte3 = data[index_pointer]
					index_pointer += 1
					byte4 = data[index_pointer] 
					index_pointer += 1			
					
					#pack to unsigned bytes
					#byte1 = struct.pack('B', byte1)
					#byte2 = struct.pack('B', byte2)
					#byte3 = struct.pack('B', byte3)
					#byte4 = struct.pack('B', byte4)
					
					#merge into a fcon
					segmentbox[segmentbox_pointer] = byte1+byte2+byte3+byte4
					segmentbox[segmentbox_pointer] = struct.unpack('>f', segmentbox[segmentbox_pointer])
					#print(segmentbox[segmentbox_pointer])
					# python has no switch statement .. #
					if cycle_counter == 1:
						obarray[array_pointer].tranx = segmentbox[segmentbox_pointer][0]
						cycle_counter += 1
					elif cycle_counter == 2:
						obarray[array_pointer].trany = segmentbox[segmentbox_pointer][0]
						cycle_counter += 1
					elif cycle_counter == 3:
						obarray[array_pointer].tranz = segmentbox[segmentbox_pointer][0]
						cycle_counter += 1
					elif cycle_counter == 4:
						obarray[array_pointer].rotx = segmentbox[segmentbox_pointer][0]
						cycle_counter += 1
					elif cycle_counter == 5:
						obarray[array_pointer].roty = segmentbox[segmentbox_pointer][0]
						cycle_counter += 1
					elif cycle_counter == 6:
						obarray[array_pointer].rotz = segmentbox[segmentbox_pointer][0]
						cycle_counter = 1 #reset
					
					# point to next part of the segment
					segmentbox_pointer += 1 
					
				# at the end of the float cycles :
				#print(obarray[array_pointer])
				obarray[array_pointer].trantuple = (obarray[array_pointer].tranx, obarray[array_pointer].trany, obarray[array_pointer].tranz)
				obarray[array_pointer].rotatuple = (obarray[array_pointer].rotx, obarray[array_pointer].roty, obarray[array_pointer].rotz)
				
				# point to next segment for post-processing
				array_pointer += 1
				segmentbox_pointer = 0
		#execute all known transformations
		#print("obarray before attribute setting", obarray)
		utils.executeInMainThreadWithResult(execute_transformations)
		utils.executeInMainThreadWithResult(execute_keyframe)
		frame += 1
		
	else:
		#print("invalid")
		stop()
示例#39
0
def invoke(*args, **kwargs):
    return utils.executeInMainThreadWithResult(*args, **kwargs)
示例#40
0
def ExecuteFunction(func, *args, **kwargs):
    return utils.executeInMainThreadWithResult(func, *args, **kwargs)
示例#41
0
	def blast_background(self):
		utils.executeInMainThreadWithResult(self._blast_background_inner)
示例#42
0
 def execute_in_main_thread(*args, **kwargs):
     return utils.executeInMainThreadWithResult(*args, **kwargs)
示例#43
0
 def _FILE_Project(s):
     path = utils.executeInMainThreadWithResult(lambda: cmds.workspace(q=True, rd=True))
     return path
示例#44
0
 def execute(self, func, *args):
     return utils.executeInMainThreadWithResult(func, *args)
示例#45
0
 def _FILE_Running(s):
     f = utils.executeInMainThreadWithResult(lambda: cmds.file(q=True, sn=True))
     return f if f else ""
示例#46
0
        getattr(targetInstance, testMethodName)()
    finally:
        targetInstance.tearDown()
        
def serverHandler(request):
    def mainThreadHandler(request):
        try:
            launch(**request)
            return {'result':'success'}
        except Exception,e:
            import traceback;traceback.print_exc()
            #return {'result':'exception','exception':pickle.dumps(e, pickle.HIGHEST_PROTOCOL)}
            return {'result':'exception','exception':base64.b64encode(pickle.dumps(e, pickle.HIGHEST_PROTOCOL)),'stackTrace':traceback.format_exc()}
        
    from maya.utils import executeInMainThreadWithResult
    return executeInMainThreadWithResult(mainThreadHandler,request) 
    
def mayaTest(setupModule):
    setupModule = sys.modules[setupModule]
    
    def decorator(cls):
        if not insideMaya:
            voidMethod = lambda *args,**kwargs:None
            setattr(cls,'setUp',voidMethod)
            setattr(cls, "tearDown", voidMethod)
            
        
        for methodName,method in list(inspect.getmembers(cls, inspect.ismethod))[:]:
            if not methodName.startswith("test"):
                continue
    
示例#47
0
 def threaded_wrapper(func, *args, **kwargs):
     return utils.executeInMainThreadWithResult(func, *args, **kwargs)
示例#48
0
文件: lib.py 项目: linez69/pyblish
 def threaded_wrapper(func, *args, **kwargs):
     return utils.executeInMainThreadWithResult(func, *args, **kwargs)
示例#49
0
def UpdateThread():
    userAppPath = utils.executeInMainThreadWithResult(GetUserAppPath)
    serverListPath = os.path.join(userAppPath, "server_list.tmp")
    serverStatusPath = os.path.join(userAppPath, "server_status.tmp")
    serverPortPath = os.path.join(userAppPath, "server_ports.tmp")

    serverSettingsPath = os.path.join(userAppPath, "vray_dr_list.xml")

    usesSingleFile = utils.executeInMainThreadWithResult(
        VrayUsesSingleSettingsFile)

    jobId = utils.executeInMainThreadWithResult(GetSpawnerJobId)
    portNumber = utils.executeInMainThreadWithResult(GetSpawnerPortNumber)

    while jobId != "":
        # Update the server list.
        useIpAddress = utils.executeInMainThreadWithResult(GetUseIpAddress)
        servers = CallDeadlineCommand([
            "GetMachinesRenderingJob", jobId,
            "true" if useIpAddress else "false"
        ])
        servers = servers.splitlines()
        utils.executeInMainThreadWithResult(UpdateServers, servers)

        # Update the job's state.
        jobState = ""
        jobInfo = CallDeadlineCommand(["GetJob", jobId, "false"])
        for line in jobInfo.splitlines():
            if line.startswith("Status="):
                jobState = line[7:]
                break

        if jobState == "Active":
            jobState = "Rendering" if len(servers) > 0 else "Queued"
        elif jobState == "":
            jobState = "Deleted"

        utils.executeInMainThreadWithResult(UpdateState, jobState)

        if not usesSingleFile:
            # Update the vray config file.
            serverText = "\n".join(servers) + "\n"

            enabledList = []
            portNumberList = []

            for i in range(0, len(servers)):
                enabledList.append("Enable")
                portNumberList.append(portNumber)
            enabledText = "\n".join(enabledList) + "\n"
            portNumberText = "\n".join(portNumberList) + "\n"

            try:
                with open(serverListPath, "w") as fileHandle:
                    fileHandle.write(serverText)

                with open(serverPortPath, "w") as fileHandle:
                    fileHandle.write(portNumberText)

                with open(serverStatusPath, "w") as fileHandle:
                    fileHandle.write(enabledText)

            except:
                print(traceback.format_exc())

        else:
            tree = ET.parse(serverSettingsPath)
            root = tree.getroot()

            for server in root.findall("server"):
                root.remove(server)

            for serverName in servers:
                curServer = ET.SubElement(root, "server")
                hostElement = ET.SubElement(curServer, "host")
                hostElement.text = serverName
                portElement = ET.SubElement(curServer, "port")
                portElement.text = portNumber
                aliasElement = ET.SubElement(curServer, "alias")
                enabledElement = ET.SubElement(curServer, "enabled")
                enabledElement.text = "1"

            tree.write(serverSettingsPath,
                       encoding="UTF-8",
                       xml_declaration=True)

        if jobState != "Rendering" and jobState != "Queued":
            utils.executeInMainThreadWithResult(NotifyJobStateChanged,
                                                jobState)
        else:
            time.sleep(5.0)

        jobId = utils.executeInMainThreadWithResult(GetSpawnerJobId)
示例#50
0
 def __getattr__(s, n):
     if hasattr(cmds, n):
         at = getattr(cmds, n)
         return lambda *a, **kw: utils.executeInMainThreadWithResult(lambda: at(*a, **kw))
     raise AttributeError
 def run(self):
     while(self.running):
         time.sleep(1.0/30.0)
         utils.executeInMainThreadWithResult(self.command)