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])
def __init__(self, template, character, parent=None): super(SkillWidget, self).__init__(template, character, parent) self.__layout = QVBoxLayout() self.setLayout(self.__layout) self.__scrollArea = QScrollArea() ## Die Auflistung der Fertigkeiten soll auch unter Windows einen transparenten Hintergrund haben. self.__scrollArea.setObjectName("transparentWidget") ## \todo Sollte nicht vom Betriebssystem, sondern vom verwendeten Style abhängen. if os.name == "nt": self.__scrollArea.setStyleSheet( "QWidget#transparentWidget { background: transparent; }") self.__layout.addWidget(self.__scrollArea) self.__scrollLayout = QVBoxLayout() self.__scrollWidget = QWidget() ## Die Auflistung der Fertigkeiten soll auch unter Windows einen transparenten Hintergrund haben. Indem ich den selben Namen wie zuvor vergebe, wirkt auch das Stylsheet auf dieses Widget. self.__scrollWidget.setObjectName("transparentWidget") #self.__scrollWidget.setStyleSheet( "QWidget#transparentWidget { background-color:transparent; }" ) #scrollWidget.setMinimumSize(this.width(), 400); self.__scrollWidget.setLayout(self.__scrollLayout) typ = "Skill" ## Eine Liste, in der alle Eigenschafts-Widgets aufgelistet werden. self.__traitWidgets = [] for item in Config.CATEGORIES_MAIN: #Debug.debug(self._character.traits) # Für jede Kategorie wird ein eigener Abschnitt erzeugt. widgetSkillCategory = QGroupBox() widgetSkillCategory.setTitle(item) widgetSkillCategory.setFlat(True) layoutSkillCategory = QVBoxLayout() widgetSkillCategory.setLayout(layoutSkillCategory) self.__scrollLayout.addWidget(widgetSkillCategory) __list = list(self._character.traits[typ][item].items()) __list.sort() for skill in __list: # Anlegen des Widgets, das diese Eigenschaft repräsentiert. traitWidget = CharaTrait(skill[1], self) traitWidget.buttonText = 0 traitWidget.setDescriptionHidden(True) traitWidget.enableButton( 0 ) # Zu Beginn sollen die Spezailisierungen nicht enabled sein. # Dieses Widget auch an Liste anhängen, damit ich einfacher darauf zugreifen kann. traitListItem = traitWidget self.__traitWidgets.append(traitListItem) # Es werden nur Fertigkeiten der richtigen Alters- und Zeit-Kategorie angezeigt. self.hideReasonChanged.connect(traitWidget.hideOrShowTrait) # Fertigkeiten haben Spezialisierungen. traitWidget.specialtiesClicked.connect( self.uncheckOtherButtons) traitWidget.specialtiesClicked.connect( self.specialtiesActivated.emit) ## Wenn sich die Spezialisierungen ändern, sollen die veränderten Spezialisierungen auch angezeigt werden. Das wird so gelöst, als wäre der Knopf für die Spezialisierungen erneut gedrückt worden. #skill.specialtiesChanged.connect(self.emitSpecialtiesActivated) layoutSkillCategory.addWidget(traitWidget) self.maxTraitChanged.connect(traitWidget.setMaximum) # Stretch einfügen, damit die Eigenschaften besser angeordnet sind. self.__scrollLayout.addStretch() self.__scrollArea.setWidget(self.__scrollWidget) self.__scrollArea.setWidgetResizable(True) self.__scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.__scrollArea.setMinimumWidth( self.__scrollArea.viewport().minimumWidth())
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 FeatureDlg(QDialog): def __init__(self, parent=None): QDialog.__init__(self, parent) # init # ------------------------------------------------ self.setWindowTitle("Spatial Features") # widgets and layouts # ------------------------------------------------ self.layout = QHBoxLayout() self.setLayout(self.layout) self.tableAndViewGroupBox = QGroupBox(" Scales and Groups") self.tableAndViewGroupBox.setFlat(True) self.featureTableWidget = featureTableWidget.FeatureTableWidget() self.tableAndViewLayout = QVBoxLayout() self.tableAndViewLayout.setSizeConstraint(QLayout.SetNoConstraint) self.tableAndViewLayout.addWidget(self.featureTableWidget) self.viewAndButtonLayout = QVBoxLayout() self.preView = preView.PreView() self.viewAndButtonLayout.addWidget(self.preView) self.viewAndButtonLayout.addStretch() self.buttonsLayout = QHBoxLayout() self.memReqLabel = QLabel() self.buttonsLayout.addWidget(self.memReqLabel) self.buttonsLayout.addStretch() # Add Cancel self.cancel = QToolButton() self.cancel.setText("Cancel") self.cancel.clicked.connect(self.on_cancelClicked) self.buttonsLayout.addWidget(self.cancel) # Add OK self.ok = QToolButton() self.ok.setText("OK") self.ok.clicked.connect(self.on_okClicked) self.buttonsLayout.addWidget(self.ok) self.buttonsLayout.addSpacerItem(QSpacerItem(10, 0)) self.viewAndButtonLayout.addSpacerItem(QSpacerItem(0, 10)) self.tableAndViewGroupBox.setLayout(self.tableAndViewLayout) self.tableAndViewLayout.addLayout(self.buttonsLayout) self.layout.addWidget(self.tableAndViewGroupBox) self.layout.setContentsMargins(0, 0, 0, 0) self.tableAndViewGroupBox.setContentsMargins(4, 10, 4, 4) self.tableAndViewLayout.setContentsMargins(0, 10, 0, 0) self.featureTableWidget.brushSizeChanged.connect(self.preView.setFilledBrsuh) self.setMemReq() # methods # ------------------------------------------------ @property def selectedFeatureBoolMatrix(self): """Return the bool matrix of features that the user selected.""" return self.featureTableWidget.createSelectedFeaturesBoolMatrix() @selectedFeatureBoolMatrix.setter def selectedFeatureBoolMatrix(self, newMatrix): """Populate the table of selected features with the provided matrix.""" self.featureTableWidget.setSelectedFeatureBoolMatrix(newMatrix) def createFeatureTable(self, features, sigmas, brushNames=None): self.featureTableWidget.createTableForFeatureDlg(features, sigmas, brushNames) def setImageToPreView(self, image): self.preView.setVisible(image is not None) if image is not None: self.preView.setPreviewImage(qimage2ndarray.array2qimage(image)) def setIconsToTableWidget(self, checked, partiallyChecked, unchecked): self.featureTableWidget.itemDelegate.setCheckBoxIcons(checked, partiallyChecked, unchecked) def setMemReq(self): # featureSelectionList = self.featureTableWidget.createFeatureList() # TODO # memReq = self.ilastik.project.dataMgr.Classification.featureMgr.computeMemoryRequirement(featureSelectionList) # self.memReqLabel.setText("%8.2f MB" % memReq) pass def on_okClicked(self): # featureSelectionList = self.featureTableWidget.createFeatureList() # selectedFeatureList = self.featureTableWidget.createSelectedFeatureList() # sigmaList = self.featureTableWidget.createSigmaList() # featureMgr.ilastikFeatureGroups.newGroupScaleValues = sigmaList # featureMgr.ilastikFeatureGroups.newSelection = selectedFeatureList # res = self.parent().project.dataMgr.Classification.featureMgr.setFeatureItems(featureSelectionList) # if res is True: # self.parent().labelWidget.setBorderMargin(int(self.parent().project.dataMgr.Classification.featureMgr.maxContext)) # self.ilastik.project.dataMgr.Classification.featureMgr.computeMemoryRequirement(featureSelectionList) # self.accept() # else: # QErrorMessage.qtHandler().showMessage("Not enough Memory, please select fewer features !") # self.on_cancelClicked() self.accept() def on_cancelClicked(self): self.reject()
def viewDatasetAction(self): #print "viewDatasetAction" model = self.model table_name = str(model.fileName(self.currentIndex)) table_name_full = str(model.filePath(self.currentIndex)) parentIndex = model.parent(self.currentIndex) parent_name = str(model.fileName(parentIndex)) parent_name_full = str(model.filePath(parentIndex)) storage = StorageFactory().get_storage('flt_storage', storage_location=parent_name_full) columns = storage.get_column_names(table_name) # temporarily use the table name for the dataset name # dataset_name = DatasetFactory().dataset_name_for_table(table_name) # Aaron - please check this way of getting the XMLConfiguration -- is this the best way? # general = self.mainwindow.toolboxBase.opus_core_xml_configuration.get_section('general') # # problem: this gets the package order for the current project, but the viewer shows all the data # package_order = general['dataset_pool_configuration'].package_order # PREVIOUS HACK: # package_order = ['seattle_parcel','urbansim_parcel', 'eugene', 'urbansim', 'opus_core'] # temporary code: just use a generic dataset for now data = Dataset(in_storage=storage, dataset_name=table_name, in_table_name=table_name, id_name=[]) # code to get a more specialized dataset if possible (doesn't work with table names not ending in 's' # unless they are in the exceptions list in DatasetFactory) # data = DatasetFactory().search_for_dataset_with_hidden_id(dataset_name, package_order, # arguments={'in_storage': storage, 'in_table_name': table_name}) # Need to add a new tab to the main tabs for display of the data container = QWidget() widgetLayout = QVBoxLayout(container) summaryGroupBox = QGroupBox(container) summaryGroupBox.setTitle(QString("Year: %s Run name: %s" % (parent_name,table_name_full.split('/')[-3]))) summaryGroupBox.setFlat(True) summaryGroupBoxLayout = QVBoxLayout(summaryGroupBox) # Grab the summary data buffer = StringIO() data.summary(output=buffer) strng = buffer.getvalue() buffer.close() textBrowser = QTextBrowser() # textBrowser.insertPlainText(strng) textBrowser.insertHtml(self.parse_dataset_summary(strng)) summaryGroupBoxLayout.addWidget(textBrowser) widgetLayout.addWidget(summaryGroupBox) tableGroupBox = QGroupBox(container) tableGroupBox.setTitle(QString("Table View")) tableGroupBox.setFlat(True) tableGroupBoxLayout = QVBoxLayout(tableGroupBox) tv = QTableView() header = columns tabledata_tmp = [] for column in columns: tabledata_tmp.append(data.get_attribute(column)) # Transpose the lists tabledata = map(None,*tabledata_tmp) # If the table data is not empty then we display it if tabledata: #tv.resizeColumnsToContents() tm = TableModel(tabledata, header, container) tv.setModel(tm) tv.setSortingEnabled(True) tableGroupBoxLayout.addWidget(tv) widgetLayout.addWidget(tableGroupBox) container.tabIcon = IconLibrary.icon('inspect') container.tabLabel = QString(table_name) self.manager._attach_tab(container)
def viewDatasetAction(self): #print "viewDatasetAction" model = self.model table_name = str(model.fileName(self.currentIndex)) table_name_full = str(model.filePath(self.currentIndex)) parentIndex = model.parent(self.currentIndex) parent_name = str(model.fileName(parentIndex)) parent_name_full = str(model.filePath(parentIndex)) storage = StorageFactory().get_storage( 'flt_storage', storage_location=parent_name_full) columns = storage.get_column_names(table_name) # temporarily use the table name for the dataset name # dataset_name = DatasetFactory().dataset_name_for_table(table_name) # Aaron - please check this way of getting the XMLConfiguration -- is this the best way? # general = self.mainwindow.toolboxBase.opus_core_xml_configuration.get_section('general') # # problem: this gets the package order for the current project, but the viewer shows all the data # package_order = general['dataset_pool_configuration'].package_order # PREVIOUS HACK: # package_order = ['seattle_parcel','urbansim_parcel', 'eugene', 'urbansim', 'opus_core'] # temporary code: just use a generic dataset for now data = Dataset(in_storage=storage, dataset_name=table_name, in_table_name=table_name, id_name=[]) # code to get a more specialized dataset if possible (doesn't work with table names not ending in 's' # unless they are in the exceptions list in DatasetFactory) # data = DatasetFactory().search_for_dataset_with_hidden_id(dataset_name, package_order, # arguments={'in_storage': storage, 'in_table_name': table_name}) # Need to add a new tab to the main tabs for display of the data container = QWidget() widgetLayout = QVBoxLayout(container) summaryGroupBox = QGroupBox(container) summaryGroupBox.setTitle( QString("Year: %s Run name: %s" % (parent_name, table_name_full.split('/')[-3]))) summaryGroupBox.setFlat(True) summaryGroupBoxLayout = QVBoxLayout(summaryGroupBox) # Grab the summary data buffer = StringIO() data.summary(output=buffer, unload_after_each_attribute=True) strng = buffer.getvalue() buffer.close() textBrowser = QTextBrowser() # textBrowser.insertPlainText(strng) textBrowser.insertHtml(self.parse_dataset_summary(strng)) summaryGroupBoxLayout.addWidget(textBrowser) widgetLayout.addWidget(summaryGroupBox) tableGroupBox = QGroupBox(container) tableGroupBox.setTitle(QString("Table View")) tableGroupBox.setFlat(True) tableGroupBoxLayout = QVBoxLayout(tableGroupBox) tv = QTableView() header = columns tabledata_tmp = [] for column in columns: tabledata_tmp.append(data.get_attribute(column)) # Transpose the lists tabledata = map(None, *tabledata_tmp) # If the table data is not empty then we display it if tabledata: #tv.resizeColumnsToContents() tm = TableModel(tabledata, header, container) tv.setModel(tm) tv.setSortingEnabled(True) tableGroupBoxLayout.addWidget(tv) widgetLayout.addWidget(tableGroupBox) container.tabIcon = IconLibrary.icon('inspect') container.tabLabel = QString(table_name) self.manager._attach_tab(container)
def __init__(self, template, character, parent=None): super(SkillWidget, self).__init__(template, character, parent) self.__layout = QVBoxLayout() self.setLayout( self.__layout ) self.__scrollArea = QScrollArea() ## Die Auflistung der Fertigkeiten soll auch unter Windows einen transparenten Hintergrund haben. self.__scrollArea.setObjectName("transparentWidget") ## \todo Sollte nicht vom Betriebssystem, sondern vom verwendeten Style abhängen. if os.name == "nt": self.__scrollArea.setStyleSheet( "QWidget#transparentWidget { background: transparent; }" ) self.__layout.addWidget( self.__scrollArea) self.__scrollLayout = QVBoxLayout() self.__scrollWidget = QWidget() ## Die Auflistung der Fertigkeiten soll auch unter Windows einen transparenten Hintergrund haben. Indem ich den selben Namen wie zuvor vergebe, wirkt auch das Stylsheet auf dieses Widget. self.__scrollWidget.setObjectName("transparentWidget") #self.__scrollWidget.setStyleSheet( "QWidget#transparentWidget { background-color:transparent; }" ) #scrollWidget.setMinimumSize(this.width(), 400); self.__scrollWidget.setLayout(self.__scrollLayout) typ = "Skill" ## Eine Liste, in der alle Eigenschafts-Widgets aufgelistet werden. self.__traitWidgets = [] for item in Config.CATEGORIES_MAIN: #Debug.debug(self._character.traits) # Für jede Kategorie wird ein eigener Abschnitt erzeugt. widgetSkillCategory = QGroupBox() widgetSkillCategory.setTitle(item) widgetSkillCategory.setFlat(True) layoutSkillCategory = QVBoxLayout() widgetSkillCategory.setLayout( layoutSkillCategory ); self.__scrollLayout.addWidget( widgetSkillCategory ) __list = list( self._character.traits[typ][item].items() ) __list.sort() for skill in __list: # Anlegen des Widgets, das diese Eigenschaft repräsentiert. traitWidget = CharaTrait( skill[1], self ) traitWidget.buttonText = 0 traitWidget.setDescriptionHidden( True ) traitWidget.enableButton(0) # Zu Beginn sollen die Spezailisierungen nicht enabled sein. # Dieses Widget auch an Liste anhängen, damit ich einfacher darauf zugreifen kann. traitListItem = traitWidget self.__traitWidgets.append(traitListItem) # Es werden nur Fertigkeiten der richtigen Alters- und Zeit-Kategorie angezeigt. self.hideReasonChanged.connect(traitWidget.hideOrShowTrait) # Fertigkeiten haben Spezialisierungen. traitWidget.specialtiesClicked.connect(self.uncheckOtherButtons) traitWidget.specialtiesClicked.connect(self.specialtiesActivated.emit) ## Wenn sich die Spezialisierungen ändern, sollen die veränderten Spezialisierungen auch angezeigt werden. Das wird so gelöst, als wäre der Knopf für die Spezialisierungen erneut gedrückt worden. #skill.specialtiesChanged.connect(self.emitSpecialtiesActivated) layoutSkillCategory.addWidget( traitWidget ) self.maxTraitChanged.connect(traitWidget.setMaximum) # Stretch einfügen, damit die Eigenschaften besser angeordnet sind. self.__scrollLayout.addStretch() self.__scrollArea.setWidget(self.__scrollWidget) self.__scrollArea.setWidgetResizable(True) self.__scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.__scrollArea.setMinimumWidth(self.__scrollArea.viewport().minimumWidth())
class Widget(QWidget): def __init__(self, dockwidget): super(Widget, self).__init__(dockwidget) self._document = None self._midiin = midiinput.MidiIn(self) self._dockwidget = weakref.ref(dockwidget) signals = list() self._labelmidichannel = QLabel() self._midichannel = QComboBox() signals.append(self._midichannel.currentIndexChanged) self._labelkeysignature = QLabel() self._keysignature = QComboBox() signals.append(self._keysignature.currentIndexChanged) self._labelaccidentals = QLabel() self._accidentalssharps = QRadioButton() signals.append(self._accidentalssharps.clicked) self._accidentalsflats = QRadioButton() signals.append(self._accidentalsflats.clicked) self._groupaccidentals = QGroupBox() self._groupaccidentals.setFlat(True) hbox = QHBoxLayout() self._groupaccidentals.setLayout(hbox) hbox.addWidget(self._accidentalssharps) hbox.addWidget(self._accidentalsflats) self._accidentalssharps.setChecked(True) self._chordmode = QCheckBox() signals.append(self._chordmode.clicked) self._relativemode = QCheckBox() signals.append(self._relativemode.clicked) self._labeldamper = QLabel() self._damper = QComboBox() self._labelsostenuto = QLabel() self._sostenuto = QComboBox() self._labelsoft = QLabel() self._soft = QComboBox() ac = self.parentWidget().actionCollection self._capture = QToolButton() self._capture.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self._capture.setDefaultAction(ac.capture_start) self._notemode = QLabel() layout = QVBoxLayout() self.setLayout(layout) grid = QGridLayout(spacing=0) layout.addLayout(grid) grid.addWidget(self._labelmidichannel, 0, 0) grid.addWidget(self._midichannel, 0, 1) grid.addWidget(self._labelkeysignature, 1, 0) grid.addWidget(self._keysignature, 1, 1) grid.addWidget(self._labelaccidentals, 2, 0) grid.addWidget(self._groupaccidentals, 2, 1) grid.addWidget(self._chordmode, 3, 0) grid.addWidget(self._relativemode, 3, 1) grid.addWidget(self._labeldamper, 4, 0) grid.addWidget(self._damper, 4, 1) grid.addWidget(self._labelsostenuto, 5, 0) grid.addWidget(self._sostenuto, 5, 1) grid.addWidget(self._labelsoft, 6, 0) grid.addWidget(self._soft, 6, 1) hbox = QHBoxLayout() layout.addLayout(hbox) hbox.addWidget(self._capture) hbox.addStretch() app.translateUI(self) self.loadsettings() for s in signals: s.connect(self.savesettings) def mainwindow(self): return self._dockwidget().mainwindow() def channel(self): return self._midichannel.currentIndex() def keysignature(self): return self._keysignature.currentIndex() def accidentals(self): if self._accidentalsflats.isChecked(): return 'flats' else: return 'sharps' def chordmode(self): return self._chordmode.isChecked() def relativemode(self): return self._relativemode.isChecked() def startcapturing(self): self._midiin.capture() ac = self.parentWidget().actionCollection while self._capture.actions(): # remove all old actions self._capture.removeAction(self._capture.actions()[0]) self._capture.setDefaultAction(ac.capture_stop) def stopcapturing(self): self._midiin.capturestop() ac = self.parentWidget().actionCollection while self._capture.actions(): # remove all old actions self._capture.removeAction(self._capture.actions()[0]) self._capture.setDefaultAction(ac.capture_start) def savesettings(self): s = QSettings() s.beginGroup("midiinputdock") s.setValue("midichannel", self._midichannel.currentIndex()) s.setValue("keysignature", self._keysignature.currentIndex()) if self._accidentalsflats.isChecked(): s.setValue("accidentals", 'flats') else: s.setValue("accidentals", 'sharps') s.setValue("chordmode", self._chordmode.isChecked()) s.setValue("relativemode", self._relativemode.isChecked()) def loadsettings(self): s = QSettings() s.beginGroup("midiinputdock") self._midichannel.setCurrentIndex(s.value("midichannel", 0, int)) self._keysignature.setCurrentIndex(s.value("keysignature", 7, int)) if s.value("accidentals", 'sharps', str) == 'flats': self._accidentalsflats.setChecked(True) else: self._accidentalssharps.setChecked(True) self._chordmode.setChecked(s.value("chordmode", False, bool)) self._relativemode.setChecked(s.value("relativemode", False, bool)) def translateUI(self): self._labelmidichannel.setText(_("MIDI channel")) self._midichannel.addItems([_("all")]+[str(i) for i in range(1,17)]) self._labelkeysignature.setText(_("Key signature")) self._keysignature.addItems([ _("C flat major (7 flats)"), _("G flat major (6 flats)"), _("D flat major (5 flats)"), _("A flat major (4 flats)"), _("E flat major (3 flats)"), _("B flat major (2 flats)"), _("F major (1 flat)"), _("C major"), _("G major (1 sharp)"), _("D major (2 sharps)"), _("A major (3 sharps)"), _("E major (4 sharps)"), _("B major (5 sharps)"), _("F sharp major (6 sharps)"), _("C sharp major (7 sharps)") ]) self._keysignature.setCurrentIndex(7) self._labelaccidentals.setText(_("Accidentals")) self._accidentalssharps.setText(_("sharps")) self._accidentalsflats.setText(_("flats")) self._chordmode.setText(_("Chord mode")) self._chordmode.setToolTip(_( "Enter simultaneously played notes as chords. " "See \"What's This\" for more information.")) self._chordmode.setWhatsThis(_( "Notes which are played simultaneously are written " "as chords. As a consequence they are not written " "before the last key is lifted. Of course single " "can also be entered.")) self._relativemode.setText(_("Relative mode")) self._relativemode.setToolTip(_( "Enter octaves of notes relative to the last note. " "See \"What's This\" for more information.")) self._relativemode.setWhatsThis(_( "Enter octaves of notes relative to the last note. " "This refers to the last key pressed on the MIDI keyboard, not the last note in the document." "Hold Shift with a note to enter an octave check.")) self._labeldamper.setText(_("Damper pedal")) self._labelsostenuto.setText(_("Sostenuto pedal")) self._labelsoft.setText(_("Soft pedal"))
class DAyarlar(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.resize(600, 375) self.gridLayout = QGridLayout(self) self.gridLayout.setMargin(0) self.gridLayout.setSpacing(0) self.treeWidget = QTreeWidget(self) self.treeWidget.setMaximumSize(200, 1500) self.virux = QTreeWidgetItem(self.treeWidget) self.virux.setExpanded(True) icon = QIcon() icon.addPixmap(QPixmap("data/logo.png"), QIcon.Normal, QIcon.On) self.virux.setIcon(0, icon) item_1 = QTreeWidgetItem(self.virux) item_1 = QTreeWidgetItem(self.virux) self.dialog = QTreeWidgetItem(self.treeWidget) self.dialog.setExpanded(True) item_1 = QTreeWidgetItem(self.dialog) item_1 = QTreeWidgetItem(self.dialog) self.treeWidget.header().setVisible(False) self.gridLayout.addWidget(self.treeWidget, 0, 0, 1, 1) self.groupBox = QGroupBox(self) self.groupBox.setFlat(True) self.gridLayout_3 = QGridLayout(self.groupBox) self.gridLayout_3.setMargin(0) self.gridLayout_3.setSpacing(0) self.widget = QWidget(self.groupBox) self.gridLayout_4 = QGridLayout(self.widget) self.gridLayout_4.setMargin(0) self.gridLayout_4.setSpacing(0) self.gridLayout_4.setMargin(0) spacerItem = QSpacerItem(300, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_4.addItem(spacerItem, 0, 0, 1, 1) self.gridLayout_3.addWidget(self.widget, 0, 0, 1, 1) self.gridLayout.addWidget(self.groupBox, 0, 1, 1, 1) self.pButton = QPushButton(self) self.pButton.setText("asd") self.pButton.setDefault(True) self.buttonBox = QDialogButtonBox(self) self.buttonBox.addButton(self.pButton, QDialogButtonBox.AcceptRole) #self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.gridLayout.addWidget(self.buttonBox, 1, 0, 1, 2) self.setWindowTitle("Virux Ayarlar") self.treeWidget.headerItem().setText(0, "") self.treeWidget.topLevelItem(0).setText(0, u"Virux") self.treeWidget.topLevelItem(0).child(0).setText(0, u"Virux1") self.treeWidget.topLevelItem(0).child(1).setText(0, u"Virux2") self.treeWidget.topLevelItem(1).setText(0, u"Dialog") self.treeWidget.topLevelItem(1).child(0).setText(0, u"Dialog1") self.treeWidget.topLevelItem(1).child(1).setText(0, u"Dialog2") self.groupBox.setTitle(u"GroupBox") self.groupYaz() self.treeWidget.itemPressed.connect(self.lale) def lale(self, item): print item self.groupBox.setTitle(item.text(0)) def groupYaz(self): for option in DOptions: if hasattr(option, "getOption"): #self.gridLayout_3.addWidget(option.getOption(), 0, 0, 1, 1) item = QTreeWidgetItem(self.dialog) a = option.getOption() if hasattr(a, "name"): item.setText(0, a.name) else: item.setText(0, "F**k") #self.gridLayout_3.addWidget(a, 0, 0, 1, 1)
class ConditionsDialog(QDialog): def __init__(self, reaction): super(ConditionsDialog, self).__init__() self.setGeometry(300, 200, 700, 350) self.setWindowTitle('Edit Conditions') if reaction is None: self._reaction = Reaction() else: self._reaction = reaction self._CanReturnReaction = False # Sets up GUI widgets # Reactants section self._reactantbox = QGroupBox("Reactants", self) self._reactantform = QFormLayout() self._reactantinfoboxes = [] self._productinfoboxes = [] self._catalystinfoboxes = [] self._checkbuttons = [] for x in range(Reaction.REACTING_SPECIES_LIMIT): self._reactantinfoboxes.append(QLineEdit()) self._reactantinfoboxes[x * 2].setText( self._reaction.GetReactants()[x].GetFormula()) self._reactantinfoboxes.append(QLineEdit()) self._reactantinfoboxes[x * 2 + 1].setText( str(self._reaction.GetReactants()[x].GetInitialMoles())) self._reactantform.addRow(QLabel(str(x + 1) + ".\tFormula:"), self._reactantinfoboxes[x * 2]) self._reactantform.addRow(QLabel("\tFinal Moles:"), self._reactantinfoboxes[x * 2 + 1]) self._checkbuttons.append(QCheckBox("Use this reactant", self)) self._checkbuttons[-1].setChecked( self._reaction.GetReactants()[x].GetUsed()) self._reactantform.addRow(self._checkbuttons[-1]) self._reactantbox.setLayout(self._reactantform) # Products section self._productbox = QGroupBox("Products", self) self._productform = QFormLayout() for x in range(Reaction.REACTING_SPECIES_LIMIT): self._productinfoboxes.append(QLineEdit()) self._productinfoboxes[x * 2].setText( self._reaction.GetProducts()[x].GetFormula()) self._productinfoboxes.append(QLineEdit()) self._productinfoboxes[x * 2 + 1].setText( str(self._reaction.GetProducts()[x].GetInitialMoles())) self._productform.addRow(QLabel(str(x + 1) + ".\tFormula:"), self._productinfoboxes[x * 2]) self._productform.addRow(QLabel("\tFinal Moles:"), self._productinfoboxes[x * 2 + 1]) self._checkbuttons.append(QCheckBox("Use this product", self)) self._checkbuttons[-1].setChecked( self._reaction.GetProducts()[x].GetUsed()) self._productform.addRow(self._checkbuttons[-1]) self._productbox.setLayout(self._productform) # Catalyst section self._catalystbox = QGroupBox("Catalyst", self) self._catalystform = QFormLayout() self._catalystinfoboxes.append(QLineEdit()) self._catalystinfoboxes.append(QLineEdit()) self._catalystinfoboxes[0].setText( self._reaction.GetCatalyst().GetFormula()) self._catalystinfoboxes[1].setText( str(self._reaction.GetCatalyst().GetInitialMoles())) self._catalystform.addRow(QLabel("Formula:"), self._catalystinfoboxes[0]) self._catalystform.addRow(QLabel("Moles:"), self._catalystinfoboxes[1]) self._good = QRadioButton("Good") self._poor = QRadioButton("Poor") self._inhibitor = QRadioButton("Inhibitor") self._checkbuttons.append(QCheckBox("Use this catalyst", self)) self._checkbuttons[-1].setChecked( self._reaction.GetCatalyst().GetUsed()) efficacy = self._reaction.GetCatalyst().GetEfficacy() if efficacy == 5: self._good.setChecked(True) elif efficacy == 2: self._poor.setChecked(True) else: self._inhibitor.setChecked(True) self._cataefficacygroup = QVBoxLayout() self._cataefficacygroup.addWidget(self._good) self._cataefficacygroup.addWidget(self._poor) self._cataefficacygroup.addWidget(self._inhibitor) self._catalystform.addRow(QLabel("Efficacy:"), self._cataefficacygroup) self._catalystform.addRow(self._checkbuttons[-1]) self._catalystbox.setLayout(self._catalystform) # Forward heat transfer section self._heatbox = QGroupBox("Forward heat transfer", self) self._heatform = QFormLayout() self._endo = QRadioButton("Endothermic") self._exo = QRadioButton("Exothermic") if self._reaction.GetEndothermic(): self._endo.setChecked(True) else: self._exo.setChecked(True) self._heatform.addRow(self._endo) self._heatform.addRow(self._exo) self._heatbox.setLayout(self._heatform) # Other conditions section: vessel volume; temperature self._otherbox = QGroupBox("Other conditions") self._otherform = QFormLayout() self._tempbox = QLineEdit() self._volbox = QLineEdit() self._tempbox.setText(str(self._reaction.GetTemperature())) self._volbox.setText(str(self._reaction.GetVolume())) self._otherform.addRow(QLabel("Vessel volume:"), self._volbox) self._otherform.addRow(QLabel("Temperature:"), self._tempbox) self._otherbox.setLayout(self._otherform) # Help text explaining how to enter super/subscript characters. self._scriptinfo1 = QLabel("Enter _ before a subscript character.") self._scriptinfo2 = QLabel("Enter ^ before a superscript one.") # OK and cancel buttons; checkbox so that students can try to balance the equation before it is revealed self._try = QCheckBox("Students attempt to balance equation") self._try.setChecked(False) self._okbtn = QPushButton("OK") self._okbtn.clicked.connect(self.ApplyChanges) self._cancelbtn = QPushButton("Cancel") self._rightbox = QGroupBox() self._rightbox.setFlat(False) self._rightform = QVBoxLayout() self._rightform.addWidget(self._catalystbox) self._rightform.addWidget(self._heatbox) self._rightform.addWidget(self._otherbox) self._rightbox.setLayout(self._rightform) # Layout of all those group boxes self._grid = QGridLayout() self._grid.addWidget(self._scriptinfo1, 0, 0) self._grid.addWidget(self._scriptinfo2, 1, 0) self._grid.addWidget(self._reactantbox, 2, 0) self._grid.addWidget(self._productbox, 2, 1) self._grid.addWidget(self._rightbox, 2, 2) self._grid.addWidget(self._try, 3, 0) self._grid.addWidget(self._okbtn, 3, 1) self._grid.addWidget(self._cancelbtn, 3, 2) self.setLayout(self._grid) if reaction is None: self._reaction = Reaction() else: self._reaction = reaction self._cancelbtn.clicked.connect(self.close) self.exec_() def ApplyChanges(self): errorlist = [] # Validation. If invalid data has been entered, a message describing where the problem is # and explaining what constitutes valid data is added to errorlist. formularegex = "[2-9]?(\(([A-Z][a-z]?(_[0-9])*)+\)(_[0-9])*|[A-Z][a-z]?(_[0-9])*)+((\^[0-9])*\^(\+|-))?" molesorvolumeregex = "[0-9]?[0-9]\.[0-9][0-9]?" # VALIDATES REACTANT AND PRODUCT DATA (if used) for x in range(Reaction.REACTING_SPECIES_LIMIT): if self._checkbuttons[x].isChecked(): formula = self._reactantinfoboxes[x * 2].text() moles = self._reactantinfoboxes[x * 2 + 1].text() if len(formula) not in range(1, 26): errorlist.append( "The formula of reactant " + str(x + 1) + " must be 1-25 characters long inclusive.") else: try: if formula != re.match(formularegex, formula).group(): errorlist.append( "The formula you have entered for reactant " + str(x + 1) + " is invalid.") except: errorlist.append( "The formula you have entered for reactant " + str(x + 1) + " is invalid.") try: if float(moles) < 0.01 or float(moles) > 99.99: errorlist.append( "The number of moles of reactant " + str(x + 1) + " must be between 0.01 and 99.99 inclusive.") else: try: if moles != re.match(molesorvolumeregex, moles).group(): errorlist.append( "The number of moles must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places." ) except: errorlist.append( "The number of moles must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places." ) except: errorlist.append("Number of moles of reactant " + str(x + 1) + " must be a decimal number.") if self._checkbuttons[x + Reaction.REACTING_SPECIES_LIMIT].isChecked(): formula = self._productinfoboxes[x * 2].text() moles = self._productinfoboxes[x * 2 + 1].text() if len(formula) not in range(1, 26): errorlist.append( "The formula of product " + str(x + 1) + " must be 1-25 characters long inclusive.") else: try: if formula != re.match(formularegex, formula).group(): errorlist.append( "The formula you have entered for product " + str(x + 1) + " is invalid.") except: errorlist.append( "The formula you have entered for product " + str(x + 1) + " is invalid.") try: if float(moles) < 0.01 or float(moles) > 99.99: errorlist.append( "The number of moles of product " + str(x + 1) + " must be between 0.01 and 99.99 inclusive.") else: try: if moles != re.match(molesorvolumeregex, moles).group(): errorlist.append( "The number of moles must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places." ) except: errorlist.append( "The number of moles must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places." ) except: errorlist.append("Number of moles of product " + str(x + 1) + " must be a decimal number.") # VALIDATES CATALYST DATA (if used) if self._checkbuttons[2 * Reaction.REACTING_SPECIES_LIMIT].isChecked(): formula = self._catalystinfoboxes[0].text() moles = self._catalystinfoboxes[1].text() if len(formula) not in range(1, 26): errorlist.append( "The formula of the catalyst must be 1-25 characters long inclusive." ) else: try: if formula != re.match(formularegex, formula).group(): errorlist.append( "The formula you have entered for the catalyst is invalid." ) except: errorlist.append( "The formula you have entered for the catalyst is invalid." ) try: if float(moles) < 0.01 or float(moles) > 99.99: errorlist.append( "The number of moles of the catalyst must be between 0.01 and 99.99 inclusive." ) else: try: if moles != re.match(molesorvolumeregex, moles).group(): errorlist.append( "The number of moles must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places." ) except: errorlist.append( "The number of moles must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places." ) except: errorlist.append( "Number of moles of catalyst must be a decimal number.") # VALIDATES TEMPERATURE DATA try: if int(self._tempbox.text()) not in range(1, 1000): errorlist.append( "Temperature must be between 1 and 999 inclusive.") except: errorlist.append("Temperature must be a whole number.") # VALIDATES VOLUME DATA try: volume = self._volbox.text() if float(volume) < 0.01 or float(volume) > 99.99: errorlist.append( "Volume must be between 0.01 and 99.99 inclusive.") else: try: if volume != re.match(molesorvolumeregex, volume).group(): errorlist.append( "Volume must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places." ) except: errorlist.append( "Volume must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places." ) except: errorlist.append("Volume must be a decimal number.") # If all data is valid, it applies this data to the reaction. if len(errorlist) == 0: for x in range(Reaction.REACTING_SPECIES_LIMIT): self._reaction.GetReactants()[x].SetFormula( self._reactantinfoboxes[x * 2].text()) self._reaction.GetReactants()[x].SetInitialMoles( float(str(self._reactantinfoboxes[x * 2 + 1].text()))) self._reaction.GetReactants()[x].SetUsed( self._checkbuttons[x].isChecked()) self._reaction.GetProducts()[x].SetFormula( self._productinfoboxes[x * 2].text()) self._reaction.GetProducts()[x].SetInitialMoles( float(str(self._productinfoboxes[x * 2 + 1].text()))) self._reaction.GetProducts()[x].SetUsed(self._checkbuttons[ x + Reaction.REACTING_SPECIES_LIMIT].isChecked()) self._reaction.GetCatalyst().SetFormula( self._catalystinfoboxes[0].text()) self._reaction.GetCatalyst().SetInitialMoles( float(str(self._catalystinfoboxes[1].text()))) self._reaction.GetCatalyst().SetUsed(self._checkbuttons[ 2 * Reaction.REACTING_SPECIES_LIMIT].isChecked()) if self._good.isChecked(): self._reaction.GetCatalyst().SetEfficacy(5) elif self._poor.isChecked(): self._reaction.GetCatalyst().SetEfficacy(2) elif self._inhibitor.isChecked(): self._reaction.GetCatalyst().SetEfficacy(0.75) if self._endo.isChecked(): self._reaction.SetEndothermic(True) elif self._exo.isChecked(): self._reaction.SetEndothermic(False) self._reaction.SetTemperature(int(self._tempbox.text())) self._reaction.SetVolume(float(self._volbox.text())) self._CanReturnReaction = True self._showformulae = not self._try.isChecked() self.close() else: # Sets up the error list to be displayed (if not empty) and displays self._errorbox = QMessageBox() self._errorbox.setWindowTitle("Invalid Data") texttoadd = """""" for x in errorlist: texttoadd += x + "\n" self._errorbox.setText( "Some of the data you entered is invalid:\n" + texttoadd) self._errorbox.setStandardButtons(QMessageBox.Ok) self._errorbox.setDefaultButton(QMessageBox.Ok) self._CanReturnReaction = False self._showformulae = True self._errorbox.exec_() # To avoid errors, make sure to check in case of a NoneType object being returned # None is returned when the window is unable to return the reaction; for example, # when some data is invalid def GetReaction(self): if self._CanReturnReaction: return self._reaction else: return None #GETTERS AND SETTERS def GetCanShowFormulae(self): return self._showformulae
class FeatureDlg(QDialog): def __init__(self, parent=None): QDialog.__init__(self, parent) # init # ------------------------------------------------ self.setWindowTitle("Spatial Features") # widgets and layouts # ------------------------------------------------ self.layout = QHBoxLayout() self.setLayout(self.layout) self.tableAndViewGroupBox = QGroupBox(" Scales and Groups") self.tableAndViewGroupBox.setFlat(True) self.featureTableWidget = featureTableWidget.FeatureTableWidget() self.tableAndViewLayout = QVBoxLayout() self.tableAndViewLayout.setSizeConstraint(QLayout.SetNoConstraint) self.tableAndViewLayout.addWidget(self.featureTableWidget) self.viewAndButtonLayout = QVBoxLayout() self.preView = preView.PreView() self.viewAndButtonLayout.addWidget(self.preView) self.viewAndButtonLayout.addStretch() self.buttonsLayout = QHBoxLayout() self.memReqLabel = QLabel() self.buttonsLayout.addWidget(self.memReqLabel) self.buttonsLayout.addStretch() # Add Cancel self.cancel = QToolButton() self.cancel.setText("Cancel") self.cancel.clicked.connect(self.on_cancelClicked) self.buttonsLayout.addWidget(self.cancel) # Add OK self.ok = QToolButton() self.ok.setText("OK") self.ok.clicked.connect(self.on_okClicked) self.buttonsLayout.addWidget(self.ok) self.buttonsLayout.addSpacerItem(QSpacerItem(10, 0)) self.viewAndButtonLayout.addSpacerItem(QSpacerItem(0, 10)) self.tableAndViewGroupBox.setLayout(self.tableAndViewLayout) self.tableAndViewLayout.addLayout(self.buttonsLayout) self.layout.addWidget(self.tableAndViewGroupBox) self.layout.setContentsMargins(0, 0, 0, 0) self.tableAndViewGroupBox.setContentsMargins(4, 10, 4, 4) self.tableAndViewLayout.setContentsMargins(0, 10, 0, 0) self.featureTableWidget.brushSizeChanged.connect( self.preView.setFilledBrsuh) self.setMemReq() # methods # ------------------------------------------------ @property def selectedFeatureBoolMatrix(self): """Return the bool matrix of features that the user selected.""" return self.featureTableWidget.createSelectedFeaturesBoolMatrix() @selectedFeatureBoolMatrix.setter def selectedFeatureBoolMatrix(self, newMatrix): """Populate the table of selected features with the provided matrix.""" self.featureTableWidget.setSelectedFeatureBoolMatrix(newMatrix) def createFeatureTable(self, features, sigmas, brushNames=None): self.featureTableWidget.createTableForFeatureDlg( features, sigmas, brushNames) def setImageToPreView(self, image): self.preView.setVisible(image is not None) if image is not None: self.preView.setPreviewImage(qimage2ndarray.array2qimage(image)) def setIconsToTableWidget(self, checked, partiallyChecked, unchecked): self.featureTableWidget.itemDelegate.setCheckBoxIcons( checked, partiallyChecked, unchecked) def setMemReq(self): # featureSelectionList = self.featureTableWidget.createFeatureList() #TODO #memReq = self.ilastik.project.dataMgr.Classification.featureMgr.computeMemoryRequirement(featureSelectionList) #self.memReqLabel.setText("%8.2f MB" % memReq) pass def on_okClicked(self): # featureSelectionList = self.featureTableWidget.createFeatureList() # selectedFeatureList = self.featureTableWidget.createSelectedFeatureList() # sigmaList = self.featureTableWidget.createSigmaList() # featureMgr.ilastikFeatureGroups.newGroupScaleValues = sigmaList # featureMgr.ilastikFeatureGroups.newSelection = selectedFeatureList # res = self.parent().project.dataMgr.Classification.featureMgr.setFeatureItems(featureSelectionList) # if res is True: # self.parent().labelWidget.setBorderMargin(int(self.parent().project.dataMgr.Classification.featureMgr.maxContext)) # self.ilastik.project.dataMgr.Classification.featureMgr.computeMemoryRequirement(featureSelectionList) # self.accept() # else: # QErrorMessage.qtHandler().showMessage("Not enough Memory, please select fewer features !") # self.on_cancelClicked() self.accept() def on_cancelClicked(self): self.reject()
class ConditionsDialog(QDialog): def __init__(self, reaction): super(ConditionsDialog, self).__init__() self.setGeometry(300, 200, 700, 350) self.setWindowTitle('Edit Conditions') if reaction is None: self._reaction = Reaction() else: self._reaction = reaction self._CanReturnReaction = False # Sets up GUI widgets # Reactants section self._reactantbox = QGroupBox("Reactants", self) self._reactantform = QFormLayout() self._reactantinfoboxes = [] self._productinfoboxes = [] self._catalystinfoboxes = [] self._checkbuttons = [] for x in range(Reaction.REACTING_SPECIES_LIMIT): self._reactantinfoboxes.append(QLineEdit()) self._reactantinfoboxes[x*2].setText(self._reaction.GetReactants()[x].GetFormula()) self._reactantinfoboxes.append(QLineEdit()) self._reactantinfoboxes[x*2+1].setText(str(self._reaction.GetReactants()[x].GetInitialMoles())) self._reactantform.addRow(QLabel(str(x + 1)+".\tFormula:"), self._reactantinfoboxes[x*2]) self._reactantform.addRow(QLabel("\tFinal Moles:"), self._reactantinfoboxes[x*2+1]) self._checkbuttons.append(QCheckBox("Use this reactant", self)) self._checkbuttons[-1].setChecked(self._reaction.GetReactants()[x].GetUsed()) self._reactantform.addRow(self._checkbuttons[-1]) self._reactantbox.setLayout(self._reactantform) # Products section self._productbox = QGroupBox("Products", self) self._productform = QFormLayout() for x in range(Reaction.REACTING_SPECIES_LIMIT): self._productinfoboxes.append(QLineEdit()) self._productinfoboxes[x*2].setText(self._reaction.GetProducts()[x].GetFormula()) self._productinfoboxes.append(QLineEdit()) self._productinfoboxes[x*2+1].setText(str(self._reaction.GetProducts()[x].GetInitialMoles())) self._productform.addRow(QLabel(str(x + 1)+".\tFormula:"), self._productinfoboxes[x*2]) self._productform.addRow(QLabel("\tFinal Moles:"), self._productinfoboxes[x*2+1]) self._checkbuttons.append(QCheckBox("Use this product", self)) self._checkbuttons[-1].setChecked(self._reaction.GetProducts()[x].GetUsed()) self._productform.addRow(self._checkbuttons[-1]) self._productbox.setLayout(self._productform) # Catalyst section self._catalystbox = QGroupBox("Catalyst", self) self._catalystform = QFormLayout() self._catalystinfoboxes.append(QLineEdit()) self._catalystinfoboxes.append(QLineEdit()) self._catalystinfoboxes[0].setText(self._reaction.GetCatalyst().GetFormula()) self._catalystinfoboxes[1].setText(str(self._reaction.GetCatalyst().GetInitialMoles())) self._catalystform.addRow(QLabel("Formula:"), self._catalystinfoboxes[0]) self._catalystform.addRow(QLabel("Moles:"), self._catalystinfoboxes[1]) self._good = QRadioButton("Good") self._poor = QRadioButton("Poor") self._inhibitor = QRadioButton("Inhibitor") self._checkbuttons.append(QCheckBox("Use this catalyst", self)) self._checkbuttons[-1].setChecked(self._reaction.GetCatalyst().GetUsed()) efficacy = self._reaction.GetCatalyst().GetEfficacy() if efficacy == 5: self._good.setChecked(True) elif efficacy == 2: self._poor.setChecked(True) else: self._inhibitor.setChecked(True) self._cataefficacygroup = QVBoxLayout() self._cataefficacygroup.addWidget(self._good) self._cataefficacygroup.addWidget(self._poor) self._cataefficacygroup.addWidget(self._inhibitor) self._catalystform.addRow(QLabel("Efficacy:"), self._cataefficacygroup) self._catalystform.addRow(self._checkbuttons[-1]) self._catalystbox.setLayout(self._catalystform) # Forward heat transfer section self._heatbox = QGroupBox("Forward heat transfer", self) self._heatform = QFormLayout() self._endo = QRadioButton("Endothermic") self._exo = QRadioButton("Exothermic") if self._reaction.GetEndothermic(): self._endo.setChecked(True) else: self._exo.setChecked(True) self._heatform.addRow(self._endo) self._heatform.addRow(self._exo) self._heatbox.setLayout(self._heatform) # Other conditions section: vessel volume; temperature self._otherbox = QGroupBox("Other conditions") self._otherform = QFormLayout() self._tempbox = QLineEdit() self._volbox = QLineEdit() self._tempbox.setText(str(self._reaction.GetTemperature())) self._volbox.setText(str(self._reaction.GetVolume())) self._otherform.addRow(QLabel("Vessel volume:"), self._volbox) self._otherform.addRow(QLabel("Temperature:"), self._tempbox) self._otherbox.setLayout(self._otherform) # Help text explaining how to enter super/subscript characters. self._scriptinfo1 = QLabel("Enter _ before a subscript character.") self._scriptinfo2 = QLabel("Enter ^ before a superscript one.") # OK and cancel buttons; checkbox so that students can try to balance the equation before it is revealed self._try = QCheckBox("Students attempt to balance equation") self._try.setChecked(False) self._okbtn = QPushButton("OK") self._okbtn.clicked.connect(self.ApplyChanges) self._cancelbtn = QPushButton("Cancel") self._rightbox = QGroupBox() self._rightbox.setFlat(False) self._rightform = QVBoxLayout() self._rightform.addWidget(self._catalystbox) self._rightform.addWidget(self._heatbox) self._rightform.addWidget(self._otherbox) self._rightbox.setLayout(self._rightform) # Layout of all those group boxes self._grid = QGridLayout() self._grid.addWidget(self._scriptinfo1, 0, 0) self._grid.addWidget(self._scriptinfo2, 1, 0) self._grid.addWidget(self._reactantbox, 2, 0) self._grid.addWidget(self._productbox, 2, 1) self._grid.addWidget(self._rightbox, 2, 2) self._grid.addWidget(self._try, 3, 0) self._grid.addWidget(self._okbtn, 3, 1) self._grid.addWidget(self._cancelbtn, 3, 2) self.setLayout(self._grid) if reaction is None: self._reaction = Reaction() else: self._reaction = reaction self._cancelbtn.clicked.connect(self.close) self.exec_() def ApplyChanges(self): errorlist = [] # Validation. If invalid data has been entered, a message describing where the problem is # and explaining what constitutes valid data is added to errorlist. formularegex = "[2-9]?(\(([A-Z][a-z]?(_[0-9])*)+\)(_[0-9])*|[A-Z][a-z]?(_[0-9])*)+((\^[0-9])*\^(\+|-))?" molesorvolumeregex = "[0-9]?[0-9]\.[0-9][0-9]?" # VALIDATES REACTANT AND PRODUCT DATA (if used) for x in range(Reaction.REACTING_SPECIES_LIMIT): if self._checkbuttons[x].isChecked(): formula = self._reactantinfoboxes[x*2].text() moles = self._reactantinfoboxes[x*2 + 1].text() if len(formula) not in range(1, 26): errorlist.append("The formula of reactant "+str(x + 1)+" must be 1-25 characters long inclusive.") else: try: if formula != re.match(formularegex, formula).group(): errorlist.append("The formula you have entered for reactant "+str(x + 1)+" is invalid.") except: errorlist.append("The formula you have entered for reactant "+str(x + 1)+" is invalid.") try: if float(moles) < 0.01 or float(moles) > 99.99: errorlist.append("The number of moles of reactant "+str(x + 1)+" must be between 0.01 and 99.99 inclusive.") else: try: if moles != re.match(molesorvolumeregex, moles).group(): errorlist.append("The number of moles must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places.") except: errorlist.append("The number of moles must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places.") except: errorlist.append("Number of moles of reactant "+str(x + 1)+" must be a decimal number.") if self._checkbuttons[x + Reaction.REACTING_SPECIES_LIMIT].isChecked(): formula = self._productinfoboxes[x*2].text() moles = self._productinfoboxes[x*2 + 1].text() if len(formula) not in range(1, 26): errorlist.append("The formula of product "+str(x + 1)+" must be 1-25 characters long inclusive.") else: try: if formula != re.match(formularegex, formula).group(): errorlist.append("The formula you have entered for product "+str(x + 1)+" is invalid.") except: errorlist.append("The formula you have entered for product "+str(x + 1)+" is invalid.") try: if float(moles) < 0.01 or float(moles) > 99.99: errorlist.append("The number of moles of product "+str(x + 1)+" must be between 0.01 and 99.99 inclusive.") else: try: if moles != re.match(molesorvolumeregex, moles).group(): errorlist.append("The number of moles must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places.") except: errorlist.append("The number of moles must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places.") except: errorlist.append("Number of moles of product "+str(x + 1)+" must be a decimal number.") # VALIDATES CATALYST DATA (if used) if self._checkbuttons[2 * Reaction.REACTING_SPECIES_LIMIT].isChecked(): formula = self._catalystinfoboxes[0].text() moles = self._catalystinfoboxes[1].text() if len(formula) not in range(1, 26): errorlist.append("The formula of the catalyst must be 1-25 characters long inclusive.") else: try: if formula != re.match(formularegex, formula).group(): errorlist.append("The formula you have entered for the catalyst is invalid.") except: errorlist.append("The formula you have entered for the catalyst is invalid.") try: if float(moles) < 0.01 or float(moles) > 99.99: errorlist.append("The number of moles of the catalyst must be between 0.01 and 99.99 inclusive.") else: try: if moles != re.match(molesorvolumeregex, moles).group(): errorlist.append("The number of moles must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places.") except: errorlist.append("The number of moles must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places.") except: errorlist.append("Number of moles of catalyst must be a decimal number.") # VALIDATES TEMPERATURE DATA try: if int(self._tempbox.text()) not in range(1, 1000): errorlist.append("Temperature must be between 1 and 999 inclusive.") except: errorlist.append("Temperature must be a whole number.") # VALIDATES VOLUME DATA try: volume = self._volbox.text() if float(volume) < 0.01 or float(volume) > 99.99: errorlist.append("Volume must be between 0.01 and 99.99 inclusive.") else: try: if volume != re.match(molesorvolumeregex, volume).group(): errorlist.append("Volume must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places.") except: errorlist.append("Volume must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places.") except: errorlist.append("Volume must be a decimal number.") # If all data is valid, it applies this data to the reaction. if len(errorlist) == 0: for x in range(Reaction.REACTING_SPECIES_LIMIT): self._reaction.GetReactants()[x].SetFormula(self._reactantinfoboxes[x*2].text()) self._reaction.GetReactants()[x].SetInitialMoles(float(str(self._reactantinfoboxes[x*2+1].text()))) self._reaction.GetReactants()[x].SetUsed(self._checkbuttons[x].isChecked()) self._reaction.GetProducts()[x].SetFormula(self._productinfoboxes[x*2].text()) self._reaction.GetProducts()[x].SetInitialMoles(float(str(self._productinfoboxes[x*2+1].text()))) self._reaction.GetProducts()[x].SetUsed(self._checkbuttons[x + Reaction.REACTING_SPECIES_LIMIT].isChecked()) self._reaction.GetCatalyst().SetFormula(self._catalystinfoboxes[0].text()) self._reaction.GetCatalyst().SetInitialMoles(float(str(self._catalystinfoboxes[1].text()))) self._reaction.GetCatalyst().SetUsed(self._checkbuttons[2 * Reaction.REACTING_SPECIES_LIMIT].isChecked()) if self._good.isChecked(): self._reaction.GetCatalyst().SetEfficacy(5) elif self._poor.isChecked(): self._reaction.GetCatalyst().SetEfficacy(2) elif self._inhibitor.isChecked(): self._reaction.GetCatalyst().SetEfficacy(0.75) if self._endo.isChecked(): self._reaction.SetEndothermic(True) elif self._exo.isChecked(): self._reaction.SetEndothermic(False) self._reaction.SetTemperature(int(self._tempbox.text())) self._reaction.SetVolume(float(self._volbox.text())) self._CanReturnReaction = True self._showformulae = not self._try.isChecked() self.close() else: # Sets up the error list to be displayed (if not empty) and displays self._errorbox = QMessageBox() self._errorbox.setWindowTitle("Invalid Data") texttoadd = """""" for x in errorlist: texttoadd += x + "\n" self._errorbox.setText("Some of the data you entered is invalid:\n"+texttoadd) self._errorbox.setStandardButtons(QMessageBox.Ok) self._errorbox.setDefaultButton(QMessageBox.Ok) self._CanReturnReaction = False self._showformulae = True self._errorbox.exec_() # To avoid errors, make sure to check in case of a NoneType object being returned # None is returned when the window is unable to return the reaction; for example, # when some data is invalid def GetReaction(self): if self._CanReturnReaction: return self._reaction else: return None #GETTERS AND SETTERS def GetCanShowFormulae(self): return self._showformulae
class DAyarlar(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.resize(600, 375) self.gridLayout = QGridLayout(self) self.gridLayout.setMargin(0) self.gridLayout.setSpacing(0) self.treeWidget = QTreeWidget(self) self.treeWidget.setMaximumSize(200, 1500) self.virux = QTreeWidgetItem(self.treeWidget) self.virux.setExpanded(True) icon = QIcon() icon.addPixmap(QPixmap("data/logo.png"), QIcon.Normal, QIcon.On) self.virux.setIcon(0, icon) item_1 = QTreeWidgetItem(self.virux) item_1 = QTreeWidgetItem(self.virux) self.dialog = QTreeWidgetItem(self.treeWidget) self.dialog.setExpanded(True) item_1 = QTreeWidgetItem(self.dialog) item_1 = QTreeWidgetItem(self.dialog) self.treeWidget.header().setVisible(False) self.gridLayout.addWidget(self.treeWidget, 0, 0, 1, 1) self.groupBox = QGroupBox(self) self.groupBox.setFlat(True) self.gridLayout_3 = QGridLayout(self.groupBox) self.gridLayout_3.setMargin(0) self.gridLayout_3.setSpacing(0) self.widget = QWidget(self.groupBox) self.gridLayout_4 = QGridLayout(self.widget) self.gridLayout_4.setMargin(0) self.gridLayout_4.setSpacing(0) self.gridLayout_4.setMargin(0) spacerItem = QSpacerItem(300, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.gridLayout_4.addItem(spacerItem, 0, 0, 1, 1) self.gridLayout_3.addWidget(self.widget, 0, 0, 1, 1) self.gridLayout.addWidget(self.groupBox, 0, 1, 1, 1) self.pButton = QPushButton(self) self.pButton.setText("asd") self.pButton.setDefault(True) self.buttonBox = QDialogButtonBox(self) self.buttonBox.addButton(self.pButton, QDialogButtonBox.AcceptRole) #self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.gridLayout.addWidget(self.buttonBox, 1, 0, 1, 2) self.setWindowTitle("Virux Ayarlar") self.treeWidget.headerItem().setText(0, "") self.treeWidget.topLevelItem(0).setText(0, u"Virux") self.treeWidget.topLevelItem(0).child(0).setText(0, u"Virux1") self.treeWidget.topLevelItem(0).child(1).setText(0, u"Virux2") self.treeWidget.topLevelItem(1).setText(0, u"Dialog") self.treeWidget.topLevelItem(1).child(0).setText(0, u"Dialog1") self.treeWidget.topLevelItem(1).child(1).setText(0, u"Dialog2") self.groupBox.setTitle(u"GroupBox") self.groupYaz() self.treeWidget.itemPressed.connect(self.lale) def lale(self, item): print item self.groupBox.setTitle(item.text(0)) def groupYaz(self): for option in DOptions: if hasattr(option, "getOption"): #self.gridLayout_3.addWidget(option.getOption(), 0, 0, 1, 1) item = QTreeWidgetItem(self.dialog) a = option.getOption() if hasattr(a, "name"): item.setText(0, a.name) else: item.setText(0, "F**k")
class ConditionsDialog(QDialog): def __init__(self, reaction): super(ConditionsDialog, self).__init__() self.setGeometry (300 , 300 , 700 , 350) self.setWindowTitle ('Edit Conditions') if reaction is None: self._reaction = Reaction() else: self._reaction = reaction self._CanReturnReaction = False # Sets up GUI widgets. Formula boxes will need to support super and subscript somehow # Will also need validation later # Reactants section self._reactantbox = QGroupBox("Reactants", self) self._reactantform = QFormLayout() self._reactantinfoboxes = [] self._productinfoboxes = [] self._catalystinfoboxes = [] for x in range(Reaction.REACTING_SPECIES_LIMIT): self._reactantinfoboxes.append(QLineEdit()) self._reactantinfoboxes[x*2].setText(self._reaction.GetReactants()[x].GetFormula()) self._reactantinfoboxes.append(QLineEdit()) self._reactantinfoboxes[x*2+1].setText(str(self._reaction.GetReactants()[x].GetInitialMoles())) self._reactantform.addRow(QLabel(str(x + 1)+".\tFormula:"), self._reactantinfoboxes[x*2]) self._reactantform.addRow(QLabel("\tInitial Moles:"), self._reactantinfoboxes[x*2+1]) self._reactantbox.setLayout(self._reactantform) # Products section self._productbox = QGroupBox("Products", self) self._productform = QFormLayout() for x in range(Reaction.REACTING_SPECIES_LIMIT): self._productinfoboxes.append(QLineEdit()) self._productinfoboxes[x*2].setText(self._reaction.GetProducts()[x].GetFormula()) self._productinfoboxes.append(QLineEdit()) self._productinfoboxes[x*2+1].setText(str(self._reaction.GetProducts()[x].GetInitialMoles())) self._productform.addRow(QLabel(str(x + 1)+".\tFormula:"), self._productinfoboxes[x*2]) self._productform.addRow(QLabel("\tInitial Moles:"), self._productinfoboxes[x*2+1]) self._productbox.setLayout(self._productform) # Catalyst section self._catalystbox = QGroupBox("Catalyst", self) self._catalystform = QFormLayout() self._catalystinfoboxes.append(QLineEdit()) self._catalystinfoboxes.append(QLineEdit()) self._catalystinfoboxes.append(QLineEdit()) self._catalystinfoboxes[0].setText(self._reaction.GetCatalyst().GetFormula()) self._catalystinfoboxes[1].setText(str(self._reaction.GetCatalyst().GetInitialMoles())) self._catalystinfoboxes[2].setText(str(self._reaction.GetCatalyst().GetEaChangePerMole())) self._catalystform.addRow(QLabel("Formula:"), self._catalystinfoboxes[0]) self._catalystform.addRow(QLabel("Moles:"), self._catalystinfoboxes[1]) self._catalystform.addRow(QLabel("Ea change (per mole):"), self._catalystinfoboxes[2]) self._catalystbox.setLayout(self._catalystform) # Forward heat transfer self._heatbox = QGroupBox("Forward heat transfer", self) self._heatform = QFormLayout() self._endo = QRadioButton("Endothermic") self._exo = QRadioButton("Exothermic") if self._reaction.GetEndothermic(): self._endo.setChecked(True) else: self._exo.setChecked(True) self._heatform.addRow(self._endo) self._heatform.addRow(self._exo) self._heatbox.setLayout(self._heatform) # Other conditions section. Includes Vessel volume; Temperature. self._otherbox = QGroupBox("Other conditions") self._otherform = QFormLayout() self._tempbox = QLineEdit() self._volbox = QLineEdit() self._tempbox.setText(str(self._reaction.GetTemperature())) self._volbox.setText(str(self._reaction.GetVolume())) self._otherform.addRow(QLabel("Vessel volume:"), self._volbox) self._otherform.addRow(QLabel("Temperature:"), self._tempbox) self._otherbox.setLayout(self._otherform) # OK and Cancel buttons self._okbtn = QPushButton("OK") self._okbtn.clicked.connect(self.ApplyChanges) self._cancelbtn = QPushButton("Cancel") self._rightbox = QGroupBox() self._rightbox.setFlat(False) self._rightform = QVBoxLayout() self._rightform.addWidget(self._catalystbox) self._rightform.addWidget(self._heatbox) self._rightform.addWidget(self._otherbox) self._rightbox.setLayout(self._rightform) # Layout of all those group boxes self._grid = QGridLayout() self._grid.addWidget(self._reactantbox, 0, 0) self._grid.addWidget(self._productbox, 0, 1) self._grid.addWidget(self._rightbox, 0, 2) self._grid.addWidget(self._okbtn, 1, 1) self._grid.addWidget(self._cancelbtn, 1, 2) self.setLayout(self._grid) if reaction is None: self._reaction = Reaction() else: self._reaction = reaction self._okbtn.clicked.connect(self.close) self._cancelbtn.clicked.connect(self.close) self.exec_() def ApplyChanges(self): errorlist = [] # Validation goes here later if len(errorlist) == 0: for x in range(Reaction.REACTING_SPECIES_LIMIT): self._reaction.GetReactants()[x].SetFormula(self._reactantinfoboxes[x*2].text()) self._reaction.GetReactants()[x].SetInitialMoles(float(str(self._reactantinfoboxes[x*2+1].text()))) self._reaction.GetProducts()[x].SetFormula(self._productinfoboxes[x*2].text()) self._reaction.GetProducts()[x].SetInitialMoles(float(str(self._productinfoboxes[x*2+1].text()))) self._reaction.GetCatalyst().SetFormula(self._catalystinfoboxes[0].text()) self._reaction.GetCatalyst().SetInitialMoles(float(str(self._catalystinfoboxes[1].text()))) self._reaction.GetCatalyst().SetEaChangePerMole(int(str(self._catalystinfoboxes[2].text()))) self._reaction.SetTemperature(int(self._tempbox.text())) self._reaction.SetVolume(float(self._volbox.text())) def GetReaction(self): if self._CanReturnReaction: return self._reaction def close(self): self._CanReturnReaction = True super(ConditionsDialog, self).close()
class Widget(QWidget): def __init__(self, dockwidget): super(Widget, self).__init__(dockwidget) self._document = None self._midiin = midiinput.MidiIn(self) self._dockwidget = weakref.ref(dockwidget) signals = list() self._labelmidichannel = QLabel() self._midichannel = QComboBox() signals.append(self._midichannel.currentIndexChanged) self._labelkeysignature = QLabel() self._keysignature = QComboBox() signals.append(self._keysignature.currentIndexChanged) self._labelaccidentals = QLabel() self._accidentalssharps = QRadioButton() signals.append(self._accidentalssharps.clicked) self._accidentalsflats = QRadioButton() signals.append(self._accidentalsflats.clicked) self._groupaccidentals = QGroupBox() self._groupaccidentals.setFlat(True) hbox = QHBoxLayout() self._groupaccidentals.setLayout(hbox) hbox.addWidget(self._accidentalssharps) hbox.addWidget(self._accidentalsflats) self._accidentalssharps.setChecked(True) self._chordmode = QCheckBox() signals.append(self._chordmode.clicked) self._relativemode = QCheckBox() signals.append(self._relativemode.clicked) self._labeldamper = QLabel() self._damper = QComboBox() self._labelsostenuto = QLabel() self._sostenuto = QComboBox() self._labelsoft = QLabel() self._soft = QComboBox() ac = self.parentWidget().actionCollection self._capture = QToolButton() self._capture.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self._capture.setDefaultAction(ac.capture_start) self._notemode = QLabel() layout = QVBoxLayout() self.setLayout(layout) grid = QGridLayout(spacing=0) layout.addLayout(grid) grid.addWidget(self._labelmidichannel, 0, 0) grid.addWidget(self._midichannel, 0, 1) grid.addWidget(self._labelkeysignature, 1, 0) grid.addWidget(self._keysignature, 1, 1) grid.addWidget(self._labelaccidentals, 2, 0) grid.addWidget(self._groupaccidentals, 2, 1) grid.addWidget(self._chordmode, 3, 0) grid.addWidget(self._relativemode, 3, 1) grid.addWidget(self._labeldamper, 4, 0) grid.addWidget(self._damper, 4, 1) grid.addWidget(self._labelsostenuto, 5, 0) grid.addWidget(self._sostenuto, 5, 1) grid.addWidget(self._labelsoft, 6, 0) grid.addWidget(self._soft, 6, 1) hbox = QHBoxLayout() layout.addLayout(hbox) hbox.addWidget(self._capture) hbox.addStretch() app.translateUI(self) self.loadsettings() for s in signals: s.connect(self.savesettings) def mainwindow(self): return self._dockwidget().mainwindow() def channel(self): return self._midichannel.currentIndex() def keysignature(self): return self._keysignature.currentIndex() def accidentals(self): if self._accidentalsflats.isChecked(): return 'flats' else: return 'sharps' def chordmode(self): return self._chordmode.isChecked() def relativemode(self): return self._relativemode.isChecked() def startcapturing(self): self._midiin.capture() ac = self.parentWidget().actionCollection while self._capture.actions(): # remove all old actions self._capture.removeAction(self._capture.actions()[0]) self._capture.setDefaultAction(ac.capture_stop) def stopcapturing(self): self._midiin.capturestop() ac = self.parentWidget().actionCollection while self._capture.actions(): # remove all old actions self._capture.removeAction(self._capture.actions()[0]) self._capture.setDefaultAction(ac.capture_start) def savesettings(self): s = QSettings() s.beginGroup("midiinputdock") s.setValue("midichannel", self._midichannel.currentIndex()) s.setValue("keysignature", self._keysignature.currentIndex()) if self._accidentalsflats.isChecked(): s.setValue("accidentals", 'flats') else: s.setValue("accidentals", 'sharps') s.setValue("chordmode", self._chordmode.isChecked()) s.setValue("relativemode", self._relativemode.isChecked()) def loadsettings(self): s = QSettings() s.beginGroup("midiinputdock") self._midichannel.setCurrentIndex(s.value("midichannel", 0, int)) self._keysignature.setCurrentIndex(s.value("keysignature", 7, int)) if s.value("accidentals", 'sharps', str) == 'flats': self._accidentalsflats.setChecked(True) else: self._accidentalssharps.setChecked(True) self._chordmode.setChecked(s.value("chordmode", False, bool)) self._relativemode.setChecked(s.value("relativemode", False, bool)) def translateUI(self): self._labelmidichannel.setText(_("MIDI channel")) self._midichannel.addItems([_("all")] + [str(i) for i in range(1, 17)]) self._labelkeysignature.setText(_("Key signature")) self._keysignature.addItems([ _("C flat major (7 flats)"), _("G flat major (6 flats)"), _("D flat major (5 flats)"), _("A flat major (4 flats)"), _("E flat major (3 flats)"), _("B flat major (2 flats)"), _("F major (1 flat)"), _("C major"), _("G major (1 sharp)"), _("D major (2 sharps)"), _("A major (3 sharps)"), _("E major (4 sharps)"), _("B major (5 sharps)"), _("F sharp major (6 sharps)"), _("C sharp major (7 sharps)") ]) self._keysignature.setCurrentIndex(7) self._labelaccidentals.setText(_("Accidentals")) self._accidentalssharps.setText(_("sharps")) self._accidentalsflats.setText(_("flats")) self._chordmode.setText(_("Chord mode")) self._chordmode.setToolTip( _("Enter simultaneously played notes as chords. " "See \"What's This\" for more information.")) self._chordmode.setWhatsThis( _("Notes which are played simultaneously are written " "as chords. As a consequence they are not written " "before the last key is lifted. Of course single " "can also be entered.")) self._relativemode.setText(_("Relative mode")) self._relativemode.setToolTip( _("Enter octaves of notes relative to the last note. " "See \"What's This\" for more information.")) self._relativemode.setWhatsThis( _("Enter octaves of notes relative to the last note. " "This refers to the last key pressed on the MIDI keyboard, not the last note in the document." "Hold Shift with a note to enter an octave check.")) self._labeldamper.setText(_("Damper pedal")) self._labelsostenuto.setText(_("Sostenuto pedal")) self._labelsoft.setText(_("Soft pedal"))