class LabelDistributionOptionsDlg( QDialog ): """ A little dialog to let the user specify how the labels should be distributed from the current stages to the other stages. """ def __init__(self, source_stage_index, num_stages, *args, **kwargs): super(LabelDistributionOptionsDlg, self).__init__(*args, **kwargs) from PyQt4.QtCore import Qt from PyQt4.QtGui import QGroupBox, QCheckBox, QRadioButton, QDialogButtonBox self.setWindowTitle("Distributing from Stage {}".format(source_stage_index+1)) self.stage_checkboxes = [] for stage_index in range(1, num_stages+1): self.stage_checkboxes.append( QCheckBox("Stage {}".format( stage_index )) ) # By default, send labels back into the current stage, at least. self.stage_checkboxes[source_stage_index].setChecked(True) stage_selection_layout = QVBoxLayout() for checkbox in self.stage_checkboxes: stage_selection_layout.addWidget( checkbox ) stage_selection_groupbox = QGroupBox("Send labels from Stage {} to:".format( source_stage_index+1 ), self) stage_selection_groupbox.setLayout(stage_selection_layout) self.copy_button = QRadioButton("Copy", self) self.partition_button = QRadioButton("Partition", self) self.partition_button.setChecked(True) distribution_mode_layout = QVBoxLayout() distribution_mode_layout.addWidget(self.copy_button) distribution_mode_layout.addWidget(self.partition_button) distribution_mode_group = QGroupBox("Distribution Mode", self) distribution_mode_group.setLayout(distribution_mode_layout) buttonbox = QDialogButtonBox( Qt.Horizontal, parent=self ) buttonbox.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Cancel ) buttonbox.accepted.connect( self.accept ) buttonbox.rejected.connect( self.reject ) dlg_layout = QVBoxLayout() dlg_layout.addWidget(stage_selection_groupbox) dlg_layout.addWidget(distribution_mode_group) dlg_layout.addWidget(buttonbox) self.setLayout(dlg_layout) def distribution_mode(self): if self.copy_button.isChecked(): return "copy" if self.partition_button.isChecked(): return "partition" assert False, "Shouldn't get here." def destination_stages(self): """ Return the list of stage_indexes (0-based) that the user checked. """ return [ i for i,box in enumerate(self.stage_checkboxes) if box.isChecked() ]
class StartSession(preferences.Group): def __init__(self, page): super(StartSession, self).__init__(page) grid = QGridLayout() self.setLayout(grid) def changed(): self.changed.emit() self.combo.setEnabled(self.custom.isChecked()) self.none = QRadioButton(toggled=changed) self.lastused = QRadioButton(toggled=changed) self.custom = QRadioButton(toggled=changed) self.combo = QComboBox(currentIndexChanged=changed) grid.addWidget(self.none, 0, 0, 1, 2) grid.addWidget(self.lastused, 1, 0, 1, 2) grid.addWidget(self.custom, 2, 0, 1, 1) grid.addWidget(self.combo, 2, 1, 1, 1) app.translateUI(self) def translateUI(self): self.setTitle(_("Session to load if Frescobaldi is started without arguments")) self.none.setText(_("Start with no session")) self.lastused.setText(_("Start with last used session")) self.custom.setText(_("Start with session:")) def loadSettings(self): s = QSettings() s.beginGroup("session") startup = s.value("startup", "none", type("")) if startup == "lastused": self.lastused.setChecked(True) elif startup == "custom": self.custom.setChecked(True) else: self.none.setChecked(True) sessionNames = sessions.sessionNames() self.combo.clear() self.combo.addItems(sessionNames) custom = s.value("custom", "", type("")) if custom in sessionNames: self.combo.setCurrentIndex(sessionNames.index(custom)) def saveSettings(self): s = QSettings() s.beginGroup("session") s.setValue("custom", self.combo.currentText()) if self.custom.isChecked(): startup = "custom" elif self.lastused.isChecked(): startup = "lastused" else: startup = "none" s.setValue("startup", startup)
def RadioGet(widget : QtGui.QRadioButton, id : int) -> str or None: """If QRadioButton name match 'val' return it state.""" # if not widget.isChecked(): return # return widget.accessibleName() if not widget.isChecked(): return assert len(self.enum) > id return self.enum[id]
class RadioButton(QWidget): selected = pyqtSignal() def __init__(self, caption, parent, selected=False): QWidget.__init__(self) self.value = selected self.radiobutton = QRadioButton(caption, parent) self.radiobutton.clicked.connect(self.__on_change) hbox = QHBoxLayout() hbox.addWidget(self.radiobutton) hbox.setMargin(0) self.setLayout(hbox) self.setContentsMargins(0, 0, 0, 0) self.radiobutton.setChecked(self.value) def __on_change(self): self.value = True self.selected.emit() def set_value(self, value): self.radiobutton.setChecked(value) def get_value(self): return self.radiobutton.isChecked()
class RepoTypeWizardPage(QWizardPage): def __init__(self, parent=None): super(RepoTypeWizardPage, self).__init__( parent, title="Select Account Type", subTitle="Select the type of Repo to create") # RadioButtons self.githubRadioButton = QRadioButton('Github Repo') # Layout self.mainLayout = QVBoxLayout() self.mainLayout.addWidget(self.githubRadioButton) self.setLayout(self.mainLayout) # Setup self.githubRadioButton.toggle() def nextId(self): if self.githubRadioButton.isChecked(): return 1
def Build_Tab(group, source_key, default, projector, projectordb, edit=False): """ Create the radio button page for a tab. Dictionary will be a 1-key entry where key=tab to setup, val=list of inputs. source_key: {"groupkey1": {"key11": "key11-text", "key12": "key12-text", ... }, "groupkey2": {"key21": "key21-text", "key22": "key22-text", .... }, ... } :param group: Button group widget to add buttons to :param source_key: Dictionary of sources for radio buttons :param default: Default radio button to check :param projector: Projector instance :param projectordb: ProjectorDB instance for session :param edit: If we're editing the source text """ buttonchecked = False widget = QWidget() layout = QFormLayout() if edit else QVBoxLayout() layout.setSpacing(10) widget.setLayout(layout) tempkey = list(source_key.keys())[0] # Should only be 1 key sourcelist = list(source_key[tempkey]) sourcelist.sort() button_count = len(sourcelist) if edit: for key in sourcelist: item = QLineEdit() item.setObjectName('source_key_%s' % key) source_item = projectordb.get_source_by_code(code=key, projector_id=projector.db_item.id) if source_item is None: item.setText(PJLINK_DEFAULT_CODES[key]) else: item.setText(source_item.text) layout.addRow(PJLINK_DEFAULT_CODES[key], item) group.append(item) else: for key in sourcelist: source_item = projectordb.get_source_by_code(code=key, projector_id=projector.db_item.id) if source_item is None: text = source_key[tempkey][key] else: text = source_item.text itemwidget = QRadioButton(text) itemwidget.setAutoExclusive(True) if default == key: itemwidget.setChecked(True) buttonchecked = itemwidget.isChecked() or buttonchecked group.addButton(itemwidget, int(key)) layout.addWidget(itemwidget) layout.addStretch() return widget, button_count, buttonchecked
def __init__(self, result): QDialog.__init__(self) self.layout = QVBoxLayout(self) self.result = result observation_window = result.observation_window group = QButtonGroup(self) use_simu_duration = QRadioButton("Use entire simulation.") use_simu_duration.setChecked( observation_window[0] == 0 and observation_window[1] == result.model.duration) group.addButton(use_simu_duration) self.layout.addWidget(use_simu_duration) use_custom = QRadioButton("Use a custom observation window:") use_custom.setChecked(not use_simu_duration.isChecked()) group.addButton(use_custom) self.layout.addWidget(use_custom) self._slider = QxtSpanSliderWidget( 0, result.model.now() // result.model.cycles_per_ms, self) self._slider.setSpan( observation_window[0] // result.model.cycles_per_ms, observation_window[1] // result.model.cycles_per_ms) self._slider.setEnabled(use_custom.isChecked()) group.buttonClicked.connect( lambda x: self._slider.setEnabled(x == use_custom)) self.layout.addWidget(self._slider) buttons = QWidget(self) buttons_layout = QHBoxLayout() buttons.setLayout(buttons_layout) buttons_layout.addStretch() ok_button = QPushButton("Ok") cancel_button = QPushButton("Cancel") ok_button.clicked.connect(self.accept) cancel_button.clicked.connect(self.reject) buttons_layout.addWidget(ok_button) buttons_layout.addWidget(cancel_button) self.layout.addWidget(buttons)
class CrossModeGroupItem(GroupItem): def __init__(self, setup): super(CrossModeGroupItem, self).__init__("Cross-Mode Terms", [("Cross-Mode Term", CrossModeItem)], setup) self.context_menu.add_action('Add Terms From Matrix', self.add_from_matrix) self.array_model = UpperHalfArrayModel() array_view = QTableView() array_view.setModel(self.array_model) type_group = QGroupBox() type_layout = QVBoxLayout(type_group) self.cross_kerr_type_radio = QRadioButton("Cross-Kerr") self.cross_kerr_type_radio.setChecked(True) self.xx_type_radio = QRadioButton("X-X") type_layout.addWidget(self.cross_kerr_type_radio) type_layout.addWidget(self.xx_type_radio) self.dialog = OKCancelDialog(QLabel("Mode Array"), array_view, type_group) def add_item(self, dialog=True): if self.setup.modes_item.rowCount() < 2: message_box.setIcon(QMessageBox.Warning) message_box.setText("Need more than two modes") message_box.exec_() else: return super(CrossModeGroupItem, self).add_item(dialog=dialog) def add_from_matrix(self): self.array_model.set_n(self.setup.modes_item.rowCount()) names = [m.text() for m in self.setup.modes_item.items_list()] self.array_model.setHorizontalHeaderLabels(names) self.array_model.setVerticalHeaderLabels(names) if self.dialog.exec_(): if self.cross_kerr_type_radio.isChecked(): type_str = "Cross-Kerr" elif self.xx_type_radio.isChecked(): type_str = "X-X" else: return for i, row in enumerate(self.array_model.array): for j, val in enumerate(row): if val: self.appendRow(CrossModeItem(type_str, val, i, j, self.setup.modes_item))
def network_dialog(self): # skip this if config already exists if self.config.get('server') is not None: return grid = QGridLayout() grid.setSpacing(5) label = QLabel(_( "Electrum communicates with remote servers to get ", 'information about your transactions and addresses. ', 'The servers all fulfil the same purpose only ', 'differing in hardware. In most cases you simply ', 'want to let Electrum pick one at random if you ', 'have a preference though feel free to select a server manually.') + "\n\n" + _( "How do you want to connect to a server:") + " ") label.setWordWrap(True) grid.addWidget(label, 0, 0) gb = QGroupBox() b1 = QRadioButton(gb) b1.setText(_("Auto connect")) b1.setChecked(True) b2 = QRadioButton(gb) b2.setText(_("Select server manually")) # b3 = QRadioButton(gb) # b3.setText(_("Stay offline")) grid.addWidget(b1, 1, 0) grid.addWidget(b2, 2, 0) # grid.addWidget(b3, 3, 0) vbox = QVBoxLayout() vbox.addLayout(grid) vbox.addStretch(1) vbox.addLayout(Buttons(CancelButton(self), OkButton(self, _('Next')))) self.set_layout(vbox) if not self.exec_(): return if b2.isChecked(): return NetworkDialog(self.network, self.config, None).do_exec() else: self.config.set_key('auto_connect', True, True) return
class Target(preferences.Group): def __init__(self, page): super(Target, self).__init__(page) layout = QGridLayout() self.setLayout(layout) self.targetPDF = QRadioButton(toggled=page.changed) self.targetSVG = QRadioButton(toggled=page.changed) self.openDefaultView = QCheckBox(clicked=page.changed) layout.addWidget(self.targetPDF, 0, 0) layout.addWidget(self.targetSVG, 0, 1) layout.addWidget(self.openDefaultView, 1, 0, 1, 5) app.translateUI(self) def translateUI(self): self.setTitle(_("Default output format")) self.targetPDF.setText(_("PDF")) self.targetPDF.setToolTip(_( "Create PDF (Portable Document Format) documents by default.")) self.targetSVG.setText(_("SVG")) self.targetSVG.setToolTip(_( "Create SVG (Scalable Vector Graphics) documents by default.")) self.openDefaultView.setText(_("Open default viewer after successful compile")) self.openDefaultView.setToolTip(_( "Shows the PDF or SVG music view when a compile job finishes " "successfully.")) def loadSettings(self): s = settings() target = s.value("default_output_target", "pdf", type("")) if target == "svg": self.targetSVG.setChecked(True) self.targetPDF.setChecked(False) else: self.targetSVG.setChecked(False) self.targetPDF.setChecked(True) self.openDefaultView.setChecked(s.value("open_default_view", True, bool)) def saveSettings(self): s = settings() if self.targetSVG.isChecked(): target = "svg" else: target = "pdf" s.setValue("default_output_target", target) s.setValue("open_default_view", self.openDefaultView.isChecked())
class Book(_base.Group): @staticmethod def title(_=_base.translate): return _("Book") def accepts(self): return (BookPart, Score, StaffGroup, _base.Part) def createWidgets(self, layout): self.bookOutputInfo = QLabel(wordWrap=True) self.bookOutputLabel = QLabel() self.bookOutput = widgets.lineedit.LineEdit() self.bookOutputFileName = QRadioButton() self.bookOutputSuffix = QRadioButton(checked=True) layout.addWidget(self.bookOutputInfo) grid = QGridLayout(spacing=0) grid.addWidget(self.bookOutputLabel, 0, 0) grid.addWidget(self.bookOutput, 0, 1, 1, 2) grid.addWidget(self.bookOutputFileName, 1, 1) grid.addWidget(self.bookOutputSuffix, 1, 2) layout.addLayout(grid) def translateWidgets(self): self.bookOutputInfo.setText(_( "<p>Here you can specify a filename or suffix (without extension) " "to set the names of generated output files for this book.</p>\n" "<p>If you choose \"Suffix\" the entered name will be appended " "to the document's file name; if you choose \"Filename\", just " "the entered name will be used.</p>")) self.bookOutputLabel.setText(_("Output Filename:")) self.bookOutputFileName.setText(_("Filename")) self.bookOutputSuffix.setText(_("Suffix")) def makeNode(self, node): book = ly.dom.Book(node) name = self.bookOutput.text().strip() if name: cmd = 'bookOutputName' if self.bookOutputFileName.isChecked() else 'bookOutputSuffix' ly.dom.Line(r'\{0} "{1}"'.format(cmd, name.replace('"', r'\"')), book) return book
class AccountTypeWizardPage(QWizardPage): def __init__(self, parent=None): super(AccountTypeWizardPage, self).__init__( parent, title="Select Account Type", subTitle="Select the type of account to create") # Radio Buttons self.githubRadioButton = QRadioButton("Github account") self.githubRadioButton.toggle() # Layout self.mainLayout = QVBoxLayout() self.mainLayout.addWidget(self.githubRadioButton) self.setLayout(self.mainLayout) def nextId(self): if self.githubRadioButton.isChecked(): return 1 # TODO remove magic number
class DatabaseTypePage(QWizardPage): def __init__(self, parent=None): super(DatabaseTypePage, self).__init__(parent) self.setTitle(self.tr(u"Typ databáze")) self.textRB = QRadioButton(QApplication.translate("DatabaseTypePage", 'Databáze uložená jako textové soubory v adresáři', None, QApplication.UnicodeUTF8), None) self.pgRB = QRadioButton(QApplication.translate("DatabaseTypePage", 'Databáze PostGIS', None, QApplication.UnicodeUTF8), None) self.setCheckedButton() grid = QGridLayout() grid.addWidget(self.textRB, 0, 0) grid.addWidget(self.pgRB, 1, 0) self.setLayout(grid) self.connect(self.textRB, SIGNAL("clicked()"), self.updateDatabaseTypeText) self.connect(self.pgRB, SIGNAL("clicked()"), self.updateDatabaseTypePG) def setCheckedButton(self): dbType = config['selectedDatabaseType'] if dbType == 'textFile_DBHandler': return self.textRB.setChecked(True) elif dbType == 'postGIS_DBHandler': return self.pgRB.setChecked(True) def updateDatabaseTypeText(self): config['selectedDatabaseType'] = 'textFile_DBHandler' def updateDatabaseTypePG(self): config['selectedDatabaseType'] = 'postGIS_DBHandler' def nextId(self): if self.textRB.isChecked(): return LicenseWizard.PageTextFileDBHandler else: return LicenseWizard.PagePostGISDBHandler
class Preferences(QDialog): def __init__(self, parent=None, test = False): super(Preferences, self).__init__(parent) self.parent = parent self.home = os.getenv('HOME') saveLabel = QLabel('<html><b>' + self.tr('Save files') + '</b></html>') exist_Label = QLabel(self.tr('Existing files:')) self.exst_add_prefixRadioButton = QRadioButton( self.tr("Add '~' prefix")) self.exst_overwriteRadioButton = QRadioButton(self.tr('Overwrite')) exist_layout = pyqttools.add_to_layout(QHBoxLayout(), self.exst_add_prefixRadioButton, self.exst_overwriteRadioButton) defaultLabel = QLabel(self.tr('Default output destination:')) self.defaultLineEdit = QLineEdit() self.defaultToolButton = QToolButton() self.defaultToolButton.setText('...') deafult_fol_layout = pyqttools.add_to_layout(QHBoxLayout(), self.defaultLineEdit, self.defaultToolButton) name_Label = QLabel('<html><b>' + self.tr('Name files') +'</b></html>') prefixLabel = QLabel(self.tr('Prefix:')) suffixLabel = QLabel(self.tr('Suffix:')) self.prefixLineEdit = QLineEdit() self.suffixLineEdit = QLineEdit() grid = pyqttools.add_to_grid(QGridLayout(), [prefixLabel, self.prefixLineEdit], [suffixLabel, self.suffixLineEdit]) prefix_layout = pyqttools.add_to_layout(QHBoxLayout(), grid, None) tabwidget1_layout = pyqttools.add_to_layout(QVBoxLayout(), saveLabel, QSpacerItem(14, 13), exist_Label, exist_layout, QSpacerItem(14, 13), defaultLabel, deafult_fol_layout, QSpacerItem(13, 13), name_Label, QSpacerItem(14, 13), prefix_layout) ffmpegLabel = QLabel('<html><b>' + self.tr('FFmpeg') +'</b></html>') default_commandLabel = QLabel(self.tr('Default command:')) self.commandLineEdit = QLineEdit() useLabel = QLabel(self.tr('Use:')) self.ffmpegRadioButton = QRadioButton(self.tr('FFmpeg')) self.avconvRadioButton = QRadioButton(self.tr('avconv')) hlayout = pyqttools.add_to_layout(QHBoxLayout(), self.ffmpegRadioButton, self.avconvRadioButton) tabwidget2_layout = pyqttools.add_to_layout(QVBoxLayout(), ffmpegLabel, QSpacerItem(14, 13), useLabel, hlayout, QSpacerItem(14, 13), default_commandLabel, self.commandLineEdit, None) widget1 = QWidget() widget1.setLayout(tabwidget1_layout) widget2 = QWidget() widget2.setLayout(tabwidget2_layout) self.TabWidget = QTabWidget() self.TabWidget.addTab(widget1, self.tr('General')) self.TabWidget.addTab(widget2, self.tr('Audio/Video')) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok| QDialogButtonBox.Cancel) final_layout = pyqttools.add_to_layout(QVBoxLayout(), self.TabWidget, None, self.buttonBox) self.setLayout(final_layout) self.defaultToolButton.clicked.connect(self.open_dir) self.buttonBox.accepted.connect(self.save_settings) self.buttonBox.rejected.connect(self.reject) settings = QSettings() overwrite_existing = settings.value('overwrite_existing').toBool() default_output = settings.value('default_output').toString() prefix = settings.value('prefix').toString() suffix = settings.value('suffix').toString() avconv_prefered = settings.value('avconv_prefered').toBool() default_command = settings.value('default_command').toString() if overwrite_existing: self.exst_overwriteRadioButton.setChecked(True) else: self.exst_add_prefixRadioButton.setChecked(True) if default_output: self.defaultLineEdit.setText(default_output) if prefix: self.prefixLineEdit.setText(prefix) if suffix: self.suffixLineEdit.setText(suffix) if avconv_prefered: self.avconvRadioButton.setChecked(True) else: self.ffmpegRadioButton.setChecked(True) if default_command: self.commandLineEdit.setText(default_command) else: self.commandLineEdit.setText('-ab 320k -ar 48000 -ac 2') if not test and not self.parent.ffmpeg: self.avconvRadioButton.setChecked(True) self.ffmpegRadioButton.setEnabled(False) if not test and not self.parent.avconv: self.ffmpegRadioButton.setChecked(True) self.avconvRadioButton.setEnabled(False) self.resize(400, 390) self.setWindowTitle(self.tr('Preferences')) def open_dir(self): """Get a directory name using a standard Qt dialog and update self.defaultLineEdit with dir's name.""" if self.defaultLineEdit.isEnabled(): _dir = QFileDialog.getExistingDirectory(self, 'FF Multi Converter ' '- ' + self.tr('Choose default output destination'), self.home) #_dir = unicode(_dir) if _dir: self.defaultLineEdit.setText(_dir) def save_settings(self): """Set settings values, extracting the appropriate information from the graphical widgets.""" overwrite_existing = self.exst_overwriteRadioButton.isChecked() default_output = unicode(self.defaultLineEdit.text()) prefix = unicode(self.prefixLineEdit.text()) suffix = unicode(self.suffixLineEdit.text()) avconv_prefered = self.avconvRadioButton.isChecked() default_command = unicode(self.commandLineEdit.text()) settings = QSettings() settings.setValue('overwrite_existing', overwrite_existing) settings.setValue('default_output', default_output) settings.setValue('prefix', prefix) settings.setValue('suffix', suffix) settings.setValue('avconv_prefered', avconv_prefered) settings.setValue('default_command', default_command) self.accept()
class RunDialog(QDialog): """ Run parameters dialog implementation """ # See utils.run for runParameters def __init__(self, path, runParameters, termType, profilerParams, debuggerParams, action="", parent=None): QDialog.__init__(self, parent) # Used as a return value self.termType = termType self.profilerParams = copy.deepcopy(profilerParams) self.debuggerParams = copy.deepcopy(debuggerParams) self.__action = action.lower() # Avoid pylint complains self.__argsEdit = None self.__scriptWDRButton = None self.__dirRButton = None self.__dirEdit = None self.__dirSelectButton = None self.__inheritParentRButton = None self.__inheritParentPlusRButton = None self.__inhPlusEnvTable = None self.__addInhButton = None self.__delInhButton = None self.__editInhButton = None self.__specificRButton = None self.__specEnvTable = None self.__addSpecButton = None self.__delSpecButton = None self.__editSpecButton = None self.__runButton = None self.__nodeLimitEdit = None self.__edgeLimitEdit = None self.__createLayout(action) self.setWindowTitle(action + " parameters for " + path) # Restore the values self.runParams = copy.deepcopy(runParameters) self.__argsEdit.setText(self.runParams.arguments) # Working dir if self.runParams.useScriptLocation: self.__scriptWDRButton.setChecked(True) self.__dirEdit.setEnabled(False) self.__dirSelectButton.setEnabled(False) else: self.__dirRButton.setChecked(True) self.__dirEdit.setEnabled(True) self.__dirSelectButton.setEnabled(True) self.__dirEdit.setText(self.runParams.specificDir) # Environment self.__populateTable(self.__inhPlusEnvTable, self.runParams.additionToParentEnv) self.__populateTable(self.__specEnvTable, self.runParams.specificEnv) if self.runParams.envType == RunParameters.InheritParentEnv: self.__inheritParentRButton.setChecked(True) self.__setEnabledInheritedPlusEnv(False) self.__setEnabledSpecificEnv(False) elif self.runParams.envType == RunParameters.InheritParentEnvPlus: self.__inheritParentPlusRButton.setChecked(True) self.__setEnabledSpecificEnv(False) else: self.__specificRButton.setChecked(True) self.__setEnabledInheritedPlusEnv(False) # Terminal if self.termType == TERM_REDIRECT: self.__redirectRButton.setChecked(True) elif self.termType == TERM_AUTO: self.__autoRButton.setChecked(True) elif self.termType == TERM_KONSOLE: self.__konsoleRButton.setChecked(True) elif self.termType == TERM_GNOME: self.__gnomeRButton.setChecked(True) else: self.__xtermRButton.setChecked(True) # Close checkbox self.__closeCheckBox.setChecked(self.runParams.closeTerminal) if self.termType == TERM_REDIRECT: self.__closeCheckBox.setEnabled(False) # Profile limits if so if self.__action == "profile": if self.profilerParams.nodeLimit < 0.0 or \ self.profilerParams.nodeLimit > 100.0: self.profilerParams.nodeLimit = 1.0 self.__nodeLimitEdit.setText(str(self.profilerParams.nodeLimit)) if self.profilerParams.edgeLimit < 0.0 or \ self.profilerParams.edgeLimit > 100.0: self.profilerParams.edgeLimit = 1.0 self.__edgeLimitEdit.setText(str(self.profilerParams.edgeLimit)) elif self.__action == "debug": self.__reportExceptionCheckBox.setChecked( self.debuggerParams.reportExceptions) self.__traceInterpreterCheckBox.setChecked( self.debuggerParams.traceInterpreter) self.__stopAtFirstCheckBox.setChecked( self.debuggerParams.stopAtFirstLine) self.__autoforkCheckBox.setChecked(self.debuggerParams.autofork) self.__debugChildCheckBox.setChecked( self.debuggerParams.followChild) self.__debugChildCheckBox.setEnabled(self.debuggerParams.autofork) self.__setRunButtonProps() return @staticmethod def __populateTable(table, dictionary): " Populates the given table " for key, value in dictionary.iteritems(): item = QTreeWidgetItem([key, value]) table.addTopLevelItem(item) if dictionary: table.setCurrentItem(table.topLevelItem(0)) return def __setEnabledInheritedPlusEnv(self, value): " Disables/enables 'inherited and add' section controls " self.__inhPlusEnvTable.setEnabled(value) self.__addInhButton.setEnabled(value) self.__delInhButton.setEnabled(value) self.__editInhButton.setEnabled(value) return def __setEnabledSpecificEnv(self, value): " Disables/enables 'specific env' section controls " self.__specEnvTable.setEnabled(value) self.__addSpecButton.setEnabled(value) self.__delSpecButton.setEnabled(value) self.__editSpecButton.setEnabled(value) return def __createLayout(self, action): """ Creates the dialog layout """ self.resize(650, 300) self.setSizeGripEnabled(True) # Top level layout layout = QVBoxLayout(self) # Cmd line arguments argsLabel = QLabel("Command line arguments") self.__argsEdit = QLineEdit() self.__argsEdit.textChanged.connect(self.__argsChanged) argsLayout = QHBoxLayout() argsLayout.addWidget(argsLabel) argsLayout.addWidget(self.__argsEdit) layout.addLayout(argsLayout) # Working directory workDirGroupbox = QGroupBox(self) workDirGroupbox.setTitle("Working directory") sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( \ workDirGroupbox.sizePolicy().hasHeightForWidth() ) workDirGroupbox.setSizePolicy(sizePolicy) gridLayoutWD = QGridLayout(workDirGroupbox) self.__scriptWDRButton = QRadioButton(workDirGroupbox) self.__scriptWDRButton.setText("&Use script location") gridLayoutWD.addWidget(self.__scriptWDRButton, 0, 0) self.__scriptWDRButton.clicked.connect(self.__scriptWDirClicked) self.__dirRButton = QRadioButton(workDirGroupbox) self.__dirRButton.setText("Select &directory") gridLayoutWD.addWidget(self.__dirRButton, 1, 0) self.__dirRButton.clicked.connect(self.__dirClicked) self.__dirEdit = QLineEdit(workDirGroupbox) gridLayoutWD.addWidget(self.__dirEdit, 1, 1) self.__dirEdit.textChanged.connect(self.__workingDirChanged) self.__dirSelectButton = QPushButton(workDirGroupbox) self.__dirSelectButton.setText("...") gridLayoutWD.addWidget(self.__dirSelectButton, 1, 2) self.__dirSelectButton.clicked.connect(self.__selectDirClicked) layout.addWidget(workDirGroupbox) # Environment envGroupbox = QGroupBox(self) envGroupbox.setTitle("Environment") sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( \ envGroupbox.sizePolicy().hasHeightForWidth() ) envGroupbox.setSizePolicy(sizePolicy) layoutEnv = QVBoxLayout(envGroupbox) self.__inheritParentRButton = QRadioButton(envGroupbox) self.__inheritParentRButton.setText("Inherit &parent") self.__inheritParentRButton.clicked.connect(self.__inhClicked) layoutEnv.addWidget(self.__inheritParentRButton) self.__inheritParentPlusRButton = QRadioButton(envGroupbox) self.__inheritParentPlusRButton.setText( "Inherit parent and add/&modify") self.__inheritParentPlusRButton.clicked.connect(self.__inhPlusClicked) layoutEnv.addWidget(self.__inheritParentPlusRButton) hInhPlusLayout = QHBoxLayout() self.__inhPlusEnvTable = QTreeWidget() self.__inhPlusEnvTable.itemActivated.connect( self.__inhPlusItemActivated) self.__tuneTable(self.__inhPlusEnvTable) hInhPlusLayout.addWidget(self.__inhPlusEnvTable) vInhPlusLayout = QVBoxLayout() self.__addInhButton = QPushButton() self.__addInhButton.clicked.connect(self.__addInhClicked) self.__addInhButton.setText('Add') vInhPlusLayout.addWidget(self.__addInhButton) self.__delInhButton = QPushButton() self.__delInhButton.clicked.connect(self.__delInhClicked) self.__delInhButton.setText('Delete') vInhPlusLayout.addWidget(self.__delInhButton) self.__editInhButton = QPushButton() self.__editInhButton.clicked.connect(self.__editInhClicked) self.__editInhButton.setText("Edit") vInhPlusLayout.addWidget(self.__editInhButton) hInhPlusLayout.addLayout(vInhPlusLayout) layoutEnv.addLayout(hInhPlusLayout) self.__specificRButton = QRadioButton(envGroupbox) self.__specificRButton.setText("&Specific") self.__specificRButton.clicked.connect(self.__specClicked) layoutEnv.addWidget(self.__specificRButton) hSpecLayout = QHBoxLayout() self.__specEnvTable = QTreeWidget() self.__specEnvTable.itemActivated.connect(self.__specItemActivated) self.__tuneTable(self.__specEnvTable) hSpecLayout.addWidget(self.__specEnvTable) vSpecLayout = QVBoxLayout() self.__addSpecButton = QPushButton() self.__addSpecButton.clicked.connect(self.__addSpecClicked) self.__addSpecButton.setText('Add') vSpecLayout.addWidget(self.__addSpecButton) self.__delSpecButton = QPushButton() self.__delSpecButton.clicked.connect(self.__delSpecClicked) self.__delSpecButton.setText('Delete') vSpecLayout.addWidget(self.__delSpecButton) self.__editSpecButton = QPushButton() self.__editSpecButton.clicked.connect(self.__editSpecClicked) self.__editSpecButton.setText("Edit") vSpecLayout.addWidget(self.__editSpecButton) hSpecLayout.addLayout(vSpecLayout) layoutEnv.addLayout(hSpecLayout) layout.addWidget(envGroupbox) # Terminal and profile limits if self.__action in ["profile", "debug"]: layout.addWidget(self.__getIDEWideGroupbox()) else: termGroupbox = self.__getTermGroupbox() termGroupbox.setTitle("Terminal to run in (IDE wide setting)") layout.addWidget(termGroupbox) # Close checkbox self.__closeCheckBox = QCheckBox("&Close terminal upon " "successful completion") self.__closeCheckBox.stateChanged.connect(self.__onCloseChanged) layout.addWidget(self.__closeCheckBox) # Buttons at the bottom buttonBox = QDialogButtonBox(self) buttonBox.setOrientation(Qt.Horizontal) buttonBox.setStandardButtons(QDialogButtonBox.Cancel) self.__runButton = buttonBox.addButton(action, QDialogButtonBox.AcceptRole) self.__runButton.setDefault(True) self.__runButton.clicked.connect(self.onAccept) layout.addWidget(buttonBox) buttonBox.rejected.connect(self.close) return def __getTermGroupbox(self): " Creates the term groupbox " termGroupbox = QGroupBox(self) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( termGroupbox.sizePolicy().hasHeightForWidth()) termGroupbox.setSizePolicy(sizePolicy) layoutTerm = QVBoxLayout(termGroupbox) self.__redirectRButton = QRadioButton(termGroupbox) self.__redirectRButton.setText("&Redirect to IDE") self.__redirectRButton.toggled.connect(self.__redirectedChanged) layoutTerm.addWidget(self.__redirectRButton) self.__autoRButton = QRadioButton(termGroupbox) self.__autoRButton.setText("Aut&o detection") layoutTerm.addWidget(self.__autoRButton) self.__konsoleRButton = QRadioButton(termGroupbox) self.__konsoleRButton.setText("Default &KDE konsole") layoutTerm.addWidget(self.__konsoleRButton) self.__gnomeRButton = QRadioButton(termGroupbox) self.__gnomeRButton.setText("gnome-&terminal") layoutTerm.addWidget(self.__gnomeRButton) self.__xtermRButton = QRadioButton(termGroupbox) self.__xtermRButton.setText("&xterm") layoutTerm.addWidget(self.__xtermRButton) return termGroupbox def __redirectedChanged(self, checked): " Triggered when the redirected radio button changes its state " self.__closeCheckBox.setEnabled(not checked) return def __getIDEWideGroupbox(self): " Creates the IDE wide groupbox " ideGroupbox = QGroupBox(self) ideGroupbox.setTitle("IDE Wide Settings") sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( ideGroupbox.sizePolicy().hasHeightForWidth()) ideGroupbox.setSizePolicy(sizePolicy) layoutIDE = QHBoxLayout(ideGroupbox) termGroupbox = self.__getTermGroupbox() termGroupbox.setTitle("Terminal to run in") layoutIDE.addWidget(termGroupbox) if self.__action == "profile": # Profile version of the dialog limitsGroupbox = self.__getProfileLimitsGroupbox() layoutIDE.addWidget(limitsGroupbox) else: # Debug version of the dialog dbgGroupbox = self.__getDebugGroupbox() layoutIDE.addWidget(dbgGroupbox) return ideGroupbox def __getProfileLimitsGroupbox(self): " Creates the profile limits groupbox " limitsGroupbox = QGroupBox(self) limitsGroupbox.setTitle("Profiler diagram limits") sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( limitsGroupbox.sizePolicy().hasHeightForWidth()) limitsGroupbox.setSizePolicy(sizePolicy) layoutLimits = QGridLayout(limitsGroupbox) self.__nodeLimitEdit = QLineEdit() self.__nodeLimitEdit.textEdited.connect(self.__setRunButtonProps) self.__nodeLimitValidator = QDoubleValidator(0.0, 100.0, 2, self) self.__nodeLimitValidator.setNotation( QDoubleValidator.StandardNotation) self.__nodeLimitEdit.setValidator(self.__nodeLimitValidator) nodeLimitLabel = QLabel("Hide nodes below") self.__edgeLimitEdit = QLineEdit() self.__edgeLimitEdit.textEdited.connect(self.__setRunButtonProps) self.__edgeLimitValidator = QDoubleValidator(0.0, 100.0, 2, self) self.__edgeLimitValidator.setNotation( QDoubleValidator.StandardNotation) self.__edgeLimitEdit.setValidator(self.__edgeLimitValidator) edgeLimitLabel = QLabel("Hide edges below") layoutLimits.addWidget(nodeLimitLabel, 0, 0) layoutLimits.addWidget(self.__nodeLimitEdit, 0, 1) layoutLimits.addWidget(QLabel("%"), 0, 2) layoutLimits.addWidget(edgeLimitLabel, 1, 0) layoutLimits.addWidget(self.__edgeLimitEdit, 1, 1) layoutLimits.addWidget(QLabel("%"), 1, 2) return limitsGroupbox def __getDebugGroupbox(self): " Creates the debug settings groupbox " dbgGroupbox = QGroupBox(self) dbgGroupbox.setTitle("Debugger") sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( dbgGroupbox.sizePolicy().hasHeightForWidth()) dbgGroupbox.setSizePolicy(sizePolicy) dbgLayout = QVBoxLayout(dbgGroupbox) self.__reportExceptionCheckBox = QCheckBox("Report &exceptions") self.__reportExceptionCheckBox.stateChanged.connect( self.__onReportExceptionChanged) self.__traceInterpreterCheckBox = QCheckBox("T&race interpreter libs") self.__traceInterpreterCheckBox.stateChanged.connect( self.__onTraceInterpreterChanged) self.__stopAtFirstCheckBox = QCheckBox("Stop at first &line") self.__stopAtFirstCheckBox.stateChanged.connect( self.__onStopAtFirstChanged) self.__autoforkCheckBox = QCheckBox("&Fork without asking") self.__autoforkCheckBox.stateChanged.connect(self.__onAutoforkChanged) self.__debugChildCheckBox = QCheckBox("Debu&g child process") self.__debugChildCheckBox.stateChanged.connect(self.__onDebugChild) dbgLayout.addWidget(self.__reportExceptionCheckBox) dbgLayout.addWidget(self.__traceInterpreterCheckBox) dbgLayout.addWidget(self.__stopAtFirstCheckBox) dbgLayout.addWidget(self.__autoforkCheckBox) dbgLayout.addWidget(self.__debugChildCheckBox) return dbgGroupbox @staticmethod def __tuneTable(table): " Sets the common settings for a table " table.setAlternatingRowColors(True) table.setRootIsDecorated(False) table.setItemsExpandable(False) table.setUniformRowHeights(True) table.setSelectionMode(QAbstractItemView.SingleSelection) table.setSelectionBehavior(QAbstractItemView.SelectRows) table.setItemDelegate(NoOutlineHeightDelegate(4)) table.setHeaderLabels(["Variable", "Value"]) header = table.header() header.setSortIndicator(0, Qt.AscendingOrder) header.setSortIndicatorShown(True) header.setClickable(True) table.setSortingEnabled(True) return def __scriptWDirClicked(self): " The script working dir button is clicked " self.__dirEdit.setEnabled(False) self.__dirSelectButton.setEnabled(False) self.runParams.useScriptLocation = True self.__setRunButtonProps() return def __dirClicked(self): " The script specific working dir button is clicked " self.__dirEdit.setEnabled(True) self.__dirSelectButton.setEnabled(True) self.runParams.useScriptLocation = False self.__setRunButtonProps() return def __argsChanged(self, value): " Triggered when cmd line args are changed " value = str(value).strip() self.runParams.arguments = value self.__setRunButtonProps() return def __workingDirChanged(self, value): " Triggered when a working dir value is changed " value = str(value) self.runParams.specificDir = value self.__setRunButtonProps() return def __onCloseChanged(self, state): " Triggered when the close terminal check box changed " self.runParams.closeTerminal = state != 0 return def __onReportExceptionChanged(self, state): " Triggered when exception report check box changed " self.debuggerParams.reportExceptions = state != 0 return def __onTraceInterpreterChanged(self, state): " Triggered when trace interpreter changed " self.debuggerParams.traceInterpreter = state != 0 return def __onStopAtFirstChanged(self, state): " Triggered when stop at first changed " self.debuggerParams.stopAtFirstLine = state != 0 return def __onAutoforkChanged(self, state): " Triggered when autofork changed " self.debuggerParams.autofork = state != 0 self.__debugChildCheckBox.setEnabled(self.debuggerParams.autofork) return def __onDebugChild(self, state): " Triggered when debug child changed " self.debuggerParams.followChild = state != 0 return def __argumentsOK(self): " Returns True if the arguments are OK " try: parseCommandLineArguments(self.runParams.arguments) return True except: return False def __dirOK(self): " Returns True if the working dir is OK " if self.__scriptWDRButton.isChecked(): return True return os.path.isdir(self.__dirEdit.text()) def __setRunButtonProps(self, newText=None): " Enable/disable run button and set its tooltip " if not self.__argumentsOK(): self.__runButton.setEnabled(False) self.__runButton.setToolTip("No closing quotation in arguments") return if not self.__dirOK(): self.__runButton.setEnabled(False) self.__runButton.setToolTip("The given working " "dir is not found") return if self.__nodeLimitEdit is not None: txt = self.__nodeLimitEdit.text().strip() try: value = float(txt) if value < 0.0 or value > 100.0: raise Exception("Out of range") except: self.__runButton.setEnabled(False) self.__runButton.setToolTip("The given node limit " "is out of range") return if self.__edgeLimitEdit is not None: txt = self.__edgeLimitEdit.text().strip() try: value = float(txt) if value < 0.0 or value > 100.0: raise Exception("Out of range") except: self.__runButton.setEnabled(False) self.__runButton.setToolTip("The given edge limit " "is out of range") return self.__runButton.setEnabled(True) self.__runButton.setToolTip("Save parameters and " + self.__action + " script") return def __selectDirClicked(self): " Selects the script working dir " dirName = QFileDialog.getExistingDirectory( self, "Select the script working directory", self.__dirEdit.text(), QFileDialog.Options(QFileDialog.ShowDirsOnly)) if dirName: self.__dirEdit.setText(os.path.normpath(dirName)) return def __inhClicked(self): " Inerit parent env radio button clicked " self.__setEnabledInheritedPlusEnv(False) self.__setEnabledSpecificEnv(False) self.runParams.envType = RunParameters.InheritParentEnv return def __inhPlusClicked(self): " Inherit parent and add radio button clicked " self.__setEnabledInheritedPlusEnv(True) self.__setEnabledSpecificEnv(False) self.runParams.envType = RunParameters.InheritParentEnvPlus if self.__inhPlusEnvTable.selectedIndexes(): self.__delInhButton.setEnabled(True) self.__editInhButton.setEnabled(True) else: self.__delInhButton.setEnabled(False) self.__editInhButton.setEnabled(False) return def __specClicked(self): " Specific env radio button clicked " self.__setEnabledInheritedPlusEnv(False) self.__setEnabledSpecificEnv(True) self.runParams.envType = RunParameters.SpecificEnvironment if self.__specEnvTable.selectedIndexes(): self.__delSpecButton.setEnabled(True) self.__editSpecButton.setEnabled(True) else: self.__delSpecButton.setEnabled(False) self.__editSpecButton.setEnabled(False) return @staticmethod def __delAndInsert(table, name, value): " Deletes an item by name if so; insert new; highlight it " for index in xrange(table.topLevelItemCount()): item = table.topLevelItem(index) if str(item.text(0)) == name: table.takeTopLevelItem(index) break item = QTreeWidgetItem([name, value]) table.addTopLevelItem(item) table.setCurrentItem(item) return item def __addInhClicked(self): " Add env var button clicked " dlg = EnvVarDialog() if dlg.exec_() == QDialog.Accepted: name = str(dlg.name) value = str(dlg.value) self.__delAndInsert(self.__inhPlusEnvTable, name, value) self.runParams.additionToParentEnv[name] = value self.__delInhButton.setEnabled(True) self.__editInhButton.setEnabled(True) return def __addSpecClicked(self): " Add env var button clicked " dlg = EnvVarDialog() if dlg.exec_() == QDialog.Accepted: name = str(dlg.name) value = str(dlg.value) self.__delAndInsert(self.__specEnvTable, name, value) self.runParams.specificEnv[name] = value self.__delSpecButton.setEnabled(True) self.__editSpecButton.setEnabled(True) return def __delInhClicked(self): " Delete the highlighted variable " if self.__inhPlusEnvTable.topLevelItemCount() == 0: return name = self.__inhPlusEnvTable.currentItem().text(0) for index in xrange(self.__inhPlusEnvTable.topLevelItemCount()): item = self.__inhPlusEnvTable.topLevelItem(index) if name == item.text(0): self.__inhPlusEnvTable.takeTopLevelItem(index) break del self.runParams.additionToParentEnv[str(name)] if self.__inhPlusEnvTable.topLevelItemCount() == 0: self.__delInhButton.setEnabled(False) self.__editInhButton.setEnabled(False) else: self.__inhPlusEnvTable.setCurrentItem( \ self.__inhPlusEnvTable.topLevelItem( 0 ) ) return def __delSpecClicked(self): " Delete the highlighted variable " if self.__specEnvTable.topLevelItemCount() == 0: return name = self.__specEnvTable.currentItem().text(0) for index in xrange(self.__specEnvTable.topLevelItemCount()): item = self.__specEnvTable.topLevelItem(index) if name == item.text(0): self.__specEnvTable.takeTopLevelItem(index) break del self.runParams.specificEnv[str(name)] if self.__specEnvTable.topLevelItemCount() == 0: self.__delSpecButton.setEnabled(False) self.__editSpecButton.setEnabled(False) else: self.__specEnvTable.setCurrentItem( \ self.__specEnvTable.topLevelItem( 0 ) ) return def __editInhClicked(self): " Edits the highlighted variable " if self.__inhPlusEnvTable.topLevelItemCount() == 0: return item = self.__inhPlusEnvTable.currentItem() dlg = EnvVarDialog(str(item.text(0)), str(item.text(1)), self) if dlg.exec_() == QDialog.Accepted: name = str(dlg.name) value = str(dlg.value) self.__delAndInsert(self.__inhPlusEnvTable, name, value) self.runParams.additionToParentEnv[name] = value return def __inhPlusItemActivated(self, item, column): " Triggered when a table item is activated " self.__editInhClicked() return def __editSpecClicked(self): " Edits the highlighted variable " if self.__specEnvTable.topLevelItemCount() == 0: return item = self.__specEnvTable.currentItem() dlg = EnvVarDialog(str(item.text(0)), str(item.text(1)), self) if dlg.exec_() == QDialog.Accepted: name = str(dlg.name) value = str(dlg.value) self.__delAndInsert(self.__specEnvTable, name, value) self.runParams.specificEnv[name] = value return def __specItemActivated(self, item, column): " Triggered when a table item is activated " self.__editSpecClicked() return def onAccept(self): " Saves the selected terminal and profiling values " if self.__redirectRButton.isChecked(): self.termType = TERM_REDIRECT elif self.__autoRButton.isChecked(): self.termType = TERM_AUTO elif self.__konsoleRButton.isChecked(): self.termType = TERM_KONSOLE elif self.__gnomeRButton.isChecked(): self.termType = TERM_GNOME else: self.termType = TERM_XTERM if self.__action == "profile": self.profilerParams.nodeLimit = float(self.__nodeLimitEdit.text()) self.profilerParams.edgeLimit = float(self.__edgeLimitEdit.text()) self.accept() return
class FindOptions(QWidget): """ Find widget with options """ def __init__(self, parent, search_text, search_text_regexp, search_path, include, include_regexp, exclude, exclude_regexp, supported_encodings): QWidget.__init__(self, parent) if search_path is None: search_path = os.getcwdu() if not isinstance(search_text, (list, tuple)): search_text = [search_text] if not isinstance(search_path, (list, tuple)): search_path = [search_path] if not isinstance(include, (list, tuple)): include = [include] if not isinstance(exclude, (list, tuple)): exclude = [exclude] self.supported_encodings = supported_encodings # Layout 1 hlayout1 = QHBoxLayout() self.search_text = PatternComboBox(self, search_text, translate('FindInFiles', "Search pattern")) search_label = QLabel(translate('FindInFiles', "Search text:")) search_label.setBuddy(self.search_text) self.edit_regexp = create_toolbutton(self, get_icon("advanced.png"), tip=translate('FindInFiles', "Regular expression")) self.edit_regexp.setCheckable(True) self.edit_regexp.setChecked(search_text_regexp) self.ok_button = create_toolbutton(self, text=translate('FindInFiles', "Search"), triggered=lambda: self.emit(SIGNAL('find()')), icon=get_std_icon("DialogApplyButton"), tip=translate('FindInFiles', "Start search")) self.connect(self.ok_button, SIGNAL('clicked()'), self.update_combos) self.stop_button = create_toolbutton(self, text=translate('FindInFiles', "Stop"), triggered=lambda: self.emit(SIGNAL('stop()')), icon=get_icon("terminate.png"), tip=translate('FindInFiles', "Stop search")) self.stop_button.setEnabled(False) for widget in [search_label, self.search_text, self.edit_regexp, self.ok_button, self.stop_button]: hlayout1.addWidget(widget) # Layout 2 hlayout2 = QHBoxLayout() self.include_pattern = PatternComboBox(self, include, translate('FindInFiles', "Included filenames pattern")) self.include_regexp = create_toolbutton(self, get_icon("advanced.png"), tip=translate('FindInFiles', "Regular expression")) self.include_regexp.setCheckable(True) self.include_regexp.setChecked(include_regexp) include_label = QLabel(translate('FindInFiles', "Include:")) include_label.setBuddy(self.include_pattern) self.exclude_pattern = PatternComboBox(self, exclude, translate('FindInFiles', "Excluded filenames pattern")) self.exclude_regexp = create_toolbutton(self, get_icon("advanced.png"), tip=translate('FindInFiles', "Regular expression")) self.exclude_regexp.setCheckable(True) self.exclude_regexp.setChecked(exclude_regexp) exclude_label = QLabel(translate('FindInFiles', "Exclude:")) exclude_label.setBuddy(self.exclude_pattern) for widget in [include_label, self.include_pattern, self.include_regexp, exclude_label, self.exclude_pattern, self.exclude_regexp]: hlayout2.addWidget(widget) # Layout 3 hlayout3 = QHBoxLayout() searchin_label = QLabel(translate('FindInFiles', "Search in:")) self.python_path = QRadioButton(translate('FindInFiles', "PYTHONPATH"), self) self.python_path.setToolTip(translate('FindInFiles', "Search in all directories listed in sys.path which" " are outside the Python installation directory")) self.hg_manifest = QRadioButton(translate('FindInFiles', "Hg repository"), self) self.detect_hg_repository() self.hg_manifest.setToolTip(translate('FindInFiles', "Search in current directory hg repository")) searchin_label.setBuddy(self.hg_manifest) self.custom_dir = QRadioButton(translate('FindInFiles', "Directory:"), self) self.custom_dir.setChecked(True) self.dir_combo = PathComboBox(self) self.dir_combo.addItems(search_path) self.dir_combo.setToolTip(translate('FindInFiles', "Search recursively in this directory")) self.connect(self.dir_combo, SIGNAL("open_dir(QString)"), self.set_directory) self.connect(self.python_path, SIGNAL('toggled(bool)'), self.dir_combo.setDisabled) self.connect(self.hg_manifest, SIGNAL('toggled(bool)'), self.dir_combo.setDisabled) browse = create_toolbutton(self, get_std_icon('DirOpenIcon'), tip=translate('FindInFiles', 'Browse a search directory'), triggered=self.select_directory) for widget in [searchin_label, self.python_path, self.hg_manifest, self.custom_dir, self.dir_combo, browse]: hlayout3.addWidget(widget) vlayout = QVBoxLayout() vlayout.addLayout(hlayout1) vlayout.addLayout(hlayout2) vlayout.addLayout(hlayout3) self.setLayout(vlayout) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum) def update_combos(self): self.search_text.lineEdit().emit(SIGNAL('returnPressed()')) self.include_pattern.lineEdit().emit(SIGNAL('returnPressed()')) self.exclude_pattern.lineEdit().emit(SIGNAL('returnPressed()')) def detect_hg_repository(self, path=None): if path is None: path = os.getcwdu() hg_repository = is_hg_installed() and get_hg_root(path) is not None self.hg_manifest.setEnabled(hg_repository) if not hg_repository and self.hg_manifest.isChecked(): self.custom_dir.setChecked(True) def set_search_text(self, text): self.search_text.setEditText(text) self.search_text.lineEdit().selectAll() self.search_text.setFocus() def get_options(self, all=False): # Getting options utext = unicode(self.search_text.currentText()) if not utext: return try: texts = [str(utext)] except UnicodeDecodeError: texts = [] for encoding in self.supported_encodings: try: texts.append( utext.encode(encoding) ) except UnicodeDecodeError: pass text_re = self.edit_regexp.isChecked() include = unicode(self.include_pattern.currentText()) include_re = self.include_regexp.isChecked() exclude = unicode(self.exclude_pattern.currentText()) exclude_re = self.exclude_regexp.isChecked() python_path = self.python_path.isChecked() hg_manifest = self.hg_manifest.isChecked() path = osp.abspath( unicode( self.dir_combo.currentText() ) ) # Finding text occurences if not include_re: include = fnmatch.translate(include) if not exclude_re: exclude = fnmatch.translate(exclude) if all: search_text = [unicode(self.search_text.itemText(index)) \ for index in range(self.search_text.count())] search_path = [unicode(self.dir_combo.itemText(index)) \ for index in range(self.dir_combo.count())] include = [unicode(self.include_pattern.itemText(index)) \ for index in range(self.include_pattern.count())] exclude = [unicode(self.exclude_pattern.itemText(index)) \ for index in range(self.exclude_pattern.count())] return (search_text, text_re, search_path, include, include_re, exclude, exclude_re) else: return (path, python_path, hg_manifest, include, exclude, texts, text_re) def select_directory(self): """Select directory""" self.parent().emit(SIGNAL('redirect_stdio(bool)'), False) directory = QFileDialog.getExistingDirectory(self, translate('FindInFiles', "Select directory"), self.dir_combo.currentText()) if not directory.isEmpty(): self.set_directory(directory) self.parent().emit(SIGNAL('redirect_stdio(bool)'), True) def set_directory(self, directory): path = unicode(osp.abspath(unicode(directory))) self.dir_combo.setEditText(path) self.detect_hg_repository(path) def keyPressEvent(self, event): """Reimplemented to handle key events""" ctrl = event.modifiers() & Qt.ControlModifier shift = event.modifiers() & Qt.ShiftModifier if event.key() in (Qt.Key_Enter, Qt.Key_Return): self.emit(SIGNAL('find()')) elif event.key() == Qt.Key_F and ctrl and shift: # Toggle find widgets self.parent().emit(SIGNAL('toggle_visibility(bool)'), not self.isVisible()) event.accept() else: event.ignore()
class FindInFilesDialog(QDialog, object): """ find in files dialog implementation """ inProject = 0 inDirectory = 1 inOpenFiles = 2 def __init__(self, where, what="", dirPath="", filters=[], parent=None): QDialog.__init__(self, parent) mainWindow = GlobalData().mainWindow self.editorsManager = mainWindow.editorsManagerWidget.editorsManager self.__cancelRequest = False self.__inProgress = False self.searchRegexp = None self.searchResults = [] # Avoid pylint complains self.findCombo = None self.caseCheckBox = None self.wordCheckBox = None self.regexpCheckBox = None self.projectRButton = None self.openFilesRButton = None self.dirRButton = None self.dirEditCombo = None self.dirSelectButton = None self.filterCombo = None self.fileLabel = None self.progressBar = None self.findButton = None self.__createLayout() self.setWindowTitle("Find in files") # Restore the combo box values project = GlobalData().project if project.fileName != "": self.findFilesWhat = project.findFilesWhat self.findFilesDirs = project.findFilesDirs self.findFilesMasks = project.findFilesMasks else: settings = Settings() self.findFilesWhat = settings.findFilesWhat self.findFilesDirs = settings.findFilesDirs self.findFilesMasks = settings.findFilesMasks self.findCombo.addItems(self.findFilesWhat) self.findCombo.setEditText("") self.dirEditCombo.addItems(self.findFilesDirs) self.dirEditCombo.setEditText("") self.filterCombo.addItems(self.findFilesMasks) self.filterCombo.setEditText("") if where == self.inProject: self.setSearchInProject(what, filters) elif where == self.inDirectory: self.setSearchInDirectory(what, dirPath, filters) else: self.setSearchInOpenFiles(what, filters) return def __createLayout(self): """ Creates the dialog layout """ self.resize(600, 300) self.setSizeGripEnabled(True) verticalLayout = QVBoxLayout(self) gridLayout = QGridLayout() # Combo box for the text to search findLabel = QLabel(self) findLabel.setText("Find text:") self.findCombo = QComboBox(self) self.__tuneCombo(self.findCombo) self.findCombo.lineEdit().setToolTip( "Regular expression to search for") self.findCombo.editTextChanged.connect(self.__someTextChanged) gridLayout.addWidget(findLabel, 0, 0, 1, 1) gridLayout.addWidget(self.findCombo, 0, 1, 1, 1) verticalLayout.addLayout(gridLayout) # Check boxes horizontalCBLayout = QHBoxLayout() self.caseCheckBox = QCheckBox(self) self.caseCheckBox.setText("Match &case") horizontalCBLayout.addWidget(self.caseCheckBox) self.wordCheckBox = QCheckBox(self) self.wordCheckBox.setText("Match whole &word") horizontalCBLayout.addWidget(self.wordCheckBox) self.regexpCheckBox = QCheckBox(self) self.regexpCheckBox.setText("Regular &expression") horizontalCBLayout.addWidget(self.regexpCheckBox) verticalLayout.addLayout(horizontalCBLayout) # Files groupbox filesGroupbox = QGroupBox(self) filesGroupbox.setTitle("Find in") sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( filesGroupbox.sizePolicy().hasHeightForWidth()) filesGroupbox.setSizePolicy(sizePolicy) gridLayoutFG = QGridLayout(filesGroupbox) self.projectRButton = QRadioButton(filesGroupbox) self.projectRButton.setText("&Project") gridLayoutFG.addWidget(self.projectRButton, 0, 0) self.projectRButton.clicked.connect(self.__projectClicked) self.openFilesRButton = QRadioButton(filesGroupbox) self.openFilesRButton.setText("&Opened files only") gridLayoutFG.addWidget(self.openFilesRButton, 1, 0) self.openFilesRButton.clicked.connect(self.__openFilesOnlyClicked) self.dirRButton = QRadioButton(filesGroupbox) self.dirRButton.setText("&Directory tree") gridLayoutFG.addWidget(self.dirRButton, 2, 0) self.dirRButton.clicked.connect(self.__dirClicked) self.dirEditCombo = QComboBox(filesGroupbox) self.__tuneCombo(self.dirEditCombo) self.dirEditCombo.lineEdit().setToolTip("Directory to search in") gridLayoutFG.addWidget(self.dirEditCombo, 2, 1) self.dirEditCombo.editTextChanged.connect(self.__someTextChanged) self.dirSelectButton = QPushButton(filesGroupbox) self.dirSelectButton.setText("...") gridLayoutFG.addWidget(self.dirSelectButton, 2, 2) self.dirSelectButton.clicked.connect(self.__selectDirClicked) filterLabel = QLabel(filesGroupbox) filterLabel.setText("Files filter:") gridLayoutFG.addWidget(filterLabel, 3, 0) self.filterCombo = QComboBox(filesGroupbox) self.__tuneCombo(self.filterCombo) self.filterCombo.lineEdit().setToolTip("File names regular expression") gridLayoutFG.addWidget(self.filterCombo, 3, 1) self.filterCombo.editTextChanged.connect(self.__someTextChanged) verticalLayout.addWidget(filesGroupbox) # File label self.fileLabel = FitPathLabel(self) self.fileLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) verticalLayout.addWidget(self.fileLabel) # Progress bar self.progressBar = QProgressBar(self) self.progressBar.setValue(0) self.progressBar.setOrientation(Qt.Horizontal) verticalLayout.addWidget(self.progressBar) # Buttons at the bottom buttonBox = QDialogButtonBox(self) buttonBox.setOrientation(Qt.Horizontal) buttonBox.setStandardButtons(QDialogButtonBox.Cancel) self.findButton = buttonBox.addButton("Find", QDialogButtonBox.AcceptRole) self.findButton.setDefault(True) self.findButton.clicked.connect(self.__process) verticalLayout.addWidget(buttonBox) buttonBox.rejected.connect(self.__onClose) return @staticmethod def __tuneCombo(comboBox): " Sets the common settings for a combo box " sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( \ comboBox.sizePolicy().hasHeightForWidth() ) comboBox.setSizePolicy(sizePolicy) comboBox.setEditable(True) comboBox.setInsertPolicy(QComboBox.InsertAtTop) comboBox.setAutoCompletion(False) comboBox.setDuplicatesEnabled(False) return def __onClose(self): " Triggered when the close button is clicked " self.__cancelRequest = True if not self.__inProgress: self.close() return def setSearchInProject(self, what="", filters=[]): " Set search ready for the whole project " if GlobalData().project.fileName == "": # No project loaded, fallback to opened files self.setSearchInOpenFiles(what, filters) return # Select the project radio button self.projectRButton.setEnabled(True) self.projectRButton.setChecked(True) self.dirEditCombo.setEnabled(False) self.dirSelectButton.setEnabled(False) openedFiles = self.editorsManager.getTextEditors() self.openFilesRButton.setEnabled(len(openedFiles) != 0) self.setFilters(filters) self.findCombo.setEditText(what) self.findCombo.lineEdit().selectAll() self.findCombo.setFocus() # Check searchability self.__testSearchability() return def setSearchInOpenFiles(self, what="", filters=[]): " Sets search ready for the opened files " openedFiles = self.editorsManager.getTextEditors() if len(openedFiles) == 0: # No opened files, fallback to search in dir self.setSearchInDirectory(what, "", filters) return # Select the radio buttons self.projectRButton.setEnabled(GlobalData().project.fileName != "") self.openFilesRButton.setEnabled(True) self.openFilesRButton.setChecked(True) self.dirEditCombo.setEnabled(False) self.dirSelectButton.setEnabled(False) self.setFilters(filters) self.findCombo.setEditText(what) self.findCombo.lineEdit().selectAll() self.findCombo.setFocus() # Check searchability self.__testSearchability() return def setSearchInDirectory(self, what="", dirPath="", filters=[]): " Sets search ready for the given directory " # Select radio buttons self.projectRButton.setEnabled(GlobalData().project.fileName != "") openedFiles = self.editorsManager.getTextEditors() self.openFilesRButton.setEnabled(len(openedFiles) != 0) self.dirRButton.setEnabled(True) self.dirRButton.setChecked(True) self.dirEditCombo.setEnabled(True) self.dirSelectButton.setEnabled(True) self.dirEditCombo.setEditText(dirPath) self.setFilters(filters) self.findCombo.setEditText(what) self.findCombo.lineEdit().selectAll() self.findCombo.setFocus() # Check searchability self.__testSearchability() return def setFilters(self, filters): " Sets up the filters " # Set filters if provided if filters: self.filterCombo.setEditText(";".join(filters)) else: self.filterCombo.setEditText("") return def __testSearchability(self): " Tests the searchability and sets the Find button status " startTime = time.time() if self.findCombo.currentText().strip() == "": self.findButton.setEnabled(False) self.findButton.setToolTip("No text to search") return if self.dirRButton.isChecked(): dirname = self.dirEditCombo.currentText().strip() if dirname == "": self.findButton.setEnabled(False) self.findButton.setToolTip("No directory path") return if not os.path.isdir(dirname): self.findButton.setEnabled(False) self.findButton.setToolTip("Path is not a directory") return # Now we need to match file names if there is a filter filtersText = self.filterCombo.currentText().strip() if filtersText == "": self.findButton.setEnabled(True) self.findButton.setToolTip("Find in files") return # Need to check the files match try: filterRe = re.compile(filtersText, re.IGNORECASE) except: self.findButton.setEnabled(False) self.findButton.setToolTip( "Incorrect files " \ "filter regular expression" ) return matched = False tooLong = False if self.projectRButton.isChecked(): # Whole project for fname in GlobalData().project.filesList: if fname.endswith(sep): continue matched = filterRe.match(fname) if matched: break # Check the time, it might took too long if time.time() - startTime > 0.1: tooLong = True break elif self.openFilesRButton.isChecked(): # Opened files openedFiles = self.editorsManager.getTextEditors() for record in openedFiles: matched = filterRe.match(record[1]) if matched: break # Check the time, it might took too long if time.time() - startTime > 0.1: tooLong = True break else: # Search in the dir if not dirname.endswith(sep): dirname += sep matched, tooLong = self.__matchInDir(dirname, filterRe, startTime) if matched: self.findButton.setEnabled(True) self.findButton.setToolTip("Find in files") else: if tooLong: self.findButton.setEnabled(True) self.findButton.setToolTip("Find in files") else: self.findButton.setEnabled(False) self.findButton.setToolTip("No files matched to search in") return @staticmethod def __matchInDir(path, filterRe, startTime): " Provides the 'match' and 'too long' statuses " matched = False tooLong = False for item in os.listdir(path): if time.time() - startTime > 0.1: tooLong = True return matched, tooLong if os.path.isdir(path + item): dname = path + item + sep matched, tooLong = FindInFilesDialog.__matchInDir( dname, filterRe, startTime) if matched or tooLong: return matched, tooLong continue if filterRe.match(path + item): matched = True return matched, tooLong return matched, tooLong def __projectClicked(self): " project radio button clicked " self.dirEditCombo.setEnabled(False) self.dirSelectButton.setEnabled(False) self.__testSearchability() return def __openFilesOnlyClicked(self): " open files only radio button clicked " self.dirEditCombo.setEnabled(False) self.dirSelectButton.setEnabled(False) self.__testSearchability() return def __dirClicked(self): " dir radio button clicked " self.dirEditCombo.setEnabled(True) self.dirSelectButton.setEnabled(True) self.dirEditCombo.setFocus() self.__testSearchability() return def __someTextChanged(self, text): " Text to search, filter or dir name has been changed " self.__testSearchability() return def __selectDirClicked(self): " The user selects a directory " dirName = QFileDialog.getExistingDirectory( self, "Select directory to search in", self.dirEditCombo.currentText(), QFileDialog.Options(QFileDialog.ShowDirsOnly)) if dirName: self.dirEditCombo.setEditText(os.path.normpath(dirName)) self.__testSearchability() return def __projectFiles(self, filterRe): " Project files list respecting the mask " mainWindow = GlobalData().mainWindow files = [] for fname in GlobalData().project.filesList: if fname.endswith(sep): continue if filterRe is None or filterRe.match(fname): widget = mainWindow.getWidgetForFileName(fname) if widget is None: # Do not check for broken symlinks if isFileSearchable(fname, False): files.append(ItemToSearchIn(fname, "")) else: if widget.getType() in \ [ MainWindowTabWidgetBase.PlainTextEditor ]: files.append(ItemToSearchIn(fname, widget.getUUID())) QApplication.processEvents() if self.__cancelRequest: raise Exception("Cancel request") return files def __openedFiles(self, filterRe): " Currently opened editor buffers " files = [] openedFiles = self.editorsManager.getTextEditors() for record in openedFiles: uuid = record[0] fname = record[1] if filterRe is None or filterRe.match(fname): files.append(ItemToSearchIn(fname, uuid)) QApplication.processEvents() if self.__cancelRequest: raise Exception("Cancel request") return files def __dirFiles(self, path, filterRe, files): " Files recursively for the dir " for item in os.listdir(path): QApplication.processEvents() if self.__cancelRequest: raise Exception("Cancel request") if os.path.isdir(path + item): if item in [".svn", ".cvs"]: # It does not make sense to search in revision control dirs continue anotherDir, isLoop = resolveLink(path + item) if not isLoop: self.__dirFiles(anotherDir + sep, filterRe, files) continue if not os.path.isfile(path + item): continue realItem, isLoop = resolveLink(path + item) if isLoop: continue if filterRe is None or filterRe.match(realItem): found = False for itm in files: if itm.fileName == realItem: found = True break if not found: mainWindow = GlobalData().mainWindow widget = mainWindow.getWidgetForFileName(realItem) if widget is None: if isFileSearchable(realItem): files.append(ItemToSearchIn(realItem, "")) else: if widget.getType() in \ [ MainWindowTabWidgetBase.PlainTextEditor ]: files.append( ItemToSearchIn(realItem, widget.getUUID())) return def __buildFilesList(self): " Builds the list of files to search in " filtersText = self.filterCombo.currentText().strip() if filtersText != "": filterRe = re.compile(filtersText, re.IGNORECASE) else: filterRe = None if self.projectRButton.isChecked(): return self.__projectFiles(filterRe) if self.openFilesRButton.isChecked(): return self.__openedFiles(filterRe) dirname = os.path.realpath(self.dirEditCombo.currentText().strip()) files = [] self.__dirFiles(dirname + sep, filterRe, files) return files def __process(self): " Search process " # Add entries to the combo box if required regexpText = self.findCombo.currentText() if regexpText in self.findFilesWhat: self.findFilesWhat.remove(regexpText) self.findFilesWhat.insert(0, regexpText) if len(self.findFilesWhat) > 32: self.findFilesWhat = self.findFilesWhat[:32] self.findCombo.clear() self.findCombo.addItems(self.findFilesWhat) filtersText = self.filterCombo.currentText().strip() if filtersText in self.findFilesMasks: self.findFilesMasks.remove(filtersText) self.findFilesMasks.insert(0, filtersText) if len(self.findFilesMasks) > 32: self.findFilesMasks = self.findFilesMasks[:32] self.filterCombo.clear() self.filterCombo.addItems(self.findFilesMasks) if self.dirRButton.isChecked(): dirText = self.dirEditCombo.currentText().strip() if dirText in self.findFilesDirs: self.findFilesDirs.remove(dirText) self.findFilesDirs.insert(0, dirText) if len(self.findFilesDirs) > 32: self.findFilesDirs = self.findFilesDirs[:32] self.dirEditCombo.clear() self.dirEditCombo.addItems(self.findFilesDirs) # Save the combo values for further usage if GlobalData().project.fileName != "": GlobalData().project.setFindInFilesHistory(self.findFilesWhat, self.findFilesDirs, self.findFilesMasks) else: Settings().findFilesWhat = self.findFilesWhat Settings().findFilesDirs = self.findFilesDirs Settings().findFilesMasks = self.findFilesMasks self.__inProgress = True numberOfMatches = 0 self.searchResults = [] self.searchRegexp = None # Form the regexp to search if not self.regexpCheckBox.isChecked(): regexpText = re.escape(regexpText) if self.wordCheckBox.isChecked(): regexpText = "\\b%s\\b" % regexpText flags = re.UNICODE | re.LOCALE if not self.caseCheckBox.isChecked(): flags |= re.IGNORECASE try: self.searchRegexp = re.compile(regexpText, flags) except: logging.error("Invalid search expression") self.close() return QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.fileLabel.setPath('Building list of files to search in...') QApplication.processEvents() try: files = self.__buildFilesList() except Exception, exc: if "Cancel request" in str(exc): QApplication.restoreOverrideCursor() self.close() return else: QApplication.restoreOverrideCursor() logging.error(str(exc)) self.close() return QApplication.restoreOverrideCursor() QApplication.processEvents() if len(files) == 0: self.fileLabel.setPath('No files to search in') return self.progressBar.setRange(0, len(files)) index = 1 for item in files: if self.__cancelRequest: self.__inProgress = False self.close() return self.fileLabel.setPath( 'Matches: ' + str( numberOfMatches ) + \ ' Processing: ' + item.fileName ) item.search(self.searchRegexp) found = len(item.matches) if found > 0: numberOfMatches += found self.searchResults.append(item) self.progressBar.setValue(index) index += 1 QApplication.processEvents() if numberOfMatches == 0: if len(files) == 1: self.fileLabel.setPath("No matches in 1 file.") else: self.fileLabel.setPath( "No matches in " + \ str( len( files ) ) + " files." ) self.__inProgress = False else: self.close() return
class ShortcutEditDialog(QDialog): """A modal dialog to view and/or edit keyboard shortcuts.""" def __init__(self, parent=None, conflictCallback=None, *cbArgs): """conflictCallback is a optional method called when a shortcut is changed. cbArgs is optional arguments of the conflictCallback method. it should return the name of the potential conflict or a null value """ super(ShortcutEditDialog, self).__init__(parent) self.conflictCallback = conflictCallback self.cbArgs = cbArgs self.setMinimumWidth(400) # create gui layout = QVBoxLayout() layout.setSpacing(10) self.setLayout(layout) top = QHBoxLayout() top.setSpacing(4) p = self.toppixmap = QLabel() l = self.toplabel = QLabel() top.addWidget(p) top.addWidget(l, 1) layout.addLayout(top) grid = QGridLayout() grid.setSpacing(4) grid.setColumnStretch(1, 2) layout.addLayout(grid) self.buttonDefault = QRadioButton(self, toggled=self.slotButtonDefaultToggled) self.buttonNone = QRadioButton(self) self.lconflictDefault = QLabel('test') self.lconflictDefault.setStyleSheet("color : red;") self.lconflictDefault.setVisible(False) self.buttonCustom = QRadioButton(self) grid.addWidget(self.buttonDefault, 0, 0, 1, 2) grid.addWidget(self.lconflictDefault, 1, 0, 1, 2) grid.addWidget(self.buttonNone, 2, 0, 1, 2) grid.addWidget(self.buttonCustom, 3, 0, 1, 2) self.keybuttons = [] self.keylabels = [] self.conflictlabels = [] for num in range(4): l = QLabel(self) l.setStyleSheet("margin-left: 2em;") l.setAlignment(Qt.AlignRight | Qt.AlignVCenter) b = KeySequenceWidget(self, num) b.keySequenceChanged.connect(self.slotKeySequenceChanged) l.setBuddy(b) self.keylabels.append(l) self.keybuttons.append(b) grid.addWidget(l, num+4+num, 0) grid.addWidget(b, num+4+num, 1) lconflict = QLabel() lconflict.setStyleSheet("color : red;") self.conflictlabels.append(lconflict) lconflict.setVisible(False) grid.addWidget(lconflict, num+5+num, 0, 1, 2, Qt.AlignHCenter) layout.addWidget(Separator(self)) b = QDialogButtonBox(self) b.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) layout.addWidget(b) b.accepted.connect(self.accept) b.rejected.connect(self.reject) app.translateUI(self) def translateUI(self): self.setWindowTitle(app.caption(_("window title", "Edit Shortcut"))) self.buttonNone.setText(_("&No shortcut")) self.buttonCustom.setText(_("Use a &custom shortcut:")) for num in range(4): self.keylabels[num].setText(_("Alternative #{num}:").format(num=num) if num else _("Primary shortcut:")) def slotKeySequenceChanged(self, num): """Called when one of the keysequence buttons has changed.""" self.checkConflict(num) self.buttonCustom.setChecked(True) def slotButtonDefaultToggled(self, val): if self.conflictCallback is not None: if not val: self.lconflictDefault.setVisible(False) else: if self._default: conflictList = [] for s in self._default: conflictName = self.conflictCallback(s, *self.cbArgs) if conflictName: conflictList.append(conflictName) if conflictList: text = _("Conflict with: {name}").format( name="<b>{0}</b>".format(', '.join(conflictList))) self.lconflictDefault.setText(text) self.lconflictDefault.setVisible(True) QTimer.singleShot(0, self.adjustSize) def checkConflict(self, num): if self.conflictCallback is not None: conflictName = self.conflictCallback(self.keybuttons[num].shortcut(), *self.cbArgs) if conflictName: text = _("Conflict with: {name}").format( name="<b>{0}</b>".format(conflictName)) self.conflictlabels[num].setText(text) self.conflictlabels[num].setVisible(True) else: self.conflictlabels[num].setVisible(False) QTimer.singleShot(0, self.adjustSize) def editAction(self, action, default=None): # load the action self._action = action self._default = default self.toplabel.setText('<p>{0}</p>'.format( _("Here you can edit the shortcuts for {name}").format( name='<br/><b>{0}</b>:'.format(action.text())))) self.toppixmap.setPixmap(action.icon().pixmap(32)) shortcuts = action.shortcuts() self.buttonDefault.setVisible(bool(default)) if default is not None and shortcuts == default: self.buttonDefault.setChecked(True) else: if shortcuts: self.buttonCustom.setChecked(True) for num, key in enumerate(shortcuts[:4]): self.keybuttons[num].setShortcut(key) self.checkConflict(num) else: self.buttonNone.setChecked(True) if default: ds = "; ".join(key.toString(QKeySequence.NativeText) for key in default) else: ds = _("no keyboard shortcut", "none") self.buttonDefault.setText(_("Use &default shortcut ({name})").format(name=ds)) return self.exec_() def done(self, result): if result: shortcuts = [] if self.buttonDefault.isChecked(): shortcuts = self._default elif self.buttonCustom.isChecked(): for num in range(4): seq = self.keybuttons[num].shortcut() if not seq.isEmpty(): shortcuts.append(seq) self._action.setShortcuts(shortcuts) super(ShortcutEditDialog, self).done(result)
class FindInFilesDialog(QDialog): """Dialog to configure and trigger the search in the files.""" def __init__(self, result_widget, parent): super(FindInFilesDialog, self).__init__(parent) self._find_thread = FindInFilesThread() self.setWindowTitle("Find in files") self.resize(400, 300) #MAIN LAYOUT main_vbox = QVBoxLayout(self) self.pattern_line_edit = QLineEdit() self.dir_name_root = None self.user_home = os.path.expanduser('~') self.dir_combo = QComboBox() self.dir_combo.addItem(self.user_home) self.dir_combo.setEditable(True) self.open_button = QPushButton(QIcon(":img/find"), self.tr("Open")) self.filters_line_edit = QLineEdit("*.py") self.replace_line = QLineEdit() self.replace_line.setEnabled(False) self.check_replace = QCheckBox(self.tr("Replace: ")) self.case_checkbox = QCheckBox(self.tr("C&ase sensitive")) self.type_checkbox = QCheckBox(self.tr("R&egular Expression")) self.recursive_checkbox = QCheckBox(self.tr("Rec&ursive")) self.recursive_checkbox.setCheckState(Qt.Checked) self.phrase_radio = QRadioButton( self.tr("Search by Phrase (Exact Match).")) self.phrase_radio.setChecked(True) self.words_radio = QRadioButton( self.tr("Search for all the words " "(anywhere in the document, not together).")) self.find_button = QPushButton(self.tr("Find!")) self.find_button.setMaximumWidth(150) self.cancel_button = QPushButton(self.tr("Cancel")) self.cancel_button.setMaximumWidth(150) self.result_widget = result_widget hbox = QHBoxLayout() hbox.addWidget(self.find_button) hbox.addWidget(self.cancel_button) #main section find_group_box = QGroupBox(self.tr("Main")) grid = QGridLayout() grid.addWidget(QLabel(self.tr("Text: ")), 0, 0) grid.addWidget(self.pattern_line_edit, 0, 1) grid.addWidget(QLabel(self.tr("Directory: ")), 1, 0) grid.addWidget(self.dir_combo, 1, 1) grid.addWidget(self.open_button, 1, 2) grid.addWidget(QLabel(self.tr("Filter: ")), 2, 0) grid.addWidget(self.filters_line_edit, 2, 1) grid.addWidget(self.check_replace, 3, 0) grid.addWidget(self.replace_line, 3, 1) find_group_box.setLayout(grid) #add main section to MAIN LAYOUT main_vbox.addWidget(find_group_box) #options sections options_group_box = QGroupBox(self.tr("Options")) gridOptions = QGridLayout() gridOptions.addWidget(self.case_checkbox, 0, 0) gridOptions.addWidget(self.type_checkbox, 1, 0) gridOptions.addWidget(self.recursive_checkbox, 2, 0) gridOptions.addWidget(self.phrase_radio, 0, 1) gridOptions.addWidget(self.words_radio, 1, 1) options_group_box.setLayout(gridOptions) #add options sections to MAIN LAYOUT main_vbox.addWidget(options_group_box) #add buttons to MAIN LAYOUT main_vbox.addLayout(hbox) #Focus self.pattern_line_edit.setFocus() self.open_button.setFocusPolicy(Qt.NoFocus) #signal self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir) self.connect(self.find_button, SIGNAL("clicked()"), self._find_in_files) self.connect(self.cancel_button, SIGNAL("clicked()"), self._kill_thread) self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"), self._found_match) self.connect(self._find_thread, SIGNAL("finished()"), self._find_thread_finished) self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"), self._change_radio_enabled) self.connect(self.check_replace, SIGNAL("stateChanged(int)"), self._replace_activated) self.connect(self.words_radio, SIGNAL("clicked(bool)"), self._words_radio_pressed) def _replace_activated(self): """If replace is activated, display the replace widgets.""" self.replace_line.setEnabled(self.check_replace.isChecked()) self.phrase_radio.setChecked(True) def _words_radio_pressed(self, value): """If search by independent words is activated, replace is not.""" self.replace_line.setEnabled(not value) self.check_replace.setChecked(not value) self.words_radio.setChecked(True) def _change_radio_enabled(self, val): """Control the state of the radio buttons.""" enabled = not self.type_checkbox.isChecked() self.phrase_radio.setEnabled(enabled) self.words_radio.setEnabled(enabled) def show(self, actual_project=None, actual=None): """Display the dialog and load the projects.""" self.dir_combo.clear() self.dir_name_root = actual_project if \ actual_project else [self.user_home] self.dir_combo.addItems(self.dir_name_root) if actual: index = self.dir_combo.findText(actual) self.dir_combo.setCurrentIndex(index) super(FindInFilesDialog, self).show() self.pattern_line_edit.setFocus() def reject(self): """Close the dialog and hide the tools dock.""" self._kill_thread() tools_dock = IDE.get_service('tools_dock') if tools_dock: tools_dock.hide() super(FindInFilesDialog, self).reject() def _find_thread_finished(self): """Wait on thread finished.""" self.emit(SIGNAL("finished()")) self._find_thread.wait() def _select_dir(self): """When a new folder is selected, add to the combo if needed.""" dir_name = QFileDialog.getExistingDirectory( self, self.tr("Open Directory"), self.dir_combo.currentText(), QFileDialog.ShowDirsOnly) index = self.dir_combo.findText(dir_name) if index >= 0: self.dir_combo.setCurrentIndex(index) else: self.dir_combo.insertItem(0, dir_name) self.dir_combo.setCurrentIndex(0) def _found_match(self, result): """Update the tree for each match found.""" file_name = result[0] items = result[1] self.result_widget.update_result(self.dir_combo.currentText(), file_name, items) def _kill_thread(self): """Kill the thread.""" if self._find_thread.isRunning(): self._find_thread.cancel() self.accept() def _find_in_files(self): """Trigger the search on the files.""" self.emit(SIGNAL("findStarted()")) self._kill_thread() self.result_widget.clear() pattern = self.pattern_line_edit.text() dir_name = self.dir_combo.currentText() filters = re.split("[,;]", self.filters_line_edit.text()) #remove the spaces in the words Ex. (" *.foo"--> "*.foo") filters = [f.strip() for f in filters] case_sensitive = self.case_checkbox.isChecked() type_ = QRegExp.RegExp if \ self.type_checkbox.isChecked() else QRegExp.FixedString recursive = self.recursive_checkbox.isChecked() by_phrase = True if self.phrase_radio.isChecked() or self.type_checkbox.isChecked(): regExp = QRegExp(pattern, case_sensitive, type_) elif self.words_radio.isChecked(): by_phrase = False type_ = QRegExp.RegExp pattern = '|'.join([word.strip() for word in pattern.split()]) regExp = QRegExp(pattern, case_sensitive, type_) #save a reference to the root directory where we find self.dir_name_root = dir_name self._find_thread.find_in_files(dir_name, filters, regExp, recursive, by_phrase)
class UserDialog(QDialog): holdc = {} def __init__(self, parent=None): super(UserDialog, self).__init__(parent) self.pagetitle = self.sessionname self.tableFont = QFont('Century Gothic', 8) self.table = QTableWidget() self.cols = [ 'SN', 'ITEM', 'QUANTITY', 'UNIT AMOUNT', 'TOTAL AMOUNT', 'DATE' ] self.h1_pull_box = QVBoxLayout() #self.tableFont.setFamily('Century Gothic') self.tableHeaderStyle = "::section {" "background-color: teal; color:white}" #pull all CA self.editID = 0 self.hold_unit = {} self.hold_store = {} self.hold_storeGroup = {} self.hold_borrowed = {} from_label = QLabel('From:') to_label = QLabel('To:') self.fromData = QDateEdit() self.toData = QDateEdit() currentDate = QDate() self.fromData.setDate(currentDate.currentDate()) self.fromData.setCalendarPopup(True) self.toData.setDate(currentDate.currentDate()) self.toData.setCalendarPopup(True) menu = QMenu() menu.addAction('All', lambda: self.reloadTable(0)) menu.addAction('In-Stock', lambda: self.reloadTable(1)) menu.addAction('Out-Stock', lambda: self.reloadTable(2)) menu.addAction('Damaged', lambda: self.reloadTable(3)) menu.addAction('Borrowed', lambda: self.reloadTable(4)) self.pull_btn = QPushButton() self.pull_btn.setText("Load") self.pull_btn.setMenu(menu) h_pull_box = QHBoxLayout() h_pull_box.addWidget(from_label) h_pull_box.addWidget(self.fromData) h_pull_box.addWidget(to_label) h_pull_box.addWidget(self.toData) h_pull_box.addWidget(self.pull_btn) storeGroup = self.pullGroupStore() unit = self.pullUnit() self.storeGroupText = QLabel('Category') self.storeGroupData = QComboBox() self.storeGroupData.currentIndexChanged.connect(self.reloadStore) self.storeText = QLabel('Items') self.storeData = QComboBox() self.amountText = QLabel('Total Cost') self.amountData = QLineEdit() self.amountData.setPlaceholderText('0000.00') self.tellerText = QLabel('Reciept No.') self.tellerData = QLineEdit() self.tellerData.setPlaceholderText('xxxxxxxxx') self.quantityText = QLabel('Quantity.') self.quantityData = QLineEdit() self.quantityData.setPlaceholderText('00.0') self.periodText = QLabel('Period (days)') self.periodData = QLineEdit() self.periodData.setPlaceholderText('00.0') self.personText = QLabel('Recieved By:') self.personData = QLineEdit() self.personData.setPlaceholderText('00.0') self.unitText = QLabel('Unit') self.unitData = QComboBox() self.borrowedText = QLabel('Borrowed') self.borrowedData = QComboBox() self.dateText = QLabel('Date') self.dateData = QDateEdit() self.dateData.setDate(currentDate.currentDate()) self.dateData.setCalendarPopup(True) self.descriptionText = QLabel('Description') self.descriptionData = QPlainTextEdit() self.descriptionData.move(200, 100) self.borrowedText.hide() self.borrowedData.hide() mboz = QVBoxLayout() hboz = QHBoxLayout() self.state = QLabel('') self.r1 = QRadioButton('In-stock') self.r1.setChecked(True) self.r1.toggled.connect(lambda: self.changeStates()) self.r2 = QRadioButton('Out-stock') self.r2.toggled.connect(lambda: self.changeStates()) self.r3 = QRadioButton('Damaged') self.r3.toggled.connect(lambda: self.changeStates()) self.r4 = QRadioButton('Borrowed') self.r4.toggled.connect(lambda: self.changeStates()) self.r5 = QRadioButton('Returned') self.r5.toggled.connect(lambda: self.changeStates()) hboz.addWidget(self.r1) hboz.addWidget(self.r2) hboz.addWidget(self.r3) hboz.addWidget(self.r4) hboz.addWidget(self.r5) i = 0 for a in storeGroup: self.hold_storeGroup[i] = a['id'] tex = str(a['name']).upper() self.storeGroupData.addItem(tex) i += 1 i = 0 str_key = self.hold_storeGroup[self.storeGroupData.currentIndex()] store = self.pullStore(str_key) for a in store: self.hold_store[i] = a['id'] tex = str(a['name']).upper() self.storeData.addItem(tex) i += 1 i = 0 for a in unit: self.hold_unit[i] = a['id'] tex = str(a['name']).upper() self.unitData.addItem(tex) i += 1 self.reloadBorrowed() self.FormLayout = QFormLayout() self.FormLayout.addRow(self.storeGroupText, self.storeGroupData) self.FormLayout.addRow(self.storeText, self.storeData) self.FormLayout.addRow(self.tellerText, self.tellerData) self.FormLayout.addRow(self.quantityText, self.quantityData) self.FormLayout.addRow(self.amountText, self.amountData) self.FormLayout.addRow(self.dateText, self.dateData) self.FormLayout.addRow(self.periodText, self.periodData) self.FormLayout.addRow(self.borrowedText, self.borrowedData) self.FormLayout.addRow(self.personText, self.personData) self.FormLayout.addRow(self.descriptionText, self.descriptionData) self.periodText.hide() self.periodData.hide() mboz.addLayout(hboz) mboz.addLayout(self.FormLayout) mboz.addWidget(self.state) groupBox1 = QGroupBox('Add Store Item') groupBox1.setLayout(mboz) self.pb = QPushButton() self.pb.setObjectName("Add") self.pb.setText("Add Store Item") self.pb1 = QPushButton() self.pb1.setObjectName("Edit") self.pb1.setText("Edit Row") self.pb1.setEnabled(False) self.pb2 = QPushButton() self.pb2.setObjectName("Close") self.pb2.setText("Close") self.pb3 = QPushButton() self.pb3.setObjectName("Delete") self.pb3.setText("Delete Row") self.pb3.setEnabled(False) self.pb4 = QPushButton() self.pb4.setObjectName("Reset") self.pb4.setText("Reset") self.pb4.hide() self.pb5 = QPushButton() self.pb5.setObjectName("Change") self.pb5.setText("Change Store") self.pb5.hide() self.pb6 = QPushButton() self.pb6.setObjectName("Clear") self.pb6.setText("Clear Selection") self.pb6.setEnabled(False) hbo = QHBoxLayout() hbo.addWidget(self.pb) hbo.addWidget(self.pb5) hbo.addWidget(self.pb4) hbo.addWidget(self.pb2) groupBox2 = QGroupBox('Store Data') groupBox2.setLayout(hbo) al = self.pullStoreData(0) if al and len(al) > 0: al = al else: al = {} self.storeData.currentIndexChanged.connect( lambda: self.reloadBorrowed()) header = self.table.horizontalHeader() header.setResizeMode(QHeaderView.ResizeToContents) header.setStretchLastSection(True) header.setStyleSheet(self.tableHeaderStyle) vheader = self.table.verticalHeader() vheader.setStyleSheet(self.tableHeaderStyle) # Body self.table.setWindowTitle("Store") self.table.setStyleSheet("color:white") self.table.resize(300, 250) self.table.setFont(self.tableFont) self.table.setSortingEnabled(2) #self.table.resizeColumnsToContents() self.table.setRowCount(len(al)) self.table.setColumnCount(len(self.cols)) self.table.setHorizontalHeaderLabels(self.cols) self.table.setContextMenuPolicy(Qt.CustomContextMenu) self.table.customContextMenuRequested.connect(self.handleHeaderMenu) self.table.hideColumn(0) self.table.setSelectionMode(QAbstractItemView.MultiSelection) self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.setEditTriggers(QAbstractItemView.NoEditTriggers) i = 0 for q in al: #row id if q['state'] == 1: color = QColor(100, 0, 0) elif q['state'] == 2: color = QColor(100, 100, 0) elif q['state'] == 3: color = QColor(100, 0, 100) elif q['state'] == 4: color = QColor(0, 100, 100) else: color = QColor(0, 50, 150) self.table.setItem(i, 0, QTableWidgetItem(str(q['id']))) self.table.item(i, 0).setBackground(color) self.table.setItem(i, 1, QTableWidgetItem(str(q['itemname']).upper())) self.table.item(i, 1).setBackground(color) self.table.setItem(i, 2, QTableWidgetItem(str(q['quantity']).upper())) self.table.item(i, 2).setBackground(color) try: zamt = str("{:,}".format(float(q['amount']))) except: zamt = '' self.table.setItem(i, 3, QTableWidgetItem(zamt)) self.table.item(i, 3).setBackground(color) try: if len(q['amount']) > 0 and float(q['amount']) > 0: tot = float(q['amount']) * float(q['quantity']) else: tot = 0 except: tot = 0 self.table.setItem(i, 4, QTableWidgetItem(str(tot).upper())) self.table.item(i, 4).setBackground(color) damz = float(q['datepaid']) damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y') self.table.setItem(i, 5, QTableWidgetItem(str(damt))) self.table.item(i, 5).setBackground(color) i += 1 self.table.itemSelectionChanged.connect(self.confirmSelection) self.table.resizeRowsToContents() v_pull_box = QVBoxLayout() self.h1_pull_box.addWidget(self.table) v_pull_box.addLayout(h_pull_box) v_pull_box.addLayout(self.h1_pull_box) h2_pull_box = QHBoxLayout() h2_pull_box.addWidget(self.pb1) h2_pull_box.addWidget(self.pb3) h2_pull_box.addWidget(self.pb6) v_pull_box.addLayout(h2_pull_box) groupBox3 = QGroupBox() groupBox3.setLayout(hbo) groupBox2.setLayout(v_pull_box) grid = QGridLayout() grid.addWidget(groupBox1, 0, 0) grid.addWidget(groupBox2, 0, 1, 2, 1) grid.addWidget(groupBox3, 1, 0) self.setLayout(grid) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click()) self.connect(self.pb1, SIGNAL("clicked()"), lambda: self.button_editshow()) self.connect(self.pb2, SIGNAL("clicked()"), lambda: self.button_close(self)) self.connect(self.pb3, SIGNAL("clicked()"), lambda: self.button_delete()) self.connect(self.pb4, SIGNAL("clicked()"), lambda: self.button_reset()) self.connect(self.pb5, SIGNAL("clicked()"), lambda: self.button_edit()) self.connect(self.pb6, SIGNAL("clicked()"), lambda: self.button_clear()) #self.connect(self.pull_btn, SIGNAL("clicked()"), lambda x =1: self.reloadTable(x)) self.setWindowTitle(self.pagetitle) def stateReciept(self): self.amountText.show() self.amountData.show() self.tellerText.show() self.tellerData.show() self.tellerText.setText('Reciept No.') self.periodText.hide() self.periodData.hide() self.personText.setText('Recieved By:') self.personData.setPlaceholderText('Fullname or department') self.borrowedText.hide() self.borrowedData.hide() self.reloadTable(1) def stateIssue(self): self.amountText.hide() self.amountData.hide() self.tellerText.show() self.tellerData.show() self.tellerText.setText('Issue No.') self.periodText.hide() self.periodData.hide() self.personText.setText('Issued to:') self.personData.setPlaceholderText('Fullname or department issued to') self.borrowedText.hide() self.borrowedData.hide() self.reloadTable(2) def stateDamage(self): self.amountText.hide() self.amountData.hide() self.tellerText.hide() self.tellerData.hide() self.periodText.hide() self.periodData.hide() self.personText.setText('Reported By:') self.personData.setPlaceholderText('Fullname or department') self.borrowedText.hide() self.borrowedData.hide() self.reloadTable(3) def stateBorrowed(self): self.amountText.hide() self.amountData.hide() self.tellerText.hide() self.tellerData.hide() self.periodText.show() self.periodData.show() self.personText.setText('Given to:') self.personData.setPlaceholderText( 'Fullname or department borrowed to') self.borrowedText.hide() self.borrowedData.hide() self.reloadTable(4) def stateReturned(self): self.amountText.hide() self.amountData.hide() self.tellerText.hide() self.tellerData.hide() self.periodText.hide() self.periodData.hide() self.personText.setText('Returned By:') self.personData.setPlaceholderText( 'Fullname or department borrowed to') self.borrowedText.show() self.borrowedData.show() self.reloadBorrowed() self.reloadTable(5) def changeStates(self): self.getQuantity() if self.r1.isChecked(): self.stateReciept() elif self.r2.isChecked(): self.stateIssue() elif self.r3.isChecked(): self.stateDamage() elif self.r4.isChecked(): self.stateBorrowed() elif self.r5.isChecked(): self.stateReturned() def handleHeaderMenu(self, pos): print('column(%d)' % self.table.horizontalHeader().logicalIndexAt(pos)) menu = QMenu() menu.addAction('Add') menu.addAction('Delete') menu.exec_(QCursor.pos()) def pullGroupStore(self): cn = Db() arr = cn.selectn('datas', '', '', {"pubID": 23, "active": 0}) return arr def pullStore(self, a): cn = Db() arr = cn.selectn('datas', '', '', {"subID": a}) return arr def pullUnit(self): cn = Db() arr = cn.selectn('datas', '', '', {"pubID": 20, "active": 0}) return arr def pullStoreData(self, a=None): st_date = self.fromData.date().toPyDate() en_date = self.toData.date().toPyDate() st_date = time.mktime(st_date.timetuple()) en_date = time.mktime(en_date.timetuple()) db = 'school_stores' + str(self.session) cn = Db() arr = cn.selectStoreDate(db, st_date, en_date, a) return arr def mySelectTable(self): ''' get the selected rpws in a table returns list or row ids ''' sels = self.table.selectedIndexes() sels = self.table.selectionModel().selectedRows() park = [] park1 = [] for j in sels: park.append(j.row()) for i in set(park): selected = self.table.item(i, 0).text() park1.append(selected) return park1 def editRow(self, a): _session = self.session g = Db() db = 'school_stores' + str(_session) data = g.selectn(db, '', 1, {'id': a}) if len(data) > 0: try: amt = float(data['amount']) qty = float(data['quantity']) if amt > 0 and qty > 0: cost = amt * qty else: cost = 0 except: cost = 0 amt = 0 qty = 0 if data['state'] == 1: self.r1.setChecked(True) elif data['state'] == 2: self.r2.setChecked(True) elif data['state'] == 3: self.r3.setChecked(True) elif data['state'] == 4: self.r4.setChecked(True) elif data['state'] == 5: self.r5.setChecked(True) self.amountData.setText(str(cost)) self.descriptionData.clear() self.descriptionData.insertPlainText(str(data['description'])) self.tellerData.setText(str(data['teller'])) self.periodData.setText(str(data['period'])) self.personData.setText(str(data['person'])) self.quantityData.setText(str(qty)) stID = self.hold_store.keys()[self.hold_store.values().index( data['itemID'])] self.storeData.setCurrentIndex(stID) def reloadBorrowed(self): self.getQuantity() _store = self.hold_store[self.storeData.currentIndex()] _session = self.session g = Db() db = 'school_stores' + str(_session) data = g.selectn(db, '', '', {'itemID': _store, 'state': 4}) fig = 0 self.borrowedData.clear() self.hold_borrowed = {} i = 0 for a in data: ret = g.selectStoreReturned(db, a['id']) if ret: retu = ret['qty'] else: retu = 0 fig = float(a['quantity']) - float(retu) damz = float(a['datepaid']) if float(fig) > 0: self.hold_borrowed[i] = a['id'] damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y') tex = str(damt) + " " + str( a['person']).upper() + " (" + str(fig).upper() + ")" self.borrowedData.addItem(tex) i += 1 def reloadStore(self): self.getQuantity() cat = self.hold_storeGroup[self.storeGroupData.currentIndex()] store = self.pullStore(cat) self.storeData.clear() self.hold_store = {} i = 0 for a in store: self.hold_store[i] = a['id'] tex = str(a['name']).upper() self.storeData.addItem(tex) i += 1 def getQuantity(self): if self.storeData.currentIndex() > -1: s = self.hold_store[self.storeData.currentIndex()] _session = self.session g = Db() db = 'school_stores' + str(_session) fi = g.selectStoreQuantity(db, s) remain = 0 arr = {} for a in fi: arr[a['state']] = a['qty'] if 1 in arr: re = arr[1] else: re = 0 if 2 in arr: isu = arr[2] else: isu = 0 if 3 in arr: dam = arr[3] else: dam = 0 if 4 in arr: bor = arr[4] else: bor = 0 if 5 in arr: ret = arr[5] else: ret = 0 borrowed = float(bor) - float(ret) issued = float(isu) + float(borrowed) + float(dam) remain = float(re) - float(issued) self.quantityText.setText('QTY: ' + str(remain)) if remain == 0 and (self.r2.isChecked() or self.r3.isChecked() or self.r4.isChecked()): self.quantityData.setEnabled(False) else: self.quantityData.setEnabled(True) return remain def reloadTable(self, a): self.getQuantity() if not a == 0: data = self.pullStoreData(a) else: data = self.pullStoreData() self.table.close() self.table = QTableWidget() header = self.table.horizontalHeader() header.setResizeMode(QHeaderView.ResizeToContents) header.setStretchLastSection(True) header.setStyleSheet(self.tableHeaderStyle) vheader = self.table.verticalHeader() vheader.setStyleSheet(self.tableHeaderStyle) # Body self.table.setWindowTitle("Stores") self.table.setStyleSheet("color:white") self.table.resize(300, 250) self.table.setFont(self.tableFont) self.table.setSortingEnabled(2) self.table.resizeColumnsToContents() self.table.setRowCount(len(data)) self.table.setColumnCount(len(self.cols)) self.table.setHorizontalHeaderLabels(self.cols) self.table.setContextMenuPolicy(Qt.CustomContextMenu) self.table.customContextMenuRequested.connect(self.handleHeaderMenu) self.table.hideColumn(0) self.table.setSelectionMode(QAbstractItemView.MultiSelection) self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.setEditTriggers(QAbstractItemView.NoEditTriggers) i = 0 for q in data: #row id if q['state'] == 1: color = QColor(100, 0, 0) elif q['state'] == 2: color = QColor(100, 100, 0) elif q['state'] == 3: color = QColor(100, 0, 100) elif q['state'] == 4: color = QColor(0, 100, 100) else: color = QColor(0, 50, 150) self.table.setItem(i, 0, QTableWidgetItem(str(q['id']))) self.table.item(i, 0).setBackground(color) self.table.setItem(i, 1, QTableWidgetItem(str(q['itemname']).upper())) self.table.item(i, 1).setBackground(color) self.table.setItem(i, 2, QTableWidgetItem(str(q['quantity']).upper())) self.table.item(i, 2).setBackground(color) try: zamt = str("{:,}".format(float(q['amount']))) except: zamt = '' self.table.setItem(i, 3, QTableWidgetItem(zamt)) self.table.item(i, 3).setBackground(color) try: if len(q['amount']) > 0 and float(q['amount']) > 0: tot = float(q['amount']) * float(q['quantity']) else: tot = 0 except: tot = 0 self.table.setItem(i, 4, QTableWidgetItem(str(tot).upper())) self.table.item(i, 4).setBackground(color) damz = float(q['datepaid']) damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y') self.table.setItem(i, 5, QTableWidgetItem(str(damt))) self.table.item(i, 5).setBackground(color) i += 1 self.table.itemSelectionChanged.connect(self.confirmSelection) self.table.resizeRowsToContents() self.h1_pull_box.addWidget(self.table) self.table.show() def pullOnes(self, a, b): cn = Db() arr = cn.selectn(a, '', 1, {'id': b}) return arr def confirmSelection(self): item = self.mySelectTable() if len(item) == 1: self.pb1.setEnabled(True) self.pb3.setEnabled(True) self.pb6.setEnabled(True) elif len(item) > 1: self.pb1.setEnabled(False) self.pb3.setEnabled(True) self.pb6.setEnabled(True) else: self.pb1.setEnabled(False) self.pb3.setEnabled(False) self.pb6.setEnabled(False) def button_close(self, b): b.close() def button_editshow(self): item = self.mySelectTable() self.editRow(item[0]) self.pb.hide() self.pb4.show() self.pb5.show() def button_delete(self): item = self.mySelectTable() _session = self.session g = Db() db = 'school_stores' + str(_session) for j in item: g.delete(db, {'id': j}) self.reloadTable(1) def button_edit(self): _session = self.session _amounts = self.amountData.text() _teller = self.tellerData.text() _quantity = self.quantityData.text() _person = self.personData.text() _period = self.periodData.text() _date = self.dateData.date().toPyDate() _date = time.mktime(_date.timetuple()) _description = self.descriptionData.toPlainText() _store = self.hold_store[self.storeData.currentIndex()] _borrowed = self.hold_borrowed[self.borrowedData.currentIndex()] arr = {} #recieved if self.r1.isChecked() and _amounts and not ( _amounts == 0) and int(_store) > 0 and int(_quantity) > 0: _amount = float(_amounts) / float(_quantity) arr['amount'] = _amount arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['teller'] = _teller arr['quantity'] = _quantity arr['person'] = _person arr['state'] = 1 #issued elif self.r2.isChecked() and int(_store) > 0 and int(_quantity) > 0: _amount = float(_amounts) / float(_quantity) arr['amount'] = _amount arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['teller'] = _teller arr['quantity'] = _quantity arr['person'] = _person arr['state'] = 2 #damaged elif self.r3.isChecked() and int(_store) > 0 and int(_quantity) > 0: arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['teller'] = _teller arr['quantity'] = _quantity arr['person'] = _person arr['state'] = 3 elif self.r4.isChecked() and int(_store) > 0 and int(_quantity) > 0: arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['quantity'] = _quantity arr['person'] = _person arr['period'] = _period arr['state'] = 4 elif self.r5.isChecked() and int(_store) > 0 and int(_quantity) > 0: _borrowed = self.hold_borrowed[self.borrowedData.currentIndex()] arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['quantity'] = _quantity arr['person'] = _person arr['period'] = _period arr['active'] = _borrowed arr['state'] = 5 ups = {} ups['id'] = self.editID if int(self.editID) > 0 and len(arr) > 0: db = 'school_stores' + str(_session) g = Db() g.update(db, arr, ups) if int(self.editID) > 0: self.button_reset() def button_reset(self): self.getQuantity() self.reloadTable(1) self.amountData.setText('') self.descriptionData.clear() self.tellerData.setText('') self.personData.setText('') self.periodData.setText('') self.quantityData.setText('') self.pb4.hide() self.pb5.hide() self.pb.show() self.editID = 0 self.button_clear() self.confirmSelection() self.reloadBorrowed() def button_clear(self): self.table.selectionModel().clearSelection() def button_click(self): _session = self.session _amounts = self.amountData.text() _teller = self.tellerData.text() _quantity = self.quantityData.text() _person = self.personData.text() _period = self.periodData.text() _date = self.dateData.date().toPyDate() _date = time.mktime(_date.timetuple()) _description = self.descriptionData.toPlainText() _store = self.hold_store[self.storeData.currentIndex()] arr = {} #recieved if self.r1.isChecked() and _amounts and not ( _amounts == 0) and int(_store) > 0 and int(_quantity) > 0: _amount = float(_amounts) / float(_quantity) arr['amount'] = _amount arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['teller'] = _teller arr['quantity'] = _quantity arr['person'] = _person arr['state'] = 1 #issued elif self.r2.isChecked() and _amounts and not ( _amounts == 0) and int(_store) > 0 and int(_quantity) > 0: _amount = float(_amounts) / float(_quantity) arr['amount'] = _amount arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['teller'] = _teller arr['quantity'] = _quantity arr['person'] = _person arr['state'] = 2 #damaged elif self.r3.isChecked() and int(_store) > 0 and int( float(_quantity)) > 0: arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['teller'] = _teller arr['quantity'] = _quantity arr['person'] = _person arr['state'] = 3 elif self.r4.isChecked() and int(_store) > 0 and int( float(_quantity)) > 0: arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['quantity'] = _quantity arr['person'] = _person arr['period'] = _period arr['state'] = 4 elif self.r5.isChecked() and int(_store) > 0 and int( float(_quantity)) > 0 and self.borrowedData.currentIndex() > 0: _borrowed = self.hold_borrowed[self.borrowedData.currentIndex()] arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['quantity'] = _quantity arr['person'] = _person arr['period'] = _period arr['active'] = _borrowed arr['state'] = 5 if len(arr) > 0: db = 'school_stores' + str(_session) g = Db() ins = g.insert(db, arr) if int(ins) > 0: self.button_reset()
class QFellesController(QFellesWidgetBaseClass): """ @brief: Widget representing a PID controller """ proportional = pyqtSignal(float) integral = pyqtSignal(float) derivative = pyqtSignal(float) MV_sp = pyqtSignal(float) CV_sp = pyqtSignal(float) def initUi(self, parent=None): """ Generates the user interface """ #Update widget meta data self.meta["type"] = "Controller" self.meta["name"] = "foobar" self.meta["unit"] = "--" self.label = QLabel(parent) self.label.setObjectName("PID Controller") #Group box group_box = QGroupBox('Controller Settings') #Spin button Labels gain = "K<sub>c</sub>" Kc = gain.decode('utf-8') self.gain_label = QLabel(Kc) self.gain_label.setStyleSheet("font:25pt") time1 = "τ<sub>i</sub>" taui = time1.decode('utf-8') self.taui_label = QLabel(taui) self.taui_label.setStyleSheet("font:25pt ") time2 = "τ<sub>d</sub>" taud = time2.decode('utf-8') self.taud_label = QLabel(taud) self.taud_label.setStyleSheet("font:25pt") #Spin buttons self.gain = QDoubleSpinBox() #Controller gain self.taui = QDoubleSpinBox() #Controller integral time constant self.taud = QDoubleSpinBox() #Controller derivative time constant self.GAIN_0 = self.gain.value() self.TAUI_0 = self.taui.value() self.TAUD_0 = self.taud.value() self.gain.setKeyboardTracking(False) self.taui.setKeyboardTracking(False) self.taud.setKeyboardTracking(False) #self.gain.setRange(minimum, maximum) self.gain_label.setBuddy(self.gain) self.taui_label.setBuddy(self.taui) self.taud_label.setBuddy(self.taud) self.gain.valueChanged.connect(self.controllersettings) self.taui.valueChanged.connect(self.controllersettings) self.taud.valueChanged.connect(self.controllersettings) self.setpoint = QDoubleSpinBox() #Controlled variable setpoint self.setpoint.setHidden(True) self.setpoint_label = QLabel('CV Setpoint') self.setpoint_label.setBuddy(self.setpoint) self.setpoint.valueChanged.connect(self.CVSetPoint) #On-Off Buttons self.on = QRadioButton("Controller On") self.on.setChecked(False) #Default to have controller off self.on.toggled.connect(self.btnstate) #Slider self.MV_manual = QSlider(Qt.Horizontal) self.MV_manual_label = QLabel('MV Setpoint') self.MV_manual.sliderReleased.connect(self.mv_state) #self.MV_manual.setRange(minimum, maximum) #Layout controlsLayout = QGridLayout() controlsLayout.addWidget(self.gain_label, 0, 0) controlsLayout.addWidget(self.gain, 0, 1) controlsLayout.addWidget(self.setpoint_label, 0, 2) controlsLayout.addWidget(self.setpoint, 0, 3) controlsLayout.addWidget(self.taui_label, 1, 0) controlsLayout.addWidget(self.taui, 1, 1) controlsLayout.addWidget(self.MV_manual_label, 1, 2) controlsLayout.addWidget(self.MV_manual, 1, 3) controlsLayout.addWidget(self.taud_label, 2, 0) controlsLayout.addWidget(self.taud, 2, 1) controlsLayout.addWidget(self.on, 2, 2) controlsLayout.setRowStretch(3, 1) layout = QHBoxLayout() layout.addLayout(controlsLayout) self.setLayout(layout) @pyqtSlot() def CVSetPoint(self, event=None): self.setpoint_value = self.setpoint.value() self.CV_sp.emit(self.setpoint_value) #print self.setpoint_value @pyqtSlot() def controllersettings(self, event=None): if self.gain.value() != self.GAIN_0: self.GAIN_0 = self.gain.value() self.gain_value = self.gain.value() self.proportional.emit(self.gain_value) #Emitting Gain value #print self.gain_value elif self.taui.value() != self.TAUI_0: self.TAUI_0 = self.taui.value() self.taui_value = self.taui.value() self.integral.emit(self.taui_value) #print self.taui_value elif self.taud.value() != self.TAUD_0: self.TAUD_0 = self.taud.value() self.taud_value = self.taud.value() self.derivative.emit(self.taud_value) #print self.taud_value @pyqtSlot() def btnstate(self, event=None): if self.on.isChecked() == True: self.setpoint.setHidden(False) self.MV_manual.setHidden(True) #print "Controller is on" else: self.setpoint.setHidden(True) self.MV_manual.setHidden(False) #print "Controller is off" @pyqtSlot() def mv_state(self, event=None): MV_setpoint = self.MV_manual.value() self.MV_sp.emit(MV_setpoint) #print MV_setpoint def closeEvent(self, event=None): print("Shutting down %s" % self.__class__.__name__) self.onQuit()
class ControllerWidget(QWidget): proportional = pyqtSignal(float) integral = pyqtSignal(float) derivative = pyqtSignal(float) MV_sp = pyqtSignal(float) CV_sp = pyqtSignal(float) def __init__(self, parent): super(ControllerWidget, self).__init__() # self._controllerstate = 1 #default off self.initUI() self.on.toggled.connect(self.btnstate) self.setpoint.valueChanged[str].connect(self.CVSetPoint) self.gain.valueChanged[str].connect(self.controllersettings) self.taui.valueChanged[str].connect(self.controllersettings) self.taud.valueChanged[str].connect(self.controllersettings) self.MV_manual.sliderReleased.connect(self.mv_state) # @property # def controllerstate(self): # return self._controllerstate # # @controllerstate.setter # def controllerstate(self, value): # self._controllerstate = value def initUI(self): #Group box group_box = QGroupBox('Controller Settings') #Spin button Labels gain = "K<sub>c</sub>" Kc = gain.decode('utf-8') self.gain_label = QLabel(Kc) self.gain_label.setStyleSheet("font:25pt") time1 = "τ<sub>i</sub>" taui = time1.decode('utf-8') self.taui_label = QLabel(taui) self.taui_label.setStyleSheet("font:25pt ") time2 = "τ<sub>d</sub>" taud = time2.decode('utf-8') self.taud_label = QLabel(taud) self.taud_label.setStyleSheet("font:25pt") #Spin buttons self.gain = QDoubleSpinBox() #Controller gain self.taui = QDoubleSpinBox() #Controller integral time constant self.taud = QDoubleSpinBox() #Controller derivative time constant self.GAIN_0 = self.gain.value() self.TAUI_0 = self.taui.value() self.TAUD_0 = self.taud.value() self.gain.setKeyboardTracking(False) self.taui.setKeyboardTracking(False) self.taud.setKeyboardTracking(False) #self.gain.setRange(minimum, maximum) self.gain_label.setBuddy(self.gain) self.taui_label.setBuddy(self.taui) self.taud_label.setBuddy(self.taud) self.setpoint = QDoubleSpinBox() #Controlled variable setpoint self.setpoint.setHidden(True) self.setpoint_label = QLabel('CV Setpoint') self.setpoint_label.setBuddy(self.setpoint) #On-Off Buttons self.on = QRadioButton("Controller On") self.on.setChecked(False) #Default to have controller off #Slider self.MV_manual = QSlider(Qt.Horizontal) self.MV_manual_label = QLabel('MV Setpoint') #self.MV_manual.setRange(minimum, maximum) #Layout controlsLayout = QGridLayout() controlsLayout.addWidget(self.gain_label, 0, 0) controlsLayout.addWidget(self.gain, 0, 1) controlsLayout.addWidget(self.setpoint_label, 0, 2) controlsLayout.addWidget(self.setpoint, 0, 3) controlsLayout.addWidget(self.taui_label, 1, 0) controlsLayout.addWidget(self.taui, 1, 1) controlsLayout.addWidget(self.MV_manual_label, 1, 2) controlsLayout.addWidget(self.MV_manual, 1, 3) controlsLayout.addWidget(self.taud_label, 2, 0) controlsLayout.addWidget(self.taud, 2, 1) controlsLayout.addWidget(self.on, 2, 2) controlsLayout.setRowStretch(3, 1) layout = QHBoxLayout() layout.addLayout(controlsLayout) self.setLayout(layout) @pyqtSlot() def CVSetPoint(self, event=None): self.setpoint_value = self.setpoint.value() self.CV_sp.emit(self.setpoint_value) #print self.setpoint_value @pyqtSlot() def controllersettings(self, event=None): if self.gain.value() != self.GAIN_0: self.GAIN_0 = self.gain.value() self.gain_value = self.gain.value() self.proportional.emit(self.gain_value) #emitting Gain value #print self.gain_value elif self.taui.value() != self.TAUI_0: self.TAUI_0 = self.taui.value() self.taui_value = self.taui.value() self.integral.emit(self.taui_value) #print self.taui_value elif self.taud.value() != self.TAUD_0: self.TAUD_0 = self.taud.value() self.taud_value = self.taud.value() self.derivative.emit(self.taud_value) #print self.taud_value @pyqtSlot() def btnstate(self, event=None): if self.on.isChecked() == True: self.setpoint.setHidden(False) self.MV_manual.setHidden(True) #print "Controller is on" else: self.setpoint.setHidden(True) self.MV_manual.setHidden(False) #print "Controller is off" @pyqtSlot() def mv_state(self, event=None): MV_setpoint = self.MV_manual.value() self.MV_sp.emit(MV_setpoint)
class GeosurfaceSimulationDialog(QDialog): def __init__(self, application_dir, help_html_subpath): super(GeosurfaceSimulationDialog, self).__init__() self.application_dir = application_dir self.help_html_subpath = help_html_subpath self.analytical_surface_params = None self.geographical_surface_params = None self.setup_gui() def setup_gui(self): dialog_layout = QVBoxLayout() main_widget = QTabWidget() main_widget.addTab(self.setup_simulation_tab(), "Simulation") main_widget.addTab(self.setup_help_tab(), "Help") dialog_layout.addWidget(main_widget) self.setLayout(dialog_layout) self.adjustSize() self.setWindowTitle('simSurf - Geosurface simulation') def setup_simulation_tab(self): simulWidget = QWidget() simulLayout = QGridLayout() simulToolBox = QToolBox() simulToolBox.addItem(self.setup_analformula_tb(), "Analytical formula") simulToolBox.addItem(self.setup_geogrparams_tb(), "Geographic parameters") simulToolBox.addItem(self.setup_output_tb(), "Output") simulLayout.addWidget(simulToolBox, 0, 0, 1, 2) simulWidget.setLayout(simulLayout) return simulWidget def setup_analformula_tb(self): analformWidget = QWidget() analformLayout = QGridLayout() analformLayout.addWidget(QLabel("a min"), 0, 0, 1, 1) self.a_min_QLineEdit = QLineEdit() analformLayout.addWidget(self.a_min_QLineEdit, 0, 1, 1, 1) analformLayout.addWidget(QLabel("a max"), 0, 2, 1, 1) self.a_max_QLineEdit = QLineEdit() analformLayout.addWidget(self.a_max_QLineEdit, 0, 3, 1, 1) analformLayout.addWidget(QLabel("grid cols"), 0, 4, 1, 1) self.num_columns_QLineEdit = QLineEdit() analformLayout.addWidget(self.num_columns_QLineEdit, 0, 5, 1, 1) analformLayout.addWidget(QLabel("b min"), 1, 0, 1, 1) self.b_min_QLineEdit = QLineEdit() analformLayout.addWidget(self.b_min_QLineEdit, 1, 1, 1, 1) analformLayout.addWidget(QLabel("b max"), 1, 2, 1, 1) self.b_max_QLineEdit = QLineEdit() analformLayout.addWidget(self.b_max_QLineEdit, 1, 3, 1, 1) analformLayout.addWidget(QLabel("grid rows"), 1, 4, 1, 1) self.num_rows_QLineEdit = QLineEdit() analformLayout.addWidget(self.num_rows_QLineEdit, 1, 5, 1, 1) analformLayout.addWidget(QLabel("Formula"), 2, 0, 1, 1) self.formula_QLineEdit = QLineEdit() analformLayout.addWidget(self.formula_QLineEdit, 2, 1, 1, 5) analform_validate_QPushButton = QPushButton("Calculate matrix") analform_validate_QPushButton.clicked.connect(self.calculate_z_array) analformLayout.addWidget(analform_validate_QPushButton, 3, 0, 1, 6) view_anal_surface_QPushButton = QPushButton("View as 3D surface") view_anal_surface_QPushButton.clicked[bool].connect( self.view_analytical_surface) view_anal_surface_QPushButton.setEnabled(True) analformLayout.addWidget(view_anal_surface_QPushButton, 4, 0, 1, 6) analformWidget.setLayout(analformLayout) return analformWidget def setup_geogrparams_tb(self): geogrparWidget = QWidget() geogrparLayout = QGridLayout() geogrparLayout.addWidget(QLabel("lower-left x"), 0, 0, 1, 1) self.geog_x_min_QLineEdit = QLineEdit() geogrparLayout.addWidget(self.geog_x_min_QLineEdit, 0, 1, 1, 1) geogrparLayout.addWidget(QLabel("lower-left y"), 1, 0, 1, 1) self.geog_y_min_QLineEdit = QLineEdit() geogrparLayout.addWidget(self.geog_y_min_QLineEdit, 1, 1, 1, 1) geogrparLayout.addWidget(QLabel("map width (x range)"), 2, 0, 1, 1) self.grid_width_QLineEdit = QLineEdit() geogrparLayout.addWidget(self.grid_width_QLineEdit, 2, 1, 1, 1) geogrparLayout.addWidget(QLabel("map height (y range)"), 3, 0, 1, 1) self.grid_height_QLineEdit = QLineEdit() geogrparLayout.addWidget(self.grid_height_QLineEdit, 3, 1, 1, 1) geogrparLayout.addWidget(QLabel("grid rot. angle (anti-clockwise)"), 4, 0, 1, 1) self.rotation_angle_QLineEdit = QLineEdit() geogrparLayout.addWidget(self.rotation_angle_QLineEdit, 4, 1, 1, 1) simulate_surface_pButton = QPushButton("Create simulated geosurface") simulate_surface_pButton.clicked[bool].connect(self.geosurface_XYZ) simulate_surface_pButton.setEnabled(True) geogrparLayout.addWidget(simulate_surface_pButton, 5, 0, 1, 2) view_anal_surface_QPushButton = QPushButton("View as 3D surface") view_anal_surface_QPushButton.clicked[bool].connect( self.view_geographical_surface) view_anal_surface_QPushButton.setEnabled(True) geogrparLayout.addWidget(view_anal_surface_QPushButton, 6, 0, 1, 2) geogrparWidget.setLayout(geogrparLayout) return geogrparWidget def setup_output_tb(self): outputWidget = QWidget() outputLayout = QGridLayout() outputLayout.addWidget(QLabel("Format: "), 0, 0, 1, 1) self.save_as_grass_QRadioButton = QRadioButton("Grass") self.save_as_grass_QRadioButton.setChecked(True) outputLayout.addWidget(self.save_as_grass_QRadioButton, 0, 1, 1, 1) self.save_as_vtk_QRadioButton = QRadioButton("VTK") outputLayout.addWidget(self.save_as_vtk_QRadioButton, 0, 2, 1, 1) self.save_as_gas_QRadioButton = QRadioButton("Gas (json)") outputLayout.addWidget(self.save_as_gas_QRadioButton, 0, 3, 1, 1) self.save_as_xyz_QRadioButton = QRadioButton("xyz") outputLayout.addWidget(self.save_as_xyz_QRadioButton, 1, 1, 1, 2) self.save_as_esri_generate_QRadioButton = QRadioButton( "3D ESRI generate") outputLayout.addWidget(self.save_as_esri_generate_QRadioButton, 1, 3, 1, 2) simulation_output_browse_QPushButton = QPushButton("Save as ...") simulation_output_browse_QPushButton.clicked.connect( self.select_output_file) outputLayout.addWidget(simulation_output_browse_QPushButton, 2, 0, 1, 1) self.output_filename_QLineEdit = QLineEdit() outputLayout.addWidget(self.output_filename_QLineEdit, 2, 1, 1, 4) self.save_surface_pButton = QPushButton("Save surface") self.save_surface_pButton.clicked[bool].connect(self.save_surface) self.save_surface_pButton.setEnabled(True) outputLayout.addWidget(self.save_surface_pButton, 3, 0, 1, 5) outputWidget.setLayout(outputLayout) return outputWidget def setup_help_tab(self): helpWidget = QWidget() helpLayout = QVBoxLayout() helpLayout.addWidget(self.setup_help()) helpWidget.setLayout(helpLayout) return helpWidget def setup_help(self): help_QGroupBox = QGroupBox(self.tr("Help")) helpLayout = QVBoxLayout() self.help_pButton = QPushButton("Open help in browser") self.help_pButton.clicked[bool].connect(self.open_html_help) self.help_pButton.setEnabled(True) helpLayout.addWidget(self.help_pButton) help_QGroupBox.setLayout(helpLayout) return help_QGroupBox def open_html_help(self): help_file_path = os.path.join(self.application_dir, self.help_html_subpath) webbrowser.open(help_file_path, new=True) def calculate_z_array(self): try: a_min = float(eval(str(self.a_min_QLineEdit.text()))) a_max = float(eval(str(self.a_max_QLineEdit.text()))) grid_cols = int(self.num_columns_QLineEdit.text()) b_min = float(eval(str(self.b_min_QLineEdit.text()))) b_max = float(eval(str(self.b_max_QLineEdit.text()))) grid_rows = int(self.num_rows_QLineEdit.text()) except: QMessageBox.critical(self, "Surface simulation", "Check input analytical values") return if a_min >= a_max or b_min >= b_max: QMessageBox.critical(self, "Surface simulation", "Check a and b values") return if grid_cols <= 0 or grid_rows <= 0: QMessageBox.critical(self, "Surface simulation", "Check grid column and row values") return formula = str(self.formula_QLineEdit.text()) if formula == '': QMessageBox.critical(self, "Surface simulation", "Define an analytical formula") return a_array = linspace(a_min, a_max, num=grid_cols) b_array = linspace( b_max, b_min, num=grid_rows) # note: reversed for conventional j order in arrays try: a_list = [a for a in a_array for b in b_array] b_list = [b for a in a_array for b in b_array] z_list = [eval(formula) for a in a_array for b in b_array] except: QMessageBox.critical(self, "Surface simulation", "Error in matrix calculation") return self.analytical_surface_abz = a_list, b_list, z_list self.array_params = a_min, a_max, b_min, b_max self.grid_dims = grid_rows, grid_cols self.analytical_surface_params = { 'a min': a_min, 'a max': a_max, 'b min': b_min, 'b max': b_max, 'grid cols': grid_cols, 'grid rows': grid_rows, 'formula': formula } QMessageBox.information(self, "Surface simulation", "Matrix created") def view_analytical_surface(self): if self.analytical_surface_params is None: QMessageBox.critical(self, "Surface simulation", "Matrix not yet calculated") return view_3D_surface(self.analytical_surface_abz) def view_geographical_surface(self): if self.geographical_surface_params is None: QMessageBox.critical(self, "Surface simulation", "Geographic surface not yet calculated") return view_3D_surface(self.simulated_geosurface) def calculate_scale_matrix(self, a_range, b_range, grid_height, grid_width): assert a_range > 0.0 assert b_range > 0.0 assert grid_height > 0.0 assert grid_width > 0.0 sx = grid_width / a_range sy = grid_height / b_range return array([(sx, 0.0), (0.0, sy)]) def rotation_matrix(self, grid_rot_angle_degr): grid_rot_angle_rad = radians(grid_rot_angle_degr) sin_rot_angle = sin(grid_rot_angle_rad) cos_rot_angle = cos(grid_rot_angle_rad) return array([(cos_rot_angle, -sin_rot_angle), (sin_rot_angle, cos_rot_angle)]) def calculate_offset_parameters(self, transformation_matrix, llc_point_matr, llc_point_geog): llc_point_matr_offset = dot(transformation_matrix, llc_point_matr) return llc_point_geog - llc_point_matr_offset def geosurface_XYZ(self): try: geog_x_min = float(self.geog_x_min_QLineEdit.text()) geog_y_min = float(self.geog_y_min_QLineEdit.text()) grid_rot_angle_degr = float(self.rotation_angle_QLineEdit.text()) grid_height = float(self.grid_height_QLineEdit.text()) grid_width = float(self.grid_width_QLineEdit.text()) except: QMessageBox.critical(self, "Surface simulation", "Check input values") return if grid_height <= 0.0 or grid_width <= 0.0: QMessageBox.critical(self, "Surface simulation", "Check height and width values") return try: X, Y, Z = self.analytical_surface_abz a_min, a_max, b_min, b_max = self.array_params grid_rows, grid_cols = self.grid_dims # just for checking input completeness except: QMessageBox.critical(self, "Surface simulation", "Matrix not yet calculated") return a_range, b_range = a_max - a_min, b_max - b_min scale_matrix = self.calculate_scale_matrix(a_range, b_range, grid_height, grid_width) rotation_matrix = self.rotation_matrix(grid_rot_angle_degr) transformation_matrix = dot(rotation_matrix, scale_matrix) offset_parameters_matrix = self.calculate_offset_parameters( transformation_matrix, array([a_min, b_min]), array([geog_x_min, geog_y_min])) X_tr = [] Y_tr = [] for x, y in zip(X, Y): orig_pt = array([x, y]) trasl_pt = dot(transformation_matrix, orig_pt) + offset_parameters_matrix X_tr.append(trasl_pt[0]) Y_tr.append(trasl_pt[1]) self.simulated_geosurface = (X_tr, Y_tr, Z) self.geographical_surface_params = { 'geog x min': geog_x_min, 'geog y min': geog_y_min, 'grid rot angle degr': grid_rot_angle_degr, 'grid height': grid_height, 'grid width': grid_width } QMessageBox.information(self, "Surface simulation", "Completed") def select_output_file(self): if self.save_as_vtk_QRadioButton.isChecked(): short_txt = "*.vtk" long_txt = "vtk (*.vtk *.VTK)" elif self.save_as_grass_QRadioButton.isChecked(): short_txt = "*.txt" long_txt = "txt (*.txt *.TXT)" elif self.save_as_gas_QRadioButton.isChecked(): short_txt = "*.json" long_txt = "json (*.json *.JSON)" elif self.save_as_xyz_QRadioButton.isChecked(): short_txt = "*.xyz" long_txt = "xyz (*.xyz *.XYZ)" elif self.save_as_esri_generate_QRadioButton.isChecked(): short_txt = "*.*" long_txt = "generate file (*.*)" output_filename = QFileDialog.getSaveFileName(self, self.tr("Save as"), short_txt, long_txt) if not output_filename: return self.output_filename_QLineEdit.setText(output_filename) def save_surface(self): try: self.simulated_geosurface except AttributeError: QMessageBox.critical(self, "Surface saving", "Geosurface is not yet defined") return geodata = self.simulated_geosurface, self.grid_dims if self.save_as_vtk_QRadioButton.isChecked(): save_function = geosurface_export_vtk elif self.save_as_grass_QRadioButton.isChecked(): save_function = geosurface_export_grass elif self.save_as_xyz_QRadioButton.isChecked(): save_function = geosurface_export_xyz elif self.save_as_gas_QRadioButton.isChecked(): save_function = geosurface_save_gas geodata = { 'analytical surface': self.analytical_surface_params, 'geographical params': self.geographical_surface_params } elif self.save_as_esri_generate_QRadioButton.isChecked(): save_function = geosurface_export_esri_generate done = save_function(self.output_filename_QLineEdit.text(), geodata) if done: QMessageBox.information(self, "Surface saving", "Done") else: QMessageBox.critical(self, "Surface saving", "Some errors occurred")
class SectorSetingDlg(QDialog): def __init__(self, iface=None, directioy='', parent=None): super(SectorSetingDlg, self).__init__() self.iface = iface self.parent = parent self.directioy = directioy # 项目路径 self.setWindowTitle(u'扇区角度设置') self.setWindowIcon(QIcon('images/logo.png')) self.resize(280, 320) self.initView() def initView(self): self.setWindowFlags(Qt.WindowStaysOnTopHint) jsLable = QLabel(u'设置不同运营商扇形的角度和半径长度,\n方便在地图上分辨出各运营商的小区', self) jsBox = QHBoxLayout() jsBox.addWidget(jsLable) patternLabel = QLabel(u'请选择显示模式: ') paBox = QHBoxLayout() self.pattern1 = QRadioButton(u'指针模式 ', self) self.pattern1.setChecked(True) self.pattern2 = QRadioButton(u'扇形模式 ', self) paBox.addWidget(patternLabel) paBox.addStretch(1) paBox.addWidget(self.pattern1) paBox.addWidget(self.pattern2) angle_validator = QIntValidator(0, 360, self) ydLable = QLabel(u"角度:", self) self.ydInput = QLineEdit(self) self.ydInput.setPlaceholderText(u'移动:20') self.ydInput.setValidator(angle_validator) ydLenLable = QLabel(u'长度:', self) self.ydLenInput = QLineEdit(self) self.ydLenInput.setPlaceholderText(u'移动:0.0015') ydBox = QHBoxLayout() ydBox.addWidget(ydLable) ydBox.addWidget(self.ydInput) ydBox.addWidget(ydLenLable) ydBox.addWidget(self.ydLenInput) ltLable = QLabel(u'角度:', self) self.ltInput = QLineEdit(self) self.ltInput.setPlaceholderText(u'联通:30') self.ltInput.setValidator(angle_validator) ltLenLable = QLabel(u'长度:', self) self.ltLenInput = QLineEdit(self) self.ltLenInput.setPlaceholderText(u'联通:0.0015') ltBox = QHBoxLayout() ltBox.addWidget(ltLable) ltBox.addWidget(self.ltInput) ltBox.addWidget(ltLenLable) ltBox.addWidget(self.ltLenInput) dxLable = QLabel(u'角度:', self) self.dxInput = QLineEdit(self) self.dxInput.setPlaceholderText(u'电信:40') self.dxInput.setValidator(angle_validator) dxLenLable = QLabel(u'长度:', self) self.dxLenInput = QLineEdit(self) self.dxLenInput.setPlaceholderText(u'电信:0.0015') dxBox = QHBoxLayout() dxBox.addWidget(dxLable) dxBox.addWidget(self.dxInput) dxBox.addWidget(dxLenLable) dxBox.addWidget(self.dxLenInput) ttLable = QLabel(u'角度:', self) self.ttInput = QLineEdit(self) self.ttInput.setPlaceholderText(u'铁塔:50') self.ttInput.setValidator(angle_validator) ttLenLable = QLabel(u'长度:', self) self.ttLenInput = QLineEdit(self) self.ttLenInput.setPlaceholderText(u'铁塔:0.0015') ttBox = QHBoxLayout() ttBox.addWidget(ttLable) ttBox.addWidget(self.ttInput) ttBox.addWidget(ttLenLable) ttBox.addWidget(self.ttLenInput) okBtn = QPushButton(u'确定', self) okBtn.clicked.connect(self.okBtnListenner) custom_btn = QPushButton(u'切换设置模式', self) custom_btn.clicked.connect(self.custom_setting) btnBox = QHBoxLayout() btnBox.addWidget(okBtn) btnBox.addWidget(custom_btn) vBox = QVBoxLayout() vBox.addLayout(jsBox) vBox.addLayout(paBox) vBox.addLayout(ydBox) vBox.addLayout(ltBox) vBox.addLayout(dxBox) vBox.addLayout(ttBox) vBox.addLayout(btnBox) vBox.setStretchFactor(jsLable, 3) vBox.setStretchFactor(ydBox, 2) vBox.setStretchFactor(ltBox, 2) vBox.setStretchFactor(dxBox, 2) vBox.setStretchFactor(ttBox, 2) vBox.setStretchFactor(btnBox, 1) self.setLayout(vBox) def okBtnListenner(self): self.accept() ydR = self.ydInput.text().strip() ltR = self.ltInput.text().strip() dxR = self.dxInput.text().strip() ttR = self.ttInput.text().strip() ydL = self.ydLenInput.text().strip() ltL = self.ltLenInput.text().strip() dxL = self.dxLenInput.text().strip() ttL = self.ttLenInput.text().strip() '''扇形模式扇形大小默认设置''' if not self.pattern1.isChecked() and self.pattern2.isChecked(): if ydR: ydR = int(ydR) else: ydR = 20 if ltR: ltR = int(ltR) else: ltR = 35 if dxR: dxR = int(dxR) else: dxR = 50 if ttR: ttR = int(ttR) else: ttR = 65 '''指针模式扇形大小默认设置''' if self.pattern1.isChecked() and not self.pattern2.isChecked(): ydR = 2 ltR = 2 dxR = 2 ttR = 2 if ydL: ydL = float(ydL) else: ydL = 0.0015 if ltL: ltL = float(ltL) else: ltL = 0.0015 if dxL: dxL = float(dxL) else: dxL = 0.0015 if ttL: ttL = float(ttL) else: ttL = 0.0015 # 传出角度设置参数,传于文本文件‘sectorsetting.txt’中 try: f = open(os.path.join(self.directioy, u'sectorsetting.txt'), 'w') sector_setting = {} sector_setting["type"] = 0 sector_setting[u"移动"] = (ydR, ydL) # (角度大小, 长度) sector_setting[u"联通"] = (ltR, ltL) sector_setting[u"电信"] = (dxR, dxL) sector_setting[u"铁塔"] = (ttR, ttL) # 把字典保存于txt中 pickle.dump(sector_setting, f) f.close() QMessageBox.information(self.parent, u"创建项目", u"创建项目成功") except IOError: QMessageBox.critical(self.parent, u"错误", u"请使用管理员身份运行QGIS软件 ") return def custom_setting(self): self.accept() setting_dlg = SectorSetingDlg2(self.iface, self.directioy, self.parent) setting_dlg.show() setting_dlg.exec_()
class SectorSetingDlg2(QDialog): def __init__(self, iface=None, directioy='', parent=None): super(SectorSetingDlg2, self).__init__() self.iface = iface self.directioy = directioy # 项目路径 self.parent = parent self.setWindowTitle(u"扇区图形设置") self.setWindowIcon(QIcon('images/logo.png')) self.resize(280, 350) self.initUI() def initUI(self): self.setWindowFlags(Qt.WindowStaysOnTopHint) patternLabel = QLabel(u'请选择显示模式: ') paBox = QHBoxLayout() self.pattern1 = QRadioButton(u'指针模式 ', self) self.pattern1.setChecked(True) self.pattern2 = QRadioButton(u'扇形模式 ', self) paBox.addWidget(patternLabel) paBox.addStretch(1) paBox.addWidget(self.pattern1) paBox.addWidget(self.pattern2) angle_validator = QIntValidator(0, 360, self) len_validator = QDoubleValidator(0, 99.99999, 5, self) # 取值范围为0~99.99999 label = QLabel(u"请输入网络制式和频段的相应图形参数:") default_label = QLabel(u"默认") self.default_angle = QLineEdit() self.default_angle.setPlaceholderText(u'角度大小:20') self.default_angle.setValidator(angle_validator) self.default_len = QLineEdit() self.default_len.setPlaceholderText(u'长度:0.0015') self.default_len.setValidator(len_validator) default_hbox = QHBoxLayout() default_hbox.addWidget(default_label) default_hbox.setStretchFactor(default_label, 1) default_hbox.addWidget(self.default_angle) default_hbox.addWidget(self.default_len) default_hbox.addStretch(1) system = [u"网络制式", u"G", u"D", u"C", u"W", u"T", u"F", u"TDS"] frequency = [ u"频段", u"700M", u"800M", u"900M", u"1800M", u"1900M", u"2100M", u"2300M", u"2600M" ] self.system_combox_1 = QComboBox() self.system_combox_1.addItems(system) self.frequency_combox_1 = QComboBox() self.frequency_combox_1.addItems(frequency) self.angle_1 = QLineEdit() self.angle_1.setPlaceholderText(u'角度大小:30') self.angle_1.setValidator(angle_validator) self.len_1 = QLineEdit() self.len_1.setPlaceholderText(u'长度:0.0015') self.len_1.setValidator(len_validator) hbox_1 = QHBoxLayout() hbox_1.setSpacing(10) hbox_1.addWidget(self.system_combox_1) hbox_1.addWidget(self.frequency_combox_1) hbox_1.addWidget(self.angle_1) hbox_1.addWidget(self.len_1) self.system_combox_2 = QComboBox() self.system_combox_2.addItems(system) self.frequency_combox_2 = QComboBox() self.frequency_combox_2.addItems(frequency) self.angle_2 = QLineEdit() self.angle_2.setPlaceholderText(u'角度大小:40') self.angle_2.setValidator(angle_validator) self.len_2 = QLineEdit() self.len_2.setPlaceholderText(u'长度:0.0015') self.len_2.setValidator(len_validator) hbox_2 = QHBoxLayout() hbox_2.setSpacing(10) hbox_2.addWidget(self.system_combox_2) hbox_2.addWidget(self.frequency_combox_2) hbox_2.addWidget(self.angle_2) hbox_2.addWidget(self.len_2) self.system_combox_3 = QComboBox() self.system_combox_3.addItems(system) self.frequency_combox_3 = QComboBox() self.frequency_combox_3.addItems(frequency) self.angle_3 = QLineEdit() self.angle_3.setPlaceholderText(u'角度大小:50') self.angle_3.setValidator(angle_validator) self.len_3 = QLineEdit() self.len_3.setPlaceholderText(u'长度:0.0015') self.len_3.setValidator(len_validator) hbox_3 = QHBoxLayout() hbox_3.setSpacing(10) hbox_3.addWidget(self.system_combox_3) hbox_3.addWidget(self.frequency_combox_3) hbox_3.addWidget(self.angle_3) hbox_3.addWidget(self.len_3) self.system_combox_4 = QComboBox() self.system_combox_4.addItems(system) self.frequency_combox_4 = QComboBox() self.frequency_combox_4.addItems(frequency) self.angle_4 = QLineEdit() self.angle_4.setPlaceholderText(u'角度大小:60') self.angle_4.setValidator(angle_validator) self.len_4 = QLineEdit() self.len_4.setPlaceholderText(u'长度:0.0015') self.len_4.setValidator(len_validator) hbox_4 = QHBoxLayout() hbox_4.setSpacing(10) hbox_4.addWidget(self.system_combox_4) hbox_4.addWidget(self.frequency_combox_4) hbox_4.addWidget(self.angle_4) hbox_4.addWidget(self.len_4) ok = QPushButton(u"确定") self.connect(ok, SIGNAL("clicked()"), self.okBtnListenner) operator = QPushButton(u'切换设置模式', self) operator.clicked.connect(self.operator_setting) btn_hbox = QHBoxLayout() btn_hbox.setSpacing(15) btn_hbox.addWidget(ok) btn_hbox.addWidget(operator) vbox = QVBoxLayout() vbox.setSpacing(10) vbox.addWidget(label) vbox.addLayout(paBox) vbox.addLayout(default_hbox) vbox.addLayout(hbox_1) vbox.addLayout(hbox_2) vbox.addLayout(hbox_3) vbox.addLayout(hbox_4) vbox.addStretch(1) vbox.addLayout(btn_hbox) self.setLayout(vbox) def operator_setting(self): self.accept() setting_dlg = SectorSetingDlg(self.iface, self.directioy, self.parent) setting_dlg.show() setting_dlg.exec_() def okBtnListenner(self): default_angle = self.default_angle.text().strip() default_len = self.default_len.text().strip() system_1 = self.system_combox_1.currentText().strip() frequency_1 = self.frequency_combox_1.currentText().strip() angle_1 = self.angle_1.text().strip() len_1 = self.len_1.text().strip() system_2 = self.system_combox_2.currentText().strip() frequency_2 = self.frequency_combox_2.currentText().strip() angle_2 = self.angle_2.text().strip() len_2 = self.len_2.text().strip() system_3 = self.system_combox_3.currentText().strip() frequency_3 = self.frequency_combox_3.currentText().strip() angle_3 = self.angle_3.text().strip() len_3 = self.len_3.text().strip() system_4 = self.system_combox_4.currentText().strip() frequency_4 = self.frequency_combox_4.currentText().strip() angle_4 = self.angle_4.text().strip() len_4 = self.len_4.text().strip() '''扇形模式扇形大小默认设置''' if not self.pattern1.isChecked() and self.pattern2.isChecked(): if default_angle: default_angle = int(default_angle) else: default_angle = 20 if angle_1: angle_1 = int(angle_1) else: angle_1 = 30 if angle_2: angle_2 = int(angle_2) else: angle_2 = 40 if angle_3: angle_3 = int(angle_3) else: angle_3 = 50 if angle_4: angle_4 = int(angle_4) else: angle_4 = 60 '''指针模式扇形大小默认设置''' if self.pattern1.isChecked() and not self.pattern2.isChecked(): default_angle = 2 angle_1 = 2 angle_2 = 2 angle_3 = 2 angle_4 = 2 if default_len: default_len = float(default_len) else: default_len = 0.0015 if len_1: len_1 = float(len_1) else: len_1 = 0.0015 if len_2: len_2 = float(len_2) else: len_2 = 0.0015 if len_3: len_3 = float(len_3) else: len_3 = 0.0015 if len_4: len_4 = float(len_4) else: len_4 = 0.0015 try: # 传出角度设置参数,传于文本文件‘sectorsetting.txt’中 f = open(os.path.join(self.directioy, u'sectorsetting.txt'), 'w') sector_setting = {} sector_setting["type"] = 1 sector_setting[u"默认"] = (default_angle, default_len) # (角度大小, 长度) case_list = [] if (self.system_combox_1.currentIndex() != 0) or (self.frequency_combox_1.currentIndex() != 0): if self.system_combox_1.currentIndex() == 0: system_1 = None if self.frequency_combox_1.currentIndex() == 0: frequency_1 = None case_1 = (system_1, frequency_1, angle_1, len_1) case_list.append(case_1) if (self.system_combox_2.currentIndex() != 0) or (self.frequency_combox_2.currentIndex() != 0): if self.system_combox_2.currentIndex() == 0: system_2 = None if self.frequency_combox_2.currentIndex() == 0: frequency_2 = None case_2 = (system_2, frequency_2, angle_2, len_2) case_list.append(case_2) if (self.system_combox_3.currentIndex() != 0) or (self.frequency_combox_3.currentIndex() != 0): if self.system_combox_3.currentIndex() == 0: system_3 = None if self.frequency_combox_3.currentIndex() == 0: frequency_3 = None case_3 = (system_3, frequency_3, angle_3, len_3) case_list.append(case_3) if (self.system_combox_4.currentIndex() != 0) or (self.frequency_combox_4.currentIndex() != 0): if self.system_combox_4.currentIndex() == 0: system_4 = None if self.frequency_combox_4.currentIndex() == 0: frequency_4 = None case_4 = (system_4, frequency_4, angle_4, len_4) case_list.append(case_4) sector_setting["case_list"] = case_list # 把字典保存于txt中 pickle.dump(sector_setting, f) f.close() QMessageBox.information(self.parent, u'创建项目', u'创建项目成功') except IOError: QMessageBox.critical(self.parent, u"错误", u"请使用管理员身份运行QGIS软件 ") return
class ExpensesDialog(QDialog): holdc = {} def __init__(self, session, parent=None): super(ExpensesDialog, self).__init__(parent) self.session = session session = self.pullOnes('session', session) self.sessionname = str(session['name']) + ' Session' self.pagetitle = self.sessionname self.tableFont = QFont('Century Gothic', 8) #self.tableFont.setFamily('Century Gothic') self.tableHeaderStyle = "::section {" "background-color: teal; color:white}" #pull all CA self.editID = 0 self.hold_account = {} self.hold_expenses = {} self.hold_expensesGroup = {} from_label = QLabel('From:') to_label = QLabel('To:') self.fromData = QDateEdit() self.toData = QDateEdit() currentDate = QDate() self.fromData.setDate(currentDate.currentDate()) self.fromData.setCalendarPopup(True) self.toData.setDate(currentDate.currentDate()) self.toData.setCalendarPopup(True) self.pull_btn = QPushButton() self.pull_btn.setText("Load") h_pull_box = QHBoxLayout() h_pull_box.addWidget(from_label) h_pull_box.addWidget(self.fromData) h_pull_box.addWidget(to_label) h_pull_box.addWidget(self.toData) h_pull_box.addWidget(self.pull_btn) expensesGroup = self.pullGroupExpenses() account = self.pullAccount() self.expenseGroupText = QLabel('Category') self.expenseGroupData = QComboBox() self.expenseGroupData.currentIndexChanged.connect(self.reloadExpenses) self.expenseText = QLabel('Expenses') self.expenseData = QComboBox() self.amountText = QLabel('Amount') self.amountData = QLineEdit() self.amountData.setPlaceholderText('0000.00') self.tellerText = QLabel('Teller/Reciept No.') self.tellerData = QLineEdit() self.tellerData.setPlaceholderText('xxxxxxxxx') self.accountText = QLabel('Account') self.accountData = QComboBox() self.dateText = QLabel('Date') self.dateData = QDateEdit() self.dateData.setDate(currentDate.currentDate()) self.dateData.setCalendarPopup(True) self.descriptionText = QLabel('Brief Description') self.descriptionData = QPlainTextEdit() self.descriptionData.move(200, 100) hboz = QHBoxLayout() self.gender = QLabel('State') self.r1 = QRadioButton('Expenses') self.r1.setChecked(True) self.r2 = QRadioButton('Refund') hboz.addWidget(self.r1) hboz.addWidget(self.r2) i = 0 for a in expensesGroup: self.hold_expensesGroup[i] = a['id'] tex = str(a['name']).upper() self.expenseGroupData.addItem(tex) i += 1 i = 0 exp_key = self.hold_expensesGroup[self.expenseGroupData.currentIndex()] expenses = self.pullExpenses(exp_key) for a in expenses: self.hold_expenses[i] = a['id'] tex = str(a['name']).upper() self.expenseData.addItem(tex) i += 1 i = 0 for a in account: self.hold_account[i] = a['id'] tex = str(a['name']).upper() self.accountData.addItem(tex) i += 1 self.FormLayout = QFormLayout() self.FormLayout.addRow(self.expenseGroupText, self.expenseGroupData) self.FormLayout.addRow(self.expenseText, self.expenseData) self.FormLayout.addRow(self.accountText, self.accountData) self.FormLayout.addRow(self.tellerText, self.tellerData) self.FormLayout.addRow(self.amountText, self.amountData) self.FormLayout.addRow(self.gender, hboz) self.FormLayout.addRow(self.dateText, self.dateData) self.FormLayout.addRow(self.descriptionText, self.descriptionData) groupBox1 = QGroupBox('Add Expenses') groupBox1.setLayout(self.FormLayout) self.pb = QPushButton() self.pb.setObjectName("Add") self.pb.setText("Add Expenses") self.pb1 = QPushButton() self.pb1.setObjectName("Edit") self.pb1.setText("Edit Row") self.pb1.setEnabled(False) self.pb2 = QPushButton() self.pb2.setObjectName("Close") self.pb2.setText("Close") self.pb3 = QPushButton() self.pb3.setObjectName("Delete") self.pb3.setText("Delete Row") self.pb3.setEnabled(False) self.pb4 = QPushButton() self.pb4.setObjectName("Reset") self.pb4.setText("Reset") self.pb4.hide() self.pb5 = QPushButton() self.pb5.setObjectName("Change") self.pb5.setText("Change Expenses") self.pb5.hide() self.pb6 = QPushButton() self.pb6.setObjectName("Clear") self.pb6.setText("Clear Selection") self.pb6.setEnabled(False) hbo = QHBoxLayout() hbo.addWidget(self.pb) hbo.addWidget(self.pb5) hbo.addWidget(self.pb4) hbo.addWidget(self.pb2) groupBox2 = QGroupBox('Expenses Data') groupBox2.setLayout(hbo) self.cols = ['SN', 'EXPENSES', 'ACCOUNT', 'AMOUNT', 'DATE'] al = self.pullExpensesData() if len(al) > 0: al = al else: al = {} self.table = QTableWidget() header = self.table.horizontalHeader() header.setResizeMode(QHeaderView.ResizeToContents) header.setStretchLastSection(True) header.setStyleSheet(self.tableHeaderStyle) vheader = self.table.verticalHeader() vheader.setStyleSheet(self.tableHeaderStyle) # Body self.table.setWindowTitle("Expenses") self.table.resize(300, 250) self.table.setFont(self.tableFont) self.table.setSortingEnabled(2) #self.table.resizeColumnsToContents() self.table.setRowCount(len(al)) self.table.setColumnCount(len(self.cols)) self.table.setHorizontalHeaderLabels(self.cols) self.table.setContextMenuPolicy(Qt.CustomContextMenu) self.table.customContextMenuRequested.connect(self.handleHeaderMenu) self.table.hideColumn(0) self.table.setSelectionMode(QAbstractItemView.MultiSelection) self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.setEditTriggers(QAbstractItemView.NoEditTriggers) i = 0 for q in al: #row id self.table.setItem(i, 0, QTableWidgetItem(str(q['id']))) self.table.setItem(i, 1, QTableWidgetItem(str(q['expensename']).upper())) self.table.setItem(i, 2, QTableWidgetItem(str(q['accountname']).upper())) zamt = str("{:,}".format(float(q['amount']))) self.table.setItem(i, 3, QTableWidgetItem(zamt)) damz = float(q['datepaid']) damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y') self.table.setItem(i, 4, QTableWidgetItem(str(damt))) i += 1 self.table.itemSelectionChanged.connect(self.confirmSelection) self.table.resizeRowsToContents() v_pull_box = QVBoxLayout() self.h1_pull_box = QVBoxLayout() self.h1_pull_box.addWidget(self.table) v_pull_box.addLayout(h_pull_box) v_pull_box.addLayout(self.h1_pull_box) h2_pull_box = QHBoxLayout() h2_pull_box.addWidget(self.pb1) h2_pull_box.addWidget(self.pb3) h2_pull_box.addWidget(self.pb6) v_pull_box.addLayout(h2_pull_box) groupBox3 = QGroupBox() groupBox3.setLayout(hbo) groupBox2.setLayout(v_pull_box) grid = QGridLayout() grid.addWidget(groupBox1, 0, 0) grid.addWidget(groupBox2, 0, 1, 2, 1) grid.addWidget(groupBox3, 1, 0) self.setLayout(grid) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click()) self.connect(self.pb1, SIGNAL("clicked()"), lambda: self.button_editshow()) self.connect(self.pb2, SIGNAL("clicked()"), lambda: self.button_close(self)) self.connect(self.pb3, SIGNAL("clicked()"), lambda: self.button_delete()) self.connect(self.pb4, SIGNAL("clicked()"), lambda: self.button_reset()) self.connect(self.pb5, SIGNAL("clicked()"), lambda: self.button_edit()) self.connect(self.pb6, SIGNAL("clicked()"), lambda: self.button_clear()) self.connect(self.pull_btn, SIGNAL("clicked()"), lambda x=1: self.reloadTable(x)) self.setWindowTitle(self.pagetitle) def handleHeaderMenu(self, pos): print('column(%d)' % self.table.horizontalHeader().logicalIndexAt(pos)) menu = QMenu() menu.addAction('Add') menu.addAction('Delete') menu.exec_(QCursor.pos()) def pullGroupExpenses(self): cn = Db() arr = cn.selectn('datas', '', '', {"pubID": 15, "active": 0}) return arr def pullExpenses(self, a): cn = Db() arr = cn.selectn('datas', '', '', {"subID": a}) return arr def pullAccount(self): cn = Db() arr = cn.selectn('datas', '', '', {"pubID": 20, "active": 0}) return arr def pullExpensesData(self): st_date = self.fromData.date().toPyDate() en_date = self.toData.date().toPyDate() st_date = time.mktime(st_date.timetuple()) en_date = time.mktime(en_date.timetuple()) db = 'school_expenses' + str(self.session) cn = Db() arr = cn.selectExpenseDate(db, st_date, en_date) return arr def mySelectTable(self): ''' get the selected rpws in a table returns list or row ids ''' sels = self.table.selectedIndexes() sels = self.table.selectionModel().selectedRows() park = [] park1 = [] for j in sels: park.append(j.row()) for i in set(park): selected = self.table.item(i, 0).text() park1.append(selected) return park1 def editRow(self, a): _session = self.session g = Db() db = 'school_expenses' + str(_session) data = g.selectn(db, '', 1, {'id': a}) if len(data) > 0: self.editID = int(data['id']) if float(data['amount']) < 0: amt = float(data['amount']) * -1 self.amountData.setText(str(amt)) self.r1.setChecked(True) else: amt = float(data['amount']) self.amountData.setText(str(amt)) self.r2.setChecked(True) self.descriptionData.clear() self.descriptionData.insertPlainText(str(data['description'])) self.tellerData.setText(str(data['teller'])) acID = self.hold_account.keys()[self.hold_account.values().index( data['accountID'])] self.accountData.setCurrentIndex(acID) exID = self.hold_expenses.keys()[self.hold_expenses.values().index( data['expenseID'])] self.expenseData.setCurrentIndex(exID) def reloadExpenses(self): cat = self.hold_expensesGroup[self.expenseGroupData.currentIndex()] expenses = self.pullExpenses(cat) self.expenseData.clear() self.hold_expenses = {} i = 0 for a in expenses: self.hold_expenses[i] = a['id'] tex = str(a['name']).upper() self.expenseData.addItem(tex) i += 1 def reloadTable(self, a): data = self.pullExpensesData() self.table.close() self.table = QTableWidget() header = self.table.horizontalHeader() header.setResizeMode(QHeaderView.ResizeToContents) header.setStretchLastSection(True) header.setStyleSheet(self.tableHeaderStyle) vheader = self.table.verticalHeader() vheader.setStyleSheet(self.tableHeaderStyle) # Body self.table.setWindowTitle("Expenses") self.table.resize(300, 250) self.table.setFont(self.tableFont) self.table.setSortingEnabled(2) self.table.resizeColumnsToContents() self.table.setRowCount(len(data)) self.table.setColumnCount(len(self.cols)) self.table.setHorizontalHeaderLabels(self.cols) self.table.setContextMenuPolicy(Qt.CustomContextMenu) self.table.customContextMenuRequested.connect(self.handleHeaderMenu) self.table.hideColumn(0) self.table.setSelectionMode(QAbstractItemView.MultiSelection) self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.setEditTriggers(QAbstractItemView.NoEditTriggers) i = 0 for q in data: #row id self.table.setItem(i, 0, QTableWidgetItem(str(q['id']))) self.table.setItem(i, 1, QTableWidgetItem(str(q['expensename']).upper())) self.table.setItem(i, 2, QTableWidgetItem(str(q['accountname']).upper())) zamt = str("{:,}".format(float(q['amount']))) self.table.setItem(i, 3, QTableWidgetItem(zamt)) damz = float(q['datepaid']) damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y') self.table.setItem(i, 4, QTableWidgetItem(str(damt))) i += 1 self.table.itemSelectionChanged.connect(self.confirmSelection) self.table.resizeRowsToContents() self.h1_pull_box.addWidget(self.table) self.table.show() def pullOnes(self, a, b): cn = Db() arr = cn.selectn(a, '', 1, {'id': b}) return arr def confirmSelection(self): item = self.mySelectTable() if len(item) == 1: self.pb1.setEnabled(True) self.pb3.setEnabled(True) self.pb6.setEnabled(True) elif len(item) > 1: self.pb1.setEnabled(False) self.pb3.setEnabled(True) self.pb6.setEnabled(True) else: self.pb1.setEnabled(False) self.pb3.setEnabled(False) self.pb6.setEnabled(False) def button_close(self, b): b.close() def button_editshow(self): item = self.mySelectTable() self.editRow(item[0]) self.pb.hide() self.pb4.show() self.pb5.show() def button_delete(self): item = self.mySelectTable() _session = self.session g = Db() db = 'school_expenses' + str(_session) for j in item: g.delete(db, {'id': j}) self.reloadTable(1) def button_edit(self): _session = self.session _amount = self.amountData.text() _teller = self.tellerData.text() _date = self.dateData.date().toPyDate() _date = time.mktime(_date.timetuple()) _description = self.descriptionData.toPlainText() _account = self.hold_account[self.accountData.currentIndex()] _expense = self.hold_expenses[self.expenseData.currentIndex()] if self.r1.isChecked(): _amount = float(_amount) else: _amount = float(_amount) * -1 arr = {} if _amount and not (_amount == 0) and int(_expense) > 0 and int(_account) > 0: arr['amount'] = _amount arr['datepaid'] = _date arr['description'] = _description arr['accountID'] = _account arr['expenseID'] = _expense arr['teller'] = _teller ups = {} ups['id'] = self.editID if int(self.editID) > 0: db = 'school_expenses' + str(_session) g = Db() g.update(db, arr, ups) if int(self.editID) > 0: self.button_reset() def button_reset(self): self.reloadTable(1) self.amountData.setText('') self.descriptionData.clear() self.tellerData.setText('') self.pb4.hide() self.pb5.hide() self.pb.show() self.editID = 0 self.button_clear() self.confirmSelection() def button_clear(self): self.table.selectionModel().clearSelection() def button_click(self): _session = self.session _amount = self.amountData.text() _teller = self.tellerData.text() _date = self.dateData.date().toPyDate() _date = time.mktime(_date.timetuple()) _description = self.descriptionData.toPlainText() _account = self.hold_account[self.accountData.currentIndex()] _expense = self.hold_expenses[self.expenseData.currentIndex()] if self.r1.isChecked(): _amount = float(_amount) else: _amount = float(_amount) * -1 arr = {} if _amount and not (_amount == 0) and int(_expense) > 0 and int(_account) > 0: arr['amount'] = _amount arr['datepaid'] = _date arr['description'] = _description arr['accountID'] = _account arr['expenseID'] = _expense arr['teller'] = _teller db = 'school_expenses' + str(_session) g = Db() ins = g.insert(db, arr) if int(ins) > 0: self.button_reset()
class SearchUI(QDialog): def __init__(self, iface, parent=None): super(SearchUI, self).__init__() self.iface = iface self.parent = parent # 获取图层对象 self.siteLayer = getLayerByName(u'基站', self.iface) self.cellLayer = getLayerByName(u'小区', self.iface) self.initUI() # 初始化界面 def initUI(self): self.setGeometry(200, 200, 250, 200) self.setWindowTitle(u'查找') title = QLabel(u'请选择搜索模式:') self.type_site_id = QRadioButton(u"基站ID ") self.type_site_id.setChecked(True) # 默认查找基站ID self.type_site_name = QRadioButton(u"基站名 ") self.type_cell_id = QRadioButton(u"小区ID ") self.type_cell_name = QRadioButton(u"小区名 ") self.type_pn = QRadioButton(u"PN ") self.type_psc = QRadioButton(u"PSC ") self.type_pci = QRadioButton(u"PCI ") self.type_bcch = QRadioButton(u"BCCH ") search_type = QButtonGroup() search_type.addButton(self.type_site_id) search_type.addButton(self.type_site_name) search_type.addButton(self.type_cell_id) search_type.addButton(self.type_cell_name) search_type.addButton(self.type_pn) search_type.addButton(self.type_psc) search_type.addButton(self.type_pci) search_type.addButton(self.type_bcch) search_grid = QGridLayout() search_grid.setSpacing(10) search_grid.addWidget(self.type_site_id, 0, 1) search_grid.addWidget(self.type_site_name, 0, 2) search_grid.addWidget(self.type_cell_id, 0, 3) search_grid.addWidget(self.type_cell_name, 0, 4) search_grid.addWidget(self.type_pn, 1, 1) search_grid.addWidget(self.type_psc, 1, 2) search_grid.addWidget(self.type_pci, 1, 3) search_grid.addWidget(self.type_bcch, 1, 4) search_hbox = QHBoxLayout() search_hbox.setSpacing(10) search_hbox.addStretch(1) search_hbox.addLayout(search_grid) search_hbox.addStretch(1) self.searchText = QLineEdit() ok = QPushButton(u'确定') self.connect(ok, SIGNAL('clicked()'), self.search) cancel = QPushButton(u'取消') self.connect(cancel, SIGNAL('clicked()'), self.cancel) btn_hbox = QHBoxLayout() btn_hbox.setSpacing(10) btn_hbox.addStretch(1) btn_hbox.addWidget(ok) btn_hbox.addWidget(cancel) btn_hbox.addStretch(1) vbox = QVBoxLayout() vbox.setSpacing(15) vbox.addWidget(title) vbox.addLayout(search_hbox) vbox.addWidget(self.searchText) vbox.addStretch(1) vbox.addLayout(btn_hbox) self.setLayout(vbox) self.resize(350, 190) # 取消按钮监听事件 def cancel(self): self.iface.mapCanvas().setSelectionColor(QColor("yellow")) self.accept() # 重写关闭事件 def closeEvent(self, event): self.iface.mapCanvas().setSelectionColor(QColor("yellow")) # 确定按钮绑定事件 def search(self): search_text = self.searchText.text().strip() # 检查是否已填入搜索数据 if search_text == "": QMessageBox.critical(self, u"错误", u"请输入查找内容!") return False layer = None if self.type_site_id.isChecked(): layer = self.siteLayer sql = u'"基站ID" =\'' + search_text + u'\'' resultFeatures = getFeaturesBySQL(self.iface, u"基站", sql) elif self.type_site_name.isChecked(): layer = self.siteLayer sql = u'"基站名" LIKE \'%' + search_text + u'%\'' resultFeatures = getFeaturesBySQL(self.iface, u"基站", sql) elif self.type_cell_id.isChecked(): layer = self.cellLayer sql = u'"小区ID" LIKE \'%' + search_text + u'%\'' resultFeatures = getFeaturesBySQL(self.iface, u"小区", sql) elif self.type_cell_name.isChecked(): layer = self.cellLayer sql = u'"小区名" LIKE \'%' + search_text + u'%\'' resultFeatures = getFeaturesBySQL(self.iface, u"小区", sql) elif self.type_pn.isChecked(): layer = self.cellLayer sql = u'"PN" =\'' + search_text + u'\'' resultFeatures = getFeaturesBySQL(self.iface, u"小区", sql) elif self.type_psc.isChecked(): layer = self.cellLayer sql = u'"PSC" =\'' + search_text + u'\'' resultFeatures = getFeaturesBySQL(self.iface, u"小区", sql) elif self.type_pci.isChecked(): layer = self.cellLayer sql = u'"PCI" =\'' + search_text + u'\'' resultFeatures = getFeaturesBySQL(self.iface, u"小区", sql) elif self.type_bcch.isChecked(): layer = self.cellLayer sql = u'"BCCH" =\'' + search_text + u'\'' resultFeatures = getFeaturesBySQL(self.iface, u"小区", sql) else: QMessageBox.critical(self, u"提醒", u"找不到相关信息,请重新输入或选择!") return False if len(resultFeatures) == 0: QMessageBox.critical(self, u"提醒", u"找不到相关基站或小区!") return False else: # 获取所有搜索结果features的id resultId_list = [] for f in resultFeatures: resultId_list.append(f.id()) # 取消现有选择 self.cellLayer.setSelectedFeatures([]) self.siteLayer.setSelectedFeatures([]) layer.setSelectedFeatures(resultId_list) self.iface.mapCanvas().setSelectionColor(QColor("red")) self.iface.activeLayer = layer self.iface.actionZoomToSelected().trigger()
class AnimationWindow(PyDialog): """ +-------------------+ | Animation | +-------------------------+ | icase ______ | | scale ______ Default | | time ______ Default | | | | nframes ______ Default | | resolu. ______ Default | | Dir ______ Browse | | iFrame ______ | | | | Animations: | | o Scale, Phase, Time | # TODO: add time | | | x delete images | | x repeat | # TODO: change to an integer | x make gif | | | | Step, RunAll | | Close | +-------------------------+ TODO: add key-frame support """ def __init__(self, data, win_parent=None): PyDialog.__init__(self, data, win_parent) self.set_font_size(data['font_size']) self.istep = 0 self._animate_type = 'time' self._updated_animation = False self._icase = data['icase'] self._default_name = data['name'] self._default_time = data['time'] self._default_fps = data['frames/sec'] self._default_resolution = data['resolution'] self._scale = data['scale'] self._default_scale = data['default_scale'] self._default_is_scale = data['is_scale'] self._phase = data['phase'] self._default_phase = data['default_phase'] self._default_dirname = data['dirname'] self._default_gif_name = os.path.join(self._default_dirname, data['name'] + '.gif') self.animation_types = [ 'Animate Scale', ] #'Animate Phase', #'Animate Time', #'Animate Frequency Sweep' #] self.setWindowTitle('Animate Model') self.create_widgets() self.create_layout() self.set_connections() self.is_gui = False if hasattr(self.win_parent, '_updated_legend'): self.win_parent.is_animate_open = True self.is_gui = True def create_widgets(self): """creates the menu objects""" icase_max = 1000 # TODO: update 1000 self.icase = QLabel("iCase:") self.icase_edit = QSpinBox(self) self.icase_edit.setRange(1, icase_max) self.icase_edit.setSingleStep(1) self.icase_edit.setValue(self._icase) self.icase_edit.setToolTip( 'Case Number for the Scale/Phase Animation Type.\n' 'Defaults to the result you had shown when you clicked "Create Animation".\n' 'iCase can be seen by clicking "Apply" on a result.') self.scale = QLabel("Scale:") self.scale_edit = QLineEdit(str(self._scale)) self.scale_button = QPushButton("Default") self.scale_edit.setToolTip('Scale factor of the "deflection"') self.scale_button.setToolTip('Sets the scale factor of the gif to %s' % self._scale) self.time = QLabel("Total Time (sec):") self.time_edit = QDoubleSpinBox(self) self.time_edit.setValue(self._default_time) self.time_edit.setRange(0.1, 10.0) self.time_edit.setDecimals(2) self.time_edit.setSingleStep(0.1) self.time_button = QPushButton("Default") self.time_edit.setToolTip("Total time of the gif") self.time_button.setToolTip('Sets the total time of the gif to %.2f' % self._default_time) self.fps = QLabel("Frames/Second:") self.fps_edit = QSpinBox(self) self.fps_edit.setRange(1, 60) self.fps_edit.setSingleStep(1) self.fps_edit.setValue(self._default_fps) self.fps_button = QPushButton("Default") self.fps_edit.setToolTip( "A higher FPS is smoother, but may not play well for large gifs") self.fps_button.setToolTip('Sets the FPS to %s' % self._default_fps) self.resolution = QLabel("Resolution Scale:") self.resolution_edit = QSpinBox(self) self.resolution_edit.setRange(1, 5) self.resolution_edit.setSingleStep(1) self.resolution_edit.setValue(self._default_resolution) self.resolution_button = QPushButton("Default") self.resolution_edit.setToolTip( 'Scales the window resolution by an integer factor') self.resolution_button.setToolTip('Sets the resolution to %s' % self._default_resolution) #----------------- # Time plot self.icase_start = QLabel("iCase Start:") self.icase_start_edit = QSpinBox(self) self.icase_start_edit.setRange(0, icase_max) self.icase_start_edit.setSingleStep(1) self.icase_start_edit.setValue(self._icase) self.icase_start_button = QPushButton("Default") self.icase_end = QLabel("iCase End:") self.icase_end_edit = QSpinBox(self) self.icase_end_edit.setRange(0, icase_max) self.icase_end_edit.setSingleStep(1) self.icase_end_edit.setValue(self._icase) self.icase_end_button = QPushButton("Default") self.icase_delta = QLabel("iCase Delta:") self.icase_delta_edit = QSpinBox(self) self.icase_delta_edit.setRange(1, icase_max) self.icase_delta_edit.setSingleStep(1) self.icase_delta_edit.setValue(1) self.icase_delta_button = QPushButton("Default") self.min_value = QLabel("Min Value:") self.min_value_edit = QLineEdit(str(0.)) #self.min_value_edit.setRange(1, 1000) #self.min_value_edit.setSingleStep(1) #self.min_value_edit.setValue(1) self.min_value_button = QPushButton("Default") self.max_value = QLabel("Max Value:") self.max_value_edit = QLineEdit(str(1.)) #self.min_value_edit.setRange(1, 1000) # TODO: update 1000 #self.min_value_edit.setSingleStep(1) #self.min_value_edit.setValue(1) self.max_value_button = QPushButton("Default") self.icase_start_edit.setToolTip('The first frame of the animation') self.icase_end_edit.setToolTip( 'The last frame of the animation\n' 'Assumes icase_start + nframes * icase_delta = icase_end') self.icase_delta_edit.setToolTip( 'The frame step size (to skip non-consecutive results).\n' 'Frame skipping can be used to:\n' " - skip across results that you don't want to plot\n" ' - adjust the FPS') self.min_value_edit.setToolTip( 'Min value of the legend (not supported)') self.max_value_edit.setToolTip( 'Max value of the legend (not supported)') #'time' : 0., #'default_time' : 0, #'icase_start' : 10, #'icase_delta' : 3, #'min_value' : 0., #'max_value' : 1000., self.browse_folder = QLabel('Output Directory:') self.browse_folder_edit = QLineEdit(str(self._default_dirname)) self.browse_folder_button = QPushButton('Browse') self.browse_folder_edit.setToolTip( 'Location to save the png/gif files') self.gif = QLabel("Gif Filename:") self.gif_edit = QLineEdit(str(self._default_name + '.gif')) self.gif_button = QPushButton('Default') self.gif_edit.setToolTip('Name of the gif') self.gif_button.setToolTip('Sets the name of the gif to %s.gif' % self._default_name) # scale / phase self.animate_scale_radio = QRadioButton("Animate Scale") self.animate_phase_radio = QRadioButton("Animate Phase") self.animate_time_radio = QRadioButton("Animate Time") self.animate_freq_sweeep_radio = QRadioButton( "Animate Frequency Sweep") self.animate_scale_radio.setToolTip( 'Animates the scale factor based on the "Animation Type"') self.animate_time_radio.setToolTip('Animates the time/load/mode step') self.animate_scale_radio.setChecked(self._default_is_scale) self.animate_phase_radio.setChecked(not self._default_is_scale) self.animate_time_radio.setChecked(False) msg = 'Scale : Animates the scale factor based on the "Animation Profile"\n' if self._default_phase is None: self.animate_phase_radio.setDisabled(True) self.animate_phase_radio.setToolTip('Animates the phase angle ' '(only for complex results)') msg += 'Phase : Animates the phase angle (only for complex results)\n' else: self.animate_phase_radio.setToolTip("Animates the phase angle") msg += 'Phase : Animates the phase angle\n' msg += ( 'Time : Animates the time/load/mode step\n' 'Freq Sweep : Animates a complex result across a range of frequencies ' '(not supported)\n') self.animate_freq_sweeep_radio.setDisabled(True) self.animate_freq_sweeep_radio.setToolTip( 'Animates a complex result across a range of frequencies (not supported)' ) self.animation_type = QLabel("Animation Type:") animation_type = OrderedDict() #scale_msg = 'Scale\n' #phase_msg = 'Phase\n' #time_msg = 'Time\n' #animation_types = [ #('Animate Scale', scale_msg), #('Animate Phase', phase_msg), #('Animate Time', time_msg), ##'Animate Frequency Sweep' #] if self._phase is not None: self.animation_types.append('Animate Phase') self.animation_types.append('Animate Time') self.animation_profile = QLabel("Animation Profile:") self.animation_profile_edit = QComboBox() for animation_profile in ANIMATION_PROFILES: self.animation_profile_edit.addItem(animation_profile) self.animation_profile_edit.setToolTip('The profile for a scaled GIF') self.animation_type_edit = QComboBox() # TODO: add a tooltip for each item for animation_type in self.animation_types: self.animation_type_edit.addItem(animation_type) #self.animation_type_edit.setToolTip('The profile for a scaled GIF') self.animation_type_edit.setToolTip(msg) self.csv_profile = QLabel("CSV profile:") self.csv_profile_edit = QLineEdit() self.csv_profile_browse_button = QPushButton('Browse') self.csv_profile_edit.setToolTip( 'The path to the CSV file of (Scale1, Scale2, Scale3, ...)') widget = QWidget(self) horizontal_vertical_group = QButtonGroup(widget) horizontal_vertical_group.addButton(self.animate_scale_radio) horizontal_vertical_group.addButton(self.animate_phase_radio) horizontal_vertical_group.addButton(self.animate_time_radio) horizontal_vertical_group.addButton(self.animate_freq_sweeep_radio) # one / two sided self.onesided_radio = QRadioButton("One Sided") self.onesided_radio.setToolTip( "A one sided gif doesn't return to the starting point (e.g., 0 to 360 degrees)" ) self.twosided_radio = QRadioButton("Two Sided") self.twosided_radio.setToolTip( 'A two sided gif returns to the starting point (e.g., 0 to 10 to 0)' ) if self._default_phase is None: self.onesided_radio.setChecked(False) self.twosided_radio.setChecked(True) else: self.onesided_radio.setChecked(True) self.twosided_radio.setChecked(False) widget = QWidget(self) horizontal_vertical_group = QButtonGroup(widget) horizontal_vertical_group.addButton(self.onesided_radio) horizontal_vertical_group.addButton(self.twosided_radio) # animate in gui self.animate_in_gui_checkbox = QCheckBox("Animate In GUI?") self.animate_in_gui_checkbox.setChecked(True) # make images self.make_images_checkbox = QCheckBox("Make images?") self.make_images_checkbox.setChecked(True) # make images self.overwrite_images_checkbox = QCheckBox("Overwrite images?") self.overwrite_images_checkbox.setChecked(True) # delete images when finished self.delete_images_checkbox = QCheckBox("Delete images when finished?") self.delete_images_checkbox.setChecked(True) # endless loop self.repeat_checkbox = QCheckBox("Repeat?") self.repeat_checkbox.setChecked(True) self.repeat_checkbox.setToolTip( "Repeating creates an infinitely looping gif") # endless loop self.make_gif_checkbox = QCheckBox("Make Gif?") if IS_IMAGEIO: self.make_gif_checkbox.setChecked(True) else: self.make_gif_checkbox.setChecked(False) self.make_gif_checkbox.setEnabled(False) self.make_gif_checkbox.setToolTip( 'imageio is not available; install it') # bottom buttons self.step_button = QPushButton("Step") self.stop_button = QPushButton("Stop") self.run_button = QPushButton("Run All") #self.apply_button = QPushButton("Apply") #self.ok_button = QPushButton("OK") self.cancel_button = QPushButton("Close") #self.set_grid_time(enabled=False) #self.set_grid_scale(enabled=self._default_is_scale) if self._default_phase: self.on_animate_phase(force=True) else: self.on_animate_scale(force=True) def set_connections(self): """creates button actions""" self.scale_button.clicked.connect(self.on_default_scale) self.time_button.clicked.connect(self.on_default_time) self.fps_button.clicked.connect(self.on_default_fps) self.resolution_button.clicked.connect(self.on_default_resolution) self.browse_folder_button.clicked.connect(self.on_browse_folder) self.csv_profile_browse_button.clicked.connect(self.on_browse_csv) self.gif_button.clicked.connect(self.on_default_name) self.step_button.clicked.connect(self.on_step) self.stop_button.clicked.connect(self.on_stop) self.run_button.clicked.connect(self.on_run) #self.animate_scale_radio.clicked.connect(self.on_animate_scale) #self.animate_phase_radio.clicked.connect(self.on_animate_phase) #self.animate_time_radio.clicked.connect(self.on_animate_time) self.animation_type_edit.currentIndexChanged.connect(self.on_animate) #self.animate_freq_sweeep_radio #self.apply_button.clicked.connect(self.on_apply) #self.ok_button.clicked.connect(self.on_ok) self.cancel_button.clicked.connect(self.on_cancel) self.animate_in_gui_checkbox.clicked.connect(self.on_animate_in_gui) self.animate_in_gui_checkbox.setChecked(True) self.on_animate_in_gui() def on_animate_in_gui(self): animate_in_gui = self.animate_in_gui_checkbox.isChecked() enable = not animate_in_gui self.make_images_checkbox.setEnabled(enable) self.delete_images_checkbox.setEnabled(enable) self.make_gif_checkbox.setEnabled(enable) self.repeat_checkbox.setEnabled(enable) self.resolution_button.setEnabled(enable) self.resolution_edit.setEnabled(enable) self.gif_edit.setEnabled(enable) self.gif_button.setEnabled(enable) self.browse_folder_button.setEnabled(enable) self.browse_folder_edit.setEnabled(enable) self.step_button.setEnabled(enable) def on_animate(self, value): """ animate pulldown Parameters ---------- value : int index in animation_types """ #animation_types = ['Animate Scale', 'Animate Phase', 'Animate Time', #'Animate Frequency Sweep'] animation_type = self.animation_types[value] if animation_type == 'Animate Scale': self.on_animate_scale() elif animation_type == 'Animate Phase': self.on_animate_phase() elif animation_type == 'Animate Time': self.on_animate_time() else: raise NotImplementedError('value = ', value) def on_animate_time(self, force=False): """enables the secondary input""" #print('on_animate_time') if self._animate_type == 'scale' or force: self.set_grid_scale(False, 'time') self.set_grid_time(True, 'time') self._animate_type = 'time' def on_animate_scale(self, force=False): """enables the secondary input""" #print('on_animate_scale') self.set_grid_scale(True, 'scale') if self._animate_type == 'time' or force: self.set_grid_time(False, 'scale') self._animate_type = 'scale' def on_animate_phase(self, force=False): """enables the secondary input""" #print('on_animate_phase') if self._animate_type == 'scale' or force: self.set_grid_scale(False, 'phase') if self._animate_type == 'time' or force: self.set_grid_time(False, 'phase') self._animate_type = 'phase' def set_grid_scale(self, enabled=True, word=''): """enables/disables the secondary input""" #print('%s-set_grid_scale; enabled = %r' % (word, enabled)) self.animation_profile.setEnabled(enabled) self.animation_profile_edit.setEnabled(enabled) # TODO: doesn't work... #self.csv_profile.setEnabled(enabled) #self.csv_profile_edit.setEnabled(enabled) #self.csv_profile_button.setEnabled(enabled) def set_grid_time(self, enabled=True, word=''): """enables/disables the secondary input""" #print('%s-set_grid_time; enabled = %r' % (word, enabled)) self.icase_start.setEnabled(enabled) self.icase_start_edit.setEnabled(enabled) self.icase_start_button.setEnabled(enabled) self.icase_end.setEnabled(enabled) self.icase_end_edit.setEnabled(enabled) self.icase_end_button.setEnabled(enabled) self.icase_delta.setEnabled(enabled) self.icase_delta_edit.setEnabled(enabled) self.icase_delta_button.setEnabled(enabled) self.min_value.setEnabled(enabled) self.min_value_edit.setEnabled(enabled) self.min_value_button.setEnabled(enabled) self.max_value.setEnabled(enabled) self.max_value_edit.setEnabled(enabled) self.max_value_button.setEnabled(enabled) self.icase.setEnabled(not enabled) self.icase_edit.setEnabled(not enabled) self.fps.setEnabled(not enabled) self.fps_edit.setEnabled(not enabled) self.fps_button.setEnabled(not enabled) def on_browse_folder(self): """opens a folder dialog""" dirname = open_directory_dialog(self, 'Select a Directory') if not dirname: return self.browse_folder_edit.setText(dirname) def on_browse_csv(self): """opens a file dialog""" default_filename = '' file_types = 'Delimited Text (*.txt; *.dat; *.csv)' dirname = open_file_dialog(self, 'Select a CSV File', default_filename, file_types) if not dirname: return self.csv_profile_browse_button.setText(dirname) def on_default_name(self): """sets the default gif name""" self.gif_edit.setText(self._default_name + '.gif') def on_default_scale(self): """sets the default displacement scale factor""" self.scale_edit.setText(str(self._default_scale)) self.scale_edit.setStyleSheet("QLineEdit{background: white;}") def on_default_time(self): """sets the default gif time""" self.time_edit.setValue(self._default_time) def on_default_fps(self): """sets the default FPS""" self.fps_edit.setValue(self._default_fps) def on_default_resolution(self): """sets the default image resolution scale factor""" self.resolution_edit.setValue(self._default_resolution) def create_layout(self): """displays the menu objects""" grid = QGridLayout() grid.addWidget(self.icase, 0, 0) grid.addWidget(self.icase_edit, 0, 1) grid.addWidget(self.scale, 1, 0) grid.addWidget(self.scale_edit, 1, 1) grid.addWidget(self.scale_button, 1, 2) grid.addWidget(self.time, 2, 0) grid.addWidget(self.time_edit, 2, 1) grid.addWidget(self.time_button, 2, 2) # spacer spacer = QLabel('') grid.addWidget(self.fps, 3, 0) grid.addWidget(self.fps_edit, 3, 1) grid.addWidget(self.fps_button, 3, 2) grid.addWidget(self.resolution, 4, 0) grid.addWidget(self.resolution_edit, 4, 1) grid.addWidget(self.resolution_button, 4, 2) grid.addWidget(self.browse_folder, 5, 0) grid.addWidget(self.browse_folder_edit, 5, 1) grid.addWidget(self.browse_folder_button, 5, 2) grid.addWidget(self.gif, 6, 0) grid.addWidget(self.gif_edit, 6, 1) grid.addWidget(self.gif_button, 6, 2) grid.addWidget(self.animation_type, 7, 0) grid.addWidget(self.animation_type_edit, 7, 1) grid.addWidget(spacer, 8, 0) #---------- #Time grid_time = QGridLayout() grid_time.addWidget(self.icase_start, 0, 0) grid_time.addWidget(self.icase_start_edit, 0, 1) #grid_time.addWidget(self.icase_start_button, 0, 2) grid_time.addWidget(self.icase_end, 1, 0) grid_time.addWidget(self.icase_end_edit, 1, 1) #grid_time.addWidget(self.icase_end_button, 1, 2) grid_time.addWidget(self.icase_delta, 2, 0) grid_time.addWidget(self.icase_delta_edit, 2, 1) #grid_time.addWidget(self.icase_delta_button, 2, 2) #grid_time.addWidget(self.min_value, 3, 0) #grid_time.addWidget(self.min_value_edit, 3, 1) #grid_time.addWidget(self.min_value_button, 3, 2) #grid_time.addWidget(self.max_value, 4, 0) #grid_time.addWidget(self.max_value_edit, 4, 1) #grid_time.addWidget(self.max_value_button, 4, 2) grid_time.addWidget(spacer, 5, 0) #-------------- grid_scale = QGridLayout() grid_scale.addWidget(self.animation_profile, 0, 0) grid_scale.addWidget(self.animation_profile_edit, 0, 1) #grid_scale.addWidget(self.csv_profile, 1, 0) #grid_scale.addWidget(self.csv_profile_edit, 1, 1) #grid_scale.addWidget(self.csv_profile_browse_button, 1, 2) self.csv_profile = QLabel("CSV profile:") self.csv_profile_edit = QLineEdit() self.csv_profile_button = QPushButton('Browse') #box_time = QVBoxLayout() # TODO: It's super annoying that the animate time box doesn't # line up with the previous box box_scale = QGroupBox('Animate Scale') box_scale.setLayout(grid_scale) box_time = QGroupBox('Animate Time') box_time.setLayout(grid_time) #---------- grid2 = QGridLayout() #grid2.addWidget(self.animate_scale_radio, 8, 0) #grid2.addWidget(self.animate_phase_radio, 8, 1) #grid2.addWidget(self.animate_time_radio, 8, 2) #grid2.addWidget(self.animate_freq_sweeep_radio, 8, 3) grid2.addWidget(self.animate_in_gui_checkbox, 10, 0) grid2.addWidget(self.make_images_checkbox, 11, 0) #grid2.addWidget(self.overwrite_images_checkbox, 11, 0) grid2.addWidget(self.delete_images_checkbox, 11, 1) grid2.addWidget(self.make_gif_checkbox, 11, 2) grid2.addWidget(self.repeat_checkbox, 12, 0) grid2.addWidget(spacer, 13, 0) grid_hbox = QHBoxLayout() grid_hbox.addWidget(spacer) grid_hbox.addLayout(grid2) grid_hbox.addWidget(spacer) # bottom buttons step_run_box = QHBoxLayout() step_run_box.addWidget(self.step_button) step_run_box.addWidget(self.stop_button) step_run_box.addWidget(self.run_button) ok_cancel_box = QHBoxLayout() ok_cancel_box.addWidget(self.cancel_button) vbox = QVBoxLayout() vbox.addLayout(grid) vbox.addWidget(box_scale) vbox.addWidget(box_time) #vbox.addLayout(checkboxes) vbox.addLayout(grid_hbox) vbox.addStretch() vbox.addLayout(step_run_box) vbox.addLayout(ok_cancel_box) self.setLayout(vbox) def on_step(self): """click the Step button""" passed, validate_out = self.on_validate() if passed: try: self._make_gif(validate_out, istep=self.istep) self.istep += 1 except IndexError: self._make_gif(validate_out, istep=0) self.istep += 1 def on_stop(self): passed, validate_out = self.on_validate() if passed: self._make_gif(validate_out, stop_animation=True) def on_run(self): """click the Run button""" self.istep = 0 passed, validate_out = self.on_validate() if passed: self._make_gif(validate_out, istep=None) return passed def _make_gif(self, validate_out, istep=None, stop_animation=False): """interface for making the gif""" icase, scale, time, fps, animate_in_gui, magnify, output_dir, gifbase = validate_out gif_filename = None if not stop_animation and not animate_in_gui: if gifbase.lower().endswith('.gif'): gifbase = gifbase[:-4] gif_filename = os.path.join(output_dir, gifbase + '.gif') animate_scale = self.animate_scale_radio.isChecked() animate_phase = self.animate_phase_radio.isChecked() animate_time = self.animate_time_radio.isChecked() animate_scale = False animate_phase = False animate_time = False if self._animate_type == 'scale': animate_scale = True elif self._animate_type == 'phase': animate_phase = True elif self._animate_type == 'time': animate_time = True else: raise NotImplementedError(self._animate_type) make_images = self.make_images_checkbox.isChecked() delete_images = self.delete_images_checkbox.isChecked() make_gif = self.make_gif_checkbox.isChecked() key = str(self.animation_profile_edit.currentText()) #profile = ANIMATION_PROFILES[key] #ANIMATION_PROFILES['0 to Scale'] = [0., 1.] #ANIMATION_PROFILES['0 to Scale to 0'] = [0., 1., 0.] if key == '0 to Scale': onesided = True else: onesided = False icase_start = self.icase_start_edit.value() icase_end = self.icase_end_edit.value() icase_delta = self.icase_delta_edit.value() #onesided = self.onesided_radio.isChecked() bool_repeat = self.repeat_checkbox.isChecked( ) # TODO: change this to an integer if bool_repeat: nrepeat = 0 else: nrepeat = 1 #self.out_data['is_shown'] = self.show_radio.isChecked() #icase = self._icase if self.is_gui: self.win_parent.win_parent.make_gif( gif_filename, scale, istep=istep, animate_scale=animate_scale, animate_phase=animate_phase, animate_time=animate_time, icase=icase, icase_start=icase_start, icase_end=icase_end, icase_delta=icase_delta, time=time, onesided=onesided, nrepeat=nrepeat, fps=fps, magnify=magnify, make_images=make_images, delete_images=delete_images, make_gif=make_gif, stop_animation=stop_animation, animate_in_gui=animate_in_gui, ) self.out_data['clicked_ok'] = True self.out_data['close'] = True def on_validate(self): """checks to see if the input is valid""" icase, flag0 = self.check_int(self.icase_edit) scale, flag1 = self.check_float(self.scale_edit) time, flag2 = self.check_float(self.time_edit) fps, flag3 = self.check_float(self.fps_edit) animate_in_gui = self.animate_in_gui_checkbox.isChecked() if animate_in_gui: passed = all([flag0, flag1, flag2, flag3]) return passed, (icase, scale, time, fps, animate_in_gui, None, None, None) magnify, flag4 = self.check_int(self.resolution_edit) output_dir, flag5 = self.check_path(self.browse_folder_edit) gifbase, flag6 = self.check_name(self.gif_edit) passed = all([flag0, flag1, flag2, flag3, flag4, flag5, flag6]) return passed, (icase, scale, time, fps, animate_in_gui, magnify, output_dir, gifbase) @staticmethod def check_name(cell): """verifies that the data is string-able""" cell_value = cell.text() try: text = str(cell_value).strip() except UnicodeEncodeError: cell.setStyleSheet("QLineEdit{background: red;}") return None, False if len(text): cell.setStyleSheet("QLineEdit{background: white;}") return text, True else: cell.setStyleSheet("QLineEdit{background: red;}") return None, False def check_path(self, cell): """verifies that the path exists""" text, passed = self.check_name(cell) if not passed: return None, False if os.path.exists(text): cell.setStyleSheet("QLineEdit{background: white;}") return text, True else: cell.setStyleSheet("QLineEdit{background: red;}") return None, False #def on_ok(self): #"""click the OK button""" #passed = self.on_apply() #if passed: #self.win_parent._animation_window_shown = False #self.close() ##self.destroy() def on_cancel(self): """click the Cancel button""" self.on_stop() self.out_data['close'] = True self.close()
class Mplayer(QDialog): REVENIR, PAS_PRECEDENT_SUIVANT, PRECEDENT_SUIVANT, CURSEUR_SUR_UNE_LIGNE,\ CURSEUR_A_PART, PARCOURIR, PAS_PARCOURIR, LIST, RATIO = range(9) HAUTEUR, LARGEUR = range(2) def __init__(self, cheminVideo=[], taille=(250,225), choixWidget=(RATIO, REVENIR, PAS_PRECEDENT_SUIVANT,CURSEUR_SUR_UNE_LIGNE,PAS_PARCOURIR,LIST), debutFin=(0,0), cheminMPlayer=None, barreTaches=None, facteurLimitant=HAUTEUR, cheminParcourir=None, parent=None): """widget mplayer""" QDialog.__init__(self, parent) #=== Paramètres généraux ===# self.setAttribute(Qt.WA_DeleteOnClose) self.setWindowTitle(_(u"Player vidéo")) #On réduit la marge pour gagner de l'espace self.setContentsMargins(0,0,0,0) self.systeme = os.name ### Quand EKD windows est installé, le chemin des dépendances sont ########### ### positionnées dans les variables d'environnement donc pas besoin de ####### ### collecter le chemin des ces dépendances ################################## self.cheminMPlayer = "mplayer" ############################################################################## # liste de chemins vidéos if type(cheminVideo) != list : self.listeVideos=[cheminVideo] else : self.listeVideos = cheminVideo # est-ce que la vidéo est lue? self.estLue=False # est-ce que la vidéo est en pause? self.estEnPause=False self.debutFin = debutFin # Nom du fichier courant (le self n'est pas encore utile) txtParDefaut = u"Pas de fichier lu" if self.listeVideos.__len__()!=0: self.fichierCourant = [txtParDefaut, self.listeVideos[0]] else: self.fichierCourant = [txtParDefaut, ""] # Barre des tâches de la fenêtre self.barreTaches = barreTaches # Taille de la vidéo self.tailleLargeur=taille[0] self.tailleHauteur=taille[1] # paramètres des boutons-icones iconTaille=22 flat=1 # Pour récupérer le temps courant depuis certains cadre self.temps = 0 self.dureeTimer = 10 # temps en ms ############################################################################################################################### #Pour être plus précis lors de la lecture, on prend comme unité la miliseconde. ###################### ## Il faut donc utiliser une echelle 1000 fois plus grande pour les unités du slider self.echelle=1000 ############################################################################################################################### # Permet de récupérer la durée de la vidéo depuis une instance de la classe # Sert dans certains cadres self.dureeVideo = 0 # Chemin sur lequel peut s'ouvrir la boite de dialogue de fichier # associée au bouton parcourir self.cheminPourBoutonParcourir = cheminParcourir self.taille = taille debug("self.taille avant lecture : %s %s" % (self.taille, type(self.taille))) #=== Widgets ===# self.icone_lire=QIcon("Icones" + os.sep + "player_play.png") self.icone_pause=QIcon("Icones" + os.sep + "player_pause.png") self.icone_arret=QIcon("Icones" + os.sep + "player_stop.png") if Mplayer.REVENIR in choixWidget: self.bout_revenir = QPushButton(u"Revenir") self.bout_revenir.setIcon(QIcon("Icones" + os.sep + "revenir.png")) if Mplayer.PARCOURIR in choixWidget: self.bout_ouvVideo = QPushButton(u"Parcourir...") if Mplayer.PRECEDENT_SUIVANT in choixWidget: self.bout_prec = QPushButton(QIcon("Icones" + os.sep + "player_rew.png"),"") self.bout_prec.setIconSize(QSize(iconTaille, iconTaille)) self.bout_prec.setFlat(flat) self.bout_suivant = QPushButton(QIcon("Icones" + os.sep + "player_fwd.png"),"") self.bout_suivant.setIconSize(QSize(iconTaille, iconTaille)) self.bout_suivant.setFlat(flat) self.LISTW=False if Mplayer.LIST in choixWidget : self.LISTW = True self.listFichiers = QComboBox() self.listFichiers.hide() self.setListeVideo() self.bout_LectPause = QPushButton(self.icone_lire,"") self.bout_LectPause.setIconSize(QSize(iconTaille, iconTaille)) self.bout_LectPause.setFlat(flat) self.bout_Arret = QPushButton(self.icone_arret,"") self.bout_Arret.setIconSize(QSize(iconTaille, iconTaille)) self.bout_Arret.setFlat(flat) # widget qui contiendra la vidéo self.cibleVideo = DisplayVid(self) # par défaut le widget-cible est noir color = QColor(0, 0, 0) self.cibleVideo.setAutoFillBackground(True) self.cibleVideo.setPalette(QPalette(color)) self.cibleVideo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.cibleVideo.setFixedHeight(self.taille[1]) self.cibleVideo.setToolTip(self.fichierCourant[0]) #Choix de l'aspect ratio de la vidéo if Mplayer.RATIO in choixWidget : self.conf = QGroupBox() self.conf.setContentsMargins(0,0,0,0) self.conf.setMinimumSize(QSize(self.tailleLargeur, 0)) self.conf.setObjectName("conf") self.verticalLayout = QHBoxLayout(self.conf) self.verticalLayout.setObjectName("verticalLayout") self.choicenorm = QRadioButton(self.conf) self.choicenorm.setObjectName("choicenorm") self.verticalLayout.addWidget(self.choicenorm) self.choicewide = QRadioButton(self.conf) self.choicewide.setObjectName("choicewide") self.verticalLayout.addWidget(self.choicewide) self.choiceone = QRadioButton(self.conf) self.choiceone.setObjectName("choiceone") self.verticalLayout.addWidget(self.choiceone) self.choicenorm.setText("4:3") self.choicewide.setText("16:9") self.choiceone.setText("w:h") # Checked le ratio de la vidéo if self.listeVideos.__len__()!=0: self.changeRatio(self.listeVideos[0]) else : self.setRatio(4.0/3.0) if Mplayer.RATIO in choixWidget : self.choicenorm.setChecked(True) self.slider = QSlider(Qt.Horizontal) self.slider.setEnabled(True) self.mplayerProcess = QProcess(self) self.timer = QTimer(self) self.tempsChrono = TracerChrono() #=== mise-en-page/plan ===# mhbox = QHBoxLayout() vbox = QVBoxLayout() vbox.addWidget(self.cibleVideo) if Mplayer.RATIO in choixWidget : vbox.addWidget(self.conf) hbox = QHBoxLayout() if Mplayer.REVENIR in choixWidget: hbox.addWidget(self.bout_revenir) if Mplayer.PARCOURIR in choixWidget: hbox.addWidget(self.bout_ouvVideo) hbox.addWidget(self.bout_LectPause) hbox.addWidget(self.bout_Arret) if Mplayer.PRECEDENT_SUIVANT in choixWidget: hbox.addWidget(self.bout_prec) hbox.addWidget(self.bout_suivant) hbox.addWidget(self.tempsChrono) if Mplayer.CURSEUR_A_PART not in choixWidget: hbox.addWidget(self.slider) vbox.addLayout(hbox) if Mplayer.CURSEUR_A_PART in choixWidget: hbox.setAlignment(Qt.AlignLeft) hbox = QHBoxLayout() hbox.addWidget(self.slider) vbox.addLayout(hbox) # Liste fichier dans combobox if self.LISTW : hbox = QHBoxLayout() hbox.addWidget(self.listFichiers) vbox.addLayout(hbox) mhbox.addLayout(vbox) self.setLayout(mhbox) #=== connexion des widgets à des fonctions ===# if Mplayer.REVENIR in choixWidget: self.connect(self.bout_revenir, SIGNAL('clicked()'), SLOT('close()')) if Mplayer.PARCOURIR in choixWidget: self.connect(self.bout_ouvVideo, SIGNAL('clicked()'), self.ouvrirVideo) if Mplayer.PRECEDENT_SUIVANT in choixWidget: self.connect(self.bout_prec, SIGNAL('clicked()'), self.precedent) self.connect(self.bout_suivant, SIGNAL('clicked()'), self.suivant) #Ajouté le 08/11/2009 - Liste des fichiers dans une combobox if self.LISTW : self.connect(self.listFichiers, SIGNAL('currentIndexChanged(int)'), self.changeVideo) self.connect(self.bout_LectPause, SIGNAL('clicked()'), self.lectPause) self.connect(self.bout_Arret, SIGNAL('clicked()'), self.arretMPlayer) self.connect(self.mplayerProcess, SIGNAL('readyReadStandardOutput()'), self.recupSortie) self.connect(self.mplayerProcess, SIGNAL('finished(int,QProcess::ExitStatus)'), self.finVideo) self.connect(self.timer, SIGNAL('timeout()'), self.sonderTempsActuel) self.connect(self.slider, SIGNAL('sliderMoved(int)'), self.changerTempsCurseur) self.connect(self.cibleVideo, SIGNAL('changeSize'), self.sizeMplayer) if Mplayer.RATIO in choixWidget : self.connect(self.choicenorm, SIGNAL("clicked(bool)"), self.defRatio) self.connect(self.choicewide, SIGNAL("clicked(bool)"), self.defRatio) self.connect(self.choiceone, SIGNAL("clicked(bool)"), self.defRatio) def setListeVideo(self) : self.referenceVideo = [] self.listFichiers.clear() for vid in self.listeVideos : self.referenceVideo.append(vid) self.listFichiers.addItem(os.path.basename(vid)) if self.listeVideos.__len__() > 1 : self.listFichiers.show() def setAudio(self,au) : if au : self.cibleVideo.hide() if "conf" in self.__dict__ : self.conf.hide() else : self.cibleVideo.show() if "conf" in self.__dict__ : self.conf.show() def changeVideo(self, index) : self.arretMPlayer() if index >= 0 : # Condition ajoutée pour éviter une erreure de dépassement de range dans la liste. self.listeVideos = self.referenceVideo[index] self.listFichiers.setCurrentIndex(index) def defRatio(self, state=0) : if state : if self.choicenorm.isChecked() : self.setRatio(4.0/3.0) if self.choicewide.isChecked() : self.setRatio(16.0/9.0) if self.choiceone.isChecked() : try : dim=getVideoSize(unicode(self.listeVideos[0])) self.setRatio(dim[0]/dim[1]) except : None self.defRatio() else : self.adjustSize() def setRatio(self,ratio) : self.ratio = ratio self.sizeMplayer() def changeRatio(self,video) : rv = getVideoRatio(video) if rv[0]==0.0 and type(rv[1])==float : rat = rv[1] else : rat = rv[0] if rat > 1.7 : if "choicewide" in self.__dict__ : self.choicewide.setChecked(True) self.setRatio(16.0/9.0) elif rat > 1.3 and rat <= 1.7 : if "choicenorm" in self.__dict__ : self.choicenorm.setChecked(True) self.setRatio(4.0/3.0) elif rat < 1.3 and rat != 0.0 : if "choiceone" in self.__dict__ : self.choiceone.setChecked(True) dim=getVideoSize(video) self.setRatio(dim[0]/dim[1]) else : if "choicenorm" in self.__dict__ : self.choicenorm.setChecked(True) self.setRatio(4.0/3.0) def sizeMplayer(self) : self.cibleVideo.setFixedHeight(int(self.cibleVideo.width()/self.ratio)) def ouvrirVideo(self): """Ouverture de la boîte de dialogue de fichiers""" txt = u"Fichiers vidéo" if self.cheminPourBoutonParcourir: chemin = self.cheminPourBoutonParcourir else: try: chemin = EkdConfig.get('general','video_input_path').decode("UTF8") except: chemin = os.path.expanduser('~') liste=QFileDialog.getOpenFileNames(None, u"Ouvrir", chemin, "%s (*.avi *.mpg *.mpeg *.mjpeg *.flv *.mp4 *.ogg *.vob *.mov *.wmv *.3gp *.h264)\n*" %txt) if not liste: return self.listeVideos = liste self.changeRatio(unicode(self.listeVideos[0])) chemin = unicode(self.listeVideos[0]) EkdConfig.set('general','video_input_path',os.path.dirname(chemin).encode("UTF8")) def setVideos(self, videos) : '''Définie proprement la liste des vidéos à jouer''' if type(videos) != list : self.listeVideos = [videos] else : self.listeVideos = videos if self.LISTW and videos.__len__() > 1 : self.setListeVideo() elif self.LISTW : self.listFichiers.hide() def demarrerMPlayer(self): """démarrage de mplayer avec les arguments choisis""" if self.estLue: return True args = QStringList() # Liste Qt qui contiendra les options de mplayer # Ajout d'options à liste: args << "-option" # mplayer fonctionnera comme un terminal dans ce script args << "-slave" # on ne veut pas avoir des commentaires sans grand intérêt args << "-quiet" # Sous linux, aucun driver n'a été nécessaire et pas de manip pour Wid :) if self.systeme=='posix': # try - except? # la fenêtre de mplayer restera attaché à la fenêtre # wid prend en valeur le nombre identifiant le widget (celui qui contiendra la vidéo) args << "-wid" << QString.number(self.cibleVideo.winId()) # Objet QString car args est une liste de ch de caractères settings = QSettings() videoOutput = settings.value("vo", QVariant('')).toString() if videoOutput: args << '-vo' << videoOutput # Sous windows else: # reinterpret_cast<qlonglong> obligatoire, winId() ne se laissant pas convertir gentiment ;) args << "-wid" << self.cibleVideo.winId().__hex__() args << "-vo" << "directx:noaccel" #args << "-vo" << "gl" # alternative # chemin de la vidéo args << self.listeVideos if PYQT_VERSION_STR >= "4.1.0": # mode de canal: on fusionne le canal de sortie normal (stdout) et celui des erreurs (stderr) self.mplayerProcess.setProcessChannelMode(QProcess.MergedChannels) # démarrage de mplayer (en tenant compte des arguments définis ci-dessus) # comme un nouveau processus self.mplayerProcess.start(self.cheminMPlayer, args) # au cas où mplayer ne démarrerait pas au bout de 3 sec (ex. problème de codec) if not self.mplayerProcess.waitForStarted(3000): QMessageBox.critical(self, u"Avertissement", u"Bogue au lancement de la vidéo avec mplayer") return False # donne le temps toutes les x secondes self.timer.start(self.dureeTimer) self.estLue = True return True def recupSortie(self): """récupère les lignes d'information émises par QProcess (mplayerProcess) et en tire les conséquences""" while self.mplayerProcess.canReadLine(): # renvoie True si une ligne complète peut être lue à partir du système # stocker l'ensemble des bits d'une ligne tampon=QByteArray(self.mplayerProcess.readLine()) # readline: lit une ligne ascii à partir du système # On vérifie si on a eu des réponses if tampon.startsWith("Playing"): # On récupère les infos de base ('$ mplayer -input cmdlist' pour avoir la liste complète - file:///usr/share/doc/mplayer-doc/tech/slave.txt.gz pour plus de détails) self.mplayerProcess.write("get_video_resolution\n") # récupère la résolution de la vidéo self.mplayerProcess.write("get_time_length\n") # Nouveau fichier chargé -> on récupère son nom ind = tampon.length() - 2 # suppression du '.' à la fin tampon.remove(ind,ind) tampon.remove(0, 8) # vire Playing tampon.replace(QByteArray("\n"), QByteArray("")) tampon.replace(QByteArray("\r"), QByteArray("")) try: # Tour de passe-passe pour ne pas avoir de problème d'accents # Condition pour détection windows if os.name == 'nt': self.fichierCourant[1]=unicode(QString(tampon)) # Condition pour détection Linux ou MacOSX elif os.name in ['posix', 'mac']: self.fichierCourant[1]=unicode(QString(tampon)).encode("Latin1").decode("UTF8") except UnicodeEncodeError, e: debug(e) self.fichierCourant[1]="?" self.cibleVideo.setToolTip(self.fichierCourant[1]) if self.barreTaches is not None: self.barreTaches.showMessage(self.fichierCourant[1]) # réponse à get_video_resolution : ANS_VIDEO_RESOLUTION='<width> x <height>' if tampon.startsWith("ANS_VIDEO_RESOLUTION"): # retourne True si l'ensemble de bits démarre avec "..." debug("tampon : %s" % tampon) # ex. -> ANS_VIDEO_RESOLUTION='352 x 288' tampon.remove(0, 21) # suppression des 21 1er caract -> '352 x 288' tampon.replace(QByteArray("'"), QByteArray("")) # -> 352 x 288 tampon.replace(QByteArray(" "), QByteArray("")) # -> 352x288 tampon.replace(QByteArray("\n"), QByteArray("")) # -> 352x288 # retour chariot unix tampon.replace(QByteArray("\r"), QByteArray("")) # -> 352x288 # retour chariot windows #print "-----tampon.indexOf('x') :", tampon.indexOf('x'), type(tampon.indexOf('x')) sepIndex = tampon.indexOf('x') # récupère la position de 'x' # 3 <type 'int'> #print "-----tampon.left(sepIndex).toInt():", tampon.left(sepIndex).toInt(), type(tampon.left(sepIndex).toInt()) resX = tampon.left(sepIndex).toInt()[0] # -> 352 # (352, True) <type 'tuple'> #print "-----tampon.mid(sepIndex+1).toInt() :", tampon.mid(sepIndex+1).toInt(), type(tampon.mid(sepIndex+1).toInt()) resY = tampon.mid(sepIndex+1).toInt()[0] # -> 288 # (288, True) <type 'tuple'> # on définit les nouvelles dimensions de l'image du widget-mplayer. # try pour éviter les bogues sur les fichiers audio (sans dimension d'image)!!! #try: if resX!=0 or resY!=0: debug( "ratio : %s - %s" % (self.ratio, type(self.ratio))) else: debug("fichier audio") # réponse à get_time_length : ANS_LENGTH=xx.yy elif tampon.startsWith("ANS_LENGTH"): debug("tampon : %s" % tampon) # -> ANS_LENGTH=279.38 tampon.remove(0, 11) # vire ANS_LENGTH= tampon.replace(QByteArray("'"), QByteArray("")) tampon.replace(QByteArray(" "), QByteArray("")) tampon.replace(QByteArray("\n"), QByteArray("")) tampon.replace(QByteArray("\r"), QByteArray("")) # -> 279.38 #print "-----tampon.toFloat() :", tampon.toFloat(), type(tampon.toFloat()) tempsMax = tampon.toFloat()[0] # (279.3800048828125, True) <type 'tuple'> self.dureeVideo = tempsMax ## Modifié le 28/05/2009 : On augmente la précision du slider #self.slider.setMaximum(tempsMax) # déf du domaine de valeur du curseur self.slider.setMaximum(tempsMax*self.echelle) # ATTENTION J'AI COMMENTE CETTE LIGNE !!! #self.slider.setMaximum(tempsMax) # réponse à get_time_pos : ANS_TIME_POSITION=xx.y elif tampon.startsWith("ANS_TIME_POSITION"): #print "tampon :",tampon # -> ANS_TIME_POSITION=1.4 (temps courant) tampon.remove(0, 18) # vire ANS_TIME_POSITION= tampon.replace(QByteArray("'"), QByteArray("")) tampon.replace(QByteArray(" "), QByteArray("")) tampon.replace(QByteArray("\n"), QByteArray("")) tampon.replace(QByteArray("\r"), QByteArray("")) #print "-----tampon.toFloat() :", tampon.toFloat(), type(tampon.toFloat()) tempsCourant = tampon.toFloat()[0] # (1.3999999761581421, True) <type 'tuple'> # récupération du temps courant: utile dans certains cadres self.temps = tempsCourant # Programmer un arrêt. Utile pour les aperçus temps = float("%.1f" %self.temps) if self.debutFin!=(0,0) and self.debutFin[1]==temps: self.arretMPlayer() return self.slider.setValue(tempsCourant*self.echelle) ############################################################################# self.changerTempsChrono(tempsCourant) # modifier le chrono du bouton
class OperatorValueDialog(QtHelper.EnhancedQDialog): """ Operator dialog """ def __init__(self, parent, currentOperator={}, liteMode=False): """ Operator to fill parameter description @param dataArgs: @type dataArgs: @param parent: @type parent: """ super(OperatorValueDialog, self).__init__(parent) self.parentWidget = parent self.liteMode = liteMode self.currentOperator = currentOperator self.createDialog() self.createConnections() def createDialog(self): """ Create qt dialog """ self.buttonBox = QDialogButtonBox(self) self.buttonBox.setStyleSheet("""QDialogButtonBox { dialogbuttonbox-buttons-have-icons: 1; dialog-ok-icon: url(:/ok.png); dialog-cancel-icon: url(:/test-close-black.png); }""") self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) mainLayout = QHBoxLayout() main2Layout = QHBoxLayout() titleLabel = QLabel(self.currentOperator['operator']) font = QFont() font.setBold(True) titleLabel.setFont(font) self.opType = QComboBox() if not self.liteMode: for i in xrange(len(LIST_CONDITIONS)): self.opType.addItem(LIST_CONDITIONS[i].title()) if self.currentOperator['operator'] == LIST_CONDITIONS[ i].title(): self.opType.setCurrentIndex(i) else: for i in xrange(len(LIST_CONDITIONS_LITE)): self.opType.addItem(LIST_CONDITIONS_LITE[i].title()) if self.currentOperator['operator'] == LIST_CONDITIONS_LITE[ i].title(): self.opType.setCurrentIndex(i) main2Layout.addWidget(titleLabel) main2Layout.addWidget(self.opType) if not self.liteMode: self.textValue = QTextEdit() self.textValue.setFixedHeight(HEIGHT_TEXT_AREA) self.textValue.setMinimumWidth(WIDTH_TEXT_AREA) radioGroup = QButtonGroup(self) self.strRadioButton = QRadioButton("string") self.strRadioButton.setChecked(True) self.inRadioButton = QRadioButton("inputs") self.outRadioButton = QRadioButton("outputs") self.varRadioButton = QRadioButton("variables") radioGroup.addButton(self.strRadioButton) radioGroup.addButton(self.inRadioButton) radioGroup.addButton(self.outRadioButton) radioGroup.addButton(self.varRadioButton) self.inputsCombo = QComboBox() for inpt in self.parentWidget.getInputs(): self.inputsCombo.addItem(inpt['name']) self.outputsCombo = QComboBox() for inpt in self.parentWidget.getOutputs(): self.outputsCombo.addItem(inpt['name']) self.variablesCombo = QComboBox() self.variablesCombo.addItems(self.parentWidget.variables) if self.currentOperator['type'] == 'string': self.strRadioButton.setChecked(True) self.textValue.setText(self.currentOperator['value']) if self.currentOperator['type'] == 'inputs': self.inRadioButton.setChecked(True) for x in xrange(self.inputsCombo.count()): if self.inputsCombo.itemText( x) == self.currentOperator['value']: self.inputsCombo.setCurrentIndex(x) if self.currentOperator['type'] == 'outputs': self.outRadioButton.setChecked(True) for x in xrange(self.outputsCombo.count()): if self.outputsCombo.itemText( x) == self.currentOperator['value']: self.outputsCombo.setCurrentIndex(x) if self.currentOperator['type'] == 'variables': self.varRadioButton.setChecked(True) for x in xrange(self.variablesCombo.count()): if self.variablesCombo.itemText( x) == self.currentOperator['value']: self.variablesCombo.setCurrentIndex(x) mainLayout.addWidget(self.strRadioButton) mainLayout.addWidget(self.textValue) mainLayout.addWidget(self.inRadioButton) mainLayout.addWidget(self.inputsCombo) mainLayout.addWidget(self.outRadioButton) mainLayout.addWidget(self.outputsCombo) mainLayout.addWidget(self.varRadioButton) mainLayout.addWidget(self.variablesCombo) finalLayout = QVBoxLayout() finalLayout.addLayout(main2Layout) finalLayout.addLayout(mainLayout) finalLayout.addWidget(self.buttonBox) self.setLayout(finalLayout) self.setWindowTitle(self.tr("Operators configuration")) self.setMinimumWidth(500) self.center() def createConnections(self): """ Create qt connections """ self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def getValue(self): """ Return value """ self.currentOperator['operator'] = unicode(self.opType.currentText()) if not self.liteMode: if self.currentOperator['operator'].lower() == OP_ANY: self.currentOperator['type'] = 'string' self.currentOperator['value'] = '' else: if self.strRadioButton.isChecked(): self.currentOperator['type'] = 'string' self.currentOperator['value'] = unicode( self.textValue.toPlainText()) if self.inRadioButton.isChecked(): self.currentOperator['type'] = 'inputs' self.currentOperator['value'] = unicode( self.inputsCombo.currentText()) if self.outRadioButton.isChecked(): self.currentOperator['type'] = 'outputs' self.currentOperator['value'] = unicode( self.outputsCombo.currentText()) if self.varRadioButton.isChecked(): self.currentOperator['type'] = 'variables' self.currentOperator['value'] = unicode( self.variablesCombo.currentText()) return self.currentOperator
class ShortcutEditDialog(QDialog): """A modal dialog to view and/or edit keyboard shortcuts.""" def __init__(self, parent=None, conflictCallback=None, *cbArgs): """conflictCallback is a optional method called when a shortcut is changed. cbArgs is optional arguments of the conflictCallback method. it should return the name of the potential conflict or a null value """ super(ShortcutEditDialog, self).__init__(parent) self.conflictCallback = conflictCallback self.cbArgs = cbArgs self.setMinimumWidth(400) # create gui layout = QVBoxLayout() layout.setSpacing(10) self.setLayout(layout) top = QHBoxLayout() top.setSpacing(4) p = self.toppixmap = QLabel() l = self.toplabel = QLabel() top.addWidget(p) top.addWidget(l, 1) layout.addLayout(top) grid = QGridLayout() grid.setSpacing(4) grid.setColumnStretch(1, 2) layout.addLayout(grid) self.buttonDefault = QRadioButton( self, toggled=self.slotButtonDefaultToggled) self.buttonNone = QRadioButton(self) self.lconflictDefault = QLabel('test') self.lconflictDefault.setStyleSheet("color : red;") self.lconflictDefault.setVisible(False) self.buttonCustom = QRadioButton(self) grid.addWidget(self.buttonDefault, 0, 0, 1, 2) grid.addWidget(self.lconflictDefault, 1, 0, 1, 2) grid.addWidget(self.buttonNone, 2, 0, 1, 2) grid.addWidget(self.buttonCustom, 3, 0, 1, 2) self.keybuttons = [] self.keylabels = [] self.conflictlabels = [] for num in range(4): l = QLabel(self) l.setStyleSheet("margin-left: 2em;") l.setAlignment(Qt.AlignRight | Qt.AlignVCenter) b = KeySequenceWidget(self, num) b.keySequenceChanged.connect(self.slotKeySequenceChanged) l.setBuddy(b) self.keylabels.append(l) self.keybuttons.append(b) grid.addWidget(l, num + 4 + num, 0) grid.addWidget(b, num + 4 + num, 1) lconflict = QLabel() lconflict.setStyleSheet("color : red;") self.conflictlabels.append(lconflict) lconflict.setVisible(False) grid.addWidget(lconflict, num + 5 + num, 0, 1, 2, Qt.AlignHCenter) layout.addWidget(Separator(self)) b = QDialogButtonBox(self) b.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) layout.addWidget(b) b.accepted.connect(self.accept) b.rejected.connect(self.reject) app.translateUI(self) def translateUI(self): self.setWindowTitle(app.caption(_("window title", "Edit Shortcut"))) self.buttonNone.setText(_("&No shortcut")) self.buttonCustom.setText(_("Use a &custom shortcut:")) for num in range(4): self.keylabels[num].setText( _("Alternative #{num}:").format( num=num) if num else _("Primary shortcut:")) def slotKeySequenceChanged(self, num): """Called when one of the keysequence buttons has changed.""" self.checkConflict(num) self.buttonCustom.setChecked(True) def slotButtonDefaultToggled(self, val): if self.conflictCallback is not None: if not val: self.lconflictDefault.setVisible(False) else: if self._default: conflictList = [] for s in self._default: conflictName = self.conflictCallback(s, *self.cbArgs) if conflictName: conflictList.append(conflictName) if conflictList: text = _("Conflict with: {name}").format( name="<b>{0}</b>".format(', '.join(conflictList))) self.lconflictDefault.setText(text) self.lconflictDefault.setVisible(True) QTimer.singleShot(0, self.adjustSize) def checkConflict(self, num): if self.conflictCallback is not None: conflictName = self.conflictCallback( self.keybuttons[num].shortcut(), *self.cbArgs) if conflictName: text = _("Conflict with: {name}").format( name="<b>{0}</b>".format(conflictName)) self.conflictlabels[num].setText(text) self.conflictlabels[num].setVisible(True) else: self.conflictlabels[num].setVisible(False) QTimer.singleShot(0, self.adjustSize) def editAction(self, action, default=None): # load the action self._action = action self._default = default self.toplabel.setText('<p>{0}</p>'.format( _("Here you can edit the shortcuts for {name}").format( name='<br/><b>{0}</b>:'.format(action.text())))) self.toppixmap.setPixmap(action.icon().pixmap(32)) shortcuts = action.shortcuts() self.buttonDefault.setVisible(bool(default)) if default is not None and shortcuts == default: self.buttonDefault.setChecked(True) else: if shortcuts: self.buttonCustom.setChecked(True) for num, key in enumerate(shortcuts[:4]): self.keybuttons[num].setShortcut(key) self.checkConflict(num) else: self.buttonNone.setChecked(True) if default: ds = "; ".join( key.toString(QKeySequence.NativeText) for key in default) else: ds = _("no keyboard shortcut", "none") self.buttonDefault.setText( _("Use &default shortcut ({name})").format(name=ds)) return self.exec_() def done(self, result): if result: shortcuts = [] if self.buttonDefault.isChecked(): shortcuts = self._default elif self.buttonCustom.isChecked(): for num in range(4): seq = self.keybuttons[num].shortcut() if not seq.isEmpty(): shortcuts.append(seq) self._action.setShortcuts(shortcuts) super(ShortcutEditDialog, self).done(result)
def RadioGet(widget : QtGui.QRadioButton, id : int) -> bool or None: if id == 0: return widget.isChecked()
class LegendPropertiesWindow(PyDialog): """ +-------------------+ | Legend Properties | +-----------------------+ | Title ______ Default | | Min ______ Default | | Max ______ Default | | Format ______ Default | | Scale ______ Default | | Number of Colors ____ | | Number of Labels ____ | | Label Size ____ | (TODO) | ColorMap ____ | (TODO) | | | x Min/Max (Blue->Red) | | o Max/Min (Red->Blue) | | | | x Vertical/Horizontal | | x Show/Hide | | | | Apply OK Cancel | +-----------------------+ """ def __init__(self, data, win_parent=None): PyDialog.__init__(self, data, win_parent) #Init the base class self._updated_legend = False self._icase = data['icase'] self._default_icase = self._icase self._default_name = data['name'] self._default_min = data['min'] self._default_max = data['max'] self._default_scale = data['default_scale'] self._scale = data['scale'] self._default_format = data['default_format'] self._format = data['format'] self._default_labelsize = data['default_labelsize'] self._labelsize = data['labelsize'] self._default_nlabels = data['default_nlabels'] self._nlabels = data['nlabels'] self._default_ncolors = data['default_ncolors'] self._ncolors = data['ncolors'] self._default_colormap = data['default_colormap'] self._colormap = data['colormap'] self._default_is_low_to_high = data['is_low_to_high'] self._default_is_discrete = data['is_discrete'] self._default_is_horizontal = data['is_horizontal'] self._default_is_shown = data['is_shown'] self._update_defaults_to_blank() #self.setupUi(self) self.setWindowTitle('Legend Properties') self.create_widgets() self.create_layout() self.set_connections() #self.show() def _update_defaults_to_blank(self): """Changes the default (None) to a blank string""" if self._default_colormap is None: self._default_colormap = 'jet' if self._default_labelsize is None: self._default_labelsize = '' if self._default_ncolors is None: self._default_ncolors = '' if self._default_nlabels is None: self._default_nlabels = '' if self._colormap is None: self._colormap = 'jet' if self._labelsize is None: self._labelsize = '' if self._ncolors is None: self._ncolors = '' if self._nlabels is None: self._nlabels = '' def update_legend(self, icase, name, min_value, max_value, data_format, scale, nlabels, labelsize, ncolors, colormap, default_title, default_min_value, default_max_value, default_data_format, default_scale, default_nlabels, default_labelsize, default_ncolors, default_colormap, is_low_to_high, is_horizontal_scalar_bar): """ We need to update the legend if there's been a result change request """ if icase != self._default_icase: self._default_icase = icase self._default_name = default_title self._default_min = default_min_value self._default_max = default_max_value self._default_format = default_data_format self._default_is_low_to_high = is_low_to_high self._default_is_discrete = True self._default_is_horizontal = is_horizontal_scalar_bar self._default_scale = default_scale self._default_nlabels = default_nlabels self._default_labelsize = default_labelsize self._default_ncolors = default_ncolors self._default_colormap = default_colormap if colormap is None: colormap = 'jet' if labelsize is None: labelsize = '' if ncolors is None: ncolors = '' if nlabels is None: nlabels = '' self._update_defaults_to_blank() assert isinstance(scale, float), 'scale=%r' % scale assert isinstance(default_scale, float), 'default_scale=%r' % default_scale if self._default_scale == 0.0: self.scale_edit.setEnabled(False) self.scale_button.setEnabled(False) else: self.scale_edit.setEnabled(True) self.scale_button.setEnabled(True) #self.on_default_name() #self.on_default_min() #self.on_default_max() #self.on_default_format() #self.on_default_scale() # reset defaults self.name_edit.setText(name) self.name_edit.setStyleSheet("QLineEdit{background: white;}") self.min_edit.setText(str(min_value)) self.min_edit.setStyleSheet("QLineEdit{background: white;}") self.max_edit.setText(str(max_value)) self.max_edit.setStyleSheet("QLineEdit{background: white;}") self.format_edit.setText(str(data_format)) self.format_edit.setStyleSheet("QLineEdit{background: white;}") self.scale_edit.setText(str(scale)) self.scale_edit.setStyleSheet("QLineEdit{background: white;}") self.nlabels_edit.setText(str(nlabels)) self.nlabels_edit.setStyleSheet("QLineEdit{background: white;}") self.labelsize_edit.setText(str(labelsize)) self.labelsize_edit.setStyleSheet("QLineEdit{background: white;}") self.ncolors_edit.setText(str(ncolors)) self.ncolors_edit.setStyleSheet("QLineEdit{background: white;}") self.colormap_edit.setCurrentIndex(colormap_keys.index(str(colormap))) self.on_apply() def create_widgets(self): # Name self.name = QLabel("Title:") self.name_edit = QLineEdit(str(self._default_name)) self.name_button = QPushButton("Default") # Min self.min = QLabel("Min:") self.min_edit = QLineEdit(str(self._default_min)) self.min_button = QPushButton("Default") # Max self.max = QLabel("Max:") self.max_edit = QLineEdit(str(self._default_max)) self.max_button = QPushButton("Default") # Format self.format = QLabel("Format (e.g. %.3f, %g, %.6e):") self.format_edit = QLineEdit(str(self._format)) self.format_button = QPushButton("Default") # Scale self.scale = QLabel("Scale:") self.scale_edit = QLineEdit(str(self._scale)) self.scale_button = QPushButton("Default") if self._default_scale == 0.0: self.scale_edit.setEnabled(False) self.scale_button.setEnabled(False) #tip = QtGui.QToolTip() #tip.setTe #self.format_edit.toolTip(tip) #--------------------------------------- # nlabels self.nlabels = QLabel("Number of Labels:") self.nlabels_edit = QLineEdit(str(self._nlabels)) self.nlabels_button = QPushButton("Default") self.labelsize = QLabel("Label Size:") self.labelsize_edit = QLineEdit(str(self._labelsize)) self.labelsize_button = QPushButton("Default") self.ncolors = QLabel("Number of Colors:") self.ncolors_edit = QLineEdit(str(self._ncolors)) self.ncolors_button = QPushButton("Default") self.colormap = QLabel("Color Map:") self.colormap_edit = QComboBox(self) self.colormap_button = QPushButton("Default") for key in colormap_keys: self.colormap_edit.addItem(key) self.colormap_edit.setCurrentIndex(colormap_keys.index(self._colormap)) # red/blue or blue/red self.low_to_high_radio = QRadioButton('Low -> High') self.high_to_low_radio = QRadioButton('High -> Low') widget = QWidget(self) low_to_high_group = QButtonGroup(widget) low_to_high_group.addButton(self.low_to_high_radio) low_to_high_group.addButton(self.high_to_low_radio) self.low_to_high_radio.setChecked(self._default_is_low_to_high) self.high_to_low_radio.setChecked(not self._default_is_low_to_high) # horizontal / vertical self.horizontal_radio = QRadioButton("Horizontal") self.vertical_radio = QRadioButton("Vertical") widget = QWidget(self) horizontal_vertical_group = QButtonGroup(widget) horizontal_vertical_group.addButton(self.horizontal_radio) horizontal_vertical_group.addButton(self.vertical_radio) self.horizontal_radio.setChecked(self._default_is_horizontal) self.vertical_radio.setChecked(not self._default_is_horizontal) # on / off self.show_radio = QRadioButton("Show") self.hide_radio = QRadioButton("Hide") widget = QWidget(self) show_hide_group = QButtonGroup(widget) show_hide_group.addButton(self.show_radio) show_hide_group.addButton(self.hide_radio) self.show_radio.setChecked(self._default_is_shown) self.hide_radio.setChecked(not self._default_is_shown) # closing self.apply_button = QPushButton("Apply") self.ok_button = QPushButton("OK") self.cancel_button = QPushButton("Cancel") def create_layout(self): grid = QGridLayout() grid.addWidget(self.name, 0, 0) grid.addWidget(self.name_edit, 0, 1) grid.addWidget(self.name_button, 0, 2) grid.addWidget(self.min, 1, 0) grid.addWidget(self.min_edit, 1, 1) grid.addWidget(self.min_button, 1, 2) grid.addWidget(self.max, 2, 0) grid.addWidget(self.max_edit, 2, 1) grid.addWidget(self.max_button, 2, 2) grid.addWidget(self.format, 3, 0) grid.addWidget(self.format_edit, 3, 1) grid.addWidget(self.format_button, 3, 2) grid.addWidget(self.scale, 4, 0) grid.addWidget(self.scale_edit, 4, 1) grid.addWidget(self.scale_button, 4, 2) grid.addWidget(self.nlabels, 5, 0) grid.addWidget(self.nlabels_edit, 5, 1) grid.addWidget(self.nlabels_button, 5, 2) #grid.addWidget(self.labelsize, 6, 0) #grid.addWidget(self.labelsize_edit, 6, 1) #grid.addWidget(self.labelsize_button, 6, 2) grid.addWidget(self.ncolors, 6, 0) grid.addWidget(self.ncolors_edit, 6, 1) grid.addWidget(self.ncolors_button, 6, 2) grid.addWidget(self.colormap, 7, 0) grid.addWidget(self.colormap_edit, 7, 1) grid.addWidget(self.colormap_button, 7, 2) ok_cancel_box = QHBoxLayout() ok_cancel_box.addWidget(self.apply_button) ok_cancel_box.addWidget(self.ok_button) ok_cancel_box.addWidget(self.cancel_button) grid2 = QGridLayout() title = QLabel("Color Scale:") grid2.addWidget(title, 0, 0) grid2.addWidget(self.low_to_high_radio, 1, 0) grid2.addWidget(self.high_to_low_radio, 2, 0) grid2.addWidget(self.vertical_radio, 1, 1) grid2.addWidget(self.horizontal_radio, 2, 1) grid2.addWidget(self.show_radio, 1, 2) grid2.addWidget(self.hide_radio, 2, 2) #grid2.setSpacing(0) vbox = QVBoxLayout() vbox.addLayout(grid) #vbox.addLayout(checkboxes) vbox.addLayout(grid2) vbox.addStretch() vbox.addLayout(ok_cancel_box) #Create central widget, add layout and set #central_widget = QtGui.QWidget() #central_widget.setLayout(vbox) #self.setCentralWidget(central_widget) self.setLayout(vbox) def set_connections(self): if qt_version == 4: self.connect(self.name_button, QtCore.SIGNAL('clicked()'), self.on_default_name) self.connect(self.min_button, QtCore.SIGNAL('clicked()'), self.on_default_min) self.connect(self.max_button, QtCore.SIGNAL('clicked()'), self.on_default_max) self.connect(self.format_button, QtCore.SIGNAL('clicked()'), self.on_default_format) self.connect(self.scale_button, QtCore.SIGNAL('clicked()'), self.on_default_scale) self.connect(self.nlabels_button, QtCore.SIGNAL('clicked()'), self.on_default_nlabels) self.connect(self.labelsize_button, QtCore.SIGNAL('clicked()'), self.on_default_labelsize) self.connect(self.ncolors_button, QtCore.SIGNAL('clicked()'), self.on_default_ncolors) self.connect(self.colormap_button, QtCore.SIGNAL('clicked()'), self.on_default_colormap) self.connect(self.apply_button, QtCore.SIGNAL('clicked()'), self.on_apply) self.connect(self.ok_button, QtCore.SIGNAL('clicked()'), self.on_ok) self.connect(self.cancel_button, QtCore.SIGNAL('clicked()'), self.on_cancel) self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent) #self.colormap_edit.activated[str].connect(self.onActivated) else: self.name_button.clicked.connect(self.on_default_name) self.min_button.clicked.connect(self.on_default_min) self.max_button.clicked.connect(self.on_default_max) self.format_button.clicked.connect(self.on_default_format) self.scale_button.clicked.connect(self.on_default_scale) self.nlabels_button.clicked.connect(self.on_default_nlabels) self.labelsize_button.clicked.connect(self.on_default_labelsize) self.ncolors_button.clicked.connect(self.on_default_ncolors) self.colormap_button.clicked.connect(self.on_default_colormap) self.apply_button.clicked.connect(self.on_apply) self.ok_button.clicked.connect(self.on_ok) self.cancel_button.clicked.connect(self.on_cancel) # closeEvent??? def on_default_name(self): name = str(self._default_name) self.name_edit.setText(name) self.name_edit.setStyleSheet("QLineEdit{background: white;}") def on_default_min(self): self.min_edit.setText(str(self._default_min)) self.min_edit.setStyleSheet("QLineEdit{background: white;}") def on_default_max(self): self.max_edit.setText(str(self._default_max)) self.max_edit.setStyleSheet("QLineEdit{background: white;}") def on_default_format(self): self.format_edit.setText(str(self._default_format)) self.format_edit.setStyleSheet("QLineEdit{background: white;}") def on_default_scale(self): self.scale_edit.setText(str(self._default_scale)) self.scale_edit.setStyleSheet("QLineEdit{background: white;}") def on_default_ncolors(self): self.ncolors_edit.setText(str(self._default_ncolors)) self.ncolors_edit.setStyleSheet("QLineEdit{background: white;}") def on_default_colormap(self): self.colormap_edit.setCurrentIndex(colormap_keys.index(self._default_colormap)) def on_default_nlabels(self): self.nlabels_edit.setStyleSheet("QLineEdit{background: white;}") self.nlabels_edit.setText(str(self._default_nlabels)) def on_default_labelsize(self): self.labelsize_edit.setText(str(self._default_labelsize)) self.labelsize_edit.setStyleSheet("QLineEdit{background: white;}") @staticmethod def check_name(cell): cell_value = cell.text() try: text = str(cell_value).strip() except UnicodeEncodeError: cell.setStyleSheet("QLineEdit{background: red;}") return None, False if len(text): cell.setStyleSheet("QLineEdit{background: white;}") return text, True else: cell.setStyleSheet("QLineEdit{background: red;}") return None, False @staticmethod def check_colormap(cell): text = str(cell.text()).strip() if text in colormap_keys: cell.setStyleSheet("QLineEdit{background: white;}") return text, True else: cell.setStyleSheet("QLineEdit{background: red;}") return None, False def on_validate(self): name_value, flag0 = self.check_name(self.name_edit) min_value, flag1 = self.check_float(self.min_edit) max_value, flag2 = self.check_float(self.max_edit) format_value, flag3 = self.check_format(self.format_edit) scale_value, flag4 = self.check_float(self.scale_edit) nlabels, flag5 = self.check_positive_int_or_blank(self.nlabels_edit) ncolors, flag6 = self.check_positive_int_or_blank(self.ncolors_edit) labelsize, flag7 = self.check_positive_int_or_blank(self.labelsize_edit) colormap = str(self.colormap_edit.currentText()) if all([flag0, flag1, flag2, flag3, flag4, flag5, flag6, flag7]): if 'i' in format_value: format_value = '%i' assert isinstance(scale_value, float), scale_value self.out_data['name'] = name_value self.out_data['min'] = min_value self.out_data['max'] = max_value self.out_data['format'] = format_value self.out_data['scale'] = scale_value self.out_data['nlabels'] = nlabels self.out_data['ncolors'] = ncolors self.out_data['labelsize'] = labelsize self.out_data['colormap'] = colormap self.out_data['is_low_to_high'] = self.low_to_high_radio.isChecked() self.out_data['is_horizontal'] = self.horizontal_radio.isChecked() self.out_data['is_shown'] = self.show_radio.isChecked() self.out_data['clicked_ok'] = True self.out_data['close'] = True #print('self.out_data = ', self.out_data) #print("name = %r" % self.name_edit.text()) #print("min = %r" % self.min_edit.text()) #print("max = %r" % self.max_edit.text()) #print("format = %r" % self.format_edit.text()) return True return False def on_apply(self): passed = self.on_validate() if passed: self.win_parent._apply_legend(self.out_data) return passed def on_ok(self): passed = self.on_apply() if passed: self.close() #self.destroy() def on_cancel(self): self.out_data['close'] = True self.close()
class FindOptions(QWidget): """ Find widget with options """ def __init__(self, parent, search_text, search_text_regexp, search_path, include, include_regexp, exclude, exclude_regexp, supported_encodings): QWidget.__init__(self, parent) if search_path is None: search_path = os.getcwdu() if not isinstance(search_text, (list, tuple)): search_text = [search_text] if not isinstance(search_path, (list, tuple)): search_path = [search_path] if not isinstance(include, (list, tuple)): include = [include] if not isinstance(exclude, (list, tuple)): exclude = [exclude] self.supported_encodings = supported_encodings # Layout 1 hlayout1 = QHBoxLayout() self.search_text = PatternComboBox( self, search_text, translate('FindInFiles', "Search pattern")) search_label = QLabel(translate('FindInFiles', "Search text:")) search_label.setBuddy(self.search_text) self.edit_regexp = create_toolbutton(self, get_icon("advanced.png"), tip=translate( 'FindInFiles', "Regular expression")) self.edit_regexp.setCheckable(True) self.edit_regexp.setChecked(search_text_regexp) self.ok_button = create_toolbutton( self, text=translate('FindInFiles', "Search"), triggered=lambda: self.emit(SIGNAL('find()')), icon=get_std_icon("DialogApplyButton"), tip=translate('FindInFiles', "Start search")) self.connect(self.ok_button, SIGNAL('clicked()'), self.update_combos) self.stop_button = create_toolbutton( self, text=translate('FindInFiles', "Stop"), triggered=lambda: self.emit(SIGNAL('stop()')), icon=get_icon("terminate.png"), tip=translate('FindInFiles', "Stop search")) self.stop_button.setEnabled(False) for widget in [ search_label, self.search_text, self.edit_regexp, self.ok_button, self.stop_button ]: hlayout1.addWidget(widget) # Layout 2 hlayout2 = QHBoxLayout() self.include_pattern = PatternComboBox( self, include, translate('FindInFiles', "Included filenames pattern")) self.include_regexp = create_toolbutton(self, get_icon("advanced.png"), tip=translate( 'FindInFiles', "Regular expression")) self.include_regexp.setCheckable(True) self.include_regexp.setChecked(include_regexp) include_label = QLabel(translate('FindInFiles', "Include:")) include_label.setBuddy(self.include_pattern) self.exclude_pattern = PatternComboBox( self, exclude, translate('FindInFiles', "Excluded filenames pattern")) self.exclude_regexp = create_toolbutton(self, get_icon("advanced.png"), tip=translate( 'FindInFiles', "Regular expression")) self.exclude_regexp.setCheckable(True) self.exclude_regexp.setChecked(exclude_regexp) exclude_label = QLabel(translate('FindInFiles', "Exclude:")) exclude_label.setBuddy(self.exclude_pattern) for widget in [ include_label, self.include_pattern, self.include_regexp, exclude_label, self.exclude_pattern, self.exclude_regexp ]: hlayout2.addWidget(widget) # Layout 3 hlayout3 = QHBoxLayout() searchin_label = QLabel(translate('FindInFiles', "Search in:")) self.python_path = QRadioButton(translate('FindInFiles', "PYTHONPATH"), self) self.python_path.setToolTip( translate( 'FindInFiles', "Search in all directories listed in sys.path which" " are outside the Python installation directory")) self.hg_manifest = QRadioButton( translate('FindInFiles', "Hg repository"), self) self.detect_hg_repository() self.hg_manifest.setToolTip( translate('FindInFiles', "Search in current directory hg repository")) searchin_label.setBuddy(self.hg_manifest) self.custom_dir = QRadioButton(translate('FindInFiles', "Directory:"), self) self.custom_dir.setChecked(True) self.dir_combo = PathComboBox(self) self.dir_combo.addItems(search_path) self.dir_combo.setToolTip( translate('FindInFiles', "Search recursively in this directory")) self.connect(self.dir_combo, SIGNAL("open_dir(QString)"), self.set_directory) self.connect(self.python_path, SIGNAL('toggled(bool)'), self.dir_combo.setDisabled) self.connect(self.hg_manifest, SIGNAL('toggled(bool)'), self.dir_combo.setDisabled) browse = create_toolbutton(self, get_std_icon('DirOpenIcon'), tip=translate('FindInFiles', 'Browse a search directory'), triggered=self.select_directory) for widget in [ searchin_label, self.python_path, self.hg_manifest, self.custom_dir, self.dir_combo, browse ]: hlayout3.addWidget(widget) vlayout = QVBoxLayout() vlayout.addLayout(hlayout1) vlayout.addLayout(hlayout2) vlayout.addLayout(hlayout3) self.setLayout(vlayout) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum) def update_combos(self): self.search_text.lineEdit().emit(SIGNAL('returnPressed()')) self.include_pattern.lineEdit().emit(SIGNAL('returnPressed()')) self.exclude_pattern.lineEdit().emit(SIGNAL('returnPressed()')) def detect_hg_repository(self, path=None): if path is None: path = os.getcwdu() hg_repository = is_hg_installed() and get_hg_root(path) is not None self.hg_manifest.setEnabled(hg_repository) if not hg_repository and self.hg_manifest.isChecked(): self.custom_dir.setChecked(True) def set_search_text(self, text): self.search_text.setEditText(text) self.search_text.lineEdit().selectAll() self.search_text.setFocus() def get_options(self, all=False): # Getting options utext = unicode(self.search_text.currentText()) if not utext: return try: texts = [str(utext)] except UnicodeDecodeError: texts = [] for encoding in self.supported_encodings: try: texts.append(utext.encode(encoding)) except UnicodeDecodeError: pass text_re = self.edit_regexp.isChecked() include = unicode(self.include_pattern.currentText()) include_re = self.include_regexp.isChecked() exclude = unicode(self.exclude_pattern.currentText()) exclude_re = self.exclude_regexp.isChecked() python_path = self.python_path.isChecked() hg_manifest = self.hg_manifest.isChecked() path = osp.abspath(unicode(self.dir_combo.currentText())) # Finding text occurences if not include_re: include = fnmatch.translate(include) if not exclude_re: exclude = fnmatch.translate(exclude) if all: search_text = [unicode(self.search_text.itemText(index)) \ for index in range(self.search_text.count())] search_path = [unicode(self.dir_combo.itemText(index)) \ for index in range(self.dir_combo.count())] include = [unicode(self.include_pattern.itemText(index)) \ for index in range(self.include_pattern.count())] exclude = [unicode(self.exclude_pattern.itemText(index)) \ for index in range(self.exclude_pattern.count())] return (search_text, text_re, search_path, include, include_re, exclude, exclude_re) else: return (path, python_path, hg_manifest, include, exclude, texts, text_re) def select_directory(self): """Select directory""" self.parent().emit(SIGNAL('redirect_stdio(bool)'), False) directory = QFileDialog.getExistingDirectory( self, translate('FindInFiles', "Select directory"), self.dir_combo.currentText()) if not directory.isEmpty(): self.set_directory(directory) self.parent().emit(SIGNAL('redirect_stdio(bool)'), True) def set_directory(self, directory): path = unicode(osp.abspath(unicode(directory))) self.dir_combo.setEditText(path) self.detect_hg_repository(path) def keyPressEvent(self, event): """Reimplemented to handle key events""" ctrl = event.modifiers() & Qt.ControlModifier shift = event.modifiers() & Qt.ShiftModifier if event.key() in (Qt.Key_Enter, Qt.Key_Return): self.emit(SIGNAL('find()')) elif event.key() == Qt.Key_F and ctrl and shift: # Toggle find widgets self.parent().emit(SIGNAL('toggle_visibility(bool)'), not self.isVisible()) event.accept() else: event.ignore()
class ConditionsDialog(QDialog): def __init__(self, reaction): super(ConditionsDialog, self).__init__() self.setGeometry(300, 200, 700, 350) self.setWindowTitle('Edit Conditions') if reaction is None: self._reaction = Reaction() else: self._reaction = reaction self._CanReturnReaction = False # Sets up GUI widgets # Reactants section self._reactantbox = QGroupBox("Reactants", self) self._reactantform = QFormLayout() self._reactantinfoboxes = [] self._productinfoboxes = [] self._catalystinfoboxes = [] self._checkbuttons = [] for x in range(Reaction.REACTING_SPECIES_LIMIT): self._reactantinfoboxes.append(QLineEdit()) self._reactantinfoboxes[x * 2].setText( self._reaction.GetReactants()[x].GetFormula()) self._reactantinfoboxes.append(QLineEdit()) self._reactantinfoboxes[x * 2 + 1].setText( str(self._reaction.GetReactants()[x].GetInitialMoles())) self._reactantform.addRow(QLabel(str(x + 1) + ".\tFormula:"), self._reactantinfoboxes[x * 2]) self._reactantform.addRow(QLabel("\tFinal Moles:"), self._reactantinfoboxes[x * 2 + 1]) self._checkbuttons.append(QCheckBox("Use this reactant", self)) self._checkbuttons[-1].setChecked( self._reaction.GetReactants()[x].GetUsed()) self._reactantform.addRow(self._checkbuttons[-1]) self._reactantbox.setLayout(self._reactantform) # Products section self._productbox = QGroupBox("Products", self) self._productform = QFormLayout() for x in range(Reaction.REACTING_SPECIES_LIMIT): self._productinfoboxes.append(QLineEdit()) self._productinfoboxes[x * 2].setText( self._reaction.GetProducts()[x].GetFormula()) self._productinfoboxes.append(QLineEdit()) self._productinfoboxes[x * 2 + 1].setText( str(self._reaction.GetProducts()[x].GetInitialMoles())) self._productform.addRow(QLabel(str(x + 1) + ".\tFormula:"), self._productinfoboxes[x * 2]) self._productform.addRow(QLabel("\tFinal Moles:"), self._productinfoboxes[x * 2 + 1]) self._checkbuttons.append(QCheckBox("Use this product", self)) self._checkbuttons[-1].setChecked( self._reaction.GetProducts()[x].GetUsed()) self._productform.addRow(self._checkbuttons[-1]) self._productbox.setLayout(self._productform) # Catalyst section self._catalystbox = QGroupBox("Catalyst", self) self._catalystform = QFormLayout() self._catalystinfoboxes.append(QLineEdit()) self._catalystinfoboxes.append(QLineEdit()) self._catalystinfoboxes[0].setText( self._reaction.GetCatalyst().GetFormula()) self._catalystinfoboxes[1].setText( str(self._reaction.GetCatalyst().GetInitialMoles())) self._catalystform.addRow(QLabel("Formula:"), self._catalystinfoboxes[0]) self._catalystform.addRow(QLabel("Moles:"), self._catalystinfoboxes[1]) self._good = QRadioButton("Good") self._poor = QRadioButton("Poor") self._inhibitor = QRadioButton("Inhibitor") self._checkbuttons.append(QCheckBox("Use this catalyst", self)) self._checkbuttons[-1].setChecked( self._reaction.GetCatalyst().GetUsed()) efficacy = self._reaction.GetCatalyst().GetEfficacy() if efficacy == 5: self._good.setChecked(True) elif efficacy == 2: self._poor.setChecked(True) else: self._inhibitor.setChecked(True) self._cataefficacygroup = QVBoxLayout() self._cataefficacygroup.addWidget(self._good) self._cataefficacygroup.addWidget(self._poor) self._cataefficacygroup.addWidget(self._inhibitor) self._catalystform.addRow(QLabel("Efficacy:"), self._cataefficacygroup) self._catalystform.addRow(self._checkbuttons[-1]) self._catalystbox.setLayout(self._catalystform) # Forward heat transfer section self._heatbox = QGroupBox("Forward heat transfer", self) self._heatform = QFormLayout() self._endo = QRadioButton("Endothermic") self._exo = QRadioButton("Exothermic") if self._reaction.GetEndothermic(): self._endo.setChecked(True) else: self._exo.setChecked(True) self._heatform.addRow(self._endo) self._heatform.addRow(self._exo) self._heatbox.setLayout(self._heatform) # Other conditions section: vessel volume; temperature self._otherbox = QGroupBox("Other conditions") self._otherform = QFormLayout() self._tempbox = QLineEdit() self._volbox = QLineEdit() self._tempbox.setText(str(self._reaction.GetTemperature())) self._volbox.setText(str(self._reaction.GetVolume())) self._otherform.addRow(QLabel("Vessel volume:"), self._volbox) self._otherform.addRow(QLabel("Temperature:"), self._tempbox) self._otherbox.setLayout(self._otherform) # Help text explaining how to enter super/subscript characters. self._scriptinfo1 = QLabel("Enter _ before a subscript character.") self._scriptinfo2 = QLabel("Enter ^ before a superscript one.") # OK and cancel buttons; checkbox so that students can try to balance the equation before it is revealed self._try = QCheckBox("Students attempt to balance equation") self._try.setChecked(False) self._okbtn = QPushButton("OK") self._okbtn.clicked.connect(self.ApplyChanges) self._cancelbtn = QPushButton("Cancel") self._rightbox = QGroupBox() self._rightbox.setFlat(False) self._rightform = QVBoxLayout() self._rightform.addWidget(self._catalystbox) self._rightform.addWidget(self._heatbox) self._rightform.addWidget(self._otherbox) self._rightbox.setLayout(self._rightform) # Layout of all those group boxes self._grid = QGridLayout() self._grid.addWidget(self._scriptinfo1, 0, 0) self._grid.addWidget(self._scriptinfo2, 1, 0) self._grid.addWidget(self._reactantbox, 2, 0) self._grid.addWidget(self._productbox, 2, 1) self._grid.addWidget(self._rightbox, 2, 2) self._grid.addWidget(self._try, 3, 0) self._grid.addWidget(self._okbtn, 3, 1) self._grid.addWidget(self._cancelbtn, 3, 2) self.setLayout(self._grid) if reaction is None: self._reaction = Reaction() else: self._reaction = reaction self._cancelbtn.clicked.connect(self.close) self.exec_() def ApplyChanges(self): errorlist = [] # Validation. If invalid data has been entered, a message describing where the problem is # and explaining what constitutes valid data is added to errorlist. formularegex = "[2-9]?(\(([A-Z][a-z]?(_[0-9])*)+\)(_[0-9])*|[A-Z][a-z]?(_[0-9])*)+((\^[0-9])*\^(\+|-))?" molesorvolumeregex = "[0-9]?[0-9]\.[0-9][0-9]?" # VALIDATES REACTANT AND PRODUCT DATA (if used) for x in range(Reaction.REACTING_SPECIES_LIMIT): if self._checkbuttons[x].isChecked(): formula = self._reactantinfoboxes[x * 2].text() moles = self._reactantinfoboxes[x * 2 + 1].text() if len(formula) not in range(1, 26): errorlist.append( "The formula of reactant " + str(x + 1) + " must be 1-25 characters long inclusive.") else: try: if formula != re.match(formularegex, formula).group(): errorlist.append( "The formula you have entered for reactant " + str(x + 1) + " is invalid.") except: errorlist.append( "The formula you have entered for reactant " + str(x + 1) + " is invalid.") try: if float(moles) < 0.01 or float(moles) > 99.99: errorlist.append( "The number of moles of reactant " + str(x + 1) + " must be between 0.01 and 99.99 inclusive.") else: try: if moles != re.match(molesorvolumeregex, moles).group(): errorlist.append( "The number of moles must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places." ) except: errorlist.append( "The number of moles must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places." ) except: errorlist.append("Number of moles of reactant " + str(x + 1) + " must be a decimal number.") if self._checkbuttons[x + Reaction.REACTING_SPECIES_LIMIT].isChecked(): formula = self._productinfoboxes[x * 2].text() moles = self._productinfoboxes[x * 2 + 1].text() if len(formula) not in range(1, 26): errorlist.append( "The formula of product " + str(x + 1) + " must be 1-25 characters long inclusive.") else: try: if formula != re.match(formularegex, formula).group(): errorlist.append( "The formula you have entered for product " + str(x + 1) + " is invalid.") except: errorlist.append( "The formula you have entered for product " + str(x + 1) + " is invalid.") try: if float(moles) < 0.01 or float(moles) > 99.99: errorlist.append( "The number of moles of product " + str(x + 1) + " must be between 0.01 and 99.99 inclusive.") else: try: if moles != re.match(molesorvolumeregex, moles).group(): errorlist.append( "The number of moles must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places." ) except: errorlist.append( "The number of moles must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places." ) except: errorlist.append("Number of moles of product " + str(x + 1) + " must be a decimal number.") # VALIDATES CATALYST DATA (if used) if self._checkbuttons[2 * Reaction.REACTING_SPECIES_LIMIT].isChecked(): formula = self._catalystinfoboxes[0].text() moles = self._catalystinfoboxes[1].text() if len(formula) not in range(1, 26): errorlist.append( "The formula of the catalyst must be 1-25 characters long inclusive." ) else: try: if formula != re.match(formularegex, formula).group(): errorlist.append( "The formula you have entered for the catalyst is invalid." ) except: errorlist.append( "The formula you have entered for the catalyst is invalid." ) try: if float(moles) < 0.01 or float(moles) > 99.99: errorlist.append( "The number of moles of the catalyst must be between 0.01 and 99.99 inclusive." ) else: try: if moles != re.match(molesorvolumeregex, moles).group(): errorlist.append( "The number of moles must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places." ) except: errorlist.append( "The number of moles must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places." ) except: errorlist.append( "Number of moles of catalyst must be a decimal number.") # VALIDATES TEMPERATURE DATA try: if int(self._tempbox.text()) not in range(1, 1000): errorlist.append( "Temperature must be between 1 and 999 inclusive.") except: errorlist.append("Temperature must be a whole number.") # VALIDATES VOLUME DATA try: volume = self._volbox.text() if float(volume) < 0.01 or float(volume) > 99.99: errorlist.append( "Volume must be between 0.01 and 99.99 inclusive.") else: try: if volume != re.match(molesorvolumeregex, volume).group(): errorlist.append( "Volume must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places." ) except: errorlist.append( "Volume must be between 0.01 and 99.99 inclusive, and must have a maximum of 2 decimal places." ) except: errorlist.append("Volume must be a decimal number.") # If all data is valid, it applies this data to the reaction. if len(errorlist) == 0: for x in range(Reaction.REACTING_SPECIES_LIMIT): self._reaction.GetReactants()[x].SetFormula( self._reactantinfoboxes[x * 2].text()) self._reaction.GetReactants()[x].SetInitialMoles( float(str(self._reactantinfoboxes[x * 2 + 1].text()))) self._reaction.GetReactants()[x].SetUsed( self._checkbuttons[x].isChecked()) self._reaction.GetProducts()[x].SetFormula( self._productinfoboxes[x * 2].text()) self._reaction.GetProducts()[x].SetInitialMoles( float(str(self._productinfoboxes[x * 2 + 1].text()))) self._reaction.GetProducts()[x].SetUsed(self._checkbuttons[ x + Reaction.REACTING_SPECIES_LIMIT].isChecked()) self._reaction.GetCatalyst().SetFormula( self._catalystinfoboxes[0].text()) self._reaction.GetCatalyst().SetInitialMoles( float(str(self._catalystinfoboxes[1].text()))) self._reaction.GetCatalyst().SetUsed(self._checkbuttons[ 2 * Reaction.REACTING_SPECIES_LIMIT].isChecked()) if self._good.isChecked(): self._reaction.GetCatalyst().SetEfficacy(5) elif self._poor.isChecked(): self._reaction.GetCatalyst().SetEfficacy(2) elif self._inhibitor.isChecked(): self._reaction.GetCatalyst().SetEfficacy(0.75) if self._endo.isChecked(): self._reaction.SetEndothermic(True) elif self._exo.isChecked(): self._reaction.SetEndothermic(False) self._reaction.SetTemperature(int(self._tempbox.text())) self._reaction.SetVolume(float(self._volbox.text())) self._CanReturnReaction = True self._showformulae = not self._try.isChecked() self.close() else: # Sets up the error list to be displayed (if not empty) and displays self._errorbox = QMessageBox() self._errorbox.setWindowTitle("Invalid Data") texttoadd = """""" for x in errorlist: texttoadd += x + "\n" self._errorbox.setText( "Some of the data you entered is invalid:\n" + texttoadd) self._errorbox.setStandardButtons(QMessageBox.Ok) self._errorbox.setDefaultButton(QMessageBox.Ok) self._CanReturnReaction = False self._showformulae = True self._errorbox.exec_() # To avoid errors, make sure to check in case of a NoneType object being returned # None is returned when the window is unable to return the reaction; for example, # when some data is invalid def GetReaction(self): if self._CanReturnReaction: return self._reaction else: return None #GETTERS AND SETTERS def GetCanShowFormulae(self): return self._showformulae
def restore_or_create(self): vbox = QVBoxLayout() main_label = QLabel(_("Electrum-VCN could not find an existing wallet.")) vbox.addWidget(main_label) grid = QGridLayout() grid.setSpacing(5) gb1 = QGroupBox(_("What do you want to do?")) vbox.addWidget(gb1) vbox1 = QVBoxLayout() gb1.setLayout(vbox1) b1 = QRadioButton(gb1) b1.setText(_("Create new wallet")) b1.setChecked(True) b2 = QRadioButton(gb1) b2.setText(_("Restore a wallet or import keys")) group1 = QButtonGroup() group1.addButton(b1) group1.addButton(b2) vbox1.addWidget(b1) vbox1.addWidget(b2) gb2 = QGroupBox(_("Wallet type:")) vbox.addWidget(gb2) vbox2 = QVBoxLayout() gb2.setLayout(vbox2) group2 = QButtonGroup() self.wallet_types = [ ('standard', _("Standard wallet")), ('twofactor', _("Wallet with two-factor authentication")), ('multisig', _("Multi-signature wallet")), ('hardware', _("Hardware wallet")), ] for i, (wtype, name) in enumerate(self.wallet_types): if not filter(lambda x: x[0] == wtype, electrum.wallet.wallet_types): continue button = QRadioButton(gb2) button.setText(name) vbox2.addWidget(button) group2.addButton(button) group2.setId(button, i) if i == 0: button.setChecked(True) vbox.addStretch(1) self.set_layout(vbox) vbox.addLayout(Buttons(CancelButton(self), OkButton(self, _('Next')))) self.show() self.raise_() if not self.exec_(): return None, None action = 'create' if b1.isChecked() else 'restore' wallet_type = self.wallet_types[group2.checkedId()][0] return action, wallet_type
class DUdpReplay(QtHelper.EnhancedQDialog, Logger.ClassLogger): """ Http replay dialog """ def __init__(self, parent = None, offlineMode=False): """ Constructor @param parent: @type parent: """ super(DUdpReplay, self).__init__(parent) self.offlineMode = offlineMode self.defaultIp = "127.0.0.1" self.defaultPort = "80" self.newTest = '' self.newTestExec = '' self.newInputs = [] self.requests = [] self.responses = [] self.defaultTemplates = DefaultTemplates.Templates() self.testType = None self.createDialog() self.createConnections() self.createActions() self.createToolbar() def createActions (self): """ Create qt actions """ self.openAction = QtHelper.createAction(self, "&Open", self.importTrace, icon=QIcon(":/folder_add.png"), tip = 'Open network trace.') self.exportTUAction = QtHelper.createAction(self, "&Test Unit", self.exportToTU, icon=QIcon(":/%s.png" % WWorkspace.TestUnit.TYPE), tip = 'Export to Test Unit') self.exportTSAction = QtHelper.createAction(self, "&Test Suite", self.exportToTS, icon=QIcon(":/%s.png" % WWorkspace.TestSuite.TYPE), tip = 'Export to Test Suite') self.cancelAction = QtHelper.createAction(self, "&Cancel", self.reject, tip = 'Cancel') menu = QMenu(self) menu.addAction( self.exportTUAction ) menu.addAction( self.exportTSAction ) self.exportToAction = QtHelper.createAction(self, "&Export to", self.exportToTU, icon=QIcon(":/%s.png" % WWorkspace.TestUnit.TYPE), tip = 'Export to tests' ) self.exportToAction.setMenu(menu) self.exportToAction.setEnabled(False) def createDialog(self): """ Create dialog """ self.dockToolbar = QToolBar(self) self.dockToolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) self.setWindowTitle(WINDOW_TITLE) self.resize(500, 400) self.ipEdit = QLineEdit(self.defaultIp) ipRegExpVal = QRegExpValidator(self) ipRegExp = QRegExp("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}") ipRegExpVal.setRegExp(ipRegExp) self.ipEdit.setValidator(ipRegExpVal) self.portEdit = QLineEdit(self.defaultPort) self.portEdit.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Fixed ) validatorPort = QIntValidator (self) self.portEdit.setValidator(validatorPort) self.progressBar = QProgressBar(self) self.progressBar.setMaximum(100) self.progressBar.setProperty("value", 0) self.progressBar.setAlignment(Qt.AlignCenter) self.progressBar.setObjectName("progressBar") self.guiSikuliGroupBox = QGroupBox("") self.guiSikuliGroupBox.setFlat(True) self.automaticAdp = QRadioButton("Automatic") self.automaticAdp.setChecked(True) self.defaultAdp = QRadioButton("Default") self.genericAdp = QRadioButton("Generic") vbox = QHBoxLayout() vbox.addWidget(self.automaticAdp) vbox.addWidget(self.defaultAdp) vbox.addWidget(self.genericAdp) vbox.addStretch(1) self.guiSikuliGroupBox.setLayout(vbox) layout = QVBoxLayout() layout.addWidget(self.dockToolbar) layout.addSpacing(12) paramLayout = QGridLayout() paramLayout.addWidget(QLabel("Destination IP:"), 0, 0, Qt.AlignRight) paramLayout.addWidget(self.ipEdit, 0, 1) paramLayout.addWidget(QLabel("Destination Port:"), 1, 0, Qt.AlignRight) paramLayout.addWidget(self.portEdit, 1, 1) paramLayout.addWidget( QLabel( self.tr("Gui adapter selector:") ), 2, 0, Qt.AlignRight) paramLayout.addWidget(self.guiSikuliGroupBox, 2, 1) layout.addLayout(paramLayout) self.logsEdit = QTextEdit() self.logsEdit.setReadOnly(True) self.logsEdit.setTextInteractionFlags(Qt.NoTextInteraction) layout.addSpacing(12) layout.addWidget(self.logsEdit) layout.addSpacing(12) layout.addWidget(self.progressBar) self.setLayout(layout) def createToolbar(self): """ Create toolbar """ self.dockToolbar.setObjectName("File toolbar") self.dockToolbar.addAction(self.openAction) self.dockToolbar.addSeparator() self.dockToolbar.addAction(self.exportToAction) self.dockToolbar.addSeparator() self.dockToolbar.setIconSize(QSize(16, 16)) def createConnections(self): """ Create qt connections """ pass def autoScrollOnTextEdit(self): """ Automatic scroll on text edit """ cursor = self.logsEdit.textCursor() cursor.movePosition(QTextCursor.End) self.logsEdit.setTextCursor(cursor) def strip_html(self, txt): """ Strip html """ if "<" in txt: txt = txt.replace( '<', '<' ) if ">" in txt: txt = txt.replace( '>', '>' ) return txt def addLogSuccess(self, txt): """ Add log success in the text edit """ self.logsEdit.insertHtml( "<span style='color:darkgreen'>%s</span><br />" % unicode( self.strip_html(txt) ) ) self.autoScrollOnTextEdit() def addLogWarning(self, txt): """ Add log warning in the text edit """ self.logsEdit.insertHtml( "<span style='color:darkorange'>%s</span><br />" % unicode( self.strip_html(txt) ) ) self.autoScrollOnTextEdit() def addLogError(self, txt): """ Add log error in the text edit """ self.logsEdit.insertHtml( "<span style='color:red'>%s</span><br />" % unicode( self.strip_html(txt) ) ) self.autoScrollOnTextEdit() def addLog(self, txt): """ Append log to the logsEdit widget """ self.logsEdit.insertHtml( "%s<br />" % unicode( self.strip_html(txt) ) ) self.autoScrollOnTextEdit() def importTrace(self): """ Import network trace """ self.logsEdit.clear() self.testType = None if not self.offlineMode: if not RCI.instance().isAuthenticated(): self.addLogWarning(txt="<< Connect to the test center in first!" ) QMessageBox.warning(self, "Import" , "Connect to the test center in first!") return self.exportToAction.setEnabled(False) self.newTest = '' self.progressBar.setMaximum(100) self.progressBar.setValue(0) if sys.version_info > (3,): fileName = QFileDialog.getOpenFileName(self, self.tr("Open File"), "", "Network dump (*.cap;*.pcap;*.pcapng)") else: fileName = QFileDialog.getOpenFileName(self, self.tr("Open File"), "", "Network dump (*.cap)") # new in v18 to support qt5 if QtHelper.IS_QT5: _fileName, _type = fileName else: _fileName = fileName # end of new if not _fileName: return if sys.version_info < (3,): extension = str(_fileName).rsplit(".", 1)[1] if not ( extension == "cap" ): self.addLogError(txt="<< File not supported %s" % _fileName) QMessageBox.critical(self, "Open" , "File not supported") return _fileName = str(_fileName) capName = _fileName.rsplit("/", 1)[1] self.addLogSuccess(txt=">> Reading the file %s" % _fileName) self.readFileV2(fileName=_fileName) def exportToTS(self): """ Export to test suite """ self.testType = TS self.exportToTest(TS=True, TU=False) def exportToTU(self): """ Export to test unit """ self.testType = TU self.exportToTest(TS=False, TU=True) def searchUDP(self): """ Search UDP module in assistant """ # modules accessor ret = "SutAdapters" if self.automaticAdp.isChecked(): isGeneric = WWorkspace.Helper.instance().isGuiGeneric(name="GUI") if isGeneric: ret = "SutAdapters.Generic" elif self.defaultAdp.isChecked(): return ret elif self.genericAdp.isChecked(): ret = "SutAdapters.Generic" else: pass return ret def exportToTest(self, TS=True, TU=False): """ Export to test """ if not RCI.instance().isAuthenticated(): self.addLogWarning(txt="<< Connect to the test center in first!" ) QMessageBox.warning(self, "Import" , "Connect to the test center in first!") return if TS: self.newTest = self.defaultTemplates.getTestDefinitionAuto() self.newTestExec = self.defaultTemplates.getTestExecutionAuto() if TU: self.newTest = self.defaultTemplates.getTestUnitDefinitionAuto() destIp = str(self.ipEdit.text()) destPort = str(self.portEdit.text()) self.newInputs = [] self.newInputs.append( {'type': 'self-ip', 'name': 'BIND_IP' , 'description': '', 'value' : '0.0.0.0', 'color': '' } ) self.newInputs.append( {'type': 'int', 'name': 'BIND_PORT' , 'description': '', 'value' : '0', 'color': '' } ) self.newInputs.append( {'type': 'str', 'name': 'DEST_IP' , 'description': '', 'value' : '%s' % destIp, 'color': '' } ) self.newInputs.append( {'type': 'int', 'name': 'DEST_PORT' , 'description': '', 'value' : '%s' % destPort, 'color': '' } ) self.newInputs.append( {'type': 'bool', 'name': 'DEBUG' , 'description': '', 'value' : 'False', 'color': '' } ) self.newInputs.append( {'type': 'float', 'name': 'TIMEOUT' , 'description': '', 'value' : '5.0', 'color': '' } ) adps = """self.ADP_UDP = %s.UDP.Client(parent=self, bindIp=input('BIND_IP'), bindPort=input('BIND_PORT'), destinationIp=input('DEST_IP'), destinationPort=input('DEST_PORT'), debug=input('DEBUG'), separatorDisabled=True)""" % self.searchUDP() # prepare steps steps = [] j = 0 for i in xrange(len(self.requests)): j = i + 1 sentrecv, req = self.requests[i] if sentrecv == 'sent': steps.append( 'self.step%s = self.addStep(expected="udp data sent", description="send udp data", summary="send udp data")' % j ) else: steps.append( 'self.step%s = self.addStep(expected="udp data received", description="received udp data", summary="received udp data")' % j ) tests = [] for i in xrange(len(self.requests)): j = i + 1 sentrecv, req = self.requests[i] (source, dest, source_port, dest_port, data) = req if sentrecv == 'sent': tests.append( "# data to sent %s" % j ) tests.append( 'self.step%s.start()' % j ) if sys.version_info > (3,): tests.append( 'rawSent = %s' % data.replace( b"'", b"\\'") ) else: tests.append( 'rawSent = """%s"""' % data ) tests.append( 'SentMsg = self.ADP_UDP.sendData(data=rawSent)' ) tests.append( 'if not SentMsg:' ) tests.append( '\tself.step%s.setFailed(actual="unable to send data")' % j) tests.append( 'else:' ) tests.append( '\tself.step%s.setPassed(actual="udp data sent succesfully")' % j ) tests.append( '' ) if sentrecv == 'recv': tests.append( "# data to received %s" % j ) tests.append( 'self.step%s.start()' % j ) if sys.version_info > (3,): tests.append( 'rawRecv = %s' % data.replace( b'"', b'\\"') ) else: tests.append( 'rawRecv = """%s"""' % data ) tests.append( 'RecvMsg = self.ADP_UDP.hasReceivedData(data=rawRecv, timeout=input("TIMEOUT"))' ) tests.append( 'if RecvMsg is None:' ) tests.append( '\tself.step%s.setFailed(actual="unable to received data")' % j) tests.append( 'else:' ) tests.append( '\tself.step%s.setPassed(actual="udp data received succesfully")' % j ) tests.append( '' ) if TS: init = """self.ADP_UDP.startListening() udpListening = self.ADP_UDP.isListening( timeout=input('TIMEOUT') ) if not udpListening: self.abort( 'unable to listing to the udp port %s' ) """ % str(self.portEdit.text()) if TU: init = """self.ADP_UDP.startListening() udpListening = self.ADP_UDP.isListening( timeout=input('TIMEOUT') ) if not udpListening: self.abort( 'unable to connect to the udp port %s' ) """ % str(self.portEdit.text()) if TS: cleanup = """self.ADP_UDP.stopListening() udpStopped = self.ADP_UDP.isStopped( timeout=input('TIMEOUT') ) if not udpStopped: self.error( 'unable to no more listen from the udp port %s' ) """ % str(self.portEdit.text()) if TU: cleanup = """self.ADP_UDP.stopListening() udpStopped = self.ADP_UDP.isStopped( timeout=input('TIMEOUT') ) if not udpStopped: self.error( 'unable to no more listen from the udp port %s' ) """ % str(self.portEdit.text()) self.newTest = self.newTest.replace( "<<PURPOSE>>", 'self.setPurpose(purpose="Replay UDP")' ) self.newTest = self.newTest.replace( "<<ADPS>>", adps ) if TS: self.newTest = self.newTest.replace( "<<STEPS>>", '\n\t\t'.join(steps) ) if TU: self.newTest = self.newTest.replace( "<<STEPS>>", '\n\t'.join(steps) ) self.newTest = self.newTest.replace( "<<INIT>>", init ) self.newTest = self.newTest.replace( "<<CLEANUP>>", cleanup ) if TS: self.newTest = self.newTest.replace( "<<TESTS>>", '\n\t\t'.join(tests) ) if TU: self.newTest = self.newTest.replace( "<<TESTS>>", '\n\t'.join(tests) ) self.accept() def readFileV2(self, fileName): """ Read pcap file Support pcap-ng too """ fd = open(fileName, 'rb') fileFormat, fileHead = PcapParse.extractFormat(fd) if fileFormat == PcapParse.FileFormat.PCAP: self.trace("pcap file detected") pcapFile = PcapReader.PcapFile(fd, fileHead).read_packet self.readFilePacket(pcapFile=pcapFile) elif fileFormat == PcapParse.FileFormat.PCAP_NG: self.trace("pcap-png file detected") pcapFile = PcapngReader.PcapngFile(fd, fileHead).read_packet self.readFilePacket(pcapFile=pcapFile) else: self.addLogError(txt="<< Error to open the network trace") self.error( 'unable to open the network trace: file format = %s' % fileFormat ) QMessageBox.critical(self, "Import" , "File not supported") def readFilePacket(self, pcapFile): """ Read file packet by packet """ ip_expected = str( self.ipEdit.text() ) port_expected = int( self.portEdit.text() ) # read packet) packets = pcapFile() ethernetPackets = list(packets) self.addLogSuccess(txt="<< Total packets detected: %s " % len(ethernetPackets)) # extract udp packet according to the expected ip and port self.requests = [] i = 1 self.progressBar.setMaximum(len(ethernetPackets)) self.progressBar.setValue(0) for pkt in ethernetPackets: self.progressBar.setValue(i) i += 1 pktDecoded = PcapParse.decodePacket(pkt, getTcp=False, getUdp=True) if pktDecoded is not None: (source, dest, source_port, dest_port, data) = pktDecoded # skip when no data exists if dest == ip_expected and int(dest_port) == int(port_expected) and len(data) > 0 : self.requests.append( ('sent', pktDecoded) ) if source == ip_expected and int(source_port) == int(port_expected) and len(data) > 0: self.requests.append( ( 'recv', pktDecoded) ) self.addLogSuccess(txt="<< Number of UDP packets detected: %s" % len(self.requests)) if self.requests: self.addLogSuccess( "<< File decoded with success!" ) self.addLogWarning( "<< Click on the export button to generate the test!" ) self.exportToAction.setEnabled(True) else: self.addLogWarning( "<< No udp extracted!" )
class FindInFilesDialog(QDialog): def __init__(self, result_widget): QDialog.__init__(self) self._find_thread = FindInFilesThread() self.setWindowTitle("Find in files") self.resize(400, 300) #MAIN LAYOUT main_vbox = QVBoxLayout(self) self.pattern_line_edit = QLineEdit() self.dir_name_root = None self.user_home = os.path.expanduser('~') self.dir_combo = QComboBox() self.dir_combo.addItem(self.user_home) self.dir_combo.setEditable(True) self.open_button = QPushButton(QIcon(resources.IMAGES['find']), self.tr("Open")) self.filters_line_edit = QLineEdit("*.py") self.case_checkbox = QCheckBox(self.tr("C&ase sensitive")) self.type_checkbox = QCheckBox(self.tr("R&egular Expression")) self.recursive_checkbox = QCheckBox(self.tr("Rec&ursive")) self.recursive_checkbox.setCheckState(Qt.Checked) self.phrase_radio = QRadioButton( self.tr("Search by Phrase (Exact Match).")) self.phrase_radio.setChecked(True) self.words_radio = QRadioButton( self.tr("Search for all the words " "(anywhere in the document, not together).")) self.find_button = QPushButton(self.tr("Find!")) self.find_button.setMaximumWidth(150) self.cancel_button = QPushButton(self.tr("Cancel")) self.cancel_button.setMaximumWidth(150) self.result_widget = result_widget hbox = QHBoxLayout() hbox.addWidget(self.find_button) hbox.addWidget(self.cancel_button) #main section find_group_box = QGroupBox(self.tr("Main")) grid = QGridLayout() grid.addWidget(QLabel(self.tr("Text: ")), 0, 0) grid.addWidget(self.pattern_line_edit, 0, 1) grid.addWidget(QLabel(self.tr("Directory: ")), 1, 0) grid.addWidget(self.dir_combo, 1, 1) grid.addWidget(self.open_button, 1, 2) grid.addWidget(QLabel(self.tr("Filter: ")), 2, 0) grid.addWidget(self.filters_line_edit, 2, 1) find_group_box.setLayout(grid) #add main section to MAIN LAYOUT main_vbox.addWidget(find_group_box) #options sections options_group_box = QGroupBox(self.tr("Options")) gridOptions = QGridLayout() gridOptions.addWidget(self.case_checkbox, 0, 0) gridOptions.addWidget(self.type_checkbox, 1, 0) gridOptions.addWidget(self.recursive_checkbox, 2, 0) gridOptions.addWidget(self.phrase_radio, 0, 1) gridOptions.addWidget(self.words_radio, 1, 1) options_group_box.setLayout(gridOptions) #add options sections to MAIN LAYOUT main_vbox.addWidget(options_group_box) #add buttons to MAIN LAYOUT main_vbox.addLayout(hbox) #Focus self.pattern_line_edit.setFocus() self.open_button.setFocusPolicy(Qt.NoFocus) #signal self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir) self.connect(self.find_button, SIGNAL("clicked()"), self._find_in_files) self.connect(self.cancel_button, SIGNAL("clicked()"), self._kill_thread) self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"), self._found_match) self.connect(self._find_thread, SIGNAL("finished()"), self._find_thread_finished) self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"), self._change_radio_enabled) def _change_radio_enabled(self, val): enabled = not self.type_checkbox.isChecked() self.phrase_radio.setEnabled(enabled) self.words_radio.setEnabled(enabled) def show(self, actual_project=None, actual=None): self.dir_combo.clear() self.dir_name_root = actual_project if \ actual_project else [self.user_home] self.dir_combo.addItems(self.dir_name_root) if actual: index = self.dir_combo.findText(actual) self.dir_combo.setCurrentIndex(index) super(FindInFilesDialog, self).show() self.pattern_line_edit.setFocus() def reject(self): self._kill_thread() # Crazy hack to avoid circular imports self.result_widget.parent().parent().parent().hide() super(FindInFilesDialog, self).reject() def _find_thread_finished(self): self.emit(SIGNAL("finished()")) def _select_dir(self): dir_name = QFileDialog.getExistingDirectory(self, self.tr("Open Directory"), self.dir_combo.currentText(), QFileDialog.ShowDirsOnly) index = self.dir_combo.findText(dir_name) if index >= 0: self.dir_combo.setCurrentIndex(index) else: self.dir_combo.insertItem(0, dir_name) self.dir_combo.setCurrentIndex(0) def _found_match(self, result): file_name = result[0] items = result[1] self.result_widget.update_result( self.dir_combo.currentText(), file_name, items) def _kill_thread(self): if self._find_thread.isRunning(): self._find_thread.cancel() self.accept() def _find_in_files(self): self.emit(SIGNAL("findStarted()")) self._kill_thread() self.result_widget.clear() pattern = self.pattern_line_edit.text() dir_name = self.dir_combo.currentText() filters = self.filters_line_edit.text().split(QRegExp("[,;]"), QString.SkipEmptyParts) #remove the spaces in the words Ex. (" *.foo"--> "*.foo") filters = [f.simplified() for f in filters] case_sensitive = self.case_checkbox.isChecked() type_ = QRegExp.RegExp if \ self.type_checkbox.isChecked() else QRegExp.FixedString recursive = self.recursive_checkbox.isChecked() by_phrase = True if self.phrase_radio.isChecked() or self.type_checkbox.isChecked(): regExp = QRegExp(pattern, case_sensitive, type_) elif self.words_radio.isChecked(): by_phrase = False type_ = QRegExp.RegExp pattern = '|'.join( [word.strip() for word in unicode(pattern).split()]) regExp = QRegExp(pattern, case_sensitive, type_) #save a reference to the root directory where we find self.dir_name_root = dir_name self._find_thread.find_in_files(dir_name, filters, regExp, recursive, by_phrase)
class FindInFilesDialog(QDialog): """Dialog to configure and trigger the search in the files.""" def __init__(self, result_widget, parent): super(FindInFilesDialog, self).__init__(parent) self._find_thread = FindInFilesThread() self.setWindowTitle(translations.TR_FIND_IN_FILES) self.resize(400, 300) #MAIN LAYOUT main_vbox = QVBoxLayout(self) self.pattern_line_edit = QLineEdit() self.pattern_line_edit.setPlaceholderText(translations.TR_FIND + "...") self.dir_name_root = None self.user_home = os.path.expanduser('~') self.dir_combo = QComboBox() self.dir_combo.addItem(self.user_home) self.dir_combo.setEditable(True) self.open_button = QPushButton(QIcon(":img/find"), translations.TR_OPEN) self.filters_line_edit = QLineEdit("*.py") self.filters_line_edit.setPlaceholderText("*.py") self.filters_line_edit.setCompleter(QCompleter( ["*{}".format(item) for item in settings.SUPPORTED_EXTENSIONS])) self.replace_line = QLineEdit() self.replace_line.setEnabled(False) self.replace_line.setPlaceholderText( translations.TR_TEXT_FOR_REPLACE + "...") self.check_replace = QCheckBox(translations.TR_REPLACE) self.case_checkbox = QCheckBox(translations.TR_CASE_SENSITIVE) self.type_checkbox = QCheckBox(translations.TR_REGULAR_EXPRESSION) self.recursive_checkbox = QCheckBox(translations.TR_RECURSIVE) self.recursive_checkbox.setCheckState(Qt.Checked) self.phrase_radio = QRadioButton(translations.TR_SEARCH_BY_PHRASE) self.phrase_radio.setChecked(True) self.words_radio = QRadioButton( translations.TR_SEARCH_FOR_ALL_THE_WORDS) self.find_button = QPushButton(translations.TR_FIND + "!") self.find_button.setMaximumWidth(150) self.cancel_button = QPushButton(translations.TR_CANCEL) self.cancel_button.setMaximumWidth(150) self.result_widget = result_widget hbox = QHBoxLayout() hbox.addWidget(self.find_button) hbox.addWidget(self.cancel_button) #main section find_group_box = QGroupBox(translations.TR_MAIN) grid = QGridLayout() grid.addWidget(QLabel(translations.TR_TEXT), 0, 0) grid.addWidget(self.pattern_line_edit, 0, 1) grid.addWidget(QLabel(translations.TR_DIRECTORY), 1, 0) grid.addWidget(self.dir_combo, 1, 1) grid.addWidget(self.open_button, 1, 2) grid.addWidget(QLabel(translations.TR_FILTER), 2, 0) grid.addWidget(self.filters_line_edit, 2, 1) grid.addWidget(self.check_replace, 3, 0) grid.addWidget(self.replace_line, 3, 1) find_group_box.setLayout(grid) #add main section to MAIN LAYOUT main_vbox.addWidget(find_group_box) #options sections options_group_box = QGroupBox(translations.TR_OPTIONS) gridOptions = QGridLayout() gridOptions.addWidget(self.case_checkbox, 0, 0) gridOptions.addWidget(self.type_checkbox, 1, 0) gridOptions.addWidget(self.recursive_checkbox, 2, 0) gridOptions.addWidget(self.phrase_radio, 0, 1) gridOptions.addWidget(self.words_radio, 1, 1) options_group_box.setLayout(gridOptions) #add options sections to MAIN LAYOUT main_vbox.addWidget(options_group_box) #add buttons to MAIN LAYOUT main_vbox.addLayout(hbox) #Focus self.pattern_line_edit.setFocus() self.open_button.setFocusPolicy(Qt.NoFocus) #signal self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir) self.connect(self.find_button, SIGNAL("clicked()"), self._find_in_files) self.connect(self.cancel_button, SIGNAL("clicked()"), self._kill_thread) self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"), self._found_match) self.connect(self._find_thread, SIGNAL("finished()"), self._find_thread_finished) self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"), self._change_radio_enabled) self.connect(self.check_replace, SIGNAL("stateChanged(int)"), self._replace_activated) self.connect(self.words_radio, SIGNAL("clicked(bool)"), self._words_radio_pressed) def _replace_activated(self): """If replace is activated, display the replace widgets.""" self.replace_line.setEnabled(self.check_replace.isChecked()) self.phrase_radio.setChecked(True) def _words_radio_pressed(self, value): """If search by independent words is activated, replace is not.""" self.replace_line.setEnabled(not value) self.check_replace.setChecked(not value) self.words_radio.setChecked(True) def _change_radio_enabled(self, val): """Control the state of the radio buttons.""" enabled = not self.type_checkbox.isChecked() self.phrase_radio.setEnabled(enabled) self.words_radio.setEnabled(enabled) def show(self, actual_project=None, actual=None): """Display the dialog and load the projects.""" self.dir_combo.clear() self.dir_name_root = actual_project if \ actual_project else [self.user_home] self.dir_combo.addItems(self.dir_name_root) if actual: index = self.dir_combo.findText(actual) self.dir_combo.setCurrentIndex(index) super(FindInFilesDialog, self).show() self.pattern_line_edit.setFocus() def reject(self): """Close the dialog and hide the tools dock.""" self._kill_thread() tools_dock = IDE.get_service('tools_dock') if tools_dock: tools_dock.hide() super(FindInFilesDialog, self).reject() def _find_thread_finished(self): """Wait on thread finished.""" self.emit(SIGNAL("finished()")) self._find_thread.wait() def _select_dir(self): """When a new folder is selected, add to the combo if needed.""" dir_name = QFileDialog.getExistingDirectory(self, translations.TR_OPEN, self.dir_combo.currentText(), QFileDialog.ShowDirsOnly) index = self.dir_combo.findText(dir_name) if index >= 0: self.dir_combo.setCurrentIndex(index) else: self.dir_combo.insertItem(0, dir_name) self.dir_combo.setCurrentIndex(0) def _found_match(self, result): """Update the tree for each match found.""" file_name = result[0] items = result[1] self.result_widget.update_result( self.dir_combo.currentText(), file_name, items) def _kill_thread(self): """Kill the thread.""" if self._find_thread.isRunning(): self._find_thread.cancel() self.accept() def _find_in_files(self): """Trigger the search on the files.""" self.emit(SIGNAL("findStarted()")) self._kill_thread() self.result_widget.clear() pattern = self.pattern_line_edit.text() dir_name = self.dir_combo.currentText() filters = re.split("[,;]", self.filters_line_edit.text()) #remove the spaces in the words Ex. (" *.foo"--> "*.foo") filters = [f.strip() for f in filters] case_sensitive = self.case_checkbox.isChecked() type_ = QRegExp.RegExp if \ self.type_checkbox.isChecked() else QRegExp.FixedString recursive = self.recursive_checkbox.isChecked() by_phrase = True if self.phrase_radio.isChecked() or self.type_checkbox.isChecked(): regExp = QRegExp(pattern, case_sensitive, type_) elif self.words_radio.isChecked(): by_phrase = False type_ = QRegExp.RegExp pattern = '|'.join( [word.strip() for word in pattern.split()]) regExp = QRegExp(pattern, case_sensitive, type_) #save a reference to the root directory where we find self.dir_name_root = dir_name self._find_thread.find_in_files(dir_name, filters, regExp, recursive, by_phrase)
class MyForm(QWidget): def __init__(self): QWidget.__init__(self) # setGeometry(x_pos, y_pos, width, height) self.setGeometry(100, 150, 500, 460) self.readSettings() self.setWindowTitle(APPNAME + ' ' + VERSION + " - " + self.chanells_path ) self.icon_path = get_icon_resource(imgdata_png_main) # self.icon_path = os.path.join(os.path.dirname(sys.argv[0]), 'chanchan.ico') self.icon = QIcon(self.icon_path) self.setWindowIcon(self.icon) self.chanells = None self.chanells_all = None self.num_channels = 0 # the player subprocess process self.proc = None self.proc_sopcast = None self.is_sopcast = False self.is_playlist = False self.on_top = False self.cache_size = CACHE_SIZE_DEFAULT if not self.haveSeenFirstTime: copy_default_playlist() self.haveSeenFirstTime = True # saving settings should be done in closeEvent() instead! # settings = QSettings(QSettings.IniFormat, QSettings.UserScope, "xh", "chanchan") # settings.setValue("seen_first_time", QVariant(self.haveSeenFirstTime)) # settings.sync() # use a grid layout for the widgets grid = QGridLayout() # bind the button click to a function reference # new connect style, needs PyQt 4.5+ ###btn_load.clicked.connect(self.load_channels_data) btn_play = QPushButton("&Play") btn_play.setToolTip("Click to play selected stream") btn_play.clicked.connect(self.on_button_play) btn_kill = QPushButton("&Stop") btn_kill.setToolTip("Click to stop current player") btn_kill.clicked.connect(self.kill_proc) self.listbox = QListWidget() # new connect style, needs PyQt 4.5+ self.listbox.clicked.connect(self.on_select) self.listbox.doubleClicked.connect(self.on_double_click) # attach right-click handler self.listbox.setContextMenuPolicy(Qt.ActionsContextMenu) #self.listbox.setContextMenuPolicy(Qt.CustomContextMenu) #http://talk.maemo.org/showthread.php?t=64034 self.actionCopyUrl = QAction("Copy URL", self.listbox) self.connect(self.actionCopyUrl, SIGNAL("triggered()"), self.copy_to_clipboard) self.actionPlay = QAction("Play", self.listbox) self.actionPlay.setShortcut("Ctrl+P") self.actionRestartPlayer = QAction("Restart SopPlayer", self.listbox) self.actionReloadChannels = QAction("Reload List", self.listbox) self.actionEditChannels = QAction("Edit Playlist", self.listbox) self.actionEditChannels.setShortcut("Ctrl+E") self.actionOpenChannelsFile = QAction("Open Playlist File", self.listbox) self.actionEditSource = QAction("Edit Source", self.listbox) self.actionAbout = QAction("About %s" % APPNAME, self.listbox) self.actionQuit = QAction("Quit", self) self.actionQuit.setShortcut("Ctrl+Q") self.search = QLineEdit() self.connect(self.search, SIGNAL("textChanged(QString)"), self.on_search_text_change) # clear button self.clear_button = QToolButton() self.clear_button.setIcon(get_icon_resource(imgdata_png_clear)) self.clear_button.setIconSize(QSize(16, 16)) self.clear_button.setCursor(Qt.ArrowCursor) self.clear_button.setAutoRaise(True) self.clear_button.setEnabled(False) # self.main_layout.addWidget(self.clear_button) self.connect(self.clear_button, SIGNAL("clicked()"), self.clear_search_text) self.listbox.addAction(self.actionPlay) self.listbox.addAction(self.actionRestartPlayer) self.listbox.addAction(self.actionCopyUrl) self.listbox.addAction(self.actionOpenChannelsFile) self.listbox.addAction(self.actionReloadChannels) self.listbox.addAction(self.actionEditChannels) self.listbox.addAction(self.actionEditSource) self.listbox.addAction(self.actionAbout) self.addAction(self.actionQuit) self.connect(self.actionPlay, SIGNAL("triggered()"), self.on_double_click) self.connect(self.actionRestartPlayer, SIGNAL("triggered()"), self.restart_sopplayer) self.connect(self.actionReloadChannels, SIGNAL("triggered()"), lambda: self.load_channels_data(self.chanells_path)) self.connect(self.actionEditChannels, SIGNAL("triggered()"), lambda: self.edit_file(str(self.chanells_path))) self.connect(self.actionOpenChannelsFile, SIGNAL("triggered()"), lambda: self.load_channels_data()) self.connect(self.actionEditSource, SIGNAL("triggered()"), lambda: self.edit_file(path=sys.argv[0], editor=EDITOR)) self.connect(self.actionQuit, SIGNAL("triggered()"), self.close) self.connect(self.actionAbout, SIGNAL("triggered()"), lambda: QMessageBox.about(self, 'About %s' % APPNAME, ''' <h4>%s version %s</h4> <p> Created by <i>%s</i></p> <p><a href="mailto:%s">%s</a></p> <p><a href="%s">chanchantv.googlecode.com</a></p> ''' % (APPNAME, VERSION, AUTHOR, EMAIL.decode('base64'), EMAIL, WEB)) # warning(self, APPNAME, 'No playlist selected') ) # self.listbox.connect(self.listbox, SIGNAL("customContextMenuRequested(QPoint)"), # self.on_right_click) # self.txtChanInfo = QLineEdit() # self.txtChanInfo.setReadOnly(True) # self.logWindow = QTextEdit() # self.logWindow.setSizePolicyx(QSizePolicy.) self.status = QLabel() self.status.setText('channels') # ADD BEVELED BORDER::self.status.setFrameStyle(QFrame.Panel | QFrame.Sunken) self.groupBox = QGroupBox("Engine") sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth()) self.groupBox.setSizePolicy(sizePolicy) # self.groupBox.setAutoFillBackground(True) self.rbMplayer = QRadioButton('&Mplayer', self.groupBox) self.rbMplayer.setChecked(True) self.rbMplayer.setToolTip("Play with Mplayer") #self.rbGstreamer = QRadioButton('gst&123', self.groupBox) self.rbVlc = QRadioButton('&Vlc', self.groupBox) self.rbVlc.setToolTip("Play with VLC") self.rbTotem = QRadioButton('&Totem', self.groupBox) self.rbTotem.setToolTip("Play with Totem") self.rbBrowser = QRadioButton('&Browser', self.groupBox) self.rbBrowser.setToolTip("Open URL in web browser") self.hBoxTop = QHBoxLayout() self.hBoxTop.addWidget(self.rbMplayer) #self.hBoxTop.addWidget(self.rbGstreamer) self.hBoxTop.addWidget(self.rbVlc) self.hBoxTop.addWidget(self.rbTotem) self.hBoxTop.addWidget(self.rbBrowser) self.groupBox.setLayout(self.hBoxTop) self.cbPlaylistFlag = QCheckBox('Playlist') self.cbPlaylistFlag.setToolTip('Resource is a M3U, ASX or PLS playlist') self.cbFullScreen = QCheckBox('Full Screen') self.cbFullScreen.setToolTip('Start video in full screen') self.cbFullScreen.setChecked(self.is_full_screen) self.cbInhibitScreensaver = QCheckBox('Inhibit Screensaver') self.cbInhibitScreensaver.setToolTip('Disable screensaver while playing stream') self.cbInhibitScreensaver.setChecked(self.is_inhibit_screen) # addWidget(widget, row, column, rowSpan, columnSpan) grid.addWidget(self.groupBox, 0, 0, 1, 3) grid.addWidget(btn_play, 0, 4, 1, 1) grid.addWidget(btn_kill, 0, 5, 1, 1) grid.addWidget(self.search, 1, 0, 1, 4) grid.addWidget(self.clear_button, 1, 3, 1, 1) grid.addWidget(self.status, 1, 5, 1, 1) # listbox spans over 5 rows and 2 columns grid.addWidget(self.listbox, 2, 0, 5, 6) ## BAD grid.addWidget(self.hBoxFlags, 6, 0, 1, 1) grid.addWidget(self.cbPlaylistFlag, 7, 0, 1, 1) grid.addWidget(self.cbFullScreen, 7, 1, 1, 1) grid.addWidget(self.cbInhibitScreensaver, 7, 2, 1, 1) # grid.addWidget(self.txtChanInfo, 7, 0, 1, 6) # grid.addWidget(self.logWindow, 8, 0, 1, 6) self.setLayout(grid) self.search.setFocus() self.load_channels_data(self.chanells_path) def clear_search_text(self): print '------clear-search-text---------' self.search.clear() def on_search_text_change(self): if not self.chanells_all: # only need to do this once self.chanells_all = list(self.chanells) text = str(self.search.text()).strip() print 'DBG', len(text), len(self.chanells_all) if len(text) > 1: self.clear_button.setEnabled(True) filtered_list = self.get_matching_items(text.lower(), self.chanells_all) if len(filtered_list): self.chanells = filtered_list else: self.chanells = [] else: self.chanells = list(self.chanells_all) self.clear_button.setEnabled(False) self.load_channels_data(None, False) def get_matching_items(self, needle, haystack): 'search for a substring in channel list' matches = [] found_in_meta = False last_meta_item = None for ch in haystack: is_meta = ch.startswith('#') if is_meta and not needle in ch.lower(): last_meta_item = ch if needle in ch.lower(): if is_meta: found_in_meta = True elif not found_in_meta and last_meta_item not in matches: matches.append(last_meta_item) matches.append(ch) elif found_in_meta: if not is_meta: matches.append(ch) else: found_in_meta = False return matches def closeEvent(self, event): self.writeSettings() print 'closeEvent: Saving settings and exiting...' return quit_msg = "Are you sure you want to exit the program?" reply = QMessageBox.question(self, 'Message', quit_msg, QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.Yes: self.writeSettings() event.accept() QApplication.instance().quit() else: event.ignore() def keyPressEvent(self, event): if event.key() == Qt.Key_Escape: self.search.setFocus() self.search.selectAll() def copy_to_clipboard(self): clipboard = QApplication.clipboard() clipboard.setText(self.listbox.currentItem().text()) def load_channels_data(self, new_path=None, read_from_file=True): MediaItem.num_items = 0 if read_from_file: if not new_path: new_path = str(self.get_new_filename()) if not new_path: # QMessageBox.warning(self, APPNAME, 'No playlist selected') return try: fh = codecs.open(new_path, 'r', 'utf8') self.chanells = [ch.strip() for ch in fh.readlines()] except Exception as e: show_gui_error(e, 'File not found', 'Error opening playlist "%s" \n\n%s' % (new_path, str(e))) return self.chanells_path = new_path self.chanells = [ch.strip() for ch in self.chanells] self.chanells_all = None self.listbox.clear() current_params = None for chan in self.chanells: if not len(chan) or chan.strip() == '#EXTM3U': continue item = MediaItem(chan, self.icon) if item.is_meta: '''if a metadata line, then store and apply to all the following non-metadata items ''' current_params = item.params elif current_params: item.params = current_params item.setStatusTip(chan) self.listbox.addItem(item) self.setWindowTitle(APPNAME + ' ' + VERSION + ' - ' + self.chanells_path) self.status.setText(str(MediaItem.num_items) + ' channels') def edit_file(self, path, editor=EDITOR): if ' ' in editor: editor = editor.split(' ') subprocess.Popen([editor, path]) def get_new_filename(self): return QFileDialog.getOpenFileName(self, 'Load Playlist file', '', "Playlist files (*.m3u);;All Files (*.*);") def on_button_play(self): # self.on_select() self.play_media() def on_select(self): """an item in the listbox has been clicked/selected""" current_item = self.listbox.currentItem() if not current_item: return current_channel = current_item and str(current_item.text()) or '<no channel>' self.is_playlist = current_channel[-4:].lower() in ['.m3u', '.asx', '.pls'] # if current_channel.startswith('sop:'): #self.rbMplayer.setChecked(True) # self.cache_size = '1024' if current_item.params: 'set params for current channel according to metadata line' myparams = current_item.params.keys() if 'player' in myparams: player = current_item.params['player'].lower() if player == 'totem': self.rbTotem.setChecked(True) elif player == MPLAYER: self.rbMplayer.setChecked(True) #elif player == 'gst123': # self.rbGstreamer.setChecked(True) elif player == VLC: self.rbVlc.setChecked(True) elif player in ('browser', 'web'): self.rbBrowser.setChecked(True) if 'playlist' in myparams or 'pl' in myparams: self.is_playlist = current_item.params['playlist'].lower() in GOOD_VALUES if 'fullscreen' in myparams or 'fs' in myparams: self.is_full_screen = current_item.params['fullscreen'].lower() in GOOD_VALUES else: self.is_full_screen = IS_FULLSCREEN_DEFAULT if 'ontop' in myparams or 'top' in myparams: self.on_top = current_item.params['top'].lower() in GOOD_VALUES else: self.on_top = IS_ON_TOP_DEFAULT if 'cache' in myparams: self.cache_size = current_item.params['cache'] else: self.cache_size = CACHE_SIZE_DEFAULT if 'exec' in myparams or 'shell' in myparams: # set shell options: console or no console self.exec_shell_command = current_item.params['exec'] # # if 'exec' in myparams: # self.executable_name = current_item.params['exec'] self.cbPlaylistFlag.setChecked(self.is_playlist) # only setting True state if self.is_full_screen: self.cbFullScreen.setChecked(True) def on_double_click(self): self.play_media() """an item in the listbox has been double-clicked""" def restart_sopplayer(self): # if self.rbVlc.isChecked(): # if vlc_remote_command('testing if vlc remote is running...'): # vlc_remote_command('add %s' % SOPCAST_SERVER_URL) # vlc_remote_command('volume 200') # else: self.play_media(start_sopcast_server=False) def play_media(self, start_sopcast_server=True): current_item = self.listbox.currentItem() if not current_item: return current_channel = str(current_item.text()) if self.proc and self.proc.pid: self.kill_proc() args = [] if self.cbInhibitScreensaver.isChecked(): suspend_screensaver() ################ RUN SHELL COMMAND ############# if 'exec' in current_item.params: show_console = current_item.params['exec'].lower() == 'console' if show_console: args += ['xterm', '-geometry', '45x8-20+400', '-e'] args += [current_channel.strip()] self.proc = subprocess.Popen(args, stdout=subprocess.PIPE) print 'DBG:', self.proc else: args.insert(0, current_item.params['exec']) args += [current_channel.strip()] self.proc = subprocess.Popen(args, shell=True) return # don't use xterm for vlc, totem if (self.rbMplayer.isChecked()): if not is_win32 and not is_osx: args += ['xterm', '-geometry', '45x8-20+150', '-e'] self.is_sopcast = current_channel.lower().startswith('sop://') if self.is_sopcast: if start_sopcast_server: # args_sopcast = ['xterm', '-geometry', '45x8-20+400', '-e', sopcast_binary, current_channel, SOPCAST_LISTEN_PORT, SOPCAST_SERVER_PORT] try: print 'Waiting for sopcast server starup at %s ...' % current_channel self.proc_sopcast = run_command_in_new_terminal( sopcast_binary, current_channel, SOPCAST_LISTEN_PORT, SOPCAST_SERVER_PORT) # except Exception as e: show_gui_error(e, """ERROR! Sopcast executable not found or other error: To install sopcast support on Linux, run: %s""" % (SOPCAST_INSTALL_HOWTO)) return current_channel = SOPCAST_SERVER_URL time.sleep(SOPCAST_SERVER_WAIT_SECS) if self.rbMplayer.isChecked(): if is_win32: args = ['cmd', '/c', MPLAYER_PATH_WIN32, '-cache-min', CACHE_SIZE_MIN, '-cache', self.cache_size] else: args += [MPLAYER, '-cache-min', CACHE_SIZE_MIN, '-cache', self.cache_size] self.on_top and args.append('-ontop') self.cbFullScreen.isChecked() and args.append('-fs') self.cbPlaylistFlag.isChecked() and args.append('-playlist') #elif self.rbGstreamer.isChecked(): # args.append('gst123') # if '.m3u' in current_channel: # current_channel = getFirstUrl(current_channel) elif self.rbVlc.isChecked(): if is_win32: if os.path.exists(VLC_PATH_WIN32): args = [VLC_PATH_WIN32] elif os.path.exists(VLC_PATH_WIN32_CUSTOM): args = [VLC_PATH_WIN32_CUSTOM] elif is_osx: args = [VLC_PATH_OSX]#, '--one-instance'] else: args = ['vlc']#, '--one-instance'] # if vlc_remote_command('testing if vlc remote is running...'): # # print 'VLC Remote Control not running, starting new VLC instance...' # vlc_remote_command('add %s' % current_channel) # vlc_remote_command('volume 150') # return # else: # print 'VLC Remote Control not running, starting new VLC instance...' self.cbFullScreen.isChecked() and args.append('--fullscreen') args.append('--video-on-top') elif self.rbTotem.isChecked(): args += ['totem', '--replace'] # FIXME!!! totem segfaults when started with the --fullscreen switch # self.cbFullScreen.isChecked() and args.append('--fullscreen') elif self.rbBrowser.isChecked(): open_webbrowser(current_channel) return args.append(current_channel) print args try: if is_win32: #self.proc = subprocess.Popen(args, creationflags=subprocess.STARTF_USESHOWWINDOW, cwd=os.path.dirname(sys.argv[0])) ## TODO: get right options on win32 #http://stackoverflow.com/questions/7006238/how-do-i-hide-the-console-when-i-use-os-system-or-subprocess-call #startupinfo = subprocess.STARTUPINFO() #startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW #subprocess.call('taskkill /F /IM exename.exe', startupinfo=startupinfo) self.proc = subprocess.Popen(args, shell=True, cwd=os.path.dirname(sys.argv[0])) else: self.proc = subprocess.Popen(args, stdout=subprocess.PIPE, stdin=subprocess.PIPE) print 'DBG:', type(self.proc), self.proc # console_data = self.proc.stdout.read() # self.logWindow.setText(console_data) except Exception as e: show_gui_error(e, "ERROR! Selected player not available:\n") def kill_proc(self): if self.cbInhibitScreensaver.isChecked(): resume_screensaver() if self.proc and not self.rbVlc.isChecked(): try: self.proc.kill() except: pass if self.is_sopcast and self.proc_sopcast: try: self.proc_sopcast.kill() os.system('killall sopcast') except: pass def readSettings(self): # store settings object self.settings = QSettings(QSettings.IniFormat, QSettings.UserScope, "xh", "chanchan") pos = self.settings.value("pos", QVariant(QPoint(200, 200))).toPoint() size = self.settings.value("size", QVariant(QSize(400, 400))).toSize() self.resize(size) self.move(pos) self.chanells_path = self.settings.contains('channels_file') and str(self.settings.value("channels_file").toString()) or get_default_channels_path() self.is_inhibit_screen = self.settings.contains('inhibit_screen') and self.settings.value("inhibit_screen").toBool() self.is_full_screen = self.settings.contains('fullscreen') and self.settings.value("fullscreen").toBool() self.haveSeenFirstTime = self.settings.contains('seen_first_time') and self.settings.value("seen_first_time").toBool() def writeSettings(self): settings = QSettings(QSettings.IniFormat, QSettings.UserScope, "xh", "chanchan") settings.setValue("pos", QVariant(self.pos())) settings.setValue("size", QVariant(self.size())) settings.setValue("channels_file", QVariant(self.chanells_path)) settings.setValue("inhibit_screen", QVariant(self.cbInhibitScreensaver.isChecked())) settings.setValue("fullscreen", QVariant(self.cbFullScreen.isChecked())) settings.setValue("seen_first_time", QVariant(self.haveSeenFirstTime)) settings.sync()
class LegendPropertiesWindow(PyDialog): """ +-------------------+ | Legend Properties | +-----------------------+ | Title ______ Default | | Min ______ Default | | Max ______ Default | | Format ______ Default | | Scale ______ Default | | Number of Colors ____ | | Number of Labels ____ | | Label Size ____ | (TODO) | ColorMap ____ | (TODO) | | | x Min/Max (Blue->Red) | | o Max/Min (Red->Blue) | | | | x Vertical/Horizontal | | x Show/Hide | | | | Apply OK Cancel | +-----------------------+ """ def __init__(self, data, win_parent=None): PyDialog.__init__(self, data, win_parent) #Init the base class self._updated_legend = False self._icase = data['icase'] self._default_icase = self._icase self._default_name = data['name'] self._default_min = data['min'] self._default_max = data['max'] self._default_scale = data['default_scale'] self._scale = data['scale'] self._default_format = data['default_format'] self._format = data['format'] self._default_labelsize = data['default_labelsize'] self._labelsize = data['labelsize'] self._default_nlabels = data['default_nlabels'] self._nlabels = data['nlabels'] self._default_ncolors = data['default_ncolors'] self._ncolors = data['ncolors'] self._default_colormap = data['default_colormap'] self._colormap = data['colormap'] self._default_is_low_to_high = data['is_low_to_high'] self._default_is_discrete = data['is_discrete'] self._default_is_horizontal = data['is_horizontal'] self._default_is_shown = data['is_shown'] self._update_defaults_to_blank() #self.setupUi(self) self.setWindowTitle('Legend Properties') self.create_widgets() self.create_layout() self.set_connections() #self.show() def _update_defaults_to_blank(self): """Changes the default (None) to a blank string""" if self._default_colormap is None: self._default_colormap = 'jet' if self._default_labelsize is None: self._default_labelsize = '' if self._default_ncolors is None: self._default_ncolors = '' if self._default_nlabels is None: self._default_nlabels = '' if self._colormap is None: self._colormap = 'jet' if self._labelsize is None: self._labelsize = '' if self._ncolors is None: self._ncolors = '' if self._nlabels is None: self._nlabels = '' def update_legend(self, icase, name, min_value, max_value, data_format, scale, nlabels, labelsize, ncolors, colormap, default_title, default_min_value, default_max_value, default_data_format, default_scale, default_nlabels, default_labelsize, default_ncolors, default_colormap, is_low_to_high, is_horizontal_scalar_bar): """ We need to update the legend if there's been a result change request """ if icase != self._default_icase: self._default_icase = icase self._default_name = default_title self._default_min = default_min_value self._default_max = default_max_value self._default_format = default_data_format self._default_is_low_to_high = is_low_to_high self._default_is_discrete = True self._default_is_horizontal = is_horizontal_scalar_bar self._default_scale = default_scale self._default_nlabels = default_nlabels self._default_labelsize = default_labelsize self._default_ncolors = default_ncolors self._default_colormap = default_colormap if colormap is None: colormap = 'jet' if labelsize is None: labelsize = '' if ncolors is None: ncolors = '' if nlabels is None: nlabels = '' self._update_defaults_to_blank() assert isinstance(scale, float), 'scale=%r' % scale assert isinstance(default_scale, float), 'default_scale=%r' % default_scale if self._default_scale == 0.0: self.scale_edit.setEnabled(False) self.scale_button.setEnabled(False) else: self.scale_edit.setEnabled(True) self.scale_button.setEnabled(True) #self.on_default_name() #self.on_default_min() #self.on_default_max() #self.on_default_format() #self.on_default_scale() # reset defaults self.name_edit.setText(name) self.name_edit.setStyleSheet("QLineEdit{background: white;}") self.min_edit.setText(str(min_value)) self.min_edit.setStyleSheet("QLineEdit{background: white;}") self.max_edit.setText(str(max_value)) self.max_edit.setStyleSheet("QLineEdit{background: white;}") self.format_edit.setText(str(data_format)) self.format_edit.setStyleSheet("QLineEdit{background: white;}") self.scale_edit.setText(str(scale)) self.scale_edit.setStyleSheet("QLineEdit{background: white;}") self.nlabels_edit.setText(str(nlabels)) self.nlabels_edit.setStyleSheet("QLineEdit{background: white;}") self.labelsize_edit.setText(str(labelsize)) self.labelsize_edit.setStyleSheet("QLineEdit{background: white;}") self.ncolors_edit.setText(str(ncolors)) self.ncolors_edit.setStyleSheet("QLineEdit{background: white;}") self.colormap_edit.setCurrentIndex( colormap_keys.index(str(colormap))) self.on_apply() def create_widgets(self): # Name self.name = QLabel("Title:") self.name_edit = QLineEdit(str(self._default_name)) self.name_button = QPushButton("Default") # Min self.min = QLabel("Min:") self.min_edit = QLineEdit(str(self._default_min)) self.min_button = QPushButton("Default") # Max self.max = QLabel("Max:") self.max_edit = QLineEdit(str(self._default_max)) self.max_button = QPushButton("Default") # Format self.format = QLabel("Format (e.g. %.3f, %g, %.6e):") self.format_edit = QLineEdit(str(self._format)) self.format_button = QPushButton("Default") # Scale self.scale = QLabel("Scale:") self.scale_edit = QLineEdit(str(self._scale)) self.scale_button = QPushButton("Default") if self._default_scale == 0.0: self.scale_edit.setEnabled(False) self.scale_button.setEnabled(False) #tip = QtGui.QToolTip() #tip.setTe #self.format_edit.toolTip(tip) #--------------------------------------- # nlabels self.nlabels = QLabel("Number of Labels:") self.nlabels_edit = QLineEdit(str(self._nlabels)) self.nlabels_button = QPushButton("Default") self.labelsize = QLabel("Label Size:") self.labelsize_edit = QLineEdit(str(self._labelsize)) self.labelsize_button = QPushButton("Default") self.ncolors = QLabel("Number of Colors:") self.ncolors_edit = QLineEdit(str(self._ncolors)) self.ncolors_button = QPushButton("Default") self.colormap = QLabel("Color Map:") self.colormap_edit = QComboBox(self) self.colormap_button = QPushButton("Default") for key in colormap_keys: self.colormap_edit.addItem(key) self.colormap_edit.setCurrentIndex(colormap_keys.index(self._colormap)) # red/blue or blue/red self.low_to_high_radio = QRadioButton('Low -> High') self.high_to_low_radio = QRadioButton('High -> Low') widget = QWidget(self) low_to_high_group = QButtonGroup(widget) low_to_high_group.addButton(self.low_to_high_radio) low_to_high_group.addButton(self.high_to_low_radio) self.low_to_high_radio.setChecked(self._default_is_low_to_high) self.high_to_low_radio.setChecked(not self._default_is_low_to_high) # horizontal / vertical self.horizontal_radio = QRadioButton("Horizontal") self.vertical_radio = QRadioButton("Vertical") widget = QWidget(self) horizontal_vertical_group = QButtonGroup(widget) horizontal_vertical_group.addButton(self.horizontal_radio) horizontal_vertical_group.addButton(self.vertical_radio) self.horizontal_radio.setChecked(self._default_is_horizontal) self.vertical_radio.setChecked(not self._default_is_horizontal) # on / off self.show_radio = QRadioButton("Show") self.hide_radio = QRadioButton("Hide") widget = QWidget(self) show_hide_group = QButtonGroup(widget) show_hide_group.addButton(self.show_radio) show_hide_group.addButton(self.hide_radio) self.show_radio.setChecked(self._default_is_shown) self.hide_radio.setChecked(not self._default_is_shown) # closing self.apply_button = QPushButton("Apply") self.ok_button = QPushButton("OK") self.cancel_button = QPushButton("Cancel") def create_layout(self): grid = QGridLayout() grid.addWidget(self.name, 0, 0) grid.addWidget(self.name_edit, 0, 1) grid.addWidget(self.name_button, 0, 2) grid.addWidget(self.min, 1, 0) grid.addWidget(self.min_edit, 1, 1) grid.addWidget(self.min_button, 1, 2) grid.addWidget(self.max, 2, 0) grid.addWidget(self.max_edit, 2, 1) grid.addWidget(self.max_button, 2, 2) grid.addWidget(self.format, 3, 0) grid.addWidget(self.format_edit, 3, 1) grid.addWidget(self.format_button, 3, 2) grid.addWidget(self.scale, 4, 0) grid.addWidget(self.scale_edit, 4, 1) grid.addWidget(self.scale_button, 4, 2) grid.addWidget(self.nlabels, 5, 0) grid.addWidget(self.nlabels_edit, 5, 1) grid.addWidget(self.nlabels_button, 5, 2) #grid.addWidget(self.labelsize, 6, 0) #grid.addWidget(self.labelsize_edit, 6, 1) #grid.addWidget(self.labelsize_button, 6, 2) grid.addWidget(self.ncolors, 6, 0) grid.addWidget(self.ncolors_edit, 6, 1) grid.addWidget(self.ncolors_button, 6, 2) grid.addWidget(self.colormap, 7, 0) grid.addWidget(self.colormap_edit, 7, 1) grid.addWidget(self.colormap_button, 7, 2) ok_cancel_box = QHBoxLayout() ok_cancel_box.addWidget(self.apply_button) ok_cancel_box.addWidget(self.ok_button) ok_cancel_box.addWidget(self.cancel_button) grid2 = QGridLayout() title = QLabel("Color Scale:") grid2.addWidget(title, 0, 0) grid2.addWidget(self.low_to_high_radio, 1, 0) grid2.addWidget(self.high_to_low_radio, 2, 0) grid2.addWidget(self.vertical_radio, 1, 1) grid2.addWidget(self.horizontal_radio, 2, 1) grid2.addWidget(self.show_radio, 1, 2) grid2.addWidget(self.hide_radio, 2, 2) #grid2.setSpacing(0) vbox = QVBoxLayout() vbox.addLayout(grid) #vbox.addLayout(checkboxes) vbox.addLayout(grid2) vbox.addStretch() vbox.addLayout(ok_cancel_box) #Create central widget, add layout and set #central_widget = QtGui.QWidget() #central_widget.setLayout(vbox) #self.setCentralWidget(central_widget) self.setLayout(vbox) def set_connections(self): if qt_version == 4: self.connect(self.name_button, QtCore.SIGNAL('clicked()'), self.on_default_name) self.connect(self.min_button, QtCore.SIGNAL('clicked()'), self.on_default_min) self.connect(self.max_button, QtCore.SIGNAL('clicked()'), self.on_default_max) self.connect(self.format_button, QtCore.SIGNAL('clicked()'), self.on_default_format) self.connect(self.scale_button, QtCore.SIGNAL('clicked()'), self.on_default_scale) self.connect(self.nlabels_button, QtCore.SIGNAL('clicked()'), self.on_default_nlabels) self.connect(self.labelsize_button, QtCore.SIGNAL('clicked()'), self.on_default_labelsize) self.connect(self.ncolors_button, QtCore.SIGNAL('clicked()'), self.on_default_ncolors) self.connect(self.colormap_button, QtCore.SIGNAL('clicked()'), self.on_default_colormap) self.connect(self.apply_button, QtCore.SIGNAL('clicked()'), self.on_apply) self.connect(self.ok_button, QtCore.SIGNAL('clicked()'), self.on_ok) self.connect(self.cancel_button, QtCore.SIGNAL('clicked()'), self.on_cancel) self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent) #self.colormap_edit.activated[str].connect(self.onActivated) else: self.name_button.clicked.connect(self.on_default_name) self.min_button.clicked.connect(self.on_default_min) self.max_button.clicked.connect(self.on_default_max) self.format_button.clicked.connect(self.on_default_format) self.scale_button.clicked.connect(self.on_default_scale) self.nlabels_button.clicked.connect(self.on_default_nlabels) self.labelsize_button.clicked.connect(self.on_default_labelsize) self.ncolors_button.clicked.connect(self.on_default_ncolors) self.colormap_button.clicked.connect(self.on_default_colormap) self.apply_button.clicked.connect(self.on_apply) self.ok_button.clicked.connect(self.on_ok) self.cancel_button.clicked.connect(self.on_cancel) # closeEvent??? def on_default_name(self): name = str(self._default_name) self.name_edit.setText(name) self.name_edit.setStyleSheet("QLineEdit{background: white;}") def on_default_min(self): self.min_edit.setText(str(self._default_min)) self.min_edit.setStyleSheet("QLineEdit{background: white;}") def on_default_max(self): self.max_edit.setText(str(self._default_max)) self.max_edit.setStyleSheet("QLineEdit{background: white;}") def on_default_format(self): self.format_edit.setText(str(self._default_format)) self.format_edit.setStyleSheet("QLineEdit{background: white;}") def on_default_scale(self): self.scale_edit.setText(str(self._default_scale)) self.scale_edit.setStyleSheet("QLineEdit{background: white;}") def on_default_ncolors(self): self.ncolors_edit.setText(str(self._default_ncolors)) self.ncolors_edit.setStyleSheet("QLineEdit{background: white;}") def on_default_colormap(self): self.colormap_edit.setCurrentIndex( colormap_keys.index(self._default_colormap)) def on_default_nlabels(self): self.nlabels_edit.setStyleSheet("QLineEdit{background: white;}") self.nlabels_edit.setText(str(self._default_nlabels)) def on_default_labelsize(self): self.labelsize_edit.setText(str(self._default_labelsize)) self.labelsize_edit.setStyleSheet("QLineEdit{background: white;}") @staticmethod def check_name(cell): cell_value = cell.text() try: text = str(cell_value).strip() except UnicodeEncodeError: cell.setStyleSheet("QLineEdit{background: red;}") return None, False if len(text): cell.setStyleSheet("QLineEdit{background: white;}") return text, True else: cell.setStyleSheet("QLineEdit{background: red;}") return None, False @staticmethod def check_colormap(cell): text = str(cell.text()).strip() if text in colormap_keys: cell.setStyleSheet("QLineEdit{background: white;}") return text, True else: cell.setStyleSheet("QLineEdit{background: red;}") return None, False def on_validate(self): name_value, flag0 = self.check_name(self.name_edit) min_value, flag1 = self.check_float(self.min_edit) max_value, flag2 = self.check_float(self.max_edit) format_value, flag3 = self.check_format(self.format_edit) scale_value, flag4 = self.check_float(self.scale_edit) nlabels, flag5 = self.check_positive_int_or_blank(self.nlabels_edit) ncolors, flag6 = self.check_positive_int_or_blank(self.ncolors_edit) labelsize, flag7 = self.check_positive_int_or_blank( self.labelsize_edit) colormap = str(self.colormap_edit.currentText()) if all([flag0, flag1, flag2, flag3, flag4, flag5, flag6, flag7]): if 'i' in format_value: format_value = '%i' assert isinstance(scale_value, float), scale_value self.out_data['name'] = name_value self.out_data['min'] = min_value self.out_data['max'] = max_value self.out_data['format'] = format_value self.out_data['scale'] = scale_value self.out_data['nlabels'] = nlabels self.out_data['ncolors'] = ncolors self.out_data['labelsize'] = labelsize self.out_data['colormap'] = colormap self.out_data['is_low_to_high'] = self.low_to_high_radio.isChecked( ) self.out_data['is_horizontal'] = self.horizontal_radio.isChecked() self.out_data['is_shown'] = self.show_radio.isChecked() self.out_data['clicked_ok'] = True self.out_data['close'] = True #print('self.out_data = ', self.out_data) #print("name = %r" % self.name_edit.text()) #print("min = %r" % self.min_edit.text()) #print("max = %r" % self.max_edit.text()) #print("format = %r" % self.format_edit.text()) return True return False def on_apply(self): passed = self.on_validate() if passed: self.win_parent._apply_legend(self.out_data) return passed def on_ok(self): passed = self.on_apply() if passed: self.close() #self.destroy() def on_cancel(self): self.out_data['close'] = True self.close()
class GithubCredentialsWizardPage(QWizardPage): def __init__(self, parent=None): super(GithubCredentialsWizardPage, self).__init__( parent, title="Credentials", subTitle="Enter your username/password or token") # Radio Buttons self.userPassRadioButton = QRadioButton() self.userPassRadioButton.toggled.connect(self.changeMode) self.userPassRadioButton.toggled.connect(self.completeChanged.emit) self.tokenRadioButton = QRadioButton() self.tokenRadioButton.toggled.connect(self.changeMode) self.tokenRadioButton.toggled.connect(self.completeChanged.emit) # LineEdits # usernameEdit self.usernameEdit = QLineEdit( textChanged=self.completeChanged.emit) # Username may only contain alphanumeric characters or dash # and cannot begin with a dash self.usernameEdit.setValidator( QRegExpValidator(QRegExp('[A-Za-z\d]+[A-Za-z\d-]+'))) # passwordEdit self.passwordEdit = QLineEdit( textChanged=self.completeChanged.emit) self.passwordEdit.setValidator( QRegExpValidator(QRegExp('.+'))) self.passwordEdit.setEchoMode(QLineEdit.Password) # tokenEdit self.tokenEdit = QLineEdit( textChanged=self.completeChanged.emit) # token may only contain alphanumeric characters self.tokenEdit.setValidator( QRegExpValidator(QRegExp('[A-Za-z\d]+'))) self.tokenEdit.setEchoMode(QLineEdit.Password) # Form form = QFormLayout() form.addRow("<b>username/password</b>", self.userPassRadioButton) form.addRow("username: "******"password: "******"<b>token</b>", self.tokenRadioButton) form.addRow("token: ", self.tokenEdit) # Layout self.mainLayout = QVBoxLayout() self.mainLayout.addLayout(form) self.setLayout(self.mainLayout) # Fields self.registerField("username", self.usernameEdit) self.registerField("password", self.passwordEdit) self.registerField("token", self.tokenEdit) self.userPassRadioButton.toggle() self.require_2fa = False def changeMode(self): if self.userPassRadioButton.isChecked(): self.usernameEdit.setEnabled(True) self.passwordEdit.setEnabled(True) self.tokenEdit.setEnabled(False) elif self.tokenRadioButton.isChecked(): self.usernameEdit.setEnabled(False) self.passwordEdit.setEnabled(False) self.tokenEdit.setEnabled(True) def nextId(self): if self.require_2fa: return 2 # TODO remove magic number else: return 3 # TODO remove magic number def isComplete(self): if self.userPassRadioButton.isChecked(): usernameValidator = self.usernameEdit.validator() usernameText = self.usernameEdit.text() usernameState = usernameValidator.validate(usernameText, 0)[0] passwordValidator = self.passwordEdit.validator() passwordText = self.passwordEdit.text() passwordState = passwordValidator.validate(passwordText, 0)[0] if usernameState == QValidator.Acceptable and \ passwordState == QValidator.Acceptable: return True elif self.tokenRadioButton.isChecked(): tokenValidator = self.tokenEdit.validator() tokenText = self.tokenEdit.text() tokenState = tokenValidator.validate(tokenText, 0)[0] if tokenState == QValidator.Acceptable: return True return False @waiting_effects def validatePage(self): # TODO - clean this up if self.userPassRadioButton.isChecked(): username = str(self.field('username').toString()) password = str(self.field('password').toString()) try: g = Github(username, password) user = g.get_user() authentication = user.create_authorization(scopes=['repo'], note='test') except TwoFactorException: self.require_2fa = True return True except GithubException: self.require_2fa = False return False self.setField('token', str(authentication.token)) self.require_2fa = False return True elif self.tokenRadioButton.isChecked(): token = str(self.field('token').toString()) try: self.setField('username', Github(token).get_user().login) except BadCredentialsException: return False else: self.require_2fa = False return True else: self.require_2fa = False return False
class SkinsTab(QWidget): def __init__(self): QWidget.__init__(self) vbox = QVBoxLayout(self) #Top Bar hbox = QHBoxLayout() self.radioDefault = QRadioButton("Default Skin") self.radioCustom = QRadioButton("Custom") self.comboSkins = QComboBox() self.skins = loader.load_gui_skins() for item in self.skins: self.comboSkins.addItem(item) hbox.addWidget(self.radioDefault) hbox.addWidget(self.radioCustom) hbox.addWidget(self.comboSkins) #Text Area self.txtStyle = QPlainTextEdit() self.txtStyle.setReadOnly(True) #Settings settings = QSettings() settings.beginGroup('preferences') settings.beginGroup('skins') if settings.value('default', True).toBool(): self.radioDefault.setChecked(True) self.comboSkins.setEnabled(False) else: self.radioCustom.setChecked(True) index = self.comboSkins.findText(settings.value('selectedSkin', '').toString()) self.comboSkins.setCurrentIndex(index) content = self.skins[str(self.comboSkins.currentText())] self.txtStyle.setPlainText(content) settings.endGroup() settings.endGroup() vbox.addLayout(hbox) vbox.addWidget(self.txtStyle) vbox.addWidget(QLabel('Requires restart the IDE')) #Signals self.connect(self.radioDefault, SIGNAL("clicked()"), self._default_clicked) self.connect(self.radioCustom, SIGNAL("clicked()"), self._custom_clicked) def _default_clicked(self): self.comboSkins.setEnabled(False) self.txtStyle.setPlainText('') def _custom_clicked(self): self.comboSkins.setEnabled(True) content = self.skins[str(self.comboSkins.currentText())] self.txtStyle.setPlainText(content) def save(self): settings = QSettings() settings.beginGroup('preferences') settings.beginGroup('skins') settings.setValue('default', self.radioDefault.isChecked()) settings.setValue('selectedSkin', self.comboSkins.currentText()) settings.endGroup() settings.endGroup()
class NewDocument(preferences.Group): def __init__(self, page): super(NewDocument, self).__init__(page) grid = QGridLayout() self.setLayout(grid) def changed(): self.changed.emit() self.combo.setEnabled(self.template.isChecked()) self.emptyDocument = QRadioButton(toggled=changed) self.lilyVersion = QRadioButton(toggled=changed) self.template = QRadioButton(toggled=changed) self.combo = QComboBox(currentIndexChanged=changed) grid.addWidget(self.emptyDocument, 0, 0, 1, 2) grid.addWidget(self.lilyVersion, 1, 0, 1, 2) grid.addWidget(self.template, 2, 0, 1, 1) grid.addWidget(self.combo, 2, 1, 1, 1) self.loadCombo() app.translateUI(self) def translateUI(self): self.setTitle(_("When creating new documents")) self.emptyDocument.setText(_("Create an empty document")) self.lilyVersion.setText(_("Create a document that contains the LilyPond version statement")) self.template.setText(_("Create a document from a template:")) from snippet import snippets for i, name in enumerate(self._names): self.combo.setItemText(i, snippets.title(name)) def loadCombo(self): from snippet import snippets self._names = [name for name in snippets.names() if snippets.get(name).variables.get('template')] self.combo.clear() self.combo.addItems([''] * len(self._names)) def loadSettings(self): s = QSettings() ndoc = s.value("new_document", "empty", type("")) template = s.value("new_document_template", "", type("")) if template in self._names: self.combo.setCurrentIndex(self._names.index(template)) if ndoc == "template": self.template.setChecked(True) elif ndoc == "version": self.lilyVersion.setChecked(True) else: self.emptyDocument.setChecked(True) def saveSettings(self): s = QSettings() if self._names and self.template.isChecked(): s.setValue("new_document", "template") s.setValue("new_document_template", self._names[self.combo.currentIndex()]) elif self.lilyVersion.isChecked(): s.setValue("new_document", "version") else: s.setValue("new_document", "empty")
class Preferences(QDialog): def __init__(self, parent=None, test = False): super(Preferences, self).__init__(parent) self.parent = parent self.test = test self.default_videocodecs = [ 'flv', 'h263', 'libvpx', 'libx264', 'libxvid', 'mpeg2video', 'mpeg4', 'msmpeg4', 'wmv2' ] self.default_audiocodecs = [ 'aac', 'ac3', 'copy', 'libfaac', 'libmp3lame', 'libvo_aacenc', 'libvorbis', 'mp2', 'wmav2' ] saveQL = QLabel('<html><b>' + self.tr('Save files') + '</b></html>') existQL = QLabel(self.tr('Existing files:')) self.exst_prefixQRB = QRadioButton(self.tr("Add '~' prefix")) self.exst_overwriteQRB = QRadioButton(self.tr('Overwrite')) exist_layout = utils.add_to_layout( 'h', self.exst_prefixQRB, self.exst_overwriteQRB) defaultQL = QLabel(self.tr('Default output destination:')) self.defaultQLE = QLineEdit() self.defaultQTB = QToolButton() self.defaultQTB.setText('...') deafult_fol_layout = utils.add_to_layout( 'h', self.defaultQLE, self.defaultQTB) nameQL = QLabel('<html><b>' + self.tr('Name files') +'</b></html>') prefixQL = QLabel(self.tr('Prefix:')) suffixQL = QLabel(self.tr('Suffix:')) self.prefixQLE = QLineEdit() self.suffixQLE = QLineEdit() grid = utils.add_to_grid( [prefixQL, self.prefixQLE], [suffixQL, self.suffixQLE]) prefix_layout = utils.add_to_layout('h', grid, None) tabwidget1_layout = utils.add_to_layout( 'v', saveQL, QSpacerItem(14, 13), existQL, exist_layout, QSpacerItem(14, 13), defaultQL, deafult_fol_layout, QSpacerItem(13, 13), nameQL, QSpacerItem(14, 13), prefix_layout, None ) ffmpegQL = QLabel('<html><b>' + self.tr('FFmpeg') +'</b></html>') default_cmdQL = QLabel(self.tr('Default command:')) self.cmdQLE = QLineEdit() useQL = QLabel(self.tr('Use:')) self.ffmpegQRB = QRadioButton(self.tr('FFmpeg')) self.avconvQRB = QRadioButton(self.tr('avconv')) hlayout = utils.add_to_layout('h', self.ffmpegQRB, self.avconvQRB) vidcodecsQL = QLabel( '<html><b>' + self.tr('Video codecs') +'</b></html>') self.vidcodecsQPTE = QPlainTextEdit() audcodecsQL = QLabel( '<html><b>' + self.tr('Audio codecs') +'</b></html>') self.audcodecsQPTE = QPlainTextEdit() extraformatsQL = QLabel( '<html><b>' + self.tr('Extra formats') +'</b></html>') self.extraformatsQPTE = QPlainTextEdit() gridlayout = utils.add_to_grid( [vidcodecsQL, audcodecsQL, extraformatsQL], [self.vidcodecsQPTE, self.audcodecsQPTE, self.extraformatsQPTE]) defvidcodecsQPB = QPushButton(self.tr("Default video codecs")) defaudcodecsQPB = QPushButton(self.tr("Default audio codecs")) hlayout2 = utils.add_to_layout( 'h', None, defvidcodecsQPB, defaudcodecsQPB) tabwidget2_layout = utils.add_to_layout( 'v', ffmpegQL, QSpacerItem(14, 13), useQL, hlayout, QSpacerItem(14, 13), default_cmdQL, self.cmdQLE, QSpacerItem(20, 20), gridlayout, hlayout2, None ) widget1 = QWidget() widget1.setLayout(tabwidget1_layout) widget2 = QWidget() widget2.setLayout(tabwidget2_layout) tabWidget = QTabWidget() tabWidget.addTab(widget1, self.tr('General')) tabWidget.addTab(widget2, self.tr('Audio/Video')) buttonBox = QDialogButtonBox( QDialogButtonBox.Ok|QDialogButtonBox.Cancel) final_layout = utils.add_to_layout('v', tabWidget, None, buttonBox) self.setLayout(final_layout) self.defaultQTB.clicked.connect(self.open_dir) buttonBox.accepted.connect(self.save_settings) buttonBox.rejected.connect(self.reject) defvidcodecsQPB.clicked.connect(self.set_default_videocodecs) defaudcodecsQPB.clicked.connect(self.set_default_audiocodecs) self.resize(400, 480) self.setWindowTitle(self.tr('Preferences')) QTimer.singleShot(0, self.load_settings) def load_settings(self): """Load settings and update graphical widgets with loaded values.""" settings = QSettings() overwrite_existing = utils.str_to_bool( settings.value('overwrite_existing')) default_output = settings.value('default_output') prefix = settings.value('prefix') suffix = settings.value('suffix') avconv_prefered = utils.str_to_bool(settings.value('avconv_prefered')) default_command = settings.value('default_command') videocodecs = settings.value('videocodecs') audiocodecs = settings.value('audiocodecs') extraformats = settings.value('extraformats') # QSettings.value() returns str() in python3, not QVariant() as in p2 if overwrite_existing: self.exst_overwriteQRB.setChecked(True) else: self.exst_prefixQRB.setChecked(True) if default_output: self.defaultQLE.setText(default_output) if prefix: self.prefixQLE.setText(prefix) if suffix: self.suffixQLE.setText(suffix) if avconv_prefered: self.avconvQRB.setChecked(True) else: self.ffmpegQRB.setChecked(True) if default_command: self.cmdQLE.setText(default_command) else: self.cmdQLE.setText(config.default_ffmpeg_cmd) if not self.test and not self.parent.ffmpeg: self.avconvQRB.setChecked(True) self.ffmpegQRB.setEnabled(False) if not self.test and not self.parent.avconv: self.ffmpegQRB.setChecked(True) self.avconvQRB.setEnabled(False) if not videocodecs: self.set_default_videocodecs() else: self.vidcodecsQPTE.setPlainText(videocodecs) if not audiocodecs: self.set_default_audiocodecs else: self.audcodecsQPTE.setPlainText(audiocodecs) self.extraformatsQPTE.setPlainText(extraformats) def set_default_videocodecs(self): self.vidcodecsQPTE.setPlainText("\n".join(self.default_videocodecs)) def set_default_audiocodecs(self): self.audcodecsQPTE.setPlainText("\n".join(self.default_audiocodecs)) def open_dir(self): """Get a directory name using a standard Qt dialog and update self.defaultQLE with dir's name.""" if self.defaultQLE.isEnabled(): _dir = QFileDialog.getExistingDirectory( self, 'FF Multi Converter - ' + self.tr('Choose default output destination'), config.home ) if _dir: self.defaultQLE.setText(_dir) def save_settings(self): """Set settings values, extracting the appropriate information from the graphical widgets.""" # remove empty codecs videocodecs = [] audiocodecs = [] extraformats = [] for i in self.vidcodecsQPTE.toPlainText().split("\n"): i = i.strip() if len(i.split()) == 1: # single word videocodecs.append(i) for i in self.audcodecsQPTE.toPlainText().split("\n"): i = i.strip() if len(i.split()) == 1: audiocodecs.append(i) for i in self.extraformatsQPTE.toPlainText().split("\n"): i = i.strip() if len(i.split()) == 1: extraformats.append(i) videocodecs = "\n".join(sorted(videocodecs)) audiocodecs = "\n".join(sorted(audiocodecs)) extraformats = "\n".join(sorted(extraformats)) settings = QSettings() settings.setValue( 'overwrite_existing', self.exst_overwriteQRB.isChecked()) settings.setValue( 'default_output', self.defaultQLE.text()) settings.setValue( 'prefix', self.prefixQLE.text()) settings.setValue( 'suffix', self.suffixQLE.text()) settings.setValue( 'avconv_prefered', self.avconvQRB.isChecked()) settings.setValue( 'default_command', self.cmdQLE.text()) settings.setValue( 'videocodecs', videocodecs) settings.setValue( 'audiocodecs', audiocodecs) settings.setValue( 'extraformats', extraformats) self.accept()
class FeeSelectionDialog(ArmoryDialog): ############################################################################# def __init__(self, parent, main, cs_callback, get_csstate): super(FeeSelectionDialog, self).__init__(parent, main) #Button Label self.lblButtonFee = QLabelButton("") #get default values flatFee = self.main.getSettingOrSetDefault("Default_Fee", MIN_TX_FEE) flatFee = coin2str(flatFee, maxZeros=1).strip() fee_byte = str(self.main.getSettingOrSetDefault("Default_FeeByte", MIN_FEE_BYTE)) blocksToConfirm = self.main.getSettingOrSetDefault(\ "Default_FeeByte_BlocksToConfirm", NBLOCKS_TO_CONFIRM) self.coinSelectionCallback = cs_callback self.getCoinSelectionState = get_csstate self.validAutoFee = True try: autoFee_byte = str(estimateFee(blocksToConfirm) / 1000.0) except: autoFee_byte = "N/A" self.validAutoFee = False defaultCheckState = \ self.main.getSettingOrSetDefault("FeeOption", DEFAULT_FEE_TYPE) #flat free def setFlatFee(): def callbck(): return self.selectType('FlatFee') return callbck def updateLbl(): self.updateCoinSelection() self.radioFlatFee = QRadioButton(self.tr("Flat Fee (BTC)")) self.edtFeeAmt = QLineEdit(flatFee) self.edtFeeAmt.setFont(GETFONT('Fixed')) self.edtFeeAmt.setMinimumWidth(tightSizeNChar(self.edtFeeAmt, 6)[0]) self.edtFeeAmt.setMaximumWidth(tightSizeNChar(self.edtFeeAmt, 12)[0]) self.connect(self.radioFlatFee, SIGNAL('clicked()'), setFlatFee()) self.connect(self.edtFeeAmt, SIGNAL('textChanged(QString)'), updateLbl) frmFlatFee = QFrame() frmFlatFee.setFrameStyle(STYLE_RAISED) layoutFlatFee = QGridLayout() layoutFlatFee.addWidget(self.radioFlatFee, 0, 0, 1, 1) layoutFlatFee.addWidget(self.edtFeeAmt, 0, 1, 1, 1) frmFlatFee.setLayout(layoutFlatFee) #fee/byte def setFeeByte(): def callbck(): return self.selectType('FeeByte') return callbck self.radioFeeByte = QRadioButton(self.tr("Fee/Byte (Satoshi/Byte)")) self.edtFeeByte = QLineEdit(fee_byte) self.edtFeeByte.setFont(GETFONT('Fixed')) self.edtFeeByte.setMinimumWidth(tightSizeNChar(self.edtFeeByte, 6)[0]) self.edtFeeByte.setMaximumWidth(tightSizeNChar(self.edtFeeByte, 12)[0]) self.connect(self.radioFeeByte, SIGNAL('clicked()'), setFeeByte()) self.connect(self.edtFeeByte, SIGNAL('textChanged(QString)'), updateLbl) frmFeeByte = QFrame() frmFeeByte.setFrameStyle(STYLE_RAISED) layoutFeeByte = QGridLayout() layoutFeeByte.addWidget(self.radioFeeByte, 0, 0, 1, 1) layoutFeeByte.addWidget(self.edtFeeByte, 0, 1, 1, 1) frmFeeByte.setLayout(layoutFeeByte) #auto fee/byte def setAutoFeeByte(): def callbck(): return self.selectType('Auto') return callbck radioButtonTxt = self.tr("Fee rate from node (sat/Byte): ") if not self.validAutoFee: radioButtonTxt = self.tr("Failed to fetch fee/byte from node") self.radioAutoFeeByte = QRadioButton(radioButtonTxt) self.lblAutoFeeByte = QLabel(autoFee_byte) self.lblAutoFeeByte.setFont(GETFONT('Fixed')) self.lblAutoFeeByte.setMinimumWidth(tightSizeNChar(self.lblAutoFeeByte, 6)[0]) self.lblAutoFeeByte.setMaximumWidth(tightSizeNChar(self.lblAutoFeeByte, 12)[0]) self.sliderAutoFeeByte = QSlider(Qt.Horizontal, self) self.sliderAutoFeeByte.setMinimum(2) self.sliderAutoFeeByte.setMaximum(6) self.sliderAutoFeeByte.setValue(blocksToConfirm) self.lblSlider = QLabel() def getSliderLabelTxt(): return self.tr("Blocks to confirm: %1").arg(\ unicode(self.sliderAutoFeeByte.value())) def updateAutoFeeByte(): blocksToConfirm = self.sliderAutoFeeByte.value() try: autoFee_byte = str(estimateFee(blocksToConfirm) / 1000.0) except: autoFee_byte = "N/A" self.lblSlider.setText(getSliderLabelTxt()) self.lblAutoFeeByte.setText(autoFee_byte) updateLbl() self.lblSlider.setText(getSliderLabelTxt()) self.connect(self.radioAutoFeeByte, SIGNAL('clicked()'), setAutoFeeByte()) self.sliderAutoFeeByte.valueChanged.connect(updateAutoFeeByte) self.sliderAutoFeeByte.setEnabled(False) frmAutoFeeByte = QFrame() frmAutoFeeByte.setFrameStyle(STYLE_RAISED) layoutAutoFeeByte = QGridLayout() layoutAutoFeeByte.addWidget(self.radioAutoFeeByte, 0, 0, 1, 1) layoutAutoFeeByte.addWidget(self.lblAutoFeeByte, 0, 1, 1, 1) layoutAutoFeeByte.addWidget(self.lblSlider, 1, 0, 1, 2) layoutAutoFeeByte.addWidget(self.sliderAutoFeeByte, 2, 0, 1, 2) frmAutoFeeByte.setLayout(layoutAutoFeeByte) if not self.validAutoFee: frmAutoFeeByte.setEnabled(False) #adjust and close self.btnClose = QPushButton(self.tr('Close')) self.connect(self.btnClose, SIGNAL('clicked()'), self.accept) self.checkBoxAdjust = QCheckBox(self.tr('Adjust fee/byte for privacy')) self.checkBoxAdjust.setChecked(\ self.main.getSettingOrSetDefault('AdjustFee', True)) self.connect(self.checkBoxAdjust, SIGNAL('clicked()'), updateLbl) frmClose = makeHorizFrame(\ [self.checkBoxAdjust, 'Stretch', self.btnClose], STYLE_NONE) #main layout layout = QGridLayout() layout.addWidget(frmAutoFeeByte, 0, 0, 1, 4) layout.addWidget(frmFeeByte, 2, 0, 1, 4) layout.addWidget(frmFlatFee, 4, 0, 1, 4) layout.addWidget(frmClose, 5, 0, 1, 4) self.setLayout(layout) self.setWindowTitle(self.tr('Select Fee Type')) self.selectType(defaultCheckState) self.setFocus() ############################################################################# def selectType(self, strType): self.radioFlatFee.setChecked(False) self.radioFeeByte.setChecked(False) self.radioAutoFeeByte.setChecked(False) self.sliderAutoFeeByte.setEnabled(False) if strType == 'FlatFee': self.radioFlatFee.setChecked(True) elif strType == 'FeeByte': self.radioFeeByte.setChecked(True) elif strType == 'Auto': if not self.validAutoFee: self.radioFeeByte.setChecked(True) else: self.radioAutoFeeByte.setChecked(True) self.sliderAutoFeeByte.setEnabled(True) self.updateCoinSelection() self.updateLabelButton() ############################################################################# def updateCoinSelection(self): try: self.coinSelectionCallback() except: self.updateLabelButton() ############################################################################# def getLabelButton(self): return self.lblButtonFee ############################################################################# def updateLabelButtonText(self, txSize, flatFee, fee_byte): txSize = str(txSize) if txSize != 'N/A': txSize += " B" if flatFee != 'N/A': flatFee = coin2str(flatFee, maxZeros=0).strip() flatFee += " BTC" if not isinstance(fee_byte, str): fee_byte = '%.2f' % fee_byte lblStr = "Size: %s, Fee: %s" % (txSize, flatFee) if fee_byte != 'N/A': lblStr += " (%s sat/B)" % fee_byte self.lblButtonFee.setText(lblStr) ############################################################################# def updateLabelButton(self, reset=False): try: if reset: raise Exception() txSize, flatFee, feeByte = self.getCoinSelectionState() self.updateLabelButtonText(txSize, flatFee, feeByte) except: self.updateLabelButtonText('N/A', 'N/A', 'N/A') ############################################################################# def resetLabel(self): self.updateLabelButton(True) ############################################################################# def getFeeData(self): fee = 0 fee_byte = 0 if self.radioFlatFee.isChecked(): flatFeeText = str(self.edtFeeAmt.text()) fee = str2coin(flatFeeText) elif self.radioFeeByte.isChecked(): fee_byteText = str(self.edtFeeByte.text()) fee_byte = float(fee_byteText) elif self.radioAutoFeeByte.isChecked(): fee_byteText = str(self.lblAutoFeeByte.text()) fee_byte = float(fee_byteText) adjust_fee = self.checkBoxAdjust.isChecked() return fee, fee_byte, adjust_fee
class Preferences(QDialog): def __init__(self, parent=None, test=False): super(Preferences, self).__init__(parent) self.parent = parent self.test = test saveQL = QLabel('<html><b>' + self.tr('Save files') + '</b></html>') existQL = QLabel(self.tr('Existing files:')) self.exst_prefixQRB = QRadioButton(self.tr("Add '~' prefix")) self.exst_overwriteQRB = QRadioButton(self.tr('Overwrite')) exist_layout = utils.add_to_layout('h', self.exst_prefixQRB, self.exst_overwriteQRB) defaultQL = QLabel(self.tr('Default output destination:')) self.defaultQLE = QLineEdit() self.defaultQTB = QToolButton() self.defaultQTB.setText('...') deafult_fol_layout = utils.add_to_layout('h', self.defaultQLE, self.defaultQTB) nameQL = QLabel('<html><b>' + self.tr('Name files') + '</b></html>') prefixQL = QLabel(self.tr('Prefix:')) suffixQL = QLabel(self.tr('Suffix:')) self.prefixQLE = QLineEdit() self.suffixQLE = QLineEdit() grid = utils.add_to_grid([prefixQL, self.prefixQLE], [suffixQL, self.suffixQLE]) prefix_layout = utils.add_to_layout('h', grid, None) tabwidget1_layout = utils.add_to_layout('v', saveQL, QSpacerItem(14, 13), existQL, exist_layout, QSpacerItem(14, 13), defaultQL, deafult_fol_layout, QSpacerItem(13, 13), nameQL, QSpacerItem(14, 13), prefix_layout, None) ffmpegQL = QLabel('<html><b>FFmpeg</b></html>') default_cmd_ffmpegQL = QLabel(self.tr('Default command:')) self.ffmpegcmdQLE = QLineEdit() vidcodecsQL = QLabel('<html><b>' + self.tr('Video codecs') + '</b></html>') self.vidcodecsQPTE = QPlainTextEdit() audcodecsQL = QLabel('<html><b>' + self.tr('Audio codecs') + '</b></html>') self.audcodecsQPTE = QPlainTextEdit() extraformatsffmpegQL = QLabel('<html><b>' + self.tr('Extra formats') + '</b></html>') self.extraformatsffmpegQPTE = QPlainTextEdit() gridlayout = utils.add_to_grid( [vidcodecsQL, audcodecsQL, extraformatsffmpegQL], [ self.vidcodecsQPTE, self.audcodecsQPTE, self.extraformatsffmpegQPTE ]) defvidcodecsQPB = QPushButton(self.tr("Default video codecs")) defaudcodecsQPB = QPushButton(self.tr("Default audio codecs")) hlayout1 = utils.add_to_layout('h', None, defvidcodecsQPB, defaudcodecsQPB) tabwidget2_layout = utils.add_to_layout('v', ffmpegQL, QSpacerItem(14, 13), default_cmd_ffmpegQL, self.ffmpegcmdQLE, QSpacerItem(20, 20), gridlayout, hlayout1, None) imagemagickQL = QLabel('<html><b>ImageMagick (convert)</b></html>') default_cmd_imageQL = QLabel(self.tr('Default options:')) self.imagecmdQLE = QLineEdit() extraformatsimageQL = QLabel('<html><b>' + self.tr('Extra formats') + '</b></html>') self.extraformatsimageQPTE = QPlainTextEdit() hlayout2 = utils.add_to_layout('h', self.extraformatsimageQPTE, QSpacerItem(220, 20)) tabwidget3_layout = utils.add_to_layout('v', imagemagickQL, QSpacerItem(14, 13), default_cmd_imageQL, self.imagecmdQLE, QSpacerItem(20, 20), extraformatsimageQL, hlayout2, None) widget1 = QWidget() widget1.setLayout(tabwidget1_layout) widget2 = QWidget() widget2.setLayout(tabwidget2_layout) widget3 = QWidget() widget3.setLayout(tabwidget3_layout) tabWidget = QTabWidget() tabWidget.addTab(widget1, self.tr('General')) tabWidget.addTab(widget2, self.tr('Audio/Video')) tabWidget.addTab(widget3, self.tr('Images')) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) final_layout = utils.add_to_layout('v', tabWidget, None, buttonBox) self.setLayout(final_layout) self.defaultQTB.clicked.connect(self.open_dir) buttonBox.accepted.connect(self.save_settings) buttonBox.rejected.connect(self.reject) defvidcodecsQPB.clicked.connect(self.set_default_videocodecs) defaudcodecsQPB.clicked.connect(self.set_default_audiocodecs) self.resize(400, 450) self.setWindowTitle(self.tr('Preferences')) QTimer.singleShot(0, self.load_settings) def load_settings(self): """Load settings and update graphical widgets with loaded values.""" settings = QSettings() overwrite_existing = utils.str_to_bool( settings.value('overwrite_existing')) default_output = settings.value('default_output') prefix = settings.value('prefix') suffix = settings.value('suffix') default_command = settings.value('default_command') videocodecs = settings.value('videocodecs') audiocodecs = settings.value('audiocodecs') extraformats_video = settings.value('extraformats') default_command_image = settings.value('default_command_image') extraformats_image = settings.value('extraformats_image') # QSettings.value() returns str() in python3, not QVariant() as in p2 if overwrite_existing: self.exst_overwriteQRB.setChecked(True) else: self.exst_prefixQRB.setChecked(True) if default_output: self.defaultQLE.setText(default_output) if prefix: self.prefixQLE.setText(prefix) if suffix: self.suffixQLE.setText(suffix) if default_command: self.ffmpegcmdQLE.setText(default_command) else: self.ffmpegcmdQLE.setText(config.default_ffmpeg_cmd) if not videocodecs: self.set_default_videocodecs() else: self.vidcodecsQPTE.setPlainText(videocodecs) if not audiocodecs: self.set_default_audiocodecs else: self.audcodecsQPTE.setPlainText(audiocodecs) self.extraformatsffmpegQPTE.setPlainText(extraformats_video) if default_command_image: self.imagecmdQLE.setText(default_command_image) else: self.imagecmdQLE.setText(config.default_imagemagick_cmd) self.extraformatsimageQPTE.setPlainText(extraformats_image) def set_default_videocodecs(self): self.vidcodecsQPTE.setPlainText("\n".join(config.video_codecs)) def set_default_audiocodecs(self): self.audcodecsQPTE.setPlainText("\n".join(config.audio_codecs)) def open_dir(self): """Get a directory name using a standard Qt dialog and update self.defaultQLE with dir's name.""" if self.defaultQLE.isEnabled(): _dir = QFileDialog.getExistingDirectory( self, 'FF Multi Converter - ' + self.tr('Choose default output destination'), config.home) if _dir: self.defaultQLE.setText(_dir) def save_settings(self): """Set settings values, extracting the appropriate information from the graphical widgets.""" # remove empty codecs videocodecs = [] audiocodecs = [] extraformats_video = [] extraformats_image = [] for i in self.vidcodecsQPTE.toPlainText().split("\n"): i = i.strip() if len(i.split()) == 1 and i not in videocodecs: # i single word videocodecs.append(i) for i in self.audcodecsQPTE.toPlainText().split("\n"): i = i.strip() if len(i.split()) == 1 and i not in audiocodecs: audiocodecs.append(i) for i in self.extraformatsffmpegQPTE.toPlainText().split("\n"): i = i.strip() if len(i.split()) == 1 and i not in extraformats_video \ and i not in config.video_formats: extraformats_video.append(i) for i in self.extraformatsimageQPTE.toPlainText().split("\n"): i = i.strip() if len(i.split()) == 1 and i not in extraformats_image \ and i not in config.image_formats: extraformats_image.append(i) videocodecs = "\n".join(sorted(videocodecs)) audiocodecs = "\n".join(sorted(audiocodecs)) extraformats_video = "\n".join(sorted(extraformats_video)) extraformats_image = "\n".join(sorted(extraformats_image)) settings = QSettings() settings.setValue('overwrite_existing', self.exst_overwriteQRB.isChecked()) settings.setValue('default_output', self.defaultQLE.text()) settings.setValue('prefix', self.prefixQLE.text()) settings.setValue('suffix', self.suffixQLE.text()) settings.setValue('default_command', self.ffmpegcmdQLE.text()) settings.setValue('videocodecs', videocodecs) settings.setValue('audiocodecs', audiocodecs) settings.setValue('extraformats', extraformats_video) settings.setValue('default_command_image', self.imagecmdQLE.text()) settings.setValue('extraformats_image', extraformats_image) self.accept()
class GeosurfaceSimulationDialog( QDialog): def __init__(self, application_dir, help_html_subpath): super( GeosurfaceSimulationDialog, self ).__init__() self.application_dir = application_dir self.help_html_subpath = help_html_subpath self.analytical_surface_params = None self.geographical_surface_params = None self.setup_gui() def setup_gui( self ): dialog_layout = QVBoxLayout() main_widget = QTabWidget() main_widget.addTab( self.setup_simulation_tab(), "Simulation" ) main_widget.addTab( self.setup_help_tab(), "Help" ) dialog_layout.addWidget(main_widget) self.setLayout( dialog_layout ) self.adjustSize() self.setWindowTitle( 'simSurf - Geosurface simulation' ) def setup_simulation_tab( self ): simulWidget = QWidget() simulLayout = QGridLayout( ) simulToolBox = QToolBox() simulToolBox.addItem( self.setup_analformula_tb(), "Analytical formula" ) simulToolBox.addItem( self.setup_geogrparams_tb(), "Geographic parameters" ) simulToolBox.addItem( self.setup_output_tb(), "Output" ) simulLayout.addWidget( simulToolBox, 0, 0, 1, 2 ) simulWidget.setLayout(simulLayout) return simulWidget def setup_analformula_tb( self ): analformWidget = QWidget() analformLayout = QGridLayout( ) analformLayout.addWidget( QLabel("a min"), 0, 0, 1, 1 ) self.a_min_QLineEdit = QLineEdit() analformLayout.addWidget( self.a_min_QLineEdit, 0, 1, 1, 1 ) analformLayout.addWidget( QLabel("a max"), 0, 2, 1, 1 ) self.a_max_QLineEdit = QLineEdit() analformLayout.addWidget( self.a_max_QLineEdit, 0, 3, 1, 1 ) analformLayout.addWidget( QLabel("grid cols"), 0, 4, 1, 1 ) self.num_columns_QLineEdit = QLineEdit() analformLayout.addWidget( self.num_columns_QLineEdit, 0, 5, 1, 1 ) analformLayout.addWidget( QLabel("b min"), 1, 0, 1, 1 ) self.b_min_QLineEdit = QLineEdit() analformLayout.addWidget( self.b_min_QLineEdit, 1, 1, 1, 1 ) analformLayout.addWidget( QLabel("b max"), 1, 2, 1, 1 ) self.b_max_QLineEdit = QLineEdit() analformLayout.addWidget( self.b_max_QLineEdit, 1, 3, 1, 1 ) analformLayout.addWidget( QLabel("grid rows"), 1, 4, 1, 1 ) self.num_rows_QLineEdit = QLineEdit() analformLayout.addWidget( self.num_rows_QLineEdit, 1, 5, 1, 1 ) analformLayout.addWidget( QLabel("Formula"), 2, 0, 1, 1 ) self.formula_QLineEdit = QLineEdit() analformLayout.addWidget( self.formula_QLineEdit, 2, 1, 1, 5 ) analform_validate_QPushButton = QPushButton("Calculate matrix") analform_validate_QPushButton.clicked.connect( self.calculate_z_array ) analformLayout.addWidget( analform_validate_QPushButton, 3, 0, 1, 6 ) view_anal_surface_QPushButton = QPushButton( "View as 3D surface" ) view_anal_surface_QPushButton.clicked[bool].connect( self.view_analytical_surface ) view_anal_surface_QPushButton.setEnabled( True ) analformLayout.addWidget( view_anal_surface_QPushButton, 4, 0, 1, 6 ) analformWidget.setLayout( analformLayout ) return analformWidget def setup_geogrparams_tb( self ): geogrparWidget = QWidget() geogrparLayout = QGridLayout( ) geogrparLayout.addWidget( QLabel("lower-left x"), 0, 0, 1, 1 ) self.geog_x_min_QLineEdit = QLineEdit() geogrparLayout.addWidget( self.geog_x_min_QLineEdit, 0, 1, 1, 1 ) geogrparLayout.addWidget( QLabel("lower-left y"), 1, 0, 1, 1 ) self.geog_y_min_QLineEdit = QLineEdit() geogrparLayout.addWidget( self.geog_y_min_QLineEdit, 1, 1, 1, 1 ) geogrparLayout.addWidget( QLabel("map width (x range)"), 2, 0, 1, 1 ) self.grid_width_QLineEdit = QLineEdit() geogrparLayout.addWidget( self.grid_width_QLineEdit, 2, 1, 1, 1 ) geogrparLayout.addWidget( QLabel("map height (y range)"), 3, 0, 1, 1 ) self.grid_height_QLineEdit = QLineEdit() geogrparLayout.addWidget( self.grid_height_QLineEdit, 3, 1, 1, 1 ) geogrparLayout.addWidget( QLabel("grid rot. angle (anti-clockwise)"), 4, 0, 1, 1 ) self.rotation_angle_QLineEdit = QLineEdit() geogrparLayout.addWidget( self.rotation_angle_QLineEdit, 4, 1, 1, 1 ) simulate_surface_pButton = QPushButton( "Create simulated geosurface" ) simulate_surface_pButton.clicked[bool].connect( self.geosurface_XYZ ) simulate_surface_pButton.setEnabled( True ) geogrparLayout.addWidget( simulate_surface_pButton, 5, 0, 1, 2 ) view_anal_surface_QPushButton = QPushButton( "View as 3D surface" ) view_anal_surface_QPushButton.clicked[bool].connect( self.view_geographical_surface ) view_anal_surface_QPushButton.setEnabled( True ) geogrparLayout.addWidget( view_anal_surface_QPushButton, 6, 0, 1, 2 ) geogrparWidget.setLayout( geogrparLayout ) return geogrparWidget def setup_output_tb( self ): outputWidget = QWidget() outputLayout = QGridLayout( ) outputLayout.addWidget( QLabel("Format: "), 0, 0, 1, 1 ) self.save_as_grass_QRadioButton = QRadioButton( "Grass") self.save_as_grass_QRadioButton.setChecked ( True ) outputLayout.addWidget( self.save_as_grass_QRadioButton, 0, 1, 1, 1 ) self.save_as_vtk_QRadioButton = QRadioButton( "VTK") outputLayout.addWidget( self.save_as_vtk_QRadioButton, 0, 2, 1, 1 ) self.save_as_gas_QRadioButton = QRadioButton( "Gas (json)") outputLayout.addWidget( self.save_as_gas_QRadioButton, 0, 3, 1, 1 ) self.save_as_xyz_QRadioButton = QRadioButton( "xyz") outputLayout.addWidget( self.save_as_xyz_QRadioButton, 1, 1, 1, 2 ) self.save_as_esri_generate_QRadioButton = QRadioButton( "3D ESRI generate") outputLayout.addWidget( self.save_as_esri_generate_QRadioButton, 1, 3, 1, 2 ) simulation_output_browse_QPushButton = QPushButton("Save as ...") simulation_output_browse_QPushButton.clicked.connect( self.select_output_file ) outputLayout.addWidget( simulation_output_browse_QPushButton, 2, 0, 1, 1 ) self.output_filename_QLineEdit = QLineEdit() outputLayout.addWidget( self.output_filename_QLineEdit, 2, 1, 1, 4 ) self.save_surface_pButton = QPushButton( "Save surface" ) self.save_surface_pButton.clicked[bool].connect( self.save_surface ) self.save_surface_pButton.setEnabled( True ) outputLayout.addWidget( self.save_surface_pButton, 3, 0, 1, 5 ) outputWidget.setLayout( outputLayout ) return outputWidget def setup_help_tab( self ): helpWidget = QWidget() helpLayout = QVBoxLayout( ) helpLayout.addWidget( self.setup_help() ) helpWidget.setLayout(helpLayout) return helpWidget def setup_help( self ): help_QGroupBox = QGroupBox( self.tr("Help") ) helpLayout = QVBoxLayout( ) self.help_pButton = QPushButton( "Open help in browser" ) self.help_pButton.clicked[bool].connect( self.open_html_help ) self.help_pButton.setEnabled( True ) helpLayout.addWidget( self.help_pButton ) help_QGroupBox.setLayout( helpLayout ) return help_QGroupBox def open_html_help( self ): help_file_path = os.path.join(self.application_dir, self.help_html_subpath) webbrowser.open(help_file_path, new=True) def calculate_z_array(self): try: a_min = float( eval( str( self.a_min_QLineEdit.text() ) ) ) a_max = float( eval( str( self.a_max_QLineEdit.text() ) ) ) grid_cols = int( self.num_columns_QLineEdit.text() ) b_min = float( eval( str( self.b_min_QLineEdit.text() ) ) ) b_max = float( eval( str( self.b_max_QLineEdit.text() ) ) ) grid_rows = int( self.num_rows_QLineEdit.text() ) except: QMessageBox.critical( self, "Surface simulation", "Check input analytical values" ) return if a_min >= a_max or b_min >= b_max: QMessageBox.critical( self, "Surface simulation", "Check a and b values" ) return if grid_cols <= 0 or grid_rows <= 0: QMessageBox.critical( self, "Surface simulation", "Check grid column and row values" ) return formula = str( self.formula_QLineEdit.text() ) if formula == '': QMessageBox.critical( self, "Surface simulation", "Define an analytical formula" ) return a_array = linspace( a_min, a_max, num=grid_cols ) b_array = linspace( b_max, b_min, num=grid_rows ) # note: reversed for conventional j order in arrays try: a_list = [ a for a in a_array for b in b_array ] b_list = [ b for a in a_array for b in b_array ] z_list = [ eval( formula ) for a in a_array for b in b_array ] except: QMessageBox.critical( self, "Surface simulation", "Error in matrix calculation" ) return self.analytical_surface_abz = a_list, b_list, z_list self.array_params = a_min, a_max, b_min, b_max self.grid_dims = grid_rows, grid_cols self.analytical_surface_params = {'a min': a_min, 'a max': a_max, 'b min': b_min, 'b max': b_max, 'grid cols': grid_cols, 'grid rows': grid_rows, 'formula': formula} QMessageBox.information( self, "Surface simulation", "Matrix created" ) def view_analytical_surface( self ): if self.analytical_surface_params is None: QMessageBox.critical( self, "Surface simulation", "Matrix not yet calculated" ) return view_3D_surface( self.analytical_surface_abz ) def view_geographical_surface( self ): if self.geographical_surface_params is None: QMessageBox.critical( self, "Surface simulation", "Geographic surface not yet calculated" ) return view_3D_surface( self.simulated_geosurface ) def calculate_scale_matrix( self, a_range, b_range, grid_height, grid_width ): assert a_range > 0.0 assert b_range > 0.0 assert grid_height > 0.0 assert grid_width > 0.0 sx = grid_width / a_range sy = grid_height / b_range return array( [ ( sx , 0.0 ) , ( 0.0, sy ) ] ) def rotation_matrix( self, grid_rot_angle_degr ): grid_rot_angle_rad = radians( grid_rot_angle_degr ) sin_rot_angle = sin( grid_rot_angle_rad ) cos_rot_angle = cos( grid_rot_angle_rad ) return array( [ ( cos_rot_angle , -sin_rot_angle ) , ( sin_rot_angle, cos_rot_angle ) ] ) def calculate_offset_parameters( self, transformation_matrix, llc_point_matr, llc_point_geog): llc_point_matr_offset = dot( transformation_matrix, llc_point_matr ) return llc_point_geog - llc_point_matr_offset def geosurface_XYZ( self ): try: geog_x_min = float( self.geog_x_min_QLineEdit.text() ) geog_y_min = float( self.geog_y_min_QLineEdit.text() ) grid_rot_angle_degr = float( self.rotation_angle_QLineEdit.text() ) grid_height = float( self.grid_height_QLineEdit.text() ) grid_width = float( self.grid_width_QLineEdit.text() ) except: QMessageBox.critical( self, "Surface simulation", "Check input values" ) return if grid_height <= 0.0 or grid_width <= 0.0: QMessageBox.critical( self, "Surface simulation", "Check height and width values" ) return try: X, Y, Z = self.analytical_surface_abz a_min, a_max, b_min, b_max = self.array_params grid_rows, grid_cols = self.grid_dims # just for checking input completeness except: QMessageBox.critical( self, "Surface simulation", "Matrix not yet calculated" ) return a_range, b_range = a_max-a_min, b_max-b_min scale_matrix = self.calculate_scale_matrix( a_range, b_range, grid_height, grid_width ) rotation_matrix = self.rotation_matrix( grid_rot_angle_degr ) transformation_matrix = dot( rotation_matrix, scale_matrix ) offset_parameters_matrix = self.calculate_offset_parameters( transformation_matrix, array( [a_min, b_min] ), array( [geog_x_min, geog_y_min] ) ) X_tr =[]; Y_tr =[] for x, y in zip( X, Y ): orig_pt = array([x,y]) trasl_pt = dot( transformation_matrix, orig_pt) + offset_parameters_matrix X_tr.append( trasl_pt[0] ) Y_tr.append( trasl_pt[1] ) self.simulated_geosurface = ( X_tr, Y_tr, Z ) self.geographical_surface_params = {'geog x min': geog_x_min, 'geog y min': geog_y_min, 'grid rot angle degr': grid_rot_angle_degr, 'grid height': grid_height, 'grid width': grid_width} QMessageBox.information( self, "Surface simulation", "Completed" ) def select_output_file( self ): if self.save_as_vtk_QRadioButton.isChecked(): short_txt = "*.vtk" long_txt = "vtk (*.vtk *.VTK)" elif self.save_as_grass_QRadioButton.isChecked(): short_txt = "*.txt" long_txt = "txt (*.txt *.TXT)" elif self.save_as_gas_QRadioButton.isChecked(): short_txt = "*.json" long_txt = "json (*.json *.JSON)" elif self.save_as_xyz_QRadioButton.isChecked(): short_txt = "*.xyz" long_txt = "xyz (*.xyz *.XYZ)" elif self.save_as_esri_generate_QRadioButton.isChecked(): short_txt = "*.*" long_txt = "generate file (*.*)" output_filename = QFileDialog.getSaveFileName(self, self.tr( "Save as" ), short_txt, long_txt ) if not output_filename: return self.output_filename_QLineEdit.setText( output_filename ) def save_surface( self ): try: self.simulated_geosurface except AttributeError: QMessageBox.critical( self, "Surface saving", "Geosurface is not yet defined" ) return geodata = self.simulated_geosurface, self.grid_dims if self.save_as_vtk_QRadioButton.isChecked(): save_function = geosurface_export_vtk elif self.save_as_grass_QRadioButton.isChecked(): save_function = geosurface_export_grass elif self.save_as_xyz_QRadioButton.isChecked(): save_function = geosurface_export_xyz elif self.save_as_gas_QRadioButton.isChecked(): save_function = geosurface_save_gas geodata = {'analytical surface': self.analytical_surface_params, 'geographical params': self.geographical_surface_params } elif self.save_as_esri_generate_QRadioButton.isChecked(): save_function = geosurface_export_esri_generate done = save_function( self.output_filename_QLineEdit.text(), geodata ) if done: QMessageBox.information( self, "Surface saving", "Done" ) else: QMessageBox.critical( self, "Surface saving", "Some errors occurred" )
class SettingsPage(QWidget): """ """ ReloadSettings = pyqtSignal() TestSettings = pyqtSignal(dict) def __init__(self, parent): """ """ super(SettingsPage, self).__init__() self.__core = parent self.config = None self.createWidgets() self.createConnections() self.loadCfg() def core(self): """ """ return self.__core def createConnections(self): """ """ self.saveButton.clicked.connect( self.__saveCfg ) self.testButton.clicked.connect( self.testConnection ) def createWidgets(self): """ """ qcCredGroup = QGroupBox(self.tr("HP ALM server credentials")) self.hpCredLogin = QLineEdit() self.hpCredPwd = QLineEdit() self.hpCredPwd.setEchoMode(QLineEdit.Password) qcCredLayout = QGridLayout() qcCredLayout.addWidget( QLabel("Login"), 0, 0) qcCredLayout.addWidget( self.hpCredLogin, 0, 1) qcCredLayout.addWidget( QLabel("Password"), 1, 0) qcCredLayout.addWidget( self.hpCredPwd, 1, 1) qcCredGroup.setLayout(qcCredLayout) qcSvrGroup = QGroupBox(self.tr("HP ALM server informations")) self.hpSvrURL = QLineEdit() self.hpSvrDomain = QLineEdit() self.hpSvrProject = QLineEdit() self.comAPI = QRadioButton("COM") self.comAPI.setChecked(False) self.comAPI.setEnabled(False) self.restAPI = QRadioButton("REST") self.restAPI.setChecked(True) layoutApi = QHBoxLayout() layoutApi.addWidget(self.comAPI) layoutApi.addWidget(self.restAPI) qcSvrLayout = QGridLayout() qcSvrLayout.addWidget( QLabel("URL"), 0, 0) qcSvrLayout.addWidget( self.hpSvrURL, 0, 1) qcSvrLayout.addWidget( QLabel("Domain"), 1, 0) qcSvrLayout.addWidget( self.hpSvrDomain, 1, 1) qcSvrLayout.addWidget( QLabel("Project"), 2, 0) qcSvrLayout.addWidget( self.hpSvrProject, 2, 1) qcSvrLayout.addWidget( QLabel("API"), 3, 0) qcSvrLayout.addLayout( layoutApi, 3, 1) qcSvrGroup.setLayout(qcSvrLayout) # begin export result settings qcExportResultGroup = QGroupBox(self.tr("Export results")) self.ignoreTcCheckBox = QCheckBox(self.tr("Ignore testcase(s)")) self.ignoreUncompleteCheckBox = QCheckBox(self.tr("Ignore uncomplete test(s)")) self.addFoldersTlCheckBox = QCheckBox(self.tr("Create missing folders in test lab")) self.addTestsetCheckBox = QCheckBox(self.tr("Create testset if missing in test lab")) self.addTestinstanceCheckBox = QCheckBox(self.tr("Create test instance in test set")) self.cfgsTestsetTable = DesignPage.ConfigsTableView(self, core=self.core()) qcExportResultLayout = QVBoxLayout() qcExportResultLayout.addWidget( self.ignoreTcCheckBox ) qcExportResultLayout.addWidget( self.ignoreUncompleteCheckBox ) qcExportResultLayout.addWidget( self.addFoldersTlCheckBox ) qcExportResultLayout.addWidget( self.addTestsetCheckBox ) qcExportResultLayout.addWidget( self.addTestinstanceCheckBox ) qcExportResultLayout.addWidget( QLabel("Custom TestSet Fields")) qcExportResultLayout.addWidget( self.cfgsTestsetTable ) qcExportResultLayout.addStretch(1) qcExportResultGroup.setLayout(qcExportResultLayout) # end # begin export test settings qcExportGroup = QGroupBox(self.tr("Export tests")) self.mergeCheckBox = QCheckBox(self.tr("Merge all tests in one")) self.mergeStepsCheckBox = QCheckBox(self.tr("Merge all steps in one")) self.showTcNameCheckBox = QCheckBox(self.tr("Load with original test name")) self.replaceTcCheckBox = QCheckBox(self.tr("Replace testcase with testname")) self.addFoldersTpCheckBox = QCheckBox(self.tr("Create missing folders in test plan")) self.overwriteTcCheckBox = QCheckBox(self.tr("Overwrite testcases in test plan")) self.cfgsTable = DesignPage.ConfigsTableView(self, core=self.core()) qcExportLayout = QGridLayout() qcExportLayout.addWidget( self.mergeCheckBox, 0, 0) qcExportLayout.addWidget( self.mergeStepsCheckBox, 1, 0) qcExportLayout.addWidget( self.showTcNameCheckBox, 2, 0) qcExportLayout.addWidget( self.replaceTcCheckBox, 3, 0) qcExportLayout.addWidget( self.addFoldersTpCheckBox, 4, 0) qcExportLayout.addWidget( self.overwriteTcCheckBox, 5, 0) qcExportLayout.addWidget( QLabel("Custom Test Fields"), 6, 0) qcExportLayout.addWidget( self.cfgsTable, 7, 0) qcExportGroup.setLayout(qcExportLayout) # end layoutCtrls = QHBoxLayout() self.saveButton = QPushButton(self.tr("Save Settings"), self) self.testButton = QPushButton(self.tr("Test Connection"), self) layoutCtrls.addWidget(self.saveButton) layoutCtrls.addWidget(self.testButton) mainLayout = QGridLayout() mainLayout.addWidget(qcSvrGroup, 0, 0) mainLayout.addWidget(qcCredGroup, 0, 1) mainLayout.addWidget(qcExportGroup, 2, 0) mainLayout.addWidget(qcExportResultGroup, 2, 1) mainLayout.addLayout(layoutCtrls, 3, 1) self.setLayout(mainLayout) def loadCfg(self): """ """ with open( "%s/config.json" % (QtHelper.dirExec()) ) as f: CONFIG_RAW = f.read() self.config = json.loads(CONFIG_RAW) self.hpCredLogin.setText(self.config["credentials"]["login"]) self.hpSvrURL.setText(self.config["qc-server"]["url"]) self.hpSvrDomain.setText(self.config["qc-server"]["domain"]) self.hpSvrProject.setText(self.config["qc-server"]["project"]) self.restAPI.setChecked(True) if self.config["export-tests"]["merge-all-tests"]: self.mergeCheckBox.setCheckState(Qt.Checked) if self.config["export-tests"]["merge-all-steps"]: self.mergeStepsCheckBox.setCheckState(Qt.Checked) if self.config["export-tests"]["original-test"]: self.showTcNameCheckBox.setCheckState(Qt.Checked) if self.config["export-tests"]["replace-testcase"]: self.replaceTcCheckBox.setCheckState(Qt.Checked) if self.config["export-tests"]["add-folders"]: self.addFoldersTpCheckBox.setCheckState(Qt.Checked) if self.config["export-tests"]["overwrite-tests"]: self.overwriteTcCheckBox.setCheckState(Qt.Checked) self.cfgsTable.loadTable(data=self.config["custom-test-fields"]) if self.config["export-results"]["ignore-testcase"]: self.ignoreTcCheckBox.setCheckState(Qt.Checked) if self.config["export-results"]["ignore-uncomplete"]: self.ignoreUncompleteCheckBox.setCheckState(Qt.Checked) if self.config["export-results"]["add-folders"]: self.addFoldersTlCheckBox.setCheckState(Qt.Checked) if self.config["export-results"]["add-testset"]: self.addTestsetCheckBox.setCheckState(Qt.Checked) if self.config["export-results"]["add-testinstance"]: self.addTestinstanceCheckBox.setCheckState(Qt.Checked) self.cfgsTestsetTable.loadTable(data=self.config["custom-testset-fields"]) # decrypt password if len(self.config["credentials"]["password"]): decrypted = self.decryptPwd( key=bytes(self.config["credentials"]["login"], "utf8" ), ciphertext=bytes(self.config["credentials"]["password"], "utf8" ) ) self.config["credentials"]["password"] = decrypted self.hpCredPwd.setText(decrypted) def __saveCfg(self): """ """ self.saveCfg(successMsg=True) def saveCfg(self, successMsg=True): """ """ # if successMsg: if not len(self.hpSvrURL.text()): QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set the server url") ) return if not len(self.hpSvrDomain.text()): QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set the server domain") ) return if not len(self.hpSvrProject.text()): QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set the server project") ) return if not len(self.hpCredLogin.text()): QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set a login") ) return if not len(self.hpCredPwd.text()): QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set a password") ) return self.config["credentials"]["login"] = self.hpCredLogin.text() # encrypt password encryptPwd = self.encryptPwd( key=self.hpCredLogin.text(), plaintext=self.hpCredPwd.text() ) self.config["credentials"]["password"] = str(encryptPwd, "utf8") self.config["qc-server"]["url"] = self.hpSvrURL.text() self.config["qc-server"]["domain"] = self.hpSvrDomain.text() self.config["qc-server"]["project"] = self.hpSvrProject.text() self.config["qc-server"]["use-rest"] = False if self.restAPI.isChecked(): self.config["qc-server"]["use-rest"] = True self.config["export-tests"]["merge-all-tests"] = False self.config["export-tests"]["merge-all-steps"] = False self.config["export-tests"]["original-test"] = False self.config["export-tests"]["replace-testcase"] = False self.config["export-tests"]["add-folders"] = False self.config["export-tests"]["overwrite-tests"] = False if self.mergeCheckBox.isChecked(): self.config["export-tests"]["merge-all-tests"] = True if self.mergeStepsCheckBox.isChecked(): self.config["export-tests"]["merge-all-steps"] = True if self.showTcNameCheckBox.isChecked(): self.config["export-tests"]["original-test"] = True if self.replaceTcCheckBox.isChecked(): self.config["export-tests"]["replace-testcase"] = True if self.addFoldersTpCheckBox.isChecked(): self.config["export-tests"]["add-folders"] = True if self.overwriteTcCheckBox.isChecked(): self.config["export-tests"]["overwrite-tests"] = True self.config["custom-test-fields"] = self.cfgsTable.model.getData() self.config["export-results"]["add-folders"] = False self.config["export-results"]["ignore-testcase"] = False self.config["export-results"]["ignore-uncomplete"] = False self.config["export-results"]["add-testset"] = False self.config["export-results"]["add-testinstance"] = False if self.ignoreTcCheckBox.isChecked(): self.config["export-results"]["ignore-testcase"] = True if self.ignoreUncompleteCheckBox.isChecked(): self.config["export-results"]["ignore-uncomplete"] = True if self.addFoldersTlCheckBox.isChecked(): self.config["export-results"]["add-folders"] = True if self.addTestsetCheckBox.isChecked(): self.config["export-results"]["add-testset"] = True if self.addTestinstanceCheckBox.isChecked(): self.config["export-results"]["add-testinstance"] = True self.config["custom-testset-fields"] = self.cfgsTestsetTable.model.getData() with open( "%s/config.json" % (QtHelper.dirExec()), "w" ) as f: f.write( json.dumps(self.config) ) if len(self.config["credentials"]["password"]): self.config["credentials"]["password"] = self.decryptPwd( key=bytes(self.config["credentials"]["login"], "utf8" ), ciphertext=bytes(self.config["credentials"]["password"], "utf8" ) ) self.ReloadSettings.emit() if successMsg: QMessageBox.information(self, self.tr("Save Settings") , self.tr("Settings saved.") ) def cfg(self): """ """ return self.config def encryptPwd(self, key, plaintext): """ """ return base64.b64encode( bytes( plaintext, "utf8" ) ) def decryptPwd(self, key, ciphertext): """ """ return str( base64.b64decode(ciphertext) , "utf8") def testConnection(self): """ """ self.TestSettings.emit(self.config)
class FeeSelectionDialog(ArmoryDialog): ############################################################################# def __init__(self, parent, main, cs_callback, get_csstate): super(FeeSelectionDialog, self).__init__(parent, main) #Button Label self.lblButtonFee = QLabelButton("") #get default values flatFee = self.main.getSettingOrSetDefault("Default_Fee", MIN_TX_FEE) flatFee = coin2str(flatFee, maxZeros=1).strip() fee_byte = str( self.main.getSettingOrSetDefault("Default_FeeByte", MIN_FEE_BYTE)) blocksToConfirm = self.main.getSettingOrSetDefault(\ "Default_FeeByte_BlocksToConfirm", NBLOCKS_TO_CONFIRM) feeStrategy = str(self.main.getSettingOrSetDefault(\ "Default_FeeByte_Strategy", FEEBYTE_CONSERVATIVE)) self.coinSelectionCallback = cs_callback self.getCoinSelectionState = get_csstate self.validAutoFee = True isSmartFee = True try: feeEstimate, isSmartFee, errorMsg = self.getFeeByteFromNode( blocksToConfirm, feeStrategy) except: feeEstimate = "N/A" self.validAutoFee = False defaultCheckState = \ self.main.getSettingOrSetDefault("FeeOption", DEFAULT_FEE_TYPE) #flat free def setFlatFee(): def callbck(): return self.selectType('FlatFee') return callbck def updateLbl(): self.updateCoinSelection() self.radioFlatFee = QRadioButton(self.tr("Flat Fee (BTC)")) self.edtFeeAmt = QLineEdit(flatFee) self.edtFeeAmt.setFont(GETFONT('Fixed')) self.edtFeeAmt.setMinimumWidth(tightSizeNChar(self.edtFeeAmt, 6)[0]) self.edtFeeAmt.setMaximumWidth(tightSizeNChar(self.edtFeeAmt, 12)[0]) self.connect(self.radioFlatFee, SIGNAL('clicked()'), setFlatFee()) self.connect(self.edtFeeAmt, SIGNAL('textChanged(QString)'), updateLbl) frmFlatFee = QFrame() frmFlatFee.setFrameStyle(STYLE_RAISED) layoutFlatFee = QGridLayout() layoutFlatFee.addWidget(self.radioFlatFee, 0, 0, 1, 1) layoutFlatFee.addWidget(self.edtFeeAmt, 0, 1, 1, 1) frmFlatFee.setLayout(layoutFlatFee) #fee/byte def setFeeByte(): def callbck(): return self.selectType('FeeByte') return callbck self.radioFeeByte = QRadioButton(self.tr("Fee/Byte (Satoshi/Byte)")) self.edtFeeByte = QLineEdit(fee_byte) self.edtFeeByte.setFont(GETFONT('Fixed')) self.edtFeeByte.setMinimumWidth(tightSizeNChar(self.edtFeeByte, 6)[0]) self.edtFeeByte.setMaximumWidth(tightSizeNChar(self.edtFeeByte, 12)[0]) self.connect(self.radioFeeByte, SIGNAL('clicked()'), setFeeByte()) self.connect(self.edtFeeByte, SIGNAL('textChanged(QString)'), updateLbl) frmFeeByte = QFrame() frmFeeByte.setFrameStyle(STYLE_RAISED) layoutFeeByte = QGridLayout() layoutFeeByte.addWidget(self.radioFeeByte, 0, 0, 1, 1) layoutFeeByte.addWidget(self.edtFeeByte, 0, 1, 1, 1) frmFeeByte.setLayout(layoutFeeByte) #auto fee/byte if isSmartFee: frmAutoFeeByte = self.setupSmartAutoFeeByteUI(\ feeEstimate, blocksToConfirm, feeStrategy) else: frmAutoFeeByte = self.setupLegacyAutoFeeByteUI(\ feeEstimate, blocksToConfirm) #adjust and close self.btnClose = QPushButton(self.tr('Close')) self.connect(self.btnClose, SIGNAL('clicked()'), self.accept) self.checkBoxAdjust = QCheckBox(self.tr('Adjust fee/byte for privacy')) self.checkBoxAdjust.setChecked(\ self.main.getSettingOrSetDefault('AdjustFee', True)) self.connect(self.checkBoxAdjust, SIGNAL('clicked()'), updateLbl) frmClose = makeHorizFrame(\ [self.checkBoxAdjust, 'Stretch', self.btnClose], STYLE_NONE) #main layout layout = QGridLayout() layout.addWidget(frmAutoFeeByte, 0, 0, 1, 4) layout.addWidget(frmFeeByte, 2, 0, 1, 4) layout.addWidget(frmFlatFee, 4, 0, 1, 4) layout.addWidget(frmClose, 5, 0, 1, 4) self.setLayout(layout) self.setWindowTitle(self.tr('Select Fee Type')) self.selectType(defaultCheckState) self.setFocus() ############################################################################# def setupLegacyAutoFeeByteUI(self, feeEstimate, blocksToConfirm): def setAutoFeeByte(): def callbck(): return self.selectType('Auto') return callbck def updateLbl(): self.updateCoinSelection() def feeByteToStr(feeByte): try: self.feeByte = feeByte return "<u>%.1f</u>" % feeByte except: self.feeByte = -1 if isinstance(feeByte, str): return feeByte else: return "N/A" radioButtonTxt = self.tr("Fee rate from node (sat/Byte): ") if not self.validAutoFee: radioButtonTxt = self.tr("Failed to fetch fee/byte from node") self.radioAutoFeeByte = QRadioButton(radioButtonTxt) self.lblAutoFeeByte = QLabel(feeByteToStr(feeEstimate)) self.lblAutoFeeByte.setFont(GETFONT('Fixed')) self.lblAutoFeeByte.setMinimumWidth( tightSizeNChar(self.lblAutoFeeByte, 6)[0]) self.lblAutoFeeByte.setMaximumWidth( tightSizeNChar(self.lblAutoFeeByte, 12)[0]) self.sliderAutoFeeByte = QSlider(Qt.Horizontal, self) self.sliderAutoFeeByte.setMinimum(2) self.sliderAutoFeeByte.setMaximum(6) self.sliderAutoFeeByte.setValue(blocksToConfirm) self.lblSlider = QLabel() def getSliderLabelTxt(): return self.tr("Blocks to confirm: %1").arg(\ unicode(self.sliderAutoFeeByte.value())) def updateAutoFeeByte(): blocksToConfirm = self.sliderAutoFeeByte.value() try: feeEstimate, version, err = \ self.getFeeByteFromNode(blocksToConfirm, FEEBYTE_CONSERVATIVE) except: feeEstimate = "N/A" self.lblSlider.setText(getSliderLabelTxt()) self.lblAutoFeeByte.setText(feeByteToStr(feeEstimate)) updateLbl() self.lblSlider.setText(getSliderLabelTxt()) self.connect(self.radioAutoFeeByte, SIGNAL('clicked()'), setAutoFeeByte()) self.sliderAutoFeeByte.valueChanged.connect(updateAutoFeeByte) self.sliderAutoFeeByte.setEnabled(False) frmAutoFeeByte = QFrame() frmAutoFeeByte.setFrameStyle(STYLE_RAISED) layoutAutoFeeByte = QGridLayout() layoutAutoFeeByte.addWidget(self.radioAutoFeeByte, 0, 0, 1, 1) layoutAutoFeeByte.addWidget(self.lblAutoFeeByte, 0, 1, 1, 1) layoutAutoFeeByte.addWidget(self.lblSlider, 1, 0, 1, 2) layoutAutoFeeByte.addWidget(self.sliderAutoFeeByte, 2, 0, 1, 2) frmAutoFeeByte.setLayout(layoutAutoFeeByte) if not self.validAutoFee: frmAutoFeeByte.setEnabled(False) return frmAutoFeeByte ############################################################################# def setupSmartAutoFeeByteUI(self, feeEstimate, blocksToConfirm, strat): def setAutoFeeByte(): def callbck(): return self.selectType('Auto') return callbck stratList = [FEEBYTE_CONSERVATIVE, FEEBYTE_ECONOMICAL] def updateLbl(): self.updateCoinSelection() def getStrategyString(): try: cbIndex = self.comboStrat.currentIndex() return stratList[cbIndex] except: return FEEBYTE_CONSERVATIVE def feeByteToStr(feeByte): try: self.feeByte = feeByte return "<u>%.1f</u>" % feeByte except: self.feeByte = -1 if isinstance(feeByte, str): return feeByte else: return "N/A" radioButtonTxt = self.tr("Fee rate from node (sat/Byte): ") if not self.validAutoFee: radioButtonTxt = self.tr("Failed to fetch fee/byte from node") self.radioAutoFeeByte = QRadioButton(radioButtonTxt) self.lblAutoFeeByte = QLabel(feeByteToStr(feeEstimate)) self.lblAutoFeeByte.setFont(GETFONT('Fixed')) self.lblAutoFeeByte.setMinimumWidth( tightSizeNChar(self.lblAutoFeeByte, 6)[0]) self.lblAutoFeeByte.setMaximumWidth( tightSizeNChar(self.lblAutoFeeByte, 12)[0]) self.sliderAutoFeeByte = QSlider(Qt.Horizontal, self) self.sliderAutoFeeByte.setMinimum(2) self.sliderAutoFeeByte.setMaximum(100) self.sliderAutoFeeByte.setValue(blocksToConfirm) self.lblSlider = QLabel() self.lblStrat = QLabel(self.tr("Profile:")) self.ttStart = self.main.createToolTipWidget( self.tr(''' <u>Fee Estimation Profiles:</u><br><br> <b>CONSERVATIVE:</b> Short term estimate. More reactive to current changes in the mempool. Use this estimate if you want a high probability of getting your transaction mined quickly. <br><br> <b>ECONOMICAL:</b> Long term estimate. Ignores short term changes to the mempool. Use this profile if you want low fees and can tolerate swings in the projected confirmation window. <br><br> The estimate profiles may not diverge until your node has gathered enough data from the network to refine its predictions. Refer to the \"estimatesmartfee\" section in the Bitcoin Core 0.15 changelog for more informations. ''')) self.comboStrat = QComboBox() currentIndex = 0 for i in range(len(stratList)): self.comboStrat.addItem(stratList[i]) if stratList[i] == strat: currentIndex = i self.comboStrat.setCurrentIndex(currentIndex) def getSliderLabelTxt(): return self.tr("Blocks to confirm: %1").arg(\ unicode(self.sliderAutoFeeByte.value())) def updateAutoFeeByte(): blocksToConfirm = self.sliderAutoFeeByte.value() strategy = getStrategyString() try: feeEstimate, version, err = \ self.getFeeByteFromNode(blocksToConfirm, strategy) except: feeEstimate = "N/A" self.lblSlider.setText(getSliderLabelTxt()) self.lblAutoFeeByte.setText(feeByteToStr(feeEstimate)) updateLbl() def stratComboChange(): updateAutoFeeByte() self.lblSlider.setText(getSliderLabelTxt()) self.connect(self.radioAutoFeeByte, SIGNAL('clicked()'), setAutoFeeByte()) self.sliderAutoFeeByte.valueChanged.connect(updateAutoFeeByte) self.sliderAutoFeeByte.setEnabled(False) self.connect(self.comboStrat, SIGNAL('currentIndexChanged(int)'), stratComboChange) frmAutoFeeByte = QFrame() frmAutoFeeByte.setFrameStyle(STYLE_RAISED) layoutAutoFeeByte = QGridLayout() layoutAutoFeeByte.addWidget(self.radioAutoFeeByte, 0, 0, 1, 2) layoutAutoFeeByte.addWidget(self.lblAutoFeeByte, 0, 2, 1, 2) layoutAutoFeeByte.addWidget(self.lblSlider, 1, 0, 1, 1) layoutAutoFeeByte.addWidget(self.sliderAutoFeeByte, 2, 0, 1, 4) layoutAutoFeeByte.addWidget(self.lblStrat, 3, 0, 1, 1) layoutAutoFeeByte.addWidget(self.comboStrat, 3, 1, 1, 2) layoutAutoFeeByte.addWidget(self.ttStart, 3, 3, 1, 1) frmAutoFeeByte.setLayout(layoutAutoFeeByte) if not self.validAutoFee: frmAutoFeeByte.setEnabled(False) return frmAutoFeeByte ############################################################################# def getFeeByteFromNode(self, blocksToConfirm, strategy): try: feeEstimateResult = estimateFee(blocksToConfirm, strategy) return feeEstimateResult.val_ * 100000, \ feeEstimateResult.isSmart_, \ feeEstimateResult.error_ except: self.validAutoFee = False return "N/A", False, "" ############################################################################# def selectType(self, strType): self.radioFlatFee.setChecked(False) self.radioFeeByte.setChecked(False) self.radioAutoFeeByte.setChecked(False) self.sliderAutoFeeByte.setEnabled(False) if strType == 'FlatFee': self.radioFlatFee.setChecked(True) elif strType == 'FeeByte': self.radioFeeByte.setChecked(True) elif strType == 'Auto': if not self.validAutoFee: self.radioFeeByte.setChecked(True) else: self.radioAutoFeeByte.setChecked(True) self.sliderAutoFeeByte.setEnabled(True) self.updateCoinSelection() self.updateLabelButton() ############################################################################# def updateCoinSelection(self): try: self.coinSelectionCallback() except: self.updateLabelButton() ############################################################################# def getLabelButton(self): return self.lblButtonFee ############################################################################# def updateLabelButtonText(self, txSize, flatFee, fee_byte): txSize = str(txSize) if txSize != 'N/A': txSize += " B" if flatFee != 'N/A': flatFee = coin2str(flatFee, maxZeros=0).strip() flatFee += " BTC" if not isinstance(fee_byte, str): fee_byte = '%.2f' % fee_byte lblStr = "Size: %s, Fee: %s" % (txSize, flatFee) if fee_byte != 'N/A': lblStr += " (%s sat/B)" % fee_byte self.lblButtonFee.setText(lblStr) ############################################################################# def updateLabelButton(self, reset=False): try: if reset: raise Exception() txSize, flatFee, feeByte = self.getCoinSelectionState() self.updateLabelButtonText(txSize, flatFee, feeByte) except: self.updateLabelButtonText('N/A', 'N/A', 'N/A') ############################################################################# def resetLabel(self): self.updateLabelButton(True) ############################################################################# def getFeeData(self): fee = 0 fee_byte = 0 if self.radioFlatFee.isChecked(): flatFeeText = str(self.edtFeeAmt.text()) fee = str2coin(flatFeeText) elif self.radioFeeByte.isChecked(): fee_byteText = str(self.edtFeeByte.text()) fee_byte = float(fee_byteText) elif self.radioAutoFeeByte.isChecked(): fee_byte = self.feeByte adjust_fee = self.checkBoxAdjust.isChecked() return fee, fee_byte, adjust_fee ############################################################################# def setZeroFee(self): self.edtFeeAmt.setText('0') self.selectType('FlatFee')
class RunsDialog(QtHelper.EnhancedQDialog): """ Runs several dialog """ RefreshRepository = pyqtSignal(str) def __init__(self, dialogName, parent = None, iRepo=None, lRepo=None, rRepo=None): """ Constructor """ QtHelper.EnhancedQDialog.__init__(self, parent) self.name = self.tr("Prepare a group of runs") self.projectReady = False self.iRepo = iRepo self.lRepo = lRepo self.rRepo = rRepo self.createDialog() self.createConnections() def createDialog(self): """ Create qt dialog """ self.setWindowTitle( self.name ) mainLayout = QHBoxLayout() layoutTests = QHBoxLayout() layoutRepoTest = QVBoxLayout() self.prjCombo = QComboBox(self) self.prjCombo.setEnabled(False) self.repoTests = QTreeWidget(self) self.repoTests.setFrameShape(QFrame.NoFrame) if USE_PYQT5: self.repoTests.header().setSectionResizeMode(QHeaderView.Stretch) else: self.repoTests.header().setResizeMode(QHeaderView.Stretch) self.repoTests.setHeaderHidden(True) self.repoTests.setContextMenuPolicy(Qt.CustomContextMenu) self.repoTests.setIndentation(10) layoutRepoTest.addWidget(self.prjCombo) layoutRepoTest.addWidget(self.repoTests) self.testsList = QListWidget(self) layoutTests.addLayout( layoutRepoTest ) layoutTests.addWidget( self.testsList ) mainLayout.addLayout( layoutTests ) buttonLayout = QVBoxLayout() self.okButton = QPushButton(self.tr("Execute All"), self) self.okButton.setEnabled(False) self.cancelButton = QPushButton(self.tr("Cancel"), self) self.upButton = QPushButton(self.tr("UP"), self) self.upButton.setEnabled(False) self.downButton = QPushButton(self.tr("DOWN"), self) self.downButton.setEnabled(False) self.clearButton = QPushButton(self.tr("Remove All"), self) self.delButton = QPushButton(self.tr("Remove"), self) self.delButton.setEnabled(False) self.runSimultaneous = QCheckBox(self.tr("Simultaneous Run")) self.schedImmed = QRadioButton(self.tr("Run Immediately")) self.schedImmed.setChecked(True) self.schedAt = QRadioButton(self.tr("Run At:")) self.schedAtDateTimeEdit = QDateTimeEdit(QDateTime.currentDateTime()) self.schedAtDateTimeEdit.setEnabled(False) buttonLayout.addWidget(self.okButton) buttonLayout.addWidget(self.runSimultaneous) buttonLayout.addWidget(self.schedImmed) buttonLayout.addWidget(self.schedAt) buttonLayout.addWidget(self.schedAtDateTimeEdit) buttonLayout.addWidget( self.upButton ) buttonLayout.addWidget( self.downButton ) buttonLayout.addWidget( self.delButton ) buttonLayout.addWidget( self.clearButton ) buttonLayout.addWidget(self.cancelButton) mainLayout.addLayout(buttonLayout) self.setMinimumHeight(400) self.setMinimumWidth(750) self.setLayout(mainLayout) def initProjects(self, projects=[], defaultProject=1): """ Initialize projects """ # init date and time self.schedAtDateTimeEdit.setDateTime(QDateTime.currentDateTime()) self.projectReady = False self.repoTests.clear() self.prjCombo.clear() self.testsList.clear() self.prjCombo.setEnabled(True) # insert data pname = '' for p in projects: self.prjCombo.addItem ( p['name'] ) if defaultProject == p['project_id']: pname = p['name'] for i in xrange(self.prjCombo.count()): item_text = self.prjCombo.itemText(i) if str(pname) == str(item_text): self.prjCombo.setCurrentIndex(i) self.projectReady = True self.RefreshRepository.emit(pname) def initializeTests(self, listing): """ Initialize tests """ self.repoTests.clear() self.testRoot = self.rRepo.Item(repo = self.iRepo.remote(), parent = self.repoTests, txt = "Root", type = QTreeWidgetItem.UserType+10, isRoot = True ) self.testRoot.setSelected(True) self.createRepository(listing=listing, parent=self.testRoot,fileincluded=True) self.repoTests.sortItems(0, Qt.AscendingOrder) self.hideItems(hideTsx=False, hideTpx=False, hideTcx=True, hideTdx=True, hideTxt=True, hidePy=True, hideTux=False, hidePng=True, hideTgx=False, hideTax=False) def createRepository(self, listing, parent, fileincluded=True): """ Create repository @param listing: @type listing: list @param parent: @type parent: @param fileincluded: @type fileincluded: boolean """ try: for dct in listing: if dct["type"] == "folder": item = self.rRepo.Item(repo = self.iRepo.remote(), parent = parent, txt = dct["name"], propertiesFile=dct ) self.createRepository( dct["content"] , item, fileincluded ) else: if fileincluded: if dct["type"] == "file": pname = self.iRepo.remote().getProjectName(dct["project"]) # {'modification': 1342259500, 'type': 'file', 'name': '__init__.py', 'size': '562 } item = self.rRepo.Item(repo = self.iRepo.remote(), parent = parent, txt = dct["name"] , propertiesFile=dct, type = QTreeWidgetItem.UserType+0, projectId=dct["project"], projectName=pname ) except Exception as e: self.error( "unable to create tree for runs: %s" % e ) def onProjectChanged(self, projectItem): """ Called when the project changed on the combo box """ if self.projectReady: item_text = self.prjCombo.itemText(projectItem) self.RefreshRepository.emit(item_text) def createConnections (self): """ create qt connections * ok * cancel """ self.prjCombo.currentIndexChanged.connect(self.onProjectChanged) self.okButton.clicked.connect( self.acceptClicked ) self.cancelButton.clicked.connect( self.reject ) self.upButton.clicked.connect(self.upTest) self.downButton.clicked.connect(self.downTest) self.clearButton.clicked.connect(self.clearList) self.delButton.clicked.connect(self.delTest) self.testsList.itemClicked.connect(self.onItemSelected) self.testsList.itemSelectionChanged.connect(self.onItemSelectionChanged) self.schedAt.toggled.connect(self.onSchedAtActivated) self.repoTests.itemDoubleClicked.connect( self.onTestDoucleClicked ) def onSchedAtActivated(self, toggled): """ On sched at button activated """ if toggled: self.schedAtDateTimeEdit.setEnabled(True) else: self.schedAtDateTimeEdit.setEnabled(False) def onItemSelectionChanged(self): """ Called on item selection changed """ self.onItemSelected(itm=None) def onItemSelected(self, itm): """ Call on item selected """ selectedItems = self.testsList.selectedItems() if len(selectedItems): self.delButton.setEnabled(True) self.upButton.setEnabled(True) self.downButton.setEnabled(True) else: self.delButton.setEnabled(False) self.upButton.setEnabled(False) self.downButton.setEnabled(False) if not self.testsList.count(): self.okButton.setEnabled(False) def upTest(self): """ Up test """ currentRow = self.testsList.currentRow() currentItem = self.testsList.takeItem(currentRow) self.testsList.insertItem(currentRow - 1, currentItem) def downTest(self): """ Down test """ currentRow = self.testsList.currentRow() currentItem = self.testsList.takeItem(currentRow) self.testsList.insertItem(currentRow + 1, currentItem) def delTest(self): """ Del test """ currentRow = self.testsList.currentRow() currentItem = self.testsList.takeItem(currentRow) def clearList(self): """ Clear test """ self.testsList.clear() self.delButton.setEnabled(False) self.upButton.setEnabled(False) self.downButton.setEnabled(False) self.okButton.setEnabled(False) def iterateTree(self, item, hideTsx, hideTpx, hideTcx, hideTdx, hideTxt, hidePy, hideTux, hidePng, hideTgx, hideTax): """ Iterate tree """ child_count = item.childCount() for i in range(child_count): subitem = item.child(i) subchild_count = subitem.childCount() if subchild_count > 0: self.iterateTree(item=subitem, hideTsx=hideTsx, hideTpx=hideTpx, hideTcx=hideTcx, hideTdx=hideTdx, hideTxt=hideTxt, hidePy=hidePy, hideTux=hideTux, hidePng=hidePng, hideTgx=hideTgx, hideTax=hideTax) else: if hideTux and subitem.getExtension() == self.rRepo.EXTENSION_TUX: subitem.setHidden (True) elif hideTpx and subitem.getExtension() == self.rRepo.EXTENSION_TPX: subitem.setHidden (True) elif hideTgx and subitem.getExtension() == self.rRepo.EXTENSION_TGX: subitem.setHidden (True) elif hideTcx and subitem.getExtension() == self.rRepo.EXTENSION_TCX: subitem.setHidden (True) elif hideTsx and subitem.getExtension() == self.rRepo.EXTENSION_TSX: subitem.setHidden (True) elif hideTdx and subitem.getExtension() == self.rRepo.EXTENSION_TDX: subitem.setHidden (True) elif hideTxt and subitem.getExtension() == self.rRepo.EXTENSION_TXT: subitem.setHidden (True) elif hidePy and subitem.getExtension() == self.rRepo.EXTENSION_PY: subitem.setHidden (True) elif hidePng and subitem.getExtension() == self.rRepo.EXTENSION_PNG: subitem.setHidden (True) elif hideTax and subitem.getExtension() == self.rRepo.EXTENSION_TAx: subitem.setHidden (True) else: subitem.setHidden(False) def hideItems(self, hideTsx=False, hideTpx=False, hideTcx=False, hideTdx=False, hideTxt=False, hidePy=False, hideTux=False, hidePng=False, hideTgx=False, hideTax=False): """ Hide items """ root = self.repoTests.invisibleRootItem() self.iterateTree(item=root, hideTsx=hideTsx, hideTpx=hideTpx, hideTcx=hideTcx, hideTdx=hideTdx, hideTxt=hideTxt, hidePy=hidePy, hideTux=hideTux, hidePng=hidePng, hideTgx=hideTgx, hideTax=hideTax) def onTestDoucleClicked(self, testItem): """ On tests double clicked """ if testItem.type() != QTreeWidgetItem.UserType+0: return self.okButton.setEnabled(True) currentProject = self.prjCombo.currentText() testName = "%s:%s" % (str(currentProject),testItem.getPath(withFileName = True)) testItem = QListWidgetItem(testName ) if testName.endswith(self.rRepo.EXTENSION_TUX): testItem.setIcon(QIcon(":/tux.png")) if testName.endswith(self.rRepo.EXTENSION_TSX): testItem.setIcon(QIcon(":/tsx.png")) if testName.endswith(self.rRepo.EXTENSION_TPX): testItem.setIcon(QIcon(":/tpx.png")) if testName.endswith(self.rRepo.EXTENSION_TGX): testItem.setIcon(QIcon(":/tgx.png")) if testName.endswith(self.rRepo.EXTENSION_TAX): testItem.setIcon(QIcon(":/tax.png")) self.testsList.addItem( testItem ) def acceptClicked (self): """ Called on accept button """ self.accept() def getTests(self): """ Returns all tests in the list """ tests = [] for i in xrange(self.testsList.count()): testItem = self.testsList.item(i) tests.append( str(testItem.text()) ) runSimultaneous = False if self.runSimultaneous.isChecked(): runSimultaneous = True if self.schedImmed.isChecked(): runAt = (0,0,0,0,0,0) return (tests, False, runAt, runSimultaneous) else: pydt = self.schedAtDateTimeEdit.dateTime().toPyDateTime() runAt = (pydt.year, pydt.month, pydt.day, pydt.hour, pydt.minute, pydt.second) return (tests, True, runAt, runSimultaneous)
class UserMngForm(QDialog): def __init__(self, parent=None): QDialog.__init__(self) self.setObjectName(("ui_UserMngForm")) self.resize(200, 200) font = QFont() font.setFamily(("Arial")) font.setBold(False) font.setWeight(50) self.setFont(font) self.vlForm = QVBoxLayout(self) self.vlForm.setObjectName(("vl_UserMngForm")) self.vlForm.setSpacing(9) self.vlForm.setMargin(9) self.setWindowTitle("User Manage Dialog") self.basicFrame = Frame(self) self.vlForm.addWidget(self.basicFrame) self.userContentFrm = Frame(self.basicFrame, "HL") self.basicFrame.Add = self.userContentFrm self.groupbox = GroupBox(self.userContentFrm) self.groupbox.Caption = "Users" self.userContentFrm.Add = self.groupbox self.listBoxUser = ListBox(self.groupbox) self.groupbox.Add = self.listBoxUser self.userDataFrm = Frame(self.userContentFrm) self.userContentFrm.Add = self.userDataFrm self.groupBoxUserinfo = GroupBox(self.userDataFrm) self.groupBoxUserinfo.Caption = "User Information" self.userDataFrm.Add = self.groupBoxUserinfo self.userFullFrm = Frame(self.groupBoxUserinfo, "HL") self.groupBoxUserinfo.Add = self.userFullFrm self.textFirstName = TextBoxPanel(self.userFullFrm) self.textFirstName.Caption = "First Name" self.textFirstName.LabelWidth = 70 self.textFirstName.Width = 120 self.userFullFrm.Add = self.textFirstName self.textLastName = TextBoxPanel(self.userFullFrm) self.textLastName.Caption = "Last Name" self.textLastName.LabelWidth = 70 self.textLastName.Width = 120 self.userFullFrm.Add = self.textLastName self.userEmailPhoneFrm = Frame(self.groupBoxUserinfo, "HL") self.groupBoxUserinfo.Add = self.userEmailPhoneFrm self.textEMail = TextBoxPanel(self.userEmailPhoneFrm) self.textEMail.Caption = "E-Mail" self.textEMail.LabelWidth = 70 self.textEMail.Width = 120 self.userEmailPhoneFrm.Add = self.textEMail self.textPhone = TextBoxPanel(self.userEmailPhoneFrm) self.textPhone.Caption = "Phone" self.textPhone.LabelWidth = 70 self.textPhone.Width = 120 self.userEmailPhoneFrm.Add = self.textPhone self.userAddressCityFrm = Frame(self.groupBoxUserinfo, "HL") self.groupBoxUserinfo.Add = self.userAddressCityFrm self.textAddress = TextBoxPanel(self.userAddressCityFrm) self.textAddress.Caption = "Address" self.textAddress.LabelWidth = 70 self.textAddress.Width = 120 self.userAddressCityFrm.Add = self.textAddress self.textCity = TextBoxPanel(self.userAddressCityFrm) self.textCity.Caption = "City" self.textCity.LabelWidth = 70 self.textCity.Width = 120 self.userAddressCityFrm.Add = self.textCity self.userPostCodeStateFrm = Frame(self.groupBoxUserinfo, "HL") self.groupBoxUserinfo.Add = self.userPostCodeStateFrm self.textPostcode = TextBoxPanel(self.userPostCodeStateFrm) self.textPostcode.Caption = "Post Code" self.textPostcode.LabelWidth = 70 self.textPostcode.Width = 120 self.userPostCodeStateFrm.Add = self.textPostcode self.textState = TextBoxPanel(self.userPostCodeStateFrm) self.textState.Caption = "State" self.textState.LabelWidth = 70 self.textState.Width = 120 self.userPostCodeStateFrm.Add = self.textState self.groupBoxUserRoles = GroupBox(self.userDataFrm, "HL") self.groupBoxUserRoles.Caption = "User Roles" self.userDataFrm.Add = self.groupBoxUserRoles self.radioAdmin = QRadioButton(self.groupBoxUserRoles) self.radioAdmin.setObjectName("radioAdmin") self.radioAdmin.setText("Administrator") self.radioAdmin.setChecked(True) self.groupBoxUserRoles.Add = self.radioAdmin self.radioSuperuser = QRadioButton(self.groupBoxUserRoles) self.radioSuperuser.setObjectName("radioSuperuser") self.radioSuperuser.setText("Super User") self.groupBoxUserRoles.Add = self.radioSuperuser self.radioReadwrite = QRadioButton(self.groupBoxUserRoles) self.radioReadwrite.setObjectName("radioReadwrite") self.radioReadwrite.setText("Read / Write") self.groupBoxUserRoles.Add = self.radioReadwrite self.radioReadonly = QRadioButton(self.groupBoxUserRoles) self.radioReadonly.setObjectName("radioReadonly") self.radioReadonly.setText("Read Only") self.groupBoxUserRoles.Add = self.radioReadonly self.groupBoxUserDisplayInfo = GroupBox(self.userDataFrm, "HL") self.groupBoxUserDisplayInfo.Caption = "User Display Information" self.userDataFrm.Add = self.groupBoxUserDisplayInfo self.textName = TextBoxPanel(self.groupBoxUserDisplayInfo) self.textName.Caption = "Name" self.textName.LabelWidth = 70 self.textName.Width = 120 self.groupBoxUserDisplayInfo.Add = self.textName self.textPassword = TextBoxPanel(self.groupBoxUserDisplayInfo) self.textPassword.Caption = "Password" self.textPassword.LabelWidth = 70 self.textPassword.Width = 120 self.textPassword.EchoMode = "Password" self.groupBoxUserDisplayInfo.Add = self.textPassword self.btnFrame = Frame(self.basicFrame, "HL") self.basicFrame.Add = self.btnFrame self.buttonAddUser = QPushButton(self.btnFrame) self.buttonAddUser.setObjectName("buttonAddUser") self.buttonAddUser.setText("Add") self.btnFrame.Add = self.buttonAddUser self.buttonModifyUser = QPushButton(self.btnFrame) self.buttonModifyUser.setObjectName("buttonModifyUser") self.buttonModifyUser.setText("Modify") self.btnFrame.Add = self.buttonModifyUser self.buttonDeleteUser = QPushButton(self.btnFrame) self.buttonDeleteUser.setObjectName("buttonDeleteUser") self.buttonDeleteUser.setText("Delete") self.btnFrame.Add = self.buttonDeleteUser self.buttonSaveUser = QPushButton(self.btnFrame) self.buttonSaveUser.setObjectName("buttonSaveUser") self.buttonSaveUser.setText("Save") self.buttonSaveUser.setVisible(False) self.btnFrame.Add = self.buttonSaveUser self.buttonCloseUser = QPushButton(self.btnFrame) self.buttonCloseUser.setObjectName("buttonCloseProject") self.buttonCloseUser.setText("Close") self.btnFrame.Add = self.buttonCloseUser self.connect(self.listBoxUser, SIGNAL("Event_0"), self.listBoxUser_SelectedIndexChanged) self.buttonAddUser.clicked.connect(self.buttonAddUser_Click) self.buttonModifyUser.clicked.connect(self.buttonModifyUser_Click) self.buttonDeleteUser.clicked.connect(self.buttonDeleteUser_Click) self.buttonSaveUser.clicked.connect(self.buttonSaveUser_Click) self.buttonCloseUser.clicked.connect(self.buttonCloseUser_Click) for ui in AirCraftOperation.g_userList.ListUserInfo: self.listBoxUser.Add(ui.Name) def listBoxUser_SelectedIndexChanged(self): try: if (self.listBoxUser.SelectedIndex < 0): return selectedName = self.listBoxUser.Items[ self.listBoxUser.SelectedIndex] ui = AirCraftOperation.g_userList.FindUser(selectedName) if (ui.FName != None): self.textFirstName.Text = ui.FName else: self.textFirstName.Text = "" if (ui.LName != None): self.textLastName.Text = ui.LName else: self.textLastName.Text = "" if (ui.EMail != None): self.textEMail.Text = ui.EMail else: self.textEMail.Text = "" if (ui.Phone != None): self.textPhone.Text = ui.Phone else: self.textPhone.Text = "" if (ui.Address != None): self.textAddress.Text = ui.Address else: self.textAddress.Text = "" if (ui.PCode != None): self.textPostcode.Text = ui.PCode else: self.textPostcode.Text = "" if (ui.City != None): self.textCity.Text = ui.City else: self.textCity.Text = "" if (ui.State != None): self.textState.Text = ui.State else: self.textState.Text = "" if (ui.Name != None): self.textName.Text = ui.Name else: self.textName.Text = "" if (ui.Password != None): self.textPassword.Text = ui.Password else: self.textPassword.Text = "" if ui.Right == enumUserRight.ur_Admin: self.radioAdmin.setChecked(True) elif ui.Right == enumUserRight.ur_SuperUser: self.radioSuperuser.setChecked(True) elif ui.Right == enumUserRight.ur_ReadWrite: self.radioReadwrite.setChecked(True) elif ui.Right == enumUserRight.ur_ReadOnly: self.radioReadonly.setChecked(True) except: pass def buttonAddUser_Click(self): if (not self.CheckInputValues()): return newUser = self.SetUserInfo() if (AirCraftOperation.g_userList.AddUser(newUser)): self.listBoxUser.Add(newUser.Name) self.buttonSaveUser.Enabled = True def buttonModifyUser_Click(self): try: if (self.listBoxUser.SelectedIndex < 0): QMessageBox.warning( self, "Warning", "Please select an user in users list box!") if (not self.CheckInputValues()): return newUser = self.SetUserInfo() oldUser = AirCraftOperation.g_userList.FindUser( self.listBoxUser.Items[self.listBoxUser.SelectedIndex]) if (oldUser != None): AirCraftOperation.g_userList.DeleteUser(oldUser) AirCraftOperation.g_userList.AddUser(newUser) self.listBoxUser.Clear() for ui in AirCraftOperation.g_userList.ListUserInfo: self.listBoxUser.Add(ui.Name) self.buttonSaveUser.setEnabled(True) except: pass def buttonDeleteUser_Click(self): if (self.listBoxUser.SelectedIndex > -1): res = QMessageBox.question( self, "Question", "Do you want to delete this user information?", QMessageBox.Yes | QMessageBox.No) if (res == QMessageBox.No): return userName = self.listBoxUser.Items[self.listBoxUser.SelectedIndex] AirCraftOperation.g_userList.DeleteUser(userName) self.listBoxUser.Clear() for ui in AirCraftOperation.g_userList.ListUserInfo: self.listBoxUser.Add(ui.Name) AirCraftOperation.g_userList.WriteUserInfoFile() # self.buttonSaveUser.setEnabled(True) self.listBoxUser.SelectedIndex = self.listBoxUser.SelectedIndex - 1 if ( self.listBoxUser.SelectedIndex > 0) else 0 self.listBoxUser_SelectedIndexChanged() def buttonSaveUser_Click(self): if (self.buttonSaveUser.isEnabled() == True): res = QMessageBox.question(self, "Question", "Save changes to user information?", QMessageBox.Yes | QMessageBox.No) if (res == QMessageBox.Yes): AirCraftOperation.g_userList.WriteUserInfoFile() self.buttonSaveUser.setEnabled(False) def buttonCloseUser_Click(self): if (self.buttonSaveUser.isEnabled() == True): res = QMessageBox.question(self, "Question", "Save changes to user information?", QMessageBox.Yes | QMessageBox.No) if (res == QMessageBox.Yes): AirCraftOperation.g_userList.WriteUserInfoFile() self.buttonSaveUser.setEnabled(False) self.accept() def CheckInputValues(self): try: if (self.textFirstName.Text == ""): QMessageBox.warning( self, "Warning", "First name is required! Please input first name.") return False if (self.textLastName.Text == ""): QMessageBox.warning( self, "Warning", "Last name is required! Please input last name.") return False if (self.textName.Text == ""): QMessageBox.warning( self, "Warning", "Name is required! Please input display name.") return False return True except: return False def SetUserInfo(self): ui = MYUSERINFO() try: if (self.radioAdmin.isChecked()): ui.Right = enumUserRight.ur_Admin elif (self.radioSuperuser.isChecked()): ui.Right = enumUserRight.ur_SuperUser elif (self.radioReadwrite.isChecked()): ui.Right = enumUserRight.ur_ReadWrite elif (self.radioReadonly.isChecked()): ui.Right = enumUserRight.ur_ReadOnly if (self.textFirstName.Text != None): ui.FName = self.textFirstName.Text if (self.textFirstName.Text != None): ui.LName = self.textLastName.Text if (self.textFirstName.Text != None): ui.EMail = self.textEMail.Text if (self.textFirstName.Text != None): ui.Phone = self.textPhone.Text if (self.textFirstName.Text != None): ui.Address = self.textAddress.Text if (self.textFirstName.Text != None): ui.PCode = self.textPostcode.Text if (self.textFirstName.Text != None): ui.City = self.textCity.Text if (self.textFirstName.Text != None): ui.State = self.textState.Text if (self.textFirstName.Text != None): ui.Name = self.textName.Text if (self.textFirstName.Text != None): ui.Password = self.textPassword.Text return ui except: return None
class EditContact(QWidget): def __init__(self, db, mainWindow, username, contact): QWidget.__init__(self) self.contact = contact self.username = username self.mainWindow = mainWindow self.db = db self.resize(400, 300) self.setWindowTitle('Edit Contact') self.addressListLabel = QLabel('Addresses') addresses = self.contact.getAddresses(self.db) addresses = [("%s: %s" % (address['strAddressType'], address['strAddress']), address['strAddress']) for address in addresses] self.addresses = AutoCompleteListBox(self, addresses) self.addresses.getLineEdit().hide() saveButton = QPushButton('Save') cancelButton = QPushButton('Cancel') self.personRadio = QRadioButton('Contact is a person', self) self.companyRadio = QRadioButton('Contact is an organization', self) self.personWidget = self._getPersonWidget() self.companyWidget = self._getCompanyWidget() self.personRadio.toggled.connect(self.switchToPerson) self.companyRadio.toggled.connect(self.switchToCompany) grid = QGridLayout() grid.setSpacing(10) grid.addWidget(self.addressListLabel, 1, 0) grid.addWidget(self.addresses.getLineEdit(), 0, 1, 1, 2) grid.addWidget(self.addresses.getListBox(), 1, 1, 1, 2) grid.addWidget(self.personRadio, 2, 1, 1, 2) grid.addWidget(self.companyRadio, 3, 1, 1, 2) grid.addWidget(self.personWidget, 4, 0, 1, 3) grid.addWidget(self.companyWidget, 5, 0, 1, 3) grid.addWidget(saveButton, 7, 1) grid.addWidget(cancelButton, 7, 2) self.setLayout(grid) if contact.isPerson == True: self.personRadio.setChecked(True) self.switchToPerson() elif contact.isPerson == False: self.companyRadio.setChecked(True) self.switchToCompany() else: self.personWidget.hide() self.companyWidget.hide() self.connect(cancelButton, SIGNAL('clicked()'), SLOT('close()')) self.connect(saveButton, SIGNAL('clicked()'), self.save) def _getPersonWidget(self): widget = QWidget() grid = QGridLayout() grid.setSpacing(10) self.forenameLabel = QLabel('Forename') self.surnameLabel = QLabel('Surname') self.forenameLineEdit = QLineEdit() self.surnameLineEdit = QLineEdit() if self.contact.forename: self.forenameLineEdit.setText(self.contact.forename) if self.contact.surname: self.surnameLineEdit.setText(self.contact.surname) grid.addWidget(self.forenameLabel, 0, 0) grid.addWidget(self.surnameLabel, 1, 0) grid.addWidget(self.forenameLineEdit, 0, 1) grid.addWidget(self.surnameLineEdit, 1, 1) widget.setLayout(grid) return widget def _getCompanyWidget(self): widget = QWidget() grid = QGridLayout() grid.setSpacing(10) self.companyNameLabel = QLabel('Company Name') self.companyNameLineEdit = QLineEdit() if self.contact.companyName: self.companyNameLineEdit.setText(self.contact.companyName) grid.addWidget(self.companyNameLabel, 0, 0) grid.addWidget(self.companyNameLineEdit, 0, 1) widget.setLayout(grid) return widget def switchToPerson(self): self.companyWidget.hide() self.personWidget.show() def switchToCompany(self): self.personWidget.hide() self.companyWidget.show() def save(self): self.contact.forename = unicode(self.forenameLineEdit.text()) self.contact.surname = unicode(self.surnameLineEdit.text()) self.contact.companyName = unicode(self.companyNameLineEdit.text()) self.contact.isPerson = self.personRadio.isChecked() self.contact.update(self.db) self.mainWindow.refreshLists() self.close()
class TaskGeneratorDialog(QDialog): def __init__(self, nbprocessors): QDialog.__init__(self) self.layout = QVBoxLayout(self) self.taskset = None # Utilizations: vbox_utilizations = QVBoxLayout() group = QGroupBox("Task Utilizations:") hbox = QHBoxLayout() hbox.addWidget(QLabel("Generator:", self)) self.comboGenerator = QComboBox() self.comboGenerator.addItem("RandFixedSum") self.comboGenerator.addItem("UUniFast-Discard") self.comboGenerator.addItem("Kato's method") self.comboGenerator.currentIndexChanged.connect(self.generator_changed) hbox.addWidget(self.comboGenerator) vbox_utilizations.addLayout(hbox) # Load slider + spinner: hbox_load = QHBoxLayout() sld = _DoubleSlider(QtCore.Qt.Horizontal, self) sld.setMinimum(0) sld.setMaximum(32) self.spin_load = QDoubleSpinBox(self) self.spin_load.setMinimum(0) self.spin_load.setMaximum(32) self.spin_load.setSingleStep(0.1) hbox_load.addWidget(QLabel("Total utilization: ", self)) hbox_load.addWidget(sld) hbox_load.addWidget(self.spin_load) sld.doubleValueChanged.connect(self.spin_load.setValue) self.spin_load.valueChanged.connect(sld.setValue) self.spin_load.setValue(nbprocessors / 2.) vbox_utilizations.addLayout(hbox_load) # Number of periodic tasks: self.hbox_tasks = QHBoxLayout() self.spin_tasks = QSpinBox(self) self.spin_tasks.setMinimum(0) self.spin_tasks.setMaximum(999) # That's arbitrary. self.hbox_tasks.addWidget(QLabel("Number of periodic tasks: ", self)) self.hbox_tasks.addStretch(1) self.hbox_tasks.addWidget(self.spin_tasks) vbox_utilizations.addLayout(self.hbox_tasks) # Number of sporadic tasks: self.hbox_sporadic_tasks = QHBoxLayout() self.spin_sporadic_tasks = QSpinBox(self) self.spin_sporadic_tasks.setMinimum(0) self.spin_sporadic_tasks.setMaximum(999) # That's arbitrary. self.hbox_sporadic_tasks.addWidget( QLabel("Number of sporadic tasks: ", self)) self.hbox_sporadic_tasks.addStretch(1) self.hbox_sporadic_tasks.addWidget(self.spin_sporadic_tasks) vbox_utilizations.addLayout(self.hbox_sporadic_tasks) # Min / Max utilizations self.hbox_utilizations = QHBoxLayout() self.hbox_utilizations.addWidget(QLabel("Min/Max utilizations: ", self)) self.interval_utilization = IntervalSpinner(self, min_=0, max_=1, step=.01, round_option=False) self.hbox_utilizations.addWidget(self.interval_utilization) vbox_utilizations.addLayout(self.hbox_utilizations) group.setLayout(vbox_utilizations) self.layout.addWidget(group) # Periods: vbox_periods = QVBoxLayout() group = QGroupBox("Task Periods:") # Log uniform self.lunif = QRadioButton("log-uniform distribution between:") vbox_periods.addWidget(self.lunif) self.lunif.setChecked(True) self.lunif_interval = IntervalSpinner(self) self.lunif_interval.setEnabled(self.lunif.isChecked()) self.lunif.toggled.connect(self.lunif_interval.setEnabled) vbox_periods.addWidget(self.lunif_interval) # Uniform self.unif = QRadioButton("uniform distribution between:") vbox_periods.addWidget(self.unif) self.unif_interval = IntervalSpinner(self) self.unif_interval.setEnabled(self.unif.isChecked()) self.unif.toggled.connect(self.unif_interval.setEnabled) vbox_periods.addWidget(self.unif_interval) # Discrete discrete = QRadioButton("chosen among these (space separated) values:") vbox_periods.addWidget(discrete) self.periods = QLineEdit(self) self.periods.setValidator( QRegExpValidator(QRegExp("^\\d*(\.\\d*)?( \\d*(\.\\d*)?)*$"))) vbox_periods.addWidget(self.periods) self.periods.setEnabled(discrete.isChecked()) discrete.toggled.connect(self.periods.setEnabled) vbox_periods.addStretch(1) group.setLayout(vbox_periods) self.layout.addWidget(group) buttonBox = QDialogButtonBox() cancel = buttonBox.addButton(QDialogButtonBox.Cancel) generate = buttonBox.addButton("Generate", QDialogButtonBox.AcceptRole) cancel.clicked.connect(self.reject) generate.clicked.connect(self.generate) self.layout.addWidget(buttonBox) self.show_randfixedsum_options() def generator_changed(self, value): if value == 2: self.show_kato_options() else: self.show_randfixedsum_options() def show_randfixedsum_options(self): for i in range(self.hbox_utilizations.count()): self.hbox_utilizations.itemAt(i).widget().hide() for i in range(self.hbox_tasks.count()): if self.hbox_tasks.itemAt(i).widget(): self.hbox_tasks.itemAt(i).widget().show() for i in range(self.hbox_sporadic_tasks.count()): if self.hbox_sporadic_tasks.itemAt(i).widget(): self.hbox_sporadic_tasks.itemAt(i).widget().show() def show_kato_options(self): for i in range(self.hbox_utilizations.count()): if self.hbox_utilizations.itemAt(i).widget(): self.hbox_utilizations.itemAt(i).widget().show() for i in range(self.hbox_tasks.count()): if self.hbox_tasks.itemAt(i).widget(): self.hbox_tasks.itemAt(i).widget().hide() for i in range(self.hbox_sporadic_tasks.count()): if self.hbox_sporadic_tasks.itemAt(i).widget(): self.hbox_sporadic_tasks.itemAt(i).widget().hide() def get_min_utilization(self): return self.interval_utilization.getMin() def get_max_utilization(self): return self.interval_utilization.getMax() def generate(self): if self.comboGenerator.currentIndex() == 0: n = self.get_nb_tasks() u = StaffordRandFixedSum(n, self.get_utilization(), 1) elif self.comboGenerator.currentIndex() == 1: n = self.get_nb_tasks() u = UUniFastDiscard(n, self.get_utilization(), 1) else: u = gen_kato_utilizations(1, self.get_min_utilization(), self.get_max_utilization(), self.get_utilization()) n = len(u[0]) p_types = self.get_periods() if p_types[0] == "unif": p = gen_periods_uniform(n, 1, p_types[1], p_types[2], p_types[3]) elif p_types[0] == "lunif": p = gen_periods_loguniform(n, 1, p_types[1], p_types[2], p_types[3]) else: p = gen_periods_discrete(n, 1, p_types[1]) if u and p: self.taskset = gen_tasksets(u, p)[0] self.accept() elif not u: QMessageBox.warning( self, "Generation failed", "Please check the utilization and the number of tasks.") else: QMessageBox.warning(self, "Generation failed", "Pleache check the periods.") def get_nb_tasks(self): return self.spin_tasks.value() + self.spin_sporadic_tasks.value() def get_nb_periodic_tasks(self): return self.spin_tasks.value() def get_nb_sporadic_tasks(self): return self.spin_sporadic_tasks.value() def get_utilization(self): return self.spin_load.value() def get_periods(self): if self.unif.isChecked(): return ("unif", self.unif_interval.getMin(), self.unif_interval.getMax(), self.unif_interval.getRound()) elif self.lunif.isChecked(): return ("lunif", self.lunif_interval.getMin(), self.lunif_interval.getMax(), self.lunif_interval.getRound()) else: return ("discrete", map(float, str(self.periods.text()).split()))
class ProxyConfigPage(QWizardPage): def __init__(self, parent=None,key=None): super(ProxyConfigPage, self).__init__(parent) self.parent = parent self.key = key try: (pxytype,pxyhost,pxyport,pxyauth,pxyusr,pxypwd) = self.parent.mfr.readProxyConfig() except: (pxytype,pxyhost,pxyport,pxyauth,pxyusr,pxypwd) = (None,)*6 #if we use enums for pxy types #pxytype = [a[0] for a in WFSDataStore.PROXY_TYPE.reverse.items() if a[1]==pxytype][0] self.setTitle(self.parent.plist.get(self.key)[1]+' Configuration Options') self.setSubTitle('Enter the hostname/ip-address, port number and authentication details of your HTTP proxy') QToolTip.setFont(QFont('SansSerif', 10)) #labels directlabel = QLabel('Direct Connection') systemlabel = QLabel('Use System Proxy settings') proxylabel = QLabel('Configure Proxy') hostLabel = QLabel('Proxy Host') portLabel = QLabel('Proxy Port') authLabel = QLabel('Authentication') usrLabel = QLabel('Username') pwdLabel = QLabel('Password') #radio buttons self.directradio = QRadioButton() self.systemradio = QRadioButton() self.usrdefradio = QRadioButton() #edit boxes self.hostEdit = QLineEdit(pxyhost) self.hostEdit.setToolTip('Enter Proxy host (IP Address or hostname)') self.portEdit = QLineEdit(pxyport) self.portEdit.setToolTip('Enter Proxy port') #dropdown self.authSelect = QComboBox() self.authSelect.addItem('') self.authSelect.setToolTip('Select appropriate proxy authentication mechanism') self.authSelect.addItems(WFSDataStore.PROXY_AUTH) self.authSelect.setCurrentIndex(0 if LU.assessNone(pxyauth) is None else WFSDataStore.PROXY_AUTH.index(pxyauth)) self.usrEdit = QLineEdit(pxyusr) self.usrEdit.setToolTip('Enter your proxy username (if required)') self.pwdEdit = QLineEdit('')#pxypwd self.usrEdit.setToolTip('Enter your proxy password (if required)') self.pwdEdit.setEchoMode(QLineEdit.Password) self.portEdit.setValidator(QRegExpValidator(QRegExp("\d{1,5}"), self)) self.registerField(self.key+"host",self.hostEdit) self.registerField(self.key+"port",self.portEdit) self.registerField(self.key+"auth",self.authSelect,"currentIndex") self.registerField(self.key+"usr",self.usrEdit) self.registerField(self.key+"pwd",self.pwdEdit) self.registerField(self.key+WFSDataStore.PROXY_TYPE[0],self.directradio) self.registerField(self.key+WFSDataStore.PROXY_TYPE[1],self.systemradio) self.registerField(self.key+WFSDataStore.PROXY_TYPE[2],self.usrdefradio) #grid grid1 = QGridLayout() grid1.setSpacing(10) grid2 = QGridLayout() grid2.setSpacing(10) #layout hbox = QHBoxLayout() grid1.addWidget(self.directradio,1,0) grid1.addWidget(directlabel,1,1) grid1.addWidget(self.systemradio,2,0) grid1.addWidget(systemlabel,2,1) grid1.addWidget(self.usrdefradio,3,0) grid1.addWidget(proxylabel,3,1) hbox.addLayout(grid1) hbox.addStretch(1) self.gbox = QGroupBox('Proxy Configuration') #dsu subs = False if pxytype == WFSDataStore.PROXY_TYPE[1]: #system self.systemradio.setChecked(True) elif pxytype == WFSDataStore.PROXY_TYPE[2]: #user_defined self.usrdefradio.setChecked(True) subs = True else: #direct (default) self.directradio.setChecked(True) self.setUserDefined(subs) self.directradio.clicked.connect(self.disableUserDefined) self.systemradio.clicked.connect(self.disableUserDefined) self.usrdefradio.clicked.connect(self.enableUserDefined) grid2.addWidget(hostLabel, 1, 0) grid2.addWidget(self.hostEdit, 1, 2) grid2.addWidget(portLabel, 2, 0) grid2.addWidget(self.portEdit, 2, 2) grid2.addWidget(authLabel, 3, 0) grid2.addWidget(self.authSelect, 3, 2) grid2.addWidget(usrLabel, 4, 0) grid2.addWidget(self.usrEdit, 4, 2) grid2.addWidget(pwdLabel, 5, 0) grid2.addWidget(self.pwdEdit, 5, 2) self.gbox.setLayout(grid2) #layout vbox = QVBoxLayout() vbox.addLayout(hbox) vbox.insertWidget(1,self.gbox) self.setLayout(vbox) def selectConfFile(self): self.fileEdit.setText(QFileDialog.getOpenFileName()) def nextId(self): #now go to selected dest configger #return int(self.field("ldsdest").toString()) if self.testConnection(): return self.field("ldsdest") return self.parent.plist.get('proxy')[0] def disableUserDefined(self): self.setUserDefined(False) def enableUserDefined(self): self.setUserDefined(True) def setUserDefined(self,udval): self.gbox.setEnabled(udval) self.hostEdit.setEnabled(udval) self.portEdit.setEnabled(udval) self.authSelect.setEnabled(udval) self.usrEdit.setEnabled(udval) self.pwdEdit.setEnabled(udval) def testConnection(self): if not self.usrdefradio.isChecked(): return True if not any(f for f in (self.hostEdit.isModified(),self.portEdit.isModified(), self.usrEdit.isModified(),self.pwdEdit.isModified())): return False proxydata = {'type':'USER','host':str(self.hostEdit.text()),'port':str(self.portEdit.text()), 'auth':str(WFSDataStore.PROXY_AUTH[self.authSelect.currentIndex()-1]), 'user':str(self.usrEdit.text()),'pass':str(self.pwdEdit.text())} wfsdata = {'key':'00112233445566778899aabbccddeeff'}#key not necessary but config tester checks format lds = LDSDataStore(None,{'Proxy':proxydata,'WFS':wfsdata}) lds.applyConfigOptions() try: #use website likely to be up (that isn't LDS so error is distinct) lds.initDS('http://www.google.com/',False) except DatasourceConnectException as dce: QMessageBox.warning(self, 'Connection Error', 'Cannot connect to network using proxy parameters provided {}'.format(dce), 'OK') return False except DatasourceOpenException as dse: QMessageBox.info(self, 'Connection Warning', 'Connection parameters confirmed, Datasource initialisation untested. Continuing.\n{}'.format(dse), 'OK') return True except RuntimeError as rte: QMessageBox.warning(self, 'RuntimeError', 'Error connecting to network: '+str(rte), 'OK') return False return True
def __init__(self, nbprocessors): QDialog.__init__(self) self.layout = QVBoxLayout(self) self.taskset = None # Utilizations: vbox_utilizations = QVBoxLayout() group = QGroupBox("Task Utilizations:") hbox = QHBoxLayout() hbox.addWidget(QLabel("Generator:", self)) self.comboGenerator = QComboBox() self.comboGenerator.addItem("RandFixedSum") self.comboGenerator.addItem("UUniFast-Discard") self.comboGenerator.addItem("Kato's method") self.comboGenerator.currentIndexChanged.connect(self.generator_changed) hbox.addWidget(self.comboGenerator) vbox_utilizations.addLayout(hbox) # Load slider + spinner: hbox_load = QHBoxLayout() sld = _DoubleSlider(QtCore.Qt.Horizontal, self) sld.setMinimum(0) sld.setMaximum(32) self.spin_load = QDoubleSpinBox(self) self.spin_load.setMinimum(0) self.spin_load.setMaximum(32) self.spin_load.setSingleStep(0.1) hbox_load.addWidget(QLabel("Total utilization: ", self)) hbox_load.addWidget(sld) hbox_load.addWidget(self.spin_load) sld.doubleValueChanged.connect(self.spin_load.setValue) self.spin_load.valueChanged.connect(sld.setValue) self.spin_load.setValue(nbprocessors / 2.) vbox_utilizations.addLayout(hbox_load) # Number of periodic tasks: self.hbox_tasks = QHBoxLayout() self.spin_tasks = QSpinBox(self) self.spin_tasks.setMinimum(0) self.spin_tasks.setMaximum(999) # That's arbitrary. self.hbox_tasks.addWidget(QLabel("Number of periodic tasks: ", self)) self.hbox_tasks.addStretch(1) self.hbox_tasks.addWidget(self.spin_tasks) vbox_utilizations.addLayout(self.hbox_tasks) # Number of sporadic tasks: self.hbox_sporadic_tasks = QHBoxLayout() self.spin_sporadic_tasks = QSpinBox(self) self.spin_sporadic_tasks.setMinimum(0) self.spin_sporadic_tasks.setMaximum(999) # That's arbitrary. self.hbox_sporadic_tasks.addWidget( QLabel("Number of sporadic tasks: ", self)) self.hbox_sporadic_tasks.addStretch(1) self.hbox_sporadic_tasks.addWidget(self.spin_sporadic_tasks) vbox_utilizations.addLayout(self.hbox_sporadic_tasks) # Min / Max utilizations self.hbox_utilizations = QHBoxLayout() self.hbox_utilizations.addWidget(QLabel("Min/Max utilizations: ", self)) self.interval_utilization = IntervalSpinner(self, min_=0, max_=1, step=.01, round_option=False) self.hbox_utilizations.addWidget(self.interval_utilization) vbox_utilizations.addLayout(self.hbox_utilizations) group.setLayout(vbox_utilizations) self.layout.addWidget(group) # Periods: vbox_periods = QVBoxLayout() group = QGroupBox("Task Periods:") # Log uniform self.lunif = QRadioButton("log-uniform distribution between:") vbox_periods.addWidget(self.lunif) self.lunif.setChecked(True) self.lunif_interval = IntervalSpinner(self) self.lunif_interval.setEnabled(self.lunif.isChecked()) self.lunif.toggled.connect(self.lunif_interval.setEnabled) vbox_periods.addWidget(self.lunif_interval) # Uniform self.unif = QRadioButton("uniform distribution between:") vbox_periods.addWidget(self.unif) self.unif_interval = IntervalSpinner(self) self.unif_interval.setEnabled(self.unif.isChecked()) self.unif.toggled.connect(self.unif_interval.setEnabled) vbox_periods.addWidget(self.unif_interval) # Discrete discrete = QRadioButton("chosen among these (space separated) values:") vbox_periods.addWidget(discrete) self.periods = QLineEdit(self) self.periods.setValidator( QRegExpValidator(QRegExp("^\\d*(\.\\d*)?( \\d*(\.\\d*)?)*$"))) vbox_periods.addWidget(self.periods) self.periods.setEnabled(discrete.isChecked()) discrete.toggled.connect(self.periods.setEnabled) vbox_periods.addStretch(1) group.setLayout(vbox_periods) self.layout.addWidget(group) buttonBox = QDialogButtonBox() cancel = buttonBox.addButton(QDialogButtonBox.Cancel) generate = buttonBox.addButton("Generate", QDialogButtonBox.AcceptRole) cancel.clicked.connect(self.reject) generate.clicked.connect(self.generate) self.layout.addWidget(buttonBox) self.show_randfixedsum_options()
class OutputAnalyserDialog(QDialog): def __init__(self, iface, parent, params): QDialog.__init__(self, parent) self.iface = iface self.parent = parent self.params = params self.output_reader = None self.tool = None self.element_ids_nodes = None self.element_ids_links = None self.nodes_lay = None self.links_lay = None self.setWindowTitle(Parameters.plug_in_name) # Selection changed listeners self.params.junctions_vlay.selectionChanged.connect( self.feature_sel_changed) self.params.reservoirs_vlay.selectionChanged.connect( self.feature_sel_changed) self.params.tanks_vlay.selectionChanged.connect( self.feature_sel_changed) self.params.pipes_vlay.selectionChanged.connect( self.feature_sel_changed) self.params.pumps_vlay.selectionChanged.connect( self.feature_sel_changed) self.params.valves_vlay.selectionChanged.connect( self.feature_sel_changed) # self.setMinimumWidth(min_width) # self.setMinimumHeight(min_height) fra_main_lay = QVBoxLayout(self) self.fra_out_file = QFrame(self) fra_out_file_lay = QHBoxLayout(self.fra_out_file) self.lbl_out_file = QLabel('Simulation output file:') self.txt_out_file = QLineEdit('') self.txt_out_file.setReadOnly(True) self.btn_out_file = QToolButton() self.btn_out_file.setText('...') self.btn_out_file.clicked.connect(self.btn_out_file_clicked) fra_out_file_lay.addWidget(self.lbl_out_file) fra_out_file_lay.addWidget(self.txt_out_file) fra_out_file_lay.addWidget(self.btn_out_file) self.tab_widget = QTabWidget(self) # Graphs tab --------------------------------------------------------------------------------------------------- self.tab_graphs = QWidget() tab_graphs_lay = QHBoxLayout(self.tab_graphs) # Left frame self.fra_graphs_left = QFrame() self.fra_graphs_left.setMaximumWidth(100) fra_graphs_left_lay = QVBoxLayout(self.fra_graphs_left) self.btn_sel_element = QPushButton('Pick') self.btn_sel_element.clicked.connect(self.btn_sel_element_clicked) fra_graphs_left_lay.addWidget(self.btn_sel_element) # Nodes self.grb_nodes = QGroupBox(u'Nodes') lay_grb_nodes = QVBoxLayout(self.grb_nodes) self.chk_node_demand = QCheckBox('Demand') lay_grb_nodes.addWidget(self.chk_node_demand) self.chk_node_head = QCheckBox('Head') lay_grb_nodes.addWidget(self.chk_node_head) self.chk_node_pressure = QCheckBox('Pressure') lay_grb_nodes.addWidget(self.chk_node_pressure) self.chk_node_quality = QCheckBox('Quality') lay_grb_nodes.addWidget(self.chk_node_quality) fra_graphs_left_lay.addWidget(self.grb_nodes) # Links self.grb_links = QGroupBox(u'Links') lay_grb_links = QVBoxLayout(self.grb_links) self.chk_link_flow = QCheckBox('Flow') lay_grb_links.addWidget(self.chk_link_flow) self.chk_link_velocity = QCheckBox('Velocity') lay_grb_links.addWidget(self.chk_link_velocity) self.chk_link_headloss = QCheckBox('Headloss') lay_grb_links.addWidget(self.chk_link_headloss) self.chk_link_quality = QCheckBox('Quality') lay_grb_links.addWidget(self.chk_link_quality) fra_graphs_left_lay.addWidget(self.grb_links) self.btn_draw_graph = QPushButton('Draw') self.btn_draw_graph.clicked.connect(self.draw_graphs) fra_graphs_left_lay.addWidget(self.btn_draw_graph) self.spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) fra_graphs_left_lay.addItem(self.spacer) tab_graphs_lay.addWidget(self.fra_graphs_left) # Right frame self.fra_graphs_right = QFrame() fra_graphs_right_lay = QVBoxLayout(self.fra_graphs_right) fra_graphs_right_lay.setContentsMargins(0, 0, 0, 0) self.static_canvas = StaticMplCanvas(self.fra_graphs_right, width=5, height=4, dpi=100) fra_graphs_right_lay.addWidget(self.static_canvas) tab_graphs_lay.addWidget(self.fra_graphs_right) # lay.addWidget(self.button) self.tab_widget.addTab(self.tab_graphs, 'Graphs') # Maps tab ----------------------------------------------------------------------------------------------------- self.tab_maps = QWidget() tab_maps_lay = QHBoxLayout(self.tab_maps) # Left frame self.fra_maps_left = QFrame() self.fra_maps_left.setMaximumWidth(200) fra_maps_left_lay = QVBoxLayout(self.fra_maps_left) self.grb_maps = QGroupBox(u'Variable') grb_maps_lay = QVBoxLayout(self.grb_maps) self.rad_maps_node_demand = QRadioButton(u'Node demand') grb_maps_lay.addWidget(self.rad_maps_node_demand) self.rad_maps_node_head = QRadioButton(u'Node head') grb_maps_lay.addWidget(self.rad_maps_node_head) self.rad_maps_node_pressure = QRadioButton(u'Node pressure') grb_maps_lay.addWidget(self.rad_maps_node_pressure) self.rad_maps_node_quality = QRadioButton(u'Node quality') grb_maps_lay.addWidget(self.rad_maps_node_quality) self.rad_maps_link_flow = QRadioButton(u'Link flow') grb_maps_lay.addWidget(self.rad_maps_link_flow) self.rad_maps_link_velocity = QRadioButton(u'Link velocity') grb_maps_lay.addWidget(self.rad_maps_link_velocity) self.rad_maps_link_headloss = QRadioButton(u'Link headloss') grb_maps_lay.addWidget(self.rad_maps_link_headloss) self.rad_maps_link_quality = QRadioButton(u'Link quality') grb_maps_lay.addWidget(self.rad_maps_link_quality) fra_maps_left_lay.addWidget(self.grb_maps) fra_maps_left_lay.addItem(self.spacer) tab_maps_lay.addWidget(self.fra_maps_left) # Right maps frame self.fra_maps_right = QFrame() fra_maps_right_lay = QVBoxLayout(self.fra_maps_right) self.fra_maps_right_time = QFrame() fra_maps_right_time_lay = QFormLayout(self.fra_maps_right_time) self.lbl_map_times = QLabel(u'Period [h]:') self.cbo_map_times = QComboBox() fra_maps_right_time_lay.addRow(self.lbl_map_times, self.cbo_map_times) fra_maps_right_lay.addWidget(self.fra_maps_right_time) self.btn_draw_map = QPushButton(u'Draw map') self.btn_draw_map.clicked.connect(self.draw_maps) fra_maps_right_lay.addWidget(self.btn_draw_map) fra_maps_right_lay.addItem(self.spacer) tab_maps_lay.addWidget(self.fra_maps_right) self.tab_widget.addTab(self.tab_maps, 'Maps') # # Add to main fra_main_lay.addWidget(self.fra_out_file) fra_main_lay.addWidget(self.tab_widget) self.setup() self.initialize() # self.read_outputs() # Set size self.setMinimumWidth(self.tab_graphs.width()) self.setMinimumHeight(self.tab_graphs.height()) def setup(self): pass def btn_out_file_clicked(self): config_file = ConfigFile(Parameters.config_file_path) out_file = QFileDialog.getOpenFileName(self, 'Select out file', config_file.get_last_out_file(), 'Out files (*.out)') if out_file is None or out_file == '': return config_file.set_last_out_file(out_file) self.txt_out_file.setText(out_file) self.read_outputs() if self.output_reader is None: return # Fill times combo self.cbo_map_times.clear() for period_s in self.output_reader.period_results.iterkeys(): text = self.seconds_to_string( period_s, self.output_reader.sim_duration_secs, self.output_reader.report_time_step_secs) self.cbo_map_times.addItem(text, period_s) def initialize(self): # Graphs self.grb_nodes.setEnabled(False) self.grb_links.setEnabled(False) # Maps self.rad_maps_node_demand.setChecked(True) def feature_sel_changed(self): is_nodes = False sel_junctions = self.params.junctions_vlay.selectedFeatureCount() sel_reservoirs = self.params.reservoirs_vlay.selectedFeatureCount() sel_tanks = self.params.tanks_vlay.selectedFeatureCount() if sel_junctions > 0 or sel_reservoirs > 0 or sel_tanks > 0: is_nodes = True self.grb_nodes.setEnabled(is_nodes) is_links = False sel_pipes = self.params.pipes_vlay.selectedFeatureCount() sel_pumps = self.params.pumps_vlay.selectedFeatureCount() sel_valves = self.params.valves_vlay.selectedFeatureCount() if sel_pipes > 0 or sel_pumps > 0 or sel_valves > 0: is_links = True self.grb_links.setEnabled(is_links) def read_outputs(self): try: QApplication.setOverrideCursor(Qt.WaitCursor) self.output_reader = BinaryOutputReader() self.output_reader.read(self.txt_out_file.text()) QApplication.restoreOverrideCursor() # Check if output compatible with loaded project compatible = True out_nodes_nr = self.output_reader.nodes_nr out_tanks_reservs_nr = self.output_reader.tanks_reservs_nr out_juncts_nr = out_nodes_nr - out_tanks_reservs_nr out_links_nr = self.output_reader.links_nr out_pumps_nr = self.output_reader.pumps_nr out_valves_nr = self.output_reader.valves_nr out_pipes_nr = out_links_nr - out_pumps_nr - out_valves_nr if out_juncts_nr != self.params.junctions_vlay.featureCount(): compatible = False if out_tanks_reservs_nr != ( self.params.reservoirs_vlay.featureCount() + self.params.tanks_vlay.featureCount()): compatible = False if out_pipes_nr != self.params.pipes_vlay.featureCount(): compatible = False if out_valves_nr != self.params.valves_vlay.featureCount(): compatible = False if out_pumps_nr != self.params.pumps_vlay.featureCount(): compatible = False if not compatible: message = 'The out file appears to incompatible with the actual project layers.' QMessageBox.warning(self, Parameters.plug_in_name, message, QMessageBox.Ok) self.output_reader = None self.txt_out_file.setText('') else: # Message after reading completed message = 'Out file loaded: ' + str( out_nodes_nr) + ' nodes, ' + str( out_links_nr) + ' links found.' # Clear refs to output layer self.params.out_lay_node_demand = None self.params.out_lay_node_head = None self.params.out_lay_node_pressure = None self.params.out_lay_node_quality = None self.params.out_lay_link_flow = None self.params.out_lay_link_velocity = None self.params.out_lay_link_headloss = None self.params.out_lay_link_quality = None QMessageBox.information(self, Parameters.plug_in_name, message, QMessageBox.Ok) finally: # self.iface.messageBar().pushWarning( # Parameters.plug_in_name, # 'Error while reading output file.') # TODO: softcode # self.output_reader = None # self.txt_out_file.setText('') QApplication.restoreOverrideCursor() def btn_sel_element_clicked(self): if self.output_reader is None: self.iface.messageBar().pushMessage( Parameters.plug_in_name, 'Please select the simulation out file.', QgsMessageBar.WARNING, 5) # TODO: softcode return self.tool = SelectTool(self, self.params) self.iface.mapCanvas().setMapTool(self.tool) cursor = QCursor() cursor.setShape(Qt.ArrowCursor) self.iface.mapCanvas().setCursor(cursor) def draw_graphs(self): # Get selected features self.element_ids_nodes = [] for junction_feat in self.params.junctions_vlay.selectedFeatures(): self.element_ids_nodes.append( junction_feat.attribute(Junction.field_name_eid)) for reservoir_feat in self.params.reservoirs_vlay.selectedFeatures(): self.element_ids_nodes.append( reservoir_feat.attribute(Reservoir.field_name_eid)) for tank_feat in self.params.tanks_vlay.selectedFeatures(): self.element_ids_nodes.append( tank_feat.attribute(Tank.field_name_eid)) self.element_ids_links = [] for pipe_feat in self.params.pipes_vlay.selectedFeatures(): self.element_ids_links.append( pipe_feat.attribute(Pipe.field_name_eid)) for pump_feat in self.params.pumps_vlay.selectedFeatures(): self.element_ids_links.append( pump_feat.attribute(Pump.field_name_eid)) for valve_feat in self.params.valves_vlay.selectedFeatures(): self.element_ids_links.append( valve_feat.attribute(Valve.field_name_eid)) # Build values dictionaries xs = self.output_reader.report_times ys_d_d = {} params_count = 0 # Nodes if self.grb_nodes.isEnabled(): if self.chk_node_demand.isChecked(): params_count += 1 ys_d = {} for element_id in self.element_ids_nodes: ys_d[element_id] = [ self.output_reader.node_demands_d[element_id], self.params.options.flow_units ] ys_d_d[OutputParamCodes.NODE_DEMAND] = ys_d if self.chk_node_head.isChecked(): params_count += 1 ys_d = {} for element_id in self.element_ids_nodes: ys_d[element_id] = [ self.output_reader.node_heads_d[element_id], Options.units_diameter_tanks[self.params.options.units] ] ys_d_d[OutputParamCodes.NODE_HEAD] = ys_d if self.chk_node_pressure.isChecked(): params_count += 1 ys_d = {} for element_id in self.element_ids_nodes: ys_d[element_id] = [ self.output_reader.node_pressures_d[element_id], Options.units_pressure[self.params.options.units] ] ys_d_d[OutputParamCodes.NODE_PRESSURE] = ys_d if self.chk_node_quality.isChecked(): params_count += 1 ys_d = {} for element_id in self.element_ids_nodes: ys_d[element_id] = [ self.output_reader.node_qualities_d[element_id], Quality.quality_units_text[ self.params.options.quality.mass_units] ] ys_d_d[OutputParamCodes.NODE_QUALITY] = ys_d # Links if self.grb_links.isEnabled(): if self.chk_link_flow.isChecked(): params_count += 1 ys_d = {} for element_id in self.element_ids_links: ys_d[element_id] = [ self.output_reader.link_flows_d[element_id], self.params.options.flow_units ] ys_d_d[OutputParamCodes.LINK_FLOW] = ys_d if self.chk_link_velocity.isChecked(): params_count += 1 ys_d = {} for element_id in self.element_ids_links: ys_d[element_id] = [ self.output_reader.link_velocities_d[element_id], Options.units_velocity[self.params.options.units] ] ys_d_d[OutputParamCodes.LINK_VELOCITY] = ys_d if self.chk_link_headloss.isChecked(): params_count += 1 ys_d = {} for element_id in self.element_ids_links: ys_d[element_id] = [ self.output_reader.link_headlosses_d[element_id], Options.units_diameter_tanks[self.params.options.units] ] ys_d_d[OutputParamCodes.LINK_HEADLOSS] = ys_d if self.chk_link_quality.isChecked(): params_count += 1 ys_d = {} for element_id in self.element_ids_links: ys_d[element_id] = [ self.output_reader.link_qualities_d[element_id], Quality.quality_units_text[ self.params.options.quality.mass_units] ] ys_d_d[OutputParamCodes.LINK_QUALITY] = ys_d if ys_d_d: self.static_canvas.draw_output_line(xs, ys_d_d, params_count) def draw_maps(self): """ Draws layers with all the attributes :return: """ report_time = self.cbo_map_times.itemText( self.cbo_map_times.currentIndex()) if self.rad_maps_node_demand.isChecked( ): # ------------------------------------------------------------------- lay_name = u'Node demand' lay_id = self.draw_map(LayerType.NODE, self.params.out_lay_node_demand_id, lay_name, self.output_reader.node_demands_d, report_time) self.params.out_lay_node_demand_id = lay_id elif self.rad_maps_node_head.isChecked(): lay_name = u'Node head' lay_id = self.draw_map(LayerType.NODE, self.params.out_lay_node_head_id, lay_name, self.output_reader.node_heads_d, report_time) self.params.out_lay_node_head_id = lay_id elif self.rad_maps_node_pressure.isChecked(): lay_name = u'Node pressure' lay_id = self.draw_map(LayerType.NODE, self.params.out_lay_node_pressure_id, lay_name, self.output_reader.node_pressures_d, report_time) self.params.out_lay_node_pressure_id = lay_id elif self.rad_maps_node_quality.isChecked(): lay_name = u'Node quality' lay_id = self.draw_map(LayerType.NODE, self.params.out_lay_node_quality_id, lay_name, self.output_reader.node_qualities_d, report_time) self.params.out_lay_node_quality_id = lay_id elif self.rad_maps_link_flow.isChecked( ): # ------------------------------------------------------------------- lay_name = u'Link flow' lay_id = self.draw_map(LayerType.LINK, self.params.out_lay_link_flow_id, lay_name, self.output_reader.link_flows_d, report_time) self.params.out_lay_link_flow_id = lay_id elif self.rad_maps_link_velocity.isChecked(): lay_name = u'Link velocity' lay_id = self.draw_map(LayerType.LINK, self.params.out_lay_link_velocity_id, lay_name, self.output_reader.link_velocities_d, report_time) self.params.out_lay_link_velocity_id = lay_id elif self.rad_maps_link_headloss.isChecked(): lay_name = u'Link headloss' lay_id = self.draw_map(LayerType.LINK, self.params.out_lay_link_headloss_id, lay_name, self.output_reader.link_headlosses_d, report_time) self.params.out_lay_link_headloss_id = lay_id elif self.rad_maps_link_quality.isChecked(): lay_name = u'Link quality' lay_id = self.draw_map(LayerType.LINK, self.params.out_lay_link_quality_id, lay_name, self.output_reader.link_qualities_d, report_time) self.params.out_lay_link_quality_id = lay_id def draw_map(self, lay_type, lay_id, lay_name, dataset, report_time): try: QApplication.setOverrideCursor(Qt.WaitCursor) lay_name += ' ' + report_time lay = LayerUtils.get_lay_from_id(lay_id) if lay is None: if lay_type == LayerType.NODE: lay = self.create_out_node_layer(lay_name, dataset) ns = NodeSymbology() lay.setRendererV2( ns.make_graduated_sym_renderer(lay, report_time)) elif lay_type == LayerType.LINK: lay = self.create_out_link_layer(lay_name, dataset) ls = LinkSymbology() lay.setRendererV2( ls.make_flow_sym_renderer(lay, report_time)) lay_id = lay.id() QgsMapLayerRegistry.instance().addMapLayer(lay) self.params.out_layers.append(lay) else: lay.setLayerName(lay_name) lay.triggerRepaint() QApplication.restoreOverrideCursor() finally: QApplication.restoreOverrideCursor() return lay_id def btn_cancel_clicked(self): self.setVisible(False) def btn_ok_clicked(self): pass def create_out_node_layer(self, lay_name, values_d): return self.create_out_layer(lay_name, values_d, LayerType.NODE) def create_out_link_layer(self, lay_name, values_d): return self.create_out_layer(lay_name, values_d, LayerType.LINK) def create_out_layer(self, lay_name, values_d, lay_type): field_name_vars = [] periods = self.output_reader.period_results.keys() for period_s in periods: text = self.seconds_to_string( period_s, self.output_reader.sim_duration_secs, self.output_reader.report_time_step_secs) field_name_vars.append(text) if lay_type == LayerType.NODE: new_lay = MemoryDS.create_nodes_lay(self.params, field_name_vars, lay_name, self.params.crs) elif lay_type == LayerType.LINK: new_lay = MemoryDS.create_links_lay(self.params, field_name_vars, lay_name, self.params.crs) with edit(new_lay): # Update attributes for feat in new_lay.getFeatures(): fid = feat.id() eid = feat.attribute(Node.field_name_eid) values = values_d[eid] for p in range(len(periods)): new_lay.changeAttributeValue(fid, p + 1, values[p]) return new_lay def seconds_to_string(self, period_s, duration_s, interval_s): day = int(math.floor(period_s / 86400)) hour = period_s / 3600 - day * 24 minute = period_s / 60 - day * 24 * 60 - hour * 60 second = period_s - day * 86400 - hour * 3600 - minute * 60 text = '' if duration_s >= 86400: # We need days text += str(day) + 'd' if duration_s >= 3600: # We need hours text += '{:02}'.format(hour) + 'H' text += '{:02}'.format(minute) + 'm' if second > 0: text += '{:02}'.format(second) + 's' return text
class RunConfigOptions(QWidget): """Run configuration options""" def __init__(self, parent=None): QWidget.__init__(self, parent) self.current_radio = None self.dedicated_radio = None self.systerm_radio = None self.runconf = RunConfiguration() firstrun_o = CONF.get('run', ALWAYS_OPEN_FIRST_RUN_OPTION, False) # --- General settings ---- common_group = QGroupBox(_("General settings")) common_layout = QGridLayout() common_group.setLayout(common_layout) self.clo_cb = QCheckBox(_("Command line options:")) common_layout.addWidget(self.clo_cb, 0, 0) self.clo_edit = QLineEdit() self.connect(self.clo_cb, SIGNAL("toggled(bool)"), self.clo_edit.setEnabled) self.clo_edit.setEnabled(False) common_layout.addWidget(self.clo_edit, 0, 1) self.wd_cb = QCheckBox(_("Working directory:")) common_layout.addWidget(self.wd_cb, 1, 0) wd_layout = QHBoxLayout() self.wd_edit = QLineEdit() self.connect(self.wd_cb, SIGNAL("toggled(bool)"), self.wd_edit.setEnabled) self.wd_edit.setEnabled(False) wd_layout.addWidget(self.wd_edit) browse_btn = QPushButton(get_std_icon('DirOpenIcon'), "", self) browse_btn.setToolTip(_("Select directory")) self.connect(browse_btn, SIGNAL("clicked()"), self.select_directory) wd_layout.addWidget(browse_btn) common_layout.addLayout(wd_layout, 1, 1) # --- Interpreter --- interpreter_group = QGroupBox(_("Interpreter")) interpreter_layout = QVBoxLayout() interpreter_group.setLayout(interpreter_layout) self.current_radio = QRadioButton(CURRENT_INTERPRETER) interpreter_layout.addWidget(self.current_radio) self.dedicated_radio = QRadioButton(DEDICATED_INTERPRETER) interpreter_layout.addWidget(self.dedicated_radio) self.systerm_radio = QRadioButton(SYSTERM_INTERPRETER) interpreter_layout.addWidget(self.systerm_radio) # --- Dedicated interpreter --- new_group = QGroupBox(_("Dedicated Python interpreter")) self.connect(self.current_radio, SIGNAL("toggled(bool)"), new_group.setDisabled) new_layout = QGridLayout() new_group.setLayout(new_layout) self.interact_cb = QCheckBox( _("Interact with the Python " "interpreter after execution")) new_layout.addWidget(self.interact_cb, 1, 0, 1, -1) self.pclo_cb = QCheckBox(_("Command line options:")) new_layout.addWidget(self.pclo_cb, 2, 0) self.pclo_edit = QLineEdit() self.connect(self.pclo_cb, SIGNAL("toggled(bool)"), self.pclo_edit.setEnabled) self.pclo_edit.setEnabled(False) self.pclo_edit.setToolTip( _("<b>-u</b> is added to the " "other options you set here")) new_layout.addWidget(self.pclo_edit, 2, 1) #TODO: Add option for "Post-mortem debugging" # Checkbox to preserve the old behavior, i.e. always open the dialog # on first run hline = QFrame() hline.setFrameShape(QFrame.HLine) hline.setFrameShadow(QFrame.Sunken) self.firstrun_cb = QCheckBox(ALWAYS_OPEN_FIRST_RUN % _("this dialog")) self.connect(self.firstrun_cb, SIGNAL("clicked(bool)"), self.set_firstrun_o) self.firstrun_cb.setChecked(firstrun_o) layout = QVBoxLayout() layout.addWidget(interpreter_group) layout.addWidget(common_group) layout.addWidget(new_group) layout.addWidget(hline) layout.addWidget(self.firstrun_cb) self.setLayout(layout) def select_directory(self): """Select directory""" basedir = unicode(self.wd_edit.text()) if not osp.isdir(basedir): basedir = os.getcwdu() directory = getexistingdirectory(self, _("Select directory"), basedir) if directory: self.wd_edit.setText(directory) self.wd_cb.setChecked(True) def set(self, options): self.runconf.set(options) self.clo_cb.setChecked(self.runconf.args_enabled) self.clo_edit.setText(self.runconf.args) self.wd_cb.setChecked(self.runconf.wdir_enabled) self.wd_edit.setText(self.runconf.wdir) if self.runconf.current: self.current_radio.setChecked(True) elif self.runconf.systerm: self.systerm_radio.setChecked(True) else: self.dedicated_radio.setChecked(True) self.interact_cb.setChecked(self.runconf.interact) self.pclo_cb.setChecked(self.runconf.python_args_enabled) self.pclo_edit.setText(self.runconf.python_args) def get(self): self.runconf.args_enabled = self.clo_cb.isChecked() self.runconf.args = unicode(self.clo_edit.text()) self.runconf.wdir_enabled = self.wd_cb.isChecked() self.runconf.wdir = unicode(self.wd_edit.text()) self.runconf.current = self.current_radio.isChecked() self.runconf.systerm = self.systerm_radio.isChecked() self.runconf.interact = self.interact_cb.isChecked() self.runconf.python_args_enabled = self.pclo_cb.isChecked() self.runconf.python_args = unicode(self.pclo_edit.text()) return self.runconf.get() def is_valid(self): wdir = unicode(self.wd_edit.text()) if not self.wd_cb.isChecked() or osp.isdir(wdir): return True else: QMessageBox.critical( self, _("Run configuration"), _("The following working directory is " "not valid:<br><b>%s</b>") % wdir) return False def set_firstrun_o(self): CONF.set('run', ALWAYS_OPEN_FIRST_RUN_OPTION, self.firstrun_cb.isChecked())
class FindInFilesDialog(QDialog): def __init__(self, result_widget, parent): QDialog.__init__(self, parent) self._find_thread = FindInFilesThread() self.setWindowTitle("Find in files") self.resize(400, 300) #MAIN LAYOUT main_vbox = QVBoxLayout(self) self.pattern_line_edit = QLineEdit() self.dir_name_root = None self.user_home = os.path.expanduser('~') self.dir_combo = QComboBox() self.dir_combo.addItem(self.user_home) self.dir_combo.setEditable(True) self.open_button = QPushButton(QIcon(resources.IMAGES['find']), self.tr("Open")) self.filters_line_edit = QLineEdit("*.py") self.replace_line = QLineEdit() self.replace_line.setEnabled(False) self.check_replace = QCheckBox(self.tr("Replace: ")) self.case_checkbox = QCheckBox(self.tr("C&ase sensitive")) self.type_checkbox = QCheckBox(self.tr("R&egular Expression")) self.recursive_checkbox = QCheckBox(self.tr("Rec&ursive")) self.recursive_checkbox.setCheckState(Qt.Checked) self.phrase_radio = QRadioButton( self.tr("Search by Phrase (Exact Match).")) self.phrase_radio.setChecked(True) self.words_radio = QRadioButton( self.tr("Search for all the words " "(anywhere in the document, not together).")) self.find_button = QPushButton(self.tr("Find!")) self.find_button.setMaximumWidth(150) self.cancel_button = QPushButton(self.tr("Cancel")) self.cancel_button.setMaximumWidth(150) self.result_widget = result_widget hbox = QHBoxLayout() hbox.addWidget(self.find_button) hbox.addWidget(self.cancel_button) #main section find_group_box = QGroupBox(self.tr("Main")) grid = QGridLayout() grid.addWidget(QLabel(self.tr("Text: ")), 0, 0) grid.addWidget(self.pattern_line_edit, 0, 1) grid.addWidget(QLabel(self.tr("Directory: ")), 1, 0) grid.addWidget(self.dir_combo, 1, 1) grid.addWidget(self.open_button, 1, 2) grid.addWidget(QLabel(self.tr("Filter: ")), 2, 0) grid.addWidget(self.filters_line_edit, 2, 1) grid.addWidget(self.check_replace, 3, 0) grid.addWidget(self.replace_line, 3, 1) find_group_box.setLayout(grid) #add main section to MAIN LAYOUT main_vbox.addWidget(find_group_box) #options sections options_group_box = QGroupBox(self.tr("Options")) gridOptions = QGridLayout() gridOptions.addWidget(self.case_checkbox, 0, 0) gridOptions.addWidget(self.type_checkbox, 1, 0) gridOptions.addWidget(self.recursive_checkbox, 2, 0) gridOptions.addWidget(self.phrase_radio, 0, 1) gridOptions.addWidget(self.words_radio, 1, 1) options_group_box.setLayout(gridOptions) #add options sections to MAIN LAYOUT main_vbox.addWidget(options_group_box) #add buttons to MAIN LAYOUT main_vbox.addLayout(hbox) #Focus self.pattern_line_edit.setFocus() self.open_button.setFocusPolicy(Qt.NoFocus) #signal self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir) self.connect(self.find_button, SIGNAL("clicked()"), self._find_in_files) self.connect(self.cancel_button, SIGNAL("clicked()"), self._kill_thread) self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"), self._found_match) self.connect(self._find_thread, SIGNAL("finished()"), self._find_thread_finished) self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"), self._change_radio_enabled) self.connect(self.check_replace, SIGNAL("stateChanged(int)"), self._replace_activated) self.connect(self.words_radio, SIGNAL("clicked(bool)"), self._words_radio_pressed) def _replace_activated(self): self.replace_line.setEnabled(self.check_replace.isChecked()) self.phrase_radio.setChecked(True) def _words_radio_pressed(self, value): self.replace_line.setEnabled(not value) self.check_replace.setChecked(not value) self.words_radio.setChecked(True) def _change_radio_enabled(self, val): enabled = not self.type_checkbox.isChecked() self.phrase_radio.setEnabled(enabled) self.words_radio.setEnabled(enabled) def show(self, actual_project=None, actual=None): self.dir_combo.clear() self.dir_name_root = actual_project if \ actual_project else [self.user_home] self.dir_combo.addItems(self.dir_name_root) if actual: index = self.dir_combo.findText(actual) self.dir_combo.setCurrentIndex(index) super(FindInFilesDialog, self).show() self.pattern_line_edit.setFocus() def reject(self): self._kill_thread() # Crazy hack to avoid circular imports self.result_widget.parent().parent().parent().hide() super(FindInFilesDialog, self).reject() def _find_thread_finished(self): self.emit(SIGNAL("finished()")) self._find_thread.wait() def _select_dir(self): dir_name = QFileDialog.getExistingDirectory(self, self.tr("Open Directory"), self.dir_combo.currentText(), QFileDialog.ShowDirsOnly) index = self.dir_combo.findText(dir_name) if index >= 0: self.dir_combo.setCurrentIndex(index) else: self.dir_combo.insertItem(0, dir_name) self.dir_combo.setCurrentIndex(0) def _found_match(self, result): file_name = result[0] items = result[1] self.result_widget.update_result( self.dir_combo.currentText(), file_name, items) def _kill_thread(self): if self._find_thread.isRunning(): self._find_thread.cancel() self.accept() def _find_in_files(self): self.emit(SIGNAL("findStarted()")) self._kill_thread() self.result_widget.clear() pattern = self.pattern_line_edit.text() dir_name = self.dir_combo.currentText() filters = re.split("[,;]", self.filters_line_edit.text()) # Version of PyQt API 1 # filters = self.filters_line_edit.text().split(QRegExp("[,;]"), # QString.SkipEmptyParts) #remove the spaces in the words Ex. (" *.foo"--> "*.foo") filters = [f.strip() for f in filters] case_sensitive = self.case_checkbox.isChecked() type_ = QRegExp.RegExp if \ self.type_checkbox.isChecked() else QRegExp.FixedString recursive = self.recursive_checkbox.isChecked() by_phrase = True if self.phrase_radio.isChecked() or self.type_checkbox.isChecked(): regExp = QRegExp(pattern, case_sensitive, type_) elif self.words_radio.isChecked(): by_phrase = False type_ = QRegExp.RegExp pattern = '|'.join( [word.strip() for word in pattern.split()]) regExp = QRegExp(pattern, case_sensitive, type_) #save a reference to the root directory where we find self.dir_name_root = dir_name self._find_thread.find_in_files(dir_name, filters, regExp, recursive, by_phrase)
class SVNPluginConfigDialog( QDialog ): " SVN Plugin config dialog " def __init__( self, ideWideSettings, projectSettings, parent = None ): QDialog.__init__( self, parent ) self.__createLayout() self.setWindowTitle( "SVN plugin configuration" ) self.ideWideSettings = copy.deepcopy( ideWideSettings ) if projectSettings is None: self.projectSettings = None else: self.projectSettings = copy.deepcopy( projectSettings ) # Set the values self.__setIDEWideValues() if projectSettings is None: self.__tabWidget.setTabEnabled( 1, False ) else: self.__setProjectValues() self.__tabWidget.setCurrentIndex( 1 ) self.__updateOKStatus() self.__idewideUser.textChanged.connect( self.__updateOKStatus ) self.__projectUser.textChanged.connect( self.__updateOKStatus ) return def __setIDEWideValues( self ): " Sets the values in the IDE wide tab " if self.ideWideSettings.authKind == AUTH_EXTERNAL: self.__idewideAuthExtRButton.setChecked( True ) self.__idewideUser.setEnabled( False ) self.__idewidePasswd.setEnabled( False ) else: self.__idewideAuthPasswdRButton.setChecked( True ) if self.ideWideSettings.userName: self.__idewideUser.setText( self.ideWideSettings.userName ) if self.ideWideSettings.password: self.__idewidePasswd.setText( self.ideWideSettings.password ) if self.ideWideSettings.statusKind == STATUS_REPOSITORY: self.__idewideReposRButton.setChecked( True ) else: self.__idewideLocalRButton.setChecked( True ) return def __setProjectValues( self ): " Sets the values in the project tab " if self.projectSettings.authKind == AUTH_EXTERNAL: self.__projectAuthExtRButton.setChecked( True ) self.__projectUser.setEnabled( False ) self.__projectPasswd.setEnabled( False ) else: self.__projectAuthPasswdRButton.setChecked( True ) if self.projectSettings.userName: self.__projectUser.setText( self.projectSettings.userName ) if self.projectSettings.password: self.__projectPasswd.setText( self.projectSettings.password ) if self.projectSettings.statusKind == STATUS_REPOSITORY: self.__projectReposRButton.setChecked( True ) else: self.__projectLocalRButton.setChecked( True ) return def __createLayout( self ): " Creates the dialog layout " self.resize( 640, 420 ) self.setSizeGripEnabled( True ) vboxLayout = QVBoxLayout( self ) hboxLayout = QHBoxLayout() iconLabel = QLabel() logoPath = os.path.dirname( os.path.abspath( __file__ ) ) + \ os.path.sep + "svn-logo.png" iconLabel.setPixmap( QPixmap( logoPath ) ) iconLabel.setScaledContents( True ) iconLabel.setFixedSize( 48, 48 ) hboxLayout.addWidget( iconLabel ) titleLabel = QLabel( "Codimension SVN plugin settings" ) titleLabel.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Expanding ) titleLabel.setFixedHeight( 48 ) titleLabel.setAlignment( Qt.AlignCenter ) hboxLayout.addWidget( titleLabel ) vboxLayout.addLayout( hboxLayout ) self.__tabWidget = QTabWidget( self ) self.__tabWidget.setFocusPolicy( Qt.NoFocus ) ideWide = self.__createIDEWide() self.__tabWidget.addTab( ideWide, "IDE Wide" ) projectSpecific = self.__createProjectSpecific() self.__tabWidget.addTab( projectSpecific, "Project Specific" ) version = self.__createVersionWidget() self.__tabWidget.addTab( version, "Versions" ) vboxLayout.addWidget( self.__tabWidget ) # Buttons at the bottom self.__buttonBox = QDialogButtonBox( self ) self.__buttonBox.setOrientation( Qt.Horizontal ) self.__buttonBox.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Cancel ) self.__buttonBox.accepted.connect( self.userAccept ) self.__buttonBox.rejected.connect( self.close ) vboxLayout.addWidget( self.__buttonBox ) return def __createIDEWide( self ): " Creates the IDE wide part " widget = QWidget() verticalLayout = QVBoxLayout( widget ) infoLabel = QLabel( "Note: the settings below are used " "when there is no project loaded." ) verticalLayout.addWidget( infoLabel ) # Authorization group box authGroupbox = QGroupBox( self ) authGroupbox.setTitle( "Authorization" ) sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred ) sizePolicy.setHorizontalStretch( 0 ) sizePolicy.setVerticalStretch( 0 ) sizePolicy.setHeightForWidth( authGroupbox.sizePolicy().hasHeightForWidth() ) authGroupbox.setSizePolicy( sizePolicy ) layoutAuth = QVBoxLayout( authGroupbox ) self.__idewideAuthExtRButton = QRadioButton( "External", authGroupbox ) self.__idewideAuthExtRButton.clicked.connect( self.__idewideAuthChanged ) layoutAuth.addWidget( self.__idewideAuthExtRButton ) self.__idewideAuthPasswdRButton = QRadioButton( "Use user name / password", authGroupbox ) self.__idewideAuthPasswdRButton.clicked.connect( self.__idewideAuthChanged ) layoutAuth.addWidget( self.__idewideAuthPasswdRButton ) upLayout = QGridLayout() self.__idewideUser = QLineEdit() self.__idewideUser.setToolTip( "Attention: user name is " "saved unencrypted" ) self.__idewidePasswd = QLineEdit() self.__idewidePasswd.setToolTip( "Attention: password is " "saved unencrypted" ) spacer = QWidget() spacer.setFixedWidth( 16 ) upLayout.addWidget( spacer, 0, 0 ) upLayout.addWidget( QLabel( "User name" ), 0, 1 ) upLayout.addWidget( self.__idewideUser, 0, 2 ) upLayout.addWidget( QLabel( "Password" ), 1, 1 ) upLayout.addWidget( self.__idewidePasswd, 1, 2 ) layoutAuth.addLayout( upLayout ) # Update status group box updateGroupbox = QGroupBox( self ) updateGroupbox.setTitle( "Update status policy" ) sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred ) sizePolicy.setHorizontalStretch( 0 ) sizePolicy.setVerticalStretch( 0 ) sizePolicy.setHeightForWidth( updateGroupbox.sizePolicy().hasHeightForWidth() ) updateGroupbox.setSizePolicy( sizePolicy ) layoutUpdate = QVBoxLayout( updateGroupbox ) self.__idewideReposRButton = QRadioButton( "Check repository", updateGroupbox ) layoutUpdate.addWidget( self.__idewideReposRButton ) self.__idewideLocalRButton = QRadioButton( "Local only", updateGroupbox ) layoutUpdate.addWidget( self.__idewideLocalRButton ) verticalLayout.addWidget( authGroupbox ) verticalLayout.addWidget( updateGroupbox ) return widget def __idewideAuthChanged( self ): " Triggered when authorization has been changed " if self.__idewideAuthExtRButton.isChecked(): self.__idewideUser.setEnabled( False ) self.__idewidePasswd.setEnabled( False ) else: self.__idewideUser.setEnabled( True ) self.__idewidePasswd.setEnabled( True ) self.__idewideUser.setFocus() self.__updateOKStatus() return def __createProjectSpecific( self ): " Creates the project specific part " widget = QWidget() verticalLayout = QVBoxLayout( widget ) infoLabel = QLabel( "Note: the settings below are used " "only for the specific project." ) verticalLayout.addWidget( infoLabel ) # Authorization group box authGroupbox = QGroupBox( self ) authGroupbox.setTitle( "Authorization" ) sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred ) sizePolicy.setHorizontalStretch( 0 ) sizePolicy.setVerticalStretch( 0 ) sizePolicy.setHeightForWidth( authGroupbox.sizePolicy().hasHeightForWidth() ) authGroupbox.setSizePolicy( sizePolicy ) layoutAuth = QVBoxLayout( authGroupbox ) self.__projectAuthExtRButton = QRadioButton( "External", authGroupbox ) self.__projectAuthExtRButton.clicked.connect( self.__projectAuthChanged ) layoutAuth.addWidget( self.__projectAuthExtRButton ) self.__projectAuthPasswdRButton = QRadioButton( "Use user name / password", authGroupbox ) self.__projectAuthPasswdRButton.clicked.connect( self.__projectAuthChanged ) layoutAuth.addWidget( self.__projectAuthPasswdRButton ) upLayout = QGridLayout() self.__projectUser = QLineEdit() self.__projectUser.setToolTip( "Attention: user name is " "saved unencrypted" ) self.__projectPasswd = QLineEdit() self.__projectPasswd.setToolTip( "Attention: password is " "saved unencrypted" ) spacer = QWidget() spacer.setFixedWidth( 16 ) upLayout.addWidget( spacer, 0, 0 ) upLayout.addWidget( QLabel( "User name" ), 0, 1 ) upLayout.addWidget( self.__projectUser, 0, 2 ) upLayout.addWidget( QLabel( "Password" ), 1, 1 ) upLayout.addWidget( self.__projectPasswd, 1, 2 ) layoutAuth.addLayout( upLayout ) # Update status group box updateGroupbox = QGroupBox( self ) updateGroupbox.setTitle( "Update status policy" ) sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred ) sizePolicy.setHorizontalStretch( 0 ) sizePolicy.setVerticalStretch( 0 ) sizePolicy.setHeightForWidth( updateGroupbox.sizePolicy().hasHeightForWidth() ) updateGroupbox.setSizePolicy( sizePolicy ) layoutUpdate = QVBoxLayout( updateGroupbox ) self.__projectReposRButton = QRadioButton( "Check repository", updateGroupbox ) layoutUpdate.addWidget( self.__projectReposRButton ) self.__projectLocalRButton = QRadioButton( "Local only", updateGroupbox ) layoutUpdate.addWidget( self.__projectLocalRButton ) verticalLayout.addWidget( authGroupbox ) verticalLayout.addWidget( updateGroupbox ) return widget def __projectAuthChanged( self ): " Triggered when authorization has been changed " if self.__projectAuthExtRButton.isChecked(): self.__projectUser.setEnabled( False ) self.__projectPasswd.setEnabled( False ) else: self.__projectUser.setEnabled( True ) self.__projectPasswd.setEnabled( True ) self.__projectUser.setFocus() self.__updateOKStatus() return def __createVersionWidget( self ): " Creates the version tab content " ver = pysvn.svn_version svnVersion = ".".join( [ str( ver[ 0 ] ), str( ver[ 1 ] ), str( ver[ 2 ] ) ] ) ver = pysvn.version pysvnVersion = ".".join( [ str( ver[ 0 ] ), str( ver[ 1 ] ), str( ver[ 2 ] ) ] ) text = "<p>The major Codimension SVN plugin components are listed below:</p>" \ "<ul>" \ "<li><a href='http://subversion.apache.org/'>Subversion</a><br>" \ "Version: " + svnVersion + "<br></li>" \ "<li><a href='http://pysvn.tigris.org/docs/pysvn.html'>PySvn</a><br>" \ "Version: " + pysvnVersion + "<br>" \ "License: <a href='http://www.apache.org/licenses/LICENSE-1.1'>Apache License 1.1</a>" \ "<br></li>" \ "</ul>" browser = QTextBrowser() browser.setHtml( text ) browser.setOpenExternalLinks( True ) return browser def userAccept( self ): " Triggered when the user clicks OK " # Collect IDE-wide values if self.__idewideAuthExtRButton.isChecked(): self.ideWideSettings.authKind = AUTH_EXTERNAL self.ideWideSettings.userName = None self.ideWideSettings.password = None else: self.ideWideSettings.authKind = AUTH_PASSWD self.ideWideSettings.userName = self.__idewideUser.text().strip() self.ideWideSettings.password = self.__idewidePasswd.text().strip() if self.__idewideReposRButton.isChecked(): self.ideWideSettings.statusKind = STATUS_REPOSITORY else: self.ideWideSettings.statusKind = STATUS_LOCAL_ONLY if self.projectSettings is not None: if self.__projectAuthExtRButton.isChecked(): self.projectSettings.authKind = AUTH_EXTERNAL self.projectSettings.userName = None self.projectSettings.password = None else: self.projectSettings.authKind = AUTH_PASSWD self.projectSettings.userName = self.__projectUser.text().strip() self.projectSettings.password = self.__projectPasswd.text().strip() if self.__projectReposRButton.isChecked(): self.projectSettings.statusKind = STATUS_REPOSITORY else: self.projectSettings.statusKind = STATUS_LOCAL_ONLY self.accept() return def __updateOKStatus( self ): " Updates the OK button status " okButton = self.__buttonBox.button( QDialogButtonBox.Ok ) if self.__idewideAuthPasswdRButton.isChecked(): userName = self.__idewideUser.text().strip() if not userName: okButton.setEnabled( False ) okButton.setToolTip( "IDE wide SVN user name cannot be empty" ) return if self.projectSettings is not None: if self.__projectAuthPasswdRButton.isChecked(): userName = self.__projectUser.text().strip() if not userName: okButton.setEnabled( False ) okButton.setToolTip( "Project specific SVN " "user name cannot be empty" ) return okButton.setEnabled( True ) okButton.setToolTip( "" ) return