class RangeSelection(QWidget): """ Allow to select a date, a build id, a release number or an arbitrary changeset. """ def __init__(self, parent=None): QWidget.__init__(self, parent) layout = QHBoxLayout(self) self._create_widgets() layout.addWidget(self.stacked) layout.addWidget(self.select_combo) self.setLayout(layout) def _create_widgets(self): self.stacked = QStackedWidget() self.datew = QDateEdit() self.datew.setDisplayFormat("yyyy-MM-dd") self.stacked.addWidget(self.datew) self.buildidw = QLineEdit() self.stacked.addWidget(self.buildidw) self.releasew = QComboBox() self.releasew.addItems([str(k) for k in sorted(releases())]) self.stacked.addWidget(self.releasew) self.revw = QLineEdit() self.stacked.addWidget(self.revw) self.select_combo = QComboBox() self.select_combo.addItems(['date', 'buildid', 'release', 'changeset']) self.select_combo.activated.connect(self.stacked.setCurrentIndex) def get_value(self): currentw = self.stacked.currentWidget() if currentw == self.datew: return self.datew.date().toPyDate() elif currentw == self.buildidw: buildid = unicode(self.buildidw.text()) try: return parse_date(buildid) except DateFormatError: raise DateFormatError(buildid, "Not a valid build id: `%s`") elif currentw == self.releasew: return parse_date( date_of_release(str(self.releasew.currentText()))) elif currentw == self.revw: return unicode(self.revw.text())
class H264Dialog(QDialog): def __init__(self, parent=None, retval=None): super().__init__(parent) self.setWindowTitle('H264 Profile') profiles = ('baseline', 'main', 'high', 'high10', 'high422', 'high444') presets = ('ultrafast', 'superfast', 'veryfast', 'faster', 'fast', 'medium', 'slow', 'slower', 'veryslow', 'placebo') tunes = ('film', 'animation', 'grain', 'stillimage', 'psnr', 'ssim', 'fastdecode', 'zerolatency') layout = QFormLayout() self.cbo_profiles = QComboBox(self) self.cbo_profiles.addItems(profiles) try: index = profiles.index(retval['-profile']) except: index = 2 self.cbo_profiles.setCurrentIndex(index) layout.addRow('Profile:', self.cbo_profiles) self.cbo_presets = QComboBox(self) self.cbo_presets.addItems(presets) try: index = presets.index(retval['-preset']) except: index = 5 self.cbo_presets.setCurrentIndex(index) layout.addRow('Preset:', self.cbo_presets) self.cbo_tunes = QComboBox(self) self.cbo_tunes.addItems(tunes) try: index = tunes.index(retval['-tune']) except: index = 0 self.cbo_tunes.setCurrentIndex(index) layout.addRow('Tune:', self.cbo_tunes) bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) bbox.accepted.connect(self.accept) bbox.rejected.connect(self.reject) layout.addRow(bbox) self.returnval = retval self.setLayout(layout) def accept(self): self.returnval = { '-profile': self.cbo_profiles.currentText(), '-preset': self.cbo_presets.currentText(), '-tune': self.cbo_tunes.currentText() } super().accept() def reject(self): self.returnval = None super().reject()
class choixSonSortieWidget(QGroupBox) : """Class pour faire le widget standard de sélection du format de sortie son + réglages experts""" def __init__(self, soxSuppFormat, parent=None) : super(choixSonSortieWidget, self).__init__(parent) self.setObjectName("groupBox") self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setObjectName("horizontalLayout") self.label = QLabel(self) self.label.setObjectName("label") self.horizontalLayout.addWidget(self.label) self.formatSound = QComboBox(self) for x in soxSuppFormat : self.formatSound.addItem(QString(x)) self.formatSound.setObjectName("formatSound") self.horizontalLayout.addWidget(self.formatSound) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.reglageExp = reglageExpert(soxSuppFormat, self.formatSound) self.horizontalLayout.addWidget(self.reglageExp) self.setTitle(_(u"Réglage du format de sortie")) self.label.setText(_(u"Format du fichier de sortie :")) self.formatSound.setToolTip(_(u"Format du fichier son de sortie")) def getFileExt(self) : return unicode(self.formatSound.currentText())
class FontLayout(QHBoxLayout): """Font selection""" def __init__(self, value, parent=None): QHBoxLayout.__init__(self) font = tuple_to_qfont(value) assert font is not None # Font family self.family = QFontComboBox(parent) self.family.setCurrentFont(font) self.addWidget(self.family) # Font size self.size = QComboBox(parent) self.size.setEditable(True) sizelist = list(itertools.chain(range(6, 12), range(12, 30, 2), [36, 48, 72])) size = font.pointSize() if size not in sizelist: sizelist.append(size) sizelist.sort() self.size.addItems([str(s) for s in sizelist]) self.size.setCurrentIndex(sizelist.index(size)) self.addWidget(self.size) def get_font(self): font = self.family.currentFont() font.setPointSize(int(self.size.currentText())) return qfont_to_tuple(font)
class LateralPanel(QWidget): def __init__(self, parent=None): super(LateralPanel, self).__init__(parent) self.has_component = False self.vbox = QVBoxLayout(self) self.vbox.setContentsMargins(0, 0, 0, 0) hbox = QHBoxLayout() hbox.setContentsMargins(0, 0, 0, 0) self.combo = QComboBox() ui_tools.ComboBoxButton(self.combo, self.combo.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.combo.setToolTip(self.trUtf8("Select the item from the Paste " "History list.\nYou can Copy items into this list with: " "%s\nor Paste them using: %s") % (resources.get_shortcut("History-Copy").toString( QKeySequence.NativeText), resources.get_shortcut("History-Paste").toString( QKeySequence.NativeText))) self.combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) hbox.addWidget(self.combo) self.vbox.addLayout(hbox) def add_component(self, widget): self.vbox.insertWidget(0, widget) self.has_component = True def add_new_copy(self, copy): self.combo.insertItem(0, copy) self.combo.setCurrentIndex(0) if self.combo.count() > settings.COPY_HISTORY_BUFFER: self.combo.removeItem(self.combo.count() - 1) def get_paste(self): return self.combo.currentText()
class KeywordConfigurationWidget(ConfigurationWidget): def __init__(self): ConfigurationWidget.__init__(self) self.keyIndexCombo = QComboBox() self.addRow("Key index:", self.keyIndexCombo) self.connect(self.keyIndexCombo, SIGNAL("currentIndexChanged(QString)"), self.applyConfiguration) def setKeyIndexList(self, list): self.disconnect(self.keyIndexCombo, SIGNAL("currentIndexChanged(QString)"), self.applyConfiguration) self.keyIndexCombo.clear() self.keyIndexCombo.addItems(list) self.connect(self.keyIndexCombo, SIGNAL("currentIndexChanged(QString)"), self.applyConfiguration) def setParameter(self, parameter): self.parameter = parameter self.applyConfiguration(False) def applyConfiguration(self, emit=True): user_data = {"state": self.getState(), "key_index": self.getKeyIndex()} self.parameter.setUserData(user_data) self.emitConfigurationChanged(emit) def getKeyIndex(self): return str(self.keyIndexCombo.currentText())
class Dial(QDialog): choices = ['flat', 'hanning', 'hamming', 'bartlett', 'blackman'] def __init__(self, parent): QDialog.__init__(self, parent) f = QFormLayout(self) self.a = QSpinBox(self) self.a.setValue(30) self.b = QComboBox(self) self.b.addItems(self.choices) self.c = QDialogButtonBox(self) self.c.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) f.addRow("window:", self.a) f.addRow("method:", self.b) f.addRow("", self.c) self.connect(self.c, SIGNAL("accepted()"), self.sendData) self.connect(self.c, SIGNAL("rejected()"), self.reinitialize) def sendData(self): self.parent().window = self.a.value() self.parent().method = self.b.currentText() self.close() def reinitialize(self): self.parent().window = None self.parent().method = None self.close()
class EnumConfigControl(ConfigControl): def __init__(self, config_item): ConfigControl.__init__(self, config_item) self._init_ui() def _init_ui(self): lbl_enum = QLabel(self._config_item.tag()) lbl_enum.setFixedWidth(self.LABEL_WIDTH) self._cmbo_enum = QComboBox() self._cmbo_enum.addItems(self._config_item.enum_names) selected = self._config_item.value() index = self._cmbo_enum.findText(selected, QtCore.Qt.MatchFixedString) self._cmbo_enum.setCurrentIndex(index) hbox = QHBoxLayout() hbox.setContentsMargins(0, 0, 0, 0) hbox.addWidget(lbl_enum) hbox.addWidget(self._cmbo_enum) hbox.addStretch() self.setLayout(hbox) def update_from_config(self): selected = self._config_item.value() index = self._cmbo_enum.findText(selected, QtCore.Qt.MatchFixedString) index = max(0, index) self._cmbo_enum.setCurrentIndex(index) def save_to_config(self): value = self._cmbo_enum.currentText() self._config_item.set(value)
class FilterDialog(QDialog): def __init__(self, opcoes_list, parent=None): super(FilterDialog, self).__init__(parent) """ Janela de dialogo criada independente (como uma opção ao uso do qt designer) """ # Cria um layout para a sua janela de input QDialog self.layout = QVBoxLayout(self) #Cria um label e adiciona no layout self.label = QLabel(u"Escolha o valor de filtro:") self.layout.addWidget(self.label) # Cria combobox com a lista de opcoes a escolher # e adicionar no layout self.filtro_box = QComboBox() self.filtro_box.addItems(opcoes_list) self.layout.addWidget(self.filtro_box) # Cria botoes de submeter e adiciona ao layout self.buttons = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self) self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.reject) self.layout.addWidget(self.buttons) def valor_atual(self): """ Retorna qual valor atual na combo box (valor escolhido) """ return self.filtro_box.currentText()
class StateDialog(QtHelper.EnhancedQDialog, Logger.ClassLogger): """ State dialog """ def __init__(self, parent=None): """ Dialog to fill parameter description @param dataArgs: @type dataArgs: @param parent: @type parent: """ super(StateDialog, self).__init__(parent) # make a copy self.createDialog() self.createConnections() def createDialog(self): """ Create qt dialog """ mainLayout = QVBoxLayout() self.comboType = QComboBox() self.comboType.addItem("Writing") self.comboType.addItem("Executing") typeLayout = QHBoxLayout() typeLayout.addWidget(self.comboType) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setStyleSheet("""QDialogButtonBox { dialogbuttonbox-buttons-have-icons: 1; dialog-ok-icon: url(:/ok.png); dialog-cancel-icon: url(:/ko.png); }""") self.buttonBox.setStandardButtons(QDialogButtonBox.Ok) mainLayout.addLayout(typeLayout) mainLayout.addWidget(self.buttonBox) self.setLayout(mainLayout) self.setWindowTitle("Test Description > State") self.setFixedWidth(350) self.center() def createConnections(self): """ Create qt connections """ self.buttonBox.accepted.connect(self.accept) def getSelectedState(self): """ Returns selected state """ return q(self.comboType.currentText())
class Dial(QDialog): choices =['flat', 'hanning', 'hamming', 'bartlett', 'blackman'] def __init__(self, parent): QDialog.__init__(self, parent) f =QFormLayout(self) self.a =QSpinBox(self) self.a.setValue(30) self.b = QComboBox(self) self.b.addItems(self.choices) self.c= QDialogButtonBox(self) self.c.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) f.addRow("window:" ,self.a) f.addRow("method:", self.b) f.addRow("", self.c) self.connect(self.c, SIGNAL("accepted()"), self.sendData) self.connect(self.c, SIGNAL("rejected()"), self.reinitialize) def sendData(self): self.parent().window = self.a.value() self.parent().method = self.b.currentText() self.close() def reinitialize(self): self.parent().window = None self.parent().method = None self.close()
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)
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)
class LilyPondPreferences(QGroupBox): def __init__(self, parent): super(LilyPondPreferences, self).__init__(parent) grid = QGridLayout() self.setLayout(grid) self.pitchLanguageLabel = QLabel() self.pitchLanguage = QComboBox() self.versionLabel = QLabel() self.version = QComboBox(editable=True) self.pitchLanguage.addItem('') self.pitchLanguage.addItems( [lang.title() for lang in sorted(scoreproperties.keyNames)]) self.version.addItem(lilypondinfo.preferred().versionString()) for v in ("2.18.0", "2.16.0", "2.14.0", "2.12.0"): if v != lilypondinfo.preferred().versionString(): self.version.addItem(v) grid.addWidget(self.pitchLanguageLabel, 0, 0) grid.addWidget(self.pitchLanguage, 0, 1) grid.addWidget(self.versionLabel, 1, 0) grid.addWidget(self.version, 1, 1) self.pitchLanguage.activated.connect(self.slotPitchLanguageChanged) app.translateUI(self) self.loadSettings() self.window().finished.connect(self.saveSettings) def translateUI(self): self.setTitle(_("LilyPond")) self.pitchLanguageLabel.setText(_("Pitch name language:")) self.pitchLanguage.setToolTip( _("The LilyPond language you want to use for the pitch names.")) self.pitchLanguage.setItemText(0, _("Default")) self.versionLabel.setText(_("Version:")) self.version.setToolTip( _("The LilyPond version you will be using for this document.")) def slotPitchLanguageChanged(self, index): if index == 0: language = '' else: language = self.pitchLanguage.currentText().lower() self.window().setPitchLanguage(language) def loadSettings(self): language = self.window().pitchLanguage() languages = list(sorted(scoreproperties.keyNames)) index = languages.index(language) + 1 if language in languages else 0 self.pitchLanguage.setCurrentIndex(index) def saveSettings(self): QSettings().setValue('scorewiz/lilypond/pitch_language', self.window().pitchLanguage())
class LilyPondPreferences(QGroupBox): def __init__(self, parent): super(LilyPondPreferences, self).__init__(parent) grid = QGridLayout() self.setLayout(grid) self.pitchLanguageLabel = QLabel() self.pitchLanguage = QComboBox() self.versionLabel = QLabel() self.version = QComboBox(editable=True) self.pitchLanguage.addItem('') self.pitchLanguage.addItems([lang.title() for lang in sorted(scoreproperties.keyNames)]) self.version.addItem(lilypondinfo.preferred().versionString()) for v in ("2.18.0", "2.16.0", "2.14.0", "2.12.0"): if v != lilypondinfo.preferred().versionString(): self.version.addItem(v) grid.addWidget(self.pitchLanguageLabel, 0, 0) grid.addWidget(self.pitchLanguage, 0, 1) grid.addWidget(self.versionLabel, 1, 0) grid.addWidget(self.version, 1, 1) self.pitchLanguage.activated.connect(self.slotPitchLanguageChanged) app.translateUI(self) self.loadSettings() self.window().finished.connect(self.saveSettings) def translateUI(self): self.setTitle(_("LilyPond")) self.pitchLanguageLabel.setText(_("Pitch name language:")) self.pitchLanguage.setToolTip(_( "The LilyPond language you want to use for the pitch names.")) self.pitchLanguage.setItemText(0, _("Default")) self.versionLabel.setText(_("Version:")) self.version.setToolTip(_( "The LilyPond version you will be using for this document.")) def slotPitchLanguageChanged(self, index): if index == 0: language = '' else: language = self.pitchLanguage.currentText().lower() self.window().setPitchLanguage(language) def loadSettings(self): language = self.window().pitchLanguage() languages = list(sorted(scoreproperties.keyNames)) index = languages.index(language) + 1 if language in languages else 0 self.pitchLanguage.setCurrentIndex(index) def saveSettings(self): QSettings().setValue('scorewiz/lilypond/pitch_language', self.window().pitchLanguage())
class CharColumnConfigurationWidget(QWidget, columnproviders.AbstractColumnConfigurationWidget): def __init__(self, parent, hex_widget, column): QWidget.__init__(self, parent) columnproviders.AbstractColumnConfigurationWidget.__init__(self) self.hexWidget = hex_widget self.columnModel = column self.setLayout(QFormLayout()) self.layout().setContentsMargins(0, 0, 0, 0) self.cmbEncoding = QComboBox(self) self.cmbEncoding.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self.layout().addRow(utils.tr('Encoding:'), self.cmbEncoding) for encoding in sorted(encodings.encodings.keys()): self.cmbEncoding.addItem(encoding) if column is not None and column.codec.name.lower() == encoding.lower(): self.cmbEncoding.setCurrentIndex(self.cmbEncoding.count() - 1) if column is None: self.cmbEncoding.setCurrentIndex(self.cmbEncoding.findText('Windows-1251')) self.spnBytesOnRow = QSpinBox(self) self.spnBytesOnRow.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self.spnBytesOnRow.setMinimum(1) self.spnBytesOnRow.setMaximum(32) self.layout().addRow(utils.tr('Bytes on row:'), self.spnBytesOnRow) if column is not None: self.spnBytesOnRow.setValue(column.bytesOnRow) else: self.spnBytesOnRow.setValue(16) def createColumnModel(self, hex_widget): model = CharColumnModel(self.hexWidget.document, encodings.getCodec(self.cmbEncoding.currentText()), self.hexWidget.font(), self.spnBytesOnRow.value()) return model def saveToColumn(self, column): column.codec = encodings.getCodec(self.cmbEncoding.currentText()) column._bytesOnRow = self.spnBytesOnRow.value() column.reset()
class OptionsDialog(QDialog): def __init__(self, parent=None): super().__init__(parent) self._langs = get_langs() self._lang_selection = QComboBox() langs = list(self._langs.keys()) langs.sort() i = 0 lang_index = None for lang in langs: self._lang_selection.addItem(lang) if self._langs[lang] == get('Global', 'lang'): lang_index = i i += 1 try: self._lang_selection.setCurrentIndex(lang_index) except TypeError: pass langBox = QHBoxLayout() langBox.addWidget(QLabel(_('OptionsDialog.lang'))) langBox.addStretch(1) langBox.addWidget(self._lang_selection) cancelButton = QPushButton(_('cancel')) cancelButton.clicked.connect(self.reject) okButton = QPushButton(_('OK')) okButton.clicked.connect(self.accept) buttonBox = QHBoxLayout() buttonBox.addStretch(1) buttonBox.addWidget(cancelButton) buttonBox.addWidget(okButton) layout = QVBoxLayout() layout.addLayout(langBox) layout.addLayout(buttonBox) self.accepted.connect(self._save) self.setLayout(layout) self.setWindowTitle(_('OptionsDialog.title')) def _save(self): set_lang(self._langs[self._lang_selection.currentText()])
class DocumentTab(QWidget): def __init__(self, parent): self.parent = parent super(DocumentTab, self).__init__(parent) self.name = 'Documents' self.formats = config.document_formats flist = [] for i in self.formats: for y in self.formats[i]: flist.append(i + ' to ' + y) flist.sort() convertQL = QLabel(self.tr('Convert:')) self.convertQCB = QComboBox() self.convertQCB.addItems(flist) final_layout = utils.add_to_layout( 'h', convertQL, self.convertQCB, None) self.setLayout(final_layout) def ok_to_continue(self): """ Check if everything is ok with documenttab to continue conversion. Checks if: - unoconv is missing. - Given file extension is same with the declared extension. Return True if all tests pass, else False. """ decl_ext = self.convertQCB.currentText().split(' ')[0] try: if not self.parent.unoconv: raise ValidationError( self.tr( 'Unocov is not installed.\nYou will not be able ' 'to convert document files until you install it.') ) for i in self.parent.fnames: file_ext = os.path.splitext(i)[-1][1:] if file_ext != decl_ext: raise ValidationError( self.trUtf8('{0} is not {1}!'.format(i, decl_ext))) return True except ValidationError as e: QMessageBox.warning(self, 'FF Multi Converter - ' + \ self.tr('Error!'), str(e)) return False
class DocumentTab(QWidget): def __init__(self, parent): self.parent = parent super(DocumentTab, self).__init__(parent) self.name = 'Documents' self.formats = config.document_formats flist = [] for i in self.formats: for y in self.formats[i]: flist.append(i + ' to ' + y) flist.sort() convertQL = QLabel(self.tr('Convert:')) self.convertQCB = QComboBox() self.convertQCB.addItems(flist) final_layout = utils.add_to_layout('h', convertQL, self.convertQCB, None) self.setLayout(final_layout) def ok_to_continue(self): """ Check if everything is ok with documenttab to continue conversion. Checks if: - unoconv is missing. - Given file extension is same with the declared extension. Return True if all tests pass, else False. """ decl_ext = self.convertQCB.currentText().split(' ')[0] try: if not self.parent.unoconv: raise ValidationError( self.tr('Unocov is not installed.\nYou will not be able ' 'to convert document files until you install it.')) for i in self.parent.fnames: file_ext = os.path.splitext(i)[-1][1:] if file_ext != decl_ext: raise ValidationError( self.trUtf8('{0} is not {1}!'.format(i, decl_ext))) return True except ValidationError as e: QMessageBox.warning(self, 'FF Multi Converter - ' + \ self.tr('Error!'), str(e)) return False
class FontLayout(QGridLayout): """Font selection""" def __init__(self, value, parent=None): QGridLayout.__init__(self) font = tuple_to_qfont(value) assert font is not None # Font family self.family = QFontComboBox(parent) self.addWidget(self.family, 0, 0, 1, -1) # Font size self.size = QComboBox(parent) self.size.setEditable(True) sizelist = list(range(6, 12)) + list(range(12, 30, 2)) + [36, 48, 72] size = font.pointSize() if size not in sizelist: sizelist.append(size) sizelist.sort() self.size.addItems([str(s) for s in sizelist]) self.addWidget(self.size, 1, 0) # Italic or not self.italic = QCheckBox(self.tr("Italic"), parent) self.addWidget(self.italic, 1, 1) # Bold or not self.bold = QCheckBox(self.tr("Bold"), parent) self.addWidget(self.bold, 1, 2) self.set_font(font) def set_font(self, font): self.family.setCurrentFont(font) size = font.pointSize() i = self.size.findText(str(size)) if i >= 0: self.size.setCurrentIndex(i) self.italic.setChecked(font.italic()) self.bold.setChecked(font.bold()) def get_font(self): font = self.family.currentFont() font.setItalic(self.italic.isChecked()) font.setBold(self.bold.isChecked()) font.setPointSize(int(self.size.currentText())) return qfont_to_tuple(font)
class saveSoundDialog(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) grid = QGridLayout() n = 0 #self.fileToWrite = None self.guessFileExtension = True formatLabel = QLabel(self.tr('File Format: ')) grid.addWidget(formatLabel, n, 0) self.formatChooser = QComboBox() self.formatChooser.addItems(["wav"]) #available_file_formats()) self.formatChooser.setCurrentIndex(0) grid.addWidget(self.formatChooser, n, 1) self.formatChooser.currentIndexChanged[int].connect( self.onFileFormatChange) self.suggestedExtension = str(self.formatChooser.currentText()) encodingLabel = QLabel(self.tr('Bits: ')) grid.addWidget(encodingLabel, n, 2) self.encodingChooser = QComboBox() self.encodingChooser.addItems([ "16", "24", "32" ]) #available_encodings(str(self.formatChooser.currentText()))) self.encodingChooser.setCurrentIndex(0) grid.addWidget(self.encodingChooser, n, 3) n = n + 1 channelLabel = QLabel(self.tr('Channel: ')) grid.addWidget(channelLabel, n, 0) self.channelChooser = QComboBox() self.channelChooser.addItems([self.tr('Stereo'), self.tr('Mono')]) self.channelChooser.setCurrentIndex(0) grid.addWidget(self.channelChooser, n, 1) n = n + 1 buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) grid.addWidget(buttonBox, n, 2) self.setLayout(grid) self.setWindowTitle(self.tr("Save Sound Options")) def onFileFormatChange(self): pass
class EkdStylePropertie(EkdPropertie): """ Définition de la propriété correspondant à un QStyle """ def __init__(self, prop, name, value, choices=[], section=None ): super(EkdStylePropertie, self).__init__(prop, name, value, EkdPropertie.STYLE, section) self.label = QLabel(name) self.widget = QComboBox() self.widget.addItems(choices) self.widget.setCurrentIndex(self.widget.findText(value)) # Quand on change de codec, on met à jour EkdConfig self.connect(self.widget, SIGNAL("currentIndexChanged(int)"), self.updateStyle) def updateStyle(self): self.value = self.widget.currentText() EkdConfig.set(self.section, self.id, self.value)
class VNAFitWidget(VNAWidget): def __init__(self): super(VNAFitWidget, self).__init__() self.fit_combo_box = QComboBox() self.fit_combo_box.addItems(["Lorentzian", "Asymmetric Hanger"]) self.form_layout.addRow("Fit Type", self.fit_combo_box) fit_button = QPushButton("Fit") self.button_layout.addWidget(fit_button) self.fitted_mags = None self.vna_params = None self.fit_params = {} fit_button.clicked.connect(self.fit_trace) def grab_trace(self): self.fitted_mags = None self.fit_params = {} super(VNAFitWidget, self).grab_trace() def replot(self): super(VNAFitWidget, self).replot() if self.fitted_mags is not None: self.mag_plot.plot(self.freqs, self.fitted_mags, pen='r', name='Fit') def fit_trace(self): fit_type = str(self.fit_combo_box.currentText()) if fit_type == "Asymmetric Hanger": self.fit_params, self.fitted_mags = fit_asymmetric_db_hanger(self.freqs, self.mags) elif fit_type == "Lorentzian": self.fit_params, self.fitted_mags = fit_db_lorentzian(self.freqs, self.mags) self.fit_params = {k: v.value for k, v in self.fit_params.items()} self.message("Parameters") self.message("----------") for pn, pv in self.fit_params.items(): self.message(pn, ":", pv) self.message("") self.replot() def save_trace(self): super(VNAFitWidget, self).save_trace() group = self.get_h5group() if 'fitted_mags' in group: del group['fitted_mags'] if self.fitted_mags is not None: group['fitted_mags'] = self.fitted_mags dataserver_helpers.set_scale(group, 'freqs', 'fitted_mags')
class LateralPanel(QWidget): def __init__(self, parent=None): super(LateralPanel, self).__init__(parent) self.has_component = False self.vbox = QVBoxLayout(self) self.vbox.setContentsMargins(0, 0, 0, 0) hbox = QHBoxLayout() hbox.setContentsMargins(0, 0, 0, 0) self.labelText = "Ln: %s, Col: %s" self.labelCursorPosition = QLabel(self.trUtf8(self.labelText % (0, 0))) hbox.addWidget(self.labelCursorPosition) self.combo = QComboBox() ui_tools.ComboBoxButton( self.combo, self.combo.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.combo.setToolTip( self.trUtf8( "Select the item from the Paste " "Historial list.\nYou can Copy items into this list with: " "%s\nor Paste them using: %s") % (resources.get_shortcut("History-Copy").toString( QKeySequence.NativeText), resources.get_shortcut("History-Paste").toString( QKeySequence.NativeText))) self.combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) hbox.addWidget(self.combo) self.vbox.addLayout(hbox) def add_component(self, widget): self.vbox.insertWidget(0, widget) self.has_component = True def update_line_col(self, line, col): self.labelCursorPosition.setText( self.trUtf8(self.labelText % (line, col))) def add_new_copy(self, copy): self.combo.insertItem(0, copy) self.combo.setCurrentIndex(0) if self.combo.count() > settings.COPY_HISTORY_BUFFER: self.combo.removeItem(self.combo.count() - 1) def get_paste(self): return self.combo.currentText()
class ComboBox(QWidget): def __init__(self, id, text, **kwargs): QWidget.__init__(self) self.id = id self.widget = QComboBox(**kwargs) label = QLabel(text) hbox = HBoxLayout() hbox.addWidget(label) hbox.addWidget(self.widget, alignment=Qt.AlignRight) self.setLayout(hbox) def parameterValues(self): index = self.widget.currentIndex() data = self.widget.itemData(index).toString() if not data.isEmpty(): text = data else: text = self.widget.currentText() return {self.id:text}
class ConfigurationWidget(QWidget): """An abstract configuration widget.""" def __init__(self): QWidget.__init__(self) self.layout = QFormLayout() self.layout.setRowWrapPolicy(QFormLayout.WrapLongRows) self.stateCombo = QComboBox() for state in enums.ert_state_enum.values(): self.stateCombo.addItem(state.name) self.stateCombo.setCurrentIndex(0) self.layout.addRow("State:", self.stateCombo) self.setLayout(self.layout) self.connect(self.stateCombo, SIGNAL("currentIndexChanged(QString)"), self.applyConfiguration) def addRow(self, label, widget): """Add another item to this widget.""" self.layout.addRow(label, widget) def setParameter(self, parameter): """Set the parameter to configure.""" self.parameter = parameter self.applyConfiguration(False) def getState(self): """State is common for all parameters.""" selectedName = str(self.stateCombo.currentText()) return enums.ert_state_enum.resolveName(selectedName) def emitConfigurationChanged(self, emit=True): """Emitted when a sub widget changes the state of the parameter.""" if emit: self.emit(SIGNAL("configurationChanged()")) def applyConfiguration(self, emit=True): """Override! Set the user_data of self.paramater and optionally: emitConfigurationChanged()""" pass
class saveSoundDialog(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) grid = QGridLayout() n = 0 #self.fileToWrite = None self.guessFileExtension = True formatLabel = QLabel(self.tr('File Format: ')) grid.addWidget(formatLabel, n, 0) self.formatChooser = QComboBox() self.formatChooser.addItems(["wav"])#available_file_formats()) self.formatChooser.setCurrentIndex(0) grid.addWidget(self.formatChooser, n, 1) self.formatChooser.currentIndexChanged[int].connect(self.onFileFormatChange) self.suggestedExtension = str(self.formatChooser.currentText()) encodingLabel = QLabel(self.tr('Bits: ')) grid.addWidget(encodingLabel, n, 2) self.encodingChooser = QComboBox() self.encodingChooser.addItems(["16", "24", "32"])#available_encodings(str(self.formatChooser.currentText()))) self.encodingChooser.setCurrentIndex(0) grid.addWidget(self.encodingChooser, n, 3) n = n+1 channelLabel = QLabel(self.tr('Channel: ')) grid.addWidget(channelLabel, n, 0) self.channelChooser = QComboBox() self.channelChooser.addItems([self.tr('Stereo'), self.tr('Mono')]) self.channelChooser.setCurrentIndex(0) grid.addWidget(self.channelChooser, n, 1) n = n+1 buttonBox = QDialogButtonBox(QDialogButtonBox.Ok| QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) grid.addWidget(buttonBox, n, 2) self.setLayout(grid) self.setWindowTitle(self.tr("Save Sound Options")) def onFileFormatChange(self): pass
class VentanaFiltrar(QDialog): def __init__(self, padre): super(VentanaFiltrar, self).__init__(padre) self.inicializar() def inicializar(self): self.titulo = QLabel("SELECCIONE EL FILTRO A APLICAR", self) self.titulo.move(50,50) self.titulo.adjustSize() self.filtros = QComboBox(self) self.filtros.move(100,100) self.filtros.sizeAdjustPolicy() self.filtros.addItem("Low pass filter") self.filtros.addItem("High pass filter") self.filtros.addItem("Gaussian filter") self.filtros.addItem("Pyramidal filter") self.filtros.addItem("Sinc filter") self.seleccionar = QPushButton("Seleccionar imagen", self) self.seleccionar.move(100,200) self.seleccionar.clicked.connect(self.filtrar) self.setWindowTitle("Filtrar una imagen") self.resize(300,300) self.setWindowModality(1) self.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed) self.show() def filtrar(self): archivo = QFileDialog(self) ruta = archivo.getOpenFileName(self, 'Seleccionar imagen', '', "Images (*.png *.gif *.jpg *.bmp)") if not ruta.isEmpty(): try: from core import filtrar img = filtrar(str(ruta), str(self.filtros.currentText())) ruta1 = archivo.getSaveFileName(self, "Guardar imagen", '', "Images (*.png *.gif *.jpg *.bmp)") img.save(str(ruta1) + ".png") except ImportError: resp = QMessageBox.information(self, 'Error', 'Hubo un error inesperado', QMessageBox.Ok, QMessageBox.NoButton) else: resp = QMessageBox.information(self, 'Error', 'No ha elegido imagenes', QMessageBox.Ok, QMessageBox.NoButton)
class LateralPanel(QWidget): def __init__(self, explorer): QWidget.__init__(self) vbox = QVBoxLayout(self) vbox.setContentsMargins(0, 0, 0, 0) vbox.addWidget(explorer) hbox = QHBoxLayout() hbox.setContentsMargins(0, 0, 0, 0) self.labelText = "Ln: %1, Col: %2" self.labelCursorPosition = QLabel( self.tr(self.labelText).arg(0).arg(0)) hbox.addWidget(self.labelCursorPosition) self.combo = QComboBox() ui_tools.ComboBoxButton( self.combo, self.combo.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.combo.setToolTip( self.tr( "Select the item from the Paste " "Historial list.\nYou can Copy items into this list with: " "%1\nor Paste them using: %2").arg( resources.get_shortcut("History-Copy").toString( QKeySequence.NativeText)).arg( resources.get_shortcut("History-Paste").toString( QKeySequence.NativeText))) self.combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) hbox.addWidget(self.combo) vbox.addLayout(hbox) def update_line_col(self, line, col): self.labelCursorPosition.setText( self.tr(self.labelText).arg(line).arg(col)) def add_new_copy(self, copy): self.combo.insertItem(0, copy) self.combo.setCurrentIndex(0) if self.combo.count() > settings.COPY_HISTORY_BUFFER: self.combo.removeItem(self.combo.count() - 1) def get_paste(self): return unicode(self.combo.currentText())
class AddFieldDialog(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) layout = QVBoxLayout(self) self.setLayout(layout) layout.addWidget(QLabel('Enter the field name:', self)) self._field_name_edit = QLineEdit(self) self._field_name_edit.textChanged.connect(self._text_changed) layout.addWidget(self._field_name_edit) layout.addWidget(QLabel('Type:', self)) self._type_combo = QComboBox(self) self._type_combo.addItems(['int', 'float', 'bool', 'str']) layout.addWidget(self._type_combo) buttons = QWidget(self) buttons_layout = QHBoxLayout() buttons.setLayout(buttons_layout) buttons_layout.addStretch() self._ok_button = QPushButton("Ok") self._ok_button.setEnabled(False) cancel_button = QPushButton("Cancel") self._ok_button.clicked.connect(self.accept) cancel_button.clicked.connect(self.reject) buttons_layout.addWidget(self._ok_button) buttons_layout.addWidget(cancel_button) layout.addWidget(buttons) def _text_changed(self, text): self._ok_button.setEnabled( re.match('^[a-zA-Z][a-zA-Z0-9_-]*$', text) is not None) @property def name(self): return self._field_name_edit.text() @property def ftype(self): return str(self._type_combo.currentText())
class LateralPanel(QWidget): def __init__(self, explorer): QWidget.__init__(self) vbox = QVBoxLayout(self) vbox.setContentsMargins(0, 0, 0, 0) vbox.addWidget(explorer) hbox = QHBoxLayout() hbox.setContentsMargins(0, 0, 0, 0) self.labelText = "Ln: %s, Col: %s" self.labelCursorPosition = QLabel(self.trUtf8(self.labelText % (0, 0))) hbox.addWidget(self.labelCursorPosition) self.combo = QComboBox() ui_tools.ComboBoxButton(self.combo, self.combo.clear, self.style().standardPixmap(self.style().SP_TrashIcon)) self.combo.setToolTip( self.trUtf8( "Select the item from the Paste " "Historial list.\nYou can Copy items into this list with: " "%s\nor Paste them using: %s" % ( resources.get_shortcut("History-Copy").toString(QKeySequence.NativeText), resources.get_shortcut("History-Paste").toString(QKeySequence.NativeText), ) ) ) self.combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) hbox.addWidget(self.combo) vbox.addLayout(hbox) def update_line_col(self, line, col): self.labelCursorPosition.setText(self.trUtf8(self.labelText % (line, col))) def add_new_copy(self, copy): self.combo.insertItem(0, copy) self.combo.setCurrentIndex(0) if self.combo.count() > settings.COPY_HISTORY_BUFFER: self.combo.removeItem(self.combo.count() - 1) def get_paste(self): return self.combo.currentText()
class WCSWindow(QtGui.QWidget): def __init__(self): super(WCSWindow, self).__init__() self.initUI() def initUI(self): self.resize(800, 600) self.center() self.setWindowTitle('Center') tablemodel = CoverageTableModel(my_array, self) self.tableview = QTableView() self.tableview.setModel(tablemodel) layout = QVBoxLayout(self) layout.addWidget(self.tableview) self.setLayout(layout) self.show() self.tableview.doubleClicked.connect(self.coverageDoubleClick) self.combobox = QComboBox() self.combobox.addItem("AAAAA") self.combobox.addItem("BBBBB") layout.addWidget(self.combobox) self.combobox.activated.connect(self.changedCombo) def coverageDoubleClick(self, mi): row = mi.row() col = mi.column() print(row, col) def changedCombo(self, ob): print(self.combobox.currentText()) def center(self): qr = self.frameGeometry() cp = QtGui.QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft())
class General(preferences.Group): def __init__(self, page): super(General, self).__init__(page) grid = QGridLayout() self.setLayout(grid) self.langLabel = QLabel() self.lang = QComboBox(currentIndexChanged=self.changed) grid.addWidget(self.langLabel, 0, 0) grid.addWidget(self.lang, 0, 1) self.styleLabel = QLabel() self.styleCombo = QComboBox(currentIndexChanged=self.changed) grid.addWidget(self.styleLabel, 1, 0) grid.addWidget(self.styleCombo, 1, 1) self.systemIcons = QCheckBox(toggled=self.changed) grid.addWidget(self.systemIcons, 2, 0, 1, 3) self.tabsClosable = QCheckBox(toggled=self.changed) grid.addWidget(self.tabsClosable, 3, 0, 1, 3) self.splashScreen = QCheckBox(toggled=self.changed) grid.addWidget(self.splashScreen, 4, 0, 1, 3) self.allowRemote = QCheckBox(toggled=self.changed) grid.addWidget(self.allowRemote, 5, 0, 1, 3) grid.setColumnStretch(2, 1) # fill in the language combo self._langs = ["C", ""] self.lang.addItems(('', '')) langnames = [(language_names.languageName(lang, lang), lang) for lang in po.available()] langnames.sort() for name, lang in langnames: self._langs.append(lang) self.lang.addItem(name) # fill in style combo self.styleCombo.addItem('') self.styleCombo.addItems(QStyleFactory.keys()) app.translateUI(self) def loadSettings(self): s = QSettings() lang = s.value("language", "", type("")) try: index = self._langs.index(lang) except ValueError: index = 1 self.lang.setCurrentIndex(index) style = s.value("guistyle", "", type("")).lower() styles = [name.lower() for name in QStyleFactory.keys()] try: index = styles.index(style) + 1 except ValueError: index = 0 self.styleCombo.setCurrentIndex(index) self.systemIcons.setChecked(s.value("system_icons", True, bool)) self.tabsClosable.setChecked(s.value("tabs_closable", True, bool)) self.splashScreen.setChecked(s.value("splash_screen", True, bool)) self.allowRemote.setChecked(remote.enabled()) def saveSettings(self): s = QSettings() s.setValue("language", self._langs[self.lang.currentIndex()]) s.setValue("system_icons", self.systemIcons.isChecked()) s.setValue("tabs_closable", self.tabsClosable.isChecked()) s.setValue("splash_screen", self.splashScreen.isChecked()) s.setValue("allow_remote", self.allowRemote.isChecked()) if self.styleCombo.currentIndex() == 0: s.remove("guistyle") else: s.setValue("guistyle", self.styleCombo.currentText()) def translateUI(self): self.setTitle(_("General Preferences")) self.langLabel.setText(_("Language:")) self.lang.setItemText(0, _("No Translation")) self.lang.setItemText(1, _("System Default Language (if available)")) self.styleLabel.setText(_("Style:")) self.styleCombo.setItemText(0, _("Default")) self.systemIcons.setText(_("Use System Icons")) self.systemIcons.setToolTip(_( "If checked, icons of the desktop icon theme " "will be used instead of the bundled icons.\n" "This setting takes effect on the next start of {appname}.").format(appname=appinfo.appname)) self.splashScreen.setText(_("Show Splash Screen on Startup")) self.tabsClosable.setText(_("Show Close Button on Document tabs")) self.allowRemote.setText(_("Open Files in Running Instance")) self.allowRemote.setToolTip(_( "If checked, files will be opened in a running Frescobaldi " "application if available, instead of starting a new instance."))
class SphereWidget(QWidget): """ Widget for editing sphere's parameters """ signalObjetChanged = pyqtSignal(SphereParam, name='signal_objet_changed') def __init__(self, parent=None, param=None): super(SphereWidget, self).__init__(parent) if param is None: self.param = SphereParam() else: self.param = param gbC_lay = QVBoxLayout() l_cmap = QLabel("Cmap ") self.cmap = list(get_colormaps().keys()) self.combo = QComboBox(self) self.combo.addItems(self.cmap) self.combo.currentIndexChanged.connect(self.updateParam) self.param.dict["colormap"] = self.cmap[0] hbox = QHBoxLayout() hbox.addWidget(l_cmap) hbox.addWidget(self.combo) gbC_lay.addLayout(hbox) self.sp = [] # subdiv lL = QLabel("subdiv") self.sp.append(QSpinBox()) self.sp[-1].setMinimum(0) self.sp[-1].setMaximum(6) self.sp[-1].setValue(self.param.dict["subdiv"]) # Layout hbox = QHBoxLayout() hbox.addWidget(lL) hbox.addWidget(self.sp[-1]) gbC_lay.addLayout(hbox) # signal's self.sp[-1].valueChanged.connect(self.updateParam) # Banded self.gbBand = QGroupBox(u"Banded") self.gbBand.setCheckable(True) hbox = QGridLayout() lL = QLabel("nbr band", self.gbBand) self.sp.append(QSpinBox(self.gbBand)) self.sp[-1].setMinimum(0) self.sp[-1].setMaximum(100) # Layout hbox = QHBoxLayout() hbox.addWidget(lL) hbox.addWidget(self.sp[-1]) self.gbBand.setLayout(hbox) gbC_lay.addWidget(self.gbBand) # signal's self.sp[-1].valueChanged.connect(self.updateParam) self.gbBand.toggled.connect(self.updateParam) gbC_lay.addStretch(1.0) hbox = QHBoxLayout() hbox.addLayout(gbC_lay) self.setLayout(hbox) self.updateMenu() def updateParam(self, option): """ update param and emit a signal """ tab = ["subdiv", "nbr_band"] for pos, name in enumerate(tab): self.param.dict[name] = self.sp[pos].value() self.param.dict["banded"] = self.gbBand.isChecked() self.param.dict["colormap"] = self.combo.currentText() # emit signal self.signalObjetChanged.emit(self.param) def updateMenu(self, param=None): """ Update menus """ if param is not None: self.param = param # Lock signals self.blockSignals(True) for wid in self.sp: wid.blockSignals(True) tab = ["subdiv", "nbr_band"] for pos, name in enumerate(tab): self.sp[pos].setValue(self.param.dict[name]) self.gbBand.setChecked(self.param.dict["banded"]) # unlock signals self.blockSignals(False) for wid in self.sp: wid.blockSignals(False) self.signalObjetChanged.emit(self.param)
class AddAgentDialog(QtHelper.EnhancedQDialog, Logger.ClassLogger): """ Add agent dialog """ def __init__(self, parent, agentName='AGENT', datasetView=False): """ Constructor @param parent: parent window @type parent: instance @param agentName: @type agentName: string @param datasetView: @type datasetView: boolean """ super(AddAgentDialog, self).__init__(parent) self.agentName=agentName self.parent__ = parent self.datasetView__ = datasetView self.createDialog() self.createConnections() self.initComboType() def createDialog (self): """ Create dialog """ self.labelName = QLabel("Agent Name:") self.nameEdit = QLineEdit(self.agentName) nameLayout = QHBoxLayout() nameLayout.addWidget( self.labelName ) nameLayout.addWidget( self.nameEdit ) self.labelDescr = QLabel("Description:") self.descrEdit = QTextEdit() self.labelValue= QLabel("Value:") self.comboValue = QComboBox() typeLayout = QHBoxLayout() typeLayout.addWidget( self.labelValue ) typeLayout.addWidget( self.comboValue ) self.labelType = QLabel("Type:") self.typeEdit = QLineEdit() self.typeEdit.setEnabled(False) type2Layout = QHBoxLayout() type2Layout.addWidget( self.labelType ) type2Layout.addWidget( self.typeEdit ) 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 = QVBoxLayout() mainLayout.addLayout(nameLayout) if not self.datasetView__: mainLayout.addLayout(typeLayout) mainLayout.addLayout(type2Layout) mainLayout.addWidget(self.labelDescr) mainLayout.addWidget(self.descrEdit) mainLayout.addWidget(self.buttonBox) self.setLayout(mainLayout) self.setWindowTitle("Test Config > Add agent") self.resize(350, 250) self.center() def initComboType(self): """ Initialize the combobox type with running agents """ TYPES_PARAM = ServerAgents.instance().getRunningAgentsComplete() for i in xrange(len(TYPES_PARAM)): if len(TYPES_PARAM[i]) == 0: self.comboValue.insertSeparator(i + 2) else: self.comboValue.addItem (TYPES_PARAM[i]['name']) #self.onAgentChanged(id=0) def createConnections (self): """ Create qt connections """ self.buttonBox.accepted.connect(self.onAdd) self.buttonBox.rejected.connect(self.reject) self.comboValue.currentIndexChanged.connect(self.onAgentChanged) def onAgentChanged(self, id): """ Called on agent changed on combobox """ currentAgent = self.comboValue.currentText() currentAgent = unicode(currentAgent) currentAgentType = '' for agt in ServerAgents.instance().getRunningAgentsComplete(): if unicode(agt['name']) == currentAgent: currentAgentType = unicode(agt['type'].lower()) break self.typeEdit.setText(currentAgentType) def onAdd(self): """ Called on add """ if sys.version_info > (3,): # python3 support if unicode(self.nameEdit.text().upper()): self.accept() else: if unicode(self.nameEdit.text().toUpper()): self.accept() def getParameterValue(self): """ Returns parameter value """ qvalue = self.comboValue.currentText() if sys.version_info > (3,): # python3 support nameUpper = unicode(self.nameEdit.text().upper()) else: nameUpper = unicode(self.nameEdit.text().toUpper()) r = { 'name': nameUpper, 'description': unicode(self.descrEdit.toPlainText()), 'value': unicode(qvalue), 'type': unicode(self.typeEdit.text()) } return r
class WFramework(QWidget, Logger.ClassLogger): """ Framework widget """ # action, description, misc, parameters AddStep = pyqtSignal(str, str, str, dict) UpdateStep = pyqtSignal(str, str, str, dict) CancelEdit = pyqtSignal() def __init__(self, parent): """ Constructor """ QWidget.__init__(self) self.createActions() self.createWidgets() self.createToolbar() self.createConnections() def createActions(self): """ Create qt actions """ self.addAction = QPushButton(QIcon(":/add_black.png"), '&Add Action', self) self.addAction.setMinimumHeight(40) self.addAction.setMaximumWidth(200) self.cancelAction = QtHelper.createAction(self, "&Cancel", self.cancelStep, icon=QIcon(":/undo.png"), tip = 'Cancel update') self.cancelAction.setEnabled(False) self.optionsAction = QtHelper.createAction(self, "&", self.openOptions, icon=QIcon(":/recorder-basic-small.png"), tip = 'Framework options') def openOptions(self): """ Open options dialog """ if self.optionsDialog.exec_() == QDialog.Accepted: pass def createWidgets(self): """ Create all qt widgets """ self.optionsDialog = OptionsDialog(self) self.validatorUpper = ValidatorUpper(self) self.validatorAll = ValidatorAll(self) self.validatorInt = QIntValidator(self) font = QFont() font.setBold(True) self.actionsComboBox = QComboBox(self) self.actionsComboBox.setMinimumHeight(40) for i in xrange(len(GuiSteps.ACTION_FRAMEWORK_DESCR)): if not len( GuiSteps.ACTION_FRAMEWORK_DESCR[i] ): self.actionsComboBox.insertSeparator(i+1) else: el = GuiSteps.ACTION_FRAMEWORK_DESCR[i].keys() self.actionsComboBox.addItem( list(el)[0] ) self.labelActionDescr = QLabel(self) self.labelActionDescr.setText( "%s\n" % GuiSteps.ACTION_FRAMEWORK_DESCR[0][GuiSteps.FRAMEWORK_INFO]) self.labelActionDescr.setWordWrap(True) self.labelActionDescr.hide() self.descriptionLine = QLineEdit(self) self.descriptionLine.hide() actionLayout2 = QGridLayout() self.createWidgetGetText() self.createWidgetGetWait() self.createWidgetCacheSet() self.createWidgetCheckString() self.createWidgetGetAsk() actionLayout2.addWidget( self.setCacheGroup , 0, 0) actionLayout2.addWidget( self.getCheckGroup , 1, 0) actionLayout2.addWidget( self.getTextGroup , 2, 0) actionLayout2.addWidget( self.getWaitGroup , 3, 0) actionLayout2.addWidget( self.getAskGroup , 4, 0) labelAct = QLabel( self.tr("Action: ") ) labelAct.setFont( font) self.arrowLabel = QLabel("") self.arrowLabel.setPixmap(QPixmap(":/arrow-right.png").scaledToWidth(32)) self.arrowLabel2 = QLabel("") self.arrowLabel2.setPixmap(QPixmap(":/arrow-right.png").scaledToWidth(32)) layoutFinal = QHBoxLayout() layoutFinal.addWidget( labelAct ) layoutFinal.addWidget(self.actionsComboBox) layoutFinal.addWidget( self.arrowLabel ) layoutFinal.addLayout( actionLayout2 ) layoutFinal.addWidget( self.arrowLabel2 ) layoutFinal.addWidget(self.addAction) layoutFinal.addStretch(1) self.setLayout(layoutFinal) def createToolbar(self): """ Create toolbar """ pass def createWidgetCheckString(self): """ Create widget to check string """ self.getCheckGroup = QGroupBox(self.tr("")) # check in ? self.checkInTextLine = QLineEdit(self) self.checkInTextLine.setMinimumWidth(300) self.checkInTextCombo = QComboBox(self) self.checkInTextCombo.addItems( [ "CACHE" ] ) # operator self.checkComboBox = QComboBox(self) self.checkComboBox.addItems( [ GuiSteps.OP_CONTAINS, GuiSteps.OP_NOTCONTAINS, GuiSteps.OP_REGEXP, GuiSteps.OP_NOTREGEXP, GuiSteps.OP_STARTSWITH, GuiSteps.OP_NOTSTARTSWITH, GuiSteps.OP_ENDSWITH, GuiSteps.OP_NOTENDSWITH ] ) # check what ? self.checkOutTextLine = QLineEdit(self) self.checkOutTextLine.setMinimumWidth(300) self.checkOutTextCombo = QComboBox(self) self.checkOutTextCombo.addItems( LIST_TYPES ) # final layout mainChecklayout = QGridLayout() mainChecklayout.addWidget( QLabel( self.tr("Checking from:") ), 0, 0 ) mainChecklayout.addWidget( self.checkInTextCombo, 0, 1 ) mainChecklayout.addWidget( self.checkInTextLine, 0, 2 ) mainChecklayout.addWidget( QLabel( self.tr("If:") ), 1, 0 ) mainChecklayout.addWidget( self.checkComboBox, 1, 1 ) mainChecklayout.addWidget( QLabel( self.tr("The Value:") ), 2, 0 ) mainChecklayout.addWidget( self.checkOutTextCombo, 2, 1 ) mainChecklayout.addWidget( self.checkOutTextLine, 2, 2 ) self.getCheckGroup.setLayout(mainChecklayout) self.getCheckGroup.hide() def createWidgetGetText(self): """ Create text widget """ self.getTextGroup = QGroupBox(self.tr("")) self.basicTextLine = QLineEdit(self) self.basicTextLine.setMinimumWidth(300) self.basicTextCombo = QComboBox(self) self.basicTextCombo.addItems( LIST_TYPES ) mainTextlayout = QGridLayout() mainTextlayout.addWidget( QLabel( self.tr("Value:") ), 0, 0 ) mainTextlayout.addWidget( self.basicTextCombo, 0, 1 ) mainTextlayout.addWidget( self.basicTextLine, 0, 2 ) self.getTextGroup.setLayout(mainTextlayout) def createWidgetGetAsk(self): """ Create ask widget """ # ask self.getAskGroup = QGroupBox(self.tr("")) self.askTextLine = QLineEdit(self) self.askTextLine.setMinimumWidth(300) self.askTextCombo = QComboBox(self) self.askTextCombo.addItems( LIST_TYPES ) self.askTextCacheLine = QLineEdit(self) self.askTextCacheLine.setMinimumWidth(300) self.askTextCacheCombo = QComboBox(self) self.askTextCacheCombo.addItems( [ "CACHE" ] ) mainAsklayout = QGridLayout() mainAsklayout.addWidget( QLabel( self.tr("User input prompt:") ), 0, 0 ) mainAsklayout.addWidget( self.askTextCombo, 0, 1 ) mainAsklayout.addWidget( self.askTextLine, 0, 2 ) mainAsklayout.addWidget( QLabel( self.tr("And save response in:") ), 1, 0 ) mainAsklayout.addWidget( self.askTextCacheCombo, 1, 1 ) mainAsklayout.addWidget( self.askTextCacheLine, 1, 2 ) self.getAskGroup.setLayout(mainAsklayout) self.getAskGroup.hide() def createWidgetGetWait(self): """ Create wait text widget """ self.getWaitGroup = QGroupBox(self.tr("")) self.valueWaitLine = QLineEdit(self) self.valueWaitLine.setMinimumWidth(300) self.valueWaitLine.setValidator(self.validatorInt) self.valueWaitCombo = QComboBox(self) self.valueWaitCombo.addItems( LIST_TYPES ) mainTextlayout = QGridLayout() mainTextlayout.addWidget( QLabel( self.tr("Value (in seconds):") ), 0, 0 ) mainTextlayout.addWidget( self.valueWaitCombo, 0, 1 ) mainTextlayout.addWidget( self.valueWaitLine, 0, 2 ) self.getWaitGroup.setLayout(mainTextlayout) self.getWaitGroup.hide() def createWidgetCacheSet(self): """ Create cache widget """ self.setCacheGroup = QGroupBox(self.tr("")) setCacheLayout = QGridLayout() self.cacheKeyName = QLineEdit(self) self.cacheKeyName.setMinimumWidth(300) setCacheLayout.addWidget( QLabel( self.tr("Key name:") ) , 0, 1) setCacheLayout.addWidget( self.cacheKeyName , 0, 2) self.setCacheGroup.setLayout(setCacheLayout) self.setCacheGroup.hide() def createConnections(self): """ Createa qt connections """ self.actionsComboBox.currentIndexChanged.connect(self.onActionChanged) self.addAction.clicked.connect(self.addStep) self.basicTextCombo.currentIndexChanged.connect(self.onBasicTextTypeChanged) self.valueWaitCombo.currentIndexChanged.connect(self.onValueWaitTypeChanged) self.checkOutTextCombo.currentIndexChanged.connect(self.onCheckOutTextTypeChanged) self.askTextCombo.currentIndexChanged.connect(self.onAskTextTypeChanged) def onAskTextTypeChanged(self): """ On ask type changed """ if self.askTextCombo.currentText() in [ "TEXT", "CACHE" ]: self.askTextLine.setValidator(self.validatorAll) if self.askTextCombo.currentText() == "ALIAS": self.askTextLine.setText( self.askTextLine.text().upper() ) self.askTextLine.setValidator(self.validatorUpper) def onCheckOutTextTypeChanged(self): """ On check out type changed """ if self.checkOutTextCombo.currentText() in [ "TEXT", "CACHE" ]: self.checkOutTextLine.setValidator(self.validatorAll) if self.checkOutTextCombo.currentText() == "ALIAS": self.checkOutTextLine.setText( self.checkOutTextLine.text().upper() ) self.checkOutTextLine.setValidator(self.validatorUpper) def onValueWaitTypeChanged(self): """ On value wait changed """ if self.valueWaitCombo.currentText() in [ "TEXT" ]: self.valueWaitLine.setText( "0" ) self.valueWaitLine.setValidator(self.validatorInt) if self.valueWaitCombo.currentText() in [ "CACHE" ]: self.valueWaitLine.setValidator(self.validatorAll) if self.valueWaitCombo.currentText() == "ALIAS": self.valueWaitLine.setText( self.valueWaitLine.text().upper() ) self.valueWaitLine.setValidator(self.validatorUpper) def onBasicTextTypeChanged(self): """ On basic text changed """ if self.basicTextCombo.currentText() in [ "TEXT", "CACHE" ]: self.basicTextLine.setValidator(self.validatorAll) if self.basicTextCombo.currentText() == "ALIAS": self.basicTextLine.setText( self.basicTextLine.text().upper() ) self.basicTextLine.setValidator(self.validatorUpper) def pluginDataAccessor(self): """ Return data for plugins """ return { "data": "" } def onPluginImport(self, dataJson): """ On call from plugin """ pass def onRadioAskChanged(self, button): """ On radio ask changed """ if button.text() == 'From alias parameter': self.askTextLine.setText( self.askTextLine.text().upper() ) self.askTextLine.setValidator(self.validAskUpper) else: self.askTextLine.setValidator(self.validAskAll) def onActionChanged(self): """ On action changed """ descr = 'No description available!' i = 0 for el in GuiSteps.ACTION_FRAMEWORK_DESCR: if isinstance(el, dict): if self.actionsComboBox.currentText() in el: descr = GuiSteps.ACTION_FRAMEWORK_DESCR[i][self.actionsComboBox.currentText()] break i += 1 self.labelActionDescr.setText( "%s\n" % descr ) if self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_INFO, GuiSteps.FRAMEWORK_WARNING ]: self.getTextGroup.show() self.getWaitGroup.hide() self.setCacheGroup.hide() self.getCheckGroup.hide() self.getAskGroup.hide() self.arrowLabel.show() self.arrowLabel2.show() elif self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_WAIT ]: self.getWaitGroup.show() self.getTextGroup.hide() self.setCacheGroup.hide() self.getCheckGroup.hide() self.getAskGroup.hide() self.arrowLabel.show() self.arrowLabel2.show() elif self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_CACHE_SET ]: self.getTextGroup.show() self.getWaitGroup.hide() self.setCacheGroup.show() self.getCheckGroup.hide() self.getAskGroup.hide() self.arrowLabel.show() self.arrowLabel2.show() elif self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_CHECK_STRING ]: self.getCheckGroup.show() self.getTextGroup.hide() self.getWaitGroup.hide() self.setCacheGroup.hide() self.getAskGroup.hide() self.arrowLabel.show() self.arrowLabel2.show() elif self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_INTERACT ]: self.getCheckGroup.hide() self.getTextGroup.hide() self.getWaitGroup.hide() self.setCacheGroup.hide() self.getAskGroup.show() self.arrowLabel.show() self.arrowLabel2.show() elif self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_USERCODE, GuiSteps.FRAMEWORK_CACHE_RESET ]: self.getCheckGroup.hide() self.getTextGroup.hide() self.getWaitGroup.hide() self.setCacheGroup.hide() self.getAskGroup.hide() self.arrowLabel.hide() self.arrowLabel2.show() else: self.getTextGroup.hide() self.getWaitGroup.hide() self.setCacheGroup.hide() self.getCheckGroup.hide() self.getAskGroup.hide() self.arrowLabel.hide() self.arrowLabel2.hide() def addStep(self): """ Add step """ action = self.actionsComboBox.currentText() descr = self.descriptionLine.text() descr = unicode(descr).replace('"', '') signal = self.AddStep if self.cancelAction.isEnabled(): signal = self.UpdateStep if action in [ GuiSteps.FRAMEWORK_INFO, GuiSteps.FRAMEWORK_WARNING ]: fromCache = False if self.basicTextCombo.currentText() == "CACHE": fromCache = True fromAlias = False if self.basicTextCombo.currentText() == "ALIAS": fromAlias = True newText = self.basicTextLine.text() if not len(newText): QMessageBox.warning(self, "Assistant" , "Please to set a value!") else: parameters = { 'text': newText, 'from-cache': fromCache, 'from-alias': fromAlias } signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters ) elif action in [ GuiSteps.FRAMEWORK_INTERACT ]: # read text from cache, alias or not ? fromCache = False if self.askTextCombo.currentText() == "CACHE": fromCache = True fromAlias = False if self.askTextCombo.currentText() == "ALIAS": fromAlias = True askText = self.askTextLine.text() if not len(askText): QMessageBox.warning(self, "Assistant" , "Please to set question to ask!") else: saveAskText = self.askTextCacheLine.text() if not len(saveAskText): QMessageBox.warning(self, "Assistant" , "Please to set key destination cache!") else: parameters = { 'key': saveAskText, 'value': askText, 'from-cache': fromCache, 'from-alias': fromAlias } signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters ) elif action in [ GuiSteps.FRAMEWORK_CHECK_STRING ]: fromCache = False if self.checkOutTextCombo.currentText() == "CACHE": fromCache = True fromAlias = False if self.checkOutTextCombo.currentText() == "ALIAS": fromAlias = True inText = self.checkInTextLine.text() if not len(inText): QMessageBox.warning(self, "Assistant" , "Please to set a cache key value!") else: outText = self.checkOutTextLine.text() if not len(outText): QMessageBox.warning(self, "Assistant" , "Please to set a value!") else: op = self.checkComboBox.currentText() parameters = { 'key': inText, 'value': outText, 'from-cache': fromCache, 'from-alias': fromAlias, "operator": op } signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters ) elif action in [ GuiSteps.FRAMEWORK_WAIT ]: fromCache = False if self.valueWaitCombo.currentText() == "CACHE": fromCache = True fromAlias = False if self.valueWaitCombo.currentText() == "ALIAS": fromAlias = True miscStr = self.valueWaitLine.text() if not len(miscStr): QMessageBox.warning(self, "Assistant" , "Please to set a value!") else: parameters = {'from-cache': fromCache, 'from-alias': fromAlias} signal.emit( str(action), unicode(descr), miscStr, parameters ) elif action in [ GuiSteps.FRAMEWORK_CACHE_SET ]: fromCache = False if self.basicTextCombo.currentText() == "CACHE": fromCache = True fromAlias = False if self.basicTextCombo.currentText() == "ALIAS": fromAlias = True newText = self.basicTextLine.text() if not len(newText): QMessageBox.warning(self, "Assistant" , "Please to set a text value!") else: miscStr = self.cacheKeyName.text() if not len(miscStr): QMessageBox.warning(self, "Assistant" , "Please to set a key name!") else: parameters = { 'key': miscStr, 'value': newText, 'from-cache': fromCache, 'from-alias': fromAlias } signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters ) else: signal.emit( str(action), unicode(descr), EMPTY_VALUE, {} ) def cancelStep(self): """ Cancel step """ self.addAction.setText( "&Add" ) buttonFont = QFont() buttonFont.setBold(False) self.addAction.setFont(buttonFont) self.cancelAction.setEnabled(False) self.CancelEdit.emit() def finalizeUpdate(self): """ Finalize update """ self.addAction.setText( "&Add Action" ) buttonFont = QFont() buttonFont.setBold(False) self.addAction.setFont(buttonFont) self.cancelAction.setEnabled(False) def editStep(self, stepData): """ Edit step """ self.addAction.setText( "&Update" ) buttonFont = QFont() buttonFont.setBold(True) self.addAction.setFont(buttonFont) self.cancelAction.setEnabled(True) # set the current value for actions combo for i in xrange(self.actionsComboBox.count()): item_text = self.actionsComboBox.itemText(i) if unicode(stepData["action"]) == unicode(item_text): self.actionsComboBox.setCurrentIndex(i) break # and then refresh options self.onActionChanged() # finally fill all fields self.descriptionLine.setText( stepData["description"] ) if self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_INFO, GuiSteps.FRAMEWORK_WARNING ] : self.basicTextLine.setText ( stepData["parameters"]["text"] ) if stepData["parameters"]["from-cache"]: self.basicTextLine.setValidator(self.validatorAll) self.basicTextCombo.setCurrentIndex(INDEX_CACHE) elif stepData["parameters"]["from-alias"]: self.basicTextLine.setValidator(self.validatorUpper) self.basicTextCombo.setCurrentIndex(INDEX_ALIAS) else: self.basicTextLine.setValidator(self.validatorAll) self.basicTextCombo.setCurrentIndex(INDEX_TEXT) if self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_WAIT ]: self.valueWaitLine.setText ( stepData["misc"] ) if stepData["parameters"]["from-cache"]: self.valueWaitLine.setValidator(self.validatorAll) self.valueWaitCombo.setCurrentIndex(INDEX_CACHE) elif stepData["parameters"]["from-alias"]: self.valueWaitLine.setValidator(self.validatorUpper) self.valueWaitCombo.setCurrentIndex(INDEX_ALIAS) else: self.valueWaitLine.setValidator(self.validatorInt) self.valueWaitCombo.setCurrentIndex(INDEX_TEXT) if self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_CACHE_SET ]: self.basicTextLine.setText ( stepData["parameters"]["value"] ) if stepData["parameters"]["from-cache"]: self.basicTextLine.setValidator(self.validatorAll) self.basicTextCombo.setCurrentIndex(INDEX_CACHE) elif stepData["parameters"]["from-alias"]: self.basicTextLine.setValidator(self.validatorUpper) self.basicTextCombo.setCurrentIndex(INDEX_ALIAS) else: self.basicTextLine.setValidator(self.validatorAll) self.basicTextCombo.setCurrentIndex(INDEX_TEXT) self.cacheKeyName.setText( stepData["parameters"]["key"] ) if self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_CHECK_STRING ]: self.checkOutTextLine.setText ( stepData["parameters"]["value"] ) if stepData["parameters"]["from-cache"]: self.checkOutTextLine.setValidator(self.validatorAll) self.checkOutTextCombo.setCurrentIndex(INDEX_CACHE) elif stepData["parameters"]["from-alias"]: self.checkOutTextLine.setValidator(self.validatorUpper) self.checkOutTextCombo.setCurrentIndex(INDEX_ALIAS) else: self.checkOutTextLine.setValidator(self.validatorAll) self.checkOutTextCombo.setCurrentIndex(INDEX_TEXT) self.checkInTextLine.setText ( stepData["parameters"]["key"] ) for i in xrange(self.checkComboBox.count()): item_text = self.checkComboBox.itemText(i) if unicode(stepData["parameters"]["operator"]) == unicode(item_text): self.checkComboBox.setCurrentIndex(i) break if self.actionsComboBox.currentText() in [ GuiSteps.FRAMEWORK_INTERACT ]: self.askTextLine.setText ( stepData["parameters"]["value"] ) if stepData["parameters"]["from-cache"]: self.askTextLine.setValidator(self.validatorAll) self.askTextCombo.setCurrentIndex(INDEX_CACHE) elif stepData["parameters"]["from-alias"]: self.askTextLine.setValidator(self.validatorUpper) self.askTextCombo.setCurrentIndex(INDEX_ALIAS) else: self.askTextLine.setValidator(self.validatorAll) self.askTextCombo.setCurrentIndex(INDEX_TEXT) self.askTextCacheLine.setText ( stepData["parameters"]["key"] ) def getTimeout(self): """ Return timeout """ return self.optionsDialog.timeoutLine.text() def setTimeout(self, timeout): """ Set the timeout """ return self.optionsDialog.timeoutLine.setText(timeout)
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 ValidatedDialog(QDialog): """ A dialog for creating a validated new value. Performs validation of name against a provided. Can be used to select from the list or for creating a new value that is not on the list. """ INVALID_COLOR = QColor(255, 235, 235) def __init__(self, title = "Title", description = "Description", unique_names = None, choose_from_list=False): QDialog.__init__(self) self.setModal(True) self.setWindowTitle(title) # self.setMinimumWidth(250) # self.setMinimumHeight(150) if unique_names is None: unique_names = [] self.unique_names = unique_names self.choose_from_list = choose_from_list self.layout = QFormLayout() self.layout.setSizeConstraint(QLayout.SetFixedSize) label = QLabel(description) label.setAlignment(Qt.AlignHCenter) self.layout.addRow(self.createSpace(5)) self.layout.addRow(label) self.layout.addRow(self.createSpace(10)) buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self) self.ok_button = buttons.button(QDialogButtonBox.Ok) self.ok_button.setEnabled(False) if choose_from_list: self.param_name_combo = QComboBox() self.connect(self.param_name_combo, SIGNAL('currentIndexChanged(QString)'), self.validateChoice) for item in unique_names: self.param_name_combo.addItem(item) self.layout.addRow("Job:", self.param_name_combo) else: self.param_name = QLineEdit(self) self.param_name.setFocus() self.connect(self.param_name, SIGNAL('textChanged(QString)'), self.validateName) self.validColor = self.param_name.palette().color(self.param_name.backgroundRole()) self.layout.addRow("Name:", self.param_name) self.layout.addRow(self.createSpace(10)) self.layout.addRow(buttons) self.connect(buttons, SIGNAL('accepted()'), self.accept) self.connect(buttons, SIGNAL('rejected()'), self.reject) self.setLayout(self.layout) def notValid(self, msg): """Called when the name is not valid.""" self.ok_button.setEnabled(False) palette = self.param_name.palette() palette.setColor(self.param_name.backgroundRole(), self.INVALID_COLOR) self.param_name.setToolTip(msg) self.param_name.setPalette(palette) def valid(self): """Called when the name is valid.""" self.ok_button.setEnabled(True) palette = self.param_name.palette() palette.setColor(self.param_name.backgroundRole(), self.validColor) self.param_name.setToolTip("") self.param_name.setPalette(palette) def validateName(self, value): """Called to perform validation of a name. For specific needs override this function and call valid() and notValid(msg).""" value = str(value) if value == "": self.notValid("Can not be empty!") elif not value.find(" ") == -1: self.notValid("No spaces allowed!") elif value in self.unique_names: self.notValid("Name must be unique!") else: self.valid() def validateChoice(self, choice): """Only called when using selection mode.""" self.ok_button.setEnabled(not choice == "") def getName(self): """Return the new name chosen by the user""" if self.choose_from_list: return str(self.param_name_combo.currentText()) else: return str(self.param_name.text()) def showAndTell(self): """Shows the dialog and returns the result""" if self.exec_(): return str(self.getName()).strip() return "" def createSpace(self, size = 5): """Creates a widget that can be used as spacing on a panel.""" qw = QWidget() qw.setMinimumSize(QSize(size, size)) return qw
class AwindowMotherFucker(QtGui.QMainWindow): " A Window M**********r ! " def __init__(self): " Initialize the Class " QtGui.QWidget.__init__(self) # Main Window initial Geometry self.setGeometry(100, 100, 640, 400) # Main Window initial Title self.setWindowTitle('CMYK2RGB') # Main Window Minimum Size self.setMinimumSize(640, 350) # Main Window Maximum Size self.setMaximumSize(800, 480) # Main Window initial StatusBar Message self.statusBar().showMessage('CMYK2RGB (Grafica Libre Tool)') # Main Window initial ToolTip self.setToolTip('Grafica Libre Tools for Ubuntu') # Main Window initial Font type self.setFont(QtGui.QFont('Ubuntu Light', 10)) # Main Window Icon self.setWindowIcon(QtGui.QIcon('.icon.svg')) # Tux image decoration, a QLabel with a QPixmap inside self.label = QLabel(self) pixmap = QPixmap('.icon.svg') self.label.setPixmap(pixmap) self.label.setGeometry(405, 12, 300, 300) # this always gives the current user Home Folder, cross-platform homedir = os.path.expanduser("~") # this is the supported file extensions y *.* wildcard extensions = ';;'.join(['(*%s)' % e for e in ['.psd', '.icc', '']]) # print homedir and extensions variables for debug print(' INFO: My Home is ' + homedir + ',im using: ' + str(extensions)) # Menu Bar inicialization and detail definitions menu_salir = QtGui.QAction(QtGui.QIcon.fromTheme("application-exit"), 'Quit | Salir', self) menu_salir.setShortcut('Ctrl+Q') menu_salir.setStatusTip('Menu Salir') self.connect(menu_salir, QtCore.SIGNAL('triggered()'), QtGui.qApp, QtCore.SLOT('quit()')) # about self menu_self = QtGui.QAction(QtGui.QIcon.fromTheme("help-contents"), 'About | Acerca de', self) menu_self.setStatusTip('About self') self.connect(menu_self, QtCore.SIGNAL('triggered()'), lambda: QMessageBox.about(self, ' CMYK2RGB ', unicode(__doc__ + ',\nversion ' + __version__ + '(' + __license__ + '),\n by ' + __author__ + ', ( ' + __email__ + ' ). \n\n ' + 'This program takes proprietary closed canned files\n ' + 'and produce libre open files, and other magics !; \n' + 'nothing but Pure, Clean, Open Source Software!.\n\n' + 'Built for Grafica Libre + Ubuntu-AR community...'))) # about Qt menu_qt = QtGui.QAction(QtGui.QIcon.fromTheme("help-contents"), 'About Qt | Acerca de Qt', self) menu_qt.setStatusTip('About Qt') self.connect(menu_qt, QtCore.SIGNAL('triggered()'), lambda: QMessageBox.aboutQt(self)) # about python menu_py = QtGui.QAction(QtGui.QIcon.fromTheme("help-contents"), 'About Python | Acerca de Python', self) # set the status tip for this menu item menu_py.setStatusTip('About Python...') # set the triggered signal to lambda for online about python self.connect(menu_py, QtCore.SIGNAL('triggered()'), lambda: webbrowser.open_new_tab('http://www.python.org/about')) # get support help menu_support = QtGui.QAction(QtGui.QIcon.fromTheme("help-faq"), 'Get Help Online | Obtener Ayuda en Linea', self) # set the status tip for this menu item menu_support.setStatusTip('Get Help Online...') # set the triggered signal to lambda for online help self.connect(menu_support, QtCore.SIGNAL('triggered()'), lambda: webbrowser.open('mailto:[email protected]')) # qt color setting via qcolordialog menu item menu_color = QtGui.QAction( QtGui.QIcon.fromTheme("preferences-system"), 'Set GUI Colors | Configurar Colores de GUI', self) # set the status tip for this menu item menu_color.setStatusTip('Manually set GUI Colors...') # set the triggered signal to the showQColorDialog self.connect(menu_color, QtCore.SIGNAL('triggered()'), self.showQColorDialog) # theme setting menu_theme = QtGui.QAction(QtGui.QIcon.fromTheme("preferences-system"), 'Use App GUI Skin | Usar Skin de la App', self) # set the status tip for this menu item menu_theme.setStatusTip('Use App GUI Skin...') # set the triggered signal to the applySkin self.connect(menu_theme, QtCore.SIGNAL('triggered()'), self.applySkin) # define the menu menu = self.menuBar() menu.setToolTip('Menu') archivo = menu.addMenu('&Archivo') archivo.addAction(menu_salir) # Settings menu settings = menu.addMenu('&Settings') settings.addAction(menu_color) settings.addAction(menu_theme) # Help menu items jelp = menu.addMenu('&Help') jelp.addAction(menu_support) jelp.addSeparator() jelp.addAction(menu_self) jelp.addAction(menu_qt) jelp.addAction(menu_py) # # Main Input Widgets self.label1 = QtGui.QLabel( 'Elije 2 Archivos .ICC (1 CMYK, 1 RGB) y 1 Archivo .PSD (CMYK)...', self) self.label1.setGeometry(5, 25, 390, 25) self.label1.setAutoFillBackground(True) # this is the QFileDialog to open files using a open file dialog gui self.btn1 = QtGui.QPushButton('Abrir Archivo .ICC CMYK Origen', self) self.btn1.setGeometry(5, 50, 390, 25) self.btn1.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.connect(self.btn1, QtCore.SIGNAL('clicked()'), lambda: open('.cmyk2rgb-cmyk-icc.txt', 'w').write(unicode( QFileDialog.getOpenFileName(self, self.tr("Open File... "), homedir, extensions)))) self.connect(self.btn1, QtCore.SIGNAL('released()'), lambda: self.btn1.setText(open('.cmyk2rgb-cmyk-icc.txt', 'r').read())) # .ICC self.btn2 = QtGui.QPushButton('Abrir Archivo .ICC RGB Destino', self) self.btn2.setGeometry(5, 75, 390, 25) self.btn2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.connect(self.btn2, QtCore.SIGNAL('clicked()'), lambda: open('.cmyk2rgb-rgb-icc.txt', 'w').write(unicode( QFileDialog.getOpenFileName(self, self.tr("Open File... "), homedir, extensions)))) self.connect(self.btn2, QtCore.SIGNAL('released()'), lambda: self.btn2.setText(open('.cmyk2rgb-rgb-icc.txt', 'r').read())) # .PSD self.btn3 = QtGui.QPushButton('Abrir Archivo .PSD CMYK', self) self.btn3.setGeometry(5, 100, 390, 25) self.btn3.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.connect(self.btn3, QtCore.SIGNAL('clicked()'), lambda: open('.cmyk2rgb-cmyk-psd.txt', 'w').write(unicode( QFileDialog.getOpenFileName(self, self.tr("Open File... "), homedir, extensions)))) self.connect(self.btn3, QtCore.SIGNAL('released()'), lambda: self.btn3.setText(open('.cmyk2rgb-cmyk-psd.txt', 'r').read())) # Conversion Intents settings self.label2 = QtGui.QLabel('Intent: ', self) self.label2.setGeometry(535, 25, 100, 25) self.label2.setAutoFillBackground(True) # -intent self.combo1 = QComboBox(self) self.combo1.setGeometry(535, 50, 100, 25) self.combo1.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.combo1.addItems(['relative', 'absolute', 'perceptual', 'saturation']) # Color Depth settings self.label3 = QtGui.QLabel('Depth: ', self) self.label3.setGeometry(535, 75, 100, 25) self.label3.setAutoFillBackground(True) # -depth self.combo2 = QComboBox(self) self.combo2.setGeometry(535, 100, 100, 25) self.combo2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.combo2.addItems(['8', '16', '4', '2']) # Alpha settings self.label4 = QtGui.QLabel('Alpha: ', self) self.label4.setGeometry(535, 125, 100, 25) self.label4.setAutoFillBackground(True) # -alpha self.combo3 = QComboBox(self) self.combo3.setGeometry(535, 150, 100, 25) self.combo3.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.combo3.addItems(['on', 'activate', 'off', 'deactivate', '0', '1', 'opaque', 'copy', 'transparent', 'extract', 'background', 'shape']) # AutoMagical Extras self.label5 = QtGui.QLabel('Magical Extras: ', self) self.label5.setGeometry(535, 175, 100, 25) self.label5.setAutoFillBackground(True) # this enumerates ALL the so called Auto-Magical flag settings self.combo4 = QComboBox(self) self.combo4.setGeometry(535, 200, 100, 25) self.combo4.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.combo4.addItems(['NINGUNO!', 'TODAS JUNTAS?', ' -antialias ', ' -auto-gamma ', ' -auto-level ', ' -clamp ', ' -clip ', ' -despeckle ', ' -fft ', ' -enhance ', ' -equalize ', ' -flip ', ' -flop ', ' -ift ', ' -monochrome ', ' -negate ', ' -trim ', ' -normalize ', ' -transpose ', ' -transverse ', ' -unique-colors ', ' -flatten ', ' -reverse ' ]) # this are the commands to run from the gui self.label6 = QtGui.QLabel( 'Luego, puedes ejecutar alguna de estas Acciones...', self) self.label6.setGeometry(5, 150, 390, 25) self.label6.setAutoFillBackground(True) # LIBERAR PSD CMYK HACIA RGB GIMP self.boton1 = QtGui.QPushButton( 'LIBERAR PSD CMYK HACIA RGB GIMP', self) self.boton1.setGeometry(5, 175, 390, 25) self.boton1.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.connect(self.boton1, QtCore.SIGNAL('clicked()'), self.komberty) # IDENTIFICAR DATOS DE .PSD CMYK self.boton2 = QtGui.QPushButton('IDENTIFICAR DATOS DE .PSD CMYK', self) self.boton2.setGeometry(5, 200, 390, 25) self.boton2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.connect(self.boton2, QtCore.SIGNAL('clicked()'), self.identy) # EXTRAER ARCHIVO .ICC DE .PSD CMYK self.boton3 = QtGui.QPushButton( 'EXTRAER ARCHIVO .ICC DE .PSD CMYK', self) self.boton3.setGeometry(5, 225, 390, 25) self.boton3.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.connect(self.boton3, QtCore.SIGNAL('clicked()'), self.xtract) # Make a HTML5 W.WEBP file and a uncompressed .PNG file self.boton4 = QtGui.QPushButton( 'LIBERAR PSD CMYK HACIA HTML5 .WEBP + .PNG', self) self.boton4.setGeometry(5, 250, 390, 25) self.boton4.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.connect(self.boton4, QtCore.SIGNAL('clicked()'), self.webpify) # Imagen a texto plano base64 self.boton5 = QtGui.QPushButton( 'CONVERTIR IMAGEN A TEXTO PLANO BASE64', self) self.boton5.setGeometry(5, 275, 390, 25) self.boton5.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) # NOTE: hardcoded Chromium web browser call command, not my Bug, # for some reason cant use webbrowser.open(),because on some systems it # try to open the base64 with incorrect programs (like gvfs, etc) self.connect(self.boton5, QtCore.SIGNAL('clicked()'), lambda: commands.getoutput( 'chromium-browser "data:image/jpg;base64,' + base64.b64encode(open( QFileDialog.getOpenFileName(self, "Open a Image File to Encode...", os.path.expanduser("~"), ';;'.join(['(*%s)' % e for e in ['.jpg', '.png', '.webp', '']])), "rb").read()) + '"')) # Imagen a NormalMap self.boton6 = QtGui.QPushButton( 'CONVERTIR IMAGEN A NORMALMAP PNG', self) self.boton6.setGeometry(5, 300, 390, 25) self.boton6.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.connect(self.boton6, QtCore.SIGNAL('clicked()'), self.normalify) def komberty(self): " Main Conversion Function, dont Complain, Patch! " print('\n WAIT!!!, WORKING . . . ') self.statusBar().showMessage('WAIT!!!, WORKING . . . ') # get vars arg1 = unicode(open('.cmyk2rgb-cmyk-icc.txt', 'r').read()) arg2 = unicode(open('.cmyk2rgb-rgb-icc.txt', 'r').read()) arg3 = unicode(open('.cmyk2rgb-cmyk-psd.txt', 'r').read()) arg4 = unicode(self.combo1.currentText()) arg5 = unicode(self.combo2.currentText()) arg6 = unicode(self.combo3.currentText()) # handle special auto-magical settings if self.combo4.currentText() == 'NINGUNO!': # no magic!, low Mana ? arg7 = '' print(' INFO: NOT using AutoMagical Extras or Flying Unicorns...') elif self.combo4.currentText() == 'TODAS JUNTAS?': # this is an internal/backend debugging and benchmarking tool... arg7 = ' -antialias -auto-gamma -auto-level -enhance -normalize ' print('\n INFO: RUN FOR YOUR LIFE!, THIS IS GOING TO EXPLODE!! \n') else: arg7 = unicode(self.combo4.currentText()) print(' INFO: using AutoMagical Extras of ' + arg7 + '...') # convert print(' INFO: Working with ' + arg1 + ', ' + arg2 + ', ' + arg3) print(' INFO: My Intent is ' + arg4 + ', using Color Depth of ' + arg5) print(' INFO: The Alpha Channel Setting is ' + arg6 + '...') self.statusBar().showMessage('Working:' + arg1 + arg2 + arg3) commands.getoutput('convert -profile ' + arg1 + ' -profile ' + arg2 + ' -intent ' + arg4 + ' -depth ' + arg5 + ' -alpha ' + arg6 + arg7 + ' -strip -colorspace RGB ' + arg3 + ' ' + arg3 + '.tiff' + ' ; sleep 1 ; gimp --no-data --no-fonts --no-splash --as-new ' + arg3 + '.tiff') self.statusBar().showMessage('Done.') print(' INFO: Done. ') def identy(self): " Identification of the input .PSD file " print('\n WAIT!!!, WORKING . . . ') self.statusBar().showMessage('WAIT!!!, WORKING . . . ') arg3 = unicode(open('.cmyk2rgb-cmyk-psd.txt', 'r').read()) # print arg3 cmd1 = commands.getoutput('identify -verbose ' + arg3) # print cmd1 filename = "cmyk2rgb_report.txt" try: # write Report print(' Saving Report to ' + filename + "...") self.statusBar().showMessage('Saving Report to ' + filename) fout = open(filename, "w") fout.write(cmd1) fout.close() # open Report print(' Opening Report ' + filename + "...") self.statusBar().showMessage('Opening Report ' + filename + "...") webbrowser.open_new_tab(filename) self.statusBar().showMessage('Done.') print(' INFO: Done. ') # except if IO has an error, print an error except IOError: print " ERROR: File %s could not be saved!" % filename self.statusBar().showMessage("ERROR: File could not be saved!") def xtract(self): " Extract .ICC File from .PSD CMYK File " print('\n WAIT!!!, WORKING . . . ') self.statusBar().showMessage('WAIT!!!, WORKING . . . ') # get vars arg3 = unicode(open('.cmyk2rgb-cmyk-psd.txt', 'r').read()) # print info print(' INFO: Working with ' + arg3 + ' . . . ') self.statusBar().showMessage(' Working with ' + arg3 + ' . . . ') # extract the .icc files from the .psd file commands.getoutput('convert ' + arg3 + ' ' + arg3 + '.icc') print(' INFO: Done. ') self.statusBar().showMessage('Done.') def webpify(self): 'Make a .WEBP file for HTML5 web development and design, on base64 ' print('\n WAIT!!!, WORKING . . . ') self.statusBar().showMessage('WAIT!!!, WORKING . . . ') # get vars arg1 = unicode(open('.cmyk2rgb-cmyk-icc.txt', 'r').read()) arg2 = unicode(open('.cmyk2rgb-rgb-icc.txt', 'r').read()) arg3 = unicode(open('.cmyk2rgb-cmyk-psd.txt', 'r').read()) arg4 = unicode(self.combo1.currentText()) arg5 = unicode(self.combo2.currentText()) arg6 = unicode(self.combo3.currentText()) # print info print(' INFO: Working with ' + arg1 + ', ' + arg2 + ', ' + arg3) print(' INFO: My Intent is ' + arg4 + ', using Color Depth of ' + arg5) print(' INFO: The Alpha Channel Setting is ' + arg6 + '...') self.statusBar().showMessage('Working:' + arg1 + arg2 + arg3) # try to get version of WebP and print the info try: cmd1 = commands.getoutput('cwebp -version') print(' INFO: WORKING WITH: \n' + cmd1) # except if it has an error, print an error, and quit except: print(' ERROR: No WEBP Converter!\n ( sudo apt-get install webp )') exit() # NOTE: hardcoded Chromium web browser call command, not my Bug, # Firefox dont want to open .WEBP images, go complain to Mozilla. # # Convert commands.getoutput('convert -profile ' + arg1 + ' -profile ' + arg2 + ' -intent ' + arg4 + ' -depth ' + arg5 + ' -alpha ' + arg6 + ' -strip -flatten -colorspace RGB ' + arg3 + ' ' + arg3 + '.png' + ' ; sleep 1 ; cwebp -preset text -m 6 -strong -pass 10 ' + arg3 + '.png -o ' + arg3 + '.webp ; sleep 1 ; chromium-browser ' + arg3 + '.webp' ) self.statusBar().showMessage('Done.') print(' INFO: Done. ') def normalify(self): ' make a normal map from image ' def height2bump(heightBand, filter="Random"): ' oooooh, look a nested function!, are they bad ? ' if filter == "Sobel": a1 = 500 a2 = 64 a3 = 0 b1 = 1 b2 = 250 b3 = 666 elif filter == "Scharr": a1 = 21.38 a2 = 85.24 a3 = 0 b1 = 5.96 b2 = 61.81 b3 = 255 elif filter == "Random": # 5x5 random filter a1 = float(randint(0, 255)) a2 = float(randint(0, 255)) a3 = float(randint(0, 255)) b1 = float(randint(0, 255)) b2 = float(randint(0, 255)) b3 = float(randint(0, 255)) print(unicode((a1, a2, a3, b1, b2, b3))) else: raise ValueError(" ERROR: Unknown Filter arguments !") print("Filter: ", filter) a4 = -a2 a5 = -a1 b4 = b2 b5 = b1 kernel = [] kernel.append((a1 * b1, a2 * b1, a3 * b1, a4 * b1, a5 * b1, a1 * b2, a2 * b2, a3 * b2, a4 * b2, a5 * b2, a1 * b3, a2 * b3, a3 * b3, a4 * b3, a5 * b3, a1 * b4, a2 * b4, a3 * b4, a4 * b4, a5 * b4, a1 * b5, a2 * b5, a3 * b5, a4 * b5, a5 * b5)) # x kernel.append((b1 * a1, b2 * a1, b3 * a1, b4 * a1, b5 * a1, b1 * a2, b2 * a2, b3 * a2, b4 * a2, b5 * a2, b1 * a3, b2 * a3, b3 * a3, b4 * a3, b5 * a3, b1 * a4, b2 * a4, b3 * a4, b4 * a4, b5 * a4, b1 * a5, b2 * a5, b3 * a5, b4 * a5, b5 * a5)) # y # scale factor, vertical fall from 255 to 0 scale = 0.0 for i, val in enumerate(kernel[0]): if i % 5 < 5 // 2: scale += 255.0 * val scale /= 128.0 print("Scale = ", scale) r = heightBand.filter(ImageFilter.Kernel((5, 5), kernel[0], scale=scale, offset=128.0)) g = heightBand.filter(ImageFilter.Kernel((5, 5), kernel[1], scale=scale, offset=128.0)) b = ImageChops.constant(g, 128) rr = r.load() gg = g.load() bb = b.load() for y in range(r.size[1]): for x in range(r.size[0]): op = 1.0 - (rr[x, y] * 2.0 / 255.0 - 1.0) ** 2 - ( gg[x, y] * 2.0 / 255.0 - 1.0) ** 2 if op > 0.0: bb[x, y] = 128.0 + 128.0 * sqrt(op) else: bb[x, y] = 128.0 return([r, g, b]) # make a dialog gui dialog = QtGui.QDialog(self) # label1 = QtGui.QLabel('Tipo de algoritmo de procesamiento: ', dialog) label1.setAutoFillBackground(True) combo1 = QComboBox(dialog) combo1.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) combo1.addItems(['Sobel 5x5 (Strong, Fuerte)', 'Random ??? (Variable, entropic)', 'Scharr 5x5 (Soft, Suave)' ]) # label2 = QtGui.QLabel('Procesamiento de Canal Alpha: ', dialog) label2.setAutoFillBackground(True) combo2 = QComboBox(dialog) combo2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) combo2.addItems(['HeightMap (Usar Alpha)', 'Ignored (Ignorar Alpha)']) # label3 = QtGui.QLabel('\n Nombre de archivo de salida sera igual al ' + 'de entrada con el prefijo " _n ". \n Output filename will be equal ' + 'to input filename with the " _n " prefix. \n ', dialog) label3.setAutoFillBackground(True) # make a button ok = QtGui.QPushButton(dialog) # set the text on the button to ok ok.setText('&O K') ok.setDefault(True) # connect the clicked signal to an accept slot self.connect(ok, QtCore.SIGNAL('clicked()'), dialog.accept) # make a local layout layout = QtGui.QVBoxLayout() layout.addWidget(label1) layout.addWidget(combo1) layout.addWidget(label2) layout.addWidget(combo2) layout.addWidget(label3) layout.addWidget(ok) dialog.setLayout(layout) # run the dialog dialog.exec_() # Process the Algorythm string value if combo1.currentText() == 'Sobel 5x5 (Strong, Fuerte)': arg1 = 'Sobel' print(' INFO: Using Sobel for NormalMapping . . . ') elif combo1.currentText() == 'Random ??? (Variable, entropic)': arg1 = 'Random' print(' INFO: Using Random for NormalMapping . . . ') else: arg1 = 'Scharr' print(' INFO: using Scharr for NormalMapping . . . ') # Process the HeightMap Boolean if combo2.currentText() == 'HeightMap (Usar Alpha)': alphaheight = True else: alphaheight = False # try to read input filename and save the output file try: infile = unicode(QFileDialog.getOpenFileName(self, "Open an Image File to make a Normal Map... ", os.path.expanduser("~"), ';;'.join(['(*%s)' % e for e in ['.jpg', '.png', '']]))) print(infile) im = Image.open(infile) print(im) except: sys.exit(" \n ERROR: Could not open an Image File ! \n ") height = im.split()[0] normal = height2bump(height, filter=arg1) if alphaheight: normal.extend([height]) im = Image.merge("RGBA", normal) else: im = Image.merge("RGB", normal) try: outfile = unicode(infile.split('.')[0] + '_n.png') print(outfile) im.save(outfile) except: sys.exit(" \n ERROR: Could not save the Output Image File ! \n ") print(" INFO: Function completed !") return(im) def showQColorDialog(self): ' Choose a Color for Qt ' color = QtGui.QColorDialog.getColor() # print info print(' INFO: Using User requested color ' + str(color.name()) + '...') # if the color is a valid color use it into an CSS and apply it if color.isValid(): self.setStyleSheet(" * { background-color: %s } " % color.name()) def applySkin(self): ' Apply a Customized Dark Sexy Skin ' print(' INFO: Using Built-In CSS . . .') # complete CSS for Qt widgets self.setStyleSheet(''' QToolTip { border: 1px solid black; background-color: #ffa02f; padding: 1px; border-radius: 3px; opacity: 100; } QWidget{ color: #b1b1b1; background-color: #323232; } QWidget:item:hover { background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #ca0619 ); color: #000000; } QWidget:item:selected { background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a ); } QMenuBar::item { background: transparent; } QMenuBar::item:selected { background: transparent; border: 1px solid #ffaa00; } QMenuBar::item:pressed { background: #444; border: 1px solid #000; background-color: QLinearGradient( x1:0, y1:0, x2:0, y2:1, stop:1 #212121, stop:0.4 #343434, stop:0.2 #343434, stop:0.1 #ffaa00 ); margin-bottom:-1px; padding-bottom:1px; } QMenu { border: 1px solid #000; } QMenu::item { padding: 2px 20px 2px 20px; } QMenu::item:selected { color: #000000; } QWidget:disabled { color: #404040; background-color: #323232; } QAbstractItemView { background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #4d4d4d, stop: 0.1 #646464, stop: 1 #5d5d5d ); } QWidget:focus { border: 2px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a ); } QLineEdit { background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #4d4d4d, stop: 0 #646464, stop: 1 #5d5d5d ); padding: 1px; border-style: solid; border: 1px solid #1e1e1e; border-radius: 5; } QPushButton { color: #b1b1b1; background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #565656, stop: 0.1 #525252, stop: 0.5 #4e4e4e, stop: 0.9 #4a4a4a, stop: 1 #464646 ); border-width: 1px; border-color: #1e1e1e; border-style: solid; border-radius: 6; padding: 3px; font-size: 12px; padding-left: 5px; padding-right: 5px; } QPushButton:pressed { background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2d2d2d, stop: 0.1 #2b2b2b, stop: 0.5 #292929, stop: 0.9 #282828, stop: 1 #252525 ); } QComboBox { selection-background-color: #ffaa00; background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #565656, stop: 0.1 #525252, stop: 0.5 #4e4e4e, stop: 0.9 #4a4a4a, stop: 1 #464646 ); border-style: solid; border: 1px solid #1e1e1e; border-radius: 5; } QComboBox:hover,QPushButton:hover { border: 2px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a ); } QComboBox:on { padding-top: 3px; padding-left: 4px; background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2d2d2d, stop: 0.1 #2b2b2b, stop: 0.5 #292929, stop: 0.9 #282828, stop: 1 #252525 ); selection-background-color: #ffaa00; } QComboBox QAbstractItemView { border: 2px solid darkgray; selection-background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a ); } QComboBox::drop-down { subcontrol-origin: padding; subcontrol-position: top right; width: 15px; border-left-width: 0px; border-left-color: darkgray; border-left-style: solid; border-top-right-radius: 3px; border-bottom-right-radius: 3px; } QComboBox::down-arrow { } QGroupBox:focus { border: 2px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a ); } QTextEdit:focus { border: 2px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a ); } QScrollBar:horizontal { border: 1px solid #222222; background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0.0 #121212, stop: 0.2 #282828, stop: 1 #484848 ); height: 7px; margin: 0px 16px 0 16px; } QScrollBar::handle:horizontal { background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #ffa02f, stop: 0.5 #d7801a, stop: 1 #ffa02f ); min-height: 20px; border-radius: 2px; } QScrollBar::add-line:horizontal { border: 1px solid #1b1b19; border-radius: 2px; background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #ffa02f, stop: 1 #d7801a ); width: 14px; subcontrol-position: right; subcontrol-origin: margin; } QScrollBar::sub-line:horizontal { border: 1px solid #1b1b19; border-radius: 2px; background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #ffa02f, stop: 1 #d7801a ); width: 14px; subcontrol-position: left; subcontrol-origin: margin; } QScrollBar::right-arrow:horizontal, QScrollBar::left-arrow:horizontal { border: 1px solid black; width: 1px; height: 1px; background: white; } QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal { background: none; } QScrollBar:vertical { background: QLinearGradient( x1: 0, y1: 0, x2: 1, y2: 0, stop: 0.0 #121212, stop: 0.2 #282828, stop: 1 #484848 ); width: 7px; margin: 16px 0 16px 0; border: 1px solid #222222; } QScrollBar::handle:vertical { background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 0.5 #d7801a, stop: 1 #ffa02f ); min-height: 20px; border-radius: 2px; } QScrollBar::add-line:vertical { border: 1px solid #1b1b19; border-radius: 2px; background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a ); height: 14px; subcontrol-position: bottom; subcontrol-origin: margin; } QScrollBar::sub-line:vertical { border: 1px solid #1b1b19; border-radius: 2px; background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #d7801a, stop: 1 #ffa02f ); height: 14px; subcontrol-position: top; subcontrol-origin: margin; } QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical { border: 1px solid black; width: 1px; height: 1px; background: white; } QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { background: none; } QTextEdit { background-color: #242424; } QPlainTextEdit { background-color: #242424; } QHeaderView::section { background-color: QLinearGradient( x1:0, y1:0, x2:0, y2:1, stop:0 #616161, stop: 0.5 #505050, stop: 0.6 #434343, stop:1 #656565 ); color: white; padding-left: 4px; border: 1px solid #6c6c6c; } QCheckBox:disabled { color: #414141; } QDockWidget::title { text-align: center; spacing: 3px; background-color: QLinearGradient( x1:0, y1:0, x2:0, y2:1, stop:0 #323232, stop: 0.5 #242424, stop:1 #323232 ); } QDockWidget::close-button, QDockWidget::float-button { text-align: center; spacing: 1px; background-color: QLinearGradient( x1:0, y1:0, x2:0, y2:1, stop:0 #323232, stop: 0.5 #242424, stop:1 #323232 ); } QDockWidget::close-button:hover, QDockWidget::float-button:hover { background: #242424; } QDockWidget::close-button:pressed, QDockWidget::float-button:pressed { padding: 1px -1px -1px 1px;} QMainWindow::separator { background-color: QLinearGradient( x1:0, y1:0, x2:0, y2:1, stop:0 #161616, stop: 0.5 #151515, stop: 0.6 #212121, stop:1 #343434 ); color: white; padding-left: 4px; border: 1px solid #4c4c4c; spacing: 3px; } QMainWindow::separator:hover { background-color: QLinearGradient( x1:0, y1:0, x2:0, y2:1, stop:0 #d7801a, stop:0.5 #b56c17, stop:1 #ffa02f ); color: white; padding-left: 4px; border: 1px solid #6c6c6c; spacing: 3px; } QToolBar::handle { spacing: 3px; } QMenu::separator { height: 2px; background-color: QLinearGradient( x1:0, y1:0, x2:0, y2:1, stop:0 #161616, stop: 0.5 #151515, stop: 0.6 #212121, stop:1 #343434 ); color: white; padding-left: 4px; margin-left: 10px; margin-right: 5px; } QProgressBar { border: 2px solid grey; border-radius: 5px; text-align: center; } QProgressBar::chunk { background-color: #d7801a; width: 2.15px; margin: 0.5px; } QTabBar::tab { color: #b1b1b1; border: 1px solid #444; border-bottom-style: none; background-color: #323232; padding-left: 10px; padding-right: 10px; padding-top: 3px; padding-bottom: 2px; margin-right: -1px; } QTabWidget::pane { border: 1px solid #444; top: 1px; } QTabBar::tab:last { margin-right: 0; border-top-right-radius: 3px; } QTabBar::tab:first:!selected { margin-left: 0px; border-top-left-radius: 3px; } QTabBar::tab:!selected { color: #b1b1b1; border-bottom-style: solid; margin-top: 3px; background-color: QLinearGradient( x1:0, y1:0, x2:0, y2:1, stop:1 #212121, stop:.4 #343434 ); } QTabBar::tab:selected { border-top-left-radius: 3px; border-top-right-radius: 3px; margin-bottom: 0px; } QTabBar::tab:!selected:hover { border-top: 2px solid #ffaa00; padding-bottom: 3px; border-top-left-radius: 3px; border-top-right-radius: 3px; background-color: QLinearGradient( x1:0, y1:0, x2:0, y2:1, stop:1 #212121, stop:0.4 #343434, stop:0.2 #343434, stop:0.1 #ffaa00 ); } QRadioButton::indicator:checked, QRadioButton::indicator:unchecked{ color: #b1b1b1; background-color: #323232; border: 1px solid #b1b1b1; border-radius: 6px; } QRadioButton::indicator:checked { background-color: qradialgradient( cx: 0.5, cy: 0.5, fx: 0.5, fy: 0.5, radius: 1.0, stop: 0.25 #ffaa00, stop: 0.3 #323232 ); } QCheckBox::indicator { color: #b1b1b1; background-color: #323232; border: 1px solid #b1b1b1; width: 9px; height: 9px; } QRadioButton::indicator { border-radius: 6px; } QRadioButton::indicator:hover, QCheckBox::indicator:hover { border: 1px solid #ffaa00; } QCheckBox::indicator:checked { } QCheckBox::indicator:disabled, QRadioButton::indicator:disabled { border: 1px solid #444; } ''')
class NewConfigurationDialog(QDialog): """A dialog for selecting defaults for a new configuration.""" def __init__(self, configuration_path, parent=None): QDialog.__init__(self, parent) self.setModal(True) self.setWindowTitle("New configuration file") self.setMinimumWidth(250) self.setMinimumHeight(150) layout = QFormLayout() directory, filename = os.path.split(configuration_path) if directory.strip() == "": directory = os.path.abspath(os.curdir) self.configuration_path = "%s/%s" % (directory, filename) else: self.configuration_path = configuration_path configuration_location = QLabel() configuration_location.setText(directory) configuration_name = QLabel() configuration_name.setText(filename) self.db_type = QComboBox() self.db_type.addItem("BLOCK_FS") self.db_type.addItem("PLAIN") self.first_case_name = QLineEdit() self.first_case_name.setText("default") self.connect(self.first_case_name, SIGNAL('textChanged(QString)'), self._validateName) self.num_realizations = QSpinBox() self.num_realizations.setMinimum(1) self.num_realizations.setMaximum(1000) self.num_realizations.setValue(10) self.storage_path = QLineEdit() self.storage_path.setText("Storage") self.connect(self.storage_path, SIGNAL('textChanged(QString)'), self._validateName) layout.addRow(createSpace(10)) layout.addRow("Configuration name:", configuration_name) layout.addRow("Configuration location:", configuration_location) layout.addRow("Path to store DBase:", self.storage_path) layout.addRow("DBase type:", self.db_type) layout.addRow("Name of first case:", self.first_case_name) layout.addRow("Number of realizations", self.num_realizations) layout.addRow(createSpace(10)) buttons = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self) self.ok_button = buttons.button(QDialogButtonBox.Ok) layout.addRow(buttons) self.connect(buttons, SIGNAL('accepted()'), self.accept) self.connect(buttons, SIGNAL('rejected()'), self.reject) self.setLayout(layout) def getNumberOfRealizations(self): return self.num_realizations.value() def getConfigurationPath(self): return self.configuration_path def getCaseName(self): """Return the name of the first case.""" return str(self.first_case_name.text()).strip() def getDBaseType(self): """Return the DBase type""" return str(self.db_type.currentText()) def getStoragePath(self): """Return the DBase storage path""" return str(self.storage_path.text()).strip() def _validateName(self, name): name = str(name) enabled = len(name) > 0 and name.find(" ") == -1 self.ok_button.setEnabled(enabled)
class AdvancedVisualizationForm(QWidget): def __init__(self, mainwindow, result_manager): QWidget.__init__(self, mainwindow) #mainwindow is an OpusGui self.mainwindow = mainwindow self.result_manager = result_manager self.toolboxBase = self.result_manager.mainwindow.toolboxBase self.inGui = False self.logFileKey = 0 self.xml_helper = ResultsManagerXMLHelper(toolboxBase=self.toolboxBase) self.result_generator = OpusResultGenerator( toolboxBase=self.toolboxBase) self.result_generator.guiElement = self self.tabIcon = QIcon(':/Images/Images/cog.png') self.tabLabel = 'Advanced Visualization' self.widgetLayout = QVBoxLayout(self) self.widgetLayout.setAlignment(Qt.AlignTop) self.resultsGroupBox = QGroupBox(self) self.widgetLayout.addWidget(self.resultsGroupBox) self.dataGroupBox = QGroupBox(self) self.widgetLayout.addWidget(self.dataGroupBox) self.optionsGroupBox = QGroupBox(self) self.widgetLayout.addWidget(self.optionsGroupBox) self._setup_definition_widget() self._setup_buttons() self._setup_tabs() def _setup_buttons(self): # Add Generate button... self.pbn_go = QPushButton(self.resultsGroupBox) self.pbn_go.setObjectName('pbn_go') self.pbn_go.setText(QString('Go!')) QObject.connect(self.pbn_go, SIGNAL('released()'), self.on_pbn_go_released) self.widgetLayout.addWidget(self.pbn_go) self.pbn_set_esri_storage_location = QPushButton(self.optionsGroupBox) self.pbn_set_esri_storage_location.setObjectName( 'pbn_set_esri_storage_location') self.pbn_set_esri_storage_location.setText(QString('...')) self.pbn_set_esri_storage_location.hide() QObject.connect(self.pbn_set_esri_storage_location, SIGNAL('released()'), self.on_pbn_set_esri_storage_location_released) def _setup_tabs(self): # Add a tab widget and layer in a tree view and log panel self.tabWidget = QTabWidget(self.resultsGroupBox) # Log panel self.logText = QTextEdit(self.resultsGroupBox) self.logText.setReadOnly(True) self.logText.setLineWidth(0) self.tabWidget.addTab(self.logText, 'Log') # Finally add the tab to the model page self.widgetLayout.addWidget(self.tabWidget) # def _setup_definition_widget(self): #### setup results group box #### self.gridlayout = QGridLayout(self.resultsGroupBox) self.gridlayout.setObjectName('gridlayout') self.lbl_results = QLabel(self.resultsGroupBox) self.lbl_results.setObjectName('lbl_results') self.lbl_results.setText(QString('Results')) self.gridlayout.addWidget(self.lbl_results, 0, 0, 1, 3) self._setup_co_results() self.gridlayout.addWidget(self.co_results, 0, 3, 1, 10) self.pbn_add = QPushButton(self.resultsGroupBox) self.pbn_add.setObjectName('pbn_add') self.pbn_add.setText(QString('+')) QObject.connect(self.pbn_add, SIGNAL('released()'), self.on_pbn_add_released) self.gridlayout.addWidget(self.pbn_add, 0, 14, 1, 1) self.lw_indicators = QListWidget(self.resultsGroupBox) self.lw_indicators.setObjectName('lw_indicators') self.gridlayout.addWidget(self.lw_indicators, 1, 1, 1, 13) self.pbn_remove = QPushButton(self.resultsGroupBox) self.pbn_remove.setObjectName('pbn_remove') self.pbn_remove.setText(QString('-')) QObject.connect(self.pbn_remove, SIGNAL('released()'), self.on_pbn_remove_released) self.gridlayout.addWidget(self.pbn_remove, 1, 14, 1, 1) #### setup data group box #### self.gridlayout2 = QGridLayout(self.dataGroupBox) self.gridlayout2.setObjectName('gridlayout2') self._setup_co_result_style() self.gridlayout2.addWidget(self.co_result_style, 1, 0, 1, 2) self.lbl_result_style_sep = QLabel(self.resultsGroupBox) self.lbl_result_style_sep.setObjectName('lbl_result_style_sep') self.lbl_result_style_sep.setText(QString('<center>as</center>')) self.gridlayout2.addWidget(self.lbl_result_style_sep, 1, 2, 1, 1) self._setup_co_result_type() self.gridlayout2.addWidget(self.co_result_type, 1, 3, 1, 2) ##### setup options group box #### self.gridlayout3 = QGridLayout(self.optionsGroupBox) self.gridlayout3.setObjectName('gridlayout3') self.le_esri_storage_location = QLineEdit(self.optionsGroupBox) self.le_esri_storage_location.setObjectName('le_esri_storage_location') self.le_esri_storage_location.setText('[set path]') self.le_esri_storage_location.hide() self.optionsGroupBox.hide() QObject.connect(self.co_result_style, SIGNAL('currentIndexChanged(int)'), self.on_co_result_style_changed) QObject.connect(self.co_result_type, SIGNAL('currentIndexChanged(int)'), self.on_co_result_type_changed) def _setup_co_results(self): self.co_results = QComboBox(self.resultsGroupBox) self.co_results.setObjectName('co_results') self.co_results.addItem(QString('[select]')) results = self.xml_helper.get_available_results() for result in results: name = '%i.%s' % (result['run_id'], result['indicator_name']) self.co_results.addItem(QString(name)) def _setup_co_result_style(self): available_styles = [ 'visualize', 'export', ] self.co_result_style = QComboBox(self.dataGroupBox) self.co_result_style.setObjectName('co_result_style') for dataset in available_styles: self.co_result_style.addItem(QString(dataset)) def _setup_co_result_type(self): available_types = [ 'Table (per year, spans indicators)', 'Chart (per indicator, spans years)', 'Map (per indicator per year)', 'Chart (per indicator, spans years)', ] self.co_result_type = QComboBox(self.dataGroupBox) self.co_result_type.setObjectName('co_result_type') for dataset in available_types: self.co_result_type.addItem(QString(dataset)) def on_pbnRemoveModel_released(self): self.result_manager.removeTab(self) self.result_manager.updateGuiElements() def on_pbn_add_released(self): cur_selected = self.co_results.currentText() for i in range(self.lw_indicators.count()): if self.lw_indicators.item(i).text() == cur_selected: return self.lw_indicators.addItem(cur_selected) def on_pbn_remove_released(self): selected_idxs = self.lw_indicators.selectedIndexes() for idx in selected_idxs: self.lw_indicators.takeItem(idx.row()) def on_co_result_style_changed(self, ind): available_viz_types = [ 'Table (per year, spans indicators)', 'Chart (per indicator, spans years)', 'Map (per indicator per year)', 'Chart (per indicator, spans years)', ] available_export_types = ['ESRI table (for loading in ArcGIS)'] txt = self.co_result_style.currentText() if txt == 'visualize': available_types = available_viz_types else: available_types = available_export_types self.co_result_type.clear() for result_type in available_types: r_type = QString(result_type) self.co_result_type.addItem(r_type) def on_co_result_type_changed(self, ind): self.gridlayout3.removeWidget(self.le_esri_storage_location) self.gridlayout3.removeWidget(self.pbn_set_esri_storage_location) self.optionsGroupBox.hide() self.pbn_set_esri_storage_location.hide() self.le_esri_storage_location.hide() txt = self.co_result_type.currentText() print txt if txt == 'ESRI table (for loading in ArcGIS)': self.pbn_set_esri_storage_location.show() self.le_esri_storage_location.show() self.gridlayout3.addWidget(self.le_esri_storage_location, 0, 1, 1, 6) self.gridlayout3.addWidget(self.pbn_set_esri_storage_location, 0, 7, 1, 1) self.optionsGroupBox.show() def on_pbn_set_esri_storage_location_released(self): print 'pbn_set_esri_storage_location released' from opus_core.misc import directory_path_from_opus_path start_dir = directory_path_from_opus_path('opus_gui.projects') configDialog = QFileDialog() filter_str = QString("*.gdb") fd = configDialog.getExistingDirectory( self, QString("Please select an ESRI geodatabase (*.gdb)..." ), #, *.sde, *.mdb)..."), QString(start_dir), QFileDialog.ShowDirsOnly) if len(fd) != 0: fileName = QString(fd) fileNameInfo = QFileInfo(QString(fd)) fileNameBaseName = fileNameInfo.completeBaseName() self.le_esri_storage_location.setText(fileName) def on_pbn_go_released(self): # Fire up a new thread and run the model print 'Go button pressed' # References to the GUI elements for status for this run... #self.statusLabel = self.runStatusLabel #self.statusLabel.setText(QString('Model initializing...')) indicator_names = [] for i in range(self.lw_indicators.count()): indicator_names.append(str(self.lw_indicators.item(i).text())) if indicator_names == []: print 'no indicators selected' return indicator_type = str(self.co_result_type.currentText()) indicator_type = { #'Map (per indicator per year)':'matplotlib_map', 'Map (per indicator per year)': 'mapnik_map', 'Chart (per indicator, spans years)': 'matplotlib_chart', 'Table (per indicator, spans years)': 'table_per_attribute', 'Table (per year, spans indicators)': 'table_per_year', 'ESRI table (for loading in ArcGIS)': 'table_esri' }[indicator_type] kwargs = {} if indicator_type == 'table_esri': storage_location = str(self.le_esri_storage_location.text()) if not os.path.exists(storage_location): print 'Warning: %s does not exist!!' % storage_location kwargs['storage_location'] = storage_location self.result_manager.addIndicatorForm(indicator_type=indicator_type, indicator_names=indicator_names, kwargs=kwargs) def runUpdateLog(self): self.logFileKey = self.result_generator._get_current_log( self.logFileKey) def runErrorFromThread(self, errorMessage): QMessageBox.warning(self.mainwindow, 'Warning', errorMessage)
def normalify(self): ' make a normal map from image ' def height2bump(heightBand, filter="Random"): ' oooooh, look a nested function!, are they bad ? ' if filter == "Sobel": a1 = 500 a2 = 64 a3 = 0 b1 = 1 b2 = 250 b3 = 666 elif filter == "Scharr": a1 = 21.38 a2 = 85.24 a3 = 0 b1 = 5.96 b2 = 61.81 b3 = 255 elif filter == "Random": # 5x5 random filter a1 = float(randint(0, 255)) a2 = float(randint(0, 255)) a3 = float(randint(0, 255)) b1 = float(randint(0, 255)) b2 = float(randint(0, 255)) b3 = float(randint(0, 255)) print(unicode((a1, a2, a3, b1, b2, b3))) else: raise ValueError(" ERROR: Unknown Filter arguments !") print("Filter: ", filter) a4 = -a2 a5 = -a1 b4 = b2 b5 = b1 kernel = [] kernel.append((a1 * b1, a2 * b1, a3 * b1, a4 * b1, a5 * b1, a1 * b2, a2 * b2, a3 * b2, a4 * b2, a5 * b2, a1 * b3, a2 * b3, a3 * b3, a4 * b3, a5 * b3, a1 * b4, a2 * b4, a3 * b4, a4 * b4, a5 * b4, a1 * b5, a2 * b5, a3 * b5, a4 * b5, a5 * b5)) # x kernel.append((b1 * a1, b2 * a1, b3 * a1, b4 * a1, b5 * a1, b1 * a2, b2 * a2, b3 * a2, b4 * a2, b5 * a2, b1 * a3, b2 * a3, b3 * a3, b4 * a3, b5 * a3, b1 * a4, b2 * a4, b3 * a4, b4 * a4, b5 * a4, b1 * a5, b2 * a5, b3 * a5, b4 * a5, b5 * a5)) # y # scale factor, vertical fall from 255 to 0 scale = 0.0 for i, val in enumerate(kernel[0]): if i % 5 < 5 // 2: scale += 255.0 * val scale /= 128.0 print("Scale = ", scale) r = heightBand.filter(ImageFilter.Kernel((5, 5), kernel[0], scale=scale, offset=128.0)) g = heightBand.filter(ImageFilter.Kernel((5, 5), kernel[1], scale=scale, offset=128.0)) b = ImageChops.constant(g, 128) rr = r.load() gg = g.load() bb = b.load() for y in range(r.size[1]): for x in range(r.size[0]): op = 1.0 - (rr[x, y] * 2.0 / 255.0 - 1.0) ** 2 - ( gg[x, y] * 2.0 / 255.0 - 1.0) ** 2 if op > 0.0: bb[x, y] = 128.0 + 128.0 * sqrt(op) else: bb[x, y] = 128.0 return([r, g, b]) # make a dialog gui dialog = QtGui.QDialog(self) # label1 = QtGui.QLabel('Tipo de algoritmo de procesamiento: ', dialog) label1.setAutoFillBackground(True) combo1 = QComboBox(dialog) combo1.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) combo1.addItems(['Sobel 5x5 (Strong, Fuerte)', 'Random ??? (Variable, entropic)', 'Scharr 5x5 (Soft, Suave)' ]) # label2 = QtGui.QLabel('Procesamiento de Canal Alpha: ', dialog) label2.setAutoFillBackground(True) combo2 = QComboBox(dialog) combo2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) combo2.addItems(['HeightMap (Usar Alpha)', 'Ignored (Ignorar Alpha)']) # label3 = QtGui.QLabel('\n Nombre de archivo de salida sera igual al ' + 'de entrada con el prefijo " _n ". \n Output filename will be equal ' + 'to input filename with the " _n " prefix. \n ', dialog) label3.setAutoFillBackground(True) # make a button ok = QtGui.QPushButton(dialog) # set the text on the button to ok ok.setText('&O K') ok.setDefault(True) # connect the clicked signal to an accept slot self.connect(ok, QtCore.SIGNAL('clicked()'), dialog.accept) # make a local layout layout = QtGui.QVBoxLayout() layout.addWidget(label1) layout.addWidget(combo1) layout.addWidget(label2) layout.addWidget(combo2) layout.addWidget(label3) layout.addWidget(ok) dialog.setLayout(layout) # run the dialog dialog.exec_() # Process the Algorythm string value if combo1.currentText() == 'Sobel 5x5 (Strong, Fuerte)': arg1 = 'Sobel' print(' INFO: Using Sobel for NormalMapping . . . ') elif combo1.currentText() == 'Random ??? (Variable, entropic)': arg1 = 'Random' print(' INFO: Using Random for NormalMapping . . . ') else: arg1 = 'Scharr' print(' INFO: using Scharr for NormalMapping . . . ') # Process the HeightMap Boolean if combo2.currentText() == 'HeightMap (Usar Alpha)': alphaheight = True else: alphaheight = False # try to read input filename and save the output file try: infile = unicode(QFileDialog.getOpenFileName(self, "Open an Image File to make a Normal Map... ", os.path.expanduser("~"), ';;'.join(['(*%s)' % e for e in ['.jpg', '.png', '']]))) print(infile) im = Image.open(infile) print(im) except: sys.exit(" \n ERROR: Could not open an Image File ! \n ") height = im.split()[0] normal = height2bump(height, filter=arg1) if alphaheight: normal.extend([height]) im = Image.merge("RGBA", normal) else: im = Image.merge("RGB", normal) try: outfile = unicode(infile.split('.')[0] + '_n.png') print(outfile) im.save(outfile) except: sys.exit(" \n ERROR: Could not save the Output Image File ! \n ") print(" INFO: Function completed !") return(im)
class GeneralExecution(QWidget): """General Execution widget class""" def __init__(self, parent): super(GeneralExecution, self).__init__() self._preferences = parent vbox = QVBoxLayout(self) groupExecution = QGroupBox(translations.TR_WORKSPACE_PROJECTS) grid = QVBoxLayout(groupExecution) #Python Path hPath = QHBoxLayout() self._txtPythonPath = QLineEdit() self._btnPythonPath = QPushButton(QIcon(':img/open'), '') self.completer, self.dirs = QCompleter(self), QDirModel(self) self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot) self.completer.setModel(self.dirs) self._txtPythonPath.setCompleter(self.completer) hPath.addWidget(QLabel(translations.TR_SELECT_PYTHON_EXEC)) hPath.addWidget(self._txtPythonPath) hPath.addWidget(self._btnPythonPath) grid.addLayout(hPath) #Python Miscellaneous Execution options self.check_B = QCheckBox(translations.TR_SELECT_EXEC_OPTION_B) self.check_d = QCheckBox(translations.TR_SELECT_EXEC_OPTION_D) self.check_E = QCheckBox(translations.TR_SELECT_EXEC_OPTION_E) self.check_O = QCheckBox(translations.TR_SELECT_EXEC_OPTION_O) self.check_OO = QCheckBox(translations.TR_SELECT_EXEC_OPTION_OO) self.check_Q = QCheckBox(translations.TR_SELECT_EXEC_OPTION_Q) self.comboDivision = QComboBox() self.comboDivision.addItems(['old', 'new', 'warn', 'warnall']) self.check_s = QCheckBox(translations.TR_SELECT_EXEC_OPTION_s) self.check_S = QCheckBox(translations.TR_SELECT_EXEC_OPTION_S) self.check_t = QCheckBox(translations.TR_SELECT_EXEC_OPTION_T) self.check_tt = QCheckBox(translations.TR_SELECT_EXEC_OPTION_TT) self.check_v = QCheckBox(translations.TR_SELECT_EXEC_OPTION_V) self.check_W = QCheckBox(translations.TR_SELECT_EXEC_OPTION_W) self.comboWarning = QComboBox() self.comboWarning.addItems( ['default', 'ignore', 'all', 'module', 'once', 'error']) self.check_x = QCheckBox(translations.TR_SELECT_EXEC_OPTION_X) self.check_3 = QCheckBox(translations.TR_SELECT_EXEC_OPTION_3) grid.addWidget(self.check_B) grid.addWidget(self.check_d) grid.addWidget(self.check_E) grid.addWidget(self.check_O) grid.addWidget(self.check_OO) hDiv = QHBoxLayout() hDiv.addWidget(self.check_Q) hDiv.addWidget(self.comboDivision) grid.addLayout(hDiv) grid.addWidget(self.check_s) grid.addWidget(self.check_S) grid.addWidget(self.check_t) grid.addWidget(self.check_tt) grid.addWidget(self.check_v) hWarn = QHBoxLayout() hWarn.addWidget(self.check_W) hWarn.addWidget(self.comboWarning) grid.addLayout(hWarn) grid.addWidget(self.check_x) grid.addWidget(self.check_3) #Settings self._txtPythonPath.setText(settings.PYTHON_EXEC) options = settings.EXECUTION_OPTIONS.split() if '-B' in options: self.check_B.setChecked(True) if '-d' in options: self.check_d.setChecked(True) if '-E' in options: self.check_E.setChecked(True) if '-O' in options: self.check_O.setChecked(True) if '-OO' in options: self.check_OO.setChecked(True) if settings.EXECUTION_OPTIONS.find('-Q') > -1: self.check_Q.setChecked(True) index = settings.EXECUTION_OPTIONS.find('-Q') opt = settings.EXECUTION_OPTIONS[index + 2:].split(' ', 1)[0] index = self.comboDivision.findText(opt) self.comboDivision.setCurrentIndex(index) if '-s' in options: self.check_s.setChecked(True) if '-S' in options: self.check_S.setChecked(True) if '-t' in options: self.check_t.setChecked(True) if '-tt' in options: self.check_tt.setChecked(True) if '-v' in options: self.check_v.setChecked(True) if settings.EXECUTION_OPTIONS.find('-W') > -1: self.check_W.setChecked(True) index = settings.EXECUTION_OPTIONS.find('-W') opt = settings.EXECUTION_OPTIONS[index + 2:].split(' ', 1)[0] index = self.comboWarning.findText(opt) self.comboWarning.setCurrentIndex(index) if '-x' in options: self.check_x.setChecked(True) if '-3' in options: self.check_3.setChecked(True) vbox.addWidget(groupExecution) #Signals self.connect(self._btnPythonPath, SIGNAL("clicked()"), self._load_python_path) self.connect(self._preferences, SIGNAL("savePreferences()"), self.save) def _load_python_path(self): """Ask the user for a Python Path""" path = QFileDialog.getOpenFileName( self, translations.TR_SELECT_SELECT_PYTHON_EXEC) if path: self._txtPythonPath.setText(path) def save(self): """Save all the Execution Preferences""" qsettings = IDE.ninja_settings() qsettings.beginGroup('preferences') qsettings.beginGroup('execution') qsettings.setValue('pythonPath', self._txtPythonPath.text()) settings.PYTHON_PATH = self._txtPythonPath.text() options = '' if self.check_B.isChecked(): options += ' -B' if self.check_d.isChecked(): options += ' -d' if self.check_E.isChecked(): options += ' -E' if self.check_O.isChecked(): options += ' -O' if self.check_OO.isChecked(): options += ' -OO' if self.check_Q.isChecked(): options += ' -Q' + self.comboDivision.currentText() if self.check_s.isChecked(): options += ' -s' if self.check_S.isChecked(): options += ' -S' if self.check_t.isChecked(): options += ' -t' if self.check_tt.isChecked(): options += ' -tt' if self.check_v.isChecked(): options += ' -v' if self.check_W.isChecked(): options += ' -W' + self.comboWarning.currentText() if self.check_x.isChecked(): options += ' -x' if self.check_3.isChecked(): options += ' -3' settings.EXECUTION_OPTIONS = options qsettings.setValue('executionOptions', options) qsettings.endGroup() qsettings.endGroup()
class WindPanel(QFrame): def __init__(self, parent): QFrame.__init__(self, parent) # self.frame_WindIA = QFrame(parent) sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(sizePolicy) self.setFrameShape(QFrame.StyledPanel) self.setFrameShadow(QFrame.Raised) self.setObjectName(("frame_WindIA")) self.horizontalLayout_32 = QHBoxLayout(self) self.horizontalLayout_32.setSpacing(0) self.horizontalLayout_32.setMargin(0) self.horizontalLayout_32.setObjectName(("horizontalLayout_32")) self.lblIA = QLabel(self) self.lblIA.setMinimumSize(QSize(140, 0)) self.lblIA.setMaximumSize(QSize(100, 16777215)) font = QFont() font.setFamily(("Arial")) font.setBold(False) font.setWeight(50) self.lblIA.setFont(font) self.lblIA.setObjectName(("lblIA")) self.horizontalLayout_32.addWidget(self.lblIA) self.comboBox = QComboBox(self) sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.comboBox.sizePolicy().hasHeightForWidth()) self.comboBox.setSizePolicy(sizePolicy) self.comboBox.setMinimumSize(QSize(60, 0)) font = QFont() font.setFamily(("Arial")) font.setBold(False) font.setWeight(50) self.comboBox.setFont(font) self.comboBox.setObjectName(("comboBox")) self.horizontalLayout_32.addWidget(self.comboBox) self.speedBox = QLineEdit(self) sizePolicy = QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.speedBox.sizePolicy().hasHeightForWidth()) self.speedBox.setSizePolicy(sizePolicy) self.speedBox.setMinimumSize(QSize(70, 0)) self.speedBox.setMaximumSize(QSize(16777215, 16777215)) font = QFont() font.setFamily(("Arial")) font.setBold(False) font.setWeight(50) self.speedBox.setFont(font) self.speedBox.setObjectName(("speedBox")) self.horizontalLayout_32.addWidget(self.speedBox) self.altitude = Altitude.NaN() self.customValue = Speed(30).Knots self.comboBox.addItems(["ICAO", "UK", "Custom"]) self.comboBox.currentIndexChanged.connect(self.changeWindType) self.comboBox.setCurrentIndex(0) self.lblIA.setText("Wind (kts):") self.speedBox.setEnabled(False) def setAltitude(self, value): self.altitude = value self.method_5() # def getValue(self, SpeedUnits_0 = SpeedUnits.KTS): # return Speed(float(self.speedBox.text()), SpeedUnits_0) def method_3(self, altitude_0): altitude = Altitude(float(self.speedBox.text()), AltitudeUnits.FT) if (self.comboBox.currentIndex() != 0): return altitude return Altitude(altitude.Feet - altitude_0.Feet, AltitudeUnits.FT) def method_5(self): if self.comboBox.currentIndex() == 0: self.speedBox.setText( str(round(Speed.smethod_1(self.altitude).Knots, 1))) elif self.comboBox.currentIndex() == 1: self.speedBox.setText( str(round(Speed.smethod_2(self.altitude).Knots, 1))) else: self.speedBox.setText(str(self.customValue)) if self.comboBox.currentIndex() != 2: self.speedBox.setEnabled(False) else: self.speedBox.setEnabled(True) def changeWindType(self): self.method_5() def method_7(self, string_0): # object[] string0 = new object[] { string_0, this.captionLabel.Caption, this.speedBox.ToString(), this.comboBox.Items[this.comboBox.SelectedIndex] }; return "%s%s\t%s (%s)" % (string_0, "Wind: ", self.speedBox.text(), self.comboBox.currentText()) def get_speed(self): try: return Speed(float(self.speedBox.text())) except: return None Value = property(get_speed, None, None, None) def get_isEmpty(self): try: num = float(self.speedBox.text()) return False except: return True IsEmpty = property(get_isEmpty, None, None, None)
class SimpleConnectWidget(QWidget): """ this widget displays a combobox with a list of instruments which the user can connect to, it also has a refresh button """ def __init__(self, parent=None): super(SimpleConnectWidget, self).__init__(parent) # main layout of the form is the verticallayout self.verticalLayout = QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") # moved the script stuff to a separate widget that lives in the toolbar self.labelLayout = QHBoxLayout() self.labelLayout.setObjectName("labelLayout") self.portLabel = QLabel(self) self.portLabel.setText("Availiable Ports") self.instrLabel = QLabel(self) self.instrLabel.setText("Instruments") self.labelLayout.addWidget(self.portLabel) self.labelLayout.addWidget(self.instrLabel) self.verticalLayout.addLayout(self.labelLayout) self.ports = QComboBox(self) self.ports.addItems(refresh_device_port_list()) self.ports.setObjectName("cbb_ports") self.instruments = QComboBox(self) self.instruments.addItems(utils.list_drivers(interface="real")[0]) self.ports.setObjectName("cbb_instrs") self.cbbLayout = QHBoxLayout() self.cbbLayout.setObjectName("cbbLayout") self.cbbLayout.addWidget(self.ports) self.cbbLayout.addWidget(self.instruments) self.verticalLayout.addLayout(self.cbbLayout) self.connectButton = QPushButton(self) self.connectButton.setText("Connect the instrument") self.connectButton.setObjectName("connectButton") self.refreshButton = QPushButton(self) self.refreshButton.setText("refresh the port list") self.refreshButton.setObjectName("refreshButton") self.verticalLayout.addWidget(self.connectButton) self.verticalLayout.addWidget(self.refreshButton) self.headerTextEdit = QPlainTextEdit("") fontsize = self.headerTextEdit.fontMetrics() pal = QPalette() textc = QColor(245, 245, 240) pal.setColor(QPalette.Base, textc) self.headerTextEdit.setPalette(pal) # d3d3be # self.headerTextEdit.ba self.headerTextEdit.setFixedHeight(fontsize.lineSpacing() * 8) self.verticalLayout.addWidget(self.headerTextEdit) # moved the start stop button to the toolbar only self.setLayout(self.verticalLayout) self.connect(self.connectButton, SIGNAL('clicked()'), self.on_connectButton_clicked) self.connect(self.refreshButton, SIGNAL('clicked()'), self.on_refreshButton_clicked) def on_connectButton_clicked(self): """Connect a given instrument through a given port""" port = self.ports.currentText() instrument_name = self.instruments.currentText() # load the module which contains the instrument's driver if __name__ == "__main__": class_inst = import_module(instrument_name) else: class_inst = import_module("." + instrument_name, package=utils.LABDRIVER_PACKAGE_NAME) msg = "" # msg.append("example") # msg.append("</span>") self.headerTextEdit.appendHtml(msg) # self.headerTextEdit.appendPlainText(msg) try: i = class_inst.Instrument(port) self.headerTextEdit.appendPlainText("%s" % (i.identify())) self.headerTextEdit.appendHtml( "The connection to the instrument %s through the port %s <span style=\" color:#009933;\" >WORKED</span>\n" % (instrument_name, port)) i.close() except: self.headerTextEdit.appendHtml( "The connection to the instrument %s through the port %s <span style=\" color:#ff0000;\" >FAILED</span>\n" % (instrument_name, port)) def on_refreshButton_clicked(self): """Refresh the list of the availiable ports""" self.ports.clear() self.ports.addItems(refresh_device_port_list())
class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setWindowTitle('Address Book') self.resize(704, 459) self.db_file = self.database_file() self.db = database.Database(self.db_file) dialog = dialogs.UserPanelDlg(self) if dialog.exec_(): self.user = dialog.user else: self.close() self.categComboBox = QComboBox() self.cont_numLabel = QLabel() self.contactsListWidget = QListWidget() self.searchLineEdit = QLineEdit() widgets = ((QLabel('Category:'), self.categComboBox), (self.cont_numLabel, None), (self.contactsListWidget,), (QLabel('Search:'), self.searchLineEdit)) vlayout1 = QVBoxLayout() for i in widgets: hlayout = pyqttools.add_to_layout(QHBoxLayout(), i) vlayout1.addLayout(hlayout) addToolButton = QToolButton() addToolButton.setIcon(QIcon(':addcontact.jpeg')) addToolButton.setIconSize(QSize(45, 45)) self.showLabel = QLabel() self.showLabel.setFrameShape(QFrame.StyledPanel) self.showLabel.setAlignment(Qt.AlignLeading|Qt.AlignLeft|Qt.AlignTop) self.editButton = QPushButton('Edit') self.delButton = QPushButton('Delete') widgets = ((None, addToolButton, None), (self.showLabel,), (None, self.editButton, self.delButton)) vlayout2 = QVBoxLayout() for i in widgets: hlayout = pyqttools.add_to_layout(QHBoxLayout(), i) vlayout2.addLayout(hlayout) f_layout = pyqttools.add_to_layout(QHBoxLayout(), (vlayout1, vlayout2)) Widget = QWidget() Widget.setLayout(f_layout) self.setCentralWidget(Widget) self.statusBar = self.statusBar() self.userLabel = QLabel() self.statusBar.addPermanentWidget(self.userLabel) c_action = pyqttools.create_action panelAction = c_action(self, 'User panel', triggered=self.user_panel) quitAction = c_action(self, 'Quit', 'Ctrl+Q',triggered=self.close) add_contactAction = c_action(self, 'Add contact', 'Ctrl+N', triggered=self.add_contact) delete_allAction = c_action(self, 'Delete all contacts', triggered=self.delete_all) delete_categAction = c_action(self, 'Delete categories', triggered=self.delete_categories) backupAction = c_action(self, 'Backup', triggered=self.backup) restoreAction = c_action(self, 'Restore', triggered=self.restore) aboutAction = c_action(self, 'About', 'Ctrl+?', triggered=self.about) fileMenu = self.menuBar().addMenu('File') contactsMenu = self.menuBar().addMenu('Contacts') deleteMenu = self.menuBar().addMenu(self.tr('Delete')) backupMenu = self.menuBar().addMenu(self.tr('Backup')) helpMenu = self.menuBar().addMenu('Help') pyqttools.add_actions(fileMenu, [panelAction, None, quitAction]) pyqttools.add_actions(contactsMenu, [add_contactAction]) pyqttools.add_actions(deleteMenu,[delete_allAction,delete_categAction]) pyqttools.add_actions(backupMenu, [backupAction, restoreAction]) pyqttools.add_actions(helpMenu, [aboutAction]) addToolButton.clicked.connect(self.add_contact) self.editButton.clicked.connect(self.edit_contact) self.delButton.clicked.connect(self.delete_contact) self.categComboBox.currentIndexChanged.connect(self.fill_ListWidget) self.contactsListWidget.currentRowChanged.connect(self.show_contact) self.searchLineEdit.textEdited.connect(self.search) self.fill_categComboBox() self.refresh_userLabel() def fill_categComboBox(self): categories = ['All'] categories.extend([i[1] for i in self.db.get_categories(self.user)]) self.categComboBox.currentIndexChanged.disconnect(self.fill_ListWidget) self.categComboBox.clear() self.categComboBox.addItems(categories) self.categComboBox.currentIndexChanged.connect(self.fill_ListWidget) self.fill_ListWidget() def fill_ListWidget(self): self.showLabel.clear() self.contactsListWidget.clear() if self.categComboBox.currentIndex() != 0: self.searchLineEdit.clear() category = self.categComboBox.currentText() if category == 'All': contacts = self.db.get_all_contacts(self.user) else: categ_id = self.db.get_category_id(category, self.user) if categ_id is None: return contacts = self.db.get_contacts(categ_id) for i in contacts: self.contactsListWidget.addItem(MyListItem(i[1]+' '+i[2], i[0])) self.contactsListWidget.setCurrentRow(0) self.refresh_contacts_number() self.set_buttons_enabled() def refresh_userLabel(self): self.userLabel.setText('User: '******'Contacts Numer: {0}'.format(self.contactsListWidget.count()) self.cont_numLabel.setText(text) def set_buttons_enabled(self): enable = bool(self.contactsListWidget) self.editButton.setEnabled(enable) self.delButton.setEnabled(enable) def user_panel(self): dialog = dialogs.UserPanelDlg(self) if dialog.exec_(): self.user = dialog.user self.fill_categComboBox() self.refresh_userLabel() def show_contact(self): try: _id = self.contactsListWidget.currentItem()._id except AttributeError: return _id, name, surname, mail, address, tel, categ_id = \ self.db.get_contact_from_id(_id)[0] category = self.db.get_category_from_id(categ_id) text = '' data = (name, surname, mail, address, tel, category) labs = ('Name', 'Surname', 'e-mail', 'Address', 'Telephone', 'Category') for i, y in zip(labs, data): text += '''<p style=\' margin-top:0px; margin-bottom:0px; \'> <span style=\' font-weight:600;\'>{0}:</span> {1} </p>\n'''\ .format(i, y) self.showLabel.setText(text) def add_contact(self): categories = [i[1] for i in self.db.get_categories(self.user)] dialog = dialogs.AddorEditContactDlg(categories) if dialog.exec_(): data = dialog.values if data[-1] not in categories: self.db.addto_categories(data[-1], self.user) categ_id = self.db.get_category_id(data[-1], self.user) data[-1] = categ_id self.db.addto_contacts(data) self.fill_categComboBox() def edit_contact(self): _id = self.contactsListWidget.currentItem()._id data = list(self.db.get_contact_from_id(_id)[0]) categ = self.db.get_category_from_id(data[-1]) data[-1] = categ categories = [i[1] for i in self.db.get_categories(self.user)] dialog = dialogs.AddorEditContactDlg(categories, True, data) if dialog.exec_(): new_data = dialog.values if new_data[-1] not in categories: self.db.addto_categories(new_data[-1], self.user) categ_id = self.db.get_category_id(new_data[-1], self.user) new_data[-1] = categ_id self.db.edit_contact(new_data, _id) self.fill_categComboBox() def delete_contact(self): reply = QMessageBox.question(self, 'Address Book - Delete Contact', 'Are you sure that you want to delete this contact?', QMessageBox.Yes|QMessageBox.Cancel) if reply == QMessageBox.Yes: _id = self.contactsListWidget.currentItem()._id self.db.delete_contact(_id) self.fill_ListWidget() def delete_all(self): reply = QMessageBox.question(self, 'Address Book - Delete Contact', 'Are you sure that you want to delete all contacts?', QMessageBox.Yes|QMessageBox.Cancel) if reply == QMessageBox.Yes: self.db.delete_all_contacts() self.fill_ListWidget() def delete_categories(self): categories = [i[1] for i in self.db.get_categories(self.user)] dialogs.DelCategoriesDlg(categories, self).exec_() self.fill_categComboBox() def search(self): self.categComboBox.setCurrentIndex(0) self.showLabel.clear() self.contactsListWidget.clear() txt = self.searchLineEdit.text() if all(i == ' ' for i in txt): self.fill_ListWidget() return must_appear = [] contacts = self.db.get_all_contacts(self.user) if not ' ' in txt: for i in contacts: if txt.lower() in i[1].lower() or txt.lower() in i[2].lower(): must_appear.append(i) else: try: first, last = txt.split() except ValueError: return for i in contacts: _bool = bool(first.lower() in i[1].lower() or first.lower() in i[2].lower() or last.lower() in i[1].lower() or last.lower() in i[2].lower()) if _bool: must_appear.append(i) for i in must_appear: item = MyListItem(i[1] + ' ' + i[2], i[0]) self.contactsListWidget.addItem(item) self.contactsListWidget.setCurrentRow(0) self.refresh_contacts_number() self.set_buttons_enabled() def backup(self): fname = QFileDialog.getSaveFileName(self,'Address Book - Backup','.db') if fname: try: shutil.copy(self.db_file, fname) except IOError: pass def restore(self): reply = QMessageBox.question(self, 'Address Book - Restore', 'All current contacts will be deleted.\nAre you sure that you want' ' to continue?', QMessageBox.Yes|QMessageBox.Cancel) if reply == QMessageBox.Yes: fname = QFileDialog.getOpenFileName(self, 'Address Book - Restore') if fname: msg = 'Succesful restore!' try: os.remove(self.db_file) shutil.copy(fname, self.db_file) except (OSError, IOError): msg = 'Restore failed!' QMessageBox.information(self, 'Addess Book - Restore', msg) self.db = database.Database(self.db_file) self.fill_categComboBox() def database_file(self): _file = 'addressbook.db' if not platform.platform().startswith('Windows'): folder = os.getenv('HOME') + os.sep + '.addressbook' if not os.path.exists(folder): os.mkdir(folder) _file = folder + os.sep + _file return _file def about(self): link = 'http://wiki.ubuntu-gr.org/Address%20Book' QMessageBox.about(self, self.tr('About') + ' FF Multi Converter', '''<b> Address Book {0} </b> <p>Gui application to organize your contacts! <p>Copyright © 2012 Ilias Stamatis <br>License: GNU GPL3 <p><a href='{1}'>http://wiki.ubuntu-gr.org/Address Book</a> <p>Python {2} - Qt {3} - PyQt {4} on {5}''' .format(__version__, link, platform.python_version()[:5], QT_VERSION_STR, PYQT_VERSION_STR, platform.system())) def close(self): self.db.close() sys.exit()
class TradingWidget(QFrame): """简单交易组件""" signal = QtCore.pyqtSignal(type(Event())) directionList = [DIRECTION_LONG, DIRECTION_SHORT] offsetList = [OFFSET_OPEN, OFFSET_CLOSE, OFFSET_CLOSEYESTERDAY, OFFSET_CLOSETODAY] priceTypeList = [PRICETYPE_LIMITPRICE, PRICETYPE_VWAP, PRICETYPE_TWAP] exchangeList = [EXCHANGE_NONE, EXCHANGE_CFFEX, EXCHANGE_SHFE, EXCHANGE_DCE, EXCHANGE_CZCE, EXCHANGE_SSE, EXCHANGE_SZSE, EXCHANGE_SGE, EXCHANGE_HKEX, EXCHANGE_CSI, EXCHANGE_HKH, EXCHANGE_HKS, EXCHANGE_JZ, EXCHANGE_SPOT, EXCHANGE_IB, EXCHANGE_FX, EXCHANGE_INE, EXCHANGE_SMART, EXCHANGE_ICE, EXCHANGE_CME, EXCHANGE_NYMEX, EXCHANGE_GLOBEX, EXCHANGE_IDEALPRO] currencyList = [CURRENCY_NONE, CURRENCY_CNY, CURRENCY_USD] productClassList = [PRODUCT_NONE, PRODUCT_EQUITY, PRODUCT_FUTURES, PRODUCT_OPTION, PRODUCT_BOND, PRODUCT_FOREX] # ---------------------------------------------------------------------- def __init__(self, mainEngine, eventEngine, parent=None): """Constructor""" super(TradingWidget, self).__init__(parent) self.mainEngine = mainEngine self.eventEngine = eventEngine self.symbol = '' self.signalemit = None self.initUi() self.connectSignal() # ---------------------------------------------------------------------- def initUi(self): """初始化界面""" self.setWindowTitle(u'交易') self.setMaximumWidth(500) self.setFrameShape(self.Box) # 设置边框 self.setLineWidth(1) # 左边部分 labelSymbol = QLabel(u'代码') labelName = QLabel(u'名称') labelDirection = QLabel(u'方向类型') labelOffset = QLabel(u'开平') labelPrice = QLabel(u'价格') labelVolume = QLabel(u'数量') labelPriceType = QLabel(u'价格类型') labelExchange = QLabel(u'交易所') labelCurrency = QLabel(u'货币') labelProductClass = QLabel(u'产品类型') labelUrgency = QLabel(u'紧急度') self.lineSymbol = QLineEdit() self.lineName = QLineEdit() self.comboDirection = QComboBox() self.comboDirection.addItems(self.directionList) self.comboOffset = QComboBox() self.comboOffset.addItem('') self.comboOffset.addItems(self.offsetList) self.comboOffset.setEnabled(False) self.tickOffset = QCheckBox(u'指定') self.spinPrice = QDoubleSpinBox() self.spinPrice.setDecimals(4) self.spinPrice.setMinimum(0) self.spinPrice.setMaximum(100000) self.spinVolume = QSpinBox() self.spinVolume.setMinimum(0) self.spinVolume.setMaximum(1000000) self.comboPriceType = QComboBox() self.comboPriceType.addItems(self.priceTypeList) self.comboExchange = QComboBox() self.comboExchange.addItems(self.exchangeList) self.comboExchange.setEnabled(False) self.comboCurrency = QComboBox() self.comboCurrency.addItems(self.currencyList) self.comboCurrency.setEnabled(False) self.comboProductClass = QComboBox() self.comboProductClass.addItems(self.productClassList) self.comboProductClass.setEnabled(False) self.spinUrgency = QSpinBox() self.spinUrgency.setMinimum(1) self.spinUrgency.setMaximum(9) self.spinUrgency.setSingleStep(1) self.spinUrgency.setValue(5) gridleft = QGridLayout() gridleft.addWidget(labelSymbol, 0, 0) gridleft.addWidget(labelName, 1, 0) gridleft.addWidget(labelDirection, 2, 0) gridleft.addWidget(labelOffset, 3, 0) gridleft.addWidget(labelPrice, 4, 0) gridleft.addWidget(labelVolume, 5, 0) gridleft.addWidget(labelPriceType, 6, 0) gridleft.addWidget(labelUrgency, 7, 0) gridleft.addWidget(labelExchange, 8, 0) gridleft.addWidget(labelProductClass, 9, 0) gridleft.addWidget(labelCurrency, 10, 0) gridleft.addWidget(self.lineSymbol, 0, 1) gridleft.addWidget(self.lineName, 1, 1) gridleft.addWidget(self.comboDirection, 2, 1) hbox1 = QHBoxLayout() hbox1.addWidget(self.comboOffset) lable1 = QLabel() hbox1.addWidget(lable1) hbox1.addWidget(self.tickOffset) hbox1.setStretchFactor(self.comboOffset, 4) hbox1.setStretchFactor(lable1, 1) hbox1.setStretchFactor(self.tickOffset, 3) gridleft.addItem(hbox1, 3, 1) gridleft.addWidget(self.spinPrice, 4, 1) gridleft.addWidget(self.spinVolume, 5, 1) gridleft.addWidget(self.comboPriceType, 6, 1) gridleft.addWidget(self.spinUrgency, 7, 1) gridleft.addWidget(self.comboExchange, 8, 1) gridleft.addWidget(self.comboProductClass, 9, 1) gridleft.addWidget(self.comboCurrency, 10, 1) # 右边部分 labelBid1 = QLabel(u'买一') labelBid2 = QLabel(u'买二') labelBid3 = QLabel(u'买三') labelBid4 = QLabel(u'买四') labelBid5 = QLabel(u'买五') labelAsk1 = QLabel(u'卖一') labelAsk2 = QLabel(u'卖二') labelAsk3 = QLabel(u'卖三') labelAsk4 = QLabel(u'卖四') labelAsk5 = QLabel(u'卖五') self.labelBidPrice1 = QLabel() self.labelBidPrice2 = QLabel() self.labelBidPrice3 = QLabel() self.labelBidPrice4 = QLabel() self.labelBidPrice5 = QLabel() self.labelBidVolume1 = QLabel() self.labelBidVolume2 = QLabel() self.labelBidVolume3 = QLabel() self.labelBidVolume4 = QLabel() self.labelBidVolume5 = QLabel() self.labelAskPrice1 = QLabel() self.labelAskPrice2 = QLabel() self.labelAskPrice3 = QLabel() self.labelAskPrice4 = QLabel() self.labelAskPrice5 = QLabel() self.labelAskVolume1 = QLabel() self.labelAskVolume2 = QLabel() self.labelAskVolume3 = QLabel() self.labelAskVolume4 = QLabel() self.labelAskVolume5 = QLabel() labelLast = QLabel(u'最新') self.labelLastPrice = QLabel() self.labelReturn = QLabel() self.labelLastPrice.setMinimumWidth(60) self.labelReturn.setMinimumWidth(60) gridRight = QGridLayout() gridRight.addWidget(labelAsk5, 0, 0) gridRight.addWidget(labelAsk4, 1, 0) gridRight.addWidget(labelAsk3, 2, 0) gridRight.addWidget(labelAsk2, 3, 0) gridRight.addWidget(labelAsk1, 4, 0) gridRight.addWidget(labelLast, 5, 0) gridRight.addWidget(labelBid1, 6, 0) gridRight.addWidget(labelBid2, 7, 0) gridRight.addWidget(labelBid3, 8, 0) gridRight.addWidget(labelBid4, 9, 0) gridRight.addWidget(labelBid5, 10, 0) gridRight.addWidget(self.labelAskPrice5, 0, 1) gridRight.addWidget(self.labelAskPrice4, 1, 1) gridRight.addWidget(self.labelAskPrice3, 2, 1) gridRight.addWidget(self.labelAskPrice2, 3, 1) gridRight.addWidget(self.labelAskPrice1, 4, 1) gridRight.addWidget(self.labelLastPrice, 5, 1) gridRight.addWidget(self.labelBidPrice1, 6, 1) gridRight.addWidget(self.labelBidPrice2, 7, 1) gridRight.addWidget(self.labelBidPrice3, 8, 1) gridRight.addWidget(self.labelBidPrice4, 9, 1) gridRight.addWidget(self.labelBidPrice5, 10, 1) gridRight.addWidget(self.labelAskVolume5, 0, 2) gridRight.addWidget(self.labelAskVolume4, 1, 2) gridRight.addWidget(self.labelAskVolume3, 2, 2) gridRight.addWidget(self.labelAskVolume2, 3, 2) gridRight.addWidget(self.labelAskVolume1, 4, 2) gridRight.addWidget(self.labelReturn, 5, 2) gridRight.addWidget(self.labelBidVolume1, 6, 2) gridRight.addWidget(self.labelBidVolume2, 7, 2) gridRight.addWidget(self.labelBidVolume3, 8, 2) gridRight.addWidget(self.labelBidVolume4, 9, 2) gridRight.addWidget(self.labelBidVolume5, 10, 2) # 发单按钮 buttonSendOrder = QPushButton(u'发单') buttonCancelAll = QPushButton(u'全撤') size = buttonSendOrder.sizeHint() buttonSendOrder.setMinimumHeight(size.height() * 2) # 把按钮高度设为默认两倍 buttonCancelAll.setMinimumHeight(size.height() * 2) # 整合布局 hbox = QHBoxLayout() hbox.addLayout(gridleft) hbox.addLayout(gridRight) vbox = QVBoxLayout() vbox.addLayout(hbox) vbox.addWidget(buttonSendOrder) vbox.addWidget(buttonCancelAll) vbox.addStretch() self.setLayout(vbox) # 关联更新 buttonSendOrder.clicked.connect(self.sendOrder) buttonCancelAll.clicked.connect(self.cancelAll) self.lineSymbol.returnPressed.connect(self.updateSymbol) self.comboDirection.currentIndexChanged.connect(self.updateOffset) self.tickOffset.stateChanged.connect(self.updateOffset) self.labelAskPrice1.mouseDoubleClickEvent = self.ask1clicked self.labelAskPrice2.mouseDoubleClickEvent = self.ask2clicked self.labelAskPrice3.mouseDoubleClickEvent = self.ask3clicked self.labelAskPrice4.mouseDoubleClickEvent = self.ask4clicked self.labelAskPrice5.mouseDoubleClickEvent = self.ask5clicked self.labelBidPrice1.mouseDoubleClickEvent = self.bid1clicked self.labelBidPrice2.mouseDoubleClickEvent = self.bid2clicked self.labelBidPrice3.mouseDoubleClickEvent = self.bid3clicked self.labelBidPrice4.mouseDoubleClickEvent = self.bid4clicked self.labelBidPrice5.mouseDoubleClickEvent = self.bid5clicked self.labelLastPrice.mouseDoubleClickEvent = self.lastclicked def ask1clicked(self, a): self.askclicked(self.labelAskPrice1.text()) def ask2clicked(self, a): self.askclicked(self.labelAskPrice2.text()) def ask3clicked(self, a): self.askclicked(self.labelAskPrice3.text()) def ask4clicked(self, a): self.askclicked(self.labelAskPrice4.text()) def ask5clicked(self, a): self.askclicked(self.labelAskPrice5.text()) def bid1clicked(self, a): self.bidclicked(self.labelBidPrice1.text()) def bid2clicked(self, a): self.bidclicked(self.labelBidPrice2.text()) def bid3clicked(self, a): self.bidclicked(self.labelBidPrice3.text()) def bid4clicked(self, a): self.bidclicked(self.labelBidPrice4.text()) def bid5clicked(self, a): self.bidclicked(self.labelBidPrice5.text()) def lastclicked(self, a): self.setPrice(self.labelLastPrice.text()) def setPrice(self, text): result = False if text is not None and len(text) > 0: price = float(str(text)) if price > 0: self.spinPrice.setValue(price) result = True return result def askclicked(self, text): if self.setPrice(text): self.comboDirection.setCurrentIndex(self.directionList.index(DIRECTION_LONG)) self.updateOffset() def bidclicked(self, text): if self.setPrice(text): self.comboDirection.setCurrentIndex(self.directionList.index(DIRECTION_SHORT)) self.updateOffset() def updateOffset(self): if self.tickOffset.checkState(): self.comboOffset.setEnabled(True) if self.comboProductClass.currentText() in (PRODUCT_EQUITY, PRODUCT_BOND): dir = self.comboDirection.currentText() if dir == DIRECTION_LONG: self.comboOffset.setCurrentIndex(self.offsetList.index(OFFSET_OPEN) + 1) elif dir == DIRECTION_SHORT: self.comboOffset.setCurrentIndex(self.offsetList.index(OFFSET_CLOSE) + 1) elif self.comboOffset.currentIndex() == 0: self.comboOffset.setCurrentIndex(1) else: self.comboOffset.setEnabled(False) self.comboOffset.setCurrentIndex(0) # ---------------------------------------------------------------------- def updateSymbol(self): """合约变化""" # 读取组件数据 symbol = str(self.lineSymbol.text()) self.comboCurrency.setCurrentIndex(1) currency = safeUnicode(self.comboCurrency.currentText()) gatewayName = safeUnicode('quantos') # 查询合约 contract = self.mainEngine.getContract(symbol) # 清空价格数量 self.spinPrice.setValue(0) self.spinVolume.setValue(0) if contract: gatewayName = contract.gatewayName self.lineName.setText(contract.name) p = self.lineName.palette() p.setColor(self.lineName.foregroundRole(), QtGui.QColor('black')) self.lineName.setPalette(p) exchange = contract.exchange productClass = contract.productClass self.comboExchange.setCurrentIndex(self.exchangeList.index(exchange)) self.comboProductClass.setCurrentIndex(self.productClassList.index(productClass)) self.spinPrice.setSingleStep(contract.priceTick) self.spinVolume.setSingleStep(contract.lotsize) self.updateOffset() else: self.comboExchange.setCurrentIndex(0) self.comboProductClass.setCurrentIndex(0) productClass = safeUnicode(self.comboProductClass.currentText()) exchange = safeUnicode(self.comboExchange.currentText()) self.lineName.setText(u'不存在') p = self.lineName.palette() p.setColor(self.lineName.foregroundRole(), QtGui.QColor('red')) self.lineName.setPalette(p) # 清空行情显示 self.labelBidPrice1.setText('') self.labelBidPrice2.setText('') self.labelBidPrice3.setText('') self.labelBidPrice4.setText('') self.labelBidPrice5.setText('') self.labelBidVolume1.setText('') self.labelBidVolume2.setText('') self.labelBidVolume3.setText('') self.labelBidVolume4.setText('') self.labelBidVolume5.setText('') self.labelAskPrice1.setText('') self.labelAskPrice2.setText('') self.labelAskPrice3.setText('') self.labelAskPrice4.setText('') self.labelAskPrice5.setText('') self.labelAskVolume1.setText('') self.labelAskVolume2.setText('') self.labelAskVolume3.setText('') self.labelAskVolume4.setText('') self.labelAskVolume5.setText('') self.labelLastPrice.setText('') self.labelReturn.setText('') if contract: # 重新注册事件监听 if self.signalemit != None: self.eventEngine.unregister(EVENT_TICK + self.symbol, self.signalemit) self.signalemit = self.signal.emit self.eventEngine.register(EVENT_TICK + symbol, self.signalemit) # 订阅合约 self.mainEngine.subscribe(contract.symbol, gatewayName) # 更新组件当前交易的合约 self.symbol = symbol # ---------------------------------------------------------------------- def format_price(self, price): return int(price * 1000) / 1000 # ---------------------------------------------------------------------- def updateTick(self, event): """更新行情""" tick = event.dict_['data'] if tick.symbol == self.symbol: contract = self.mainEngine.getContract(tick.symbol) price_tick = contract.priceTick self.labelBidPrice1.setText(str(self.format_price(tick.bidPrice1))) self.labelAskPrice1.setText(str(self.format_price(tick.askPrice1))) self.labelBidVolume1.setText(str(tick.bidVolume1)) self.labelAskVolume1.setText(str(tick.askVolume1)) if tick.bidPrice2: self.labelBidPrice2.setText(str(self.format_price(tick.bidPrice2))) self.labelBidPrice3.setText(str(self.format_price(tick.bidPrice3))) self.labelBidPrice4.setText(str(self.format_price(tick.bidPrice4))) self.labelBidPrice5.setText(str(self.format_price(tick.bidPrice5))) self.labelAskPrice2.setText(str(self.format_price(tick.askPrice2))) self.labelAskPrice3.setText(str(self.format_price(tick.askPrice3))) self.labelAskPrice4.setText(str(self.format_price(tick.askPrice4))) self.labelAskPrice5.setText(str(self.format_price(tick.askPrice5))) self.labelBidVolume2.setText(str(tick.bidVolume2)) self.labelBidVolume3.setText(str(tick.bidVolume3)) self.labelBidVolume4.setText(str(tick.bidVolume4)) self.labelBidVolume5.setText(str(tick.bidVolume5)) self.labelAskVolume2.setText(str(tick.askVolume2)) self.labelAskVolume3.setText(str(tick.askVolume3)) self.labelAskVolume4.setText(str(tick.askVolume4)) self.labelAskVolume5.setText(str(tick.askVolume5)) self.labelLastPrice.setText(str(self.format_price(tick.lastPrice))) if self.spinPrice.value() < 0.000001 and tick.lastPrice > 0.000001: self.spinPrice.setValue(tick.lastPrice) if tick.preClosePrice: rt = (old_div(tick.lastPrice, tick.preClosePrice)) - 1 self.labelReturn.setText(('%.2f' % (rt * 100)) + '%') else: self.labelReturn.setText('') # ---------------------------------------------------------------------- def connectSignal(self): """连接Signal""" self.signal.connect(self.updateTick) # ---------------------------------------------------------------------- def sendOrder(self): """发单""" symbol = str(self.lineSymbol.text()).strip() exchange = safeUnicode(self.comboExchange.currentText()) price = self.spinPrice.value() volume = self.spinVolume.value() gatewayName = safeUnicode('quantos') if len(symbol) <= 0 or len(exchange) <= 0 or price <= 0 or volume <= 0: return # 查询合约 contract = self.mainEngine.getContract(symbol) if contract: gatewayName = contract.gatewayName exchange = contract.exchange # 保证有交易所代码 req = VtOrderReq() idx = symbol.find(".") if idx != -1: req.symbol = symbol[0:idx] else: req.symbol = symbol req.exchange = exchange req.price = price req.volume = volume req.direction = safeUnicode(self.comboDirection.currentText()) req.priceType = safeUnicode(self.comboPriceType.currentText()) req.offset = safeUnicode(self.comboOffset.currentText()) req.urgency = self.spinUrgency.value() req.productClass = safeUnicode(self.comboProductClass.currentText()) self.mainEngine.sendOrder(req, gatewayName) # ---------------------------------------------------------------------- def cancelAll(self): """一键撤销所有委托""" l = self.mainEngine.getAllWorkingOrders() for order in l: req = VtCancelOrderReq() req.symbol = order.symbol req.exchange = order.exchange req.frontID = order.frontID req.sessionID = order.sessionID req.orderID = order.taskID self.mainEngine.cancelOrder(req, order.gatewayName) # ---------------------------------------------------------------------- def closePosition(self, cell): """根据持仓信息自动填写交易组件""" # 读取持仓数据,cell是一个表格中的单元格对象 pos = cell.data symbol = pos.symbol # 更新交易组件的显示合约 self.lineSymbol.setText(symbol) self.updateSymbol() # 自动填写信息 self.comboPriceType.setCurrentIndex(self.priceTypeList.index(PRICETYPE_LIMITPRICE)) self.spinVolume.setValue(pos.enable) if pos.direction == DIRECTION_LONG or pos.direction == DIRECTION_NET: self.comboDirection.setCurrentIndex(self.directionList.index(DIRECTION_SHORT)) else: self.comboDirection.setCurrentIndex(self.directionList.index(DIRECTION_LONG)) if self.comboProductClass.currentText() not in (PRODUCT_EQUITY, PRODUCT_BOND): self.tickOffset.setChecked(True) self.comboOffset.setCurrentIndex(self.offsetList.index(OFFSET_CLOSE) + 1) elif self.tickOffset.checkState(): self.comboOffset.setCurrentIndex(self.offsetList.index(OFFSET_CLOSE) + 1) # 价格留待更新后由用户输入,防止有误操作 def fillSymbol(self, cell): tick = cell.data self.lineSymbol.setText(tick.symbol) self.updateSymbol() if type(cell) in (BidCell, AskCell): price = str(cell.text()) if len(price) > 0: price = float(price) if price > 0: self.spinPrice.setValue(price) direction = DIRECTION_LONG if type(cell) is AskCell else DIRECTION_SHORT self.comboDirection.setCurrentIndex(self.directionList.index(direction)) self.updateOffset()
class Printing(preferences.Group): def __init__(self, page): super(Printing, self).__init__(page) layout = QGridLayout(spacing=1) self.setLayout(layout) self.messageLabel = QLabel(wordWrap=True) self.printCommandLabel = QLabel() self.printCommand = widgets.urlrequester.UrlRequester() self.printCommand.setFileMode(QFileDialog.ExistingFile) self.printCommand.changed.connect(page.changed) self.printDialogCheck = QCheckBox(toggled=page.changed) self.resolutionLabel = QLabel() self.resolution = QComboBox(editable=True, editTextChanged=page.changed) self.resolution.addItems("300 600 1200".split()) self.resolution.lineEdit().setInputMask("9000") layout.addWidget(self.messageLabel, 0, 0, 1, 2) layout.addWidget(self.printCommandLabel, 1, 0) layout.addWidget(self.printCommand, 1, 1) layout.addWidget(self.printDialogCheck, 2, 0, 1, 2) layout.addWidget(self.resolutionLabel, 3, 0) layout.addWidget(self.resolution, 3, 1) app.translateUI(self) def translateUI(self): self.setTitle(_("Printing Music")) self.messageLabel.setText(_( "Here you can enter a command to print a PDF or PostScript file. " "See the Help page for more information about printing music.")) self.printCommandLabel.setText(_("Printing command:")) self.printCommand.setToolTip('<qt>' + _( "The printing command is used to print a PostScript or PDF file. " "On Linux you don't need this, but on Windows and Mac OS X you can " "provide a command to avoid that PDF documents are being printed " "using raster images, which is less optimal.\n" "<code>$pdf</code> gets replaced with the PDF filename, or alternatively, " "<code>$ps</code> is replaced with the PostScript filename. " "<code>$printer</code> is replaced with the printer's name to use.")) self.printDialogCheck.setText(_("Use Frescobaldi's print dialog")) self.printDialogCheck.setToolTip('<qt>' + _( "If enabled, Frescobaldi will show the print dialog and create a " "PDF or PostScript document containing only the selected pages " "to print. Otherwise, the command is called directly and is expected " "to show a print dialog itself.")) self.resolutionLabel.setText(_("Resolution:")) self.resolution.setToolTip(_( "Set the resolution if Frescobaldi prints using raster images.")) def loadSettings(self): s = QSettings() s.beginGroup("helper_applications") self.printCommand.setPath(s.value("printcommand", "", type(""))) self.printDialogCheck.setChecked(s.value("printcommand/dialog", False, bool)) with qutil.signalsBlocked(self.resolution): self.resolution.setEditText(format(s.value("printcommand/dpi", 300, int))) def saveSettings(self): s= QSettings() s.beginGroup("helper_applications") s.setValue("printcommand", self.printCommand.path()) s.setValue("printcommand/dialog", self.printDialogCheck.isChecked()) s.setValue("printcommand/dpi", int(self.resolution.currentText()))
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 Window(QtGui.QMainWindow): def __init__(self): super(Window, self).__init__() self.init_UI() def init_UI(self): self.save_folder = "" self.box = "" self.all_data, self.curr_data = self.readfile() self.setFixedSize(1200, 950) self.dates() self.info() self.buttons() self.sim_list() self.curr_list() self.add_plot() self.log_flag = False self.setWindowTitle("SIMULATION TOOL") self.error = False self.error_box() # self.radio_buttons() """UI FUNCTIONS""" def paintEvent(self, event): lines = QtGui.QPainter(self) # pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine) # lines.setPen(pen) lines.begin(self) lines.drawRect(20, 20, 230, 110) lines.drawRect(250, 20, 340, 110) lines.drawRect(620, 20, 560, 110) lines.drawRect(10, 10, 1180, 930) lines.drawRect(10, 149, 1180, 701) lines.end() def info(self): #Create a label where trades stats can be appended self.stats_info = QtGui.QLabel(self) self.stats_info.setGeometry(20, 860, 300, 80) self.stats_info.setText("") self.brute_lab = QtGui.QLabel(self) self.brute_lab.setGeometry(300, 870, 300, 60) self.brute_lab.setText("") def error_box(self): self.errb = QCheckBox("Error checking", self) self.errb.setGeometry(1080, 20, 100, 90) self.errb.setChecked(False) self.errb.stateChanged.connect(self.error_truth) def dates(self): #Create date input boxes self.from_lab = QtGui.QLabel(self) self.from_lab.setGeometry(30, 30, 71, 16) self.from_lab.setText('Date from') self.from_edit = QtGui.QLineEdit(self) self.from_edit.setGeometry(30, 50, 61, 20) self.from_edit.setPlaceholderText('20170101') self.to_lab = QtGui.QLabel(self) self.to_lab.setGeometry(120, 30, 71, 16) self.to_lab.setText('Date to') self.to_edit = QtGui.QLineEdit(self) self.to_edit.setGeometry(120, 50, 61, 20) self.to_edit.setPlaceholderText('20170630') def sim_list(self): #Create list of indices self.cb = QComboBox(self) self.cb.addItems(list(self.all_data.columns)) self.cb.currentIndexChanged.connect(self.plot_chart) self.cb.setGeometry(140, 80, 100, 40) def curr_list(self): #Create list of currrncies self.cl = QComboBox(self) self.cl.addItems(list(self.curr_data.columns)) self.cl.setGeometry(30, 80, 100, 40) def buttons(self): #Create all buttons and connect to appropiate functions #Row 1 starts self.a = QtGui.QPushButton('IMPLEMENT STRAT', self) self.a.clicked.connect(self.tester) self.a.setGeometry(260, 30, 100, 40) self.mov = QtGui.QPushButton('Derivative', self) self.mov.clicked.connect(self.deriv_strat) self.mov.setGeometry(370, 30, 100, 40) self.mov = QtGui.QPushButton('Moving Average', self) self.mov.clicked.connect(self.moving_average) self.mov.setGeometry(480, 30, 100, 40) #Row 2 strats self.b = QtGui.QPushButton('IMPLEMENT STRAT', self) self.b.clicked.connect(self.tester) self.b.setGeometry(260, 80, 100, 40) self.gc = QtGui.QPushButton('Golden Cross', self) self.gc.clicked.connect(self.gd) self.gc.setGeometry(370, 80, 100, 40) self.mr = QtGui.QPushButton('Mean Reversal', self) self.mr.clicked.connect(self.mean_reversion) self.mr.setGeometry(480, 80, 100, 40) #Row 1 funcs self.mavg = QtGui.QPushButton('Moving Average\nIndex', self) self.mavg.clicked.connect(self.plot_mov_avg) self.mavg.setGeometry(630, 30, 100, 40) self.log = QtGui.QPushButton('Scale', self) self.log.clicked.connect(self.log_scale) self.log.setGeometry(740, 30, 100, 40) self.repl = QtGui.QPushButton('Reset', self) self.repl.clicked.connect(self.plot_chart) self.repl.setGeometry(850, 30, 100, 40) self.sf = QtGui.QPushButton('Save Figure', self) self.sf.clicked.connect(self.save_fig) self.sf.setGeometry(960, 30, 100, 40) #Row 2 funcs self.opt = QtGui.QPushButton('Optimal\nMoving Average', self) self.opt.clicked.connect(self.brutefor) self.opt.setGeometry(630, 80, 100, 40) self.cur = QtGui.QPushButton('Currency\nPerformance', self) self.cur.clicked.connect(self.currperf) self.cur.setGeometry(740, 80, 100, 40) self.plot = QtGui.QPushButton('Plot', self) self.plot.clicked.connect(self.plot_chart_diff_curr) self.plot.setGeometry(850, 80, 100, 40) self.sf = QtGui.QPushButton('Save Folder', self) self.sf.clicked.connect(self.set_save_folder) self.sf.setGeometry(960, 80, 100, 40) """PLOTTING FUNCTIONS""" def plot_stats(self, ml): #Fetch trade stats and write to UI print(ml) trades = int(ml[0]) avg = int(ml[1]) maxval = int(ml[2]) minval = int(ml[3]) med = int(ml[4]) text = "Amount of trades: %.1f \nAverage amount of days between trades: %.1f \nMedian amount of days between trades: %.1f \nLongest period of days between trades: %.1f \nShortest amount of days between trades: %.1f" % ( trades, med, avg, maxval, minval) print(self.error) if self.error: errnum = ml[5] text2 = "\nAmount of error trades: %d" % errnum text = text + text2 print(text) self.stats_info.setText(text) def add_plot(self): #Intialise matplotlib in the UI currency = self.cl.currentText() index = self.cb.currentText() self.figure = Figure() #Create fig self.canvas = FigureCanvasQTAgg(self.figure) self.canvas.setParent(self) self.canvas.setGeometry(11, 150, 1179, 700) self.axis = self.figure.add_subplot(111) self.axis.set_xlabel("") self.axis.legend(loc=2) to_plot = self.all_data[ self.cb.currentText()] #Plotting data is first item in list to_plot = self.reindex(to_plot) #Plot from 100 self.first_date = to_plot.index[ 0] #Set universal variable for currency plotting text = index + " " + currency self.plotter(to_plot, text) #Plot def plot_strat(self, to_plot, name): #Plot each individual strategy (E.g movin avg) currency = self.cl.currentText() to_plot = self.date_cut(to_plot) to_plot = self.to_series(to_plot) to_plot = self.reindex(to_plot) text = name + " " + currency self.plotter(to_plot, text) def plot_chart(self): #Plot a new base chart and clear everything self.cl.setCurrentIndex(0) currency = self.cl.currentText() column = self.cb.currentText() all_curr_data = self.curr_data[currency] to_plot = self.all_data[column] to_plot = to_plot.dropna() to_plot = self.date_cut(to_plot) all_curr_data = self.date_cut(all_curr_data) to_plot = self.to_series(to_plot) all_curr_data = self.to_series(all_curr_data) to_plot = to_plot.div(all_curr_data) to_plot = self.reindex(to_plot) self.first_date = to_plot.index[0] self.axis.clear() text = column + " " + currency self.plotter(to_plot, text) self.stats_info.setText("") def plot_chart_diff_curr(self): #Plot base chart in a different curenncy currency = self.cl.currentText() column = self.cb.currentText() all_curr_data = self.curr_data[currency] to_plot = self.all_data[column] to_plot = to_plot.dropna() to_plot = self.date_cut(to_plot) all_curr_data = self.date_cut(all_curr_data) to_plot = self.to_series(to_plot) all_curr_data = self.to_series(all_curr_data) to_plot = to_plot.div(all_curr_data) to_plot = self.reindex(to_plot) text = column + " " + currency self.plotter(to_plot, text) def currperf(self): currency = self.cl.currentText() curr = self.curr_data[currency] to_plot = curr to_plot = self.date_cut(to_plot) to_plot = to_plot.truncate(before=self.first_date) to_plot = self.reindex(to_plot) text = "USD : " + currency self.plotter(to_plot, text) def plot_mov_avg(self): currency = self.cl.currentText() curr = self.curr_data[currency] column = self.cb.currentText() number = self.getint("Enter moving average") text = "%s %s %d Moving Average" % (column, currency, number) data = self.all_data[column] data = data.div(curr) data = data.dropna() to_plot = data.rolling(window=number).mean() if self.from_edit.text() != '' and self.from_edit.text() != '': to_plot = self.date_cut(to_plot) else: to_plot = to_plot.truncate(before=self.first_date) firstval = self.to_series( self.date_cut(self.all_data[column].div(curr))).dropna()[0] print(firstval) to_plot = self.to_series(to_plot) to_plot = to_plot / firstval * 100 self.plotter(to_plot, text) def plotter(self, to_plot, text): #Plots to_plot on plot self.axis.plot(to_plot, label=text) self.axis.legend(loc=2) self.canvas.draw() """Strategies""" def mean_reversion(self): currency = self.cl.currentText() curr = self.curr_data[currency] column = self.cb.currentText() func = mean_reversal nr_stdev = self.getfloat("Number of standard deviations") number = self.getint("Enter moving average") text = " " + str(nr_stdev) + " Deviation - Mean Reversion" data = self.all_data[column] signals, diffs = func(data, number, curr, nr_stdev) self.simulate(data, number, curr, text, signals, diffs) def moving_average(self): func = mov_avg self.strats(func) def gd(self): func = golden_cross text = ":50 GC" self.strats(func, text) def deriv_strat(self): func = derivative_strat text = ":200 Derivative" self.strats(func, text) def brutefor(self): #Find the best moving avarge lower = self.getint("Enter lower bound") upper = self.getint("Enter upper bound") self.complaint_box("This might take a while...\n") currency = self.cl.currentText() curr = self.curr_data[currency] column = self.cb.currentText() data = self.all_data[column] data = optimizer(column, currency, data, curr, lower, upper) print(data) self.bruteplot(data) def strats(self, func, text="", number=200): currency = self.cl.currentText() curr = self.curr_data[currency] column = self.cb.currentText() if number == 200: number = self.getint("Enter moving average") data = self.all_data[column] signals, diffs = func(data, number, curr) if self.error: self.error_checking(data, number, curr, text, signals, diffs) else: self.simulate(data, number, curr, text, signals, diffs) def simulate(self, data, number, curr, text, signals, diffs): if self.from_edit.text() != '' and self.from_edit.text() != '': signals = self.date_cut(signals) signals = self.to_series(signals) to_plot, masterlist = simulator(data, signals, diffs, curr) text = str(number) + text self.plot_strat(to_plot, text) self.plot_stats(masterlist) def error_checking(self, data, number, curr, text, signals, diffs): print("ERROR CHECK") if self.from_edit.text() != '' and self.from_edit.text() != '': signals = self.date_cut(signals) signals = self.to_series(signals) errnum = self.getint("Enter days for error check") to_plot, masterlist, days_between_trades = simulator_error_check( data, signals, diffs, curr, errnum) text = str(number) + text self.plot_strat(to_plot, text) self.plot_stats(masterlist) self.histogram(days_between_trades) """Underlying UI""" def histogram(self, data): print('test') window = QtGui.QMainWindow(self) window.setAttribute(QtCore.Qt.WA_DeleteOnClose) window.setWindowTitle(self.tr('Histogram')) window.setFixedSize(600, 600) figure = Figure() #Create fig canvas = FigureCanvasQTAgg(figure) canvas.setParent(window) canvas.setGeometry(10, 10, 580, 580) ax = figure.add_subplot(111) ax.hist(data, 100) canvas.draw() window.show() def bruteplot(self, data): window = QtGui.QMainWindow(self) window.setAttribute(QtCore.Qt.WA_DeleteOnClose) window.setWindowTitle(self.tr('Best Moving Average')) window.setFixedSize(1000, 600) figure = Figure() #Create fig canvas = FigureCanvasQTAgg(figure) canvas.setParent(window) canvas.setGeometry(10, 10, 980, 580) ax = figure.add_subplot(111) ax.plot(data) canvas.draw() window.show() def set_save_folder(self): self.save_folder = str( QtGui.QFileDialog.getExistingDirectory(self, "Select Directory")) return None def complaint_box(self, text): #Create an angry box when users f**** up error_dialog = QtGui.QErrorMessage(self) error_dialog.setWindowModality(QtCore.Qt.WindowModal) error_dialog.showMessage(text) def getint(self, text): print(text) num, ok = QtGui.QInputDialog.getInt(self, "Integer Input", text) if ok: print(num) return num def getfloat(self, text): print(text) num, ok = QtGui.QInputDialog.getDouble(self, "Float Input", text) if ok: print(num) return num def save_fig(self): #Save figure if self.save_folder != "": self.figure.savefig(self.save_folder + '/test.png') self.complaint_box('Figure saved in ' + self.save_folder) else: self.complaint_box('Choose a folder to save in') def log_scale(self): if self.log_flag: #Change y-scale to linear self.axis.set_yscale('linear') self.log_flag = False self.canvas.draw() else: #Change y-scale to log self.axis.set_yscale('log') self.log_flag = True self.canvas.draw() def error_truth(self): #Inlcude error stats or not self.error = not self.error """Short data funtions""" def reindex(self, data): data = self.to_series(data) data = data.dropna() data = data / data[0] * 100 return data def to_series( self, data ): #If input is pandas DF, return series based on first columns. if isinstance(data, pd.DataFrame): data = data[data.columns[0]] return data def date_cut(self, data): #Cut datframe to specified dates if self.from_edit.text() != '' and self.from_edit.text( ) != '': #Check input boxes if not isinstance( data, pd.DataFrame): #Make sire input actually is a dataframe data = data.to_frame() try: data.index = data.index.to_datetime() from_date = pd.to_datetime(str(self.from_edit.text()), format='%Y%m%d') to_date = pd.to_datetime(str(self.to_edit.text()), format='%Y%m%d') data = data.truncate(before=from_date, after=to_date) #Cut except: err = sys.exc_info()[0] err2 = sys.exc_info()[1] print(err, err2) self.complaint_box( "Invalid date, plotting all \n The index starts " + data.index[0] + " and ends " + data.index[-1] + ".") return data def readfile(self): #Read input data data = pd.read_excel("file path to index data") # data.index = data.index.to_datetime() curr_data = pd.read_excel("file path to currency data") # curr_data.index = data.index.to_datetime() return data, curr_data def tester(self): #Test function for UI elemtents print("Something happens")
class UpdatePolygonInfoUI(QDialog): def __init__(self, iface, parent=None): super(UpdatePolygonInfoUI, self).__init__() self.iface = iface self.parent = parent self.polygon_layer = self.iface.activeLayer() self.initUI() # 初始化界面 def initUI(self): self.setWindowTitle(u"Polygon") polygon_id_label = QLabel(u'"Polygon" 来源: ') self.polygon_id = QComboBox() content_label = QLabel(u'"其他" 来源: ') self.content = QComboBox() fields = [] for field in self.polygon_layer.pendingFields(): fields.append(field.name().strip()) self.polygon_id.addItems(fields) fields.insert(0, u"") self.content.addItems(fields) button_hbox = QHBoxLayout() button_hbox.addStretch(1) ok = QPushButton(u"确定") self.connect(ok, SIGNAL("clicked()"), self.run) button_hbox.addWidget(ok) cancel = QPushButton(u"取消") self.connect(cancel, SIGNAL("clicked()"), self.accept) button_hbox.addWidget(cancel) button_hbox.addStretch(1) grid = QGridLayout() grid.setSpacing(10) grid.addWidget(polygon_id_label, 0, 1) grid.addWidget(self.polygon_id, 0, 2) grid.addWidget(content_label, 1, 1) grid.addWidget(self.content, 1, 2) vbox = QVBoxLayout() vbox.setSpacing(10) vbox.addLayout(grid) vbox.addStretch(1) vbox.addLayout(button_hbox) self.setLayout(vbox) self.resize(300, 120) # 确定按钮监听事件 def run(self): polygon_id_field = self.polygon_id.currentText().strip() content_field = self.content.currentText().strip() result = updatePolygonInfo(self.iface, self.polygon_layer, polygon_id_field, content_field, self) if result: QMessageBox.information(self, u"更新Polygon属性", u"更新相关字段成功!") else: QMessageBox.critical(self, u"更新Polygon属性", u"更新相关字段失败!") self.accept()
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 options(QWidget): def __init__(self, parent): QWidget.__init__(self) self.init(parent) self.initShape() def init(self, parent): self.heditor = parent def initShape(self): self.vbox = QVBoxLayout() self.optab = QTabWidget() self.fill = QWidget() self.createHexOptions() self.vbox.addWidget(self.optab) self.createButtons() self.vbox.addWidget(self.fill) self.setLayout(self.vbox) def createPageOptions(self): self.pagegrid = QGridLayout() self.pagegroup = QWidget() pagelabel = QLabel("Page size : ") self.sizeEdit = QFFSpinBox(self) self.sizeEdit.setMaximum(self.heditor.filesize) self.sizeEdit.setValue(self.heditor.pageSize) # psize = QString("%.2d" % self.heditor.pageSize) # self.sizeEdit.insert(psize) headerlabel = QLabel("Header size : ") self.headEdit = QFFSpinBox(self) self.headEdit.setMaximum(self.heditor.filesize) self.headEdit.setValue(self.heditor.pageHead) # phead = QString("%.2d" % self.heditor.pageHead) # self.headEdit.insert(phead) sparelabel = QLabel("Spare size : ") self.spareEdit = QFFSpinBox(self) self.spareEdit.setMaximum(self.heditor.filesize) self.spareEdit.setValue(self.heditor.pageSpare) # pspare = QString("%.2d" % self.heditor.pageSpare) # self.spareEdit.insert(pspare) ppb = QLabel("Pages per block:") self.pagesperblock = QComboBox() self.pagesperblock.addItem("8") self.pagesperblock.addItem("16") self.pagesperblock.addItem("32") self.pagesperblock.addItem("64") self.pagesperblock.addItem("128") self.pagesperblock.addItem("256") self.pagesperblock.addItem("512") self.pagesperblock.setCurrentIndex(2) # lview = QLabel("Left indication: ") # self.indic = QComboBox() # self.indic.addItem("Offset") # self.indic.addItem("Block") # self.pagesperlineEdit = QLineEdit() # ppl = QString("%.2d" % self.heditor.pagesPerBlock) # self.pagesperlineEdit.insert(ppl) self.pagegrid.addWidget(pagelabel, 0, 0) self.pagegrid.addWidget(self.sizeEdit, 0, 1) self.pagegrid.addWidget(headerlabel, 1, 0) self.pagegrid.addWidget(self.headEdit, 1, 1) self.pagegrid.addWidget(sparelabel, 2, 0) self.pagegrid.addWidget(self.spareEdit, 2, 1) self.pagegrid.addWidget(ppb, 3 ,0) self.pagegrid.addWidget(self.pagesperblock, 3, 1) # self.pagegrid.addWidget(lview, 4, 0) # self.pagegrid.addWidget(self.indic, 4, 1) self.pagegrid.addWidget(self.fill, 5, 0) self.pagegrid.setRowStretch(5, 1) # self.pagegrid.addWidget(self.fill, 6, 0) # self.pagegrid.addWidget(pagesperline, 6, 0) # self.pagegrid.addWidget(self.pagesperlineEdit, 7, 0) self.pagegroup.setLayout(self.pagegrid) self.vvbox.addWidget(self.pagegroup) # self.optab.insertTab(1, self.pagegroup, "Pages" ) # self.vbox.addWidget(self.pagegroup) def createHexOptions(self): self.vvbox = QVBoxLayout() self.vcontainer = QWidget() self.hexgroup = QWidget() self.hexgrid = QGridLayout() groupebylabel = QLabel("Groupe by:") self.groupeby = QComboBox() self.groupeby.addItem("1") self.groupeby.addItem("2") self.groupeby.addItem("4") offsetlabel = QLabel("Offset as") self.offsetas = QComboBox() self.offsetas.addItem("Hexadecimal") self.offsetas.addItem("Decimal") # self.hexgrid.addWidget(groupebylabel, 0, 0) # self.hexgrid.addWidget(self.groupeby, 1, 0) self.hexgrid.addWidget(offsetlabel, 0, 0) self.hexgrid.addWidget(self.offsetas, 0, 1) # self.hexgrid.addWidget(self.fill, 2, 0) # self.hexgrid.setRowStretch(2, 1) self.hexgroup.setLayout(self.hexgrid) self.vvbox.addWidget(self.hexgroup) self.createPageOptions() self.vcontainer.setLayout(self.vvbox) self.optab.insertTab(0, self.vcontainer, "General") # self.vbox.addWidget(self.hexgroup) #Offset as decimal / hexadecimal def createButtons(self): self.applyB = QPushButton("Apply") self.connect(self.applyB, SIGNAL('clicked()'), self.apply) self.vbox.addWidget(self.applyB) def checkValue(self, value): try: n = int(value) return n except ValueError: return -1 def apply(self): #PAGE CHECK pagesize = self.sizeEdit.value() headsize = self.headEdit.value() sparesize = self.spareEdit.value() pagesperblock = self.checkValue(self.pagesperblock.currentText()) if (pagesize < 0) or (headsize < 0) or (sparesize < 0) or (pagesperblock < 0): print "Wrong values" else: offas = self.offsetas.currentText() if offas == "Decimal": self.heditor.decimalview = True elif offas == "Hexadecimal": self.heditor.decimalview = False #Hexview refresh self.heditor.readOffset(self.heditor.currentOffset) self.heditor.refreshPageValues(headsize, pagesize, sparesize, pagesperblock)
class GeneralSection(QWidget): def __init__(self): super(GeneralSection, self).__init__() container = QVBoxLayout(self) # Inicio group_on_start = QGroupBox(self.tr("Al Iniciar:")) box = QVBoxLayout(group_on_start) box.setContentsMargins(20, 5, 20, 5) self.check_splash = QCheckBox(self.tr("Mostrar Splash")) self.check_splash.setChecked( settings.get_setting('general/show-splash')) box.addWidget(self.check_splash) self.check_on_start = QCheckBox(self.tr("Mostrar Página de Inicio")) show_start_page = settings.get_setting('general/show-start-page') self.check_on_start.setChecked(show_start_page) box.addWidget(self.check_on_start) self.check_load_files = QCheckBox(self.tr("Cargar archivos desde la " "última sesión")) load_files = settings.get_setting('general/load-files') self.check_load_files.setChecked(load_files) box.addWidget(self.check_load_files) container.addWidget(group_on_start) # Al salir group_on_exit = QGroupBox(self.tr("Al Salir:")) box = QVBoxLayout(group_on_exit) box.setContentsMargins(20, 5, 20, 5) self.check_on_exit = QCheckBox(self.tr("Confirmar Salida")) self.check_on_exit.setChecked( settings.get_setting('general/confirm-exit')) box.addWidget(self.check_on_exit) self.check_geometry = QCheckBox(self.tr( "Guardar posición y tamaño de la ventana")) self.check_geometry.setChecked( settings.get_setting('window/store-size')) box.addWidget(self.check_geometry) container.addWidget(group_on_exit) # Notificaciones group_notifications = QGroupBox(self.tr("Notificaciones:")) box = QVBoxLayout(group_notifications) box.setContentsMargins(20, 5, 20, 5) self.check_updates = QCheckBox(self.tr("Buscar Actualizaciones")) self.check_updates.setChecked( settings.get_setting('general/check-updates')) box.addWidget(self.check_updates) container.addWidget(group_notifications) # Sistema if settings.IS_LINUX: group_terminal = QGroupBox(self.tr("Sistema:")) box = QHBoxLayout(group_terminal) box.addWidget(QLabel(self.tr("Ejecutar programa con:"))) self.line_terminal = QLineEdit() self.line_terminal.setAlignment(Qt.AlignLeft) self.line_terminal.setFixedWidth(300) self.line_terminal.setText(settings.get_setting('terminal')) box.addWidget(self.line_terminal, 1, Qt.AlignLeft) container.addWidget(group_terminal) # User Interface group_ui = QGroupBox(self.tr("Interfáz de Usuario:")) box = QGridLayout(group_ui) box.setContentsMargins(20, 5, 20, 5) box.addWidget(QLabel(self.tr("Tema:")), 0, 0) self.combo_theme = QComboBox() self.combo_theme.setFixedWidth(200) self._update_combo() index = self.combo_theme.findText( settings.get_setting('window/style-sheet')) self.combo_theme.setCurrentIndex(index) box.addWidget(self.combo_theme, 0, 1) self.combo_lang = QComboBox() self.combo_lang.setFixedWidth(200) box.addWidget(QLabel(self.tr("Idioma:")), 1, 0) box.addWidget(self.combo_lang, 1, 1) langs = os.listdir(os.path.join(paths.PATH, "extras", "i18n")) self.combo_lang.addItems(["Spanish"] + [lang[:-3] for lang in langs]) lang = settings.get_setting('general/language') index = 0 if not lang else self.combo_lang.findText(lang) self.combo_lang.setCurrentIndex(index) container.addWidget(group_ui) box.setAlignment(Qt.AlignLeft) # Reestablecer group_restart = QGroupBox(self.tr("Reestablecer:")) box = QHBoxLayout(group_restart) box.setContentsMargins(20, 5, 20, 5) btn_restart = QPushButton(self.tr("Reiniciar configuraciones")) btn_restart.setObjectName("custom") box.addWidget(btn_restart) box.addStretch(1) container.addWidget(group_restart) container.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding)) # Conexiones btn_restart.clicked.connect(self._restart_configurations) self.combo_theme.currentIndexChanged[int].connect( self._change_style_sheet) # Install EnvironmentConfiguration.install_widget(self.tr("General"), self) def _update_combo(self): self.combo_theme.addItems(['Default', 'Edark']) list_dir = os.listdir(paths.EDIS) list_styles = [i.split('.')[0]for i in list_dir if os.path.splitext(i)[-1] == '.qss'] self.combo_theme.insertItems(2, list_styles) def _change_style_sheet(self, index): style_sheet = None path = None if index == 1: path = os.path.join(paths.PATH, "extras", "theme", "edark.qss") elif index != 0: style = self.combo_styles.currentText() + '.qss' path = os.path.join(paths.EDIS, style) if path is not None: with open(path, mode='r') as f: style_sheet = f.read() QApplication.instance().setStyleSheet(style_sheet) def _restart_configurations(self): flags = QMessageBox.Cancel flags |= QMessageBox.Yes result = QMessageBox.question(self, self.tr("Advertencia!"), self.tr("Está seguro que quiere " "reestablecer las " "configuraciones?"), flags) if result == QMessageBox.Cancel: return elif result == QMessageBox.Yes: QSettings(paths.CONFIGURACION, QSettings.IniFormat).clear() dialog_preferences = Edis.get_component("preferences") dialog_preferences.close() def save(self): settings.set_setting('general/show-splash', self.check_splash.isChecked()) show_start_page = self.check_on_start.isChecked() settings.set_setting('general/show-start-page', show_start_page) settings.set_setting('ventana/store-size', self.check_geometry.isChecked()) settings.set_setting('general/confirm-exit', self.check_on_exit.isChecked()) settings.set_setting('general/check-updates', self.check_updates.isChecked()) load_files = self.check_load_files.isChecked() settings.set_setting('general/load-files', load_files) lang = self.combo_lang.currentText() settings.set_setting('general/language', lang) if settings.IS_LINUX: settings.set_setting('terminal', self.line_terminal.text())
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)