class View(QWidget): def __init__(self, status = None, Actions = None): super (View, self).__init__() def setup_simple_text_output_view(self): self.setWindowTitle("Standalone View") layout = QVBoxLayout() #DEMO WIDGET START #You can use this as a standard output self.te = QTextEdit() self.te.setText("Text!") layout.addWidget(self.te) #DEMO WIDGET END self.setLayout(layout) #DEMO WIDGET START def append_text(self, text): self.te.append(text) def clear_text(self): self.te.setText("")
class UdpRx(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.setWindowTitle("UDP Receive") self.setGeometry(300,300,300,300) self.setWindowIcon(QIcon('g-square.png')) self.us=QUdpSocket(self) self.us.bind(5000) self.us.readyRead.connect(self.udpRead) self.trace=QTextEdit() self.trace.setReadOnly(True) self.trace.append("UDP Trace:") l=QVBoxLayout() l.addWidget(self.trace) self.setLayout(l) def udpRead(self): while self.us.hasPendingDatagrams(): datagram, host, port=self.us.readDatagram(self.us.pendingDatagramSize()) self.trace.append("%s:%s -> %s" % (host.toString(), port, datagram)) if datagram.strip()=="::kill::": self.close()
class EventMessageWidget(QWidget): """ Widget to display event messages .. versionadded:: 0.5 """ def __init__(self, parent): """ Default constructor """ super(EventMessageWidget, self).__init__(parent) self.__set_layout() self.__set_events_to_display() def __set_layout(self): """ Set layout of this component """ self.horizontal_layout = QHBoxLayout() self.text_edit = QTextEdit() self.text_edit.setReadOnly(True) self.horizontal_layout.addWidget(self.text_edit) self.setLayout(self.horizontal_layout) def __set_events_to_display(self): """ Configure events to display """ self.event_types_to_show = [ 'attack hit', 'attack miss', 'attack nothing', 'poison triggered', 'poison ended', 'poisoned', 'heal started', 'heal ended', 'heal triggered', 'death', 'pick up', 'drop', 'damage triggered', 'equip', 'unequip', 'error', 'mitosis', 'dig', 'new level' ] def set_point_of_view(self, character): """ Set point of view for events to display """ self.character = character def receive_event(self, event): """ Receive event to display """ if e_event_type(event) in self.event_types_to_show: if e_event_type(event) == 'new level': if e_character(event) is self.character: self.text_edit.append( "You have reached new level: {0} - {1}".format( level_name(e_level(event)), level_description(e_level(event)))) else: pass
class InfoDialog(QMainWindow): def __init__(self, parent=None, info_data=''): QMainWindow.__init__(self) self.info_data = info_data self.confirmed = False self.resize(700, 400) self.initUI() def initUI(self): cw = QWidget() self.setCentralWidget(cw) layout_main = QVBoxLayout() layout_main.setSpacing(5) self.setWindowTitle('New SSH logins to Localhost') ## Info self.info = QTextEdit() self.info.setReadOnly(True) self.info.setLineWrapMode(QTextEdit.NoWrap) self.info.append(self.info_data) layout_main.addWidget(self.info, 1) # confirm button self.btn_confirm = QPushButton('Confirm') self.btn_confirm.pressed.connect(self.confirm) layout_main.addWidget(self.btn_confirm) ## add stretch layout_main.addStretch() ## Setup layout cw.setLayout(layout_main) self.show() def confirm(self): self.confirmed = True self.close() def getConfirmed(self): return self.confirmed
class QTextLogger( logging.Handler ): def __init__( self, parent, level=logging.NOTSET ): logging.Handler.__init__( self, level ) self.textedit = QTextEdit( parent ) self.textedit.setReadOnly( True ) self.textedit.setAcceptRichText( True ) def emit( self, record ): color = QColor( "#000000" ) if record.levelno > 20: color = QColor( "#ffff00" ) if record.levelno > 30: color = QColor( "#ff0000" ) if record.levelno <= 10: color = QColor( "#808080" ) self.textedit.setTextColor( color ) tmp = "%s %s: %s" % (record.asctime, record.name, record.getMessage()) self.textedit.append( tmp ) self.textedit.verticalScrollBar().triggerAction( QAbstractSlider.SliderToMaximum )
class ErrorLogDialog(QDialog): def __init__(self, parent): super(ErrorLogDialog, self).__init__(parent, Qt.WindowStaysOnTopHint) self._empty = True self._initUI() self.setWindowTitle("Error") get_notification_center().connectLogMessage(self._checkLogMessage) for record in getCachedLogRecords(): self._checkLogMessage(record) def sizeHint(self): return QSize(400, 200) def _initUI(self): layout = QVBoxLayout(self) layout.setContentsMargins(0, 10, 0, 0) layout.setSpacing(0) labelLayout = QHBoxLayout() labelLayout.addWidget(QLabel(u"Sorry, something went wrong:", self)) labelLayout.setContentsMargins(10, 0, 0, 0) layout.addLayout(labelLayout) layout.addSpacing(5) self._errorLog = QTextEdit(self) self._errorLog.setReadOnly(True) self._errorLog.setWordWrapMode(QTextOption.NoWrap) self._errorLog.setTextColor(QColor(180, 0, 0)) self._errorLog.setObjectName(u"__ERROR_LOG_") self._errorLog.setFrameShape(QFrame.StyledPanel) if getPlatform() == PLATFORM_MAC: self._errorLog.setStyleSheet("QFrame#__ERROR_LOG_{border-width: 1px; border-top-style: solid; border-right-style: none; border-bottom-style: solid; border-left-style: none; border-color:palette(mid)}"); layout.addWidget(self._errorLog) bottomWidget = QWidget(self) bottomLayout = QHBoxLayout(bottomWidget) self._notAgain = QCheckBox(u"Please, no more error messages!", self) bottomLayout.addWidget(self._notAgain, 1, Qt.AlignTop) buttonBox = QDialogButtonBox(QDialogButtonBox.Close, Qt.Horizontal, self) buttonBox.rejected.connect(self.reject) bottomLayout.addWidget(buttonBox) layout.addWidget(bottomWidget) @loggingSlot() def reject(self): self._errorLog.clear() self._empty = True return QDialog.reject(self) @loggingSlot(object) def _checkLogMessage(self, record): try: if self._notAgain.checkState() == Qt.Checked: return if record.levelno >= logging.ERROR: recMsg = record.msg if not isinstance(recMsg, basestring): recMsg = unicode(recMsg) err = convert_string(recMsg) % record.args component = record.name if component.startswith("lunchinator."): component = component[12:] msg = u"%s - In component %s (%s:%d):\n%s" % (strftime("%H:%M:%S", localtime(record.created)), component, record.pathname, record.lineno, err) if record.exc_info: out = StringIO() traceback.print_tb(record.exc_info[2], file=out) msg += u"\nStack trace:\n" + out.getvalue() + formatException(record.exc_info) + u"\n" self._errorLog.append(msg) self._empty = False if not self.isVisible(): self.showNormal() self.raise_() self.activateWindow() except: from lunchinator.log import getCoreLogger getCoreLogger().info(formatException())
class Interpreter(QWidget): lastCommands = [] lastIndex = 0 def __init__(self, context): QWidget.__init__(self) self.context = context self.setupUI() self.setWindowTitle('Interpreter') self.setMinimumSize(400, 250) def setupUI(self): layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self.out = QTextEdit() self.out.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.out.setTextInteractionFlags(Qt.TextSelectableByMouse | Qt.TextSelectableByKeyboard) self.highlighter = PythonSyntaxHighlighter( self.out, prefix = ">>>" ) self.input = QLineEdit() self.input.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum ) layout.addWidget(self.out, 1) layout.addWidget(self.input, 0) self.setLayout(layout) QWidget.connect(self.input, SIGNAL('returnPressed()'), self.run) def run(self): scode = str(self.input.text()).strip() self.out.append(">>> " + scode + "\n") self.input.setText('') name = threading.current_thread().name try: sys.stdout.flush(name) if len(self.lastCommands) == 100: del self.lastCommands[0] self.lastCommands.append(scode) self.lastIndex = 0 try: out = eval(scode, self.context) if out: print out except: code = compile(scode, '', 'exec') exec code in self.context except: traceback.print_exc() finally: self.write( sys.stdout.getOutput(name) ) def keyPressEvent(self, event): # Prev in command history if event.key() == Qt.Key_Up: try: self.lastIndex -= 1 self.input.setText(self.lastCommands[self.lastIndex]) except: self.lastIndex += 1 # Next in command history elif event.key() == Qt.Key_Down: try: self.lastIndex += 1 if self.lastIndex >= 0: self.lastIndex = 0 self.input.setText('') else: self.input.setText(self.lastCommands[self.lastIndex]) except: self.lastIndex -= 1 # Clear screen elif event.key() == Qt.Key_L: if event.modifiers() == Qt.ControlModifier: lines = self.out.height() / self.out.fontMetrics().height() #for i in xrange(lines): # self.out.append('') self.write('\n' * lines) self.out.moveCursor( QTextCursor.End ) #def getOutStream(self): # return self.TextOutput(self.out) def write(self, data): self.out.moveCursor( QTextCursor.End ) try: self.out.insertPlainText( unicode(data) ) except: self.out.insertPlainText( data ) self.out.moveCursor( QTextCursor.End )
class EventMessageWidget(QWidget): """ Widget to display event messages .. versionadded:: 0.5 """ def __init__(self, parent): """ Default constructor """ super(EventMessageWidget, self).__init__(parent) self.__set_layout() self.__set_events_to_display() def __set_layout(self): """ Set layout of this component """ self.horizontal_layout = QHBoxLayout() self.text_edit = QTextEdit() self.text_edit.setReadOnly(True) self.horizontal_layout.addWidget(self.text_edit) self.setLayout(self.horizontal_layout) def __set_events_to_display(self): """ Configure events to display """ self.event_types_to_show = ['attack hit', 'attack miss', 'attack nothing', 'poison triggered', 'poison ended', 'poisoned', 'heal started', 'heal ended', 'heal triggered', 'death', 'pick up', 'drop', 'damage triggered', 'equip', 'unequip', 'error', 'mitosis', 'dig', 'new level'] def set_point_of_view(self, character): """ Set point of view for events to display """ self.character = character def receive_event(self, event): """ Receive event to display """ if e_event_type(event) in self.event_types_to_show: if e_event_type(event) == 'new level': if e_character(event) is self.character: self.text_edit.append("You have reached new level: {0} - {1}".format( level_name(e_level(event)), level_description(e_level(event)))) else: pass
class Application(QWidget): leftSide = 1 rightSide = 0 btncontrol = None def __init__(self, parent=None): QWidget.__init__(self, parent) #self.setupUi(self) self.setWindowTitle(u'大图检测') #self.setFixedSize(1280,720) screen = QDesktopWidget().screenGeometry() #self.resize(screen.width(), screen.height()) self.setFixedSize(screen.width() - 100, screen.height() - 100) self.center() ##########################背景层,使用绝对坐标######################## palette = QPalette() self.setBackgroundandSize(self, './background.png', self.backgroundRole(), screen.height(), screen.width()) ##########################标题部分,用的一张图片###################### title = QLabel() self.setBackgroundandSize(title, './titlebg.png', QPalette.Window, 100, 706) hboxTilte = QHBoxLayout() hboxTilte.addWidget(title) ##############################下方左侧############################# #########并列部分 btnSelFile = QPushButton(u"选择文件") self.setBackgroundandSize(btnSelFile, './yellowbar.png', QPalette.Button, 23, 76) btnSelFile.setFlat(True) #边缘消失 editSelFile = QLineEdit(u"file:///") self.setBackgroundandSize(editSelFile, './greybar.png', QPalette.Base, 23, 115) hboxSelFile = QHBoxLayout() hboxSelFile.addWidget(btnSelFile) hboxSelFile.addWidget(editSelFile) self.connect( btnSelFile, SIGNAL("clicked()"), lambda: self.button_openfile_click( Application.btncontrol, editSelFile, previewImg)) hboxPicSize = QHBoxLayout() self.addRow(hboxPicSize, u"大图尺寸", u"宽:xxx 高:xxx", Application.leftSide) hboxOnlineNodes = QHBoxLayout() self.addRow(hboxOnlineNodes, u"联机集群节点数", u"xxx", Application.leftSide, smaller=True) hboxUsedNodes = QHBoxLayout() self.addRow(hboxUsedNodes, u"使用集群节点数", u"xxx", Application.leftSide, smaller=True) ########原图预览 previewTxt = QLabel(u"原图预览") previewTxt.setFixedHeight(25) previewTxt.setFont(QFont("Times New Roman", 12)) palette.setColor(QPalette.WindowText, Qt.yellow) previewTxt.setPalette(palette) previewTxt.setAlignment(Qt.AlignCenter) previewImg = QLabel() previewImg.setFixedHeight(0.3 * screen.height()) previewImg.setFixedWidth(0.2 * screen.width()) previewImg.setAutoFillBackground(True) previewImg.setAlignment(Qt.AlignCenter) image = QPixmap("./rawpic.png").scaled(previewImg.width(), previewImg.height()) previewImg.setPixmap(image) #self.setBackgroundandSize(previewImg,'./rawpic.png',QPalette.Window,128,196) ########终端显示 statusTxt = QLabel(u"集群终端状态") statusTxt.setFixedHeight(25) statusTxt.setFont(QFont("Times New Roman", 12)) palette.setColor(QPalette.WindowText, Qt.yellow) statusTxt.setPalette(palette) statusTxt.setAlignment(Qt.AlignCenter) #statusImg = QLabel() #statusImg.setFixedHeight(0.3 * screen.height()) #statusImg.setFixedWidth(0.2 * screen.width()) #statusImg.setAutoFillBackground(True) #statusImg.setAlignment(Qt.AlignCenter) #palette.setColor(statusImg.backgroundRole(), Qt.black) #statusImg.setPalette(palette) #statusImg.setText("hello!") self.statusEdit = QTextEdit("python gui.py") statusEdit = self.statusEdit statusEdit.setFixedHeight(0.3 * screen.height()) statusEdit.setFixedWidth(0.2 * screen.width()) statusEdit.setAutoFillBackground(True) statusEdit.setAlignment(Qt.AlignLeft) palette.setColor(QPalette.Base, Qt.black) palette.setColor(QPalette.Text, Qt.yellow) statusEdit.setPalette(palette) #self.setBackgroundandSize(statusImg, './rawpic.png', QPalette.Window, 128, 196) ########以垂直的结构显示 vboxleft = QVBoxLayout() vboxleft.addLayout(hboxSelFile) vboxleft.addLayout(hboxPicSize) vboxleft.addLayout(hboxOnlineNodes) vboxleft.addLayout(hboxUsedNodes) vboxleft.addWidget(previewTxt) vboxleft.addWidget(previewImg) vboxleft.addWidget(statusTxt) #vboxleft.addWidget(statusImg) vboxleft.addWidget(statusEdit) ###########################下方中间部分########################## ########控制按钮 Application.btncontrol = QPushButton(u"将大图发送至集群") Application.btncontrol.setFont(QFont("Times New Roman", 12)) Application.btncontrol.setEnabled(False) Application.btncontrol.setFixedHeight(25) Application.btncontrol.setFixedWidth(200) self.connect(Application.btncontrol, SIGNAL("clicked()"), self.button_control_click) ########显示处理后的图片 mid = QLabel() mid.setFixedHeight(440) mid.setFixedWidth(550) # palette.setColor(QPalette.Window, Qt.red) # mid.setAutoFillBackground(True) # mid.setPalette(palette) ########中间部分垂直布局 vboxmid = QVBoxLayout() vboxmid.addWidget(Application.btncontrol) vboxmid.addWidget(mid) ##########################下方右侧部分############################ ########三个返回值 hboxTime = QHBoxLayout() self.addRow(hboxTime, u"运行时间", u"xxx", Application.rightSide) hboxPlanes = QHBoxLayout() self.addRow(hboxPlanes, u"飞机目标数", u"xxx", Application.rightSide) hboxShips = QHBoxLayout() self.addRow(hboxShips, u"舰船目标数", u"xxx", Application.rightSide) btnCoordFile = QPushButton(u"展示结果图") #self.setBackgroundandSize(btnCoordFile, './yellowbar2.png', QPalette.Button, 23, 115) btnCoordFile.setFlat(True) # 边缘消失 self.connect(btnCoordFile, SIGNAL("clicked()"), self.button_show_click) ###飞机船照片路径 ########显示处理后的图片 #coordFilePath = QLabel(u"file:///") #self.setBackgroundandSize(coordFilePath, './greybar.png', QPalette.Window, 23, 115) hboxCoordFile = QHBoxLayout() #hboxCoordFile.addWidget(coordFilePath) hboxCoordFile.addWidget(btnCoordFile) ########飞机 self.planeImg = QLabel() planeImg = self.planeImg #planeImg.setAlignment(Qt.AlignCenter) #self.setBackgroundandSize(planeImg,'./rawpic2a.png',QPalette.Window,128,196) planeImg.setFixedHeight(0.3 * screen.height()) planeImg.setFixedWidth(0.2 * screen.width()) planeImg.setAutoFillBackground(True) planeImg.setAlignment(Qt.AlignCenter) planeimage = QPixmap("./rawpic2a.png").scaled(planeImg.width(), planeImg.height()) planeImg.setPixmap(planeimage) ########船 self.shipImg = QLabel() shipImg = self.shipImg #shipImg.setAlignment(Qt.AlignCenter) #self.setBackgroundandSize(shipImg, './rawpic2b.png', QPalette.Window, 128, 196) shipImg.setFixedHeight(0.3 * screen.height()) shipImg.setFixedWidth(0.2 * screen.width()) shipImg.setAutoFillBackground(True) shipImg.setAlignment(Qt.AlignCenter) self.shipimage = QPixmap("./rawpic2b.png").scaled( shipImg.width(), shipImg.height()) shipImg.setPixmap(self.shipimage) ########下方右侧布局 vboxright = QVBoxLayout() vboxright.addLayout(hboxTime) vboxright.addLayout(hboxPlanes) vboxright.addLayout(hboxShips) vboxright.addLayout(hboxCoordFile) vboxright.addWidget(planeImg) vboxright.addWidget(shipImg) ##########################整体布局############################ ########下方左中右 hboxbody = QHBoxLayout() hboxbody.addLayout(vboxleft) hboxbody.addStretch(1) hboxbody.addLayout(vboxmid) hboxbody.addStretch(1) hboxbody.addLayout(vboxright) ########上下两部分 vbox = QVBoxLayout() vbox.addLayout(hboxTilte) vbox.addStretch(0) vbox.addLayout(hboxbody) vbox.addStretch(1) self.setLayout(vbox) def center(self): screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2) def setBackgroundandSize(self, qwidget, imgpath, role, fixedHeight=None, fixedWidth=None): if isinstance(qwidget, QWidget) and isinstance(imgpath, str): palette = QPalette() palette.setBrush(role, QBrush(QPixmap(imgpath))) qwidget.setAutoFillBackground(True) qwidget.setPalette(palette) if fixedHeight is not None and fixedWidth is not None: qwidget.setFixedHeight(fixedHeight) qwidget.setFixedWidth(fixedWidth) def addRow(self, box, text, text_, pos, smaller=False): # 用smaller的原因是有时候文本过长,所以缩小字号 lab = QLabel(text) if smaller: lab.setFont(QFont("Times New Roman", 8)) lab.setAlignment(Qt.AlignCenter) if pos: self.setBackgroundandSize(lab, './yellowbar.png', QPalette.Window, 23, 76) else: self.setBackgroundandSize(lab, './yellowbar2.png', QPalette.Window, 23, 76) lab_ = QLabel(text_) lab_.setAlignment(Qt.AlignCenter) self.setBackgroundandSize(lab_, './greybar.png', QPalette.Window, 23, 115) if pos: #pos==1表示左侧那四行,pos==0表示右侧那四行 box.addWidget(lab) box.addWidget(lab_) else: box.addWidget(lab_) box.addWidget(lab) #self.labels.append(lab) #self.labels.append(lab_) def button_openfile_click(self, btncontrol, editSelFile, previewImg): absulute_path = QFileDialog.getOpenFileName(self, 'Open File', '.', 'png files(*.png)') if absulute_path: cur_path = QDir('.') relative_path = cur_path.relativeFilePath(absulute_path) editSelFile.setText(relative_path) image = QPixmap(relative_path).scaled(previewImg.width(), previewImg.height()) previewImg.setPixmap(image) os.system("python aaa.py") self.statusEdit.append("python aaa.py") #self.hboxPicSize.setText(u"???") #self.hboxOnlineNodes.setText(u"???") #self.hboxUsedNodes.setText(u"???") btncontrol.setEnabled(True) def button_control_click(self): #点几次?? Application.btncontrol.setEnabled(False) self.statusEdit.append("./???.sh") self.controlThread = Runthread(True) self.controlThread.finishSignal_sh.connect(self.terminal) self.controlThread.start() def terminal(self, str): self.statusEdit.append(str) #进程窗口展示进度条??? if str == "end": Application.btncontrol.setEnabled(True) def button_show_click(self): self.planeThread = Runthread(False, "plane") self.planeThread.finishSignal_sh.connect(self.showplanepicture) self.planeThread.start() self.shipThread = Runthread(False, "ship") self.shipThread.finishSignal_sh.connect(self.showshippicture) self.shipThread.start() #def button_show_click(self): # kinds =["plane","ship"] # for kind in kinds: # self.kindThread = Runthread(False,kind) # if kind =="plane": # self.kindThread.finishSignal_show.connect(self.showplanepicture) # else: # self.kindThread.finishSignal_show.connect(self.showshippicture) # self.kindThread.start() def showshippicture(self, str): print str if "png" in str: print "right" shipimage = QPixmap("./ship/" + str).scaled( self.shipImg.width(), self.shipImg.height()) self.shipImg.setPixmap(shipimage) else: self.statusEdit.append(str) # 进程窗口展示进度条??? def showplanepicture(self, str): print str if "png" in str: print "right" planeimage = QPixmap("./plane/" + str).scaled( self.planeImg.width(), self.planeImg.height()) self.planeImg.setPixmap(planeimage) else: self.statusEdit.append(str) # 进程窗口展示进度条???
class EditBox(QDialog): def __init__(self, data, title, description=None, parent=None): QDialog.__init__(self, parent) self.setWindowTitle(title) self.setWindowModality(Qt.ApplicationModal) QVBoxLayout(self) self.list = ListEdit(parent=parent, isChild=True) self.list.displayUpDown = False self.list.editInPopup = False self.list.headers = parent.getHeaders() self.list.setColDelegate(parent.getColDelegate) self.list.reset([data]) self.info = QTextEdit() self.error = QTextEdit() self.grid = None self.build(description) def build(self, description): self.layout().addWidget(self.list) cancel = QPushButton(QIcon(":/icons/wrong.png"), tr("Cancel"), self) save = QPushButton(QIcon(":/icons/apply.png"), tr("OK"), self) save.setDefault(True) self.connect(cancel, SIGNAL("clicked()"), self.doClose) self.connect(save, SIGNAL("clicked()"), self.doSave) self.grid = QWidget(self) self.setMinimumWidth(700) QGridLayout(self.grid) self.grid.layout().addWidget(save, 0, 0, Qt.AlignHCenter) self.grid.layout().addWidget(cancel, 0, 1, Qt.AlignHCenter) self.layout().addWidget(self.grid) self.info.setReadOnly(True) if description: self.info.append(description) else: self.info.setVisible(False) self.error.setReadOnly(True) self.error.setVisible(False) self.grid.layout().addWidget(self.info, 1, 0, 1, 0, Qt.AlignHCenter) self.grid.layout().addWidget(self.error, 2, 0, 1, 0, Qt.AlignHCenter) def doClose(self): self.reject() self.close() def doSave(self): self.error.clear() hasInvalidData = False for col in range(self.list.listEditView.model.columnCount()): index = self.list.listEditView.model.index(0, col) input_edit = self.list.listEditView.indexWidget(index) if not input_edit.isValid(): col_name = self.list.listEditView.model.headerData(col, Qt.Horizontal, Qt.DisplayRole) col_name = unicode(col_name.toString()) self.error.append(tr("Column '%s': must be '%s'") % (col_name, input_edit.getFieldInfo())) hasInvalidData = True if hasInvalidData: self.error.setVisible(True) else: self.accept() self.close() def getData(self): """ single selection only supported """ return self.list.rawData()[0]
class QPyShell(QWidget): """QPyShell - a Qt based python command shell based on code.InteractiveInterpreter. Because it catches stdout and stderr there can be only one active instance of this class. Make sure initInterpreter() and exitInterpreter() is called! """ activeInstance = None def __init__(self, parent=None): QWidget.__init__(self, parent) if parent: self.standalone = False else: self.standalone = True self.setWindowTitle(QCoreApplication.translate("QPyShell", "QPyShell - a simple python shell widget for Qt")) self.mainLayout = QVBoxLayout(self) self.outputBrowser = QTextEdit(self) self.outputBrowser.setMinimumSize(QSize(100,100)) self.outputBrowser.setReadOnly(True) self.mainLayout.addWidget(self.outputBrowser) self.clLayout = QHBoxLayout() self.mainLayout.addLayout(self.clLayout) self.promptLabel = QLabel() self.promptLabel.setText(">>>") self.clLayout.addWidget(self.promptLabel) self.lineInput = QLineEdit() self.lineInput.setToolTip(QCoreApplication.translate('QPyShell', 'The python commandline: enter code her')) self.clLayout.addWidget(self.lineInput) self.enterButton = QToolButton(self) self.enterButton.setText(QCoreApplication.translate("QPyShell", "Enter")) self.enterButton.setToolTip(QCoreApplication.translate('QPyShell', 'This button or [Enter] executes the command')) self.enterButton.setIcon(QIcon(QPixmap(enterXPM))) self.clLayout.addWidget(self.enterButton) self.clLayout.addSpacing(8) self.clearButton = QToolButton(self) self.clearButton.setText(QCoreApplication.translate("QPyShell", "Clear")) self.clearButton.setToolTip(QCoreApplication.translate('QPyShell', 'Clear the output window')) self.clearButton.setIcon(QIcon(QPixmap(clearXPM))) self.clLayout.addWidget(self.clearButton) self.saveButton = QToolButton(self) self.saveButton.setText(QCoreApplication.translate("QPyShell", "Save ...")) self.saveButton.setToolTip(QCoreApplication.translate('QPyShell', 'Save the contents of the output window')) self.saveButton.setIcon(QIcon(QPixmap(saveXPM))) self.clLayout.addWidget(self.saveButton) self.printButton = QToolButton(self) self.printButton.setText(QCoreApplication.translate("QPyShell", "Print")) self.printButton.setToolTip(QCoreApplication.translate('QPyShell', 'Print the contents of the output window')) self.printButton.setIcon(QIcon(QPixmap(printXPM))) self.clLayout.addWidget(self.printButton) self.history = [] self.historyFile = None self.history_i = -1 self.cmdBuffer = [] self.showCompletionLimit = 100 self.interpreter = None self.old_displayhook = None self.cursor = QTextCursor(self.outputBrowser.document()) self.outputBrowser.setTextCursor(self.cursor) self.outputBrowser.append(greeting) self.setTabOrder(self.lineInput, self.outputBrowser) self.setTabOrder(self.outputBrowser, self.enterButton) self.setTabOrder(self.enterButton, self.saveButton) self.setTabOrder(self.saveButton, self.clearButton) self.connect(self.enterButton, SIGNAL("pressed()"), self.run) self.connect(self.saveButton, SIGNAL("pressed()"), self.saveContents) self.connect(self.printButton, SIGNAL("pressed()"), self.printContents) self.connect(self.clearButton, SIGNAL("pressed()"), self.outputBrowser.clear) def initInterpreter(self, loc=None, greet=greeting, historyFile=None): if QPyShell.activeInstance: raise Exception(QCoreApplication.translate("QPyShell", "QPyShell: There can be only one highlander... sorry, I mean one active QPyShell widget!")) QPyShell.activeInstance = self self.loadHistoryFile(historyFile) self.interpreter = InteractiveInterpreter(loc) self.completer = Completer(loc) self.old_stdout = sys.stdout self.old_stderr = sys.stderr sys.stdout = DummyFileW(self.write) sys.stderr = sys.stdout # there's a strange problem with gettext and interactive interpreters # gettext's "_"" will be overwritten by the standard sys.displayhook... self.old_displayhook = sys.displayhook sys.displayhook = mydisplayhook def loadHistoryFile(self, historyFile): self.historyFile = historyFile if historyFile and os.path.exists(historyFile): lines = open(historyFile, 'r').read().split(os.linesep) self.history = [l for l in lines if not l.startswith('#')] def saveHistoryFile(self): if self.historyFile: h = self.history if len(h) > 100: h = h[:100] h.insert(0, unicode(QCoreApplication.translate('QPyShell', '# this is the command history of the QPyShell'))) open(self.historyFile, 'w').write(os.linesep.join(h)) def exitInterpreter(self, loc=None): sys.stdout = self.old_stdout sys.stderr = self.old_stderr self.saveHistoryFile() del self.interpreter self.interpreter = None sys.displayhook = self.old_displayhook QPyShell.ativeInstance = None def run(self): if not self.interpreter: raise Exception(QCoreApplication.translate("QPyShell", "No interpreter found! You need to call QPyShell.initInterpreter() first!")) line = unicode(self.lineInput.text()) self.lineInput.clear() if line: if (not self.history) or line != self.history[0]: # no consecutive identical entries self.history.insert(0, line) self.history_i = -1 self.cursor.movePosition(QTextCursor.End) if not self.cmdBuffer: self.cursor.insertHtml('<br><b>|>>> %s</b><br>' % formatPyLine(line)) else: self.cursor.insertHtml('<br><b>|. . . %s</b><br>' % formatPyLine(line)) self.cursor.movePosition(QTextCursor.End) self.outputBrowser.ensureCursorVisible() self.cmdBuffer.append(line) more = self.interpreter.runsource('\n'.join(self.cmdBuffer)) if more: self.promptLabel.setText('...') else: self.cmdBuffer = [] self.promptLabel.setText('>>>') def appendHtml(self, txt): self.cursor.movePosition(QTextCursor.End) self.cursor.insertHtml(txt) self.cursor.movePosition(QTextCursor.End) self.outputBrowser.ensureCursorVisible() def appendText(self, txt): self.cursor.movePosition(QTextCursor.End) self.outputBrowser.insertPlainText(txt) self.cursor.movePosition(QTextCursor.End) self.outputBrowser.ensureCursorVisible() write = appendText def keyPressEvent(self, event): key = event.key() mod = event.modifiers() if key == Qt.Key_Up and self.history: self.history_i = min(self.history_i+1, len(self.history)-1) self.lineInput.setText(self.history[self.history_i]) elif key == Qt.Key_Down and self.history: self.history_i = max(self.history_i-1, -1) if self.history_i >= 0: self.lineInput.setText(self.history[self.history_i]) else: self.lineInput.setText('') elif key == Qt.Key_Enter or key == Qt.Key_Return: if mod & Qt.ShiftModifier: self.complete() else: self.run() elif key == Qt.Key_Escape: txt, r = QInputDialog.getItem(self, QCoreApplication.translate("QPyShell", "Command line history"), QCoreApplication.translate("QPyShell", "Please select a history item:"), self.history, 0, False) if r and txt: self.lineInput.setText(txt) elif self.standalone and key == Qt.Key_Print: self.printContents() elif self.standalone and key == Qt.Key_Q and (mod & Qt.ControlModifier): self.close() else: QWidget.keyPressEvent(self, event) def closeEvent(self, event): if self.standalone: self.exitInterpreter() QWidget.closeEvent(self, event) def printContents(self, printer=None): if not printer: printer = QPrinter() dialog = QPrintDialog(printer, self) dialog.setWindowTitle(QCoreApplication.translate("QPyShell", "Print Document")) if dialog.exec_() != QDialog.Accepted: return self.outputBrowser.document().print_(printer) def saveContents(self, fileName=None): if not fileName: fileTypes = {'Text':('txt',), 'HTML':('htm', 'html')} filters = ';;'.join(['%s (%s)' % (k, ' '.join(['*.'+e for e in v])) for k, v in fileTypes.items()]) dlg = QFileDialog(self, QCoreApplication.translate('QPyShell', 'Select name of file to save'), os.getcwd(), filters) dlg.setFileMode(QFileDialog.AnyFile) dlg.setAcceptMode(QFileDialog.AcceptSave) if dlg.exec_() != QDialog.Accepted: return tmp = unicode(dlg.selectedFilter()) fileType = tmp[:tmp.find('(')-1] dlg.setDefaultSuffix(fileTypes[fileType][0]) files = dlg.selectedFiles() if not files: return fileName = unicode(files[0]) if fileType == 'Text': txt = self.outputBrowser.toPlainText() elif fileType == 'HTML': txt = self.outputBrowser.toHtml() else: raise IOError('Unknown FileType: %s' % fileType) try: open(fileName, 'w').write(txt) except IOError: QMessageBox.critical(self, QCoreApplication.translate('QPyShell', 'Could not save file!'), QCoreApplication.translate('QPyShell', 'Writing failed! Make sure you have write permissions!')) def complete(self): """ a very simple, quick and dirty completion of identifiers in the namespace """ # FIXME: fertig machen! txt = unicode(self.lineInput.text()) cur = self.lineInput.cursorPosition() s = cur while s>0 and txt[s-1] in identChars: s -= 1 try: completions = self.completer.matches(txt[s:cur]) except: return if not completions: return n_comp = len(completions) if n_comp == 1: comp = completions.pop() self.lineInput.insert(comp[cur-s:]) elif n_comp < self.showCompletionLimit: tmp = list(completions) tmp.sort() self.appendHtml('<font color="#0000ff">[%s]</font>' % ', '.join(tmp)) # get common prefix ... stolen from the python cookbook pref = tmp[0][:([min([x[0]==elem for elem in x]) for x in zip(*tmp)]+[0]).index(0)] if len(pref) > (cur-s): self.lineInput.insert(pref[cur-s:]) else: self.appendHtml(unicode(QCoreApplication.translate("QPyShell", '<font color="#0000ff">[Too many completions: %d]</font>')) % n_comp)
class lTabOptions(QGroupBox): state_change = pyqtSignal() def __init__(self, parent, run_data_dir): self.block_state_change = False self.run_data_dir = run_data_dir QGroupBox.__init__(self, "Global Tab Options", parent) self.grid_layout = QGridLayout(self) title = QLabel('Lovell') font = QFont() title.setAlignment(Qt.AlignHCenter) font.setPointSize(20) font.setBold(True) title.setFont(font) self.setMinimumWidth(275) self.grid_layout.addWidget(title, self.rowCount(), 0, 1, 2) setPadding(self.grid_layout) self.add_group_selector() self.add_ID_selector() self.add_next_prev_buttons() self.add_notify_box() self.add_reference_buttons() self.add_run_num_buttons() def add_notify_box(self): notifyFont = QFont() notifyFont.setPointSize(8) self.grid_layout.addWidget(QLabel("Notifcations:"), self.rowCount(), 0, 1, 2) self.notifyBox = QTextEdit("Hello world! :)", self) self.notifyBox.setFont(notifyFont) self.grid_layout.addWidget(self.notifyBox, self.rowCount(), 0, 1, 2) def notify(self, text, textHighlight=None): # highlightRange is range in passed text. length = len(self.notifyBox.toPlainText()) self.notifyBox.append(text) self.notifyBox.verticalScrollBar().setValue( self.notifyBox.verticalScrollBar().maximum()) if textHighlight != None: begin = length + text.find(textHighlight) + 1 end = begin + len(textHighlight) fmt = QTextCharFormat() col = QColor(Qt.red) col.setAlpha(130) fmt.setBackground(col) cursor = QTextCursor(self.notifyBox.document()) cursor.setPosition(begin) cursor.setPosition(end, QTextCursor.KeepAnchor) cursor.setCharFormat(fmt) def add_group_selector(self): self.module_group_box = QComboBox(self) self.module_group_box.currentIndexChanged.connect(self.state_changed) lab = QLabel("Module Group:") lab.setAlignment(Qt.AlignRight) self.grid_layout.addWidget(lab, self.rowCount(), 0) self.grid_layout.addWidget(self.module_group_box, self.rowCount() - 1, 1) lab.hide() self.module_group_box.hide() self.module_group_box.addItem("R (0)") self.module_group_box.addItem("Phi (1)") def add_ID_selector(self): self.module_ID_box = QComboBox(self) self.module_ID_box.currentIndexChanged.connect(self.state_changed) lab = QLabel("Sensor ID:") lab.setAlignment(Qt.AlignRight) self.grid_layout.addWidget(lab, self.rowCount(), 0) self.grid_layout.addWidget(self.module_ID_box, self.rowCount() - 1, 1) for i in range(0, 42): self.module_ID_box.addItem(str(i)) for i in range(64, 106): self.module_ID_box.addItem(str(i)) def add_next_prev_buttons(self): self.next_button = QPushButton("Next") self.grid_layout.addWidget(self.next_button, self.rowCount(), 1) self.prev_button = QPushButton("Prev") self.grid_layout.addWidget(self.prev_button, self.rowCount() - 1, 0) self.next_button.clicked.connect(self.next_clicked) self.prev_button.clicked.connect(self.prev_clicked) self.next_four_button = QPushButton("Next Four") self.grid_layout.addWidget(self.next_four_button, self.rowCount(), 1) self.prev_four_button = QPushButton("Prev Four") self.grid_layout.addWidget(self.prev_four_button, self.rowCount() - 1, 0) self.next_four_button.clicked.connect(self.next_four_clicked) self.prev_four_button.clicked.connect(self.prev_four_clicked) def add_run_num_buttons(self): self.add_bar() self.run_num_box = QComboBox(self) self.run_num_box.currentIndexChanged.connect(self.state_changed) self.grid_layout.addWidget(QLabel("Run number:"), self.rowCount(), 0, 1, 2) self.grid_layout.addWidget(self.run_num_box, self.rowCount(), 0, 1, 2) # Reference self.run_numRef_box = QComboBox(self) self.run_numRef_box.currentIndexChanged.connect(self.state_changed) self.grid_layout.addWidget(QLabel("Reference number:"), self.rowCount(), 0, 1, 2) self.grid_layout.addWidget(self.run_numRef_box, self.rowCount(), 0, 1, 2) self.run_numRef_box.addItem('Auto') for run in lInterfaces.run_list(self.run_data_dir): self.run_num_box.addItem(str(run)) self.run_numRef_box.addItem(str(run)) def add_bar(self): bar = QLabel('_______________________________') bar.setAlignment(Qt.AlignHCenter) bar.setAlignment(Qt.AlignVCenter) self.grid_layout.addWidget(bar, self.rowCount(), 0, 1, 2) def add_reference_buttons(self): self.add_bar() self.showing_ref_box = QCheckBox("Display References") self.showing_ref_box.stateChanged.connect(self.reference_button_fading) self.showing_ref_box.setChecked(True) self.overlay_ref_box = QRadioButton("Overlay", self) self.overlay_ref_box.setChecked(True) self.overlay_refDiff_box = QRadioButton("Data - Ref", self) self.overlay_refRatio_box = QRadioButton("Data/Ref", self) self.grid_layout.addWidget(self.showing_ref_box, self.rowCount(), 0, 1, 2) self.grid_layout.addWidget(self.overlay_ref_box, self.rowCount(), 0, 1, 2) self.grid_layout.addWidget(self.overlay_refDiff_box, self.rowCount(), 0, 1, 2) self.grid_layout.addWidget(self.overlay_refRatio_box, self.rowCount(), 0, 1, 2) # Slots. self.showing_ref_box.clicked.connect(self.state_changed) self.overlay_ref_box.clicked.connect(self.state_changed) self.overlay_refDiff_box.clicked.connect(self.state_changed) self.overlay_refRatio_box.clicked.connect(self.state_changed) self.reference_button_fading() def rowCount(self): return self.grid_layout.rowCount() def state_changed(self): if self.block_state_change == False: self.state_change.emit() def state(self): g = self.module_group_box.currentIndex() moduleID = int(self.module_ID_box.currentText()) state = lTabOpsState(moduleID, self.showing_ref_box.isChecked(), self.overlay_ref_box.isChecked(), self.overlay_refDiff_box.isChecked(), self.overlay_refRatio_box.isChecked(), self.run_num_box.currentText(), self.run_numRef_box.currentText(), self.run_data_dir) return state def next_four_clicked(self): self.block_state_change = True for i in range(4): self.next_clicked() self.block_state_change = False self.state_changed() def prev_four_clicked(self): self.block_state_change = True for i in range(4): self.prev_clicked() self.block_state_change = False self.state_changed() def next_clicked(self): currentGroup = self.module_group_box.currentIndex() currentModule = self.module_ID_box.currentIndex() # Check if the last one. if currentModule != self.module_ID_box.count() - 1: self.module_ID_box.setCurrentIndex(currentModule + 1) else: if currentGroup != self.module_group_box.count() - 1: self.module_group_box.setCurrentIndex(currentGroup + 1) else: self.module_group_box.setCurrentIndex(0) self.module_ID_box.setCurrentIndex(0) def prev_clicked(self): currentGroup = self.module_group_box.currentIndex() currentModule = self.module_ID_box.currentIndex() # Check if the first one. if currentModule != 0: self.module_ID_box.setCurrentIndex(currentModule - 1) else: if currentGroup != 0: self.module_group_box.setCurrentIndex(currentGroup - 1) else: self.module_group_box.setCurrentIndex( self.module_group_box.count() - 1) self.module_ID_box.setCurrentIndex(self.module_ID_box.count() - 1) def reference_button_fading(self): if self.showing_ref_box.isChecked(): self.overlay_ref_box.setEnabled(True) self.overlay_refDiff_box.setEnabled(True) self.overlay_refRatio_box.setEnabled(True) else: self.overlay_ref_box.setEnabled(False) self.overlay_refDiff_box.setEnabled(False) self.overlay_refRatio_box.setEnabled(False)
class ProgressDialog(Ui_ProgressDialog, DialogBase): def __init__(self, publisher, plugin, parentWidget=None): DialogBase.__init__(self, parentWidget) self.setupUi(self) self.setObjectName("ProgressDialog") self.viewButton_.setEnabled(False) self._publisher = publisher self._plugin = plugin self._parent = parentWidget self._cancelled = False self._timeline = QTimeLine(1000*60, self) self._timeline.setFrameRange(0, 2*60) self._timeline.setLoopCount(0) self.progressBar_.setRange(0, 60) self.connect(self._timeline, QtCore.SIGNAL("frameChanged(int)"), self.updateProgressBar) self.outputGroupBox_ = QGroupBox("Script output", None) self.outputTextEdit_ = QTextEdit() self.outputTextEdit_.setTextInteractionFlags(Qt.TextSelectableByKeyboard | Qt.TextSelectableByMouse) self.outputTextEdit_.setReadOnly(True) self.outputTextEdit_.setTabChangesFocus(True) self.outputTextEdit_.setAcceptRichText(False) groupBoxLayout = QVBoxLayout() groupBoxLayout.setObjectName("groupBoxLayout") groupBoxLayout.setMargin(0) groupBoxLayout.addWidget(self.outputTextEdit_) self.outputGroupBox_.setLayout(groupBoxLayout) gridLayout = QGridLayout() gridLayout.setSizeConstraint(gridLayout.SetFixedSize) gridLayout.addWidget(self.progressLabel_, 0, 0, 1, 4) gridLayout.addWidget(self.progressBar_, 1, 0, 1, 4) gridLayout.addWidget(self.detailsCheckBox_, 2, 0) hSpacer = QSpacerItem(250, 10, QSizePolicy.Expanding) gridLayout.addItem(hSpacer, 2, 1) gridLayout.addWidget(self.viewButton_, 2, 2) gridLayout.addWidget(self.cancelButton_, 2, 3) gridLayout.addWidget(self.outputGroupBox_, 3, 0, 1, 4) self.setLayout(gridLayout) self.outputGroupBox_.setVisible(False) def updateProgressBar(self, frame): self.progressBar_.setValue(self.progressBar_.value() + 1) def on_detailsCheckBox__stateChanged(self, state): self.outputGroupBox_.setVisible(Qt.Checked == state) gridLayout = self.layout() if Qt.Checked == state: gridLayout.setSizeConstraint(gridLayout.SetMaximumSize) self.setSizeGripEnabled(True) else: gridLayout.setSizeConstraint(gridLayout.SetFixedSize) self.setSizeGripEnabled(False) def on_cancelButton__clicked(self, released=True): if not released: return if self._cancelled: self.reject() return self.cancelButton_.setEnabled(False) self.progressLabel_.setText("Cancelling...") self._publisher.cancel() self._cancelled = True QTimer.singleShot(5*1000, self, QtCore.SLOT("_kill()")) @QtCore.pyqtSignature("_kill()") def _cancel(self): self._parent.update() self._publisher.cancel(True) self.reject() def updatePublisherOutput(self, data): self.outputTextEdit_.append(data) def publishComplete(self, exitCode, exitStatus): self.progressBar_.setValue(self.progressBar_.maximum()) self._timeline.stop() if self._cancelled: self.reject() self._cancelled = True publishSuccess = (0 == exitCode and QProcess.NormalExit == exitStatus) output_exists = self.__findOutput() self.viewButton_.setEnabled(publishSuccess and \ output_exists) if not publishSuccess: self.progressLabel_.setText("Publishing failed, see script output" " for more details") else: self.progressLabel_.setText("Publishing completed") def __findOutput(self): output_exists = os.path.exists(unicode(self._outFile)) if not output_exists: output_exists = self.__findInSubdir() if not(output_exists) and ('Dita' in self._publisher.__str__()) : output_exists = self.__findInLog() if not(output_exists) and ('Docbook' in self._publisher.__str__()) : output_exists = self.__findInPI() return output_exists def __findInLog(self): log = self.outputTextEdit_.toPlainText() src_filename = os.path.basename(self._publisher.attrs()['srcUri']) dst_filename = src_filename.split('.')[0] + "." + self._publisher.attrs()['extension'] re_str = '\[xslt\] Processing.*?' + src_filename + ' to (?P<outputFilename>.*?' + dst_filename + ')' output_re = re.compile(re_str) output_filename = '' if None != output_re.search(log): output_filename = output_re.search(log).group("outputFilename") if not output_filename: return False real_dst_dir = os.path.dirname(unicode(output_filename)) dst_filename = os.path.join(real_dst_dir, os.path.basename(self._outFile)) os.rename(output_filename, dst_filename) output_exists = os.path.exists(dst_filename) if output_exists: self._outFile = dst_filename self._parent.setOutputFilePath(self._outFile) return True return False def __findInPI(self): src_uri = self._publisher.attrs()['srcUri'] grove = Grove.buildGroveFromFile(src_uri) xpath_value = XpathExpr("//self::processing-instruction('dbhtml')").eval(grove.document()) dbhtml_pi = xpath_value.getNodeSet().firstNode() str_ = unicode(dbhtml_pi.asGrovePi().data()) filename_re = re.compile('filename="(?P<filename>.*?\n?.*?)"') dir_re = re.compile('dir="(?P<dir>.*?\n?.*?)"') if None != filename_re.search(str_): filename_ = filename_re.search(str_).group("filename") if None != dir_re.search(str_): dir_ = dir_re.search(str_).group("dir") out_dir = os.path.dirname(self._outFile) combined_output_filename = os.path.join(out_dir, dir_, filename_) output_exists = os.path.exists(combined_output_filename) if output_exists: self._outFile = combined_output_filename self._parent.setOutputFilePath(self._outFile) return True return False def __findInSubdir(self): output_filename = unicode(self._outFile) filename_ = os.path.basename(output_filename) dir_ = os.path.dirname(output_filename) folder_name = os.path.basename(dir_) output_filename = os.path.join(dir_, folder_name, filename_) output_exists = os.path.exists(output_filename) if output_exists: self._outFile = output_filename self._parent.setOutputFilePath(self._outFile) return True return False def on_viewButton__clicked(self, released=True): if not released: return self._plugin.launchViewer(os.path.abspath(self._outFile)) def publish(self, dsi, outFile): if not self._publisher: self.updatePublisherOutput("Script is not found") self.publishComplete(1, QProcess.Crashed) return self.exec_() self._outFile = outFile self.show() try: self.progressBar_.setValue(self.progressBar_.minimum() + 1) self._publisher.publish(self, dsi, outFile) self._timeline.start() except PublishException, pe: self.updatePublisherOutput(pe.getErrorString()) return self.exec_()
class LineTextWidget(QFrame): class NumberBar(QWidget): def __init__(self, *args): QWidget.__init__(self, *args) self.edit = None # This is used to update the width of the control. # It is the highest line that is currently visibile. self.highest_line = 0 def setTextEdit(self, edit): self.edit = edit def update(self, *args): ''' Updates the number bar to display the current set of numbers. Also, adjusts the width of the number bar if necessary. ''' # The + 4 is used to compensate for the current line being bold. width = self.fontMetrics().width(str(self.highest_line)) + 4 if self.width() != width: self.setFixedWidth(width) QWidget.update(self, *args) def paintEvent(self, event): contents_y = self.edit.verticalScrollBar().value() page_bottom = contents_y + self.edit.viewport().height() font_metrics = self.fontMetrics() current_block = self.edit.document().findBlock(self.edit.textCursor().position()) painter = QPainter(self) line_count = 0 # Iterate over all text blocks in the document. block = self.edit.document().begin() while block.isValid(): line_count += 1 # The top left position of the block in the document position = self.edit.document().documentLayout().blockBoundingRect(block).topLeft() # Check if the position of the block is out side of the visible # area. if position.y() > page_bottom: break # We want the line number for the selected line to be bold. bold = False if block == current_block: bold = True font = painter.font() font.setBold(True) painter.setFont(font) # Draw the line number right justified at the y position of the # line. 3 is a magic padding number. drawText(x, y, text). painter.drawText(self.width() - font_metrics.width(str(line_count)) - 3, round(position.y()) - contents_y + font_metrics.ascent(), str(line_count)) # Remove the bold style if it was set previously. if bold: font = painter.font() font.setBold(False) painter.setFont(font) block = block.next() self.highest_line = line_count painter.end() QWidget.paintEvent(self, event) def __init__(self, *args): QFrame.__init__(self, *args) #self.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) self.edit = QTextEdit(*args) #self.edit.setFrameStyle(QFrame.NoFrame) self.edit.setLineWrapMode(QTextEdit.NoWrap) self.edit.setAcceptRichText(False) #self.edit.setReadOnly(True) self.number_bar = self.NumberBar() self.number_bar.setTextEdit(self.edit) hbox = QHBoxLayout(self) hbox.setSpacing(0) hbox.setMargin(0) hbox.addWidget(self.number_bar) hbox.addWidget(self.edit) self.edit.installEventFilter(self) self.edit.viewport().installEventFilter(self) def setText(self, text): self.edit.setText(text) def toPlainText(self): return self.edit.toPlainText() def setFocus(self): self.edit.setFocus() def append(self, text): self.edit.append(text) def eventFilter(self, object, event): # Update the line numbers for all events on the text edit and the viewport. # This is easier than connecting all necessary singals. if object in (self.edit, self.edit.viewport()): self.number_bar.update() return False return QFrame.eventFilter(object, event) def getTextEdit(self): return self.edit
class NoteBook(QFrame): # ======================================================================= def __init__(self, parent=None, _PARENT=None): # ------------------------------------------------------------------- QFrame.__init__(self, parent); self.setGeometry(3, 5, 975, 548); # ------------------------------------------------------------------- self.PARENT = _PARENT; self.CONF = _PARENT.CONF; self.DIR = self.CONF["USER"]["DIR"]; self.NOTEBOOK_A_FILE = self.DIR+"NOTE_A.file"; self.NOTEBOOK_B_FILE = self.DIR+"NOTE_B.file"; _stl = " QTextEdit{ font: 12px 'monospace'; background-color: #444; color: #fff; background-image: url(); }"; _MT = 115; _ML = 12; _W = 470; _H = 400; self.NOTEBOOK_A_WIDGET = QTextEdit("", self); self.NOTEBOOK_A_WIDGET.setGeometry(_ML, _MT, _W, _H); self.NOTEBOOK_A_WIDGET.setStyleSheet( _stl ); self.NOTEBOOK_A_WIDGET.setDocumentTitle(" TTL A One test") self.NOTEBOOK_A_WIDGET.LineWrapMode( self.NOTEBOOK_A_WIDGET.WidgetWidth ); #self.NOTEBOOK_A_WIDGET.setEditable(True); self.NOTEBOOK_B_WIDGET = QTextEdit("", self); self.NOTEBOOK_B_WIDGET.setGeometry(_W+(_ML*2), _MT, _W, _H); self.NOTEBOOK_B_WIDGET.setStyleSheet( _stl ); self.NOTEBOOK_B_WIDGET.setDocumentTitle(" TTL B One test") self.NOTEBOOK_B_WIDGET.LineWrapMode( self.NOTEBOOK_B_WIDGET.WidgetWidth ); #self.NOTEBOOK_B_WIDGET.setEditable(True); """ self.SAVE_DATA_BTN = QPushButton("Save", self); self.SAVE_DATA_BTN.setGeometry(5, 5, 100, 30); self.connect( self.SAVE_DATA_BTN, SIGNAL('clicked()'), self.SAVE_DATA ); """ # ------------------------------------------------------------------- self.INIT(); # ------------------------------------------------------------------- # ======================================================================= def INIT(self): # ------------------------------------------------------------------- try: # --------------------------------------------------- # A FS = open( self.NOTEBOOK_A_FILE, "r"); lines = FS.readlines(); FS.close(); for line in lines: self.NOTEBOOK_A_WIDGET.append(line.strip()); #self.NOTEBOOK_A_WIDGET.insertPlainText(line); #self.NOTEBOOK_A_WIDGET.insertHtml(line); # --------------------------------------------------- # B FS = open( self.NOTEBOOK_B_FILE, "r"); lines = FS.readlines(); FS.close(); for line in lines: self.NOTEBOOK_B_WIDGET.append(line.strip()); #self.NOTEBOOK_B_WIDGET.insertPlainText(line); #self.NOTEBOOK_B_WIDGET.insertHtml(line); # --------------------------------------------------- except Exception as _exception: print("-----------------------------------------------------"); print(_exception); # ------------------------------------------------------------------- # ======================================================================= def SAVE_DATA(self): # ------------------------------------------------------------------- try: # A FS = open( self.NOTEBOOK_A_FILE, "r"); lines = FS.readlines(); FS.close(); for line in lines: self.NOTEBOOK_A_WIDGET.append(line.strip()); #self.NOTEBOOK_A_WIDGET.insertPlainText(line); #self.NOTEBOOK_A_WIDGET.insertHtml(line); # --------------------------------------------------- # A FS = open( self.NOTEBOOK_A_FILE, "w"); DATA = str(self.NOTEBOOK_A_WIDGET.toPlainText()).split("\n"); for line in DATA: FS.write(line+"\n"); FS.close(); # --------------------------------------------------- # B FS = open( self.NOTEBOOK_B_FILE, "w"); DATA = str(self.NOTEBOOK_B_WIDGET.toPlainText()).split("\n"); for line in DATA: FS.write(line+"\n"); FS.close(); # --------------------------------------------------- except Exception as _exception: print("-----------------------------------------------------"); print(_exception); # ------------------------------------------------------------------- # ======================================================================= ###################################################################################################
class NoteBook(QFrame): # ======================================================================= def __init__(self, parent=None, _PARENT=None): # ------------------------------------------------------------------- QFrame.__init__(self, parent) self.setGeometry(3, 5, 975, 548) # ------------------------------------------------------------------- self.PARENT = _PARENT self.CONF = _PARENT.CONF self.DIR = self.CONF["USER"]["DIR"] self.NOTEBOOK_A_FILE = self.DIR + "NOTE_A.file" self.NOTEBOOK_B_FILE = self.DIR + "NOTE_B.file" _stl = " QTextEdit{ font: 12px 'monospace'; background-color: #444; color: #fff; background-image: url(); }" _MT = 115 _ML = 12 _W = 470 _H = 400 self.NOTEBOOK_A_WIDGET = QTextEdit("", self) self.NOTEBOOK_A_WIDGET.setGeometry(_ML, _MT, _W, _H) self.NOTEBOOK_A_WIDGET.setStyleSheet(_stl) self.NOTEBOOK_A_WIDGET.setDocumentTitle(" TTL A One test") self.NOTEBOOK_A_WIDGET.LineWrapMode(self.NOTEBOOK_A_WIDGET.WidgetWidth) #self.NOTEBOOK_A_WIDGET.setEditable(True); self.NOTEBOOK_B_WIDGET = QTextEdit("", self) self.NOTEBOOK_B_WIDGET.setGeometry(_W + (_ML * 2), _MT, _W, _H) self.NOTEBOOK_B_WIDGET.setStyleSheet(_stl) self.NOTEBOOK_B_WIDGET.setDocumentTitle(" TTL B One test") self.NOTEBOOK_B_WIDGET.LineWrapMode(self.NOTEBOOK_B_WIDGET.WidgetWidth) #self.NOTEBOOK_B_WIDGET.setEditable(True); """ self.SAVE_DATA_BTN = QPushButton("Save", self); self.SAVE_DATA_BTN.setGeometry(5, 5, 100, 30); self.connect( self.SAVE_DATA_BTN, SIGNAL('clicked()'), self.SAVE_DATA ); """ # ------------------------------------------------------------------- self.INIT() # ------------------------------------------------------------------- # ======================================================================= def INIT(self): # ------------------------------------------------------------------- try: # --------------------------------------------------- # A FS = open(self.NOTEBOOK_A_FILE, "r") lines = FS.readlines() FS.close() for line in lines: self.NOTEBOOK_A_WIDGET.append(line.strip()) #self.NOTEBOOK_A_WIDGET.insertPlainText(line); #self.NOTEBOOK_A_WIDGET.insertHtml(line); # --------------------------------------------------- # B FS = open(self.NOTEBOOK_B_FILE, "r") lines = FS.readlines() FS.close() for line in lines: self.NOTEBOOK_B_WIDGET.append(line.strip()) #self.NOTEBOOK_B_WIDGET.insertPlainText(line); #self.NOTEBOOK_B_WIDGET.insertHtml(line); # --------------------------------------------------- except Exception as _exception: print("-----------------------------------------------------") print(_exception) # ------------------------------------------------------------------- # ======================================================================= def SAVE_DATA(self): # ------------------------------------------------------------------- try: # A FS = open(self.NOTEBOOK_A_FILE, "r") lines = FS.readlines() FS.close() for line in lines: self.NOTEBOOK_A_WIDGET.append(line.strip()) #self.NOTEBOOK_A_WIDGET.insertPlainText(line); #self.NOTEBOOK_A_WIDGET.insertHtml(line); # --------------------------------------------------- # A FS = open(self.NOTEBOOK_A_FILE, "w") DATA = str(self.NOTEBOOK_A_WIDGET.toPlainText()).split("\n") for line in DATA: FS.write(line + "\n") FS.close() # --------------------------------------------------- # B FS = open(self.NOTEBOOK_B_FILE, "w") DATA = str(self.NOTEBOOK_B_WIDGET.toPlainText()).split("\n") for line in DATA: FS.write(line + "\n") FS.close() # --------------------------------------------------- except Exception as _exception: print("-----------------------------------------------------") print(_exception) # ------------------------------------------------------------------- # ======================================================================= ###################################################################################################
class IO(QDockWidget): def __init__(self, mainWindow): super(IO, self).__init__() self.__mainWindow = mainWindow self.addAction() self.configure() self.io = self.initIO() self.sigout = "IOOUTputtext" self.connect(self, SIGNAL(self.sigout), self.puttextout) self.sigerr = "IOERRputtext" self.connect(self, SIGNAL(self.sigerr), self.puttexterr) self.redirect = RedirectIO(self) self.cioout = CIO(self, sys.__stdout__.fileno(), self.sigout) self.cioout.start() self.cioerr = CIO(self, sys.__stderr__.fileno(), self.sigerr) self.cioerr.start() def configure(self): self.setAllowedAreas(Qt.AllDockWidgetAreas) self.setObjectName("dockWidgetBrowser") self.setWindowTitle( QApplication.translate("Log", "Log", None, QApplication.UnicodeUTF8)) def addAction(self): self.__action = QAction(self) self.__action.setCheckable(True) self.__action.setChecked(True) self.__action.setObjectName("actionCoreInformations") self.__action.setText( QApplication.translate("MainWindow", "Log", None, QApplication.UnicodeUTF8)) self.__mainWindow.menuWindow.addAction(self.__action) self.connect(self.__action, SIGNAL("triggered()"), self.changeVisibleInformations) def changeVisibleInformations(self): if not self.isVisible(): self.setVisible(True) self.__action.setChecked(True) else: self.setVisible(False) self.__action.setChecked(False) def visibilityChanged(self, bool): if not self.isVisible(): self.__action.setChecked(False) else: self.__action.setChecked(True) def initIO(self): self.iowidget = QWidget(self) self.layout = QHBoxLayout(self.iowidget) self.iowidget.setLayout(self.layout) self.tabwidget = QTabWidget(self) self.tabwidget.setElideMode(Qt.ElideRight) self.textOut = QTextEdit(self) self.textOut.setReadOnly(1) self.textOut.name = "output" self.setWidget(self.textOut) self.tabwidget.addTab(self.textOut, "Output") self.textErr = QTextEdit(self) self.textErr.setReadOnly(1) self.textErr.name = "error" self.setWidget(self.textErr) self.tabwidget.addTab(self.textErr, "Error") self.layout.addWidget(self.tabwidget) self.setWidget(self.iowidget) def puttextout(self, text): self.textOut.append(text) def puttexterr(self, text): self.textErr.append(text)
class ChatTracer(QMainWindow): def __init__(self): super(ChatTracer, self).__init__() self.__initGui() self.__initQeo() self.connect(self, SIGNAL("newLogMsg"), self.__appendLog) def __initGui(self): self.setWindowTitle("ChatTracer") g = QGridLayout() w = QWidget() w.setLayout(g) self.setCentralWidget(w) self.logWindow = QTextEdit() self.logWindow.setReadOnly(True) self.logWindow.setFocusPolicy(Qt.NoFocus) self.logWindow.setMinimumWidth(300) g.addWidget(self.logWindow, 0, 0, 3, 1) l = QLabel("ChatParticipants") g.addWidget(l, 0, 1) self.participants = QListWidget() self.participants.setMaximumWidth(250) self.participants.setFocusPolicy(Qt.NoFocus) g.addWidget(self.participants, 1, 1) pb = QPushButton("Refresh Participants") pb.clicked.connect(self.onRefreshParticipants) g.addWidget(pb, 2, 1) g.setColumnStretch(0, 3) g.setColumnStretch(1, 2) self.show() pb.setFocus() def __initQeo(self): self.participantReader = StateReader( ChatParticipant, onData=self.forwardData, onNoMoreData=lambda cls="ChatParticipant": self.forwardNoMoreData(cls), onDispose=self.forwardDispose) self.msgReader = EventReader(ChatMessage, onData=self.forwardData, onNoMoreData=lambda cls="ChatMessage": self.forwardNoMoreData(cls)) self.connect(self, SIGNAL("onData"), self.onData) self.connect(self, SIGNAL("onNoMoreData"), self.onNoMoreData) self.connect(self, SIGNAL("onDispose"), self.onDispose) def closeApp(self): self.participantReader.close() self.participantReader = None self.msgReader.close() self.msgReader = None def __appendLog(self, msg): self.logWindow.append(msg) def __buildLogMsg(self, prefix, data): msg = [prefix + ": "] if data: msg.append("%s" % data.__class__.__name__) msg.append("{") for k, v in data.__dict__.iteritems(): msg.append("%s='%s'" % (str(k), str(v))) msg.append("}") self.__appendLog(' '.join(msg)) def forwardData(self, s): self.emit(SIGNAL("onData"), s) def forwardDispose(self, s): self.emit(SIGNAL("onDispose"), s) def forwardNoMoreData(self, s): self.emit(SIGNAL("onNoMoreData"), s) def onData(self, sample): self.__buildLogMsg("onData", sample) def onDispose(self, sample): print "onDispose called: %s - %s" % (sample.name, sample.room) def onNoMoreData(self, class_): self.__buildLogMsg("onNoMoreData", None) def onRefreshParticipants(self): self.participants.clear() for s in self.participantReader.states(): self.participants.addItem("%s - %s - %s" % (s.name, s.room, s.state))
class ChatTracer(QMainWindow): def __init__(self): super(ChatTracer, self).__init__() self.__initGui() self.__initQeo() self.connect(self, SIGNAL("newLogMsg"), self.__appendLog) def __initGui(self): self.setWindowTitle("ChatTracer") g = QGridLayout() w = QWidget() w.setLayout(g) self.setCentralWidget(w) self.logWindow = QTextEdit() self.logWindow.setReadOnly(True) self.logWindow.setFocusPolicy(Qt.NoFocus) self.logWindow.setMinimumWidth(300) g.addWidget(self.logWindow, 0, 0, 3, 1) l = QLabel("ChatParticipants") g.addWidget(l, 0, 1) self.participants = QListWidget() self.participants.setMaximumWidth(250) self.participants.setFocusPolicy(Qt.NoFocus) g.addWidget(self.participants, 1, 1) pb = QPushButton("Refresh Participants") pb.clicked.connect(self.onRefreshParticipants) g.addWidget(pb, 2, 1) g.setColumnStretch(0, 3) g.setColumnStretch(1, 2) self.show() pb.setFocus() def __initQeo(self): self.participantReader = StateReader( ChatParticipant, onData=self.forwardData, onNoMoreData=lambda cls="ChatParticipant": self.forwardNoMoreData( cls), onDispose=self.forwardDispose) self.msgReader = EventReader( ChatMessage, onData=self.forwardData, onNoMoreData=lambda cls="ChatMessage": self.forwardNoMoreData(cls)) self.connect(self, SIGNAL("onData"), self.onData) self.connect(self, SIGNAL("onNoMoreData"), self.onNoMoreData) self.connect(self, SIGNAL("onDispose"), self.onDispose) def closeApp(self): self.participantReader.close() self.participantReader = None self.msgReader.close() self.msgReader = None def __appendLog(self, msg): self.logWindow.append(msg) def __buildLogMsg(self, prefix, data): msg = [prefix + ": "] if data: msg.append("%s" % data.__class__.__name__) msg.append("{") for k, v in data.__dict__.iteritems(): msg.append("%s='%s'" % (str(k), str(v))) msg.append("}") self.__appendLog(' '.join(msg)) def forwardData(self, s): self.emit(SIGNAL("onData"), s) def forwardDispose(self, s): self.emit(SIGNAL("onDispose"), s) def forwardNoMoreData(self, s): self.emit(SIGNAL("onNoMoreData"), s) def onData(self, sample): self.__buildLogMsg("onData", sample) def onDispose(self, sample): print "onDispose called: %s - %s" % (sample.name, sample.room) def onNoMoreData(self, class_): self.__buildLogMsg("onNoMoreData", None) def onRefreshParticipants(self): self.participants.clear() for s in self.participantReader.states(): self.participants.addItem("%s - %s - %s" % (s.name, s.room, s.state))
class UpdateDialog(QDialog): def __init__(self, update_script): super(UpdateDialog, self).__init__(None, Qt.Window) self.updates_to_run = [] self.setWindowTitle("emzed updates") self.setWindowModality(Qt.WindowModal) self.setMinimumWidth(600) self.update_script = update_script self.setup_widgets() self.setup_layout() self.connect_signals() wd = QApplication.desktop().width() hd = QApplication.desktop().height() w = self.size().width() h = self.size().height() self.move((wd - w) / 2, (hd - h) / 2) def showEvent(self, evt): self.setCursor(Qt.WaitCursor) class WorkerThread(QThread): def run(self, script=self.update_script, parent=self): try: for method, args in script(parent.add_info_line, parent.add_update_info): self.emit(SIGNAL("execute_method(PyQt_PyObject, PyQt_PyObject)"), method, args) except: import traceback tb = traceback.format_exc() self.emit(SIGNAL("execute_method(PyQt_PyObject, PyQt_PyObject)"), parent.add_info_line, (tb,)) self.emit(SIGNAL("update_query_finished()")) self.t = WorkerThread() self.connect(self.t, SIGNAL("update_query_finished()"), self.start_to_interact) self.connect( self.t, SIGNAL("execute_method(PyQt_PyObject,PyQt_PyObject)"), self.execute_method) try: self.t.start() finally: self.setCursor(Qt.ArrowCursor) def execute_method(self, meth, args): meth(*args) def start_to_interact(self): self.ok_button.setEnabled(True) def setup_widgets(self): self.label_info = QLabel("updates from exchange folder:") self.info = QTextEdit(self) self.info.setReadOnly(1) self.label_updates = QLabel("updates from internet:") self.updates = QTableWidget(0, 3) self.updates.setHorizontalHeaderLabels(["updater", "info", "try updatde ?"]) self.updates.verticalHeader().hide() self.updates.horizontalHeader().setResizeMode(0, QHeaderView.Stretch) self.updates.horizontalHeader().setResizeMode(1, QHeaderView.Stretch) self.ok_button = QPushButton("OK") self.ok_button.setEnabled(False) def setup_layout(self): layout = QVBoxLayout() self.setLayout(layout) layout.addWidget(self.label_info) layout.addWidget(self.info) layout.addWidget(self.label_updates) layout.addWidget(self.updates) button_layout = QHBoxLayout() button_layout.addStretch() button_layout.addWidget(self.ok_button) layout.addLayout(button_layout) def connect_signals(self): self.connect(self.ok_button, SIGNAL("pressed()"), self.accept) def ok_button_pressed(self): self.info.append("hi") self.add_update_info("updater", "info") def _item(self, content, is_checkable): item = QTableWidgetItem(str(content)) if is_checkable: item.setCheckState(Qt.Unchecked) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable) return item def add_update_info(self, updater_id, info, with_checkbox=True): i = self.updates.rowCount() self.updates.insertRow(i) self.updates.setItem(i, 0, self._item(updater_id, False)) self.updates.setItem(i, 1, self._item(info, False)) if True or with_checkbox: self.updates.setItem(i, 2, self._item("", True)) def add_info_line(self, txt): self.info.append(txt) def get_updates_to_run(self): return self.updates_to_run def accept(self): for i in range(self.updates.rowCount()): updater_id = str(self.updates.item(i, 0).text()) item = self.updates.item(i, 2) if item is not None: # some cells in column are empty checked = self.updates.item(i, 2).checkState() == Qt.Checked if checked: self.updates_to_run.append(updater_id) super(UpdateDialog, self).accept()
class IO(QDockWidget): def __init__(self, mainWindow): super(IO, self).__init__() self.__mainWindow = mainWindow self.addAction() self.configure() self.io = self.initIO() self.sigout = "IOOUTputtext" self.connect(self, SIGNAL(self.sigout), self.puttextout) self.sigerr = "IOERRputtext" self.connect(self, SIGNAL(self.sigerr), self.puttexterr) self.redirect = RedirectIO(self) self.cioout = CIO(self, sys.__stdout__.fileno(), self.sigout) self.cioout.start() self.cioerr = CIO(self, sys.__stderr__.fileno(), self.sigerr) self.cioerr.start() def configure(self): self.setAllowedAreas(Qt.AllDockWidgetAreas) self.setObjectName("dockWidgetBrowser") self.setWindowTitle(QApplication.translate("Log", "Log", None, QApplication.UnicodeUTF8)) def addAction(self): self.__action = QAction(self) self.__action.setCheckable(True) self.__action.setChecked(True) self.__action.setObjectName("actionCoreInformations") self.__action.setText(QApplication.translate("MainWindow", "Log", None, QApplication.UnicodeUTF8)) self.__mainWindow.menuWindow.addAction(self.__action) self.connect(self.__action, SIGNAL("triggered()"), self.changeVisibleInformations) def changeVisibleInformations(self): if not self.isVisible() : self.setVisible(True) self.__action.setChecked(True) else : self.setVisible(False) self.__action.setChecked(False) def visibilityChanged(self, bool): if not self.isVisible() : self.__action.setChecked(False) else : self.__action.setChecked(True) def initIO(self): self.iowidget = QWidget(self) self.layout = QHBoxLayout(self.iowidget) self.iowidget.setLayout(self.layout) self.tabwidget = QTabWidget(self) self.tabwidget.setElideMode(Qt.ElideRight) self.textOut = QTextEdit(self) self.textOut.setReadOnly(1) self.textOut.name = "output" self.setWidget(self.textOut) self.tabwidget.addTab(self.textOut, "Output") self.textErr = QTextEdit(self) self.textErr.setReadOnly(1) self.textErr.name = "error" self.setWidget(self.textErr) self.tabwidget.addTab(self.textErr, "Error") self.layout.addWidget(self.tabwidget) self.setWidget(self.iowidget) def puttextout(self, text): self.textOut.append(text) def puttexterr(self, text): self.textErr.append(text)
class QChatWindow(QMainWindow): def __init__(self, client, messageQueue, isLightTheme): QMainWindow.__init__(self) self.client = client self.messageQueue = messageQueue self.isLightTheme = isLightTheme self.__setMenubar() self.chatLog = QTextEdit() self.chatLog.setReadOnly(True) self.chatInput = QTextEdit() self.chatInput.textChanged.connect(self.chatInputTextChanged) self.sendButton = QPushButton("Send") self.sendButton.clicked.connect(self.sendMessage) # Set the min height for the chatlog and a matching fixed height for the send button chatInputFontMetrics = QFontMetrics(self.chatInput.font()) self.chatInput.setMinimumHeight(chatInputFontMetrics.lineSpacing() * 3) self.sendButton.setFixedHeight(chatInputFontMetrics.lineSpacing() * 3) hboxLayout = QHBoxLayout() hboxLayout.addWidget(self.chatInput) hboxLayout.addWidget(self.sendButton) # Put the chatinput and send button in a wrapper widget so they may be added to the splitter chatInputWrapper = QWidget() chatInputWrapper.setLayout(hboxLayout) chatInputWrapper.setMinimumHeight(chatInputFontMetrics.lineSpacing() * 3.7) # Put the chat log and chat input into a splitter so the user can resize them at will splitter = QSplitter(Qt.Vertical) splitter.addWidget(self.chatLog) splitter.addWidget(chatInputWrapper) splitter.setSizes([int(self.height()), 1]) vboxLayout = QVBoxLayout() vboxLayout.addWidget(splitter) # Add the completeted layout to the window self.centralWidget = QWidget() self.centralWidget.setLayout(vboxLayout) self.setCentralWidget(self.centralWidget) qtUtils.resizeWindow(self, 700, 400) qtUtils.centerWindow(self) # Title and icon self.setWindowTitle("Cryptully") self.setWindowIcon(QIcon(utils.getAbsoluteResourcePath('images/' + ('light' if isLightTheme else 'dark') + '/icon.png'))) self.statusBar().showMessage("Not Connected") def showNowChattingMessage(self): self.statusBar().showMessage("Connected to " + self.client.getHostname()) self.appendMessage("You are now securely chatting with " + self.client.getHostname() + " :)", constants.SERVICE, showTimestamp=False) self.appendMessage("It's a good idea to verify the communcation is secure by selecting" "\"verify key integrity\" in the options menu.", constants.SERVICE, showTimestamp=False) def chatInputTextChanged(self): if str(self.chatInput.toPlainText())[-1:] == '\n': self.sendMessage() def sendMessage(self): message = str(self.chatInput.toPlainText())[:-1] # Don't send empty messages if message == '': return # Add the message to the message queue to be sent self.messageQueue.put(message) # Clear the chat input self.chatInput.clear() self.appendMessage(message, constants.SENDER) @pyqtSlot(str, int, bool) def appendMessage(self, message, source, showTimestamp=True): if showTimestamp: timestamp = utils.getTimestamp() else: timestamp = '' color = self.__getColor(source) # If the user has scrolled up (current value != maximum), do not move the scrollbar # to the bottom after appending the message shouldScroll = True scrollbar = self.chatLog.verticalScrollBar() if scrollbar.value() != scrollbar.maximum() and source != constants.SENDER: shouldScroll = False # Append the message to the end of the chat log self.chatLog.append(timestamp + '<font color="' + color + '">' + message + "</font>") # Move the vertical scrollbar to the bottom of the chat log if shouldScroll: scrollbar.setValue(scrollbar.maximum()) def __getColor(self, source): if source == constants.SENDER: if self.isLightTheme: return '#0000CC' else: return '#6666FF' elif source == constants.RECEIVER: if self.isLightTheme: return '#CC0000' else: return '#CC3333' else: if self.isLightTheme: return '#000000' else: return '#FFFFFF' def __setMenubar(self): iconPath = 'images/' if self.isLightTheme: iconPath = iconPath + 'light/' else: iconPath = iconPath + 'dark/' fingerprintIcon = QIcon(utils.getAbsoluteResourcePath(iconPath + 'fingerprint.png')) saveIcon = QIcon(utils.getAbsoluteResourcePath(iconPath + 'save.png')) clearIcon = QIcon(utils.getAbsoluteResourcePath(iconPath + 'delete.png')) helpIcon = QIcon(utils.getAbsoluteResourcePath(iconPath + 'help.png')) exitIcon = QIcon(utils.getAbsoluteResourcePath(iconPath + 'exit.png')) menuIcon = QIcon(utils.getAbsoluteResourcePath(iconPath + 'menu.png')) fingerprintAction = QAction(fingerprintIcon, '&Verify key integrity', self) saveKeypairAction = QAction(saveIcon, '&Save current encryption keys', self) clearKeypairAction = QAction(clearIcon, 'C&lear saved encryption keys', self) helpAction = QAction(helpIcon, 'Show &help', self) exitAction = QAction(exitIcon, '&Exit', self) fingerprintAction.triggered.connect(self.__showFingerprintDialog) saveKeypairAction.triggered.connect(self.__showSaveKeypairDialog) clearKeypairAction.triggered.connect(self.__clearKeypair) helpAction.triggered.connect(self.__showHelpDialog) exitAction.triggered.connect(self.__exit) fingerprintAction.setShortcut('Ctrl+I') saveKeypairAction.setShortcut('Ctrl+S') clearKeypairAction.setShortcut('Ctrl+L') helpAction.setShortcut('Ctrl+H') exitAction.setShortcut('Ctrl+Q') optionsMenu = QMenu() optionsMenu.addAction(fingerprintAction) optionsMenu.addAction(saveKeypairAction) optionsMenu.addAction(clearKeypairAction) optionsMenu.addAction(helpAction) optionsMenu.addAction(exitAction) toolButton = QToolButton() toolButton.setIcon(menuIcon) toolButton.setMenu(optionsMenu) toolButton.setPopupMode(QToolButton.InstantPopup) toolbar = self.addToolBar('toolbar') toolbar.addWidget(toolButton) def __showFingerprintDialog(self): QFingerprintDialog(self.client.sock.crypto).exec_() def __showSaveKeypairDialog(self): if utils.doesSavedKeypairExist(): QMessageBox.warning(self, "Keys Already Saved", "The current encryption keys have already been saved.") return QMessageBox.information(self, "Save Keys", "For extra security, your encryption keys will be protected with a passphrase. You'll need to enter this each time you start the app.") passphrase = qtUtils.getKeypairPassphrase(self.isLightTheme, parent=self, verify=True, showForgotButton=False) # Return if the user did not provide a passphrase if passphrase is None: return utils.saveKeypair(self.client.sock.crypto, passphrase) QMessageBox.information(QWidget(), "Keys Saved", "Encryption keys saved. The current keys will be used for all subsequent connections.") def __clearKeypair(self): qtUtils.clearKeypair(self) def __showHelpDialog(self): QHelpDialog(self).show() def __exit(self): qtUtils.exitApp()
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.agreement1ID = 'AG01' self.agreement2ID = 'AG02' self.dbNameInit = 'test1' self.calculate1 = '+' self.c1 = '1' self.c3 = '1' self.threads = [] self.onInit() def onInit(self): self.resize(450, 300) self.center() self.setMenu() self.setWindowTitle(u'MainWindow') self.setWindowIcon(QIcon('learning.ico')) self.agreement1 = QLabel('Contract1', self) self.agreement11 = QLabel(' Contract1 *', self) self.agreement2 = QLabel('Contract2', self) self.agreement22 = QLabel('Contract2 *', self) self.calculate = QLabel('Formula', self) self.startTime = QLabel('Start Time', self) self.endTime = QLabel('End Time', self) self.agreement1Edit = QLineEdit() self.agreement2Edit = QLineEdit() self.calculate1Edit = QLineEdit() self.calculate2Combo = QComboBox() self.calculate2Combo.addItem('+') self.calculate2Combo.addItem('-') self.calculate2Combo.addItem('*') self.calculate2Combo.addItem('/') self.calculate2Combo.activated[str].connect(self.onActivated) self.calculate2Edit = QLineEdit() self.calculate3Edit = QLineEdit() self.startTimeEdit = QDateTimeEdit( datetime.strptime('20150101 00:00:00', '%Y%m%d %H:%M:%S'), self) self.startTimeEdit.setDisplayFormat('yyyy-MM-dd') self.startTimeEdit.setCalendarPopup(True) self.endTimeEdit = QDateTimeEdit(QDateTime.currentDateTime(), self) self.endTimeEdit.setDisplayFormat('yyyy-MM-dd') self.endTimeEdit.setCalendarPopup(True) self.stateEdit = QTextEdit() self.run = QPushButton('Run', self) self.run.clicked.connect(self.runMain) #self.setAgreementBtn = QPushButton('Setting', self) #self.setAgreementBtn.clicked.connect(self.setAgreement) grid = QGridLayout() #grid.setSpacing(10) grid.addWidget(self.agreement1, 1, 0) grid.addWidget(self.agreement1Edit, 1, 1) grid.addWidget(self.agreement2, 2, 0) grid.addWidget(self.agreement2Edit, 2, 1) #grid.addWidget(self.setAgreementBtn, 2, 2) grid.addWidget(self.startTime, 3, 0) grid.addWidget(self.startTimeEdit, 3, 1) grid.addWidget(self.endTime, 4, 0) grid.addWidget(self.endTimeEdit, 4, 1) grid.addWidget(self.calculate, 5, 0) grid.addWidget(self.agreement11, 5, 1) grid.addWidget(self.calculate1Edit, 5, 2) grid.addWidget(self.calculate2Combo, 5, 3) grid.addWidget(self.agreement22, 5, 4) grid.addWidget(self.calculate3Edit, 5, 5) grid.addWidget(self.stateEdit, 6, 1, 1, 5) grid.addWidget(self.run, 7, 1) gridWidget = QWidget() gridWidget.setLayout(grid) self.agreement11.move(200, 100) self.setCentralWidget(gridWidget) self.show() def onActivated(self, text): self.calculate1 = text def setMenu(self): exitAction = QAction(u'Quit', self) exitAction.triggered.connect(qApp.quit) menubar = self.menuBar() fileMenu = menubar.addMenu(u'Menu') fileMenu.addAction(exitAction) def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def done(self, ls): self.stateEdit.append(u'Maximum:%f' % ls[1]) self.stateEdit.append(u'Minimum:%f' % ls[2]) self.stateEdit.append(u'Average:%f' % ls[3]) show(ls[0]) self.run.setEnabled(True) self.stateEdit.append('End time: %s' % time.ctime()) def runMain(self): self.run.setEnabled(False) agreementt1 = self.agreement1Edit.text() agreementt2 = self.agreement2Edit.text() if agreementt1 == '': self.stateEdit.append('Settings of contract1 have error!') elif agreementt2 == '': self.stateEdit.append('Settings of contract2 have error!') else: self.agreement1ID = agreementt1 self.agreement2ID = agreementt2 startTime = self.startTimeEdit.dateTime() endTime = self.endTimeEdit.dateTime() self.c1 = self.calculate1Edit.text() self.c3 = self.calculate3Edit.text() self.stateEdit.append('Formula: ' + self.c1 + '*' + self.agreement1ID + self.calculate1 + self.c3 + '*' + self.agreement2ID + ' have set') self.stateEdit.append('Start time: %s' % time.ctime()) self.workThread = WorkThread(self.agreement1ID, self.agreement2ID, startTime, endTime, self.c1, self.c3, self.calculate1) self.workThread.finishSignal.connect(self.done) self.workThread.start()
class WidgetFFmpeg(QDialog): def __init__(self, idCodec, cheminVideoEntre, cheminSorti, valeurNum=0, laisserOuvert=1, tailleIm=None, tailleVideo=None, systeme=None, cheminFfmpeg=None, tempsApercu=None, optionSpeciale=None, cheminMPlayer=None): """widget ffmpeg""" super(WidgetFFmpeg, self).__init__() self.cheminFfmpeg=u"ffmpeg" self.cheminVideoEntre = unicode(cheminVideoEntre) self.cheminSorti = unicode(cheminSorti) # identifiant du codec self.idCodec = idCodec # valeur de la boite de spin pour l'encodage self.valeurNum = valeurNum # dimension des images (liste de 2 éléments) self.tailleIm = tailleIm # dimension de la vidéo (liste de 2 éléments) self.tailleVideo = tailleVideo # laisser ouvert la fenêtre après encodage self.laisserOuvert = laisserOuvert # Conversion minimale du filtre pour avoir un aperçu. # Indique le temps où l'aperçu doit être créé self.tempsApercu = tempsApercu # drapeau pour ne pas lancer 2 fois l'encodage self.estLancee = False # Est-ce que le 1er % de progression a été récupéré (utile pour montage vidéo -> découper)? self.__recupPourcentDebut = 0 # Pour le son lors de la découpe vidéo pour l'instant if optionSpeciale!=None: self.optionSpeciale = optionSpeciale self.resize(500, 100) #=== Widgets ===# self.labelAttente=QLabel() self.labelAttente.setText(_(u"Attendez la fin du calcul s'il vous plaît, soyez patient !")) self.zoneTexte = QTextEdit("") # là où s'afficheront les infos if PYQT_VERSION_STR < "4.1.0": self.zoneTexte.setText = self.zoneTexte.setPlainText self.zoneTexte.setReadOnly(True) self.zoneTexte.setText("#######\n# LOG :\n#######\n") self.zoneTexte.hide() self.bout_annuler = QPushButton(_(u"Annuler")) self.bout_preZoneTexte = QPushButton(_("Voir les informations de l'encodage")) self.bout_preZoneTexte.hide() self.pbar = QProgressBar() self.pbar.setMaximum(100) vbox = QVBoxLayout() vbox.addWidget(self.labelAttente) vbox.addWidget(self.bout_preZoneTexte) vbox.addWidget(self.zoneTexte) hbox = QHBoxLayout() hbox.addWidget(self.pbar) hbox.addWidget(self.bout_annuler) vbox.addLayout(hbox) self.setLayout(vbox) self.ffmpegProcess = FFmpeg(inputfile = unicode(self.cheminVideoEntre), outputfile = unicode(self.cheminSorti), codec = self.idCodec, imgsize = self.tailleIm, videosize = self.tailleVideo) #=== connexion des widgets à des fonctions ===# self.connect(self.ffmpegProcess, SIGNAL('progress(int)'), self.pbar.setValue) self.connect(self.ffmpegProcess, SIGNAL('log(QString)'), self.zoneTexte.append) self.connect(self.ffmpegProcess, SIGNAL('finished(int)'), self.finEncodage) self.connect(self.bout_annuler, SIGNAL('clicked()'), self.close) self.connect(self.bout_preZoneTexte, SIGNAL('clicked()'), self.afficherLog) ## On sort cette partie qui ne doit pas être lancée dans l'init de l'objet. # Uniquement FFmpeg #self.demarrerEncodeur('Ffmpeg') def setVideoLen(self, videoLen) : self.ffmpegProcess.setVideoLen(videoLen) def close(self): """ Annule le traitement en cours """ self.ffmpegProcess.cancel() self.ffmpegProcess.wait() #super(WidgetFFmpeg, self).close() # Python 2.6 QDialog.close(self) def exec_(self): """ Surcharge de la fonction exec permettant l'execution hors de l'init""" self.demarrerEncodeur('Ffmpeg') #super(WidgetFFmpeg, self).exec_() # Python 2.6 QDialog.exec_(self) def demarrerEncodeur(self, encodeur): """démarrage de mencoder avec les arguments choisis""" if self.estLancee == False: # pas question de démarrer 2 fois l'encodage commande = None has_audio = False debug('\n') # Si la conversion d'images en vidéo est sélectionné, aucune # info Mplayer n'est affichée (problème de récup infos par Mplayer) if self.idCodec in ['mpeg1video', 'mjpeg', 'h263p', 'mpeg4', 'msmpeg4v2', 'ljpeg', 'dv', 'huffyuv', 'mov', 'flv', 'mp4', 'vob']: # ICI SI LES FICHIERS CHARGES SONT DES IMAGES a = "###############################" b = "# Informations sur les images :" c = "###############################" infos = '\n'+a+'\n'+b+'\n'+c+'\n' debug(infos) self.zoneTexte.append(infos) import glob # Le chemin pour l'affichage des infos sur les images ne fonctionnait # plus après la nouvelle structure des fichiers temporaires self.recupTempImgAnim = glob.glob(EkdConfig.getTempDir() + os.sep + "*.*") self.recupTempImgAnim.sort() # Affichage du chemin (temp) + le poids de chaque image # --> Une énumération de parcours a été introduite for parcNb, parcInfIm in enumerate(self.recupTempImgAnim): debug('* '+str(parcNb+1)+'. '+parcInfIm+' --> '+str(float(os.path.getsize(parcInfIm)/1000))+' ko'+'\n') self.zoneTexte.append('* '+str(parcNb+1)+'. '+parcInfIm+' --> '+str(float(os.path.getsize(parcInfIm)/1000))+' ko'+'\n') # Elimination de la dernière image de la liste car car elle # s'affiche en double ds la fenêtre information de l'encodage # et aussi ds la console #self.log = self.log[:len(self.log)-1] # On définie la longueur de la futur vidéo en divisant le nombre d'image par le # nombre d'image par seconde (valeurNum ici) self.ffmpegProcess.setVideoLen(len(self.recupTempImgAnim) / int(self.valeurNum)) # Pour les traitements autres que la transformation des images en vidéo if self.idCodec not in ['mpeg1video', 'mjpeg', 'h263p', 'mpeg4', 'msmpeg4v2', 'ljpeg', 'dv', 'huffyuv', 'mov', 'flv', 'mp4', 'vob']: a = "########################" b = "# Informations MPlayer :" c = "########################" infos = '\n'+a+'\n'+b+'\n'+c+'\n' debug(infos) ######## Ajouté le 24/07/09 ################################################################## # Utilisation de la classe infovideo (et en particilier la fonction setVideo) # présents dans gui_modules_animation/infoVideo.py info = infovideo(self.cheminVideoEntre) id_filename = 'ID_FILENAME='+self.cheminVideoEntre+'\n' debug(id_filename) id_demuxer = 'ID_DEMUXER='+info.demux+'\n' debug(id_demuxer) id_video_format = 'ID_VIDEO_FORMAT='+info.videoFormat+'\n' debug(id_video_format) id_video_codec = 'ID_VIDEO_CODEC='+info.video_codec+'\n' debug(id_video_codec) id_video_bitrate = 'ID_VIDEO_BITRATE='+str(info.videoBitrate)+'\n' debug(id_video_bitrate) id_video_largeur = 'ID_VIDEO_WIDTH='+str(info.videoLargeur)+'\n' debug(id_video_largeur) id_video_hauteur = 'ID_VIDEO_HEIGHT='+str(info.videoHauteur)+'\n' debug(id_video_hauteur) id_img_par_sec = 'ID_VIDEO_FPS='+str(info.imgParSec)+'\n' debug(id_img_par_sec) ##### Donnée très importante pour la suite du calcul (pour ffmpeg.py et ffmpeg2theora) #### self.dureeTotaleVideo = float(info.dureeTotaleVideo) ########################################################################################### id_duree_totale_video = 'ID_LENGTH='+str(info.dureeTotaleVideo)+'\n' debug(id_duree_totale_video) id_audio_codec = 'ID_AUDIO_CODEC='+info.audioCodec+'\n' debug(id_audio_codec) id_audio_rate = 'ID_AUDIO_RATE='+str(info.audioRate)+'\n' debug(id_audio_rate) id_audio_bitrate = 'ID_AUDIO_BITRATE='+str(info.audioBitrate)+'\n' debug(id_audio_bitrate) self.zoneTexte.append(infos+id_filename+id_demuxer+id_video_format+id_video_codec+id_video_bitrate+id_video_largeur+id_video_hauteur+id_img_par_sec+id_duree_totale_video+id_audio_codec+id_audio_rate+id_audio_bitrate) ############################################################################################## ## On définie la longueur de la vidéo pour le process self.ffmpegProcess.setVideoLen(self.dureeTotaleVideo) if info.audioCodec : has_audio = True debug('\n') a = "############################" b = "# Informations %s :" %encodeur c = "############################" infos = '\n'+a+'\n'+b+'\n'+c+'\n' debug(infos) self.zoneTexte.append(infos) if self.idCodec=='codec_dv_ffmpeg': self.ffmpegProcess.commandeFfmpegEncodageDv() elif self.idCodec=='codec_mov_ffmpeg': #### Enlevé le 09/04/11 ############################## #self.ffmpegProcess.commandeFfmpegEncodageMov() ###################################################### #### Ajouté/rectifié le 09/04/11 ##################### self.ffmpegProcess.commandeFfmpegEncodageMov(comp = self.valeurNum[0], size = self.valeurNum[1]) ###################################################### elif self.idCodec=='codec_hfyu_ffmpeg': #### Enlevé le 10/04/11 ############################## #self.ffmpegProcess.commandeFfmpegEncodageHfyu(audio = has_audio) ###################################################### #### Ajouté/rectifié le 10/04/11 ##################### self.ffmpegProcess.commandeFfmpegEncodageHfyu(size = self.valeurNum, audio = has_audio) ###################################################### elif self.idCodec=='codec_vob_ffmpeg': self.ffmpegProcess.commandeFfmpegEncodageVob(vquantizer = self.valeurNum) elif self.idCodec=='codec_3GP_ffmpeg': #### Enlevé le 30/03/11 ############################## #self.ffmpegProcess.commandeFfmpegEncodage3gp(audio = has_audio) #### Ajouté/rectifié le 30/03/11 ##################### self.ffmpegProcess.commandeFfmpegEncodage3gp(size = self.valeurNum) ###################################################### elif self.idCodec=='codec_AMV_ffmpeg': #### Rectifié le 30/03/11 ## Ajout de size ########### self.ffmpegProcess.commandeFfmpegEncodageAMV(size = self.valeurNum) ###################################################### elif self.idCodec=='idx': self.ffmpegProcess.commandeFfmpegNbrImgSec(rate = self.valeurNum) elif self.idCodec in ['mpeg1video', 'mjpeg', 'h263p', 'mpeg4', 'msmpeg4v2', 'ljpeg', 'dv', 'huffyuv', 'mov', 'flv', 'mp4', 'vob']: self.ffmpegProcess.commandeFfmpegConvertImg(rate = self.valeurNum, size = "%sx%s" % (self.tailleIm[0], self.tailleIm[1]), vcodec = self.idCodec) # --------------------------------------------------------------------------------- # # Traitement pour chaque entrée concernant la HD (classique, en dehors du codec Avid DNxHD) # --------------------------------------------------------------------------------- # elif self.idCodec in ['hd_1920x1080_mov__pcm_s16be__16/9', 'hd_1280x720_mov__pcm_s16be__16/9', 'hd_1440x1080_mov__pcm_s16be__4/3']: ## FIXME : La taille est récupérée du nom de idCodec (crade) self.ffmpegProcess.commandeFfmpegConvHD(size = self.idCodec.split("_")[1]) ### Ajouté le 19/08/10 (Gestion du codec Avid DNxHD) ################################ # --------------------------------------------------------------------------------- # # Traitement pour chaque entrée (24) concernant le codec Avid DNxHD pour la HD # --------------------------------------------------------------------------------- # elif self.idCodec=='hd_dnxhd_1920x1080_29.97_220_mbs': ## FIXME : Les éléments utiles sont récupérés du nom de idCodec (crade mais utile) self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 1 elif self.idCodec=='hd_dnxhd_1920x1080_29.97_145_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 2 elif self.idCodec=='hd_dnxhd_1920x1080_25_185_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 3 elif self.idCodec=='hd_dnxhd_1920x1080_25_120_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 4 elif self.idCodec=='hd_dnxhd_1920x1080_25_36_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 5 elif self.idCodec=='hd_dnxhd_1920x1080_24_175_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 6 elif self.idCodec=='hd_dnxhd_1920x1080_24_115_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 7 elif self.idCodec=='hd_dnxhd_1920x1080_24_36_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 8 elif self.idCodec=='hd_dnxhd_1920x1080_23.976_175_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 9 elif self.idCodec=='hd_dnxhd_1920x1080_23.976_115_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 10 elif self.idCodec=='hd_dnxhd_1920x1080_23.976_36_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 11 elif self.idCodec=='hd_dnxhd_1920x1080_29.97_220_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 12 elif self.idCodec=='hd_dnxhd_1920x1080_29.97_145_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 13 elif self.idCodec=='hd_dnxhd_1920x1080_29.97_45_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 14 elif self.idCodec=='hd_dnxhd_1280x720_59.94_220_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 15 elif self.idCodec=='hd_dnxhd_1280x720_59.94_145_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 16 elif self.idCodec=='hd_dnxhd_1280x720_50_175_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 17 elif self.idCodec=='hd_dnxhd_1280x720_50_115_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 18 elif self.idCodec=='hd_dnxhd_1280x720_29.97_110_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 19 elif self.idCodec=='hd_dnxhd_1280x720_29.97_75_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 20 elif self.idCodec=='hd_dnxhd_1280x720_25_90_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 21 elif self.idCodec=='hd_dnxhd_1280x720_25_60_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 22 elif self.idCodec=='hd_dnxhd_1280x720_23.976_90_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 23 elif self.idCodec=='hd_dnxhd_1280x720_23.976_60_mbs': self.ffmpegProcess.commandeFfmpegConvHD_DNxHD(size=self.idCodec.split("_")[2], vcodec=self.idCodec.split("_")[1], rate=self.idCodec.split("_")[3], vbitrate=self.idCodec.split("_")[4]+'000k') # 24 ################################################################################# elif self.idCodec=='jpeg': # convertir animation en images self.ffmpegProcess.commandeFfmpegConvAnimImg() elif self.idCodec=='extractionaudio': self.ffmpegProcess.commandeFfmpegSeparation() elif self.idCodec=='encodage_wav': # encodage de fichiers audio en wav self.ffmpegProcess.commandeFfmpegEncodageWav() elif self.idCodec=='conv_en_16_9_ou_4_3': # Convertir vidéo en 16/9 ou 4/3 self.ffmpegProcess.commandeFfmpegConv_16_9_ou_4_3( ext = os.path.splitext(self.cheminVideoEntre)[1], size = "%sx%s" % (self.tailleVideo[0], self.tailleVideo[1]), aspect = self.valeurNum, audio = has_audio) # Remonté d'un niveau pour simplifier le code et éviter les répetitions if commande == None: commande = self.ffmpegProcess.command else : self.ffmpegProcess.command = commande debug(commande) self.zoneTexte.append(commande+'\n\n') self.ffmpegProcess.start() debug(u"Commande lancée") self.estLancee = True def finEncodage(self, statutDeSortie): """choses à faire à la fin de l'encodage de la vidéo""" # fermer la fenêtre à la fin de l'encodage if not self.laisserOuvert: self.close() debug("fini!") self.labelAttente.hide() self.pbar.setValue(100) # l'encodage est fini. Il ne peut plus être annulé. La # seule action possible devient ainsi la fermeture self.bout_annuler.setText(_(u"Fermer")) if statutDeSortie != 0 : self.bout_annuler.setText(_(u"Crash")) self.bout_preZoneTexte.show() self.emit(SIGNAL("finEncodage")) def afficherLog(self): """afficher les information de la vidéo de départ et de l'encodage""" self.zoneTexte.setText(self.ffmpegProcess.log) self.zoneTexte.show() self.resize(500, 300)
class ProgressDialog(Ui_ProgressDialog, DialogBase): def __init__(self, publisher, plugin, parentWidget=None): DialogBase.__init__(self, parentWidget) self.setupUi(self) self.setObjectName("ProgressDialog") self.viewButton_.setEnabled(False) self._publisher = publisher self._plugin = plugin self._parent = parentWidget self._cancelled = False self._timeline = QTimeLine(1000 * 60, self) self._timeline.setFrameRange(0, 2 * 60) self._timeline.setLoopCount(0) self.progressBar_.setRange(0, 60) self.connect(self._timeline, QtCore.SIGNAL("frameChanged(int)"), self.updateProgressBar) self.outputGroupBox_ = QGroupBox("Script output", None) self.outputTextEdit_ = QTextEdit() self.outputTextEdit_.setTextInteractionFlags( Qt.TextSelectableByKeyboard | Qt.TextSelectableByMouse) self.outputTextEdit_.setReadOnly(True) self.outputTextEdit_.setTabChangesFocus(True) self.outputTextEdit_.setAcceptRichText(False) groupBoxLayout = QVBoxLayout() groupBoxLayout.setObjectName("groupBoxLayout") groupBoxLayout.setMargin(0) groupBoxLayout.addWidget(self.outputTextEdit_) self.outputGroupBox_.setLayout(groupBoxLayout) gridLayout = QGridLayout() gridLayout.setSizeConstraint(gridLayout.SetFixedSize) gridLayout.addWidget(self.progressLabel_, 0, 0, 1, 4) gridLayout.addWidget(self.progressBar_, 1, 0, 1, 4) gridLayout.addWidget(self.detailsCheckBox_, 2, 0) hSpacer = QSpacerItem(250, 10, QSizePolicy.Expanding) gridLayout.addItem(hSpacer, 2, 1) gridLayout.addWidget(self.viewButton_, 2, 2) gridLayout.addWidget(self.cancelButton_, 2, 3) gridLayout.addWidget(self.outputGroupBox_, 3, 0, 1, 4) self.setLayout(gridLayout) self.outputGroupBox_.setVisible(False) def updateProgressBar(self, frame): self.progressBar_.setValue(self.progressBar_.value() + 1) def on_detailsCheckBox__stateChanged(self, state): self.outputGroupBox_.setVisible(Qt.Checked == state) gridLayout = self.layout() if Qt.Checked == state: gridLayout.setSizeConstraint(gridLayout.SetMaximumSize) self.setSizeGripEnabled(True) else: gridLayout.setSizeConstraint(gridLayout.SetFixedSize) self.setSizeGripEnabled(False) def on_cancelButton__clicked(self, released=True): if not released: return if self._cancelled: self.reject() return self.cancelButton_.setEnabled(False) self.progressLabel_.setText("Cancelling...") self._publisher.cancel() self._cancelled = True QTimer.singleShot(5 * 1000, self, QtCore.SLOT("_kill()")) @QtCore.pyqtSignature("_kill()") def _cancel(self): self._parent.update() self._publisher.cancel(True) self.reject() def updatePublisherOutput(self, data): self.outputTextEdit_.append(data) def publishComplete(self, exitCode, exitStatus): self.progressBar_.setValue(self.progressBar_.maximum()) self._timeline.stop() if self._cancelled: self.reject() self._cancelled = True publishSuccess = (0 == exitCode and QProcess.NormalExit == exitStatus) output_exists = self.__findOutput() self.viewButton_.setEnabled(publishSuccess and \ output_exists) if not publishSuccess: self.progressLabel_.setText("Publishing failed, see script output" " for more details") else: self.progressLabel_.setText("Publishing completed") def __findOutput(self): output_exists = os.path.exists(unicode(self._outFile)) if not output_exists: output_exists = self.__findInSubdir() if not (output_exists) and ('Dita' in self._publisher.__str__()): output_exists = self.__findInLog() if not (output_exists) and ('Docbook' in self._publisher.__str__()): output_exists = self.__findInPI() return output_exists def __findInLog(self): log = self.outputTextEdit_.toPlainText() src_filename = os.path.basename(self._publisher.attrs()['srcUri']) dst_filename = src_filename.split( '.')[0] + "." + self._publisher.attrs()['extension'] re_str = '\[xslt\] Processing.*?' + src_filename + ' to (?P<outputFilename>.*?' + dst_filename + ')' output_re = re.compile(re_str) output_filename = '' if None != output_re.search(log): output_filename = output_re.search(log).group("outputFilename") if not output_filename: return False real_dst_dir = os.path.dirname(unicode(output_filename)) dst_filename = os.path.join(real_dst_dir, os.path.basename(self._outFile)) os.rename(output_filename, dst_filename) output_exists = os.path.exists(dst_filename) if output_exists: self._outFile = dst_filename self._parent.setOutputFilePath(self._outFile) return True return False def __findInPI(self): src_uri = self._publisher.attrs()['srcUri'] grove = Grove.buildGroveFromFile(src_uri) xpath_value = XpathExpr( "//self::processing-instruction('dbhtml')").eval(grove.document()) dbhtml_pi = xpath_value.getNodeSet().firstNode() str_ = unicode(dbhtml_pi.asGrovePi().data()) filename_re = re.compile('filename="(?P<filename>.*?\n?.*?)"') dir_re = re.compile('dir="(?P<dir>.*?\n?.*?)"') if None != filename_re.search(str_): filename_ = filename_re.search(str_).group("filename") if None != dir_re.search(str_): dir_ = dir_re.search(str_).group("dir") out_dir = os.path.dirname(self._outFile) combined_output_filename = os.path.join(out_dir, dir_, filename_) output_exists = os.path.exists(combined_output_filename) if output_exists: self._outFile = combined_output_filename self._parent.setOutputFilePath(self._outFile) return True return False def __findInSubdir(self): output_filename = unicode(self._outFile) filename_ = os.path.basename(output_filename) dir_ = os.path.dirname(output_filename) folder_name = os.path.basename(dir_) output_filename = os.path.join(dir_, folder_name, filename_) output_exists = os.path.exists(output_filename) if output_exists: self._outFile = output_filename self._parent.setOutputFilePath(self._outFile) return True return False def on_viewButton__clicked(self, released=True): if not released: return self._plugin.launchViewer(os.path.abspath(self._outFile)) def publish(self, dsi, outFile): if not self._publisher: self.updatePublisherOutput("Script is not found") self.publishComplete(1, QProcess.Crashed) return self.exec_() self._outFile = outFile self.show() try: self.progressBar_.setValue(self.progressBar_.minimum() + 1) self._publisher.publish(self, dsi, outFile) self._timeline.start() except PublishException, pe: self.updatePublisherOutput(pe.getErrorString()) return self.exec_()
class Chat(QFrame): # ======================================================================= def __init__(self, parent=None, _PARENT=None): # ------------------------------------------------------------------- QFrame.__init__(self, parent); # ------------------------------------------------------------------- self.PARENT = _PARENT; self.CONF = _PARENT.CONF; self.setGeometry(3, 5, 975, 548); self.setStyleSheet( "QFrame{ font: 12px 'monospace'; color: #000; background-color: transparent; background-image: url('./data/imgs/TAB_Chat.png'); }" ); # ------------------------------------------------------------------- self.CHAT_URL = "https://btc-e.com/"; self.CHAT_DATA = []; self.CHAT_LANG = self.CONF["USER"]["CHAT_LANG"]; self.CHAT_HEADERS = { "User-Agent" : "Mozilla/5.0 (Win-32; rv:24.0) Gecko/20140723 Firefox/24.0 Iceweasel/24.7.0", "Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language" : "en-US,en;q=0.5", "Referer" : "https://btc-e.com/", "Connection" : "keep-alive", "Cache-Control" : "max-age=0", "Cookie" : "" } self.CHAT_TIMER = QTimer(); #self.CHAT_BG_COLOR = "#555"; self.CHAT_BG_COLOR = "#0F0"; self.CHAT_ALLOW_UPD = False; # ------------------------------------------------------------------- self.CHAT_WIDGET = QTextEdit( self ); self.CHAT_WIDGET.setGeometry( 13, 116, 690, 388 ); self.CHAT_WIDGET.setStyleSheet( "QTextEdit{ background-color: transparent; color: #fff; background-image: url(''); }" ); self.CHAT_WIDGET.setReadOnly( True ); self.LANG_COMBO = QComboBox( self); self.LANG_COMBO.setGeometry( 86, 20, 108, 44 ); self.connect( self.LANG_COMBO, SIGNAL('currentIndexChanged(int)'), self.CHANGE_CHAT_LANG ); self.LANG_COMBO.setEditable(False); self.NEW_MSG = QLineEdit("", self); self.NEW_MSG.setGeometry( 20, 510, 500, 30 ); self.NEW_MSG.setStyleSheet(" QLineEdit{ border-style: none; background-color: #333; color: #fff; background-image: url(''); }"); self.NEW_MSG.setPlaceholderText(" Enter message:"); self.SEND = QPushButton(" Send", self); self.SEND.setGeometry( 593, 510, 90, 30 ); #self.SEND.setStyleSheet( "QPushButton{ background-color: transparent; border-style: none; }" ); #self.connect( self.SEND, SIGNAL('clicked()'), lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SEND_VALUES") ); # ------------------------------------------------------------------- self.ALLOW_UPDATE_CHECKBOX = QCheckBox("", self); self.ALLOW_UPDATE_CHECKBOX.setGeometry( 335, 83, 17, 17 ); self.ALLOW_UPDATE_CHECKBOX.setCheckState(Qt.Unchecked); self.connect(self.ALLOW_UPDATE_CHECKBOX, SIGNAL('stateChanged(int)'), self.CHANGE_VALUES ); self.UPDATE_NOW_BTN = QPushButton("Update Now!", self); self.UPDATE_NOW_BTN.setGeometry( 360, 74, 94, 24 ); self.connect( self.UPDATE_NOW_BTN, SIGNAL('clicked()'), self.UPDATE_NOW ); # ------------------------------------------------------------------- self.INIT(); # ------------------------------------------------------------------- # ======================================================================= def INIT(self): # ------------------------------------------------------------------- try: self.INIT_CHAT_COMBO(); self.UPDATE(); except Exception as _exception: print("-----------------------------------------------------"); print("[INIT]"+str(_exception)); # ------------------------------------------------------------------- # ======================================================================= def UPDATE_NOW(self): # ------------------------------------------------------------------- self.CHAT_ALLOW_UPD = True; self.UPDATE(); self.CHAT_ALLOW_UPD = False; # ------------------------------------------------------------------- # ======================================================================= def UPDATE(self): # ------------------------------------------------------------------- #print("UPDATE:") # ------------------------------------------------------------------- try: if self.CHAT_ALLOW_UPD: self.GET_DATA(); self.CHAT_WIDGET.clear(); for msg in self.CHAT_DATA: # --------------------------------------------------------------- """ print(msg["time"]); print(msg["nick"]); print(msg["msg"]); """ # --------------------------------------------------------------- item = '<p style="background-color: #555;">'; item += "[<span style='color: #000;'>"+msg["time"].split(" ")[1]+"</span>] : "; if msg["nick"] == "admin": item += "[<span style='color: #f00; font-weight: bold;'>"+msg["nick"]+"</span>]<br/><br/>"; else: item += "[<span style='color: #000; font-weight: bold;'>"+msg["nick"]+"</span>]<br/><br/>"; item += msg["msg"]+"<br/>"; item += "</p>"; self.CHAT_WIDGET.append(item); # --------------------------------------------------------------- self.CHAT_TIMER.singleShot( self.CONF["SYS"]["UPD_DELAY"], self.UPDATE ); except Exception as e: print("CHAT[0:0]"+str(e)) self.CHAT_TIMER.singleShot( self.CONF["SYS"]["UPD_DELAY"], self.UPDATE ); # ------------------------------------------------------------------- # ======================================================================= def CHANGE_VALUES(self): # ------------------------------------------------------------------- if self.ALLOW_UPDATE_CHECKBOX.isChecked(): self.CHAT_ALLOW_UPD = True; else: self.CHAT_ALLOW_UPD = False; # ------------------------------------------------------------------- # ======================================================================= def GET_DATA(self): # ------------------------------------------------------------------- try: self.CHAT_HEADERS["Cookie"] = "chatRefresh=1; locale="+self.CHAT_LANG+";" req = urllib2.Request(self.CHAT_URL, headers=self.CHAT_HEADERS); resp = urllib2.urlopen(req).read(); CHAT = BeautifulSoup( resp ).body.find('div', attrs={'id':'nChat'}); self.CHAT_DATA = []; for data in CHAT: self.CHAT_DATA.append( { "msg_id": data["id"], "nick":data.a.string, "time": data.a["title"], "msg": data.span.string } ); except Exception as e: print("CHAT[0:1]"+str(e)) # ------------------------------------------------------------------- # ======================================================================= def CHANGE_CHAT_LANG(self): # ------------------------------------------------------------------- self.CHAT_LANG = str(self.LANG_COMBO.currentText()).lower().strip(); #print(self.CHAT_LANG); # ------------------------------------------------------------------- # ======================================================================= def INIT_CHAT_COMBO(self): # ------------------------------------------------------------------- for LANG in self.CONF["USER"]["CHAT_LANGS"]: self.LANG_COMBO.addItem(LANG.upper()); for i in xrange(0, self.LANG_COMBO.__len__()): self.LANG_COMBO.setItemData( i, QColor("#333"),Qt.BackgroundRole ); self.LANG_COMBO.setItemData( i, QColor("#fff"),Qt.ForegroundRole );
class LineTextWidget(QFrame): class NumberBar(QWidget): def __init__(self, *args): QWidget.__init__(self, *args) self.edit = None # This is used to update the width of the control. # It is the highest line that is currently visibile. self.highest_line = 0 def setTextEdit(self, edit): self.edit = edit def update(self, *args): ''' Updates the number bar to display the current set of numbers. Also, adjusts the width of the number bar if necessary. ''' # The + 4 is used to compensate for the current line being bold. width = self.fontMetrics().width(str(self.highest_line)) + 4 if self.width() != width: self.setFixedWidth(width) QWidget.update(self, *args) def paintEvent(self, event): contents_y = self.edit.verticalScrollBar().value() page_bottom = contents_y + self.edit.viewport().height() font_metrics = self.fontMetrics() current_block = self.edit.document().findBlock( self.edit.textCursor().position()) painter = QPainter(self) line_count = 0 # Iterate over all text blocks in the document. block = self.edit.document().begin() while block.isValid(): line_count += 1 # The top left position of the block in the document position = self.edit.document().documentLayout( ).blockBoundingRect(block).topLeft() # Check if the position of the block is out side of the visible # area. if position.y() > page_bottom: break # We want the line number for the selected line to be bold. bold = False if block == current_block: bold = True font = painter.font() font.setBold(True) painter.setFont(font) # Draw the line number right justified at the y position of the # line. 3 is a magic padding number. drawText(x, y, text). painter.drawText( self.width() - font_metrics.width(str(line_count)) - 3, round(position.y()) - contents_y + font_metrics.ascent(), str(line_count)) # Remove the bold style if it was set previously. if bold: font = painter.font() font.setBold(False) painter.setFont(font) block = block.next() self.highest_line = line_count painter.end() QWidget.paintEvent(self, event) def __init__(self, *args): QFrame.__init__(self, *args) #self.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) self.edit = QTextEdit(*args) #self.edit.setFrameStyle(QFrame.NoFrame) self.edit.setLineWrapMode(QTextEdit.NoWrap) self.edit.setAcceptRichText(False) #self.edit.setReadOnly(True) self.number_bar = self.NumberBar() self.number_bar.setTextEdit(self.edit) hbox = QHBoxLayout(self) hbox.setSpacing(0) hbox.setMargin(0) hbox.addWidget(self.number_bar) hbox.addWidget(self.edit) self.edit.installEventFilter(self) self.edit.viewport().installEventFilter(self) def setText(self, text): self.edit.setText(text) def toPlainText(self): return self.edit.toPlainText() def setFocus(self): self.edit.setFocus() def append(self, text): self.edit.append(text) def eventFilter(self, object, event): # Update the line numbers for all events on the text edit and the viewport. # This is easier than connecting all necessary singals. if object in (self.edit, self.edit.viewport()): self.number_bar.update() return False return QFrame.eventFilter(object, event) def getTextEdit(self): return self.edit
class UpdateDialog(QDialog): def __init__(self, update_script): super(UpdateDialog, self).__init__(None, Qt.Window) self.updates_to_run = [] self.setWindowTitle("emzed updates") self.setWindowModality(Qt.WindowModal) self.setMinimumWidth(600) self.update_script = update_script self.setup_widgets() self.setup_layout() self.connect_signals() wd = QApplication.desktop().width() hd = QApplication.desktop().height() w = self.size().width() h = self.size().height() self.move((wd - w) / 2, (hd - h) / 2) def showEvent(self, evt): self.setCursor(Qt.WaitCursor) class WorkerThread(QThread): def run(self, script=self.update_script, parent=self): try: for method, args in script(parent.add_info_line, parent.add_update_info): self.emit(SIGNAL("execute_method(PyQt_PyObject, PyQt_PyObject)"), method, args) except: import traceback tb = traceback.format_exc() self.emit(SIGNAL("execute_method(PyQt_PyObject, PyQt_PyObject)"), parent.add_info_line, (tb,)) self.emit(SIGNAL("update_query_finished()")) self.t = WorkerThread() self.connect(self.t, SIGNAL("update_query_finished()"), self.start_to_interact) self.connect( self.t, SIGNAL("execute_method(PyQt_PyObject,PyQt_PyObject)"), self.execute_method) try: self.t.start() finally: self.setCursor(Qt.ArrowCursor) def execute_method(self, meth, args): meth(*args) def start_to_interact(self): self.ok_button.setEnabled(True) def setup_widgets(self): self.label_info = QLabel("updates from exchange folder:") self.info = QTextEdit(self) self.info.setReadOnly(1) self.label_updates = QLabel("updates from internet:") self.updates = QTableWidget(0, 3) self.updates.setHorizontalHeaderLabels(["updater", "info", "try updatde ?"]) self.updates.verticalHeader().hide() self.updates.horizontalHeader().setResizeMode(0, QHeaderView.Stretch) self.updates.horizontalHeader().setResizeMode(1, QHeaderView.Stretch) self.ok_button = QPushButton("OK") self.ok_button.setEnabled(False) def setup_layout(self): layout = QVBoxLayout() self.setLayout(layout) layout.addWidget(self.label_info) layout.addWidget(self.info) layout.addWidget(self.label_updates) layout.addWidget(self.updates) button_layout = QHBoxLayout() button_layout.addStretch() button_layout.addWidget(self.ok_button) layout.addLayout(button_layout) def connect_signals(self): self.connect(self.ok_button, SIGNAL("pressed()"), self.accept) def ok_button_pressed(self): self.info.append("hi") self.add_update_info("updater", "info") def _item(self, content, is_checkable): item = QTableWidgetItem(content) if is_checkable: item.setCheckState(Qt.Unchecked) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable) return item def add_update_info(self, updater_id, info, with_checkbox=True): i = self.updates.rowCount() self.updates.insertRow(i) self.updates.setItem(i, 0, self._item(updater_id, False)) self.updates.setItem(i, 1, self._item(info, False)) if True or with_checkbox: self.updates.setItem(i, 2, self._item("", True)) def add_info_line(self, txt): self.info.append(txt) def get_updates_to_run(self): return self.updates_to_run def accept(self): for i in range(self.updates.rowCount()): updater_id = str(self.updates.item(i, 0).text()) item = self.updates.item(i, 2) if item is not None: # some cells in column are empty checked = self.updates.item(i, 2).checkState() == Qt.Checked if checked: self.updates_to_run.append(updater_id) super(UpdateDialog, self).accept()
class SR785_MainWindow(QMainWindow): GifInfo = { SR785.SCREEN_ALL: (21200, 'all'), SR785.SCREEN_MENU: (4840, 'menu'), SR785.SCREEN_STATUS: (4410, 'status'), SR785.SCREEN_GRAPHS: (11420, 'graphs') } def __init__(self, parent=None): super(SR785_MainWindow, self).__init__(parent) centralWidget = SR785_Widget() self.setCentralWidget(centralWidget) visaResource = 'GPIB0::10' sr785 = SR785(visaResource) sr785.configureScreenDump() centralWidget.associateInstrument(sr785) self.setWindowTitle('SR785 Front Panel Emulation: %s' % sr785.visaId()) self.progressBar = QProgressBar() statusBar = self.statusBar() statusBar.addWidget(self.progressBar) toolBar = QToolBar('Screen') toolBar.addActions(centralWidget.screenActions) self.addToolBar(toolBar) thread = centralWidget.workerThread thread.gifDownloadStarted.connect(self.gifDownloadStarted) thread.gifReceived.connect(self.gifReceived) thread.keyPressSimulated.connect(self.keyPressSimulated) thread.knobRotated.connect(self.knobRotated) dockWidget = QDockWidget('History') self.historyTe = QTextEdit() dockWidget.setWidget(self.historyTe) self.addDockWidget(Qt.TopDockWidgetArea, dockWidget) toolBar = self.addToolBar('File') action = QAction('Save screen', self) action.triggered.connect(self.saveScreen) toolBar.addAction(action) action = QAction('Print', self) action.triggered.connect(self.printScreen) toolBar.addAction(action) def saveScreen(self): directory = '' saveFile = QFileDialog.getSaveFileName(self, 'Save screen to', directory, '*.png *.gif', '*.png') print "saving as:", saveFile screenPixmap = self.centralWidget().screen.pixmap() screenPixmap.save(saveFile) self.log('Screen saved as: %s' % saveFile) def printScreen(self): pass def gifDownloadStarted(self, screen): self.progressBar.setMaximum(self.GifInfo[screen][0]) self.progressBar.setValue(0) label = self.GifInfo[screen][1] self.progressBar.setFormat('%s %%p%%' % label) self.log('Downloading %s' % label) def gifReceived(self, screen): self.progressBar.setValue(self.GifInfo[screen][0]) def keyPressSimulated(self, keyCode): self.log('Key %d pressed.' % keyCode) def knobRotated(self, steps): if steps > 0: self.log('Knob rotated CW.') else: self.log('Knob rotated CCW.') def log(self, message): self.historyTe.append(message + '\n') self.statusBar().showMessage(message, 2000)
class NoteBook( QFrame ): # ======================================================================= def __init__(self, parent=None): # ------------------------------------------------------------------- QFrame.__init__(self, parent); # ------------------------------------------------------------------- self.PARENT = parent; self.DEBUG = False; self.LOG_TAG = str(self.__class__.__name__).upper(); self.setGeometry( 4, 34, 1012, 606 ); self.setStyleSheet( "QFrame{ font: 12px 'monospace'; color: #fff; background-color: rbga(0,0,0, 190); border-style: solid; border-width: 5px; border-color: #FFF; }" ); # ------------------------------------------------------------------- self.NOTEBOOK_FILE = self.PARENT.STORAGE_ROOT+"notebook.file"; # ------------------------------------------------------------------- self.TEXT = QTextEdit( "TEST: TEST", self ); self.TEXT.setGeometry(5, 35, 980, 560); self.TEXT.setStyleSheet("QTextEdit{ font: 12px 'monospace'; color: #fff; margin: 5px; padding: 5px; border-style: solid; border-width: 1px; border-color: #FFF; }") self.TEXT.setReadOnly( False ); self.TEXT.setAcceptRichText( False ); self.TEXT.setUndoRedoEnabled( True ); self.TEXT.LineWrapMode( self.TEXT.WidgetWidth ); self.TEXT.textChanged.connect( self.TEXT_CHANGED ); # ------------------------------------------------------------------- self.hide(); self.IS_OPEN = False; self.KEEP_OPEN = False; # ------------------------------------------------------------------- self.UPDATE_TIMER = QTimer(); self.UPDATE_TIMER.singleShot( 1000, self.UPDATE_FRAME ); # ------------------------------------------------------------------- self.PARENT.SPLASH.STATUS( self.LOG_TAG+": [INIT]" ); # ------------------------------------------------------------------- # ======================================================================= def TEXT_CHANGED( self ): # ------------------------------------------------------------------- pass; #self.TEXT.setText( str(self.TEXT.toPlainText() ); #self.TEXT.setText( str(self.TEXT.text() ) ); # ------------------------------------------------------------------- # ======================================================================= def CMD( self, _CMD ): # ------------------------------------------------------------------- #__exec:notebook:notes:show" #__exec:notebook:notes:hide" #__exec:notebook:notes:keep_open:(0|1) # ------------------------------------------------------------------- try: # ----------------------------------------------- if _CMD[0] == "notes": if _CMD[1] == "show": self.SHOW_NOTES( ); elif _CMD[1] == "hide": self.HIDE_NOTES( ); elif _CMD[1] == "keep_open": self.KEEP_OPEN = True if _CMD[2] == "1" else False; self.LOCAL_INFO_LOG( "notebook:notes:keep_open:"+_CMD[2] ); return; # ----------------------------------------------- if _CMD[0] == "cmd": pass; # ----------------------------------------------- except Exception as _err: self.LOCAL_ERROR_LOG( str(_CMD)+" | "+str(_err) ); # ------------------------------------------------------------------- # ======================================================================= def SHOW_NOTES( self ): # ------------------------------------------------------------------- try: """ out = ""; for _key in self.LAST_PAGE_REQUEST_HEADERS: _l = "-----------------------------------------------------------------------\n"; _l += '["'+_key+'"] => \n["'+self.LAST_PAGE_REQUEST_HEADERS[ _key ]+'"]'+"\n"; print( "L: "+_l ); out += _l; self.TEXT.setText( out ); """ self.show(); self.IS_OPEN = True; self.TEXT.setFocus( True ); except Exception as _err: self.LOCAL_ERROR_LOG( "'Can't show notes: "+str(_err) ); # ------------------------------------------------------------------- # ======================================================================= def HIDE_NOTES( self ): # ------------------------------------------------------------------- self.hide(); self.IS_OPEN = False; self.TEXT.clearFocus(); # ------------------------------------------------------------------- # ======================================================================= def UPDATE_FRAME(self): # ------------------------------------------------------------------- return; # ------------------------------------------------------------------- """ try: _style = ""; _conf = []; with open( "./ALPHA_FRAME.conf" ) as FS: _conf = FS.readline(); print(_conf ); _conf = _conf.split("|"); self.setGeometry( int(_conf[0]), int(_conf[1]), int(_conf[2]), int(_conf[3]) ); for _line in FS: _style += _line; self.setStyleSheet( _style ); except Exception as _err: print("ERROR: "+str(_err)); self.UPDATE_TIMER.singleShot( 1000, self.UPDATE_FRAME ); """ # ------------------------------------------------------------------- # ======================================================================= def LOAD(self): # ------------------------------------------------------------------- if self.DEBUG: pass; # ------------------------------------------------------------------- try: # --------------------------------------------------- self.PARENT.SPLASH.STATUS( self.LOG_TAG+": [LOAD]" ); self.PARENT.LOG_HANDLER.WRITE_LOG( "Doc-Browser: NOTEBOOK: LODE: "); self.TEXT.clear(); with open( self.NOTEBOOK_FILE, "r") as FS: for line in FS: self.TEXT.append(line.strip()); #self.TEXT.insertPlainText(line); #self.TEXT.insertHtml(line); self.PARENT.LOG_HANDLER.WRITE_LOG( "Doc-Browser: NOTEBOOK: LODE: Done"); # --------------------------------------------------- except Exception as _err: self.LOCAL_ERROR_LOG( "Can't load notes: "+str(_err) ); # ------------------------------------------------------------------- # ======================================================================= def SAVE(self): # ------------------------------------------------------------------- if self.DEBUG: pass; # ------------------------------------------------------------------- try: # --------------------------------------------------- self.PARENT.LOG_HANDLER.WRITE_LOG( "Doc-Browser: NOTEBOOK: SAVE: "); DATA = str(self.TEXT.toPlainText()).split("\n"); with open( self.NOTEBOOK_FILE, "w") as FS: for line in DATA: FS.write( line+"\n" ); self.PARENT.LOG_HANDLER.WRITE_LOG( "Doc-Browser: NOTEBOOK: SAVE: Done"); # --------------------------------------------------- except Exception as _err: self.LOCAL_ERROR_LOG( "Can't save notes: "+str(_err) ); # ------------------------------------------------------------------- # ======================================================================= def LOCAL_INFO_LOG( self, _msg, METHOD=None ): # ------------------------------------------------------------------- if METHOD is None: self.PARENT.LOCAL_INFO_LOG( "['"+self.LOG_TAG+"']: ["+_msg+"]" ); else: self.PARENT.LOCAL_INFO_LOG( "['"+self.LOG_TAG+"."+METHOD+"']: ["+_msg+"]" ); # ------------------------------------------------------------------- # ======================================================================= def LOCAL_ERROR_LOG( self, _msg, METHOD=None ): # ------------------------------------------------------------------- if self.DEBUG or self.PARENT.DEBUG_GLOBAL: self.PARENT.DEBUGGER.DEBUG(); # ------------------------------------------------------------------- if METHOD is None: self.PARENT.LOCAL_ERROR_LOG( "['"+self.LOG_TAG+"']: ["+_msg+"]" ); else: self.PARENT.LOCAL_ERROR_LOG( "['"+self.LOG_TAG+"."+METHOD+"']: ["+_msg+"]" ); # ------------------------------------------------------------------- # ======================================================================= def LOCAL_WARNING_LOG( self, _msg, METHOD=None ): # ------------------------------------------------------------------- if METHOD is None: self.PARENT.LOCAL_WARNING_LOG( "['"+self.LOG_TAG+"']: ["+_msg+"]" ); else: self.PARENT.LOCAL_WARNING_LOG( "['"+self.LOG_TAG+"."+METHOD+"']: ["+_msg+"]" );
class DownloaderWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.DownloadPath = os.path.expanduser("~") # get home dir self.pool = QThreadPool() self.pool.setMaxThreadCount(1) self.initVariables() self.resize(700, 400) self.initUI() self.line_downpath.setText(self.down_control.getDownloadPath()) def initVariables(self): self.down_control = DownloadController(self.addInfo) self.down_control.setDownloadPath(self.DownloadPath) self.chapters = None self.chapters_filtered = None self.ch_from = None self.ch_to = None def initUI(self): cw = QWidget() self.setCentralWidget(cw) layout_main = QVBoxLayout() layout_main.setSpacing(5) ## Info self.info = QTextEdit() self.info.setReadOnly(True) self.info.setLineWrapMode(QTextEdit.NoWrap) layout_main.addWidget(self.info, 1) ## Line edit layout_url = QHBoxLayout() layout_url.setSpacing(5) self.line_url = QLineEdit() layout_url.addWidget(QLabel('<b>Series URL:</b>')) layout_url.addWidget(self.line_url, 1) layout_main.addLayout(layout_url) ## Comboboxes layout_combo = QHBoxLayout() layout_combo.setSpacing(5) self.combo_from = QComboBox() self.combo_from.setEnabled(False) self.combo_to = QComboBox() self.combo_to.setEnabled(False) layout_combo.addWidget(QLabel('<b>Download chapters: </b>')) layout_combo.addWidget(QLabel(' From:')) layout_combo.addWidget(self.combo_from, 1) layout_combo.addWidget(QLabel('To:')) layout_combo.addWidget(self.combo_to, 1) layout_main.addLayout(layout_combo) ## Download path layout_downpath = QHBoxLayout() layout_downpath.setSpacing(5) self.line_downpath = QLineEdit() self.line_downpath.setEnabled(False) self.btn_downpath = QPushButton('Change') self.btn_downpath.pressed.connect(self.selectDownloadPath) layout_downpath.addWidget(QLabel('<b>Download path:</b>')) layout_downpath.addWidget(self.line_downpath, 1) layout_downpath.addWidget(self.btn_downpath) layout_main.addLayout(layout_downpath) ## Buttons layout_btn = QHBoxLayout() layout_btn.setSpacing(5) self.btn_getlist = QPushButton('Get List of Chapters') self.btn_getlist.pressed.connect(self.getChaptersList) self.btn_download = QPushButton('Download chapters') self.btn_download.pressed.connect(self.downloadChapters) self.btn_download.setEnabled(False) self.btn_exit = QPushButton('Exit') self.btn_exit.pressed.connect(self.close) layout_btn.addStretch() layout_btn.addWidget(self.btn_getlist) layout_btn.addWidget(self.btn_download) layout_btn.addWidget(self.btn_exit) layout_btn.addStretch() layout_main.addLayout(layout_btn) # status bar self.statusBar().showMessage('Ready') # add layout to main window cw.setLayout(layout_main) self.setWindowTitle('OMAD - Online MAnga Downloader') self.show() def closeEvent(self, event): """ Runs when user tryes to close main window. sys.exit(0) - to fix wierd bug, where process is not terminated. """ sys.exit(0) def addInfo(self, s='Testing printing...', exception=False, downloadProgress=False, trace=[]): logger.info(s+', '+str(exception)+', '+str(downloadProgress)+', '+str(trace)) if type(s)!=type("") and type(s)!=type(b"") and type(s) != type(QtCore.QString('')): s = str(s) if exception: s = "!!! Exception: "+s if downloadProgress: s = "Downloading progress: "+s self.setStatusBarText(s) self.info.append(s) if exception: for t in trace: self.info.append(str(t)) sb = self.info.verticalScrollBar() sb.setValue(sb.maximum()) QtCore.QCoreApplication.processEvents() def setStatusBarText(self, s='Testing...'): """ Changes status bar text """ self.statusBar().showMessage(s) QtCore.QCoreApplication.processEvents() def getChaptersList(self): self.addInfo('Getting list of chapters...') # reinit clean variables self.initVariables() # get series url url = str(self.line_url.text()).strip() if not self.down_control.setSeriesUrl(url): return # bad url self.chapters = self.down_control.getChaptersList() logger.debug('Setting up comboBoxes...') for i in range(0, self.combo_from.count()): self.combo_from.removeItem(0) for i in range(0, self.combo_to.count()): self.combo_to.removeItem(0) for c in self.chapters: self.combo_from.addItem(c[0]) self.combo_to.addItem(c[0]) self.combo_from.setCurrentIndex(0) self.combo_to.setCurrentIndex(len(self.chapters)-1) self.addInfo('Chapter list loaded') self.combo_from.setEnabled(True) self.combo_to.setEnabled(True) self.btn_download.setEnabled(True) def downloadChapters(self): self.addInfo('Checking chapter range') self.ch_from = self.combo_from.currentIndex() self.ch_to = self.combo_to.currentIndex() if self.ch_from>self.ch_to: self.addInfo('Bad range. Cant download backwards!') return else: self.addInfo('Range OK, starting download of '+str((self.ch_to-self.ch_from)+1)+' chapters...') self.gui_disable(True) worker = DownloadWorker(self.down_control, self.ch_from, self.ch_to) worker.signals.update.connect(self.addInfo) worker.signals.finished.connect(self.downloadChapters_finished) self.pool.start(worker) def downloadChapters_finished(self): self.gui_disable(False) self.setStatusBarText('Ready - Download Finished!!') # Finished self.addInfo('Download Finished!!') # Print failed downloads failed_chs = [] for i, r in enumerate(self.down_control.results): if r is False: failed_chs.append(self.chapters[i+self.ch_from]) if len(failed_chs)==0: self.addInfo('\nNo failed downloads') else: self.addInfo('\nChapters with failed downloads:') for c in failed_chs: self.addInfo(c[0]) self.addInfo('') def selectDownloadPath(self): downdir = self._get_dir(directory=self.DownloadPath) self.down_control.setDownloadPath(downdir) self.DownloadPath = self.down_control.getDownloadPath() self.line_downpath.setText(self.DownloadPath) def _get_dir(self, directory=''): """ Draw a dialog for directory selection. """ downdir = QFileDialog.getExistingDirectory( caption='Select Folder', options=QFileDialog.ShowDirsOnly, directory=directory ) if len(downdir) > 0: downdir = "%s" % (downdir) else: downdir = directory return downdir def gui_disable(self, downloading=True): self.line_url.setEnabled(not downloading) self.combo_from.setEnabled(not downloading) self.combo_to.setEnabled(not downloading) self.btn_getlist.setEnabled(not downloading) self.btn_download.setEnabled(not downloading) self.btn_downpath.setEnabled(not downloading)
def _set_add_rocon_master(self): print '_add_rocon_master' if self._connect_dlg_isValid: print "Dialog is live!!" self._connect_dlg.done(0) #dialog self._connect_dlg = QDialog(self._widget_main) self._connect_dlg.setWindowTitle("Add Ros Master") self._connect_dlg.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Ignored) self._connect_dlg.setMinimumSize(350, 0) # dlg_rect = self._connect_dlg.geometry() #dialog layout ver_layout = QVBoxLayout(self._connect_dlg) ver_layout.setContentsMargins(9, 9, 9, 9) #param layout text_grid_sub_widget = QWidget() text_grid_layout = QGridLayout(text_grid_sub_widget) text_grid_layout.setColumnStretch(1, 0) text_grid_layout.setRowStretch(2, 0) #param 1 title_widget1 = QLabel("MASTER_URI: ") context_widget1 = QTextEdit() context_widget1.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Ignored) context_widget1.setMinimumSize(0, 30) context_widget1.append(self.master_uri) #param 2 title_widget2 = QLabel("HOST_NAME: ") context_widget2 = QTextEdit() context_widget2.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Ignored) context_widget2.setMinimumSize(0, 30) context_widget2.append(self.host_name) #add param text_grid_layout.addWidget(title_widget1) text_grid_layout.addWidget(context_widget1) text_grid_layout.addWidget(title_widget2) text_grid_layout.addWidget(context_widget2) #add param layout ver_layout.addWidget(text_grid_sub_widget) #button layout button_hor_sub_widget = QWidget() button_hor_layout = QHBoxLayout(button_hor_sub_widget) params = {} params['param1'] = context_widget1 params['param2'] = context_widget2 #check box use_env_var_check = QCheckBox("Use environment variables") use_env_var_check.setCheckState(Qt.Unchecked) def set_use_env_var(data, text_widget1, text_widget2): if data == Qt.Unchecked: text_widget1.setText(self.master_uri) text_widget2.setText(self.host_name) elif data == Qt.Checked: self.master_uri = str(text_widget1.toPlainText()) self.host_name = str(text_widget2.toPlainText()) text_widget1.setText(self.env_master_uri) text_widget2.setText(self.env_host_name) def check_event(data): set_use_env_var(data, context_widget1, context_widget2) use_env_var_check.stateChanged.connect(check_event) ver_layout.addWidget(use_env_var_check) #button btn_call = QPushButton("Add") btn_cancel = QPushButton("Cancel") btn_call.clicked.connect(lambda: self._connect_dlg.done(0)) btn_call.clicked.connect(lambda: self._add_rocon_master(params)) btn_cancel.clicked.connect(lambda: self._connect_dlg.done(0)) #add button button_hor_layout.addWidget(btn_call) button_hor_layout.addWidget(btn_cancel) #add button layout ver_layout.addWidget(button_hor_sub_widget) self._connect_dlg.setVisible(True) self._connect_dlg.finished.connect(self._destroy_connect_dlg) self._connect_dlg_isValid = True
class MyWidget(QWidget): def __init__(self): super(MyWidget, self).__init__() self.i = 0 self.setup_window() t = threading.Thread(target=self.setup_networking) t.start() def setup_window(self): self.setWindowTitle("Chat app") self.setGeometry(100, 100, 400, 300) self.layout = QVBoxLayout(self) self.setLayout(self.layout) self.label = QLabel(self) self.textbox = QLineEdit(self) self.textbox.setReadOnly(True) self.layout2 = QHBoxLayout(self) self.chathistory = QTextEdit(self) self.chathistory.setReadOnly(True) self.widget2 = QWidget() self.widget2.setLayout(self.layout2) self.layout.addWidget(self.textbox) self.layout.addWidget(self.chathistory) self.layout2.addWidget(self.label) self.layout.addWidget(self.widget2) #first it'll try to be client and fail. So it will be server. Next time it'll be client # # t3=threading.Thread(target=self.be_client) # t3.start() # t4=threading.Thread(target=self.be_server) # t4.start() def setup_networking(self): try: self.be_client() except: print "unable to connect as client, opening server mode:\n" self.be_server() self.textbox.setReadOnly(False) t2 = threading.Thread(target=self.recv_message) t2.start() self.textbox.returnPressed.connect( self.send_message) #if they press enter, then call send_message fn # self.isclosed = False #doesnt work def be_client(self): host = '127.0.0.1' port = 5000 self.s = socket.socket() print "client socket opened" self.i = t(self.i, True) self.s.connect((host, port)) self.label.setText("<connected>") def be_server(self): host = '127.0.0.1' port = 5000 self.ss = socket.socket() print "temp sock open" self.i = t(self.i, True) self.ss.bind((host, port)) self.ss.listen(1) self.label.setText("<waiting to be connected>") self.s, self.address = self.ss.accept( ) #address is ip address of what tries to connect self.ss.close() print "temp client socket closed" self.i = t(self.i, False) self.label.setText("<connected>") def send_message(self): message = self.textbox.text() if message != "": self.chathistory.append("Sent: " + str(message)) self.s.send(message) self.textbox.clear() else: t2 = threading.Thread(target=self.recv_message) t2.start() sys.stdout.flush() def loner(self): self.label.setText("<Connection Lost>") print "socket closed" self.s.close() self.i = t(self.i, False) print "^should be zero" self.textbox.setReadOnly(True) self.be_server() self.textbox.setReadOnly(False) t2 = threading.Thread(target=self.recv_message) t2.start() def recv_message(self): # try: #so it doesn't keep saying socket.timeout on console if 1 == 1: data = self.s.recv(1024) # print self.isclosed # if self.isclosed is True: #gonna send a blank message when u close window # self.label.setText("<connection closed>") # print "got here" if data == "<close command>": print "Cmnd received" self.loner() # self.label.setText("<Connection Lost>") # print "socket closed" # self.i = t(self.i, False) # print "^should be zero" # self.s.close() # self.textbox.setReadOnly(True) # self.setup_networking() else: self.chathistory.append("Recieved: " + str(data)) sys.stdout.flush() # except socket.timeout: #we dont want it to keep saying it on the console # pass # except socket.error: #when it closes, need to make a new socket # self.s = socket.socket() def closeEvent(self, e): self.s.send("<close command>") print "cmd sent" print "closed window" #self.isclosed=True print "socket closed" self.i = t(self.i, False) print "^ should be zero" self.s.close()