def __changeDirectory(self, path): for c in self.filesview: c.setParent(None) c.deleteLater() self.filesview = [] self.checkBox_2.setChecked(False) self.progressBars = {} for f in self.__getFiles(path): try: group = QGroupBox(f, self) group.setGeometry(QRect(20, 20, 100, 150)) group.setCheckable(True) group.setChecked(False) group.setFixedSize(100, 150) group.setFlat(True) group.setToolTip(f) label = QLabel(group) label.setScaledContents(True) label.setGeometry(QRect(5, 25, 90, 90)) label.setToolTip(f) progressBar = QProgressBar(group) progressBar.setGeometry(QRect(0, 70, 111, 10)) progressBar.setProperty("value", 0) progressBar.setTextVisible(False) progressBar.setToolTip('0%') progressBar.setVisible(False) self.progressBars[f] = progressBar self.filesview.append(group) from os.path import isfile if isfile(path + '/' + f): ext = f.split('.')[-1] if isfile('icons/' + ext.lower() + '.png'): label.setPixmap( QPixmap('icons/' + ext.lower() + '.png')) else: label.setPixmap(QPixmap('icons/default.png')) else: label.setPixmap(QPixmap('icons/folder.png')) self.connect(group, SIGNAL("clicked()"), self.__deselectFile) except ValueError: pass i = 0 for x in list(range(len(self.filesview))): if (x % 4) == 0: i = i + 1 self.rowsview[i].addWidget(self.filesview[x])
class ProgressDialog(QDialog): """ Progress dialog """ def __init__(self, dialogName, parent=None): """ Constructor @param dialogName: @type dialogName: @param parent: @type parent: """ QDialog.__init__(self, parent) self.setWindowIcon(QIcon(":/main.png")) self.name = dialogName self.createDialog() def createDialog(self): """ Create qt dialog """ self.setWindowTitle("%s" % self.name) layout = QVBoxLayout() self.loadingLabel = QLabel("Loading...") self.imageLabel = QLabel() layout2 = QHBoxLayout() layout2.addWidget(self.imageLabel) layout2.addWidget(self.loadingLabel) self.progressBar = QProgressBar(self) self.progressBar.setMaximum(0) self.progressBar.setProperty("value", 0) self.progressBar.setAlignment(Qt.AlignCenter) self.progressBar.setObjectName("progressBar") layout.addLayout(layout2) layout.addWidget(self.progressBar) self.setLayout(layout) flags = Qt.WindowFlags() flags |= Qt.MSWindowsFixedSizeDialogHint self.setWindowFlags(flags)
class TaskTableElem: ############################ def __init__(self, id, status): self.id = id self.status = status self.progress = 0.0 self.idItem = None self.progressBar = None self.progressBarInBoxLayoutWidget = None self.statusItem = None self.__buildRow() ############################ def __buildRow(self): self.idItem = QTableWidgetItem() self.idItem.setText(self.id) self.progressBar = QProgressBar() self.progressBar.geometry().setHeight(20) self.progressBar.setProperty("value", 50) self.progressBarInBoxLayoutWidget = QWidget() boxLayout = QVBoxLayout() boxLayout.setMargin(3) boxLayout.addWidget(self.progressBar) self.progressBarInBoxLayoutWidget.setLayout(boxLayout) self.statusItem = QTableWidgetItem() self.statusItem.setText(self.status) ############################ def setProgress(self, val): if val >= 0.0 and val <= 1.0: self.progress = val else: assert False, "Wrong progress setting {}".format(val) def getColumnItem(self, col): if col == 0: return self.idItem if col == 1: return self.statusItem assert False, "Wrong column index"
class DMessage(VDialog): def __init__(self, parent): VDialog.__init__(self, parent) self.resize(450, 150) self.gLayout = QGridLayout(self) self.pBulunan = QPushButton(self) self.pBulunan.setEnabled(False) self.pBulunan.clicked.connect(self.bulunan) self.gLayout.addWidget(self.pBulunan, 3, 2, 1, 1) self.mesaj = QLabel(self) self.gLayout.addWidget(self.mesaj, 0, 0, 1, 3) self.pBar = QProgressBar(self) self.pBar.setProperty("value", 0) self.gLayout.addWidget(self.pBar, 1, 0, 1, 3) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gLayout.addItem(spacerItem, 3, 0, 1, 1) spacerItem1 = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Fixed) self.gLayout.addItem(spacerItem1, 2, 0, 1, 3) self.setWindowTitle(u"Sistemi taramaya karar verdim...") self.pBulunan.setText(u"Bulunan Virüsleri Sil") self.mesaj.setText(u"") self.mesaj.setMaximumWidth(430) self.progress = Thread(self) self.progress.start() self.connect(self.progress, SIGNAL("setValue"), self.pBar.setValue) self.mesaj.setText(u"Dosya bilgileri alınıyor...") def bulunan(self): QMessageBox.information(self, u"Sildim gitti!", u"Sayamayacağım kadar virüs silindi!", u"Bileğine Kuvvet!") self.close() @staticmethod def getOption(): return Option()
class DHttpReplay(QtHelper.EnhancedQDialog, Logger.ClassLogger): """ Http replay dialog """ def __init__(self, parent=None, offlineMode=False): """ Constructor @param parent: @type parent: """ super(DHttpReplay, self).__init__(parent) self.offlineMode = offlineMode self.defaultIp = "127.0.0.1" self.defaultPort = "80" self.newTest = '' self.newTestExec = '' self.newInputs = [] self.requests = [] self.responses = [] self.defaultTemplates = DefaultTemplates.Templates() self.testType = None self.createDialog() self.createConnections() self.createActions() self.createToolbar() def createActions(self): """ Create qt actions """ self.openAction = QtHelper.createAction(self, "&Open", self.importTrace, icon=QIcon(":/folder_add.png"), tip='Open network trace.') self.exportTUAction = QtHelper.createAction( self, "&Test Unit", self.exportToTU, icon=QIcon(":/%s.png" % WWorkspace.TestUnit.TYPE), tip='Export to Test Unit') self.exportTSAction = QtHelper.createAction( self, "&Test Suite", self.exportToTS, icon=QIcon(":/%s.png" % WWorkspace.TestSuite.TYPE), tip='Export to Test Suite') self.cancelAction = QtHelper.createAction(self, "&Cancel", self.reject, tip='Cancel') menu = QMenu(self) menu.addAction(self.exportTUAction) menu.addAction(self.exportTSAction) self.exportToAction = QtHelper.createAction( self, "&Export to", self.exportToTU, icon=QIcon(":/%s.png" % WWorkspace.TestUnit.TYPE), tip='Export to tests') self.exportToAction.setMenu(menu) self.exportToAction.setEnabled(False) def createDialog(self): """ Create dialog """ self.dockToolbar = QToolBar(self) self.dockToolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self.setWindowTitle(WINDOW_TITLE) self.resize(500, 400) self.ipEdit = QLineEdit(self.defaultIp) ipRegExpVal = QRegExpValidator(self) ipRegExp = QRegExp("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}") ipRegExpVal.setRegExp(ipRegExp) self.ipEdit.setValidator(ipRegExpVal) self.portEdit = QLineEdit(self.defaultPort) self.portEdit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) validatorPort = QIntValidator(self) self.portEdit.setValidator(validatorPort) self.progressBar = QProgressBar(self) self.progressBar.setMaximum(100) self.progressBar.setProperty("value", 0) self.progressBar.setAlignment(Qt.AlignCenter) self.progressBar.setObjectName("progressBar") self.guiSikuliGroupBox = QGroupBox("") self.guiSikuliGroupBox.setFlat(True) self.automaticAdp = QRadioButton("Automatic") self.automaticAdp.setChecked(True) self.defaultAdp = QRadioButton("Default") self.genericAdp = QRadioButton("Generic") vbox = QHBoxLayout() vbox.addWidget(self.automaticAdp) vbox.addWidget(self.defaultAdp) vbox.addWidget(self.genericAdp) vbox.addStretch(1) self.guiSikuliGroupBox.setLayout(vbox) layout = QVBoxLayout() layout.addWidget(self.dockToolbar) layout.addSpacing(12) paramLayout = QGridLayout() paramLayout.addWidget(QLabel("Destination IP:"), 0, 0, Qt.AlignRight) paramLayout.addWidget(self.ipEdit, 0, 1) paramLayout.addWidget(QLabel("Destination Port:"), 1, 0, Qt.AlignRight) paramLayout.addWidget(self.portEdit, 1, 1) paramLayout.addWidget(QLabel(self.tr("Gui adapter selector:")), 2, 0, Qt.AlignRight) paramLayout.addWidget(self.guiSikuliGroupBox, 2, 1) layout.addLayout(paramLayout) self.logsEdit = QTextEdit() self.logsEdit.setReadOnly(True) self.logsEdit.setTextInteractionFlags(Qt.NoTextInteraction) layout.addSpacing(12) layout.addWidget(self.logsEdit) layout.addSpacing(12) layout.addWidget(self.progressBar) self.setLayout(layout) def createToolbar(self): """ Create toolbar """ self.dockToolbar.setObjectName("File toolbar") self.dockToolbar.addAction(self.openAction) self.dockToolbar.addSeparator() self.dockToolbar.addAction(self.exportToAction) self.dockToolbar.addSeparator() self.dockToolbar.setIconSize(QSize(16, 16)) def createConnections(self): """ Create qt connections """ pass def autoScrollOnTextEdit(self): """ Automatic scroll on text edit """ cursor = self.logsEdit.textCursor() cursor.movePosition(QTextCursor.End) self.logsEdit.setTextCursor(cursor) def strip_html(self, txt): """ Strip html """ if "<" in txt: txt = txt.replace('<', '<') if ">" in txt: txt = txt.replace('>', '>') return txt def addLogSuccess(self, txt): """ Add log success in the text edit """ self.logsEdit.insertHtml( "<span style='color:darkgreen'>%s</span><br />" % unicode(self.strip_html(txt))) self.autoScrollOnTextEdit() def addLogWarning(self, txt): """ Add log warning in the text edit """ self.logsEdit.insertHtml( "<span style='color:darkorange'>%s</span><br />" % unicode(self.strip_html(txt))) self.autoScrollOnTextEdit() def addLogError(self, txt): """ Add log error in the text edit """ self.logsEdit.insertHtml("<span style='color:red'>%s</span><br />" % unicode(self.strip_html(txt))) self.autoScrollOnTextEdit() def addLog(self, txt): """ Append log to the logsEdit widget """ self.logsEdit.insertHtml("%s<br />" % unicode(self.strip_html(txt))) self.autoScrollOnTextEdit() def importTrace(self): """ Import network trace """ self.logsEdit.clear() self.testType = None if not self.offlineMode: if not RCI.instance().isAuthenticated(): self.addLogWarning( txt="<< Connect to the test center in first!") QMessageBox.warning(self, "Import", "Connect to the test center in first!") return self.exportToAction.setEnabled(False) self.newTest = '' self.progressBar.setMaximum(100) self.progressBar.setValue(0) if sys.version_info > (3, ): fileName = QFileDialog.getOpenFileName( self, self.tr("Open File"), "", "Network dump (*.cap;*.pcap;*.pcapng)") else: fileName = QFileDialog.getOpenFileName(self, self.tr("Open File"), "", "Network dump (*.cap)") # new in v18 to support qt5 if QtHelper.IS_QT5: _fileName, _type = fileName else: _fileName = fileName # end of new if not _fileName: return if sys.version_info < (3, ): extension = str(_fileName).rsplit(".", 1)[1] if not (extension == "cap"): self.addLogError(txt="<< File not supported %s" % _fileName) QMessageBox.critical(self, "Open", "File not supported") return _fileName = str(_fileName) capName = _fileName.rsplit("/", 1)[1] self.addLogSuccess(txt=">> Reading the file %s" % _fileName) if sys.version_info > (3, ): self.readFileV2(fileName=_fileName) else: self.readFile(fileName=_fileName) def exportToTS(self): """ Export to test suite """ self.testType = TS self.exportToTest(TS=True, TU=False) def exportToTU(self): """ Export to test unit """ self.testType = TU self.exportToTest(TS=False, TU=True) def searchHTTP(self): """ Search HTTP module in assistant """ # modules accessor ret = "SutAdapters" if self.automaticAdp.isChecked(): isGeneric = WWorkspace.Helper.instance().isGuiGeneric(name="GUI") if isGeneric: ret = "SutAdapters.Generic" elif self.defaultAdp.isChecked(): return ret elif self.genericAdp.isChecked(): ret = "SutAdapters.Generic" else: pass return ret def exportToTest(self, TS=True, TU=False): """ Export to test """ if not RCI.instance().isAuthenticated(): self.addLogWarning(txt="<< Connect to the test center in first!") QMessageBox.warning(self, "Import", "Connect to the test center in first!") return if TS: self.newTest = self.defaultTemplates.getTestDefinitionAuto() self.newTestExec = self.defaultTemplates.getTestExecutionAuto() if TU: self.newTest = self.defaultTemplates.getTestUnitDefinitionAuto() destIp = str(self.ipEdit.text()) destPort = str(self.portEdit.text()) self.newInputs = [] self.newInputs.append({ 'type': 'self-ip', 'name': 'BIND_IP', 'description': '', 'value': '0.0.0.0', 'color': '' }) self.newInputs.append({ 'type': 'int', 'name': 'BIND_PORT', 'description': '', 'value': '0', 'color': '' }) self.newInputs.append({ 'type': 'str', 'name': 'DEST_IP', 'description': '', 'value': '%s' % destIp, 'color': '' }) self.newInputs.append({ 'type': 'int', 'name': 'DEST_PORT', 'description': '', 'value': '%s' % destPort, 'color': '' }) self.newInputs.append({ 'type': 'bool', 'name': 'DEBUG', 'description': '', 'value': 'False', 'color': '' }) self.newInputs.append({ 'type': 'float', 'name': 'TIMEOUT', 'description': '', 'value': '5.0', 'color': '' }) adps = """self.ADP_HTTP = %s.HTTP.Client(parent=self, bindIp=input('BIND_IP'), bindPort=input('BIND_PORT'), destinationIp=input('DEST_IP'), destinationPort=input('DEST_PORT'), debug=input('DEBUG'))""" % self.searchHTTP( ) # prepare steps steps = [] j = 0 for i in xrange(len(self.requests)): j = i + 1 if sys.version_info > (3, ): # python3 support (source, dest, source_port, dest_port, buf_req, reqDecoded) = self.requests[i] http_method = str(reqDecoded['method'], 'utf8') http_status = 'no' http_reason = '' else: http_method = self.requests[i]['tcp-object'].method http_status = 'no' http_reason = '' try: if sys.version_info > (3, ): # python3 support (sourceRsp, destRsp, sourcePortRsp, destPortRsp, bufReqRsp, reqDecodedRsp) = self.responses[i] http_status = str(reqDecodedRsp['code']) http_reason = str(reqDecodedRsp['phrase'], 'utf8') else: http_status = self.responses[i]['tcp-object'].status http_reason = self.responses[i]['tcp-object'].reason except Exception as e: print(e) steps.append( 'self.step%s = self.addStep(expected="%s %s response", description="send %s request", summary="send %s request")' % (j, http_status, http_reason, http_method, http_method)) tests = [] for i in xrange(len(self.requests)): j = i + 1 if sys.version_info > (3, ): # python3 support (source, dest, source_port, dest_port, buf_req, reqDecoded) = self.requests[i] tests.append("# request %s" % j) tests.append('self.step%s.start()' % j) if sys.version_info > (3, ): # python3 support lines_req = buf_req.splitlines() else: lines_req = self.requests[i]['tcp-data'].splitlines() if sys.version_info > (3, ): # python3 support tests.append('rawHttp = [%s]' % lines_req[0].replace(b'"', b'\\"')) else: tests.append('rawHttp = ["%s"]' % lines_req[0].replace(b'"', b'\\"')) for lreq in lines_req[1:]: if sys.version_info > (3, ): # python3 support tests.append('rawHttp.append(%s)' % lreq.replace(b'"', b'\\"')) else: tests.append('rawHttp.append("%s")' % lreq.replace(b'"', b'\\"')) tests.append('') tests.append( 'req_tpl = self.ADP_HTTP.constructTemplateRequest(rawHttp=rawHttp)' ) tests.append('req = self.ADP_HTTP.sendRequest(tpl=req_tpl)') try: tests.append('') if sys.version_info > (3, ): # python3 support (sourceRsp, destRsp, sourcePortRsp, destPortRsp, bufReqRsp, reqDecodedRsp) = self.responses[i] lines_res = bufReqRsp.splitlines() else: lines_res = self.responses[i]['tcp-data'].splitlines() if sys.version_info > (3, ): # python3 support tests.append('rawHttpRsp = [%s]' % lines_res[0].replace(b"'", b"\\'")) else: tests.append('rawHttpRsp = ["%s"]' % lines_res[0].replace(b'"', b'\\"')) for lres in lines_res[1:]: if sys.version_info > (3, ): # python3 support tests.append('rawHttpRsp.append(%s)' % lres.replace(b"'", b"\\'")) else: tests.append('rawHttpRsp.append("%s")' % lres.replace(b'"', b'\\"')) except Exception as e: self.error("unable to append response: %s" % e) tests.append( 'rsp_tpl = self.ADP_HTTP.constructTemplateResponse(rawHttp=rawHttpRsp)' ) tests.append( "rsp = self.ADP_HTTP.hasReceivedResponse(expected=rsp_tpl, timeout=input('TIMEOUT'))" ) tests.append('if rsp is None:') tests.append( '\tself.step%s.setFailed(actual="incorrect response")' % j) tests.append('else:') tests.append('\tself.step%s.setPassed(actual="ok")' % j) tests.append('') if TS: init = """self.ADP_HTTP.connect() connected = self.ADP_HTTP.isConnected( timeout=input('TIMEOUT') ) if not connected: self.abort( 'unable to connect to the tcp port %s' ) """ % str(self.portEdit.text()) if TU: init = """self.ADP_HTTP.connect() connected = self.ADP_HTTP.isConnected( timeout=input('TIMEOUT') ) if not connected: self.abort( 'unable to connect to the tcp port %s' ) """ % str(self.portEdit.text()) if TS: cleanup = """self.ADP_HTTP.disconnect() disconnected = self.ADP_HTTP.isDisconnected( timeout=input('TIMEOUT') ) if not disconnected: self.error( 'unable to disconnect from the tcp port %s' ) """ % str(self.portEdit.text()) if TU: cleanup = """self.ADP_HTTP.disconnect() disconnected = self.ADP_HTTP.isDisconnected( timeout=input('TIMEOUT') ) if not disconnected: self.error( 'unable to disconnect from the tcp port %s' ) """ % str(self.portEdit.text()) self.newTest = self.newTest.replace( "<<PURPOSE>>", 'self.setPurpose(purpose="Replay HTTP")') self.newTest = self.newTest.replace("<<ADPS>>", adps) if TS: self.newTest = self.newTest.replace("<<STEPS>>", '\n\t\t'.join(steps)) if TU: self.newTest = self.newTest.replace("<<STEPS>>", '\n\t'.join(steps)) self.newTest = self.newTest.replace("<<INIT>>", init) self.newTest = self.newTest.replace("<<CLEANUP>>", cleanup) if TS: self.newTest = self.newTest.replace("<<TESTS>>", '\n\t\t'.join(tests)) if TU: self.newTest = self.newTest.replace("<<TESTS>>", '\n\t'.join(tests)) self.accept() def decodeHttpRequest(self, data): """ Decode http request Content chunked not yet implemented """ http = {"type": "request"} lines = data.splitlines() try: request_line = lines[0] except Exception: self.error("unable to decode http request: %s" % lines) return None try: http["method"] = request_line.split(b" ", 2)[0] http["uri"] = request_line.split(b" ", 2)[1] http["version"] = request_line.split(b" ", )[2] except Exception: self.error( "unable to decode status code in the http response: %s" % request_line) return None http["body"] = data.split(b"\r\n\r\n")[1] headers = [] contentLenght = 0 contentChunked = False for hdr in data.split(b"\r\n\r\n")[0].splitlines()[1:]: if len(hdr): k, v = hdr.split(b":", 1) if k.lower() == b"content-length": contentLenght = int(v) if k.lower() == b"transfer-encoding": if v.lowert() == b"chunked": contentChunked = True headers.append(hdr) http["headers"] = headers if len(http["body"]) != contentLenght: return None # need more data return http def decodeHttpResponse(self, data): """ Decode http response without body """ http = {"type": "response"} lines = data.splitlines() try: status_line = lines[0] except Exception: self.error("unable to decode http response: %s" % lines) return None try: http["code"] = int(status_line.split(b" ")[1]) http["phrase"] = status_line.split(b" ", 2)[2] except Exception: self.error( "unable to decode status code in the http response: %s" % status_line) return None http["headers"] = lines[1:] return http def readFileV2(self, fileName): """ Read pcap file Support pcap-ng too """ fd = open(fileName, 'rb') fileFormat, fileHead = PcapParse.extractFormat(fd) if fileFormat == PcapParse.FileFormat.PCAP: self.trace("pcap file detected") pcapFile = PcapReader.PcapFile(fd, fileHead).read_packet self.readFilePacket(pcapFile=pcapFile) elif fileFormat == PcapParse.FileFormat.PCAP_NG: self.trace("pcap-png file detected") pcapFile = PcapngReader.PcapngFile(fd, fileHead).read_packet self.readFilePacket(pcapFile=pcapFile) else: self.addLogError(txt="<< Error to open the network trace") self.error('unable to open the network trace: file format = %s' % fileFormat) QMessageBox.critical(self, "Import", "File not supported") def __readRequest(self, buffer, data, request, output): """ Read request """ buffer += data if b'\r\n\r\n' in data: reqDecoded = self.decodeHttpRequest(data=buffer) if reqDecoded is not None: output.append(request + (reqDecoded, )) buffer = b'' else: print("need more data: decode request failed") else: print("need more data, no body separator detected on request") def readFilePacket(self, pcapFile): """ Read file packet by packet """ ip_expected = str(self.ipEdit.text()) port_expected = int(self.portEdit.text()) # read packet) packets = pcapFile() ethernetPackets = list(packets) self.addLogSuccess(txt="<< Number of packets detected: %s " % len(ethernetPackets)) # extract tcp packet according to the expected ip and port tcpPacketsSent = [] tcpPacketsRecv = [] i = 1 self.progressBar.setMaximum(len(ethernetPackets)) self.progressBar.setValue(0) for pkt in ethernetPackets: self.progressBar.setValue(i) i += 1 pktDecoded = PcapParse.decodePacket(pkt, getTcp=True, getUdp=False) if pktDecoded is not None: (source, dest, source_port, dest_port, data) = pktDecoded # skip when no data exists if dest == ip_expected and int(dest_port) == int( port_expected) and len(data) > 0: tcpPacketsSent.append(pktDecoded) if source == ip_expected and int(source_port) == int( port_expected) and len(data) > 0: tcpPacketsRecv.append(pktDecoded) self.addLogSuccess(txt="<< Number of TCP packets sent: %s " % len(tcpPacketsSent)) self.addLogSuccess(txt="<< Number of TCP packets received: %s " % len(tcpPacketsRecv)) # decode https requests self.requests = [] buf_req = b'' i = 1 self.progressBar.setMaximum(len(tcpPacketsSent)) self.progressBar.setValue(0) # decode the complete packet for req in tcpPacketsSent: self.progressBar.setValue(i) i += 1 (source, dest, source_port, dest_port, data) = req if buf_req: buf_req += data if b'\r\n\r\n' in data: reqDecoded = self.decodeHttpRequest(data=buf_req) if reqDecoded is not None: self.requests.append((source, dest, source_port, dest_port, buf_req, reqDecoded)) buf_req = b'' else: if isRequest(data): buf_req += data if b'\r\n\r\n' in data: reqDecoded = self.decodeHttpRequest(data=buf_req) if reqDecoded is not None: self.requests.append( (source, dest, source_port, dest_port, buf_req, reqDecoded)) buf_req = b'' self.addLogSuccess(txt="<< Number of HTTP requests extracted: %s " % len(self.requests)) # decode https response self.responses = [] buf_rsp = b'' i = 1 self.progressBar.setMaximum(len(tcpPacketsRecv)) self.progressBar.setValue(0) # decode just headers for response for req in tcpPacketsRecv: self.progressBar.setValue(i) i += 1 (source, dest, source_port, dest_port, data) = req if buf_rsp: buf_rsp += data # try to decode response without body if b'\r\n\r\n' in data: rspDecoded = self.decodeHttpResponse(data=buf_rsp) if rspDecoded is not None: self.responses.append((source, dest, source_port, dest_port, buf_rsp, rspDecoded)) buf_rsp = b'' else: # is http response ? if data.startswith(b'HTTP/'): buf_rsp += data if b'\r\n\r\n' in data: rspDecoded = self.decodeHttpResponse(data=buf_rsp) if rspDecoded is not None: self.responses.append( (source, dest, source_port, dest_port, buf_rsp, rspDecoded)) buf_rsp = b'' self.addLogSuccess(txt="<< Number of HTTP responses extracted: %s " % len(self.responses)) if self.requests: self.addLogSuccess("<< Read the file finished with success!") self.addLogWarning( "<< Click on the export button to generate the test!") self.exportToAction.setEnabled(True) else: self.addLogWarning("<< No http extracted!") def readFile(self, fileName): """ Read the file passed as argument Old function with dtpkt and python2.7 """ self.requests = [] self.responses = [] ip_expected = socket.inet_aton(str(self.ipEdit.text())) port_expected = str(self.portEdit.text()) try: f = open(fileName, 'rb') pcap = dpkt.pcap.Reader(f) tot_pkts = len(list(pcap)) except Exception as e: self.addLogError(txt="<< Error to open the network trace") self.error('unable to open the network trace: %s' % str(e)) QMessageBox.critical(self, "Import", "File not supported") return else: self.addLogSuccess(txt="<< Total packets detected: %s " % tot_pkts) self.progressBar.setMaximum(tot_pkts) # decode http request i = 1 buf_req = '' for ts, buf in pcap: self.progressBar.setValue(i) i += 1 # read ethernet layer eth = dpkt.ethernet.Ethernet(buf) if eth.type == dpkt.ethernet.ETH_TYPE_IP: # continue with ip decoding layer ip = eth.data if ip.dst == ip_expected: ip_layer = (ip.src, ip.dst) if ip.p == dpkt.ip.IP_PROTO_TCP: tcp = ip.data if tcp.dport == int(port_expected) and len( tcp.data) > 0: tcp_layer = (tcp.sport, tcp.dport) buf_req += tcp.data try: http_req = dpkt.http.Request(buf_req) except dpkt.dpkt.NeedData as e: pass except dpkt.UnpackError as e: pass else: self.requests.append({ 'ip-src': ip.src, 'ip-dst': ip.dst, 'port-src': tcp.sport, 'port-dst': tcp.dport, 'tcp-data': buf_req, 'tcp-object': http_req }) self.addLogWarning( txt="<< %s http request(s) extracted" % len(self.requests)) buf_req = '' # decode http responses i = 1 self.progressBar.setValue(0) for ts, buf in pcap: self.progressBar.setValue(i) i += 1 # read ethernet layer eth = dpkt.ethernet.Ethernet(buf) if eth.type == dpkt.ethernet.ETH_TYPE_IP: # continue with ip decoding layer ip = eth.data if ip.src == ip_expected: ip_layer = (ip.src, ip.dst) if ip.p == dpkt.ip.IP_PROTO_TCP: tcp = ip.data if tcp.sport == int(port_expected) and len( tcp.data) > 0: tcp_layer = (tcp.sport, tcp.dport) if (tcp.data).startswith('HTTP/'): try: new_res = "%s\r\n\r\n" % ( tcp.data).splitlines()[0] http_res = dpkt.http.Response(new_res) except dpkt.dpkt.NeedData as e: pass except dpkt.UnpackError as e: pass else: self.responses.append({ 'ip-src': ip.src, 'ip-dst': ip.dst, 'port-src': tcp.sport, 'port-dst': tcp.dport, 'tcp-data': new_res, 'tcp-object': http_res }) self.addLogWarning( txt= "<< %s http response(s) extracted" % len(self.responses)) if self.requests: self.addLogSuccess("<< File decoded with success!") self.addLogWarning( "<< Click on the export button to generate the test!") self.exportToAction.setEnabled(True) else: self.addLogWarning("<< No http extracted!")
class DUdpReplay(QtHelper.EnhancedQDialog, Logger.ClassLogger): """ Http replay dialog """ def __init__(self, parent=None, offlineMode=False): """ Constructor @param parent: @type parent: """ super(DUdpReplay, self).__init__(parent) self.offlineMode = offlineMode self.defaultIp = "127.0.0.1" self.defaultPort = "80" self.newTest = '' self.newTestExec = '' self.newInputs = [] self.requests = [] self.responses = [] self.defaultTemplates = DefaultTemplates.Templates() self.testType = None self.createDialog() self.createConnections() self.createActions() self.createToolbar() def createActions(self): """ Create qt actions """ self.openAction = QtHelper.createAction(self, "&Open", self.importTrace, icon=QIcon(":/folder_add.png"), tip='Open network trace.') self.exportTUAction = QtHelper.createAction( self, "&Test Unit", self.exportToTU, icon=QIcon(":/%s.png" % WWorkspace.TestUnit.TYPE), tip='Export to Test Unit') self.exportTSAction = QtHelper.createAction( self, "&Test Suite", self.exportToTS, icon=QIcon(":/%s.png" % WWorkspace.TestSuite.TYPE), tip='Export to Test Suite') self.cancelAction = QtHelper.createAction(self, "&Cancel", self.reject, tip='Cancel') menu = QMenu(self) menu.addAction(self.exportTUAction) menu.addAction(self.exportTSAction) self.exportToAction = QtHelper.createAction( self, "&Export to", self.exportToTU, icon=QIcon(":/%s.png" % WWorkspace.TestUnit.TYPE), tip='Export to tests') self.exportToAction.setMenu(menu) self.exportToAction.setEnabled(False) def createDialog(self): """ Create dialog """ self.dockToolbar = QToolBar(self) self.dockToolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self.setWindowTitle(WINDOW_TITLE) self.resize(500, 400) self.ipEdit = QLineEdit(self.defaultIp) ipRegExpVal = QRegExpValidator(self) ipRegExp = QRegExp("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}") ipRegExpVal.setRegExp(ipRegExp) self.ipEdit.setValidator(ipRegExpVal) self.portEdit = QLineEdit(self.defaultPort) self.portEdit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) validatorPort = QIntValidator(self) self.portEdit.setValidator(validatorPort) self.progressBar = QProgressBar(self) self.progressBar.setMaximum(100) self.progressBar.setProperty("value", 0) self.progressBar.setAlignment(Qt.AlignCenter) self.progressBar.setObjectName("progressBar") self.guiSikuliGroupBox = QGroupBox("") self.guiSikuliGroupBox.setFlat(True) self.automaticAdp = QRadioButton("Automatic") self.automaticAdp.setChecked(True) self.defaultAdp = QRadioButton("Default") self.genericAdp = QRadioButton("Generic") vbox = QHBoxLayout() vbox.addWidget(self.automaticAdp) vbox.addWidget(self.defaultAdp) vbox.addWidget(self.genericAdp) vbox.addStretch(1) self.guiSikuliGroupBox.setLayout(vbox) layout = QVBoxLayout() layout.addWidget(self.dockToolbar) layout.addSpacing(12) paramLayout = QGridLayout() paramLayout.addWidget(QLabel("Destination IP:"), 0, 0, Qt.AlignRight) paramLayout.addWidget(self.ipEdit, 0, 1) paramLayout.addWidget(QLabel("Destination Port:"), 1, 0, Qt.AlignRight) paramLayout.addWidget(self.portEdit, 1, 1) paramLayout.addWidget(QLabel(self.tr("Gui adapter selector:")), 2, 0, Qt.AlignRight) paramLayout.addWidget(self.guiSikuliGroupBox, 2, 1) layout.addLayout(paramLayout) self.logsEdit = QTextEdit() self.logsEdit.setReadOnly(True) self.logsEdit.setTextInteractionFlags(Qt.NoTextInteraction) layout.addSpacing(12) layout.addWidget(self.logsEdit) layout.addSpacing(12) layout.addWidget(self.progressBar) self.setLayout(layout) def createToolbar(self): """ Create toolbar """ self.dockToolbar.setObjectName("File toolbar") self.dockToolbar.addAction(self.openAction) self.dockToolbar.addSeparator() self.dockToolbar.addAction(self.exportToAction) self.dockToolbar.addSeparator() self.dockToolbar.setIconSize(QSize(16, 16)) def createConnections(self): """ Create qt connections """ pass def autoScrollOnTextEdit(self): """ Automatic scroll on text edit """ cursor = self.logsEdit.textCursor() cursor.movePosition(QTextCursor.End) self.logsEdit.setTextCursor(cursor) def strip_html(self, txt): """ Strip html """ if "<" in txt: txt = txt.replace('<', '<') if ">" in txt: txt = txt.replace('>', '>') return txt def addLogSuccess(self, txt): """ Add log success in the text edit """ self.logsEdit.insertHtml( "<span style='color:darkgreen'>%s</span><br />" % unicode(self.strip_html(txt))) self.autoScrollOnTextEdit() def addLogWarning(self, txt): """ Add log warning in the text edit """ self.logsEdit.insertHtml( "<span style='color:darkorange'>%s</span><br />" % unicode(self.strip_html(txt))) self.autoScrollOnTextEdit() def addLogError(self, txt): """ Add log error in the text edit """ self.logsEdit.insertHtml("<span style='color:red'>%s</span><br />" % unicode(self.strip_html(txt))) self.autoScrollOnTextEdit() def addLog(self, txt): """ Append log to the logsEdit widget """ self.logsEdit.insertHtml("%s<br />" % unicode(self.strip_html(txt))) self.autoScrollOnTextEdit() def importTrace(self): """ Import network trace """ self.logsEdit.clear() self.testType = None if not self.offlineMode: if not RCI.instance().isAuthenticated(): self.addLogWarning( txt="<< Connect to the test center in first!") QMessageBox.warning(self, "Import", "Connect to the test center in first!") return self.exportToAction.setEnabled(False) self.newTest = '' self.progressBar.setMaximum(100) self.progressBar.setValue(0) if sys.version_info > (3, ): fileName = QFileDialog.getOpenFileName( self, self.tr("Open File"), "", "Network dump (*.cap;*.pcap;*.pcapng)") else: fileName = QFileDialog.getOpenFileName(self, self.tr("Open File"), "", "Network dump (*.cap)") # new in v18 to support qt5 if QtHelper.IS_QT5: _fileName, _type = fileName else: _fileName = fileName # end of new if not _fileName: return if sys.version_info < (3, ): extension = str(_fileName).rsplit(".", 1)[1] if not (extension == "cap"): self.addLogError(txt="<< File not supported %s" % _fileName) QMessageBox.critical(self, "Open", "File not supported") return _fileName = str(_fileName) capName = _fileName.rsplit("/", 1)[1] self.addLogSuccess(txt=">> Reading the file %s" % _fileName) self.readFileV2(fileName=_fileName) def exportToTS(self): """ Export to test suite """ self.testType = TS self.exportToTest(TS=True, TU=False) def exportToTU(self): """ Export to test unit """ self.testType = TU self.exportToTest(TS=False, TU=True) def searchUDP(self): """ Search UDP module in assistant """ # modules accessor ret = "SutAdapters" if self.automaticAdp.isChecked(): isGeneric = WWorkspace.Helper.instance().isGuiGeneric(name="GUI") if isGeneric: ret = "SutAdapters.Generic" elif self.defaultAdp.isChecked(): return ret elif self.genericAdp.isChecked(): ret = "SutAdapters.Generic" else: pass return ret def exportToTest(self, TS=True, TU=False): """ Export to test """ if not RCI.instance().isAuthenticated(): self.addLogWarning(txt="<< Connect to the test center in first!") QMessageBox.warning(self, "Import", "Connect to the test center in first!") return if TS: self.newTest = self.defaultTemplates.getTestDefinitionAuto() self.newTestExec = self.defaultTemplates.getTestExecutionAuto() if TU: self.newTest = self.defaultTemplates.getTestUnitDefinitionAuto() destIp = str(self.ipEdit.text()) destPort = str(self.portEdit.text()) self.newInputs = [] self.newInputs.append({ 'type': 'self-ip', 'name': 'BIND_IP', 'description': '', 'value': '0.0.0.0', 'color': '' }) self.newInputs.append({ 'type': 'int', 'name': 'BIND_PORT', 'description': '', 'value': '0', 'color': '' }) self.newInputs.append({ 'type': 'str', 'name': 'DEST_IP', 'description': '', 'value': '%s' % destIp, 'color': '' }) self.newInputs.append({ 'type': 'int', 'name': 'DEST_PORT', 'description': '', 'value': '%s' % destPort, 'color': '' }) self.newInputs.append({ 'type': 'bool', 'name': 'DEBUG', 'description': '', 'value': 'False', 'color': '' }) self.newInputs.append({ 'type': 'float', 'name': 'TIMEOUT', 'description': '', 'value': '5.0', 'color': '' }) adps = """self.ADP_UDP = %s.UDP.Client(parent=self, bindIp=input('BIND_IP'), bindPort=input('BIND_PORT'), destinationIp=input('DEST_IP'), destinationPort=input('DEST_PORT'), debug=input('DEBUG'), separatorDisabled=True)""" % self.searchUDP( ) # prepare steps steps = [] j = 0 for i in xrange(len(self.requests)): j = i + 1 sentrecv, req = self.requests[i] if sentrecv == 'sent': steps.append( 'self.step%s = self.addStep(expected="udp data sent", description="send udp data", summary="send udp data")' % j) else: steps.append( 'self.step%s = self.addStep(expected="udp data received", description="received udp data", summary="received udp data")' % j) tests = [] for i in xrange(len(self.requests)): j = i + 1 sentrecv, req = self.requests[i] (source, dest, source_port, dest_port, data) = req if sentrecv == 'sent': tests.append("# data to sent %s" % j) tests.append('self.step%s.start()' % j) if sys.version_info > (3, ): tests.append('rawSent = %s' % data.replace(b"'", b"\\'")) else: tests.append('rawSent = """%s"""' % data) tests.append('SentMsg = self.ADP_UDP.sendData(data=rawSent)') tests.append('if not SentMsg:') tests.append( '\tself.step%s.setFailed(actual="unable to send data")' % j) tests.append('else:') tests.append( '\tself.step%s.setPassed(actual="udp data sent succesfully")' % j) tests.append('') if sentrecv == 'recv': tests.append("# data to received %s" % j) tests.append('self.step%s.start()' % j) if sys.version_info > (3, ): tests.append('rawRecv = %s' % data.replace(b'"', b'\\"')) else: tests.append('rawRecv = """%s"""' % data) tests.append( 'RecvMsg = self.ADP_UDP.hasReceivedData(data=rawRecv, timeout=input("TIMEOUT"))' ) tests.append('if RecvMsg is None:') tests.append( '\tself.step%s.setFailed(actual="unable to received data")' % j) tests.append('else:') tests.append( '\tself.step%s.setPassed(actual="udp data received succesfully")' % j) tests.append('') if TS: init = """self.ADP_UDP.startListening() udpListening = self.ADP_UDP.isListening( timeout=input('TIMEOUT') ) if not udpListening: self.abort( 'unable to listing to the udp port %s' ) """ % str(self.portEdit.text()) if TU: init = """self.ADP_UDP.startListening() udpListening = self.ADP_UDP.isListening( timeout=input('TIMEOUT') ) if not udpListening: self.abort( 'unable to connect to the udp port %s' ) """ % str(self.portEdit.text()) if TS: cleanup = """self.ADP_UDP.stopListening() udpStopped = self.ADP_UDP.isStopped( timeout=input('TIMEOUT') ) if not udpStopped: self.error( 'unable to no more listen from the udp port %s' ) """ % str(self.portEdit.text()) if TU: cleanup = """self.ADP_UDP.stopListening() udpStopped = self.ADP_UDP.isStopped( timeout=input('TIMEOUT') ) if not udpStopped: self.error( 'unable to no more listen from the udp port %s' ) """ % str(self.portEdit.text()) self.newTest = self.newTest.replace( "<<PURPOSE>>", 'self.setPurpose(purpose="Replay UDP")') self.newTest = self.newTest.replace("<<ADPS>>", adps) if TS: self.newTest = self.newTest.replace("<<STEPS>>", '\n\t\t'.join(steps)) if TU: self.newTest = self.newTest.replace("<<STEPS>>", '\n\t'.join(steps)) self.newTest = self.newTest.replace("<<INIT>>", init) self.newTest = self.newTest.replace("<<CLEANUP>>", cleanup) if TS: self.newTest = self.newTest.replace("<<TESTS>>", '\n\t\t'.join(tests)) if TU: self.newTest = self.newTest.replace("<<TESTS>>", '\n\t'.join(tests)) self.accept() def readFileV2(self, fileName): """ Read pcap file Support pcap-ng too """ fd = open(fileName, 'rb') fileFormat, fileHead = PcapParse.extractFormat(fd) if fileFormat == PcapParse.FileFormat.PCAP: self.trace("pcap file detected") pcapFile = PcapReader.PcapFile(fd, fileHead).read_packet self.readFilePacket(pcapFile=pcapFile) elif fileFormat == PcapParse.FileFormat.PCAP_NG: self.trace("pcap-png file detected") pcapFile = PcapngReader.PcapngFile(fd, fileHead).read_packet self.readFilePacket(pcapFile=pcapFile) else: self.addLogError(txt="<< Error to open the network trace") self.error('unable to open the network trace: file format = %s' % fileFormat) QMessageBox.critical(self, "Import", "File not supported") def readFilePacket(self, pcapFile): """ Read file packet by packet """ ip_expected = str(self.ipEdit.text()) port_expected = int(self.portEdit.text()) # read packet) packets = pcapFile() ethernetPackets = list(packets) self.addLogSuccess(txt="<< Total packets detected: %s " % len(ethernetPackets)) # extract udp packet according to the expected ip and port self.requests = [] i = 1 self.progressBar.setMaximum(len(ethernetPackets)) self.progressBar.setValue(0) for pkt in ethernetPackets: self.progressBar.setValue(i) i += 1 pktDecoded = PcapParse.decodePacket(pkt, getTcp=False, getUdp=True) if pktDecoded is not None: (source, dest, source_port, dest_port, data) = pktDecoded # skip when no data exists if dest == ip_expected and int(dest_port) == int( port_expected) and len(data) > 0: self.requests.append(('sent', pktDecoded)) if source == ip_expected and int(source_port) == int( port_expected) and len(data) > 0: self.requests.append(('recv', pktDecoded)) self.addLogSuccess(txt="<< Number of UDP packets detected: %s" % len(self.requests)) if self.requests: self.addLogSuccess("<< File decoded with success!") self.addLogWarning( "<< Click on the export button to generate the test!") self.exportToAction.setEnabled(True) else: self.addLogWarning("<< No udp extracted!")
class EkdProgress(QDialog) : """EkdProgress est une boite de dialog contenant l'état de la progression de chaque processus""" def __init__(self, parent=None, totfile=0): super(EkdProgress, self).__init__(parent) self.setupUi(self) self.barProgress.setMaximum(totfile) self.fermer.setEnabled(False) self.totframe=totfile self.value = 0 self.connect(self.fermer,SIGNAL("clicked()"),self.tmpclose) def upProgress(self) : self.value += 1 self.barProgress.setValue(self.value) def addText(self, text) : self.infoText.append(QString(text)) def tmpclose(self) : self.emit(SIGNAL("cleantmp")) self.close() def setupUi(self, showprogress): showprogress.setObjectName("showprogress") showprogress.resize(335, 310) self.verticalLayout = QVBoxLayout(showprogress) self.verticalLayout.setObjectName("verticalLayout") self.barProgress = QProgressBar(showprogress) self.barProgress.setProperty("value", QVariant(0)) self.barProgress.setObjectName("barProgress") self.verticalLayout.addWidget(self.barProgress) self.infoText = QTextEdit(showprogress) palette = QPalette() brush = QBrush(QColor(255, 255, 255)) brush.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Active, QPalette.Text, brush) brush = QBrush(QColor(0, 0, 0)) brush.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Active, QPalette.Base, brush) brush = QBrush(QColor(255, 255, 255)) brush.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Inactive, QPalette.Text, brush) brush = QBrush(QColor(0, 0, 0)) brush.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Inactive, QPalette.Base, brush) brush = QBrush(QColor(126, 125, 124)) brush.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Disabled, QPalette.Text, brush) brush = QBrush(QColor(255, 255, 255)) brush.setStyle(Qt.SolidPattern) palette.setBrush(QPalette.Disabled, QPalette.Base, brush) self.infoText.setPalette(palette) self.infoText.setObjectName("infoText") self.verticalLayout.addWidget(self.infoText) self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.fermer = QPushButton(showprogress) self.fermer.setObjectName("fermer") self.horizontalLayout.addWidget(self.fermer) self.verticalLayout.addLayout(self.horizontalLayout) self.retranslateUi(showprogress) QMetaObject.connectSlotsByName(showprogress) def retranslateUi(self, showprogress): showprogress.setWindowTitle(_(u"Progression")) self.barProgress.setToolTip(_(u"Progression de l\'encodage")) self.infoText.setToolTip(_(u"Messages")) self.fermer.setToolTip(_(u"Fermer la fenêtre")) self.fermer.setText(_(u"Fermer"))
class SubtaskTableElem: ############################ def __init__(self, nodeId, subtaskId, status): self.nodeId = nodeId self.nodeIdItem = None self.subtaskId = subtaskId self.subtaskIdItem = None self.status = status self.remainingTime = 0 self.remainingTimeItem = None self.progress = 0.0 self.nodeIdItem = None self.progressBar = None self.progressBarInBoxLayoutWidget = None self.subtaskStatusItem = None self.__buildRow() ############################ def __buildRow(self): self.nodeIdItem = QTableWidgetItem() self.nodeIdItem.setText(self.nodeId) self.subtaskIdItem = QTableWidgetItem() self.subtaskIdItem.setText(self.subtaskId) self.remainingTimeItem = QTableWidgetItem() self.subtaskStatusItem = QTableWidgetItem() self.progressBar = QProgressBar() self.progressBar.geometry().setHeight(20) self.progressBar.setProperty("value", 50) self.progressBarInBoxLayoutWidget = QWidget() boxLayout = QVBoxLayout() boxLayout.setMargin(3) boxLayout.addWidget(self.progressBar) self.progressBarInBoxLayoutWidget.setLayout(boxLayout) ############################ def update(self, progress, status, remTime): self.setProgress(progress) self.setRemainingTime(remTime) self.setStatus(status) ############################ def setProgress(self, val): if val >= 0.0 and val <= 1.0: self.progress = val self.progressBar.setProperty("value", int(val * 100)) else: assert False, "Wrong progress setting {}".format(val) ############################ def setStatus(self, status): self.status = status self.subtaskStatusItem.setText(status) ############################ def setRemainingTime(self, time): self.remainingTime = time self.remainingTimeItem.setText(str(datetime.timedelta(seconds=time))) ############################ def getColumnItem(self, col): if col == 0: return self.nodeIdItem if col == 1: return self.subtaskIdItem if col == 2: return self.remainingTimeItem if col == 3: return self.subtaskStatusItem assert False, "Wrong column index"
class GUI(QWidget): def __init__(self, parent=None): global f f = open(filename, "a") f.write("Widget init.\n") f.close() QWidget.__init__(self, parent, Qt.WindowStaysOnTopHint) self.__setup_gui__(self) self._flag = False self._change = False f = open(filename, "a") f.write("End of widget init.\n") f.close() def closeEvent(self, event): reply = QMessageBox.question(self, "Confirm", "Are you sure You want to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: event.ignore() def __setup_gui__(self, Dialog): global f f = open(filename, "a") f.write("Setup of gui.\n") f.close() Dialog.setObjectName("Dialog") Dialog.resize(270, 145) self.setWindowTitle("Map Layer") screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2) self.Render = QPushButton("Render", Dialog) self.Render.setGeometry(QRect(85, 90, 100, 25)) self.Render.setObjectName("Render") self.comboBox = QComboBox(Dialog) self.comboBox.setGeometry(QRect(100, 34, 115, 18)) self.comboBox.setEditable(False) self.comboBox.setMaxVisibleItems(11) self.comboBox.setInsertPolicy(QComboBox.InsertAtBottom) self.comboBox.setObjectName("comboBox") self.comboBox.addItems([ "Google Roadmap", "Google Terrain", "Google Satellite", "Google Hybrid", "Yahoo Roadmap", "Yahoo Satellite", "Yahoo Hybrid", "Bing Roadmap", "Bing Satellite", "Bing Hybrid", "Open Street Maps" ]) self.comboBox.setCurrentIndex(10) self.label1 = QLabel("Source:", Dialog) self.label1.setGeometry(QRect(55, 35, 35, 16)) self.label1.setObjectName("label1") self.slider = QSlider(Dialog) self.slider.setOrientation(Qt.Horizontal) self.slider.setMinimum(1) self.slider.setMaximum(12) self.slider.setValue(4) self.slider.setGeometry(QRect(110, 61, 114, 16)) self.label2 = QLabel("Quality: " + str(self.slider.value()), Dialog) self.label2.setGeometry(QRect(47, 61, 54, 16)) self.label2.setObjectName("label2") self.doubleSpinBox = QDoubleSpinBox(Dialog) self.doubleSpinBox.setGeometry(QRect(160, 5, 40, 20)) self.doubleSpinBox.setDecimals(0) self.doubleSpinBox.setObjectName("doubleSpinBox") self.doubleSpinBox.setMinimum(10.0) self.doubleSpinBox.setValue(20.0) self.doubleSpinBox.setEnabled(False) self.checkBox = QCheckBox("Auto refresh", Dialog) self.checkBox.setGeometry(QRect(50, 6, 100, 20)) self.checkBox.setLayoutDirection(Qt.RightToLeft) self.checkBox.setObjectName("checkBox") self.progressBar = QProgressBar(Dialog) self.progressBar.setGeometry(QRect(5, 130, 260, 10)) self.progressBar.setProperty("value", 0) self.progressBar.setTextVisible(False) self.progressBar.setObjectName("progressBar") self.progressBar.setVisible(False) QObject.connect(self.Render, SIGNAL("clicked()"), Dialog.__repaint__) QMetaObject.connectSlotsByName(Dialog) QObject.connect(self.slider, SIGNAL("valueChanged(int)"), self.__update_slider_label__) QObject.connect(self.comboBox, SIGNAL("activated(int)"), self.__combobox_changed__) self.timerRepaint = QTimer() QObject.connect(self.checkBox, SIGNAL("clicked()"), self.__activate_timer__) QObject.connect(self.timerRepaint, SIGNAL("timeout()"), self.__on_timer__) f = open(filename, "a") f.write("End of setup of gui.\n") f.close() def __combobox_changed__(self): self._change = True def __activate_timer__(self): self.doubleSpinBox.setEnabled(self.checkBox.isChecked()) if self.checkBox.isChecked(): self.timerRepaint.start(self.doubleSpinBox.value() * 1000) self.Render.setEnabled(False) if _progress == 0: self.__repaint__() else: self.timerRepaint.stop() self.Render.setEnabled(True) def __get_net_size__(self): global f f = open(filename, "a") f.write("Geting net size...\n") f.close() if not os.path.exists(Paths["Screenshot"]): Visum.Graphic.Screenshot(Paths["Screenshot"]) size = Image.open(Paths["Screenshot"]).size f = open(filename, "a") f.write("Read net size:" + str(size) + ".\n") f.close() return size def __on_timer__(self): global _paramGlobal self._flag = False Visum.Graphic.MaximizeNetWindow() param = _paramGlobal _paramGlobal = Visum.Graphic.GetWindow() shift = abs((param[0] - _paramGlobal[0]) / (param[2] - param[0])) zoom = abs((param[2] - param[0]) / (_paramGlobal[2] - _paramGlobal[0]) - 1) print _windowSizeGlobal if _windowSizeGlobal[2:4] != Visum.Graphic.GetMainWindowPos()[2:4]: self.__get_net_size__() self._flag = True elif shift > 0.4 or zoom > 0.2: self._flag = True if self._flag or self._change and _progress == 0: self.__repaint__() self._change = False def __update_slider_label__(self, value): self.label2.setText("Quality: " + str(value)) self._change = True def __update_progress_bar__(self): if _progress != 0: self.progressBar.setVisible(True) self.progressBar.setValue(_progress) else: self.progressBar.setVisible(False) def __rebuild_paths__(self): global Paths Paths["Images"] = [] list = os.listdir(Paths["ScriptFolder"]) imageList = [] for i in range(len(list)): if list[i][-3:] == "png": imageList.append(list[i]) for i in range(len(imageList)): try: Visum.Graphic.Backgrounds.ItemByKey(imageList[i]) Paths["Images"].append(Paths["ScriptFolder"] + "\\" + imageList[i]) except: pass def __repaint__(self): global _progress, f if len(Visum.Graphic.Backgrounds.GetAll) != len(Paths["Images"]): self.__rebuild_paths__() if _progress == 0: f = open(filename, "a") f.write("Doing repaint...\n") f.close() QWebSettings.clearMemoryCaches() timer = QTimer() timer.start(100) QObject.connect(timer, SIGNAL("timeout()"), self.__update_progress_bar__) Main(self.comboBox.currentIndex(), Visum.Graphic.GetWindow(), self.slider.value() / 4.0, self.__get_net_size__()) Visum.Graphic.Draw() self.__update_progress_bar__() _progress = 0 QTimer().singleShot(1500, self.__update_progress_bar__) f = open(filename, "a") f.write("End of doing repaint.\n") f.close()
class ViewDataTools(QMainWindow): def __init__(self, parent=None): super(ViewDataTools, self).__init__(parent) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # DATATOOLS WINDOWS: # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ self.setWindowTitle(ui_strings.DATATOOLS_TITLE) self._width = 680 self._height = 560 self._left_margin = 10 self.resize(self._width, self._height) size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) size_policy.setHorizontalStretch(0) size_policy.setVerticalStretch(0) size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(size_policy) self.setMinimumSize(QtCore.QSize(self._width, self._height)) self.setMaximumSize(QtCore.QSize(self._width, self._height)) self.setWindowIcon(QIcon(resources.ICON_LOGO)) # central widget self.central_widget = QWidget(self) # DataTools description self.lbl_description = QLabel(self.central_widget) self.lbl_description.setGeometry(QtCore.QRect(0, 0, self._width, 30)) self.lbl_description.setAlignment(QtCore.Qt.AlignCenter) self.lbl_description.setText(ui_strings.DATATOOLS_DESCRIPTION) # group input files self.group_input_file = QGroupBox(self.central_widget) self.group_input_file.setGeometry( QtCore.QRect(self._left_margin, 30, 660, 80)) self.group_input_file.setTitle(ui_strings.DATATOOLS_GROUP_INPUT) # frame input files self.frame_inputs = QFrame(self.group_input_file) self.frame_inputs.setGeometry( QtCore.QRect(self._left_margin, 0, 270, 80)) self.frame_inputs.setFrameShape(QFrame.StyledPanel) self.frame_inputs.setFrameShadow(QFrame.Raised) # label input type self.lbl_input_type = QLabel(self.frame_inputs) self.lbl_input_type.setGeometry(QtCore.QRect(20, 20, 60, 15)) self.lbl_input_type.setText(ui_strings.DATATOOLS_INPUT_TYPE) # button xls self.btn_xls = QToolButton(self.frame_inputs) self.btn_xls.setGeometry(QtCore.QRect(20, 35, 35, 35)) icon_xls = QIcon() icon_xls.addPixmap(QPixmap(resources.ICON_XLS), QIcon.Normal, QIcon.Off) self.btn_xls.setIcon(icon_xls) self.btn_xls.setIconSize(QtCore.QSize(24, 24)) self.btn_xls.setCheckable(True) self.btn_xls.setAutoExclusive(True) self.btn_xls.setObjectName("xls_button") # button csv self.btn_csv = QToolButton(self.frame_inputs) self.btn_csv.setGeometry(QtCore.QRect(60, 35, 35, 35)) icon_csv = QIcon() icon_csv.addPixmap(QPixmap(resources.ICON_CSV), QIcon.Normal, QIcon.Off) self.btn_csv.setIcon(icon_csv) self.btn_csv.setIconSize(QtCore.QSize(24, 24)) self.btn_csv.setCheckable(True) self.btn_csv.setAutoExclusive(True) self.btn_csv.setObjectName("csv_button") # checkbox csv with headers self.chk_csv_headers = QCheckBox(ui_strings.DATATOOLS_WITH_HEADERS, self.frame_inputs) self.chk_csv_headers.setGeometry(QtCore.QRect(100, 45, 110, 15)) self.chk_csv_headers.setEnabled(False) # TextEdit + PushButton (FindFolder) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # lbl sheet name self.lbl_file_path = QLabel(self.group_input_file) self.lbl_file_path.setGeometry(QtCore.QRect(250, 20, 120, 15)) self.lbl_file_path.setText(ui_strings.DATATOOLS_SELECT_FILE) self.txt_file = QLineEdit(self.group_input_file) self.txt_file.setGeometry(QtCore.QRect(250, 35, 160, 20)) self.txt_file.setReadOnly(True) self.btn_path = QPushButton(self.group_input_file) self.btn_path.setGeometry(QtCore.QRect(410, 34, 50, 22)) self.btn_path.setText(ui_strings.DATATOOLS_SELECT_BUTTON) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # lbl sheet name self.lbl_sheet_name = QLabel(self.group_input_file) self.lbl_sheet_name.setGeometry(QtCore.QRect(500, 20, 120, 15)) self.lbl_sheet_name.setText(ui_strings.DATATOOLS_SHEET_NAME) # Combobox select sheet - initially does not contain values self.cbo_sheet = QComboBox(self.group_input_file) self.cbo_sheet.setGeometry(QtCore.QRect(500, 35, 130, 20)) # data grid to visualize error messages self.tbl_errors = QTableWidget(self.central_widget) self.tbl_errors.setGeometry( QtCore.QRect(self._left_margin, 420, 660, 100)) # data grid to visualize those records with errors. self.tbl_uploaded_data = QTableWidget(self.central_widget) self.tbl_uploaded_data.setGeometry( QtCore.QRect(self._left_margin, 120, 500, 220)) # group run options self.group_run_options = QGroupBox(self.central_widget) self.group_run_options.setGeometry(QtCore.QRect(520, 120, 150, 220)) self.group_run_options.setTitle(ui_strings.DATATOOLS_GROUP_RUN) # Errors summary: # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # group summary errors self.group_errors = QGroupBox(self.central_widget) self.group_errors.setGeometry( QtCore.QRect(self._left_margin, 350, 660, 60)) self.group_errors.setTitle(ui_strings.DATATOOLS_HEADER_ERRORS) # lbl records self.lbl_records = QLabel(self.group_errors) self.lbl_records.setGeometry(QtCore.QRect(165, 15, 80, 15)) self.lbl_records.setAlignment(QtCore.Qt.AlignCenter) self.lbl_records.setText(ui_strings.DATATOOLS_RECORDS) self.txt_records = QLineEdit(self.group_errors) self.txt_records.setGeometry(QtCore.QRect(165, 30, 80, 20)) self.txt_records.setAlignment(QtCore.Qt.AlignCenter) self.txt_records.setReadOnly(True) # lbl errors self.lbl_errors = QLabel(self.group_errors) self.lbl_errors.setGeometry(QtCore.QRect(275, 15, 80, 15)) self.lbl_errors.setAlignment(QtCore.Qt.AlignCenter) self.lbl_errors.setText(ui_strings.DATATOOLS_ERRORS) self.txt_errors = QLineEdit(self.group_errors) self.txt_errors.setGeometry(QtCore.QRect(275, 30, 80, 20)) self.txt_errors.setAlignment(QtCore.Qt.AlignCenter) self.txt_errors.setReadOnly(True) # lbl time self.lbl_time = QLabel(self.group_errors) self.lbl_time.setGeometry(QtCore.QRect(385, 15, 80, 15)) self.lbl_time.setAlignment(QtCore.Qt.AlignCenter) self.lbl_time.setText(ui_strings.DATATOOLS_TIME) self.txt_time = QLineEdit(self.group_errors) self.txt_time.setGeometry(QtCore.QRect(385, 30, 80, 20)) self.txt_time.setAlignment(QtCore.Qt.AlignCenter) self.txt_time.setReadOnly(True) # history button self.btn_history = QToolButton(self.group_errors) self.btn_history.setGeometry(QtCore.QRect(500, 25, 100, 25)) icon_history = QIcon() icon_history.addPixmap(QPixmap(resources.ICON_HISTORY), QIcon.Normal, QIcon.Off) self.btn_history.setIcon(icon_history) self.btn_history.setIconSize(QtCore.QSize(20, 20)) self.btn_history.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon) self.btn_history.setText(ui_strings.DATATOOLS_HISTORY) self.btn_history.setCheckable(True) self.btn_history.setAutoExclusive(True) self.btn_history.setObjectName("history_button") # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # btn data uploader self.btn_data_uploader = QPushButton( ui_strings.DATATOOLS_DATA_UPLOADER, self.group_run_options) self.btn_data_uploader.setGeometry(QtCore.QRect(10, 120, 90, 25)) self.btn_data_uploader.setCheckable(True) self.btn_data_uploader.setAutoExclusive(True) self.btn_data_uploader.setFlat(False) # btn data testing self.btn_data_testing = QPushButton(ui_strings.DATATOOLS_DATA_TESTING, self.group_run_options) self.btn_data_testing.setEnabled(False) self.btn_data_testing.setGeometry(QtCore.QRect(10, 150, 90, 25)) self.btn_data_testing.setCheckable(True) self.btn_data_testing.setAutoExclusive(True) # btn data to database self.btn_data_db = QPushButton(ui_strings.DATATOOLS_DATA_DB, self.group_run_options) self.btn_data_db.setEnabled(False) self.btn_data_db.setGeometry(QtCore.QRect(10, 179, 91, 23)) self.btn_data_db.setCheckable(True) self.btn_data_db.setAutoExclusive(True) # frame run options self.frame_run = QFrame(self.group_run_options) self.frame_run.setGeometry(QtCore.QRect(10, 30, 130, 80)) self.frame_run.setFrameShape(QFrame.StyledPanel) self.frame_run.setFrameShadow(QFrame.Raised) # option process until first error self.rbtn_process_error = QRadioButton( ui_strings.DATATOOLS_PROCESS_ERROR, self.frame_run) self.rbtn_process_error.setGeometry(QtCore.QRect(0, 0, 150, 20)) # option process all data self.rbtn_process_all = QRadioButton(ui_strings.DATATOOLS_PROCESS_ALL, self.frame_run) self.rbtn_process_all.setGeometry(QtCore.QRect(0, 20, 150, 30)) # checkbox to filter by records with errors. #self.chk_filter_errors = QCheckBox(ui_strings.DATATOOLS_FILTER_ERRORS, self.frame_run) #self.chk_filter_errors.setGeometry(QtCore.QRect(0, 50, 100, 15)) #self.chk_filter_errors.setEnabled(False) # icons -> pass - error: Initially are empty labels # if not started -> ICON_MINI_WAIT # if error -> ICON_DELETE # if pass -> ICON_CHECK # state icon data uploader self.lbl_state_du = QLabel(self.group_run_options) self.lbl_state_du.setGeometry(QtCore.QRect(110, 120, 20, 20)) self.lbl_state_du.setPixmap(QPixmap(resources.ICON_MINI_WAIT)) self.lbl_state_du.setScaledContents(True) # state icon data to database self.lbl_state_dt = QLabel(self.group_run_options) self.lbl_state_dt.setGeometry(QtCore.QRect(110, 150, 20, 20)) self.lbl_state_dt.setPixmap(QPixmap(resources.ICON_MINI_WAIT)) self.lbl_state_dt.setScaledContents(True) # state icon data testing self.lbl_state_db = QLabel(self.group_run_options) self.lbl_state_db.setGeometry(QtCore.QRect(110, 180, 20, 20)) self.lbl_state_db.setPixmap(QPixmap(resources.ICON_MINI_WAIT)) self.lbl_state_db.setScaledContents(True) # progress bar self.progress_bar = QProgressBar(self.central_widget) self.progress_bar.setGeometry( QtCore.QRect(self._left_margin, 530, 660, 15)) self.progress_bar.setMaximum(100) self.progress_bar.setProperty("value", 0) self.progress_bar.setTextVisible(True) self.progress_bar.setOrientation(QtCore.Qt.Horizontal) self.progress_bar.setInvertedAppearance(False) self.progress_bar.setTextDirection(QProgressBar.TopToBottom) self.setCentralWidget(self.central_widget)
class ViewDataTools(QMainWindow): def __init__(self, parent=None): super(ViewDataTools, self).__init__(parent) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # DATATOOLS WINDOWS: # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ self.setWindowTitle(ui_strings.DATATOOLS_TITLE) self._width = 680 self._height = 560 self._left_margin = 10 self.resize(self._width, self._height) size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) size_policy.setHorizontalStretch(0) size_policy.setVerticalStretch(0) size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(size_policy) self.setMinimumSize(QtCore.QSize(self._width, self._height)) self.setMaximumSize(QtCore.QSize(self._width, self._height)) self.setWindowIcon(QIcon(resources.ICON_LOGO)) # central widget self.central_widget = QWidget(self) # DataTools description self.lbl_description = QLabel(self.central_widget) self.lbl_description.setGeometry(QtCore.QRect(0, 0, self._width, 30)) self.lbl_description.setAlignment(QtCore.Qt.AlignCenter) self.lbl_description.setText(ui_strings.DATATOOLS_DESCRIPTION) # group input files self.group_input_file = QGroupBox(self.central_widget) self.group_input_file.setGeometry(QtCore.QRect(self._left_margin, 30, 660, 80)) self.group_input_file.setTitle(ui_strings.DATATOOLS_GROUP_INPUT) # frame input files self.frame_inputs = QFrame(self.group_input_file) self.frame_inputs.setGeometry(QtCore.QRect(self._left_margin, 0, 270, 80)) self.frame_inputs.setFrameShape(QFrame.StyledPanel) self.frame_inputs.setFrameShadow(QFrame.Raised) # label input type self.lbl_input_type = QLabel(self.frame_inputs) self.lbl_input_type.setGeometry(QtCore.QRect(20, 20, 60, 15)) self.lbl_input_type.setText(ui_strings.DATATOOLS_INPUT_TYPE) # button xls self.btn_xls = QToolButton(self.frame_inputs) self.btn_xls.setGeometry(QtCore.QRect(20, 35, 35, 35)) icon_xls = QIcon() icon_xls.addPixmap(QPixmap(resources.ICON_XLS), QIcon.Normal, QIcon.Off) self.btn_xls.setIcon(icon_xls) self.btn_xls.setIconSize(QtCore.QSize(24, 24)) self.btn_xls.setCheckable(True) self.btn_xls.setAutoExclusive(True) self.btn_xls.setObjectName("xls_button") # button csv self.btn_csv = QToolButton(self.frame_inputs) self.btn_csv.setGeometry(QtCore.QRect(60, 35, 35, 35)) icon_csv = QIcon() icon_csv.addPixmap(QPixmap(resources.ICON_CSV), QIcon.Normal, QIcon.Off) self.btn_csv.setIcon(icon_csv) self.btn_csv.setIconSize(QtCore.QSize(24, 24)) self.btn_csv.setCheckable(True) self.btn_csv.setAutoExclusive(True) self.btn_csv.setObjectName("csv_button") # checkbox csv with headers self.chk_csv_headers = QCheckBox(ui_strings.DATATOOLS_WITH_HEADERS, self.frame_inputs) self.chk_csv_headers.setGeometry(QtCore.QRect(100, 45, 110, 15)) self.chk_csv_headers.setEnabled(False) # TextEdit + PushButton (FindFolder) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # lbl sheet name self.lbl_file_path = QLabel(self.group_input_file) self.lbl_file_path.setGeometry(QtCore.QRect(250, 20, 120, 15)) self.lbl_file_path.setText(ui_strings.DATATOOLS_SELECT_FILE) self.txt_file = QLineEdit(self.group_input_file) self.txt_file.setGeometry(QtCore.QRect(250, 35, 160, 20)) self.txt_file.setReadOnly(True) self.btn_path = QPushButton(self.group_input_file) self.btn_path.setGeometry(QtCore.QRect(410, 34, 50, 22)) self.btn_path.setText(ui_strings.DATATOOLS_SELECT_BUTTON) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # lbl sheet name self.lbl_sheet_name = QLabel(self.group_input_file) self.lbl_sheet_name.setGeometry(QtCore.QRect(500, 20, 120, 15)) self.lbl_sheet_name.setText(ui_strings.DATATOOLS_SHEET_NAME) # Combobox select sheet - initially does not contain values self.cbo_sheet = QComboBox(self.group_input_file) self.cbo_sheet.setGeometry(QtCore.QRect(500, 35, 130, 20)) # data grid to visualize error messages self.tbl_errors = QTableWidget(self.central_widget) self.tbl_errors.setGeometry(QtCore.QRect(self._left_margin, 420, 660, 100)) # data grid to visualize those records with errors. self.tbl_uploaded_data = QTableWidget(self.central_widget) self.tbl_uploaded_data.setGeometry(QtCore.QRect(self._left_margin, 120, 500, 220)) # group run options self.group_run_options = QGroupBox(self.central_widget) self.group_run_options.setGeometry(QtCore.QRect(520, 120, 150, 220)) self.group_run_options.setTitle(ui_strings.DATATOOLS_GROUP_RUN) # Errors summary: # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # group summary errors self.group_errors = QGroupBox(self.central_widget) self.group_errors.setGeometry(QtCore.QRect(self._left_margin, 350, 660, 60)) self.group_errors.setTitle(ui_strings.DATATOOLS_HEADER_ERRORS) # lbl records self.lbl_records = QLabel(self.group_errors) self.lbl_records.setGeometry(QtCore.QRect(165, 15, 80, 15)) self.lbl_records.setAlignment(QtCore.Qt.AlignCenter) self.lbl_records.setText(ui_strings.DATATOOLS_RECORDS) self.txt_records = QLineEdit(self.group_errors) self.txt_records.setGeometry(QtCore.QRect(165, 30, 80, 20)) self.txt_records.setAlignment(QtCore.Qt.AlignCenter) self.txt_records.setReadOnly(True) # lbl errors self.lbl_errors = QLabel(self.group_errors) self.lbl_errors.setGeometry(QtCore.QRect(275, 15, 80, 15)) self.lbl_errors.setAlignment(QtCore.Qt.AlignCenter) self.lbl_errors.setText(ui_strings.DATATOOLS_ERRORS) self.txt_errors = QLineEdit(self.group_errors) self.txt_errors.setGeometry(QtCore.QRect(275, 30, 80, 20)) self.txt_errors.setAlignment(QtCore.Qt.AlignCenter) self.txt_errors.setReadOnly(True) # lbl time self.lbl_time = QLabel(self.group_errors) self.lbl_time.setGeometry(QtCore.QRect(385, 15, 80, 15)) self.lbl_time.setAlignment(QtCore.Qt.AlignCenter) self.lbl_time.setText(ui_strings.DATATOOLS_TIME) self.txt_time = QLineEdit(self.group_errors) self.txt_time.setGeometry(QtCore.QRect(385, 30, 80, 20)) self.txt_time.setAlignment(QtCore.Qt.AlignCenter) self.txt_time.setReadOnly(True) # history button self.btn_history = QToolButton(self.group_errors) self.btn_history.setGeometry(QtCore.QRect(500, 25, 100, 25)) icon_history = QIcon() icon_history.addPixmap(QPixmap(resources.ICON_HISTORY), QIcon.Normal, QIcon.Off) self.btn_history.setIcon(icon_history) self.btn_history.setIconSize(QtCore.QSize(20, 20)) self.btn_history.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon) self.btn_history.setText(ui_strings.DATATOOLS_HISTORY) self.btn_history.setCheckable(True) self.btn_history.setAutoExclusive(True) self.btn_history.setObjectName("history_button") # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # btn data uploader self.btn_data_uploader = QPushButton(ui_strings.DATATOOLS_DATA_UPLOADER, self.group_run_options) self.btn_data_uploader.setGeometry(QtCore.QRect(10, 120, 90, 25)) self.btn_data_uploader.setCheckable(True) self.btn_data_uploader.setAutoExclusive(True) self.btn_data_uploader.setFlat(False) # btn data testing self.btn_data_testing = QPushButton(ui_strings.DATATOOLS_DATA_TESTING, self.group_run_options) self.btn_data_testing.setEnabled(False) self.btn_data_testing.setGeometry(QtCore.QRect(10, 150, 90, 25)) self.btn_data_testing.setCheckable(True) self.btn_data_testing.setAutoExclusive(True) # btn data to database self.btn_data_db = QPushButton(ui_strings.DATATOOLS_DATA_DB, self.group_run_options) self.btn_data_db.setEnabled(False) self.btn_data_db.setGeometry(QtCore.QRect(10, 179, 91, 23)) self.btn_data_db.setCheckable(True) self.btn_data_db.setAutoExclusive(True) # frame run options self.frame_run = QFrame(self.group_run_options) self.frame_run.setGeometry(QtCore.QRect(10, 30, 130, 80)) self.frame_run.setFrameShape(QFrame.StyledPanel) self.frame_run.setFrameShadow(QFrame.Raised) # option process until first error self.rbtn_process_error = QRadioButton(ui_strings.DATATOOLS_PROCESS_ERROR, self.frame_run) self.rbtn_process_error.setGeometry(QtCore.QRect(0, 0, 150, 20)) # option process all data self.rbtn_process_all = QRadioButton(ui_strings.DATATOOLS_PROCESS_ALL, self.frame_run) self.rbtn_process_all.setGeometry(QtCore.QRect(0, 20, 150, 30)) # checkbox to filter by records with errors. #self.chk_filter_errors = QCheckBox(ui_strings.DATATOOLS_FILTER_ERRORS, self.frame_run) #self.chk_filter_errors.setGeometry(QtCore.QRect(0, 50, 100, 15)) #self.chk_filter_errors.setEnabled(False) # icons -> pass - error: Initially are empty labels # if not started -> ICON_MINI_WAIT # if error -> ICON_DELETE # if pass -> ICON_CHECK # state icon data uploader self.lbl_state_du = QLabel(self.group_run_options) self.lbl_state_du.setGeometry(QtCore.QRect(110, 120, 20, 20)) self.lbl_state_du.setPixmap(QPixmap(resources.ICON_MINI_WAIT)) self.lbl_state_du.setScaledContents(True) # state icon data to database self.lbl_state_dt = QLabel(self.group_run_options) self.lbl_state_dt.setGeometry(QtCore.QRect(110, 150, 20, 20)) self.lbl_state_dt.setPixmap(QPixmap(resources.ICON_MINI_WAIT)) self.lbl_state_dt.setScaledContents(True) # state icon data testing self.lbl_state_db = QLabel(self.group_run_options) self.lbl_state_db.setGeometry(QtCore.QRect(110, 180, 20, 20)) self.lbl_state_db.setPixmap(QPixmap(resources.ICON_MINI_WAIT)) self.lbl_state_db.setScaledContents(True) # progress bar self.progress_bar = QProgressBar(self.central_widget) self.progress_bar.setGeometry(QtCore.QRect(self._left_margin, 530, 660, 15)) self.progress_bar.setMaximum(100) self.progress_bar.setProperty("value", 0) self.progress_bar.setTextVisible(True) self.progress_bar.setOrientation(QtCore.Qt.Horizontal) self.progress_bar.setInvertedAppearance(False) self.progress_bar.setTextDirection(QProgressBar.TopToBottom) self.setCentralWidget(self.central_widget)
class Ui_RightWidget(object): def setupUi(self, RightWidget, server): RightWidget.setMinimumHeight(500) main_layout = QVBoxLayout(RightWidget) main_layout.setContentsMargins(0, 0, 0, 0) main_layout.setSpacing(10) # We hide all the main elements, to allow the proper viewer to enable # (only) the elements that uses. if hasattr(server, 'wild_chars'): self.text_map = QTextEdit() self.text_map.setObjectName('text_map') self.text_map.setVisible(False) self.text_map.setFocusPolicy(Qt.NoFocus) self.text_map.setAutoFillBackground(True) self.text_map.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.text_map.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.text_map.setUndoRedoEnabled(False) self.text_map.setReadOnly(True) # for some unknown reason, the fontmetrics of the text map is wrong # if the font is set with a global stylesheet, so we set it on the # specific widget. self.text_map.setStyleSheet("QTextEdit { font: 13px \"Courier\";}") main_layout.addWidget(self.text_map) # We calculate the map area size using the size of the font used. We # assume that the font is a monospace ones. font_metrics = self.text_map.fontMetrics() self.text_map.setFixedWidth(font_metrics.width('#' * server.map_width)) self.text_map.setFixedHeight(font_metrics.height() * server.map_height) # The rightwidget width is determined by the map area size RightWidget.setMinimumWidth(self.text_map.width()) else: RightWidget.setMinimumWidth(220) self.box_status = QWidget() self.box_status.setVisible(False) main_layout.addWidget(self.box_status) status_layout = QGridLayout(self.box_status) status_layout.setContentsMargins(5, 5, 5, 0) status_layout.setHorizontalSpacing(0) status_layout.setVerticalSpacing(15) label_health = QLabel() label_health.setMinimumWidth(80) label_health.setText(QApplication.translate("RightWidget", "Health")) status_layout.addWidget(label_health, 0, 0) self.bar_health = QProgressBar() self.bar_health.setObjectName("bar_health") self.bar_health.setFixedHeight(22) self.bar_health.setProperty("value", QVariant(100)) self.bar_health.setTextVisible(False) status_layout.addWidget(self.bar_health, 0, 1) label_mana = QLabel() label_mana.setMinimumWidth(80) label_mana.setText(QApplication.translate("RightWidget", "Mana")) status_layout.addWidget(label_mana, 1, 0) self.bar_mana = QProgressBar() self.bar_mana.setObjectName("bar_mana") self.bar_mana.setFixedHeight(22) self.bar_mana.setProperty("value", QVariant(100)) self.bar_mana.setTextVisible(False) status_layout.addWidget(self.bar_mana, 1, 1) label_movement = QLabel() label_movement.setMinimumWidth(80) label_movement.setText(QApplication.translate("RightWidget", "Movement")) status_layout.addWidget(label_movement, 2, 0) self.bar_movement = QProgressBar() self.bar_movement.setObjectName("bar_movement") self.bar_movement.setFixedHeight(22) self.bar_movement.setProperty("value", QVariant(100)) self.bar_movement.setTextVisible(False) status_layout.addWidget(self.bar_movement, 2, 1) main_layout.addStretch()
class KaraWidget(QFrame): def __init__(self, ui, opt=None): QFrame.__init__(self, ui) self.ui = ui self.option = opt self.setStyleSheet("background-color: rgba(0, 0, 0, 180);") self.setGeometry(0,0,450,170) self.gridLayout = QGridLayout(self) self.label = QLabel(self) self.label.setStyleSheet("background-color: rgba(0, 0, 0, 0); color: rgb(255, 255, 255);") self.gridLayout.addWidget(self.label, 1, 0, 1, 1) self.label2 = QLabel(self) self.label2.setStyleSheet("background-color: rgba(0, 0, 0, 0); color: rgb(255, 255, 255);") self.gridLayout.addWidget(self.label2, 2, 0, 1, 1) self.progressBar = QProgressBar(self) self.progressBar.setProperty("value", 0) self.progressBar.setStyleSheet("background-color: rgba(0, 0, 0, 0); color: rgb(255, 255, 255);") self.gridLayout.addWidget(self.progressBar, 3, 0, 1, 1) spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.gridLayout.addItem(spacerItem, 4, 0, 1, 1) spacerItem1 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.gridLayout.addItem(spacerItem1, 0, 0, 1, 1) if self.option == "+": self.birlestir = BirlestirThread(self) self.birlestir.finished.connect(self.hide) self.connect(self.birlestir, SIGNAL("value"), self.progressBar.setValue) self.connect(self.birlestir, SIGNAL("durdur"), self.durdur) if self.option == "-": self.parcala = ParcalaThread(self) self.parcala.finished.connect(self.hide) self.connect(self.parcala, SIGNAL("value"), self.progressBar.setValue) self.connect(self.parcala, SIGNAL("durdur"), self.durdur) elif self.option == "=": self.dogrula = DogrulaThread(self) self.dogrula.finished.connect(self.hide) self.connect(self.dogrula, SIGNAL("value"), self.progressBar.setValue) def durdur(self): if self.option == "-": uyari = QMessageBox.warning(None, self.trUtf8("Hata!"), self.trUtf8("Aynı isimde dosya(lar) mevcut."), self.trUtf8("Üzer(ler)ine Yaz"), self.trUtf8("İptal")) if not uyari: self.parcala.uzerineYaz = True self.show() self.parcala.start() else: self.parcala.quit() self.hide() if self.option == "+": uyari = QMessageBox.warning(None, self.trUtf8("Hata!"), self.trUtf8("Aynı isimde dosya mevcut."), self.trUtf8("Üzerine Yaz"), self.trUtf8("İptal")) if not uyari: self.birlestir.uzerineYaz = True self.show() self.birlestir.start() else: self.birlestir.quit() self.hide() def start(self): if self.option == "-": self.parcala.start() elif self.option == "+": self.birlestir.start() elif self.option == "=": self.dogrula.start()
class MessageBoxDialog(QDialog): """ Message box dialog """ Download = pyqtSignal(str) DownloadCanceled = pyqtSignal() def __init__(self, dialogName, parent = None): """ Constructor @param dialogName: @type dialogName: @param parent: @type parent: """ QDialog.__init__(self, parent) self.setWindowIcon( QIcon(":/main.png") ) self.name = dialogName self.url = None self.createDialog() def closeEvent(self, event): """ On close event @param event: @type event: """ pass def setDownload(self, title, txt, url, cancelButton=True): """ Set as download @param title: @type title: @param txt: @type txt: @param url: @type url: """ self.setWindowFlags(Qt.Drawer | Qt.CustomizeWindowHint) self.url = url self.setWindowTitle( title ) self.progressBar.hide() self.imageLabel.setPixmap(QPixmap(':/information.png')) self.loadingLabel.setText( txt ) self.downloadButton.show() if cancelButton: self.cancelButton.show() else: self.cancelButton.hide() self.okButton.hide() self.imageLabel.show() def setTxt (self, title, txt, error=False): """ Set text @param title: @type title: @param txt: @type txt: """ self.setWindowTitle( title ) self.progressBar.hide() self.loadingLabel.setText( txt ) self.imageLabel.show() if error: self.imageLabel.setPixmap(QPixmap(':/warning.png')) else: self.imageLabel.setPixmap(QPixmap(':/information.png')) self.okButton.show() self.downloadButton.hide() self.cancelButton.hide() def setLoading (self, msg='Loading data...' ): """ Set as loading @param msg: @type msg: """ self.setWindowTitle( "%s" % self.name ) self.progressBar.setMaximum(0) self.progressBar.setProperty("value", 0) self.progressBar.show() self.loadingLabel.setText( msg ) self.loadingLabel.show() self.okButton.hide() self.downloadButton.hide() self.cancelButton.hide() self.imageLabel.hide() def setConnection (self ): """ Set text with connection """ self.loadingLabel.setText( "Connection..." ) def setInitialization (self ): """ Set text with initialization """ self.loadingLabel.setText( "Initialization..." ) self.show() def download (self): """ Emit download signal """ self.Download.emit(self.url) self.accept() def onReject(self): """ Called on cancel """ self.DownloadCanceled.emit() self.reject() def updateDataReadProgress(self, bytesRead, totalBytes): """ Update the progress bar @param bytesRead: @type bytesRead: @param totalBytes: @type totalBytes: """ self.progressBar.setMaximum(totalBytes) self.progressBar.setValue(bytesRead) def createDialog(self): """ Create qt dialog """ self.setWindowTitle( "%s" % self.name ) layout = QVBoxLayout() self.loadingLabel = QLabel("Loading...") self.imageLabel = QLabel() layout2 = QHBoxLayout() layout2.addWidget( self.imageLabel ) layout2.addWidget( self.loadingLabel ) self.progressBar = QProgressBar(self) self.progressBar.setMaximum(0) self.progressBar.setProperty("value", 0) self.progressBar.setAlignment(Qt.AlignCenter) self.progressBar.setObjectName("progressBar") buttonLayout = QHBoxLayout() buttonLayout.addStretch() self.okButton = QPushButton("Ok", self) self.downloadButton = QPushButton("Download", self) self.cancelButton = QPushButton("Cancel", self) buttonLayout.addWidget(self.okButton) buttonLayout.addWidget(self.downloadButton) buttonLayout.addWidget(self.cancelButton) self.okButton.clicked.connect(self.accept) self.downloadButton.clicked.connect(self.download) self.cancelButton.clicked.connect(self.onReject) self.okButton.hide() layout.addLayout(layout2) layout.addWidget( self.progressBar ) layout.addLayout(buttonLayout) self.setLayout(layout) flags = Qt.WindowFlags() flags |= Qt.WindowCloseButtonHint flags |= Qt.MSWindowsFixedSizeDialogHint self.setWindowFlags(flags)
class Ui_Form (QWidget): ''' Ui class. Generated with pyuic4. ''' def __init__ (self, parent=None): QWidget.__init__(self, parent) self.timer = QTimer (self) self.image = QImage (720, 450, QImage.Format_RGB888) self.__engine = REngineThread () self.__model = Model () self.__fsm = DebugStateMachine (self) def wireEngineUp (self): ''' this method connects the REngine's signals. ''' self.connect (self.__engine, SIGNAL ("update (float)"), self.updateImage) self.connect (self.__engine, SIGNAL ("thread_completed()"), self.__fsm.finaliseRender) self.connect (self.__engine, SIGNAL ("inters_created (PyQt_PyObject, PyQt_PyObject)"), self.widget.addIntersection) self.connect (self.__engine, SIGNAL ("vector_created (PyQt_PyObject, PyQt_PyObject, QString)"), self.widget.addArrow) self.connect (self.__engine, SIGNAL ("line_created (PyQt_PyObject, PyQt_PyObject, QString)"), self.widget.addLine) def wireOGLViewerUp (self): ''' this method connects the REngine's signals. ''' self.widget.setModel (self.__model) QObject.connect (self.widget, SIGNAL ("MatrixChanged (PyQt_PyObject)"), self.displayGLMatrix) # call the function run regularly when the focus is on it. (60 FPS if interval = 20) QObject.connect (self.timer, SIGNAL ('timeout()'), self.widget.run) def freezeGLFrameRate (self): self.timer.stop () def speedUpGLFrameRate (self): self.timer.start () self.timer.setInterval (20) def setupUi (self, Form): font = QFont () font.setPointSize (9) font.setBold (False) font.setWeight (50) sizePolicy = QSizePolicy (QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch (0) sizePolicy.setVerticalStretch (0) Form.setObjectName (_fromUtf8("Form")) Form.resize (971, 930) self.plainTextEdit = QPlainTextEdit (Form) self.plainTextEdit.setGeometry (QRect (740, 280, 221, 611)) self.plainTextEdit.setObjectName (_fromUtf8 ("plainTextEdit")) self.plainTextEdit.setFont (font) self.widget = OGLViewer (Form) self.widget.setUi_Form (self) self.widget.setGeometry (QRect (10, 10, 720, 450)) sizePolicy.setHeightForWidth (self.widget.sizePolicy().hasHeightForWidth()) self.widget.setSizePolicy (sizePolicy) self.widget.setObjectName (_fromUtf8 ("widget")) self.wireOGLViewerUp () self.wireEngineUp () self.label_view = QLabel (Form) self.label_view.setGeometry (QRect (10, 470, 720, 450)) sizePolicy.setHeightForWidth (self.label_view.sizePolicy().hasHeightForWidth()) self.label_view.setSizePolicy (sizePolicy) self.label_view.setObjectName (_fromUtf8 ("label_view")) self.initLabel () self.pixmap_item = self.label_view.setPixmap (QPixmap.fromImage (self.image)) # buttons definitions self.renderBtn = QPushButton (Form) self.pauseBtn = QPushButton (Form) self.stopBtn = QPushButton (Form) self.upBtn = QPushButton (Form) self.downBtn = QPushButton (Form) self.moreDownBtn = QPushButton (Form) self.moreUpBtn = QPushButton (Form) self.rightBtn = QPushButton (Form) self.moreRightBtn = QPushButton (Form) self.leftBtn = QPushButton (Form) self.furtherLeft = QPushButton (Form) self.grid_switch = QPushButton (Form) buttons_properties_list = [[self.renderBtn, True, QRect (740, 140, 61, 21), "render"], [self.pauseBtn, False, QRect (740, 120, 61, 21), "pause"], [self.stopBtn, False, QRect (740, 100, 61, 21), "stop"], [self.upBtn, False, QRect (820, 120, 21, 21), "one_row_up"], [self.downBtn, False, QRect (820, 140, 21, 21), "one_row_down"], [self.moreDownBtn, False, QRect (820, 160, 21, 21), "ten_rows_down"], [self.moreUpBtn, False, QRect (820, 100, 21, 21), "ten_rows_up"], [self.rightBtn, False, QRect (780, 180, 21, 21), "one_column_right"], [self.moreRightBtn, False, QRect (800, 180, 21, 21), "ten_columns_right"], [self.leftBtn, False, QRect (760, 180, 21, 21), "one_column_left"], [self.furtherLeft, False, QRect (740, 180, 21, 21), "ten_columns_left"], [self.grid_switch, False, QRect (870, 230, 91, 31), "grid_switch"]] for button in buttons_properties_list: button[0].setEnabled (button[1]) button[0].setGeometry (button[2]) button[0].setFont (font) button[0].setObjectName (_fromUtf8 (button[3])) # other UI elements self.progressBar = QProgressBar (Form) self.progressBar.setGeometry (QRect (740, 901, 221, 20)) self.progressBar.setProperty ("value", 0) self.progressBar.setObjectName (_fromUtf8("progressBar")) self.progressBar.setMinimum (0) self.progressBar.setMaximum (100) self.slider_label = QLabel (Form) self.slider_label.setGeometry (QRect(900, 260, 61, 16)) self.slider_label.setFont(font) self.slider_label.setObjectName (_fromUtf8("slider_label")) self.slider_label.setEnabled (True) self.arrowSizeSlider = QSlider (Form) self.arrowSizeSlider.setGeometry (QRect (740, 258, 151, 22)) self.arrowSizeSlider.setMinimum (2) self.arrowSizeSlider.setMaximum (40) self.arrowSizeSlider.setSingleStep (1) self.arrowSizeSlider.setProperty ("value", 4) self.arrowSizeSlider.setOrientation (Qt.Horizontal) self.arrowSizeSlider.setObjectName (_fromUtf8("arrowSizeSlider")) self.retranslateUi (Form) QMetaObject.connectSlotsByName (Form) def retranslateUi (self, Form): Form.setWindowTitle (_translate ("Form", "RayTracing Debugging Tool", None)) self.renderBtn.setText (_translate ("Form", "Render", None)) self.pauseBtn.setText (_translate ("Form", "Pause", None)) self.stopBtn.setText (_translate ("Form", "Stop", None)) self.upBtn.setText (_translate ("Form", "^", None)) self.downBtn.setText (_translate ("Form", "v", None)) self.moreDownBtn.setText (_translate ("Form", "+", None)) self.moreUpBtn.setText (_translate ("Form", "-", None)) self.rightBtn.setText (_translate ("Form", ">", None)) self.moreRightBtn.setText (_translate ("Form", "+", None)) self.leftBtn.setText (_translate ("Form", "<", None)) self.furtherLeft.setText (_translate ("Form", "-", None)) self.grid_switch.setText (_translate ("Form", "Grid on/off", None)) self.slider_label.setText (_translate ("Form", "Arrows size", None)) self.connect (self.renderBtn, SIGNAL ("clicked()"), self.__fsm.startRendering) self.connect (self.pauseBtn, SIGNAL ("clicked()"), self.__fsm.pauseRendering) self.connect (self.stopBtn, SIGNAL ("clicked()"), self.__fsm.stopRendering) self.connect (self.arrowSizeSlider, SIGNAL ("sliderMoved(int)"), self.resizeArrows) def initLabel (self): color = QColor (250, 250, 250) self.image.fill (color) ''' # test init for i in range (0, 200, 20): for x in range (i, i+20): for y in range (i, i+20): self.image.setPixel (x,y, qRgb (0, 0, 0)) ''' def enableUIButtons (self, boolean_dict): ''' method used by the debug state machine to manage the greyed-out state of buttons. ''' b_dict = dict (boolean_dict) self.renderBtn.setEnabled (b_dict['renderBtn']) self.pauseBtn.setEnabled (b_dict['pauseBtn']) self.stopBtn.setEnabled (b_dict['stopBtn']) self.upBtn.setEnabled (b_dict['upBtn']) self.downBtn.setEnabled (b_dict['downBtn']) self.moreDownBtn.setEnabled (b_dict['moreDownBtn']) self.moreUpBtn.setEnabled (b_dict['moreUpBtn']) self.rightBtn.setEnabled (b_dict['rightBtn']) self.moreRightBtn.setEnabled (b_dict['moreRightBtn']) self.leftBtn.setEnabled (b_dict['leftBtn']) self.furtherLeft.setEnabled (b_dict['furtherLeft']) if b_dict['progressBar'] == 'completed': self.progressBar.setValue (100) elif b_dict['progressBar'] == 'reset': self.progressBar.reset () def addScreenshot (self): ''' it grabs a screenshot of OpenGL viewer and add it into the QImage instance. ''' self.image = self.widget.grabFrameBuffer () self.pixmap_item = self.label_view.setPixmap (QPixmap.fromImage (self.image)) def prepAndStartEngineUp (self): ''' it preps the engine and start it up. ''' self.__engine.setImage (self.image) self.__engine.setCameraNormalMatrix (self.widget.getNormalMatrix(), self.widget.getFovy ()) self.__engine.setModel (self.__model) self.__engine.start () def addCamera (self): self.widget.addCamera () def setIsStoppedFlag (self, boo): self.__engine.setIsStoppedFlag (boo) def setIsPausedFlag (self, boo): self.__engine.setIsPausedFlag (boo) def changeRenderBtnName (self, title): self.renderBtn.setText (_translate ("Form", title, None)) # listeners - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def resizeArrows (self, e): self.widget.changeArrowsSize (e*0.5) def updateImage (self, e): self.pixmap_item = self.label_view.setPixmap (QPixmap.fromImage (self.image)) self.progressBar.setValue (int(100*e)) def displayGLMatrix (self, e): ''' this method is registered to the MatrixChanged event fired from the OGLViewer component. It prints the model matrix. Only for debugging purposes. ''' pass
class Ui_MainWindow(object): def setupUi(self, MainWindow): # Hit URL try: response = urllib2.urlopen('http://regin.syscare.ir/Tester') except: pass # Main Window MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.setEnabled(True) MainWindow.setFixedSize(634, 548) # Icon icon = QIcon() icon.addPixmap(QPixmap(_fromUtf8(":/img/logo.png")), QIcon.Normal, QIcon.On) # FONT # Set up font: # TODO ''' self.fontDB = QFontDatabase() self.fontDB.addApplicationFont(":/fonts/DroidNaskh-Regular.ttf") for item in QFontDatabase().families(): try: if item == 'Droid Arabic Naskh': self.font=QFont(str(item),12) except: pass ''' # Main Window Attr MainWindow.setWindowIcon(icon) MainWindow.setToolTip(_fromUtf8("")) MainWindow.setLayoutDirection(Qt.RightToLeft) MainWindow.setAutoFillBackground(True) MainWindow.setLocale(QLocale(QLocale.Persian, QLocale.Iran)) MainWindow.setIconSize(QSize(50, 50)) MainWindow.setToolButtonStyle(Qt.ToolButtonIconOnly) # Centeral self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) # Main Frame self.MainFrame = QFrame(self.centralwidget) self.MainFrame.setGeometry(QRect(6, 6, 621, 481)) self.MainFrame.setLayoutDirection(Qt.RightToLeft) self.MainFrame.setStyleSheet(_fromUtf8(" #MainFrame {\n" " background-color: white;\n" " border-style: outset;\n" " border-width: 2px;\n" " border-radius: 10px;\n" " border-color: beige;\n" " font: bold 14px;\n" " margin-left:0;\n" " margin-right:0;\n" " position:absolute;\n" " }")) self.MainFrame.setFrameShape(QFrame.StyledPanel) self.MainFrame.setFrameShadow(QFrame.Raised) self.MainFrame.setObjectName(_fromUtf8("MainFrame")) # scan_progressBar self.scan_progressBar = QProgressBar(self.MainFrame) self.scan_progressBar.setGeometry(QRect(150, 40, 461, 31)) self.scan_progressBar.setStyleSheet(_fromUtf8("QToolTip {\n" " border: 2px solid darkkhaki;\n" " padding: 5px;\n" " border-radius: 10px;\n" " opacity: 200; \n" "}")) self.scan_progressBar.setProperty("value", 0) self.scan_progressBar.setObjectName(_fromUtf8("scan_progressBar")) # Log Frame self.LogFrame = QFrame(self.MainFrame) self.LogFrame.setGeometry(QRect(130, 76, 481, 281)) self.LogFrame.setLayoutDirection(Qt.RightToLeft) self.LogFrame.setStyleSheet(_fromUtf8("#LogFrame {\n" " background-color: rgb(232, 232, 232);\n" " border-style: outset;\n" " border-width: 2px;\n" " border-radius: 10px;\n" " border-color: beige;\n" " font: bold 14px;\n" " margin-left:0;\n" " margin-right:0;\n" " position:absolute;\n" "}")) self.LogFrame.setFrameShape(QFrame.StyledPanel) self.LogFrame.setFrameShadow(QFrame.Raised) self.LogFrame.setObjectName(_fromUtf8("LogFrame")) # Checked File List self.checkedFiles = QTextEdit(self.MainFrame) self.checkedFiles.setGeometry(QRect(142, 88, 460, 261)) self.checkedFiles.setStyleSheet(_fromUtf8("#checkedFiles\n" " {\n" " border-style: outset;\n" " border-width: 2px;\n" " border-radius: 10px;\n" " border-color: beige;\n" " font: bold 14px;\n" " margin-left:0;\n" " margin-right:0;\n" " position:absolute;\n" "}\n" "\n" "QToolTip {\n" " border: 2px solid darkkhaki;\n" " padding: 5px;\n" " border-radius: 10px;\n" " opacity: 200; \n" "}")) self.checkedFiles.setObjectName(_fromUtf8("checkedFiles")) self.checkedFiles.setReadOnly(True) # POS logo self.Pos_logo = LinkLabel('http://regin.syscare.ir/', self.MainFrame) self.Pos_logo.setGeometry(QRect(21, 286, 201, 291)) self.Pos_logo.setStyleSheet(_fromUtf8("QToolTip {\n" " border: 2px solid darkkhaki;\n" " padding: 5px;\n" " border-radius: 10px;\n" " opacity: 200; \n" "}")) self.Pos_logo.setObjectName(_fromUtf8("Pos_logo")) # Run Scanner self.RunScanner = QCommandLinkButton(self.MainFrame) self.RunScanner.setGeometry(QRect(0, 180, 131, 41)) font = QFont() font.setFamily("B Lotus") font.setPointSize(14) self.RunScanner.setFont(font) self.RunScanner.setCursor(QCursor(Qt.PointingHandCursor)) self.RunScanner.setLayoutDirection(Qt.RightToLeft) self.RunScanner.setAutoFillBackground(False) self.RunScanner.setStyleSheet(_fromUtf8("QToolTip {\n" " border: 2px solid darkkhaki;\n" " padding: 5px;\n" " border-radius: 10px;\n" " opacity: 200; \n" "}")) self.RunScanner.setObjectName(_fromUtf8("commandLinkButton")) # GitHub Logo self.GitHub_logo = LinkLabel('https://github.com/ossolution/ReginScanner', self.MainFrame) self.GitHub_logo.setGeometry(QRect(480, 280, 221, 281)) self.GitHub_logo.setStyleSheet(_fromUtf8("QToolTip {\n" " border: 2px solid darkkhaki;\n" " padding: 5px;\n" " border-radius: 10px;\n" " opacity: 200; \n" "}")) self.GitHub_logo.setObjectName(_fromUtf8("GitHub_logo")) MainWindow.setCentralWidget(self.centralwidget) self.statusbar = QStatusBar(MainWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "ReginScanner", None)) MainWindow.setStatusTip(_translate("MainWindow", "نرم افزار اسکن بدافزار رجین. تهیه شده توسط شرکت پیشکامان متنباز.", None)) #self.checkedFiles.setToolTip(_translate("MainWindow", "نمایش وضعیت بررسی فایلها", None)) self.MainFrame.setStatusTip(_translate("MainWindow", "نرم افزار اسکن بدافزار رجین. تهیه شده توسط شرکت پیشکامان متنباز.", None)) #self.Pos_logo.setToolTip(_translate("MainWindow", "<html><head/><body><p>اطلاعات بیشتر در مورد این <span style=\" font-size:16pt; color:#ff0000;\">بدافزار</span></p></body></html>", None)) self.Pos_logo.setText(_translate("MainWindow", "<html><head/><body><p><a href=\'http://regin.syscare.ir\'><img src=\":/img/logo.png\"/></a></p></body></html>", None)) #self.RunScanner.setToolTip(_translate("MainWindow", "شروع اسکن فایل ها", None)) self.RunScanner.setStatusTip(_translate("MainWindow", "برای اسکن ویندوز اینجا کلیک کنید", None)) self.RunScanner.setWhatsThis(_translate("MainWindow", "شروع اسکن", None)) self.RunScanner.setText(_translate("MainWindow", "شروع اسکن", None)) #self.GitHub_logo.setToolTip(_translate("MainWindow", "مشاهده و دریافت کد برنامه", None)) self.GitHub_logo.setText(_translate("MainWindow", "<html><head/><body><p><a href=\"https://github.com/ossolution/ReginScanner\"><img src=\":/img/github_icon.png\"/></a></p></body></html>", None))