def __init__(self, socketRef: sockets.SocketThread, parent=None): self.config = config.ConfigSettings() self.needRestart = False self._sockRef = socketRef super().__init__(parent=parent) self.setupUi(self) self.portNumber.setText(self.config.getConfigSetting("Socket", "port")) self.portNumber.setValidator(QtGui.QIntValidator(self)) self.portNumber.textChanged.connect(self._setNeedRestart) self.timeoutNumber.setText( self.config.getConfigSetting("Socket", "timeout")) self.timeoutNumber.setValidator(QtGui.QIntValidator(0, 60, self)) self.timeoutNumber.textChanged.connect(self._setNeedRestart) self.showlog.setCheckState( Qt.CheckState.Checked if self.config.checkIfOptionIsSet( "General", "outputConsole") else Qt.CheckState.Unchecked) self.createGraph.setCheckState( Qt.CheckState.Checked if self.config.checkIfOptionIsSet( "General", "createGraph") else Qt.CheckState.Unchecked) self.importLODs.setCheckState( Qt.CheckState.Checked if self.config.checkIfOptionIsSet( "3D Asset", "importLODs") else Qt.CheckState.Unchecked) self.saveBtn.pressed.connect(self.saveSettings) self.cancelBtn.pressed.connect(lambda: self.close()) self.helpIcon.setPixmap(QtGui.QPixmap(icon.getIcon('help_icon.png')))
def Log(cls, msg: str, logLevel=logging.INFO): """Helper function used to log a massage to a file or if specified in the config file with the `outputConsole` propriety also to the Python Editor output of Substance Designer :param msg: the message to print :type msg: str :param logLevel: the log level to print with if it is lower than the current :attr:`~megascan_link.log.LoggerLink._logger` level it would not be printed, defaults to logging.INFO :type logLevel: int, optional """ conf = config.ConfigSettings() lvl = "" if not cls._isSetup: cls.setUpLogger() if logLevel == logging.INFO: lvl = "INFO" cls._logger.info(msg) if logLevel == logging.WARNING: lvl = "WARNING" cls._logger.warning(msg) if logLevel == logging.ERROR: lvl = "ERROR" cls._logger.error(msg) if logLevel == logging.DEBUG: lvl = "DEBUG" cls._logger.debug(msg) if conf.checkIfOptionIsSet("General", "outputConsole"): if logLevel >= cls._logger.level: print("[megascanlink][{}] {}".format(lvl, msg))
def processImportForPacakges(self, packages): """this is the actual method that performs the bitmaps/meshes import and graph creation tasks it does it for every package that the user selected this method uses the class attribute data and clears it when done and look up for the settings from the configuration file :param packages: List of SDPackage where to import the currently processing data :type packages: List[SDPackage] """ if not self.data: return conf = config.ConfigSettings() for package in packages: parentFolder = None for resource in package.getChildrenResources(False): if resource.getIdentifier() == "Resources": parentFolder = resource if not parentFolder: parentFolder = SDResourceFolder.sNew(package) parentFolder.setIdentifier("Resources") for imprt in self.data: bitmaps = [] folder = SDResourceFolder.sNew(parentFolder) folder.setIdentifier(imprt['name']) for bitmap in imprt['components']: bitmapResource = SDResourceBitmap.sNewFromFile(folder, bitmap['path'], EmbedMethod.Linked) bitmaps.append(MegascanBitmap(bitmapResource, bitmap['path'], bitmap["type"], bitmap['nameOverride'])) for mesh in imprt['meshList']: SDResourceScene.sNewFromFile(folder, mesh['path'], EmbedMethod.Linked) if conf.checkIfOptionIsSet("3D Asset", "importLODs"): for lod in imprt['lodList']: SDResourceScene.sNewFromFile(folder, lod['path'], EmbedMethod.Linked) if conf.checkIfOptionIsSet("General","createGraph"): self.createGraphWith(imprt['name'],bitmaps,package) self.data = None
def initializeSDPlugin(): """**Main entry point of the plugin**""" # Debug Stub # ptvsd.enable_attach() # ptvsd.wait_for_attach() # ptvsd.break_into_debugger() # ================================================== # Set up initial config proprietiess conf = config.ConfigSettings() initConfig = configparser.ConfigParser() initConfig["Socket"] = {"port": 24981, "timeout": 5} initConfig["General"] = {"creategraph": "True", "outputConsole": "False"} initConfig["3D Asset"] = {"importlods": "False"} conf.setUpInitialConfig(initConfig) # Setup logger logger = log.LoggerLink() logger.Log("Initializing Megascan Link Plugin") # set up the toolbar icon createToolBarAction() # =================================================== # Get the main window to set the thread parent of uiMgr = utilities.getUiManager() mainWindow = uiMgr.getMainWindow() # =================================================== # Create and start the listening socket thread # Link the resourceimporter class to the socket thread for receiving and processing the incoming data Data.socketThread = sockets.SocketThread(parent=mainWindow) importer = resImporter.ResourceImporter(parent=mainWindow) Data.socketThread.onDataReceived.connect(importer.importFromData, Qt.QueuedConnection) Data.socketThread.start()
def run(self): """This is the method that manages the socket lifetime process To interact with the socket use the :meth:`~megascan_link.sockets.SocketThread.close` and :meth:`~megascan_link.sockets.SocketThread.restart` method instead While this method is running the associated thread is kept alive **closing** the socket without requesting a **restart** will make this thread close too The socket is listening on the port specified on the config file and it is restarted every time the timeout duration expires (also setted from the config file) """ logger = log.LoggerLink() # get config settings conf = config.ConfigSettings() # get the port number port = int(conf.getConfigSetting("Socket", "port")) timeout = int(conf.getConfigSetting("Socket", "timeout")) # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(timeout) #bind to an address and port server_address = ('localhost', port) logger.Log( 'trying to start up socket on {} with port {} and timeout {}'. format(server_address[0], server_address[1], timeout), INFO) while not self.started: try: sock.bind(server_address) self.started = True except Exception: logger.Log("Failed to start up socket .... retrying", INFO) time.sleep(1) if not self.started: return # Listen for incoming connections sock.listen(1) while True: if self._tryCloseSocket(sock): break # Wait for a connection try: logger.Log('waiting for a connection', DEBUG) self._receivedData = io.StringIO() self._connection, client_address = sock.accept() logger.Log('connection from {}'.format(client_address), DEBUG) # Receive the data in small chunks and gather it until there is no more while True: if self._tryCloseSocket(sock): break data = self._connection.recv(16) if data: self._receivedData.write(data.decode("utf-8")) else: logger.Log( 'no more data from {}'.format(client_address), DEBUG) break except socket.timeout: logger.Log("socket timeout", DEBUG) else: # Clean up the connection data = self._receivedData.getvalue() if data: jsonObj = json.loads(self._receivedData.getvalue()) self.onDataReceived.emit(jsonObj) finally: if hasattr(self, '_connection'): self._connection.close() self._receivedData.close() self.shouldClose = False if self.shouldRestart: logger.Log("Restarting socket", INFO) self.shouldRestart = False self.started = False self.run() self.started = False