def __init__(self): super(STM32FProgrammerDialog, self).__init__(CWMainGUI.getInstance()) # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint) self.stm32f = STM32FProgrammer() self.setWindowTitle("Serial STM32F Programmer") layout = QVBoxLayout() layoutFW = QHBoxLayout() self.flashLocation = QtFixes.QLineEdit() flashFileButton = QPushButton("Find") flashFileButton.clicked.connect(self.findFlash) layoutFW.addWidget(QLabel("FLASH File")) layoutFW.addWidget(self.flashLocation) layoutFW.addWidget(flashFileButton) layout.addLayout(layoutFW) self.flashLocation.setText(QSettings().value("stm32f-flash-location")) # Add buttons readSigBut = QPushButton("Check Signature") readSigBut.clicked.connect(self.readSignature) verifyFlashBut = QPushButton("Verify FLASH") verifyFlashBut.clicked.connect(self.verifyFlash) verifyFlashBut.setEnabled(False) progFlashBut = QPushButton("Erase/Program/Verify FLASH") progFlashBut.clicked.connect(self.writeFlash) layoutBut = QHBoxLayout() layoutBut.addWidget(readSigBut) layoutBut.addWidget(verifyFlashBut) layoutBut.addWidget(progFlashBut) layout.addLayout(layoutBut) layoutsetting = QHBoxLayout() mode = QComboBox() mode.addItem("fast", False) mode.addItem("slow", True) mode.currentIndexChanged.connect(self.modechanged) layoutsetting.addWidget(QLabel("Speed:")) layoutsetting.addWidget(mode) blocksize = QComboBox() blocksize.addItem("256", False) blocksize.addItem("64", True) blocksize.currentIndexChanged.connect(self.blocksizechanged) layoutsetting.addStretch() layoutsetting.addWidget(QLabel("Read Block Size:")) layoutsetting.addWidget(blocksize) layout.addLayout(layoutsetting) # Add status stuff self.statusLine = QPlainTextEdit() self.statusLine.setReadOnly(True) # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10) self.stm32f.newTextLog.connect(self.append) layout.addWidget(self.statusLine) # Set dialog layout self.setLayout(layout)
def __init__(self, *args, **kwrgs): existing_widgets = Window.mayaWin.findChildren(QDialog, Window.objectName) if existing_widgets: map(lambda x: x.deleteLater(), existing_widgets) super(Window, self).__init__(*args, **kwrgs) self.installEventFilter(self) self.setObjectName(Window.objectName) self.setWindowTitle(Window.title) mainLayout = QVBoxLayout(self) w_rendererSelect = Widget_chooseRenderer() w_resolusion = Widget_resolusion() optimizer = QFrame() optimizer.setFrameShape(QFrame.HLine) button_sep = QPushButton("SEPARATE") listWidget = QListWidget() listWidget.setSelectionMode(QAbstractItemView.ExtendedSelection) button_convert = QPushButton("CONVERT TO LAMBERT") button_convert.setEnabled(False) mainLayout.addWidget(w_rendererSelect) mainLayout.addWidget(w_resolusion) mainLayout.addWidget(button_sep) mainLayout.addWidget(listWidget) mainLayout.addWidget(button_convert) self.resize(Window.defaultWidth, Window.defaultHeight) self.load_shapeInfo(Window.path_uiInfo) self.w_rendererSelect = w_rendererSelect self.w_resolusion = w_resolusion self.listWidget = listWidget self.button_convert = button_convert QtCore.QObject.connect(button_sep, QtCore.SIGNAL("clicked()"), self.separate) QtCore.QObject.connect(button_convert, QtCore.SIGNAL("clicked()"), self.convert) QtCore.QObject.connect(listWidget, QtCore.SIGNAL("itemSelectionChanged()"), self.selectShader) try: Cmds_mainCommands.get_csv_form_google_spreadsheets( Window.shaderAttr_url, Window.shaderAttr_csv) except: pass self.dict_shaderAttr = Cmds_mainCommands.get_dictdata_from_csvPath( Window.shaderAttr_csv) try: Cmds_mainCommands.get_csv_form_google_spreadsheets( Window.removeTarget_url, Window.removeTarget_csv) except: pass self.dict_removeTargets = Cmds_mainCommands.get_dictdata_from_csvPath( Window.removeTarget_csv)
class PluginDialog(QWidget): def __init__(self, pluginManager): super(PluginDialog, self).__init__() self.view = PluginView(pluginManager, self) self.vbLayout = QVBoxLayout(self) self.vbLayout.setContentsMargins(0, 0, 0, 0) self.vbLayout.setSpacing(0) self.vbLayout.addWidget(self.view) self.hbLayout = QHBoxLayout() self.vbLayout.addLayout(self.hbLayout) self.hbLayout.setContentsMargins(0, 0, 0, 0) self.hbLayout.setSpacing(6) self.detailsButton = QPushButton("Details", self) self.errorDetailsButton = QPushButton("Error Details", self) self.detailsButton.setEnabled(False) self.errorDetailsButton.setEnabled(False) self.hbLayout.addWidget(self.detailsButton) self.hbLayout.addWidget(self.errorDetailsButton) self.hbLayout.addStretch(5) self.resize(650, 300) self.setWindowTitle("Installed Plugins") self.view.currentPluginChanged.connect(self.updateButtons) self.view.pluginActivated.connect(self.openDetails) self.detailsButton.clicked.connect(self.openDetails) self.errorDetailsButton.clicked.connect(self.openErrorDetails) @Slot() def updateButtons(self): # todo pass @Slot() def openDetails(self): # todo pass @Slot() def openDetails(self, spec): # todo print("TODO open details") pass @Slot() def openErrorDetails(self): # todo pass
def createWidgets(self): self.listWidget = QListWidget() self.buttonLayout = QVBoxLayout() self.linkButton = None for icon, text, slot, tip in ((":/add.svg", "&Add", self.add, """\ <p><b>Add</b> (Alt+A)</p><p>Add a new Normal Group.</p>"""), (":/edit.svg", "&Rename", self.rename, """\ <p><b>Rename</b> (Alt+R)</p><p>Rename the current Group.</p>"""), (":/grouplink.svg", "&Link", self.link, """\ <p><b>Link</b> (Alt+L)</p><p>Change the current group into a Linked Group.</p> <p>This means that the pages of every entry in this group will be merged and synchronized, and any future changes to the pages of any entries in this group will be propagated to all the other entries in this group to keep them all synchronized.</p>"""), (":/groups.svg", "&Unlink", self.unlink, """\ <p><b>Unlink</b> (Alt+U)</p><p>Change the current group into a Normal (unlinked) Group. If the linked group has entries, the <b>Delete Linked Group</b> dialog will pop up.</p>"""), (":/groupset.svg", "&View", self.viewGroup, """\ <p><b>View</b> (Alt+V)</p><p>View the current group in the Filtered View.</p>"""), (":/delete.svg", "&Delete", self.delete, """\ <p><b>Delete</b> (Alt+D)</p><p>Remove entries from the current normal group and then delete the group. If the current group is a linked group that has entries, the <b>Delete Linked Group</b> dialog will pop up.</p>"""), (":/help.svg", "Help", self.help, """\ Help on the Groups dialog"""), (":/dialog-close.svg", "&Close", self.accept, """\ <p><b>Close</b></p><p>Close the dialog.</p>""")): button = QPushButton(QIcon(icon), text) button.setFocusPolicy(Qt.NoFocus) if text in {"&Close", "Help"}: self.buttonLayout.addStretch() else: self.buttons.append(button) self.buttonLayout.addWidget(button) button.clicked.connect(slot) self.tooltips.append((button, tip)) if text == "&Link": self.linkButton = button button.setEnabled(False) elif text == "&Unlink": self.unlinkButton = button button.setEnabled(False) self.tooltips.append((self.listWidget, "List of Groups"))
def __init__(self): super(XMEGAProgrammerDialog, self).__init__(CWMainGUI.getInstance()) # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint) self.xmega = XMEGAProgrammer() self.setWindowTitle("ChipWhisperer-Lite XMEGA Programmer") layout = QVBoxLayout() layoutFW = QHBoxLayout() self.flashLocation = QtFixes.QLineEdit() flashFileButton = QPushButton("Find") flashFileButton.clicked.connect(self.findFlash) layoutFW.addWidget(QLabel("FLASH File")) layoutFW.addWidget(self.flashLocation) layoutFW.addWidget(flashFileButton) layout.addLayout(layoutFW) self.flashLocation.setText(QSettings().value("xmega-flash-location")) # Add buttons readSigBut = QPushButton("Check Signature") readSigBut.clicked.connect(self.readSignature) verifyFlashBut = QPushButton("Verify FLASH") verifyFlashBut.clicked.connect(self.verifyFlash) verifyFlashBut.setEnabled(False) progFlashBut = QPushButton("Erase/Program/Verify FLASH") progFlashBut.clicked.connect(self.writeFlash) layoutBut = QHBoxLayout() layoutBut.addWidget(readSigBut) layoutBut.addWidget(verifyFlashBut) layoutBut.addWidget(progFlashBut) layout.addLayout(layoutBut) # Add status stuff self.statusLine = QPlainTextEdit() self.statusLine.setReadOnly(True) # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10) self.statusLine.append = self.statusLine.appendPlainText layout.addWidget(self.statusLine) self.xmega._logging = self.statusLine.append # Set dialog layout self.setLayout(layout)
def __init__(self): super(XMEGAProgrammerDialog, self).__init__(CWMainGUI.getInstance()) # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint) self.xmega = XMEGAProgrammer() self.setWindowTitle("ChipWhisperer-Lite XMEGA Programmer") layout = QVBoxLayout() layoutFW = QHBoxLayout() self.flashLocation = QtFixes.QLineEdit() flashFileButton = QPushButton("Find") flashFileButton.clicked.connect(self.findFlash) layoutFW.addWidget(QLabel("FLASH File")) layoutFW.addWidget(self.flashLocation) layoutFW.addWidget(flashFileButton) layout.addLayout(layoutFW) self.flashLocation.setText(QSettings().value("xmega-flash-location")) # Add buttons readSigBut = QPushButton("Check Signature") readSigBut.clicked.connect(self.readSignature) verifyFlashBut = QPushButton("Verify FLASH") verifyFlashBut.clicked.connect(self.verifyFlash) verifyFlashBut.setEnabled(False) progFlashBut = QPushButton("Erase/Program/Verify FLASH") progFlashBut.clicked.connect(self.writeFlash) layoutBut = QHBoxLayout() layoutBut.addWidget(readSigBut) layoutBut.addWidget(verifyFlashBut) layoutBut.addWidget(progFlashBut) layout.addLayout(layoutBut) # Add status stuff self.statusLine = QPlainTextEdit() self.statusLine.setReadOnly(True) # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10) self.xmega.newTextLog.connect(self.append) layout.addWidget(self.statusLine) # Set dialog layout self.setLayout(layout)
class LoggingArea(QWidget): def __init__(self, parent=None): super(LoggingArea, self).__init__() self.layout = QVBoxLayout(self) self.hbox_buttons_top = QHBoxLayout(self) self.button_start = QPushButton('Start Logging', self) self.button_start.clicked.connect(parent._start_logging) self.hbox_buttons_top.addWidget(self.button_start) self.button_stop = QPushButton('Stop Logging', self) self.button_stop.clicked.connect(parent._stop_logging) self.hbox_buttons_top.addWidget(self.button_stop) self.layout.addLayout(self.hbox_buttons_top) self.te_logging = QTextEdit(self) self.layout.addWidget(self.te_logging) self.hbox_buttons_bottom = QHBoxLayout(self) self.button_clear = QPushButton('Clear Data', self) self.button_clear.clicked.connect(self._clear_data) self.hbox_buttons_bottom.addWidget(self.button_clear) self.button_clipboard = QPushButton('Copy to Clipboard', self) self.button_clipboard.clicked.connect(self._copy_to_cliboard) self.hbox_buttons_bottom.addWidget(self.button_clipboard) self.button_file = QPushButton('Save to CSV', self) self.button_file.clicked.connect(self._save_to_csv) self.button_file.setEnabled(False) self.hbox_buttons_bottom.addWidget(self.button_file) self.layout.addLayout(self.hbox_buttons_bottom) self.setLayout(self.layout) def _clear_data(self): self.te_logging.clear() def _copy_to_cliboard(self): self.te_logging.selectAll() self.te_logging.copy() def _save_to_csv(self): print('Save to csv')
def _init_widgets(self): # name label name_label = QLabel(self) name_label.setText('New name') name_box = LabelNameBox(self._on_name_changed, self) if self._label_addr in self._disasm_view.disasm.kb.labels: name_box.setText(self._disasm_view.disasm.kb.labels[self._label_addr]) name_box.selectAll() self._name_box = name_box label_layout = QHBoxLayout() label_layout.addWidget(name_label) label_layout.addWidget(name_box) self.main_layout.addLayout(label_layout) # status label status_label = QLabel(self) self.main_layout.addWidget(status_label) self._status_label = status_label # buttons ok_button = QPushButton(self) ok_button.setText('OK') ok_button.setEnabled(False) ok_button.clicked.connect(self._on_ok_clicked) self._ok_button = ok_button cancel_button = QPushButton(self) cancel_button.setText('Cancel') cancel_button.clicked.connect(self._on_cancel_clicked) buttons_layout = QHBoxLayout() buttons_layout.addWidget(ok_button) buttons_layout.addWidget(cancel_button) self.main_layout.addLayout(buttons_layout)
def _init_widgets(self): # address label address_label = QLabel(self) address_label.setText('Address') address = QAddressInput(self._on_address_changed, parent=self) self._address_box = address address_layout = QHBoxLayout() address_layout.addWidget(address_label) address_layout.addWidget(address) self.main_layout.addLayout(address_layout) # status label status_label = QLabel(self) self.main_layout.addWidget(status_label) self._status_label = status_label # buttons ok_button = QPushButton(self) ok_button.setText('OK') ok_button.setEnabled(False) ok_button.clicked.connect(self._on_ok_clicked) self._ok_button = ok_button cancel_button = QPushButton(self) cancel_button.setText('Cancel') cancel_button.clicked.connect(self._on_cancel_clicked) buttons_layout = QHBoxLayout() buttons_layout.addWidget(ok_button) buttons_layout.addWidget(cancel_button) self.main_layout.addLayout(buttons_layout)
def __init__(self): super(AVRProgrammerDialog, self).__init__(CWMainGUI.getInstance()) # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint) self.avr = AVRProgrammer() self.setWindowTitle("ChipWhisperer-Lite AVR Programmer") layout = QVBoxLayout() layoutFW = QHBoxLayout() self.flashLocation = QtFixes.QLineEdit() flashFileButton = QPushButton("Find") flashFileButton.clicked.connect(self.findFlash) layoutFW.addWidget(QLabel("FLASH File")) layoutFW.addWidget(self.flashLocation) layoutFW.addWidget(flashFileButton) layout.addLayout(layoutFW) self.flashLocation.setText(QSettings().value("avr-flash-location")) # Add buttons readSigBut = QPushButton("Check Signature") readSigBut.clicked.connect(self.readSignature) verifyFlashBut = QPushButton("Verify FLASH") verifyFlashBut.clicked.connect(self.verifyFlash) verifyFlashBut.setEnabled(False) progFlashBut = QPushButton("Erase/Program/Verify FLASH") progFlashBut.clicked.connect(self.writeFlash) layoutBut = QHBoxLayout() layoutBut.addWidget(readSigBut) layoutBut.addWidget(verifyFlashBut) layoutBut.addWidget(progFlashBut) layout.addLayout(layoutBut) layoutFuse = QHBoxLayout() readFuseBut = QPushButton("Read Fuses") readFuseBut.clicked.connect(self.readFuses) writeFuseBut = QPushButton("Write Fuses") writeFuseBut.clicked.connect(self.writeFuses) self.lowfuseLine = QtFixes.QLineEdit("?") self.lowfuseLine.setMaxLength(2) self.lowfuseLine.setFixedWidth(25) self.highfuseLine = QtFixes.QLineEdit("?") self.highfuseLine.setMaxLength(2) self.highfuseLine.setFixedWidth(25) self.extfuseLine = QtFixes.QLineEdit("?") self.extfuseLine.setMaxLength(2) self.extfuseLine.setFixedWidth(25) # Don't allow use to change these fuses self.highfuseLine.setReadOnly(True) self.extfuseLine.setReadOnly(True) layoutFuse.addWidget(readFuseBut) layoutFuse.addWidget(QLabel("LOW:")) layoutFuse.addWidget(self.lowfuseLine) layoutFuse.addWidget(QLabel("HIGH:")) layoutFuse.addWidget(self.highfuseLine) layoutFuse.addWidget(QLabel("EXT:")) layoutFuse.addWidget(self.extfuseLine) layoutFuse.addWidget(writeFuseBut) layout.addLayout(layoutFuse) layoutExtra = QHBoxLayout() self.clockMode = QPushButton("Enable Slow Clock Mode") self.clockMode.setCheckable(True) self.clockMode.clicked.connect(self.toggleSlowClock) layoutExtra.addWidget(self.clockMode) layoutExtra.addStretch() layout.addLayout(layoutExtra) # Add status stuff self.statusLine = QPlainTextEdit() self.statusLine.setReadOnly(True) # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10) self.statusLine.append = self.statusLine.appendPlainText layout.addWidget(self.statusLine) self.avr._logging = self.statusLine.append # Set dialog layout self.setLayout(layout)
class Form(QDialog): def __init__(self, state, parent=None): super().__init__(parent) Lib.prepareModalDialog(self) self.state = state self.setWindowTitle("New Empty Copy — {}".format( QApplication.applicationName())) self.createWidgets() self.layoutWidgets() self.createConnections() self.updateUi() settings = QSettings() self.updateToolTips( bool( int( settings.value(Gopt.Key.ShowDialogToolTips, Gopt.Default.ShowDialogToolTips)))) def createWidgets(self): self.filenameLabelLabel = QLabel("New Filename") self.filenameLabel = QLabel() self.filenameLabel.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) self.filenameButton = QPushButton("C&hoose...") self.tooltips.append((self.filenameButton, """\ <p><b>Choose</b></p> <p>Choose the {} <tt>.xix</tt> file to copy the current index's options, spelling words, etc., to.</p>""".format(QApplication.applicationName()))) self.copyGroupBox = QGroupBox("Copy") self.configCheckBox = QCheckBox("&Options") self.tooltips.append((self.configCheckBox, """\ <p><b>Options</b></p> <p>If checked, copy all the current index's option and output option settings (language, sort as and page range rules, display preferences, fonts, output style, etc.) to the new empty copy.</p>""")) self.spellWordsCheckBox = QCheckBox("&Spelling Words") self.tooltips.append((self.spellWordsCheckBox, """\ <p><b>Spelling Words</b></p> <p>If checked, copy all the current index's spelling words to the new empty copy.</p>""")) self.ignoredFirstWordsCheckBox = QCheckBox( "&Ignored Subentry Function Words") self.tooltips.append((self.ignoredFirstWordsCheckBox, """\ <p><b>Ignored Subentry Function Words</b></p> <p>If checked, copy all the current index's ignored subentry function words words to the new empty copy.</p>""")) self.customMarkupCheckBox = QCheckBox("Custom &Markup") self.tooltips.append((self.customMarkupCheckBox, """\ <p><b>Custom Markup</b></p> <p>If checked, copy all the current index's custom markup to the new empty copy.</p>""")) self.groupsCheckBox = QCheckBox("&Groups") self.tooltips.append((self.groupsCheckBox, """\ <p><b>Groups</b></p> <p>If checked, copy all the current index's groups to the new empty copy.</p>""")) self.autoReplaceCheckBox = QCheckBox("&Auto Replacements") self.tooltips.append((self.autoReplaceCheckBox, """\ <p><b>Auto Replacements</b></p> <p>If checked, copy all the current index's auto replacements to the new empty copy.</p>""")) for checkbox in (self.configCheckBox, self.spellWordsCheckBox, self.ignoredFirstWordsCheckBox, self.customMarkupCheckBox, self.groupsCheckBox, self.autoReplaceCheckBox): checkbox.setChecked(True) self.helpButton = QPushButton(QIcon(":/help.svg"), "Help") self.tooltips.append( (self.helpButton, "Help on the New Empty Copy dialog")) self.newCopyButton = QPushButton(QIcon(":/document-new.svg"), "&New Empty Copy") self.tooltips.append((self.newCopyButton, """\ <p><b>New Empty Copy</b></p> <p>Create a new empty index and copy the options, spelling words, etc.—providing they have been checked—into the new index.</p>""")) self.cancelButton = QPushButton(QIcon(":/dialog-close.svg"), "&Cancel") self.tooltips.append((self.cancelButton, """<p><b>Cancel</b></p> <p>Close the dialog without making a new empty copy.</p>""")) def layoutWidgets(self): layout = QVBoxLayout() hbox = QHBoxLayout() hbox.addWidget(self.filenameLabelLabel) hbox.addWidget(self.filenameLabel, 1) hbox.addWidget(self.filenameButton) layout.addLayout(hbox) grid = QGridLayout() grid.addWidget(self.configCheckBox, 0, 0) grid.addWidget(self.autoReplaceCheckBox, 0, 1) grid.addWidget(self.spellWordsCheckBox, 1, 0) grid.addWidget(self.ignoredFirstWordsCheckBox, 1, 1) grid.addWidget(self.groupsCheckBox, 2, 0) grid.addWidget(self.customMarkupCheckBox, 2, 1) hbox = QHBoxLayout() hbox.addLayout(grid) hbox.addStretch() self.copyGroupBox.setLayout(hbox) layout.addWidget(self.copyGroupBox) layout.addStretch() buttonBox = QDialogButtonBox() buttonBox.addButton(self.newCopyButton, QDialogButtonBox.AcceptRole) buttonBox.addButton(self.cancelButton, QDialogButtonBox.RejectRole) buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole) layout.addWidget(buttonBox) self.setLayout(layout) def createConnections(self): self.newCopyButton.clicked.connect(self.accept) self.cancelButton.clicked.connect(self.reject) self.helpButton.clicked.connect(self.help) self.filenameButton.clicked.connect(self.setFilename) def updateUi(self): filename = self.filenameLabel.text() self.newCopyButton.setEnabled( bool(filename) and filename != os.path.normpath(self.state.model.filename)) def setFilename(self): # No need to restore focus widget with Lib.Qt.DisableUI(self, forModalDialog=True): filename, _ = QFileDialog.getSaveFileName( self, "New Empty Index — {}".format(QApplication.applicationName()), self.state.indexPath, "{} index (*{})".format(QApplication.applicationName(), EXTENSION)) if filename and not filename.casefold().endswith(EXTENSION): filename += EXTENSION if filename: self.state.indexPath = os.path.dirname(filename) self.filenameLabel.setText(os.path.normpath(filename)) self.updateUi() def help(self): self.state.help("xix_ref_dlg_newcopy.html") def accept(self): settings = QSettings() language = LanguageKind( settings.value(Gopt.Key.Language, Gopt.Default.Language)) if self.configCheckBox.isChecked(): sortasrules = Gopt.Default.SortAsRules pagerangerules = Gopt.Default.PageRangeRules else: sortasrules = self.state.model.sortAsRules() pagerangerules = self.state.model.pageRangeRules() copyInfo = CopyInfo(self.state.model.filename, self.filenameLabel.text(), self.configCheckBox.isChecked(), self.customMarkupCheckBox.isChecked(), self.spellWordsCheckBox.isChecked(), self.ignoredFirstWordsCheckBox.isChecked(), self.autoReplaceCheckBox.isChecked(), self.groupsCheckBox.isChecked(), self.state.model.username, language, sortasrules, pagerangerules) self.state.window.closeXix() self.state.model.copyEmpty(copyInfo) self.state.window.openXix(copyInfo.newname) self.state.entryPanel.clearForm() self.state.setMode(ModeKind.VIEW) super().accept()
class ServiceBrowser(QWidget): def __init__(self, parent = None): QWidget.__init__(self, parent) self.serviceManager = QServiceManager(self) self.registerExampleServices() self.initWidgets() self.reloadServicesList() self.setWindowTitle(self.tr("Services Browser")) def __del__(self): self.unregisterExampleServices() def currentInterfaceImplChanged(self, current, previous): if not current: return descriptor = current.data(Qt.UserRole) self.reloadAttributesList() self.reloadAttributesRadioButtonText() if descriptor.isValid(): self.defaultInterfaceButton.setText(self.tr("Set as default implementation for %s" % str(descriptor.interfaceName()))) self.defaultInterfaceButton.setEnabled(True) def reloadServicesList(self): self.servicesListWidget.clear() services = self.serviceManager.findServices() for serv in services: self.servicesListWidget.addItem(serv) self.servicesListWidget.addItem(self.showAllServicesItem) self._services = services def reloadInterfaceImplementationsList(self): serviceName = None allServices = self.servicesListWidget.currentItem().text() == self.showAllServicesItem.text() if self.servicesListWidget.currentItem() and not allServices: serviceName = self.servicesListWidget.currentItem().text() self.interfacesGroup.setTitle(self.tr("Interfaces implemented by %s" % str(serviceName))) else: self.interfacesGroup.setTitle(self.tr("All interface implementations")) descriptors = self.serviceManager.findInterfaces(serviceName) self.attributesListWidget.clear() self.interfacesListWidget.clear() self._i = [] for desc in descriptors: text = "%s %d.%d" % (desc.interfaceName(), desc.majorVersion(), desc.minorVersion()) if not serviceName: text += " (" + desc.serviceName() + ")" defaultInterfaceImpl = self.serviceManager.interfaceDefault(desc.interfaceName()) if desc == defaultInterfaceImpl: text += self.tr(" (default)") item = QListWidgetItem(text) item.setData(Qt.UserRole, desc) item._data = desc self.interfacesListWidget.addItem(item) self.defaultInterfaceButton.setEnabled(False) def reloadAttributesList(self): item = self.interfacesListWidget.currentItem() if not item: return selectedImpl = item.data(Qt.UserRole) implementationRef = None if self.selectedImplRadioButton.isChecked(): implementationRef = self.serviceManager.loadInterface(selectedImpl) else: implementationRef = self.serviceManager.loadInterface(selectedImpl.interfaceName()) self.attributesListWidget.clear() if not implementationRef: self.attributesListWidget.addItem(self.tr("(Error loading service plugin)")) return metaObject = implementationRef.metaObject() self.attributesGroup.setTitle(self.tr("Invokable attributes for %s class" % metaObject.className())) for i in range(metaObject.methodCount()): method = metaObject.method(i) self.attributesListWidget.addItem("[METHOD] " + method.signature()) for i in range(metaObject.propertyCount()): p = metaObject.property(i) self.attributesListWidget.addItem("[PROPERTY] " + p.name()) def setDefaultInterfaceImplementation(self): item = self.interfacesListWidget.currentItem() if not item: return descriptor = item.data(Qt.UserRole) if descriptor.isValid(): if self.serviceManager.setInterfaceDefault(descriptor): currentIndex = self.interfacesListWidget.row(item) self.reloadInterfaceImplementationsList() self.interfacesListWidget.setCurrentRow(currentIndex) else: print "Unable to set default service for interface:", descriptor.interfaceName() def registerExampleServices(self): exampleXmlFiles = ["filemanagerservice.xml", "bluetoothtransferservice.xml"] for fileName in exampleXmlFiles: path = "./xmldata/" + fileName self.serviceManager.addService(path) def unregisterExampleServices(self): self.serviceManager.removeService("FileManagerService") self.serviceManager.removeService("BluetoothTransferService") def reloadAttributesRadioButtonText(self): item = self.interfacesListWidget.currentItem() if not item: return selectedImpl = item.data(Qt.UserRole) defaultImpl = self.serviceManager.interfaceDefault(selectedImpl.interfaceName()) self.defaultImplRadioButton.setText(self.tr("Default implementation for %s\n(currently provided by %s)" % (str(defaultImpl.interfaceName()), str(defaultImpl.serviceName())))) def initWidgets(self): self.showAllServicesItem = QListWidgetItem(self.tr("(All registered services)")) self.servicesListWidget = QListWidget() self.interfacesListWidget = QListWidget() self.interfacesListWidget.addItem(self.tr("(Select a service)")) self.attributesListWidget = QListWidget() self.attributesListWidget.addItem(self.tr("(Select an interface implementation)")) self.interfacesListWidget.setMinimumWidth(450) self.servicesListWidget.currentItemChanged.connect(self.reloadInterfaceImplementationsList) self.interfacesListWidget.currentItemChanged.connect(self.currentInterfaceImplChanged) self.defaultInterfaceButton = QPushButton(self.tr("Set as default implementation")) self.defaultInterfaceButton.setEnabled(False) self.defaultInterfaceButton.clicked.connect(self.setDefaultInterfaceImplementation) self.selectedImplRadioButton = QRadioButton(self.tr("Selected interface implementation")) self.defaultImplRadioButton = QRadioButton(self.tr("Default implementation")) self.selectedImplRadioButton.setChecked(True) self.radioButtons = QButtonGroup(self) self.radioButtons.addButton(self.selectedImplRadioButton) self.radioButtons.addButton(self.defaultImplRadioButton) self.radioButtons.buttonClicked.connect(self.reloadAttributesList) self.servicesGroup = QGroupBox(self.tr("Show services for:")) servicesLayout = QVBoxLayout() servicesLayout.addWidget(self.servicesListWidget) self.servicesGroup.setLayout(servicesLayout) self.interfacesGroup = QGroupBox(self.tr("Interface implementations")) interfacesLayout = QVBoxLayout() interfacesLayout.addWidget(self.interfacesListWidget) interfacesLayout.addWidget(self.defaultInterfaceButton) self.interfacesGroup.setLayout(interfacesLayout) self.attributesGroup = QGroupBox(self.tr("Invokable attributes")) attributesLayout = QVBoxLayout() self.attributesGroup.setLayout(attributesLayout) attributesLayout.addWidget(self.attributesListWidget) attributesLayout.addWidget(QLabel(self.tr("Show attributes for:"))) attributesLayout.addWidget(self.selectedImplRadioButton) attributesLayout.addWidget(self.defaultImplRadioButton) self.attributesGroup.setLayout(attributesLayout) layout = QGridLayout() layout.addWidget(self.servicesGroup, 0, 0) layout.addWidget(self.attributesGroup, 0, 1, 2, 1) layout.addWidget(self.interfacesGroup, 1, 0) self.setLayout(layout)
def __init__(self, *args, **kwargs): QMainWindow.__init__(self, *args, **kwargs) self.installEventFilter(self) #self.setWindowFlags( QtCore.Qt.Drawer ) self.setWindowTitle(Window_global.title) verticalSplitter = QSplitter(QtCore.Qt.Vertical) self.setCentralWidget(verticalSplitter) horizonSplitter1 = QSplitter(QtCore.Qt.Horizontal) horizonSplitter2 = QSplitter(QtCore.Qt.Horizontal) verticalSplitter.addWidget(horizonSplitter1) verticalSplitter.addWidget(horizonSplitter2) widgetSelArea = QWidget() layoutSelArea = QVBoxLayout(widgetSelArea) labelSelTextList = QLabel('Images from Selection') selTextureList = QListWidget() selTextureList.setSelectionMode(QAbstractItemView.ExtendedSelection) layoutSelArea.addWidget(labelSelTextList) layoutSelArea.addWidget(selTextureList) imageBaseSelArea = ImageBase() horizonSplitter1.addWidget(widgetSelArea) horizonSplitter1.addWidget(imageBaseSelArea) widgetPathArea = QWidget() layoutPathArea = QVBoxLayout(widgetPathArea) layoutAddTab = QHBoxLayout() removeTabButton = QPushButton('Remove Tab') addTabButton = QPushButton('Add Tab') self.tabWidget = Tab() buttonLayout = QHBoxLayout() getImageButton = QPushButton('Get Image') removeImageButton = QPushButton('Remove Image') layoutPathArea.addLayout(layoutAddTab) layoutPathArea.addWidget(self.tabWidget) layoutPathArea.addLayout(buttonLayout) imageBasePathArea = ImageBase() layoutAddTab.addWidget(removeTabButton) layoutAddTab.addWidget(addTabButton) buttonLayout.addWidget(getImageButton) buttonLayout.addWidget(removeImageButton) horizonSplitter2.addWidget(widgetPathArea) horizonSplitter2.addWidget(imageBasePathArea) Window_global.selTextureList = selTextureList Window_global.imageBaseSelArea = imageBaseSelArea Window_global.imageBasePathArea = imageBasePathArea Window_global.verticalSplitter = verticalSplitter Window_global.horizonSplitter1 = horizonSplitter1 Window_global.horizonSplitter2 = horizonSplitter2 Window_global.getImageButton = getImageButton Window_global.removeImageButton = removeImageButton Window_global.tabWidget = self.tabWidget Window_global.tabWidget.addTab('newTab') verticalSplitter.setSizes([100, 100]) horizonSplitter1.setSizes([100, 100]) horizonSplitter2.setSizes([100, 100]) Window_global.loadInfo() try: Window_global.loadInfo2() except: pass Functions.updateSelTextureList() QtCore.QObject.connect(addTabButton, QtCore.SIGNAL('clicked()'), self.addTab) QtCore.QObject.connect(removeTabButton, QtCore.SIGNAL('clicked()'), self.removeTab) QtCore.QObject.connect(Window_global.selTextureList, QtCore.SIGNAL('itemSelectionChanged()'), Functions.loadImageSelArea) QtCore.QObject.connect(Window_global.horizonSplitter1, QtCore.SIGNAL('splitterMoved(int,int)'), Functions.splitterMoved1) QtCore.QObject.connect(Window_global.horizonSplitter2, QtCore.SIGNAL('splitterMoved(int,int)'), Functions.splitterMoved2) QtCore.QObject.connect(getImageButton, QtCore.SIGNAL('clicked()'), Functions.getImage) QtCore.QObject.connect(removeImageButton, QtCore.SIGNAL('clicked()'), Functions.removeImage) imageBaseSelArea.clear() imageBasePathArea.clear() getImageButton.setEnabled(False) removeImageButton.setEnabled(False)
class MainWindow(QWidget, object): # noinspection PyUnresolvedReferences def __init__(self): super(MainWindow, self).__init__() self.clip_filename = None self.audio_filename = None layout = QBoxLayout(QBoxLayout.TopToBottom) clip_row = QBoxLayout(QBoxLayout.LeftToRight) self.clip_button = QPushButton() self.clip_button.clicked.connect(self.open_clip) self.clip_button.setText(self.tr("Open clip")) clip_row.addWidget(self.clip_button) self.clip_view = QLabel() clip_row.addWidget(self.clip_view) clip_frame = QFrame() clip_frame.setLayout(clip_row) layout.addWidget(clip_frame) audio_row = QBoxLayout(QBoxLayout.LeftToRight) self.audio_button = QPushButton() self.audio_button.clicked.connect(self.open_audio) self.audio_button.setText(self.tr("Open audio")) audio_row.addWidget(self.audio_button) self.audio_view = QLabel() audio_row.addWidget(self.audio_view) audio_frame = QFrame() audio_frame.setLayout(audio_row) layout.addWidget(audio_frame) save_row = QBoxLayout(QBoxLayout.LeftToRight) self.save_button = QPushButton() self.save_button.clicked.connect(self.save) self.save_button.setText(self.tr("Save synced clip")) save_row.addWidget(self.save_button) save_frame = QFrame() save_frame.setLayout(save_row) layout.addWidget(save_frame) self.update_save_button() layout.addStretch() self.setLayout(layout) self.show() def open_clip(self): self.clip_filename = QFileDialog.getOpenFileName( self, self.tr("Open Clip"), os.getcwd(), self.tr("Video Files [.mp4, .ogv, .mkv, .avi, .mov] (*.mp4 *.ogv *.mkv *.avi *.mov);;" + "Audio Files [.flac, .ogg, .wav, .mp3] (*.flac *.ogg *.wav *.mp3)"))[0] self.clip_view.setText(self.clip_filename) self.update_save_button() def open_audio(self): self.audio_filename = QFileDialog.getOpenFileName( self, self.tr("Open Audio"), os.getcwd(), self.tr("Audio Files [.flac, .ogg, .wav, .mp3] (*.flac *.ogg *.wav *.mp3)"))[0] self.audio_view.setText(self.audio_filename) self.update_save_button() def update_save_button(self): self.save_button.setEnabled(bool(self.clip_filename and self.audio_filename)) def save(self): dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.AnyFile) dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setDefaultSuffix("avi") dialog.setDirectory(os.getcwd()) dialog.setNameFilter(self.tr("Video Files [.avi] (*.avi)")) if dialog.exec_(): output_file_name = dialog.selectedFiles()[0] correlate(self.clip_filename, self.audio_filename, output_file_name)
class SubtransactionForm: """ Represents the SubTransaction Form """ def __init__(self, parent): """ Initialize the Subtransaction Form """ self.parent = parent self.subtransactionTable = SubTransactionTableWidget(self.transaction, self) self.subtransactionLabels = [] def setup(self): """ Setup the Subtransactions for the Transaction Details """ self.subtransactionFrame = QFrame() self.verticalLayout = QVBoxLayout(self.subtransactionFrame) self.horizontalLayout = QHBoxLayout() label = QLabel("<b>Subtransactions</b>") self.horizontalLayout.addWidget(label) button = QPushButton("Add New Subtransaction") button.clicked.connect(self.addSubtransaction) self.horizontalLayout.addWidget(button) self.removeButton = QPushButton("Remove Subtransaction") self.removeButton.clicked.connect(self.removeSubtransaction) self.horizontalLayout.addWidget(self.removeButton) self.removeButton.setEnabled(False) self.verticalLayout.addLayout(self.horizontalLayout) self.verticalLayout.addWidget(self.subtransactionTable) self.verticalLayout.addStretch() self.subtransactionFrame.setLayout(self.verticalLayout) self.layout.addWidget(self.subtransactionFrame) def addSubtransactionLabels(self): """ Add Subtransaction Labels """ self.subtransactionLabels = [] if self.transaction is not None and self.transaction.subtransaction_set is not None: for transaction in self.transaction.subtransaction_set.transactions: if transaction is not self.transaction: label = QLabel("{0}".format(transaction.description)) self.subtransactionLabels.append(label) self.formLayout.insertRow(1, label) def updateOnTransactionChange(self): """ Update on a Transaction Change """ self.subtransactionTable.parent_transaction = self.transaction self.subtransactionTable.updateTransactions() def tabSelected(self): """ Do nothing when selected """ def addSubtransaction(self, checked=False): """ Add the new Subtransaction """ if self.transaction is not None: transaction = CreateSubtransactionFromRelative(self.transaction) TheBalanceHelper.setupBalancesForAccount(transaction.account) self.subtransactionTable.updateTransactions() if transaction.account is self.table.account: self.table.insertRow(transaction, selectRow=False) def removeSubtransaction(self, checked=False): """ Remove the current Subtransaction """ subtransaction = self.subtransactionTable.currentSubtransaction if subtransaction is not None: subtransactionSet = subtransaction.subtransaction_set if len(subtransactionSet.transactions) == 2: SubtransactionSets.delete(subtransactionSet) else: subtransactionSet.transactions.remove(subtransaction) SubtransactionSets.save() row = self.subtransactionTable.currentRow() self.subtransactionTable.removeRow(row) def updateSubtransactionDetails(self): """ Update the Form's Subtransaction Details """ subtransaction = self.subtransactionTable.currentSubtransaction self.removeButton.setEnabled(subtransaction is not None) @property def layout(self): return self.parent.layout @property def table(self): return self.parent.table @property def transaction(self): return self.parent.transaction
class AddRemoveGroupTreeContainer(QWidget): """ Tracks the selection model of the group tree to enable adding and removing spiders/groups. Adds a dynamic button and a layout to the group tree """ def __init__(self, parent=None): super(AddRemoveGroupTreeContainer, self).__init__(parent) self._tree_spider_group = SpiderGroupTreeView() selection_model = self._tree_spider_group.selectionModel() selection_model.selectionChanged.connect(self._updateButtonText) self._button_add_remove = QPushButton(self.tr("Add launch group...")) self._button_add_remove.clicked.connect(self._updateTree) self._button_add_remove.setProperty("_state", ButtonStates.NO_SELECTION) layout = QGridLayout() layout.addWidget(self._tree_spider_group, 0, 0, 1, 2) layout.addWidget(self._button_add_remove, 1, 1) self.setLayout(layout) def _updateButtonText(self, selectedIndexes, deselectedIndexes): # this may not work because these are NEWLY selected and deselected. Strange. This only means mostly one index at a time if not selectedIndexes: self._button_add_remove.setEnabled(True) self._button_add_remove.setText(self.tr("Add launch group...")) self._button_add_remove.setProperty("_state", ButtonStates.NO_SELECTION) else: all_groups = all([not index.parent().isValid() for index in selectedIndexes]) if all_groups: self._button_add_remove.setEnabled(True) self._button_add_remove.setText(self.tr("Delete groups...")) self._button_add_remove.setProperty("_state", ButtonStates.GROUPS_SELECTED) return all_spiders = all([index.parent().isValid() for index in selectedIndexes]) if all_spiders: self._button_add_remove.setEnabled(True) self._button_add_remove.setText(self.tr("Delete spiders...")) self._button_add_remove.setProperty("_state", ButtonStates.SPIDERS_SELECTED) return # I assume now that we have a mixture of spiders and groups. That can be a user mistake and will disable the button self._button_add_remove.setEnabled(False) def _updateTree(self): current_state = self._button_add_remove.property("_state") selected_indexes = self._tree_spider_group.selectionModel().selectedIndexes() selected_texts = [selected_index.data(Qt.DisplayRole) for selected_index in selected_indexes] if current_state == ButtonStates.NO_SELECTION: # Add a new launch group. First collect current group names. group_name_dialog = GroupNameDialog(selected_texts) result = group_name_dialog.exec_() if result == QDialog.Accepted: new_group_name = group_name_dialog.groupName() self._tree_spider_group.model().addSpiderGroup(new_group_name) elif current_state == ButtonStates.GROUPS_SELECTED: accepted = self._askAreYouSure() if accepted: self._tree_spider_group.model().removeGroupsByIndexes(selected_indexes) elif current_state == ButtonStates.SPIDERS_SELECTED: accepted = self._askAreYouSure() if accepted: self._tree_spider_group.model().removeSpidersByIndexes(selected_indexes) def _askAreYouSure(self): dialog_sure = QMessageBox(self) dialog_sure.setWindowTitle(self.tr("Confirm")) dialog_sure.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) dialog_sure.setIcon(QMessageBox.Warning) dialog_sure.setText(self.tr("Are you sure")) result = dialog_sure.exec_() if result == QMessageBox.Ok: return True else: return False
class HighwaySimulatorGui(QMainWindow): def __init__(self): super(HighwaySimulatorGui, self).__init__() centralTab = QTabWidget() mainWidget = QWidget() self.resultsWidget = HighwayAnalyzeWidget() centralTab.addTab(mainWidget, 'Run') centralTab.addTab(self.resultsWidget, 'Analyze') self.setCentralWidget(centralTab) centralLayout = QVBoxLayout() #centralLayout.setSpacing(0) centralLayout.setAlignment(Qt.AlignTop) gridWidget = QWidget() gridLayout = QGridLayout() gridLayout.setSpacing(0) gridWidget.setLayout(gridLayout) mainWidget.setLayout(centralLayout) self.options = dict() # GENERAL generalGroup = QGroupBox('General Settings') generalGroup.setLayout(QVBoxLayout()) generalGroup.layout().setSpacing(0) self.pathOption = SimpleOption('path','Output Path','/home/thomas/Dropbox/Keio/research/results/') generalGroup.layout().addWidget(self.pathOption) self.scenarioOption = SimpleComboboxOption('scenario','Scenario',1, False, 'vanet-highway-test-thomas','vanet-highway-scenario2') self.scenarioOption.combo.currentIndexChanged[int].connect(self.scenarioChanged) generalGroup.layout().addWidget(self.scenarioOption) self.options['time'] = SimpleSpinOption('time','Simulation Time (sec.)',1500,True) self.options['time'].setRange(0,3000) self.options['mix'] = SimpleSpinOption('mix','Percentage of cars compare to trucks (%)',80,True) self.options['mix'].setRange(0,100) self.options['gap'] = SimpleSpinOption('gap','Average Gap (m.)',5) self.options['gap'].setRange(1,2000) self.options['lane'] = SimpleSpinOption('lane','Number of Lanes',2,True) self.options['lane'].setRange(2,4) self.options['spl'] = SimpleSpinOption('spl','Speed Limit (km/h)',130,True) self.options['spl'].setRange(1,200) for widget in ('time','mix','gap','lane','spl'): generalGroup.layout().addWidget(self.options[widget]) gridLayout.addWidget(generalGroup,0,0) # TRAFFIC trafficGroup = QGroupBox('Traffic Settings') trafficGroup.setLayout(QVBoxLayout()) trafficGroup.layout().setSpacing(0) # m/s = (km/h)*1000/3600 self.options['vel1'] = SimpleSpinOption('vel1','Average Speed (km/h)',105,True) self.options['vel1'].setRange(5,150) self.options['dis'] = SimpleComboboxOption('dis','Speed Distribution Model',3, False, 'Uniform','Exponential','Normal','Log Normal') self.options['spstd'] = SimpleSpinOption('spstd','Speed Distribution Variance',1.0) self.options['spstd'].setRange(0,50) self.options['flow1'] = SimpleSpinOption('flow1','Traffic Flow Mean (veh/s)',1.0) self.options['flow1'].setRange(0.1,50.0) self.options['std1'] = SimpleSpinOption('std1','Traffic Flow Variance',0.8) self.options['std1'].setRange(0.1,50.0) self.options['maxflow'] = SimpleSpinOption('maxflow','Traffic Maximum Flow (veh/s)',5) self.options['maxflow'].setRange(0.1,50.0) # Scenar 2 self.options['avgdist'] = SimpleSpinOption('avgdist','Average Distance (m)',100) self.options['avgdist'].setRange(1,10000) self.options['avgspeed'] = SimpleSpinOption('avgspeed','Average Speed (km/h)',105) self.options['avgspeed'].setRange(1,10000) self.options['despeed'] = SimpleSpinOption('despeed','Desired Speed (km/h)',130) self.options['despeed'].setRange(1,10000) self.options['ambumaxspeed'] = SimpleSpinOption('ambumaxspeed','Ambu Max Speed (km/h)',165) self.options['ambumaxspeed'].setRange(1,10000) self.options['ambuinitspeed'] = SimpleSpinOption('ambuinitspeed','Ambu Initial Speed (km/h)',130) self.options['ambuinitspeed'].setRange(1,10000) for widget in ('vel1','dis','spstd','flow1','std1','maxflow', 'avgdist', 'avgspeed', 'despeed', 'ambumaxspeed', 'ambuinitspeed'): trafficGroup.layout().addWidget(self.options[widget]) self.scenarioChanged(self.scenarioOption.combo.currentIndex()) gridLayout.addWidget(trafficGroup,0,1) # VANET vanetGroup = QGroupBox('VANET Settings') vanetGroup.setLayout(QVBoxLayout()) vanetGroup.layout().setSpacing(0) # self.options['prate'] = SimpleSpinOption('prate','Penetration Rate of VANET (%)',100,True) # self.options['prate'].setRange(0,100) self.options['prate'] = 0 # start with 0 self.options['pw'] = SimpleSpinOption('pw','Transmission Power (dBm)',21.5) self.options['pw'].setRange(10,50) #for widget in ('prate','pw'): for widget in ('pw',): vanetGroup.layout().addWidget(self.options[widget]) gridLayout.addWidget(vanetGroup,1,0) # BATCH SETTINGS batchGroup = QGroupBox("Batch Settings") batchGroup.setLayout(QVBoxLayout()) self.gapPrateOption = SimpleSpinOption('gapPrate', 'VANET percentage rate gap', 10, integer=True) self.sameSimuTimesOption = SimpleSpinOption('sameSimuTimes', 'How many times the same simulation', 100, integer=True) batchGroup.layout().setSpacing(0) batchGroup.layout().addWidget(self.gapPrateOption) batchGroup.layout().addWidget(self.sameSimuTimesOption) gridLayout.addWidget(batchGroup,1,1) # START SIMU centralLayout.addWidget(gridWidget) self.startButton = QPushButton('START') self.startButton.clicked.connect(self.startSimu) centralLayout.addWidget(self.startButton) self.progressBar = QProgressBar() centralLayout.addWidget(self.progressBar) self.shutdownWhenDone = QCheckBox('Shutdown when done') self.actionWhenDone = QComboBox() self.actionWhenDone.addItems(['When finished... do nothing', 'When finished... shutdown the computer', 'When finished... Re-run the simulations!']) self.actionWhenDone.setCurrentIndex(int(QSettings().value('actionWhenDone', 0))) centralLayout.addWidget(self.actionWhenDone) self.infoLabel = QLabel() centralLayout.addWidget(self.infoLabel) # LOG self.logText = QTextBrowser() self.logText.setFont(QFont('Century Gothic', 7)) centralLayout.addWidget(self.logText) self.setWindowTitle('Nishimura Lab | Highway Simulation') #self.resize(520,len(self.options)*60+100) #self.resultFile = open('/home/thomas/Dropbox/Keio/research/results/summary.txt', 'a') #self.resultFile = os.path.join(self.pathOption.getValue(), 'summary.txt') self.logFile = os.path.join(self.pathOption.getValue(), 'results_'+os.uname()[1]+'.log') @Slot(int) def scenarioChanged(self, index): #print index scenar1options = ['gap', 'vel1', 'dis', 'flow1', 'std1','spstd', 'maxflow'] scenar2options = ['avgdist', 'avgspeed', 'despeed', 'ambumaxspeed', 'ambuinitspeed'] if index==0: # first scenario scenar1 = True scenar2 = False else: scenar1 = False scenar2 = True for option in scenar1options: self.options[option].setVisible(scenar1) for option in scenar2options: self.options[option].setVisible(scenar2) def log(self, txt): toLog = '%s | %s' % (datetime.now(), txt) with open(self.logFile, 'a') as logFile: logFile.write(toLog+'\n') self.logText.append(toLog) def blockUi(self): self.startButton.setEnabled(False) self.scenarioOption.setEnabled(False) for option in self.options: if option!='prate': self.options[option].setEnabled(False) def releaseUi(self): self.startButton.setEnabled(True) self.scenarioOption.setEnabled(True) self.startButton.setText('START') for option in self.options: if option!='prate': self.options[option].setEnabled(True) def startSimu(self): self.log("=== SIMULATIONS START ===") self.logText.clear() self.startTime = datetime.now() self.simulations = [] #self.nextPrate = 0 self.gapPrate = self.gapPrateOption.getValue() self.sameSimuTimes = self.sameSimuTimesOption.getValue() #self.nextSimu = 0 self.blockUi() self.simulationsDone = 0 #output = self.pathOption.getValue() + dateToFilename(d) + '_results.txt' pRate = 0 self.simulationsTotal = 0 # print 'sameSimuTimes: %d'%self.sameSimuTimes # print 'gapPrate: %d'%self.gapPrate while pRate <= 100: simu = 0 self.options['prate'] = pRate while simu<self.sameSimuTimes: waf = WafThread(self.options, self.pathOption.getValue(), self.scenarioOption.getName()) waf.setAutoDelete(True) waf.simuDone.connect(self.wafDone) self.simulations.append(waf) QThreadPool.globalInstance().start(waf) self.simulationsTotal += 1 simu += 1 pRate += self.gapPrate runningSimulations = 'Running %d Simulations...' % self.simulationsTotal self.startButton.setText(runningSimulations) self.log(runningSimulations) self.progressBar.setRange(0,self.simulationsTotal) self.progressBar.setValue(0) # 300 seconds per task average roughTime = self.simulationsTotal*self.resultsWidget.averageSimulationTime/QThreadPool.globalInstance().maxThreadCount() self.infoLabel.setText('Rough time estimation: %s' % formatTimeLeft(roughTime)) @Slot(str) def wafDone(self, outputPath): #print 'thread done!\nReceived:' self.simulationsDone += 1 simulationsLeft = self.simulationsTotal-self.simulationsDone with open(outputPath,'r') as out: r = json.loads(out.read()) out.close() if 'timeToReachDest' in r['results']: try: result = "%3.3d\t%f" % (int(r['settings']['prate']),float(r['results']['timeToReachDest'])) except TypeError, e: result = 'PYTHON ERROR: %s | File: %s' % (e, outputPath) print result print r else:
class UI(gobject.GObject): __gsignals__ = { 'command': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING, )) } def __init__(self, args, continuous): self.continuous = continuous gobject.GObject.__init__(self) #start by making our app self.app = QApplication(args) #make a window self.window = QMainWindow() #give the window a name self.window.setWindowTitle("BlatherQt") self.window.setMaximumSize(400, 200) center = QWidget() self.window.setCentralWidget(center) layout = QVBoxLayout() center.setLayout(layout) #make a listen/stop button self.lsbutton = QPushButton("Listen") layout.addWidget(self.lsbutton) #make a continuous button self.ccheckbox = QCheckBox("Continuous Listen") layout.addWidget(self.ccheckbox) #connect the buttons self.lsbutton.clicked.connect(self.lsbutton_clicked) self.ccheckbox.clicked.connect(self.ccheckbox_clicked) #add a label to the UI to display the last command self.label = QLabel() layout.addWidget(self.label) #add the actions for quiting quit_action = QAction(self.window) quit_action.setShortcut('Ctrl+Q') quit_action.triggered.connect(self.accel_quit) self.window.addAction(quit_action) def accel_quit(self): #emit the quit self.emit("command", "quit") def ccheckbox_clicked(self): checked = self.ccheckbox.isChecked() if checked: #disable lsbutton self.lsbutton.setEnabled(False) self.lsbutton_stopped() self.emit('command', "continuous_listen") else: self.lsbutton.setEnabled(True) self.emit('command', "continuous_stop") def lsbutton_stopped(self): self.lsbutton.setText("Listen") def lsbutton_clicked(self): val = self.lsbutton.text() if val == "Listen": self.emit("command", "listen") self.lsbutton.setText("Stop") #clear the label self.label.setText("") else: self.lsbutton_stopped() self.emit("command", "stop") def run(self): self.window.show() if self.continuous: self.ccheckbox.setCheckState(Qt.Checked) self.ccheckbox_clicked() self.app.exec_() self.emit("command", "quit") def finished(self, text): print text #if the continuous isn't pressed if not self.ccheckbox.isChecked(): self.lsbutton_stopped() self.label.setText(text) def set_icon(self, icon): self.window.setWindowIcon(QIcon(icon))
class Form(QDialog): def __init__(self, state, parent=None): super().__init__(parent) Lib.prepareModalDialog(self) self.state = state self.setWindowTitle("Recreate Entries — {}".format( QApplication.applicationName())) self.createWidgets() self.layoutWidgets() self.populate() self.updateUi() self.createConnections() settings = QSettings() self.updateToolTips( bool( int( settings.value(Gopt.Key.ShowDialogToolTips, Gopt.Default.ShowDialogToolTips)))) def createWidgets(self): self.listWidget = Widgets.List.HtmlListWidget(self.state) self.tooltips.append((self.listWidget, """\ <p><b>Recreatable Entries view</b></p> <p>The list of this index's recreatable entries.</p>""")) self.recreateSubentriesCheckBox = QCheckBox("Recreate &Subentries") self.recreateSubentriesCheckBox.setChecked(True) self.tooltips.append((self.recreateSubentriesCheckBox, """\ <p><b>Recreate Subentries</b></p> <p>If checked, when an entry or subentry is recreated, all of its subentries, and their subentries, and so on (if any), will also be recrected if possible.</p>""")) self.recreateButton = QPushButton(QIcon(":/recreate.svg"), "&Recreate") self.recreateButton.setDefault(True) self.recreateButton.setAutoDefault(True) self.tooltips.append((self.recreateButton, """\ <p><b>Recreate</b></p> <p>Recreate the current entry or subentry (and its subentries and their subentries, and so on, if the <b>Recreate Subentries</b> checkbox is checked), and then close the dialog.</p> <p>Note that it is possible to get rid of the recreated entries by clicking <b>Index→Undo</b> immediately after the dialog closes. (Or, at any later time by simply deleting them.)""")) self.deleteButton = QPushButton(QIcon(":/delete.svg"), "&Delete...") self.tooltips.append((self.deleteButton, """\ <p><b>Delete</b></p> <p>Permanently delete the current recreatable entry or subentry from this index's list of recreatable entries.</p>""")) self.helpButton = QPushButton(QIcon(":/help.svg"), "Help") self.tooltips.append( (self.helpButton, "Help on the Recreate Entries dialog")) self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Close") self.tooltips.append((self.closeButton, """<p><b>Close</b></p> <p>Close the dialog.</p>""")) def layoutWidgets(self): buttonBox = QDialogButtonBox() buttonBox.addButton(self.recreateButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.deleteButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.closeButton, QDialogButtonBox.AcceptRole) buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole) layout = QVBoxLayout() layout.addWidget(self.listWidget) layout.addWidget(self.recreateSubentriesCheckBox) layout.addWidget(buttonBox) self.setLayout(layout) def createConnections(self): self.recreateButton.clicked.connect(self.recreate) self.deleteButton.clicked.connect(self.delete) self.closeButton.clicked.connect(self.reject) self.helpButton.clicked.connect(self.help) def help(self): self.state.help("xix_ref_dlg_recreate.html") def updateUi(self): enable = self.listWidget.currentRow() > -1 self.recreateButton.setEnabled(enable) self.deleteButton.setEnabled(enable) def populate(self): self.listWidget.clear() for entry in self.state.model.deletedEntries(): pages = "" if entry.pages: pages = ", {}".format(entry.pages) top = MAIN_INDICATOR if entry.peid == ROOT else SUB_INDICATOR item = QListWidgetItem("{} {}{}".format( top, Lib.elidePatchHtml(entry.term, self.state), Lib.elidePatchHtml(pages, self.state))) item.setData(Qt.UserRole, entry.eid) self.listWidget.addItem(item) if self.listWidget.count(): self.listWidget.setCurrentRow(0) def recreate(self): # No need to restore focus widget item = self.listWidget.currentItem() if item: eid = item.data(Qt.UserRole) subentries = self.recreateSubentriesCheckBox.isChecked() with Lib.DisableUI(self): self.state.model.recreateEntry(eid, subentries) say("Recreated", SAY_TIMEOUT) self.accept() def delete(self): widget = QApplication.focusWidget() item = self.listWidget.currentItem() if item: eid = item.data(Qt.UserRole) if self.state.model.hasDeletedEntry(eid): with Lib.Qt.DisableUI(self, forModalDialog=True): reply = QMessageBox.question( self, "Delete Revivable Entry — {}".format( QApplication.applicationName()), "<p>Permanently delete revivable entry<br>“{}”?". format(item.text()), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if reply == QMessageBox.Yes: with Lib.DisableUI(self): self.state.model.deleteDeletedEntry(eid) self.populate() self.updateUi() Lib.restoreFocus(widget)
class Form(QDialog): def __init__(self, state, parent=None): super().__init__(parent) Lib.prepareModalDialog(self) self.state = state self.setWindowTitle("Move Entry — {}".format( QApplication.applicationName())) self.message = None self.createWidgets() self.layoutWidgets() self.createConnections() self.updateUi() settings = QSettings() self.updateToolTips( bool( int( settings.value(Gopt.Key.ShowDialogToolTips, Gopt.Default.ShowDialogToolTips)))) def createWidgets(self): selectedEid = self.state.viewAllPanel.view.selectedEid self.selectedEntry = self.state.model.entry(selectedEid) self.entryLabel = QLabel("Move ") self.termLabel = Widgets.Label.HtmlLabel("“{}”".format( Lib.elidePatchHtml(self.selectedEntry.term, self.state))) self.eidGroup = QGroupBox() parentEid = self.selectedEntry.peid self.moveToTopRadioButton = QRadioButton("to be a &Main Entry") self.grandParentEntry = None grandParentEid = None if parentEid != ROOT: grandParentEid = self.state.model.parentOf(parentEid) if grandParentEid != ROOT: self.grandParentEntry = self.state.model.entry(grandParentEid) self.grandParentRadioButton = QRadioButton("up under &Grandparent") self.filteredEntry = self.circledEntry = None filteredEid = self.state.viewFilteredPanel.view.selectedEid if filteredEid is not None: self.filteredEntry = self.state.model.entry(filteredEid) circledEid = self.state.viewAllPanel.view.circledEid if circledEid is not None: self.circledEntry = self.state.model.entry(circledEid) self.filteredRadioButton = QRadioButton("under &Filtered") self.circledRadioButton = QRadioButton("under C&ircled") self.recentRadioButton = QRadioButton("under &Recent") self.tooltips.append( (self.recentRadioButton, """<p><b>under Recent</b></p> <p>Move the current entry under a recently visited entry.</p>""")) self.grandParentLabel = Widgets.Label.HtmlLabel() self.filteredLabel = Widgets.Label.HtmlLabel() self.circledLabel = Widgets.Label.HtmlLabel() self.moveToTopRadioButton.setEnabled(parentEid != ROOT) self.moveToTopRadioButton.setChecked(parentEid != ROOT) seen = {selectedEid, self.selectedEntry.peid} self.buttons = (self.moveToTopRadioButton, self.grandParentRadioButton, self.filteredRadioButton, self.circledRadioButton, self.recentRadioButton) Forms.Util.setUpRadioButton( self, self.grandParentEntry, self.grandParentRadioButton, self.grandParentLabel, self.buttons, seen, """<p><b>under Grandparent</b></p> <p>Move the current entry up under its grandparent “{}”.</p>""") Forms.Util.setUpRadioButton( self, self.filteredEntry, self.filteredRadioButton, self.filteredLabel, self.buttons, seen, """<p><b>under Filtered</b></p> <p>Move the current entry under the filtered entry “{}”.</p>""") Forms.Util.setUpRadioButton( self, self.circledEntry, self.circledRadioButton, self.circledLabel, self.buttons, seen, """<p><b>under Circled</b></p> <p>Move the current entry under the circled entry “{}”.</p>""") self.recentComboBox = Forms.Util.createTermsComboBox( self.state, self.state.gotoEids, ignore=seen, maximum=MAX_RECENT) if self.recentComboBox.count() and all(not radio.isChecked() for radio in self.buttons): self.recentRadioButton.setChecked(True) self.recentComboBox.setFocus() self.buttonBox = QDialogButtonBox() self.moveButton = QPushButton(QIcon(":/move.svg"), "M&ove") self.tooltips.append((self.moveButton, """<p><b>Move</b></p> <p>Move the “{}” entry.</p>""".format(self.termLabel.text()))) self.buttonBox.addButton(self.moveButton, QDialogButtonBox.AcceptRole) self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Cancel") self.tooltips.append((self.closeButton, """<p><b>Cancel</b></p> <p>Close the dialog without making any changes to the index.</p>""")) self.buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole) self.helpButton = QPushButton(QIcon(":/help.svg"), "Help") self.tooltips.append( (self.helpButton, "Help on the Move Entry dialog")) self.buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole) def layoutWidgets(self): layout = QVBoxLayout() entryLayout = QHBoxLayout() entryLayout.setSpacing(0) entryLayout.addWidget(self.entryLabel) entryLayout.addWidget(self.termLabel) entryLayout.addStretch() layout.addLayout(entryLayout) eidLayout = QVBoxLayout() eidLayout.addWidget(self.moveToTopRadioButton) hbox = QHBoxLayout() hbox.setSpacing(0) hbox.addWidget(self.grandParentRadioButton) hbox.addWidget(self.grandParentLabel, 1) eidLayout.addLayout(hbox) hbox = QHBoxLayout() hbox.setSpacing(0) hbox.addWidget(self.filteredRadioButton) hbox.addWidget(self.filteredLabel, 1) eidLayout.addLayout(hbox) hbox = QHBoxLayout() hbox.setSpacing(0) hbox.addWidget(self.circledRadioButton) hbox.addWidget(self.circledLabel, 1) eidLayout.addLayout(hbox) hbox = QHBoxLayout() hbox.setSpacing(0) hbox.addWidget(self.recentRadioButton) hbox.addWidget(self.recentComboBox, 1) eidLayout.addLayout(hbox) eidLayout.addStretch() self.eidGroup.setLayout(eidLayout) layout.addWidget(self.eidGroup) layout.addWidget(self.buttonBox) self.setLayout(layout) def createConnections(self): self.buttonBox.accepted.connect(self.move) self.buttonBox.rejected.connect(self.reject) self.helpButton.clicked.connect(self.help) self.recentRadioButton.toggled.connect(self.moveFocus) self.recentComboBox.currentIndexChanged[int].connect( self.recentChanged) def recentChanged(self): self.recentRadioButton.setChecked(True) self.updateUi() def moveFocus(self): if self.recentRadioButton.isChecked(): self.recentComboBox.setFocus() def updateUi(self): self.recentRadioButton.setEnabled(self.recentComboBox.count()) self.recentComboBox.setEnabled(self.recentComboBox.count()) self.moveButton.setEnabled( any(button.isChecked() for button in self.buttons)) def help(self): self.state.help("xix_ref_dlg_move.html") def move(self): self.state.maybeSave() eid = self.selectedEntry.eid if self.moveToTopRadioButton.isChecked(): self.state.model.moveToTop(eid) else: peid = None if self.grandParentRadioButton.isChecked(): peid = self.grandParentEntry.eid message = "move up" elif self.filteredRadioButton.isChecked(): peid = self.filteredEntry.eid message = "move under filtered" elif self.circledRadioButton.isChecked(): peid = self.circledEntry.eid message = "move under circled" elif self.recentRadioButton.isChecked(): peid = self.recentComboBox.itemData( self.recentComboBox.currentIndex()) message = "move under recently visited" if peid is not None: # Should always be True self.state.model.moveUnder(eid, peid, message) term = Lib.htmlToPlainText(self.state.model.term(eid)) if peid == ROOT: message = "Moved “{}” to be a main entry".format(term) else: message = "Moved “{}” under “{}”".format( term, Lib.htmlToPlainText(self.state.model.term(peid))) say(message, SAY_TIMEOUT) self.accept()
class Form(QDialog): # Only use if there's a model present def __init__(self, state, parent=None): super().__init__(parent) Lib.prepareModalDialog(self) self.state = state self.formatActions = None self.extension = None self.markup = None self.dirty = False self.setWindowTitle("Custom Markup — {}".format( QApplication.applicationName())) self.createWidgets() self.layoutWidgets() self.createConnections() self.refresh() settings = QSettings() self.updateToolTips( bool( int( settings.value(Gopt.Key.ShowDialogToolTips, Gopt.Default.ShowDialogToolTips)))) def createWidgets(self): self.extensionLabel = QLabel("&Extension") self.extensionComboBox = QComboBox() for markup in self.state.model.markups(): self.extensionComboBox.addItem(markup) self.tooltips.append((self.extensionComboBox, """\ <p><b>Extension</b></p> <p>Choose the file extension to view and edit its custom markup.</p>""")) self.extensionLabel.setBuddy(self.extensionComboBox) self.helpButton = QPushButton(QIcon(":/help.svg"), "Help") self.tooltips.append( (self.helpButton, "Help on the Custom Markup dialog")) self.addButton = QPushButton(QIcon(":/add.svg"), "&Add...") self.tooltips.append((self.addButton, """\ <p><b>Add</b></p> <p>Add a new custom markup to the index.</p>""")) self.deleteButton = QPushButton(QIcon(":/delete.svg"), "&Delete...") self.tooltips.append((self.deleteButton, """\ <p><b>Delete</b></p> <p>Permanently delete the custom markup from the index's <tt>.xix</tt> file. (Note that <tt>.ucp</tt> custom markup cannot be deleted.)</p>""")) self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Close") self.tooltips.append((self.closeButton, """<p><b>Close</b></p> <p>Close the dialog.</p>""")) self.tabWidget = QTabWidget() self.documentPanel = CustomMarkupPanels.Document.Panel( self.state, self) self.characterPanel = CustomMarkupPanels.Character.Panel( self.state, self) self.tabWidget.addTab(self.documentPanel, "D&ocument") self.tabWidget.addTab(self.characterPanel, "C&haracter") def layoutWidgets(self): buttonBox = QDialogButtonBox() buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole) buttonBox.addButton(self.addButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.deleteButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.closeButton, QDialogButtonBox.AcceptRole) hbox = QHBoxLayout() hbox.addWidget(self.extensionLabel) hbox.addWidget(self.extensionComboBox) hbox.addStretch() hbox.addWidget(buttonBox) vbox = QVBoxLayout() vbox.addLayout(hbox) vbox.addWidget(self.tabWidget, 1) self.setLayout(vbox) def createConnections(self): self.helpButton.clicked.connect(self.help) self.extensionComboBox.currentIndexChanged.connect(self.refresh) self.addButton.clicked.connect(self.add) self.deleteButton.clicked.connect(self.delete) self.closeButton.clicked.connect(self.accept) self.documentPanel.changed.connect(self.setDirty) self.characterPanel.changed.connect(self.setDirty) def help(self): self.state.help("xix_ref_dlg_markup.html") def setDirty(self): self.dirty = True def refresh(self): self.save() self.extension = self.extensionComboBox.currentText() if self.extension not in self.state.model.markups(): self.markup = Output.Markup.user_markup() else: self.markup = self.state.model.markup(self.extension) self.documentPanel.populateFromMarkup(self.markup) self.characterPanel.populateFromMarkup(self.markup) self.deleteButton.setEnabled(self.extension != ".ucp") def save(self): if self.dirty and self.extension is not None: self.documentPanel.updateMarkup(self.markup) self.characterPanel.updateMarkup(self.markup) self.state.model.updateMarkup(self.extension, self.markup) self.dirty = False def add(self): # No need to restore focus widget self.save() with Lib.DisableUI(self, forModalDialog=True): extension, ok = QInputDialog.getText( self, "Add Custom Markup -— {}".format( QApplication.applicationName()), "Extension") if ok and extension and extension.strip(): extension = extension.strip() if not extension.startswith("."): extension = "." + extension index = self.extensionComboBox.findText(extension, Qt.MatchExactly) if index != -1: self.extensionComboBox.setCurrentIndex(index) else: self.extension = extension self.markup = Output.Markup.user_markup() self.state.model.updateMarkup(self.extension, self.markup) self.extensionComboBox.addItem(extension) self.extensionComboBox.setCurrentIndex( self.extensionComboBox.count() - 1) def delete(self): # No need to restore focus widget index = self.extensionComboBox.currentIndex() if index == -1: return with Lib.Qt.DisableUI(self, forModalDialog=True): extension = self.extensionComboBox.currentText() reply = QMessageBox.question( self, "Delete Custom Markup — {}".format( QApplication.applicationName()), """<p>Delete “{}”?<p> <font color=red>Warning: deleting custom markup cannot be undone.</font>""". format(extension), QMessageBox.Yes | QMessageBox.No) if reply == QMessageBox.Yes: self.extensionComboBox.removeItem(index) if index < self.extensionComboBox.count(): self.extensionComboBox.setCurrentIndex(index) else: self.extensionComboBox.setCurrentIndex(max(0, index - 1)) self.state.model.deleteMarkup(extension) def reject(self): self.accept() def accept(self): self.save() super().accept()
class MainWindow(QDialog): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.stopSign = 0 self.ws = 0 self.comment = '' self.clipboard = QApplication.clipboard() self.setWindowTitle(u'勤務表') self.setWindowIcon(QIcon('./img/tray.png')) self.systemTrayIcon = QSystemTrayIcon(self) self.systemTrayIcon.setIcon(QIcon('./img/tray.png')) self.systemTrayIcon.setVisible(True) self.systemTrayIcon.show() self.systemTrayIcon.activated.connect(self.on_systemTrayIcon_activated) self.tableLabel = QLabel('select *.xls file') self.pathText = QLineEdit() self.triggerBtn = QPushButton(u'檢查 / 開始') self.browseBtn = QPushButton(u' 瀏覽 ') self.stopBtn = QPushButton(u'停止') self.table = QTableWidget(26,0,self) self.setUpTable() self.hbox1 = QHBoxLayout() self.hbox2 = QHBoxLayout() self.hbox3 = QHBoxLayout() self.hbox4 = QHBoxLayout() self.hbox1.addWidget(self.pathText) self.hbox1.addWidget(self.browseBtn) self.hbox1.addWidget(self.triggerBtn) self.browseBtn.clicked.connect(self.OpenFile) self.triggerBtn.clicked.connect(self.setupTypeThread) self.stopBtn.clicked.connect(self.threadStop) self.status = QTreeWidget(self) self.status.setHeaderHidden(True) self.hbox2.addWidget(self.status) self.hbox3.addWidget(self.table) self.hbox4.addWidget(self.stopBtn) self.setGeometry(200, 200, 700, 400) self.status.setFixedHeight (80) self.layout = QVBoxLayout() self.layout.addWidget(self.tableLabel) self.layout.addLayout(self.hbox1) self.layout.addLayout(self.hbox2) self.layout.addLayout(self.hbox3) self.layout.addLayout(self.hbox4) self.setLayout(self.layout) self.stopBtn.setEnabled(False) def setUpTable(self): self.table.horizontalHeader().setVisible(False) for i in xrange(0, 26, 1): self.vhfont = QFont('Times', pointSize = 10, weight=QFont.Bold) timePos = i+6 if i == 0: item = QTableWidgetItem(u'[標題]') elif i == 1: item = QTableWidgetItem(u'[設定]') elif 2 < timePos < 24: item = QTableWidgetItem(('{0}~{1}').format(timePos, timePos+1)) else: item = QTableWidgetItem(('{0}~{1}').format(timePos-24, timePos-23)) item.setFont(self.vhfont) item.setTextAlignment(Qt.AlignCenter) self.table.setVerticalHeaderItem(i, item) def on_systemTrayIcon_activated(self, reason): if reason == QSystemTrayIcon.DoubleClick: if self.isHidden(): try: self.typeThread self.threadStop() except: pass self.show() else: self.hide() def setupTypeThread(self): self.clipboard.setText('') det = self.loadDetec() self.ws, vaild = self.checkTableValidation(det, self.table) ws = [] for col in self.ws: ws.append(col[0]) self.addStatus( u' 狀態: 檢查勤務表狀態....', 0) errStat = self.check(ws) if vaild != True and self.table.columnCount()!=0: self.addStatus( vaild, 1) elif self.table.columnCount() ==0: self.addStatus( u' 錯誤: 請載入勤務表', 1) self.typeThread = startType(self.ws) self.typeThread.threadDone.connect(self.showDoneMsg, Qt.QueuedConnection) self.typeThread.toTray.connect(self.toTray, Qt.QueuedConnection) self.typeThread.toCilpboard.connect(self.toCilpboard, Qt.QueuedConnection) self.typeThread.enableButtons.connect(self.enableButtons, Qt.QueuedConnection) self.typeThread.showErrMsg.connect(self.showErrMsg, Qt.QueuedConnection) self.typeThread.addStatus.connect(self.addStatus, Qt.QueuedConnection) if not self.typeThread.isRunning() and vaild == True and errStat == True: self.addStatus( u' 狀態: 檢查通過,開始進行登打作業....', -1) self.browseBtn.setEnabled(False) self.triggerBtn.setEnabled(False) self.stopBtn.setEnabled(True) self.typeThread.start() def toTray(self, state): if state: pass self.hide() self.systemTrayIcon.showMessage(u'輸入中',u'勤務表背景輸入中....\n\n雙擊圖示可暫停程序', msecs=1000000) else: self.show() def toCilpboard(self, text): self.clipboard.setText(text) def threadStop(self): self.typeThread.stopSign = 1 if self.typeThread.isRunning(): self.browseBtn.setEnabled(True) self.triggerBtn.setEnabled(True) self.stopBtn.setEnabled(False) def addStatus(self, text, err): subTreeItem = QTreeWidgetItem(self.status) subTreeItem.setText(0, text) self.activateWindow() if err == 1: font = QFont('Serif', 10, QFont.Bold) subTreeItem.setFont(0, font) subTreeItem.setForeground(0, QBrush(Qt.white)) subTreeItem.setBackground(0, QBrush(QColor(150,0,0))) elif err == 0: font = QFont('Serif', 10, QFont.Bold) subTreeItem.setFont(0, font) subTreeItem.setForeground(0, QBrush(Qt.black)) subTreeItem.setBackground(0, QBrush(Qt.white)) else: font = QFont('Serif', 10, QFont.Bold) subTreeItem.setFont(0, font) subTreeItem.setForeground(0, QBrush(Qt.white)) subTreeItem.setBackground(0, QBrush(QColor(0,150,0))) self.status.scrollToItem(subTreeItem, QAbstractItemView.PositionAtCenter) def showErrMsg(self, title, msg): self.addStatus( u'錯誤: ' + msg, 1) QMessageBox.warning(self, title, msg, QMessageBox.Ok) def showDoneMsg(self): self.addStatus( u'完成: 完成!', 1) QMessageBox.warning(self, u'完成!', u'完成!', QMessageBox.Ok) def enableButtons(self): self.clipboard.setText(self.comment) self.browseBtn.setEnabled(True) self.triggerBtn.setEnabled(True) self.stopBtn.setEnabled(False) self.show() def OpenFile(self): fileName = QFileDialog.getOpenFileName(self, "Open File.", "/home") self.comment = '' ext = fileName[0].split('.')[-1] if ext == 'xls' or ext == 'xlsx': self.pathText.setText(fileName[0]) sheet = open_workbook(fileName[0]).sheets()[0] self.setFixedHeight(550) self.addStatus( u' 狀態: 載入勤務表: [' + fileName[0] + ']', -1) for col in xrange(self.table.columnCount()-1,-1,-1): self.table.removeColumn(col) ws, header, headerNum = self.loadWS(sheet) self.appendTable(header, ws) self.check(ws) self.comment += self.yieldcomment(sheet) self.ws = ws else: self.showErrMsg(u'錯誤',u'選取檔案不是EXCEL檔') self.ws = 0 def checkTableValidation(self, detCol, table): # .[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ws = [[], [], [], [], [], [], [], [], [], []] errStat = True if len(detCol) == 0 or (0 in detCol): errStat = u' 狀態: 勤務表標頭錯誤,點選 [ --請選擇-- ] 選取有效標頭' for i in xrange(len(detCol)-1): if sorted(detCol)[i] == sorted(detCol)[i+1]: errStat = u' 狀態: 勤務表標頭重複' print detCol for c in xrange(table.columnCount()): col = [] colNum = detCol[c] for r in xrange(2, 26, 1): col.append(table.item(r,c).text()) ws[colNum-1].append(col) for i in xrange(len(ws)): if len(ws[i]) == 0: ws[i].append(['','','','','','','','','','','','','','','','','','','','','','','','']) return (ws), errStat def loadWS(self, sheet): header, headerNum, ws= [],[],[] for c in xrange(3, 26 ,1): title = (sheet.cell_value(3, c)) if len(title) != 0 and len(header) <6: header.append(title) col = [] for m in xrange(7, 31, 1): try: col.append(str(sheet.cell_value(m, c)).strip('()').replace('.0', '').replace('.', ',')) except: col.append(u'error') ws.append(col) return ws, header, headerNum def appendTable(self, header, ws): try: font = QFont('TypeWriter', pointSize = 10, weight=QFont.Bold) for text in header: self.table.insertColumn(0) for c in xrange(len(header)): det = self.determine(header[c]) item = QTableWidgetItem(header[c]) if det == 0: item.setBackground(QBrush(QColor('#FF8D00'))) else: item.setBackground(QBrush(QColor('#005588'))) item.setFont(font) item.setTextAlignment(Qt.AlignCenter) self.table.setItem(0, c, item) nComboBox = self.newCombo() nComboBox.setCurrentIndex(det) self.table.setCellWidget(1, c, (nComboBox)) for r in xrange(2,26,1): item = QTableWidgetItem(ws[c][r-2]) item.setFont(font) item.setTextAlignment(Qt.AlignCenter) self.table.setItem(r, c, item) self.addStatus( u' 狀態: 勤務表預覽成功', -1) return 0 except: self.addStatus( u' 狀態: 勤務表預覽失敗', 1) return 'error' def loadDetec(self): det = [] for col in xrange(self.table.columnCount()): det.append( self.table.cellWidget(1, col).currentIndex()) return det def newCombo(self): taskList = [u'--請選擇--', u'值班', u'救護勤務', u'備勤', u'待命服勤', u'水源查察', u'消防查察', u'宣導勤務', u'訓(演)練', u'專案勤務', u'南山救護站'] nComboBox = QComboBox() nComboBox.addItems(taskList) for i in xrange(len(taskList)): if i == 0: nComboBox.setItemData(i, QColor('#550000'), Qt.BackgroundColorRole) nComboBox.setItemData(i, Qt.AlignCenter, Qt.TextAlignmentRole) nComboBox.setStyleSheet("text-align: right; font: bold 13px;") return nComboBox def setTableErr(self, row, state): if state == 'illegal' : color = '#CC0033' elif state == 'repeated' : color = '#FF8D00' elif state == 'legal' : color = '#201F1F' for col in xrange(self.table.columnCount()): self.table.item(row,col).setBackground(QBrush(QColor(color))) def check(self, ws): errStat = True for m in xrange(2,26): self.setTableErr(m, 'legal') for i in xrange(24): ary = [] for j in xrange(len(ws)): for each in ws[j][i].replace(' ', '').split(','): try: if each == "A": ary.append(-1) elif each == '' : pass else: each == ary.append(int(each)) except: errStat = False timePos = i+8 rptErrMSG = u" 錯誤: 於 {0} ~ {1} 時 數字: {2} --不合法, 請修正" self.setTableErr(i+2, 'illegal') print timePos if timePos < 23: print 'a' self.addStatus(rptErrMSG.format(timePos, timePos+1, each), 1) else: self.addStatus(rptErrMSG.format(timePos-24, timePos-23, each), 1) ary = sorted(ary) for idx in xrange(len(ary)-1): if ary[idx] == ary[idx+1]: errStat = False timePos = i+8 rptErrMSG = u" 錯誤: 於 {0} ~ {1} 時 數字: {2} --番號重複, 請修正" self.setTableErr(i+2, 'repeated') if timePos < 23: self.addStatus(rptErrMSG.format(timePos, timePos+1, str(ary[idx]).replace('-1', 'A')), 1) else: self.addStatus(rptErrMSG.format(timePos-24, timePos-23, str(ary[idx]).replace('-1', 'A')), 1) return errStat def determine(self, title): cmpfactor = 0 smp = [u'值班', u'救護分隊務', u'備', u'待命服', u'水源', u'消防', u'宣導', u'訓演練', u'專案其它', u'南山站'] for index, each in zip(xrange(len(smp)),smp): for text in each: for elem in title: cmpfactor += ( elem == text ) if cmpfactor > 0: return index+1 return 0 def yieldcomment(self, sheet): comment0, comment1 = '', '' # for i,j in [[24,27], [27,27], [29,27], [29,35]]: # try: # comment0 += (smart_str(sheet.cell_value(i, j)) + '\n') # except: # pass for i,j in [[31,3], [32,3], [33,3], [34,3]]: try: comment1 += (sheet.cell_value(i, j) + '\n') except: pass return comment1
class NewWindow(QWidget): def __init__(self, app=None): super(NewWindow, self).__init__() self.app = app glo = QVBoxLayout(self) icp = r_path(solve_path('static/images/favicon.png')) # need to used objective message boxs instead of functions to set font self.Arial = QFont("", 12, QFont.Bold) self.Arials = QFont("", 10, QFont.Bold) # Language support variable self.Language = 'en' self.Runningo = False icon = QIcon(icp) self.SelfIinit(icon) self.center() self.langsList(glo) self.set_Abutton(icp, glo) self.Lists(glo) self.Flabel(glo) self.set_button(glo) self.setLayout(glo) mip = self.slchange() self.P = rwser(mip[1].split(',')[1], mip[0], self.app) self.activateWindow() self.show() def SelfIinit(self, icon): self.setWindowTitle('Free Queue Manager ' + version) self.setGeometry(300, 300, 200, 150) self.setMinimumWidth(500) self.setMaximumWidth(500) self.setMinimumHeight(400) self.setMaximumHeight(400) # Setting Icon self.setWindowIcon(icon) QToolTip.setFont(self.Arials) def Flabel(self, glo): fontt = self.Arial self.ic1 = QIcon(r_path(solve_path('static/images/pause.png'))) self.l = QLabel('Icond', self) self.ic1 = self.ic1.pixmap(70, 70, QIcon.Active, QIcon.On) self.l.setPixmap(self.ic1) self.l.setAlignment(Qt.AlignCenter | Qt.AlignHCenter) self.l.setFont(fontt) self.t = QLabel('Texted', self) self.t.setText(self.getTrans('11')) self.t.setOpenExternalLinks(True) self.t.setAlignment(Qt.AlignCenter | Qt.AlignHCenter) self.t.setFont(fontt) self.t.setToolTip(self.getTrans('9')) self.l.setToolTip(self.getTrans('9')) glo.addStretch() glo.addWidget(self.l) glo.addWidget(self.t) glo.addStretch() def langsList(self, glo): self.langs = { # languages to be displayed in select 'en': 'English', 'ar': 'Arabic', 'fr': 'French', 'it': 'Italian', 'es': 'Spanish' } self.langs_list = QComboBox() self.langs_list.addItems(list(self.langs.values())) self.langs_list.setCurrentIndex(1) self.langs_list.setToolTip(self.getTrans('1')) self.langs_list.currentIndexChanged.connect(self.langChange) glo.addWidget(self.langs_list) def langChange (self): self.language = list(self.langs.keys())[self.langs_list.currentIndex()] self.langs_list.setToolTip(self.getTrans('1')) self.Amsgb = self.getTrans('2') self.abutton.setToolTip( self.getTrans('2') ) self.mbutton.setText(self.getTrans('3')) self.mbutton.setToolTip(self.getTrans('4')) self.mbutton2.setText(self.getTrans('5')) self.mbutton2.setToolTip(self.getTrans('6')) self.sl.setToolTip( self.getTrans('7') ) self.sl2.setToolTip(self.getTrans('8')) self.t.setToolTip(self.getTrans('9')) self.l.setToolTip(self.getTrans('9')) if self.Runningo: pp = self.slchange() addr = self.getTrans('10') addr += u"<a href='http://" addr += pp[1].split(',')[1] + u":" + pp[0] addr += u"'> http://" + pp[1].split(',')[1] + u":" + pp[0] addr += u"</a>" self.t.setText(addr) else: self.t.setText(self.getTrans('11')) def getTrans(self, index): lang = list(self.langs.keys())[self.langs_list.currentIndex()] try: return LANGUAGES[lang][index] except Exception: return None def Lists(self, glo): ips = self.get_ips() self.sl = QComboBox() self.sl.addItems(ips) self.sl.setToolTip(self.getTrans('7')) self.sl2 = QComboBox() self.get_ports() self.sl2.setToolTip('8') self.sl.currentIndexChanged.connect(self.get_ports) glo.addWidget(self.sl) glo.addWidget(self.sl2) def get_ports(self, nauto=True): d_ports = ['5000', '8080', '3000', '80', '9931'] m_ports = [] while len(m_ports) < 10: mip = self.slchange() for p in d_ports: s = socket(AF_INET, SOCK_STREAM) try: s.bind((mip[1].split(',')[1], int(p))) s.close() m_ports.append(p) except: s.close() d_ports.remove(p) s = socket(AF_INET, SOCK_STREAM) p = randint(1000, 9999) try: s.bind((mip[1].split(',')[1], p)) s.close() m_ports.append(str(p)) except: s.close() if len(m_ports) >= 10: break self.sl2.clear() self.sl2.addItems(m_ports) def slchange(self): return [self.sl2.currentText(), self.sl.currentText()] def set_button(self, glo): hlayout = QHBoxLayout() self.mbutton = QPushButton('Start', self) self.mbutton.clicked.connect(self.s_server) self.mbutton.setFont(self.Arials) self.mbutton.setIcon(QPixmap(r_path(solve_path('static/images/play.png')))) self.mbutton2 = QPushButton('Stop', self) self.mbutton2.clicked.connect(self.st_server) self.mbutton2.setIcon(QPixmap(r_path(solve_path('static/images/pause.png')))) self.mbutton.setToolTip(self.getTrans('4')) self.mbutton2.setToolTip(self.getTrans('6')) self.mbutton2.setEnabled(False) self.mbutton2.setFont(self.Arials) hlayout.addWidget(self.mbutton) hlayout.addWidget(self.mbutton2) glo.addLayout(hlayout) def s_server(self): mip = self.slchange() self.P = rwser(mip[1].split(',')[1], mip[0], self.app) self.P.setTerminationEnabled(True) if not self.P.isRunning(): try: self.pport = mip[0] self.mbutton.setEnabled(False) self.mbutton2.setEnabled(True) self.sl.setEnabled(False) self.sl2.setEnabled(False) self.ic1 = QIcon(r_path(solve_path('static/images/play.png'))) self.ic1 = self.ic1.pixmap(70, 70, QIcon.Active, QIcon.On) self.l.setPixmap(self.ic1) pp = self.slchange() addr = self.getTrans('10') addr += "<a href='http://" addr += pp[1].split(',')[1] + ":" + pp[0] addr += "'> http://" + pp[1].split(',')[1] + ":" + pp[0] addr += "</a>" self.t.setText(addr) self.t.setFont(self.Arial) self.P.start() self.Runningo = True except: self.eout() else: self.eout() def st_server(self): if self.P.isRunning(): try: if self.P.isRunning: self.P.stop() self.mbutton.setEnabled(True) self.mbutton2.setEnabled(False) self.sl.setEnabled(True) self.sl2.setEnabled(True) self.t.setText(self.getTrans('11')) # removing the last used port to avoid termination error cind = self.sl2.currentIndex() self.sl2.removeItem(cind) self.get_ports() self.Runningo = False except: self.eout() else: self.eout() def set_Abutton(self, icon, glo): def show_about(nself): Amsg = u" <center> " Amsg += self.getTrans('12') + version + u" " Amsg += self.getTrans('13') Amsg += self.getTrans('14') Amsg += self.getTrans('15') Amsg += u"<br> <b><a href='https://fqms.github.io/'>" Amsg += u"https://fqms.github.io </a> </b></center>" Amsgb = self.getTrans('2') return QMessageBox.about( self, Amsgb, Amsg) self.abutton = QPushButton('', self) self.abutton.setIcon(QPixmap(icon)) self.abutton.setIconSize(QSize(150, 70)) self.abutton.setToolTip(self.getTrans('2')) self.abutton.clicked.connect(partial(show_about, self)) glo.addWidget(self.abutton) def closeEvent(self, event=None): if self.Runningo: response = self.msgApp( self.getTrans('16'), self.getTrans('17')) if response == 'y': if event is not None: event.accept() if self.P.isRunning(): self.P.stop() sys.exit(0) else: if event is not None: event.ignore() else: if event is not None: event.accept() if self.P.isRunning(): self.P.stop() sys.exit(0) def msgApp(self, title, msg): uinfo = QMessageBox.question(self, title, msg, QMessageBox.Yes | QMessageBox.No) if uinfo == QMessageBox.Yes: return 'y' if uinfo == QMessageBox.No: return 'n' def eout(self): if self.P.isRunning(): self.P.stop() msgg = u"<center>" msgg += self.getTrans('18') msgg += self.getTrans('19') msgg += u"<br><b><a href='https://fqms.github.io/'> " msgg += u"https://fqms.github.io </a></b> </center>" mm = QMessageBox.critical( self, self.getTrans('20'), msgg, QMessageBox.Ok) def center(self): qrect = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qrect.moveCenter(cp) self.move(qrect.topLeft()) def get_ips(self): il = [] for i in interfaces(): try: if os.name != 'nt': inf = i + " ," else: inf = ' ,' inf += ifaddresses(i)[2][0].get('addr') il.append(inf) except: pass return il
class Form(QDialog): def __init__(self, state, parent=None): super().__init__(parent) Lib.prepareModalDialog(self) self.state = state self.setWindowTitle("Combine Overlapping Pages — {}".format( QApplication.applicationName())) self.createWidgets() self.layoutWidgets() self.createConnections() self.entry = None QApplication.setOverrideCursor(Qt.WaitCursor) try: self.eids = list( self.state.model.filteredEntries( filter=FilterKind.HAS_OVERLAPPING_PAGES, match=None, offset=0, limit=UNLIMITED, entryData=EntryDataKind.EID)) finally: QApplication.restoreOverrideCursor() self.eidIndex = -1 if self.eids else None if self.eids: self.skip() self.combineButton.setFocus() say( "Found {:,} entries with overlapping pages".format( len(self.eids)), SAY_TIMEOUT) else: say("No overlapping pages found", SAY_TIMEOUT) self.updateUi() settings = QSettings() self.updateToolTips( bool( int( settings.value(Gopt.Key.ShowDialogToolTips, Gopt.Default.ShowDialogToolTips)))) def createWidgets(self): self.termLabelLabel = QLabel("Term") self.termLabel = Widgets.Label.HtmlLabel() self.originalPagesLabel = Widgets.Label.HtmlLabel() self.originalPagesLabel.setStyleSheet(_BG_SAME) self.combinedPagesLabel = Widgets.Label.HtmlLabel() self.combinedPagesLabel.setStyleSheet(_BG_SAME) self.buttonBox = QDialogButtonBox() self.combineButton = QPushButton(QIcon(":/combinepages.svg"), "Co&mbine") self.tooltips.append((self.combineButton, """\ <p><b>Combine</b></p> <p>Combine overlapping pages as shown, and move to the next term with overlapping pages.</p>""")) self.buttonBox.addButton(self.combineButton, QDialogButtonBox.ActionRole) self.skipButton = QPushButton(QIcon(":/skip.svg"), "S&kip") self.tooltips.append((self.skipButton, """\ <p><b>Skip</b></p> <p>Skip this term's overlapping pages, and move to the next term with overlapping pages.</p>""")) self.buttonBox.addButton(self.skipButton, QDialogButtonBox.ActionRole) self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Close") self.tooltips.append((self.closeButton, """<p><b>Close</b></p> <p>Close the dialog.</p>""")) self.buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole) self.helpButton = QPushButton(QIcon(":/help.svg"), "Help") self.tooltips.append( (self.helpButton, "Help on the Combine Overlapping Pages dialog")) self.buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole) def layoutWidgets(self): layout = QFormLayout() layout.addRow(self.termLabelLabel, self.termLabel) layout.addRow("Pages", self.originalPagesLabel) layout.addRow("Pages if Combined", self.combinedPagesLabel) layout.addRow(self.buttonBox) self.setLayout(layout) def createConnections(self): self.buttonBox.rejected.connect(self.reject) self.combineButton.clicked.connect(self.combine) self.skipButton.clicked.connect(self.skip) self.helpButton.clicked.connect(self.help) def help(self): self.state.help("xix_ref_dlg_combpages.html") def updateUi(self): if bool(self.eids) and self.eidIndex < len(self.eids): enableReplace = (self.combinedPagesLabel.text() != self.originalPagesLabel.text()) self.combineButton.setEnabled(enableReplace) self.skipButton.setEnabled(True) if enableReplace: self.combineButton.setFocus() else: self.skipButton.setFocus() else: self.combineButton.setEnabled(False) self.skipButton.setEnabled(False) def combine(self): pages = self.combinedPagesLabel.text() if pages != self.originalPagesLabel.text(): with Lib.BlockSignals(self.state.model): self.state.model.editEntry(self.entry, self.entry.saf, self.entry.sortas, self.entry.term, pages) self.skip() def skip(self): self.eidIndex += 1 while 0 <= self.eidIndex < len(self.eids): self.entry = self.state.model.entry(self.eids[self.eidIndex]) self.termLabelLabel.setText("Term ({:,} of {:,})".format( self.eidIndex + 1, len(self.eids))) self.termLabel.setText( Lib.elidePatchHtml(self.entry.term, self.state)) self.originalPagesLabel.setText(self.entry.pages) pages = Pages.combinedOverlappingPages(self.entry.pages) self.combinedPagesLabel.setText(pages) self.combinedPagesLabel.setStyleSheet( _BG_DIFFERENT if pages != self.entry.pages else _BG_SAME) if pages != self.entry.pages: break self.eidIndex += 1 self.updateUi() def reject(self): message = "Combine overlapping pages" if self.state.model.canUndo: self.state.model.can_undo.emit(True, message) if self.state.model.canRedo: self.state.model.can_redo.emit(True, message) self.state.updateUi() super().accept() # Because this is Close not Cancel
class AddAccountDialog(QDialog): # --------------------------------------------------------------------- def __init__(self, parent=None): super(AddAccountDialog, self).__init__(parent) # self.setAttribute(Qt.WA_DeleteOnClose) lbMinWidth = 150 leMinWidth = 200 self.isMatch = False # self.keyDialog.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.setWindowTitle("Create a new account preset") baseLayout = QVBoxLayout(self) nameLayout = QHBoxLayout() keyLayout = QHBoxLayout() keyConfirmLayout = QHBoxLayout() baseLayout.addLayout(nameLayout) baseLayout.addLayout(keyLayout) baseLayout.addLayout(keyConfirmLayout) lb_name = QLabel('Account Preset Name: ', self) lb_name.setMinimumWidth(lbMinWidth) self.name_le = QLineEdit(self) self.name_le.setMinimumWidth(leMinWidth) nameLayout.addWidget(lb_name) nameLayout.addWidget(self.name_le) lb_key = QLabel('Encryption Key: ', self) lb_key.setMinimumWidth(lbMinWidth) self.key_le = QLineEdit(self) # self.key_le.setPlaceholderText('Encryption Key') self.key_le.setEchoMode(self.key_le.Password) self.key_le.setMinimumWidth(leMinWidth) keyLayout.addWidget(lb_key) keyLayout.addWidget(self.key_le) lb_keyConfirm = QLabel('Confirm Key: ', self) lb_keyConfirm.setMinimumWidth(lbMinWidth) self.keyConfirm_le = QLineEdit(self) # self.keyConfirm_le.setPlaceholderText('Encryption Key') self.keyConfirm_le.setEchoMode(self.key_le.Password) self.keyConfirm_le.setMinimumWidth(leMinWidth) keyConfirmLayout.addWidget(lb_keyConfirm) keyConfirmLayout.addWidget(self.keyConfirm_le) self.okBtn = QPushButton(self.tr("&Ok")) self.okBtn.setDefault(True) self.okBtn.setEnabled(False) cancelBtn = QPushButton(self.tr("&Cancel")) cancelBtn.setAutoDefault(False) buttonBox = QDialogButtonBox(Qt.Horizontal, self) buttonBox.addButton(self.okBtn, QDialogButtonBox.AcceptRole) buttonBox.addButton(cancelBtn, QDialogButtonBox.RejectRole) baseLayout.addWidget(buttonBox) self.name_le.textChanged.connect(self.name_confirmator) self.key_le.textChanged.connect(self.key_confirmator) self.keyConfirm_le.textChanged.connect(self.key_confirmator) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) # --------------------------------------------------------------------- @Slot(unicode) def name_confirmator(self, name): if name and self.isMatch: self.okBtn.setEnabled(True) else: self.okBtn.setEnabled(False) # --------------------------------------------------------------------- def key_confirmator(self): if self.keyConfirm_le.text() == self.key_le.text(): if not self.keyConfirm_le.text(): self.key_le.setStyleSheet("QLineEdit {background: white;}") self.keyConfirm_le.setStyleSheet("QLineEdit {background: white;}") self.okBtn.setEnabled(False) self.isMatch = False else: self.key_le.setStyleSheet("QLineEdit {background: #BBFFAA;}") self.keyConfirm_le.setStyleSheet("QLineEdit {background: #BBFFAA;}") self.isMatch = True if self.name_le.text(): self.okBtn.setEnabled(True) else: self.okBtn.setEnabled(False) else: self.key_le.setStyleSheet("QLineEdit {background: #FFAAAA;}") self.keyConfirm_le.setStyleSheet("QLineEdit {background: #FFAAAA;}") self.okBtn.setEnabled(False) self.isMatch = False # --------------------------------------------------------------------- @staticmethod def getAccountPresetNameAndEncryptionKey(parent=None): dialog = AddAccountDialog(parent) result = dialog.exec_() if result: name = dialog.name_le.text() key = dialog.key_le.text() dialog.key_le.clear() dialog.keyConfirm_le.clear() return result, name, key else: return result
class LoginForm(QDialog): logged_in = Signal() def __init__(self, parent=None): super(LoginForm, self).__init__(parent) self.setWindowTitle("Login") self.status_icon = QIcon.fromTheme("user-offline") self.setWindowIcon(self.status_icon) self.server_status = QLabel() self.server_status.setAlignment(Qt.AlignCenter) self.server_status.setPixmap(self.status_icon.pixmap(64)) self.username = QLineEdit("Username") self.password = QLineEdit("Password") self.password.setEchoMode(QLineEdit.Password) self.login_button = QPushButton("Getting server status...") self.login_button.setEnabled(False) self.login_button.clicked.connect(self.login) self.login_button.setIcon(self.status_icon) self.ping_timer = QTimer(self) self.connect(self.ping_timer, SIGNAL("timeout()"), self.is_server_up) self.ping_timer.start(1000) layout = QVBoxLayout() for w in (self.server_status, self.username, self.password, self.login_button): layout.addWidget(w) self.setLayout(layout) self.logged_in.connect(qtclient.login) def is_server_up(self): '''Tests to see if the authentication server is up.''' global client from requests.exceptions import ConnectionError try: if client.ping(): self.login_button.setEnabled(True) self.login_button.setText("Login!") self.status_icon = QIcon.fromTheme("user-online") except(ConnectionError): # We can only wait until the server comes back up. self.login_button.setEnabled(False) self.login_button.setText("Server is offline. :(") self.status_icon = QIcon.fromTheme("user-offline") self.setWindowIcon(self.status_icon) self.server_status.setPixmap(self.status_icon.pixmap(64)) self.login_button.setIcon(self.status_icon) def login(self): # TODO: This could be an exception if login failed. Catch it. login_result = client.authenticate(self.username.text(), self.password.text()) if login_result: # We logged in, so show the character select dialog self.logged_in.emit() # Once its shown, mark this dialog as accepted (And by extension, close it.) self.accept()
class MainWindow(QMainWindow): def __init__(self, datta): QMainWindow.__init__(self) self.setWindowTitle('Project Parser') appIcon = QIcon('search.png') self.setWindowIcon(appIcon) self.viewPortBL = QDesktopWidget().availableGeometry().topLeft() self.viewPortTR = QDesktopWidget().availableGeometry().bottomRight() self.margin = int(QDesktopWidget().availableGeometry().width()*0.1/2) self.shirina = QDesktopWidget().availableGeometry().width() - self.margin*2 self.visota = QDesktopWidget().availableGeometry().height() - self.margin*2 self.setGeometry(self.viewPortBL.x() + self.margin, self.viewPortBL.y() + self.margin, self.shirina, self.visota) # statusbar self.myStatusBar = QStatusBar() self.setStatusBar(self.myStatusBar) #lower long layout self.lowerLong = QFrame() self.detailsLabel = QLabel() self.skillsLabel = QLabel() self.urlLabel = QLabel() self.locationLabel = QLabel() self.skillsLabel.setText('skills') self.detailsLabel.setWordWrap(True) self.la = QVBoxLayout() self.la.addWidget(self.detailsLabel) self.la.addWidget(self.skillsLabel) self.la.addWidget(self.urlLabel) self.la.addWidget(self.locationLabel) self.lowerLong.setLayout(self.la) # table self.source_model = MyTableModel(self, datta, ['Id', 'Date', 'Title']) self.proxy_model = myTableProxy(self) self.proxy_model.setSourceModel(self.source_model) self.proxy_model.setDynamicSortFilter(True) self.table_view = QTableView() self.table_view.setModel(self.proxy_model) self.table_view.setAlternatingRowColors(True) self.table_view.resizeColumnsToContents() self.table_view.resizeRowsToContents() self.table_view.horizontalHeader().setStretchLastSection(True) self.table_view.setSortingEnabled(True) self.table_view.sortByColumn(2, Qt.AscendingOrder) # events self.selection = self.table_view.selectionModel() self.selection.selectionChanged.connect(self.handleSelectionChanged) #DO NOT use CreateIndex() method, use index() index = self.proxy_model.index(0,0) self.selection.select(index, QItemSelectionModel.Select) self.upperLong = self.table_view # right side widgets self.right = QFrame() self.la1 = QVBoxLayout() self.btnDownload = QPushButton('Download data') self.btnDownload.clicked.connect(self.download) self.myButton = QPushButton('Show Skillls') self.myButton.clicked.connect(self.showAllSkills) self.btnSearchByWord = QPushButton('Search by word(s)') self.btnSearchByWord.clicked.connect(self.onSearchByWord) self.btnResetFilter= QPushButton('Discard Filter') self.btnResetFilter.clicked.connect(self.discardFilter) self.btnCopyURL = QPushButton('URL to Clipboard') self.btnCopyURL.clicked.connect(self.copyToClipboard) self.btnExit = QPushButton('Exit') self.btnExit.clicked.connect(lambda: sys.exit()) self.dateTimeStamp = QLabel() self.la1.addWidget(self.btnDownload) self.la1.addSpacing(10) self.la1.addWidget(self.myButton) self.la1.addSpacing(10) self.la1.addWidget(self.btnSearchByWord) self.la1.addSpacing(10) self.la1.addWidget(self.btnResetFilter) self.la1.addSpacing(10) self.la1.addWidget(self.btnCopyURL) self.la1.addSpacing(70) self.la1.addWidget(self.btnExit) self.la1.addStretch(stretch=0) self.la1.addWidget(self.dateTimeStamp) self.right.setLayout(self.la1) self.right.setFrameShape(QFrame.StyledPanel) # splitters self.horiSplit = QSplitter(Qt.Vertical) self.horiSplit.addWidget(self.upperLong) self.horiSplit.addWidget(self.lowerLong) self.horiSplit.setSizes([self.visota/2, self.visota/2]) self.vertiSplit = QSplitter(Qt.Horizontal) self.vertiSplit.addWidget(self.horiSplit) self.vertiSplit.addWidget(self.right) self.vertiSplit.setSizes([self.shirina*3/4, self.shirina*1/4]) self.setCentralWidget(self.vertiSplit) self.settings = QSettings('elance.ini', QSettings.IniFormat) self.settings.beginGroup('DATE_STAMP') self.dateTimeStamp.setText('Data actuality: %s' % self.settings.value('date/time')) self.settings.endGroup() self.statusText = '' def handleSelectionChanged(self, selected, deselected): for index in selected.first().indexes(): #print('Row %d is selected' % index.row()) ind = index.model().mapToSource(index) desc = ind.model().mylist[ind.row()]['Description'] self.detailsLabel.setText(desc) skills = ', '.join(ind.model().mylist[ind.row()]['Skills']).strip() self.skillsLabel.setText(skills) url = ind.model().mylist[ind.row()]['URL'] self.urlLabel.setText(url) location = ind.model().mylist[ind.row()]['Location'] self.locationLabel.setText(location) def showAllSkills(self): listSkills = [] for elem in self.source_model.mylist: listSkills += elem['Skills'] allSkills = Counter(listSkills) tbl = MyTableModel(self, allSkills.items(), ['Skill', 'Freq']) win = skillsWindow(tbl, self.table_view) win.exec_() def discardFilter(self): self.table_view.model().emit(SIGNAL("modelAboutToBeReset()")) self.table_view.model().criteria = {} self.table_view.model().emit(SIGNAL("modelReset()")) self.table_view.resizeRowsToContents() def download(self): self.btnDownload.setDisabled(True) self.statusLabel = QLabel('Connecting') self.progressBar = QProgressBar() self.progressBar.setMinimum(0) self.progressBar.setMaximum(100) self.myStatusBar.addWidget(self.statusLabel, 2) self.myStatusBar.addWidget(self.progressBar, 1) self.progressBar.setValue(1) self.settings.beginGroup('URLS') initialLink = self.settings.value('CategoriesDetailed/VahaSelected/InitialLink') pagingLink = self.settings.value('CategoriesDetailed/VahaSelected/PagingLink') self.settings.endGroup() downloader = Downloader(initialLink, pagingLink, 25, 5) downloader.messenger.downloadProgressChanged.connect(self.onDownloadProgressChanged) downloader.messenger.downloadComplete.connect(self.onDownloadComplete) downloader.download() def onDownloadComplete(self): #QMessageBox.information(self, 'Download complete', 'Download complete!', QMessageBox.Ok) self.table_view.model().emit(SIGNAL("modelAboutToBeReset()")) self.settings.beginGroup('DATE_STAMP') self.settings.setValue('date/time', time.strftime('%d-%b-%Y, %H:%M:%S')) self.dateTimeStamp.setText('Data actuality: %s' % self.settings.value('date/time')) self.settings.endGroup() with open("elance.json") as json_file: jobDB = json.load(json_file) for elem in jobDB: words = nltk.tokenize.regexp_tokenize(elem['Title'].lower(), r'\w+') elem['Tokens'] = words elem['Skills'] = [t.strip() for t in elem['Skills'].split(',')] self.source_model.mylist = jobDB self.table_view.model().emit(SIGNAL("modelReset()")) self.btnDownload.setEnabled(True) self.myStatusBar.removeWidget(self.statusLabel) self.myStatusBar.removeWidget(self.progressBar) self.myStatusBar.showMessage(self.statusText, timeout = 5000) def onDownloadProgressChanged(self, stata): self.progressBar.setValue(stata[2]) #text = 'Processed records{:5d} of{:5d}'.format(percentage[0], percentage[1]) bajtikov = '{:,}'.format(stata[5]) self.statusText = 'Processed page{:4d} of{:4d}. \ Job entries{:5d} of{:5d}. \ Downloaded{:>12s} Bytes'.format(stata[3], stata[4], stata[0], stata[1], bajtikov) self.statusLabel.setText(self.statusText) def copyToClipboard(self): clipboard = QApplication.clipboard() clipboard.setText(self.urlLabel.text()) self.myStatusBar.showMessage(self.urlLabel.text(), timeout = 3000) def onSearchByWord(self): text, ok = QInputDialog.getText(self, 'Search the base by word(s)', 'Enter your keyword/phrase to search for:') if ok: words = [t.strip() for t in nltk.tokenize.regexp_tokenize(text.lower(), r'\w+')] self.table_view.model().emit(SIGNAL("modelAboutToBeReset()")) self.table_view.model().criteria = {'Description' : words} self.table_view.model().emit(SIGNAL("modelReset()"))
class Meso1819Gui( QMainWindow ): timeCheck = Signal(); # Signal for time checking; used if the user tries to create Skew-T before the request sounding time actually happens; i.e., sounding date is in future def __init__(self, parent = None): QMainWindow.__init__(self); # Initialize the base class self.setWindowTitle('Meso 18/19 Sounding Processor'); # Set the window title self.src_dir = None; # Set attribute for source data directory to None self.dst_dir = None; # Set attribute for destination data directory to None self.dst_dirFull = None; # Set attribute for destination data directory to None self.iopName = None; # Set attribute for the IOP name to None self.dateFrame = None; # Set attribute for the date QFrame to None self.date = None; self.date_str = None; # Set attribute for date string self.skew = None; # Set attribute for the skewt plot to None self.sndDataFile = None; # Set attribute for sounding data input file self.sndDataPNG = None; # Set attribute for sounding image file self.ftpInfo = None; # Set attribute for ftp info self.ranFTP = False; # Boolean to check if FTP uploading has been tried self.config = ConfigParser.RawConfigParser(); # Initialize a ConfigParser; required for the SPCWidget self.timeCheck.connect( self.on_timeCheck ); # Connect on_timeCheck method to the timeCheck signal if not self.config.has_section('paths'): # If there is no 'paths' section in the parser self.config.add_section( 'paths' ); # Add a 'paths' section to the parser self.log = logging.getLogger( __name__ ); # Get a logger rfh = RotatingFileHandler(_logfile,maxBytes=_logsize,backupCount=_logcount);# Create rotating file handler rfhFMT = logging.Formatter( '%(asctime)s - ' + settings.log_fmt ); # Logger format rfh.setFormatter( rfhFMT ) rfh.setLevel( logging.DEBUG ); # Set log level to debug self.log.addHandler( rfh ); # Add handler to main logger self.initUI(); # Run method to initialize user interface ############################################################################## def initUI(self): ''' Method to setup the buttons/entries of the Gui ''' self.dateFrame = dateFrame( ); # Initialize the dateFrame self.iopLabel = QLabel('IOP Number'); # Initialize Entry widget for the IOP name self.iopName = QLineEdit(); # Initialize Entry widget for the IOP name self.stationLabel = QLabel('Station Name'); # Initialize Entry widget for the IOP name self.stationName = QLineEdit(); # Initialize Entry widget for the IOP name self.sourceButton = QPushButton('Source Directory'); # Initialize button for selecting the source directory self.destButton = QPushButton('Destination Directory'); # Initialize button for selecting the destination directory self.sourcePath = QLineEdit(''); # Initialize entry widget that will display the source directory path self.destPath = QLineEdit(''); # Initialize entry widget that will display the destination directory path self.sourceSet = indicator(); # Initialize an indictor that will appear when the source path is set self.destSet = indicator(); # Initialize an indictor that will appear when the destination path is set self.sourcePath.setEnabled( False ); # Disable the sourcePath widget; that way no one can manually edit it self.destPath.setEnabled( False ); # Disable the destPath widget; that way no one can manually edit it self.sourcePath.hide(); # Hide the source directory path self.destPath.hide(); # Hide the destination directory path self.sourceSet.hide(); # Hide the source directory indicator self.destSet.hide(); # Hide the destination directory indicator self.sourceButton.clicked.connect( self.select_source ); # Set method to run when the source button is clicked self.destButton.clicked.connect( self.select_dest ); # Set method to run when the destination button is clicked self.copyButton = QPushButton( 'Copy Files' ); # Create 'Copy Files' button self.copyButton.clicked.connect( self.copy_files ); # Set method to run when 'Copy Files' button is clicked self.copyButton.setEnabled(False); # Set enabled state to False; cannot click until after the source and destination directories set self.copySucces = indicator(); # Initialize an indictor that will appear when the copy complete successfuly self.copySucces.hide(); self.procButton = QPushButton( 'Process Files' ); # Create 'Process Files' button self.procButton.clicked.connect( self.proc_files ); # Set method to run when 'Process Files' button is clicked self.procButton.setEnabled(False); # Set enabled state to False; cannot click until after 'Copy Files' completes self.procSucces = indicator(); # Initialize an indictor that will appear when the processing complete successfuly self.procSucces.hide(); self.genButton = QPushButton( 'Generate Sounding' ); # Create 'Generate Sounding' button self.genButton.clicked.connect( self.gen_sounding ); # Set method to run when 'Generate Sounding' button is clicked self.genButton.setEnabled(False); # Set enabled state to False; cannot click until after 'Process Files' completes self.genSucces = indicator(); # Initialize an indictor that will appear when the sounding generation complete successfuly self.genSucces.hide(); self.uploadButton = QPushButton( 'FTP Upload' ); # Create 'FTP Upload' button self.uploadButton.clicked.connect( self.ftp_upload ); # Set method to run when 'FTP Upload' button is clicked self.uploadButton.setEnabled(False); # Set enabled state to False; cannot click until after 'Generate Sounding' completes self.uploadSucces = indicator(); # Initialize an indictor that will appear when the ftp upload complete successfuly self.uploadSucces.hide(); self.checkButton = QPushButton( 'Check website' ); # Create 'Check website' button self.checkButton.clicked.connect( self.check_site ); # Set method to run when 'Check website' button is clicked self.checkButton.setEnabled(False); # Set enabled state to False; cannot click until after 'FTP Upload' completes self.resetButton = QPushButton( 'Reset' ); # Create 'Check website' button self.resetButton.clicked.connect( self.reset_values ); # Set method to run when 'Check website' button is clicked versionLabel = QLabel( 'version: {}'.format(__version__) ); # Version label versionLabel.setAlignment( Qt.AlignHCenter ); # Set alignment to center log_handler = QLogger( ); # Initialize a QLogger logging.Handler object logging.getLogger('Meso1819').addHandler( log_handler ); # Get the Meso1819 root logger and add the handler to it grid = QGridLayout(); # Initialize grid layout grid.setSpacing(10); # Set spacing to 10 for i in range(4): grid.setColumnStretch(i, 0); # Set column stretch for ith column grid.setColumnMinimumWidth(i, 60); # Set column min width for ith column grid.setColumnStretch(4, 0); # Set column stretch for 5th column grid.setColumnMinimumWidth(4, 20); # Set column min width for 5th column grid.setRowStretch(1, 0); # Set column stretch for 5th column grid.setRowStretch(3, 0); # Set column stretch for 5th column grid.setRowMinimumHeight(1, 25); # Set column min width for 5th column grid.setRowMinimumHeight(3, 25); # Set column min width for 5th column grid.addWidget( self.sourceButton, 0, 0, 1, 4 ); # Place a widget in the grid grid.addWidget( self.sourceSet, 0, 4, 1, 1 ); # Place a widget in the grid grid.addWidget( self.sourcePath, 1, 0, 1, 5 ); # Place a widget in the grid grid.addWidget( self.destButton, 2, 0, 1, 4 ); # Place a widget in the grid grid.addWidget( self.destSet, 2, 4, 1, 1 ); # Place a widget in the grid grid.addWidget( self.destPath, 3, 0, 1, 5 ); # Place a widget in the grid grid.addWidget( self.iopLabel, 4, 0, 1, 2 ); # Place a widget in the grid grid.addWidget( self.iopName, 5, 0, 1, 2 ); # Place a widget in the grid grid.addWidget( self.stationLabel, 4, 2, 1, 2 ); # Place a widget in the grid grid.addWidget( self.stationName, 5, 2, 1, 2 ); # Place a widget in the grid grid.addWidget( self.dateFrame, 6, 0, 1, 4 ); # Place a widget in the grid grid.addWidget( self.copyButton, 7, 0, 1, 4 ); # Place a widget in the grid grid.addWidget( self.copySucces, 7, 4, 1, 1 ); # Place a widget in the grid grid.addWidget( self.procButton, 8, 0, 1, 4 ); # Place a widget in the grid grid.addWidget( self.procSucces, 8, 4, 1, 1 ); # Place a widget in the grid grid.addWidget( self.genButton, 9, 0, 1, 4 ); # Place a widget in the grid grid.addWidget( self.genSucces, 9, 4, 1, 1 ); # Place a widget in the grid grid.addWidget( self.uploadButton, 10, 0, 1, 4 ); # Place a widget in the grid grid.addWidget( self.uploadSucces, 10, 4, 1, 1 ); # Place a widget in the grid grid.addWidget( self.checkButton, 11, 0, 1, 4 ); # Place a widget in the grid grid.addWidget( self.resetButton, 12, 0, 1, 4 ); # Place a widget in the grid grid.addWidget( log_handler.frame, 0, 6, 13, 1); grid.addWidget( versionLabel, 20, 0, 1, 7) centralWidget = QWidget(); # Create a main widget centralWidget.setLayout( grid ); # Set the main widget's layout to the grid self.setCentralWidget(centralWidget); # Set the central widget of the base class to the main widget self.show( ); # Show the main widget ############################################################################## def select_source(self, *args): ''' Method for selecting the source directory of the sounding data that was collected ''' self.log.info('Setting the source directory') src_dir = QFileDialog.getExistingDirectory( dir = _desktop ); # Open a selection dialog self.src_dir = None if src_dir == '' else src_dir; # Update the src_dir attribute based on the value of src_dir if self.src_dir is None: # If the src_dir attribute is None self.log.warning( 'No source directory set' ); # Log a warning self.reset_values( noDialog = True ); # Reset all the values in the GUI with no confirmation dialog else: # Else self.sourcePath.setText( src_dir ); # Set the sourcePath label text self.sourcePath.show(); # Show the sourcePath label self.sourceSet.show(); # Show the sourceSet icon if self.dst_dir is not None: # If the dst_dir attribute is not None self.copyButton.setEnabled( True ); # Set the 'Copy Files' button to enabled self.reset_values(noDialog = True, noSRC = True, noDST = True); # Reset all values excluding the src AND dst directory else: self.reset_values(noDialog = True, noSRC = True); # Reset all values excluding the src directory ############################################################################## def select_dest(self, *args): ''' Method for selecting the destination directory of the sounding data that was collected ''' self.log.info('Setting the destination directory') dst_dir = QFileDialog.getExistingDirectory( dir = _desktop); # Open a selection dialog self.dst_dir = None if dst_dir == '' else dst_dir; # Update the dst_dir attribute based on the value of dst_dir if self.dst_dir is None: # If the dst_dir attribute is None self.log.warning( 'No destination directory set' ) # Log a warning self.reset_values( noDialog = True ) # Reset all the values in the GUI with no confirmation dialog else: # Else if 'IOP' in os.path.basename( self.dst_dir ).upper(): # If an IOP directory was selected self.log.debug('Moved IOP# from directory path as it is append later'); # Log some debugging information self.dst_dir = os.path.dirname( self.dst_dir ); # Remove the IOP directory from the destination directory self.destSet.show( ); # Set the destPath label text self.destPath.setText( self.dst_dir ) # Show the destPath label self.destPath.show() # Show the destSet icon if self.src_dir is not None: # If the src_dir attribute is not None self.copyButton.setEnabled( True ); # Set the 'Copy Files' button to enabled self.reset_values(noDialog = True, noSRC = True, noDST = True); # Reset all values excluding the src AND dst directory else: self.reset_values(noDialog = True, noDST = True); # Reset all values excluding the dst directory ############################################################################## def copy_files(self, *args): ''' Method for copying files from source to destination, renaming files along the way ''' if self.dst_dir is None: self.log.error( 'Destination directory NOT set!' ); return; if self.src_dir is None: self.log.error( 'Source directory NOT set!' ); return; if self.iopName.text() == '': self.log.error( 'IOP Number NOT set!!!' ) criticalMessage( "Must set the IOP Number!!!" ).exec_(); return if self.stationName.text() == '': self.log.error( 'Station Name NOT set!!!' ) criticalMessage( "Must set the Station Name!!!" ).exec_(); return # Main copying code failed = False; # Initialize failed to False self.__init_ftpInfo(); # Initialize ftpInfo attribute using method self.date, self.date_str = self.dateFrame.getDate( ); # Get datetime object and date string as entered in the gui if self.date is None: return; # If the date variable is set to None self.dst_dirFull = os.path.join( self.dst_dir, 'IOP'+self.iopName.text(), self.date_str ); # Build destination directory using the dst_dir, iopName, and date string if not os.path.isdir( self.dst_dirFull ): # If the output directory does NOT exist self.log.info( 'Creating directory: ' + self.dst_dirFull ); # Log some information os.makedirs( self.dst_dirFull ); # IF the dst_dir does NOT exist, then create it else: # Else, the directory exists, so check to over write dial = confirmMessage( "The destination directory exists!\n" + \ "Do you want to overwrite it?\n\n" + \ "YOU CANNOT UNDO THIS ACTION!!!" ); dial.exec_(); # Generate the message window if dial.check(): self.log.info( 'Removing directory: ' + self.dst_dirFull ); # Log some information shutil.rmtree( self.dst_dirFull ); # Delete the directory self.log.info( 'Creating directory: ' + self.dst_dirFull ); # Log some information os.makedirs( self.dst_dirFull ); # IF the dst_dir does NOT exist, then create it else: # Else, don't do anything self.log.warning('Cannot over write data!'); # Log a warning return; # Return from function self.log.info( 'Source directory: {}'.format(self.src_dir) ); # Log some information self.log.info( 'Destination directory: {}'.format(self.dst_dirFull) ); # Log some information self.log.info( 'Copying directory' ); # Log some information for root, dirs, files in os.walk( self.src_dir ): # Walk over the source directory for file in files: # Loop over all files src = os.path.join( root, file ); # Set the source file path dst = os.path.join( self.dst_dirFull, file ); # Set the destination path shutil.copy2( src, dst ); # Copy all data from the source directory to the dst_dir if not os.path.isfile( dst ): # If the destination file does NOT exist self.log.error( 'There was an error copying file: {}'.format(file) ); # Log a warning failed = True; # Set failed to True break; # Break the for loop if not failed: self.log.info( 'Finished copying' ); # log some information self.log.info( 'Ready to process data files!' ); # Log some info self.copySucces.show(); # Show green light next to the 'Copy Files' button to indicate that step is complete self.procButton.setEnabled( True ); # Enable the 'Process Files' button else: # Else, something went wrong criticalMessage( "Something went wrong!\n\n" + \ "There was an error copying a data file.\n" + \ "Please check the logs and directories to see what happened." ).exec_(); ############################################################################## def proc_files(self, *args): ''' Method for processing sounding files; i.e., renaming and removing values where ballon is descending in sounding ''' failed = False; # Initialize failed to False self.log.info( 'Processing files' ); files = os.listdir( self.dst_dirFull ); # Get list of all files in the directory rename_status = dict.fromkeys( settings.rename.keys(), False); # Status of file renaming process_status = dict.fromkeys( settings.convert.keys(), False); # Status of file processing for file in files: # Iterate over the list of files for key in settings.rename: # Loop over the keys in the settings.rename dictionary if key in file: # If the key is in the source file name rename_status[key] = True; # Add rname status as True dst_file = settings.rename[key].format( self.date_str ); # Set a destination file name dst = os.path.join( self.dst_dirFull, dst_file ); # Build the destination file path src = os.path.join( self.dst_dirFull, file ); # Set source file path # self.uploadFiles.append( dst ); # Append the file to the uploadFile list self.log.info( 'Moving file: {} -> {}'.format(src, dst) ); # Log some information os.rename( src, dst ); # Move the file if not os.path.isfile( dst ): # If the renamed file does NOT exist self.log.error( 'There was an error renaming the file!' ); # Log an error failed = True; # Set failed to True file_found = False; # Flag for in the file to process is found! for key in settings.convert: # Loop over the keys in the settings.rename dictionary if key in file: # If the key is in the source file name process_status[key] = True; # Set to true if the file is found dst_file = settings.convert[key].format( self.date_str ); # Set a destination file name self.sndDataFile = os.path.join( self.dst_dirFull, dst_file ); # Build the destination file path src = os.path.join( self.dst_dirFull, file ); # Set source file path # self.uploadFiles.append( dst ); # Append the file to the uploadFile list self.log.info( 'Converting sounding data to SHARPpy format...' ); # Log some information res = iMet2SHARPpy( src, self.stationName.text().upper(), datetime = self.date, output = self.sndDataFile); # Run function to convert data to SHARPpy format if res and os.path.isfile( self.sndDataFile ): # If function returned True and the output file exists for key in self.ftpInfo: # Iterate over keys in ftpInfo attribute self.ftpInfo[key]['files'].append( self.sndDataFile ); # Append sounding data file path to files key in ftpInfo dictionary else: failed = True; # Set failed to True self.sndDataFile = None; # if the function failed to run OR the output file does NOT exist self.log.error( 'There was an error creating SHARPpy file!' ); # Log an error criticalMessage( 'Problem converting the sounding data to SHARPpy format!' ).exec_(); # Generate critical error message box if not all( rename_status.values() ): failed = True; self.log.error( 'There was an error renaming one or more files!' ); # Log an error criticalMessage( 'Problem renaming one or more files!' ).exec_(); # Generate critical error message box if not all( process_status.values() ): failed = True; self.log.error( 'There was an error converting one or more files to SHARPpy format!' ); # Log an error criticalMessage( 'Problem converting one or more files to SHARPpy format!' ).exec_(); # Generate critical error message box if not failed: # If failed is False self.procSucces.show(); # Show green light next to the 'Process Files' button to indicate that step is complete if self.date <= datetime.utcnow(): # If the date for the sound is NOT in the future self.timeCheck.emit(); # Emit signal to activate the 'Generate Sounding' button else: # Else, date for sounding IS in the future dt = self.date - datetime.utcnow(); # Compute the current time difference between the sounding and utcnow msg = ['Date requested is in the future!', 'Sounding generation disabled until requested sounding time', 'Wait time remaining {}'.format( str(dt) ) ]; # List that contains message for the logger self.log.warning( '\n'.join(msg) ); # Log the message as a warning criticalMessage( 'The data processing has completed!\n\n' + \ 'However, the requested date/time for the\n' + \ 'sounding is in the future!\n\n' +\ 'The \'Generate Sounding\' button will activate\n' + \ 'when the current time is after the requested time!' ).exec_(); # Generate critical error message box dt = (int( dt.total_seconds() ) + 2) * 1000; # Get total time between now and future time, add 2 seconds, convert to integer, then conver to milliseconds QTimer.singleShot( dt, self._timeCheck ); # Run single shot timer thread for the _timeCheck method, waiting dt milliseconds before running ############################################################################## def gen_sounding(self, *args): ''' Method for generating the SPC-like sounding using the SPCWindow class of SHARPpy. ''' self.log.info( 'Generating Skew-T diagram' ); # Log some information sndDataPNG = settings.skewT_fmt.format( self.date_str ); # Set the name for the skewT file using the settings.skew_T_fmt string self.sndDataPNG = os.path.join( self.dst_dirFull, sndDataPNG ); # Set the sndDataPNG attribute using the dst_dirFull attribute and sndDataFile variable save_msg = "Check that the image looks okay.\n " + \ "If ok, click save, else click cancel"; # Confirmation message for the save dialog for Skew-T; will update if cannot save Skew-T due to issue in SHARPpy sharppy_bug = False; # Flag for if sharppy bug encountered try: # Try to... decoder = SPCDecoder( self.sndDataFile ); # Decode the sounding file using the SPCDecoder profile = decoder.getProfiles(); # Get the profiles from the file stn_id = decoder.getStnId(); # Get the station id from the file except: # On exception criticalMessage( "There was an error loading the sounding data\n\n" ).exec_(); # Initialize and display critical error dialog return; # Return from method model = "Archive"; # Set model to 'Archive'; not sure why but was in the SHARPpy full_gui.py disp_name = stn_id; # Set the display name to the station ID from the sounding data file run = profile.getCurrentDate(); # Set the run to the current date from the sounding data profile.setMeta('model', model); # Set the model in the sounding data profile.setMeta('loc', disp_name); # Set the display name in the sounding data profile.setMeta('run', run); # Set the run in the sounding data if not profile.getMeta('observed'): # If it's not an observed profile profile.setAsync( AsyncThreads(2, debug) ); # Generate profile objects in background. Not sure why works but in SHARPpy full_gui.py self.log.debug('Generating SHARPpy window') if self.skew is None: # If there is no skew window setup; there should never be... self.skew = SPCWindow(cfg=self.config); # Initialize a new SPCWindow object self.skew.closed.connect(self.__skewAppClosed); # Connect the closed method to the __skewAppClosed private method self.skew.addProfileCollection(profile); # Add the profile data to the SPCWindow object try: self.skew.show(); # Show the window except: sharppy_bug = True; self.log.warning("SHARPpy didn't like that sounding very much!") save_msg = "Congradulations!\n\n" + \ "You just found a bug in SHARPpy.\n" + \ "There is nothing we can about this. No Skew-T can be created.\n" + \ "Just click 'Save' and continue with the uploading"; dial = saveMessage( save_msg ); # Set up save message pop-up dial.exec_(); # Display the save message pop-up if dial.check(): # If clicked save if not sharppy_bug: # If the SHARPpy bug did NOT occur self.ftpInfo['ucar']['files'].append( self.sndDataPNG ); # Append the SHARPpy image file name to the ftpInfo['ucar']['files'] list self.log.info('Saving the Skew-T to: {}'.format( self.sndDataPNG ) ); # Log some information pixmap = QPixmap.grabWidget( self.skew ); # Grab the image from the skew T window pixmap.save( self.sndDataPNG, 'PNG', 100); # Save the image self.config.set('paths', 'save_img', os.path.dirname(self.sndDataPNG)); # Add image path to the config object self.log.debug( 'Files to upload to UCAR: {}'.format( ', '.join(self.ftpInfo['ucar']['files']) ) ) self.genSucces.show(); # Show green light next to the 'Generate Sounding' button to indicate that step is complete self.uploadButton.setEnabled( True ); # Enable the upload button else: # Else self.log.critical('Skew-T save aborted! Not allowed to upload!'); # Log an error try: self.skew.close(); # Close the skew T window except: pass; ############################################################################## def ftp_upload(self, *args): if self.ranFTP: self.log.info( 'You already ran this step!' ); criticalMessage( "You already tried to upload to FTP" ).exec_(); # Initialize confirmation for quitting return; self.ranFTP = True; # Set ran FTP to True for key in self.ftpInfo: # Iterate over all keys in the ftpInfo dictionary self.log.info( 'Uploading data to: {}'.format(self.ftpInfo[key]['url']) );# Log some info try: # Try to... ftp = ftpUpload( self.ftpInfo[key]['url'] ); # Set up and FTP instance except: # On exception... self.log.critical( 'Error initializing the FTP upload: {}'.format( self.ftpInfo[key]['url'] ) ); # Log a critical error else: # Else... self.ftpInfo[key]['upload'] = ftp.uploadFiles( self.ftpInfo[key]['dir'], self.ftpInfo[key]['files'], user = self.ftpInfo[key]['user'], passwd = self.ftpInfo[key]['passwd'], ); # Attempt to upload the files if not self.ftpInfo[key]['upload']: # If one or more files failed to upload msg = 'FAILED!!! Upload to {} NOT successful'; # Formatter for error message self.log.critical( msg.format( self.ftpInfo[key]['url'] ) ); # Log a critical error criticalMessage( "Something went wrong!\n\n" + \ "There was an error uploading one or more files to the FTP.\n\n" + \ "FTP Address: {}\n\n".format( self.ftpInfo[key]['url'] ) + \ "Check the logs to determine which file(s) failed to upload.\n\n" + \ "YOU MUST MANUALLY UPLOAD ANY FILES THAT FAILED!!!" ).exec_(); else: self.log.info( 'Data upload successful!' ); if self.ftpInfo['ucar']['upload']: # If the upload to UCAR was a success self.uploadSucces.show(); # Show green light next to the 'FTP Upload' button to indicate that step is complete self.checkButton.setEnabled(True) ############################################################################## def check_site(self, *args): self.log.info( 'Checking site' ) webbrowser.open( settings.url_check ) ############################################################################## def reset_values(self, noDialog = False, noSRC = False, noDST = False): ''' Method to reset all the values in the GUI Keywords: noDialog : Set to true to disable the checking dialog noSRC : Set to true so that all values BUT source directory info are cleared noDST : Set to true so that all values BUT destination directory info are cleared Setting both noSRC and noDST will exclude the two directories ''' check = False; # Dialog check value initialize to False if not noDialog: # If noDialog is False dial = confirmMessage( 'Are you sure you want to reset all values?' ); # Initialize confirmation dialog dial.exec_(); # Display the confirmation dialog check = dial.check(); # Check which button selected if check or noDialog: # If the check is True or noDialog is True self.log.debug( 'Resetting all values!' ); # Log some information if not noSRC or not noDST: # If noSRC is False OR noDST is false self.copyButton.setEnabled( False ); # Set enabled state to False; cannot click until after the source and destination directories set self.procButton.setEnabled( False ); # Set enabled state to False; cannot click until after 'Copy Files' completes self.genButton.setEnabled( False ); # Set enabled state to False; cannot click until after 'Process Files' completes self.uploadButton.setEnabled( False ); # Set enabled state to False; cannot click until after 'Generate Sounding' completes self.checkButton.setEnabled( False ); # Set enabled state to False; cannot click until after 'FTP Upload' completes self.copySucces.hide(); self.procSucces.hide(); self.genSucces.hide() self.uploadSucces.hide(); if not noSRC: # If the noSRC keyword is NOT set self.sourcePath.hide(); # Hide the source directory path self.sourceSet.hide(); # Hide the source directory indicator if not noDST: # If the noDST keyword is NOT set self.destPath.hide(); # Hide the destination directory path self.destSet.hide(); # Hide the destination directory indicator self.dateFrame.resetDate(); # Reset all the dates self.iopName.setText( '' ); # Initialize Entry widget for the IOP name self.stationName.setText( '' ); # Initialize Entry widget for the IOP name self.ranFTP = False; # Reset ranFTP to False on reset self.__reset_ftpInfo(); ############################################################################## def closeEvent(self, event): ''' Method to override closeEvent handler to add a confirmation dialog to application quit ''' dial = confirmMessage( "Are you sure you want to quit?" ); # Initialize confirmation for quitting dial.exec_(); # Generate the message window if dial.check(): # If user selected yes on dialog event.accept(); # Accept the event and close the GUI else: # Else event.ignore(); # Ignore the event; i.e., keep GUI open ############################################################################## @Slot() def on_timeCheck(self): self.log.info( 'Ready to generate sounding image!' ); # Log some info self.genButton.setEnabled( True ); # Enable the 'Generate Sounding' button ############################################################################## def _timeCheck(self): if self.date <= datetime.utcnow(): # Check requested date is in the future AND the timeEvent is NOT set self.timeCheck.emit(); # Emit a signal to enable the 'Generate Sounding' button else: # Else, date is still in future... QTimer.singleShot( 1000, self._timeCheck ); # Wait one second and call this method again ############################################################################## def __skewAppClosed(self): self.skew = None; ############################################################################## def __init_ftpInfo(self): self.ftpInfo = {'ucar' : settings.ucar_ftp, 'noaa' : settings.noaa_ftp}; for key in self.ftpInfo: self.ftpInfo[key]['files'] = []; self.ftpInfo[key]['upload'] = False; ############################################################################## def __reset_ftpInfo(self): self.ftpInfo = None;
class FindReplaceDialog(QDialog): """A find and replace dialog that has a search-as-I-type option The caller should keep a reference to this dialog, or delete it explicitly""" find_text_changed = Signal(str) replace_committed = Signal(str, str) find_cancelled = Signal() def __init__(self, parent=None): super(FindReplaceDialog, self).__init__(parent) layout = QGridLayout() # prepare the widgets label_find = QLabel(self.tr("Find")) self.lineedit_find = QLineEdit() label_replace = QLabel(self.tr("Replace")) self.lineedit_replace = QLineEdit() self.checkbox_dynamic_find = QCheckBox(self.tr("Search as I type")) self.button_find = QPushButton(self.tr("Find")) self.button_replace = QPushButton(self.tr("Replace")) button_cancel = QPushButton(self.tr("Cancel")) # connect the signals self.lineedit_find.textEdited.connect(self._findEdited) self.button_find.clicked.connect(self._emitFind) self.checkbox_dynamic_find.stateChanged.connect(self._dynamicFindChanged) self.button_replace.clicked.connect(self._emitReplacement) button_cancel.clicked.connect(self._cancel) # setup the layout row = 0; col = 0; layout.addWidget(label_find, row, col) col += 1; layout.addWidget(self.lineedit_find, row, col) row += 1; col -= 1 layout.addWidget(label_replace, row, col) col += 1 layout.addWidget(self.lineedit_replace, row, col) row += 1; col -= 1; layout.addWidget(self.checkbox_dynamic_find, row, col, 1, 2) row += 1 layout.addWidget(self.button_find, row, col) col += 1 layout.addWidget(self.button_replace, row, col) row += 1; col -= 1 layout.addWidget(button_cancel, row, col, 1, 2) self.setLayout(layout) self.setWindowTitle(self.tr("Find/Replace")) def keyPressEvent(self, kpe): if kpe.key() == Qt.Key.Key_Enter: self._emitFind() else: super(FindReplaceDialog, self).keyPressEvent(kpe) def _findEdited(self, text): if self.checkbox_dynamic_find.isChecked(): self.find_text_changed.emit(text) else: pass def _emitFind(self): self.find_text_changed.emit(self.lineedit_find.text()) def _dynamicFindChanged(self, state): print state if self.button_find.isEnabled(): self.button_find.setEnabled(False) else: self.button_find.setEnabled(True) def _emitReplacement(self): # don't emit a replacement with empty fields if not self.lineedit_find.text() or not self.lineedit_replace.text(): QApplication.beep() else: self.replace_committed.emit(self.lineedit_find.text(), self.lineedit_replace.text()) def _cancel(self): self.find_cancelled.emit() self.hide() def closeEvent(self, ce): self._cancel()
class TransferPanel(QWidget): ''' Transfer Panel This Panel is the main dialog box for the Dive Computer Transfer GUI ''' def __init__(self, parent=None): super(TransferPanel, self).__init__(parent) self._logbook = None self._logbookName = 'None' self._logbookPath = None self._createLayout() self._readSettings() self.setWindowTitle(self.tr('DC Transfer - %s') % self._logbookName) def _createLayout(self): 'Create the Widget Layout' self._txtLogbook = QLineEdit() self._txtLogbook.setReadOnly(True) self._lblLogbook = QLabel(self.tr('&Logbook File:')) self._lblLogbook.setBuddy(self._txtLogbook) self._btnBrowse = QPushButton('...') self._btnBrowse.clicked.connect(self._btnBrowseClicked) self._btnBrowse.setStyleSheet('QPushButton { min-width: 24px; max-width: 24px; }') self._btnBrowse.setToolTip(self.tr('Browse for a Logbook')) self._cbxComputer = QComboBox() self._lblComputer = QLabel(self.tr('Dive &Computer:')) self._lblComputer.setBuddy(self._cbxComputer) self._btnAddComputer = QPushButton(QPixmap(':/icons/list-add.png'), self.tr('')) self._btnAddComputer.setStyleSheet('QPushButton { min-width: 24px; min-height: 24; max-width: 24px; max-height: 24; }') self._btnAddComputer.clicked.connect(self._btnAddComputerClicked) self._btnRemoveComputer = QPushButton(QPixmap(':/icons/list-remove.png'), self.tr('')) self._btnRemoveComputer.setStyleSheet('QPushButton { min-width: 24px; min-height: 24; max-width: 24px; max-height: 24; }') self._btnRemoveComputer.clicked.connect(self._btnRemoveComputerClicked) hbox = QHBoxLayout() hbox.addWidget(self._btnAddComputer) hbox.addWidget(self._btnRemoveComputer) gbox = QGridLayout() gbox.addWidget(self._lblLogbook, 0, 0) gbox.addWidget(self._txtLogbook, 0, 1) gbox.addWidget(self._btnBrowse, 0, 2) gbox.addWidget(self._lblComputer, 1, 0) gbox.addWidget(self._cbxComputer, 1, 1) gbox.addLayout(hbox, 1, 2) gbox.setColumnStretch(1, 1) self._pbTransfer = QProgressBar() self._pbTransfer.reset() self._txtStatus = QTextEdit() self._txtStatus.setReadOnly(True) self._btnTransfer = QPushButton(self.tr('&Transfer Dives')) self._btnTransfer.clicked.connect(self._btnTransferClicked) self._btnExit = QPushButton(self.tr('E&xit')) self._btnExit.clicked.connect(self.close) hbox = QHBoxLayout() hbox.addWidget(self._btnTransfer) hbox.addStretch() hbox.addWidget(self._btnExit) vbox = QVBoxLayout() vbox.addLayout(gbox) vbox.addWidget(self._pbTransfer) vbox.addWidget(self._txtStatus) vbox.addLayout(hbox) self.setLayout(vbox) def _closeLogbook(self): 'Close the current Logbook' if self._logbook is None: return self._logbook = None self._logbookName = 'None' self._logbookPath = None self._txtLogbook.clear() self._cbxComputer.setModel(None) self._writeSettings() self.setWindowTitle(self.tr('DC Transfer - %s') % self._logbookName) def _openLogbook(self, path): 'Open an existing Logbook' if self._logbook is not None: self._closeLogbook() if not os.path.exists(path): QMessageBox.critical(self, self.tr('Missing Logbook'), self.tr('Logbook File "%s" does not exist.') % path) return #TODO: Handle a Schema Upgrade in a user-friendly manner self._logbook = Logbook(path, auto_update=False) self._logbookName = os.path.basename(path) self._logbookPath = path self._txtLogbook.setText(self._logbookPath) self._cbxComputer.setModel(DiveComputersModel(self._logbook)) self._writeSettings() self.setWindowTitle(self.tr('DC Transfer - %s') % self._logbookName) def _readSettings(self): 'Read main window settings from the configuration' settings = QSettings() settings.beginGroup('MainWindow') max = settings.value('max') size = settings.value('size') pos = settings.value('pos') file = settings.value('file') settings.endGroup() # Size and Position the Main Window if size is not None: self.resize(size) if pos is not None: self.move(pos) # HAX because QVariant is not exposed in PySide and the default # coercion to string is just stupid if max is not None and (max == 'true'): self.showMaximized() # Open the Logbook if file is not None: self._openLogbook(file) def _writeSettings(self): 'Write settings to the configuration' settings = QSettings() settings.beginGroup('MainWindow') settings.setValue('pos', self.pos()) settings.setValue('size', self.size()) settings.setValue('max', self.isMaximized()) settings.setValue('file', self._logbookPath) settings.endGroup() def closeEvent(self, e): 'Intercept an OnClose event' self._writeSettings() e.accept() #-------------------------------------------------------------------------- # Slots @QtCore.Slot() def _btnAddComputerClicked(self): 'Add a Dive Computer' dc = AddDiveComputerWizard.RunWizard(self) if dc is not None: self._logbook.session.add(dc) self._logbook.session.commit() self._cbxComputer.model().reload() self._cbxComputer.setCurrentIndex(self._cbxComputer.findText(dc.name)) @QtCore.Slot() def _btnRemoveComputerClicked(self): 'Remove a Dive Computer' idx = self._cbxComputer.currentIndex() dc = self._cbxComputer.itemData(idx, Qt.UserRole+0) if QMessageBox.question(self, self.tr('Delete Dive Computer?'), self.tr('Are you sure you want to delete "%s"?') % dc.name, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) == QMessageBox.Yes: self._logbook.session.delete(dc) self._logbook.session.commit() self._cbxComputer.model().reload() @QtCore.Slot() def _btnBrowseClicked(self): 'Browse for a Logbook File' if self._logbook is not None: dir = os.path.dirname(self._logbookPath) else: dir = os.path.expanduser('~') fn = QFileDialog.getOpenFileName(self, caption=self.tr('Select a Logbook file'), dir=dir, filter='Logbook Files (*.lbk);;All Files(*.*)')[0] if fn == '': return if not os.path.exists(fn): if QMessageBox.question(self, self.tr('Create new Logbook?'), self.tr('Logbook "%s" does not exist. Would you like to create it?') % os.path.basename(fn), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) != QMessageBox.Yes: return Logbook.Create(fn) self._openLogbook(fn) @QtCore.Slot() def _btnTransferClicked(self): 'Transfer Dives' idx = self._cbxComputer.currentIndex() dc = self._cbxComputer.itemData(idx, Qt.UserRole+0) if self._logbook.session.dirty: print "Flushing dirty session" self._logbook.rollback() self._txtLogbook.setEnabled(False) self._btnBrowse.setEnabled(False) self._cbxComputer.setEnabled(False) self._btnAddComputer.setEnabled(False) self._btnRemoveComputer.setEnabled(False) self._btnTransfer.setEnabled(False) self._btnExit.setEnabled(False) self._txtStatus.clear() thread = QThread(self) #FIXME: ZOMG HAX: Garbage Collector will eat TransferWorker when moveToThread is called #NOTE: Qt.QueuedConnection is important... self.worker = None self.worker = TransferWorker(dc) thread.started.connect(self.worker.start, Qt.QueuedConnection) self.worker.moveToThread(thread) self.worker.finished.connect(self._transferFinished, Qt.QueuedConnection) self.worker.finished.connect(self.worker.deleteLater, Qt.QueuedConnection) self.worker.finished.connect(thread.deleteLater, Qt.QueuedConnection) self.worker.progress.connect(self._transferProgress, Qt.QueuedConnection) self.worker.started.connect(self._transferStart, Qt.QueuedConnection) self.worker.status.connect(self._transferStatus, Qt.QueuedConnection) thread.start() @QtCore.Slot(str) def _transferStatus(self, msg): 'Transfer Status Message' self._txtStatus.append(msg) @QtCore.Slot(int) def _transferStart(self, nBytes): 'Transfer Thread Stated' if nBytes > 0: self._pbTransfer.setMaximum(nBytes) else: self._pbTransfer.setMaximum(100) self._pbTransfer.reset() @QtCore.Slot(int) def _transferProgress(self, nTransferred): 'Transfer Thread Progress Event' self._pbTransfer.setValue(nTransferred) @QtCore.Slot(models.Dive) def _transferParsed(self, dive): 'Transfer Thread Parsed Dive' self._logbook.session.add(dive) @QtCore.Slot() def _transferFinished(self): 'Transfer Thread Finished' self._logbook.session.commit() self._txtLogbook.setEnabled(True) self._btnBrowse.setEnabled(True) self._cbxComputer.setEnabled(True) self._btnAddComputer.setEnabled(True) self._btnRemoveComputer.setEnabled(True) self._btnTransfer.setEnabled(True) self._btnExit.setEnabled(True)
class CC_window(QWidget): def __init__(self): super(CC_window, self).__init__() self.version = '0.2' glo = QVBoxLayout(self) self.Runningo = None self.Looping = None self.P = CC_thread() if name == 'nt': ficon = r_path('images\\favicon.png') licon = r_path('images\\logo.png') else: ficon = r_path('images/favicon.png') licon = r_path('images/logo.png') self.tf = QFont("", 13, QFont.Bold) self.sf = QFont("", 10, QFont.Bold) self.SelfIinit(QIcon(ficon)) self.center() self.a_btn(licon, glo) self.ss_btns(glo) self.i_list(glo) self.cl_btn(glo) self.l_btns(glo) self.f_btns(glo) self.ds_bar(glo) self.setLayout(glo) self.activateWindow() self.show() def SelfIinit(self, icon): self.setWindowTitle('chrome-cut ' + self.version) self.setGeometry(300, 300, 200, 150) self.setMinimumWidth(600) self.setMaximumWidth(600) self.setMinimumHeight(500) self.setMaximumHeight(500) # Setting Icon self.setWindowIcon(icon) QToolTip.setFont(self.sf) def msgApp(self, title, msg): uinfo = QMessageBox.question(self, title, msg, QMessageBox.Yes | QMessageBox.No) if uinfo == QMessageBox.Yes: return 'y' if uinfo == QMessageBox.No: return 'n' def closeEvent(self, event=None): if self.P.isRunning(): response = self.msgApp("Making sure", "Sure, you want to exit while looping ?") if response == 'y': if event is not None: event.accept() self.P.stop() exit(0) else: if event is not None: event.ignore() else: if event is not None: event.accept() exit(0) def center(self): qrect = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qrect.moveCenter(cp) self.move(qrect.topLeft()) def a_btn(self, icon, glo): def show_about(): Amsg = "<center>All credit reserved to the author of chrome-cut " Amsg += " version " + self.version Amsg += ", This work is a free, open-source project licensed " Amsg += " under Mozilla Public License version 2.0 . <br><br>" Amsg += " visit us for more infos and how-tos :<br> " Amsg += "<b><a href='https://github.io/mrf345/chrome-cut'> " Amsg += "https://github.io/mrf345/chrome-cut </a> </b></center>" Amsgb = "About chrome-cut" return QMessageBox.about(self, Amsgb, Amsg) self.abutton = QPushButton('', self) self.abutton.setIcon(QPixmap(icon)) self.abutton.setIconSize(QSize(500, 100)) self.abutton.setToolTip('About chrome-cut') self.abutton.clicked.connect(show_about) glo.addWidget(self.abutton) def ss_btns(self, glo): self.lebutton = QPushButton('Scan IP address', self) self.lebutton.setToolTip( 'Insert and check if a specific IP is a valid chrome cast') self.lebutton.setFont(self.tf) self.lebutton.clicked.connect(self.sip_input) glo.addWidget(self.lebutton) def sip_input(self): self.lebutton.setEnabled(False) self.s_bar.setStyleSheet(self.s_norm) self.s_bar.showMessage('> Checking out the IP ..') msg = "<center>Enter suspected IP to check : <br><i><u>Usually it is " msg += "on 192.168.what_have_you.188</i></center>" text, okPressed = QInputDialog.getText(self, "Scan IP", msg) if okPressed and text != '': self.setCursor(Qt.BusyCursor) ch = is_ccast(text) if ch: self.il_add([text]) self.unsetCursor() self.lebutton.setEnabled(True) return True else: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage( '! Error: inserted IP is not chrome cast device') self.unsetCursor() self.lebutton.setEnabled(True) return True self.s_bar.clearMessage() self.lebutton.setEnabled(True) return True def i_list(self, glo): self.ci_list = QListWidget() self.ci_list.setToolTip("List of discovered devices") self.ci_list.setEnabled(False) self.setFont(self.sf) glo.addWidget(self.ci_list) def cl_btn(self, glo): self.cle_btn = QPushButton('Clear devices list') self.cle_btn.setToolTip("Remove all devices from the list") self.cle_btn.setFont(self.sf) self.cle_btn.setEnabled(False) self.cle_btn.clicked.connect(self.il_add) glo.addWidget(self.cle_btn) def l_btns(self, glo): hlayout = QHBoxLayout() self.llo = QCheckBox("Looping") self.llo.setToolTip( 'Automate repeating the smae command on the smae device selected ') self.llo.setEnabled(False) self.nlo = QLineEdit() self.nlo.setPlaceholderText("duration in seconds. Default is 10") self.nlo.setEnabled(False) self.nlo.setToolTip("Duration of sleep after each loop") self.lbtn = QPushButton('Stop') self.lbtn.setEnabled(False) self.lbtn.setFont(self.tf) self.llo.setFont(self.sf) self.lbtn.setToolTip("stop on-going command or loop") self.llo.toggled.connect(self.loped) self.lbtn.clicked.connect(partial(self.inloop_state, out=True)) hlayout.addWidget(self.llo) hlayout.addWidget(self.nlo) hlayout.addWidget(self.lbtn) glo.addLayout(hlayout) def loped(self): if self.Looping: self.Looping = None self.llo.setChecked(False) self.nlo.setEnabled(False) else: self.Looping = True self.llo.setChecked(True) self.nlo.setEnabled(True) return True def f_btns(self, glo): hlayout = QHBoxLayout() self.ksbutton = QPushButton('Kill stream', self) self.ksbutton.setToolTip('Kill whetever been streamed') self.ksbutton.setFont(self.tf) self.ksbutton.clicked.connect(self.k_act) self.sbutton = QPushButton('Stream', self) self.sbutton.setFont(self.tf) self.sbutton.setToolTip('Stream a youtube video') self.fbutton = QPushButton('Factory reset', self) self.fbutton.setFont(self.tf) self.fbutton.setToolTip('Factory reset the device') self.fbutton.clicked.connect(self.fr_act) self.sbutton.clicked.connect(self.yv_input) self.ksbutton.setEnabled(False) self.sbutton.setEnabled(False) self.fbutton.setEnabled(False) hlayout.addWidget(self.ksbutton) hlayout.addWidget(self.sbutton) hlayout.addWidget(self.fbutton) glo.addLayout(hlayout) def ch_dur(th=None, dur=10): if len(dur) >= 1: try: dur = int(dur) except: dur = None if dur is None or not isinstance(dur, int): self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage( '! Error: wrong duration entery, only integers') return None else: dur = 10 return dur def k_act(self): if self.ci_list.count() >= 1: cr = self.ci_list.currentRow() if cr is None or cr <= 0: cr = 0 ip = self.ci_list.item(cr).text() if self.Looping is not None: dur = self.ch_dur(self.nlo.text()) if dur is None: return True self.P = CC_thread(cancel_app, dur, ip) self.P.start() self.P.somesignal.connect(self.handleStatusMessage) self.P.setTerminationEnabled(True) self.inloop_state() return True else: ch = cancel_app(ip) if ch is None: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: failed to kill stream ..') else: self.s_bar.setStyleSheet(self.s_norm) self.s_bar.showMessage('# Stream got killed ') else: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: No items selected from the list') self.eout() return True def fr_act(self): if self.ci_list.count() >= 1: cr = self.ci_list.currentRow() if cr is None or cr <= 0: cr = 0 ip = self.ci_list.item(cr).text() if self.Looping is not None: dur = self.ch_dur(self.nlo.text()) if dur is None: return True self.P = CC_thread(reset_cc, dur, ip) self.P.start() self.P.somesignal.connect(self.handleStatusMessage) self.P.setTerminationEnabled(True) self.inloop_state() return True else: ch = reset_cc(ip) if ch is None: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage( '! Error: failed to factory reset ..') else: self.s_bar.setStyleSheet(self.s_norm) self.s_bar.showMessage('# Got factory reseted ') else: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: No items selected from the list') self.eout() return True def y_act(self, link=None): if self.ci_list.count() >= 1: cr = self.ci_list.currentRow() if cr is None or cr <= 0: cr = 0 ip = self.ci_list.item(cr).text() if self.Looping is not None: dur = self.ch_dur(self.nlo.text()) if dur is None: return True self.P = CC_thread(send_app, dur, ip, link) self.P.start() self.P.somesignal.connect(self.handleStatusMessage) self.P.setTerminationEnabled(True) self.inloop_state() return True else: ch = reset_cc(ip) if ch is None: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: failed to stream link ..') else: self.s_bar.setStyleSheet(self.s_norm) self.s_bar.showMessage('# Streamed the link ') else: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: No items selected from the list') self.eout() return True def yv_input(self): text, okPressed = QInputDialog.getText( self, "Stream youtube", "Enter youtube video link to be streamed :") if okPressed and text != '': ntext = text.split('?') if len(ntext) <= 1: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: Invalid youtube linkd ') return False ntext = ntext[1] if ntext != '' and len(ntext) > 1 and "youtube" in text: self.y_act(ntext) return True else: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage('! Error: Invalid youtube linkd ') return False @Slot(object) def handleStatusMessage(self, message): self.s_bar.setStyleSheet(self.s_loop) self.s_bar.showMessage(message) def il_add(self, items=[]): if len(items) >= 1: self.s_bar.setStyleSheet(self.s_norm) for i in items: fitem = self.ci_list.findItems(i, Qt.MatchExactly) if len(fitem) >= 1: self.s_bar.setStyleSheet(self.s_error) self.s_bar.showMessage( '! Error: Device exists in the list') else: self.s_bar.setStyleSheet(self.s_norm) self.ci_list.addItem(i) self.s_bar.showMessage('# Device was found and added') if not self.P.isRunning(): self.cle_btn.setEnabled(True) self.ci_list.setEnabled(True) self.llo.setEnabled(True) self.nlo.setEnabled(True) self.ksbutton.setEnabled(True) self.sbutton.setEnabled(True) self.fbutton.setEnabled(True) else: self.s_bar.setStyleSheet(self.s_norm) self.s_bar.showMessage('# Cleard devices list') self.ci_list.clear() self.cle_btn.setEnabled(False) self.ci_list.setEnabled(False) self.ksbutton.setEnabled(False) self.llo.setEnabled(False) self.nlo.setEnabled(False) self.sbutton.setEnabled(False) self.fbutton.setEnabled(False) return True def inloop_state(self, out=False): if not out: self.lbtn.setEnabled(True) self.cle_btn.setEnabled(False) self.ci_list.setEnabled(False) self.ksbutton.setEnabled(False) self.llo.setEnabled(False) self.nlo.setEnabled(False) self.sbutton.setEnabled(False) self.fbutton.setEnabled(False) else: if self.P.isRunning(): self.P.stop() self.lbtn.setEnabled(False) self.cle_btn.setEnabled(True) self.ci_list.setEnabled(True) self.ksbutton.setEnabled(True) self.llo.setEnabled(True) self.nlo.setEnabled(True) self.sbutton.setEnabled(True) self.fbutton.setEnabled(True) self.s_bar.clearMessage() return True def ds_bar(self, glo): self.s_bar = QStatusBar() self.s_error = "QStatusBar{color:red;font-weight:1000;}" self.s_loop = "QStatusBar{color:black;font-weight:1000;}" self.s_norm = "QStatusBar{color:blue;font-style:italic;" self.s_norm += "font-weight:500;}" self.s_bar.setStyleSheet(self.s_norm) glo.addWidget(self.s_bar) def eout(self): msgg = "<center>" msgg += " Opps, a critical error has occurred, we will be " msgg += " grateful if you can help fixing it, by reporting to us " msgg += " at : <br><br> " msgg += "<b><a href='https://github.io/mrf345/chrome-cut'> " msgg += "https://github.io/mrf345/chrome-cut </a></b> </center>" mm = QMessageBox.critical(self, "Critical Error", msgg, QMessageBox.Ok) exit(0)
class UI(gobject.GObject): __gsignals__ = { 'command' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,)) } def __init__(self,args,continuous): self.continuous = continuous gobject.GObject.__init__(self) #start by making our app self.app = QApplication(args) #make a window self.window = QMainWindow() #give the window a name self.window.setWindowTitle("BlatherQt") self.window.setMaximumSize(400,200) center = QWidget() self.window.setCentralWidget(center) layout = QVBoxLayout() center.setLayout(layout) #make a listen/stop button self.lsbutton = QPushButton("Listen") layout.addWidget(self.lsbutton) #make a continuous button self.ccheckbox = QCheckBox("Continuous Listen") layout.addWidget(self.ccheckbox) #connect the buttonsc self.lsbutton.clicked.connect(self.lsbutton_clicked) self.ccheckbox.clicked.connect(self.ccheckbox_clicked) #add a label to the UI to display the last command self.label = QLabel() layout.addWidget(self.label) def ccheckbox_clicked(self): checked = self.ccheckbox.isChecked() if checked: #disable lsbutton self.lsbutton.setEnabled(False) self.lsbutton_stopped() self.emit('command', "continuous_listen") else: self.lsbutton.setEnabled(True) self.emit('command', "continuous_stop") def lsbutton_stopped(self): self.lsbutton.setText("Listen") def lsbutton_clicked(self): val = self.lsbutton.text() if val == "Listen": self.emit("command", "listen") self.lsbutton.setText("Stop") #clear the label self.label.setText("") else: self.lsbutton_stopped() self.emit("command", "stop") def run(self): self.window.show() if self.continuous: self.ccheckbox.setCheckState(Qt.Checked) self.ccheckbox_clicked() self.app.exec_() self.emit("command", "quit") def quit(self): pass def finished(self, text): print text #if the continuous isn't pressed if not self.ccheckbox.isChecked(): self.lsbutton_stopped() self.label.setText(text) def quit(self): #sys.exit() pass
class MTTFilterFileDialog(QDialog): def __init__(self, define_path='', define_type=None): super(MTTFilterFileDialog, self).__init__(get_maya_window()) self.supported_node_type = sorted([ node_type for (node_type, nice, attr) in MTTSettings.SUPPORTED_TYPE ]) self.defined_path = (define_path if os.path.isdir(define_path) or define_path == SOURCEIMAGES_TAG else None) self.defined_type = (define_type if define_type in self.supported_node_type else None) self.path_edit = None self.filter_reset_btn = None self.filter_line = None self.parent_folder_btn = None self.files_model = None self.files_list = None self.bookmark_list = None self.bookmark_list_sel_model = None self.types = None # move window to cursor position win_geo = MTTSettings.value('FilterFileDialog/windowGeometry', QRect(0, 0, 400, 300)) self.setGeometry(win_geo) mouse_pos = QCursor.pos() mouse_pos.setX(mouse_pos.x() - (win_geo.width() * 0.5)) self.move(mouse_pos) self.__create_ui() self.filter_line.setFocus() self.on_change_root_path(self.defined_path or SOURCEIMAGES_TAG) def __create_ui(self): """ Create main UI """ self.setWindowTitle(CREATE_NODE_TITLE) # remove window decoration if path and type is set if self.defined_path and self.defined_type: self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup) main_layout = QVBoxLayout(self) main_layout.setSpacing(1) main_layout.setContentsMargins(2, 2, 2, 2) # content layout content_layout = QVBoxLayout() self.files_model = QFileSystemModel() self.files_model.setNameFilterDisables(False) self.files_list = MTTFileList() self.files_list.setAlternatingRowColors(True) self.files_list.setSelectionMode(QAbstractItemView.ExtendedSelection) self.files_list.selectionValidated.connect(self.do_validate_selection) self.files_list.goToParentDirectory.connect(self.on_go_up_parent) self.files_list.doubleClicked.connect(self.on_double_click) self.files_list.setModel(self.files_model) buttons_layout = QHBoxLayout() content_layout.addLayout(self.__create_filter_ui()) content_layout.addWidget(self.files_list) content_layout.addLayout(buttons_layout) self.files_list.filter_line = self.filter_line if not self.defined_path: # path line path_layout = QHBoxLayout() # bookmark button bookmark_btn = QPushButton('') bookmark_btn.setFlat(True) bookmark_btn.setIcon(QIcon(':/addBookmark.png')) bookmark_btn.setToolTip('Bookmark this Folder') bookmark_btn.setStatusTip('Bookmark this Folder') bookmark_btn.clicked.connect(self.on_add_bookmark) # path line edit self.path_edit = QLineEdit() self.path_edit.editingFinished.connect(self.on_enter_path) # parent folder button self.parent_folder_btn = QPushButton('') self.parent_folder_btn.setFlat(True) self.parent_folder_btn.setIcon( QIcon(':/SP_FileDialogToParent.png')) self.parent_folder_btn.setToolTip('Parent Directory') self.parent_folder_btn.setStatusTip('Parent Directory') self.parent_folder_btn.clicked.connect(self.on_go_up_parent) # browse button browse_btn = QPushButton('') browse_btn.setFlat(True) browse_btn.setIcon(QIcon(':/navButtonBrowse.png')) browse_btn.setToolTip('Browse Directory') browse_btn.setStatusTip('Browse Directory') browse_btn.clicked.connect(self.on_browse) # parent widget and layout path_layout.addWidget(bookmark_btn) path_layout.addWidget(self.path_edit) path_layout.addWidget(self.parent_folder_btn) path_layout.addWidget(browse_btn) main_layout.addLayout(path_layout) # bookmark list bookmark_parent_layout = QHBoxLayout() bookmark_frame = QFrame() bookmark_frame.setFixedWidth(120) bookmark_layout = QVBoxLayout() bookmark_layout.setSpacing(1) bookmark_layout.setContentsMargins(2, 2, 2, 2) bookmark_frame.setLayout(bookmark_layout) bookmark_frame.setFrameStyle(QFrame.Sunken) bookmark_frame.setFrameShape(QFrame.StyledPanel) self.bookmark_list = MTTBookmarkList() self.bookmark_list.bookmarkDeleted.connect(self.do_delete_bookmark) self.bookmark_list.setAlternatingRowColors(True) self.bookmark_list.dragEnabled() self.bookmark_list.setAcceptDrops(True) self.bookmark_list.setDropIndicatorShown(True) self.bookmark_list.setDragDropMode(QListView.InternalMove) self.bookmark_list_sel_model = self.bookmark_list.selectionModel() self.bookmark_list_sel_model.selectionChanged.connect( self.on_select_bookmark) bookmark_layout.addWidget(self.bookmark_list) bookmark_parent_layout.addWidget(bookmark_frame) bookmark_parent_layout.addLayout(content_layout) main_layout.addLayout(bookmark_parent_layout) self.do_populate_bookmarks() else: main_layout.addLayout(content_layout) if not self.defined_type: # type layout self.types = QComboBox() self.types.addItems(self.supported_node_type) self.types.currentIndexChanged.connect(self.on_node_type_changed) if cmds.optionVar(exists='MTT_lastNodeType'): last = cmds.optionVar(query='MTT_lastNodeType') if last in self.supported_node_type: self.types.setCurrentIndex( self.supported_node_type.index(last)) buttons_layout.addWidget(self.types) if not self.defined_path or not self.defined_type: create_btn = QPushButton('C&reate') create_btn.clicked.connect(self.accept) cancel_btn = QPushButton('&Cancel') cancel_btn.clicked.connect(self.reject) buttons_layout.addStretch() buttons_layout.addWidget(create_btn) buttons_layout.addWidget(cancel_btn) def __create_filter_ui(self): """ Create filter widgets """ filter_layout = QHBoxLayout() filter_layout.setSpacing(1) filter_layout.setContentsMargins(0, 0, 0, 0) self.filter_reset_btn = QPushButton() icon = QIcon(':/filtersOff.png') self.filter_reset_btn.setIcon(icon) self.filter_reset_btn.setIconSize(QSize(22, 22)) self.filter_reset_btn.setFixedSize(24, 24) self.filter_reset_btn.setToolTip('Reset filter') self.filter_reset_btn.setFlat(True) self.filter_reset_btn.clicked.connect( partial(self.on_filter_set_text, '')) self.filter_line = QLineEdit() self.filter_line.setPlaceholderText('Enter filter string here') self.filter_line.textChanged.connect(self.on_filter_change_text) completer = QCompleter(self) completer.setCaseSensitivity(Qt.CaseInsensitive) completer.setModel(QStringListModel([], self)) self.filter_line.setCompleter(completer) filter_layout.addWidget(self.filter_reset_btn) filter_layout.addWidget(self.filter_line) return filter_layout def on_filter_set_text(self, text=''): """ Set text in filter field """ self.filter_line.setText(text) def on_filter_change_text(self, text): """ Apply filter string """ if len(text): icon = QIcon(':/filtersOn.png') self.filter_reset_btn.setIcon(icon) else: icon = QIcon(':/filtersOff.png') self.filter_reset_btn.setIcon(icon) self.files_model.setNameFilters([ '*%s*' % item.strip() for item in text.split(',') if item.strip() ]) def on_node_type_changed(self, index): cmds.optionVar( sv=['MTT_lastNodeType', self.supported_node_type[index]]) def on_double_click(self, index): current_item = self.files_model.filePath(index) if os.path.isdir(current_item): self.on_change_root_path(current_item) elif os.path.isfile(current_item): self.accept() def on_change_root_path(self, current_path): if current_path == SOURCEIMAGES_TAG: current_path = os.path.join( cmds.workspace(query=True, rootDirectory=True), cmds.workspace(fileRuleEntry='sourceImages')) self.files_model.setRootPath(current_path) self.files_list.setRootIndex(self.files_model.index(current_path)) if self.path_edit: self.path_edit.setText(current_path) if self.parent_folder_btn: current_dir = QDir(current_path) self.parent_folder_btn.setEnabled(current_dir.cdUp()) def on_go_up_parent(self): current_path = QDir(self.files_model.rootPath()) current_path.cdUp() self.on_change_root_path(current_path.absolutePath()) def on_enter_path(self): new_path = self.path_edit.text() if os.path.isdir(new_path): self.on_change_root_path(new_path) else: self.path_edit.setText(self.files_model.rootPath()) def on_browse(self): current_path = self.files_model.rootPath() file_dialog = QFileDialog(self, 'Select a Folder', current_path) file_dialog.setFileMode(QFileDialog.Directory) file_dialog.setOption(QFileDialog.ShowDirsOnly) if file_dialog.exec_(): self.on_change_root_path(file_dialog.selectedFiles()[0]) def on_select_bookmark(self, selected, deselected): current_item = selected.indexes() if current_item: self.on_change_root_path( self.bookmark_list.selectedItems()[0].root_path) def on_add_bookmark(self): current_path = self.files_model.rootPath() self.on_add_bookmark_item( '%s|%s' % (os.path.basename(current_path), current_path)) def on_add_bookmark_item(self, item): if item == '': return current_item = MTTBookmarkItem() current_item.add_raw_data(item) current_item.setSizeHint(QSize(40, 25)) current_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled) self.bookmark_list.addItem(current_item) def do_delete_bookmark(self): current_item = self.bookmark_list.selectedItems() if current_item: item_row = self.bookmark_list.row(current_item[0]) self.bookmark_list.takeItem(item_row) del current_item[0] def do_save_bookmark(self): if not self.bookmark_list: return row_count = self.bookmark_list.count() ordered_list = list() for i in range(row_count): item = self.bookmark_list.item(i) name = item.text().replace(',', '_').replace('|', '_') path = item.root_path if name != 'sourceimages': ordered_list.append('%s|%s' % (name, path)) MTTSettings.set_value('FilterFileDialog/bookmarks', ','.join(ordered_list)) def do_populate_bookmarks(self): bookmarks = ['sourceimages|%s' % SOURCEIMAGES_TAG] bookmarks.extend( MTTSettings.value('FilterFileDialog/bookmarks').split(',')) for bm in bookmarks: self.on_add_bookmark_item(bm) def do_validate_selection(self): selection = self.files_list.selectedIndexes() if len(selection) == 1: current_path = self.files_model.filePath(selection[0]) if os.path.isdir(current_path): self.on_change_root_path(current_path) return self.accept() def get_selected_files(self): selected_items = list() for item_index in self.files_list.selectedIndexes(): current_path = self.files_model.filePath(item_index) if os.path.isfile(current_path): selected_items.append(current_path) return selected_items def get_node_type(self): return self.types.currentText() if self.types else self.defined_type def closeEvent(self, event): MTTSettings.set_value('FilterFileDialog/windowGeometry', self.geometry()) self.do_save_bookmark() self.deleteLater() event.accept()
class ToolBox(QVBoxLayout): sig = QtCore.Signal(object) listThread = None groupBoxThreadInfo = None threadvbox = None mode = None def __init__(self, mode, parentQWidget=None): QVBoxLayout.__init__(self) self.sig.connect(self.addThreadList) self.mode = mode self.sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Expanding) self.groupBoxSearch = QGroupBox() self.groupBoxSearch.setStyleSheet( "QGroupBox {border: 1px solid gray; border-radius: 4px; };") vboxSearch = QVBoxLayout() self.searchTitle = QLabel("Search Messages") vboxSearch.addWidget(self.searchTitle) self.searchHLayout = QHBoxLayout() self.editTextSearch = QTextEdit('') self.editTextSearch.setFixedSize(200, 30) self.buttonSearch = QPushButton('Search') self.buttonSearch.setFixedSize(100, 30) self.buttonSearch.clicked.connect(self.searchMsg) vboxSearch.addWidget(self.editTextSearch) self.searchHLayout.addWidget(self.buttonSearch) self.searchCursor = QLabel() self.searchHLayout.addWidget(self.searchCursor) vboxSearch.addLayout(self.searchHLayout) self.browseHLayout = QHBoxLayout() self.buttonLookUp = QPushButton('\u21e7') #Arrow up self.buttonLookUp.setFixedWidth(100) self.buttonLookUp.clicked.connect(self.moveToPrev) self.buttonLookDown = QPushButton('\u21e9') #Arrow down self.buttonLookDown.setFixedWidth(100) self.buttonLookDown.clicked.connect(self.moveToNext) self.browseHLayout.addWidget(self.buttonLookUp) self.browseHLayout.addWidget(self.buttonLookDown) vboxSearch.addLayout(self.browseHLayout) self.groupBoxSearch.setLayout(vboxSearch) self.addWidget(self.groupBoxSearch) self.groupBoxSearch.setSizePolicy( QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)) self.buttonHiddenLifelines = QPushButton('Show hidden life-lines') self.buttonHiddenLifelines.setFixedWidth(200) self.buttonHiddenLifelines.clicked.connect(self.showHiddenLifelines) self.addWidget(self.buttonHiddenLifelines) self.buttonHiddenMessages = QPushButton('Show hidden Messages') self.buttonHiddenMessages.setFixedWidth(200) self.buttonHiddenMessages.clicked.connect(self.showHiddenMessages) self.addWidget(self.buttonHiddenMessages) if const.mode_interactive == mode: self.buttonCapture = QPushButton('Capture') self.buttonCapture.setFixedWidth(200) self.buttonCapture.clicked.connect(self.notifyCapture) self.addWidget(self.buttonCapture) self.msgRcv = [] self.msgInfo = QLabel("Message Info.") self.groupBoxMessageInfo = QGroupBox() self.groupBoxMessageInfo.setStyleSheet( "QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;" ) vbox = QVBoxLayout() vbox.addWidget(self.msgInfo) self.tableTime = QtGui.QTableWidget(3, 2) self.tableTime.setHorizontalHeaderLabels(['-', 'time']) self.tableTime.setColumnWidth(0, 80) self.tableTime.setColumnWidth(1, 150) vwidth = self.tableTime.verticalHeader().length() hwidth = self.tableTime.horizontalHeader().height() fwidth = self.tableTime.frameWidth() * 2 self.tableTime.setFixedHeight(vwidth + hwidth + fwidth) self.tableTime.horizontalHeader().setStretchLastSection(True) self.tableTime.setItem(0, 0, QTableWidgetItem('begin')) self.tableTime.setItem(0, 1, QTableWidgetItem(' - ')) self.tableTime.setItem(1, 0, QTableWidgetItem('end')) self.tableTime.setItem(1, 1, QTableWidgetItem(' - ')) self.tableTime.setItem(2, 0, QTableWidgetItem('duration')) self.tableTime.setItem(2, 1, QTableWidgetItem(' - ')) vbox.addWidget(self.tableTime) self.titleArg = QLabel('Argument List') vbox.addWidget(self.titleArg) max_arg_num = 10 self.tableArgs = QtGui.QTableWidget(max_arg_num, 2) self.tableArgs.setHorizontalHeaderLabels(['type', 'value']) for idx in range(0, max_arg_num): self.tableArgs.setItem(idx, 0, QTableWidgetItem()) self.tableArgs.setItem(idx, 1, QTableWidgetItem()) self.tableArgs.horizontalHeader().setStretchLastSection(True) vbox.addWidget(self.tableArgs) self.titleArg = QLabel('Return Value List') vbox.addWidget(self.titleArg) max_ret_num = 4 self.tableRet = QtGui.QTableWidget(max_ret_num, 2) self.tableRet.setHorizontalHeaderLabels(['type', 'value']) for idx in range(0, max_ret_num): self.tableRet.setItem(idx, 0, QTableWidgetItem()) self.tableRet.setItem(idx, 1, QTableWidgetItem()) self.tableRet.horizontalHeader().setStretchLastSection(True) vwidth = self.tableRet.verticalHeader().length() hwidth = self.tableRet.horizontalHeader().height() fwidth = self.tableRet.frameWidth() * 2 self.tableRet.setFixedHeight(vwidth + hwidth + fwidth) vbox.addWidget(self.tableRet) self.buttonSrcView = QPushButton('view code') self.buttonSrcView.setFixedWidth(200) self.buttonSrcView.clicked.connect(self.openSourceViewer) self.buttonHide = QPushButton('Hide') self.buttonHide.setFixedWidth(200) self.buttonHide.clicked.connect(self.notifyHide) self.buttonHideAllMsg = QPushButton('Hide All') self.buttonHideAllMsg.setFixedWidth(200) self.buttonHideAllMsg.clicked.connect(self.hideAllMsgNamedAsSelected) self.groupBoxMessageInfo.setLayout(vbox) self.checkHideCircular = QCheckBox('Hide Circular Messages') self.checkHideCircular.setCheckState(QtCore.Qt.Unchecked) self.checkHideCircular.stateChanged.connect( self.changeHideCircularMessage) self.addWidget(self.checkHideCircular) self.addWidget(self.groupBoxMessageInfo) self.groupBoxMessageInfo.setSizePolicy(self.sizePolicy) def reset(self): for idx in reversed(range(0, self.listThread.count())): self.listThread.takeItem(idx) def setMsgInfoMessage(self, msg): self.strMessage = msg def changeHideCircularMessage(self, state): if state == QtCore.Qt.Unchecked: self.diagramView.hideCircularChanged(False) elif state == QtCore.Qt.Checked: self.diagramView.hideCircularChanged(True) def setMsgInfoModule(self, module): self.strModule = module def updateSearchStatus(self, curr, number): self.searchCursor.setText("%d/%d" % (curr, number)) def connectSourceViewer(self, viewer): self.srcViewer = viewer def openSourceViewer(self): self.srcViewer.openViewer(self.strModule, self.strMessage) def setMessageInfoTime(self, begin, end, duration): self.tableTime.item(0, 1).setText(begin) self.tableTime.item(1, 1).setText(end) self.tableTime.item(2, 1).setText(duration + ' msec') def setMessageInfoArg(self, listParam, listArg): if listArg: for idx, text in enumerate(listArg): self.tableArgs.item(idx, 1).setText(text) for idx, text in enumerate(listParam): self.tableArgs.item(idx, 0).setText(text) else: for idx in range(0, self.tableArgs.rowCount()): self.tableArgs.item(idx, 1).setText('') self.tableArgs.item(idx, 0).setText('') def setMessageInfoRet(self, listRet): if listRet: for idx, text in enumerate(listRet): self.tableRet.item(idx, 1).setText(text) else: for idx in range(0, self.tableRet.rowCount()): self.tableRet.item(idx, 1).setText('') self.tableRet.item(idx, 0).setText('') def notifyInteractiveStateChanged(self, state): if const.mode_interactive != self.mode: return if const.STATE_INTERACTIVE_CAPTURING == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Stop Capture') if const.STATE_INTERACTIVE_PROCESSING == state: self.buttonCapture.setEnabled(False) if const.STATE_INTERACTIVE_IDLE == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Capture') if const.STATE_INTERACTIVE_RESET == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Capture') elif const.STATE_INTERACTIVE_ACTIVE == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Capture') def setMessageInfo(self, info): self.msgInfo.setText(info) def setAvailable(self, threads): self.sig.emit(threads) def toggleThreadDisplay(self, item): print(self.listThread.currentRow()) #if item.isSelected(): # print(item.text() + " is selected") #else: # print(item.text() + " is not selected") self.diagramView.showThread(self.listThread.currentRow(), item.isSelected()) def hideAllMsgNamedAsSelected(self): self.diagramView.hideAllMessageSelected() def addThreadList(self, threads): if not self.groupBoxThreadInfo: self.groupBoxThreadInfo = QGroupBox() self.threadInfo = QLabel("Thread Info.") self.groupBoxThreadInfo.setStyleSheet( "QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;" ) if not self.threadvbox: self.threadvbox = QVBoxLayout() if not self.listThread: self.listThread = QListWidget() self.listThread.setFixedWidth(200) self.listThread.setSelectionMode( QtGui.QAbstractItemView.MultiSelection) QtCore.QObject.connect(self.listThread, QtCore.SIGNAL("itemClicked(QListWidgetItem *)"), self.toggleThreadDisplay) self.threadvbox.addWidget(self.threadInfo) self.threadvbox.addWidget(self.listThread) self.groupBoxThreadInfo.setLayout(self.threadvbox) self.addWidget(self.groupBoxThreadInfo) self.groupBoxThreadInfo.setSizePolicy(self.sizePolicy) for id in threads: item = QtGui.QListWidgetItem(id) self.listThread.addItem(item) def connectController(self, controller): self.controller = controller self.connect(controller, QtCore.SIGNAL('setAvailable()'), self.setAvailable) def connectDiagramView(self, view): self.diagramView = view def disconnectMsgRcv(self, receiver): print("Implement this method !!! disconnectMsgRcv") def connectMsgRcv(self, receiver): self.msgRcv.append(receiver) def notifyHide(self): for rcv in self.msgRcv: rcv.activateHide(True) def showHiddenLifelines(self): response, selected_items = HiddenDialog.HiddenDialog.getSelectedItems( self.diagramView.getHiddenLifeLines()) if response: self.diagramView.showLifelines(selected_items) def showHiddenMessages(self): response, selected_items = HiddenMessageDialog.HiddenMessageDialog.getSelectedItems( self.diagramView.getHiddenMessages(), self.diagramView.getHiddenLifeLines()) if response: if selected_items[3] in self.diagramView.getHiddenLifeLines(): confirmation = ShowLifeLineDialog.ShowLifeLineDialog.confirmToShowLifeLine( selected_items[3]) if confirmation: self.diagramView.showLifelines([selected_items[3]]) self.diagramView.showMessages(selected_items) else: self.diagramView.showMessages(selected_items) def notifyCapture(self): for rcv in self.msgRcv: rcv.activateCapture(True) def moveToPrev(self): for rcv in self.msgRcv: rcv.moveToPrev() def moveToNext(self): for rcv in self.msgRcv: rcv.moveToNext() def searchMsg(self): str = self.editTextSearch.toPlainText() for rcv in self.msgRcv: rcv.searchMessage(str)
class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(810, 492) lbMinWidth = 65 lbMinWidthLogin = 110 # leMinWidth = 200 # self.centralwidget = QWidget(MainWindow) self.mainSplitter = QSplitter(Qt.Horizontal, MainWindow) self.mainSplitter.setObjectName("centralwidget") self.mainSplitter.setProperty("childrenCollapsible", False) MainWindow.setCentralWidget(self.mainSplitter) self.leftSplitter = QSplitter(Qt.Vertical, self.mainSplitter) self.leftSplitter.setProperty("childrenCollapsible", False) # login_gbox self.login_gbox = QGroupBox(self.leftSplitter) self.login_gbox.setFlat(True) self.login_gbox.setObjectName("login_gbox") login_gbox_layout = QVBoxLayout(self.login_gbox) login_gbox_presets_layout = QHBoxLayout() login_gbox_server_layout = QHBoxLayout() login_gbox_ssl_layout = QHBoxLayout() login_gbox_address_layout = QHBoxLayout() login_gbox_pass_layout = QHBoxLayout() login_gbox_connect_layout = QHBoxLayout() login_gbox_layout.addLayout(login_gbox_presets_layout) login_gbox_layout.addLayout(login_gbox_server_layout) login_gbox_layout.addLayout(login_gbox_ssl_layout) login_gbox_layout.addLayout(login_gbox_address_layout) login_gbox_layout.addLayout(login_gbox_pass_layout) login_gbox_layout.addLayout(login_gbox_connect_layout) self.lb_presets = QLabel(self.login_gbox) self.lb_presets.setObjectName("lb_presets") self.lb_presets.setMinimumWidth(lbMinWidthLogin) self.lb_presets.setMaximumWidth(lbMinWidthLogin) self.presets_cbox = QComboBox(self.login_gbox) self.presets_cbox.setObjectName("presets_cbox") self.add_preset_btn = QPushButton(self.login_gbox) self.add_preset_btn.setObjectName("add_preset_btn") self.add_preset_btn.setMaximumWidth(30) self.remove_preset_btn = QPushButton(self.login_gbox) self.remove_preset_btn.setObjectName("remove_preset_btn") self.remove_preset_btn.setMaximumWidth(20) login_gbox_presets_layout.addWidget(self.lb_presets) login_gbox_presets_layout.addWidget(self.presets_cbox) login_gbox_presets_layout.addWidget(self.add_preset_btn) login_gbox_presets_layout.addWidget(self.remove_preset_btn) self.lb_imap_server = QLabel(self.login_gbox) self.lb_imap_server.setObjectName("lb_imap_server") self.lb_imap_server.setMinimumWidth(lbMinWidthLogin) self.imap_server_le = QLineEdit(self.login_gbox) self.imap_server_le.setObjectName("imap_server_le") login_gbox_server_layout.addWidget(self.lb_imap_server) login_gbox_server_layout.addWidget(self.imap_server_le) self.lb_ssl = QLabel(self.login_gbox) self.lb_ssl.setObjectName("lb_ssl") self.lb_ssl.setMinimumWidth(lbMinWidthLogin) self.lb_ssl.setMaximumWidth(lbMinWidthLogin) self.ssl_cb = QCheckBox(self.login_gbox) self.ssl_cb.setEnabled(False) self.ssl_cb.setCheckable(True) self.ssl_cb.setChecked(True) self.ssl_cb.setObjectName("ssl_cb") login_gbox_ssl_layout.addWidget(self.lb_ssl) login_gbox_ssl_layout.addWidget(self.ssl_cb) self.lb_adress = QLabel(self.login_gbox) self.lb_adress.setObjectName("lb_adress") self.lb_adress.setMinimumWidth(lbMinWidthLogin) self.adress_le = QLineEdit(self.login_gbox) self.adress_le.setInputMethodHints(Qt.ImhNone) self.adress_le.setObjectName("adress_le") login_gbox_address_layout.addWidget(self.lb_adress) login_gbox_address_layout.addWidget(self.adress_le) self.lb_pass = QLabel(self.login_gbox) self.lb_pass.setObjectName("lb_pass") self.lb_pass.setMinimumWidth(lbMinWidthLogin) self.pass_le = QLineEdit(self.login_gbox) self.pass_le.setText("") self.pass_le.setEchoMode(QLineEdit.Password) self.pass_le.setObjectName("pass_le") login_gbox_pass_layout.addWidget(self.lb_pass) login_gbox_pass_layout.addWidget(self.pass_le) self.connect_btn = QPushButton(self.login_gbox) self.connect_btn.setObjectName("connect_btn") login_gbox_connect_layout.addStretch() login_gbox_connect_layout.addWidget(self.connect_btn) # search_gbox self.search_gbox = QGroupBox(self.leftSplitter) self.search_gbox.hide() self.search_gbox.setObjectName("search_gbox") search_gbox_layout = QVBoxLayout(self.search_gbox) search_gbox_mailbox_layout = QVBoxLayout() search_gbox_date_layout = QHBoxLayout() search_gbox_from_layout = QHBoxLayout() search_gbox_to_layout = QHBoxLayout() search_gbox_subject_layout = QHBoxLayout() search_gbox_threads_layout = QHBoxLayout() search_gbox_paramaters_layout = QHBoxLayout() search_gbox_layout.addLayout(search_gbox_mailbox_layout) search_gbox_layout.addLayout(search_gbox_date_layout) search_gbox_layout.addLayout(search_gbox_from_layout) search_gbox_layout.addLayout(search_gbox_to_layout) search_gbox_layout.addLayout(search_gbox_subject_layout) search_gbox_layout.addLayout(search_gbox_threads_layout) search_gbox_layout.addLayout(search_gbox_paramaters_layout) self.lb_select_mailbox = QLabel(self.search_gbox) self.lb_select_mailbox.setObjectName("lb_select_mailbox") self.mailboxes_lw = QListWidget(self.search_gbox) self.mailboxes_lw.setEditTriggers(QAbstractItemView.NoEditTriggers) self.mailboxes_lw.setSelectionMode(QAbstractItemView.ExtendedSelection) self.mailboxes_lw.setObjectName("mailboxes_lw") search_gbox_mailbox_layout.addWidget(self.lb_select_mailbox) search_gbox_mailbox_layout.addWidget(self.mailboxes_lw) self.since_date_cb = QCheckBox(self.search_gbox) self.since_date_cb.setObjectName("since_date_cb") self.since_date_cb.setMinimumWidth(lbMinWidth) self.since_date_cb.setMaximumWidth(lbMinWidth) self.since_date_edit = QDateEdit(self.search_gbox) self.since_date_edit.setCalendarPopup(True) self.since_date_edit.setObjectName("since_date_edit") self.since_date_edit.setDate(QDate.currentDate().addDays(-365)) self.since_date_edit.setMaximumDate(QDate.currentDate()) self.since_date_edit.setEnabled(False) self.before_date_cb = QCheckBox(self.search_gbox) self.before_date_cb.setObjectName("before_date_cb") self.before_date_cb.setMinimumWidth(70) self.before_date_cb.setMaximumWidth(70) self.before_date_edit = QDateEdit(self.search_gbox) self.before_date_edit.setCalendarPopup(True) self.before_date_edit.setObjectName("before_date_edit") self.before_date_edit.setDate(QDate.currentDate()) self.before_date_edit.setMaximumDate(QDate.currentDate()) self.before_date_edit.setEnabled(False) search_gbox_date_layout.addWidget(self.since_date_cb) search_gbox_date_layout.addWidget(self.since_date_edit) search_gbox_date_layout.addWidget(self.before_date_cb) search_gbox_date_layout.addWidget(self.before_date_edit) self.lb_from = QLabel(self.search_gbox) self.lb_from.setObjectName("lb_from") self.lb_from.setMinimumWidth(lbMinWidth) self.from_le = QLineEdit(self.search_gbox) self.from_le.setObjectName("from_le") search_gbox_from_layout.addWidget(self.lb_from) search_gbox_from_layout.addWidget(self.from_le) self.lb_to = QLabel(self.search_gbox) self.lb_to.setObjectName("lb_to") self.lb_to.setMinimumWidth(lbMinWidth) self.to_le = QLineEdit(self.search_gbox) self.to_le.setObjectName("to_le") search_gbox_to_layout.addWidget(self.lb_to) search_gbox_to_layout.addWidget(self.to_le) self.lb_subject = QLabel(self.search_gbox) self.lb_subject.setObjectName("lb_subject") self.lb_subject.setMinimumWidth(lbMinWidth) self.subject_le = QLineEdit(self.search_gbox) self.subject_le.setObjectName("subject_le") search_gbox_subject_layout.addWidget(self.lb_subject) search_gbox_subject_layout.addWidget(self.subject_le) # self.lb_threads = QLabel(self.search_gbox) # self.lb_threads.setObjectName("lb_threads") # self.lb_threads.setMaximumWidth(lbMinWidth) # self.thread_count_sb = QSpinBox(self.search_gbox) # self.thread_count_sb.setMinimum(1) # self.thread_count_sb.setMaximum(10) # self.thread_count_sb.setObjectName("thread_count_sb") self.html_radio = QRadioButton(self.search_gbox) self.html_radio.setObjectName("html_radio") self.text_radio = QRadioButton(self.search_gbox) self.text_radio.setObjectName("text_radio") self.extactTypeButtonGroup = QButtonGroup(self) self.extactTypeButtonGroup.addButton(self.html_radio) self.extactTypeButtonGroup.addButton(self.text_radio) self.html_radio.setChecked(True) self.search_btn = QPushButton(self.search_gbox) self.search_btn.setObjectName("search_btn") # search_gbox_threads_layout.addWidget(self.lb_threads) # search_gbox_threads_layout.addWidget(self.thread_count_sb) search_gbox_threads_layout.addStretch() search_gbox_threads_layout.addWidget(self.html_radio) search_gbox_threads_layout.addWidget(self.text_radio) # search_gbox_threads_layout.addStretch() search_gbox_threads_layout.addWidget(self.search_btn) self.parameters_cb = QCheckBox(self.search_gbox) self.parameters_cb.setText("") self.parameters_cb.setObjectName("parameters_cb") self.parameters_le = QLineEdit(self.search_gbox) self.parameters_le.setEnabled(False) self.parameters_le.setObjectName("parameters_le") search_gbox_paramaters_layout.addWidget(self.parameters_cb) search_gbox_paramaters_layout.addWidget(self.parameters_le) # log_gbox self.log_gbox = QGroupBox(self.leftSplitter) self.log_gbox.setFlat(True) self.log_gbox.setObjectName("log_gbox") log_layout = QVBoxLayout(self.log_gbox) self.log_te = QTextEdit(self.log_gbox) self.log_te.setLineWrapMode(QTextEdit.NoWrap) self.log_te.setReadOnly(True) self.log_te.setTextInteractionFlags(Qt.TextSelectableByKeyboard | Qt.TextSelectableByMouse) self.log_te.setObjectName("log_te") self.disconnect_btn = QPushButton(self.log_gbox) self.disconnect_btn.setObjectName("disconnect_btn") self.disconnect_btn.hide() log_layout.addWidget(self.log_te) log_layout_btn = QHBoxLayout() log_layout.addLayout(log_layout_btn) log_layout_btn.addWidget(self.disconnect_btn) log_layout_btn.addStretch() # links_gbox self.links_gbox = QGroupBox(self.mainSplitter) self.links_gbox.setFlat(True) self.links_gbox.setObjectName("links_gbox") links_gbox_layout = QVBoxLayout(self.links_gbox) links_gbox_links_layout = QVBoxLayout() links_gbox_buttons_layout = QHBoxLayout() links_gbox_layout.addLayout(links_gbox_links_layout) links_gbox_layout.addLayout(links_gbox_buttons_layout) self.links_text_edit = QTextEdit(self.links_gbox) self.links_text_edit.setObjectName("links_text_edit") links_gbox_links_layout.addWidget(self.links_text_edit) self.export_txt_btn = QPushButton(self.links_gbox) self.export_txt_btn.setObjectName("export_txt_btn") self.export_txt_btn.setEnabled(False) self.export_html_btn = QPushButton(self.links_gbox) self.export_html_btn.setObjectName("export_html_btn") self.export_html_btn.setEnabled(False) links_gbox_buttons_layout.addWidget(self.export_txt_btn) links_gbox_buttons_layout.addWidget(self.export_html_btn) # menubar self.menubar = QMenuBar(MainWindow) self.menubar.setObjectName("menubar") self.menu_file = QMenu(self.menubar) self.menu_file.setObjectName("menu_file") self.menu_about = QMenu(self.menubar) self.menu_about.setObjectName("menu_about") MainWindow.setMenuBar(self.menubar) self.action_about = QAction(MainWindow) self.action_about.setObjectName("action_about") self.action_About_Qt = QAction(MainWindow) self.action_About_Qt.setObjectName("action_About_Qt") self.action_exit = QAction(MainWindow) self.action_exit.setObjectName("action_exit") self.actionSave = QAction(MainWindow) self.actionSave.setObjectName("actionSave") self.menu_file.addAction(self.action_exit) self.menu_about.addAction(self.action_about) self.menu_about.addAction(self.action_About_Qt) self.menubar.addAction(self.menu_file.menuAction()) self.menubar.addAction(self.menu_about.menuAction()) self.retranslateUi(MainWindow) QMetaObject.connectSlotsByName(MainWindow) MainWindow.setTabOrder(self.presets_cbox, self.imap_server_le) MainWindow.setTabOrder(self.imap_server_le, self.adress_le) MainWindow.setTabOrder(self.adress_le, self.pass_le) MainWindow.setTabOrder(self.pass_le, self.connect_btn) MainWindow.setTabOrder(self.connect_btn, self.log_te) MainWindow.setTabOrder(self.log_te, self.since_date_cb) MainWindow.setTabOrder(self.since_date_cb, self.since_date_edit) MainWindow.setTabOrder(self.since_date_edit, self.before_date_cb) MainWindow.setTabOrder(self.before_date_cb, self.before_date_edit) MainWindow.setTabOrder(self.before_date_edit, self.mailboxes_lw) MainWindow.setTabOrder(self.mailboxes_lw, self.from_le) MainWindow.setTabOrder(self.from_le, self.to_le) MainWindow.setTabOrder(self.to_le, self.subject_le) MainWindow.setTabOrder(self.subject_le, self.search_btn) MainWindow.setTabOrder(self.search_btn, self.links_text_edit) MainWindow.setTabOrder(self.links_text_edit, self.export_txt_btn) MainWindow.setTabOrder(self.export_txt_btn, self.export_html_btn) MainWindow.setTabOrder(self.export_html_btn, self.disconnect_btn) MainWindow.setTabOrder(self.disconnect_btn, self.add_preset_btn) MainWindow.setTabOrder(self.add_preset_btn, self.remove_preset_btn) MainWindow.setTabOrder(self.remove_preset_btn, self.ssl_cb) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QApplication.translate("MainWindow", "Email Link Extractor", None, QApplication.UnicodeUTF8)) self.login_gbox.setTitle(QApplication.translate("MainWindow", " Login", None, QApplication.UnicodeUTF8)) self.lb_presets.setText(QApplication.translate("MainWindow", "Server Presets", None, QApplication.UnicodeUTF8)) self.add_preset_btn.setText(QApplication.translate("MainWindow", "+", None, QApplication.UnicodeUTF8)) self.remove_preset_btn.setText(QApplication.translate("MainWindow", "-", None, QApplication.UnicodeUTF8)) self.lb_imap_server.setText(QApplication.translate("MainWindow", "IMAP Server", None, QApplication.UnicodeUTF8)) self.lb_ssl.setText(QApplication.translate("MainWindow", "SSL", None, QApplication.UnicodeUTF8)) self.ssl_cb.setText(QApplication.translate("MainWindow", "Port : 993", None, QApplication.UnicodeUTF8)) self.lb_adress.setText(QApplication.translate("MainWindow", "Adress", None, QApplication.UnicodeUTF8)) self.lb_pass.setText(QApplication.translate("MainWindow", "Password", None, QApplication.UnicodeUTF8)) self.connect_btn.setText(QApplication.translate("MainWindow", "Connect", None, QApplication.UnicodeUTF8)) self.lb_select_mailbox.setText(QApplication.translate("MainWindow", "Select Mailbox", None, QApplication.UnicodeUTF8)) self.search_gbox.setTitle(QApplication.translate("MainWindow", " Search Parameters", None, QApplication.UnicodeUTF8)) self.since_date_cb.setText(QApplication.translate("MainWindow", "Since", None, QApplication.UnicodeUTF8)) self.since_date_edit.setDisplayFormat(QApplication.translate("MainWindow", "dd-MMM-yyyy", None, QApplication.UnicodeUTF8)) self.before_date_cb.setText(QApplication.translate("MainWindow", "Before", None, QApplication.UnicodeUTF8)) self.before_date_edit.setDisplayFormat(QApplication.translate("MainWindow", "dd-MMM-yyyy", None, QApplication.UnicodeUTF8)) self.html_radio.setText(QApplication.translate("MainWindow", "html", None, QApplication.UnicodeUTF8)) self.text_radio.setText(QApplication.translate("MainWindow", "text", None, QApplication.UnicodeUTF8)) # self.lb_threads.setText(QApplication.translate("MainWindow", "Threads", None, QApplication.UnicodeUTF8)) self.lb_from.setText(QApplication.translate("MainWindow", "From", None, QApplication.UnicodeUTF8)) self.lb_to.setText(QApplication.translate("MainWindow", "To", None, QApplication.UnicodeUTF8)) self.lb_subject.setText(QApplication.translate("MainWindow", "Subject", None, QApplication.UnicodeUTF8)) self.search_btn.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8)) self.links_gbox.setTitle(QApplication.translate("MainWindow", " Links", None, QApplication.UnicodeUTF8)) self.export_html_btn.setText(QApplication.translate("MainWindow", "Export as HTML", None, QApplication.UnicodeUTF8)) self.export_txt_btn.setText(QApplication.translate("MainWindow", "Export as txt", None, QApplication.UnicodeUTF8)) self.log_gbox.setTitle(QApplication.translate("MainWindow", " Log", None, QApplication.UnicodeUTF8)) self.disconnect_btn.setText(QApplication.translate("MainWindow", "Disconnect", None, QApplication.UnicodeUTF8)) self.menu_file.setTitle(QApplication.translate("MainWindow", "File", None, QApplication.UnicodeUTF8)) self.menu_about.setTitle(QApplication.translate("MainWindow", "About", None, QApplication.UnicodeUTF8)) self.action_about.setText(QApplication.translate("MainWindow", "About", None, QApplication.UnicodeUTF8)) self.action_About_Qt.setText(QApplication.translate("MainWindow", "About Qt", None, QApplication.UnicodeUTF8)) self.action_exit.setText(QApplication.translate("MainWindow", "Exit", None, QApplication.UnicodeUTF8)) self.action_exit.setShortcut(QApplication.translate("MainWindow", "Ctrl+Q", None, QApplication.UnicodeUTF8)) self.actionSave.setText(QApplication.translate("MainWindow", "Save", None, QApplication.UnicodeUTF8))
class LoginForm(QDialog): logged_in = Signal() def __init__(self, parent=None): super(LoginForm, self).__init__(parent) self.setWindowTitle("Login") self.status_icon = QIcon.fromTheme("user-offline") self.setWindowIcon(self.status_icon) self.server_status = QLabel() self.server_status.setAlignment(Qt.AlignCenter) self.server_status.setPixmap(self.status_icon.pixmap(64)) self.username = QLineEdit("Username") self.password = QLineEdit("Password") self.password.setEchoMode(QLineEdit.Password) self.login_button = QPushButton("Getting server status...") self.login_button.setEnabled(False) self.login_button.clicked.connect(self.login) self.login_button.setIcon(self.status_icon) self.ping_timer = QTimer(self) self.connect(self.ping_timer, SIGNAL("timeout()"), self.is_server_up) self.ping_timer.start(1000) layout = QVBoxLayout() for w in (self.server_status, self.username, self.password, self.login_button): layout.addWidget(w) self.setLayout(layout) self.logged_in.connect(qtclient.login) def is_server_up(self): '''Tests to see if the authentication server is up.''' global client from requests.exceptions import ConnectionError try: if client.ping(): self.login_button.setEnabled(True) self.login_button.setText("Login!") self.status_icon = QIcon.fromTheme("user-online") except (ConnectionError): # We can only wait until the server comes back up. self.login_button.setEnabled(False) self.login_button.setText("Server is offline. :(") self.status_icon = QIcon.fromTheme("user-offline") self.setWindowIcon(self.status_icon) self.server_status.setPixmap(self.status_icon.pixmap(64)) self.login_button.setIcon(self.status_icon) def login(self): # TODO: This could be an exception if login failed. Catch it. login_result = client.authenticate(self.username.text(), self.password.text()) if login_result: # We logged in, so show the character select dialog self.logged_in.emit() # Once its shown, mark this dialog as accepted (And by extension, close it.) self.accept()
class SyncView(View): """`View` derived class. Defines the sync widget""" sync = Signal((str, )) def __init__(self, parent=None): """ Init method. Initializes parent classes :param parent: Reference to a `QWidget` object to be used as parent """ super(SyncView, self).__init__(parent) self.createWidgets() self.createLayouts() self.setFixedSize(580, 340) self.status.setMessage('Ready') def createLayouts(self): """Put widgets into layouts, thus creating the widget""" mainLayout = QHBoxLayout() fieldsLayout = QVBoxLayout() pathLayout = QHBoxLayout() buttonLayout = QHBoxLayout() mainLayout.addStretch(10) fieldsLayout.addStretch(50) fieldsLayout.addWidget(self.linkLabel) fieldsLayout.addWidget(self.line) fieldsLayout.addWidget(self.localdirLabel) pathLayout.addWidget(self.localdirEdit) pathLayout.addWidget(self.browseButton) fieldsLayout.addLayout(pathLayout) buttonLayout.addStretch(50) buttonLayout.addWidget(self.syncButton, 50, Qt.AlignRight) fieldsLayout.addLayout(buttonLayout) fieldsLayout.addStretch(10) fieldsLayout.addWidget(self.statusLabel) fieldsLayout.addWidget(self.status) fieldsLayout.addStretch(80) mainLayout.addLayout(fieldsLayout, 60) mainLayout.addStretch(10) self.setLayout(mainLayout) def createWidgets(self): """Create children widgets needed by this view""" fieldsWidth = 450 labelsFont = View.labelsFont() editsFont = View.editsFont() self.setLogo() self.localdirLabel = QLabel(self) self.localdirEdit = QLineEdit(self) self.localdirLabel.setText('Choose a folder') self.localdirLabel.setFont(labelsFont) self.localdirEdit.setFixedWidth(fieldsWidth) self.localdirEdit.setReadOnly(False) self.localdirEdit.setFont(editsFont) self.browseButton = QPushButton(self) self.browseButton.setText('Browse') self.browseButton.setFont(labelsFont) self.syncButton = QPushButton(self) self.syncButton.setText('Sync') self.syncButton.setFont(labelsFont) self.browseButton.clicked.connect(self.onBrowseClicked) self.syncButton.clicked.connect(self.onSyncClicked) settings = get_settings() self.localdirEdit.setText(settings.value(SettingsKeys['localdir'], '')) self.statusLabel = QLabel(self) self.statusLabel.setText('Status') self.statusLabel.setFont(View.labelsFont()) self.status = StatusArea(self) @Slot() def onBrowseClicked(self): """Slot. Called when the user clicks on the `browseButton` button""" # Presents the user with a native directory selector window localdir = QFileDialog.getExistingDirectory() localdir = QDir.fromNativeSeparators(localdir) if len(localdir) > 0: # If `localdir`'s value is good, store it using a `QSettings` object # and triggers a sync request. # Careful with '\' separators on Windows. localdir = QDir.toNativeSeparators(localdir) get_settings().setValue(SettingsKeys['localdir'], localdir) self.localdirEdit.setText(localdir) @Slot() def onSyncClicked(self): """Slot. Called when the user clicks on the `syncButton` button""" localdir = self.localdirEdit.text() if len(localdir) > 0: self.syncButton.setEnabled(False) self.sync.emit(localdir)
class NewWindow(QWidget): def __init__(self, app=None): super(NewWindow, self).__init__() self.app = app glo = QVBoxLayout(self) if os.name == 'nt': icp = r_path('static\\images\\favicon.png') else: icp = r_path('static/images/favicon.png') # need to used objective message boxs instead of functions to set font self.Arial = QFont("", 15, QFont.Bold) self.Arials = QFont("", 10, QFont.Bold) # Language support varibels used by translate func self.Arabic = None self.Runningo = False icon = QIcon(icp) self.SelfIinit(icon) self.center() self.Llists(glo) self.set_Abutton(icp, glo) self.Lists(glo) self.Flabel(glo) self.set_button(glo) self.setLayout(glo) mip = self.slchange() self.P = rwser(mip[1].split(',')[1], mip[0], self.app) self.activateWindow() self.show() def SelfIinit(self, icon): self.setWindowTitle('Free Queue Manager ' + version) self.setGeometry(300, 300, 200, 150) self.setMinimumWidth(500) self.setMaximumWidth(500) self.setMinimumHeight(400) self.setMaximumHeight(400) # Setting Icon self.setWindowIcon(icon) QToolTip.setFont(self.Arials) def Flabel(self, glo): fontt = self.Arial if os.name == 'nt': self.ic1 = QIcon(r_path('static\\images\\pause.png')) else: self.ic1 = QIcon(r_path('static/images/pause.png')) self.l = QLabel('Icond', self) self.ic1 = self.ic1.pixmap(70, 70, QIcon.Active, QIcon.On) self.l.setPixmap(self.ic1) self.l.setAlignment(Qt.AlignCenter | Qt.AlignHCenter) self.l.setFont(fontt) self.t = QLabel('Texted', self) self.t.setText("Server is <u> Not running </u> <br>") self.t.setOpenExternalLinks(True) self.t.setAlignment(Qt.AlignCenter | Qt.AlignHCenter) self.t.setFont(fontt) self.t.setToolTip('Status of the server') self.l.setToolTip('Status of the server') glo.addStretch() glo.addWidget(self.l) glo.addWidget(self.t) glo.addStretch() def Lists(self, glo): ips = self.get_ips() self.sl = QComboBox() self.sl.addItems(ips) self.sl.setToolTip( 'Select network interface with ip, so the server runs on it') self.sl2 = QComboBox() self.get_ports() self.sl2.setToolTip('Select a port, so server runs through it') self.sl.currentIndexChanged.connect(self.get_ports) glo.addWidget(self.sl) glo.addWidget(self.sl2) def get_ports(self, nauto=True): d_ports = ['5000', '8080', '3000', '80', '9931'] m_ports = [] while len(m_ports) < 10: mip = self.slchange() for p in d_ports: s = socket(AF_INET, SOCK_STREAM) try: s.bind((mip[1].split(',')[1], int(p))) s.close() m_ports.append(p) except: s.close() d_ports.remove(p) s = socket(AF_INET, SOCK_STREAM) p = randint(1000, 9999) try: s.bind((mip[1].split(',')[1], p)) s.close() m_ports.append(str(p)) except: s.close() if len(m_ports) >= 10: break self.sl2.clear() self.sl2.addItems(m_ports) def Llists(self, glo): hlayout = QHBoxLayout() self.lebutton = QPushButton('English', self) self.lebutton.setToolTip('Change language to English') self.lebutton.setEnabled(False) self.lebutton.setFont(self.Arials) self.labutton = QPushButton('Arabic', self) self.labutton.setFont(self.Arials) if os.name == 'nt': self.lebutton.setIcon( QPixmap(r_path('static\\images\\english.png'))) self.labutton.setIcon(QPixmap( r_path('static\\images\\arabic.png'))) else: self.lebutton.setIcon(QPixmap(r_path('static/images/english.png'))) self.labutton.setIcon(QPixmap(r_path('static/images/arabic.png'))) self.labutton.setToolTip('Change language to Arabic') self.labutton.setEnabled(True) self.lebutton.clicked.connect(partial(self.translate, ar=False)) self.labutton.clicked.connect(self.translate) hlayout.addWidget(self.lebutton) hlayout.addWidget(self.labutton) glo.addLayout(hlayout) def slchange(self): return [self.sl2.currentText(), self.sl.currentText()] def set_button(self, glo): hlayout = QHBoxLayout() self.mbutton = QPushButton('Start', self) self.mbutton.clicked.connect(self.s_server) self.mbutton.setFont(self.Arials) if os.name == 'nt': self.mbutton.setIcon(QPixmap(r_path('static\\images\\play.png'))) else: self.mbutton.setIcon(QPixmap(r_path('static/images/play.png'))) self.mbutton2 = QPushButton('Stop', self) self.mbutton2.clicked.connect(self.st_server) if os.name == 'nt': self.mbutton2.setIcon(QPixmap(r_path('static\\images\\pause.png'))) else: self.mbutton2.setIcon(QPixmap(r_path('static/images/pause.png'))) self.mbutton.setToolTip('Start the server') self.mbutton2.setToolTip('Stop the server') self.mbutton2.setEnabled(False) self.mbutton2.setFont(self.Arials) hlayout.addWidget(self.mbutton) hlayout.addWidget(self.mbutton2) glo.addLayout(hlayout) def s_server(self): mip = self.slchange() self.P = rwser(mip[1].split(',')[1], mip[0], self.app) self.P.setTerminationEnabled(True) if not self.P.isRunning(): try: self.pport = mip[0] self.mbutton.setEnabled(False) self.mbutton2.setEnabled(True) self.sl.setEnabled(False) self.sl2.setEnabled(False) if os.name == 'nt': self.ic1 = QIcon(r_path('static\\images\\play.png')) else: self.ic1 = QIcon(r_path('static/images/play.png')) self.ic1 = self.ic1.pixmap(70, 70, QIcon.Active, QIcon.On) self.l.setPixmap(self.ic1) if self.Arabic is None: pp = self.slchange() addr = "Server is <u>Running</u> <br>" addr += " On : <a href='http://" addr += pp[1].split(',')[1] + ":" + pp[0] addr += "'> http://" + pp[1].split(',')[1] + ":" + pp[0] addr += "</a>" self.t.setText(addr) self.t.setFont(self.Arial) else: pp = self.slchange() addr = u"الخدمة <u>مشغــلة</u> و تبث على : <br>" addr += u"<a href='http://" addr += pp[1].split(',')[1] + u":" + pp[0] addr += u"'> http://" + pp[1].split(',')[1] + u":" + pp[0] addr += u"</a>" self.t.setText(addr) self.t.setFont(self.Arial) self.P.start() self.Runningo = True except: self.eout() else: self.eout() def st_server(self): if self.P.isRunning(): try: if self.P.isRunning: self.P.stop() self.mbutton.setEnabled(True) self.mbutton2.setEnabled(False) self.sl.setEnabled(True) self.sl2.setEnabled(True) if self.Arabic is None: self.t.setText("Server is <u> Not running </u> <br>") else: self.t.setText(u"الــخـدمة <u>متــوقفــة</u><br>") # removing the last used port to avoid termination error cind = self.sl2.currentIndex() self.sl2.removeItem(cind) self.get_ports() self.Runningo = False except: self.eout() else: self.eout() def set_Abutton(self, icon, glo): def show_about(nself): if nself.Arabic is None: Amsg = "<center>All credit reserved to the author of FQM " Amsg += " version " + version Amsg += ", This work is a free, open-source project licensed " Amsg += " under Mozilla Public License version 2.0 . <br><br>" Amsg += " visit us for more infos and how-tos :<br> " Amsg += "<b><a href='https://fqms.github.io/'> " Amsg += "https://fqms.github.io/ </a> </b></center>" Amsgb = "About FQM" else: Amsg = u" <center> " Amsg += u" إدارة الحشود الحر النسخة " + version + u" " Amsg += u"حقوق نشر هذا البرنامج محفوظة و تخضع " Amsg += u" لرخصة البرامج الحرة و مفتوحة المصدر " Amsg += u" Mozilla Public License version 2.0 . " Amsg += u"<br><br> " Amsg += u"للمزيد من المعلومات و الشروحات , قم بزيارة :" Amsg += u"<br> <b><a href='https://fqms.github.io/'>" Amsg += u"https://fqms.github.io </a> </b></center>" Amsgb = u"عن النظام" return QMessageBox.about(self, Amsgb, Amsg) self.abutton = QPushButton('', self) self.abutton.setIcon(QPixmap(icon)) self.abutton.setIconSize(QSize(150, 70)) self.abutton.setToolTip('About FQM') self.abutton.clicked.connect(partial(show_about, self)) glo.addWidget(self.abutton) def closeEvent(self, event=None): if self.Runningo: if self.Arabic is None: response = self.msgApp( "Exiting while running", "Are you really sure, you want to exit ?") else: response = self.msgApp( u"تأكيد الخروج", u"تريد بالفعل , الخروج و إيقاف البرنامج ؟") if response == 'y': if event is not None: event.accept() if self.P.isRunning(): self.P.stop() sys.exit(0) else: if event is not None: event.ignore() else: if event is not None: event.accept() if self.P.isRunning(): self.P.stop() sys.exit(0) def msgApp(self, title, msg): uinfo = QMessageBox.question(self, title, msg, QMessageBox.Yes | QMessageBox.No) if uinfo == QMessageBox.Yes: return 'y' if uinfo == QMessageBox.No: return 'n' def eout(self): if self.P.isRunning(): self.P.stop() if self.Arabic is None: msgg = "<center>" msgg += " Opps, a critical error has occurred, we will be " msgg += " grateful if you can help fixing it, by reporting to us " msgg += " at : <br><br> " msgg += "<b><a href='https://fqms.github.io/'> " msgg += "https://fqms.github.io/ </a></b> </center>" mm = QMessageBox.critical(self, "Critical Error", msgg, QMessageBox.Ok) else: msgg = u"<center>" msgg += u"حدث خطأ فادح في تشغيل النظام , سنكون شاكرين لك إن " msgg += u"قمت بتبليغنا عنه , ليتم إصلاحه في أقرب وقت " msgg += u"<br>" msgg += u"<br><b><a href='https://fqms.github.io/'> " msgg += u"https://fqms.github.io </a></b> </center>" mm = QMessageBox.critical(self, u"خطأ في التشغيل", msgg, QMessageBox.Ok) def center(self): qrect = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qrect.moveCenter(cp) self.move(qrect.topLeft()) def get_ips(self): il = [] for i in interfaces(): try: if os.name != 'nt': inf = i + " ," else: inf = ' ,' inf += ifaddresses(i)[2][0].get('addr') il.append(inf) except: pass return il def translate(self, ar=True): if ar: self.Arabic = "arabic" self.labutton.setEnabled(False) self.labutton.setText(u"العربية") self.labutton.setToolTip(u"تغير اللغة إلى العربية") self.lebutton.setText(u"الإنجليزية") self.lebutton.setToolTip(u"تغير اللغة إلى الإنجليزية") self.lebutton.setEnabled(True) self.Amsgb = u"عن النظام" self.abutton.setToolTip(u"عن النظام") self.mbutton.setText(u"تشغــيل") self.mbutton.setToolTip(u"تشغيل الخدمة") self.mbutton2.setText(u"إيــقاف") self.mbutton2.setToolTip(u"إيقاف الخدمة") self.sl.setToolTip(u"إختار عنوان IP ليتم بث الخدمة عليه") self.sl2.setToolTip(u"إختار منفذ ليتم بث الخدمة من خلاله") self.t.setToolTip(u"حالة الخدمة ") self.l.setToolTip(u"حالة الخدمة ") if self.Runningo: pp = self.slchange() addr = u"الخدمة <u>مشغــلة</u> و تبث على : <br>" addr += u"<a href='http://" addr += pp[1].split(',')[1] + u":" + pp[0] addr += u"'> http://" + pp[1].split(',')[1] + u":" + pp[0] addr += u"</a>" self.t.setText(addr) else: self.t.setText(u"الــخـدمة <u>متــوقفــة</u><br>") else: self.Arabic = None self.lebutton.setEnabled(False) self.lebutton.setText("English") self.lebutton.setToolTip('Change language to English') self.labutton.setEnabled(True) self.labutton.setText("Arabic") self.labutton.setToolTip('Change language to Arabic') self.Amsgb = "About FQM" self.abutton.setToolTip('About FQM') self.mbutton.setText("Start") self.mbutton.setToolTip("Start the server") self.mbutton2.setText("Stop") self.mbutton2.setToolTip("Stop the server") self.sl.setToolTip( 'Select network interface with ip, so the server runs on it') self.sl2.setToolTip('Select a port, so server runs through it') self.t.setToolTip('Status of the server') self.l.setToolTip('Status of the server') if self.Runningo: pp = self.slchange() addr = "Server is <u>Running</u> <br>" addr += " On : <a href='http://" addr += pp[1].split(',')[1] + ":" + pp[0] addr += "'> http://" + pp[1].split(',')[1] + ":" + pp[0] addr += "</a>" self.t.setText(addr) else: self.t.setText("Server is <u> Not running </u> <br>")
class MainWindow(QWidget, object): # noinspection PyUnresolvedReferences def __init__(self): super(MainWindow, self).__init__() self.clip_filename = None self.audio_filename = None layout = QBoxLayout(QBoxLayout.TopToBottom) clip_row = QBoxLayout(QBoxLayout.LeftToRight) self.clip_button = QPushButton() self.clip_button.clicked.connect(self.open_clip) self.clip_button.setText(self.tr("Open clip")) clip_row.addWidget(self.clip_button) self.clip_view = QLabel() clip_row.addWidget(self.clip_view) clip_frame = QFrame() clip_frame.setLayout(clip_row) layout.addWidget(clip_frame) audio_row = QBoxLayout(QBoxLayout.LeftToRight) self.audio_button = QPushButton() self.audio_button.clicked.connect(self.open_audio) self.audio_button.setText(self.tr("Open audio")) audio_row.addWidget(self.audio_button) self.audio_view = QLabel() audio_row.addWidget(self.audio_view) audio_frame = QFrame() audio_frame.setLayout(audio_row) layout.addWidget(audio_frame) save_row = QBoxLayout(QBoxLayout.LeftToRight) self.save_button = QPushButton() self.save_button.clicked.connect(self.save) self.save_button.setText(self.tr("Save synced clip")) save_row.addWidget(self.save_button) save_frame = QFrame() save_frame.setLayout(save_row) layout.addWidget(save_frame) self.update_save_button() layout.addStretch() self.setLayout(layout) self.show() def open_clip(self): self.clip_filename = QFileDialog.getOpenFileName( self, self.tr("Open Clip"), os.getcwd(), self. tr("Video Files [.mp4, .ogv, .mkv, .avi, .mov] (*.mp4 *.ogv *.mkv *.avi *.mov);;" + "Audio Files [.flac, .ogg, .wav, .mp3] (*.flac *.ogg *.wav *.mp3)" ))[0] self.clip_view.setText(self.clip_filename) self.update_save_button() def open_audio(self): self.audio_filename = QFileDialog.getOpenFileName( self, self.tr("Open Audio"), os.getcwd(), self. tr("Audio Files [.flac, .ogg, .wav, .mp3] (*.flac *.ogg *.wav *.mp3)" ))[0] self.audio_view.setText(self.audio_filename) self.update_save_button() def update_save_button(self): self.save_button.setEnabled( bool(self.clip_filename and self.audio_filename)) def save(self): dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.AnyFile) dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setDefaultSuffix("avi") dialog.setDirectory(os.getcwd()) dialog.setNameFilter(self.tr("Video Files [.avi] (*.avi)")) if dialog.exec_(): output_file_name = dialog.selectedFiles()[0] correlate(self.clip_filename, self.audio_filename, output_file_name)
class Form(QDialog): def __init__(self, state, parent=None): super().__init__(parent) Lib.prepareModalDialog(self) self.state = state self.setWindowTitle("Renumber Pages — {}".format( QApplication.applicationName())) self.createWidgets() self.layoutWidgets() self.createConnections() self.romanStartSpinBox.setFocus() self.updateUi() settings = QSettings() self.updateToolTips( bool( int( settings.value(Gopt.Key.ShowDialogToolTips, Gopt.Default.ShowDialogToolTips)))) def createWidgets(self): self.romanStartLabel = QLabel("&Roman from") self.romanStartSpinBox = Widgets.RomanSpinBox.SpinBox() self.tooltips.append((self.romanStartSpinBox, """\ <p><b>Roman from</b></p> <p>The first roman page number to change.</p>""")) self.romanStartLabel.setBuddy(self.romanStartSpinBox) self.romanEndLabel = QLabel("to") self.romanEndSpinBox = Widgets.RomanSpinBox.SpinBox() self.romanEndSpinBox.setValue(200) self.tooltips.append((self.romanEndSpinBox, """\ <p><b>Roman, to</b></p> <p>The last roman page number to change.</p>""")) self.romanChangeLabel = QLabel("change") self.romanChangeSpinBox = Widgets.ChangeSpinBox.SpinBox() self.romanChangeSpinBox.setRange(-100, 100) self.romanChangeSpinBox.setValue(0) self.romanChangeSpinBox.setMinimumWidth( self.romanChangeSpinBox.fontMetrics().width("W(no change)W")) self.tooltips.append((self.romanChangeSpinBox, """\ <p><b>Roman, change</b></p> <p>The amount to change the roman page numbers in the Roman from–to range.</p>""")) self.decimalStartLabel = QLabel("&Decimal from") self.decimalStartSpinBox = QSpinBox() self.decimalStartSpinBox.setAlignment(Qt.AlignRight) self.decimalStartLabel.setBuddy(self.decimalStartSpinBox) self.decimalStartSpinBox.setRange(1, 10000) self.tooltips.append((self.decimalStartSpinBox, """\ <p><b>Decimal from</b></p> <p>The first decimal page number to change.</p>""")) self.decimalEndLabel = QLabel("to") self.decimalEndSpinBox = QSpinBox() self.decimalEndSpinBox.setAlignment(Qt.AlignRight) self.decimalEndSpinBox.setRange(1, 10000) self.decimalEndSpinBox.setValue(2000) self.tooltips.append((self.decimalEndSpinBox, """\ <p><b>Decimal, to</b></p> <p>The last decimal page number to change.</p>""")) self.decimalChangeLabel = QLabel("change") self.decimalChangeSpinBox = Widgets.ChangeSpinBox.SpinBox() self.decimalChangeSpinBox.setRange(-100, 100) self.decimalChangeSpinBox.setValue(0) self.tooltips.append((self.decimalChangeSpinBox, """\ <p><b>Decimal, change</b></p> <p>The amount to change the decimal page numbers in the Decimal from–to range.</p>""")) self.buttonBox = QDialogButtonBox() self.renumberButton = QPushButton(QIcon(":/renumberpages.svg"), "Re&number") self.tooltips.append((self.renumberButton, """\ <p><b>Renumber</b></p> <p>Renumber roman and decimal page numbers within the given ranges by the specified amounts of change throughout the entire index.</p>""")) self.buttonBox.addButton(self.renumberButton, QDialogButtonBox.ActionRole) self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Cancel") self.tooltips.append((self.closeButton, """<p><b>Cancel</b></p> <p>Close the dialog without making any changes to the index.</p>""")) self.buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole) self.helpButton = QPushButton(QIcon(":/help.svg"), "Help") self.tooltips.append( (self.helpButton, "Help on the Renumber Pages dialog")) self.buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole) def layoutWidgets(self): grid = QGridLayout() grid.addWidget(self.romanStartLabel, 0, 0) grid.addWidget(self.romanStartSpinBox, 0, 1) grid.addWidget(self.romanEndLabel, 0, 2) grid.addWidget(self.romanEndSpinBox, 0, 3) grid.addWidget(self.romanChangeLabel, 0, 4) grid.addWidget(self.romanChangeSpinBox, 0, 5) grid.addWidget(self.decimalStartLabel, 1, 0) grid.addWidget(self.decimalStartSpinBox, 1, 1) grid.addWidget(self.decimalEndLabel, 1, 2) grid.addWidget(self.decimalEndSpinBox, 1, 3) grid.addWidget(self.decimalChangeLabel, 1, 4) grid.addWidget(self.decimalChangeSpinBox, 1, 5) hbox = QHBoxLayout() hbox.addLayout(grid) hbox.addStretch() layout = QVBoxLayout() layout.addLayout(hbox) layout.addStretch() layout.addWidget(self.buttonBox) self.setLayout(layout) def createConnections(self): self.buttonBox.rejected.connect(self.reject) self.renumberButton.clicked.connect(self.renumber) for spinbox in (self.romanStartSpinBox, self.romanEndSpinBox, self.romanChangeSpinBox, self.decimalStartSpinBox, self.decimalEndSpinBox, self.decimalChangeSpinBox): spinbox.valueChanged.connect(self.updateUi) self.helpButton.clicked.connect(self.help) def updateUi(self): self._synchronize(self.romanStartSpinBox, self.romanEndSpinBox) self._synchronize(self.decimalStartSpinBox, self.decimalEndSpinBox) changeRoman = ( (self.romanStartSpinBox.value() != self.romanEndSpinBox.value()) and self.romanChangeSpinBox.value() != 0) changeDecimal = ((self.decimalStartSpinBox.value() != self.decimalEndSpinBox.value()) and self.decimalChangeSpinBox.value() != 0) self.renumberButton.setEnabled(changeRoman or changeDecimal) self._setPrefix(self.romanChangeSpinBox) self._setPrefix(self.decimalChangeSpinBox) def _synchronize(self, startSpinBox, endSpinBox): value = startSpinBox.value() if endSpinBox.value() < value: endSpinBox.setValue(value) def _setPrefix(self, spinbox): spinbox.setPrefix("+" if spinbox.value() > 0 else "") def help(self): self.state.help("xix_ref_dlg_renumpages.html") def renumber(self): # No need to restore focus widget options = RenumberOptions(self.romanStartSpinBox.value(), self.romanEndSpinBox.value(), self.romanChangeSpinBox.value(), self.decimalStartSpinBox.value(), self.decimalEndSpinBox.value(), self.decimalChangeSpinBox.value()) with Lib.DisableUI(self): self.state.model.renumber(options, self.state.window.reportProgress) message = "Renumber pages" if self.state.model.canUndo: self.state.model.can_undo.emit(True, message) if self.state.model.canRedo: self.state.model.can_redo.emit(True, message) self.state.updateUi() say("Renumbered pages", SAY_TIMEOUT) self.accept()
class SyncView(View): """`View` derived class. Defines the sync widget""" sync = Signal((str,)) def __init__(self, parent=None): """ Init method. Initializes parent classes :param parent: Reference to a `QWidget` object to be used as parent """ super(SyncView, self).__init__(parent) self.createWidgets() self.createLayouts() self.setFixedSize(580, 340) self.status.setMessage('Ready') def createLayouts(self): """Put widgets into layouts, thus creating the widget""" mainLayout = QHBoxLayout() fieldsLayout = QVBoxLayout() pathLayout = QHBoxLayout() buttonLayout = QHBoxLayout() mainLayout.addStretch(10) fieldsLayout.addStretch(50) fieldsLayout.addWidget(self.linkLabel) fieldsLayout.addWidget(self.line) fieldsLayout.addWidget(self.localdirLabel) pathLayout.addWidget(self.localdirEdit) pathLayout.addWidget(self.browseButton) fieldsLayout.addLayout(pathLayout) buttonLayout.addStretch(50) buttonLayout.addWidget(self.syncButton, 50, Qt.AlignRight) fieldsLayout.addLayout(buttonLayout) fieldsLayout.addStretch(10) fieldsLayout.addWidget(self.statusLabel) fieldsLayout.addWidget(self.status) fieldsLayout.addStretch(80) mainLayout.addLayout(fieldsLayout, 60) mainLayout.addStretch(10) self.setLayout(mainLayout) def createWidgets(self): """Create children widgets needed by this view""" fieldsWidth = 450 labelsFont = View.labelsFont() editsFont = View.editsFont() self.setLogo() self.localdirLabel = QLabel(self) self.localdirEdit = QLineEdit(self) self.localdirLabel.setText('Choose a folder') self.localdirLabel.setFont(labelsFont) self.localdirEdit.setFixedWidth(fieldsWidth) self.localdirEdit.setReadOnly(False) self.localdirEdit.setFont(editsFont) self.browseButton = QPushButton(self) self.browseButton.setText('Browse') self.browseButton.setFont(labelsFont) self.syncButton = QPushButton(self) self.syncButton.setText('Sync') self.syncButton.setFont(labelsFont) self.browseButton.clicked.connect(self.onBrowseClicked) self.syncButton.clicked.connect(self.onSyncClicked) settings = get_settings() self.localdirEdit.setText(settings.value(SettingsKeys['localdir'], '')) self.statusLabel = QLabel(self) self.statusLabel.setText('Status') self.statusLabel.setFont(View.labelsFont()) self.status = StatusArea(self) @Slot() def onBrowseClicked(self): """Slot. Called when the user clicks on the `browseButton` button""" # Presents the user with a native directory selector window localdir = QFileDialog.getExistingDirectory() localdir = QDir.fromNativeSeparators(localdir) if len(localdir) > 0: # If `localdir`'s value is good, store it using a `QSettings` object # and triggers a sync request. # Careful with '\' separators on Windows. localdir = QDir.toNativeSeparators(localdir) get_settings().setValue(SettingsKeys['localdir'], localdir) self.localdirEdit.setText(localdir) @Slot() def onSyncClicked(self): """Slot. Called when the user clicks on the `syncButton` button""" localdir = self.localdirEdit.text() if len(localdir) > 0: self.syncButton.setEnabled(False) self.sync.emit(localdir)
class HighwayAnalyzeWidget(QWidget): def __init__(self): super(HighwayAnalyzeWidget,self).__init__() self.averageSimulationTime = 325.0 mainLayout = QVBoxLayout() mainLayout.setAlignment(Qt.AlignTop|Qt.AlignHCenter) mainLayout.setSpacing(0) self.setLayout(mainLayout) topWidget = QWidget() self.topLayout = QHBoxLayout() self.topLayout.setSpacing(0) topWidget.setLayout(self.topLayout) topLeftWidget = QWidget() self.topLeftLayout = QVBoxLayout() topLeftWidget.setLayout(self.topLeftLayout) self.setupTopGroup() self.setupFilterGroup() self.topLayout.addWidget(topLeftWidget) self.layout().addWidget(topWidget) # Button and log buttonAndLogWidget = QWidget() buttonAndLogWidget.setLayout(QVBoxLayout()) # Analyze the results BUTTON self.analyzeResultsButton = QPushButton('Analyze the results') self.analyzeResultsButton.clicked.connect(self.analyzeResults) self.analyzeResultsButton.setEnabled(False) buttonAndLogWidget.layout().addWidget(self.analyzeResultsButton) # LOG self.logText = QTextBrowser() self.logText.setFont(QFont('Century Gothic', 7)) self.logText.setWordWrapMode(QTextOption.NoWrap) buttonAndLogWidget.layout().addWidget(self.logText) self.topLayout.addWidget(buttonAndLogWidget) self.results = [] self.logFile = os.path.join(self.resultsPath(), 'analyze_'+os.uname()[1]+'.log') # Image self.picLabel = QLabel() self.picLabel.setAlignment(Qt.AlignHCenter) #self.picLabel.resize(800,600) self.picLabel.setMinimumSize(800,600) self.layout().addWidget(self.picLabel) def setupTopGroup(self): topGroup = QGroupBox("Simulation Results") self.resultsPathLineEdit = SimpleOption('resultsPath','Results Path','/home/thomas/Dropbox/Keio/research/results/') topGroupLayout = QVBoxLayout() topGroupLayout.setSpacing(0) topGroupLayout.setAlignment(Qt.AlignTop) topGroupLayout.addWidget(self.resultsPathLineEdit) self.loadResultsLabel = QLabel() self.loadResultsLabel.setAlignment(Qt.AlignHCenter) topGroupLayout.addWidget(self.loadResultsLabel) self.loadResultsButton = QPushButton("Load the results") self.loadResultsButton.clicked.connect(self.loadResults) topGroupLayout.addWidget(self.loadResultsButton) topGroup.setLayout(topGroupLayout) self.topLeftLayout.addWidget(topGroup) def resultsPath(self): return self.resultsPathLineEdit.getValue() def setupFilterGroup(self): filterGroup = QGroupBox('Filter the results') filterGroupLayout = QVBoxLayout() filterGroupLayout.setSpacing(0) filterGroupLayout.setAlignment(Qt.AlignTop) # Distribution Model self.filterDistribution = SimpleComboboxOption('dis','Speed Distribution Model',3, True, 'Uniform','Exponential','Normal','Log Normal') filterGroupLayout.addWidget(self.filterDistribution) self.filterDistribution.setVisible(False) # Number of results per point self.filterNb = SimpleSpinOption('simuNbMin', 'Minimum results for a given setting', 10, integer=True, checkable=True) self.filterNb.checkBox.setChecked(True) filterGroupLayout.addWidget(self.filterNb) # Filter the date dateWidget = QWidget() dateWidget.setLayout(QHBoxLayout()) self.filterDate = QCheckBox('After') self.filterDate.setChecked(QSettings().value('filterDate','0')=='1') dateWidget.layout().addWidget(self.filterDate) self.filterDateYear = QComboBox() for m in xrange(2010,2012): self.filterDateYear.addItem(str(m)) self.filterDateYear.setCurrentIndex(int(QSettings().value('dateYear', 1))) dateWidget.layout().addWidget(self.filterDateYear) dateWidget.layout().addWidget(QLabel('Year')) self.filterDateMonth = QComboBox() for m in xrange(1,13): self.filterDateMonth.addItem(str(m)) self.filterDateMonth.setCurrentIndex(int(QSettings().value('dateMonth', 4))) dateWidget.layout().addWidget(self.filterDateMonth) dateWidget.layout().addWidget(QLabel('Month')) self.filterDateDay = QComboBox() for d in xrange(1,32): self.filterDateDay.addItem(str(d)) self.filterDateDay.setCurrentIndex(int(QSettings().value('dateDay', 0))) dateWidget.layout().addWidget(self.filterDateDay) dateWidget.layout().addWidget(QLabel('Day')) filterGroupLayout.addWidget(dateWidget) filterGroup.setLayout(filterGroupLayout) self.topLeftLayout.addWidget(filterGroup) # Filter the scenario self.filterScenar = SimpleComboboxOption('scenar','Scenario',1, True, 'vanet-highway-test-thomas','vanet-highway-scenario2') filterGroupLayout.addWidget(self.filterScenar) # Filter gap self.filterGap = SimpleSpinOption('avgdistanalyze','Average Distance (m)',100, checkable=True) filterGroupLayout.addWidget(self.filterGap) def loadResults(self): self.loadResultsButton.setText('Loading the results...') self.loadResultsButton.setEnabled(False) self.results = [] self.resultsThread = LoadResults(resultsPath=self.resultsPath()) self.resultsThread.done.connect(self.loadResultsDone) self.resultsThread.error.connect(self.loadResultsError) self.resultsThread.start() @Slot(str) def loadResultsError(self, errorMsg): QMessageBox.critical(self, 'Error!', errorMsg) self.analyzeResultsButton.setEnabled(False) @Slot(dict) def loadResultsDone(self, results): self.results = results resultsNb = len(self.results) msg= 'Found %d Simulation Results\n(%d invalid files, %d simulations failed)' % (resultsNb, self.resultsThread.fileUnloadable, self.resultsThread.simulationFailed) self.loadResultsLabel.setText(msg) #self.calculateAverageSimulationTime() self.loadResultsButton.setText('Reload the results') self.loadResultsButton.setEnabled(True) self.analyzeResultsButton.setEnabled(True) if resultsNb>0: self.analyzeResults() def calculateAverageSimulationTime(self): totalTime = 0 nb = 0 for r in self.results: if 'simulationTime' in r: #print 'simu time: %s' % r['simulationTime'] totalTime += int(r['simulationTime']) nb += 1 #print 'from %s: [%3.3f,%3.3f]' % (r['filename'], r['settings']['prate'],r['results']['timeToReachDest']) if nb<=0: errorMsg= 'No simulation found with simulationTime' QMessageBox.critical(self, 'Error!', errorMsg) self.averageSimulationTime = 290.0 else: self.averageSimulationTime= totalTime/nb self.loadResultsLabel.setText(self.loadResultsLabel.text()+'\nAverage simulation time: %3.0f'%self.averageSimulationTime) def fil(self, r): return self.checkDis(r) and self.checkDate(r) and self.checkGap(r) and self.checkScenario(r) def checkDis(self,r): return (not self.filterDistribution.checkBox.isChecked()) or r['settings']['dis']==self.filterDistribution.getValue() def checkDate(self, r): return (not self.filterDate.isChecked()) or (r['date'] >= datetime(int(self.filterDateYear.currentText()), int(self.filterDateMonth.currentText()), int(self.filterDateDay.currentText()))) def checkScenario(self, r): return (not self.filterScenar.checkBox.isChecked()) or r['scenario']==self.filterScenar.getName() def checkGap(self, r): return (not self.filterGap.checkBox.isChecked()) or float(r['settings']['avgdist'])==float(self.filterGap.getValue()) def analyzeResults(self): self.saveSettings() if len(self.results)<=0: QMessageBox.critical(self, 'Error!', 'No results loaded :s') return self.log("=== ANALYZING RESULTS ===") self.logText.clear() p=0 meanValues = {} uniqueName = dateToFilename() gnuPlotDataFile =os.path.join(self.resultsPath(),'graphs/' + uniqueName+'.dat') with open(gnuPlotDataFile,'w') as data: while p<=100: nb = 0 totalTimeToReachDest = 0 totalSimulationTime = 0 for result in filter(lambda x: x['settings']['prate']==p and self.fil(x), self.results): totalSimulationTime += float(result['simulationTime']) totalTimeToReachDest += float(result['results']['timeToReachDest']) nb += 1 if self.filterNb.checkBox.isChecked(): minNb = self.filterNb.getValue() else: minNb = 0 if nb>minNb: meanSimulationTime = float(1.0*totalSimulationTime/nb) meanTimeToReachDest = float(1.0*totalTimeToReachDest/nb) meanValues[p] = {'prate':p, 'simuLationTime':meanSimulationTime, 'simulationsNb':nb, 'timeToReachDest':meanTimeToReachDest} self.log(meanValues[p]) toPlot = '%s %s' % (p, meanValues[p]['timeToReachDest']) #print toPlot data.write(toPlot+'\n') p += 1 data.close() if len(meanValues)>0: outputPic = 'graphs/' + uniqueName s = subprocess.Popen(['./toPlot.sh', outputPic, gnuPlotDataFile], cwd=self.resultsPath()) s.wait() outputPicPath = os.path.join(self.resultsPath(),outputPic+'.svg') pic = QImage(outputPicPath) #pic = pic.scaled(QSize(640,480)) self.picLabel.setPixmap(QPixmap(pic)) #os.system(os.path.join(self.resultsPath(),'toPlot.sh')) else: QMessageBox.critical(self, 'Error!', 'No simulation satisfies the criteria...') def log(self, txt): toLog = str(txt) toLogFile = '%s | %s' % (datetime.now(), txt) with open(self.logFile, 'a') as logFile: logFile.write(toLogFile+'\n') self.logText.append(toLog) def saveSettings(self): QSettings().setValue('simuNbMin', self.filterNb.getValue()) QSettings().setValue('avgdistanalyze', self.filterGap.getValue()) QSettings().setValue('scenar', self.filterScenar.getValue()) QSettings().setValue('dis', self.filterDistribution.getValue()) QSettings().setValue('dateDay', self.filterDateDay.currentIndex()) QSettings().setValue('dateMonth', self.filterDateMonth.currentIndex()) QSettings().setValue('dateYear', self.filterDateYear.currentIndex()) if self.filterDate.isChecked(): QSettings().setValue('filterDate', '1') else: QSettings().setValue('filterDate', '0')
class ToolBox(QVBoxLayout): sig = QtCore.Signal(object) listThread = None groupBoxThreadInfo = None threadvbox = None mode = None def __init__(self, mode, parentQWidget = None): QVBoxLayout.__init__(self) self.sig.connect(self.addThreadList) self.mode = mode self.sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Expanding) self.groupBoxSearch = QGroupBox() self.groupBoxSearch.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 4px; };") vboxSearch = QVBoxLayout() self.searchTitle = QLabel("Search Messages") vboxSearch.addWidget(self.searchTitle) self.searchHLayout = QHBoxLayout() self.editTextSearch = QTextEdit('') self.editTextSearch.setFixedSize(200,30) self.buttonSearch = QPushButton('Search') self.buttonSearch.setFixedSize(100,30) self.buttonSearch.clicked.connect(self.searchMsg) vboxSearch.addWidget(self.editTextSearch) self.searchHLayout.addWidget(self.buttonSearch) self.searchCursor = QLabel() self.searchHLayout.addWidget(self.searchCursor) vboxSearch.addLayout(self.searchHLayout) self.browseHLayout = QHBoxLayout() self.buttonLookUp = QPushButton('\u21e7') #Arrow up self.buttonLookUp.setFixedWidth(100) self.buttonLookUp.clicked.connect(self.moveToPrev) self.buttonLookDown = QPushButton('\u21e9') #Arrow down self.buttonLookDown.setFixedWidth(100) self.buttonLookDown.clicked.connect(self.moveToNext) self.browseHLayout.addWidget(self.buttonLookUp) self.browseHLayout.addWidget(self.buttonLookDown) vboxSearch.addLayout(self.browseHLayout) self.groupBoxSearch.setLayout(vboxSearch) self.addWidget(self.groupBoxSearch) self.groupBoxSearch.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)) self.buttonHiddenLifelines = QPushButton('Show hidden life-lines') self.buttonHiddenLifelines.setFixedWidth(200) self.buttonHiddenLifelines.clicked.connect(self.showHiddenLifelines) self.addWidget(self.buttonHiddenLifelines) self.buttonHiddenMessages = QPushButton('Show hidden Messages') self.buttonHiddenMessages.setFixedWidth(200) self.buttonHiddenMessages.clicked.connect(self.showHiddenMessages) self.addWidget(self.buttonHiddenMessages) if const.mode_interactive == mode: self.buttonCapture = QPushButton('Capture') self.buttonCapture.setFixedWidth(200) self.buttonCapture.clicked.connect(self.notifyCapture) self.addWidget(self.buttonCapture) self.msgRcv = [] self.msgInfo = QLabel("Message Info.") self.groupBoxMessageInfo = QGroupBox() self.groupBoxMessageInfo.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;") vbox = QVBoxLayout() vbox.addWidget(self.msgInfo) self.tableTime = QtGui.QTableWidget(3,2) self.tableTime.setHorizontalHeaderLabels(['-','time']) self.tableTime.setColumnWidth(0,80) self.tableTime.setColumnWidth(1,150) vwidth = self.tableTime.verticalHeader().length() hwidth = self.tableTime.horizontalHeader().height() fwidth = self.tableTime.frameWidth() * 2 self.tableTime.setFixedHeight(vwidth + hwidth + fwidth) self.tableTime.horizontalHeader().setStretchLastSection(True) self.tableTime.setItem(0,0,QTableWidgetItem('begin')) self.tableTime.setItem(0,1,QTableWidgetItem(' - ')) self.tableTime.setItem(1,0,QTableWidgetItem('end')) self.tableTime.setItem(1,1,QTableWidgetItem(' - ')) self.tableTime.setItem(2,0,QTableWidgetItem('duration')) self.tableTime.setItem(2,1,QTableWidgetItem(' - ')) vbox.addWidget(self.tableTime) self.titleArg = QLabel('Argument List') vbox.addWidget(self.titleArg) max_arg_num = 10 self.tableArgs = QtGui.QTableWidget(max_arg_num,2) self.tableArgs.setHorizontalHeaderLabels(['type','value']) for idx in range(0,max_arg_num): self.tableArgs.setItem(idx,0,QTableWidgetItem()) self.tableArgs.setItem(idx,1,QTableWidgetItem()) self.tableArgs.horizontalHeader().setStretchLastSection(True) vbox.addWidget(self.tableArgs) self.titleArg = QLabel('Return Value List') vbox.addWidget(self.titleArg) max_ret_num = 4 self.tableRet = QtGui.QTableWidget(max_ret_num,2) self.tableRet.setHorizontalHeaderLabels(['type','value']) for idx in range(0,max_ret_num): self.tableRet.setItem(idx,0,QTableWidgetItem()) self.tableRet.setItem(idx,1,QTableWidgetItem()) self.tableRet.horizontalHeader().setStretchLastSection(True) vwidth = self.tableRet.verticalHeader().length() hwidth = self.tableRet.horizontalHeader().height() fwidth = self.tableRet.frameWidth() * 2 self.tableRet.setFixedHeight(vwidth + hwidth + fwidth) vbox.addWidget(self.tableRet) self.buttonSrcView = QPushButton('view code') self.buttonSrcView.setFixedWidth(200) self.buttonSrcView.clicked.connect(self.openSourceViewer) self.buttonHide = QPushButton('Hide') self.buttonHide.setFixedWidth(200) self.buttonHide.clicked.connect(self.notifyHide) self.buttonHideAllMsg = QPushButton('Hide All') self.buttonHideAllMsg.setFixedWidth(200) self.buttonHideAllMsg.clicked.connect(self.hideAllMsgNamedAsSelected) self.groupBoxMessageInfo.setLayout(vbox) self.checkHideCircular = QCheckBox('Hide Circular Messages') self.checkHideCircular.setCheckState(QtCore.Qt.Unchecked) self.checkHideCircular.stateChanged.connect(self.changeHideCircularMessage) self.addWidget(self.checkHideCircular) self.addWidget(self.groupBoxMessageInfo) self.groupBoxMessageInfo.setSizePolicy(self.sizePolicy) def reset(self): for idx in reversed(range(0,self.listThread.count())): self.listThread.takeItem(idx) def setMsgInfoMessage(self,msg): self.strMessage = msg def changeHideCircularMessage(self,state): if state == QtCore.Qt.Unchecked: self.diagramView.hideCircularChanged(False) elif state == QtCore.Qt.Checked: self.diagramView.hideCircularChanged(True) def setMsgInfoModule(self,module): self.strModule = module def updateSearchStatus(self,curr,number): self.searchCursor.setText("%d/%d" % (curr,number)) def connectSourceViewer(self,viewer): self.srcViewer = viewer def openSourceViewer(self): self.srcViewer.openViewer(self.strModule,self.strMessage) def setMessageInfoTime(self,begin,end,duration): self.tableTime.item(0,1).setText(begin) self.tableTime.item(1,1).setText(end) self.tableTime.item(2,1).setText(duration + ' msec') def setMessageInfoArg(self,listParam,listArg): if listArg: for idx, text in enumerate(listArg): self.tableArgs.item(idx,1).setText(text) for idx, text in enumerate(listParam): self.tableArgs.item(idx,0).setText(text) else: for idx in range(0,self.tableArgs.rowCount()): self.tableArgs.item(idx,1).setText('') self.tableArgs.item(idx,0).setText('') def setMessageInfoRet(self,listRet): if listRet: for idx, text in enumerate(listRet): self.tableRet.item(idx,1).setText(text) else: for idx in range(0,self.tableRet.rowCount()): self.tableRet.item(idx,1).setText('') self.tableRet.item(idx,0).setText('') def notifyInteractiveStateChanged(self,state): if const.mode_interactive != self.mode: return if const.STATE_INTERACTIVE_CAPTURING == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Stop Capture') if const.STATE_INTERACTIVE_PROCESSING == state: self.buttonCapture.setEnabled(False) if const.STATE_INTERACTIVE_IDLE == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Capture') if const.STATE_INTERACTIVE_RESET == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Capture') elif const.STATE_INTERACTIVE_ACTIVE == state: self.buttonCapture.setEnabled(True) self.buttonCapture.setText('Capture') def setMessageInfo(self,info): self.msgInfo.setText(info) def setAvailable(self,threads): self.sig.emit(threads) def toggleThreadDisplay(self,item): print(self.listThread.currentRow()) #if item.isSelected(): # print(item.text() + " is selected") #else: # print(item.text() + " is not selected") self.diagramView.showThread(self.listThread.currentRow(),item.isSelected()) def hideAllMsgNamedAsSelected(self): self.diagramView.hideAllMessageSelected() def addThreadList(self,threads): if not self.groupBoxThreadInfo: self.groupBoxThreadInfo = QGroupBox() self.threadInfo = QLabel("Thread Info.") self.groupBoxThreadInfo.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;") if not self.threadvbox: self.threadvbox = QVBoxLayout() if not self.listThread: self.listThread = QListWidget() self.listThread.setFixedWidth(200) self.listThread.setSelectionMode(QtGui.QAbstractItemView.MultiSelection) QtCore.QObject.connect(self.listThread, QtCore.SIGNAL("itemClicked(QListWidgetItem *)"), self.toggleThreadDisplay) self.threadvbox.addWidget(self.threadInfo) self.threadvbox.addWidget(self.listThread) self.groupBoxThreadInfo.setLayout(self.threadvbox) self.addWidget(self.groupBoxThreadInfo) self.groupBoxThreadInfo.setSizePolicy(self.sizePolicy) for id in threads: item = QtGui.QListWidgetItem(id) self.listThread.addItem(item) def connectController(self,controller): self.controller = controller self.connect(controller,QtCore.SIGNAL('setAvailable()'),self.setAvailable) def connectDiagramView(self,view): self.diagramView = view def disconnectMsgRcv(self,receiver): print("Implement this method !!! disconnectMsgRcv") def connectMsgRcv(self,receiver): self.msgRcv.append(receiver) def notifyHide(self): for rcv in self.msgRcv: rcv.activateHide(True) def showHiddenLifelines(self): response, selected_items = HiddenDialog.HiddenDialog.getSelectedItems(self.diagramView.getHiddenLifeLines()) if response: self.diagramView.showLifelines(selected_items) def showHiddenMessages(self): response, selected_items = HiddenMessageDialog.HiddenMessageDialog.getSelectedItems(self.diagramView.getHiddenMessages(),self.diagramView.getHiddenLifeLines()) if response: if selected_items[3] in self.diagramView.getHiddenLifeLines(): confirmation = ShowLifeLineDialog.ShowLifeLineDialog.confirmToShowLifeLine(selected_items[3]) if confirmation: self.diagramView.showLifelines([selected_items[3]]) self.diagramView.showMessages(selected_items) else: self.diagramView.showMessages(selected_items) def notifyCapture(self): for rcv in self.msgRcv: rcv.activateCapture(True) def moveToPrev(self): for rcv in self.msgRcv: rcv.moveToPrev() def moveToNext(self): for rcv in self.msgRcv: rcv.moveToNext() def searchMsg(self): str = self.editTextSearch.toPlainText() for rcv in self.msgRcv: rcv.searchMessage(str)
class window(QMainWindow): """Main window.""" def __init__(self, parent=None): """Initialize the parent class of this instance.""" super(window, self).__init__(parent) app.aboutToQuit.connect(self.myExitHandler) self.style_sheet = self.styleSheet('style') # app.setStyle(QStyleFactory.create('Macintosh')) #app.setStyleSheet(self.style_sheet) self.layout().setSpacing(0) self.layout().setContentsMargins(0,0,0,0) app.setOrganizationName("Eivind Arvesen") app.setOrganizationDomain("https://github.com/eivind88/raskolnikov") app.setApplicationName("Raskolnikov") app.setApplicationVersion("0.0.1") settings = QSettings() self.data_location = QDesktopServices.DataLocation self.temp_location = QDesktopServices.TempLocation self.cache_location = QDesktopServices.CacheLocation self.startpage = "https://duckduckgo.com/" self.new_tab_behavior = "insert" global bookmarks global saved_tabs print "Currently saved_tabs:\n", saved_tabs global menubar menubar = QMenuBar() # Initialize a statusbar for the window self.statusbar = self.statusBar() self.statusbar.setFont(QFont("Helvetica Neue", 11, QFont.Normal)) self.statusbar.setStyleSheet(self.style_sheet) self.statusbar.setMinimumHeight(15) self.pbar = QProgressBar() self.pbar.setMaximumWidth(100) self.statusbar.addPermanentWidget(self.pbar) self.statusbar.hide() self.setMinimumSize(504, 235) # self.setWindowModified(True) # app.alert(self, 0) self.setWindowTitle("Raskolnikov") # toolbar = self.addToolBar('Toolbar') # toolbar.addAction(exitAction) # self.setUnifiedTitleAndToolBarOnMac(True) self.setWindowIcon(QIcon("")) # Create input widgets self.bbutton = QPushButton(u"<") self.fbutton = QPushButton(u">") self.hbutton = QPushButton(u"⌂") self.edit = QLineEdit("") self.edit.setFont(QFont("Helvetica Neue", 12, QFont.Normal)) self.edit.setPlaceholderText("Enter URL") # self.edit.setMinimumSize(400, 24) self.rbutton = QPushButton(u"↻") self.dbutton = QPushButton(u"☆") self.tbutton = QPushButton(u"⁐") # ↆ ⇧ √ ⌘ ⏎ ⏏ ⚠ ✓ ✕ ✖ ✗ ✘ ::: ❤ ☮ ☢ ☠ ✔ ☑ ♥ ✉ ☣ ☤ ✘ ☒ ♡ ツ ☼ ☁ ❅ ✎ self.nbutton = QPushButton(u"+") self.nbutton.setObjectName("NewTab") self.nbutton.setMinimumSize(35, 30) self.nbutton.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum) self.edit.setTextMargins(2, 1, 2, 0) # create a horizontal layout for the input input_layout = QHBoxLayout() input_layout.setSpacing(4) input_layout.setContentsMargins(0, 0, 0, 0) # add the input widgets to the input layout input_layout.addWidget(self.bbutton) input_layout.addWidget(self.fbutton) input_layout.addWidget(self.hbutton) input_layout.addWidget(self.edit) input_layout.addWidget(self.rbutton) input_layout.addWidget(self.dbutton) input_layout.addWidget(self.tbutton) # create a widget to hold the input layout self.input_widget = QFrame() self.input_widget.setObjectName("InputWidget") self.input_widget.setStyleSheet(self.style_sheet) # set the layout of the widget self.input_widget.setLayout(input_layout) self.input_widget.setVisible(True) # CREATE BOOKMARK-LINE HERE self.bookmarks_layout = QHBoxLayout() self.bookmarks_layout.setSpacing(0) self.bookmarks_layout.setContentsMargins(0, 0, 0, 0) for i in bookmarks: link = QToolButton() link.setDefaultAction(QAction(unicode(i), link)) link.setObjectName(unicode(i)) link.setFont(QFont("Helvetica Neue", 11, QFont.Normal)) link.clicked.connect(self.handleBookmarks) self.bookmarks_layout.addWidget(link) self.bookmarks_widget = QFrame() self.bookmarks_widget.setObjectName("BookmarkWidget") self.bookmarks_widget.setStyleSheet(self.style_sheet) self.bookmarks_widget.setLayout(self.bookmarks_layout) if not bookmarks: self.bookmarks_widget.hide() # Task list self.tasklist = QStandardItemModel() #parentItem = self.tasklist.invisibleRootItem() #self.tasklist.header().hide() self.tasklist.setHorizontalHeaderItem(0, QStandardItem('Tasks')) parentItem = QStandardItem("Parent") self.tasklist.appendRow(parentItem) for i in range(4): item = QStandardItem("Item %d" % i) parentItem.appendRow(item) #parentItem = item #self.list.activated[str].connect(self.handleBookmarks) #self.list.view().setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum) # create tabs self.tabs = QTabWidget() self.tabs.setDocumentMode(True) self.tabs.setTabsClosable(True) self.tabs.setMovable(True) self.tabs.tabBar().hide() self.tabs.setFont(QFont("Helvetica Neue", 11, QFont.Normal)) self.tabs.setCornerWidget(self.nbutton) self.tabs.cornerWidget().setObjectName("CornerWidget") self.tabs.cornerWidget().setMinimumSize(10, 24) self.tabs.cornerWidget().setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum) if saved_tabs: for tab in saved_tabs['tabs']: tasklist = QTreeView() tasklist.hide() tasklist.setObjectName('taskList') tasklist.setMinimumWidth(100) tasklist.setMaximumWidth(250) new_tab = QWebView() new_tab.setObjectName('webView') inspector = QWebInspector(self) inspector.setObjectName('webInspector') inspector.hide() page_layout = QVBoxLayout() page_layout.setSpacing(0) page_layout.setContentsMargins(0, 0, 0, 0) page_layout.addWidget(new_tab) page_layout.addWidget(inspector) page_widget = QFrame() page_widget.setObjectName('pageWidget') page_widget.setLayout(page_layout) complete_tab_layout = QHBoxLayout() complete_tab_layout.setSpacing(0) complete_tab_layout.setContentsMargins(0, 0, 0, 0) complete_tab_layout.addWidget(tasklist) complete_tab_layout.addWidget(page_widget) complete_tab_widget = QFrame() complete_tab_widget.setLayout(complete_tab_layout) #for page in tab['history']: # new_tab.load(QUrl(page['url'])) #print tab['current_history'] #for item in new_tab.history().items(): # print item #new_tab.history().goToItem(new_tab.history().itemAt(tab['current_history'])) new_tab.load(QUrl(tab['history'][tab['current_history']]['url'])) tab['current_history'] self.tabs.setUpdatesEnabled(False) if self.new_tab_behavior == "insert": self.tabs.insertTab(self.tabs.currentIndex()+1, complete_tab_widget, unicode(new_tab.title())) elif self.new_tab_behavior == "append": self.tabs.appendTab(complete_tab_widget, unicode(new_tab.title())) self.tabs.setUpdatesEnabled(True) new_tab.titleChanged.connect(self.change_tab) new_tab.urlChanged.connect(self.change_tab) new_tab.loadStarted.connect(self.load_start) new_tab.loadFinished.connect(self.load_finish) new_tab.loadProgress.connect(self.pbar.setValue) new_tab.page().linkHovered.connect(self.linkHover) inspector.setPage(new_tab.page()) for index, tab in enumerate(saved_tabs['tabs']): self.tabs.setTabText(index, tab['history'][tab['current_history']]['title']) self.tabs.setCurrentIndex(saved_tabs['current_tab']) else: self.new_tab() tabs_layout = QVBoxLayout() tabs_layout.setSpacing(0) tabs_layout.setContentsMargins(0, 0, 0, 0) tabs_layout.addWidget(self.tabs) self.tabs_widget = QFrame() self.tabs_widget.setObjectName("TabLine") self.tabs_widget.setStyleSheet(self.style_sheet) self.tabs_widget.setLayout(tabs_layout) self.tabs_widget.setVisible(True) # Webkit settings gsettings = self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).settings().globalSettings() # Basic settings gsettings.setAttribute(QWebSettings.AutoLoadImages, True) gsettings.setAttribute(QWebSettings.JavascriptEnabled, True) gsettings.setAttribute(QWebSettings.JavascriptCanOpenWindows, False) gsettings.setAttribute(QWebSettings.JavascriptCanAccessClipboard, False) gsettings.setAttribute(QWebSettings.PluginsEnabled, False) # Flash isn't stable at present gsettings.setAttribute(QWebSettings.JavaEnabled, False) # Java applet's aren't supported by PySide gsettings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True) gsettings.setAttribute(QWebSettings.AcceleratedCompositingEnabled, True) # Performace settings gsettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True) gsettings.setAttribute(QWebSettings.AcceleratedCompositingEnabled, True) gsettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True) # Other settings gsettings.setAttribute(QWebSettings.PrivateBrowsingEnabled, False) # Create a vertical layout and add widgets vlayout = QVBoxLayout() vlayout.setSpacing(0) vlayout.setContentsMargins(0, 0, 0, 0) # toolbar.addWidget(self.input_widget) vlayout.addWidget(self.input_widget) vlayout.addWidget(self.bookmarks_widget) vlayout.addWidget(self.tabs_widget) # create a widget to hold the vertical layout wrapper_widget = QWidget() wrapper_widget.setLayout(vlayout) self.setCentralWidget(wrapper_widget) self.bbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).back) self.fbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).forward) self.hbutton.clicked.connect(self.goHome) self.edit.returnPressed.connect(self.set_url) # Add button signal to "go" slot self.rbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).reload) self.dbutton.clicked.connect(self.bookmark) self.tbutton.clicked.connect(self.toggleTaskBar) self.nbutton.clicked.connect(self.new_tab) self.tabs.tabCloseRequested.connect(self.tabs.removeTab) self.tabs.currentChanged.connect(self.change_tab) widgets = (input_layout.itemAt(i).widget() for i in range( input_layout.count())) for widget in widgets: if isinstance(widget, QPushButton): widget.setFixedSize(33, 21) widget.setFont(QFont("Helvetica Neue", 12, QFont.Normal)) widget.pressed.connect(self.press_button) widget.released.connect(self.release_button) # make a ctrl+q quit sequence = QKeySequence(Qt.CTRL + Qt.Key_Q) QShortcut(sequence, self, SLOT("close()")) # make an accelerator to toggle fullscreen sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_F) QShortcut(sequence, self, self.toggle_fullscreen) # make an accelerator to toggle input visibility sequence = QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_L) QShortcut(sequence, self, self.toggle_input) # make an accelerator to focus adress-bar sequence = QKeySequence(Qt.CTRL + Qt.Key_L) QShortcut(sequence, self, self.focus_adress) # make an accelerator to reload page sequence = QKeySequence(Qt.CTRL + Qt.Key_R) QShortcut(sequence, self, self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).reload) # make an accelerator to create new tab sequence = QKeySequence(Qt.CTRL + Qt.Key_T) QShortcut(sequence, self, self.new_tab) # make an accelerator to close tab sequence = QKeySequence(Qt.CTRL + Qt.Key_W) QShortcut(sequence, self, self.close_tab) # make an accelerator to navigate tabs sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Left) QShortcut(sequence, self, self.previous_tab) sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Right) QShortcut(sequence, self, self.next_tab) # make an accelerator to toggle inspector sequence = QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_U) QShortcut(sequence, self, self.handleShowInspector) # make an accelerator to toggle bookmark sequence = QKeySequence(Qt.CTRL + Qt.Key_D) QShortcut(sequence, self, self.bookmark) # make an accelerator to toggle task/project-list sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_L) QShortcut(sequence, self, self.toggleTaskBar) # finally set the attribute need to rotate # try: # self.setAttribute(Qt.WA_Maemo5AutoOrientation, True) # except: # print "not maemo" self.statusbar.show() def press_button(self): """On button press. Connected.""" self.sender().setStyleSheet('background-color: rgba(228, 228, 228)') def release_button(self): """On button release. Connected.""" self.sender().setStyleSheet('background-color: rgba(252, 252, 252)') def goHome(self): """Go to startpage.""" self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).setUrl(QUrl(self.startpage)) def handleShowInspector(self): """Toggle web inspector.""" self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).setShown(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).isHidden()) def toggleTaskBar(self): """Toggle task bar.""" if self.tabs.currentWidget().findChild(QTreeView, unicode('taskList')).isHidden(): self.tabs.currentWidget().findChild(QTreeView, unicode('taskList')).setModel(self.tasklist) self.tabs.currentWidget().findChild(QTreeView, unicode('taskList')).setShown(self.tabs.currentWidget().findChild(QTreeView, unicode('taskList')).isHidden()) #self.tasklist.setShown(self.tasklist.isHidden()) def focus_adress(self): """Focus adress bar.""" self.edit.selectAll() self.edit.setFocus() def toggle_input(self): """Toggle input visibility.""" if self.input_widget.isVisible(): visible = False else: visible = True self.input_widget.setVisible(visible) def toggle_fullscreen(self): """Toggle fullscreen.""" if self.isFullScreen(): self.showNormal() else: self.showFullScreen() self.change_tab() def linkHover(self, l): """Show link adress in status bar on mouse hover.""" self.statusbar.showMessage(l) def new_tab(self): """Open new tab.""" tasklist = QTreeView() tasklist.hide() tasklist.setObjectName('taskList') tasklist.setMinimumWidth(100) tasklist.setMaximumWidth(250) new_tab = QWebView() new_tab.setObjectName('webView') inspector = QWebInspector(self) inspector.setObjectName('webInspector') inspector.hide() page_layout = QVBoxLayout() page_layout.setSpacing(0) page_layout.setContentsMargins(0, 0, 0, 0) page_layout.addWidget(new_tab) page_layout.addWidget(inspector) page_widget = QFrame() page_widget.setObjectName('pageWidget') page_widget.setLayout(page_layout) complete_tab_layout = QHBoxLayout() complete_tab_layout.setSpacing(0) complete_tab_layout.setContentsMargins(0, 0, 0, 0) complete_tab_layout.addWidget(tasklist) complete_tab_layout.addWidget(page_widget) complete_tab_widget = QFrame() complete_tab_widget.setLayout(complete_tab_layout) new_tab.load(QUrl(self.startpage)) self.tabs.setUpdatesEnabled(False) if self.new_tab_behavior == "insert": self.tabs.insertTab(self.tabs.currentIndex()+1, complete_tab_widget, unicode(new_tab.title())) elif self.new_tab_behavior == "append": self.tabs.appendTab(complete_tab_widget, unicode(new_tab.title())) self.tabs.setCurrentWidget(complete_tab_widget) self.tabs.setTabText(self.tabs.currentIndex(), unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).title())) self.tabs.setUpdatesEnabled(True) # tab.page().mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) # tab.page().mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) new_tab.titleChanged.connect(self.change_tab) new_tab.urlChanged.connect(self.change_tab) new_tab.loadStarted.connect(self.load_start) new_tab.loadFinished.connect(self.load_finish) new_tab.loadProgress.connect(self.pbar.setValue) new_tab.page().linkHovered.connect(self.linkHover) inspector.setPage(new_tab.page()) def change_tab(self): """Change active tab.""" if self.tabs.count() <= 1: self.tabs.tabBar().hide() else: self.tabs.tabBar().show() try: self.edit.setText(str(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded())) self.tabs.setTabText(self.tabs.currentIndex(), unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).title())) self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).setFocus() except Exception: self.tabs.tabBar().hide() self.new_tab() #print (self.tabs.widget(self.tabs.currentIndex()).size().width()-10), self.tabs.count() self.tabs_widget.setStyleSheet(self.style_sheet + "QTabBar::tab { width:" + str( (self.tabs.widget( self.tabs.currentIndex() ).size().width()-26-self.tabs.count()*2)/self.tabs.count() ) + "px; }") def previous_tab(self): """Previous tab.""" try: if self.tabs.currentIndex() > 0: self.tabs.setCurrentIndex(self.tabs.currentIndex()-1) else: self.tabs.setCurrentIndex(self.tabs.count()-1) self.change_tab() except Exception: pass def next_tab(self): """Next tab.""" try: if self.tabs.currentIndex() < self.tabs.count()-1: self.tabs.setCurrentIndex(self.tabs.currentIndex()+1) else: self.tabs.setCurrentIndex(0) self.change_tab() except Exception: #, e pass def close_tab(self): """Close tab.""" self.tabs.removeTab(self.tabs.currentIndex()) def close(self): """Close app.""" Qapplication.quit() def set_url(self): """Set url.""" url = self.edit.text() # does the url start with http://? if "." not in url: url = "http://www.google.com/search?q="+url elif not url.startswith("http://"): url = "http://" + url qurl = QUrl(url) self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).load(qurl) self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).setFocus() def load_start(self): """Update view values, called upon started page load.""" self.rbutton.setText(u"╳") self.rbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).stop) self.pbar.show() def load_finish(self): """Update view values, called upon finished page load.""" if (self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).history().canGoBack()): self.bbutton.setEnabled(True) else: self.bbutton.setEnabled(False) if (self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).history().canGoForward()): self.fbutton.setEnabled(True) else: self.fbutton.setEnabled(False) self.rbutton.setText(u"↻") self.rbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).reload) self.pbar.hide() global bookmarks if unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded()) in bookmarks: self.dbutton.setText(u"★") else: self.dbutton.setText(u"☆") if not self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).isHidden(): self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).hide() self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebInspector, unicode('webInspector')).show() def bookmark(self): """Toggle bookmark.""" global bookmarks if not self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded() in bookmarks: bookmarks.append(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded()) pickle.dump(bookmarks, open(bookFile, "wb")) link = QToolButton() link.setDefaultAction(QAction(unicode(unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded())), link)) link.setObjectName(unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded())) link.setFont(QFont("Helvetica Neue", 11, QFont.Normal)) link.clicked.connect(self.handleBookmarks) self.bookmarks_layout.addWidget(link) if self.bookmarks_widget.isHidden(): self.bookmarks_widget.show() self.dbutton.setText(u"★") else: bookmarks.remove(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded()) pickle.dump(bookmarks, open(bookFile, "wb")) link = self.bookmarks_widget.findChild(QToolButton, unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).url().toEncoded())) self.bookmarks_layout.removeWidget(link) link.deleteLater() link = None if not bookmarks: self.bookmarks_widget.hide() self.dbutton.setText(u"☆") def handleBookmarks(self): self.gotoLink(self.sender().objectName()) #self.gotoLink(unicode()) def gotoLink(self, url): self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).load(QUrl(url)) def styleSheet(self, style_sheet): """Load stylesheet.""" try: with open(os.path.join (basedir, 'assets', 'style.qss'), 'r') as file: return file.read() except Exception: # print e return '' def resizeEvent(self, evt=None): """Called on window resize.""" self.change_tab() def myExitHandler(self): """Exiting.""" pass global tabFile # {current_tab: 1, tabs:[0: {current_history:3, history:[{title, url}]]} pb = {'current_tab': self.tabs.currentIndex()} pb['tabs'] = list() for tab in range(self.tabs.count()): pb['tabs'].append(dict(current_history=self.tabs.widget( tab).findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).history().currentItemIndex(), history=list(dict( title=item.title(), url=item.url() ) for item in self.tabs.widget(tab).findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).history().items()))) # print pb pickle.dump(pb, open(tabFile, "wb"))
class UsbResetter(QWidget): def __init__(self): super(UsbResetter, self).__init__() self.P = UR_thread() self.thr_counter = 0 self.Looping = None self.Hidden = None self.Fhidden = None self.s_error = "QStatusBar{color:red;font-weight:1000;}" self.s_loop = "QStatusBar{color:black;font-weight:1000;}" self.s_norm = "QStatusBar{color:blue;font-style:italic;" self.s_norm += "font-weight:500;}" favicon = r_path("images/favicon.png") logo = r_path("images/logo.png") if name == 'nt': favicon = r_path("images\\favicon.png") logo = r_path("images\\logo.png") self.favicon = QIcon(favicon) self.plogo = logo self.logo = QIcon(logo) self.setStyle() mlayout = QVBoxLayout() self.setAbout(mlayout) self.setUlist(mlayout) self.setCboxs(mlayout) self.setReset(mlayout) self.setLoop(mlayout) self.setSb(mlayout) # functionalities self.set_list() self.rootWarn() # initiation self.activateWindow() self.setLayout(mlayout) self.show() def setSb(self, m): self.statusbar = QStatusBar() m.addWidget(self.statusbar) def setStyle(self): self.setMaximumWidth(350) self.setMinimumWidth(350) self.setMaximumHeight(340) self.setMinimumHeight(340) self.setWindowTitle("usb-resetter 1.0") self.setWindowIcon(self.favicon) self.show() def setAbout(self, m): self.pushButton = QPushButton() self.icon1 = QIcon() self.icon1.addPixmap(QPixmap(self.plogo), QIcon.Normal, QIcon.Off) self.pushButton.setIcon(self.icon1) self.pushButton.setIconSize(QSize(300, 100)) self.pushButton.clicked.connect(self.show_about) m.addWidget(self.pushButton) def setUlist(self, m): self.comboBox = QComboBox() m.addWidget(self.comboBox) def setCboxs(self, m): ml = QVBoxLayout() fl = QHBoxLayout() self.checkBox_2 = QCheckBox("Audio") self.checkBox_3 = QCheckBox("Mass storage") self.checkBox_2.setToolTip("Filter by audio devices") self.checkBox_3.setToolTip("Filter by mass storage devices") fl.addWidget(self.checkBox_2) fl.addWidget(self.checkBox_3) ml.addLayout(fl) sl = QHBoxLayout() self.checkBox_4 = QCheckBox("Network") self.checkBox_4.setToolTip("Filter by network devices") self.checkBox_5 = QCheckBox("Human interface") self.checkBox_5.setToolTip("Filter by Keyboard, mouse, joystick ..etc") sl.addWidget(self.checkBox_4) sl.addWidget(self.checkBox_5) ml.addLayout(sl) self.checkBox_2.clicked.connect(self.set_list) self.checkBox_3.clicked.connect(self.set_list) self.checkBox_4.clicked.connect(self.set_list) self.checkBox_5.clicked.connect(self.set_list) m.addLayout(ml) def setReset(self, m): self.pushButton_2 = QPushButton("Reset it") font = QFont() font.setPointSize(17) font.setWeight(75) font.setBold(True) self.pushButton_2.setFont(font) self.pushButton_2.clicked.connect(self.setbut_reset) m.addWidget(self.pushButton_2) def setLoop(self, m): ml = QHBoxLayout() self.checkBox = QCheckBox("Looping") self.checkBox.setToolTip("To repeat resetting for specified duration") self.lineEdit = QLineEdit() self.lineEdit.setToolTip("Duration in-which the resetting is done") self.pushButton_3 = QPushButton("Stop") self.pushButton_3.setToolTip("Stop looping") ml.addWidget(self.checkBox) ml.addWidget(self.lineEdit) ml.addWidget(self.pushButton_3) self.pushButton_3.setEnabled(False) self.lineEdit.setEnabled(False) self.lineEdit.setPlaceholderText("duration in seconds") self.checkBox.clicked.connect(self.loop_status) self.pushButton_3.clicked.connect(self.in_loop) m.addLayout(ml) # Functionalities def show_about(self): Amsg = "<center>All credit reserved to the author of " Amsg += "usb-resetter version 1.0" Amsg += ", This work is a free, open-source project licensed " Amsg += " under Mozilla Public License version 2.0 . <br><br>" Amsg += " visit us for more infos and how-tos :<br> " Amsg += "<b><a href='https://usb-resetter.github.io/'> " Amsg += "https://usb-resetter.github.io/ </a> </b></center>" Amsgb = "About usb-resetter" v = QMessageBox.about(self, Amsgb, Amsg) v = str(v) return v def closeEvent(self, event=None): if self.Hidden is None: response = QMessageBox.question( self, "Hide or close", "Do you want to hide the application ?", QMessageBox.Yes, QMessageBox.No) if response == QMessageBox.Yes: if event is not None: event.ignore() self.Hidden = True self.hide() elif response == QMessageBox.No: if event is not None: event.accept() return self.exitEvent() else: return False else: return self.exitEvent() def exitEvent(self): if self.P.isRunning(): response = QMessageBox.question( self, "Making sure", "Sure, you want to exit while looping ?", QMessageBox.Yes, QMessageBox.No) if response == QMessageBox.Yes: self.P.stop() exit(0) else: return False else: exit(0) def get_list(self): ol = [] if self.checkBox_2.isChecked(): ol.append(1) if self.checkBox_3.isChecked(): ol.append(8) if self.checkBox_4.isChecked(): ol.append(2) if self.checkBox_5.isChecked(): ol.append(3) if len(ol) >= 1: return listd(ol, True) else: return listd(None, True) def set_list(self): self.comboBox.clear() its = self.get_list() if len(its) >= 1: self.comboBox.addItems(its) self.pushButton_2.setEnabled(True) self.checkBox.setEnabled(True) else: self.pushButton_2.setEnabled(False) self.checkBox.setEnabled(False) self.lineEdit.setEnabled(False) self.pushButton_3.setEnabled(False) def setbut_reset(self): t = self.comboBox.currentText() if self.Looping is None: if resetit(t): self.statusbar.setStyleSheet(self.s_norm) self.statusbar.showMessage( "# Done: usb device got reset") return True self.statusbar.setStyleSheet(self.s_error) if name != 'nt': self.statusbar.showMessage( "# Error: maybe you need sudo permissions") else: self.statusbar.showMessage( "# Error: maybe you need to add device to libusb") return False else: tl = self.lineEdit.text() self.statusbar.setStyleSheet(self.s_error) if len(tl) == 0: self.statusbar.showMessage( "# Error: you must enter duration for looping") return False try: self.thr_counter += 1 tl = int(tl) if tl < 2: self.statusbar.showMessage( "# Error: the least allowed value is 2") return False self.P = UR_thread(t, tl, self.thr_counter) self.P.start() self.P.somesignal.connect(self.handleStatusMessage) self.P.setTerminationEnabled(True) self.in_loop(False) except: self.statusbar.showMessage( "# Error: only valid integers allowed") return False def loop_status(self): if self.Looping: self.Looping = None self.lineEdit.setEnabled(False) self.pushButton_3.setEnabled(False) else: self.Looping = True self.lineEdit.setEnabled(True) return True def in_loop(self, stop=True): if stop: if self.P.isRunning(): self.P.stop() self.pushButton_3.setEnabled(False) self.pushButton_2.setEnabled(True) self.checkBox.setEnabled(True) if self.checkBox.isChecked(): self.lineEdit.setEnabled(True) self.checkBox_2.setEnabled(True) self.checkBox_3.setEnabled(True) self.checkBox_4.setEnabled(True) self.checkBox_5.setEnabled(True) self.comboBox.setEnabled(True) else: self.pushButton_3.setEnabled(True) self.pushButton_2.setEnabled(False) self.checkBox.setEnabled(False) self.lineEdit.setEnabled(False) self.checkBox_2.setEnabled(False) self.checkBox_3.setEnabled(False) self.checkBox_4.setEnabled(False) self.checkBox_5.setEnabled(False) self.comboBox.setEnabled(False) return True def rootWarn(self): if platform[:len(platform) - 1] == "linux": from os import getuid if getuid() != 0: self.statusbar.setStyleSheet(self.s_error) self.statusbar.showMessage( "# Error: you must use sudo on Linux") @Slot(object) def handleStatusMessage(self, message): self.statusbar.setStyleSheet(self.s_loop) if message[:7] == '# Error': self.in_loop() self.statusbar.setStyleSheet(self.s_error) self.statusbar.showMessage(message)
class ServiceBrowser(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.serviceManager = QServiceManager(self) self.registerExampleServices() self.initWidgets() self.reloadServicesList() self.setWindowTitle(self.tr("Services Browser")) def __del__(self): self.unregisterExampleServices() def currentInterfaceImplChanged(self, current, previous): if not current: return descriptor = current.data(Qt.UserRole) self.reloadAttributesList() self.reloadAttributesRadioButtonText() if descriptor.isValid(): self.defaultInterfaceButton.setText( self.tr("Set as default implementation for %s" % str(descriptor.interfaceName()))) self.defaultInterfaceButton.setEnabled(True) def reloadServicesList(self): self.servicesListWidget.clear() services = self.serviceManager.findServices() for serv in services: self.servicesListWidget.addItem(serv) self.servicesListWidget.addItem(self.showAllServicesItem) self._services = services def reloadInterfaceImplementationsList(self): serviceName = None allServices = self.servicesListWidget.currentItem().text( ) == self.showAllServicesItem.text() if self.servicesListWidget.currentItem() and not allServices: serviceName = self.servicesListWidget.currentItem().text() self.interfacesGroup.setTitle( self.tr("Interfaces implemented by %s" % str(serviceName))) else: self.interfacesGroup.setTitle( self.tr("All interface implementations")) descriptors = self.serviceManager.findInterfaces(serviceName) self.attributesListWidget.clear() self.interfacesListWidget.clear() self._i = [] for desc in descriptors: text = "%s %d.%d" % (desc.interfaceName(), desc.majorVersion(), desc.minorVersion()) if not serviceName: text += " (" + desc.serviceName() + ")" defaultInterfaceImpl = self.serviceManager.interfaceDefault( desc.interfaceName()) if desc == defaultInterfaceImpl: text += self.tr(" (default)") item = QListWidgetItem(text) item.setData(Qt.UserRole, desc) item._data = desc self.interfacesListWidget.addItem(item) self.defaultInterfaceButton.setEnabled(False) def reloadAttributesList(self): item = self.interfacesListWidget.currentItem() if not item: return selectedImpl = item.data(Qt.UserRole) implementationRef = None if self.selectedImplRadioButton.isChecked(): implementationRef = self.serviceManager.loadInterface(selectedImpl) else: implementationRef = self.serviceManager.loadInterface( selectedImpl.interfaceName()) self.attributesListWidget.clear() if not implementationRef: self.attributesListWidget.addItem( self.tr("(Error loading service plugin)")) return metaObject = implementationRef.metaObject() self.attributesGroup.setTitle( self.tr("Invokable attributes for %s class" % metaObject.className())) for i in range(metaObject.methodCount()): method = metaObject.method(i) self.attributesListWidget.addItem("[METHOD] " + method.signature()) for i in range(metaObject.propertyCount()): p = metaObject.property(i) self.attributesListWidget.addItem("[PROPERTY] " + p.name()) def setDefaultInterfaceImplementation(self): item = self.interfacesListWidget.currentItem() if not item: return descriptor = item.data(Qt.UserRole) if descriptor.isValid(): if self.serviceManager.setInterfaceDefault(descriptor): currentIndex = self.interfacesListWidget.row(item) self.reloadInterfaceImplementationsList() self.interfacesListWidget.setCurrentRow(currentIndex) else: print "Unable to set default service for interface:", descriptor.interfaceName( ) def registerExampleServices(self): exampleXmlFiles = [ "filemanagerservice.xml", "bluetoothtransferservice.xml" ] for fileName in exampleXmlFiles: path = "./xmldata/" + fileName self.serviceManager.addService(path) def unregisterExampleServices(self): self.serviceManager.removeService("FileManagerService") self.serviceManager.removeService("BluetoothTransferService") def reloadAttributesRadioButtonText(self): item = self.interfacesListWidget.currentItem() if not item: return selectedImpl = item.data(Qt.UserRole) defaultImpl = self.serviceManager.interfaceDefault( selectedImpl.interfaceName()) self.defaultImplRadioButton.setText( self.tr( "Default implementation for %s\n(currently provided by %s)" % (str(defaultImpl.interfaceName()), str(defaultImpl.serviceName())))) def initWidgets(self): self.showAllServicesItem = QListWidgetItem( self.tr("(All registered services)")) self.servicesListWidget = QListWidget() self.interfacesListWidget = QListWidget() self.interfacesListWidget.addItem(self.tr("(Select a service)")) self.attributesListWidget = QListWidget() self.attributesListWidget.addItem( self.tr("(Select an interface implementation)")) self.interfacesListWidget.setMinimumWidth(450) self.servicesListWidget.currentItemChanged.connect( self.reloadInterfaceImplementationsList) self.interfacesListWidget.currentItemChanged.connect( self.currentInterfaceImplChanged) self.defaultInterfaceButton = QPushButton( self.tr("Set as default implementation")) self.defaultInterfaceButton.setEnabled(False) self.defaultInterfaceButton.clicked.connect( self.setDefaultInterfaceImplementation) self.selectedImplRadioButton = QRadioButton( self.tr("Selected interface implementation")) self.defaultImplRadioButton = QRadioButton( self.tr("Default implementation")) self.selectedImplRadioButton.setChecked(True) self.radioButtons = QButtonGroup(self) self.radioButtons.addButton(self.selectedImplRadioButton) self.radioButtons.addButton(self.defaultImplRadioButton) self.radioButtons.buttonClicked.connect(self.reloadAttributesList) self.servicesGroup = QGroupBox(self.tr("Show services for:")) servicesLayout = QVBoxLayout() servicesLayout.addWidget(self.servicesListWidget) self.servicesGroup.setLayout(servicesLayout) self.interfacesGroup = QGroupBox(self.tr("Interface implementations")) interfacesLayout = QVBoxLayout() interfacesLayout.addWidget(self.interfacesListWidget) interfacesLayout.addWidget(self.defaultInterfaceButton) self.interfacesGroup.setLayout(interfacesLayout) self.attributesGroup = QGroupBox(self.tr("Invokable attributes")) attributesLayout = QVBoxLayout() self.attributesGroup.setLayout(attributesLayout) attributesLayout.addWidget(self.attributesListWidget) attributesLayout.addWidget(QLabel(self.tr("Show attributes for:"))) attributesLayout.addWidget(self.selectedImplRadioButton) attributesLayout.addWidget(self.defaultImplRadioButton) self.attributesGroup.setLayout(attributesLayout) layout = QGridLayout() layout.addWidget(self.servicesGroup, 0, 0) layout.addWidget(self.attributesGroup, 0, 1, 2, 1) layout.addWidget(self.interfacesGroup, 1, 0) self.setLayout(layout)
class UI(gobject.GObject): __gsignals__ = { 'command' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,)) } def __init__(self,args,continuous): self.continuous = continuous gobject.GObject.__init__(self) #start by making our app self.app = QApplication(args) #make a window self.window = QMainWindow() #give the window a name self.window.setWindowTitle("BlatherQt") self.window.setMaximumSize(400,200) center = QWidget() self.window.setCentralWidget(center) layout = QVBoxLayout() center.setLayout(layout) #make a listen/stop button self.lsbutton = QPushButton("Listen") layout.addWidget(self.lsbutton) #make a continuous button self.ccheckbox = QCheckBox("Continuous Listen") layout.addWidget(self.ccheckbox) #connect the buttons self.lsbutton.clicked.connect(self.lsbutton_clicked) self.ccheckbox.clicked.connect(self.ccheckbox_clicked) #add a label to the UI to display the last command self.label = QLabel() layout.addWidget(self.label) #add the actions for quiting quit_action = QAction(self.window) quit_action.setShortcut('Ctrl+Q') quit_action.triggered.connect(self.accel_quit) self.window.addAction(quit_action) def accel_quit(self): #emit the quit self.emit("command", "quit") #function for managing the continuou listening check box being clicked. When it is clicked it #emits an event for blather to let blather know that the state of things has changed. This is #caught by blather's process_command function. def ccheckbox_clicked(self): checked = self.ccheckbox.isChecked() if checked: #disable lsbutton self.lsbutton.setEnabled(False) self.lsbutton_stopped() self.emit('command', "continuous_listen") self.set_icon_active() else: self.lsbutton.setEnabled(True) self.emit('command', "continuous_stop") self.set_icon_inactive() #functions related to the listen button. lsbutton_stopped is a quasi place holder for if I #want to expand the end of listening to do other things as well. def lsbutton_stopped(self): self.lsbutton.setText("Listen") def lsbutton_clicked(self): val = self.lsbutton.text() if val == "Listen": self.emit("command", "listen") self.lsbutton.setText("Stop") #clear the label self.label.setText("") self.set_icon_active() else: self.lsbutton_stopped() self.emit("command", "stop") self.set_icon_inactive() #called by blather right before the main loop is started. Mainloop is handled by gst. def run(self): self.set_icon_inactive() self.window.show() if self.continuous: self.set_icon_active() self.ccheckbox.setCheckState(Qt.Checked) self.ccheckbox_clicked() self.app.exec_() self.emit("command", "quit") #This function is called when it hears a pause in the audio. #This is called after the command has been sent of to the commander. def finished(self, text): #if the continuous isn't pressed if not self.ccheckbox.isChecked(): self.lsbutton_stopped() self.label.setText(text) #functions dealing with the icon def set_icon(self, icon): self.window.setWindowIcon(QIcon(icon)) def set_icon_active_asset(self, i): self.icon_active = i def set_icon_inactive_asset(self, i): self.icon_inactive = i def set_icon_active(self): self.window.setWindowIcon(QIcon(self.icon_active)) def set_icon_inactive(self): self.window.setWindowIcon(QIcon(self.icon_inactive))
class MainWindow(QMainWindow): '''The main window of the program''' def __init__(self): '''Initialize the main window and it's parents''' super(MainWindow, self).__init__() self._createtWidgets() self._initUI() self._makeMenu() self._makeConnections() self.fileName = None self.pdfName = None self.scriptName = None self.expName = None self.rawName = None self.rawExpName = None # Set initial number of peaks self.exchange.setNumPeaks(2) # Set matrix to symmetric by default self.exchange.setMatrixSymmetry(True) # Set the initial window. self.scale.setValue(1900, 2100, False) # Default to rate in units of THz self.rate.setUnit('THz') # Clear button starts off inactive self.clear.setEnabled(False) def _createtWidgets(self): '''Creates all the widgets''' # Make the views self.plot = Plot(self) self.rate = RateView(parent=self) self.exchange = ExchangeView(parent=self) self.peak = PeakView(parent=self) self.scale = ScaleView(parent=self) # Create the model controller self.control = Controller(self) # Attach models to the views self.rate.setModel(self.control.rate) self.exchange.setModel(self.control.exchange, self.control.numpeaks) self.peak.setModel(self.control.peak) self.scale.setModel(self.control.scale) # Init the UI of all the views self.rate.initUI() self.exchange.initUI() self.peak.initUI() self.scale.initUI() # Last, make inter-view connections self.rate.makeConnections() self.exchange.makeConnections() self.peak.makeConnections() self.scale.makeConnections() self.plot.makeConnections() # The window will own a button to clear raw data self.clear = QPushButton('Clear Raw Data', self) self.clear.setToolTip(ttt('Remove raw data from the plot ' 'if there is any')) def _initUI(self): '''Sets up the layout of the window''' # Define a central widget and a layout for the window self.setCentralWidget(QWidget()) self.mainLayout = QHBoxLayout() self.setWindowTitle('Spectral Exchange') # Make a layout for all the parameter views params = QVBoxLayout() params.addWidget(self.rate) params.addWidget(self.exchange) params.addWidget(self.peak) # Add the parameter dialog self.mainLayout.addLayout(params) # Add the plot plot_lim = QVBoxLayout() plot_lim.addWidget(self.plot) lim_clear = QHBoxLayout() lim_clear.addWidget(self.scale) lim_clear.addWidget(self.clear) plot_lim.addLayout(lim_clear) self.mainLayout.addLayout(plot_lim) # Add the widgets to the central widget self.centralWidget().setLayout(self.mainLayout) def _makeConnections(self): '''Connect the widgets to each other''' # When the controller says plot, plot self.control.plotSpectrum.connect(self.plot.plotCalculatedData) # When the controller says resize x limits, do so self.control.newXLimits.connect(self.plot.changeScale) # Clear raw data if pushed self.clear.clicked.connect(self.clearRawData) # If the plot is clicked, send info to the scale widget self.plot.pointPicked.connect(self.scale.setSelection) def _makeMenu(self): '''Makes the menu bar for this widget''' # Get the menu bar object self.menu = self.menuBar() self.fileMenu = self.menu.addMenu('&File') # Open action open = QAction('&Open', self) open.setShortcuts(QKeySequence.Open) open.triggered.connect(self.openFromInput) open.setToolTip('Open an already made input file') self.fileMenu.addAction(open) # Save action save = QAction('&Save', self) save.setShortcuts(QKeySequence.Save) save.triggered.connect(self.saveToInput) save.setToolTip('Save settings to an input file') self.fileMenu.addAction(save) # Save action saveas = QAction('Save As', self) saveas.triggered.connect(self.saveToInputAs) save.setToolTip('Save settings to an input file of a new name') self.fileMenu.addAction(saveas) # Save action savepdf = QAction('Save as PDF', self) savepdf.triggered.connect(self.saveAsPDF) save.setToolTip('Save image to a PDF') self.fileMenu.addAction(savepdf) # Menu separator self.fileMenu.addSeparator() # Import action imp = QAction('&Import raw XY data', self) imp.setShortcut(QKeySequence('Ctrl+I')) imp.triggered.connect(self.importRawData) imp.setToolTip('Import raw data an plot alongside calculated data') self.fileMenu.addAction(imp) # Export action raw = QAction('Export raw XY data', self) raw.triggered.connect(self.exportRawData) raw.setToolTip('Export raw data to a file for use elsewhere') self.fileMenu.addAction(raw) # Export action exp = QAction('&Export calculated XY data', self) exp.setShortcut(QKeySequence('Ctrl+E')) exp.triggered.connect(self.exportXYData) exp.setToolTip('Export calculated data to a file for use elsewhere') self.fileMenu.addAction(exp) # Make script action scr = QAction('Make Sc&ript', self) scr.setShortcut(QKeySequence('Ctrl+R')) scr.triggered.connect(self.makeScript) scr.setToolTip('Create a python script that directly recreates this ' 'spectrum') self.fileMenu.addAction(scr) # Menu separator self.fileMenu.addSeparator() # Quit action quit = QAction('&Quit', self) quit.setShortcuts(QKeySequence.Quit) quit.triggered.connect(QApplication.instance().quit) self.fileMenu.addAction(quit) ####### # SLOTS ####### def clearRawData(self): '''Clear the raw data from the plot''' self.plot.clearRawData() self.clear.setEnabled(False) def openFromInput(self): '''Open parameters from an input file''' filter = 'Input Files (*.inp);;All (*)' s = QFileDialog.getOpenFileName(self, 'Input File Name', '', filter) # Continue unless the user hit cancel if not s[0]: return fileName = s[0] # Read given input file try: args = read_input(fileName) except ReaderError as r: # Error reading the input file error.showMessage(str(r)) # Set the number of peaks npeaks = len(args.num) if npeaks < 2: error.showMessage('Need at least 2 peaks for exchange') return elif npeaks > 4: error.showMessage('This GUI can only handle up to 4 peaks. ' 'Use the command-line version for an arbitrary ' 'number of peaks') return self.exchange.setNumPeaks(npeaks) # Set the exchange matrix = ZMat(npeaks, args.exchanges, args.exchange_rates, args.symmetric_exchange) self.exchange.setMatrixSymmetry(args.symmetric_exchange) self.exchange.setMatrix(matrix) # Set the rate if 'lifetime' in args: self.rate.setUnit(args.lifetime[1]) self.rate.setRate(args.lifetime[0]) else: self.rate.setUnit(args.rate[1]) self.rate.setRate(args.rate[0]) # Set the peak data self.peak.setPeaks(args.vib, args.Gamma_Lorentz, args.Gamma_Gauss, args.heights) # Plot this data self.control.setDataForPlot() # Plot raw data if it exists if args.raw is not None: self.rawName = args.rawName self.plot.setRawData(args.raw) self.plot.plotRawData() self.clear.setEnabled(True) # Set the limits self.scale.setValue(args.xlim[0], args.xlim[1], args.reverse) def saveToInput(self): '''Save current settings to current input file if available''' if not self.control.hasPlot: error.showMessage('Cannot save.. there is no data to save yet') return if self.fileName is None: self.saveToInputAs() else: self.inputGen(self.fileName) def saveToInputAs(self): '''Save current settings to an input file of specified name''' if not self.control.hasPlot: error.showMessage('Cannot save.. there is no data to save yet') return filter = 'Input Files (*.inp);;All (*)' d = '' if self.fileName is None else self.fileName s = QFileDialog.getSaveFileName(self, 'Input File Name', d, filter) # Continue unless the user hit cancel if not s[0]: return self.fileName = s[0] # Generate the input file self.inputGen(self.fileName) def saveAsPDF(self): '''Save plot as a PDF''' if not self.control.hasPlot: error.showMessage('Cannot save.. there is no data to save yet') return filter = 'PDF Documents (*.pdf);;All (*)' d = '' if self.pdfName is None else self.pdfName s = QFileDialog.getSaveFileName(self, 'PDF File Name', d, filter) # Continue unless the user hit cancel if not s[0]: return self.pdfName = s[0] # Set up the PDF printer printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setOrientation(QPrinter.Landscape) printer.setOutputFileName(self.pdfName) printer.setCreator('RAPID') # Send to the plot for printing p = QPainter() p.begin(printer) x, y = self.plot.calculatedData() plt = pgplot(x, y, antialias=True, connect='all', pen={'color': 'b', 'width': 0}) plt.setLabel('bottom', "Frequency (Wavenumbers, cm<sup>-1</sup>)") plt.getAxis('bottom').setPen('k') plt.setLabel('left', "Intensity (Normalized)") plt.getAxis('left').setPen('k') plt.setYRange(0, 1.1, padding=0) plt.invertX(self.plot.reversed) plt.setBackground('w') # White # The raw (experimental) data, if any if self.plot.rawData is not None: data = self.plot.getRawData() x, y = data[:,0], data[:,1] curve2 = PlotCurveItem(x, y, antialias=True, connect='all', pen={'color': 'g', 'width': 0}) plt.addItem(curve2) plt.render(p) p.end() def exportXYData(self): '''Export current spectrum to XY data''' if not self.control.hasPlot: error.showMessage('Cannot export.. there is no data to export yet') return filter = 'Data Files (*.txt *.data);;All (*)' d = '' if self.expName is None else self.expName s = QFileDialog.getSaveFileName(self, 'Calculated XY Data File Name', d, filter) # Continue unless the user hit cancel if not s[0]: return self.expName = s[0] # Grab the XY data from the plot x, y = self.plot.calculatedData() # Save in a standard format try: write_data(x, y, self.expName) except (IOError, OSError) as e: error.showMessage(str(e)) def exportRawData(self): '''Export current raw data to XY data''' if self.plot.rawData is None: error.showMessage('Cannot export.. there is no raw data to export yet') return filter = 'Data Files (*.txt *.data);;All (*)' d = '' if self.rawExpName is None else self.rawExpName s = QFileDialog.getSaveFileName(self, 'Raw XY Data File Name', d, filter) # Continue unless the user hit cancel if not s[0]: return self.rawExpName = s[0] # Grab the raw XY data from the plot data = self.plot.getRawData() # Save in a standard format try: write_data(data[:,0], data[:,1], self.rawExpName) except (IOError, OSError) as e: error.showMessage(str(e)) def importRawData(self): '''Import data from an XY file''' filter = 'Data Files (*.txt *.data);;All (*)' d = '' if self.rawName is None else self.rawName s = QFileDialog.getOpenFileName(self, 'Raw XY Data File Name', d, filter) # Continue unless the user hit cancel if not s[0]: return self.rawName = s[0] # Load raw data and plot in a second curve rawData = loadtxt(str(self.rawName)) self.plot.setRawData(rawData) self.plot.plotRawData() self.clear.setEnabled(True) def makeScript(self): '''Open parameters from an input file''' if not self.control.hasPlot: error.showMessage('Cannot save.. there is no data to save yet') return filter = 'Python Scripts (*.py)' d = '' if self.scriptName is None else self.scriptName s = QFileDialog.getSaveFileName(self, 'Python Script File Name', d, filter) # Continue unless the user hit cancel if not s[0]: return self.scriptName = s[0] # Get parameters needed xlim, rev, oldp, newp = self.control.getParametersForScript() x, y = self.plot.calculatedData() if self.clear.isEnabled(): raw = self.plot.rawData else: raw = None save_script(x, y, raw, xlim, rev, oldp, newp, self.scriptName) def inputGen(self, fileName): '''Generate an input file''' # Open file for writing try: fl = open(fileName, 'w') except (IOError, OSError) as e: error.showError(str(e)) # Generate a template string to print s = dedent('''\ # The rate or lifetime of the reaction {rate} # The exchange matrix {exchange} # The peak data {peaks} # The plot limits {limits} # Raw input file, if any {raw} ''') # Get the parameters from the underlying data xlim, rev, rate, exchange, peaks = self.control.getParametersForInput() # Create the rate string if rate[1] in ('s', 'ns', 'ps', 'fs'): lr = 'lifetime' else: lr = 'rate' ratestr = '{0} {1[0]:.3G} {1[1]}'.format(lr, rate) # Create exchange string exstr = [] if not exchange[2]: exstr.append('nosym') f = 'exchange {0:d} {1:d} {2:.3f}' for indx, r in zip(exchange[1], exchange[0]): exstr.append(f.format(indx[0]+1, indx[1]+1, r)) exstr = '\n'.join(exstr) # Create peak string peakstr = [] f = 'peak {0:.2f} {1:.3f} L={2:.3f} G={3:.3f}' for p, l, g, h in zip(peaks[0], peaks[1], peaks[2], peaks[3]): peakstr.append(f.format(p, h, l, g)) peakstr = '\n'.join(peakstr) # Create the limits string limitstr = 'xlim {0[0]:d} {0[1]:d}'.format(xlim) if rev: limitstr += '\nreverse' # Create the IO string if self.rawName is not None: rawstr = 'raw {0}'.format(self.rawName) else: rawstr = '' # Write the string to file fl.write(s.format(rate=ratestr, peaks=peakstr, limits=limitstr, exchange=exstr, raw=rawstr)) # Close file fl.close()
class Form(QDialog): def __init__(self, state, term, candidates, result, parent=None): super().__init__(parent) Lib.prepareModalDialog(self) self.state = state self.term = term self.candidates = [] for candidate in candidates: self.candidates.append(humanizedCandidate( term, candidate.candidate, candidate.saf)) self.result = result self.setWindowTitle("Sort As — {}".format( QApplication.applicationName())) self.createWidgets() self.layoutWidgets() self.createConnections() self.updateUi() settings = QSettings() self.updateToolTips(bool(int(settings.value( Gopt.Key.ShowDialogToolTips, Gopt.Default.ShowDialogToolTips)))) def createWidgets(self): self.termLabel = Widgets.Label.HtmlLabel( "<p>Sort “{}” with</p>".format(Lib.elidePatchHtml(self.term, self.state))) self.radioButtons = [] seen = set() for index, candidate in enumerate(self.candidates, 1): candidate_word = str(candidate.candidate_word) name = self.nameForKind(candidate.kind, candidate_word) extra = "" if candidate_word in seen: extra = " (treat roman numbers as literal text)" else: seen.add(candidate_word) radioButton = QRadioButton("&{} “{}” as{} “{}”{}".format( index, candidate.term_word, name, candidate_word, extra)) self.radioButtons.append(radioButton) self.radioButtons[0].setChecked(True) self.customRadioButton = QRadioButton("&Custom:") self.tooltips.append((self.customRadioButton, """\ <p><b>Custom</b></p> <p>If checked, this entry's <b>Automatically Calculate Sort As</b> setting will be <i>unchecked</i>, and the sort as text entered here will be used as ther entry's sort as text.</p>""")) self.sortAsEdit = Widgets.LineEdit.LineEdit(self.state) self.tooltips.append((self.sortAsEdit, """\ <p><b>Custom Sort As editor</b></p> <p>If <b>Custom</b> is checked, this entry's <b>Automatically Calculate Sort As</b> setting will be <i>unchecked</i>, and the sort as text entered here will be used as ther entry's sort as text.</p>""")) self.sortAsEdit.setText(self.candidates[0].candidate) self.sortAsEdit.selectAll() self.buttonBox = QDialogButtonBox() self.okButton = QPushButton(QIcon(":/ok.svg"), "&OK") self.tooltips.append((self.okButton, """\ <p><b>OK</b></p> <p>Use the specified or custom sort as text for entry “{}”.</p>""".format(Lib.elidePatchHtml(self.term, self.state)))) self.buttonBox.addButton( self.okButton, QDialogButtonBox.AcceptRole) self.helpButton = QPushButton(QIcon(":/help.svg"), "Help") self.tooltips.append((self.helpButton, "Help on the Sort As dialog")) self.buttonBox.addButton( self.helpButton, QDialogButtonBox.HelpRole) def nameForKind(self, kind, candidate_word): name = kind.name.lower() if name == "unchanged": name = "" elif (name == "roman" or ( name == "phrase" and re.fullmatch(r"[\d.]+", candidate_word) is not None)): name = "number" if name: name = " " + name return name def layoutWidgets(self): vbox = QVBoxLayout() vbox.addWidget(self.termLabel) for radioButton in self.radioButtons: vbox.addWidget(radioButton) hbox = QHBoxLayout() hbox.addWidget(self.customRadioButton) hbox.addWidget(self.sortAsEdit) vbox.addLayout(hbox) vbox.addWidget(self.buttonBox) self.setLayout(vbox) def createConnections(self): for radioButton in itertools.chain((self.customRadioButton,), self.radioButtons): radioButton.toggled.connect(self.updateUi) self.sortAsEdit.textChanged.connect(self.updateUi) self.okButton.clicked.connect(self.accept) self.helpButton.clicked.connect(self.help) def help(self): self.state.help("xix_ref_dlg_sortas.html") def updateUi(self): self.sortAsEdit.setEnabled(self.customRadioButton.isChecked()) with Lib.BlockSignals(self.sortAsEdit): for i, radioButton in enumerate(self.radioButtons): if radioButton.isChecked(): self.sortAsEdit.setText(self.candidates[i].candidate) self.sortAsEdit.selectAll() break self.okButton.setEnabled( not self.customRadioButton.isChecked() or (self.customRadioButton.isChecked() and bool(self.sortAsEdit.toPlainText()))) def reject(self): self.accept() def accept(self): if self.customRadioButton.isChecked(): self.result.sortas = self.sortAsEdit.toPlainText() self.result.saf = Saf.CUSTOM else: for index, radioButton in enumerate(self.radioButtons): if radioButton.isChecked(): self.result.sortas = self.candidates[index].candidate kind = self.candidates[index].kind if kind is CandidateKind.LITERAL: saf = Saf.AUTO_BASIC elif kind is CandidateKind.NUMBER: saf = Saf.AUTO_NUMBER elif kind is CandidateKind.ROMAN: saf = Saf.AUTO_NUMBER_ROMAN elif kind is CandidateKind.PHRASE: saf = Saf.AUTO elif kind is CandidateKind.UNCHANGED: saf = self.candidates[index].saf self.result.saf = saf break super().accept()
class Ui_MainWindow(object): def setupUi(self, MainWindow): lbMinWidth = 65 # leMinWidth = 200 MainWindow.setObjectName("MainWindow") MainWindow.resize(400, 310) # self.centralwidget = QWidget(MainWindow) self.mainSplitter = QSplitter(Qt.Horizontal, MainWindow) self.mainSplitter.setObjectName("centralwidget") self.mainSplitter.setProperty("childrenCollapsible", False) MainWindow.setCentralWidget(self.mainSplitter) self.leftSplitter = QSplitter(Qt.Vertical, self.mainSplitter) self.leftSplitter.setProperty("childrenCollapsible", False) ##### login_gbox self.login_gbox = QGroupBox(self.leftSplitter) self.login_gbox.setFlat(True) self.login_gbox.setObjectName("login_gbox") login_gbox_layout = QVBoxLayout(self.login_gbox) login_gbox_csf_layout = QHBoxLayout() login_gbox_account_layout = QHBoxLayout() login_gbox_connect_layout = QHBoxLayout() login_gbox_layout.addLayout(login_gbox_csf_layout) login_gbox_layout.addLayout(login_gbox_account_layout) login_gbox_layout.addLayout(login_gbox_connect_layout) self.lb_client_secrets_file_path = QLabel(self.login_gbox) self.lb_client_secrets_file_path.setObjectName("lb_client_secrets_file_path") self.lb_client_secrets_file_path.setMinimumWidth(lbMinWidth) self.client_secrets_file_path_le = QLineEdit(self.login_gbox) self.client_secrets_file_path_le.setObjectName("client_secrets_file_path_le") self.client_secret_file_path_tBtn = QToolButton(self.login_gbox) self.client_secret_file_path_tBtn.setObjectName("client_secret_file_path_tBtn") login_gbox_csf_layout.addWidget(self.lb_client_secrets_file_path) login_gbox_csf_layout.addWidget(self.client_secrets_file_path_le) login_gbox_csf_layout.addWidget(self.client_secret_file_path_tBtn) self.lb_account = QLabel(self.login_gbox) self.lb_account.setMaximumWidth(lbMinWidth) self.lb_account.setObjectName("lb_account") self.remove_account_btn = QToolButton(self.login_gbox) self.remove_account_btn.setObjectName("remove_account_btn") self.remove_account_btn.setMinimumWidth(20) self.remove_account_btn.setEnabled(False) self.add_account_btn = QToolButton(self.login_gbox) self.add_account_btn.setObjectName("add_account_btn") self.add_account_btn.setMinimumWidth(20) self.accounts_cb = QComboBox(self.login_gbox) self.accounts_cb.setObjectName("accounts_cb") login_gbox_account_layout.addWidget(self.lb_account) login_gbox_account_layout.addWidget(self.remove_account_btn) login_gbox_account_layout.addWidget(self.add_account_btn) login_gbox_account_layout.addWidget(self.accounts_cb) self.lb_decryption_key = QLabel(self.login_gbox) self.lb_decryption_key.setObjectName("lb_decryption_key") self.lb_decryption_key.setMinimumWidth(lbMinWidth) self.lb_decryption_key.hide() self.decryption_key_le = QLineEdit(self.login_gbox) self.decryption_key_le.setEchoMode(QLineEdit.Password) self.decryption_key_le.setObjectName("decryption_key_le") self.decryption_key_le.hide() self.connect_btn = QPushButton(self.login_gbox) self.connect_btn.setEnabled(False) self.connect_btn.setObjectName("connect_btn") login_gbox_connect_layout.addWidget(self.lb_decryption_key) login_gbox_connect_layout.addWidget(self.decryption_key_le) login_gbox_connect_layout.addWidget(self.connect_btn) #### search_gbox self.search_gbox = QGroupBox(self.leftSplitter) self.search_gbox.setFlat(True) self.search_gbox.setObjectName("search_gbox") self.search_gbox.hide() search_gbox_layout = QVBoxLayout(self.search_gbox) search_gbox_mailbox_layout = QVBoxLayout() search_gbox_date_layout = QHBoxLayout() search_gbox_from_layout = QHBoxLayout() search_gbox_to_layout = QHBoxLayout() search_gbox_subject_layout = QHBoxLayout() search_gbox_threads_layout = QHBoxLayout() search_gbox_paramaters_layout = QHBoxLayout() search_gbox_layout.addLayout(search_gbox_mailbox_layout) search_gbox_layout.addLayout(search_gbox_date_layout) search_gbox_layout.addLayout(search_gbox_from_layout) search_gbox_layout.addLayout(search_gbox_to_layout) search_gbox_layout.addLayout(search_gbox_subject_layout) search_gbox_layout.addLayout(search_gbox_threads_layout) search_gbox_layout.addLayout(search_gbox_paramaters_layout) self.lb_select_mailbox = QLabel(self.search_gbox) self.lb_select_mailbox.setObjectName("lb_select_mailbox") self.mailboxes_lw = QListWidget(self.search_gbox) self.mailboxes_lw.setEditTriggers(QAbstractItemView.NoEditTriggers) self.mailboxes_lw.setSelectionMode(QAbstractItemView.ExtendedSelection) self.mailboxes_lw.setObjectName("mailboxes_lw") search_gbox_mailbox_layout.addWidget(self.lb_select_mailbox) search_gbox_mailbox_layout.addWidget(self.mailboxes_lw) self.after_date_cb = QCheckBox(self.search_gbox) self.after_date_cb.setObjectName("after_date_cb") self.after_date_cb.setMinimumWidth(lbMinWidth) self.after_date_cb.setMaximumWidth(lbMinWidth) self.after_date_edit = QDateEdit(self.search_gbox) self.after_date_edit.setCalendarPopup(True) self.after_date_edit.setObjectName("after_date_edit") self.after_date_edit.setDate(QDate.currentDate().addDays(-365)) self.after_date_edit.setMaximumDate(QDate.currentDate()) self.after_date_edit.setEnabled(False) self.before_date_cb = QCheckBox(self.search_gbox) self.before_date_cb.setObjectName("before_date_cb") self.before_date_cb.setMinimumWidth(70) self.before_date_cb.setMaximumWidth(70) self.before_date_edit = QDateEdit(self.search_gbox) self.before_date_edit.setCalendarPopup(True) self.before_date_edit.setObjectName("before_date_edit") self.before_date_edit.setDate(QDate.currentDate()) self.before_date_edit.setMaximumDate(QDate.currentDate()) self.before_date_edit.setEnabled(False) search_gbox_date_layout.addWidget(self.after_date_cb) search_gbox_date_layout.addWidget(self.after_date_edit) search_gbox_date_layout.addWidget(self.before_date_cb) search_gbox_date_layout.addWidget(self.before_date_edit) self.lb_from = QLabel(self.search_gbox) self.lb_from.setObjectName("lb_from") self.lb_from.setMinimumWidth(lbMinWidth) self.from_le = QLineEdit(self.search_gbox) self.from_le.setObjectName("from_le") search_gbox_from_layout.addWidget(self.lb_from) search_gbox_from_layout.addWidget(self.from_le) self.lb_to = QLabel(self.search_gbox) self.lb_to.setObjectName("lb_to") self.lb_to.setMinimumWidth(lbMinWidth) self.to_le = QLineEdit(self.search_gbox) self.to_le.setObjectName("to_le") search_gbox_to_layout.addWidget(self.lb_to) search_gbox_to_layout.addWidget(self.to_le) self.lb_subject = QLabel(self.search_gbox) self.lb_subject.setObjectName("lb_subject") self.lb_subject.setMinimumWidth(lbMinWidth) self.subject_le = QLineEdit(self.search_gbox) self.subject_le.setObjectName("subject_le") search_gbox_subject_layout.addWidget(self.lb_subject) search_gbox_subject_layout.addWidget(self.subject_le) self.lb_threads = QLabel(self.search_gbox) self.lb_threads.setObjectName("lb_threads") self.lb_threads.setMaximumWidth(lbMinWidth) self.thread_count_sb = QSpinBox(self.search_gbox) self.thread_count_sb.setMinimum(1) self.thread_count_sb.setMaximum(10) self.thread_count_sb.setObjectName("thread_count_sb") self.html_radio = QRadioButton(self.search_gbox) self.html_radio.setObjectName("html_radio") self.text_radio = QRadioButton(self.search_gbox) self.text_radio.setObjectName("text_radio") self.extactTypeButtonGroup = QButtonGroup(self) self.extactTypeButtonGroup.addButton(self.html_radio) self.extactTypeButtonGroup.addButton(self.text_radio) self.html_radio.setChecked(True) self.search_btn = QPushButton(self.search_gbox) self.search_btn.setObjectName("search_btn") search_gbox_threads_layout.addWidget(self.lb_threads) search_gbox_threads_layout.addWidget(self.thread_count_sb) search_gbox_threads_layout.addWidget(self.html_radio) search_gbox_threads_layout.addWidget(self.text_radio) search_gbox_threads_layout.addWidget(self.search_btn) self.parameters_cb = QCheckBox(self.search_gbox) self.parameters_cb.setText("") self.parameters_cb.setObjectName("parameters_cb") self.parameters_le = QLineEdit(self.search_gbox) self.parameters_le.setEnabled(False) self.parameters_le.setObjectName("parameters_le") search_gbox_paramaters_layout.addWidget(self.parameters_cb) search_gbox_paramaters_layout.addWidget(self.parameters_le) #### log_gbox self.log_gbox = QGroupBox(self.leftSplitter) self.log_gbox.setFlat(True) self.log_gbox.setObjectName("log_gbox") log_layout = QVBoxLayout(self.log_gbox) self.log_te = QTextEdit(self.log_gbox) self.log_te.setLineWrapMode(QTextEdit.NoWrap) self.log_te.setReadOnly(True) self.log_te.setTextInteractionFlags(Qt.TextSelectableByKeyboard | Qt.TextSelectableByMouse) self.log_te.setObjectName("log_te") self.disconnect_btn = QPushButton(self.log_gbox) self.disconnect_btn.setObjectName("disconnect_btn") self.disconnect_btn.hide() log_layout.addWidget(self.log_te) log_layout_btn = QHBoxLayout() log_layout.addLayout(log_layout_btn) log_layout_btn.addWidget(self.disconnect_btn) log_layout_btn.addStretch() #### links_gbox self.links_gbox = QGroupBox(self.mainSplitter) self.links_gbox.setFlat(True) self.links_gbox.setObjectName("links_gbox") self.links_gbox.hide() links_gbox_layout = QVBoxLayout(self.links_gbox) links_gbox_links_layout = QVBoxLayout() links_gbox_buttons_layout = QHBoxLayout() links_gbox_layout.addLayout(links_gbox_links_layout) links_gbox_layout.addLayout(links_gbox_buttons_layout) self.links_text_edit = QTextEdit(self.links_gbox) self.links_text_edit.setObjectName("links_text_edit") links_gbox_links_layout.addWidget(self.links_text_edit) self.export_txt_btn = QPushButton(self.links_gbox) self.export_txt_btn.setObjectName("export_txt_btn") self.export_txt_btn.setEnabled(False) self.export_html_btn = QPushButton(self.links_gbox) self.export_html_btn.setObjectName("export_html_btn") self.export_html_btn.setEnabled(False) links_gbox_buttons_layout.addWidget(self.export_txt_btn) links_gbox_buttons_layout.addWidget(self.export_html_btn) ### menubar self.menubar = QMenuBar(MainWindow) # self.menubar.setGeometry(QRect(0, 0, 860, 21)) self.menubar.setObjectName("menubar") self.menu_file = QMenu(self.menubar) self.menu_file.setObjectName("menu_file") self.menu_help = QMenu(self.menubar) self.menu_help.setObjectName("menu_help") MainWindow.setMenuBar(self.menubar) self.action_about = QAction(MainWindow) self.action_about.setObjectName("action_about") self.action_About_Qt = QAction(MainWindow) self.action_About_Qt.setObjectName("action_About_Qt") self.action_exit = QAction(MainWindow) self.action_exit.setObjectName("action_exit") self.actionSave = QAction(MainWindow) self.actionSave.setObjectName("actionSave") self.action_Gmail_Advanced_Search_Syntax = QAction(MainWindow) self.action_Gmail_Advanced_Search_Syntax.setObjectName("action_Gmail_Advanced_Search_Syntax") self.menu_file.addAction(self.action_exit) self.menu_help.addAction(self.action_Gmail_Advanced_Search_Syntax) self.menu_help.addSeparator() self.menu_help.addAction(self.action_about) self.menu_help.addAction(self.action_About_Qt) self.menubar.addAction(self.menu_file.menuAction()) self.menubar.addAction(self.menu_help.menuAction()) self.retranslateUi(MainWindow) QMetaObject.connectSlotsByName(MainWindow) MainWindow.setTabOrder(self.client_secrets_file_path_le, self.client_secret_file_path_tBtn) MainWindow.setTabOrder(self.client_secret_file_path_tBtn, self.remove_account_btn) MainWindow.setTabOrder(self.remove_account_btn, self.add_account_btn) MainWindow.setTabOrder(self.add_account_btn, self.accounts_cb) MainWindow.setTabOrder(self.decryption_key_le, self.connect_btn) MainWindow.setTabOrder(self.connect_btn, self.log_te) MainWindow.setTabOrder(self.log_te, self.mailboxes_lw) MainWindow.setTabOrder(self.mailboxes_lw, self.after_date_cb) MainWindow.setTabOrder(self.after_date_cb, self.after_date_edit) MainWindow.setTabOrder(self.after_date_edit, self.before_date_cb) MainWindow.setTabOrder(self.before_date_cb, self.before_date_edit) MainWindow.setTabOrder(self.before_date_edit, self.from_le) MainWindow.setTabOrder(self.from_le, self.to_le) MainWindow.setTabOrder(self.to_le, self.subject_le) MainWindow.setTabOrder(self.subject_le, self.thread_count_sb) MainWindow.setTabOrder(self.thread_count_sb, self.html_radio) MainWindow.setTabOrder(self.html_radio, self.text_radio) MainWindow.setTabOrder(self.text_radio, self.search_btn) MainWindow.setTabOrder(self.search_btn, self.parameters_cb) MainWindow.setTabOrder(self.parameters_cb, self.parameters_le) MainWindow.setTabOrder(self.parameters_le, self.disconnect_btn) MainWindow.setTabOrder(self.disconnect_btn, self.links_text_edit) MainWindow.setTabOrder(self.links_text_edit, self.export_txt_btn) MainWindow.setTabOrder(self.export_txt_btn, self.export_html_btn) MainWindow.setTabOrder(self.export_html_btn, self.mailboxes_lw) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QApplication.translate("MainWindow", "Gmail URL Parser", None, QApplication.UnicodeUTF8)) self.login_gbox.setTitle(QApplication.translate("MainWindow", " Client secrets file path ", None, QApplication.UnicodeUTF8)) self.client_secrets_file_path_le.setPlaceholderText(QApplication.translate("MainWindow", "Please select your client secrets file", None, QApplication.UnicodeUTF8)) self.lb_client_secrets_file_path.setText(QApplication.translate("MainWindow", "Path", None, QApplication.UnicodeUTF8)) self.connect_btn.setText(QApplication.translate("MainWindow", "Connect", None, QApplication.UnicodeUTF8)) self.client_secret_file_path_tBtn.setText(QApplication.translate("MainWindow", "...", None, QApplication.UnicodeUTF8)) self.lb_account.setText(QApplication.translate("MainWindow", "Account", None, QApplication.UnicodeUTF8)) self.add_account_btn.setText(QApplication.translate("MainWindow", "+", None, QApplication.UnicodeUTF8)) self.remove_account_btn.setText(QApplication.translate("MainWindow", "-", None, QApplication.UnicodeUTF8)) self.decryption_key_le.setPlaceholderText(QApplication.translate("MainWindow", "Decryption key", None, QApplication.UnicodeUTF8)) self.lb_decryption_key.setText(QApplication.translate("MainWindow", "Key", None, QApplication.UnicodeUTF8)) self.log_gbox.setTitle(QApplication.translate("MainWindow", " Log ", None, QApplication.UnicodeUTF8)) self.search_gbox.setTitle(QApplication.translate("MainWindow", " Search Parameters ", None, QApplication.UnicodeUTF8)) self.lb_to.setText(QApplication.translate("MainWindow", "To", None, QApplication.UnicodeUTF8)) self.lb_from.setText(QApplication.translate("MainWindow", "From", None, QApplication.UnicodeUTF8)) self.lb_subject.setText(QApplication.translate("MainWindow", "Subject", None, QApplication.UnicodeUTF8)) self.search_btn.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8)) self.after_date_edit.setDisplayFormat(QApplication.translate("MainWindow", "yyyy-MM-dd", None, QApplication.UnicodeUTF8)) self.before_date_edit.setDisplayFormat(QApplication.translate("MainWindow", "yyyy-MM-dd", None, QApplication.UnicodeUTF8)) self.lb_select_mailbox.setToolTip(QApplication.translate("MainWindow", "<html><head/><body><p>Select multiple items to select labels</p></body></html>", None, QApplication.UnicodeUTF8)) self.lb_select_mailbox.setText(QApplication.translate("MainWindow", "Select Mailbox or Labels", None, QApplication.UnicodeUTF8)) self.after_date_cb.setText(QApplication.translate("MainWindow", "After", None, QApplication.UnicodeUTF8)) self.before_date_cb.setText(QApplication.translate("MainWindow", "Before", None, QApplication.UnicodeUTF8)) self.html_radio.setText(QApplication.translate("MainWindow", "html", None, QApplication.UnicodeUTF8)) self.text_radio.setText(QApplication.translate("MainWindow", "text", None, QApplication.UnicodeUTF8)) self.lb_threads.setText(QApplication.translate("MainWindow", "Threads", None, QApplication.UnicodeUTF8)) self.links_gbox.setTitle(QApplication.translate("MainWindow", " Links ", None, QApplication.UnicodeUTF8)) self.disconnect_btn.setText(QApplication.translate("MainWindow", "Disconnect", None, QApplication.UnicodeUTF8)) self.export_txt_btn.setText(QApplication.translate("MainWindow", "Export as txt", None, QApplication.UnicodeUTF8)) self.export_html_btn.setText(QApplication.translate("MainWindow", "Export as HTML", None, QApplication.UnicodeUTF8)) self.menu_file.setTitle(QApplication.translate("MainWindow", "File", None, QApplication.UnicodeUTF8)) self.menu_help.setTitle(QApplication.translate("MainWindow", "Help", None, QApplication.UnicodeUTF8)) self.action_about.setText(QApplication.translate("MainWindow", "About", None, QApplication.UnicodeUTF8)) self.action_About_Qt.setText(QApplication.translate("MainWindow", "About Qt", None, QApplication.UnicodeUTF8)) self.action_exit.setText(QApplication.translate("MainWindow", "Exit", None, QApplication.UnicodeUTF8)) self.action_exit.setShortcut(QApplication.translate("MainWindow", "Ctrl+Q", None, QApplication.UnicodeUTF8)) self.actionSave.setText(QApplication.translate("MainWindow", "Save", None, QApplication.UnicodeUTF8)) self.action_Gmail_Advanced_Search_Syntax.setText(QApplication.translate("MainWindow", "Gmail Advanced Search Syntax", None, QApplication.UnicodeUTF8))
class RunnerDialog(QDialog): options_added = Signal(Options) options_running = Signal(Options) options_simulated = Signal(Options) options_error = Signal(Options, Exception) results_saved = Signal(Results, str) results_error = Signal(Results, Exception) def __init__(self, parent=None): QDialog.__init__(self, parent) self.setWindowTitle('Runner') self.setMinimumWidth(750) # Runner self._runner = None self._running_timer = QTimer() self._running_timer.setInterval(500) # Widgets self._dlg_progress = QProgressDialog() self._dlg_progress.setRange(0, 100) self._dlg_progress.setModal(True) self._dlg_progress.hide() lbl_outputdir = QLabel("Output directory") self._txt_outputdir = DirBrowseWidget() max_workers = cpu_count() #@UndefinedVariable lbl_workers = QLabel('Number of workers') self._spn_workers = QSpinBox() self._spn_workers.setRange(1, max_workers) self._spn_workers.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) lbl_max_workers = QLabel('(max: %i)' % max_workers) self._chk_overwrite = QCheckBox("Overwrite existing results in output directory") self._chk_overwrite.setChecked(True) self._lbl_available = QLabel('Available') self._lst_available = QListView() self._lst_available.setModel(_AvailableOptionsListModel()) self._lst_available.setSelectionMode(QListView.SelectionMode.MultiSelection) tlb_available = QToolBar() spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) tlb_available.addWidget(spacer) act_open = tlb_available.addAction(getIcon("document-open"), "Open") act_open.setShortcut(QKeySequence.Open) tlb_available.addSeparator() act_remove = tlb_available.addAction(getIcon("list-remove"), "Remove") act_clear = tlb_available.addAction(getIcon("edit-clear"), "Clear") self._btn_addtoqueue = QPushButton(getIcon("go-next"), "") self._btn_addtoqueue.setToolTip("Add to queue") self._btn_addtoqueue.setEnabled(False) self._btn_addalltoqueue = QPushButton(getIcon("go-last"), "") self._btn_addalltoqueue.setToolTip("Add all to queue") self._btn_addalltoqueue.setEnabled(False) self._lbl_options = QLabel('Queued/Running/Completed') self._tbl_options = QTableView() self._tbl_options.setModel(_StateOptionsTableModel()) self._tbl_options.setItemDelegate(_StateOptionsItemDelegate()) self._tbl_options.setSelectionMode(QListView.SelectionMode.NoSelection) self._tbl_options.setColumnWidth(1, 60) self._tbl_options.setColumnWidth(2, 80) header = self._tbl_options.horizontalHeader() header.setResizeMode(0, QHeaderView.Interactive) header.setResizeMode(1, QHeaderView.Fixed) header.setResizeMode(2, QHeaderView.Fixed) header.setResizeMode(3, QHeaderView.Stretch) self._btn_start = QPushButton(getIcon("media-playback-start"), "Start") self._btn_cancel = QPushButton("Cancel") self._btn_cancel.setEnabled(False) self._btn_close = QPushButton("Close") self._btn_import = QPushButton("Import") self._btn_import.setEnabled(False) # Layouts layout = QVBoxLayout() sublayout = QGridLayout() sublayout.addWidget(lbl_outputdir, 0, 0) sublayout.addWidget(self._txt_outputdir, 0, 1) sublayout.addWidget(lbl_workers, 1, 0) subsublayout = QHBoxLayout() subsublayout.addWidget(self._spn_workers) subsublayout.addWidget(lbl_max_workers) sublayout.addLayout(subsublayout, 1, 1) layout.addLayout(sublayout) sublayout.addWidget(self._chk_overwrite, 2, 0, 1, 3) sublayout = QGridLayout() sublayout.setColumnStretch(0, 1) sublayout.setColumnStretch(2, 3) sublayout.addWidget(self._lbl_available, 0, 0) sublayout.addWidget(self._lst_available, 1, 0) sublayout.addWidget(tlb_available, 2, 0) subsublayout = QVBoxLayout() subsublayout.addStretch() subsublayout.addWidget(self._btn_addtoqueue) subsublayout.addWidget(self._btn_addalltoqueue) subsublayout.addStretch() sublayout.addLayout(subsublayout, 1, 1) sublayout.addWidget(self._lbl_options, 0, 2) sublayout.addWidget(self._tbl_options, 1, 2) layout.addLayout(sublayout) sublayout = QHBoxLayout() sublayout.addStretch() sublayout.addWidget(self._btn_import) sublayout.addWidget(self._btn_start) sublayout.addWidget(self._btn_cancel) sublayout.addWidget(self._btn_close) layout.addLayout(sublayout) self.setLayout(layout) # Signal self._running_timer.timeout.connect(self._onRunningTimer) act_open.triggered.connect(self._onOpen) act_remove.triggered.connect(self._onRemove) act_clear.triggered.connect(self._onClear) self._btn_addtoqueue.released.connect(self._onAddToQueue) self._btn_addalltoqueue.released.connect(self._onAddAllToQueue) self._btn_start.released.connect(self._onStart) self._btn_cancel.released.connect(self._onCancel) self._btn_close.released.connect(self._onClose) self._btn_import.released.connect(self._onImport) self.options_added.connect(self._onOptionsAdded) self.options_running.connect(self._onOptionsRunning) self.options_simulated.connect(self._onOptionsSimulated) self.options_error.connect(self._onOptionsError) self.results_error.connect(self._onResultsError) # Defaults settings = get_settings() section = settings.add_section('gui') if hasattr(section, 'outputdir'): self._txt_outputdir.setPath(section.outputdir) if hasattr(section, 'maxworkers'): self._spn_workers.setValue(int(section.maxworkers)) if hasattr(section, 'overwrite'): state = True if section.overwrite.lower() == 'true' else False self._chk_overwrite.setChecked(state) def _onDialogProgressProgress(self, progress, status): self._dlg_progress.setValue(progress * 100) self._dlg_progress.setLabelText(status) def _onDialogProgressCancel(self): self._dlg_progress.hide() if self._options_reader_thread is None: return self._options_reader_thread.cancel() self._options_reader_thread.quit() self._options_reader_thread.wait() def _onDialogProgressException(self, ex): self._dlg_progress.hide() self._options_reader_thread.quit() self._options_reader_thread.wait() messagebox.exception(self, ex) def _onRunningTimer(self): self._tbl_options.model().reset() def _onOpen(self): settings = get_settings() curdir = getattr(settings.gui, 'opendir', os.getcwd()) filepath, namefilter = \ QFileDialog.getOpenFileName(self, "Open", curdir, 'Options [*.xml] (*.xml)') if not filepath or not namefilter: return settings.gui.opendir = os.path.dirname(filepath) if not filepath.endswith('.xml'): filepath += '.xml' self._options_reader_thread = _OptionsReaderWrapperThread(filepath) self._dlg_progress.canceled.connect(self._onDialogProgressCancel) self._options_reader_thread.resultReady.connect(self._onOpened) self._options_reader_thread.progressUpdated.connect(self._onDialogProgressProgress) self._options_reader_thread.exceptionRaised.connect(self._onDialogProgressException) self._options_reader_thread.start() self._dlg_progress.reset() self._dlg_progress.show() def _onOpened(self, options): self._dlg_progress.hide() self._options_reader_thread.quit() self._options_reader_thread.wait() self._options_reader_thread = None try: self._lst_available.model().addOptions(options) except Exception as ex: messagebox.exception(self, ex) def _onRemove(self): selection = self._lst_available.selectionModel().selection().indexes() if len(selection) == 0: QMessageBox.warning(self, "Queue", "Select an options") return model = self._lst_available.model() for row in sorted(map(methodcaller('row'), selection), reverse=True): model.popOptions(row) def _onClear(self): self._lst_available.model().clearOptions() def _onAddToQueue(self): selection = self._lst_available.selectionModel().selection().indexes() if len(selection) == 0: QMessageBox.warning(self, "Queue", "Select an options") return model = self._lst_available.model() for row in sorted(map(methodcaller('row'), selection), reverse=True): options = model.options(row) try: self._runner.put(options) except Exception as ex: messagebox.exception(self, ex) return def _onAddAllToQueue(self): model = self._lst_available.model() for row in reversed(range(0, model.rowCount())): options = model.options(row) try: self._runner.put(options) except Exception as ex: messagebox.exception(self, ex) return def _onStart(self): outputdir = self._txt_outputdir.path() if not outputdir: QMessageBox.critical(self, 'Start', 'Missing output directory') return max_workers = self._spn_workers.value() overwrite = self._chk_overwrite.isChecked() self.start(outputdir, overwrite, max_workers) def _onCancel(self): self.cancel() def _onClose(self): if self._runner is not None: self._runner.close() self._running_timer.stop() self.close() def _onImport(self): list_options = self._lst_available.model().listOptions() if not list_options: return # Select options dialog = _OptionsSelector(list_options) if not dialog.exec_(): return options = dialog.options() # Start importer outputdir = self._runner.outputdir max_workers = self._runner.max_workers importer = LocalImporter(outputdir, max_workers) importer.start() importer.put(options) self._dlg_progress.show() try: while importer.is_alive(): if self._dlg_progress.wasCanceled(): importer.cancel() break self._dlg_progress.setValue(importer.progress * 100) finally: self._dlg_progress.hide() def _onOptionsAdded(self, options): logging.debug('runner: optionsAdded') self._tbl_options.model().addOptions(options) def _onOptionsRunning(self, options): logging.debug('runner: optionsRunning') self._tbl_options.model().resetOptions(options) def _onOptionsSimulated(self, options): logging.debug('runner: optionsSimulated') self._tbl_options.model().resetOptions(options) def _onOptionsError(self, options, ex): logging.debug('runner: optionsError') self._tbl_options.model().resetOptions(options) def _onResultsError(self, results, ex): logging.debug('runner: resultsError') self._tbl_options.model().reset() def closeEvent(self, event): if self.is_running(): message = 'Runner is running. Do you want to continue?' answer = QMessageBox.question(self, 'Runner', message, QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.No: event.ignore() return self.cancel() self._dlg_progress.close() settings = get_settings() section = settings.add_section('gui') path = self._txt_outputdir.path() if path: section.outputdir = path section.maxworkers = str(self._spn_workers.value()) section.overwrite = str(self._chk_overwrite.isChecked()) settings.write() event.accept() def addAvailableOptions(self, options): self._lst_available.model().addOptions(options) def removeAvailableOptions(self, options): self._lst_available.model().removeOptions(options) def clearAvailableOptions(self): self._lbl_available.model().clearOptions() def start(self, outputdir, overwrite, max_workers): self._runner = LocalRunner(outputdir=outputdir, overwrite=overwrite, max_workers=max_workers) self._tbl_options.setModel(_StateOptionsTableModel(self._runner)) self._spn_workers.setEnabled(False) self._txt_outputdir.setEnabled(False) self._chk_overwrite.setEnabled(False) self._btn_addtoqueue.setEnabled(True) self._btn_addalltoqueue.setEnabled(True) self._btn_start.setEnabled(False) self._btn_cancel.setEnabled(True) self._btn_close.setEnabled(False) self._btn_import.setEnabled(True) self._runner.options_added.connect(self.options_added.emit) self._runner.options_running.connect(self.options_running.emit) self._runner.options_simulated.connect(self.options_simulated.emit) self._runner.options_error.connect(self.options_error.emit) self._runner.results_saved.connect(self.results_saved.emit) self._runner.results_error.connect(self.results_error.emit) self._running_timer.start() self._runner.start() def cancel(self): if self._runner is None: return self._runner.cancel() self._running_timer.stop() self._runner.options_added.disconnect(self.options_added.emit) self._runner.options_running.disconnect(self.options_running.emit) self._runner.options_simulated.disconnect(self.options_simulated.emit) self._runner.options_error.disconnect(self.options_error.emit) self._runner.results_saved.disconnect(self.results_saved.emit) self._runner.results_error.disconnect(self.results_error.emit) self._runner = None self._spn_workers.setEnabled(True) self._txt_outputdir.setEnabled(True) self._chk_overwrite.setEnabled(True) self._btn_addtoqueue.setEnabled(False) self._btn_addalltoqueue.setEnabled(False) self._btn_start.setEnabled(True) self._btn_cancel.setEnabled(False) self._btn_close.setEnabled(True) self._btn_import.setEnabled(False) def is_running(self): return self._runner is not None and self._runner.is_alive()
class MTTFilterFileDialog(QDialog): def __init__(self, define_path='', define_type=None): super(MTTFilterFileDialog, self).__init__(get_maya_window()) self.supported_node_type = sorted( [node_type for (node_type, nice, attr) in MTTSettings.SUPPORTED_TYPE]) self.defined_path = ( define_path if os.path.isdir(define_path) or define_path == SOURCEIMAGES_TAG else None) self.defined_type = ( define_type if define_type in self.supported_node_type else None) self.path_edit = None self.filter_reset_btn = None self.filter_line = None self.parent_folder_btn = None self.files_model = None self.files_list = None self.bookmark_list = None self.bookmark_list_sel_model = None self.types = None # move window to cursor position win_geo = MTTSettings.value( 'FilterFileDialog/windowGeometry', QRect(0, 0, 400, 300)) self.setGeometry(win_geo) mouse_pos = QCursor.pos() mouse_pos.setX(mouse_pos.x() - (win_geo.width() * 0.5)) self.move(mouse_pos) self.__create_ui() self.filter_line.setFocus() self.on_change_root_path(self.defined_path or SOURCEIMAGES_TAG) def __create_ui(self): """ Create main UI """ self.setWindowTitle(CREATE_NODE_TITLE) # remove window decoration if path and type is set if self.defined_path and self.defined_type: self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup) main_layout = QVBoxLayout(self) main_layout.setSpacing(1) main_layout.setContentsMargins(2, 2, 2, 2) # content layout content_layout = QVBoxLayout() self.files_model = QFileSystemModel() self.files_model.setNameFilterDisables(False) self.files_list = MTTFileList() self.files_list.setAlternatingRowColors(True) self.files_list.setSelectionMode(QAbstractItemView.ExtendedSelection) self.files_list.selectionValidated.connect(self.do_validate_selection) self.files_list.goToParentDirectory.connect(self.on_go_up_parent) self.files_list.doubleClicked.connect(self.on_double_click) self.files_list.setModel(self.files_model) buttons_layout = QHBoxLayout() content_layout.addLayout(self.__create_filter_ui()) content_layout.addWidget(self.files_list) content_layout.addLayout(buttons_layout) self.files_list.filter_line = self.filter_line if not self.defined_path: # path line path_layout = QHBoxLayout() # bookmark button bookmark_btn = QPushButton('') bookmark_btn.setFlat(True) bookmark_btn.setIcon(QIcon(':/addBookmark.png')) bookmark_btn.setToolTip('Bookmark this Folder') bookmark_btn.setStatusTip('Bookmark this Folder') bookmark_btn.clicked.connect(self.on_add_bookmark) # path line edit self.path_edit = QLineEdit() self.path_edit.editingFinished.connect(self.on_enter_path) # parent folder button self.parent_folder_btn = QPushButton('') self.parent_folder_btn.setFlat(True) self.parent_folder_btn.setIcon(QIcon(':/SP_FileDialogToParent.png')) self.parent_folder_btn.setToolTip('Parent Directory') self.parent_folder_btn.setStatusTip('Parent Directory') self.parent_folder_btn.clicked.connect(self.on_go_up_parent) # browse button browse_btn = QPushButton('') browse_btn.setFlat(True) browse_btn.setIcon(QIcon(':/navButtonBrowse.png')) browse_btn.setToolTip('Browse Directory') browse_btn.setStatusTip('Browse Directory') browse_btn.clicked.connect(self.on_browse) # parent widget and layout path_layout.addWidget(bookmark_btn) path_layout.addWidget(self.path_edit) path_layout.addWidget(self.parent_folder_btn) path_layout.addWidget(browse_btn) main_layout.addLayout(path_layout) # bookmark list bookmark_parent_layout = QHBoxLayout() bookmark_frame = QFrame() bookmark_frame.setFixedWidth(120) bookmark_layout = QVBoxLayout() bookmark_layout.setSpacing(1) bookmark_layout.setContentsMargins(2, 2, 2, 2) bookmark_frame.setLayout(bookmark_layout) bookmark_frame.setFrameStyle(QFrame.Sunken) bookmark_frame.setFrameShape(QFrame.StyledPanel) self.bookmark_list = MTTBookmarkList() self.bookmark_list.bookmarkDeleted.connect(self.do_delete_bookmark) self.bookmark_list.setAlternatingRowColors(True) self.bookmark_list.dragEnabled() self.bookmark_list.setAcceptDrops(True) self.bookmark_list.setDropIndicatorShown(True) self.bookmark_list.setDragDropMode(QListView.InternalMove) self.bookmark_list_sel_model = self.bookmark_list.selectionModel() self.bookmark_list_sel_model.selectionChanged.connect( self.on_select_bookmark) bookmark_layout.addWidget(self.bookmark_list) bookmark_parent_layout.addWidget(bookmark_frame) bookmark_parent_layout.addLayout(content_layout) main_layout.addLayout(bookmark_parent_layout) self.do_populate_bookmarks() else: main_layout.addLayout(content_layout) if not self.defined_type: # type layout self.types = QComboBox() self.types.addItems(self.supported_node_type) self.types.currentIndexChanged.connect(self.on_node_type_changed) if cmds.optionVar(exists='MTT_lastNodeType'): last = cmds.optionVar(query='MTT_lastNodeType') if last in self.supported_node_type: self.types.setCurrentIndex( self.supported_node_type.index(last)) buttons_layout.addWidget(self.types) if not self.defined_path or not self.defined_type: create_btn = QPushButton('C&reate') create_btn.clicked.connect(self.accept) cancel_btn = QPushButton('&Cancel') cancel_btn.clicked.connect(self.reject) buttons_layout.addStretch() buttons_layout.addWidget(create_btn) buttons_layout.addWidget(cancel_btn) def __create_filter_ui(self): """ Create filter widgets """ filter_layout = QHBoxLayout() filter_layout.setSpacing(1) filter_layout.setContentsMargins(0, 0, 0, 0) self.filter_reset_btn = QPushButton() icon = QIcon(':/filtersOff.png') self.filter_reset_btn.setIcon(icon) self.filter_reset_btn.setIconSize(QSize(22, 22)) self.filter_reset_btn.setFixedSize(24, 24) self.filter_reset_btn.setToolTip('Reset filter') self.filter_reset_btn.setFlat(True) self.filter_reset_btn.clicked.connect( partial(self.on_filter_set_text, '')) self.filter_line = QLineEdit() self.filter_line.setPlaceholderText('Enter filter string here') self.filter_line.textChanged.connect(self.on_filter_change_text) completer = QCompleter(self) completer.setCaseSensitivity(Qt.CaseInsensitive) completer.setModel(QStringListModel([], self)) self.filter_line.setCompleter(completer) filter_layout.addWidget(self.filter_reset_btn) filter_layout.addWidget(self.filter_line) return filter_layout def on_filter_set_text(self, text=''): """ Set text in filter field """ self.filter_line.setText(text) def on_filter_change_text(self, text): """ Apply filter string """ if len(text): icon = QIcon(':/filtersOn.png') self.filter_reset_btn.setIcon(icon) else: icon = QIcon(':/filtersOff.png') self.filter_reset_btn.setIcon(icon) self.files_model.setNameFilters( ['*%s*' % item.strip() for item in text.split(',') if item.strip()]) def on_node_type_changed(self, index): cmds.optionVar(sv=['MTT_lastNodeType', self.supported_node_type[index]]) def on_double_click(self, index): current_item = self.files_model.filePath(index) if os.path.isdir(current_item): self.on_change_root_path(current_item) elif os.path.isfile(current_item): self.accept() def on_change_root_path(self, current_path): if current_path == SOURCEIMAGES_TAG: current_path = os.path.join( cmds.workspace(query=True, rootDirectory=True), cmds.workspace(fileRuleEntry='sourceImages') ) self.files_model.setRootPath(current_path) self.files_list.setRootIndex(self.files_model.index(current_path)) if self.path_edit: self.path_edit.setText(current_path) if self.parent_folder_btn: current_dir = QDir(current_path) self.parent_folder_btn.setEnabled(current_dir.cdUp()) def on_go_up_parent(self): current_path = QDir(self.files_model.rootPath()) current_path.cdUp() self.on_change_root_path(current_path.absolutePath()) def on_enter_path(self): new_path = self.path_edit.text() if os.path.isdir(new_path): self.on_change_root_path(new_path) else: self.path_edit.setText(self.files_model.rootPath()) def on_browse(self): current_path = self.files_model.rootPath() file_dialog = QFileDialog(self, 'Select a Folder', current_path) file_dialog.setFileMode(QFileDialog.Directory) file_dialog.setOption(QFileDialog.ShowDirsOnly) if file_dialog.exec_(): self.on_change_root_path(file_dialog.selectedFiles()[0]) def on_select_bookmark(self, selected, deselected): current_item = selected.indexes() if current_item: self.on_change_root_path( self.bookmark_list.selectedItems()[0].root_path) def on_add_bookmark(self): current_path = self.files_model.rootPath() self.on_add_bookmark_item( '%s|%s' % (os.path.basename(current_path), current_path)) def on_add_bookmark_item(self, item): if item == '': return current_item = MTTBookmarkItem() current_item.add_raw_data(item) current_item.setSizeHint(QSize(40, 25)) current_item.setFlags( Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled ) self.bookmark_list.addItem(current_item) def do_delete_bookmark(self): current_item = self.bookmark_list.selectedItems() if current_item: item_row = self.bookmark_list.row(current_item[0]) self.bookmark_list.takeItem(item_row) del current_item[0] def do_save_bookmark(self): if not self.bookmark_list: return row_count = self.bookmark_list.count() ordered_list = list() for i in range(row_count): item = self.bookmark_list.item(i) name = item.text().replace(',', '_').replace('|', '_') path = item.root_path if name != 'sourceimages': ordered_list.append('%s|%s' % (name, path)) MTTSettings.set_value( 'FilterFileDialog/bookmarks', ','.join(ordered_list)) def do_populate_bookmarks(self): bookmarks = ['sourceimages|%s' % SOURCEIMAGES_TAG] bookmarks.extend( MTTSettings.value('FilterFileDialog/bookmarks').split(',')) for bm in bookmarks: self.on_add_bookmark_item(bm) def do_validate_selection(self): selection = self.files_list.selectedIndexes() if len(selection) == 1: current_path = self.files_model.filePath(selection[0]) if os.path.isdir(current_path): self.on_change_root_path(current_path) return self.accept() def get_selected_files(self): selected_items = list() for item_index in self.files_list.selectedIndexes(): current_path = self.files_model.filePath(item_index) if os.path.isfile(current_path): selected_items.append(current_path) return selected_items def get_node_type(self): return self.types.currentText() if self.types else self.defined_type def closeEvent(self, event): MTTSettings.set_value( 'FilterFileDialog/windowGeometry', self.geometry()) self.do_save_bookmark() self.deleteLater() event.accept()
class AddPresetDialog(QDialog): def __init__(self, parent=None): super(AddPresetDialog, self).__init__(parent) self.setWindowTitle(self.tr("Add IMAP Server Preset")) self.resize(388, 125) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setGeometry(QRect(184, 80, 181, 32)) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setCenterButtons(False) self.save_btn = QPushButton("&Save") self.save_btn.setDefault(True) self.save_btn.setEnabled(False) self.cancel_btn = QPushButton(self.tr("&Cancel")) self.cancel_btn.setCheckable(True) self.cancel_btn.setAutoDefault(False) self.buttonBox.addButton(self.save_btn, QDialogButtonBox.AcceptRole) self.buttonBox.addButton(self.cancel_btn, QDialogButtonBox.RejectRole) self.preset_name_le = QLineEdit(self) self.preset_name_le.setGeometry(QRect(134, 12, 231, 20)) self.lb_name = QLabel(self) self.lb_name.setGeometry(QRect(14, 16, 58, 14)) self.lb_name.setText(self.tr("Name")) self.server_address_le = QLineEdit(self) self.server_address_le.setGeometry(QRect(134, 45, 231, 20)) self.lb_server = QLabel(self) self.lb_server.setGeometry(QRect(14, 48, 81, 16)) self.lb_server.setText(self.tr("IMAP Server")) self.lb_info = QLabel(self) self.lb_info.setGeometry(QRect(14, 90, 161, 16)) self.lb_info.setText(self.tr("(SSL is always on.)")) self.buttonBox.accepted.connect(self.act_save_preset) self.buttonBox.rejected.connect(self.reject) self.init_settings() self.settings.beginGroup("Server Presets") self.presetNameList = [] for preset in self.settings.allKeys(): self.presetNameList.append(preset) self.settings.endGroup() self.preset_name_le.textChanged.connect(self.check_preset_name_availability) self.server_address_le.textChanged.connect(self.check_server_address) # --------------------------------------------------------------------- def init_settings(self): QCoreApplication.setOrganizationName("erdinc.me") QCoreApplication.setOrganizationDomain("erdinc.me") QCoreApplication.setApplicationName("IMAPLinkParser") self.settings = QSettings() # self.settings.clear() # --------------------------------------------------------------------- @Slot() def act_save_preset(self): try: self.settings.beginGroup("Server Presets") self.settings.setValue(self.preset_name_le.text(), self.server_address_le.text()) self.settings.endGroup() except: self.reject() self.accept() # --------------------------------------------------------------------- @Slot(unicode) def check_preset_name_availability(self, text): if text in self.presetNameList: self.save_btn.setEnabled(False) self.lb_info.setText('<p style="color:red;">Preset name exists!') else: if self.server_address_le.text() and self.preset_name_le.text(): self.save_btn.setEnabled(True) self.lb_info.setText(self.tr("(SSL is always on.)")) else: self.save_btn.setEnabled(False) self.lb_info.setText(self.tr("(SSL is always on.)")) # --------------------------------------------------------------------- @Slot(unicode) def check_server_address(self): if self.server_address_le.text(): preset = self.preset_name_le.text() if preset and preset not in self.presetNameList: self.save_btn.setEnabled(True) else: self.save_btn.setEnabled(False)
class CompareSequences(QMainWindow): def __init__(self): super(CompareSequences, self).__init__() self.setWindowTitle('Compare Sequences') self.setFixedHeight(125) self._ledit1 = QLineEdit() self._btn_pick_1 = QPushButton('...') self._ledit2 = QLineEdit() self._btn_pick_2 = QPushButton('...') self._btn_compare = QPushButton('Compare') self._progress_bar = QProgressBar(self.statusBar()) self._setup_ui() self._set_connections() def _compare(self): self._toggle_ui() src_one = self._ledit1.text() src_two = self._ledit2.text() # TODO: put in some checks for valid sequences if not (src_one and src_two): msg = 'Please pick proper sequences.' print msg nuke.message(msg) else: read1 = nuke.createNode('Read', inpanel=False) read1.knob('file').fromUserText(src_one) read2 = nuke.createNode('Read', inpanel=False) read2.knob('file').fromUserText(src_two) read2.setXYpos(read1.xpos() + 100, read1.ypos()) if not (read1.width() == read2.width() and read1.height() == read2.height()): msg = 'Sequences are not the same resolution.' print msg nuke.message(msg) else: # TODO: check for same resolution m = nuke.createNode('Merge2', inpanel=False) m.knob('operation').setValue(6) m.setXYpos(read1.xpos(), read2.ypos() + 100) m.setInput(0, read1) m.setInput(1, read2) c = nuke.createNode('CurveTool', inpanel=False) c.knob('operation').setValue(3) c.knob('ROI').fromDict( { 'x': 0, 'y': 0, 'r': read1.width(), 't': read1.height() } ) v = nuke.createNode('Viewer') check = False frame = None first = read1.knob('first').value() last = read1.knob('last').value() self._progress_bar.setRange(first, last) for i in range(first, last + 1): self._progress_bar.setValue(i) nuke.execute(c, i, i) data = c.knob('maxlumapixvalue').animations() check = False for curve in data: if not curve.constant(): check = True frame = i break if check: break if not check: msg = 'There is no difference.' else: msg = 'There is a difference at frame %d.' % frame nuke.message(msg) self._progress_bar.reset() self._toggle_ui() def _pick_sequence(self): btn = self.sender() le_btn_pair = { self._btn_pick_1: self._ledit1, self._btn_pick_2: self._ledit2 } clip_path = nuke.getClipname('Pick Sequence to compare') le_btn_pair[btn].setText(clip_path) def _set_connections(self): self._btn_pick_1.released.connect(self._pick_sequence) self._btn_pick_2.released.connect(self._pick_sequence) self._btn_compare.released.connect(self._compare) def _setup_ui(self): self._btn_pick_1.setFixedWidth(25) self._btn_pick_1.setToolTip('Pick first sequence.') self._btn_pick_2.setFixedWidth(25) self._btn_pick_2.setToolTip('Pick second sequence.') self._btn_compare.setToolTip('Compare sequences.') self._progress_bar.setFixedHeight(10) lyt_seq1 = QHBoxLayout() lyt_seq1.addWidget(self._ledit1) lyt_seq1.addWidget(self._btn_pick_1) lyt_seq2 = QHBoxLayout() lyt_seq2.addWidget(self._ledit2) lyt_seq2.addWidget(self._btn_pick_2) lyt_main = QVBoxLayout() lyt_main.addLayout(lyt_seq1) lyt_main.addLayout(lyt_seq2) lyt_main.addWidget(self._btn_compare) main_widget = QWidget() main_widget.setLayout(lyt_main) self.setCentralWidget(main_widget) def _toggle_ui(self): self._ledit1.setEnabled(not self._ledit1.isEnabled()) self._ledit2.setEnabled(not self._ledit2.isEnabled()) self._btn_pick_1.setEnabled(not self._btn_pick_1.isEnabled()) self._btn_pick_2.setEnabled(not self._btn_pick_2.isEnabled()) self._btn_compare.setEnabled(not self._btn_compare.isEnabled())
def __init__(self, *args, **kwargs ): QMainWindow.__init__( self, *args, **kwargs ) self.installEventFilter( self ) #self.setWindowFlags( QtCore.Qt.Drawer ) self.setWindowTitle( Window_global.title ) verticalSplitter = QSplitter(QtCore.Qt.Vertical) self.setCentralWidget( verticalSplitter ) horizonSplitter1 = QSplitter(QtCore.Qt.Horizontal) horizonSplitter2 = QSplitter(QtCore.Qt.Horizontal) verticalSplitter.addWidget( horizonSplitter1 ) verticalSplitter.addWidget( horizonSplitter2 ) widgetSelArea = QWidget() layoutSelArea = QVBoxLayout(widgetSelArea) labelSelTextList = QLabel( 'Images from Selection' ) selTextureList = QListWidget() selTextureList.setSelectionMode( QAbstractItemView.ExtendedSelection ) layoutSelArea.addWidget( labelSelTextList ) layoutSelArea.addWidget( selTextureList ) imageBaseSelArea = ImageBase() horizonSplitter1.addWidget( widgetSelArea ) horizonSplitter1.addWidget( imageBaseSelArea ) widgetPathArea = QWidget() layoutPathArea = QVBoxLayout( widgetPathArea ) layoutAddTab = QHBoxLayout() removeTabButton = QPushButton( 'Remove Tab' ) addTabButton = QPushButton( 'Add Tab' ) self.tabWidget = Tab() buttonLayout = QHBoxLayout() getImageButton = QPushButton( 'Get Image' ) removeImageButton = QPushButton( 'Remove Image' ) layoutPathArea.addLayout( layoutAddTab ) layoutPathArea.addWidget( self.tabWidget ) layoutPathArea.addLayout( buttonLayout ) imageBasePathArea = ImageBase() layoutAddTab.addWidget( removeTabButton ) layoutAddTab.addWidget( addTabButton ) buttonLayout.addWidget( getImageButton ) buttonLayout.addWidget( removeImageButton ) horizonSplitter2.addWidget( widgetPathArea ) horizonSplitter2.addWidget( imageBasePathArea ) Window_global.selTextureList = selTextureList Window_global.imageBaseSelArea = imageBaseSelArea Window_global.imageBasePathArea = imageBasePathArea Window_global.verticalSplitter = verticalSplitter Window_global.horizonSplitter1 = horizonSplitter1 Window_global.horizonSplitter2 = horizonSplitter2 Window_global.getImageButton = getImageButton Window_global.removeImageButton = removeImageButton Window_global.tabWidget = self.tabWidget Window_global.tabWidget.addTab( 'newTab' ) verticalSplitter.setSizes( [100,100] ) horizonSplitter1.setSizes( [100,100] ) horizonSplitter2.setSizes( [100,100] ) Window_global.loadInfo() try:Window_global.loadInfo2() except:pass Functions.updateSelTextureList() QtCore.QObject.connect( addTabButton, QtCore.SIGNAL( 'clicked()' ), self.addTab ) QtCore.QObject.connect( removeTabButton, QtCore.SIGNAL( 'clicked()' ), self.removeTab ) QtCore.QObject.connect( Window_global.selTextureList, QtCore.SIGNAL( 'itemSelectionChanged()' ), Functions.loadImageSelArea ) QtCore.QObject.connect( Window_global.horizonSplitter1, QtCore.SIGNAL( 'splitterMoved(int,int)' ), Functions.splitterMoved1 ) QtCore.QObject.connect( Window_global.horizonSplitter2, QtCore.SIGNAL( 'splitterMoved(int,int)' ), Functions.splitterMoved2 ) QtCore.QObject.connect( getImageButton, QtCore.SIGNAL( 'clicked()' ), Functions.getImage ) QtCore.QObject.connect( removeImageButton, QtCore.SIGNAL( 'clicked()' ), Functions.removeImage ) imageBaseSelArea.clear() imageBasePathArea.clear() getImageButton.setEnabled( False ) removeImageButton.setEnabled( False )
class SpiderTab(QWidget): """Has handlers for spider data and events. It houses the results table of the spider, controls for the spider and progress indication It implicitly conforms to IEventHandler interface""" TIMER_CHECK_INTERVAL = 3000 favicon_received = Signal(str) # send the url or path to the handler, which should be the tab widget stop_spider_signal = Signal(int) became_current = Signal(bool) # tell the table it has become active. it's an interesting property for producers! def __init__(self, parent=None, **kwargs): super(SpiderTab, self).__init__(parent) self._event_queue = None self._data_queue = None self._engine = None self._favicon_received = False self._spider_id = None self._item_count = 0 self.setContextMenuPolicy(Qt.ContextMenuPolicy.DefaultContextMenu) self.initInterface(kwargs) self._context_menu = None self._setupContextMenu() self.became_current.connect(self._set_table_activity) self._queue_check_timer = QTimer() self._queue_check_timer.setInterval(self.TIMER_CHECK_INTERVAL) self._queue_check_timer.timeout.connect(self._checkQueues) self._queue_check_timer.start() def initInterface(self, kwargs): layout = QGridLayout() self._data_table = SearchTable(name=kwargs.get("name")) self._progress_spider = QProgressBar() self._label_count = QLabel(self.tr("0 items scraped")) # make it a busy indicator. you don't know when it'll finish self._progress_spider.setMinimum(0); self._progress_spider.setMaximum(0) self._progress_spider.setTextVisible(False) self._btn_stop_spider = QPushButton(self.tr("Stop Spider")) self._btn_stop_spider.clicked.connect(self.stop_spider) row = 0; col = 0; layout.addWidget(self._data_table, row, col, 1, 4) row += 1; layout.addWidget(self._progress_spider, row, col, 1, 1) col += 1 layout.addWidget(self._label_count, row, col, 1, 2) col += 2 layout.addWidget(self._btn_stop_spider, row, col, 1, 1) self.setLayout(layout) def _setupContextMenu(self): from visualscrape.lib.data import ActionStore self._context_menu = QMenu(self) # get the export action from the action store action_store = ActionStore.get_instance() for action in action_store: if action.get_name() == "export": export_action = action break self._context_menu.addAction(export_action) def export_table(self): export_dialog = ExportDialog() export_dialog.exec_() export_info = export_dialog.data() if export_info: data = self._data_table.get_visible_data() FileExporter.export(data, self._data_table.name.lower(), export_info.location, export_info.format) def set_event_queue(self, eq): self._event_queue = eq def set_data_queue(self, dq): self._data_queue = dq def stop_spider(self): if self._spider_id is None: # do not stop the the spider before receiving data pass else: if self._queue_check_timer.isActive(): confirm_stop = QMessageBox(self) confirm_stop.setIcon(QMessageBox.Warning) confirm_stop.setStandardButtons(QMessageBox.Yes | QMessageBox.No) confirm_stop.setText(self.tr("Scraping process still running")) confirm_stop.setDetailedText(self.tr("Are you sure you want to stop it?")) confirm_stop.setWindowTitle(self.tr("Spider still running")) ret = confirm_stop.exec_() if ret == QMessageBox.Yes: self.stop_spider_signal.emit(self._spider_id) return True else: return False # I won't whip you if you stop it accidentally else: return True # already over def configure_searchlineedit(self, lineEdit): self._data_table.configure_search_lineedit(lineEdit) def _checkQueues(self): while not self._event_queue.empty(): event = self._event_queue.get(block=False, timeout=0) if isinstance(event, SpiderClosed): self._queue_check_timer.stop() self._progress_spider.setMinimum(0) self._progress_spider.setMaximum(100) self._progress_spider.setValue(100) self._btn_stop_spider.setEnabled(False) while not self._data_queue.empty(): item = self._data_queue.get(block=False, timeout=0) if not self._favicon_received: # the first item on the data queue should be the favicon favicon_data = item["images"][0] self.favicon_received.emit(favicon_data["path"]) # note that icons are not guaranteed to have a path. Not everybody wants to save images self._favicon_received = True self._spider_id = item["_id"] else: item.pop("_id") # the table has nothing to do with spider ids self._data_table.addItem(item) self._item_count += 1 self._label_count.setText(self.tr("{0:n} items scraped".format(self._item_count))) def _set_table_activity(self, state): self._data_table.set_active(state)
def __init__(self): super(AVRProgrammerDialog, self).__init__(CWMainGUI.getInstance()) # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint) self.avr = AVRProgrammer() self.setWindowTitle("ChipWhisperer-Lite AVR Programmer") layout = QVBoxLayout() layoutFW = QHBoxLayout() self.flashLocation = QtFixes.QLineEdit() flashFileButton = QPushButton("Find") flashFileButton.clicked.connect(self.findFlash) layoutFW.addWidget(QLabel("FLASH File")) layoutFW.addWidget(self.flashLocation) layoutFW.addWidget(flashFileButton) layout.addLayout(layoutFW) self.flashLocation.setText(QSettings().value("avr-flash-location")) # Add buttons readSigBut = QPushButton("Check Signature") readSigBut.clicked.connect(self.readSignature) verifyFlashBut = QPushButton("Verify FLASH") verifyFlashBut.clicked.connect(self.verifyFlash) verifyFlashBut.setEnabled(False) progFlashBut = QPushButton("Erase/Program/Verify FLASH") progFlashBut.clicked.connect(self.writeFlash) layoutBut = QHBoxLayout() layoutBut.addWidget(readSigBut) layoutBut.addWidget(verifyFlashBut) layoutBut.addWidget(progFlashBut) layout.addLayout(layoutBut) layoutFuse = QHBoxLayout() readFuseBut = QPushButton("Read Fuses") readFuseBut.clicked.connect(self.readFuses) writeFuseBut = QPushButton("Write Fuses") writeFuseBut.clicked.connect(self.writeFuses) self.lowfuseLine = QtFixes.QLineEdit("?") self.lowfuseLine.setMaxLength(2) self.lowfuseLine.setFixedWidth(25) self.highfuseLine = QtFixes.QLineEdit("?") self.highfuseLine.setMaxLength(2) self.highfuseLine.setFixedWidth(25) self.extfuseLine = QtFixes.QLineEdit("?") self.extfuseLine.setMaxLength(2) self.extfuseLine.setFixedWidth(25) # Don't allow use to change these fuses self.highfuseLine.setReadOnly(True) self.extfuseLine.setReadOnly(True) layoutFuse.addWidget(readFuseBut) layoutFuse.addWidget(QLabel("LOW:")) layoutFuse.addWidget(self.lowfuseLine) layoutFuse.addWidget(QLabel("HIGH:")) layoutFuse.addWidget(self.highfuseLine) layoutFuse.addWidget(QLabel("EXT:")) layoutFuse.addWidget(self.extfuseLine) layoutFuse.addWidget(writeFuseBut) layout.addLayout(layoutFuse) layoutExtra = QHBoxLayout() self.clockMode = QPushButton("Enable Slow Clock Mode") self.clockMode.setCheckable(True) self.clockMode.clicked.connect(self.toggleSlowClock) layoutExtra.addWidget(self.clockMode) layoutExtra.addStretch() layout.addLayout(layoutExtra) # Add status stuff self.statusLine = QPlainTextEdit() self.statusLine.setReadOnly(True) # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10) layout.addWidget(self.statusLine) self.avr.newTextLog.connect(self.append) # Set dialog layout self.setLayout(layout)
class LandmarkLocationWidget(QWidget): # Signals activated = Signal(int, bool) removed = Signal(int) def __init__(self): super(LandmarkLocationWidget, self).__init__() self._active = False self._font = QFont() self._font.setPointSize(10) self.indexLabel = QLabel() self.indexLabel.setMaximumWidth(8) self.indexLabel.setMinimumWidth(8) self.doneButton = QPushButton("Done") self.doneButton.setMaximumWidth(50) self.doneButton.setFont(self._font) self.doneButton.clicked.connect(self.doneButtonClicked) self.fixedButton = QPushButton("") self.fixedButton.setFont(self._font) self.movingButton = QPushButton("") self.movingButton.setFont(self._font) layout = QGridLayout() layout.setAlignment(Qt.AlignTop) layout.setContentsMargins(0, 0, 0, 0) layout.setHorizontalSpacing(4) layout.setVerticalSpacing(0) layout.addWidget(self.indexLabel, 0, 0) layout.addWidget(self.fixedButton, 0, 1) layout.addWidget(self.movingButton, 0, 2) layout.addWidget(self.doneButton, 0, 3) self.setLayout(layout) self._updateState() def setIndex(self, index): self.index = index self.indexLabel.setText(str(index + 1)) @property def active(self): return self._active @active.setter def active(self, value): self._active = value self._updateState() def setLandmarkSet(self, points): self.setFixedLandmark(points[0]) self.setMovingLandmark(points[1]) def setFixedLandmark(self, landmark): if not landmark: return labelX = "%2.0f" % landmark[0] labelY = "%2.0f" % landmark[1] labelZ = "%2.0f" % landmark[2] self.fixedButton.setText(labelX + ", " + labelY + ", " + labelZ) def setMovingLandmark(self, landmark): if not landmark: return labelX = "%2.0f" % landmark[0] labelY = "%2.0f" % landmark[1] labelZ = "%2.0f" % landmark[2] self.movingButton.setText(labelX + ", " + labelY + ", " + labelZ) @Slot() def doneButtonClicked(self): self._active = not self._active self.activated.emit(self.index, self._active) self._updateState() def _updateState(self): if self._active: self.doneButton.setText("Done") else: self.doneButton.setText("Edit") self.fixedButton.setEnabled(self._active) self.movingButton.setEnabled(self._active)