def runProcess(self, args): self.logDb(u"BEFEHL: '%s'" % (u"' '".join(args))) currout = "" currerr = "" p = QProcess() p.start(args[0], args[1:]) i = 0 while not p.waitForFinished(500): i += 1 self.alive.setText(self.alive.text()[:-1] + ("-\|/")[i % 4]) app.processEvents() currout = self.processOutput(currout, p.readAllStandardOutput()) currerr = self.processOutput(currerr, p.readAllStandardError()) if p.state() <> QProcess.Running: if self.canceled: self.log(u"Prozeß abgebrochen.") break if self.canceled: self.log(u"Prozeß wird abgebrochen.") p.kill() currout = self.processOutput(currout, p.readAllStandardOutput()) if currout and currout != "": self.log("E %s" % currout) currerr = self.processOutput(currerr, p.readAllStandardError()) if currerr and currerr != "": self.log("E %s" % currerr) ok = False if p.exitStatus() == QProcess.NormalExit: if p.exitCode() == 0: ok = True else: self.log(u"Fehler bei Prozeß: %d" % p.exitCode()) else: self.log(u"Prozeß abgebrochen: %d" % p.exitCode()) self.logDb("EXITCODE: %d" % p.exitCode()) p.close() return ok
def runProcess(self, args): self.logDb( u"BEFEHL: '%s'" % ( u"' '".join(args) ) ) currout = "" currerr = "" p = QProcess() p.start( args[0], args[1:] ) i=0 while not p.waitForFinished(500): i += 1 self.alive.setText( self.alive.text()[:-1] + ("-\|/")[i%4] ) app.processEvents() currout = self.processOutput( currout, p.readAllStandardOutput() ) currerr = self.processOutput( currerr, p.readAllStandardError() ) if p.state()<>QProcess.Running: if self.canceled: self.log( u"Prozeß abgebrochen." ) break if self.canceled: self.log( u"Prozeß wird abgebrochen." ) p.kill() currout = self.processOutput( currout, p.readAllStandardOutput() ) if currout and currout!="": self.log( "E %s" % currout ) currerr = self.processOutput( currerr, p.readAllStandardError() ) if currerr and currerr!="": self.log( "E %s" % currerr ) ok = False if p.exitStatus()==QProcess.NormalExit: if p.exitCode()==0: ok = True else: self.log( u"Fehler bei Prozeß: %d" % p.exitCode() ) else: self.log( u"Prozeß abgebrochen: %d" % p.exitCode() ) self.logDb( "EXITCODE: %d" % p.exitCode() ) p.close() return ok
class RdpConnection(object): _cfg = None _conn = None def __init__(self, cfg): self._cfg = cfg def connect(self, parent_window=None): if not parent_window is None: setattr(self._cfg, 'parent-window', parent_window) self._conn = QProcess() # print(self._cfg.as_list()) self._conn.start('xfreerdp', self._cfg.as_list()) self._conn.readyReadStandardOutput.connect(self._read_out) self._conn.readyReadStandardError.connect(self._read_err) def close(self): self._conn.close() self._conn.terminate() def connect_output(self, out_listener): self._out_listener = out_listener def _read_out(self): if not self._out_listener is None: self._out_listener(str(self._conn.readAllStandardOutput())) def _read_err(self): if not self._out_listener is None: self._out_listener(str(self._conn.readAllStandardError())) @property def cfg(self): return self._cfg
class WorkThread(QThread): def __init__(self): QThread.__init__(self) self.process = QProcess() self.cmd = None self.process.readyReadStandardOutput.connect(self.readOutput) self.process.readyReadStandardError.connect(self.readErrors) self.process.finished.connect(self.fini) def fini(self,no): self.emit(SIGNAL("fini"),no,self.cmd) def setCmd(self,val): self.cmd = val def kill_process(self): self.process.kill() def close_process(self): self.process.close() def run(self): if(self.process.isOpen()): self.process.close() #print "open" #self.process.kill() self.process.start(self.cmd) else: #print "strgin" self.process.start(self.cmd) self.exec_() self.process.waitForFinished() self.process.kill() #self.procDone.emit(True) def run2(self): if(self.process.isOpen()): self.process.close() #print "open" #self.process.kill() self.process.start(self.cmd) else: #print "strgin" self.process.start(self.cmd) self.exec_() #self.process.kill() def readOutput(self): self.emit(SIGNAL("update"),str(self.process.readAllStandardOutput())) def readErrors(self): self.emit(SIGNAL("update"),str(self.process.readAllStandardError())) def __del__(self): self.wait()
def browseModels(self): dir_to_show = './model/'+ self.txtModelName.text() process = QProcess(self) process.startDetached("open", [dir_to_show]) if process.waitForFinished(): process.close()
class RenderW(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.ui = ui_render.Ui_RenderW() self.ui.setupUi(self) self.fFreewheel = False self.fLastTime = -1 self.fMaxTime = 180 self.fTimer = QTimer(self) self.fProcess = QProcess(self) # ------------------------------------------------------------- # Get JACK client and base information global gJackClient if gJackClient: self.fJackClient = gJackClient else: self.fJackClient = jacklib.client_open("Render-Dialog", jacklib.JackNoStartServer, None) self.fBufferSize = int(jacklib.get_buffer_size(self.fJackClient)) self.fSampleRate = int(jacklib.get_sample_rate(self.fJackClient)) for i in range(self.ui.cb_buffer_size.count()): if int(self.ui.cb_buffer_size.itemText(i)) == self.fBufferSize: self.ui.cb_buffer_size.setCurrentIndex(i) break else: self.ui.cb_buffer_size.addItem(str(self.fBufferSize)) self.ui.cb_buffer_size.setCurrentIndex( self.ui.cb_buffer_size.count() - 1) # ------------------------------------------------------------- # Set-up GUI stuff # Get List of formats self.fProcess.start(gJackCapturePath, ["-pf"]) self.fProcess.waitForFinished() formats = str(self.fProcess.readAllStandardOutput(), encoding="utf-8").split(" ") formatsList = [] for i in range(len(formats) - 1): iFormat = formats[i].strip() if iFormat: formatsList.append(iFormat) formatsList.sort() # Put all formats in combo-box, select 'wav' option for i in range(len(formatsList)): self.ui.cb_format.addItem(formatsList[i]) if formatsList[i] == "wav": self.ui.cb_format.setCurrentIndex(i) self.ui.cb_depth.setCurrentIndex(4) #Float self.ui.rb_stereo.setChecked(True) self.ui.te_end.setTime(QTime(0, 3, 0)) self.ui.progressBar.setFormat("") self.ui.progressBar.setMinimum(0) self.ui.progressBar.setMaximum(1) self.ui.progressBar.setValue(0) self.ui.b_render.setIcon(getIcon("media-record")) self.ui.b_stop.setIcon(getIcon("media-playback-stop")) self.ui.b_close.setIcon(getIcon("window-close")) self.ui.b_open.setIcon(getIcon("document-open")) self.ui.b_stop.setVisible(False) self.ui.le_folder.setText(HOME) # ------------------------------------------------------------- # Set-up connections self.connect(self.ui.b_render, SIGNAL("clicked()"), SLOT("slot_renderStart()")) self.connect(self.ui.b_stop, SIGNAL("clicked()"), SLOT("slot_renderStop()")) self.connect(self.ui.b_open, SIGNAL("clicked()"), SLOT("slot_getAndSetPath()")) self.connect(self.ui.b_now_start, SIGNAL("clicked()"), SLOT("slot_setStartNow()")) self.connect(self.ui.b_now_end, SIGNAL("clicked()"), SLOT("slot_setEndNow()")) self.connect(self.ui.te_start, SIGNAL("timeChanged(const QTime)"), SLOT("slot_updateStartTime(const QTime)")) self.connect(self.ui.te_end, SIGNAL("timeChanged(const QTime)"), SLOT("slot_updateEndTime(const QTime)")) self.connect(self.ui.group_time, SIGNAL("clicked(bool)"), SLOT("slot_transportChecked(bool)")) self.connect(self.fTimer, SIGNAL("timeout()"), SLOT("slot_updateProgressbar()")) # ------------------------------------------------------------- self.loadSettings() @pyqtSlot() def slot_renderStart(self): if not os.path.exists(self.ui.le_folder.text()): QMessageBox.warning( self, self.tr("Warning"), self. tr("The selected directory does not exist. Please choose a valid one." )) return timeStart = self.ui.te_start.time() timeEnd = self.ui.te_end.time() minTime = (timeStart.hour() * 3600) + (timeStart.minute() * 60) + (timeStart.second()) maxTime = (timeEnd.hour() * 3600) + (timeEnd.minute() * 60) + (timeEnd.second()) newBufferSize = int(self.ui.cb_buffer_size.currentText()) useTransport = self.ui.group_time.isChecked() self.fFreewheel = bool(self.ui.cb_render_mode.currentIndex() == 1) self.fLastTime = -1 self.fMaxTime = maxTime if self.fFreewheel: self.fTimer.setInterval(100) else: self.fTimer.setInterval(500) self.ui.group_render.setEnabled(False) self.ui.group_time.setEnabled(False) self.ui.group_encoding.setEnabled(False) self.ui.b_render.setVisible(False) self.ui.b_stop.setVisible(True) self.ui.b_close.setEnabled(False) if useTransport: self.ui.progressBar.setFormat("%p%") self.ui.progressBar.setMinimum(minTime) self.ui.progressBar.setMaximum(maxTime) self.ui.progressBar.setValue(minTime) else: self.ui.progressBar.setFormat("") self.ui.progressBar.setMinimum(0) self.ui.progressBar.setMaximum(0) self.ui.progressBar.setValue(0) self.ui.progressBar.update() arguments = [] # Filename prefix arguments.append("-fp") arguments.append(self.ui.le_prefix.text()) # Format arguments.append("-f") arguments.append(self.ui.cb_format.currentText()) # Bit depth arguments.append("-b") arguments.append(self.ui.cb_depth.currentText()) # Channels arguments.append("-c") if self.ui.rb_mono.isChecked(): arguments.append("1") elif self.ui.rb_stereo.isChecked(): arguments.append("2") else: arguments.append(str(self.ui.sb_channels.value())) # Controlled only by freewheel if self.fFreewheel: arguments.append("-jf") # Controlled by transport elif useTransport: arguments.append("-jt") # Silent mode arguments.append("-dc") arguments.append("-s") # Change current directory os.chdir(self.ui.le_folder.text()) if newBufferSize != int(jacklib.get_buffer_size(self.fJackClient)): print("NOTICE: buffer size changed before render") jacklib.set_buffer_size(self.fJackClient, newBufferSize) if useTransport: if jacklib.transport_query( self.fJackClient, None ) > jacklib.JackTransportStopped: # rolling or starting jacklib.transport_stop(self.fJackClient) jacklib.transport_locate(self.fJackClient, minTime * self.fSampleRate) self.fProcess.start(gJackCapturePath, arguments) self.fProcess.waitForStarted() if self.fFreewheel: print("NOTICE: rendering in freewheel mode") sleep(1) jacklib.set_freewheel(self.fJackClient, 1) if useTransport: self.fTimer.start() jacklib.transport_start(self.fJackClient) @pyqtSlot() def slot_renderStop(self): useTransport = self.ui.group_time.isChecked() if useTransport: jacklib.transport_stop(self.fJackClient) if self.fFreewheel: jacklib.set_freewheel(self.fJackClient, 0) sleep(1) self.fProcess.close() if useTransport: self.fTimer.stop() self.ui.group_render.setEnabled(True) self.ui.group_time.setEnabled(True) self.ui.group_encoding.setEnabled(True) self.ui.b_render.setVisible(True) self.ui.b_stop.setVisible(False) self.ui.b_close.setEnabled(True) self.ui.progressBar.setFormat("") self.ui.progressBar.setMinimum(0) self.ui.progressBar.setMaximum(1) self.ui.progressBar.setValue(0) self.ui.progressBar.update() # Restore buffer size newBufferSize = int(jacklib.get_buffer_size(self.fJackClient)) if newBufferSize != self.fBufferSize: jacklib.set_buffer_size(self.fJackClient, newBufferSize) @pyqtSlot() def slot_getAndSetPath(self): getAndSetPath(self, self.ui.le_folder.text(), self.ui.le_folder) @pyqtSlot() def slot_setStartNow(self): time = int( jacklib.get_current_transport_frame(self.fJackClient) / self.fSampleRate) secs = time % 60 mins = int(time / 60) % 60 hrs = int(time / 3600) % 60 self.ui.te_start.setTime(QTime(hrs, mins, secs)) @pyqtSlot() def slot_setEndNow(self): time = int( jacklib.get_current_transport_frame(self.fJackClient) / self.fSampleRate) secs = time % 60 mins = int(time / 60) % 60 hrs = int(time / 3600) % 60 self.ui.te_end.setTime(QTime(hrs, mins, secs)) @pyqtSlot(QTime) def slot_updateStartTime(self, time): if time >= self.ui.te_end.time(): self.ui.te_end.setTime(time) renderEnabled = False else: renderEnabled = True if self.ui.group_time.isChecked(): self.ui.b_render.setEnabled(renderEnabled) @pyqtSlot(QTime) def slot_updateEndTime(self, time): if time <= self.ui.te_start.time(): self.ui.te_start.setTime(time) renderEnabled = False else: renderEnabled = True if self.ui.group_time.isChecked(): self.ui.b_render.setEnabled(renderEnabled) @pyqtSlot(bool) def slot_transportChecked(self, yesNo): if yesNo: renderEnabled = bool( self.ui.te_end.time() > self.ui.te_start.time()) else: renderEnabled = True self.ui.b_render.setEnabled(renderEnabled) @pyqtSlot() def slot_updateProgressbar(self): time = int(jacklib.get_current_transport_frame( self.fJackClient)) / self.fSampleRate self.ui.progressBar.setValue(time) if time > self.fMaxTime or (self.fLastTime > time and not self.fFreewheel): self.slot_renderStop() self.fLastTime = time def saveSettings(self): settings = QSettings("Cadence", "Cadence-Render") if self.ui.rb_mono.isChecked(): channels = 1 elif self.ui.rb_stereo.isChecked(): channels = 2 else: channels = self.ui.sb_channels.value() settings.setValue("Geometry", self.saveGeometry()) settings.setValue("OutputFolder", self.ui.le_folder.text()) settings.setValue("FilenamePrefix", self.ui.le_prefix.text()) settings.setValue("EncodingFormat", self.ui.cb_format.currentText()) settings.setValue("EncodingDepth", self.ui.cb_depth.currentText()) settings.setValue("EncodingChannels", channels) settings.setValue("UseTransport", self.ui.group_time.isChecked()) settings.setValue("StartTime", self.ui.te_start.time()) settings.setValue("EndTime", self.ui.te_end.time()) def loadSettings(self): settings = QSettings("Cadence", "Cadence-Render") self.restoreGeometry(settings.value("Geometry", "")) outputFolder = settings.value("OutputFolder", HOME) if os.path.exists(outputFolder): self.ui.le_folder.setText(outputFolder) self.ui.le_prefix.setText( settings.value("FilenamePrefix", "jack_capture_")) encFormat = settings.value("EncodingFormat", "Wav", type=str) for i in range(self.ui.cb_format.count()): if self.ui.cb_format.itemText(i) == encFormat: self.ui.cb_format.setCurrentIndex(i) break encDepth = settings.value("EncodingDepth", "Float", type=str) for i in range(self.ui.cb_depth.count()): if self.ui.cb_depth.itemText(i) == encDepth: self.ui.cb_depth.setCurrentIndex(i) break encChannels = settings.value("EncodingChannels", 2, type=int) if encChannels == 1: self.ui.rb_mono.setChecked(True) elif encChannels == 2: self.ui.rb_stereo.setChecked(True) else: self.ui.rb_outro.setChecked(True) self.ui.sb_channels.setValue(encChannels) self.ui.group_time.setChecked( settings.value("UseTransport", False, type=bool)) self.ui.te_start.setTime( settings.value("StartTime", self.ui.te_start.time(), type=QTime)) self.ui.te_end.setTime( settings.value("EndTime", self.ui.te_end.time(), type=QTime)) def closeEvent(self, event): self.saveSettings() if self.fJackClient: jacklib.client_close(self.fJackClient) QDialog.closeEvent(self, event) def done(self, r): QDialog.done(self, r) self.close()
class FrD_NukeBatchRender(QtGui.QMainWindow, form_class): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.setupUi(self) self.setWindowTitle('FrD Nuke Batch Render' + PROGRAM_VERSION) self.output_LW.setEnabled(0) # ============================ STYLE ======================= # # Progress Bar Style PB_STYLE = """ QProgressBar { border: 2px solid grey; border-radius: 5px; text-align: center; } QProgressBar::chunk { background-color: #d7801a; width: 3px; margin: 1.5px; } """ # self.PB.setStyleSheet(PB_STYLE) # QMenuBar Style MB_STYLE = """ QMenuBar::item { background: transparent; } QMenuBar::item:selected { background: background-color: rgb(49,49,49); border: 1px solid #000; } QMenuBar::item:pressed { background: #444; border: 1px solid #000; background-color: QLinearGradient( x1:0, y1:0, x2:0, y2:1, stop:1 #212121, stop:0.4 #343434/*, stop:0.2 #343434, stop:0.1 #ffaa00*/ ); margin-bottom:-1px; padding-bottom:1px; } """ self.menuFiles.setStyleSheet(MB_STYLE) # ============================ STYLE ======================= # # Enable Drah and Drop self.Queue_TW.setAcceptDrops(True) # Set up handlers for the TableWidget self.Queue_TW.dragEnterEvent = self.twDragEnterEvent self.Queue_TW.dragMoveEvent = self.twDragMoveEvent self.Queue_TW.dropEvent = self.twDropEvent # Size of Table Columns self.Queue_TW.setColumnWidth(0, 250) self.Queue_TW.setColumnWidth(1, 300) self.Queue_TW.setColumnWidth(2, 100) self.Queue_TW.setColumnWidth(3, 100) self.Queue_TW.setColumnWidth(4, 310) self.Queue_TW.setColumnWidth(5, 110) # operation ALL self.Clear_BN.clicked.connect(self.ClearQueue) self.Update_BN.clicked.connect(self.UpdateQueue) # Render self.Render_BN.clicked.connect(self.NBR_render) # ============ Drag and Drop Event) ============ # def twDragEnterEvent(self, event): if event.mimeData().hasUrls: event.accept() else: event.ignore() def twDragMoveEvent(self, event): if event.mimeData().hasUrls: event.setDropAction(QtCore.Qt.CopyAction) event.accept() else: event.ignore() def twDropEvent(self, event): if event.mimeData().hasUrls: event.setDropAction(QtCore.Qt.CopyAction) event.accept() links = [] for url in event.mimeData().urls(): links.append(str(url.toLocalFile())) # print links self.nukeProjDropped(links) else: event.ignore() # ============ Drag and Drop Ends ============ # # ============ Clear and Update All ============ # def NBR_askMsg(self, title, text): qmsgBox = QtGui.QMessageBox() qmsgBox.setStyleSheet('QMessageBox {background-color: #333; font-size: 12pt; font-family: Trebuchet MS}\nQLabel{color:white;}') # 585858 return QtGui.QMessageBox.question(qmsgBox, title, text, QtGui.QMessageBox.Yes | QtGui.QMessageBox.Cancel) # | QtGui.QMessageBox.No def ClearQueue(self): global folderQueue if self.Queue_TW.rowCount() > 0: if (self.NBR_askMsg('Clear Render Queue', 'Are you sure you want to clear the whole Render Queue?') == QtGui.QMessageBox.Yes): self.Queue_TW.setRowCount(0) folderQueue = [] QtGui.QApplication.processEvents() def UpdateQueue(self): global folderQueue for project in xrange(len(folderQueue)): pass # ========== Clear and Update All Ends ========== # def nukeProjDropped(self, arg): global folderQueue appendedList = [] for url in sorted(arg): if os.path.exists(url) and os.path.isfile(url) and url.lower().endswith('.nk'): if url in folderQueue: pass else: appendedList.append(url) folderQueue.append(url) # Add table row rowPosition = self.Queue_TW.rowCount() self.Queue_TW.insertRow(rowPosition) # get All Write Node from .nk # QProcess for nuke self.nukeProcess = QProcess(self) self.nukeProcess.setProcessChannelMode(QProcess.MergedChannels) args = self.createCmdArg(str(url)) self.nukeProcess.start(NUKE_EXE, args) # For debug: read output lines self.nukeProcess.readyRead.connect(self.NBR_debug) self.nukeProcess.waitForFinished() self.nukeProcess.close() # Add row and info to table self.NBR_createCheckBoxItemTableWidget(rowPosition, 0, os.path.splitext(os.path.basename(url))[0]) # Get the write nodes from text files (D:/Temp/nukeBatch) layout = QtGui.QVBoxLayout() layout.setAlignment(QtCore.Qt.AlignLeft) with open("D:\\Temp\\nukeBatch\\" + os.path.basename(url) + ".txt", "r") as ins: bframe = False bCount = 0 for line in ins: if 'FrameRange:' in line: bframe = True continue if (bframe is False): item = QtGui.QCheckBox(str(line).strip()) item.setChecked(True) item.setFont(QtGui.QFont('meiryo', 9)) layout.addWidget(item) elif (bframe is True): self.NBR_createEditTextItemTableWidget(rowPosition, 2 + bCount, int(str(line).strip())) bCount += 1 cellWidget = QtGui.QWidget() cellWidget.setLayout(layout) self.Queue_TW.setCellWidget(rowPosition, 1, cellWidget) self.Queue_TW.resizeRowsToContents() self.Queue_TW.scrollToBottom() QtGui.QApplication.processEvents() def createCmdArg(self, nk): # nk = url return ["-ti", CHECKING_NK, nk] def createCmdArg2(self, nk, start, end, wnode=[]): return ["-ti", RENDER_NK, nk, wnode, start, end] def NBR_debug(self): while (self.nukeProcess.canReadLine()): print (str(self.nukeProcess.readLine())) def NBR_createCheckBoxItemTableWidget(self, row, col, text, color='#4c4c4c'): layout = QtGui.QVBoxLayout() layout.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft) item = QtGui.QCheckBox(text) item.setChecked(True) item.setFont(QtGui.QFont('meiryo', 9)) layout.addWidget(item) cellWidget = QtGui.QWidget() cellWidget.setStyleSheet('color:white; background-color:' + color) cellWidget.setLayout(layout) self.Queue_TW.setCellWidget(row, col, cellWidget) # self.Queue_TW.setItem(row, 0, QtGui.QTableWidgetItem(str(text))) def NBR_createEditTextItemTableWidget(self, row, col, text, color='#4c4c4c'): layout = QtGui.QVBoxLayout() layout.setAlignment(QtCore.Qt.AlignCenter) item = QtGui.QSpinBox() item.setMaximum(9999) item.setValue(text) item.setFont(QtGui.QFont('meiryo', 9)) layout.addWidget(item) cellWidget = QtGui.QWidget() cellWidget.setStyleSheet('color:white; background-color:' + color) cellWidget.setLayout(layout) self.Queue_TW.setCellWidget(row, col, cellWidget) def NBR_getCellData(self, row, col, key): cellDict = {} target = self.Queue_TW.cellWidget(row, col) if target: lay = target.layout() if lay: for k in xrange(lay.count()): w = lay.itemAt(k).widget() if isinstance(w, QtGui.QCheckBox): cellDict[key] = w.checkState() # 0 false, > 0 true elif isinstance(w, QtGui.QSpinBox): cellDict[key] = w.value() return cellDict def NBR_getCellNodeData(self, row, col): target = self.Queue_TW.cellWidget(row, col) cellUserInputList = [] if target: lay = target.layout() if lay: for k in xrange(lay.count()): w = lay.itemAt(k).widget() if isinstance(w, QtGui.QCheckBox): cellUserInputList.append([str(w.text()), w.checkState()]) else: cellUserInputList.append(-1) return cellUserInputList def NBR_render(self): global folderQueue for nk in xrange(len(folderQueue)): renderNode = [] # proj = os.path.splitext(os.path.basename(folderQueue[nk]))[0] projDict = self.NBR_getCellData(nk, 0, 'Project') if int(projDict['Project']) > 0: nodeArr = self.NBR_getCellNodeData(nk, 1) startDict = self.NBR_getCellData(nk, 2, 'Start') endDict = self.NBR_getCellData(nk, 3, 'End') # Write nodes loop for node in xrange(len(nodeArr)): if nodeArr[node][1] > 0: # get each node check state (0/2), selected write node (render) renderNode.append(nodeArr[node][0].split(":")[0]) # Debug print str(renderNode) # print nodeArr self.nukeProcess = QProcess(self) # QProcess for nuke print nodeArr[node][0].split(":")[0] # get each node from array self.nukeProcess.setProcessChannelMode(QProcess.MergedChannels) args = self.createCmdArg2(str(folderQueue[nk]), renderNode, startDict['Start'], endDict['End']) self.nukeProcess.start(NUKE_EXE, str(args)) self.nukeProcess.readyRead.connect(self.NBR_debug) self.nukeProcess.waitForFinished() self.nukeProcess.close()
class Kitty(QObject): """manage kitty process (terminals)""" exe_name = 'kitty' DELAY = 150 def __init__(self, ip, port, protocol, name, log_path, window_title, log_name, parent=None): QObject.__init__(self, parent) self.ip = ip self.port = port self.protocol = protocol self.log_path = log_path self.log_name = log_name self.id = str(os.getpid()) + name self.window_title = window_title self.terminal = QProcess() self.terminal.finished.connect(self.close) self.terminal.stateChanged.connect(self.state) self.send_process = QProcess() self.send_process.finished.connect(self.end_send) def open(self): """ kitty -telnet -P 9696 hostname """ if self.terminal.state() == QProcess.Running: return file_name = utils.set_log_name(self.log_name, self.log_path, ext='.txt') args = [ '-{}'.format(self.protocol), self.ip, '-P', self.port, '-log', os.path.join(self.log_path, file_name), '-title', self.window_title, '-classname', self.id ] while self.terminal.state() == QProcess.NotRunning: self.terminal.start(os.path.join(dep_dir, Kitty.exe_name), args) self.terminal.waitForStarted() QThread.msleep(Kitty.DELAY) def send(self, text): if self.send_process.state() == QProcess.Running: self.send_process.close() self.show_terminal() args = ['-classname', self.id, '-sendcmd', text] self.send_process.start(os.path.join(dep_dir, Kitty.exe_name), args) self.send_process.waitForStarted() self.send_process.waitForFinished() QThread.msleep(Kitty.DELAY) def show_terminal(self): if self.terminal.state() == QProcess.NotRunning: return autowin.show_window(autowin.get_qprocess_pid(self.terminal.pid())) QThread.msleep(Kitty.DELAY) @staticmethod def show_main(): autowin.show_window(os.getpid()) def end_send(self): pass def close(self): self.terminal.close() def state(self, st): print(st)
class RenderW(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.ui = ui_render.Ui_RenderW() self.ui.setupUi(self) self.fFreewheel = False self.fLastTime = -1 self.fMaxTime = 180 self.fTimer = QTimer(self) self.fProcess = QProcess(self) # ------------------------------------------------------------- # Get JACK client and base information global gJackClient if gJackClient: self.fJackClient = gJackClient else: self.fJackClient = jacklib.client_open("Render-Dialog", jacklib.JackNoStartServer, None) self.fBufferSize = int(jacklib.get_buffer_size(self.fJackClient)) self.fSampleRate = int(jacklib.get_sample_rate(self.fJackClient)) for i in range(self.ui.cb_buffer_size.count()): if int(self.ui.cb_buffer_size.itemText(i)) == self.fBufferSize: self.ui.cb_buffer_size.setCurrentIndex(i) break else: self.ui.cb_buffer_size.addItem(str(self.fBufferSize)) self.ui.cb_buffer_size.setCurrentIndex(self.ui.cb_buffer_size.count() - 1) # ------------------------------------------------------------- # Set-up GUI stuff # Get List of formats self.fProcess.start(gJackCapturePath, ["-pf"]) self.fProcess.waitForFinished() formats = str(self.fProcess.readAllStandardOutput(), encoding="utf-8").split(" ") formatsList = [] for i in range(len(formats) - 1): iFormat = formats[i].strip() if iFormat: formatsList.append(iFormat) formatsList.sort() # Put all formats in combo-box, select 'wav' option for i in range(len(formatsList)): self.ui.cb_format.addItem(formatsList[i]) if formatsList[i] == "wav": self.ui.cb_format.setCurrentIndex(i) self.ui.cb_depth.setCurrentIndex(4) #Float self.ui.rb_stereo.setChecked(True) self.ui.te_end.setTime(QTime(0, 3, 0)) self.ui.progressBar.setFormat("") self.ui.progressBar.setMinimum(0) self.ui.progressBar.setMaximum(1) self.ui.progressBar.setValue(0) self.ui.b_render.setIcon(getIcon("media-record")) self.ui.b_stop.setIcon(getIcon("media-playback-stop")) self.ui.b_close.setIcon(getIcon("window-close")) self.ui.b_open.setIcon(getIcon("document-open")) self.ui.b_stop.setVisible(False) self.ui.le_folder.setText(HOME) # ------------------------------------------------------------- # Set-up connections self.connect(self.ui.b_render, SIGNAL("clicked()"), SLOT("slot_renderStart()")) self.connect(self.ui.b_stop, SIGNAL("clicked()"), SLOT("slot_renderStop()")) self.connect(self.ui.b_open, SIGNAL("clicked()"), SLOT("slot_getAndSetPath()")) self.connect(self.ui.b_now_start, SIGNAL("clicked()"), SLOT("slot_setStartNow()")) self.connect(self.ui.b_now_end, SIGNAL("clicked()"), SLOT("slot_setEndNow()")) self.connect(self.ui.te_start, SIGNAL("timeChanged(const QTime)"), SLOT("slot_updateStartTime(const QTime)")) self.connect(self.ui.te_end, SIGNAL("timeChanged(const QTime)"), SLOT("slot_updateEndTime(const QTime)")) self.connect(self.ui.group_time, SIGNAL("clicked(bool)"), SLOT("slot_transportChecked(bool)")) self.connect(self.fTimer, SIGNAL("timeout()"), SLOT("slot_updateProgressbar()")) # ------------------------------------------------------------- self.loadSettings() @pyqtSlot() def slot_renderStart(self): if not os.path.exists(self.ui.le_folder.text()): QMessageBox.warning(self, self.tr("Warning"), self.tr("The selected directory does not exist. Please choose a valid one.")) return timeStart = self.ui.te_start.time() timeEnd = self.ui.te_end.time() minTime = (timeStart.hour() * 3600) + (timeStart.minute() * 60) + (timeStart.second()) maxTime = (timeEnd.hour() * 3600) + (timeEnd.minute() * 60) + (timeEnd.second()) newBufferSize = int(self.ui.cb_buffer_size.currentText()) useTransport = self.ui.group_time.isChecked() self.fFreewheel = bool(self.ui.cb_render_mode.currentIndex() == 1) self.fLastTime = -1 self.fMaxTime = maxTime if self.fFreewheel: self.fTimer.setInterval(100) else: self.fTimer.setInterval(500) self.ui.group_render.setEnabled(False) self.ui.group_time.setEnabled(False) self.ui.group_encoding.setEnabled(False) self.ui.b_render.setVisible(False) self.ui.b_stop.setVisible(True) self.ui.b_close.setEnabled(False) if useTransport: self.ui.progressBar.setFormat("%p%") self.ui.progressBar.setMinimum(minTime) self.ui.progressBar.setMaximum(maxTime) self.ui.progressBar.setValue(minTime) else: self.ui.progressBar.setFormat("") self.ui.progressBar.setMinimum(0) self.ui.progressBar.setMaximum(0) self.ui.progressBar.setValue(0) self.ui.progressBar.update() arguments = [] # Filename prefix arguments.append("-fp") arguments.append(self.ui.le_prefix.text()) # Format arguments.append("-f") arguments.append(self.ui.cb_format.currentText()) # Bit depth arguments.append("-b") arguments.append(self.ui.cb_depth.currentText()) # Channels arguments.append("-c") if self.ui.rb_mono.isChecked(): arguments.append("1") elif self.ui.rb_stereo.isChecked(): arguments.append("2") else: arguments.append(str(self.ui.sb_channels.value())) # Controlled only by freewheel if self.fFreewheel: arguments.append("-jf") # Controlled by transport elif useTransport: arguments.append("-jt") # Silent mode arguments.append("-dc") arguments.append("-s") # Change current directory os.chdir(self.ui.le_folder.text()) if newBufferSize != int(jacklib.get_buffer_size(self.fJackClient)): print("NOTICE: buffer size changed before render") jacklib.set_buffer_size(self.fJackClient, newBufferSize) if useTransport: if jacklib.transport_query(self.fJackClient, None) > jacklib.JackTransportStopped: # rolling or starting jacklib.transport_stop(self.fJackClient) jacklib.transport_locate(self.fJackClient, minTime * self.fSampleRate) self.fProcess.start(gJackCapturePath, arguments) self.fProcess.waitForStarted() if self.fFreewheel: print("NOTICE: rendering in freewheel mode") sleep(1) jacklib.set_freewheel(self.fJackClient, 1) if useTransport: self.fTimer.start() jacklib.transport_start(self.fJackClient) @pyqtSlot() def slot_renderStop(self): useTransport = self.ui.group_time.isChecked() if useTransport: jacklib.transport_stop(self.fJackClient) if self.fFreewheel: jacklib.set_freewheel(self.fJackClient, 0) sleep(1) self.fProcess.close() if useTransport: self.fTimer.stop() self.ui.group_render.setEnabled(True) self.ui.group_time.setEnabled(True) self.ui.group_encoding.setEnabled(True) self.ui.b_render.setVisible(True) self.ui.b_stop.setVisible(False) self.ui.b_close.setEnabled(True) self.ui.progressBar.setFormat("") self.ui.progressBar.setMinimum(0) self.ui.progressBar.setMaximum(1) self.ui.progressBar.setValue(0) self.ui.progressBar.update() # Restore buffer size newBufferSize = int(jacklib.get_buffer_size(self.fJackClient)) if newBufferSize != self.fBufferSize: jacklib.set_buffer_size(self.fJackClient, newBufferSize) @pyqtSlot() def slot_getAndSetPath(self): getAndSetPath(self, self.ui.le_folder.text(), self.ui.le_folder) @pyqtSlot() def slot_setStartNow(self): time = int(jacklib.get_current_transport_frame(self.fJackClient) / self.fSampleRate) secs = time % 60 mins = int(time / 60) % 60 hrs = int(time / 3600) % 60 self.ui.te_start.setTime(QTime(hrs, mins, secs)) @pyqtSlot() def slot_setEndNow(self): time = int(jacklib.get_current_transport_frame(self.fJackClient) / self.fSampleRate) secs = time % 60 mins = int(time / 60) % 60 hrs = int(time / 3600) % 60 self.ui.te_end.setTime(QTime(hrs, mins, secs)) @pyqtSlot(QTime) def slot_updateStartTime(self, time): if time >= self.ui.te_end.time(): self.ui.te_end.setTime(time) renderEnabled = False else: renderEnabled = True if self.ui.group_time.isChecked(): self.ui.b_render.setEnabled(renderEnabled) @pyqtSlot(QTime) def slot_updateEndTime(self, time): if time <= self.ui.te_start.time(): self.ui.te_start.setTime(time) renderEnabled = False else: renderEnabled = True if self.ui.group_time.isChecked(): self.ui.b_render.setEnabled(renderEnabled) @pyqtSlot(bool) def slot_transportChecked(self, yesNo): if yesNo: renderEnabled = bool(self.ui.te_end.time() > self.ui.te_start.time()) else: renderEnabled = True self.ui.b_render.setEnabled(renderEnabled) @pyqtSlot() def slot_updateProgressbar(self): time = int(jacklib.get_current_transport_frame(self.fJackClient)) / self.fSampleRate self.ui.progressBar.setValue(time) if time > self.fMaxTime or (self.fLastTime > time and not self.fFreewheel): self.slot_renderStop() self.fLastTime = time def saveSettings(self): settings = QSettings("Cadence", "Cadence-Render") if self.ui.rb_mono.isChecked(): channels = 1 elif self.ui.rb_stereo.isChecked(): channels = 2 else: channels = self.ui.sb_channels.value() settings.setValue("Geometry", self.saveGeometry()) settings.setValue("OutputFolder", self.ui.le_folder.text()) settings.setValue("FilenamePrefix", self.ui.le_prefix.text()) settings.setValue("EncodingFormat", self.ui.cb_format.currentText()) settings.setValue("EncodingDepth", self.ui.cb_depth.currentText()) settings.setValue("EncodingChannels", channels) settings.setValue("UseTransport", self.ui.group_time.isChecked()) settings.setValue("StartTime", self.ui.te_start.time()) settings.setValue("EndTime", self.ui.te_end.time()) def loadSettings(self): settings = QSettings("Cadence", "Cadence-Render") self.restoreGeometry(settings.value("Geometry", "")) outputFolder = settings.value("OutputFolder", HOME) if os.path.exists(outputFolder): self.ui.le_folder.setText(outputFolder) self.ui.le_prefix.setText(settings.value("FilenamePrefix", "jack_capture_")) encFormat = settings.value("EncodingFormat", "Wav", type=str) for i in range(self.ui.cb_format.count()): if self.ui.cb_format.itemText(i) == encFormat: self.ui.cb_format.setCurrentIndex(i) break encDepth = settings.value("EncodingDepth", "Float", type=str) for i in range(self.ui.cb_depth.count()): if self.ui.cb_depth.itemText(i) == encDepth: self.ui.cb_depth.setCurrentIndex(i) break encChannels = settings.value("EncodingChannels", 2, type=int) if encChannels == 1: self.ui.rb_mono.setChecked(True) elif encChannels == 2: self.ui.rb_stereo.setChecked(True) else: self.ui.rb_outro.setChecked(True) self.ui.sb_channels.setValue(encChannels) self.ui.group_time.setChecked(settings.value("UseTransport", False, type=bool)) self.ui.te_start.setTime(settings.value("StartTime", self.ui.te_start.time(), type=QTime)) self.ui.te_end.setTime(settings.value("EndTime", self.ui.te_end.time(), type=QTime)) def closeEvent(self, event): self.saveSettings() if self.fJackClient: jacklib.client_close(self.fJackClient) QDialog.closeEvent(self, event) def done(self, r): QDialog.done(self, r) self.close()
class pat_toolbar: """QGIS Plugin Implementation.""" def __init__(self, iface): """Constructor. Args: iface (QgsInterface): An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir, 'i18n', 'pat_plugin_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) self.actions = [] # Look for the existing menu self.menuPrecAg = self.iface.mainWindow().findChild(QMenu, 'm{}Menu'.format(PLUGIN_SHORT)) # If the menu does not exist, create it! if not self.menuPrecAg: self.menuPrecAg = QMenu('{}'.format(PLUGIN_SHORT), self.iface.mainWindow().menuBar()) self.menuPrecAg.setObjectName('m{}Menu'.format(PLUGIN_SHORT)) actions = self.iface.mainWindow().menuBar().actions() lastAction = actions[-1] self.iface.mainWindow().menuBar().insertMenu(lastAction, self.menuPrecAg) # create a toolbar self.toolbar = self.iface.addToolBar(u'{} Toolbar'.format(PLUGIN_SHORT)) self.toolbar.setObjectName(u'm{}ToolBar'.format(PLUGIN_SHORT)) # Load Defaults settings for First time... for eaKey in ['BASE_IN_FOLDER', 'BASE_OUT_FOLDER']: sFolder = read_setting(PLUGIN_NAME + '/' + eaKey) if sFolder is None or not os.path.exists(sFolder): sFolder = os.path.join(os.path.expanduser('~'), PLUGIN_NAME) if not os.path.exists(sFolder): os.mkdir(sFolder) write_setting(PLUGIN_NAME + '/' + eaKey, os.path.join(os.path.expanduser('~'), PLUGIN_NAME)) self.DEBUG = config.get_debug_mode() self.vesper_queue = [] self.vesper_queue_showing = False self.processVesper = None self.vesper_exe = check_vesper_dependency(iface) if not os.path.exists(TEMPDIR): os.mkdir(TEMPDIR) def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. Args: message (str, QString): String for translation. Returns: QString: Translated version of message. """ return QCoreApplication.translate('pat', message) def add_action(self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, tool_tip=None, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. Args: icon_path (str): Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. text (str): Text that should be shown in menu items for this action. callback (function): Function to be called when the action is triggered. enabled_flag (bool): A flag indicating if the action should be enabled by default. Defaults to True. add_to_menu (bool): Flag indicating whether the action should also be added to the menu. Defaults to True. add_to_toolbar (bool): Flag indicating whether the action should also be added to the toolbar. Defaults to True. tool_tip (str): Optional text to show in a popup when mouse pointer hovers over the action. status_tip (str): Optional text to show in the status bar when mouse pointer hovers over the action. whats_this (QWidget): Parent widget for the new action. Defaults None. parent (): Optional text to show in the status bar when the mouse pointer hovers over the action. Returns: QAction: The action that was created. Note that the action is also added to self.actions list. """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if tool_tip is not None: action.setToolTip(tool_tip) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.menuPrecAg.addAction(action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" '''Create new menu item source:https://gis.stackexchange.com/questions/169869/adding-multiple-plugins-to-custom-pluginMenu-in-qgis/169880#169880 https://gis.stackexchange.com/questions/127150/how-to-customize-the-qgis-gui-using-python ''' # Finally, add your action to the menu and toolbar self.add_action( icon_path=':/plugins/pat/icons/icon_blockGrid.svg', text=self.tr(u'Create block grid'), tool_tip=self.tr(u'Create raster and VESPER grids for block polygons.'), status_tip=self.tr(u'Create raster and VESPER grids for block polygons.'), callback=self.run_blockGrid, parent=self.iface.mainWindow()) self.add_action( icon_path=':/plugins/pat/icons/icon_cleanTrimPoints.svg', text=self.tr(u'Clean, trim and normalise data points'), tool_tip=self.tr(u'Clean, trim and normalise data points'), status_tip=self.tr(u'Clean, trim and normalise data points'), callback=self.run_cleanTrimPoints, parent=self.iface.mainWindow()) self.add_action( icon_path=':/plugins/pat/icons/icon_vesperKriging.svg', text=self.tr(u'Run kriging using VESPER'), tool_tip=self.tr(u'Run kriging using VESPER'), status_tip=self.tr(u'Run kriging using VESPER'), callback=self.run_preVesper, parent=self.iface.mainWindow()) self.add_action( icon_path=':/plugins/pat/icons/icon_importVesperKriging.svg', text=self.tr(u'Import VESPER results'), tool_tip=self.tr(u'Import VESPER results'), status_tip=self.tr(u'Import VESPER results'), add_to_toolbar=False, callback=self.run_postVesper, parent=self.iface.mainWindow()) self.add_action( icon_path=':/plugins/pat/icons/icon_pointTrailToPolygon.svg', text=self.tr(u'Create polygons from on-the-go GPS point trail'), tool_tip=self.tr(u'Create polygons from on-the-go GPS point trail'), status_tip=self.tr(u'Create polygons from on-the-go GPS point trail'), add_to_toolbar=False, callback=self.run_pointTrailToPolygon, parent=self.iface.mainWindow()) self.add_action( icon_path=':/plugins/pat/icons/icon_rescaleNormalise.svg', text=self.tr(u'Rescale or normalise raster'), tool_tip=self.tr(u'Rescale or normalise raster'), status_tip=self.tr(u'Rescale or normalise raster'), add_to_toolbar=False, callback=self.run_rescaleNormalise, parent=self.iface.mainWindow()) self.add_action( icon_path=':/plugins/pat/icons/icon_randomPixel.svg', text=self.tr(u'Generate random pixel selection'), tool_tip=self.tr(u'Generate random pixel selection'), status_tip=self.tr(u'Generate random pixel selection'), add_to_toolbar=True, callback=self.run_generateRandomPixels, parent=self.iface.mainWindow()) self.add_action( icon_path=':/plugins/pat/icons/icon_gridExtract.svg', text=self.tr(u'Extract raster pixel statistics for points'), tool_tip=self.tr(u'Extract raster pixel statistics for points'), status_tip=self.tr(u'Extract raster pixel statistics for points'), add_to_toolbar=True, callback=self.run_gridExtract, parent=self.iface.mainWindow()) self.add_action( icon_path=':/plugins/pat/icons/icon_calcImgIndices.svg', text=self.tr(u'Calculate image indices for blocks'), tool_tip=self.tr(u'Calculate image indices for blocks'), status_tip=self.tr(u'Calculate image indices for blocks'), add_to_toolbar=True, callback=self.run_calculateImageIndices, parent=self.iface.mainWindow()) self.add_action( icon_path=':/plugins/pat/icons/icon_resampleToBlock.svg', text=self.tr(u'Resample image band to blocks'), tool_tip=self.tr(u'Resample image band to blocks'), status_tip=self.tr(u'Resample image band to blocks'), add_to_toolbar=True, callback=self.run_resampleImage2Block, parent=self.iface.mainWindow()) self.add_action( icon_path=':/plugins/pat/icons/icon_kMeansCluster.svg', text=self.tr(u'Create zones with k-means clustering'), tool_tip=self.tr(u'Create zones with k-means clustering'), status_tip=self.tr(u'Create zones with k-means clustering'), add_to_toolbar=True, callback=self.run_kMeansClustering, parent=self.iface.mainWindow()) self.add_action( icon_path=':/plugins/pat/icons/icon_stripTrialPoints.svg', text=self.tr(u'Create strip trial points'), tool_tip=self.tr(u'Create strip trial points'), status_tip=self.tr(u'Create strip trial points'), add_to_toolbar=True, callback=self.run_stripTrialPoints, parent=self.iface.mainWindow()) self.add_action( icon_path=':/plugins/pat/icons/icon_t-test.svg', text=self.tr(u'Run strip trial t-test analysis'), tool_tip=self.tr(u'Run strip trial t-test analysis'), status_tip=self.tr(u'Run strip trial t-test analysis'), add_to_toolbar=True, callback=self.run_tTestAnalysis, parent=self.iface.mainWindow()) self.add_action( icon_path=':/plugins/pat/icons/icon_wholeOfBlockExp.svg', text=self.tr(u'Whole-of-block analysis'), tool_tip=self.tr(u'Whole-of-block analysis using co-kriging'), status_tip=self.tr(u'Whole-of-block analysis using co-kriging'), add_to_toolbar=True, callback=self.run_wholeOfBlockAnalysis, parent=self.iface.mainWindow()) self.add_action( icon_path=':/plugins/pat/icons/icon_persistor.svg', text=self.tr(u'Persistor'), tool_tip=self.tr(u'Persistence over years'), status_tip=self.tr(u'Persistence over years'), add_to_toolbar=True, callback=self.run_persistor, parent=self.iface.mainWindow()) self.add_action( icon_path=':/plugins/pat/icons/icon_rasterSymbology.svg', text=self.tr(u'Apply Raster Symbology'), tool_tip=self.tr(u'Apply Raster Symbology'), status_tip=self.tr(u'Apply Raster Symbology'), add_to_toolbar=True, callback=self.run_rasterSymbology, parent=self.iface.mainWindow()) self.add_action( icon_path=':/plugins/pat/icons/icon_help.svg', text=self.tr(u'Help'), tool_tip=self.tr(u'Help'), status_tip=self.tr(u'Help'), callback=self.run_help, parent=self.iface.mainWindow()) self.add_action( icon_path=':/plugins/pat/icons/icon_settings.svg', text=self.tr(u'Settings'), tool_tip=self.tr(u'Settings'), add_to_toolbar=False, status_tip=self.tr(u'Settings'), callback=self.run_settings, parent=self.iface.mainWindow()) self.add_action( icon_path=':/plugins/pat/icons/icon_about.svg', text=self.tr(u'About'), tool_tip=self.tr(u'About'), status_tip=self.tr(u'About'), add_to_toolbar=False, callback=self.run_about, parent=self.iface.mainWindow()) @staticmethod def clear_modules(): """Unload pyprecag functions and try to return QGIS. source: inasafe plugin """ # next lets force remove any pyprecag related modules modules = [] for module in sys.modules: if 'pyprecag' in module: LOGGER.debug('Removing: %s' % module) modules.append(module) for module in modules: del (sys.modules[module]) # Lets also clean up all the path additions that were made package_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) LOGGER.debug('Path to remove: %s' % package_path) # We use a list comprehension to ensure duplicate entries are removed LOGGER.debug(sys.path) sys.path = [y for y in sys.path if package_path not in y] LOGGER.debug(sys.path) def unload(self): """Removes the plugin menu/toolbar item and icon from QGIS GUI and clean up temp folder""" if len(self.vesper_queue) > 0: replyQuit = QMessageBox.information(self.iface.mainWindow(), "Quit QGIS", "Quitting QGIS with {} tasks in the " "VESPER queue.\n\t{}".format(len(self.vesper_queue), '\n\t'.join([ea['control_file'] for ea in self.vesper_queue])), QMessageBox.Ok) stop_logging('pyprecag') layermap = QgsMapLayerRegistry.instance().mapLayers() RemoveLayers = [] for name, layer in layermap.iteritems(): if TEMPDIR in layer.source(): RemoveLayers.append(layer.id()) if len(RemoveLayers) > 0: QgsMapLayerRegistry.instance().removeMapLayers(RemoveLayers) # remove the PrecisionAg Temp Folder. try: if not self.DEBUG and os.path.exists(TEMPDIR): shutil.rmtree(TEMPDIR) except Exception as err: exc_type, exc_value, exc_traceback = sys.exc_info() mess = str(traceback.format_exc()) print(mess) self.menuPrecAg.clear() for action in self.actions: self.iface.removePluginMenu(u'{}Menu'.format(PLUGIN_SHORT), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar del self.menuPrecAg self.clear_modules() def queueAddTo(self, vesp_dict): """ Add a control file to the VESPER queue""" if next((x for x in self.vesper_queue if x['control_file'] == vesp_dict["control_file"]) , None) is not None: self.iface.messageBar().pushMessage('Control file is already in the VESPER queue. {}'.format( vesp_dict['control_file']),level=QgsMessageBar.WARNING, duration=15) self.queueDisplay() else: self.vesper_queue.append(vesp_dict) message = 'Added control file to VESPER queue. The queue now contains {} tasks'.format( len(self.vesper_queue)) self.iface.messageBar().pushMessage(message, level=QgsMessageBar.INFO, duration=15) def queueDisplay(self): """display the VESPER queue in the python console""" # open the python console try: pythonConsolePanel = self.iface.mainWindow().findChild(QDockWidget, 'PythonConsole') if not pythonConsolePanel.isVisible(): self.iface.actionShowPythonDialog().trigger() except: # the above will bail if sitting on RecentProjects empty view. self.iface.actionShowPythonDialog().trigger() pythonConsolePanel = self.iface.mainWindow().findChild(QDockWidget, 'PythonConsole') ctrl_width = len(max([os.path.basename(ea['control_file']) for ea in self.vesper_queue], key=len)) epsg_width = len(max([str(ea['epsg']) for ea in self.vesper_queue], key=len)) header = '{:3}\t{:<{cw}}\t{:5}\t{:>{ew}} {}'.format( '#', 'Control File', 'Import', 'EPSG', 'Folder', cw=ctrl_width + 10, ew=epsg_width + 10) print('\n' + '-' * len(header)) print(header) print('-' * len(header)) for i, ea in enumerate(self.vesper_queue): print('{:3}\t{:<{cw}}\t{:5}\t{:>{ew}}\t{}'.format( i + 1, os.path.basename(ea['control_file']), str(bool(ea['epsg'] > 0)), ea['epsg'], os.path.dirname(ea['control_file']), cw=ctrl_width + 10, ew=epsg_width + 10)) print('\n') def queueClear(self): """Clear the VESPER queue of all pending jobs""" # clear all but the one running. if self.processVesper is None: self.vesper_queue = [] self.queueStatusBarHide() else: self.vesper_queue = self.vesper_queue[:1] self.lblVesperQueue.setText('{} tasks in VESPER queue'.format(len(self.vesper_queue))) self.queueDisplay() def queueStatusBarShow(self): """Add to QGIS status bar buttons to show and clear the VESPER queue""" # source: https://gis.stackexchange.com/a/153170 # https://github.com/ActiveState/code/blob/master/recipes/Python/578692_QGstartscript_Change_display/recipe-578692.py if not self.vesper_queue_showing: # it is not initiated self.iface.mainWindow().statusBar().setSizeGripEnabled(False) self.lblVesperQueue = QLabel() self.lblVesperQueue.setText('{} tasks in VESPER queue'.format(len(self.vesper_queue))) self.iface.mainWindow().statusBar().insertPermanentWidget(1, self.lblVesperQueue) self.btnShowQueue = QToolButton() # QToolButton() takes up less room self.btnShowQueue.setToolButtonStyle(Qt.ToolButtonTextOnly) self.btnShowQueue.setText("Show") self.btnShowQueue.clicked.connect(self.queueDisplay) self.iface.mainWindow().statusBar().insertPermanentWidget(2, self.btnShowQueue) self.btnClearQueue = QToolButton() # QPushButton() self.btnClearQueue.setToolButtonStyle(Qt.ToolButtonTextOnly) self.btnClearQueue.setText("Clear") self.btnClearQueue.pressed.connect(self.queueClear) self.iface.mainWindow().statusBar().insertPermanentWidget(3, self.btnClearQueue) self.vesper_queue_showing = True def queueStatusBarHide(self): """Remove VESPER queue information and buttons from the status bar""" for obj in [self.btnClearQueue, self.btnShowQueue, self.lblVesperQueue]: self.iface.mainWindow().statusBar().removeWidget(obj) del obj self.vesper_queue_showing = False def processRunVesper(self): """Run the next task in the VESPER queue""" # Queueing: http://www.qtforum.org/article/32172/qprocess-how-to-run-multiple-processes-in-a-loop.html self.vesper_run_time = time.time() if self.processVesper is None: self.processVesper = QProcess() # set a duration variable self.processVesper.started.connect(self.processStartedVesper) # sets a task for when finished. self.processVesper.finished.connect(self.processFinishedVesper) self.queueStatusBarShow() ctrl_file = self.vesper_queue[0]['control_file'] self.processVesper.setWorkingDirectory(os.path.dirname(ctrl_file)) # run and catch when finished: https://gist.github.com/justinfx/5174795 1)QProcess QTimer.singleShot(100, partial(self.processVesper.start, self.vesper_exe, [ctrl_file])) def processStartedVesper(self): # connected to process.started slot self.vesper_run_time = time.time() def processFinishedVesper(self, exitCode, exitStatus): # connected to process.finished slot """When VESPER is complete, import the results to TIFF and QGIS""" currentTask = self.vesper_queue[0] if exitCode == 0 and exitStatus == QProcess.NormalExit: self.processVesper.close() self.processVesper = None if currentTask['epsg'] > 0: try: out_PredTif, out_SETif, out_CITxt = vesper_text_to_raster(currentTask['control_file'], currentTask['epsg']) raster_sym = RASTER_SYMBOLOGY['Yield'] removeFileFromQGIS(out_PredTif) rasterLyr = addRasterFileToQGIS(out_PredTif, atTop=False) raster_apply_classified_renderer(rasterLyr, rend_type=raster_sym['type'], num_classes=raster_sym['num_classes'], color_ramp=raster_sym['colour_ramp']) removeFileFromQGIS(out_SETif) addRasterFileToQGIS(out_SETif, atTop=False) except Exception as err: message = "Could not import from VESPER to raster TIFF possibly due to a " \ "VESPER error.\n{}".format(os.path.basename(currentTask['control_file'])) LOGGER.error(message) message = "Completed VESPER kriging for {}\t Duration H:M:SS - {dur}".format( os.path.basename(currentTask['control_file']), dur=datetime.timedelta(seconds=time.time() - self.vesper_run_time)) self.iface.messageBar().pushMessage(message, level=QgsMessageBar.INFO, duration=15) LOGGER.info(message) else: message = "Error occurred with VESPER kriging for {}".format(currentTask['control_file']) self.iface.messageBar().pushMessage(message, level=QgsMessageBar.CRITICAL, duration=0) LOGGER.error(message) self.vesper_queue = self.vesper_queue[1:] # remove the recently finished one which will always be at position 0 self.lblVesperQueue.setText('{} tasks in VESPER queue'.format(len(self.vesper_queue))) if len(self.vesper_queue) > 0: self.vesper_run_time = time.time() self.processRunVesper() else: self.vesper_queue = [] self.vesper_run_time = '' self.queueStatusBarHide() return def run_persistor(self): """Run method for the Persistor dialog""" if parse_version(pyprecag.__version__) < parse_version('0.2.0'): self.iface.messageBar().pushMessage("Persistor is not supported in " "pyprecag {}. Upgrade to version 0.3.0+".format( pyprecag.__version__), level=QgsMessageBar.WARNING, duration=15) return dlgPersistor = PersistorDialog(self.iface) # Show the dialog dlgPersistor.show() if dlgPersistor.exec_(): message = 'Persistor completed successfully !' self.iface.messageBar().pushMessage(message, level=QgsMessageBar.SUCCESS, duration=15) # LOGGER.info(message) # Close Dialog dlgPersistor.deleteLater() # Refresh QGIS QCoreApplication.processEvents() def run_wholeOfBlockAnalysis(self): """Run method for the fit to block grid dialog""" # https://gis.stackexchange.com/a/160146 result = check_R_dependency() if result is not True: self.iface.messageBar().pushMessage("R configuration", result, level=QgsMessageBar.WARNING, duration=15) return proc_alg_mess = ProcessingAlgMessages(self.iface) QgsMessageLog.instance().messageReceived.connect(proc_alg_mess.processingCatcher) # Then get the algorithm you're interested in (for instance, Join Attributes): alg = Processing.getAlgorithm("r:wholeofblockanalysis") if alg is None: self.iface.messageBar().pushMessage("Whole-of-block analysis algorithm could not" " be found", level=QgsMessageBar.CRITICAL) return # Instantiate the commander window and open the algorithm's interface cw = CommanderWindow(self.iface.mainWindow(), self.iface.mapCanvas()) if alg is not None: cw.runAlgorithm(alg) # if proc_alg_mess.alg_name == '' then cancel was clicked if proc_alg_mess.error: self.iface.messageBar().pushMessage("Whole-of-block analysis", proc_alg_mess.error_msg, level=QgsMessageBar.CRITICAL, duration=0) elif proc_alg_mess.alg_name != '': data_column = proc_alg_mess.parameters['Data_Column'] # load rasters into qgis as grouped layers. for key, val in proc_alg_mess.output_files.items(): grplyr = os.path.join('Whole-of-block {}'.format(data_column), val['title']) for ea_file in val['files']: removeFileFromQGIS(ea_file) raster_layer = addRasterFileToQGIS(ea_file, group_layer_name=grplyr, atTop=False) if key in ['p_val']: raster_apply_unique_value_renderer(raster_layer) self.iface.messageBar().pushMessage("Whole-of-block analysis Completed Successfully!", level=QgsMessageBar.INFO, duration=15) del proc_alg_mess def run_stripTrialPoints(self): if parse_version(pyprecag.__version__) < parse_version('0.2.0'): self.iface.messageBar().pushMessage( "Create strip trial points tool is not supported in pyprecag {}. " "Upgrade to version 0.2.0+".format(pyprecag.__version__), level=QgsMessageBar.WARNING, duration=15) return """Run method for the Strip trial points dialog""" dlgStripTrialPoints = StripTrialPointsDialog(self.iface) # Show the dialog dlgStripTrialPoints.show() if dlgStripTrialPoints.exec_(): message = 'Strip trial points created successfully !' self.iface.messageBar().pushMessage(message, level=QgsMessageBar.SUCCESS, duration=15) # LOGGER.info(message) # Close Dialog dlgStripTrialPoints.deleteLater() # Refresh QGIS QCoreApplication.processEvents() def run_tTestAnalysis(self): if parse_version(pyprecag.__version__) < parse_version('0.3.0'): self.iface.messageBar().pushMessage("Create t-test analysis tool is not supported in " "pyprecag {}. Upgrade to version 0.3.0+".format( pyprecag.__version__), level=QgsMessageBar.WARNING, duration=15) return """Run method for the Strip trial points dialog""" dlg_tTestAnalysis = tTestAnalysisDialog(self.iface) # Show the dialog dlg_tTestAnalysis.show() if dlg_tTestAnalysis.exec_(): output_folder = dlg_tTestAnalysis.lneOutputFolder.text() import webbrowser try: from urllib import pathname2url # Python 2.x except: from urllib.request import pathname2url # Python 3.x def open_folder(): url = 'file:{}'.format(pathname2url(os.path.abspath(output_folder))) webbrowser.open(url) message = 'Strip trial t-test analysis completed!' # Add hyperlink to messagebar - this works but it places the text on the right, not left. # variation of QGIS-master\python\plugins\db_manager\db_tree.py # msgLabel = QLabel(self.tr('{0} <a href="{1}">{1}</a>'.format(message, output_folder)), self.iface.messageBar()) # msgLabel.linkActivated.connect(open_folder) # self.iface.messageBar().pushWidget(msgLabel,level=QgsMessageBar.SUCCESS, duration=15) # so use a button instead widget = self.iface.messageBar().createMessage('', message) button = QPushButton(widget) button.setText('Open Folder') button.pressed.connect(open_folder) widget.layout().addWidget(button) self.iface.messageBar().pushWidget(widget, level=QgsMessageBar.SUCCESS, duration=15) LOGGER.info(message) # Close Dialog dlg_tTestAnalysis.deleteLater() # Refresh QGIS QCoreApplication.processEvents() def run_kMeansClustering(self): """Run method for the Calculate Image Indices dialog""" dlgKMeansCluster = KMeansClusterDialog(self.iface) # Show the dialog dlgKMeansCluster.show() if dlgKMeansCluster.exec_(): message = 'Zones with k-means clusters completed successfully !' self.iface.messageBar().pushMessage(message, level=QgsMessageBar.SUCCESS, duration=15) # LOGGER.info(message) # Close Dialog dlgKMeansCluster.deleteLater() # Refresh QGIS QCoreApplication.processEvents() def run_calculateImageIndices(self): """Run method for the Calculate Image Indices dialog""" dlgCalcImgIndices = CalculateImageIndicesDialog(self.iface) # Show the dialog dlgCalcImgIndices.show() if dlgCalcImgIndices.exec_(): message = 'Image indices calculated successfully !' self.iface.messageBar().pushMessage(message, level=QgsMessageBar.SUCCESS, duration=15) LOGGER.info(message) # Close Dialog dlgCalcImgIndices.deleteLater() # Refresh QGIS QCoreApplication.processEvents() def run_resampleImage2Block(self): """Run method for the Resample image to block grid dialog""" dlgResample2Block = ResampleImageToBlockDialog(self.iface) # Show the dialog dlgResample2Block.show() if dlgResample2Block.exec_(): message = 'Resample to block grid completed Successfully !' self.iface.messageBar().pushMessage(message, level=QgsMessageBar.SUCCESS, duration=15) LOGGER.info(message) # Close Dialog dlgResample2Block.deleteLater() # Refresh QGIS QCoreApplication.processEvents() def run_gridExtract(self): """Run method for the Grid Extract dialog""" dlgGridExtract = GridExtractDialog(self.iface) # Show the dialog dlgGridExtract.show() if dlgGridExtract.exec_(): output_file = dlgGridExtract.lneSaveCSVFile.text() import webbrowser try: from urllib import pathname2url # Python 2.x except: from urllib.request import pathname2url # Python 3.x def open_folder(): url = 'file:{}'.format(pathname2url(os.path.abspath(output_file))) webbrowser.open(url) message = 'Raster statistics for points extracted successfully !' #add a button to open the file outside qgis widget = self.iface.messageBar().createMessage('', message) button = QPushButton(widget) button.setText('Open File') button.pressed.connect(open_folder) widget.layout().addWidget(button) self.iface.messageBar().pushWidget(widget, level=QgsMessageBar.SUCCESS, duration=15) LOGGER.info(message) # Close Dialog dlgGridExtract.deleteLater() # Refresh QGIS QCoreApplication.processEvents() def run_generateRandomPixels(self): """Run method for the Generate random pixels dialog""" dlgGenRandomPixel = RandomPixelSelectionDialog(self.iface) # Show the dialog dlgGenRandomPixel.show() if dlgGenRandomPixel.exec_(): message = 'Random pixel selection completed successfully !' self.iface.messageBar().pushMessage(message, level=QgsMessageBar.SUCCESS, duration=15) LOGGER.info(message) # Close Dialog dlgGenRandomPixel.deleteLater() # Refresh QGIS QCoreApplication.processEvents() def run_rescaleNormalise(self): """Run method for the rescale/normalise dialog""" dlgRescaleNorm = RescaleNormaliseDialog(self.iface) # Show the dialog dlgRescaleNorm.show() if dlgRescaleNorm.exec_(): message = 'Rescale/Normalise completed successfully !' self.iface.messageBar().pushMessage(message, level=QgsMessageBar.SUCCESS, duration=15) LOGGER.info(message) # Close Dialog dlgRescaleNorm.deleteLater() # Refresh QGIS QCoreApplication.processEvents() def run_preVesper(self): """Run method for preVesper dialog""" dlgPreVesper = PreVesperDialog(self.iface) # show the dialog dlgPreVesper.show() if dlgPreVesper.exec_(): if dlgPreVesper.gbRunVesper.isChecked(): self.queueAddTo(dlgPreVesper.vesp_dict) self.processRunVesper() if len(self.vesper_queue) > 0: self.lblVesperQueue.setText('{} tasks in VESPER queue'.format(len(self.vesper_queue))) # Close Dialog dlgPreVesper.deleteLater() # Refresh QGIS QCoreApplication.processEvents() def run_postVesper(self): """Run method for importing VESPER results dialog""" dlgPostVesper = PostVesperDialog(self.iface) # show the dialog dlgPostVesper.show() if dlgPostVesper.exec_(): if dlgPostVesper.chkRunVesper.isChecked(): self.queueAddTo(dlgPostVesper.vesp_dict) # if this is the first in the queue then start the processing. self.processRunVesper() if len(self.vesper_queue) > 0: self.lblVesperQueue.setText('{} tasks in VESPER queue'.format(len(self.vesper_queue))) # Close Dialog dlgPostVesper.deleteLater() # Refresh QGIS QCoreApplication.processEvents() def run_cleanTrimPoints(self): """Run method for cleanTrimPoints dialog""" dlgCleanTrimPoints = CleanTrimPointsDialog(self.iface) # show the dialog dlgCleanTrimPoints.show() if dlgCleanTrimPoints.exec_(): output_folder = os.path.dirname(dlgCleanTrimPoints.lneSaveCSVFile.text()) import webbrowser try: from urllib import pathname2url # Python 2.x except: from urllib.request import pathname2url # Python 3.x def open_folder(): url = 'file:{}'.format(pathname2url(os.path.abspath(output_folder))) webbrowser.open(url) message = 'Cleaned and trimmed points successfully !' widget = self.iface.messageBar().createMessage('', message) button = QPushButton(widget) button.setText('Open Folder') button.pressed.connect(open_folder) widget.layout().addWidget(button) self.iface.messageBar().pushWidget(widget, level=QgsMessageBar.SUCCESS, duration=15) LOGGER.info(message) # Close Dialog dlgCleanTrimPoints.deleteLater() # Refresh QGIS QCoreApplication.processEvents() def run_blockGrid(self): """Run method for the block grid dialog""" dlgBlockGrid = BlockGridDialog(self.iface) # Show the dialog dlgBlockGrid.show() if dlgBlockGrid.exec_(): message = 'Block grid completed successfully !' self.iface.messageBar().pushMessage(message, level=QgsMessageBar.SUCCESS, duration=15) LOGGER.info(message) # Close Dialog dlgBlockGrid.deleteLater() # Refresh QGIS QCoreApplication.processEvents() def run_pointTrailToPolygon(self): """Run method for pointTrailToPolygon dialog""" dlgPointTrailToPolygon = PointTrailToPolygonDialog(self.iface) # show the dialog dlgPointTrailToPolygon.show() if dlgPointTrailToPolygon.exec_(): message = 'On-the-go point trail to polygon completed successfully !' self.iface.messageBar().pushMessage(message, level=QgsMessageBar.SUCCESS, duration=15) LOGGER.info(message) # Close Dialog dlgPointTrailToPolygon.deleteLater() # Refresh QGIS QCoreApplication.processEvents() def run_rasterSymbology(self): """Run method for the Raster Symbology dialog""" dlgRasterSymbology = RasterSymbologyDialog(self.iface) # Show the dialog dlgRasterSymbology.show() if dlgRasterSymbology.exec_(): pass # Close Dialog dlgRasterSymbology.deleteLater() # Refresh QGIS QCoreApplication.processEvents() def run_help(self): """Open the help PDF""" webbrowser.open_new('file:///' + os.path.join(PLUGIN_DIR, 'PAT_User_Manual.pdf#pagemode=bookmarks')) def run_about(self): """Run method for the about dialog""" dlgAbout = AboutDialog() if dlgAbout.exec_(): pass dlgAbout.deleteLater() # Refresh QGIS QCoreApplication.processEvents() def run_settings(self): """Run method for the about dialog""" dlgSettings = SettingsDialog() if dlgSettings.exec_(): self.vesper_exe = dlgSettings.vesper_exe self.DEBUG = config.get_debug_mode() dlgSettings.deleteLater()
class NetWidget(QWidget): def __init__(self,parent = None): super(NetWidget,self).__init__(parent) self.setStyleSheet("font-size : 16px")#设置整体的字体大小 self.auto = False self.pro = QProcess(self) # self.tipDlg = TipDialog() # self.tipDlg.setModal(True)#引入tipdlg,并且将这个窗口设置为最前端窗口,且后面窗口无法操作 #初始化comBox控件,并且为其添加选项 self.comBox = QComboBox() self.comBox.setFixedWidth(120) self.comBox.insertItem(0, self.tr("ping")) self.comBox.insertItem(1, self.tr("ifconfig")) self.comBox.insertItem(2, self.tr("display")) #self.comBox.insertItem(3, self.tr("traceroute")) self.comBox.insertItem(4, self.tr("top")) self.connect(self.comBox, SIGNAL('activated(QString)'),self.onActivated)#设置combBox为活动的,与函数关联 """ #初始话控件设置 #lineEdit,固定长度 #runButton,显示字符串,信号量 #pingLabel,当前显示字符 #textBrower """ self.lineEdit = QLineEdit() self.lineEdit.setContextMenuPolicy(Qt.NoContextMenu) self.lineEdit.setFixedWidth(250) self.runButton = QPushButton(self.tr("Run")) self.runButton.setStyleSheet("background: rgb(7,87,198); color: white; width: 70px; height: 20px;font-size : 16px;") self.connect(self.runButton, SIGNAL("clicked()"),self.runButton_clicked) self.pingLabel = QLabel()#初始话,之后在函数操作中会改变 self.pingLabel.setText(self.tr("Tip:please input the IP address of pinging,then get the result with clicking the button")) self.textBrowser = QTextBrowser() """ #布局一上,横向布局 #将comBox,lineEdit,runButton添加到布局中 #设置前面空为20和后面空为280 """ hLayout1 = QHBoxLayout() hLayout1.addSpacing(20) hLayout1.addWidget(self.comBox) hLayout1.addWidget(self.lineEdit) hLayout1.addWidget(self.runButton) #hLayout1.addStretch() hLayout1.addSpacing(280) #布局二中,横向布局 #将pingLabel添加到布局中,并且诶设置前面的空白为20 hLayout2 = QHBoxLayout() hLayout2.addSpacing(20) hLayout2.addWidget(self.pingLabel) #布局三下 #将textBrower添加爱到布局中,并且设置前面空白为20,后面空白为60,控件的大小自适应 hLayout3 = QHBoxLayout() hLayout3.addSpacing(20) hLayout3.addWidget(self.textBrowser) hLayout3.addSpacing(60) #主题布局总,纵向布局 #将之上的三个布局添加到总布局中,并且设置布局间空间为20,最下面的空白为40 mainLayout = QVBoxLayout() mainLayout.addSpacing(20) mainLayout.addLayout(hLayout1) mainLayout.addSpacing(20) mainLayout.addLayout(hLayout2) mainLayout.addSpacing(20) mainLayout.addLayout(hLayout3) mainLayout.addSpacing(40) self.setLayout(mainLayout) self.thread = MyThread() self.connect(self.thread,SIGNAL("getoutput"),self.append) def append(self,actionType): self.textBrowser.clear() self.textBrowser.append(actionType) #cursor = QTextCursor() #self.runButton.setText(self.tr("Stop")) cursor = self.textBrowser.textCursor() cursor.movePosition(QTextCursor.Start) self.textBrowser.setTextCursor(cursor) #changeLabel = QLabel() def onActivated(self): language = StoreInfoParser.instance().getLanguage() m_pTranslator = QTranslator() exePath = "./" if language == "chinese": QmName = "zh_CN.qm" else: QmName = "en_US.qm" if(m_pTranslator.load(QmName, exePath)): QCoreApplication.instance().installTranslator(m_pTranslator) """#comBox的相应函数,随着comBox中字符串的改变,分别控制pingLabel的显示,以及lineEdit和textBrower的显示清除和可用状态 #如果comBox当前的字符串文字为ping #pingLabel的文字设置为"提示:请在文本框中输入要ping的目标地址,然后点击执行获取结果",保持当前大小 #lineEdit中内容清除,设置为不可用 #textBrower清空""" if(self.comBox.currentText() == "Ping" or self.comBox.currentText() == "ping"): self.pingLabel.setText(self.tr("Tip:please input the IP address of pinging,then get the result with clicking the button")) self.pingLabel.adjustSize() self.lineEdit.clear() self.lineEdit.setDisabled(False) self.textBrowser.clear() #如果comBox当前的字符串文字为ifconfig #类上所说 elif(self.comBox.currentText() == "ifconfig"): self.pingLabel.setText(self.tr("Tip:get the net information")) self.pingLabel.adjustSize() self.lineEdit.clear() self.lineEdit.setEnabled(False) self.textBrowser.clear() #如果comBox当前的字符串文字为display elif(self.comBox.currentText() == "display"): self.pingLabel.setText(self.tr("Tip:get the resolution information")) self.pingLabel.adjustSize() self.lineEdit.clear() self.lineEdit.setEnabled(False) self.textBrowser.clear() elif(self.comBox.currentText() == "top"): self.pingLabel.setText(self.tr("Tip:run tom command")) self.pingLabel.adjustSize() self.lineEdit.setEnabled(False) self.lineEdit.clear() self.textBrowser.clear() #按钮的响应函数 def runButton_clicked(self): language = StoreInfoParser.instance().getLanguage() m_pTranslator = QTranslator() exePath = "./" if language == "chinese": QmName = "zh_CN.qm" else: QmName = "en_US.qm" if(m_pTranslator.load(QmName, exePath)): QCoreApplication.instance().installTranslator(m_pTranslator) #self.pro = QProcess(self)#外部程序使用声明 desktop = QApplication.desktop()#获得桌面 self.textBrowser.clear()#清除 cmdstr = QString() center = QString() goal = QString() #comBox当前text为ping if (self.comBox.currentText() == "Ping" or self.comBox.currentText() == "ping"): if (self.runButton.text() == self.tr("Run")) : center = self.lineEdit.text().trimmed() if not center: InfoHintDialog(self.tr("please input the IP address")).exec_() # self.tipDlg.setTip(self.tr("请输入ping地址!!!")) # self.tipDlg.show() # self.tipDlg.move((desktop.width()-self.tipDlg.width())/2,(desktop.height()-self.tipDlg.height())/2) self.runButton.setText(self.tr("Run")) else: self.comBox.setDisabled(True) self.pro = QProcess(self) self.runButton.setText(self.tr("stop ping")) cmdstr = "ping " +center self.textBrowser.clear() self.textBrowser.append(self.tr(" ping ")+center+self.tr(" result:")) else: self.comBox.setDisabled(False) self.runButton.setText(self.tr("Run")) self.pro.close() elif(self.comBox.currentText() == "ifconfig"): self.pro = QProcess(self) self.lineEdit.clear() self.lineEdit.setEnabled(False) self.textBrowser.clear() cmdstr = "ifconfig" # #如果comBox当前为traceroute # elif(self.comBox.currentText() == "traceroute"): # goal = self.lineEdit.text() # if (self.runButton.text() == u"执行"): # if( goal.isEmpty() or goal.isNull() ): # InfoHintDialog(u'请输入tracer地址:').exec_() # # self.tipDlg.setTip(self.tr("请输入tracer地址:")) # # self.tipDlg.show() # # self.tipDlg.move((desktop.width()-self.tipDlg.width())/2,(desktop.height()-self.tipDlg.height())/2) # # # #QMessageBox.information(self,self.tr("错误"),self.tr("请输入traceroute的目标地址")) # #return # else: # self.proc = QProcess(self) # #self.textBrowser.clear() # cmdstrc = "traceroute -n "+ goal # self.proc.start(cmdstrc) # self.connect(self.proc, SIGNAL("readyReadStandardOutput()"),self.readR) # self.connect(self.proc, SIGNAL("readyReadStandardError()"),self.readErrorR) # if self.proc.waitForStarted(10) == True: # self.comBox.setDisabled(True) # self.runButton.setText(self.tr("停止执行")) # else: # self.runButton.setText(self.tr("执行")) # self.comBox.setDisabled(False) # self.proc.close() # #如果comBox当前为display elif (self.comBox.currentText() == "display"): self.pro = QProcess(self) cmdstr = "../lib/ccr_jytcapi display" self.textBrowser.clear() #如果当前命令cmdstr不为空,则 elif (self.comBox.currentText() == "top"): if self.runButton.text() == self.tr("Run") : self.thread.start() self.comBox.setDisabled(True) self.runButton.setText(self.tr("stop top")) else: self.textBrowser.clear() self.thread.auto = False #self.thread.destroyed() self.comBox.setDisabled(False) self.runButton.setText(self.tr("Run")) if (cmdstr != ""): self.pro.start(cmdstr)#开启执行命令 self.connect(self.pro, SIGNAL("readyReadStandardOutput()"),self.read)#读取执行正常输出槽函数 self.connect(self.pro, SIGNAL("readyReadStandardError()"),self.readError)#执行异常槽函数 #读取控制台输出 def read(self): res = QString.fromLocal8Bit(self.pro.readAllStandardOutput()) self.textBrowser.append(res)#添加到text框 #读取错误 def readError(self): res = QString.fromLocal8Bit(self.pro.readAllStandardError()) self.textBrowser.append(res) def readR(self): res = QString.fromLocal8Bit(self.proc.readAllStandardOutput()) #self.textBrowser.clear() self.textBrowser.append(res) def readErrorR(self): res = QString.fromLocal8Bit(self.proc.readAllStandardError()) self.textBrowser.append(res) def updateWindow(self): if self.pro.isOpen(): self.pro.close() self.thread.auto = False self.comBox.setDisabled(False) self.comBox.setCurrentIndex(0) self.runButton.setText((self.tr("Run"))) self.pingLabel.setText(self.tr("Tip:please input the IP address of pinging,then get the result with clicking the button")) self.textBrowser.clear()
class RenderW(QDialog, ui_render.Ui_RenderW): def __init__(self, parent): QDialog.__init__(self, parent) self.setupUi(self) # ------------------------------------------------------------- # Get JACK client and base information global jack_client if jack_client: self.m_jack_client = jack_client self.m_closeClient = False else: self.m_jack_client = jacklib.client_open("Render-Dialog", jacklib.JackNoStartServer, None) self.m_closeClient = True self.m_buffer_size = jacklib.get_buffer_size(self.m_jack_client) for i in range(self.cb_buffer_size.count()): if int(self.cb_buffer_size.itemText(i)) == self.m_buffer_size: self.cb_buffer_size.setCurrentIndex(i) self.m_sample_rate = jacklib.get_sample_rate(self.m_jack_client) # ------------------------------------------------------------- # Internal stuff self.m_max_time = 180 self.m_last_time = 0 self.m_freewheel = False self.m_timer = QTimer(self) self.m_process = QProcess(self) # ------------------------------------------------------------- # Set-up GUI stuff # Get List of formats self.m_process.start("jack_capture", ["-pf"]) self.m_process.waitForFinished() formats = str(self.m_process.readAllStandardOutput(), encoding="utf-8").split(" ") for i in range(len(formats) - 1): self.cb_format.addItem(formats[i]) if formats[i] == "wav": self.cb_format.setCurrentIndex(i) self.cb_depth.setCurrentIndex(4) # Float self.rb_stereo.setChecked(True) self.te_end.setTime(QTime(0, 3, 0)) self.progressBar.setMinimum(0) self.progressBar.setMaximum(0) self.progressBar.setValue(0) self.b_render.setIcon(getIcon("media-record")) self.b_stop.setIcon(getIcon("media-playback-stop")) self.b_close.setIcon(getIcon("window-close")) self.b_open.setIcon(getIcon("document-open")) self.b_stop.setVisible(False) self.le_folder.setText(HOME) # ------------------------------------------------------------- # Set-up connections self.connect(self.b_render, SIGNAL("clicked()"), SLOT("slot_renderStart()")) self.connect(self.b_stop, SIGNAL("clicked()"), SLOT("slot_renderStop()")) self.connect(self.b_open, SIGNAL("clicked()"), SLOT("slot_getAndSetPath()")) self.connect(self.b_now_start, SIGNAL("clicked()"), SLOT("slot_setStartNow()")) self.connect(self.b_now_end, SIGNAL("clicked()"), SLOT("slot_setEndNow()")) self.connect(self.te_start, SIGNAL("timeChanged(const QTime)"), SLOT("slot_updateStartTime(const QTime)")) self.connect(self.te_end, SIGNAL("timeChanged(const QTime)"), SLOT("slot_updateEndTime(const QTime)")) self.connect(self.m_timer, SIGNAL("timeout()"), SLOT("slot_updateProgressbar()")) @pyqtSlot() def slot_renderStart(self): if not os.path.exists(self.le_folder.text()): QMessageBox.warning( self, self.tr("Warning"), self.tr("The selected directory does not exist. Please choose a valid one.") ) return self.group_render.setEnabled(False) self.group_time.setEnabled(False) self.group_encoding.setEnabled(False) self.b_render.setVisible(False) self.b_stop.setVisible(True) self.b_close.setEnabled(False) self.m_freewheel = bool(self.cb_render_mode.currentIndex() == 1) new_buffer_size = int(self.cb_buffer_size.currentText()) time_start = self.te_start.time() time_end = self.te_end.time() min_time = (time_start.hour() * 3600) + (time_start.minute() * 60) + (time_start.second()) max_time = (time_end.hour() * 3600) + (time_end.minute() * 60) + (time_end.second()) self.m_max_time = max_time self.progressBar.setMinimum(min_time) self.progressBar.setMaximum(max_time) self.progressBar.setValue(min_time) self.progressBar.update() if self.m_freewheel: self.m_timer.setInterval(100) else: self.m_timer.setInterval(500) arguments = [] # Bit depth arguments.append("-b") arguments.append(self.cb_depth.currentText()) # Channels arguments.append("-c") if self.rb_mono.isChecked(): arguments.append("1") elif self.rb_stereo.isChecked(): arguments.append("2") else: arguments.append(str(self.sb_channels.value())) # Format arguments.append("-f") arguments.append(self.cb_format.currentText()) # Controlled by transport arguments.append("-jt") # Silent mode arguments.append("-dc") arguments.append("-s") # Change current directory os.chdir(self.le_folder.text()) if new_buffer_size != jacklib.get_buffer_size(self.m_jack_client): print("NOTICE: buffer size changed before render") jacklib.set_buffer_size(self.m_jack_client, new_buffer_size) if ( jacklib.transport_query(self.m_jack_client, None) > jacklib.JackTransportStopped ): # >TransportStopped is rolling/starting jacklib.transport_stop(self.m_jack_client) jacklib.transport_locate(self.m_jack_client, min_time * self.m_sample_rate) self.m_last_time = -1 self.m_process.start("jack_capture", arguments) self.m_process.waitForStarted() if self.m_freewheel: print("NOTICE: rendering in freewheel mode") sleep(1) jacklib.set_freewheel(self.m_jack_client, 1) self.m_timer.start() jacklib.transport_start(self.m_jack_client) @pyqtSlot() def slot_renderStop(self): jacklib.transport_stop(self.m_jack_client) if self.m_freewheel: jacklib.set_freewheel(self.m_jack_client, 0) sleep(1) self.m_process.close() self.m_timer.stop() self.group_render.setEnabled(True) self.group_time.setEnabled(True) self.group_encoding.setEnabled(True) self.b_render.setVisible(True) self.b_stop.setVisible(False) self.b_close.setEnabled(True) self.progressBar.setMinimum(0) self.progressBar.setMaximum(0) self.progressBar.setValue(0) self.progressBar.update() # Restore buffer size new_buffer_size = jacklib.get_buffer_size(self.m_jack_client) if new_buffer_size != self.m_buffer_size: jacklib.set_buffer_size(self.m_jack_client, new_buffer_size) @pyqtSlot() def slot_getAndSetPath(self): getAndSetPath(self, self.le_folder.text(), self.le_folder) @pyqtSlot() def slot_setStartNow(self): time = jacklib.get_current_transport_frame(self.m_jack_client) / self.m_sample_rate secs = time % 60 mins = (time / 60) % 60 hrs = (time / 3600) % 60 self.te_start.setTime(QTime(hrs, mins, secs)) @pyqtSlot() def slot_setEndNow(self): time = jacklib.get_current_transport_frame(self.m_jack_client) / self.m_sample_rate secs = time % 60 mins = (time / 60) % 60 hrs = (time / 3600) % 60 self.te_end.setTime(QTime(hrs, mins, secs)) @pyqtSlot(QTime) def slot_updateStartTime(self, time): if time >= self.te_end.time(): self.te_end.setTime(time) self.b_render.setEnabled(False) else: self.b_render.setEnabled(True) @pyqtSlot(QTime) def slot_updateEndTime(self, time): if time <= self.te_start.time(): self.te_start.setTime(time) self.b_render.setEnabled(False) else: self.b_render.setEnabled(True) @pyqtSlot() def slot_updateProgressbar(self): time = jacklib.get_current_transport_frame(self.m_jack_client) / self.m_sample_rate self.progressBar.setValue(time) if time > self.m_max_time or (self.m_last_time > time and not self.m_freewheel): self.slot_renderStop() self.m_last_time = time def closeEvent(self, event): if self.m_closeClient: jacklib.client_close(self.m_jack_client) QDialog.closeEvent(self, event) def done(self, r): QDialog.done(self, r) self.close()