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()
def Get(self, widget : QtGui.QComboBox): # return val from enum if len(self.enum) != widget.count(): raise GuiFieldEnumLenErr(self.enum, widget.count(), widget.count()) i = widget.currentIndex() if i < 0: return "" return self.enum[i]
class ComboTabWidget(QWidget): def __init__(self, parent): super(ComboTabWidget, self).__init__(parent) layout = QVBoxLayout(self) layout.setSpacing(0) self.switchCombo = QComboBox(self) layout.addWidget(self.switchCombo, 0, Qt.AlignCenter) groupBox = QGroupBox(self) groupBoxLayout = QVBoxLayout(groupBox) groupBoxLayout.setSpacing(0) self.pageArea = QStackedWidget(groupBox) groupBoxLayout.addWidget(self.pageArea) layout.addWidget(groupBox, 1) self.switchCombo.currentIndexChanged.connect(self.pageArea.setCurrentIndex) def setTabPosition(self, tabPos): pass def addTab(self, w, tabText): self.pageArea.addWidget(w) self.switchCombo.addItem(tabText) def insertTab(self, pos, w, tabText): self.pageArea.insertWidget(pos, w) self.switchCombo.insertItem(pos, tabText) def removeTab(self, index=-1): if index < 0: index = self.currentIndex() w = self.pageArea.widget(index) self.pageArea.removeWidget(w) self.switchCombo.removeItem(index) def updateTab(self, w, tabText, index=-1): if index < 0: index = self.switchCombo.currentIndex() self.removeTab(index) self.insertTab(index, w, tabText) self.setCurrentIndex(index) def setCurrentIndex(self, index): self.switchCombo.setCurrentIndex(index) def widget(self, index): return self.pageArea.widget(index) def currentIndex(self): return self.switchCombo.currentIndex() def count(self): return self.switchCombo.count()
class FloatColumnConfigurationWidget(QWidget, columnproviders.AbstractColumnConfigurationWidget): def __init__(self, parent, hex_widget, column): QWidget.__init__(self, parent) columnproviders.AbstractColumnConfigurationWidget.__init__(self) self.hexWidget = hex_widget self.column = column self.cmbBinaryFormat = QComboBox(self) self.cmbBinaryFormat.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) for fmt in (valuecodecs.FloatCodec.FormatFloat, valuecodecs.FloatCodec.FormatDouble): self.cmbBinaryFormat.addItem(valuecodecs.FloatCodec.formatName(fmt), fmt) if column is not None and column.valuecodec.binaryFormat == fmt: self.cmbBinaryFormat.setCurrentIndex(self.cmbBinaryFormat.count() - 1) self.spnPrecision = QSpinBox(self) self.spnPrecision.setMinimum(0) self.spnPrecision.setMaximum(12) if column is not None: self.spnPrecision.setValue(column.formatter.precision) else: self.spnPrecision.setValue(6) self.spnColumnsOnRow = QSpinBox(self) self.spnColumnsOnRow.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self.spnColumnsOnRow.setMinimum(1) self.spnColumnsOnRow.setMaximum(32) if column is not None: self.spnColumnsOnRow.setValue(column.columnsOnRow) else: self.spnColumnsOnRow.setValue(4) self.setLayout(QFormLayout()) self.layout().setContentsMargins(0, 0, 0, 0) self.layout().addRow(utils.tr('Binary format:'), self.cmbBinaryFormat) self.layout().addRow(utils.tr('Digits after point:'), self.spnPrecision) self.layout().addRow(utils.tr('Columns on row:'), self.spnColumnsOnRow) @property def _valueCodec(self): c = valuecodecs.FloatCodec() c.binaryFormat = self.cmbBinaryFormat.itemData(self.cmbBinaryFormat.currentIndex()) return c @property def _formatter(self): f = formatters.FloatFormatter() f.precision = self.spnPrecision.value() return f def createColumnModel(self, hex_widget): return FloatColumnModel(hex_widget.document, self._valueCodec, self._formatter, self.spnColumnsOnRow.value()) def saveToColumn(self, column): column.valuecodec = self._valueCodec column.formatter = self._formatter column.columnsOnRow = self.spnColumnsOnRow.value() column.reset()
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 InterfacePage(QWizardPage): """ Allows the user to choose one among networkable interfaces to build a net upon. """ def __init__(self, parent=None): QWizardPage.__init__(self, parent) self.__make_gui() self.__populate() self.connect(self.__dropdown, SIGNAL("currentIndexChanged(int)"), self.propagate) def __make_gui(self): self.setTitle(tr("Network Editor")) self.setSubTitle(tr("Select the interface to which you want to add a network")) box = QVBoxLayout(self) self.__dropdown = QComboBox() box.addWidget(self.__dropdown) def __candidates(self): candidates = list( QNetObject.getInstance().netcfg.iterNetworkables() ) candidates.sort() return candidates def __populate(self): candidates = self.__candidates() for interface in candidates: variant = QVariant(interface) self.__dropdown.addItem(interface.fullName(), variant) def propagate(self): """ propagate: emits a "changed" SIGNAL with the chosen interface as content """ self.emit(SIGNAL("changed"), self.interface()) def interface(self): """ returns the currently selected interface """ #QVariant with custom content variant = self.__dropdown.itemData( self.__dropdown.currentIndex() ) interface = variant.toPyObject() return interface def setInterface(self, target): for index in xrange(self.__dropdown.count()): variant = self.__dropdown.itemData(index) interface = variant.toPyObject() if interface is target: break self.__dropdown.setCurrentIndex(index)
def Set(self, widget : QtGui.QComboBox, val): """ Find index for 'text' within stored records and set currentIndex to that index. If 'text' is empty or 'None', currentIndex will be set to -1. """ if len(self.enum) != widget.count(): raise GuiFieldEnumLenErr(widget, self.enum, widget.count(), widget.count()) if not val: widget.setCurrentIndex(-1) return for i, value in enumerate(self.enum): if value == val: widget.setCurrentIndex(i) return raise GuiFieldUnknownMetaErr(val, widget, True)
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 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 ActionBar(QFrame): """ SIGNALS: @changeCurrent(PyQt_PyObject) """ def __init__(self): super(ActionBar, self).__init__() self.setObjectName("actionbar") hbox = QHBoxLayout(self) hbox.setContentsMargins(1, 1, 1, 1) self.combo = QComboBox() self.combo.setObjectName("combotab") self.connect(self.combo, SIGNAL("currentIndexChanged(int)"), self.current_changed) hbox.addWidget(self.combo) self.lbl_checks = QLabel('') self.lbl_checks.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) hbox.addWidget(self.lbl_checks) self._pos_text = "Ln: %d, Col: %d" self.lbl_position = QLabel(self._pos_text % (0, 0)) self.lbl_position.setObjectName("position") self.lbl_position.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) hbox.addWidget(self.lbl_position) self.btn_close = QPushButton( self.style().standardIcon(QStyle.SP_DialogCloseButton), '') self.btn_close.setObjectName('navigation_button') self.btn_close.setToolTip(translations.TR_CLOSE_SPLIT) self.btn_close.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) hbox.addWidget(self.btn_close) def add_item(self, text, data): self.combo.addItem(text, data) self.combo.setCurrentIndex(self.combo.count() - 1) def current_changed(self, index): data = self.combo.itemData(index) self.emit(SIGNAL("changeCurrent(PyQt_PyObject)"), data) def update_line_col(self, line, col): self.lbl_position.setText(self._pos_text % (line, col))
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 MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.d_plot = TVPlot(self) self.setCentralWidget( self.d_plot ) self.toolBar = QToolBar( self ) self.typeBox = QComboBox( self.toolBar ) self.typeBox.addItem( "Outline" ) self.typeBox.addItem( "Columns" ) self.typeBox.addItem( "Lines" ) self.typeBox.addItem( "Column Symbol" ) self.typeBox.setCurrentIndex( self.typeBox.count() - 1 ) self.typeBox.setSizePolicy( QSizePolicy.Fixed, QSizePolicy.Fixed ) self.btnExport = QToolButton( self.toolBar ) self.btnExport.setText( "Export" ) self.btnExport.setToolButtonStyle( Qt.ToolButtonTextUnderIcon ) #connect( btnExport, SIGNAL( clicked() ), d_plot, SLOT( exportPlot() ) ) self.btnExport.clicked.connect(self.d_plot.exportPlot) self.toolBar.addWidget( self.typeBox ) self.toolBar.addWidget( self.btnExport ) self.addToolBar( self.toolBar ) self.d_plot.setMode( self.typeBox.currentIndex() ) self.typeBox.currentIndexChanged['int'].connect(self.d_plot.setMode)
def generateDataTypesField(dataType=None): """ @rtype: QComboBox """ dataTypes = QComboBox() dataTypes.addItems( helper_methods.buildQStringList( ['TINYINT', 'SMALLINT', 'MEDIUMINT', 'INT', 'BIGINT', 'BIT'])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems( helper_methods.buildQStringList(['FLOAT', 'DOUBLE', 'DECIMAL'])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems( helper_methods.buildQStringList([ 'CHAR', 'VARCHAR', 'TINYTEXT', 'TEXT', 'MEDIUMTEXT', 'LONGTEXT' ])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems( helper_methods.buildQStringList([ 'BINARY', 'VARBINARY', 'TINYBLOB', 'BLOB', 'MEDIUMBLOB', 'LONGBLOB' ])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems( helper_methods.buildQStringList( ['DATE', 'TIME', 'YEAR', 'DATETIME', 'TIMESTAMP'])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems( helper_methods.buildQStringList([ 'POINT', 'LINESTRING', 'POLYGON', 'GEOMETRY', 'MULTIPOINT', 'MULTILINESTRING', 'MULTIPOLYGON', 'GEOMETRYCOLLECTION' ])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems(helper_methods.buildQStringList(['ENUM', 'SET'])) if dataType is not None: dataTypes.setCurrentIndex(dataTypes.findText(dataType.upper())) return dataTypes
def generateDataTypesField(dataType=None): """ @rtype: QComboBox """ dataTypes = QComboBox() dataTypes.addItems(helper_methods.buildQStringList(['TINYINT', 'SMALLINT', 'MEDIUMINT', 'INT', 'BIGINT', 'BIT'])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems(helper_methods.buildQStringList(['FLOAT', 'DOUBLE', 'DECIMAL'])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems(helper_methods.buildQStringList(['CHAR', 'VARCHAR', 'TINYTEXT', 'TEXT', 'MEDIUMTEXT', 'LONGTEXT'])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems(helper_methods.buildQStringList(['BINARY', 'VARBINARY', 'TINYBLOB', 'BLOB', 'MEDIUMBLOB', 'LONGBLOB'])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems(helper_methods.buildQStringList(['DATE', 'TIME', 'YEAR', 'DATETIME', 'TIMESTAMP'])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems(helper_methods.buildQStringList(['POINT', 'LINESTRING', 'POLYGON', 'GEOMETRY', 'MULTIPOINT', 'MULTILINESTRING', 'MULTIPOLYGON', 'GEOMETRYCOLLECTION'])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems(helper_methods.buildQStringList(['ENUM', 'SET'])) if dataType is not None: dataTypes.setCurrentIndex(dataTypes.findText(dataType.upper())) return dataTypes
class LoginDlg(QDialog): """login dialog for server""" def __init__(self): """self.servers is a list of tuples containing server and last playername""" QDialog.__init__(self, None) self.setWindowTitle(m18n('Login') + ' - Kajongg') self.setupUi() localName = m18nc('kajongg name for local game server', Query.localServerName) self.servers = Query( 'select url,lastname from server order by lasttime desc').records servers = [ m18nc('kajongg name for local game server', x[0]) for x in self.servers ] # the first server combobox item should be default: either the last used server # or localName for autoPlay if localName not in servers: servers.append(localName) if 'kajongg.org' not in servers: servers.append('kajongg.org') demoHost = Options.host or localName if demoHost in servers: servers.remove( demoHost ) # we want a unique list, it will be re-used for all following games servers.insert( 0, demoHost) # in this process but they will not be autoPlay self.cbServer.addItems(servers) self.passwords = Query( 'select url, p.name, passwords.password from passwords, player p ' 'where passwords.player=p.id').records Players.load() self.cbServer.editTextChanged.connect(self.serverChanged) self.cbUser.editTextChanged.connect(self.userChanged) self.serverChanged() StateSaver(self) def returns(self, dummyButton=None): """maybe we should return an class ServerConnection""" return (self.useSocket, self.url, self.username, self.__defineRuleset()) def setupUi(self): """create all Ui elements but do not fill them""" buttonBox = KDialogButtonBox(self) buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) # Ubuntu 11.10 unity is a bit strange - without this, it sets focus on # the cancel button (which it shows on the left). I found no obvious # way to use setDefault and setAutoDefault for fixing this. buttonBox.button(QDialogButtonBox.Ok).setFocus(True) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) vbox = QVBoxLayout(self) self.grid = QFormLayout() self.cbServer = QComboBox() self.cbServer.setEditable(True) self.grid.addRow(m18n('Game server:'), self.cbServer) self.cbUser = QComboBox() self.cbUser.setEditable(True) self.grid.addRow(m18n('Username:'******'Password:'******'kajongg', 'Ruleset:'), self.cbRuleset) vbox.addLayout(self.grid) vbox.addWidget(buttonBox) pol = QSizePolicy() pol.setHorizontalPolicy(QSizePolicy.Expanding) self.cbUser.setSizePolicy(pol) def serverChanged(self, dummyText=None): """the user selected a different server""" records = Query( 'select player.name from player, passwords ' 'where passwords.url=? and passwords.player = player.id', list([self.url])).records players = list(x[0] for x in records) preferPlayer = Options.player if preferPlayer: if preferPlayer in players: players.remove(preferPlayer) players.insert(0, preferPlayer) self.cbUser.clear() self.cbUser.addItems(players) if not self.cbUser.count(): user = KUser() if os.name == 'nt' else KUser(os.geteuid()) self.cbUser.addItem(user.fullName() or user.loginName()) if not preferPlayer: userNames = [x[1] for x in self.servers if x[0] == self.url] if userNames: userIdx = self.cbUser.findText(userNames[0]) if userIdx >= 0: self.cbUser.setCurrentIndex(userIdx) showPW = self.url != Query.localServerName self.grid.labelForField(self.edPassword).setVisible(showPW) self.edPassword.setVisible(showPW) self.grid.labelForField(self.cbRuleset).setVisible( not showPW and not Options.ruleset) self.cbRuleset.setVisible(not showPW and not Options.ruleset) if not showPW: self.cbRuleset.clear() if Options.ruleset: self.cbRuleset.items = [Options.ruleset] else: self.cbRuleset.items = Ruleset.selectableRulesets(self.url) def __defineRuleset(self): """find out what ruleset to use""" if Options.ruleset: return Options.ruleset elif Internal.autoPlay or bool(Options.host): return Ruleset.selectableRulesets()[0] else: return self.cbRuleset.current def userChanged(self, text): """the username has been changed, lookup password""" if text == '': self.edPassword.clear() return passw = None for entry in self.passwords: if entry[0] == self.url and entry[1] == unicode(text): passw = entry[2] if passw: self.edPassword.setText(passw) else: self.edPassword.clear() @property def url(self): """abstracts the url of the dialog""" return english(unicode(self.cbServer.currentText())) @property def host(self): """abstracts the host of the dialog""" return self.url.partition(':')[0] @property def useSocket(self): """do we use socket for current host?""" return self.host == Query.localServerName @property def port(self): """abstracts the port of the dialog""" try: return int(self.url.partition(':')[2]) except ValueError: return Options.defaultPort() @property def username(self): """abstracts the username of the dialog""" return unicode(self.cbUser.currentText()) @property def password(self): """abstracts the password of the dialog""" return unicode(self.edPassword.text()) @password.setter def password(self, password): """abstracts the password of the dialog""" self.edPassword.setText(password) def updateServerInfoInDatabase(self): """we are online. Update table server.""" lasttime = datetime.datetime.now().replace(microsecond=0).isoformat() url = english(self.url) # use unique name for Local Game with Transaction(): serverKnown = Query( 'update server set lastname=?,lasttime=? where url=?', list([self.username, lasttime, url])).rowcount() == 1 if not serverKnown: Query( 'insert into server(url,lastname,lasttime) values(?,?,?)', list([url, self.username, lasttime])) # needed if the server knows our name but our local data base does not: Players.createIfUnknown(self.username) playerId = Players.allIds[self.username] with Transaction(): if Query( 'update passwords set password=? where url=? and player=?', list([self.password, url, playerId])).rowcount() == 0: Query( 'insert into passwords(url,player,password) values(?,?,?)', list([url, playerId, self.password]))
class Interface(QWidget): """Interface widget class.""" def __init__(self, parent): super(Interface, self).__init__() self._preferences, vbox = parent, QVBoxLayout(self) self.toolbar_settings = settings.TOOLBAR_ITEMS groupBoxExplorer = QGroupBox( translations.TR_PREFERENCES_INTERFACE_EXPLORER_PANEL) #groupBoxToolbar = QGroupBox( #translations.TR_PREFERENCES_INTERFACE_TOOLBAR_CUSTOMIZATION) groupBoxLang = QGroupBox( translations.TR_PREFERENCES_INTERFACE_LANGUAGE) #Explorer vboxExplorer = QVBoxLayout(groupBoxExplorer) self._checkProjectExplorer = QCheckBox( translations.TR_PREFERENCES_SHOW_EXPLORER) self._checkSymbols = QCheckBox( translations.TR_PREFERENCES_SHOW_SYMBOLS) self._checkWebInspetor = QCheckBox( translations.TR_PREFERENCES_SHOW_WEB_INSPECTOR) self._checkFileErrors = QCheckBox( translations.TR_PREFERENCES_SHOW_FILE_ERRORS) self._checkMigrationTips = QCheckBox( translations.TR_PREFERENCES_SHOW_MIGRATION) vboxExplorer.addWidget(self._checkProjectExplorer) vboxExplorer.addWidget(self._checkSymbols) vboxExplorer.addWidget(self._checkWebInspetor) vboxExplorer.addWidget(self._checkFileErrors) vboxExplorer.addWidget(self._checkMigrationTips) #GUI - Toolbar #vbox_toolbar = QVBoxLayout(groupBoxToolbar) #hbox_select_items = QHBoxLayout() #label_toolbar = QLabel(translations.TR_PREFERENCES_TOOLBAR_ITEMS) #label_toolbar.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) #hbox_select_items.addWidget(label_toolbar) #self._comboToolbarItems = QComboBox() #self._load_combo_data(self._comboToolbarItems) #self._btnItemAdd = QPushButton(QIcon(":img/add"), '') #self._btnItemAdd.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) #self._btnItemAdd.setIconSize(QSize(16, 16)) #self._btnItemRemove = QPushButton(QIcon(':img/delete'), '') #self._btnItemRemove.setIconSize(QSize(16, 16)) #self._btnDefaultItems = QPushButton( #translations.TR_PREFERENCES_TOOLBAR_DEFAULT) #self._btnDefaultItems.setSizePolicy(QSizePolicy.Fixed, #QSizePolicy.Fixed) #self._btnItemRemove.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) #hbox_select_items.addWidget(self._comboToolbarItems) #hbox_select_items.addWidget(self._btnItemAdd) #hbox_select_items.addWidget(self._btnItemRemove) #hbox_select_items.addWidget(self._btnDefaultItems) #vbox_toolbar.addLayout(hbox_select_items) #self._toolbar_items = QToolBar() #self._toolbar_items.setObjectName("custom") #self._toolbar_items.setToolButtonStyle(Qt.ToolButtonIconOnly) #self._load_toolbar() #vbox_toolbar.addWidget(self._toolbar_items) #vbox_toolbar.addWidget(QLabel( #translations.TR_PREFERENCES_TOOLBAR_CONFIG_HELP)) #Language vboxLanguage = QVBoxLayout(groupBoxLang) vboxLanguage.addWidget(QLabel( translations.TR_PREFERENCES_SELECT_LANGUAGE)) self._comboLang = QComboBox() self._comboLang.setEnabled(False) vboxLanguage.addWidget(self._comboLang) vboxLanguage.addWidget(QLabel( translations.TR_PREFERENCES_REQUIRES_RESTART)) #Load Languages self._load_langs() #Settings self._checkProjectExplorer.setChecked( settings.SHOW_PROJECT_EXPLORER) self._checkSymbols.setChecked(settings.SHOW_SYMBOLS_LIST) self._checkWebInspetor.setChecked(settings.SHOW_WEB_INSPECTOR) self._checkFileErrors.setChecked(settings.SHOW_ERRORS_LIST) self._checkMigrationTips.setChecked(settings.SHOW_MIGRATION_LIST) vbox.addWidget(groupBoxExplorer) #vbox.addWidget(groupBoxToolbar) vbox.addWidget(groupBoxLang) #Signals #self.connect(self._btnItemAdd, SIGNAL("clicked()"), #self.toolbar_item_added) #self.connect(self._btnItemRemove, SIGNAL("clicked()"), #self.toolbar_item_removed) #self.connect(self._btnDefaultItems, SIGNAL("clicked()"), #self.toolbar_items_default) self.connect(self._preferences, SIGNAL("savePreferences()"), self.save) #def toolbar_item_added(self): #data = self._comboToolbarItems.itemData( #self._comboToolbarItems.currentIndex()) #if data not in self.toolbar_settings or data == 'separator': #selected = self.actionGroup.checkedAction() #if selected is None: #self.toolbar_settings.append(data) #else: #dataAction = selected.data() #self.toolbar_settings.insert( #self.toolbar_settings.index(dataAction) + 1, data) #self._load_toolbar() ## def toolbar_item_removed(self): #data = self._comboToolbarItems.itemData( #self._comboToolbarItems.currentIndex()) #if data in self.toolbar_settings and data != 'separator': #self.toolbar_settings.pop(self.toolbar_settings.index(data)) #self._load_toolbar() #elif data == 'separator': #self.toolbar_settings.reverse() #self.toolbar_settings.pop(self.toolbar_settings.index(data)) #self.toolbar_settings.reverse() #self._load_toolbar() ## def toolbar_items_default(self): #self.toolbar_settings = settings.TOOLBAR_ITEMS_DEFAULT #self._load_toolbar() ## def _load_combo_data(self, combo): #self.toolbar_items = { #'separator': [QIcon(':img/separator'), 'Add Separtor'], #'new-file': [QIcon(resources.IMAGES['new']), self.tr('New File')], #'new-project': [QIcon(resources.IMAGES['newProj']), #self.tr('New Project')], #'save-file': [QIcon(resources.IMAGES['save']), #self.tr('Save File')], #'save-as': [QIcon(resources.IMAGES['saveAs']), self.tr('Save As')], #'save-all': [QIcon(resources.IMAGES['saveAll']), #self.tr('Save All')], #'save-project': [QIcon(resources.IMAGES['saveAll']), #self.tr('Save Project')], #'reload-file': [QIcon(resources.IMAGES['reload-file']), #self.tr('Reload File')], #'open-file': [QIcon(resources.IMAGES['open']), #self.tr('Open File')], #'open-project': [QIcon(resources.IMAGES['openProj']), #self.tr('Open Project')], #'activate-profile': [QIcon(resources.IMAGES['activate-profile']), #self.tr('Activate Profile')], #'deactivate-profile': #[QIcon(resources.IMAGES['deactivate-profile']), #self.tr('Deactivate Profile')], #'print-file': [QIcon(resources.IMAGES['print']), #self.tr('Print File')], #'close-file': #[self.style().standardIcon(QStyle.SP_DialogCloseButton), #self.tr('Close File')], #'close-projects': #[self.style().standardIcon(QStyle.SP_DialogCloseButton), #self.tr('Close Projects')], #'undo': [QIcon(resources.IMAGES['undo']), self.tr('Undo')], #'redo': [QIcon(resources.IMAGES['redo']), self.tr('Redo')], #'cut': [QIcon(resources.IMAGES['cut']), self.tr('Cut')], #'copy': [QIcon(resources.IMAGES['copy']), self.tr('Copy')], #'paste': [QIcon(resources.IMAGES['paste']), self.tr('Paste')], #'find': [QIcon(resources.IMAGES['find']), self.tr('Find')], #'find-replace': [QIcon(resources.IMAGES['findReplace']), #self.tr('Find/Replace')], #'find-files': [QIcon(resources.IMAGES['find']), #self.tr('Find In files')], #'code-locator': [QIcon(resources.IMAGES['locator']), #self.tr('Code Locator')], #'splith': [QIcon(resources.IMAGES['splitH']), #self.tr('Split Horizontally')], #'splitv': [QIcon(resources.IMAGES['splitV']), #self.tr('Split Vertically')], #'follow-mode': [QIcon(resources.IMAGES['follow']), #self.tr('Follow Mode')], #'zoom-in': [QIcon(resources.IMAGES['zoom-in']), self.tr('Zoom In')], #'zoom-out': [QIcon(resources.IMAGES['zoom-out']), #self.tr('Zoom Out')], #'indent-more': [QIcon(resources.IMAGES['indent-more']), #self.tr('Indent More')], #'indent-less': [QIcon(resources.IMAGES['indent-less']), #self.tr('Indent Less')], #'comment': [QIcon(resources.IMAGES['comment-code']), #self.tr('Comment')], #'uncomment': [QIcon(resources.IMAGES['uncomment-code']), #self.tr('Uncomment')], #'go-to-definition': [QIcon(resources.IMAGES['go-to-definition']), #self.tr('Go To Definition')], #'insert-import': [QIcon(resources.IMAGES['insert-import']), #self.tr('Insert Import')], #'run-project': [QIcon(resources.IMAGES['play']), 'Run Project'], #'run-file': [QIcon(resources.IMAGES['file-run']), 'Run File'], #'stop': [QIcon(resources.IMAGES['stop']), 'Stop'], #'preview-web': [QIcon(resources.IMAGES['preview-web']), #self.tr('Preview Web')]} #for item in self.toolbar_items: #combo.addItem(self.toolbar_items[item][0], #self.toolbar_items[item][1], item) #combo.model().sort(0) ## def _load_toolbar(self): #pass ##self._toolbar_items.clear() ##self.actionGroup = QActionGroup(self) ##self.actionGroup.setExclusive(True) ##for item in self.toolbar_settings: ##if item == 'separator': ##self._toolbar_items.addSeparator() ##else: ##action = self._toolbar_items.addAction( ##self.toolbar_items[item][0], self.toolbar_items[item][1]) ##action.setData(item) ##action.setCheckable(True) ##self.actionGroup.addAction(action) def _load_langs(self): langs = file_manager.get_files_from_folder( resources.LANGS, '.qm') self._languages = ['English'] + \ [file_manager.get_module_name(lang) for lang in langs] self._comboLang.addItems(self._languages) if(self._comboLang.count() > 1): self._comboLang.setEnabled(True) if settings.LANGUAGE: index = self._comboLang.findText(settings.LANGUAGE) else: index = 0 self._comboLang.setCurrentIndex(index) def save(self): qsettings = IDE.ninja_settings() settings.TOOLBAR_ITEMS = self.toolbar_settings lang = self._comboLang.currentText() #preferences/interface qsettings.setValue('preferences/interface/showProjectExplorer', self._checkProjectExplorer.isChecked()) settings.SHOW_PROJECT_EXPLORER = self._checkProjectExplorer.isChecked() qsettings.setValue('preferences/interface/showSymbolsList', self._checkSymbols.isChecked()) settings.SHOW_SYMBOLS_LIST = self._checkSymbols.isChecked() qsettings.setValue('preferences/interface/showWebInspector', self._checkWebInspetor.isChecked()) settings.SHOW_WEB_INSPECTOR = self._checkWebInspetor.isChecked() qsettings.setValue('preferences/interface/showErrorsList', self._checkFileErrors.isChecked()) settings.SHOW_ERRORS_LIST = self._checkFileErrors.isChecked() qsettings.setValue('preferences/interface/showMigrationList', self._checkMigrationTips.isChecked()) settings.SHOW_MIGRATION_LIST = self._checkMigrationTips.isChecked() #qsettings.setValue('preferences/interface/toolbar', #settings.TOOLBAR_ITEMS) qsettings.setValue('preferences/interface/language', lang) lang = lang + '.qm' settings.LANGUAGE = os.path.join(resources.LANGS, lang)
def addWidgets(self): """ Add widgets """ nbArgument = 0 layoutUsed = self.mainLayout fontBold = QFont() fontBold.setBold(True) fontNormal = QFont() fontNormal.setBold(False) for i in xrange(len(self.actionData['data']['obj'])): # prevent to limit the display of all arguments # split all arguments in two tabulations if necessary nbArgument += 1 if nbArgument > MAX_ARGUMENT_TO_DISPLAY: layoutUsed = self.moreLayout # the second tab self.mainTab.setTabEnabled(1, True) if nbArgument > MAX_ARGUMENT_TO_DISPLAY2: layoutUsed = self.more2Layout # the second tab self.mainTab.setTabEnabled(2, True) # extract the name of the function varName = self.actionData['data']['obj'][i]['name'] #argNameLabel = QLabel( varName ) argNameLabel = QLabelEnhanced( varName, parent=self, data=self.actionData['data']['obj'][i]['descr']) argNameLabel.EnterLabel.connect(self.loadArgumentDescription) argNameLabel.LeaveLabel.connect(self.clearArgumentDescription) #argNameLabel.setToolTip(self.actionData['data']['obj'][i]['descr']) layoutUsed.addWidget(argNameLabel, i, 0) typeDetected = self.actionData['data']['obj'][i]['type'].split("/") opDetected = False for j in xrange(len(typeDetected)): if typeDetected[j].lower() == 'operators': opDetected = True break if typeDetected[j].lower() == 'condition': opDetected = True break labDetected = False for j in xrange(len(typeDetected)): if typeDetected[j].lower() == 'label': labDetected = True break constDetected = False for j in xrange(len(typeDetected)): if typeDetected[j].lower() in ['strconstant', 'intconstant']: constDetected = True break dictDetected = False for j in xrange(len(typeDetected)): if typeDetected[j].lower() == 'dict': dictDetected = True break tplMDetected = False for j in xrange(len(typeDetected)): if typeDetected[j].lower() == 'templatemessage': tplMDetected = True break if tplMDetected: typeDetected.pop(j) tplLDetected = False for j in xrange(len(typeDetected)): if typeDetected[j].lower() == 'templatelayer': tplLDetected = True break if tplLDetected: typeDetected.pop(j) # exception for testcase parent in adapters or libraries if self.actionData['data']['obj'][i]['type'] != "testcase": if not self.adapterMode: if dictDetected or tplMDetected or tplLDetected: typeDetected.extend(['variables']) else: if not opDetected: if not labDetected: if not constDetected: typeDetected.extend( ['inputs', 'outputs', 'variables']) else: if not constDetected: typeDetected.extend(['inputs', 'outputs']) # second exception for agent mode if self.adapterMode and varName == "agent": if "none" in typeDetected or "None" in typeDetected: typeDetected = ['agents', "none"] else: typeDetected = ['agents'] # move none if exists on the list to the end noneDetected = False for j in xrange(len(typeDetected)): if typeDetected[j].lower() == 'none': noneDetected = True break if noneDetected: typeDetected.pop(j) typeDetected.append("none") # remove image type imgDetected = False for j in xrange(len(typeDetected)): if typeDetected[j].lower() == 'image': imgDetected = True break if imgDetected: typeDetected.pop(j) # remove string type if operators exists strDetected = False if opDetected: for j in xrange(len(typeDetected)): if typeDetected[j].lower() == 'string': strDetected = True break if strDetected: typeDetected.pop(j) radioGroup = QButtonGroup(self) shiftWidget = 1 deltaWidget = 0 radioSelected = shiftWidget for j in xrange(len(typeDetected)): #if typeDetected[j].lower() == "list": # continue radioButton = QRadioButton(typeDetected[j].lower()) radioButton.setFont(fontNormal) radioGroup.addButton(radioButton) layoutUsed.addWidget(radioButton, i, j + shiftWidget + deltaWidget) if typeDetected[j].lower() == "testcase": pass elif typeDetected[j].lower() == "none": if self.actionData['data']['obj'][i][ 'selected-type'] == typeDetected[j].lower(): radioSelected = j + shiftWidget + deltaWidget else: if 'default-value' in self.actionData['data']['obj'][ i]: if not len( self.actionData['data']['obj'][i] ['selected-type']) and self.actionData['data'][ 'obj'][i]['default-value'] == 'None': radioSelected = j + shiftWidget + deltaWidget elif typeDetected[j].lower() in [ "inputs", "outputs", "agents", "variables" ]: paramCombo = QComboBox() layoutUsed.addWidget(paramCombo, i, j + shiftWidget + deltaWidget + 1) if typeDetected[j].lower() == 'inputs': for inpt in self.owner.getInputs(): paramCombo.addItem(inpt['name']) if typeDetected[j].lower() == 'outputs': for inpt in self.owner.getOutputs(): paramCombo.addItem(inpt['name']) if typeDetected[j].lower() == 'agents': for inpt in self.owner.getAgents(): paramCombo.addItem(inpt['name']) if typeDetected[j].lower() == 'variables': paramCombo.addItems(self.variables) # set as default value or not ? if self.actionData['data']['obj'][i][ 'selected-type'] == typeDetected[j].lower(): radioSelected = j + shiftWidget + deltaWidget for x in xrange(paramCombo.count()): if paramCombo.itemText(x) == self.actionData[ 'data']['obj'][i]['value']: paramCombo.setCurrentIndex(x) deltaWidget += 1 elif typeDetected[j].lower() == "string": textArea = QTextEdit() textArea.setMinimumHeight(HEIGHT_TEXT_AREA) textArea.setMinimumWidth(WIDTH_TEXT_AREA) if self.actionData['data']['obj'][i][ 'selected-type'] == typeDetected[j].lower(): radioSelected = j + shiftWidget + deltaWidget try: if sys.version_info > (3, ): # python 3 support self.actionData['data']['obj'][i][ 'value'] = self.actionData['data']['obj'][ i]['value'] else: self.actionData['data']['obj'][i][ 'value'] = self.actionData['data']['obj'][ i]['value'].decode('utf8') textArea.setText( self.actionData['data']['obj'][i]['value']) except UnicodeDecodeError as e: textArea.setText( self.actionData['data']['obj'][i]['value']) except UnicodeEncodeError as e: textArea.setText( self.actionData['data']['obj'][i]['value']) else: if 'none' not in self.actionData['data']['obj'][i][ 'type'].lower(): if 'default-value' in self.actionData['data'][ 'obj'][i]: textArea.setText(self.actionData['data']['obj'] [i]['default-value']) layoutUsed.addWidget(textArea, i, j + shiftWidget + deltaWidget + 1) deltaWidget += 1 elif typeDetected[j].lower() in ["integer", "float"]: lineEdit = QLineEdit() if typeDetected[j].lower() == "integer": validator = QIntValidator(lineEdit) else: validator = QDoubleValidator(lineEdit) validator.setNotation( QDoubleValidator.StandardNotation) lineEdit.setValidator(validator) lineEdit.installEventFilter(self) if self.actionData['data']['obj'][i]['selected-type'] in [ 'integer', 'float' ]: radioSelected = j + shiftWidget + deltaWidget lineEdit.setText( "%s" % self.actionData['data']['obj'][i]['value']) else: if 'default-value' in self.actionData['data']['obj'][ i]: lineEdit.setText( str(self.actionData['data']['obj'][i] ['default-value'])) layoutUsed.addWidget(lineEdit, i, j + shiftWidget + deltaWidget + 1) deltaWidget += 1 elif typeDetected[j].lower() in ["strconstant", "intconstant"]: consCombo = QComboBox() # extract values tmpconstant = self.actionData['data']['obj'][i]['descr'] tmpvals = tmpconstant.split("|") # extract all constant and detect the default vals = [] defConstant = 0 defConstantVal = '' for zz in xrange(len(tmpvals)): if '(default)' in tmpvals[zz]: nameConstant = tmpvals[zz].split( '(default)')[0].strip() vals.append(nameConstant) defConstant = zz defConstantVal = nameConstant else: vals.append(tmpvals[zz].strip()) # append all constant to the combobox consCombo.addItems(vals) if self.actionData['data']['obj'][i][ 'selected-type'] == typeDetected[j].lower(): radioSelected = j + shiftWidget + deltaWidget for x in xrange(len(vals)): if vals[x] == str(self.actionData['data']['obj'][i] ['value']): consCombo.setCurrentIndex(x) else: # set the current index for default value consCombo.setCurrentIndex(defConstant) layoutUsed.addWidget(consCombo, i, j + shiftWidget + deltaWidget + 1) deltaWidget += 1 elif typeDetected[j].lower() == "boolean": boolCombo = QComboBox() valBool = ["True", "False"] boolCombo.addItems(valBool) if self.actionData['data']['obj'][i][ 'selected-type'] == typeDetected[j].lower(): radioSelected = j + shiftWidget + deltaWidget for x in xrange(len(valBool)): if valBool[x] == str(self.actionData['data']['obj'] [i]['value']): boolCombo.setCurrentIndex(x) else: # set the default value if 'default-value' in self.actionData['data']['obj'][ i]: for x in xrange(len(valBool)): if valBool[x] == str( self.actionData['data']['obj'][i] ['default-value']): boolCombo.setCurrentIndex(x) layoutUsed.addWidget(boolCombo, i, j + shiftWidget + deltaWidget + 1) deltaWidget += 1 elif typeDetected[j].lower() == "dict": dictWidget = DictWidget.DictWidget( parent=self, advancedMode=False, testParams=self.testParams, variables=self.variables) if self.actionData['data']['obj'][i][ 'selected-type'] == typeDetected[j].lower(): radioSelected = j + shiftWidget + deltaWidget if not isinstance( self.actionData['data']['obj'][i]['value'], dict): self.actionData['data']['obj'][i]['value'] = { 'dict': [] } dictVal = self.actionData['data']['obj'][i]['value'][ 'dict'] dictWidget.setCurrentDict(dictVal=dictVal) layoutUsed.addWidget(dictWidget, i, j + shiftWidget + deltaWidget + 1) deltaWidget += 1 elif typeDetected[j].lower() == "dictadvanced": dictWidget = DictWidget.DictWidget( parent=self, advancedMode=True, testParams=self.testParams, variables=self.variables) if self.actionData['data']['obj'][i][ 'selected-type'] == typeDetected[j].lower(): radioSelected = j + shiftWidget + deltaWidget if not isinstance( self.actionData['data']['obj'][i]['value'], dict): self.actionData['data']['obj'][i]['value'] = { 'dictadvanced': [] } dictVal = self.actionData['data']['obj'][i]['value'][ 'dictadvanced'] dictWidget.setCurrentDict(dictVal=dictVal) layoutUsed.addWidget(dictWidget, i, j + shiftWidget + deltaWidget + 1) deltaWidget += 1 elif typeDetected[j].lower() == "operators": opWidget = OperatorsWidget.OperatorsWidget( self, testParams=self.testParams, variables=self.variables) if self.actionData['data']['obj'][i][ 'selected-type'] == typeDetected[j].lower(): radioSelected = j + shiftWidget + deltaWidget opWidget.setCurrentOperator( operatorVal=self.actionData['data']['obj'][i] ['value']) layoutUsed.addWidget(opWidget, i, j + shiftWidget + deltaWidget + 1) deltaWidget += 1 elif typeDetected[j].lower() == "condition": opWidget = OperatorsWidget.OperatorsWidget( self, testParams=self.testParams, variables=self.variables, liteMode=True) if self.actionData['data']['obj'][i][ 'selected-type'] == typeDetected[j].lower(): radioSelected = j + shiftWidget + deltaWidget opWidget.setCurrentOperator( operatorVal=self.actionData['data']['obj'][i] ['value']) layoutUsed.addWidget(opWidget, i, j + shiftWidget + deltaWidget + 1) deltaWidget += 1 elif typeDetected[j].lower() == "templatelayer": textArea = QLineEdit() if self.actionData['data']['obj'][i][ 'selected-type'] == typeDetected[j].lower(): radioSelected = j + shiftWidget + deltaWidget textArea.setText( self.actionData['data']['obj'][i]['value']) else: if 'none' not in self.actionData['data']['obj'][i][ 'type'].lower(): if 'default-value' in self.actionData['data'][ 'obj'][i]: textArea.setText(self.actionData['data']['obj'] [i]['default-value']) layoutUsed.addWidget(textArea, i, j + shiftWidget + deltaWidget + 1) deltaWidget += 1 elif typeDetected[j].lower() == "object": textArea = QTextEdit() textArea.setFixedHeight(HEIGHT_TEXT_AREA) textArea.setMinimumWidth(WIDTH_TEXT_AREA) if self.actionData['data']['obj'][i][ 'selected-type'] == typeDetected[j].lower(): radioSelected = j + shiftWidget + deltaWidget textArea.setText( self.actionData['data']['obj'][i]['value']) else: # typeParam.setChecked(True) # fix bug if 'none' not in self.actionData['data']['obj'][i][ 'type'].lower(): if 'default-value' in self.actionData['data'][ 'obj'][i]: textArea.setText(self.actionData['data']['obj'] [i]['default-value']) layoutUsed.addWidget(textArea, i, j + shiftWidget + deltaWidget + 1) deltaWidget += 1 else: textArea = QTextEdit() textArea.setFixedHeight(HEIGHT_TEXT_AREA) textArea.setMinimumWidth(WIDTH_TEXT_AREA) if self.actionData['data']['obj'][i][ 'selected-type'] == typeDetected[j].lower(): radioSelected = j + shiftWidget + deltaWidget textArea.setText( self.actionData['data']['obj'][i]['value']) else: if 'none' not in self.actionData['data']['obj'][i][ 'type'].lower(): if 'default-value' in self.actionData['data'][ 'obj'][i]: textArea.setText(self.actionData['data']['obj'] [i]['default-value']) layoutUsed.addWidget(textArea, i, j + shiftWidget + deltaWidget + 1) deltaWidget += 1 widgetRadio = layoutUsed.itemAtPosition(i, radioSelected).widget() widgetRadio.setChecked(True) widgetRadio.setFont(fontBold) if nbArgument < MAX_ARGUMENT_TO_DISPLAY: self.mainTab.setTabEnabled(1, False)
class WAndroid(QWidget, Logger.ClassLogger): """ Android 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.addAndroidAction = QPushButton(QIcon(":/add_black.png"), '&Add Action', self) self.addAndroidAction.setMinimumHeight(40) self.addAndroidAction.setMaximumWidth(150) self.cancelAndroidAction = QtHelper.createAction(self, "&Cancel", self.cancelStep, icon=None, tip = 'Cancel update') self.cancelAndroidAction.setEnabled(False) self.optionsAction = QtHelper.createAction(self, "&", self.openOptions, icon=QIcon(":/recorder-mobile-small.png"), tip = 'Android options') def createWidgets(self): """ Create qt widgets """ self.optionsDialog = OptionsDialog(self) self.validatorUpper = ValidatorUpper(self) self.validatorAll = ValidatorAll(self) self.validatorInt = QIntValidator(self) ###################### android action ######################### self.actionsAndroidComboBox = QComboBox(self) self.actionsAndroidComboBox.setMinimumHeight(40) for i in xrange(len(GuiSteps.ACTION_ANDROID_DESCR)): if not len( GuiSteps.ACTION_ANDROID_DESCR[i] ): self.actionsAndroidComboBox.insertSeparator(i+1) else: el = GuiSteps.ACTION_ANDROID_DESCR[i].keys() self.actionsAndroidComboBox.addItem( list(el)[0] ) self.descriptionAndroidLine = QLineEdit(self) self.descriptionAndroidLine.setPlaceholderText("Step purpose description") self.descriptionAndroidLine.hide() self.labelActionAndroidDescr = QLabel( ) self.labelActionAndroidDescr.hide() self.labelActionAndroidDescr.setText( "%s\n" % GuiSteps.ACTION_ANDROID_DESCR[0][GuiSteps.ANDROID_WAKEUP_UNLOCK]) self.labelActionAndroidDescr.setWordWrap(True) actionsLayout = QHBoxLayout() actionsLayout.addWidget(self.actionsAndroidComboBox) actionLayoutAndroid = QGridLayout() actionLayoutAndroid.addLayout(actionsLayout, 0, 1) self.createWidgetShortcut() self.createWidgetCode() self.createWidgetStart() self.createWidgetXY() self.createWidgetEndXY() self.createWidgetElement() self.createWidgetTextTo() self.createWidgetLine() self.createWidgetLine2() actionLayoutAndroid2 = QGridLayout() actionLayoutAndroid2.addWidget( self.shortcutAndroidGroup , 0, 0) actionLayoutAndroid2.addWidget( self.codeAndroidGroup , 0, 0) actionLayoutAndroid2.addWidget( self.elemenAndroidGroup , 0, 0) actionLayoutAndroid2.addWidget( self.xyAndroidGroup , 0, 0) actionLayoutAndroid2.addWidget( self.startAndroidGroup , 0, 0) actionLayoutAndroid2.addWidget( self.lineAndroidGroup , 1, 0) actionLayoutAndroid2.addWidget( self.line2AndroidGroup , 0, 1) actionLayoutAndroid2.addWidget( self.textToGlobalGroup , 0, 1) actionLayoutAndroid2.addWidget( self.endXyAndroidGroup, 0, 1) font = QFont() font.setBold(True) labelAct = QLabel( self.tr("Action: ") ) labelAct.setFont( font) self.arrowLabel = QLabel("") self.arrowLabel.setPixmap(QPixmap(":/arrow-right.png").scaledToWidth(32)) self.arrowLabel.hide() self.arrowLabel2 = QLabel("") self.arrowLabel2.setPixmap(QPixmap(":/arrow-right.png").scaledToWidth(32)) layoutAndroid = QHBoxLayout() layoutAndroid.addWidget( labelAct ) layoutAndroid.addLayout( actionLayoutAndroid ) layoutAndroid.addWidget( self.arrowLabel ) layoutAndroid.addLayout( actionLayoutAndroid2 ) layoutAndroid.addWidget( self.arrowLabel2 ) layoutAndroid.addWidget(self.addAndroidAction) layoutAndroid.addStretch(1) self.setLayout(layoutAndroid) def createToolbar(self): """ Create qt toolbar """ pass def openOptions(self): """ Open options """ if self.optionsDialog.exec_() == QDialog.Accepted: pass def createWidgetLine2(self): """ Create line widget """ self.valueAndroidLine2 = QLineEdit(self) self.valueAndroidLine2.setMinimumWidth(150) self.valueAndroidCombo2 = QComboBox(self) self.valueAndroidCombo2.addItems( LIST_TYPES ) self.line2AndroidGroup = QGroupBox(self.tr("")) line2Androidlayout = QGridLayout() line2Androidlayout.addWidget( QLabel( self.tr("Text to type:") ), 0, 0 ) line2Androidlayout.addWidget( self.valueAndroidCombo2, 0, 1 ) line2Androidlayout.addWidget( self.valueAndroidLine2, 0, 2 ) self.line2AndroidGroup.setLayout(line2Androidlayout) self.line2AndroidGroup.hide() def createWidgetLine(self): """ Create line widget """ self.lineAndroidGroup = QGroupBox(self.tr("")) lineAndroidlayout = QGridLayout() self.valueAndroidLine = QLineEdit(self) self.valueAndroidLine.setMinimumWidth(300) lineAndroidlayout.addWidget( QLabel( self.tr("Value:") ) , 0,1) lineAndroidlayout.addWidget( self.valueAndroidLine , 0, 2) self.lineAndroidGroup.setLayout(lineAndroidlayout) self.lineAndroidGroup.hide() def createWidgetTextTo(self): """ Create text widget """ self.valueTextCacheGlobalLine = QLineEdit(self) self.valueTextCacheGlobalLine.setMinimumWidth(150) self.valueTextCacheGlobalCombo = QComboBox(self) self.valueTextCacheGlobalCombo.addItems( ["CACHE"] ) self.textToGlobalGroup = QGroupBox(self.tr("")) textToGloballayout = QGridLayout() textToGloballayout.addWidget( QLabel( self.tr("Save text in:") ) , 0, 0) textToGloballayout.addWidget( self.valueTextCacheGlobalCombo , 0, 1) textToGloballayout.addWidget( self.valueTextCacheGlobalLine , 0, 2) self.textToGlobalGroup.setLayout(textToGloballayout) self.textToGlobalGroup.hide() def createWidgetElement(self): """ Create text widget """ self.elemenAndroidGroup = QGroupBox(self.tr("")) self.elementTextAndroidLine = QLineEdit(self) self.elementTextAndroidLine.setMinimumWidth(300) self.elementTextCombo = QComboBox(self) self.elementTextCombo.addItems( LIST_TYPES ) self.elementDescriptionAndroidLine = QLineEdit(self) self.elementDescriptionAndroidLine.setMinimumWidth(300) self.elementClassAndroidLine = QLineEdit(self) self.elementClassAndroidLine.setMinimumWidth(300) self.elementRessourceIdAndroidLine = QLineEdit(self) self.elementRessourceIdAndroidLine.setMinimumWidth(300) self.elementPackageAndroidLine = QLineEdit(self) self.elementPackageAndroidLine.setMinimumWidth(300) # get text end elementAndroidlayout = QGridLayout() elementAndroidlayout.addWidget( QLabel( self.tr("Text Element:") ) , 0,1) elementAndroidlayout.addWidget( self.elementTextCombo , 0, 2) elementAndroidlayout.addWidget( self.elementTextAndroidLine , 0, 3) elementAndroidlayout.addWidget( QLabel( self.tr("Description Element:") ) , 1,1) elementAndroidlayout.addWidget( self.elementDescriptionAndroidLine , 1, 3) elementAndroidlayout.addWidget( QLabel( self.tr("Class Name:") ) , 2,1) elementAndroidlayout.addWidget( self.elementClassAndroidLine , 2, 3) elementAndroidlayout.addWidget( QLabel( self.tr("Resource ID:") ) , 3,1) elementAndroidlayout.addWidget( self.elementRessourceIdAndroidLine , 3, 3) elementAndroidlayout.addWidget( QLabel( self.tr("Package Name:") ) , 4,1) elementAndroidlayout.addWidget( self.elementPackageAndroidLine , 4, 3) self.elemenAndroidGroup.setLayout(elementAndroidlayout) self.elemenAndroidGroup.hide() def createWidgetEndXY(self): """ Create widget """ self.endXyAndroidGroup = QGroupBox(self.tr("")) endXyAndroidlayout = QGridLayout() self.endxAndroidLine = QLineEdit(self) validatorEndXAndroid = QIntValidator (self) self.endxAndroidLine.setValidator(validatorEndXAndroid) self.endxAndroidLine.installEventFilter(self) self.endyAndroidLine = QLineEdit(self) validatorEndYAndroid = QIntValidator (self) self.endyAndroidLine.setValidator(validatorEndYAndroid) self.endyAndroidLine.installEventFilter(self) endXyAndroidlayout.addWidget( QLabel( self.tr("Destination Coordinate X:") ) , 0, 0) endXyAndroidlayout.addWidget( self.endxAndroidLine , 0, 1) endXyAndroidlayout.addWidget( QLabel( self.tr("Destination Coordinate Y:") ) , 1,0) endXyAndroidlayout.addWidget( self.endyAndroidLine , 1, 1) self.endXyAndroidGroup.setLayout(endXyAndroidlayout) self.endXyAndroidGroup.hide() def createWidgetXY(self): """ Create text widget """ self.xyAndroidGroup = QGroupBox(self.tr("")) xyAndroidlayout = QGridLayout() self.xAndroidLine = QLineEdit(self) validatorXAndroid = QIntValidator (self) self.xAndroidLine.setValidator(validatorXAndroid) self.xAndroidLine.installEventFilter(self) self.yAndroidLine = QLineEdit(self) validatorYAndroid = QIntValidator (self) self.yAndroidLine.setValidator(validatorYAndroid) self.yAndroidLine.installEventFilter(self) xyAndroidlayout.addWidget( QLabel( self.tr("Coordinate X:") ) , 0,0) xyAndroidlayout.addWidget( self.xAndroidLine , 0, 1) xyAndroidlayout.addWidget( QLabel( self.tr("Coordinate Y:") ) , 1,0) xyAndroidlayout.addWidget( self.yAndroidLine , 1, 1) self.xyAndroidGroup.setLayout(xyAndroidlayout) self.xyAndroidGroup.hide() def createWidgetStart(self): """ Create text widget """ self.startAndroidGroup = QGroupBox(self.tr("")) startAndroidlayout = QGridLayout() self.startXAndroidLine = QLineEdit(self) validatorStartXAndroid = QIntValidator (self) self.startXAndroidLine.setValidator(validatorStartXAndroid) self.startXAndroidLine.installEventFilter(self) self.startYAndroidLine = QLineEdit(self) validatorStartYAndroid = QIntValidator (self) self.startYAndroidLine.setValidator(validatorStartYAndroid) self.startYAndroidLine.installEventFilter(self) self.stopXAndroidLine = QLineEdit(self) validatorStopXAndroid = QIntValidator (self) self.stopXAndroidLine.setValidator(validatorStopXAndroid) self.stopXAndroidLine.installEventFilter(self) self.stopYAndroidLine = QLineEdit(self) validatorStopYAndroid = QIntValidator (self) self.stopYAndroidLine.setValidator(validatorStopYAndroid) self.stopYAndroidLine.installEventFilter(self) startAndroidlayout.addWidget( QLabel( self.tr("From X:") ) , 0,1) startAndroidlayout.addWidget( self.startXAndroidLine , 0, 2) startAndroidlayout.addWidget( QLabel( self.tr("From Y:") ) , 0,3) startAndroidlayout.addWidget( self.startYAndroidLine , 0, 4) startAndroidlayout.addWidget( QLabel( self.tr("To X:") ) ,1,1) startAndroidlayout.addWidget( self.stopXAndroidLine , 1, 2) startAndroidlayout.addWidget( QLabel( self.tr("To Y:") ) , 1,3) startAndroidlayout.addWidget( self.stopYAndroidLine , 1 , 4) self.startAndroidGroup.setLayout(startAndroidlayout) self.startAndroidGroup.hide() def createWidgetShortcut(self): """ Create shortcut widget """ self.shortcutAndroidGroup = QGroupBox(self.tr("")) shortcutAndroidlayout = QGridLayout() self.shortcutAndroidComboBox = QComboBox(self) for i in xrange(len(KEYS_SHORTCUT_ANDROID)): if len(KEYS_SHORTCUT_ANDROID[i]) == 0: self.shortcutAndroidComboBox.insertSeparator(i + 2) else: self.shortcutAndroidComboBox.addItem (KEYS_SHORTCUT_ANDROID[i]) shortcutAndroidlayout.addWidget( QLabel( self.tr("Button:") ) , 0,1) shortcutAndroidlayout.addWidget(self.shortcutAndroidComboBox, 0, 2) self.shortcutAndroidGroup.setLayout(shortcutAndroidlayout) self.shortcutAndroidGroup.hide() def createWidgetCode(self): """ Create code widget """ self.codeAndroidGroup = QGroupBox(self.tr("")) self.codeAndroidLine = QLineEdit(self) validatorCodeAndroid = QIntValidator (self) self.codeAndroidLine.setValidator(validatorCodeAndroid) self.codeAndroidLine.installEventFilter(self) codeAndroidlayout = QGridLayout() codeAndroidlayout.addWidget( QLabel( self.tr("Code:") ) , 0,1) codeAndroidlayout.addWidget( self.codeAndroidLine , 0, 2) self.codeAndroidGroup.setLayout(codeAndroidlayout) self.codeAndroidGroup.hide() def pluginDataAccessor(self): """ Return data for plugin """ return { "data": "" } def onPluginImport(self, dataJson): """ Received data from plugin """ pass def createConnections(self): """ Create qt connections """ self.actionsAndroidComboBox.currentIndexChanged.connect(self.onActionAndroidChanged) self.addAndroidAction.clicked.connect(self.addStep) self.valueAndroidCombo2.currentIndexChanged.connect(self.onValueAndroid2TypeChanged) self.elementTextCombo.currentIndexChanged.connect(self.onElementTextTypeChanged) def onElementTextTypeChanged(self): """ On element text changed """ if self.elementTextCombo.currentText() in [ "TEXT", "CACHE" ]: self.elementTextAndroidLine.setValidator(self.validatorAll) if self.elementTextCombo.currentText() == "ALIAS": self.elementTextAndroidLine.setText( self.elementTextAndroidLine.text().upper() ) self.elementTextAndroidLine.setValidator(self.validatorUpper) def onValueAndroid2TypeChanged(self): """ On value changed """ if self.valueAndroidCombo2.currentText() in [ "TEXT", "CACHE" ]: self.valueAndroidLine2.setValidator(self.validatorAll) if self.valueAndroidCombo2.currentText() == "ALIAS": self.valueAndroidLine2.setText( self.valueAndroidLine2.text().upper() ) self.valueAndroidLine2.setValidator(self.validatorUpper) def addStep(self): """ Add step """ action = self.actionsAndroidComboBox.currentText() descr = self.descriptionAndroidLine.text() descr = unicode(descr).replace('"', '') signal = self.AddStep if self.cancelAndroidAction.isEnabled(): signal = self.UpdateStep if self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_WAKUP, GuiSteps.ANDROID_UNLOCK, GuiSteps.ANDROID_REBOOT, GuiSteps.ANDROID_SLEEP, GuiSteps.ANDROID_FREEZE_ROTATION, GuiSteps.ANDROID_UNFREEZE_ROTATION, GuiSteps.ANDROID_BOOTLOADER, GuiSteps.ANDROID_RECOVERY, GuiSteps.ANDROID_NOTIFICATION, GuiSteps.ANDROID_SETTINGS, GuiSteps.ANDROID_DEVICEINFO, GuiSteps.ANDROID_GET_LOGS, GuiSteps.ANDROID_CLEAR_LOGS , GuiSteps.ANDROID_WAKEUP_UNLOCK, GuiSteps.ANDROID_LOCK, GuiSteps.ANDROID_SLEEP_LOCK ]: signal.emit( str(action), unicode(descr), EMPTY_VALUE, {} ) elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_TYPE_SHORTCUT]: shorcut = self.shortcutAndroidComboBox.currentText() signal.emit( str(action), unicode(descr), shorcut, {} ) elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_TYPE_KEYCODE ]: code = self.codeAndroidLine.text() if not len(code): QMessageBox.warning(self, "Recording for Gui" , "Please to set a value!") else: signal.emit( str(action), unicode(descr), code, {} ) elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_CLEAR_ELEMENT, GuiSteps.ANDROID_CLICK_ELEMENT, GuiSteps.ANDROID_LONG_CLICK_ELEMENT, GuiSteps.ANDROID_EXIST_ELEMENT, GuiSteps.ANDROID_WAIT_ELEMENT, GuiSteps.ANDROID_TYPE_TEXT_ELEMENT, GuiSteps.ANDROID_GET_TEXT_ELEMENT, GuiSteps.ANDROID_DRAG_ELEMENT, GuiSteps.ANDROID_WAIT_CLICK_ELEMENT ]: textAndroid = self.elementTextAndroidLine.text() descrAndroid = self.elementDescriptionAndroidLine.text() classAndroid = self.elementClassAndroidLine.text() ressourceAndroid = self.elementRessourceIdAndroidLine.text() packageAndroid = self.elementPackageAndroidLine.text() if not len(textAndroid) and not len(classAndroid) and not len(ressourceAndroid) and not len(packageAndroid) and not len(descrAndroid): QMessageBox.warning(self, "Recording for Gui" , "Please to set one value!") else: # read text from cache or not ? fromElCache = False if self.elementTextCombo.currentText() == "CACHE": fromElCache = True fromElAlias = False if self.elementTextCombo.currentText() == "ALIAS": fromElAlias = True if self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_TYPE_TEXT_ELEMENT: newTextAndroid = self.valueAndroidLine2.text() if not len(newTextAndroid): QMessageBox.warning(self, "Recording for Gui" , "Please to set a text value!") else: # read text from cache or not ? fromCache = False if self.valueAndroidCombo2.currentText() == "CACHE": fromCache = True fromAlias = False if self.valueAndroidCombo2.currentText() == "ALIAS": fromAlias = True parameters = {'text': textAndroid, 'class': classAndroid, 'ressource': ressourceAndroid, 'package': packageAndroid, 'description': descrAndroid, 'new-text': newTextAndroid, 'from-cache': fromCache, 'from-alias': fromAlias, 'from-el-cache': fromElCache, 'from-el-alias': fromElAlias } signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters ) elif self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_GET_TEXT_ELEMENT: # read text from cache or not ? cacheKey = '' toCache = True cacheKey = self.valueTextCacheGlobalLine.text() parameters = {'text': textAndroid, 'class': classAndroid, 'ressource': ressourceAndroid, 'package': packageAndroid, 'description': descrAndroid, 'cache-key': cacheKey, 'to-cache': toCache, 'from-el-cache': fromElCache, 'from-el-alias': fromElAlias } signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters ) elif self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_DRAG_ELEMENT: xAndroid = self.endxAndroidLine.text() yAndroid = self.endyAndroidLine.text() if not len(xAndroid) and not len(yAndroid): QMessageBox.warning(self, "Recording for Gui" , "Please to set values!") else: parameters = {'text': textAndroid, 'class': classAndroid, 'ressource': ressourceAndroid, 'package': packageAndroid, 'description': descrAndroid, 'from-el-cache': fromElCache, 'from-el-alias': fromElAlias, 'x': xAndroid, 'y': yAndroid } signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters ) else: parameters = {'text': textAndroid, 'class': classAndroid, 'ressource': ressourceAndroid, 'package': packageAndroid, 'description': descrAndroid, 'from-el-cache': fromElCache, 'from-el-alias': fromElAlias } signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters ) elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_CLICK_POSITION ]: xAndroid = self.xAndroidLine.text() yAndroid = self.yAndroidLine.text() if not len(xAndroid) and not len(yAndroid): QMessageBox.warning(self, "Recording for Gui" , "Please to set values!") else: parameters = { 'x': xAndroid, 'y': yAndroid } signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters ) elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_DRAG_ELEMENT, GuiSteps.ANDROID_DRAG_POSITION, GuiSteps.ANDROID_SWIPE_POSITION]: startXAndroid = self.startXAndroidLine.text() startYAndroid = self.startYAndroidLine.text() stopXAndroid = self.stopXAndroidLine.text() stopYAndroid = self.stopYAndroidLine.text() if not len(startXAndroid) and not len(startYAndroid) and not len(stopXAndroid) and not len(stopYAndroid): QMessageBox.warning(self, "Recording for Gui" , "Please to set values!") else: parameters = { 'start-x': startXAndroid, 'start-y': startYAndroid, 'stop-x': stopXAndroid, 'stop-y': stopYAndroid } signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters ) elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_COMMAND, GuiSteps.ANDROID_SHELL, GuiSteps.ANDROID_RESET_APP, GuiSteps.ANDROID_STOP_APP]: miscStr = self.valueAndroidLine.text() if not len(miscStr): QMessageBox.warning(self, "Recording for Gui" , "Please to set a value!") else: if self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_COMMAND: parameters = { 'cmd': miscStr } elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_RESET_APP, GuiSteps.ANDROID_STOP_APP ]: parameters = { 'pkg': miscStr } else: parameters = { 'sh': miscStr } signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters ) else: signal.emit( str(action), unicode(descr), EMPTY_VALUE, {} ) def cancelStep(self): """ Cancel step """ self.addAndroidAction.setText( "&Add" ) buttonFont = QFont() buttonFont.setBold(False) self.addAndroidAction.setFont(buttonFont) self.cancelAndroidAction.setEnabled(False) self.CancelEdit.emit() def finalizeUpdate(self): """ Finalize the update of a step """ self.addAndroidAction.setText( "&Add Action" ) buttonFont = QFont() buttonFont.setBold(False) self.addAndroidAction.setFont(buttonFont) self.cancelAndroidAction.setEnabled(False) def onActionAndroidChanged(self): """ On action changed """ descr = 'No description available!' i = 0 for el in GuiSteps.ACTION_ANDROID_DESCR: if isinstance(el, dict): if self.actionsAndroidComboBox.currentText() in el: descr = GuiSteps.ACTION_ANDROID_DESCR[i][self.actionsAndroidComboBox.currentText()] break i += 1 self.labelActionAndroidDescr.setText( "%s\n" % descr ) if self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_TYPE_SHORTCUT ]: self.shortcutAndroidGroup.show() self.codeAndroidGroup.hide() self.elemenAndroidGroup.hide() self.startAndroidGroup.hide() self.xyAndroidGroup.hide() self.lineAndroidGroup.hide() self.line2AndroidGroup.hide() self.textToGlobalGroup.hide() self.endXyAndroidGroup.hide() self.arrowLabel.show() self.arrowLabel2.show() elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_TYPE_KEYCODE ]: self.codeAndroidGroup.show() self.shortcutAndroidGroup.hide() self.elemenAndroidGroup.hide() self.startAndroidGroup.hide() self.xyAndroidGroup.hide() self.lineAndroidGroup.hide() self.line2AndroidGroup.hide() self.textToGlobalGroup.hide() self.endXyAndroidGroup.hide() self.arrowLabel.show() self.arrowLabel2.show() elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_CLEAR_ELEMENT, GuiSteps.ANDROID_CLICK_ELEMENT, GuiSteps.ANDROID_LONG_CLICK_ELEMENT, GuiSteps.ANDROID_EXIST_ELEMENT, GuiSteps.ANDROID_WAIT_ELEMENT, GuiSteps.ANDROID_WAIT_CLICK_ELEMENT ]: self.shortcutAndroidGroup.hide() self.codeAndroidGroup.hide() self.elemenAndroidGroup.show() self.startAndroidGroup.hide() self.xyAndroidGroup.hide() self.lineAndroidGroup.hide() self.line2AndroidGroup.hide() self.textToGlobalGroup.hide() self.endXyAndroidGroup.hide() self.arrowLabel.show() self.arrowLabel2.show() elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_DRAG_ELEMENT ]: self.shortcutAndroidGroup.hide() self.codeAndroidGroup.hide() self.elemenAndroidGroup.show() self.startAndroidGroup.hide() self.xyAndroidGroup.hide() self.lineAndroidGroup.hide() self.line2AndroidGroup.hide() self.textToGlobalGroup.hide() self.endXyAndroidGroup.show() self.arrowLabel.show() self.arrowLabel2.show() elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_GET_TEXT_ELEMENT ]: self.shortcutAndroidGroup.hide() self.codeAndroidGroup.hide() self.elemenAndroidGroup.show() self.startAndroidGroup.hide() self.xyAndroidGroup.hide() self.lineAndroidGroup.hide() self.line2AndroidGroup.hide() self.textToGlobalGroup.show() self.endXyAndroidGroup.hide() self.arrowLabel.show() self.arrowLabel2.show() elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_CLICK_POSITION ]: self.shortcutAndroidGroup.hide() self.codeAndroidGroup.hide() self.elemenAndroidGroup.hide() self.startAndroidGroup.hide() self.xyAndroidGroup.show() self.lineAndroidGroup.hide() self.line2AndroidGroup.hide() self.textToGlobalGroup.hide() self.endXyAndroidGroup.hide() self.arrowLabel.show() self.arrowLabel2.show() elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_DRAG_POSITION, GuiSteps.ANDROID_SWIPE_POSITION ]: self.shortcutAndroidGroup.hide() self.codeAndroidGroup.hide() self.elemenAndroidGroup.hide() self.startAndroidGroup.show() self.xyAndroidGroup.hide() self.lineAndroidGroup.hide() self.line2AndroidGroup.hide() self.textToGlobalGroup.hide() self.endXyAndroidGroup.hide() self.arrowLabel.show() self.arrowLabel2.show() elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_COMMAND, GuiSteps.ANDROID_SHELL, GuiSteps.ANDROID_RESET_APP, GuiSteps.ANDROID_STOP_APP ]: self.shortcutAndroidGroup.hide() self.codeAndroidGroup.hide() self.elemenAndroidGroup.hide() self.startAndroidGroup.hide() self.xyAndroidGroup.hide() self.lineAndroidGroup.show() self.line2AndroidGroup.hide() self.textToGlobalGroup.hide() self.endXyAndroidGroup.hide() self.arrowLabel.show() self.arrowLabel2.show() elif self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_TYPE_TEXT_ELEMENT ]: self.shortcutAndroidGroup.hide() self.codeAndroidGroup.hide() self.elemenAndroidGroup.show() self.startAndroidGroup.hide() self.xyAndroidGroup.hide() self.lineAndroidGroup.hide() self.line2AndroidGroup.show() self.textToGlobalGroup.hide() self.endXyAndroidGroup.hide() self.arrowLabel.show() self.arrowLabel2.show() else: self.shortcutAndroidGroup.hide() self.codeAndroidGroup.hide() self.elemenAndroidGroup.hide() self.startAndroidGroup.hide() self.xyAndroidGroup.hide() self.lineAndroidGroup.hide() self.line2AndroidGroup.hide() self.textToGlobalGroup.hide() self.endXyAndroidGroup.hide() self.arrowLabel.hide() self.arrowLabel2.show() def setTimeout(self, timeout): """ Set the timeout """ self.optionsDialog.timeoutAndroidLine.setText(timeout) def getTimeout(self): """ Return the timeout """ return self.optionsDialog.timeoutAndroidLine.text() def getAgentName(self): """ Get the agent name """ return self.optionsDialog.agentNameLineAndroid.text() def getAgentList(self): """ Return the agent list """ return self.optionsDialog.agentsAndroidList def editStep(self, stepData): """ Edit a step """ self.addAndroidAction.setText( "&Update" ) buttonFont = QFont() buttonFont.setBold(True) self.addAndroidAction.setFont(buttonFont) self.cancelAndroidAction.setEnabled(True) # set the current value for actions combo for i in xrange(self.actionsAndroidComboBox.count()): item_text = self.actionsAndroidComboBox.itemText(i) if unicode(stepData["action"]) == unicode(item_text): self.actionsAndroidComboBox.setCurrentIndex(i) break # and then refresh options self.onActionAndroidChanged() # finally fill all fields self.descriptionAndroidLine.setText( stepData["description"] ) if self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_COMMAND: self.valueAndroidLine.setText( stepData["parameters"]["cmd"] ) if self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_SHELL: self.valueAndroidLine.setText( stepData["parameters"]["sh"] ) if self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_RESET_APP, GuiSteps.ANDROID_STOP_APP ]: self.valueAndroidLine.setText( stepData["parameters"]["pkg"] ) if self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_CLEAR_ELEMENT, GuiSteps.ANDROID_TYPE_TEXT_ELEMENT, GuiSteps.ANDROID_CLICK_ELEMENT, GuiSteps.ANDROID_LONG_CLICK_ELEMENT, GuiSteps.ANDROID_EXIST_ELEMENT, GuiSteps.ANDROID_WAIT_ELEMENT, GuiSteps.ANDROID_GET_TEXT_ELEMENT, GuiSteps.ANDROID_DRAG_ELEMENT, GuiSteps.ANDROID_WAIT_CLICK_ELEMENT ]: self.elementTextAndroidLine.setText( "" ) self.elementDescriptionAndroidLine.setText( "" ) self.elementClassAndroidLine.setText( "" ) self.elementRessourceIdAndroidLine.setText( "" ) self.elementPackageAndroidLine.setText( "" ) self.valueAndroidLine2.setText( "" ) if "text" in stepData["parameters"]: if stepData["parameters"]["from-el-cache"]: self.elementTextCombo.setCurrentIndex(INDEX_CACHE) self.elementTextAndroidLine.setValidator(self.validatorAll) elif stepData["parameters"]["from-el-alias"]: self.elementTextCombo.setCurrentIndex(INDEX_ALIAS) self.elementTextAndroidLine.setValidator(self.validatorUpper) else: self.elementTextCombo.setCurrentIndex(INDEX_TEXT) self.elementTextAndroidLine.setValidator(self.validatorAll) self.elementTextAndroidLine.setText ( stepData["parameters"]["text"] ) if "description" in stepData["parameters"]: self.elementDescriptionAndroidLine.setText( stepData["parameters"]["description"] ) if "class" in stepData["parameters"]: self.elementClassAndroidLine.setText( stepData["parameters"]["class"] ) if "ressource" in stepData["parameters"]: self.elementRessourceIdAndroidLine.setText( stepData["parameters"]["ressource"] ) if "package" in stepData["parameters"]: self.elementPackageAndroidLine.setText( stepData["parameters"]["package"] ) if "new-text" in stepData["parameters"]: self.valueAndroidLine2.setText( stepData["parameters"]["new-text"] ) if self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_DRAG_ELEMENT: if "x" in stepData["parameters"]: self.endxAndroidLine.setText( stepData["parameters"]["x"] ) if "y" in stepData["parameters"]: self.endyAndroidLine.setText( stepData["parameters"]["y"] ) if self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_TYPE_TEXT_ELEMENT: if stepData["parameters"]["from-cache"]: self.valueAndroidCombo2.setCurrentIndex(INDEX_CACHE) self.valueAndroidLine2.setValidator(self.validatorAll) elif stepData["parameters"]["from-alias"]: self.valueAndroidCombo2.setCurrentIndex(INDEX_ALIAS) self.valueAndroidLine2.setValidator(self.validatorUpper) else: self.valueAndroidCombo2.setCurrentIndex(INDEX_TEXT) self.valueAndroidLine2.setValidator(self.validatorAll) if self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_GET_TEXT_ELEMENT: self.valueTextCacheGlobalLine.setText ( stepData["parameters"]["cache-key"] ) if self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_CLICK_POSITION]: if "x" in stepData["parameters"]: self.xAndroidLine.setText( stepData["parameters"]["x"] ) if "y" in stepData["parameters"]: self.yAndroidLine.setText( stepData["parameters"]["y"] ) if self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_DRAG_POSITION, GuiSteps.ANDROID_SWIPE_POSITION]: if "start-x" in stepData["parameters"]: self.startXAndroidLine.setText( stepData["parameters"]["start-x"] ) if "start-y" in stepData["parameters"]: self.startYAndroidLine.setText( stepData["parameters"]["start-y"] ) if "stop-x" in stepData["parameters"]: self.stopXAndroidLine.setText( stepData["parameters"]["stop-x"] ) if "stop-y" in stepData["parameters"]: self.stopYAndroidLine.setText( stepData["parameters"]["stop-y"] ) if self.actionsAndroidComboBox.currentText() == GuiSteps.ANDROID_TYPE_KEYCODE: self.codeAndroidLine.setText( stepData["misc"] ) if self.actionsAndroidComboBox.currentText() in [ GuiSteps.ANDROID_TYPE_SHORTCUT ]: # set default for i in xrange(self.shortcutAndroidComboBox.count()): item_text = self.shortcutAndroidComboBox.itemText(i) if unicode(stepData["misc"]) == unicode(item_text): self.shortcutAndroidComboBox.setCurrentIndex(i) break
class OWFile(OWWidget): settingsList = ["selected_file", "recent_files", "show_advanced", "create_new_on"] contextHandlers = {"": FileNameContextHandler()} def __init__(self, parent=None, signalManager=None, title="CSV File Import"): OWWidget.__init__(self, parent, signalManager, title, wantMainArea=False, noReport=True) self.symbol_DC = "" self.symbol_DK = "" #: List of recent opened files. self.recent_files = [] #: Current selected file name self.selected_file = None #: Variable reuse flag self.create_new_on = 2 #: Display advanced var reuse options self.show_advanced = False self.loadSettings() self.recent_files = filter(os.path.exists, self.recent_files) self._loader = None self._invalidated = False self._datareport = None layout = QHBoxLayout() OWGUI.widgetBox(self.controlArea, "File", orientation=layout) icons = standard_icons(self) self.recent_combo = QComboBox( self, objectName="recent_combo", toolTip="Recent files.", activated=self.activate_recent ) cb_append_file_list(self.recent_combo, self.recent_files) self.recent_combo.insertSeparator(self.recent_combo.count()) self.recent_combo.addItem(u"Browse documentation data sets…") self.browse_button = QPushButton( u"…", icon=icons.dir_open_icon, toolTip="Browse filesystem", clicked=self.browse ) self.reload_button = QPushButton( "Reload", icon=icons.reload_icon, toolTip="Reload the selected file", clicked=self.reload, default=True ) layout.addWidget(self.recent_combo, 2) layout.addWidget(self.browse_button) layout.addWidget(self.reload_button) ########### # Info text ########### box = OWGUI.widgetBox(self.controlArea, "Info", addSpace=True) self.infoa = OWGUI.widgetLabel(box, "No data loaded.") self.infob = OWGUI.widgetLabel(box, " ") self.warnings = OWGUI.widgetLabel(box, " ") # Set word wrap so long warnings won't expand the widget self.warnings.setWordWrap(True) self.warnings.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.MinimumExpanding) advanced = QGroupBox( "Advanced Settings", checkable=True, checked=self.show_advanced ) advanced.setLayout(QVBoxLayout()) def set_group_visible(groupbox, state): layout = groupbox.layout() for i in range(layout.count()): item = layout.itemAt(i) widget = item.widget() if widget is not None: widget.setVisible(state) groupbox.setFlat(not state) def toogle_advanced(state): self.show_advanced = state set_group_visible(advanced, state) self.layout().activate() QApplication.instance().processEvents() QTimer.singleShot(0, self.adjustSize) advanced.toggled.connect(toogle_advanced) self.taboptions = QWidget() self.taboptions.setLayout(QVBoxLayout()) box = QGroupBox("Missing Value Symbols", flat=True) form = QFormLayout(fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow) form.addRow( "Don't care:", OWGUI.lineEdit(None, self, "symbol_DC", tooltip="Default values: '~' or '*'")) form.addRow( "Don't know:", OWGUI.lineEdit(None, self, "symbol_DK", tooltip="Default values: empty fields (space), " "'?' or 'NA'")) box.setLayout(form) advanced.layout().addWidget(box) rb = OWGUI.radioButtonsInBox( advanced, self, "create_new_on", box="New Attributes", callback=self._invalidate, label=u"Create a new attribute when existing attribute(s) …", btnLabels=[u"Have mismatching order of values", u"Have no common values with the new (recommended)", u"Miss some values of the new attribute", u"… Always create a new attribute"] ) rb.setFlat(True) self.controlArea.layout().addWidget(advanced) button_box = QDialogButtonBox(orientation=Qt.Horizontal) self.import_options_button = QPushButton( u"Import Options…", enabled=False ) self.import_options_button.pressed.connect(self._activate_import_dialog) button_box.addButton( self.import_options_button, QDialogButtonBox.ActionRole ) button_box.addButton( QPushButton("&Report", pressed=self.reportAndFinish), QDialogButtonBox.ActionRole ) self.controlArea.layout().addWidget(button_box) OWGUI.rubber(self.controlArea) set_group_visible(advanced, self.show_advanced) if self.recent_files and self.recent_files[0] == self.selected_file: QTimer.singleShot( 0, lambda: self.activate_recent(0) ) else: self.selected_file = None self.recent_combo.setCurrentIndex(-1) @Slot(int) def activate_recent(self, index): """Activate an item from the recent list.""" if 0 <= index < len(self.recent_files): recent = self.recent_files[index] self.set_selected_file(recent) elif index == len(self.recent_files) + 1: status = self.browse(Orange.utils.environ.dataset_install_dir) if status == QDialog.Rejected: self.recent_combo.setCurrentIndex( min(0, len(self.recent_files) - 1) ) else: self.recent_combo.setCurrentIndex(-1) @Slot() def browse(self, startdir=None): """ Open a file dialog and select a user specified file. """ if startdir is None: if self.selected_file: startdir = os.path.dirname(self.selected_file) else: startdir = unicode( QDesktopServices.storageLocation( QDesktopServices.DocumentsLocation) ) def format_spec(format): ext_pattern = ", ".join(map("*{}".format, format.extensions)) return "{} ({})".format(format.name, ext_pattern) formats = [format_spec(format) for format in FILEFORMATS] filters = ";;".join(formats + ["All files (*.*)"]) path, selected_filter = QFileDialog.getOpenFileNameAndFilter( self, "Open Data File", startdir, filters ) if path: path = unicode(path) if selected_filter in formats: filter_idx = formats.index(str(selected_filter)) fformat = FILEFORMATS[filter_idx] loader = DEFAULT_ACTIONS[filter_idx] if fformat.extensions in ([".csv"], [".tsv"]): loader = loader._replace( params=loader_for_path(path).params) else: loader = None self.set_selected_file(path, loader=loader) return QDialog.Accepted else: return QDialog.Rejected @Slot() def reload(self): """Reload the current selected file.""" if self.selected_file: self.send_data() def _activate_import_dialog(self): assert self.selected_file is not None dlg = CSVImportDialog( self, windowTitle="Import Options", ) dlg.setAttribute(Qt.WA_DeleteOnClose) dlg.setWindowFlags(Qt.Sheet) loader = self._loader dlg.set_options(loader.params) dlg.set_path(self.selected_file) def update(): self._loader = loader._replace(params=dlg.options()) self._invalidate() dlg.accepted.connect(update) dlg.open() def set_selected_file(self, filename, loader=None): """Set the current filename path to be loaded.""" self.closeContext("") self.selected_file = filename self._loader = None self._add_recent(filename) self.warning(1) self.openContext("", filename) if loader is not None and self._loader is not None and \ self._loader.format == loader.format: loader = self._loader if loader is None: loader = self._loader if loader is None: loader = loader_for_path(filename) self.set_loader(loader) def _add_recent(self, filename): """Add filename to the list of recent files.""" index_to_remove = None if filename in self.recent_files: index_to_remove = self.recent_files.index(filename) elif len(self.recent_files) >= 20: # keep maximum of 20 files in the list. index_to_remove = len(self.recent_files) - 1 cb_insert_file_list(self.recent_combo, 0, [filename]) self.recent_files.insert(0, filename) if index_to_remove is not None: self.recent_combo.removeItem(index_to_remove + 1) self.recent_files.pop(index_to_remove + 1) self.recent_combo.setCurrentIndex(0) def set_loader(self, loader): if loader is None: loader = DEFAULT_ACTIONS[0] self._loader = loader self.import_options_button.setEnabled( isinstance(loader.params, CSV) ) self._invalidate() def _invalidate(self): if not self._invalidated: self._invalidated = True QApplication.postEvent(self, QEvent(QEvent.User)) def customEvent(self, event): if self._invalidated: self._invalidated = False self.send_data() def send_data(self): self.error(0) loader = self._loader if "DK" in loader.params._fields and self.symbol_DK: loader = loader._replace( params=loader.params._replace( DK=str(self.symbol_DK), DC=str(self.symbol_DC)) ) try: data = load_table(self.selected_file, loader, create_new_on=3 - self.create_new_on) except Exception as err: self.error(str(err)) self.infoa.setText('Data was not loaded due to an error.') self.infob.setText('Error:') self.warnings.setText(str(err)) data = None else: self._update_status_messages(data) if data is not None: add_origin(data, self.selected_file) basename = os.path.basename(self.selected_file) data.name, _ = os.path.splitext(basename) self._datareport = self.prepareDataReport(data) else: self._datareport = None self.send("Data", data) def _update_status_messages(self, data): if data is None: self.infoa.setText("No data loaded.") self.infob.setText("") self.warnings.setText("") return def pluralize(seq): return "s" if len(seq) != 1 else "" summary = ("{n_instances} data instance{plural_1}, " "{n_features} feature{plural_2}, " "{n_meta} meta{plural_3}").format( n_instances=len(data), plural_1=pluralize(data), n_features=len(data.domain.attributes), plural_2=pluralize(data.domain.attributes), n_meta=len(data.domain.getmetas()), plural_3=pluralize(data.domain.getmetas())) self.infoa.setText(summary) cl = data.domain.class_var if cl is not None: if isinstance(cl, Orange.feature.Continuous): self.infob.setText('Regression; Numerical class.') elif isinstance(cl, Orange.feature.Discrete): self.infob.setText( 'Classification; Discrete class with %d value%s.' % (len(cl.values), 's' if len(cl.values) > 1 else '') ) else: self.infob.setText("Class is neither discrete nor continuous.") elif data.domain.class_vars: self.infob.setText("Multiple class variables") else: self.infob.setText("Data has no dependent variable.") self.warnings.setText( feature_load_status_report(data, self.create_new_on)) def sendReport(self): if self._datareport: formatname = self._loader.format self.reportSettings( "File", [("File name", self.selected_file), ("Format", formatname)]) self.reportData(self._datareport) def settingsFromWidgetCallback(self, handler, context): context.filename = self.selected_file or "" context.loader = self._loader context.symbolDC, context.symbolDK = self.symbol_DC, self.symbol_DK def settingsToWidgetCallback(self, handler, context): self.symbol_DC, self.symbol_DK = context.symbolDC, context.symbolDK self._loader = getattr(context, "loader", None) def setSettings(self, settings): if settings.get(_SETTINGS_VERSION_KEY, None) is None: # import old File widget's settings mapping = [ ("recentFiles", "recent_files"), ("createNewOn", "create_new_on"), ("showAdvanced", "show_advanced") ] if all(old in settings for old, _ in mapping) and \ not any(new in settings for _, new in mapping): settings = settings.copy() for old, new in mapping: settings[new] = settings[old] del settings[old] # settings[_SETTINGS_VERSION_KEY] = self.settingsDataVersion if len(settings["recent_files"]): settings["selected_file"] = settings["recent_files"][0] super(OWFile, self).setSettings(settings)
class SettingsWidget(QWidget): """ Widget for setting entrys Inherits: QWidget Signals: sig_index_changed - Emitted, if the index of a combo box changes (Combo box name|str) """ sig_index_changed = pyqtSignal(str) def __init__(self, content, parent=None): """ Initialise the layout. Arguments: content - Content for the widget. parent - Parent widget (default None) Returns: None """ super(SettingsWidget, self).__init__(parent) # Layout layout = QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) # Global content self.default = content[0] self.typ = content[1]['typ'] self.values = content[1]['values'] self.name = content[1]['name'] self.dtype = content[1]['dtype'] if self.typ == 'PLAIN': self.edit = QLineEdit(self.name, self) self.edit.setText(self.default) elif self.typ == 'FILE': self.edit = QLineEdit(self.name, self) self.edit.setText(self.default) self.edit.setPlaceholderText('Press shift+return') self.edit.returnPressed.connect(self._find_file) elif self.typ == 'FILE/CHOICE': self.edit = QLineEdit(self.name, self) self.edit.setText(self.default) self.edit.setPlaceholderText('Press shift+return') self.edit.returnPressed.connect(self._find_file) elif self.typ == 'DIR': self.edit = QLineEdit(self.name, self) self.edit.setText(self.default) self.edit.setPlaceholderText('Press shift+return') self.edit.returnPressed.connect(self._find_dir) elif self.typ == 'COMBO': self.edit = QComboBox(self) self.edit.currentIndexChanged.connect( lambda: self.sig_index_changed.emit(self.name)) self.edit.addItems(self.values) self.edit.setCurrentIndex(self.edit.findText(self.default)) self.change_color_if_true() else: print('SettingsWidget:', self.typ, 'Not known! Stopping here!') sys.exit() self.label = QLabel(self.name, self) self.label.setObjectName('setting') self.edit.setObjectName('setting') try: self.edit.textEdited.connect( lambda: self.edit.setStyleSheet(tu.get_style(typ='unchanged'))) except AttributeError: pass try: self.edit.currentIndexChanged.connect(self.change_color_if_true) except AttributeError: pass layout.addWidget(self.label) layout.addWidget(self.edit) def change_color_if_true(self): """ Change the color, if the types are all true. Arguments: None Returns: None """ if self.edit.currentText() == 'False': self.edit.setStyleSheet(tu.get_style(typ='False')) else: self.edit.setStyleSheet(tu.get_style(typ='True')) @pyqtSlot() def _find_file(self): """ Find file with an open file dialog. Arguments: None Returns: None """ in_file = QFileDialog.getOpenFileName( caption='Find file: {0}'.format(self.name), directory=os.getcwd(), options=QFileDialog.DontUseNativeDialog) if QT_VERSION == 4: in_file = in_file elif QT_VERSION == 5: in_file = in_file[0] else: raise ImportError( 'QT version unknown! Please contact the transphire authors!') if in_file != '': self.sender().setText(in_file) @pyqtSlot() def _find_dir(self): """ Find directory with an open directory dialog Arguments: None Returns: None """ in_dir = QFileDialog.getExistingDirectory( caption='Find directory: {0}'.format(self.name), directory=os.getcwd(), options=QFileDialog.DontUseNativeDialog) if in_dir != '': self.sender().setText(in_dir) def get_settings(self, quiet=False): """ Get the settings as dict. Arguments: quiet - True, if prints should not be shown. Returns: None, if an error occured. Settings as dictionary. """ settings = {} if isinstance(self.edit, QComboBox): value = self.edit.currentText() elif isinstance(self.edit, QLineEdit): value = self.edit.text() else: message = 'Unreachable code! Please contact the TranSPHIRE authors!' print(message) tu.message(message) return None if value: if tu.check_instance(value=value, typ=self.dtype): self.edit.setStyleSheet(tu.get_style(typ='pass')) else: self.edit.setStyleSheet(tu.get_style(typ='error')) message = '{0}: {1} needs to be {2}'.format( self.label.text(), value, self.dtype) if not quiet: print(message) tu.message(message) else: pass return None else: pass settings[self.name] = value return settings def get_combo_entries(self): """ Get the entries of the combo boxes. Arguments: None Returns: List containing entries. """ entries_list = [] for idx in range(self.edit.count()): entries_list.append(self.edit.itemText(idx)) return entries_list def set_settings(self, text): """ Set settings text - Text to set to the widget. Returns: None """ if self.typ == 'COMBO': index = self.edit.findText(text) if index == -1: index = 0 else: pass self.edit.setCurrentIndex(index - 1) self.edit.setCurrentIndex(index) else: self.edit.setText(text)
class preferencesDialog(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.tmpPref = {} self.tmpPref['pref'] = copy.deepcopy(self.parent().prm['pref']) self.currLocale = self.parent().prm['data']['currentLocale'] self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator) self.tabWidget = QTabWidget() self.tabWidget.currentChanged.connect(self.tabChanged) self.appPrefWidget = QWidget() self.plotPrefWidget = QWidget() self.signalPrefWidget = QWidget() self.soundPrefWidget = QWidget() #APP PREF appPrefGrid = QGridLayout() n = 0 self.languageChooserLabel = QLabel(self.tr('Language (requires restart):')) appPrefGrid.addWidget(self.languageChooserLabel, n, 0) self.languageChooser = QComboBox() self.languageChooser.addItems(self.parent().prm['data']['available_languages']) self.languageChooser.setCurrentIndex(self.languageChooser.findText(self.tmpPref['pref']['language'])) self.languageChooser.currentIndexChanged[int].connect(self.onLanguageChooserChange) appPrefGrid.addWidget(self.languageChooser, n, 1) n = n+1 self.countryChooserLabel = QLabel(self.tr('Country (requires restart):')) appPrefGrid.addWidget(self.countryChooserLabel, n, 0) self.countryChooser = QComboBox() self.countryChooser.addItems(self.parent().prm['data']['available_countries'][self.tmpPref['pref']['language']]) self.countryChooser.setCurrentIndex(self.countryChooser.findText(self.tmpPref['pref']['country'])) appPrefGrid.addWidget(self.countryChooser, n, 1) self.appPrefWidget.setLayout(appPrefGrid) #PLOT PREF plotPrefGrid = QGridLayout() n = 0 #LINE COLOUR self.lineColor1 = self.tmpPref['pref']['lineColor1'] self.lineColorButton = QPushButton(self.tr("Line Color"), self) self.lineColorButton.clicked.connect(self.onChangeLineColor) plotPrefGrid.addWidget(self.lineColorButton, n, 0) self.lineColorSquare = QWidget(self) self.lineColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.lineColor1.name()) plotPrefGrid.addWidget(self.lineColorSquare, n, 1) n = n+1 self.backgroundColor = self.tmpPref['pref']['backgroundColor'] self.backgroundColorButton = QPushButton(self.tr("Background Color"), self) self.backgroundColorButton.clicked.connect(self.onChangeBackgroundColor) plotPrefGrid.addWidget(self.backgroundColorButton, n, 0) self.backgroundColorSquare = QWidget(self) self.backgroundColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.backgroundColor.name()) plotPrefGrid.addWidget(self.backgroundColorSquare, n, 1) n = n+1 self.canvasColor = self.tmpPref['pref']['canvasColor'] self.canvasColorButton = QPushButton(self.tr("Canvas Color"), self) self.canvasColorButton.clicked.connect(self.onChangeCanvasColor) plotPrefGrid.addWidget(self.canvasColorButton, n, 0) self.canvasColorSquare = QWidget(self) self.canvasColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.canvasColor.name()) plotPrefGrid.addWidget(self.canvasColorSquare, n, 1) n = n+1 self.dpiLabel = QLabel(self.tr('DPI - Resolution:')) plotPrefGrid.addWidget(self.dpiLabel, n, 0) self.dpiWidget = QLineEdit(str(self.tmpPref['pref']['dpi'])) plotPrefGrid.addWidget(self.dpiWidget, n, 1) self.dpiWidget.setValidator(QIntValidator(self)) self.dpiWidget.editingFinished.connect(self.ondpiChange) n = n+1 self.cmapChooserLabel = QLabel(self.tr('Color Map:')) plotPrefGrid.addWidget(self.cmapChooserLabel, n, 0) self.cmapChooser = QComboBox() self.cmapChooser.addItems(self.parent().prm['data']['available_colormaps']) self.cmapChooser.setCurrentIndex(self.cmapChooser.findText(self.tmpPref['pref']['colormap'])) plotPrefGrid.addWidget(self.cmapChooser, n, 1) n = n+1 self.gridOn = QCheckBox(self.tr('Grid')) self.gridOn.setChecked(self.tmpPref['pref']['grid']) plotPrefGrid.addWidget(self.gridOn, n, 1) self.plotPrefWidget.setLayout(plotPrefGrid) #SIGNAL PREF signalPrefGrid = QGridLayout() n = 0 self.windowChooser = QComboBox() self.windowChooser.addItems(self.parent().prm['data']['available_windows']) self.windowChooser.setCurrentIndex(self.windowChooser.findText(self.tmpPref['pref']['smoothingWindow'])) self.windowChooserLabel = QLabel(self.tr('Window:')) signalPrefGrid.addWidget(self.windowChooserLabel, 0, 0) signalPrefGrid.addWidget(self.windowChooser, 0, 1) n = n+1 self.signalPrefWidget.setLayout(signalPrefGrid) #SOUND PREF soundPrefGrid = QGridLayout() n = 0 self.wavmanagerLabel = QLabel(self.tr('Wav Manager (requires restart):')) self.wavmanagerChooser = QComboBox() self.wavmanagerChooser.addItems(["scipy"]) self.wavmanagerChooser.setCurrentIndex(self.wavmanagerChooser.findText(self.tmpPref['pref']['wavmanager'])) soundPrefGrid.addWidget(self.wavmanagerLabel, n, 0) soundPrefGrid.addWidget(self.wavmanagerChooser, n, 1) n = n+1 self.playChooser = QComboBox() self.playChooser.addItems(self.parent().prm['data']['available_play_commands']) self.playChooser.setCurrentIndex(self.playChooser.findText(self.tmpPref['pref']['playCommandType'])) self.playChooser.currentIndexChanged[int].connect(self.onPlayChooserChange) self.playChooserLabel = QLabel(self.tr('Play Command:')) soundPrefGrid.addWidget(self.playChooserLabel, n, 0) soundPrefGrid.addWidget(self.playChooser, n, 1) n = n+1 self.playCommandLabel = QLabel(self.tr('Command:')) soundPrefGrid.addWidget(self.playCommandLabel, n, 0) self.playCommandWidget = QLineEdit(str(self.tmpPref['pref']['playCommand'])) self.playCommandWidget.setReadOnly(True) soundPrefGrid.addWidget(self.playCommandWidget, n, 1) n = n+1 self.maxLevelLabel = QLabel(self.tr('Max Level:')) soundPrefGrid.addWidget(self.maxLevelLabel, n, 0) self.maxLevelWidget = QLineEdit(self.currLocale.toString(self.tmpPref['pref']['maxLevel'])) self.maxLevelWidget.setValidator(QDoubleValidator(self)) soundPrefGrid.addWidget(self.maxLevelWidget, n, 1) self.soundPrefWidget.setLayout(soundPrefGrid) self.tabWidget.addTab(self.appPrefWidget, self.tr("Applicatio&n")) self.tabWidget.addTab(self.plotPrefWidget, self.tr("Plot&s")) self.tabWidget.addTab(self.signalPrefWidget, self.tr("Signa&l")) self.tabWidget.addTab(self.soundPrefWidget, self.tr("Soun&d")) buttonBox = QDialogButtonBox(QDialogButtonBox.Apply|QDialogButtonBox.Ok|QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) buttonBox.button(QDialogButtonBox.Apply).clicked.connect(self.permanentApply) layout = QVBoxLayout() layout.addWidget(self.tabWidget) layout.addWidget(buttonBox) self.setLayout(layout) def ondpiChange(self): try: val = int(self.dpiWidget.text()) except ValueError: QMessageBox.warning(self, self.tr('Warning'), self.tr('dpi value not valid')) self.dpiWidget.setText(str(self.tmpPref['pref']['dpi'])) val = int(self.dpiWidget.text()) if val < 10: QMessageBox.warning(self, self.tr('Warning'), self.tr('dpi value too small')) self.dpiWidget.setText(str(10)) def onChangeLineColor(self): col = QColorDialog.getColor() if col.isValid(): self.lineColor1 = col self.lineColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.lineColor1.name()) def onChangeCanvasColor(self): col = QColorDialog.getColor() if col.isValid(): self.canvasColor = col self.canvasColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.canvasColor.name()) def onChangeBackgroundColor(self): col = QColorDialog.getColor() if col.isValid(): self.backgroundColor = col self.backgroundColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.backgroundColor.name()) def onLanguageChooserChange(self): for i in range(self.countryChooser.count()): self.countryChooser.removeItem(0) self.countryChooser.addItems(self.parent().prm['data']['available_countries'][self.languageChooser.currentText()]) def onPlayChooserChange(self): foo = self.playChooser.currentText() if foo != self.tr('custom'): self.playCommandWidget.setText(foo) self.playCommandWidget.setReadOnly(True) else: self.playCommandWidget.setReadOnly(False) def tryApply(self): self.tmpPref['pref']['colormap'] = str(self.cmapChooser.currentText()) self.tmpPref['pref']['dpi'] = int(self.dpiWidget.text()) self.tmpPref['pref']['lineColor1'] = self.lineColor1 self.tmpPref['pref']['canvasColor'] = self.canvasColor self.tmpPref['pref']['backgroundColor'] = self.backgroundColor self.tmpPref['pref']['language'] = self.languageChooser.currentText() self.tmpPref['pref']['country'] = self.countryChooser.currentText() self.tmpPref['pref']['wavmanager'] = str(self.wavmanagerChooser.currentText()) self.tmpPref['pref']['playCommand'] = self.playCommandWidget.text() self.tmpPref['pref']['playCommandType'] = self.playChooser.currentText() self.tmpPref['pref']['maxLevel'] = self.currLocale.toDouble(self.maxLevelWidget.text())[0] if self.gridOn.isChecked(): self.tmpPref['pref']['grid'] = True else: self.tmpPref['pref']['grid'] = False self.tmpPref['pref']['smoothingWindow'] = str(self.windowChooser.currentText()) def revertChanges(self): self.cmapChooser.setCurrentIndex(self.cmapChooser.findText(self.tmpPref['pref']['colormap'])) self.dpiWidget.setText(str(self.tmpPref['pref']['dpi'])) self.languageChooser.setCurrentIndex(self.languageChooser.findText(self.tmpPref['pref']['language'])) self.countryChooser.setCurrentIndex(self.countryChooser.findText(self.tmpPref['pref']['country'])) self.wavmanagerChooser.setCurrentIndex(self.wavmanagerChooser.findText(self.tmpPref['pref']['sound']['wavmanager'])) self.playChooser.setCurrentIndex(self.playChooser.findText(self.tmpPref['pref']['playCommandType'])) self.playCommandWidget.setText(self.tmpPref['pref']['playCommand']) if self.playChooser.currentText() != self.tr('custom'): self.playCommandWidget.setReadOnly(True) self.maxLevelWidget.setText(str(self.tmpPref['pref']['maxLevel'])) self.gridOn.setChecked(self.tmpPref['pref']['grid']) self.windowChooser.setCurrentIndex(self.windowChooser.findText(self.tmpPref['pref']['smoothingWindow'])) self.lineColor1 = self.tmpPref['pref']['lineColor1'] self.lineColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.lineColor1.name()) self.canvasColor = self.tmpPref['pref']['canvasColor'] self.backgroundColor = self.tmpPref['pref']['backgroundColor'] self.backgroundColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.backgroundColor.name()) self.canvasColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.canvasColor.name()) def permanentApply(self): self.tryApply() self.parent().prm['pref'] = copy.deepcopy(self.tmpPref['pref']) f = open(self.parent().prm['prefFile'], 'wb') pickle.dump(self.parent().prm['pref'], f) f.close() def tabChanged(self): self.tryApply() if self.tmpPref['pref'] != self.parent().prm['pref']: conf = applyChanges(self) if conf.exec_(): self.permanentApply() else: self.tmpPref['pref'] = copy.deepcopy(self.parent().prm['pref']) self.revertChanges()
class HydraulicsDialog(QDialog): def __init__(self, parent, params, new_proj=False): QDialog.__init__(self, parent) self.parent = parent self.params = params self.new_proj = new_proj self.setMinimumWidth(min_width) # self.setMinimumHeight(min_height) # Build dialog self.setWindowTitle('Options - Hydraulics') # TODO: softcode self.setWindowModality(QtCore.Qt.ApplicationModal) self.fra_form = QFrame(self) fra_form_lay = QFormLayout(self.fra_form) fra_form_lay.setContentsMargins(10, 10, 10, 10) self.lbl_units = QLabel('Units system:') # TODO: softocode self.cbo_units = QComboBox() fra_form_lay.addRow(self.lbl_units, self.cbo_units) self.lbl_flow_units = QLabel('Flow units:') # TODO: softocode self.cbo_flow_units = QComboBox() fra_form_lay.addRow(self.lbl_flow_units, self.cbo_flow_units) self.lbl_headloss = QLabel('Head loss:') # TODO: softocode self.cbo_headloss = QComboBox() fra_form_lay.addRow(self.lbl_headloss, self.cbo_headloss) self.chk_hydraulics = QCheckBox('Hydraulics:') # TODO: softcode self.cbo_hydraulics = QComboBox() fra_form_lay.addRow(self.chk_hydraulics, self.cbo_hydraulics) self.txt_hydraulics_file = QLineEdit() fra_form_lay.addRow(None, self.txt_hydraulics_file) self.btn_hydraulics_file = QPushButton('File...') # TODO: softcode fra_form_lay.addRow(None, self.btn_hydraulics_file) self.lbl_viscosity = QLabel('Viscosity:') # TODO: softocode self.txt_viscosity = QLineEdit() fra_form_lay.addRow(self.lbl_viscosity, self.txt_viscosity) self.lbl_diffusivity = QLabel('Diffusivity:') # TODO: softocode self.txt_diffusivity = QLineEdit() fra_form_lay.addRow(self.lbl_diffusivity, self.txt_diffusivity) self.lbl_spec_gravity = QLabel('Specific gravity:') # TODO: softocode self.txt_spec_gravity = QLineEdit() fra_form_lay.addRow(self.lbl_spec_gravity, self.txt_spec_gravity) self.lbl_max_trials = QLabel('Max trials:') # TODO: softocode self.txt_max_trials = QLineEdit() fra_form_lay.addRow(self.lbl_max_trials, self.txt_max_trials) self.lbl_accuracy = QLabel('Accuracy:') # TODO: softocode self.txt_accuracy = QLineEdit() fra_form_lay.addRow(self.lbl_accuracy, self.txt_accuracy) self.lbl_unbalanced = QLabel('Unbalanced:') # TODO: softcode self.fra_unbalanced = QFrame(self) fra_unbalanced_lay = QHBoxLayout(self.fra_unbalanced) fra_unbalanced_lay.setContentsMargins(0, 0, 0, 0) self.cbo_unbalanced = QComboBox() self.txt_unbalanced = QLineEdit() fra_unbalanced_lay.addWidget(self.cbo_unbalanced) fra_unbalanced_lay.addWidget(self.txt_unbalanced) fra_form_lay.addRow(self.lbl_unbalanced, self.fra_unbalanced) self.lbl_pattern = QLabel('Pattern:') # TODO: softocode self.cbo_pattern = QComboBox() fra_form_lay.addRow(self.lbl_pattern, self.cbo_pattern) self.lbl_demand_mult = QLabel('Demand multiplier:') # TODO: softocode self.txt_demand_mult = QLineEdit() fra_form_lay.addRow(self.lbl_demand_mult, self.txt_demand_mult) self.lbl_emitter_exp = QLabel('Emitter exponent:') # TODO: softocode self.txt_emitter_exp = QLineEdit() fra_form_lay.addRow(self.lbl_emitter_exp, self.txt_emitter_exp) self.lbl_tolerance = QLabel('Tolerance:') # TODO: softocode self.txt_tolerance = QLineEdit() fra_form_lay.addRow(self.lbl_tolerance, self.txt_tolerance) # Buttons self.fra_buttons = QFrame(self) fra_buttons_lay = QHBoxLayout(self.fra_buttons) self.btn_Cancel = QPushButton('Cancel') self.btn_Ok = QPushButton('OK') fra_buttons_lay.addWidget(self.btn_Ok) fra_buttons_lay.addWidget(self.btn_Cancel) # Add to main fra_main_lay = QVBoxLayout(self) fra_main_lay.setContentsMargins(0, 0, 0, 0) fra_main_lay.addWidget(self.fra_form) fra_main_lay.addWidget(self.fra_buttons) self.setup() def setup(self): # Fill units system combo box for unit in self.params.options.units_sys: self.cbo_units.addItem(self.params.options.units_sys_text[unit], unit) # Fill flow units combo box for fu in Options.units_flow[self.params.options.units]: self.cbo_flow_units.addItem(Options.units_flow_text[fu], fu) self.cbo_units.activated.connect(self.cbo_units_activated) # self.cbo_flow_units.activated.connect(self.cbo_flow_units_activated) for key, value in self.params.options.headlosses_text.iteritems(): self.cbo_headloss.addItem(value, key) self.cbo_headloss.activated.connect(self.cbo_headloss_activated) self.chk_hydraulics.stateChanged.connect(self.chk_hydraulics_changed) self.btn_hydraulics_file.clicked.connect(self.btn_hydraulics_clicked) self.cbo_hydraulics.addItem( self.params.options.hydraulics.action_names[ self.params.options.hydraulics.action_use], self.params.options.hydraulics.action_use) self.cbo_hydraulics.addItem( self.params.options.hydraulics.action_names[ self.params.options.hydraulics.action_save], self.params.options.hydraulics.action_save) self.txt_hydraulics_file.setReadOnly(True) # - Unbalanced for id, text in self.params.options.unbalanced.unb_text.iteritems(): self.cbo_unbalanced.addItem(text, id) self.cbo_unbalanced.activated.connect(self.cbo_unbalanced_changed) self.txt_unbalanced.setValidator(RegExValidators.get_pos_int_no_zero()) self.txt_unbalanced.setText('1') # - Pattern self.cbo_pattern.addItem('None (=1.0)', None) for pattern_id, pattern in self.params.patterns.iteritems(): self.cbo_pattern.addItem(pattern_id, pattern) # Buttons self.btn_Cancel.clicked.connect(self.btn_cancel_clicked) self.btn_Ok.clicked.connect(self.btn_ok_clicked) # Validators self.txt_viscosity.setValidator(RegExValidators.get_pos_decimals()) self.txt_diffusivity.setValidator(RegExValidators.get_pos_decimals()) self.txt_spec_gravity.setValidator(RegExValidators.get_pos_decimals()) self.txt_max_trials.setValidator(RegExValidators.get_pos_int_no_zero()) self.txt_accuracy.setValidator(RegExValidators.get_pos_decimals()) self.txt_demand_mult.setValidator(RegExValidators.get_pos_decimals()) self.txt_emitter_exp.setValidator(RegExValidators.get_pos_decimals()) self.txt_tolerance.setValidator(RegExValidators.get_pos_decimals()) def show(self): super(HydraulicsDialog, self).show() self.cbo_units.setCurrentIndex( self.cbo_units.findData(self.params.options.units)) self.cbo_flow_units.setCurrentIndex( self.cbo_flow_units.findData(self.params.options.flow_units)) self.cbo_headloss.setCurrentIndex( self.cbo_headloss.findData(self.params.options.headloss)) self.chk_hydraulics.setChecked( self.params.options.hydraulics.use_hydraulics) self.btn_hydraulics_file.setEnabled(self.chk_hydraulics.isChecked()) self.cbo_hydraulics.setEnabled(self.chk_hydraulics.isChecked()) self.txt_hydraulics_file.setEnabled(self.chk_hydraulics.isChecked()) if self.params.options.hydraulics.action is not None: self.cbo_hydraulics.setCurrentIndex( self.cbo_hydraulics.findData( self.params.options.hydraulics.action)) if self.params.options.hydraulics.file is not None: self.txt_hydraulics_file.setText( self.params.options.hydraulics.file) self.txt_viscosity.setText(str(self.params.options.viscosity)) self.txt_diffusivity.setText(str(self.params.options.diffusivity)) self.txt_spec_gravity.setText(str(self.params.options.spec_gravity)) self.txt_max_trials.setText(str(self.params.options.trials)) self.txt_accuracy.setText(str(self.params.options.accuracy)) self.cbo_unbalanced.setCurrentIndex( self.cbo_unbalanced.findData( self.params.options.unbalanced.unbalanced)) self.txt_unbalanced.setEnabled(self.cbo_unbalanced.currentIndex() != 0) self.txt_unbalanced.setText(str(self.params.options.unbalanced.trials)) # Patterns if self.params.options.pattern is not None: if self.params.options.pattern is None: self.cbo_pattern.setCurrentIndex(0) else: for i in range(self.cbo_pattern.count()): if self.params.options.pattern.id == self.cbo_pattern.itemText( i): self.cbo_pattern.setCurrentIndex(i) break self.txt_demand_mult.setText(str(self.params.options.demand_mult)) self.txt_emitter_exp.setText(str(self.params.options.emitter_exp)) self.txt_tolerance.setText(str(self.params.options.tolerance)) def cbo_units_activated(self): self.params.options.units = self.cbo_units.itemData( self.cbo_units.currentIndex()) # Parameters combo box self.cbo_flow_units.clear() for fu in Options.units_flow[self.params.options.units]: self.cbo_flow_units.addItem(Options.units_flow_text[fu], fu) def cbo_headloss_activated(self): # Warning if not self.new_proj: QMessageBox.warning( self, Parameters.plug_in_name, u'Head loss units changed: the head loss values already present might need to be reviewed.', QMessageBox.Ok) def chk_hydraulics_changed(self): self.btn_hydraulics_file.setEnabled(self.chk_hydraulics.isChecked()) self.cbo_hydraulics.setEnabled(self.chk_hydraulics.isChecked()) self.txt_hydraulics_file.setEnabled(self.chk_hydraulics.isChecked()) def btn_hydraulics_clicked(self): file_dialog = QFileDialog(self, 'Select hydraulics file') file_dialog.setLabelText(QFileDialog.Accept, 'Select') file_dialog.setLabelText(QFileDialog.Reject, 'Cancel') file_dialog.setFileMode(QFileDialog.AnyFile) file_dialog.exec_() hydraulics_file_path = file_dialog.selectedFiles() if not hydraulics_file_path or hydraulics_file_path[ 0] is None or hydraulics_file_path[0] == '': return self.txt_hydraulics_file.setText(hydraulics_file_path[0]) def cbo_unbalanced_changed(self): self.txt_unbalanced.setEnabled( self.cbo_unbalanced.itemData(self.cbo_unbalanced.currentIndex()) == self.params.options.unbalanced.unb_continue) def btn_cancel_clicked(self): self.setVisible(False) def btn_ok_clicked(self): if not self.check_params(): return # Update parameters and options self.params.options.units = self.cbo_units.itemData( self.cbo_units.currentIndex()) self.params.options.flow_units = self.cbo_flow_units.itemData( self.cbo_flow_units.currentIndex()) self.params.options.headloss = self.cbo_headloss.itemData( self.cbo_headloss.currentIndex()) self.params.options.hydraulics.use_hydraulics = self.chk_hydraulics.isChecked( ) if self.params.options.hydraulics.action is not None: self.params.options.hydraulics.action = self.cbo_hydraulics.itemData( self.cbo_hydraulics.currentIndex()) self.params.options.hydraulics.file = self.txt_hydraulics_file.text( ) self.params.options.viscosity = float(self.txt_viscosity.text()) self.params.options.diffusivity = float(self.txt_diffusivity.text()) self.params.options.spec_gravity = float(self.txt_spec_gravity.text()) self.params.options.trials = float(self.txt_max_trials.text()) self.params.options.accuracy = float(self.txt_accuracy.text()) self.params.options.unbalanced.unbalanced = self.cbo_unbalanced.itemData( self.cbo_unbalanced.currentIndex()) self.params.options.unbalanced.trials = int(self.txt_unbalanced.text()) self.params.options.pattern = self.cbo_pattern.itemData( self.cbo_pattern.currentIndex()) self.params.options.demand_mult = float(self.txt_demand_mult.text()) self.params.options.emitter_exp = float(self.txt_emitter_exp.text()) self.params.options.tolerance = float(self.txt_tolerance.text()) # Junctions self.parent.lbl_junction_demand.setText( pre_l('Demand', Options.units_flow[self.params.options.units] [0])) # TODO: softcode self.parent.lbl_junction_deltaz.setText( pre_l('Delta Z', Options.units_deltaz[ self.params.options.units])) # TODO: softcode # Reservoirs self.parent.lbl_reservoir_deltaz.setText( pre_l('Delta Z', Options.units_deltaz[ self.params.options.units])) # TODO: softcode self.parent.lbl_reservoir_pressure_head.setText( pre_l('Pressure head', Options.units_deltaz[ self.params.options.units])) # TODO: softcode # Tanks self.parent.lbl_tank_deltaz.setText( pre_l('Delta Z', Options.units_deltaz[ self.params.options.units])) # TODO: softcode self.parent.lbl_tank_level_init.setText( pre_l('Level init.', Options.units_deltaz[ self.params.options.units])) # TODO: softcode self.parent.lbl_tank_level_min.setText( pre_l('Level min', Options.units_deltaz[ self.params.options.units])) # TODO: softcode self.parent.lbl_tank_level_max.setText( pre_l('Level max', Options.units_deltaz[ self.params.options.units])) # TODO: softcode self.parent.lbl_tank_diameter.setText( pre_l('Diameter', Options.units_diameter_tanks[ self.params.options.units])) # TODO: softcode self.parent.lbl_tank_vol_min.setText( pre_l('Volume min', Options.units_volume[ self.params.options.units])) # TODO: softcode # Pipes self.parent.lbl_pipe_demand.setText( pre_l('Demand', Options.units_flow[self.params.options.units] [0])) # TODO: softcode self.parent.lbl_pipe_diameter.setText( pre_l('Diameter', Options.units_diameter_pipes[ self.params.options.units])) # TODO: softcode self.parent.lbl_pipe_roughness_val.setText( pre_l( 'Value', Options.units_roughness[self.params.options.units][ self.params.options.headloss])) # TODO: softcode self.params.options.headloss_units = self.cbo_headloss.itemData( self.cbo_headloss.currentIndex()) self.parent.update_roughness_params( self.parent.cbo_pipe_roughness.itemData( self.parent.cbo_pipe_roughness.currentIndex())[ self.params.options.headloss]) # self.parent.lbl_pipe_roughness.setText( # pre_l( # 'Roughness', # self.params.options.units_roughness[self.params.options.units][self.params.options.headloss_units])) # Pumps self.parent.lbl_pump_head.setText( pre_l('Head', self.params.options.units_deltaz[self.params.options.units])) self.parent.lbl_pump_power.setText( pre_l('Power', self.params.options.units_power[self.params.options.units])) # Valves valve_type = self.parent.cbo_valve_type.itemData( self.parent.cbo_valve_type.currentIndex()) # Pressure valves if valve_type == Valve.type_psv or valve_type == Valve.type_prv or valve_type == Valve.type_pbv: self.parent.lbl_valve_setting.setText( pre_l( 'Pressure', self.params.options.units_pressure[ self.params.options.units])) # FCV valve: Flow if valve_type == Valve.type_fcv: self.parent.lbl_valve_setting.setText( pre_l('Flow', self.params.options.flow_units)) # Throttle control valve elif valve_type == Valve.type_tcv: self.parent.lbl_valve_setting.setText(pre_l('Loss coeff.', '-')) # self.parent.lbl_valve_diameter.setText(pre_l('Pressure', self.params.options.units_diameter_pipes[self.params.options.units])) # Flow units units = self.cbo_flow_units.itemData( self.cbo_flow_units.currentIndex()) self.parent.lbl_junction_demand.setText(pre_l('Demand', units)) # TODO: softcode self.parent.lbl_pipe_demand.setText(pre_l('Demand', units)) # TODO: softcode self.setVisible(False) def check_params(self): if self.chk_hydraulics.isChecked(): if not os.path.isfile(self.txt_hydraulics_file.text()): QMessageBox.warning( self, Parameters.plug_in_name, u'Hydraulics option slected, but no valid file specified.', QMessageBox.Ok) return False return True
class FindReplace(QWidget): """ Find replace widget bar """ NbReplaced = pyqtSignal(int) def __init__(self, parent=None): """ This class provides an graphical interface to find and replace text @param parent: @type parent: """ QWidget.__init__(self, parent) self.editor = None self.styleEdit = { False: "background-color:rgb(255, 175, 90);", True: "" } self.createButton() self.createWidgets() self.createConnections() def showEnhanced(self, textSelected=''): """ Show enhanced (focus and text selected) """ self.show() if len(textSelected): self.edit.setEditText(textSelected) self.edit.setFocus() self.edit.lineEdit().selectAll() def createButton(self): """ create qt buttons Buttons defined: * Previous * Next * Replace """ self.previousButton = QtHelper.createButton( self, text=self.tr("Find Previous"), triggered=self.findPrevious, icon=QIcon(":/find_previous.png")) self.nextButton = QtHelper.createButton(self, text=self.tr("Find Next"), triggered=self.findNext, icon=QIcon(":/find_next.png")) self.replaceButton = QtHelper.createButton(self, text=self.tr("Replace..."), triggered=self.replaceFind, icon=QIcon(":/replace.png")) def createWidgets(self): """ QtWidgets creation QHBoxLayout -------------------------------------------..... | QLabel: QLineEdit QButton QButton QCheckBox | -------------------------------------------..... ....-------------------------------------- QLabel: QLineEdit QButton QCheckBox | ....-------------------------------------- """ glayout = QGridLayout() self.edit = QLineEditMore(parent=self) self.edit.setEditable(1) self.edit.setMaxCount(10) self.edit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.edit.lineEdit().setPlaceholderText("Search text in your test?") self.edit.setMinimumWidth(200) self.replaceEdit = QComboBox(self) self.replaceEdit.setEditable(1) self.replaceEdit.setMaxCount(10) self.replaceEdit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.replaceEdit.lineEdit().setPlaceholderText( "Replace the text with?") self.replaceEdit.setMinimumWidth(200) self.caseCheck = QCheckBox(self.tr("Case Sensitive")) self.caseCheck.setChecked( QtHelper.str2bool(Settings.instance().readValue( key='Editor/find-case-sensitive'))) self.caseWordCheck = QCheckBox(self.tr("Whole word only")) self.caseWordCheck.setChecked( QtHelper.str2bool( Settings.instance().readValue(key='Editor/find-whole-word'))) self.allCheck = QCheckBox(self.tr("All occurences")) self.allCheck.setChecked( QtHelper.str2bool( Settings.instance().readValue(key='Editor/replace-all'))) self.caseRegexpCheck = QCheckBox(self.tr("Regular expression")) self.caseRegexpCheck.setChecked( QtHelper.str2bool( Settings.instance().readValue(key='Editor/find-regexp'))) self.caseWrapCheck = QCheckBox(self.tr("Wrap at the end")) self.caseWrapCheck.setChecked( QtHelper.str2bool( Settings.instance().readValue(key='Editor/find-wrap'))) glayout.addWidget(self.edit, 0, 1) glayout.addWidget(self.nextButton, 0, 3) glayout.addWidget(self.previousButton, 0, 2) glayout.addWidget(self.caseCheck, 2, 2) glayout.addWidget(self.caseWrapCheck, 2, 3) glayout.addWidget(self.caseWordCheck, 3, 2) glayout.addWidget(self.caseRegexpCheck, 3, 3) glayout.addWidget(self.replaceEdit, 1, 1) glayout.addWidget(self.replaceButton, 1, 2) glayout.addWidget(self.allCheck, 1, 3) self.previousButton.setDisabled(True) self.nextButton.setDisabled(True) self.setLayout(glayout) flags = Qt.WindowFlags() flags |= Qt.Window flags |= Qt.WindowTitleHint flags |= Qt.WindowCloseButtonHint flags |= Qt.MSWindowsFixedSizeDialogHint self.setWindowFlags(flags) self.setWindowIcon(QIcon(":/main.png")) self.setWindowTitle("Find And Replace") def createConnections(self): """ create qt connection """ self.edit.editTextChanged.connect(self.textHasChanged) self.edit.EnterPressed.connect(self.returnPressed) self.caseCheck.stateChanged.connect(self.find) def returnPressed(self): """ Return key pressed Find next in this case """ self.findNext() def setEditor(self, editor): """ Set the target to find the text @param editor: @type editor: """ self.editor = editor def textHasChanged(self, txt): """ Find text has changed """ text = self.edit.currentText() if len(text) > 0: self.previousButton.setEnabled(True) self.nextButton.setEnabled(True) self.find(changed=True, forward=True) else: self.previousButton.setDisabled(True) self.nextButton.setDisabled(True) def updateComboBox(self): """ Update combobox """ comboUpdated = False for i in range(self.edit.count()): if self.edit.itemText(i) == self.edit.currentText(): comboUpdated = True if not comboUpdated: self.edit.addItem(self.edit.currentText()) comboUpdated = False for i in range(self.replaceEdit.count()): if self.replaceEdit.itemText(i) == self.replaceEdit.currentText(): comboUpdated = True if not comboUpdated: self.replaceEdit.addItem(self.replaceEdit.currentText()) def clearText(self): """ Clear all QlineEdit """ self.edit.setStyleSheet("") self.edit.clearEditText() self.replaceEdit.clearEditText() def findPrevious(self): """ Find previous occurence """ # update combobox self.updateComboBox() # find previous self.find(changed=False, forward=False) def findNext(self, line=-1, index=-1): """ Find next occurence """ # update combobox self.updateComboBox() return self.find(changed=False, forward=True, line=line, index=index) def find(self, changed=True, forward=True, line=-1, index=-1): """ Call the find function @param changed: @type changed: boolean @param forward: @type forward: boolean """ text = self.edit.currentText() if len(text) == 0: self.edit.setStyleSheet("") return None else: found = self.editor.findText( text, changed, forward, case=self.caseCheck.isChecked(), words=self.caseWordCheck.isChecked(), regexp=self.caseRegexpCheck.isChecked(), wraps=self.caseWrapCheck.isChecked(), line=line, index=index) self.edit.setStyleSheet(self.styleEdit[found]) return found def replaceFind(self): """ Replace and find """ if (self.editor is None): return replaceText = self.replaceEdit.currentText() searchText = self.edit.currentText() if not self.caseCheck.isChecked(): searchText = searchText.lower() current = -1 nbReplaced = 0 # find the first occurence from the beginning of the doc or not if not self.allCheck.isChecked(): detected = self.findNext() else: detected = self.findNext(line=0, index=0) (line, _) = self.editor.getCursorPosition() while detected: previous = current selectedText = self.editor.selectedText() # normalize the text in lower case if the case sensitive is not activated if not self.caseCheck.isChecked(): selectedText = selectedText.lower() # replace the selection if self.editor.hasSelectedText() and selectedText == searchText: self.editor.replace(replaceText) nbReplaced += 1 # find the next occurence of the word detected = self.findNext() (current, _) = self.editor.getCursorPosition() # all doc readed ? break the loop if previous > current: break if current == line and previous != -1: break # just execute one replace if not self.allCheck.isChecked(): break self.allCheck.setCheckState(Qt.Unchecked) self.NbReplaced.emit(nbReplaced)
class XViewProfileManager(QWidget): currentProfileChanged = qt.Signal(qt.PyObject) optionsMenuRequested = qt.Signal(QPoint) def __init__( self, parent = None ): super(XViewProfileManager, self).__init__(parent) # define custom properties self._profiles = [] self._optionsMenuPolicy = Qt.DefaultContextMenu self._viewWidget = None # define the interface self._profileCombo = QComboBox(self) self._optionsButton = QToolButton(self) self._optionsButton.setAutoRaise(True) self._optionsButton.setToolTip('Advanced Options') self._optionsButton.setIcon(QIcon(resources.find('img/advanced.png'))) layout = QHBoxLayout() layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self._profileCombo) layout.addWidget(self._optionsButton) self.setLayout(layout) # create connections self._profileCombo.currentIndexChanged.connect(self.handleProfileChange) self._optionsButton.clicked.connect(self.showOptionsMenu) def addProfile( self, profile ): """ Adds the inputed profile to the system. :param profile | <XViewProfile> """ if ( profile in self._profiles ): return self._profiles.append(profile) self._profileCombo.blockSignals(True) self._profileCombo.addItem(profile.name()) self._profileCombo.setCurrentIndex(self._profileCombo.count()-1) self._profileCombo.blockSignals(False) def currentProfile( self ): """ Returns the currently selected profile from the system. :return <XViewProfile> """ index = self._profileCombo.currentIndex() if ( 0 <= index and index < len(self._profiles) ): return self._profiles[index] return None def handleProfileChange( self ): """ Emits that the current profile has changed. """ # restore the profile settings prof = self.currentProfile() vwidget = self.viewWidget() if ( vwidget ): prof.restore(vwidget) if ( not self.signalsBlocked() ): self.currentProfileChanged.emit(self.currentProfile()) def optionsMenuPolicy( self ): """ Returns the option menu policy for this widget. :return <Qt.MenuPolicy> """ return self._optionsMenuPolicy def profiles( self ): """ Returns a list of all the profiles for this system. :return [<XViewProfile>, ..] """ return self._profiles def removeProfile( self, profile ): """ Adds the inputed profile to the system. :param profile | <XViewProfile> """ if ( not profile in self._profiles ): return index = self._profiles.index(profile) self._profiles.remove(profile) self._profileCombo.blockSignals(True) self._profileCombo.takeItem(index) self._profileCombo.blockSignals(False) def restoreSettings( self, settings ): """ Restores settings from the application. :param settings | <QSettings> """ settings.beginGroup(self.objectName()) curr_prof = None curr_name = qt.unwrapVariant(settings.value('current')) profiles = [] for prof_name in settings.childGroups(): settings.beginGroup(prof_name) prof_str = qt.unwrapVariant(settings.value('profile')) profile = XViewProfile.fromString(prof_str) profile.setName(prof_name) if ( prof_name == curr_name ): curr_prof = profile profiles.append(profile) settings.endGroup() self.blockSignals(True) self._profileCombo.blockSignals(True) self.setProfiles(profiles) if ( curr_prof ): self.setCurrentProfile(curr_prof) self._profileCombo.blockSignals(False) self.blockSignals(False) settings.endGroup() def saveSettings( self, settings ): """ Saves the settings for this widget to the application :param settings | <QSettings> """ settings.beginGroup(self.objectName()) curr_prof = self.currentProfile() if ( curr_prof ): settings.setValue('current', curr_prof.name()) for profile in self.profiles(): settings.beginGroup(profile.name()) settings.setValue('profile', qt.wrapVariant(profile.toString())) settings.endGroup() settings.endGroup() def setCurrentProfile( self, profile ): """ Sets the current profile to the inputed profile. :param profile | <XViewProfile> """ try: index = self._profiles.index(profile) except ValueError: index = -1 self._profileCombo.setCurrentIndex(index) def setOptionsMenuPolicy( self, menuPolicy ): """ Sets the options menu policy for this item. :param menuPolicy | <Qt.MenuPolicy> """ self._optionsMenuPolicy = menuPolicy def setProfiles( self, profiles ): """ Sets a list of profiles to be the options for the manager. :param profiles | [<XViewProfile>, ..] """ self.blockSignals(True) self._profileCombo.blockSignals(True) self._profiles = profiles[:] self._profileCombo.clear() self._profileCombo.addItems(map(lambda x: x.name(), profiles)) self._profileCombo.blockSignals(False) self.blockSignals(False) def setViewWidget( self, viewWidget ): """ Sets the view widget instance linked with this manager. :param viewWidget | <XViewWidget> """ self._viewWidget = viewWidget def showOptionsMenu( self ): """ Displays the options menu. If the option menu policy is set to CustomContextMenu, then the optionMenuRequested signal will be emitted, otherwise the default context menu will be displayed. """ point = QPoint(0, self._optionsButton.height()) global_point = self._optionsButton.mapToGlobal(point) # prompt the custom context menu if ( self.optionsMenuPolicy() == Qt.CustomContextMenu ): if ( not self.signalsBlocked() ): self.optionsMenuRequested.emit(global_point) return # use the default context menu menu = XViewProfileManagerMenu(self) menu.exec_(global_point) def viewWidget( self ): """ Returns the view widget that is associated with this manager. :return <XViewWidget> """ return self._viewWidget
class EditFilterDialog(QDialog): def __init__(self, client, args, filters, parent=None): QDialog.__init__(self, parent) self.vbox = QVBoxLayout(self) self.client = client self.args = args self.filters = filters self.parent = parent self.setWindowTitle(self.tr('Add a filter')) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setEnabled(True) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.connect(self.buttonBox, SIGNAL("accepted()"), self.accept) self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject) self.filter = QComboBox() self.valuebox = None self.vbox.addWidget(self.filter) for arg in self.filters: if not arg in arg_types or self.args.has_key(arg): continue if not isinstance(arg_types[arg].filter(self.client, arg, '', compatibility=self.parent.compatibility), QWidget): print 'warning, ', arg, 'isn\'t a widget' continue self.filter.addItem(arg_types[arg].label, QVariant(arg)) index = -1 if self.filter.count() > 0: index = 0 self.filter.setCurrentIndex(index) self.editFilterChanged(index) self.connect(self.filter, SIGNAL('currentIndexChanged(int)'), self.editFilterChanged) self.vbox.addWidget(self.buttonBox) def editFilterChanged(self, index): if self.valuebox: self.vbox.removeWidget(self.valuebox) self.valuebox.hide() if index < 0: self.valuebox = QLineEdit() self.value = self.valuebox self.valuebox.setEnabled(False) self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False) else: self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True) arg = unicode(self.filter.itemData(index).toString()) self.value = arg_types[arg].filter(self.client, arg, '', self.parent.compatibility) if arg_types[arg].unit: self.valuebox = QWidget(self) layout = QHBoxLayout(self.valuebox) layout.addWidget(self.value) layout.addWidget(QLabel(arg_types[arg].unit)) else: self.valuebox = self.value self.connect(self, SIGNAL('finished(int)'), self.valuebox.done) self.vbox.insertWidget(1, self.valuebox) def run(self): if self.exec_(): return self.value return None
class UserPanelDlg(QDialog): def __init__(self, parent=None): super(UserPanelDlg, self).__init__(parent) self.setWindowTitle('Address Book - User Panel') self.resize(330, 164) self.parent = parent self.db = self.parent.db chooseLabel = QLabel('Choose User:'******'New user') self.editButton = QPushButton('Edit username') self.deleteButton = QPushButton('Delete user') self.connectButton = QPushButton('Connect') line = QFrame() line.setFrameShape(QFrame.VLine) line.setFrameShadow(QFrame.Sunken) add_l = pyqttools.add_to_layout hlayout1 = add_l(QHBoxLayout(), (chooseLabel, None)) hlayout2 = add_l(QHBoxLayout(), (None, self.connectButton)) vlayout1 = add_l(QVBoxLayout(),(None, hlayout1,self.userComboBox, None)) vlayout2 = add_l(QVBoxLayout(), (newButton, self.editButton, self.deleteButton)) hlayout3 = add_l(QHBoxLayout(), (vlayout1, line, vlayout2)) f_layout = add_l(QVBoxLayout(), (hlayout3, hlayout2)) self.setLayout(f_layout) newButton.clicked.connect(self.add_user) self.editButton.clicked.connect(self.edit_user) self.deleteButton.clicked.connect(self.delete_user) self.connectButton.clicked.connect(self.accept) self.fill_combobox() def fill_combobox(self): users = self.db.get_users() self.userComboBox.clear() self.userComboBox.addItems(users) self.userComboBox.setEnabled(bool(users)) self.enable_buttons() def enable_buttons(self): enable = bool(self.userComboBox.count() > 0) self.editButton.setEnabled(enable) self.deleteButton.setEnabled(enable) self.connectButton.setEnabled(enable) def add_user(self): AddOrEditUserDlg('', False, self).exec_() self.fill_combobox() def edit_user(self): AddOrEditUserDlg(self.userComboBox.currentText(), True, self).exec_() self.fill_combobox() def delete_user(self): user = self.userComboBox.currentText() reply = QMessageBox.question(self, 'Address Book - Delete User', 'Are sou sure that you want to delete {0}?'.format(user), QMessageBox.Yes|QMessageBox.Cancel) if reply == QMessageBox.Yes: self.db.delete_user(user) self.fill_combobox() def accept(self): self.user = self.userComboBox.currentText() QDialog.accept(self) def reject(self): self.parent.close() QDialog.reject(self)
class SchemeSelector(QWidget): currentChanged = pyqtSignal() changed = pyqtSignal() def __init__(self, parent=None): super(SchemeSelector, self).__init__(parent) layout = QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.label = QLabel() self.scheme = QComboBox() self.menuButton = QPushButton(flat=True) menu = QMenu(self.menuButton) self.menuButton.setMenu(menu) layout.addWidget(self.label) layout.addWidget(self.scheme) layout.addWidget(self.menuButton) layout.addStretch(1) # action generator def act(slot, icon=None): a = QAction(self, triggered=slot) self.addAction(a) icon and a.setIcon(icons.get(icon)) return a # add action a = self.addAction_ = act(self.slotAdd, 'list-add') menu.addAction(a) # remove action a = self.removeAction = act(self.slotRemove, 'list-remove') menu.addAction(a) # rename action a = self.renameAction = act(self.slotRename, 'document-edit') menu.addAction(a) menu.addSeparator() # import action a = self.importAction = act(self.slotImport, 'document-open') menu.addAction(a) # export action a = self.exportAction = act(self.slotExport, 'document-save-as') menu.addAction(a) self.scheme.currentIndexChanged.connect(self.slotSchemeChanged) app.translateUI(self) def translateUI(self): self.label.setText(_("Scheme:")) self.menuButton.setText(_("&Menu")) self.addAction_.setText(_("&Add...")) self.removeAction.setText(_("&Remove")) self.renameAction.setText(_("Re&name...")) self.importAction.setText(_("&Import...")) self.exportAction.setText(_("&Export...")) def slotSchemeChanged(self, index): """Called when the Scheme combobox is changed by the user.""" self.disableDefault(self.scheme.itemData(index) == 'default') self.currentChanged.emit() self.changed.emit() def disableDefault(self, val): self.removeAction.setDisabled(val) self.renameAction.setDisabled(val) def schemes(self): """Returns the list with internal names of currently available schemes.""" return [self.scheme.itemData(i) for i in range(self.scheme.count())] def currentScheme(self): """Returns the internal name of the currently selected scheme""" return self.scheme.itemData(self.scheme.currentIndex()) def insertSchemeItem(self, name, scheme): for i in range(1, self.scheme.count()): n = self.scheme.itemText(i) if n.lower() > name.lower(): self.scheme.insertItem(i, name, scheme) break else: self.scheme.addItem(name, scheme) def addScheme(self, name): num, key = 1, 'user1' while key in self.schemes() or key in self._schemesToRemove: num += 1 key = 'user{0}'.format(num) self.insertSchemeItem(name, key) self.scheme.setCurrentIndex(self.scheme.findData(key)) return key def slotAdd(self): name, ok = QInputDialog.getText(self, app.caption(_("Add Scheme")), _("Please enter a name for the new scheme:")) if ok: self.addScheme(name) def slotRemove(self): index = self.scheme.currentIndex() scheme = self.scheme.itemData(index) if scheme == 'default': return # default can not be removed self._schemesToRemove.add(scheme) self.scheme.removeItem(index) def slotRename(self): index = self.scheme.currentIndex() name = self.scheme.itemText(index) scheme = self.scheme.itemData(index) newName, ok = QInputDialog.getText(self, _("Rename"), _("New name:"), text=name) if ok: self.scheme.blockSignals(True) self.scheme.removeItem(index) self.insertSchemeItem(newName, scheme) self.scheme.setCurrentIndex(self.scheme.findData(scheme)) self.scheme.blockSignals(False) self.changed.emit() def slotImport(self): filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"), _("All Files")) caption = app.caption(_("dialog title", "Import color theme")) filename = QFileDialog.getOpenFileName(self, caption, os.environ['HOME'], filetypes) if filename: self.parent().import_(filename) def slotExport(self): name = self.scheme.currentText() filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"), _("All Files")) caption = app.caption(_("dialog title", "Export {name}").format(name=name)) path = os.path.join(os.environ['HOME'], name+'.xml') filename = QFileDialog.getSaveFileName(self, caption, path, filetypes) if filename: if os.path.splitext(filename)[1] != '.xml': filename += '.xml' self.parent().export(name, filename) def loadSettings(self, currentKey, namesGroup): # dont mark schemes for removal anymore self._schemesToRemove = set() s = QSettings() cur = s.value(currentKey, "default", type("")) # load the names for the shortcut schemes s.beginGroup(namesGroup) self.scheme.clear() self.scheme.addItem(_("Default"), "default") lst = [(s.value(key, key, type("")), key) for key in s.childKeys()] for name, key in sorted(lst, key=lambda f: f[0].lower()): self.scheme.addItem(name, key) block = self.scheme.blockSignals(True) # find out index index = self.scheme.findData(cur) self.disableDefault(cur == 'default') self.scheme.setCurrentIndex(index) self.scheme.blockSignals(block) self.currentChanged.emit() def saveSettings(self, currentKey, namesGroup, removePrefix=None): # first save new scheme names s = QSettings() s.beginGroup(namesGroup) for i in range(self.scheme.count()): if self.scheme.itemData(i) != 'default': s.setValue(self.scheme.itemData(i), self.scheme.itemText(i)) for scheme in self._schemesToRemove: s.remove(scheme) s.endGroup() if removePrefix: for scheme in self._schemesToRemove: s.remove("{0}/{1}".format(removePrefix, scheme)) # then save current scheme = self.currentScheme() s.setValue(currentKey, scheme) # clean up self._schemesToRemove = set()
class InterfaceTab(QWidget): def __init__(self, parent): QWidget.__init__(self, parent) vbox = QVBoxLayout(self) self._parent = parent groupBoxExplorer = QGroupBox(self.tr("Explorer Panel:")) groupBoxGui = QGroupBox(self.tr("GUI Customization:")) groupBoxLang = QGroupBox(self.tr("Language:")) #Explorer vboxExplorer = QVBoxLayout(groupBoxExplorer) self._checkProjectExplorer = QCheckBox( self.tr("Show Project Explorer.")) self._checkSymbols = QCheckBox(self.tr("Show Symbols List.")) self._checkWebInspetor = QCheckBox(self.tr("Show Web Inspector.")) self._checkFileErrors = QCheckBox(self.tr("Show File Errors.")) vboxExplorer.addWidget(self._checkProjectExplorer) vboxExplorer.addWidget(self._checkSymbols) vboxExplorer.addWidget(self._checkWebInspetor) vboxExplorer.addWidget(self._checkFileErrors) #GUI self._btnCentralRotate = QPushButton( QIcon(resources.IMAGES['splitCPosition']), '') self._btnCentralRotate.setIconSize(QSize(64, 64)) self._btnCentralRotate.setCheckable(True) self._btnPanelsRotate = QPushButton( QIcon(resources.IMAGES['splitMPosition']), '') self._btnPanelsRotate.setIconSize(QSize(64, 64)) self._btnPanelsRotate.setCheckable(True) self._btnCentralOrientation = QPushButton( QIcon(resources.IMAGES['splitCRotate']), '') self._btnCentralOrientation.setIconSize(QSize(64, 64)) self._btnCentralOrientation.setCheckable(True) gridGuiConfig = QGridLayout(groupBoxGui) gridGuiConfig.addWidget(self._btnCentralRotate, 0, 0) gridGuiConfig.addWidget(self._btnPanelsRotate, 0, 1) gridGuiConfig.addWidget(self._btnCentralOrientation, 0, 2) gridGuiConfig.addWidget(QLabel( self.tr("Rotate Central")), 1, 0, Qt.AlignCenter) gridGuiConfig.addWidget(QLabel( self.tr("Rotate Lateral")), 1, 1, Qt.AlignCenter) gridGuiConfig.addWidget(QLabel( self.tr("Central Orientation")), 1, 2, Qt.AlignCenter) #Language vboxLanguage = QVBoxLayout(groupBoxLang) vboxLanguage.addWidget(QLabel(self.tr("Select Language:"))) self._comboLang = QComboBox() self._comboLang.setEnabled(False) vboxLanguage.addWidget(self._comboLang) vboxLanguage.addWidget(QLabel(self.tr('Requires restart...'))) #Load Languages # self.thread = ThreadLangs() # self.connect(self.thread, SIGNAL("finished()"), self.load_langs) # self.thread.start() self._load_langs() # until the thread is working #Settings self._checkProjectExplorer.setChecked( settings.SHOW_PROJECT_EXPLORER) self._checkSymbols.setChecked(settings.SHOW_SYMBOLS_LIST) self._checkWebInspetor.setChecked(settings.SHOW_WEB_INSPECTOR) self._checkFileErrors.setChecked(settings.SHOW_ERRORS_LIST) #ui layout self._btnCentralRotate.setChecked(bin(settings.UI_LAYOUT)[-1] == '1') self._btnPanelsRotate.setChecked(bin( settings.UI_LAYOUT >> 1)[-1] == '1') self._btnCentralOrientation.setChecked( bin(settings.UI_LAYOUT >> 2)[-1] == '1') vbox.addWidget(groupBoxExplorer) vbox.addWidget(groupBoxGui) vbox.addWidget(groupBoxLang) #Signals self.connect(self._btnCentralRotate, SIGNAL('clicked()'), central_widget.CentralWidget().splitter_central_rotate) self.connect(self._btnPanelsRotate, SIGNAL('clicked()'), central_widget.CentralWidget().splitter_misc_rotate) self.connect(self._btnCentralOrientation, SIGNAL('clicked()'), central_widget.CentralWidget().splitter_central_orientation) def _load_langs(self): # self.disconnect(self.thread, SIGNAL("finished()"), self.load_langs) self._langs = file_manager.get_files_from_folder( resources.LANGS, '.qm') self._langs = ['english'] + \ [file_manager.get_module_name(lang) for lang in self._langs] # if not self.thread.langs.keys() and len(self.langs) > 1: # self.comboLang.addItems(self.langs) # else: # self.comboLang.addItems(['english'] + self.thread.langs.keys()) if(self._comboLang.count() > 1): self._comboLang.setEnabled(True) index = self._comboLang.findText(settings.LANGUAGE) self._comboLang.setCurrentIndex(index) def save(self): lang = self._comboLang.currentText() if lang not in self._langs: #TODO # self.parent().overlay.show() # core.download_lang(self.thread.langs[str(lang)]) pass lang = unicode(lang) self._parent.overlay.hide() qsettings = QSettings() qsettings.beginGroup('preferences') qsettings.beginGroup('interface') qsettings.setValue('showProjectExplorer', self._checkProjectExplorer.isChecked()) settings.SHOW_PROJECT_EXPLORER = self._checkProjectExplorer.isChecked() if settings.SHOW_PROJECT_EXPLORER: explorer_container.ExplorerContainer().add_tab_projects() else: explorer_container.ExplorerContainer().remove_tab_projects() qsettings.setValue('showSymbolsList', self._checkSymbols.isChecked()) settings.SHOW_SYMBOLS_LIST = self._checkSymbols.isChecked() if settings.SHOW_SYMBOLS_LIST: explorer_container.ExplorerContainer().add_tab_symbols() else: explorer_container.ExplorerContainer().remove_tab_symbols() qsettings.setValue('showWebInspector', self._checkWebInspetor.isChecked()) settings.SHOW_WEB_INSPECTOR = self._checkWebInspetor.isChecked() if settings.SHOW_WEB_INSPECTOR: explorer_container.ExplorerContainer().add_tab_inspector() else: explorer_container.ExplorerContainer().remove_tab_inspector() qsettings.setValue('showErrorsList', self._checkFileErrors.isChecked()) settings.SHOW_ERRORS_LIST = self._checkFileErrors.isChecked() if settings.SHOW_ERRORS_LIST: explorer_container.ExplorerContainer().add_tab_errors() else: explorer_container.ExplorerContainer().remove_tab_errors() #ui layout uiLayout = 1 if self._btnCentralRotate.isChecked() else 0 uiLayout += 2 if self._btnPanelsRotate.isChecked() else 0 uiLayout += 4 if self._btnCentralOrientation.isChecked() else 0 qsettings.setValue('uiLayout', uiLayout) qsettings.setValue('language', lang) lang = unicode(lang + '.qm') settings.LANGUAGE = os.path.join(resources.LANGS, lang) qsettings.endGroup() qsettings.endGroup()
class ResolutionSettingWidget(QWidget): def __init__(self, app, parent = None): super(ResolutionSettingWidget,self).__init__(parent) self.setStyleSheet("font-size : 16px;") self.app = app CDLL("libjson-c.so", mode=RTLD_GLOBAL) self.jytcapi = cdll.LoadLibrary('../lib/libjytcapi.so') self.jytcapi.jyinittcapi() self.resolutionLabel = QLabel(self.tr("Resolution setting")) self.resolutionCombox = QComboBox() self.resolutionCombox.setFixedSize(300, 30) self.saveBtn = QPushButton(self.tr("Save")) self.saveBtn.setStyleSheet("background: rgb(7,87,198); color: white; width: 90px; height: 30px;font-size : 16px;") gridLayout = QGridLayout() gridLayout.setSpacing(15) gridLayout.setMargin(10) gridLayout.addWidget(self.resolutionLabel, 0, 0, 1, 1) gridLayout.addWidget(self.resolutionCombox, 0, 1, 1, 1) topLayout = QHBoxLayout() topLayout.addStretch() topLayout.addSpacing(50) topLayout.addLayout(gridLayout) topLayout.addStretch(1) bottomHLayout = QHBoxLayout() bottomHLayout.addStretch() bottomHLayout.addWidget(self.saveBtn) bottomHLayout.addStretch() vLayout = QVBoxLayout() vLayout.addStretch() vLayout.addSpacing(50) vLayout.addLayout(topLayout) vLayout.addStretch(2) vLayout.addSpacing(10) vLayout.addLayout(bottomHLayout) self.setLayout(vLayout) self.updateResolutionCombox() self.timer = QTimer() self.timer.setSingleShot(True) self.connect(self.timer,SIGNAL("timeout()"),self.resetScreenResolution); self.connect(self.saveBtn, SIGNAL("clicked()"),self.slotSave) def updateWindow(self): self.resolutionLabel.setText(self.tr(self.tr("Resolution setting"))) self.saveBtn.setText(self.tr("Save")) def getCmdExecValue(self, cmd): statusOutput = commands.getstatusoutput(cmd) monitorList = statusOutput[1].split("\n") return monitorList def getCmdExecValueT(self, cmd): """得到命令执行的结果""" statusOutput = commands.getstatusoutput(cmd) monitorList = statusOutput[1].split("\n") return monitorList def showCurrentScreenResolution(self, curResolutionValue): """显示当前屏幕的分辨率""" count = self.resolutionCombox.count() for i in range(count): if self.resolutionCombox.itemText(i) == curResolutionValue: self.resolutionCombox.setCurrentIndex(i) return self.resolutionCombox.setCurrentIndex(-1) def getCurrentScreenResolution(self, screenName): currentSolution = "10" reSolution = "auto" solutionMap = {"0":"800x600","1":"1024x768","2":"1280x720","3":"1440x900","4":"1600x1020","5":"1920x1080","6":"1280x1024","7":"1366x768","8":"1600x900","10":"auto"} cmd = "../lib/ccr_jytcapi current_display" value = self.getCmdExecValueT(cmd) for i in range(len(value)): LogRecord.instance().logger.info("#".join(value)) if len(value[i].split(":"))==2 and value[i].split(":")[0]=="res" and value[i].split(":")[1] !="auto": currentSolution = value[i].split(":")[1] break if solutionMap.has_key(currentSolution): reSolution = solutionMap[currentSolution] return reSolution def updateResolutionCombox(self): """更新分辨率下拉框的内容""" #得到屏幕支持的分辨率 self.resolutionCombox.clear() resolutionmMap = self.getScreenResolution() if resolutionmMap: screenName = resolutionmMap.keys()[0] for resolution in resolutionmMap[screenName]: if resolution == "800x600": pass else: self.resolutionCombox.addItem(resolution) self.resolutionCombox.setItemData(0, screenName, Qt.UserRole + 1); #获取当前屏幕的分辨率 self.curResolutionValue = self.getCurrentScreenResolution(screenName) #显示当前屏幕的分辨率 self.showCurrentScreenResolution(self.curResolutionValue) def getScreenResolution(self): """得到屏幕支持的分辨率""" #获得显示器名称,连接状态及行号 Monitors = self.getCmdExecValueT("../lib/ccr_jytcapi display"); #根据组合列表把显示器名称和支持的分辨率放入到一个字典中 resolutionMap = {} resolutionList = [] count = len(Monitors) for i in range(count): if len(Monitors[i].split(":"))<2: continue valueName = Monitors[i].split(":")[0] valueValue = Monitors[i].split(":")[1] if valueName == "value": resolutionList.append(valueValue) resolutionMap["monitorName"] = resolutionList return resolutionMap def slotSave(self): language = StoreInfoParser.instance().getLanguage() m_pTranslator = QTranslator() exePath = "./" if language == "chinese": QmName = "zh_CN.qm" else: QmName = "en_US.qm" if(m_pTranslator.load(QmName, exePath)): QCoreApplication.instance().installTranslator(m_pTranslator) """改变当前的分辨率""" screenName = self.resolutionCombox.itemData(0, Qt.UserRole + 1).toString() if not screenName.isEmpty() and not screenName.isNull(): self.curResolutionValue = self.getCurrentScreenResolution(str(screenName)) if self.curResolutionValue: reScreen = self.resolutionCombox.currentText() if reScreen == "800x600": pass else: pass #弹出提示框,默认为取消 rb = MessageBox(self.tr("making sure set the resolution to current"), self).exec_() if rb == QDialog.Accepted: self.jytcapi.jysetdispconf(str(reScreen)) elif rb == QDialog.Rejected: pass def resetScreenResolution(self): """还原分辨率""" #关闭提示窗口 children = self.children() count = len(children) for i in range(count): if isinstance(children[i], MessageBox): children[i].close() #还原之前的分辨率 if self.jytcapi.jysetdispconf(self.curResolutionValue) != 0: # QMessageBox.information(None,u"错误",u'还原分辨率失败') InfoHintDialog(self.tr("reserve failed")).exec_() return #刷新分辨率下拉框 self.updateResolutionCombox() if QString(self.curResolutionValue).contains("x"): width = self.curResolutionValue.split("x")[0] height = self.curResolutionValue.split("x")[1] self.emit(SIGNAL("resizePosition"), width, height) #刷新屏幕 self.app.slotRefreshVMList() def writeConfigFile(self, curResolution): """记录修改后的配置文件""" StoreInfoParser.instance().setResolutionValue(curResolution)
class Interface(QWidget): """Interface widget class.""" def __init__(self, parent): super(Interface, self).__init__() self._preferences, vbox = parent, QVBoxLayout(self) self.toolbar_settings = settings.TOOLBAR_ITEMS groupBoxExplorer = QGroupBox( translations.TR_PREFERENCES_INTERFACE_EXPLORER_PANEL) #groupBoxToolbar = QGroupBox( #translations.TR_PREFERENCES_INTERFACE_TOOLBAR_CUSTOMIZATION) groupBoxLang = QGroupBox( translations.TR_PREFERENCES_INTERFACE_LANGUAGE) #Explorer vboxExplorer = QVBoxLayout(groupBoxExplorer) self._checkProjectExplorer = QCheckBox( translations.TR_PREFERENCES_SHOW_EXPLORER) self._checkSymbols = QCheckBox( translations.TR_PREFERENCES_SHOW_SYMBOLS) self._checkWebInspetor = QCheckBox( translations.TR_PREFERENCES_SHOW_WEB_INSPECTOR) self._checkFileErrors = QCheckBox( translations.TR_PREFERENCES_SHOW_FILE_ERRORS) self._checkMigrationTips = QCheckBox( translations.TR_PREFERENCES_SHOW_MIGRATION) vboxExplorer.addWidget(self._checkProjectExplorer) vboxExplorer.addWidget(self._checkSymbols) vboxExplorer.addWidget(self._checkWebInspetor) vboxExplorer.addWidget(self._checkFileErrors) vboxExplorer.addWidget(self._checkMigrationTips) #GUI - Toolbar #vbox_toolbar = QVBoxLayout(groupBoxToolbar) #hbox_select_items = QHBoxLayout() #label_toolbar = QLabel(translations.TR_PREFERENCES_TOOLBAR_ITEMS) #label_toolbar.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) #hbox_select_items.addWidget(label_toolbar) #self._comboToolbarItems = QComboBox() #self._load_combo_data(self._comboToolbarItems) #self._btnItemAdd = QPushButton(QIcon(":img/add"), '') #self._btnItemAdd.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) #self._btnItemAdd.setIconSize(QSize(16, 16)) #self._btnItemRemove = QPushButton(QIcon(':img/delete'), '') #self._btnItemRemove.setIconSize(QSize(16, 16)) #self._btnDefaultItems = QPushButton( #translations.TR_PREFERENCES_TOOLBAR_DEFAULT) #self._btnDefaultItems.setSizePolicy(QSizePolicy.Fixed, #QSizePolicy.Fixed) #self._btnItemRemove.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) #hbox_select_items.addWidget(self._comboToolbarItems) #hbox_select_items.addWidget(self._btnItemAdd) #hbox_select_items.addWidget(self._btnItemRemove) #hbox_select_items.addWidget(self._btnDefaultItems) #vbox_toolbar.addLayout(hbox_select_items) #self._toolbar_items = QToolBar() #self._toolbar_items.setObjectName("custom") #self._toolbar_items.setToolButtonStyle(Qt.ToolButtonIconOnly) #self._load_toolbar() #vbox_toolbar.addWidget(self._toolbar_items) #vbox_toolbar.addWidget(QLabel( #translations.TR_PREFERENCES_TOOLBAR_CONFIG_HELP)) #Language vboxLanguage = QVBoxLayout(groupBoxLang) vboxLanguage.addWidget( QLabel(translations.TR_PREFERENCES_SELECT_LANGUAGE)) self._comboLang = QComboBox() self._comboLang.setEnabled(False) vboxLanguage.addWidget(self._comboLang) vboxLanguage.addWidget( QLabel(translations.TR_PREFERENCES_REQUIRES_RESTART)) #Load Languages self._load_langs() #Settings self._checkProjectExplorer.setChecked(settings.SHOW_PROJECT_EXPLORER) self._checkSymbols.setChecked(settings.SHOW_SYMBOLS_LIST) self._checkWebInspetor.setChecked(settings.SHOW_WEB_INSPECTOR) self._checkFileErrors.setChecked(settings.SHOW_ERRORS_LIST) self._checkMigrationTips.setChecked(settings.SHOW_MIGRATION_LIST) vbox.addWidget(groupBoxExplorer) #vbox.addWidget(groupBoxToolbar) vbox.addWidget(groupBoxLang) #Signals #self.connect(self._btnItemAdd, SIGNAL("clicked()"), #self.toolbar_item_added) #self.connect(self._btnItemRemove, SIGNAL("clicked()"), #self.toolbar_item_removed) #self.connect(self._btnDefaultItems, SIGNAL("clicked()"), #self.toolbar_items_default) self.connect(self._preferences, SIGNAL("savePreferences()"), self.save) #def toolbar_item_added(self): #data = self._comboToolbarItems.itemData( #self._comboToolbarItems.currentIndex()) #if data not in self.toolbar_settings or data == 'separator': #selected = self.actionGroup.checkedAction() #if selected is None: #self.toolbar_settings.append(data) #else: #dataAction = selected.data() #self.toolbar_settings.insert( #self.toolbar_settings.index(dataAction) + 1, data) #self._load_toolbar() ## def toolbar_item_removed(self): #data = self._comboToolbarItems.itemData( #self._comboToolbarItems.currentIndex()) #if data in self.toolbar_settings and data != 'separator': #self.toolbar_settings.pop(self.toolbar_settings.index(data)) #self._load_toolbar() #elif data == 'separator': #self.toolbar_settings.reverse() #self.toolbar_settings.pop(self.toolbar_settings.index(data)) #self.toolbar_settings.reverse() #self._load_toolbar() ## def toolbar_items_default(self): #self.toolbar_settings = settings.TOOLBAR_ITEMS_DEFAULT #self._load_toolbar() ## def _load_combo_data(self, combo): #self.toolbar_items = { #'separator': [QIcon(':img/separator'), 'Add Separtor'], #'new-file': [QIcon(resources.IMAGES['new']), self.tr('New File')], #'new-project': [QIcon(resources.IMAGES['newProj']), #self.tr('New Project')], #'save-file': [QIcon(resources.IMAGES['save']), #self.tr('Save File')], #'save-as': [QIcon(resources.IMAGES['saveAs']), self.tr('Save As')], #'save-all': [QIcon(resources.IMAGES['saveAll']), #self.tr('Save All')], #'save-project': [QIcon(resources.IMAGES['saveAll']), #self.tr('Save Project')], #'reload-file': [QIcon(resources.IMAGES['reload-file']), #self.tr('Reload File')], #'open-file': [QIcon(resources.IMAGES['open']), #self.tr('Open File')], #'open-project': [QIcon(resources.IMAGES['openProj']), #self.tr('Open Project')], #'activate-profile': [QIcon(resources.IMAGES['activate-profile']), #self.tr('Activate Profile')], #'deactivate-profile': #[QIcon(resources.IMAGES['deactivate-profile']), #self.tr('Deactivate Profile')], #'print-file': [QIcon(resources.IMAGES['print']), #self.tr('Print File')], #'close-file': #[self.style().standardIcon(QStyle.SP_DialogCloseButton), #self.tr('Close File')], #'close-projects': #[self.style().standardIcon(QStyle.SP_DialogCloseButton), #self.tr('Close Projects')], #'undo': [QIcon(resources.IMAGES['undo']), self.tr('Undo')], #'redo': [QIcon(resources.IMAGES['redo']), self.tr('Redo')], #'cut': [QIcon(resources.IMAGES['cut']), self.tr('Cut')], #'copy': [QIcon(resources.IMAGES['copy']), self.tr('Copy')], #'paste': [QIcon(resources.IMAGES['paste']), self.tr('Paste')], #'find': [QIcon(resources.IMAGES['find']), self.tr('Find')], #'find-replace': [QIcon(resources.IMAGES['findReplace']), #self.tr('Find/Replace')], #'find-files': [QIcon(resources.IMAGES['find']), #self.tr('Find In files')], #'code-locator': [QIcon(resources.IMAGES['locator']), #self.tr('Code Locator')], #'splith': [QIcon(resources.IMAGES['splitH']), #self.tr('Split Horizontally')], #'splitv': [QIcon(resources.IMAGES['splitV']), #self.tr('Split Vertically')], #'follow-mode': [QIcon(resources.IMAGES['follow']), #self.tr('Follow Mode')], #'zoom-in': [QIcon(resources.IMAGES['zoom-in']), self.tr('Zoom In')], #'zoom-out': [QIcon(resources.IMAGES['zoom-out']), #self.tr('Zoom Out')], #'indent-more': [QIcon(resources.IMAGES['indent-more']), #self.tr('Indent More')], #'indent-less': [QIcon(resources.IMAGES['indent-less']), #self.tr('Indent Less')], #'comment': [QIcon(resources.IMAGES['comment-code']), #self.tr('Comment')], #'uncomment': [QIcon(resources.IMAGES['uncomment-code']), #self.tr('Uncomment')], #'go-to-definition': [QIcon(resources.IMAGES['go-to-definition']), #self.tr('Go To Definition')], #'insert-import': [QIcon(resources.IMAGES['insert-import']), #self.tr('Insert Import')], #'run-project': [QIcon(resources.IMAGES['play']), 'Run Project'], #'run-file': [QIcon(resources.IMAGES['file-run']), 'Run File'], #'stop': [QIcon(resources.IMAGES['stop']), 'Stop'], #'preview-web': [QIcon(resources.IMAGES['preview-web']), #self.tr('Preview Web')]} #for item in self.toolbar_items: #combo.addItem(self.toolbar_items[item][0], #self.toolbar_items[item][1], item) #combo.model().sort(0) ## def _load_toolbar(self): #pass ##self._toolbar_items.clear() ##self.actionGroup = QActionGroup(self) ##self.actionGroup.setExclusive(True) ##for item in self.toolbar_settings: ##if item == 'separator': ##self._toolbar_items.addSeparator() ##else: ##action = self._toolbar_items.addAction( ##self.toolbar_items[item][0], self.toolbar_items[item][1]) ##action.setData(item) ##action.setCheckable(True) ##self.actionGroup.addAction(action) def _load_langs(self): langs = file_manager.get_files_from_folder(resources.LANGS, '.qm') self._languages = ['English'] + \ [file_manager.get_module_name(lang) for lang in langs] self._comboLang.addItems(self._languages) if (self._comboLang.count() > 1): self._comboLang.setEnabled(True) if settings.LANGUAGE: index = self._comboLang.findText(settings.LANGUAGE) else: index = 0 self._comboLang.setCurrentIndex(index) def save(self): qsettings = IDE.ninja_settings() settings.TOOLBAR_ITEMS = self.toolbar_settings lang = self._comboLang.currentText() #preferences/interface qsettings.setValue('preferences/interface/showProjectExplorer', self._checkProjectExplorer.isChecked()) settings.SHOW_PROJECT_EXPLORER = self._checkProjectExplorer.isChecked() qsettings.setValue('preferences/interface/showSymbolsList', self._checkSymbols.isChecked()) settings.SHOW_SYMBOLS_LIST = self._checkSymbols.isChecked() qsettings.setValue('preferences/interface/showWebInspector', self._checkWebInspetor.isChecked()) settings.SHOW_WEB_INSPECTOR = self._checkWebInspetor.isChecked() qsettings.setValue('preferences/interface/showErrorsList', self._checkFileErrors.isChecked()) settings.SHOW_ERRORS_LIST = self._checkFileErrors.isChecked() qsettings.setValue('preferences/interface/showMigrationList', self._checkMigrationTips.isChecked()) settings.SHOW_MIGRATION_LIST = self._checkMigrationTips.isChecked() #qsettings.setValue('preferences/interface/toolbar', #settings.TOOLBAR_ITEMS) qsettings.setValue('preferences/interface/language', lang) lang = lang + '.qm' settings.LANGUAGE = os.path.join(resources.LANGS, lang)
class OWFile(OWWidget): settingsList = [ "selected_file", "recent_files", "show_advanced", "create_new_on" ] contextHandlers = {"": FileNameContextHandler()} def __init__(self, parent=None, signalManager=None, title="CSV File Import"): OWWidget.__init__(self, parent, signalManager, title, wantMainArea=False, noReport=True) self.symbol_DC = "" self.symbol_DK = "" #: List of recent opened files. self.recent_files = [] #: Current selected file name self.selected_file = None #: Variable reuse flag self.create_new_on = 2 #: Display advanced var reuse options self.show_advanced = False self.loadSettings() self.recent_files = filter(os.path.exists, self.recent_files) self._loader = None self._invalidated = False self._datareport = None layout = QHBoxLayout() OWGUI.widgetBox(self.controlArea, "File", orientation=layout) icons = standard_icons(self) self.recent_combo = QComboBox(self, objectName="recent_combo", toolTip="Recent files.", activated=self.activate_recent) cb_append_file_list(self.recent_combo, self.recent_files) self.recent_combo.insertSeparator(self.recent_combo.count()) self.recent_combo.addItem(u"Browse documentation data sets…") self.browse_button = QPushButton(u"…", icon=icons.dir_open_icon, toolTip="Browse filesystem", clicked=self.browse) self.reload_button = QPushButton("Reload", icon=icons.reload_icon, toolTip="Reload the selected file", clicked=self.reload, default=True) layout.addWidget(self.recent_combo, 2) layout.addWidget(self.browse_button) layout.addWidget(self.reload_button) ########### # Info text ########### box = OWGUI.widgetBox(self.controlArea, "Info", addSpace=True) self.infoa = OWGUI.widgetLabel(box, "No data loaded.") self.infob = OWGUI.widgetLabel(box, " ") self.warnings = OWGUI.widgetLabel(box, " ") # Set word wrap so long warnings won't expand the widget self.warnings.setWordWrap(True) self.warnings.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.MinimumExpanding) advanced = QGroupBox("Advanced Settings", checkable=True, checked=self.show_advanced) advanced.setLayout(QVBoxLayout()) def set_group_visible(groupbox, state): layout = groupbox.layout() for i in range(layout.count()): item = layout.itemAt(i) widget = item.widget() if widget is not None: widget.setVisible(state) groupbox.setFlat(not state) def toogle_advanced(state): self.show_advanced = state set_group_visible(advanced, state) self.layout().activate() QApplication.instance().processEvents() QTimer.singleShot(0, self.adjustSize) advanced.toggled.connect(toogle_advanced) self.taboptions = QWidget() self.taboptions.setLayout(QVBoxLayout()) box = QGroupBox("Missing Value Symbols", flat=True) form = QFormLayout(fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow) form.addRow( "Don't care:", OWGUI.lineEdit(None, self, "symbol_DC", tooltip="Default values: '~' or '*'")) form.addRow( "Don't know:", OWGUI.lineEdit(None, self, "symbol_DK", tooltip="Default values: empty fields (space), " "'?' or 'NA'")) box.setLayout(form) advanced.layout().addWidget(box) rb = OWGUI.radioButtonsInBox( advanced, self, "create_new_on", box="New Attributes", callback=self._invalidate, label=u"Create a new attribute when existing attribute(s) …", btnLabels=[ u"Have mismatching order of values", u"Have no common values with the new (recommended)", u"Miss some values of the new attribute", u"… Always create a new attribute" ]) rb.setFlat(True) self.controlArea.layout().addWidget(advanced) button_box = QDialogButtonBox(orientation=Qt.Horizontal) self.import_options_button = QPushButton(u"Import Options…", enabled=False) self.import_options_button.pressed.connect( self._activate_import_dialog) button_box.addButton(self.import_options_button, QDialogButtonBox.ActionRole) button_box.addButton( QPushButton("&Report", pressed=self.reportAndFinish), QDialogButtonBox.ActionRole) self.controlArea.layout().addWidget(button_box) OWGUI.rubber(self.controlArea) set_group_visible(advanced, self.show_advanced) if self.recent_files and self.recent_files[0] == self.selected_file: QTimer.singleShot(0, lambda: self.activate_recent(0)) else: self.selected_file = None self.recent_combo.setCurrentIndex(-1) @Slot(int) def activate_recent(self, index): """Activate an item from the recent list.""" if 0 <= index < len(self.recent_files): recent = self.recent_files[index] self.set_selected_file(recent) elif index == len(self.recent_files) + 1: status = self.browse(Orange.utils.environ.dataset_install_dir) if status == QDialog.Rejected: self.recent_combo.setCurrentIndex( min(0, len(self.recent_files) - 1)) else: self.recent_combo.setCurrentIndex(-1) @Slot() def browse(self, startdir=None): """ Open a file dialog and select a user specified file. """ if startdir is None: if self.selected_file: startdir = os.path.dirname(self.selected_file) else: startdir = unicode( QDesktopServices.storageLocation( QDesktopServices.DocumentsLocation)) def format_spec(format): ext_pattern = ", ".join(map("*{}".format, format.extensions)) return "{} ({})".format(format.name, ext_pattern) formats = [format_spec(format) for format in FILEFORMATS] filters = ";;".join(formats + ["All files (*.*)"]) path, selected_filter = QFileDialog.getOpenFileNameAndFilter( self, "Open Data File", startdir, filters) if path: path = unicode(path) if selected_filter in formats: filter_idx = formats.index(str(selected_filter)) fformat = FILEFORMATS[filter_idx] loader = DEFAULT_ACTIONS[filter_idx] if fformat.extensions in ([".csv"], [".tsv"]): loader = loader._replace( params=loader_for_path(path).params) else: loader = None self.set_selected_file(path, loader=loader) return QDialog.Accepted else: return QDialog.Rejected @Slot() def reload(self): """Reload the current selected file.""" if self.selected_file: self.send_data() def _activate_import_dialog(self): assert self.selected_file is not None dlg = CSVImportDialog( self, windowTitle="Import Options", ) dlg.setAttribute(Qt.WA_DeleteOnClose) dlg.setWindowFlags(Qt.Sheet) loader = self._loader dlg.set_options(loader.params) dlg.set_path(self.selected_file) def update(): self._loader = loader._replace(params=dlg.options()) self._invalidate() dlg.accepted.connect(update) dlg.open() def set_selected_file(self, filename, loader=None): """Set the current filename path to be loaded.""" self.closeContext("") self.selected_file = filename self._loader = None self._add_recent(filename) self.warning(1) self.openContext("", filename) if loader is not None and self._loader is not None and \ self._loader.format == loader.format: loader = self._loader if loader is None: loader = self._loader if loader is None: loader = loader_for_path(filename) self.set_loader(loader) def _add_recent(self, filename): """Add filename to the list of recent files.""" index_to_remove = None if filename in self.recent_files: index_to_remove = self.recent_files.index(filename) elif len(self.recent_files) >= 20: # keep maximum of 20 files in the list. index_to_remove = len(self.recent_files) - 1 cb_insert_file_list(self.recent_combo, 0, [filename]) self.recent_files.insert(0, filename) if index_to_remove is not None: self.recent_combo.removeItem(index_to_remove + 1) self.recent_files.pop(index_to_remove + 1) self.recent_combo.setCurrentIndex(0) def set_loader(self, loader): if loader is None: loader = DEFAULT_ACTIONS[0] self._loader = loader self.import_options_button.setEnabled(isinstance(loader.params, CSV)) self._invalidate() def _invalidate(self): if not self._invalidated: self._invalidated = True QApplication.postEvent(self, QEvent(QEvent.User)) def customEvent(self, event): if self._invalidated: self._invalidated = False self.send_data() def send_data(self): self.error(0) loader = self._loader if "DK" in loader.params._fields and self.symbol_DK: loader = loader._replace(params=loader.params._replace( DK=str(self.symbol_DK), DC=str(self.symbol_DC))) try: data = load_table(self.selected_file, loader, create_new_on=3 - self.create_new_on) except Exception as err: self.error(str(err)) self.infoa.setText('Data was not loaded due to an error.') self.infob.setText('Error:') self.warnings.setText(str(err)) data = None else: self._update_status_messages(data) if data is not None: add_origin(data, self.selected_file) basename = os.path.basename(self.selected_file) data.name, _ = os.path.splitext(basename) self._datareport = self.prepareDataReport(data) else: self._datareport = None self.send("Data", data) def _update_status_messages(self, data): if data is None: self.infoa.setText("No data loaded.") self.infob.setText("") self.warnings.setText("") return def pluralize(seq): return "s" if len(seq) != 1 else "" summary = ("{n_instances} data instance{plural_1}, " "{n_features} feature{plural_2}, " "{n_meta} meta{plural_3}").format( n_instances=len(data), plural_1=pluralize(data), n_features=len(data.domain.attributes), plural_2=pluralize(data.domain.attributes), n_meta=len(data.domain.getmetas()), plural_3=pluralize(data.domain.getmetas())) self.infoa.setText(summary) cl = data.domain.class_var if cl is not None: if isinstance(cl, Orange.feature.Continuous): self.infob.setText('Regression; Numerical class.') elif isinstance(cl, Orange.feature.Discrete): self.infob.setText( 'Classification; Discrete class with %d value%s.' % (len(cl.values), 's' if len(cl.values) > 1 else '')) else: self.infob.setText("Class is neither discrete nor continuous.") elif data.domain.class_vars: self.infob.setText("Multiple class variables") else: self.infob.setText("Data has no dependent variable.") self.warnings.setText( feature_load_status_report(data, self.create_new_on)) def sendReport(self): if self._datareport: formatname = self._loader.format self.reportSettings("File", [("File name", self.selected_file), ("Format", formatname)]) self.reportData(self._datareport) def settingsFromWidgetCallback(self, handler, context): context.filename = self.selected_file or "" context.loader = self._loader context.symbolDC, context.symbolDK = self.symbol_DC, self.symbol_DK def settingsToWidgetCallback(self, handler, context): self.symbol_DC, self.symbol_DK = context.symbolDC, context.symbolDK self._loader = getattr(context, "loader", None) def setSettings(self, settings): if settings.get(_SETTINGS_VERSION_KEY, None) is None: # import old File widget's settings mapping = [("recentFiles", "recent_files"), ("createNewOn", "create_new_on"), ("showAdvanced", "show_advanced")] if all(old in settings for old, _ in mapping) and \ not any(new in settings for _, new in mapping): settings = settings.copy() for old, new in mapping: settings[new] = settings[old] del settings[old] # settings[_SETTINGS_VERSION_KEY] = self.settingsDataVersion if len(settings["recent_files"]): settings["selected_file"] = settings["recent_files"][0] super(OWFile, self).setSettings(settings)
class SupportingDocumentsWidget(QWidget): """ Widget for managing an entity's supporting documents. It enables listing of documents grouped by tabs depending on type. """ def __init__(self, entity_supporting_document, supporting_doc_model_cls, parent=None): """ Class constructor. :param entity_supporting_document: Object containing information pertaining to document types, parent entity etc. :type entity_supporting_document: EntitySupportingDocument :param supporting_doc_model_cls: Class representing the data model corresponding to the entity supporting document object. :type supporting_doc_model_cls: object :param parent: Parent container widget. :type parent: QWidget """ QWidget.__init__(self, parent) self._init_gui() self._entity_supporting_doc = entity_supporting_document #Container for document type widgets based on lookup id self._doc_type_widgets = {} #Init document manager self.source_document_manager = SourceDocumentManager( self._entity_supporting_doc, supporting_doc_model_cls, self ) self._load_document_types() #Connect signals self._btn_add_document.clicked.connect( self._on_add_supporting_document ) self._cbo_doc_type.currentIndexChanged.connect( self.on_doc_type_changed ) self._doc_tab_container.currentChanged.connect( self.on_tab_doc_type_changed ) def _init_gui(self): self._gl = QGridLayout(self) self._label = QLabel(self) self._label.setText(self.tr('Select document type')) self._gl.addWidget(self._label, 0, 0, 1, 1) self._cbo_doc_type = QComboBox(self) self._gl.addWidget(self._cbo_doc_type, 0, 1, 1, 1) self._btn_add_document = QPushButton(self) doc_ico = QIcon(':/plugins/stdm/images/icons/document.png') self._btn_add_document.setIcon(doc_ico) self._btn_add_document.setText(self.tr('Add document...')) self._btn_add_document.setMaximumWidth(200) self._gl.addWidget(self._btn_add_document, 0, 2, 1, 1) self._doc_tab_container = QTabWidget(self) self._gl.addWidget(self._doc_tab_container, 1, 0, 1, 3) self.setMinimumHeight(140) def on_doc_type_changed(self, idx): """ Slot raised when the document types changes. The corresponding widget in the tab container is also selected. :param idx: Item index in the combobox. :type idx: int """ if idx == -1: return self._doc_tab_container.setCurrentIndex(idx) def on_tab_doc_type_changed(self, idx): """ Slot raised when the document types changes. The corresponding widget in the tab container is also selected. :param idx: Item index in the tab widget. :type idx: int """ if idx == -1: return self._cbo_doc_type.setCurrentIndex(idx) def current_document_type(self): """ :return: Returns the currently selected document type in the combobox. :rtype: str """ return self._cbo_doc_type.currentText() def current_document_type_id(self): """ :return: Returns the primary key/id of the currently selected document type in the combobox, else -1 if there is not current item in the combobox :rtype: int """ if not self.current_document_type(): return -1 curr_idx = self._cbo_doc_type.currentIndex() return self._cbo_doc_type.itemData(curr_idx) def count(self): """ :return: Returns the number of document types supported by this widget. :rtype: int """ return self._cbo_doc_type.count() def document_type_containers(self): """ :return: Returns a list of document container widgets for all registered document types. :rtype: list """ return self.source_document_manager.containers.values() def document_type_widget(self, name): """ Searches for the document type widget that corresponds to the given name. :param name: Name of the document type. :type name: str :return: Returns the document widget corresponding to the given type name. :rtype: QWidget """ idx = self._cbo_doc_type.findText(name) if idx == -1: return None rec_id = self._cbo_doc_type.itemData(idx) return self._doc_type_widgets.get(rec_id, None) def _load_document_types(self): #Load document types in the combobox and tab widget vl_cls = entity_model( self._entity_supporting_doc.document_type_entity, entity_only=True ) vl_obj = vl_cls() res = vl_obj.queryObject().all() for r in res: #Add to combo self._cbo_doc_type.addItem(r.value, r.id) #Add to tab widget doc_type_widget = _DocumentTypeContainer(self) self._doc_tab_container.addTab(doc_type_widget, r.value) self._doc_type_widgets[r.id] = doc_type_widget #Register container self.source_document_manager.registerContainer( doc_type_widget.container, r.id ) def _on_add_supporting_document(self): #Slot raised when the user select to add a supporting document if self.count == 0: return select = self.tr('Select') supporting_docs_str = 'Supporting Documents' title = u'{0} {1} {2}'.format( select, self.current_document_type(), supporting_docs_str ) filter_str = u'{0} (*.jpg *.jpeg *.png *.bmp *.tiff *.svg)'.format( supporting_docs_str ) #Get last path for supporting documents last_path = last_document_path() if last_path is None: last_path = '/home' else: dir = QDir(last_path) if not dir.exists(): last_path = '/home' source_docs = QFileDialog.getOpenFileNames( self, title, last_path, filter_str ) doc_type_id = self._cbo_doc_type.itemData(self._cbo_doc_type.currentIndex()) parent_entity = self._entity_supporting_doc.parent_entity for doc in source_docs: self.source_document_manager.insertDocumentFromFile( doc, doc_type_id, parent_entity ) #Set last path if len(source_docs) > 0: doc = source_docs[0] fi = QFileInfo(doc) dir_path = fi.absolutePath() set_last_document_path(dir_path)
class ThemeConfigurationWidget(QWidget): """Themes are stored in directory 'themes' in configuration directory. Each theme file has .mixth extension and represents single theme. """ def __init__(self, parent): QWidget.__init__(self, parent) self.cmbThemes = QComboBox(self) self.cmbThemes.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self.cmbThemes.currentIndexChanged[int].connect(self._changeCurrentTheme) self.btnCopyTheme = QPushButton(self) self.btnCopyTheme.setText(utils.tr('Copy theme...')) self.btnCopyTheme.clicked.connect(self._copyTheme) self.componentsView = QTableView(self) self.themeModel = ThemeModel() self.componentsView.setModel(self.themeModel) self.componentsView.setSelectionBehavior(QTableView.SelectRows) self.componentsView.setItemDelegateForColumn(1, ComponentDelegate()) self.componentsView.setEditTriggers(QTableView.DoubleClicked) self.setLayout(QVBoxLayout()) h_layout = QHBoxLayout() h_layout.addWidget(self.cmbThemes) h_layout.addWidget(self.btnCopyTheme) self.layout().addLayout(h_layout) self.layout().addWidget(self.componentsView) def resizeEvent(self, event): view_size = self.componentsView.size() hh = self.componentsView.horizontalHeader() hh.resizeSection(0, int((view_size.width() - self.componentsView.verticalHeader().width()) * 0.6)) hh.setStretchLastSection(True) def loadThemes(self, theme_to_select=None): if theme_to_select is None: theme_to_select = globalSettings[appsettings.HexWidget_Theme] self.cmbThemes.clear() self.cmbThemes.addItem(utils.tr('Default (unmodifiable)'), '') if not theme_to_select: self.cmbThemes.setCurrentIndex(0) for theme_name in hexwidget.Theme.availableThemes(): self.cmbThemes.addItem(theme_name.capitalize(), theme_name) if theme_name == theme_to_select: self.cmbThemes.setCurrentIndex(self.cmbThemes.count() - 1) def saveCurrentTheme(self): if self.themeModel.theme is not None and self.themeName: theme_name = self.themeName self.themeModel.theme.save(theme_name) self.loadThemes(theme_name) @property def themeName(self): return self.cmbThemes.itemData(self.cmbThemes.currentIndex()) def _copyTheme(self): while True: theme_name, ok = QInputDialog.getText(self, utils.tr('Copy theme'), utils.tr('Name for copy of theme:')) if not ok: break if (not theme_name or hexwidget.Theme.themeFromName(theme_name) is not None or not utils.isValidFilename(theme_name)): QMessageBox.information(self, utils.tr('Wrong name for theme'), utils.tr('Name for theme is invalid')) else: break if ok: self.themeModel.theme.save(theme_name) self.loadThemes(theme_name) def _changeCurrentTheme(self, index): if self.themeName and self.themeModel.modified: if QMessageBox.question(self, utils.tr('Save theme'), utils.tr('Do you want to save "{0}"?').format(self.themeName), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) == QMessageBox.Yes: self.themeModel.theme.save() theme_name = self.cmbThemes.itemData(index) if index >= 0 and theme_name is not None: theme = hexwidget.Theme.themeFromName(theme_name) or hexwidget.Theme() else: theme = None self.themeModel.theme = theme
class WSystem(QWidget, Logger.ClassLogger): """ System 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(150) 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(":/system-small.png"), tip='System options') def openOptions(self): """ Open options dialog """ if self.optionsDialog.exec_() == QDialog.Accepted: pass def createWidgets(self): """ Create qt widgets """ self.optionsDialog = OptionsDialog(self) self.validatorUpper = ValidatorUpper(self) self.validatorAll = ValidatorAll(self) self.validatorInt = QIntValidator(self) self.actionsComboBox = QComboBox(self) self.actionsComboBox.setMinimumHeight(40) for i in xrange(len(GuiSteps.ACTION_SYSTEM_DESCR)): if not len(GuiSteps.ACTION_SYSTEM_DESCR[i]): self.actionsComboBox.insertSeparator(i + 1) else: el = GuiSteps.ACTION_SYSTEM_DESCR[i].keys() self.actionsComboBox.addItem(list(el)[0]) self.labelActionDescr = QLabel(self) self.labelActionDescr.hide() self.descriptionLine = QLineEdit(self) self.descriptionLine.setPlaceholderText("Step purpose description") self.descriptionLine.hide() actionsLayout = QHBoxLayout() actionsLayout.addWidget(self.actionsComboBox) actionLayout1 = QGridLayout() actionLayout1.addLayout(actionsLayout, 0, 1) self.createWidgetSession() self.createWidgetText() self.createWidgetShortcut() self.createWidgetScreen() actionLayout2 = QGridLayout() actionLayout2.addWidget(self.sessionGroup, 1, 0) actionLayout2.addWidget(self.textGroup, 1, 0) actionLayout2.addWidget(self.shortcutGroup, 1, 0) actionLayout2.addWidget(self.screenGroup, 1, 0) font = QFont() font.setBold(True) 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.addLayout(actionLayout1) 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 createWidgetScreen(self): """ Create screen widget """ self.screenGroup = QGroupBox(self.tr("")) # text self.checkComboBox = QComboBox(self) self.checkComboBox.addItems([ GuiSteps.OP_ANY, GuiSteps.OP_CONTAINS, GuiSteps.OP_NOTCONTAINS, GuiSteps.OP_REGEXP, GuiSteps.OP_NOTREGEXP, GuiSteps.OP_STARTSWITH, GuiSteps.OP_NOTSTARTSWITH, GuiSteps.OP_ENDSWITH, GuiSteps.OP_NOTENDSWITH ]) self.screenLine = QLineEdit(self) self.screenLine.setMinimumWidth(300) self.screenLine.setEnabled(False) self.screenLine.hide() self.screenArea = QTextEdit(self) self.screenArea.setMinimumWidth(300) self.screenArea.setEnabled(False) self.screenCombo = QComboBox(self) self.screenCombo.addItems(LIST_TYPES) self.screenCombo.setEnabled(False) self.screenSaveCombo = QComboBox(self) self.screenSaveCombo.addItems(["VARIABLE", "CACHE"]) self.screenSaveLine = QLineEdit(self) self.screenSaveLine.setMinimumWidth(300) self.screenSaveLine.setEnabled(False) mainTextlayout = QGridLayout() mainTextlayout.addWidget(QLabel(self.tr("Checking if the screen: ")), 0, 0) mainTextlayout.addWidget(self.checkComboBox, 0, 1) mainTextlayout.addWidget(QLabel(self.tr("The value:")), 1, 0) mainTextlayout.addWidget(self.screenCombo, 1, 1) mainTextlayout.addWidget(self.screenLine, 2, 1) mainTextlayout.addWidget(self.screenArea, 2, 1) mainTextlayout.addWidget(QLabel(self.tr("And save the screen in:")), 0, 2) mainTextlayout.addWidget(self.screenSaveCombo, 1, 2) mainTextlayout.addWidget(self.screenSaveLine, 2, 2) self.screenGroup.setLayout(mainTextlayout) self.screenGroup.hide() def createWidgetText(self): """ Create text widget """ self.textGroup = QGroupBox(self.tr("")) # text self.textLine = QLineEdit(self) self.textLine.setMinimumWidth(300) self.textCombo = QComboBox(self) self.textCombo.addItems(LIST_TYPES) mainTextlayout = QGridLayout() mainTextlayout.addWidget(QLabel(self.tr("Send the value:")), 0, 0) mainTextlayout.addWidget(self.textCombo, 0, 1) mainTextlayout.addWidget(self.textLine, 0, 2) self.textGroup.setLayout(mainTextlayout) self.textGroup.hide() def createWidgetShortcut(self): """ Create shortcut widget """ self.shortcutGroup = QGroupBox(self.tr("")) # text self.shortcutComboBox = QComboBox() self.shortcutComboBox.addItems([KEY_CTRLC, KEY_ENTER]) self.shortcutComboBox.setMinimumWidth(300) mainTextlayout = QGridLayout() mainTextlayout.addWidget(QLabel(self.tr("Shortcut:")), 0, 0) mainTextlayout.addWidget(self.shortcutComboBox, 0, 1) self.shortcutGroup.setLayout(mainTextlayout) self.shortcutGroup.hide() def createWidgetSession(self): """ Create session widget """ self.sessionGroup = QGroupBox(self.tr("")) # login self.loginLine = QLineEdit(self) self.loginLine.setMinimumWidth(300) self.loginCombo = QComboBox(self) self.loginCombo.addItems(LIST_TYPES) # password self.pwdLine = QLineEdit(self) self.pwdLine.setMinimumWidth(300) self.pwdCombo = QComboBox(self) self.pwdCombo.addItems(LIST_TYPES) # ip self.ipLine = QLineEdit(self) self.ipLine.setMinimumWidth(300) self.ipCombo = QComboBox(self) self.ipCombo.addItems(LIST_TYPES) # port self.portLine = QLineEdit(self) self.portLine.setMinimumWidth(300) self.portLine.setText("22") self.portLine.setValidator(self.validatorInt) self.portCombo = QComboBox(self) self.portCombo.addItems(LIST_TYPES) # agent support self.useAgent = QCheckBox("Use with agent mode") mainTextlayout = QGridLayout() mainTextlayout.addWidget(QLabel(self.tr("Host:")), 0, 0) mainTextlayout.addWidget(self.ipCombo, 0, 1) mainTextlayout.addWidget(self.ipLine, 0, 2) mainTextlayout.addWidget(QLabel(self.tr("Port (optional):")), 1, 0) mainTextlayout.addWidget(self.portCombo, 1, 1) mainTextlayout.addWidget(self.portLine, 1, 2) mainTextlayout.addWidget(QLabel(self.tr("Login:"******"Password:"******""" Create qt connections """ self.actionsComboBox.currentIndexChanged.connect(self.onActionChanged) self.addAction.clicked.connect(self.addStep) self.ipCombo.currentIndexChanged.connect(self.onIpTypeChanged) self.portCombo.currentIndexChanged.connect(self.onPortTypeChanged) self.loginCombo.currentIndexChanged.connect(self.onLoginTypeChanged) self.pwdCombo.currentIndexChanged.connect(self.onPwdTypeChanged) self.textCombo.currentIndexChanged.connect(self.onTextTypeChanged) self.screenCombo.currentIndexChanged.connect(self.onScreenTypeChanged) self.checkComboBox.currentIndexChanged.connect( self.onScreenOperatorChanged) self.screenSaveCombo.currentIndexChanged.connect( self.onScreenSaveChanged) def pluginDataAccessor(self): """ Return data to plugin """ return {"data": ""} def onPluginImport(self, dataJson): """ Received data from plugins """ if "steps" not in dataJson: QMessageBox.warning(self, "Assistant Automation", "bad import") return if not isinstance(dataJson['steps'], list): QMessageBox.warning(self, "Assistant Automation", "bad import") return if not ('ip' in dataJson and 'login' in dataJson and 'password' in dataJson): QMessageBox.warning(self, "Assistant Automation", "bad import") return # emit open session parameters = { 'dest-ip': dataJson['ip'], 'dest-port': 22, 'login': dataJson['login'], 'password': dataJson['password'], 'from-cache-ip': False, 'from-alias-ip': False, 'from-cache-port': False, 'from-alias-port': False, 'from-cache-login': False, 'from-alias-login': False, 'from-cache-pwd': False, 'from-alias-pwd': False, 'agent-support': False } self.AddStep.emit(GuiSteps.SYSTEM_SESSION, EMPTY_VALUE, EMPTY_VALUE, parameters) for stp in dataJson['steps']: if isinstance(stp, dict): # new in v16 fromCache = False fromAlias = False if "type-value" in stp: if stp["type-value"].lower() == "cache": fromCache = True if stp["type-value"].lower() == "alias": fromAlias = True # end of new if stp["action-name"] == "SEND": parameters = { 'text': stp["action-value"], 'from-cache': fromCache, 'from-alias': fromAlias } self.AddStep.emit(GuiSteps.SYSTEM_TEXT, EMPTY_VALUE, EMPTY_VALUE, parameters) elif stp["action-name"] == "EXPECT": op = "Contains" if stp["action-type"] == "REGEX": op = "RegEx" parameters = { 'value': stp["action-value"], 'from-cache': fromCache, 'from-alias': fromAlias, 'operator': op, 'to-cache': False, 'cache-key': '' } self.AddStep.emit(GuiSteps.SYSTEM_CHECK_SCREEN, EMPTY_VALUE, EMPTY_VALUE, parameters) else: QMessageBox.warning( self, "Assistant Automation", "action not yet supported: %s" % stp["action-name"]) # close self.AddStep.emit(GuiSteps.SYSTEM_CLOSE, EMPTY_VALUE, EMPTY_VALUE, {}) def onScreenOperatorChanged(self): """ On screen operator changed """ if self.checkComboBox.currentText() == GuiSteps.OP_ANY: self.screenLine.setEnabled(False) self.screenArea.setEnabled(False) self.screenCombo.setEnabled(False) else: self.screenLine.setEnabled(True) self.screenArea.setEnabled(True) self.screenCombo.setEnabled(True) def onScreenSaveChanged(self): """ On screen save changed """ if self.screenSaveCombo.currentText() == "VARIABLE": self.screenSaveLine.setEnabled(False) else: self.screenSaveLine.setEnabled(True) def onScreenTypeChanged(self): """ On screen type changed """ if self.screenCombo.currentText() in ["TEXT"]: self.screenArea.show() self.screenLine.hide() else: self.screenLine.show() self.screenArea.hide() if self.screenCombo.currentText() in ["CACHE"]: self.screenLine.setValidator(self.validatorAll) if self.screenCombo.currentText() == "ALIAS": self.screenLine.setText(self.screenLine.text().upper()) self.screenLine.setValidator(self.validatorUpper) def onTextTypeChanged(self): """ On text type changed """ if self.textCombo.currentText() in ["TEXT", "CACHE"]: self.textLine.setValidator(self.validatorAll) if self.textCombo.currentText() == "ALIAS": self.textLine.setText(self.textLine.text().upper()) self.textLine.setValidator(self.validatorUpper) def onLoginTypeChanged(self): """ On login type changed """ if self.loginCombo.currentText() in ["TEXT", "CACHE"]: self.loginLine.setValidator(self.validatorAll) if self.loginCombo.currentText() == "ALIAS": self.loginLine.setText(self.loginLine.text().upper()) self.loginLine.setValidator(self.validatorUpper) def onPwdTypeChanged(self): """ On password type changed """ if self.pwdCombo.currentText() in ["TEXT", "CACHE"]: self.pwdLine.setValidator(self.validatorAll) if self.pwdCombo.currentText() == "ALIAS": self.pwdLine.setText(self.pwdLine.text().upper()) self.pwdLine.setValidator(self.validatorUpper) def onIpTypeChanged(self): """ On ip type changed """ if self.ipCombo.currentText() in ["TEXT", "CACHE"]: self.ipLine.setValidator(self.validatorAll) if self.ipCombo.currentText() == "ALIAS": self.ipLine.setText(self.ipLine.text().upper()) self.ipLine.setValidator(self.validatorUpper) def onPortTypeChanged(self): """ On port type changed """ if self.portCombo.currentText() in ["TEXT"]: self.portLine.setText("22") self.portLine.setValidator(self.validatorInt) if self.portCombo.currentText() in ["CACHE"]: self.portLine.setValidator(self.validatorAll) if self.portCombo.currentText() == "ALIAS": self.portLine.setText(self.portLine.text().upper()) self.portLine.setValidator(self.validatorUpper) def onActionChanged(self): """ On action changed """ descr = 'No description available!' i = 0 for el in GuiSteps.ACTION_SYSTEM_DESCR: if isinstance(el, dict): if self.actionsComboBox.currentText() in el: descr = GuiSteps.ACTION_SYSTEM_DESCR[i][ self.actionsComboBox.currentText()] break i += 1 self.labelActionDescr.setText("%s\n" % descr) if self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_SESSION]: self.sessionGroup.show() self.textGroup.hide() self.shortcutGroup.hide() self.screenGroup.hide() self.arrowLabel.show() self.arrowLabel2.show() elif self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_CLOSE]: self.sessionGroup.hide() self.textGroup.hide() self.shortcutGroup.hide() self.screenGroup.hide() self.arrowLabel.hide() self.arrowLabel2.show() elif self.actionsComboBox.currentText() in [ GuiSteps.SYSTEM_CLEAR_SCREEN ]: self.sessionGroup.hide() self.textGroup.hide() self.shortcutGroup.hide() self.screenGroup.hide() self.arrowLabel.hide() self.arrowLabel2.show() elif self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_TEXT]: self.sessionGroup.hide() self.textGroup.show() self.shortcutGroup.hide() self.screenGroup.hide() self.arrowLabel.show() self.arrowLabel2.show() elif self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_SHORTCUT]: self.sessionGroup.hide() self.textGroup.hide() self.shortcutGroup.show() self.screenGroup.hide() self.arrowLabel.show() self.arrowLabel2.show() elif self.actionsComboBox.currentText() in [ GuiSteps.SYSTEM_CHECK_SCREEN ]: self.sessionGroup.hide() self.textGroup.hide() self.shortcutGroup.hide() self.screenGroup.show() self.arrowLabel.show() self.arrowLabel2.show() else: self.sessionGroup.hide() self.textGroup.hide() self.shortcutGroup.hide() self.screenGroup.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.SYSTEM_SESSION]: fromCacheIp = False if self.ipCombo.currentText() == "CACHE": fromCacheIp = True fromAliasIp = False if self.ipCombo.currentText() == "ALIAS": fromAliasIp = True fromCachePort = False if self.portCombo.currentText() == "CACHE": fromCachePort = True fromAliasPort = False if self.portCombo.currentText() == "ALIAS": fromAliasPort = True fromCacheLogin = False if self.loginCombo.currentText() == "CACHE": fromCacheLogin = True fromAliasLogin = False if self.loginCombo.currentText() == "ALIAS": fromAliasLogin = True fromCachePwd = False if self.pwdCombo.currentText() == "CACHE": fromCachePwd = True fromAliasPwd = False if self.pwdCombo.currentText() == "ALIAS": fromAliasPwd = True newIp = self.ipLine.text() if not len(newIp): QMessageBox.warning(self, "Assistant", "Please to provide a ip!") return newPort = self.portLine.text() if not len(newPort): QMessageBox.warning(self, "Assistant", "Please to provide a port!") return newLogin = self.loginLine.text() if not len(newLogin): QMessageBox.warning(self, "Assistant", "Please to provide a login!") return newPwd = self.pwdLine.text() agentSupport = "False" if self.useAgent.isChecked(): agentSupport = "True" parameters = { 'dest-ip': newIp, 'dest-port': newPort, 'login': newLogin, 'password': newPwd, 'from-cache-ip': fromCacheIp, 'from-alias-ip': fromAliasIp, 'from-cache-port': fromCachePort, 'from-alias-port': fromAliasPort, 'from-cache-login': fromCacheLogin, 'from-alias-login': fromAliasLogin, 'from-cache-pwd': fromCachePwd, 'from-alias-pwd': fromAliasPwd, 'agent-support': agentSupport } signal.emit(str(action), unicode(descr), EMPTY_VALUE, parameters) elif action in [GuiSteps.SYSTEM_CLOSE]: signal.emit(str(action), unicode(descr), EMPTY_VALUE, {}) elif action in [GuiSteps.SYSTEM_CLEAR_SCREEN]: signal.emit(str(action), unicode(descr), EMPTY_VALUE, {}) elif action in [GuiSteps.SYSTEM_TEXT]: fromCache = False if self.textCombo.currentText() == "CACHE": fromCache = True fromAlias = False if self.textCombo.currentText() == "ALIAS": fromAlias = True newText = self.textLine.text() if not len(newText): QMessageBox.warning(self, "Assistant", "Please to provide text!") return parameters = { 'text': newText, 'from-cache': fromCache, 'from-alias': fromAlias } signal.emit(str(action), unicode(descr), EMPTY_VALUE, parameters) elif action in [GuiSteps.SYSTEM_SHORTCUT]: newShortcut = self.shortcutComboBox.currentText() parameters = {'shortcut': newShortcut} signal.emit(str(action), unicode(descr), EMPTY_VALUE, parameters) elif action in [GuiSteps.SYSTEM_CHECK_SCREEN]: op = self.checkComboBox.currentText() fromCache = False if self.screenCombo.currentText() == "CACHE": fromCache = True fromAlias = False if self.screenCombo.currentText() == "ALIAS": fromAlias = True toCache = False if self.screenSaveCombo.currentText() == "CACHE": toCache = True keyCache = self.screenSaveLine.text() newText = "" if op != GuiSteps.OP_ANY: if fromCache or fromAlias: newText = self.screenLine.text() else: newText = self.screenArea.toPlainText() if not len(newText): QMessageBox.warning(self, "Assistant", "Please to provide value to search!") return parameters = { 'value': newText, 'from-cache': fromCache, 'from-alias': fromAlias, 'operator': op, 'to-cache': toCache, 'cache-key': keyCache } 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 the update of the step """ 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.SYSTEM_SESSION]: self.ipLine.setText(stepData["parameters"]["dest-ip"]) self.portLine.setText("%s" % stepData["parameters"]["dest-port"]) self.loginLine.setText(stepData["parameters"]["login"]) self.pwdLine.setText(stepData["parameters"]["password"]) if stepData["parameters"]["from-cache-ip"]: self.ipLine.setValidator(self.validatorAll) self.ipCombo.setCurrentIndex(INDEX_CACHE) elif stepData["parameters"]["from-alias-ip"]: self.ipLine.setValidator(self.validatorUpper) self.ipCombo.setCurrentIndex(INDEX_ALIAS) else: self.ipLine.setValidator(self.validatorAll) self.ipCombo.setCurrentIndex(INDEX_TEXT) if stepData["parameters"]["from-cache-port"]: self.portLine.setValidator(self.validatorAll) self.portCombo.setCurrentIndex(INDEX_CACHE) elif stepData["parameters"]["from-alias-port"]: self.portLine.setValidator(self.validatorUpper) self.portCombo.setCurrentIndex(INDEX_ALIAS) else: self.portLine.setValidator(self.validatorInt) self.portCombo.setCurrentIndex(INDEX_TEXT) if stepData["parameters"]["from-cache-login"]: self.loginLine.setValidator(self.validatorAll) self.loginCombo.setCurrentIndex(INDEX_CACHE) elif stepData["parameters"]["from-alias-login"]: self.loginLine.setValidator(self.validatorUpper) self.loginCombo.setCurrentIndex(INDEX_ALIAS) else: self.loginLine.setValidator(self.validatorAll) self.loginCombo.setCurrentIndex(INDEX_TEXT) if stepData["parameters"]["from-cache-pwd"]: self.pwdLine.setValidator(self.validatorAll) self.pwdCombo.setCurrentIndex(INDEX_CACHE) elif stepData["parameters"]["from-alias-pwd"]: self.pwdLine.setValidator(self.validatorUpper) self.pwdCombo.setCurrentIndex(INDEX_ALIAS) else: self.pwdLine.setValidator(self.validatorAll) self.pwdCombo.setCurrentIndex(INDEX_TEXT) if self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_CLOSE]: pass if self.actionsComboBox.currentText() in [ GuiSteps.SYSTEM_CLEAR_SCREEN ]: pass if self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_TEXT]: if stepData["parameters"]["from-cache"]: self.textLine.setValidator(self.validatorAll) self.textCombo.setCurrentIndex(INDEX_CACHE) elif stepData["parameters"]["from-alias"]: self.textLine.setValidator(self.validatorUpper) self.textCombo.setCurrentIndex(INDEX_ALIAS) else: self.textLine.setValidator(self.validatorAll) self.textCombo.setCurrentIndex(INDEX_TEXT) self.textLine.setText(stepData["parameters"]["text"]) if self.actionsComboBox.currentText() in [GuiSteps.SYSTEM_SHORTCUT]: for i in xrange(self.shortcutComboBox.count()): item_text = self.shortcutComboBox.itemText(i) if unicode(stepData["parameters"]["shortcut"]) == unicode( item_text): self.shortcutComboBox.setCurrentIndex(i) break if self.actionsComboBox.currentText() in [ GuiSteps.SYSTEM_CHECK_SCREEN ]: if stepData["parameters"]["from-cache"]: self.screenLine.setValidator(self.validatorAll) self.screenCombo.setCurrentIndex(INDEX_CACHE) self.screenLine.setText(stepData["parameters"]["value"]) elif stepData["parameters"]["from-alias"]: self.screenLine.setValidator(self.validatorUpper) self.screenCombo.setCurrentIndex(INDEX_ALIAS) self.screenLine.setText(stepData["parameters"]["value"]) else: self.screenCombo.setCurrentIndex(INDEX_TEXT) self.screenArea.setPlainText(stepData["parameters"]["value"]) 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 stepData["parameters"]["to-cache"]: self.screenSaveCombo.setCurrentIndex(1) self.screenSaveLine.setText( stepData["parameters"]["cache-key"]) else: self.screenSaveCombo.setCurrentIndex(0) def getTimeout(self): """ Return timeout value """ return self.optionsDialog.timeoutLine.text() def setTimeout(self, timeout): """ Set the timeout """ return self.optionsDialog.timeoutLine.setText(timeout) def getAgentName(self): """ Return the agent name """ return self.optionsDialog.agentNameLine.text() def getAgentList(self): """ Return the agent list """ return self.optionsDialog.agentsList
class LinkInput(QDialog): def __init__(self, cfg, parent = None): QDialog.__init__(self) self.setParent(parent) self.setWindowFlags(Qt.Dialog) self.setWindowTitle(self.tr('manage links')) self.setModal(1) self.config = cfg self.modified = [] self.links = self.config.loadLinks() self.typeSelect = QComboBox(self) self.plugins = classdirPlugins() plugs = self.plugins.classes() self.typeSelect.addItems(['generic'] + plugs) self.nameSelect = QComboBox(self) self.nameSelect.addItems([l for l in self.links]) self.connect(self.nameSelect, SIGNAL('currentIndexChanged(int)'), self.onNameSelectChange) self.lUserName = QLabel(self.tr('userName'), self) self.lPass = QLabel(self.tr('password'), self) self.lUrl = QLabel(self.tr('Url'), self) self.lType = QLabel(self.tr('widgetType'), self) self.lWidgetName = QLabel(self.tr('widgetName'), self) self.name = QLineEdit(self) self.urlEdit = QLineEdit() self.passwd = QLineEdit(self) self.passwd.setEchoMode(QLineEdit.Password) self.connect(self.typeSelect , SIGNAL('activated(int)') , self.onChange) self.connect(self.urlEdit , SIGNAL('textEdited(QString)') , self.onChange) self.connect(self.name , SIGNAL('textEdited(QString)') , self.onChange) self.connect(self.passwd , SIGNAL('textEdited(QString)') , self.onChange) self.newButton = QPushButton(self.tr('&new'), self) self.delButton = QPushButton(self.tr('&del'), self) self.savButton = QPushButton(self.tr('&save'), self) self.finButton = QPushButton(self.tr('&finish'), self) self.defFont = QFont() self.connect(self.newButton, SIGNAL('clicked()'), self.onNewClick) self.connect(self.delButton, SIGNAL('clicked()'), self.onDelClick) self.connect(self.savButton, SIGNAL('clicked()'), self.onSavClick) self.connect(self.finButton, SIGNAL('clicked()'), self.onFinClick) self.layout = QGridLayout(self) self.layout.addWidget(self.lWidgetName , 0 , 0) self.layout.addWidget(self.lType , 2 , 0) self.layout.addWidget(self.lUrl , 3 , 0) self.layout.addWidget(self.lUserName , 4 , 0) self.layout.addWidget(self.lPass , 5 , 0) self.layout.addWidget(self.nameSelect , 0 , 1) self.layout.addWidget(self.typeSelect , 2 , 1) self.layout.addWidget(self.urlEdit , 3 , 1) self.layout.addWidget(self.name , 4 , 1) self.layout.addWidget(self.passwd , 5 , 1) self.layout.addWidget(self.newButton , 1 , 2) self.layout.addWidget(self.delButton , 2 , 2) self.layout.addWidget(self.savButton , 3 , 2) self.layout.addWidget(self.finButton , 4 , 2) self.setMinimumWidth(500) self.nameSelect.setCurrentIndex(self.nameSelect.count()-1) def onChange(self): self.savButton.setFont(QFont(self.defFont.defaultFamily(), -1, QFont.Bold)) def onSavClick(self): if self.urlEdit.text().isEmpty(): self.urlEdit.setText(self.tr("insert URL here")) self.urlEdit.selectAll() else: u = QUrl() u.setUrl(self.urlEdit.text()) if not u.scheme(): u.setScheme('http') u.setUserName(self.name.text()) u.setPassword(self.passwd.text()) self.config.saveLink(self.nameSelect.currentText(), { 'type' : self.typeSelect.currentText(), 'data' : u.toString()}) #self.links = self.config.loadLinks() self.savButton.setFont(QFont()) self.modified.append(str(self.nameSelect.currentText())) def onNewClick(self): inp = StringInput([l for l in self.links], self) if inp.exec_(): self.name.clear() self.passwd.clear() self.urlEdit.clear() self.nameSelect.addItem(inp.getVal()) self.nameSelect.setCurrentIndex(self.nameSelect.findText(inp.getVal())) def onDelClick(self): if QMessageBox( QMessageBox.Question, self.tr('del_link'), self.tr('ask_del_link %1 ?').arg(self.nameSelect.currentText()), QMessageBox.Yes | QMessageBox.No, self).exec_() == QMessageBox.Yes: if not self.config.delLink(self.nameSelect.currentText()): print(('link "%s" not deleted !' % self.nameSelect.currentText())) self.links = self.config.loadLinks() self.nameSelect.removeItem(self.nameSelect.currentIndex()) def onFinClick(self): self.accept() def onNameSelectChange(self): try: l = self.links[str(self.nameSelect.currentText())] u = QUrl(l['data']) self.name.setText(u.userName()) self.passwd.setText(u.password()) self.urlEdit.setText(u.toString(QUrl.RemoveUserInfo)) self.typeSelect.setCurrentIndex(self.typeSelect.findText(l['type'])) except Exception as e: #print e pass def modifiedWidgets(self): return set(self.modified)
class OperatorValueDialog(QtHelper.EnhancedQDialog): """ Operator dialog """ def __init__(self, parent, currentOperator={}, liteMode=False): """ Operator to fill parameter description @param dataArgs: @type dataArgs: @param parent: @type parent: """ super(OperatorValueDialog, self).__init__(parent) self.parentWidget = parent self.liteMode = liteMode self.currentOperator = currentOperator self.createDialog() self.createConnections() def createDialog(self): """ Create qt dialog """ self.buttonBox = QDialogButtonBox(self) self.buttonBox.setStyleSheet("""QDialogButtonBox { dialogbuttonbox-buttons-have-icons: 1; dialog-ok-icon: url(:/ok.png); dialog-cancel-icon: url(:/test-close-black.png); }""") self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) mainLayout = QHBoxLayout() main2Layout = QHBoxLayout() titleLabel = QLabel(self.currentOperator['operator']) font = QFont() font.setBold(True) titleLabel.setFont(font) self.opType = QComboBox() if not self.liteMode: for i in xrange(len(LIST_CONDITIONS)): self.opType.addItem(LIST_CONDITIONS[i].title()) if self.currentOperator['operator'] == LIST_CONDITIONS[ i].title(): self.opType.setCurrentIndex(i) else: for i in xrange(len(LIST_CONDITIONS_LITE)): self.opType.addItem(LIST_CONDITIONS_LITE[i].title()) if self.currentOperator['operator'] == LIST_CONDITIONS_LITE[ i].title(): self.opType.setCurrentIndex(i) main2Layout.addWidget(titleLabel) main2Layout.addWidget(self.opType) if not self.liteMode: self.textValue = QTextEdit() self.textValue.setFixedHeight(HEIGHT_TEXT_AREA) self.textValue.setMinimumWidth(WIDTH_TEXT_AREA) radioGroup = QButtonGroup(self) self.strRadioButton = QRadioButton("string") self.strRadioButton.setChecked(True) self.inRadioButton = QRadioButton("inputs") self.outRadioButton = QRadioButton("outputs") self.varRadioButton = QRadioButton("variables") radioGroup.addButton(self.strRadioButton) radioGroup.addButton(self.inRadioButton) radioGroup.addButton(self.outRadioButton) radioGroup.addButton(self.varRadioButton) self.inputsCombo = QComboBox() for inpt in self.parentWidget.getInputs(): self.inputsCombo.addItem(inpt['name']) self.outputsCombo = QComboBox() for inpt in self.parentWidget.getOutputs(): self.outputsCombo.addItem(inpt['name']) self.variablesCombo = QComboBox() self.variablesCombo.addItems(self.parentWidget.variables) if self.currentOperator['type'] == 'string': self.strRadioButton.setChecked(True) self.textValue.setText(self.currentOperator['value']) if self.currentOperator['type'] == 'inputs': self.inRadioButton.setChecked(True) for x in xrange(self.inputsCombo.count()): if self.inputsCombo.itemText( x) == self.currentOperator['value']: self.inputsCombo.setCurrentIndex(x) if self.currentOperator['type'] == 'outputs': self.outRadioButton.setChecked(True) for x in xrange(self.outputsCombo.count()): if self.outputsCombo.itemText( x) == self.currentOperator['value']: self.outputsCombo.setCurrentIndex(x) if self.currentOperator['type'] == 'variables': self.varRadioButton.setChecked(True) for x in xrange(self.variablesCombo.count()): if self.variablesCombo.itemText( x) == self.currentOperator['value']: self.variablesCombo.setCurrentIndex(x) mainLayout.addWidget(self.strRadioButton) mainLayout.addWidget(self.textValue) mainLayout.addWidget(self.inRadioButton) mainLayout.addWidget(self.inputsCombo) mainLayout.addWidget(self.outRadioButton) mainLayout.addWidget(self.outputsCombo) mainLayout.addWidget(self.varRadioButton) mainLayout.addWidget(self.variablesCombo) finalLayout = QVBoxLayout() finalLayout.addLayout(main2Layout) finalLayout.addLayout(mainLayout) finalLayout.addWidget(self.buttonBox) self.setLayout(finalLayout) self.setWindowTitle(self.tr("Operators configuration")) self.setMinimumWidth(500) self.center() def createConnections(self): """ Create qt connections """ self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def getValue(self): """ Return value """ self.currentOperator['operator'] = unicode(self.opType.currentText()) if not self.liteMode: if self.currentOperator['operator'].lower() == OP_ANY: self.currentOperator['type'] = 'string' self.currentOperator['value'] = '' else: if self.strRadioButton.isChecked(): self.currentOperator['type'] = 'string' self.currentOperator['value'] = unicode( self.textValue.toPlainText()) if self.inRadioButton.isChecked(): self.currentOperator['type'] = 'inputs' self.currentOperator['value'] = unicode( self.inputsCombo.currentText()) if self.outRadioButton.isChecked(): self.currentOperator['type'] = 'outputs' self.currentOperator['value'] = unicode( self.outputsCombo.currentText()) if self.varRadioButton.isChecked(): self.currentOperator['type'] = 'variables' self.currentOperator['value'] = unicode( self.variablesCombo.currentText()) return self.currentOperator
class MainWindow(mainwindow_widget, mainwindow_base): """ Main application window """ def __init__(self, settings): super(MainWindow, self).__init__() self.setupUi(self) self.settings = settings roam.featureform.settings = settings.settings self.canvaslayers = [] self.layerbuttons = [] self.project = None self.selectionbands = defaultdict(partial(QgsRubberBand, self.canvas)) self.canvas.setCanvasColor(Qt.white) self.canvas.enableAntiAliasing(True) self.canvas.setWheelAction(QgsMapCanvas.WheelZoomToMouseCursor) self.bar = roam.messagebaritems.MessageBar(self) self.actionMap.setVisible(False) pal = QgsPalLabeling() self.canvas.mapRenderer().setLabelingEngine(pal) self.canvas.setFrameStyle(QFrame.NoFrame) self.menuGroup = QActionGroup(self) self.menuGroup.setExclusive(True) self.menuGroup.addAction(self.actionMap) self.menuGroup.addAction(self.actionDataEntry) self.menuGroup.addAction(self.actionProject) self.menuGroup.addAction(self.actionSync) self.menuGroup.addAction(self.actionSettings) self.menuGroup.triggered.connect(self.updatePage) self.editgroup = QActionGroup(self) self.editgroup.setExclusive(True) self.editgroup.addAction(self.actionPan) self.editgroup.addAction(self.actionZoom_In) self.editgroup.addAction(self.actionZoom_Out) self.editgroup.addAction(self.actionInfo) #TODO Extract GPS out into a service and remove UI stuff self.actionGPS = GPSAction(":/icons/gps", self.canvas, self.settings, self) self.projecttoolbar.addAction(self.actionGPS) self.projectwidget = ProjectsWidget(self) self.projectwidget.requestOpenProject.connect(self.loadProject) QgsProject.instance().readProject.connect(self._readProject) self.project_page.layout().addWidget(self.projectwidget) self.syncwidget = SyncWidget() self.syncpage.layout().addWidget(self.syncwidget) self.settingswidget = SettingsWidget(settings, self) self.settings_page.layout().addWidget(self.settingswidget) self.actionSettings.toggled.connect(self.settingswidget.populateControls) self.actionSettings.toggled.connect(self.settingswidget.readSettings) self.settingswidget.settingsupdated.connect(self.settingsupdated) self.dataentrywidget = DataEntryWidget(self.canvas, self.bar) self.widgetpage.layout().addWidget(self.dataentrywidget) self.dataentrywidget.rejected.connect(self.formrejected) self.dataentrywidget.featuresaved.connect(self.featureSaved) self.dataentrywidget.featuredeleted.connect(self.featuredeleted) self.dataentrywidget.failedsave.connect(self.failSave) self.dataentrywidget.helprequest.connect(self.showhelp) self.dataentrywidget.openimage.connect(self.openimage) def createSpacer(width=0, height=0): widget = QWidget() widget.setMinimumWidth(width) widget.setMinimumHeight(height) return widget gpsspacewidget = createSpacer(30) sidespacewidget = createSpacer(30) sidespacewidget2 = createSpacer(height=20) sidespacewidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sidespacewidget2.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) gpsspacewidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.topspaceraction = self.projecttoolbar.insertWidget(self.actionGPS, gpsspacewidget) def createlabel(text): style = """ QLabel { color: #706565; font: 14px "Calibri" ; }""" label = QLabel(text) label.setStyleSheet(style) return label self.projectlabel = createlabel("Project: {project}") self.userlabel = createlabel("User: {user}".format(user=getpass.getuser())) self.positionlabel = createlabel('') self.statusbar.addWidget(self.projectlabel) self.statusbar.addWidget(self.userlabel) spacer = createSpacer() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.statusbar.addWidget(spacer) self.statusbar.addWidget(self.positionlabel) self.menutoolbar.insertWidget(self.actionQuit, sidespacewidget2) self.menutoolbar.insertWidget(self.actionProject, sidespacewidget) self.stackedWidget.currentChanged.connect(self.updateUIState) self.panels = [] self.connectButtons() self.band = QgsRubberBand(self.canvas) self.band.setIconSize(20) self.band.setWidth(10) self.band.setColor(QColor(186, 93, 212, 76)) self.canvas_page.layout().insertWidget(0, self.projecttoolbar) self.dataentrymodel = QStandardItemModel(self) self.dataentrycombo = QComboBox(self.projecttoolbar) self.dataentrycombo.setIconSize(QSize(48,48)) self.dataentrycombo.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.dataentrycombo.setSizeAdjustPolicy(QComboBox.AdjustToContents) self.dataentrycombo.setModel(self.dataentrymodel) self.dataentrycomboaction = self.projecttoolbar.insertWidget(self.topspaceraction, self.dataentrycombo) self.dataentrycombo.showPopup = self.selectdataentry self.biglist = BigList(self.canvas) self.biglist.setlabel("Select data entry form") self.biglist.setmodel(self.dataentrymodel) self.biglist.itemselected.connect(self.dataentrychanged) self.biglist.hide() self.centralwidget.layout().addWidget(self.statusbar) self.actionGPSFeature.setProperty('dataentry', True) self.infodock = InfoDock(self.canvas) self.infodock.requestopenform.connect(self.openForm) self.infodock.featureupdated.connect(self.highlightfeature) self.infodock.resultscleared.connect(self.clearselection) self.infodock.openurl.connect(self.viewurl) self.infodock.hide() self.hidedataentry() self.canvas.extentsChanged.connect(self.updatestatuslabel) self.projecttoolbar.toolButtonStyleChanged.connect(self.updatecombo) def selectdataentry(self, ): if self.dataentrycombo.count() == 0: return self.biglist.show() def viewurl(self, url): """ Open a URL in Roam :param url: :return: """ key = url.toString().lstrip('file://') try: # Hack. Eww fix me. data, imagetype = roam.htmlviewer.images[os.path.basename(key)] except KeyError: # It's not a image so lets just pass it of as a normal # URL QDesktopServices.openUrl(url) return pix = QPixmap() if imagetype == 'base64': pix.loadFromData(data) else: pix.load(data) self.openimage(pix) def openimage(self, pixmap): viewer = ImageViewer(self.stackedWidget) viewer.resize(self.stackedWidget.size()) viewer.openimage(pixmap) def updatecombo(self, *args): self.dataentrycombo.setMinimumHeight(0) def settingsupdated(self, settings): settings.save() self.show() self.actionGPS.updateGPSPort() # eww! roam.featureform.settings = settings.settings def updatestatuslabel(self): extent = self.canvas.extent() self.positionlabel.setText("Map Center: {}".format(extent.center().toString())) def highlightselection(self, results): for layer, features in results.iteritems(): band = self.selectionbands[layer] band.setColor(QColor(255, 0, 0, 150)) band.setIconSize(20) band.setWidth(2) band.setBrushStyle(Qt.NoBrush) band.reset(layer.geometryType()) for feature in features: band.addGeometry(feature.geometry(), layer) def clearselection(self): # Clear the main selection rubber band self.band.reset() # Clear the rest for band in self.selectionbands.itervalues(): band.reset() def highlightfeature(self, layer, feature, features): self.clearselection() self.highlightselection({layer: features}) self.band.setToGeometry(feature.geometry(), layer) def showmap(self): self.actionMap.setVisible(True) self.actionMap.trigger() def hidedataentry(self): self.actionDataEntry.setVisible(False) def showdataentry(self): self.actionDataEntry.setVisible(True) self.actionDataEntry.trigger() def dataentrychanged(self, index): wasactive = self.clearCapatureTools() if not index.isValid(): return modelindex = index # modelindex = self.dataentrymodel.index(index, 0) form = modelindex.data(Qt.UserRole + 1) self.dataentrycombo.setCurrentIndex(index.row()) self.createCaptureButtons(form, wasactive) def raiseerror(self, *exinfo): info = traceback.format_exception(*exinfo) item = self.bar.pushError('Seems something has gone wrong. Press for more details', info) def setMapTool(self, tool, *args): self.canvas.setMapTool(tool) def homeview(self): """ Zoom the mapview canvas to the extents the project was opened at i.e. the default extent. """ self.canvas.setExtent(self.defaultextent) self.canvas.refresh() def connectButtons(self): def connectAction(action, tool): action.toggled.connect(partial(self.setMapTool, tool)) def cursor(name): pix = QPixmap(name) pix = pix.scaled(QSize(24,24)) return QCursor(pix) self.zoomInTool = QgsMapToolZoom(self.canvas, False) self.zoomOutTool = QgsMapToolZoom(self.canvas, True) self.panTool = TouchMapTool(self.canvas) self.moveTool = MoveTool(self.canvas, []) self.infoTool = InfoTool(self.canvas) connectAction(self.actionZoom_In, self.zoomInTool) connectAction(self.actionZoom_Out, self.zoomOutTool) connectAction(self.actionPan, self.panTool) connectAction(self.actionMove, self.moveTool) connectAction(self.actionInfo, self.infoTool) self.zoomInTool.setCursor(cursor(':/icons/in')) self.zoomOutTool.setCursor(cursor(':/icons/out')) self.infoTool.setCursor(cursor(':/icons/info')) self.actionRaster.triggered.connect(self.toggleRasterLayers) self.infoTool.infoResults.connect(self.showInfoResults) # The edit toolbutton is currently not being used but leaving it for feature. self.moveTool.layersupdated.connect(self.actionMove.setEnabled) self.moveTool.layersupdated.connect(self.actionEdit_Tools.setEnabled) self.actionGPSFeature.triggered.connect(self.addFeatureAtGPS) self.actionGPSFeature.setEnabled(self.actionGPS.isConnected) self.actionGPS.gpsfixed.connect(self.actionGPSFeature.setEnabled) self.actionHome.triggered.connect(self.homeview) self.actionQuit.triggered.connect(self.exit) def showToolError(self, label, message): self.bar.pushMessage(label, message, QgsMessageBar.WARNING) def clearCapatureTools(self): captureselected = False for action in self.projecttoolbar.actions(): if action.objectName() == "capture" and action.isChecked(): captureselected = True if action.property('dataentry'): self.projecttoolbar.removeAction(action) return captureselected def createCaptureButtons(self, form, wasselected): tool = form.getMaptool()(self.canvas) for action in tool.actions: # Create the action here. if action.ismaptool: action.toggled.connect(partial(self.setMapTool, tool)) # Set the action as a data entry button so we can remove it later. action.setProperty("dataentry", True) self.editgroup.addAction(action) self.layerbuttons.append(action) self.projecttoolbar.insertAction(self.topspaceraction, action) if action.isdefault: action.setChecked(wasselected) if hasattr(tool, 'geometryComplete'): add = partial(self.addNewFeature, form) tool.geometryComplete.connect(add) else: tool.finished.connect(self.openForm) tool.error.connect(partial(self.showToolError, form.label)) self.projecttoolbar.insertAction(self.topspaceraction, self.actionGPSFeature) self.actionGPSFeature.setVisible(not tool.isEditTool()) def createFormButtons(self, forms): """ Create buttons for each form that is defined """ self.dataentrymodel.clear() self.clearCapatureTools() def captureFeature(form): item = QStandardItem(QIcon(form.icon), form.icontext) item.setData(form, Qt.UserRole + 1) item.setSizeHint(QSize(item.sizeHint().width(), self.projecttoolbar.height())) self.dataentrymodel.appendRow(item) capabilitityhandlers = {"capture": captureFeature} failedforms = [] for form in forms: valid, reasons = form.valid if not valid: roam.utils.log("Form is invalid for data entry because {}".format(reasons)) failedforms.append((form, reasons)) continue for capability in form.capabilities: try: capabilitityhandlers[capability](form) except KeyError: # Just ignore capabilities we don't support yet. continue if failedforms: for form, reasons in failedforms: html = "<h3>{}</h3><br>{}".format(form.label, "<br>".join(reasons)) self.bar.pushMessage("Form errors", "Looks like some forms couldn't be loaded", level=QgsMessageBar.WARNING, extrainfo=html) visible = self.dataentrymodel.rowCount() > 0 self.dataentrycomboaction.setVisible(visible) self.dataentrycombo.setMinimumHeight(self.projecttoolbar.height()) index = self.dataentrymodel.index(0, 0) self.dataentrychanged(index) def addFeatureAtGPS(self): """ Add a record at the current GPS location. """ index = self.dataentrycombo.currentIndex() modelindex = self.dataentrymodel.index(index, 0) form = modelindex.data(Qt.UserRole + 1) point = self.actionGPS.position point = QgsGeometry.fromPoint(point) self.addNewFeature(form=form, geometry=point) def clearToolRubberBand(self): """ Clear the rubber band of the active tool if it has one """ tool = self.canvas.mapTool() try: tool.clearBand() except AttributeError: # No clearBand method found, but that's cool. pass def showhelp(self, url): help = HelpPage(self.stackedWidget) help.setHelpPage(url) help.show() def dataentryfinished(self): self.hidedataentry() self.showmap() self.cleartempobjects() self.infodock.refreshcurrent() def featuredeleted(self): self.dataentryfinished() self.bar.pushMessage("Deleted", "Feature Deleted", QgsMessageBar.INFO, 1) self.canvas.refresh() def featureSaved(self): self.dataentryfinished() self.canvas.refresh() def failSave(self, messages): self.bar.pushError("Error when saving changes.", messages) def cleartempobjects(self): self.band.reset() self.clearToolRubberBand() def formrejected(self, message, level): self.dataentryfinished() if message: self.bar.pushMessage("Form Message", message, level, duration=2) self.cleartempobjects() def openForm(self, form, feature): """ Open the form that is assigned to the layer """ self.band.setToGeometry(feature.geometry(), form.QGISLayer) self.showdataentry() self.dataentrywidget.openform(feature=feature, form=form, project=self.project) def addNewFeature(self, form, geometry): """ Add a new new feature to the given layer """ layer = form.QGISLayer fields = layer.pendingFields() feature = QgsFeature(fields) feature.setGeometry(geometry) for index in xrange(fields.count()): pkindexes = layer.dataProvider().pkAttributeIndexes() if index in pkindexes and layer.dataProvider().name() == 'spatialite': continue value = layer.dataProvider().defaultValue(index) feature[index] = value self.openForm(form, feature) def exit(self): """ Exit the application. """ QApplication.exit(0) def showInfoResults(self, results): self.infodock.clearResults() forms = {} for layer in results.keys(): layername = layer.name() if not layername in forms: forms[layername] = list(self.project.formsforlayer(layername)) self.infodock.setResults(results, forms) self.infodock.show() def toggleRasterLayers(self): """ Toggle all raster layers on or off. """ if not self.canvaslayers: return #Freeze the canvas to save on UI refresh self.canvas.freeze() for layer in self.canvaslayers: if layer.layer().type() == QgsMapLayer.RasterLayer: layer.setVisible(not layer.isVisible()) # Really!? We have to reload the whole layer set every time? # WAT? self.canvas.setLayerSet(self.canvaslayers) self.canvas.freeze(False) self.canvas.refresh() def missingLayers(self, layers): """ Called when layers have failed to load from the current project """ roam.utils.warning("Missing layers") map(roam.utils.warning, layers) missinglayers = roam.messagebaritems.MissingLayerItem(layers, parent=self.bar) self.bar.pushItem(missinglayers) def loadprojects(self, projects): """ Load the given projects into the project list """ projects = list(projects) self.projectwidget.loadProjectList(projects) self.syncwidget.loadprojects(projects) def updatePage(self, action): """ Update the current stack page based on the current selected action """ page = action.property("page") self.stackedWidget.setCurrentIndex(page) def show(self): """ Override show method. Handles showing the app in fullscreen mode or just maximized """ fullscreen = self.settings.settings.get("fullscreen", False) if fullscreen: self.showFullScreen() else: self.showMaximized() def viewprojects(self): self.stackedWidget.setCurrentIndex(1) def updateUIState(self, page): """ Update the UI state to reflect the currently selected page in the stacked widget """ pass @roam.utils.timeit def _readProject(self, doc): """ readProject is called by QgsProject once the map layer has been populated with all the layers """ parser = ProjectParser(doc) canvasnode = parser.canvasnode self.canvas.freeze() self.canvas.mapRenderer().readXML(canvasnode) self.canvaslayers = parser.canvaslayers() self.canvas.setLayerSet(self.canvaslayers) self.canvas.updateScale() self.projectOpened() self.canvas.freeze(False) self.canvas.refresh() self.showmap() @roam.utils.timeit def projectOpened(self): """ Called when a new project is opened in QGIS. """ projectpath = QgsProject.instance().fileName() self.project = Project.from_folder(os.path.dirname(projectpath)) self.projectlabel.setText("Project: {}".format(self.project.name)) self.createFormButtons(forms=self.project.forms) # Enable the raster layers button only if the project contains a raster layer. layers = QgsMapLayerRegistry.instance().mapLayers().values() hasrasters = any(layer.type() == QgsMapLayer.RasterLayer for layer in layers) self.actionRaster.setEnabled(hasrasters) self.defaultextent = self.canvas.extent() roam.utils.info("Extent: {}".format(self.defaultextent.toString())) # Show panels for panel in self.project.getPanels(): self.mainwindow.addDockWidget(Qt.BottomDockWidgetArea, panel) self.panels.append(panel) # TODO Abstract this out if not self.project.selectlayers: selectionlayers = QgsMapLayerRegistry.instance().mapLayers().values() else: selectionlayers = [] for layername in self.project.selectlayers: try: layer = QgsMapLayerRegistry.instance().mapLayersByName(layername)[0] except IndexError: roam.utils.warning("Can't find QGIS layer for select layer {}".format(layername)) continue selectionlayers.append(layer) self.infoTool.selectionlayers = selectionlayers self.actionPan.trigger() #noinspection PyArgumentList @roam.utils.timeit def loadProject(self, project): """ Load a project into the application . """ roam.utils.log(project) roam.utils.log(project.name) roam.utils.log(project.projectfile) roam.utils.log(project.valid) (passed, message) = project.onProjectLoad() if not passed: self.bar.pushMessage("Project load rejected", "Sorry this project couldn't" "be loaded. Click for me details.", QgsMessageBar.WARNING, extrainfo=message) return self.actionMap.trigger() self.closeProject() self.canvas.refresh() self.canvas.repaint() self.infodock.clearResults() # No idea why we have to set this each time. Maybe QGIS deletes it for # some reason. self.badLayerHandler = BadLayerHandler(callback=self.missingLayers) QgsProject.instance().setBadLayerHandler(self.badLayerHandler) self.stackedWidget.setCurrentIndex(3) self.projectloading_label.setText("Project {} Loading".format(project.name)) pixmap = QPixmap(project.splash) w = self.projectimage.width() h = self.projectimage.height() self.projectimage.setPixmap(pixmap.scaled(w,h, Qt.KeepAspectRatio)) QApplication.processEvents() QDir.setCurrent(os.path.dirname(project.projectfile)) fileinfo = QFileInfo(project.projectfile) QgsProject.instance().read(fileinfo) def closeProject(self): """ Close the current open project """ self.canvas.freeze() QgsMapLayerRegistry.instance().removeAllMapLayers() self.canvas.clear() self.canvas.freeze(False) for panel in self.panels: self.removeDockWidget(panel) del panel # Remove all the old buttons for action in self.layerbuttons: self.editgroup.removeAction(action) self.dataentrymodel.clear() self.panels = [] self.project = None self.dataentrywidget.clear() self.hidedataentry() self.infodock.close()
class lTabOptions(QGroupBox): state_change = pyqtSignal() def __init__(self, parent, run_data_dir): self.block_state_change = False self.run_data_dir = run_data_dir QGroupBox.__init__(self, "Global Tab Options", parent) self.grid_layout = QGridLayout(self) title = QLabel('Lovell') font = QFont() title.setAlignment(Qt.AlignHCenter) font.setPointSize(20) font.setBold(True) title.setFont(font) self.setMinimumWidth(275) self.grid_layout.addWidget(title, self.rowCount(), 0, 1, 2) setPadding(self.grid_layout) self.add_group_selector() self.add_ID_selector() self.add_next_prev_buttons() self.add_notify_box() self.add_reference_buttons() self.add_run_num_buttons() def add_notify_box(self): notifyFont = QFont() notifyFont.setPointSize(8) self.grid_layout.addWidget(QLabel("Notifcations:"), self.rowCount(), 0, 1, 2) self.notifyBox = QTextEdit("Hello world! :)", self) self.notifyBox.setFont(notifyFont) self.grid_layout.addWidget(self.notifyBox, self.rowCount(), 0, 1, 2) def notify(self, text, textHighlight=None): # highlightRange is range in passed text. length = len(self.notifyBox.toPlainText()) self.notifyBox.append(text) self.notifyBox.verticalScrollBar().setValue( self.notifyBox.verticalScrollBar().maximum()) if textHighlight != None: begin = length + text.find(textHighlight) + 1 end = begin + len(textHighlight) fmt = QTextCharFormat() col = QColor(Qt.red) col.setAlpha(130) fmt.setBackground(col) cursor = QTextCursor(self.notifyBox.document()) cursor.setPosition(begin) cursor.setPosition(end, QTextCursor.KeepAnchor) cursor.setCharFormat(fmt) def add_group_selector(self): self.module_group_box = QComboBox(self) self.module_group_box.currentIndexChanged.connect(self.state_changed) lab = QLabel("Module Group:") lab.setAlignment(Qt.AlignRight) self.grid_layout.addWidget(lab, self.rowCount(), 0) self.grid_layout.addWidget(self.module_group_box, self.rowCount() - 1, 1) lab.hide() self.module_group_box.hide() self.module_group_box.addItem("R (0)") self.module_group_box.addItem("Phi (1)") def add_ID_selector(self): self.module_ID_box = QComboBox(self) self.module_ID_box.currentIndexChanged.connect(self.state_changed) lab = QLabel("Sensor ID:") lab.setAlignment(Qt.AlignRight) self.grid_layout.addWidget(lab, self.rowCount(), 0) self.grid_layout.addWidget(self.module_ID_box, self.rowCount() - 1, 1) for i in range(0, 42): self.module_ID_box.addItem(str(i)) for i in range(64, 106): self.module_ID_box.addItem(str(i)) def add_next_prev_buttons(self): self.next_button = QPushButton("Next") self.grid_layout.addWidget(self.next_button, self.rowCount(), 1) self.prev_button = QPushButton("Prev") self.grid_layout.addWidget(self.prev_button, self.rowCount() - 1, 0) self.next_button.clicked.connect(self.next_clicked) self.prev_button.clicked.connect(self.prev_clicked) self.next_four_button = QPushButton("Next Four") self.grid_layout.addWidget(self.next_four_button, self.rowCount(), 1) self.prev_four_button = QPushButton("Prev Four") self.grid_layout.addWidget(self.prev_four_button, self.rowCount() - 1, 0) self.next_four_button.clicked.connect(self.next_four_clicked) self.prev_four_button.clicked.connect(self.prev_four_clicked) def add_run_num_buttons(self): self.add_bar() self.run_num_box = QComboBox(self) self.run_num_box.currentIndexChanged.connect(self.state_changed) self.grid_layout.addWidget(QLabel("Run number:"), self.rowCount(), 0, 1, 2) self.grid_layout.addWidget(self.run_num_box, self.rowCount(), 0, 1, 2) # Reference self.run_numRef_box = QComboBox(self) self.run_numRef_box.currentIndexChanged.connect(self.state_changed) self.grid_layout.addWidget(QLabel("Reference number:"), self.rowCount(), 0, 1, 2) self.grid_layout.addWidget(self.run_numRef_box, self.rowCount(), 0, 1, 2) self.run_numRef_box.addItem('Auto') for run in lInterfaces.run_list(self.run_data_dir): self.run_num_box.addItem(str(run)) self.run_numRef_box.addItem(str(run)) def add_bar(self): bar = QLabel('_______________________________') bar.setAlignment(Qt.AlignHCenter) bar.setAlignment(Qt.AlignVCenter) self.grid_layout.addWidget(bar, self.rowCount(), 0, 1, 2) def add_reference_buttons(self): self.add_bar() self.showing_ref_box = QCheckBox("Display References") self.showing_ref_box.stateChanged.connect(self.reference_button_fading) self.showing_ref_box.setChecked(True) self.overlay_ref_box = QRadioButton("Overlay", self) self.overlay_ref_box.setChecked(True) self.overlay_refDiff_box = QRadioButton("Data - Ref", self) self.overlay_refRatio_box = QRadioButton("Data/Ref", self) self.grid_layout.addWidget(self.showing_ref_box, self.rowCount(), 0, 1, 2) self.grid_layout.addWidget(self.overlay_ref_box, self.rowCount(), 0, 1, 2) self.grid_layout.addWidget(self.overlay_refDiff_box, self.rowCount(), 0, 1, 2) self.grid_layout.addWidget(self.overlay_refRatio_box, self.rowCount(), 0, 1, 2) # Slots. self.showing_ref_box.clicked.connect(self.state_changed) self.overlay_ref_box.clicked.connect(self.state_changed) self.overlay_refDiff_box.clicked.connect(self.state_changed) self.overlay_refRatio_box.clicked.connect(self.state_changed) self.reference_button_fading() def rowCount(self): return self.grid_layout.rowCount() def state_changed(self): if self.block_state_change == False: self.state_change.emit() def state(self): g = self.module_group_box.currentIndex() moduleID = int(self.module_ID_box.currentText()) state = lTabOpsState(moduleID, self.showing_ref_box.isChecked(), self.overlay_ref_box.isChecked(), self.overlay_refDiff_box.isChecked(), self.overlay_refRatio_box.isChecked(), self.run_num_box.currentText(), self.run_numRef_box.currentText(), self.run_data_dir) return state def next_four_clicked(self): self.block_state_change = True for i in range(4): self.next_clicked() self.block_state_change = False self.state_changed() def prev_four_clicked(self): self.block_state_change = True for i in range(4): self.prev_clicked() self.block_state_change = False self.state_changed() def next_clicked(self): currentGroup = self.module_group_box.currentIndex() currentModule = self.module_ID_box.currentIndex() # Check if the last one. if currentModule != self.module_ID_box.count() - 1: self.module_ID_box.setCurrentIndex(currentModule + 1) else: if currentGroup != self.module_group_box.count() - 1: self.module_group_box.setCurrentIndex(currentGroup + 1) else: self.module_group_box.setCurrentIndex(0) self.module_ID_box.setCurrentIndex(0) def prev_clicked(self): currentGroup = self.module_group_box.currentIndex() currentModule = self.module_ID_box.currentIndex() # Check if the first one. if currentModule != 0: self.module_ID_box.setCurrentIndex(currentModule - 1) else: if currentGroup != 0: self.module_group_box.setCurrentIndex(currentGroup - 1) else: self.module_group_box.setCurrentIndex( self.module_group_box.count() - 1) self.module_ID_box.setCurrentIndex(self.module_ID_box.count() - 1) def reference_button_fading(self): if self.showing_ref_box.isChecked(): self.overlay_ref_box.setEnabled(True) self.overlay_refDiff_box.setEnabled(True) self.overlay_refRatio_box.setEnabled(True) else: self.overlay_ref_box.setEnabled(False) self.overlay_refDiff_box.setEnabled(False) self.overlay_refRatio_box.setEnabled(False)
class preferencesDialog(QDialog): newMailerMessage = QtCore.Signal(str, str) def __init__(self, parent): QDialog.__init__(self, parent) self.tmpPref = {} self.tmpPref['pref'] = copy.deepcopy(self.parent().prm['pref']) self.currLocale = self.parent().prm['currentLocale'] self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator) self.audioManager = parent.audioManager self.mailer = emailSender(self) self.newMailerMessage.connect(self.popMailerMessage) self.tabWidget = QTabWidget() self.tabWidget.currentChanged.connect(self.tabChanged) self.appPrefWidget = QWidget() self.soundPrefWidget = QWidget() self.notificationPrefWidget = QWidget() self.eegPrefWidget = QWidget() #the gui widget for these are in an external dialog self.wavsPref = {} self.wavsPref['endMessageFiles'] = self.tmpPref['pref']['general']['endMessageFiles'] self.wavsPref['endMessageFilesUse'] = self.tmpPref['pref']['general']['endMessageFilesUse'] self.wavsPref['endMessageFilesID'] = self.tmpPref['pref']['general']['endMessageFilesID'] self.wavsPref['endMessageLevels'] = self.tmpPref['pref']['general']['endMessageLevels'] #GENERAL PREF appPrefGrid = QGridLayout() n = 0 self.languageChooserLabel = QLabel(self.tr('Language (requires restart):')) appPrefGrid.addWidget(self.languageChooserLabel, n, 0) self.languageChooser = QComboBox() self.languageChooser.addItems(self.parent().prm['appData']['available_languages']) self.languageChooser.setCurrentIndex(self.languageChooser.findText(self.tmpPref['pref']['language'])) self.languageChooser.currentIndexChanged[int].connect(self.onLanguageChooserChange) appPrefGrid.addWidget(self.languageChooser, n, 1) n = n+1 self.countryChooserLabel = QLabel(self.tr('Country (requires restart):')) appPrefGrid.addWidget(self.countryChooserLabel, n, 0) self.countryChooser = QComboBox() self.countryChooser.addItems(self.parent().prm['appData']['available_countries'][self.tmpPref['pref']['language']]) self.countryChooser.setCurrentIndex(self.countryChooser.findText(self.tmpPref['pref']['country'])) appPrefGrid.addWidget(self.countryChooser, n, 1) n = n+1 self.responseBoxLanguageChooserLabel = QLabel(self.tr('Response Box Language (requires restart):')) appPrefGrid.addWidget(self.responseBoxLanguageChooserLabel, n, 0) self.responseBoxLanguageChooser = QComboBox() self.responseBoxLanguageChooser.addItems(self.parent().prm['appData']['available_languages']) self.responseBoxLanguageChooser.setCurrentIndex(self.responseBoxLanguageChooser.findText(self.tmpPref['pref']['responseBoxLanguage'])) self.responseBoxLanguageChooser.currentIndexChanged[int].connect(self.onResponseBoxLanguageChooserChange) appPrefGrid.addWidget(self.responseBoxLanguageChooser, n, 1) n = n+1 self.responseBoxCountryChooserLabel = QLabel(self.tr('Response Box Country (requires restart):')) appPrefGrid.addWidget(self.responseBoxCountryChooserLabel, n, 0) self.responseBoxCountryChooser = QComboBox() self.responseBoxCountryChooser.addItems(self.parent().prm['appData']['available_countries'][self.tmpPref['pref']['responseBoxLanguage']]) self.responseBoxCountryChooser.setCurrentIndex(self.responseBoxCountryChooser.findText(self.tmpPref['pref']['responseBoxCountry'])) appPrefGrid.addWidget(self.responseBoxCountryChooser, n, 1) n = n+1 self.csvSeparatorLabel = QLabel(self.tr('csv separator:')) appPrefGrid.addWidget(self.csvSeparatorLabel, n, 0) self.csvSeparatorWidget = QLineEdit(self.tmpPref['pref']["general"]["csvSeparator"]) appPrefGrid.addWidget(self.csvSeparatorWidget, n, 1) n = n+1 self.listenerNameWarnCheckBox = QCheckBox(self.tr('Warn if listener name missing')) self.listenerNameWarnCheckBox.setChecked(self.tmpPref["pref"]["general"]["listenerNameWarn"]) appPrefGrid.addWidget(self.listenerNameWarnCheckBox, n, 0) n = n+1 self.sessionLabelWarnCheckBox = QCheckBox(self.tr('Warn if session label missing')) self.sessionLabelWarnCheckBox.setChecked(self.tmpPref["pref"]["general"]["sessionLabelWarn"]) appPrefGrid.addWidget(self.sessionLabelWarnCheckBox, n, 0) n = n+1 self.dpCorrCheckBox = QCheckBox(self.tr('d-prime correction')) self.dpCorrCheckBox.setChecked(self.tmpPref['pref']['general']['dprimeCorrection']) self.dpCorrCheckBox.setWhatsThis(self.tr("If checked, when automatically processing result files, convert hit rates of 0 and 1 to 1/2N and 1-1/(2N) respectively, where N is the number of trials, to avoid infinite values of d'")) appPrefGrid.addWidget(self.dpCorrCheckBox, n, 0) n = n+1 self.recursionLimitLabel = QLabel(self.tr('Max Recursion Depth (requires restart):')) appPrefGrid.addWidget(self.recursionLimitLabel, n, 0) self.recursionLimitWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["general"]["maxRecursionDepth"])) self.recursionLimitWidget.setValidator(QIntValidator(self)) appPrefGrid.addWidget(self.recursionLimitWidget, n, 1) n = n+1 n = n+1 self.startupCommandLabel = QLabel(self.tr('Execute command at startup:')) appPrefGrid.addWidget(self.startupCommandLabel, n, 0) self.startupCommandWidget = QLineEdit(self.tmpPref["pref"]["general"]["startupCommand"]) appPrefGrid.addWidget(self.startupCommandWidget, n, 1) n = n+1 self.appPrefWidget.setLayout(appPrefGrid) self.appPrefWidget.layout().setSizeConstraint(QLayout.SetFixedSize) #SOUND PREF soundPrefGrid = QGridLayout() n = 0 self.playChooser = QComboBox() self.playChooser.addItems(self.parent().prm['appData']['available_play_commands']) self.playChooser.setCurrentIndex(self.playChooser.findText(self.tmpPref['pref']['sound']['playCommandType'])) self.playChooser.currentIndexChanged[int].connect(self.onPlayChooserChange) self.playChooserLabel = QLabel(self.tr('Play Command:')) soundPrefGrid.addWidget(self.playChooserLabel, 0, 0) soundPrefGrid.addWidget(self.playChooser, 0, 1) n = n+1 self.playCommandLabel = QLabel(self.tr('Command:')) soundPrefGrid.addWidget(self.playCommandLabel, n, 0) self.playCommandWidget = QLineEdit(self.tmpPref['pref']['sound']['playCommand']) if self.playChooser.currentText() != self.tr('custom'): self.playCommandWidget.setReadOnly(True) soundPrefGrid.addWidget(self.playCommandWidget, n, 1) n = n+1 foo = self.playChooser.currentText() if foo != self.tr('custom'): self.playCommandLabel.hide() self.playCommandWidget.hide() #if alsaaudio is selected, provide device list chooser if self.parent().prm["appData"]["alsaaudioAvailable"] == True: self.alsaaudioPlaybackCardList = self.listAlsaaudioPlaybackCards() self.alsaaudioDeviceLabel = QLabel(self.tr('Device:')) soundPrefGrid.addWidget(self.alsaaudioDeviceLabel, n, 0) self.alsaaudioDeviceChooser = QComboBox() self.alsaaudioDeviceChooser.addItems(self.alsaaudioPlaybackCardList) self.alsaaudioDeviceChooser.setCurrentIndex(self.alsaaudioDeviceChooser.findText(self.tmpPref["pref"]["sound"]["alsaaudioDevice"])) soundPrefGrid.addWidget(self.alsaaudioDeviceChooser, n, 1) n = n+1 if self.tmpPref['pref']['sound']['playCommandType'] != "alsaaudio": self.alsaaudioDeviceLabel.hide() self.alsaaudioDeviceChooser.hide() #if pyaudio is selected, provide device list chooser if self.parent().prm["appData"]["pyaudioAvailable"] == True: self.listPyaudioPlaybackDevices() self.pyaudioDeviceLabel = QLabel(self.tr('Device:')) soundPrefGrid.addWidget(self.pyaudioDeviceLabel, n, 0) self.pyaudioDeviceChooser = QComboBox() self.pyaudioDeviceChooser.addItems(self.pyaudioDeviceListName) try: self.pyaudioDeviceChooser.setCurrentIndex(self.pyaudioDeviceListIdx.index(self.tmpPref["pref"]["sound"]["pyaudioDevice"])) except: self.tmpPref["pref"]["sound"]["pyaudioDevice"] = self.pyaudioDeviceListIdx[0] self.parent().prm["pref"]["sound"]["pyaudioDevice"] = self.pyaudioDeviceListIdx[0] self.pyaudioDeviceChooser.setCurrentIndex(self.pyaudioDeviceListIdx.index(self.tmpPref["pref"]["sound"]["pyaudioDevice"])) soundPrefGrid.addWidget(self.pyaudioDeviceChooser, n, 1) n = n+1 if self.tmpPref['pref']['sound']['playCommandType'] != "pyaudio": self.pyaudioDeviceLabel.hide() self.pyaudioDeviceChooser.hide() if self.parent().prm["appData"]["alsaaudioAvailable"] == True or self.parent().prm["appData"]["pyaudioAvailable"] == True: self.bufferSizeLabel = QLabel(self.tr('Buffer Size (samples):')) soundPrefGrid.addWidget(self.bufferSizeLabel, n, 0) self.bufferSizeWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["sound"]["bufferSize"])) self.bufferSizeWidget.setValidator(QIntValidator(self)) soundPrefGrid.addWidget(self.bufferSizeWidget, n, 1) n = n+1 if self.tmpPref['pref']['sound']['playCommandType'] not in ["alsaaudio", "pyaudio"]: self.bufferSizeLabel.hide() self.bufferSizeWidget.hide() self.samplerateLabel = QLabel(self.tr('Default Sampling Rate:')) soundPrefGrid.addWidget(self.samplerateLabel, n, 0) self.samplerateWidget = QLineEdit(self.tmpPref["pref"]["sound"]["defaultSampleRate"]) #self.samplerateWidget.setValidator(QIntValidator(self)) soundPrefGrid.addWidget(self.samplerateWidget, n, 1) n = n+1 self.nbitsLabel = QLabel(self.tr('Default Bits:')) self.nbitsChooser = QComboBox() self.nbitsChooser.addItems(self.parent().prm["nBitsChoices"]) self.nbitsChooser.setCurrentIndex(self.parent().prm["nBitsChoices"].index(self.tmpPref["pref"]["sound"]["defaultNBits"])) soundPrefGrid.addWidget(self.nbitsLabel, n, 0) soundPrefGrid.addWidget(self.nbitsChooser, n, 1) n = n+1 self.wavmanagerLabel = QLabel(self.tr('Wav Manager (requires restart):')) self.wavmanagerChooser = QComboBox() self.wavmanagerChooser.addItems(self.parent().prm['appData']['wavmanagers']) self.wavmanagerChooser.setCurrentIndex(self.wavmanagerChooser.findText(self.tmpPref['pref']['sound']['wavmanager'])) soundPrefGrid.addWidget(self.wavmanagerLabel, n, 0) soundPrefGrid.addWidget(self.wavmanagerChooser, n, 1) n = n+1 self.writewav = QCheckBox(self.tr('Write wav file')) self.writewav.setChecked(self.tmpPref["pref"]["sound"]["writewav"]) soundPrefGrid.addWidget(self.writewav, n, 0) n = n+1 self.writeSndSeqSegments = QCheckBox(self.tr('Write sound sequence segments wavs')) self.writeSndSeqSegments.setChecked(self.tmpPref["pref"]["sound"]["writeSndSeqSegments"]) soundPrefGrid.addWidget(self.writeSndSeqSegments, n, 0) n = n+1 self.appendSilenceLabel = QLabel(self.tr('Append silence to each sound (ms):')) soundPrefGrid.addWidget(self.appendSilenceLabel, n, 0) self.appendSilenceWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["sound"]["appendSilence"])) soundPrefGrid.addWidget(self.appendSilenceWidget, n, 1) n = n+1 self.soundPrefWidget.setLayout(soundPrefGrid) self.soundPrefWidget.layout().setSizeConstraint(QLayout.SetFixedSize) # NOTIFICATION PREF notificationPrefGrid = QGridLayout() n = 0 self.playEndMessage = QCheckBox(self.tr('Play End Message')) self.playEndMessage.setChecked(self.tmpPref["pref"]["general"]["playEndMessage"]) notificationPrefGrid.addWidget(self.playEndMessage, n, 0) self.endMessageButton = QPushButton(self.tr("Choose Wav"), self) self.endMessageButton.clicked.connect(self.onClickEndMessageButton) notificationPrefGrid.addWidget(self.endMessageButton, n, 1) n = n+1 notificationPrefGrid.addItem(QSpacerItem(20,20,QSizePolicy.Expanding), n, 0) n = n+1 self.nBlocksLabel = QLabel(self.tr('blocks before end of experiment:')) notificationPrefGrid.addWidget(self.nBlocksLabel, n, 1) self.nBlocksWidget = QLineEdit(self.currLocale.toString(self.tmpPref['pref']['email']['nBlocksNotify'])) notificationPrefGrid.addWidget(self.nBlocksWidget, n, 0) n = n+1 self.emailNotify = QCheckBox(self.tr('Send Notification e-mail')) self.emailNotify.setChecked(self.tmpPref["pref"]["email"]["notifyEnd"]) notificationPrefGrid.addWidget(self.emailNotify, n, 0) n = n+1 self.nBlocksCustomCommandLabel = QLabel(self.tr('Execute custom command:')) notificationPrefGrid.addWidget(self.nBlocksCustomCommandLabel, n, 0) self.nBlocksCustomCommandWidget = QLineEdit(self.tmpPref["pref"]["general"]["nBlocksCustomCommand"]) notificationPrefGrid.addWidget(self.nBlocksCustomCommandWidget, n, 1) n = n+1 notificationPrefGrid.addItem(QSpacerItem(20,20,QSizePolicy.Expanding), n, 0) n = n+1 self.atEndLabel = QLabel(self.tr('At the end of the experiment:')) notificationPrefGrid.addWidget(self.atEndLabel, n, 0) n = n+1 self.sendData = QCheckBox(self.tr('Send data via e-mail')) self.sendData.setChecked(self.tmpPref["pref"]["email"]["sendData"]) notificationPrefGrid.addWidget(self.sendData, n, 0) n = n+1 self.atEndCustomCommandLabel = QLabel(self.tr('Execute custom command:')) notificationPrefGrid.addWidget(self.atEndCustomCommandLabel, n, 0) self.atEndCustomCommandWidget = QLineEdit(self.tmpPref["pref"]["general"]["atEndCustomCommand"]) notificationPrefGrid.addWidget(self.atEndCustomCommandWidget, n, 1) n = n+1 notificationPrefGrid.addItem(QSpacerItem(20,20,QSizePolicy.Expanding), n, 0) n = n+1 self.serverLabel = QLabel(self.tr('Outgoing server (SMTP):')) notificationPrefGrid.addWidget(self.serverLabel, n, 0) self.serverWidget = QLineEdit(self.tmpPref['pref']['email']['SMTPServer']) notificationPrefGrid.addWidget(self.serverWidget, n, 1) n = n+1 self.serverPortLabel = QLabel(self.tr('Port:')) notificationPrefGrid.addWidget(self.serverPortLabel, n, 0) self.serverPortWidget = QLineEdit(self.currLocale.toString(self.tmpPref['pref']['email']['SMTPServerPort'])) self.serverPortWidget.setValidator(QIntValidator(self)) notificationPrefGrid.addWidget(self.serverPortWidget, n, 1) n = n+1 self.serverSecurityLabel = QLabel(self.tr('Security:')) notificationPrefGrid.addWidget(self.serverSecurityLabel, n, 0) self.serverSecurityChooser = QComboBox() self.serverSecurityChooser.addItems(["TLS/SSL (a)", "TLS/SSL (b)", "none"]) self.serverSecurityChooser.setCurrentIndex(self.serverSecurityChooser.findText(self.tmpPref['pref']['email']['SMTPServerSecurity'])) notificationPrefGrid.addWidget(self.serverSecurityChooser, n, 1) n = n+1 self.serverRequiresAuthCheckBox = QCheckBox(self.tr('Server requires authentication')) self.serverRequiresAuthCheckBox.setChecked(self.tmpPref["pref"]["email"]["serverRequiresAuthentication"]) notificationPrefGrid.addWidget(self.serverRequiresAuthCheckBox, n, 0, 1, 2) n = n+1 self.usernameLabel = QLabel(self.tr('Username:'******'pref']['email']['fromUsername']) notificationPrefGrid.addWidget(self.usernameWidget, n, 1) n = n+1 self.passwordLabel = QLabel(self.tr('Password:'******'pref']['email']['fromPassword']) self.passwordWidget.setEchoMode(QLineEdit.Password) notificationPrefGrid.addWidget(self.passwordWidget, n, 1) n = n+1 self.passwordWarningLabel = QLabel(self.tr('Password is NOT stored safely (see manual), use at your own risk!')) notificationPrefGrid.addWidget(self.passwordWarningLabel, n, 0, 1, 2) n = n+1 self.testEmailButton = QPushButton(self.tr("Send test e-mail"), self) self.testEmailButton.clicked.connect(self.onClickTestEmailButton) self.testEmailButton.setToolTip(self.tr("Send a test e-mail")) notificationPrefGrid.addWidget(self.testEmailButton, n, 0, 1, 2) self.notificationPrefWidget.setLayout(notificationPrefGrid) self.notificationPrefWidget.layout().setSizeConstraint(QLayout.SetFixedSize) ##--#--#--#--#-- # EEG PREF GRID eegPrefGrid = QGridLayout() n = 0 self.ONTriggerLabel = QLabel(self.tr('ON Trigger:')) eegPrefGrid.addWidget(self.ONTriggerLabel, n, 0) self.ONTriggerWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["general"]["ONTrigger"])) eegPrefGrid.addWidget(self.ONTriggerWidget, n, 1) n = n+1 self.OFFTriggerLabel = QLabel(self.tr('OFF Trigger:')) eegPrefGrid.addWidget(self.OFFTriggerLabel, n, 0) self.OFFTriggerWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["general"]["OFFTrigger"])) eegPrefGrid.addWidget(self.OFFTriggerWidget, n, 1) n = n+1 self.triggerDurLabel = QLabel(self.tr('Trigger Duration (ms):')) eegPrefGrid.addWidget(self.triggerDurLabel, n, 0) self.triggerDurWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["general"]["triggerDur"])) eegPrefGrid.addWidget(self.triggerDurWidget, n, 1) self.eegPrefWidget.setLayout(eegPrefGrid) self.eegPrefWidget.layout().setSizeConstraint(QLayout.SetFixedSize) # ........................ self.tabWidget.addTab(self.appPrefWidget, self.tr("Genera&l")) self.tabWidget.addTab(self.soundPrefWidget, self.tr("Soun&d")) self.tabWidget.addTab(self.notificationPrefWidget, self.tr("Notification&s")) self.tabWidget.addTab(self.eegPrefWidget, self.tr("EE&G")) buttonBox = QDialogButtonBox(QDialogButtonBox.Apply|QDialogButtonBox.Ok|QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) buttonBox.button(QDialogButtonBox.Apply).clicked.connect(self.permanentApply) layout = QVBoxLayout() layout.addWidget(self.tabWidget) layout.addWidget(buttonBox) self.setLayout(layout) def onLanguageChooserChange(self): for i in range(self.countryChooser.count()): self.countryChooser.removeItem(0) self.countryChooser.addItems(self.parent().prm['appData']['available_countries'][self.languageChooser.currentText()]) def onResponseBoxLanguageChooserChange(self): for i in range(self.responseBoxCountryChooser.count()): self.responseBoxCountryChooser.removeItem(0) self.responseBoxCountryChooser.addItems(self.parent().prm['appData']['available_countries'][self.responseBoxLanguageChooser.currentText()]) def onPlayChooserChange(self): foo = self.playChooser.currentText() if foo != self.tr('custom'): self.playCommandLabel.hide() self.playCommandWidget.hide() self.playCommandWidget.setText(foo) self.playCommandWidget.setReadOnly(True) else: self.playCommandWidget.show() self.playCommandLabel.show() self.playCommandWidget.setReadOnly(False) if self.parent().prm["appData"]["alsaaudioAvailable"] == True: if foo == "alsaaudio": self.alsaaudioDeviceLabel.show() self.alsaaudioDeviceChooser.show() else: self.alsaaudioDeviceLabel.hide() self.alsaaudioDeviceChooser.hide() if self.parent().prm["appData"]["pyaudioAvailable"] == True: if foo == "pyaudio": self.pyaudioDeviceLabel.show() self.pyaudioDeviceChooser.show() else: self.pyaudioDeviceLabel.hide() self.pyaudioDeviceChooser.hide() if self.parent().prm["appData"]["alsaaudioAvailable"] == True or self.parent().prm["appData"]["pyaudioAvailable"] == True: if foo in ["alsaaudio", "pyaudio"]: self.bufferSizeLabel.show() self.bufferSizeWidget.show() else: self.bufferSizeLabel.hide() self.bufferSizeWidget.hide() def onClickEndMessageButton(self): dialog = wavListDialog(self) if dialog.exec_(): self.wavsList = dialog.wavsList self.wavsPref = {} self.wavsPref['endMessageFiles'] = [] self.wavsPref['endMessageFilesUse'] = [] self.wavsPref['endMessageFilesID'] = [] self.wavsPref['endMessageLevels'] = [] keys = sorted(self.wavsList.keys()) for key in keys: self.wavsPref['endMessageFiles'].append(str(self.wavsList[key]['file'])) self.wavsPref['endMessageFilesUse'].append(self.wavsList[key]['use']) self.wavsPref['endMessageLevels'].append(self.wavsList[key]['level']) self.wavsPref['endMessageFilesID'].append(key) def onClickTestEmailButton(self): self.mailer.sendTestEmail() def popMailerMessage(self, msg, msgtype): if msgtype == 'critical': QMessageBox.critical(self, self.tr("Error"), msg) elif msgtype == 'warning': QMessageBox.warning(self, self.tr("Warning"), msg) elif msgtype == 'information': QMessageBox.information(self, self.tr("Information"), msg) def tryApply(self): self.tmpPref['pref']['language'] = self.tr(self.languageChooser.currentText()) self.tmpPref['pref']['country'] = self.tr(self.countryChooser.currentText()) self.tmpPref['pref']['responseBoxLanguage'] = self.tr(self.responseBoxLanguageChooser.currentText()) self.tmpPref['pref']['responseBoxCountry'] = self.tr(self.responseBoxCountryChooser.currentText()) self.tmpPref['pref']['general']['csvSeparator'] = self.csvSeparatorWidget.text() self.tmpPref['pref']['general']['ONTrigger'] = self.currLocale.toInt(self.ONTriggerWidget.text())[0] self.tmpPref['pref']['general']['OFFTrigger'] = self.currLocale.toInt(self.OFFTriggerWidget.text())[0] self.tmpPref['pref']['general']['triggerDur'] = self.currLocale.toDouble(self.triggerDurWidget.text())[0] self.tmpPref['pref']['general']['maxRecursionDepth'] = self.currLocale.toInt(self.recursionLimitWidget.text())[0] self.tmpPref['pref']['general']['startupCommand'] = self.startupCommandWidget.text() self.tmpPref['pref']['sound']['playCommand'] = self.tr(self.playCommandWidget.text()) self.tmpPref['pref']['sound']['playCommandType'] = self.tr(self.playChooser.currentText()) if self.parent().prm["appData"]["alsaaudioAvailable"] == True: self.tmpPref['pref']['sound']['alsaaudioDevice'] = self.alsaaudioDeviceChooser.currentText() if self.parent().prm["appData"]["pyaudioAvailable"] == True: self.tmpPref['pref']['sound']['pyaudioDevice'] = self.pyaudioDeviceListIdx[self.pyaudioDeviceChooser.currentIndex()] self.tmpPref['pref']['sound']['wavmanager'] = str(self.wavmanagerChooser.currentText()) if self.parent().prm["appData"]["alsaaudioAvailable"] == True or self.parent().prm["appData"]["pyaudioAvailable"] == True: self.tmpPref['pref']['sound']['bufferSize'] = self.currLocale.toInt(self.bufferSizeWidget.text())[0] self.tmpPref['pref']['sound']['defaultSampleRate'] = self.samplerateWidget.text() self.tmpPref['pref']['sound']['defaultNBits'] = self.nbitsChooser.currentText() self.tmpPref['pref']['sound']['appendSilence'] = self.currLocale.toInt(self.appendSilenceWidget.text())[0] self.tmpPref["pref"]["email"]["nBlocksNotify"] = self.currLocale.toInt(self.nBlocksWidget.text())[0] self.tmpPref["pref"]["general"]["nBlocksCustomCommand"] = self.nBlocksCustomCommandWidget.text() self.tmpPref["pref"]["general"]["atEndCustomCommand"] = self.atEndCustomCommandWidget.text() self.tmpPref["pref"]["email"]['SMTPServer'] = self.serverWidget.text() self.tmpPref["pref"]["email"]['SMTPServerPort'] = self.currLocale.toInt(self.serverPortWidget.text())[0] self.tmpPref["pref"]["email"]['fromUsername'] = self.usernameWidget.text() self.tmpPref["pref"]["email"]['SMTPServerSecurity'] = self.serverSecurityChooser.currentText() self.tmpPref["pref"]["general"]["endMessageFiles"] = self.wavsPref['endMessageFiles'] self.tmpPref["pref"]["general"]["endMessageFilesUse"] = self.wavsPref['endMessageFilesUse'] self.tmpPref["pref"]["general"]["endMessageFilesID"] = self.wavsPref['endMessageFilesID'] self.tmpPref["pref"]["general"]["endMessageLevels"] = self.wavsPref['endMessageLevels'] self.tmpPref["pref"]["email"]['fromPassword'] = self.passwordWidget.text() if self.writewav.isChecked(): self.tmpPref['pref']['sound']['writewav'] = True else: self.tmpPref['pref']['sound']['writewav'] = False if self.writeSndSeqSegments.isChecked(): self.tmpPref['pref']['sound']['writeSndSeqSegments'] = True else: self.tmpPref['pref']['sound']['writeSndSeqSegments'] = False if self.dpCorrCheckBox.isChecked(): self.tmpPref['pref']['general']['dprimeCorrection'] = True else: self.tmpPref['pref']['general']['dprimeCorrection'] = False if self.listenerNameWarnCheckBox.isChecked(): self.tmpPref['pref']['general']['listenerNameWarn'] = True else: self.tmpPref['pref']['general']['listenerNameWarn'] = False if self.sessionLabelWarnCheckBox.isChecked(): self.tmpPref['pref']['general']['sessionLabelWarn'] = True else: self.tmpPref['pref']['general']['sessionLabelWarn'] = False if self.emailNotify.isChecked(): self.tmpPref['pref']['email']['notifyEnd'] = True else: self.tmpPref['pref']['email']['notifyEnd'] = False if self.sendData.isChecked(): self.tmpPref['pref']['email']['sendData'] = True else: self.tmpPref['pref']['email']['sendData'] = False if self.serverRequiresAuthCheckBox.isChecked(): self.tmpPref['pref']['email']['serverRequiresAuthentication'] = True else: self.tmpPref['pref']['email']['serverRequiresAuthentication'] = False if self.playEndMessage.isChecked(): self.tmpPref['pref']['general']['playEndMessage'] = True else: self.tmpPref['pref']['general']['playEndMessage'] = False if self.tmpPref['pref']['email']['notifyEnd'] == True or self.tmpPref['pref']['email']['sendData'] == True: if checkUsernameValid(self.tmpPref["pref"]["email"]['fromUsername']) == False: errMsg = self.tr("Username invalid. Disabling sending e-mails.") QMessageBox.warning(self, self.tr("Warning"), errMsg) self.emailNotify.setChecked(False) self.sendData.setChecked(False) self.tmpPref['pref']['email']['notifyEnd'] = False self.tmpPref['pref']['email']['sendData'] = False elif checkServerValid(self.tmpPref["pref"]["email"]['SMTPServer']) == False: errMsg = self.tr("SMTP server name invalid. Disabling sending e-mails.") QMessageBox.warning(self, self.tr("Warning"), errMsg) self.emailNotify.setChecked(False) self.sendData.setChecked(False) self.tmpPref['pref']['email']['notifyEnd'] = False self.tmpPref['pref']['email']['sendData'] = False def revertChanges(self): self.languageChooser.setCurrentIndex(self.languageChooser.findText(self.tmpPref['pref']['language'])) self.countryChooser.setCurrentIndex(self.countryChooser.findText(self.tmpPref['pref']['country'])) self.responseBoxLanguageChooser.setCurrentIndex(self.responseBoxLanguageChooser.findText(self.tmpPref['pref']['responseBoxLanguage'])) self.responseBoxCountryChooser.setCurrentIndex(self.responseBoxCountryChooser.findText(self.tmpPref['pref']['responseBoxCountry'])) self.csvSeparatorWidget.setText(self.tmpPref['pref']['general']['csvSeparator']) self.ONTriggerWidget.setText(self.currLocale.toString(self.tmpPref['pref']['general']['ONTrigger'])) self.OFFTriggerWidget.setText(self.currLocale.toString(self.tmpPref['pref']['general']['OFFTrigger'])) self.triggerDurWidget.setText(self.currLocale.toString(self.tmpPref['pref']['general']['triggerDur'])) self.recursionLimitWidget.setText(self.currLocale.toString(self.tmpPref['pref']['general']['maxRecursionDepth'])) self.startupCommandWidget.setText(self.tmpPref['pref']['general']['startupCommand']) self.playChooser.setCurrentIndex(self.playChooser.findText(self.tmpPref['pref']['sound']['playCommandType'])) if self.parent().prm["appData"]["alsaaudioAvailable"] == True: self.alsaaudioDeviceChooser.setCurrentIndex(self.alsaaudioDeviceChooser.findText(self.tmpPref['pref']['sound']['alsaaudioDevice'])) if self.parent().prm["appData"]["pyaudioAvailable"] == True: self.pyaudioDeviceChooser.setCurrentIndex(self.pyaudioDeviceListIdx.index(self.tmpPref['pref']['sound']['pyaudioDevice'])) self.wavmanagerChooser.setCurrentIndex(self.wavmanagerChooser.findText(self.tmpPref['pref']['sound']['wavmanager'])) self.playCommandWidget.setText(self.tmpPref['pref']['sound']['playCommand']) if self.parent().prm["appData"]["alsaaudioAvailable"] == True or self.parent().prm["appData"]["pyaudioAvailable"] == True: self.bufferSizeWidget.setText(self.currLocale.toString(self.tmpPref['pref']['sound']['bufferSize'])) self.samplerateWidget.setText(self.tmpPref['pref']['sound']['defaultSampleRate']) self.nbitsChooser.setCurrentIndex(self.nbitsChooser.findText(self.tmpPref['pref']['sound']['defaultNBits'])) self.appendSilenceWidget.setText(self.currLocale.toString(self.tmpPref['pref']['sound']['appendSilence'])) self.nBlocksWidget.setText(self.currLocale.toString(self.tmpPref['pref']['email']['nBlocksNotify'])) self.nBlocksCustomCommandWidget.setText( self.tmpPref["pref"]["general"]["nBlocksCustomCommand"]) self.atEndCustomCommandWidget.setText( self.tmpPref["pref"]["general"]["nBlocksCustomCommand"]) self.serverWidget.setText(self.tmpPref['pref']['email']['SMTPServer']) self.serverPortWidget.setText(self.currLocale.toString(self.tmpPref['pref']['email']['SMTPServerPort'])) self.usernameWidget.setText(self.tmpPref['pref']['email']['fromUsername']) self.passwordWidget.setText(self.tmpPref['pref']['email']['fromPassword']) self.serverSecurityChooser.setCurrentIndex(self.serverSecurityChooser.findText(self.tmpPref['pref']['email']['SMTPServerSecurity'])) self.wavsPref["endMessageFiles"] = self.tmpPref["pref"]["general"]["endMessageFiles"] self.wavsPref["endMessageFilesUse"] = self.tmpPref["pref"]["general"]["endMessageFilesUse"] self.wavsPref["endMessageFilesID"] = self.tmpPref["pref"]["general"]["endMessageFilesID"] self.wavsPref["endMessageLevels"] = self.tmpPref["pref"]["general"]["endMessageLevels"] if self.playChooser.currentText() != self.tr('custom'): self.playCommandWidget.setReadOnly(True) self.writewav.setChecked(self.tmpPref["pref"]["sound"]["writewav"]) self.writeSndSeqSegments.setChecked(self.tmpPref["pref"]["sound"]["writeSndSeqSegments"]) self.dpCorrCheckBox.setChecked(self.tmpPref["pref"]["general"]["dprimeCorrection"]) self.listenerNameWarnCheckBox.setChecked(self.tmpPref["pref"]["general"]["listenerNameWarn"]) self.sessionLabelWarnCheckBox.setChecked(self.tmpPref["pref"]["general"]["sessionLabelWarn"]) self.emailNotify.setChecked(self.tmpPref["pref"]["email"]["notifyEnd"]) self.sendData.setChecked(self.tmpPref["pref"]["email"]["sendData"]) self.serverRequiresAuthCheckBox.setChecked(self.tmpPref["pref"]["email"]["serverRequiresAuthentication"]) self.playEndMessage.setChecked(self.tmpPref["pref"]["general"]["playEndMessage"]) def permanentApply(self): self.tryApply() if self.parent().prm['pref']['email']['fromPassword'] != self.tmpPref['pref']['email']['fromPassword']: passwd = bytes(self.passwordWidget.text(),'utf-8') encoded_passwd = base64.b64encode(passwd) encoded_passwd = str(encoded_passwd, "utf-8") #passwd = hashlib.sha1(passwd).hexdigest() self.tmpPref["pref"]["email"]['fromPassword'] = encoded_passwd self.passwordWidget.setText(self.tmpPref['pref']['email']['fromPassword']) self.parent().prm['pref'] = copy.deepcopy(self.tmpPref['pref']) f = open(self.parent().prm['prefFile'], 'wb') pickle.dump(self.parent().prm['pref'], f) f.close() def tabChanged(self): self.tryApply() if self.tmpPref['pref'] != self.parent().prm['pref']: reply = QMessageBox.warning(self, self.tr("Warning"), self.tr('There are unsaved changes. Apply Changes?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if reply == QMessageBox.Yes: self.permanentApply() else: self.tmpPref['pref'] = copy.deepcopy(self.parent().prm['pref']) self.revertChanges() def listAlsaaudioPlaybackCards(self): playbackCardList = [] for card in alsaaudio.cards(): try: alsaaudio.PCM(type=alsaaudio.PCM_PLAYBACK, mode=alsaaudio.PCM_NORMAL, card=card) playbackCardList.append(card) except: pass return playbackCardList def listPyaudioPlaybackDevices(self): self.pyaudioHostApiListName = [] self.pyaudioHostApiListIdx = [] self.pyaudioDeviceListName = [] self.pyaudioDeviceListIdx = [] paManager = pyaudio.PyAudio() nDevices = paManager.get_device_count() nApi = paManager.get_host_api_count() for i in range(nApi): self.pyaudioHostApiListName.append(paManager.get_host_api_info_by_index(i)['name']) self.pyaudioHostApiListIdx.append(paManager.get_host_api_info_by_index(i)['index']) for i in range(nDevices): thisDevInfo = paManager.get_device_info_by_index(i) if thisDevInfo["maxOutputChannels"] > 0: self.pyaudioDeviceListName.append(thisDevInfo["name"] + ' - ' + self.pyaudioHostApiListName[thisDevInfo["hostApi"]]) self.pyaudioDeviceListIdx.append(thisDevInfo["index"]) return
class SchemeSelector(QWidget): currentChanged = pyqtSignal() changed = pyqtSignal() def __init__(self, parent=None): super(SchemeSelector, self).__init__(parent) layout = QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.label = QLabel() self.scheme = QComboBox() self.menuButton = QPushButton(flat=True) menu = QMenu(self.menuButton) self.menuButton.setMenu(menu) layout.addWidget(self.label) layout.addWidget(self.scheme) layout.addWidget(self.menuButton) layout.addStretch(1) # action generator def act(slot, icon=None): a = QAction(self, triggered=slot) self.addAction(a) icon and a.setIcon(icons.get(icon)) return a # add action a = self.addAction_ = act(self.slotAdd, 'list-add') menu.addAction(a) # remove action a = self.removeAction = act(self.slotRemove, 'list-remove') menu.addAction(a) # rename action a = self.renameAction = act(self.slotRename, 'document-edit') menu.addAction(a) menu.addSeparator() # import action a = self.importAction = act(self.slotImport, 'document-open') menu.addAction(a) # export action a = self.exportAction = act(self.slotExport, 'document-save-as') menu.addAction(a) self.scheme.currentIndexChanged.connect(self.slotSchemeChanged) app.translateUI(self) def translateUI(self): self.label.setText(_("Scheme:")) self.menuButton.setText(_("&Menu")) self.addAction_.setText(_("&Add...")) self.removeAction.setText(_("&Remove")) self.renameAction.setText(_("Re&name...")) self.importAction.setText(_("&Import...")) self.exportAction.setText(_("&Export...")) def slotSchemeChanged(self, index): """Called when the Scheme combobox is changed by the user.""" self.disableDefault(self.scheme.itemData(index) == 'default') self.currentChanged.emit() self.changed.emit() def disableDefault(self, val): self.removeAction.setDisabled(val) self.renameAction.setDisabled(val) def schemes(self): """Returns the list with internal names of currently available schemes.""" return [self.scheme.itemData(i) for i in range(self.scheme.count())] def currentScheme(self): """Returns the internal name of the currently selected scheme""" return self.scheme.itemData(self.scheme.currentIndex()) def insertSchemeItem(self, name, scheme): for i in range(1, self.scheme.count()): n = self.scheme.itemText(i) if n.lower() > name.lower(): self.scheme.insertItem(i, name, scheme) break else: self.scheme.addItem(name, scheme) def addScheme(self, name): num, key = 1, 'user1' while key in self.schemes() or key in self._schemesToRemove: num += 1 key = 'user{0}'.format(num) self.insertSchemeItem(name, key) self.scheme.setCurrentIndex(self.scheme.findData(key)) return key def slotAdd(self): name, ok = QInputDialog.getText( self, app.caption(_("Add Scheme")), _("Please enter a name for the new scheme:")) if ok: self.addScheme(name) def slotRemove(self): index = self.scheme.currentIndex() scheme = self.scheme.itemData(index) if scheme == 'default': return # default can not be removed self._schemesToRemove.add(scheme) self.scheme.removeItem(index) def slotRename(self): index = self.scheme.currentIndex() name = self.scheme.itemText(index) scheme = self.scheme.itemData(index) newName, ok = QInputDialog.getText(self, _("Rename"), _("New name:"), text=name) if ok: self.scheme.blockSignals(True) self.scheme.removeItem(index) self.insertSchemeItem(newName, scheme) self.scheme.setCurrentIndex(self.scheme.findData(scheme)) self.scheme.blockSignals(False) self.changed.emit() def slotImport(self): filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"), _("All Files")) caption = app.caption(_("dialog title", "Import color theme")) filename = QFileDialog.getOpenFileName(self, caption, QDir.homePath(), filetypes) if filename: self.parent().import_(filename) def slotExport(self): name = self.scheme.currentText() filetypes = "{0} (*.xml);;{1} (*)".format(_("XML Files"), _("All Files")) caption = app.caption( _("dialog title", "Export {name}").format(name=name)) path = os.path.join(QDir.homePath(), name + '.xml') filename = QFileDialog.getSaveFileName(self, caption, path, filetypes) if filename: if os.path.splitext(filename)[1] != '.xml': filename += '.xml' self.parent().export(name, filename) def loadSettings(self, currentKey, namesGroup): # don't mark schemes for removal anymore self._schemesToRemove = set() s = QSettings() cur = s.value(currentKey, "default", type("")) # load the names for the shortcut schemes s.beginGroup(namesGroup) block = self.scheme.blockSignals(True) self.scheme.clear() self.scheme.addItem(_("Default"), "default") lst = [(s.value(key, key, type("")), key) for key in s.childKeys()] for name, key in sorted(lst, key=lambda f: f[0].lower()): self.scheme.addItem(name, key) # find out index index = self.scheme.findData(cur) self.disableDefault(cur == 'default') self.scheme.setCurrentIndex(index) self.scheme.blockSignals(block) self.currentChanged.emit() def saveSettings(self, currentKey, namesGroup, removePrefix=None): # first save new scheme names s = QSettings() s.beginGroup(namesGroup) for i in range(self.scheme.count()): if self.scheme.itemData(i) != 'default': s.setValue(self.scheme.itemData(i), self.scheme.itemText(i)) for scheme in self._schemesToRemove: s.remove(scheme) s.endGroup() if removePrefix: for scheme in self._schemesToRemove: s.remove("{0}/{1}".format(removePrefix, scheme)) # then save current scheme = self.currentScheme() s.setValue(currentKey, scheme) # clean up self._schemesToRemove = set()
class SchemeSelector(QWidget): currentChanged = pyqtSignal() changed = pyqtSignal() def __init__(self, parent=None): super(SchemeSelector, self).__init__(parent) layout = QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.label = QLabel(_("Scheme:")) self.scheme = QComboBox() self.label.setBuddy(self.scheme) self.add = QPushButton(icons.get('list-add'), '') self.remove = QPushButton(icons.get('list-remove'), '') layout.addWidget(self.label) layout.addWidget(self.scheme) layout.addWidget(self.add) layout.addWidget(self.remove) self.scheme.currentIndexChanged.connect(self.slotSchemeChanged) self.add.clicked.connect(self.addClicked) self.remove.clicked.connect(self.removeClicked) app.translateUI(self) def translateUI(self): self.label.setText(_("Scheme:")) self.add.setText(_("New Scheme", "&New...")) self.remove.setText(_("&Remove")) def slotSchemeChanged(self, index): """Called when the Scheme combobox is changed by the user.""" self.remove.setEnabled(bool(index)) self.currentChanged.emit() self.changed.emit() def schemes(self): """Returns the list with internal names of currently available schemes.""" return self._schemes def currentScheme(self): """Returns the internal name of the currently selected scheme""" return self._schemes[self.scheme.currentIndex()] def removeClicked(self): index = self.scheme.currentIndex() if index == 0: return # default can not be removed self._schemesToRemove.add(self._schemes[index]) del self._schemes[index] del self._schemeNames[index] self.scheme.removeItem(index) def addClicked(self): name, ok = QInputDialog.getText(self, app.caption("Add Scheme"), _("Please enter a name for the new scheme:")) if not ok: return num, key = 1, 'user1' while key in self._schemes or key in self._schemesToRemove: num += 1 key = 'user{0}'.format(num) self._schemes.append(key) self._schemeNames.append(name) self.scheme.addItem(name) self.scheme.setCurrentIndex(self.scheme.count() - 1) def loadSettings(self, currentKey, namesGroup): # dont mark schemes for removal anymore self._schemesToRemove = set() s = QSettings() cur = s.value(currentKey, "default") # load the names for the shortcut schemes s.beginGroup(namesGroup) self._schemes = ["default"] self._schemeNames = [_("Default")] for key in s.childKeys(): self._schemes.append(key) self._schemeNames.append(s.value(key, key)) block = self.scheme.blockSignals(True) self.scheme.clear() self.scheme.addItems(self._schemeNames) # find out index index = self._schemes.index(cur) if cur in self._schemes else 0 self.remove.setEnabled(bool(index)) self.scheme.setCurrentIndex(index) self.scheme.blockSignals(block) self.currentChanged.emit() def saveSettings(self, currentKey, namesGroup, removePrefix=None): # first save new scheme names s = QSettings() s.beginGroup(namesGroup) for scheme, name in zip(self._schemes, self._schemeNames)[1:]: s.setValue(scheme, name) # then remove removed schemes for scheme in self._schemesToRemove: s.remove(scheme) s.endGroup() if removePrefix: for scheme in self._schemesToRemove: s.remove("{0}/{1}".format(removePrefix, scheme)) # then save current scheme = self.currentScheme() s.setValue(currentKey, scheme) # clean up self._schemesToRemove = set()
def __CheckCount(self, widget : QtGui.QComboBox): if widget.count() != 2: raise GuiFieldBoolTypeErr(widget, widget.count())
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 SupportingDocumentsWidget(QWidget): """ Widget for managing an entity's supporting documents. It enables listing of documents grouped by tabs depending on type. """ def __init__(self, entity_supporting_document, supporting_doc_model_cls, parent=None): """ Class constructor. :param entity_supporting_document: Object containing information pertaining to document types, parent entity etc. :type entity_supporting_document: EntitySupportingDocument :param supporting_doc_model_cls: Class representing the data model corresponding to the entity supporting document object. :type supporting_doc_model_cls: object :param parent: Parent container widget. :type parent: QWidget """ QWidget.__init__(self, parent) self._init_gui() self._entity_supporting_doc = entity_supporting_document #Container for document type widgets based on lookup id self._doc_type_widgets = {} #Init document manager self.source_document_manager = SourceDocumentManager( self._entity_supporting_doc, supporting_doc_model_cls, self) self._load_document_types() #Connect signals self._btn_add_document.clicked.connect( self._on_add_supporting_document) self._cbo_doc_type.currentIndexChanged.connect( self.on_doc_type_changed) self._doc_tab_container.currentChanged.connect( self.on_tab_doc_type_changed) def _init_gui(self): self._gl = QGridLayout(self) self._label = QLabel(self) self._label.setText(self.tr('Select document type')) self._gl.addWidget(self._label, 0, 0, 1, 1) self._cbo_doc_type = QComboBox(self) self._gl.addWidget(self._cbo_doc_type, 0, 1, 1, 1) self._btn_add_document = QPushButton(self) doc_ico = QIcon(':/plugins/stdm/images/icons/document.png') self._btn_add_document.setIcon(doc_ico) self._btn_add_document.setText(self.tr('Add document...')) self._btn_add_document.setMaximumWidth(200) self._gl.addWidget(self._btn_add_document, 0, 2, 1, 1) self._doc_tab_container = QTabWidget(self) self._gl.addWidget(self._doc_tab_container, 1, 0, 1, 3) self.setMinimumHeight(140) def on_doc_type_changed(self, idx): """ Slot raised when the document types changes. The corresponding widget in the tab container is also selected. :param idx: Item index in the combobox. :type idx: int """ if idx == -1: return self._doc_tab_container.setCurrentIndex(idx) def on_tab_doc_type_changed(self, idx): """ Slot raised when the document types changes. The corresponding widget in the tab container is also selected. :param idx: Item index in the tab widget. :type idx: int """ if idx == -1: return self._cbo_doc_type.setCurrentIndex(idx) def current_document_type(self): """ :return: Returns the currently selected document type in the combobox. :rtype: str """ return self._cbo_doc_type.currentText() def current_document_type_id(self): """ :return: Returns the primary key/id of the currently selected document type in the combobox, else -1 if there is not current item in the combobox :rtype: int """ if not self.current_document_type(): return -1 curr_idx = self._cbo_doc_type.currentIndex() return self._cbo_doc_type.itemData(curr_idx) def count(self): """ :return: Returns the number of document types supported by this widget. :rtype: int """ return self._cbo_doc_type.count() def document_type_containers(self): """ :return: Returns a list of document container widgets for all registered document types. :rtype: list """ return self.source_document_manager.containers.values() def document_type_widget(self, name): """ Searches for the document type widget that corresponds to the given name. :param name: Name of the document type. :type name: str :return: Returns the document widget corresponding to the given type name. :rtype: QWidget """ idx = self._cbo_doc_type.findText(name) if idx == -1: return None rec_id = self._cbo_doc_type.itemData(idx) return self._doc_type_widgets.get(rec_id, None) def _load_document_types(self): #Load document types in the combobox and tab widget vl_cls = entity_model(self._entity_supporting_doc.document_type_entity, entity_only=True) vl_obj = vl_cls() res = vl_obj.queryObject().all() for r in res: #Add to combo self._cbo_doc_type.addItem(r.value, r.id) #Add to tab widget doc_type_widget = _DocumentTypeContainer(self) self._doc_tab_container.addTab(doc_type_widget, r.value) self._doc_type_widgets[r.id] = doc_type_widget #Register container self.source_document_manager.registerContainer( doc_type_widget.container, r.id) def _on_add_supporting_document(self): #Slot raised when the user select to add a supporting document if self.count == 0: return select = self.tr('Select') supporting_docs_str = 'Supporting Documents' title = u'{0} {1} {2}'.format(select, self.current_document_type(), supporting_docs_str) filter_str = u'{0} (*.jpg *.jpeg *.png *.bmp *.tiff *.svg *.pdf)'.format( supporting_docs_str) #Get last path for supporting documents last_path = last_document_path() if last_path is None: last_path = '/home' else: dir = QDir(last_path) if not dir.exists(): last_path = '/home' source_docs = QFileDialog.getOpenFileNames(self, title, last_path, filter_str) doc_type_id = self._cbo_doc_type.itemData( self._cbo_doc_type.currentIndex()) parent_entity = self._entity_supporting_doc.parent_entity for doc in source_docs: self.source_document_manager.insertDocumentFromFile( doc, doc_type_id, parent_entity) #Set last path if len(source_docs) > 0: doc = source_docs[0] fi = QFileInfo(doc) dir_path = fi.absolutePath() set_last_document_path(dir_path)
class RunsDialog(QtHelper.EnhancedQDialog): """ Runs several dialog """ RefreshRepository = pyqtSignal(str) def __init__(self, dialogName, parent = None, iRepo=None, lRepo=None, rRepo=None): """ Constructor """ QtHelper.EnhancedQDialog.__init__(self, parent) self.name = self.tr("Prepare a group of runs") self.projectReady = False self.iRepo = iRepo self.lRepo = lRepo self.rRepo = rRepo self.createDialog() self.createConnections() def createDialog(self): """ Create qt dialog """ self.setWindowTitle( self.name ) mainLayout = QHBoxLayout() layoutTests = QHBoxLayout() layoutRepoTest = QVBoxLayout() self.prjCombo = QComboBox(self) self.prjCombo.setEnabled(False) self.repoTests = QTreeWidget(self) self.repoTests.setFrameShape(QFrame.NoFrame) if USE_PYQT5: self.repoTests.header().setSectionResizeMode(QHeaderView.Stretch) else: self.repoTests.header().setResizeMode(QHeaderView.Stretch) self.repoTests.setHeaderHidden(True) self.repoTests.setContextMenuPolicy(Qt.CustomContextMenu) self.repoTests.setIndentation(10) layoutRepoTest.addWidget(self.prjCombo) layoutRepoTest.addWidget(self.repoTests) self.testsList = QListWidget(self) layoutTests.addLayout( layoutRepoTest ) layoutTests.addWidget( self.testsList ) mainLayout.addLayout( layoutTests ) buttonLayout = QVBoxLayout() self.okButton = QPushButton(self.tr("Execute All"), self) self.okButton.setEnabled(False) self.cancelButton = QPushButton(self.tr("Cancel"), self) self.upButton = QPushButton(self.tr("UP"), self) self.upButton.setEnabled(False) self.downButton = QPushButton(self.tr("DOWN"), self) self.downButton.setEnabled(False) self.clearButton = QPushButton(self.tr("Remove All"), self) self.delButton = QPushButton(self.tr("Remove"), self) self.delButton.setEnabled(False) self.runSimultaneous = QCheckBox(self.tr("Simultaneous Run")) self.schedImmed = QRadioButton(self.tr("Run Immediately")) self.schedImmed.setChecked(True) self.schedAt = QRadioButton(self.tr("Run At:")) self.schedAtDateTimeEdit = QDateTimeEdit(QDateTime.currentDateTime()) self.schedAtDateTimeEdit.setEnabled(False) buttonLayout.addWidget(self.okButton) buttonLayout.addWidget(self.runSimultaneous) buttonLayout.addWidget(self.schedImmed) buttonLayout.addWidget(self.schedAt) buttonLayout.addWidget(self.schedAtDateTimeEdit) buttonLayout.addWidget( self.upButton ) buttonLayout.addWidget( self.downButton ) buttonLayout.addWidget( self.delButton ) buttonLayout.addWidget( self.clearButton ) buttonLayout.addWidget(self.cancelButton) mainLayout.addLayout(buttonLayout) self.setMinimumHeight(400) self.setMinimumWidth(750) self.setLayout(mainLayout) def initProjects(self, projects=[], defaultProject=1): """ Initialize projects """ # init date and time self.schedAtDateTimeEdit.setDateTime(QDateTime.currentDateTime()) self.projectReady = False self.repoTests.clear() self.prjCombo.clear() self.testsList.clear() self.prjCombo.setEnabled(True) # insert data pname = '' for p in projects: self.prjCombo.addItem ( p['name'] ) if defaultProject == p['project_id']: pname = p['name'] for i in xrange(self.prjCombo.count()): item_text = self.prjCombo.itemText(i) if str(pname) == str(item_text): self.prjCombo.setCurrentIndex(i) self.projectReady = True self.RefreshRepository.emit(pname) def initializeTests(self, listing): """ Initialize tests """ self.repoTests.clear() self.testRoot = self.rRepo.Item(repo = self.iRepo.remote(), parent = self.repoTests, txt = "Root", type = QTreeWidgetItem.UserType+10, isRoot = True ) self.testRoot.setSelected(True) self.createRepository(listing=listing, parent=self.testRoot,fileincluded=True) self.repoTests.sortItems(0, Qt.AscendingOrder) self.hideItems(hideTsx=False, hideTpx=False, hideTcx=True, hideTdx=True, hideTxt=True, hidePy=True, hideTux=False, hidePng=True, hideTgx=False, hideTax=False) def createRepository(self, listing, parent, fileincluded=True): """ Create repository @param listing: @type listing: list @param parent: @type parent: @param fileincluded: @type fileincluded: boolean """ try: for dct in listing: if dct["type"] == "folder": item = self.rRepo.Item(repo = self.iRepo.remote(), parent = parent, txt = dct["name"], propertiesFile=dct ) self.createRepository( dct["content"] , item, fileincluded ) else: if fileincluded: if dct["type"] == "file": pname = self.iRepo.remote().getProjectName(dct["project"]) # {'modification': 1342259500, 'type': 'file', 'name': '__init__.py', 'size': '562 } item = self.rRepo.Item(repo = self.iRepo.remote(), parent = parent, txt = dct["name"] , propertiesFile=dct, type = QTreeWidgetItem.UserType+0, projectId=dct["project"], projectName=pname ) except Exception as e: self.error( "unable to create tree for runs: %s" % e ) def onProjectChanged(self, projectItem): """ Called when the project changed on the combo box """ if self.projectReady: item_text = self.prjCombo.itemText(projectItem) self.RefreshRepository.emit(item_text) def createConnections (self): """ create qt connections * ok * cancel """ self.prjCombo.currentIndexChanged.connect(self.onProjectChanged) self.okButton.clicked.connect( self.acceptClicked ) self.cancelButton.clicked.connect( self.reject ) self.upButton.clicked.connect(self.upTest) self.downButton.clicked.connect(self.downTest) self.clearButton.clicked.connect(self.clearList) self.delButton.clicked.connect(self.delTest) self.testsList.itemClicked.connect(self.onItemSelected) self.testsList.itemSelectionChanged.connect(self.onItemSelectionChanged) self.schedAt.toggled.connect(self.onSchedAtActivated) self.repoTests.itemDoubleClicked.connect( self.onTestDoucleClicked ) def onSchedAtActivated(self, toggled): """ On sched at button activated """ if toggled: self.schedAtDateTimeEdit.setEnabled(True) else: self.schedAtDateTimeEdit.setEnabled(False) def onItemSelectionChanged(self): """ Called on item selection changed """ self.onItemSelected(itm=None) def onItemSelected(self, itm): """ Call on item selected """ selectedItems = self.testsList.selectedItems() if len(selectedItems): self.delButton.setEnabled(True) self.upButton.setEnabled(True) self.downButton.setEnabled(True) else: self.delButton.setEnabled(False) self.upButton.setEnabled(False) self.downButton.setEnabled(False) if not self.testsList.count(): self.okButton.setEnabled(False) def upTest(self): """ Up test """ currentRow = self.testsList.currentRow() currentItem = self.testsList.takeItem(currentRow) self.testsList.insertItem(currentRow - 1, currentItem) def downTest(self): """ Down test """ currentRow = self.testsList.currentRow() currentItem = self.testsList.takeItem(currentRow) self.testsList.insertItem(currentRow + 1, currentItem) def delTest(self): """ Del test """ currentRow = self.testsList.currentRow() currentItem = self.testsList.takeItem(currentRow) def clearList(self): """ Clear test """ self.testsList.clear() self.delButton.setEnabled(False) self.upButton.setEnabled(False) self.downButton.setEnabled(False) self.okButton.setEnabled(False) def iterateTree(self, item, hideTsx, hideTpx, hideTcx, hideTdx, hideTxt, hidePy, hideTux, hidePng, hideTgx, hideTax): """ Iterate tree """ child_count = item.childCount() for i in range(child_count): subitem = item.child(i) subchild_count = subitem.childCount() if subchild_count > 0: self.iterateTree(item=subitem, hideTsx=hideTsx, hideTpx=hideTpx, hideTcx=hideTcx, hideTdx=hideTdx, hideTxt=hideTxt, hidePy=hidePy, hideTux=hideTux, hidePng=hidePng, hideTgx=hideTgx, hideTax=hideTax) else: if hideTux and subitem.getExtension() == self.rRepo.EXTENSION_TUX: subitem.setHidden (True) elif hideTpx and subitem.getExtension() == self.rRepo.EXTENSION_TPX: subitem.setHidden (True) elif hideTgx and subitem.getExtension() == self.rRepo.EXTENSION_TGX: subitem.setHidden (True) elif hideTcx and subitem.getExtension() == self.rRepo.EXTENSION_TCX: subitem.setHidden (True) elif hideTsx and subitem.getExtension() == self.rRepo.EXTENSION_TSX: subitem.setHidden (True) elif hideTdx and subitem.getExtension() == self.rRepo.EXTENSION_TDX: subitem.setHidden (True) elif hideTxt and subitem.getExtension() == self.rRepo.EXTENSION_TXT: subitem.setHidden (True) elif hidePy and subitem.getExtension() == self.rRepo.EXTENSION_PY: subitem.setHidden (True) elif hidePng and subitem.getExtension() == self.rRepo.EXTENSION_PNG: subitem.setHidden (True) elif hideTax and subitem.getExtension() == self.rRepo.EXTENSION_TAx: subitem.setHidden (True) else: subitem.setHidden(False) def hideItems(self, hideTsx=False, hideTpx=False, hideTcx=False, hideTdx=False, hideTxt=False, hidePy=False, hideTux=False, hidePng=False, hideTgx=False, hideTax=False): """ Hide items """ root = self.repoTests.invisibleRootItem() self.iterateTree(item=root, hideTsx=hideTsx, hideTpx=hideTpx, hideTcx=hideTcx, hideTdx=hideTdx, hideTxt=hideTxt, hidePy=hidePy, hideTux=hideTux, hidePng=hidePng, hideTgx=hideTgx, hideTax=hideTax) def onTestDoucleClicked(self, testItem): """ On tests double clicked """ if testItem.type() != QTreeWidgetItem.UserType+0: return self.okButton.setEnabled(True) currentProject = self.prjCombo.currentText() testName = "%s:%s" % (str(currentProject),testItem.getPath(withFileName = True)) testItem = QListWidgetItem(testName ) if testName.endswith(self.rRepo.EXTENSION_TUX): testItem.setIcon(QIcon(":/tux.png")) if testName.endswith(self.rRepo.EXTENSION_TSX): testItem.setIcon(QIcon(":/tsx.png")) if testName.endswith(self.rRepo.EXTENSION_TPX): testItem.setIcon(QIcon(":/tpx.png")) if testName.endswith(self.rRepo.EXTENSION_TGX): testItem.setIcon(QIcon(":/tgx.png")) if testName.endswith(self.rRepo.EXTENSION_TAX): testItem.setIcon(QIcon(":/tax.png")) self.testsList.addItem( testItem ) def acceptClicked (self): """ Called on accept button """ self.accept() def getTests(self): """ Returns all tests in the list """ tests = [] for i in xrange(self.testsList.count()): testItem = self.testsList.item(i) tests.append( str(testItem.text()) ) runSimultaneous = False if self.runSimultaneous.isChecked(): runSimultaneous = True if self.schedImmed.isChecked(): runAt = (0,0,0,0,0,0) return (tests, False, runAt, runSimultaneous) else: pydt = self.schedAtDateTimeEdit.dateTime().toPyDateTime() runAt = (pydt.year, pydt.month, pydt.day, pydt.hour, pydt.minute, pydt.second) return (tests, True, runAt, runSimultaneous)
class ActionBar(QFrame): """ SIGNALS: @changeCurrent(PyQt_PyObject) @runFile(QString) @reopenTab(QString) @recentTabsModified() """ def __init__(self, main_combo=False): super(ActionBar, self).__init__() self.setObjectName("actionbar") hbox = QHBoxLayout(self) hbox.setContentsMargins(1, 1, 1, 1) hbox.setSpacing(1) self.lbl_checks = QLabel('') self.lbl_checks.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.lbl_checks.setFixedWidth(48) self.lbl_checks.setVisible(False) hbox.addWidget(self.lbl_checks) self.combo = QComboBox() #model = QStandardItemModel() #self.combo.setModel(model) #self.combo.view().setDragDropMode(QAbstractItemView.InternalMove) self.combo.setMaximumWidth(300) self.combo.setObjectName("combotab") self.connect(self.combo, SIGNAL("currentIndexChanged(int)"), self.current_changed) self.combo.setToolTip(translations.TR_COMBO_FILE_TOOLTIP) self.combo.setContextMenuPolicy(Qt.CustomContextMenu) self.connect(self.combo, SIGNAL("customContextMenuRequested(const QPoint &)"), self._context_menu_requested) hbox.addWidget(self.combo) self.symbols_combo = QComboBox() self.symbols_combo.setObjectName("combo_symbols") self.connect(self.symbols_combo, SIGNAL("activated(int)"), self.current_symbol_changed) hbox.addWidget(self.symbols_combo) self.code_navigator = CodeNavigator() hbox.addWidget(self.code_navigator) self._pos_text = "Line: %d, Col: %d" self.lbl_position = QLabel(self._pos_text % (0, 0)) self.lbl_position.setObjectName("position") self.lbl_position.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) hbox.addWidget(self.lbl_position) self.btn_close = QPushButton( self.style().standardIcon(QStyle.SP_DialogCloseButton), '') if main_combo: self.btn_close.setObjectName('navigation_button') self.btn_close.setToolTip(translations.TR_CLOSE_FILE) self.connect(self.btn_close, SIGNAL("clicked()"), self.about_to_close_file) else: self.btn_close.setObjectName('close_split') self.btn_close.setToolTip(translations.TR_CLOSE_SPLIT) self.connect(self.btn_close, SIGNAL("clicked()"), self.close_split) self.btn_close.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) hbox.addWidget(self.btn_close) def resizeEvent(self, event): super(ActionBar, self).resizeEvent(event) if event.size().width() < 350: self.symbols_combo.hide() self.code_navigator.hide() self.lbl_position.hide() else: self.symbols_combo.show() self.code_navigator.show() self.lbl_position.show() def add_item(self, text, neditable): """Add a new item to the combo and add the neditable data.""" self.combo.addItem(text, neditable) self.combo.setCurrentIndex(self.combo.count() - 1) def get_editables(self): editables = [] for index in range(self.combo.count()): neditable = self.combo.itemData(index) editables.append(neditable) return editables def add_symbols(self, symbols): """Add the symbols to the symbols's combo.""" self.symbols_combo.clear() for symbol in symbols: data = symbol[1] if data[1] == 'f': icon = QIcon(":img/function") else: icon = QIcon(":img/class") self.symbols_combo.addItem(icon, data[0]) def set_current_symbol(self, index): self.symbols_combo.setCurrentIndex(index) def update_item_icon(self, neditable, icon): index = self.combo.findData(neditable) self.combo.setItemIcon(index, icon) def update_item_text(self, neditable, text): index = self.combo.findData(neditable) self.combo.setItemText(index, text) def current_changed(self, index): """Change the current item in the combo.""" neditable = self.combo.itemData(index) self.emit(SIGNAL("changeCurrent(PyQt_PyObject, int)"), neditable, index) def current_symbol_changed(self, index): """Change the current symbol in the combo.""" self.emit(SIGNAL("goToSymbol(int)"), index) def update_line_col(self, line, col): """Update the line and column position.""" self.lbl_position.setText(self._pos_text % (line, col)) def _context_menu_requested(self, point): """Display context menu for the combo file.""" if self.combo.count() == 0: # If there is not an Editor opened, don't show the menu return menu = QMenu() actionAdd = menu.addAction(translations.TR_ADD_TO_PROJECT) actionRun = menu.addAction(translations.TR_RUN_FILE) menuSyntax = menu.addMenu(translations.TR_CHANGE_SYNTAX) self._create_menu_syntax(menuSyntax) menu.addSeparator() actionClose = menu.addAction(translations.TR_CLOSE_FILE) actionCloseAll = menu.addAction(translations.TR_CLOSE_ALL_FILES) actionCloseAllNotThis = menu.addAction( translations.TR_CLOSE_OTHER_FILES) menu.addSeparator() actionSplitH = menu.addAction(translations.TR_SPLIT_VERTICALLY) actionSplitV = menu.addAction(translations.TR_SPLIT_HORIZONTALLY) menu.addSeparator() actionCopyPath = menu.addAction( translations.TR_COPY_FILE_PATH_TO_CLIPBOARD) actionReopen = menu.addAction(translations.TR_REOPEN_FILE) actionUndock = menu.addAction(translations.TR_UNDOCK_EDITOR) if len(settings.LAST_OPENED_FILES) == 0: actionReopen.setEnabled(False) #Connect actions self.connect(actionSplitH, SIGNAL("triggered()"), lambda: self._split(False)) self.connect(actionSplitV, SIGNAL("triggered()"), lambda: self._split(True)) self.connect(actionRun, SIGNAL("triggered()"), self._run_this_file) self.connect(actionAdd, SIGNAL("triggered()"), self._add_to_project) self.connect(actionClose, SIGNAL("triggered()"), self.about_to_close_file) self.connect(actionCloseAllNotThis, SIGNAL("triggered()"), self._close_all_files_except_this) self.connect(actionCloseAll, SIGNAL("triggered()"), self._close_all_files) self.connect(actionCopyPath, SIGNAL("triggered()"), self._copy_file_location) self.connect(actionReopen, SIGNAL("triggered()"), self._reopen_last_tab) self.connect(actionUndock, SIGNAL("triggered()"), self._undock_editor) menu.exec_(QCursor.pos()) def _create_menu_syntax(self, menuSyntax): """Create Menu with the list of syntax supported.""" syntax = list(settings.SYNTAX.keys()) syntax.sort() for syn in syntax: menuSyntax.addAction(syn) self.connect(menuSyntax, SIGNAL("triggered(QAction*)"), self._reapply_syntax) def _reapply_syntax(self, syntaxAction): #TODO if [self.currentIndex(), syntaxAction] != self._resyntax: self._resyntax = [self.currentIndex(), syntaxAction] self.emit(SIGNAL("syntaxChanged(QWidget, QString)"), self.currentWidget(), syntaxAction.text()) def set_current_file(self, neditable): index = self.combo.findData(neditable) self.combo.setCurrentIndex(index) def set_current_by_index(self, index): self.combo.setCurrentIndex(index) def about_to_close_file(self, index=None): """Close the NFile object.""" if index is None: index = self.combo.currentIndex() neditable = self.combo.itemData(index) if neditable: neditable.nfile.close() def close_split(self): self.emit(SIGNAL("closeSplit()")) def close_file(self, neditable): """Receive the confirmation to close the file.""" index = self.combo.findData(neditable) self.combo.removeItem(index) return index def _run_this_file(self): """Execute the current file.""" neditable = self.combo.itemData(self.combo.currentIndex()) self.emit(SIGNAL("runFile(QString)"), neditable.file_path) def _add_to_project(self): """Emit a signal to let someone handle the inclusion of the file inside a project.""" neditable = self.combo.itemData(self.combo.currentIndex()) self.emit(SIGNAL("addToProject(QString)"), neditable.file_path) def _reopen_last_tab(self): self.emit(SIGNAL("reopenTab(QString)"), settings.LAST_OPENED_FILES.pop()) self.emit(SIGNAL("recentTabsModified()")) def _undock_editor(self): self.emit(SIGNAL("undockEditor()")) def _split(self, orientation): self.emit(SIGNAL("splitEditor(bool)"), orientation) def _copy_file_location(self): """Copy the path of the current opened file to the clipboard.""" neditable = self.combo.itemData(self.combo.currentIndex()) QApplication.clipboard().setText(neditable.file_path, QClipboard.Clipboard) def _close_all_files(self): """Close all the files opened.""" for i in range(self.combo.count()): self.about_to_close_file(0) def _close_all_files_except_this(self): """Close all the files except the current one.""" neditable = self.combo.itemData(self.combo.currentIndex()) for i in reversed(list(range(self.combo.count()))): ne = self.combo.itemData(i) if ne is not neditable: self.about_to_close_file(i)
class AddWordWidget(QDialog): def __init__(self, parent=None): super(AddWordWidget, self).__init__(parent=parent) self.setWindowTitle('Add word') self.create_layout() self.create_connections() def create_layout(self): hbox = QHBoxLayout() vbox = QVBoxLayout() vbox.addWidget(QLabel("Dictionary")) vbox.addWidget(QLabel("Original")) vbox.addWidget(QLabel("Translation")) vbox.addWidget(QLabel("Phoneme")) vbox.addWidget(QLabel("Parts of Speech")) vbox.addWidget(QLabel("Synonyms")) vbox.addWidget(QLabel("Antonyms")) hbox.addLayout(vbox) vbox = QVBoxLayout() self.dictionaries = Dictionary.objects.all() self.dictionary = QComboBox() self.dictionary.addItems([d.name for d in self.dictionaries]) vbox.addWidget(self.dictionary) self.original = QLineEdit() vbox.addWidget(self.original) self.translation = QLineEdit() vbox.addWidget(self.translation) self.phoneme = QLineEdit() vbox.addWidget(self.phoneme) self.pos = QComboBox() self.pos.addItems([p.strip() for p in self.dictionaries[0].pos.split(',') if len(p) > 0]) vbox.addWidget(self.pos) self.synonyms = QLineEdit() vbox.addWidget(self.synonyms) self.antonyms = QLineEdit() vbox.addWidget(self.antonyms) hbox.addLayout(vbox) vbox = QVBoxLayout() vbox.addLayout(hbox) vbox.addWidget(QLabel("Description")) self.description = QTextEdit() vbox.addWidget(self.description) self.add_button = QPushButton("&Add") self.close_button = QPushButton("&Close") hbox = QHBoxLayout() hbox.addStretch() hbox.addWidget(self.add_button) hbox.addWidget(self.close_button) vbox.addLayout(hbox) self.status = QLabel('Add a new word to a dictionary.') vbox.addWidget(self.status) self.setLayout(vbox) def create_connections(self): self.connect(self.dictionary, SIGNAL("currentIndexChanged(int)"), self.change_pos) self.connect(self.close_button, SIGNAL("clicked()"), self.close) self.connect(self.add_button, SIGNAL("clicked()"), self.add_word) def change_pos(self, index): current_dict = self.dictionaries[index] self.pos.clear() self.pos.addItems([p.strip() for p in current_dict.pos.split(',') if len(p) > 0]) def get_texts(self): current_dict = self.dictionaries[self.dictionary.currentIndex()].abbrev original = unicode(self.original.text()).strip() translation = unicode(self.translation.text()).strip() phoneme = unicode(self.phoneme.text()).strip() pos = unicode(self.pos.currentText()).strip() synonyms = unicode(self.synonyms.text()).strip() antonyms = unicode(self.antonyms.text()).strip() description = unicode(self.description.toPlainText()).strip() if not all([original, translation, pos]): self.status.setText('There was an error inserting the word. Please' ' try again.') QMessageBox.critical(self, "Error", "You must enter at least " "'Original', 'Translation' and 'Parts of " "Speech'.") return None return dict(dictionary=current_dict, original=original, translation=translation, phoneme=phoneme, pos=pos, synonyms=synonyms, antonyms=antonyms, description=description) def clear_texts(self): self.translation.clear() self.phoneme.clear() self.synonyms.clear() self.antonyms.clear() self.description.clear() self.original.setFocus() def add_word(self): self.status.clear() texts = self.get_texts() if not texts: return word = Word(**texts) word.save() self.clear_texts() self.status.setText('Word %s has been added successfully.' % word.original) self.words_widget.load_words() def save_word(self): self.status.clear() texts = self.get_texts() if not texts: return word = self.word word.dictionary = texts['dictionary'] word.original = texts['original'] word.translation = texts['translation'] word.phoneme = texts['phoneme'] word.pos = texts['pos'] word.synonyms = texts['synonyms'] word.antonyms = texts['antonyms'] word.description = texts['description'] word.save() self.status.setText('Word %s has been saved successfully' % word.original) self.words_widget.load_words() def get_word(self): return self._word def set_word(self, word): self._word = word self.setWindowTitle("Edit %s" % word.original) self.add_button.setText("&Save") self.disconnect(self.add_button, SIGNAL("clicked()"), self.add_word) if word.exported: self.add_button.setEnabled(False) self.status.setText('This word has been exported already. ' 'You cannot save the changes to it.') else: self.connect(self.add_button, SIGNAL("clicked()"), self.save_word) self.status.setText('Edit this word and save to your dictionary.') for i, d in enumerate(self.dictionaries): if d.abbrev == word.dictionary: self.dictionary.setCurrentIndex(i) break self.original.setText(word.original) self.translation.setText(word. translation) self.phoneme.setText(word.phoneme) self.synonyms.setText(word.synonyms) self.antonyms.setText(word.antonyms) self.description.setText(word.description) for i in range(self.pos.count()): if self.pos.itemText(i) == word.pos: self.pos.setCurrentIndex(i) break word = property(get_word, set_word)
class DbConnOptions(QWidget): def __init__(self, parent, conn_properties): super(DbConnOptions, self).__init__(parent) self.plugin_manager = get_plugin_manager() self.available_types = {} self.conn_properties = None for dbplugin in self.plugin_manager.getPluginsOfCategory("db"): self.available_types[dbplugin.name] = dbplugin.plugin_object lay = QGridLayout(self) if len(self.available_types) == 0: lay.addWidget(QLabel("No DB plugin activated", parent), 0, 0, Qt.AlignRight) return lay.addWidget(QLabel("Name: ", parent), 0, 0, Qt.AlignRight) self.nameCombo = QComboBox(parent) lay.addWidget(self.nameCombo, 0, 1) lay.addWidget(QLabel("Type: ", parent), 1, 0, Qt.AlignRight) self.typeCombo = QComboBox(parent) lay.addWidget(self.typeCombo, 1, 1) self.conn_details = QStackedWidget(parent) lay.addWidget(self.conn_details, 2, 0, 1, 2) newConnButton = QPushButton("New Connection", parent) lay.addWidget(newConnButton, 3, 1) self.warningLbl = QLabel("The standard connection is used by the lunchinator internally to store messages etc." + \ " It can be used by plugins as well, but it cannot be changed.") self.warningLbl.setWordWrap(True) lay.addWidget(self.warningLbl, 4, 0, 4, 2) for p in self.available_types.values(): w = p.create_db_options_widget(parent) if w == None: w = QLabel("Plugin not activated", parent) self.conn_details.addWidget(w) self.typeCombo.addItems(self.available_types.keys()) self.reset_connection_properties(conn_properties) newConnButton.clicked.connect(self.new_conn) def reset_connection_properties(self, conn_properties): try: self.nameCombo.currentIndexChanged.disconnect(self.name_changed) self.typeCombo.currentIndexChanged.disconnect(self.type_changed) except: pass self.conn_properties = deepcopy(conn_properties) self.nameCombo.clear() self.nameCombo.addItems(self.conn_properties.keys()) type_name = self.conn_properties[str(self.nameCombo.currentText())]["plugin_type"] type_index = self.typeCombo.findText(type_name) self.typeCombo.setCurrentIndex(type_index) self.conn_details.setCurrentIndex(type_index) self.fill_conn_details() self.typeCombo.currentIndexChanged.connect(self.type_changed) self.nameCombo.currentIndexChanged.connect(self.name_changed) def store_conn_details(self): p = self.available_types[self.last_type] o = p.get_options_from_widget() if o: self.conn_properties[self.last_name].update(o) self.conn_properties[self.last_name]["plugin_type"] = self.last_type def fill_conn_details(self): self.last_type = str(self.typeCombo.currentText()) self.last_name = str(self.nameCombo.currentText()) p = self.available_types[self.last_type] p.fill_options_widget(self.conn_properties[self.last_name]) if self.nameCombo.currentText()=="Standard": self.typeCombo.setEnabled(False) self.conn_details.setEnabled(False) self.warningLbl.setVisible(True) else: self.typeCombo.setEnabled(True) self.conn_details.setEnabled(True) self.warningLbl.setVisible(False) @loggingSlot(int) def type_changed(self, index): self.conn_details.setCurrentIndex(index) self.store_conn_details() self.fill_conn_details() @loggingSlot(int) def name_changed(self, _index): type_name = self.conn_properties[str(self.nameCombo.currentText())]["plugin_type"] type_index = self.typeCombo.findText(type_name) if type_index == self.typeCombo.currentIndex(): self.store_conn_details() self.fill_conn_details() else: self.typeCombo.setCurrentIndex(type_index) @loggingSlot() def new_conn(self): i = len(self.conn_properties) while u"Conn %d" % i in self.conn_properties: i += 1 proposedName = u"Conn %d" % i new_conn_name = None while not new_conn_name or new_conn_name in self.conn_properties: if new_conn_name in self.conn_properties: msg = u"Connection \"%s\" already exists. Enter a different name:" % new_conn_name else: msg = u"Enter the name of the new connection:" new_conn_name, ok = QInputDialog.getText(self, u"Connection Name", msg, QLineEdit.Normal, proposedName) if not ok: return new_conn_name = convert_string(new_conn_name) self.conn_properties[new_conn_name] = {"plugin_type" : str(self.typeCombo.currentText()) } self.nameCombo.addItem(new_conn_name) self.nameCombo.setCurrentIndex(self.nameCombo.count() - 1) def get_connection_properties(self): self.store_conn_details() return self.conn_properties
class CSVOptionsWidget(QWidget): _PresetDelimiters = [ ("Comma", ","), ("Tab", "\t"), ("Semicolon", ";"), ("Space", " "), ] format_changed = Signal() def __init__(self, parent=None, **kwargs): self._delimiter_idx = 0 self._delimiter_custom = "|" self._delimiter = "," self._quotechar = "'" self._escapechar = "\\" self._doublequote = True self._skipinitialspace = False super(QWidget, self).__init__(parent, **kwargs) # Dialect options form = QFormLayout() self.delimiter_cb = QComboBox() self.delimiter_cb.addItems( [name for name, _ in self._PresetDelimiters]) self.delimiter_cb.insertSeparator(self.delimiter_cb.count()) self.delimiter_cb.addItem("Other") self.delimiter_cb.setCurrentIndex(self._delimiter_idx) self.delimiter_cb.activated.connect(self._on_delimiter_idx_changed) validator = QRegExpValidator(QRegExp(".")) self.delimiteredit = LineEdit(self._delimiter_custom, enabled=False, minimumContentsLength=2) self.delimiteredit.setValidator(validator) self.delimiteredit.editingFinished.connect(self._on_delimiter_changed) delimlayout = QHBoxLayout() delimlayout.setContentsMargins(0, 0, 0, 0) delimlayout.addWidget(self.delimiter_cb) delimlayout.addWidget(self.delimiteredit) self.quoteedit = LineEdit(self._quotechar, minimumContentsLength=2) self.quoteedit.setValidator(validator) self.quoteedit.editingFinished.connect(self._on_quotechar_changed) self.escapeedit = LineEdit(self._escapechar, minimumContentsLength=2) self.escapeedit.setValidator(validator) self.escapeedit.editingFinished.connect(self._on_escapechar_changed) # self.skipinitialspace_cb = QCheckBox( # checked=self._skipinitialspace # ) form.addRow("Cell delimiter", delimlayout) form.addRow("Quote character", self.quoteedit) form.addRow("Escape character", self.escapeedit) form.addRow(QFrame(self, frameShape=QFrame.HLine)) # File format option self.missingedit = QLineEdit() self.missingedit.editingFinished.connect(self.format_changed) form.addRow("Missing values", self.missingedit) self.header_format_cb = QComboBox() self.header_format_cb.addItems([ "No header", "Plain header", "Orange header", "Orange simplified header" ]) self.header_format_cb.currentIndexChanged.connect(self.format_changed) form.addRow("Header", self.header_format_cb) self.setLayout(form) self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) def dialect(self): """ Return the current state as a Dialect instance. """ if self._delimiter_idx >= len(self._PresetDelimiters): delimiter = self._delimiter_custom else: _, delimiter = self._PresetDelimiters[self._delimiter_idx] quotechar = str(self.quoteedit.text()) or "" escapechar = str(self.escapeedit.text()) or None skipinitialspace = True return Dialect(delimiter, quotechar, escapechar, doublequote=True, skipinitialspace=skipinitialspace) def set_dialect(self, dialect): """ Set the current state to match dialect instance. """ delimiter = dialect.delimiter try: index = [d for _, d in self._PresetDelimiters].index(delimiter) except ValueError: index = len(self._PresetDelimiters) + 1 self._delimiter_idx = index self._delimiter_custom = delimiter self._quotechar = dialect.quotechar self._escapechar = dialect.escapechar self._skipinitialspace = dialect.skipinitialspace self.delimiter_cb.setCurrentIndex(index) self.delimiteredit.setText(delimiter) self.quoteedit.setText(dialect.quotechar or '"') self.escapeedit.setText(dialect.escapechar or "") # self.skipinitialspace_cb.setChecked(dialect.skipinitialspace) def set_header_format(self, header_format): """Set the current selected header format.""" self._header_format = header_format self.header_format_cb.setCurrentIndex(header_format) def header_format(self): return self.header_format_cb.currentIndex() def set_missing_values(self, missing): self.missingedit.setText(missing) def missing_values(self): return str(self.missingedit.text()) def _on_delimiter_idx_changed(self, index): if index < len(self._PresetDelimiters): self.delimiteredit.setText(self._PresetDelimiters[index][1]) else: self.delimiteredit.setText(self._delimiter_custom) self.delimiteredit.setEnabled(index >= len(self._PresetDelimiters)) self._delimiter_idx = index self.format_changed.emit() def _on_delimiter_changed(self): self._delimiter_custom = str(self.delimiteredit.text()) self.format_changed.emit() def _on_quotechar_changed(self): self._quotechar = str(self.quoteedit.text()) self.format_changed.emit() def _on_escapechar_changed(self): self._escapechar = str(self.escapeedit.text()) self.format_changed.emit() def _on_skipspace_changed(self, skipinitialspace): self._skipinitialspace = skipinitialspace self.format_changed.emit()
class XViewProfileManager(QWidget): currentProfileChanged = qt.Signal(qt.PyObject) optionsMenuRequested = qt.Signal(QPoint) def __init__(self, parent=None): super(XViewProfileManager, self).__init__(parent) # define custom properties self._profiles = [] self._optionsMenuPolicy = Qt.DefaultContextMenu self._viewWidget = None # define the interface self._profileCombo = QComboBox(self) self._optionsButton = QToolButton(self) self._optionsButton.setAutoRaise(True) self._optionsButton.setToolTip('Advanced Options') self._optionsButton.setIcon(QIcon(resources.find('img/advanced.png'))) layout = QHBoxLayout() layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self._profileCombo) layout.addWidget(self._optionsButton) self.setLayout(layout) # create connections self._profileCombo.currentIndexChanged.connect( self.handleProfileChange) self._optionsButton.clicked.connect(self.showOptionsMenu) def addProfile(self, profile): """ Adds the inputed profile to the system. :param profile | <XViewProfile> """ if (profile in self._profiles): return self._profiles.append(profile) self._profileCombo.blockSignals(True) self._profileCombo.addItem(profile.name()) self._profileCombo.setCurrentIndex(self._profileCombo.count() - 1) self._profileCombo.blockSignals(False) def currentProfile(self): """ Returns the currently selected profile from the system. :return <XViewProfile> """ index = self._profileCombo.currentIndex() if (0 <= index and index < len(self._profiles)): return self._profiles[index] return None def handleProfileChange(self): """ Emits that the current profile has changed. """ # restore the profile settings prof = self.currentProfile() vwidget = self.viewWidget() if (vwidget): prof.restore(vwidget) if (not self.signalsBlocked()): self.currentProfileChanged.emit(self.currentProfile()) def optionsMenuPolicy(self): """ Returns the option menu policy for this widget. :return <Qt.MenuPolicy> """ return self._optionsMenuPolicy def profiles(self): """ Returns a list of all the profiles for this system. :return [<XViewProfile>, ..] """ return self._profiles def removeProfile(self, profile): """ Adds the inputed profile to the system. :param profile | <XViewProfile> """ if (not profile in self._profiles): return index = self._profiles.index(profile) self._profiles.remove(profile) self._profileCombo.blockSignals(True) self._profileCombo.takeItem(index) self._profileCombo.blockSignals(False) def restoreSettings(self, settings): """ Restores settings from the application. :param settings | <QSettings> """ settings.beginGroup(self.objectName()) curr_prof = None curr_name = qt.unwrapVariant(settings.value('current')) profiles = [] for prof_name in settings.childGroups(): settings.beginGroup(prof_name) prof_str = qt.unwrapVariant(settings.value('profile')) profile = XViewProfile.fromString(prof_str) profile.setName(prof_name) if (prof_name == curr_name): curr_prof = profile profiles.append(profile) settings.endGroup() self.blockSignals(True) self._profileCombo.blockSignals(True) self.setProfiles(profiles) if (curr_prof): self.setCurrentProfile(curr_prof) self._profileCombo.blockSignals(False) self.blockSignals(False) settings.endGroup() def saveSettings(self, settings): """ Saves the settings for this widget to the application :param settings | <QSettings> """ settings.beginGroup(self.objectName()) curr_prof = self.currentProfile() if (curr_prof): settings.setValue('current', curr_prof.name()) for profile in self.profiles(): settings.beginGroup(profile.name()) settings.setValue('profile', qt.wrapVariant(profile.toString())) settings.endGroup() settings.endGroup() def setCurrentProfile(self, profile): """ Sets the current profile to the inputed profile. :param profile | <XViewProfile> """ try: index = self._profiles.index(profile) except ValueError: index = -1 self._profileCombo.setCurrentIndex(index) def setOptionsMenuPolicy(self, menuPolicy): """ Sets the options menu policy for this item. :param menuPolicy | <Qt.MenuPolicy> """ self._optionsMenuPolicy = menuPolicy def setProfiles(self, profiles): """ Sets a list of profiles to be the options for the manager. :param profiles | [<XViewProfile>, ..] """ self.blockSignals(True) self._profileCombo.blockSignals(True) self._profiles = profiles[:] self._profileCombo.clear() self._profileCombo.addItems(map(lambda x: x.name(), profiles)) self._profileCombo.blockSignals(False) self.blockSignals(False) def setViewWidget(self, viewWidget): """ Sets the view widget instance linked with this manager. :param viewWidget | <XViewWidget> """ self._viewWidget = viewWidget def showOptionsMenu(self): """ Displays the options menu. If the option menu policy is set to CustomContextMenu, then the optionMenuRequested signal will be emitted, otherwise the default context menu will be displayed. """ point = QPoint(0, self._optionsButton.height()) global_point = self._optionsButton.mapToGlobal(point) # prompt the custom context menu if (self.optionsMenuPolicy() == Qt.CustomContextMenu): if (not self.signalsBlocked()): self.optionsMenuRequested.emit(global_point) return # use the default context menu menu = XViewProfileManagerMenu(self) menu.exec_(global_point) def viewWidget(self): """ Returns the view widget that is associated with this manager. :return <XViewWidget> """ return self._viewWidget
class CSVOptionsWidget(QWidget): _PresetDelimiters = [ ("Comma", ","), ("Tab", "\t"), ("Semicolon", ";"), ("Space", " "), ] format_changed = Signal() def __init__(self, parent=None, **kwargs): self._delimiter_idx = 0 self._delimiter_custom = "|" self._delimiter = "," self._quotechar = "'" self._escapechar = "\\" self._doublequote = True self._skipinitialspace = False super(QWidget, self).__init__(parent, **kwargs) # Dialect options form = QFormLayout() self.delimiter_cb = QComboBox() self.delimiter_cb.addItems( [name for name, _ in self._PresetDelimiters] ) self.delimiter_cb.insertSeparator(self.delimiter_cb.count()) self.delimiter_cb.addItem("Other") self.delimiter_cb.setCurrentIndex(self._delimiter_idx) self.delimiter_cb.activated.connect(self._on_delimiter_idx_changed) validator = QRegExpValidator(QRegExp(".")) self.delimiteredit = LineEdit( self._delimiter_custom, enabled=False, minimumContentsLength=2 ) self.delimiteredit.setValidator(validator) self.delimiteredit.editingFinished.connect(self._on_delimiter_changed) delimlayout = QHBoxLayout() delimlayout.setContentsMargins(0, 0, 0, 0) delimlayout.addWidget(self.delimiter_cb) delimlayout.addWidget(self.delimiteredit) self.quoteedit = LineEdit(self._quotechar, minimumContentsLength=2) self.quoteedit.setValidator(validator) self.quoteedit.editingFinished.connect(self._on_quotechar_changed) self.escapeedit = LineEdit(self._escapechar, minimumContentsLength=2) self.escapeedit.setValidator(validator) self.escapeedit.editingFinished.connect(self._on_escapechar_changed) # self.skipinitialspace_cb = QCheckBox( # checked=self._skipinitialspace # ) form.addRow("Cell delimiter", delimlayout) form.addRow("Quote character", self.quoteedit) form.addRow("Escape character", self.escapeedit) form.addRow(QFrame(self, frameShape=QFrame.HLine)) # File format option self.missingedit = QLineEdit() self.missingedit.editingFinished.connect(self.format_changed) form.addRow("Missing values", self.missingedit) self.header_format_cb = QComboBox() self.header_format_cb.addItems( ["No header", "Plain header", "Orange header", "Orange simplified header"] ) self.header_format_cb.currentIndexChanged.connect(self.format_changed) form.addRow("Header", self.header_format_cb) self.setLayout(form) self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) def dialect(self): """ Return the current state as a Dialect instance. """ if self._delimiter_idx >= len(self._PresetDelimiters): delimiter = self._delimiter_custom else: _, delimiter = self._PresetDelimiters[self._delimiter_idx] quotechar = str(self.quoteedit.text()) or "" escapechar = str(self.escapeedit.text()) or None skipinitialspace = True return Dialect(delimiter, quotechar, escapechar, doublequote=True, skipinitialspace=skipinitialspace) def set_dialect(self, dialect): """ Set the current state to match dialect instance. """ delimiter = dialect.delimiter try: index = [d for _, d in self._PresetDelimiters].index(delimiter) except ValueError: index = len(self._PresetDelimiters) + 1 self._delimiter_idx = index self._delimiter_custom = delimiter self._quotechar = dialect.quotechar self._escapechar = dialect.escapechar self._skipinitialspace = dialect.skipinitialspace self.delimiter_cb.setCurrentIndex(index) self.delimiteredit.setText(delimiter) self.quoteedit.setText(dialect.quotechar or '"') self.escapeedit.setText(dialect.escapechar or "") # self.skipinitialspace_cb.setChecked(dialect.skipinitialspace) def set_header_format(self, header_format): """Set the current selected header format.""" self._header_format = header_format self.header_format_cb.setCurrentIndex(header_format) def header_format(self): return self.header_format_cb.currentIndex() def set_missing_values(self, missing): self.missingedit.setText(missing) def missing_values(self): return str(self.missingedit.text()) def _on_delimiter_idx_changed(self, index): if index < len(self._PresetDelimiters): self.delimiteredit.setText(self._PresetDelimiters[index][1]) else: self.delimiteredit.setText(self._delimiter_custom) self.delimiteredit.setEnabled(index >= len(self._PresetDelimiters)) self._delimiter_idx = index self.format_changed.emit() def _on_delimiter_changed(self): self._delimiter_custom = str(self.delimiteredit.text()) self.format_changed.emit() def _on_quotechar_changed(self): self._quotechar = str(self.quoteedit.text()) self.format_changed.emit() def _on_escapechar_changed(self): self._escapechar = str(self.escapeedit.text()) self.format_changed.emit() def _on_skipspace_changed(self, skipinitialspace): self._skipinitialspace = skipinitialspace self.format_changed.emit()
class experimentersDialog(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.prm = self.parent().prm self.tmpPref = {} self.tmpPref['experimenter'] = {} self.tmpPref['experimenter'] = copy.deepcopy(self.parent().prm['experimenter']) self.currLocale = self.parent().prm['currentLocale'] self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator) self.sizer = QGridLayout() self.h1Sizer = QHBoxLayout() self.v1Sizer = QVBoxLayout() self.v2Sizer = QVBoxLayout() n = 0 self.experimenterLabel = QLabel(self.tr("Experimenter ID:"), self) self.sizer.addWidget(self.experimenterLabel, n, 0) self.experimenterChooser = QComboBox() self.experimenterChooser.addItems(self.tmpPref['experimenter']['experimenter_id']) self.sizer.addWidget(self.experimenterChooser, n, 1) self.experimenterChooser.activated[str].connect(self.onExperimenterChange) self.currIdx = self.experimenterChooser.currentIndex() n = n+1 self.experimenterNameLabel = QLabel(self.tr("Name:"), self) self.sizer.addWidget(self.experimenterNameLabel, n, 0) self.experimenterNameTF = QLineEdit("") self.experimenterNameTF.setText(self.tmpPref['experimenter']['experimenter_name'][0]) self.sizer.addWidget(self.experimenterNameTF, n, 1) n = n+1 self.experimenterSurnameLabel = QLabel(self.tr("Surname:"), self) self.sizer.addWidget(self.experimenterSurnameLabel, n, 0) self.experimenterSurnameTF = QLineEdit("") self.experimenterSurnameTF.setText(self.tmpPref['experimenter']['experimenter_surname'][0]) self.sizer.addWidget(self.experimenterSurnameTF, n, 1) n = n+1 self.experimenterEmailLabel = QLabel(self.tr("e-mail:"), self) self.sizer.addWidget(self.experimenterEmailLabel, n, 0) self.experimenterEmailTF = QLineEdit("") self.experimenterEmailTF.setText(self.tmpPref['experimenter']['experimenter_email'][0]) self.sizer.addWidget(self.experimenterEmailTF, n, 1) n = n+1 self.experimenterAddressLabel = QLabel(self.tr("Address (line 1):"), self) self.sizer.addWidget(self.experimenterAddressLabel, n, 0) self.experimenterAddressTF = QLineEdit("") self.experimenterAddressTF.setText(self.tmpPref['experimenter']['experimenter_address'][0]) self.sizer.addWidget(self.experimenterAddressTF, n, 1) n = n+1 self.experimenterAddressLabel2 = QLabel(self.tr("Address (line 2):"), self) self.sizer.addWidget(self.experimenterAddressLabel2, n, 0) self.experimenterAddressTF2 = QLineEdit("") self.experimenterAddressTF2.setText(self.tmpPref['experimenter']['experimenter_address2'][0]) self.sizer.addWidget(self.experimenterAddressTF2, n, 1) n = n+1 self.experimenterTelephoneLabel = QLabel(self.tr("Telephone:"), self) self.sizer.addWidget(self.experimenterTelephoneLabel, n, 0) self.experimenterTelephoneTF = QLineEdit("") self.experimenterTelephoneTF.setText(self.tmpPref['experimenter']['experimenter_telephone'][0]) self.sizer.addWidget(self.experimenterTelephoneTF, n, 1) n = n+1 self.experimenterMobileLabel = QLabel(self.tr("Mobile:"), self) self.sizer.addWidget(self.experimenterMobileLabel, n, 0) self.experimenterMobileTF = QLineEdit("") self.experimenterMobileTF.setText(self.tmpPref['experimenter']['experimenter_mobile'][0]) self.sizer.addWidget(self.experimenterMobileTF, n, 1) #ADD EXPERIMENTER BUTTON addExpButton = QPushButton(self.tr("Add Experimenter"), self) addExpButton.clicked.connect(self.onClickAddExpButton) self.v2Sizer.addWidget(addExpButton) #REMOVE EXPERIMENTER BUTTON removeExpButton = QPushButton(self.tr("Remove Experimenter"), self) removeExpButton.clicked.connect(self.onClickRemoveExpButton) self.v2Sizer.addWidget(removeExpButton) #CHANGE ID BUTTON changeIdButton = QPushButton(self.tr("Change Identifier"), self) changeIdButton.clicked.connect(self.onClickChangeIdButton) self.v2Sizer.addWidget(changeIdButton) #SET AS DEFAULT BUTTON setAsDefaultButton = QPushButton(self.tr("Set as default"), self) setAsDefaultButton.clicked.connect(self.onClickSetAsDefaultButton) self.v2Sizer.addWidget(setAsDefaultButton) self.v2Sizer.addStretch() buttonBox = QDialogButtonBox(QDialogButtonBox.Apply|QDialogButtonBox.Ok|QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) buttonBox.button(QDialogButtonBox.Apply).clicked.connect(self.onClickApplyButton) self.h1Sizer.addLayout(self.v2Sizer) self.sizer.setAlignment(Qt.AlignTop) self.h1Sizer.addLayout(self.sizer) self.v1Sizer.addLayout(self.h1Sizer) self.v1Sizer.addWidget(buttonBox) self.setLayout(self.v1Sizer) def onClickApplyButton(self): self.tryApply(self.currIdx) self.permanentApply() def permanentApply(self): self.parent().prm['experimenter'] = copy.deepcopy(self.tmpPref['experimenter']) f = open(self.parent().prm['experimenterPrefFile'], 'wb') pickle.dump(self.parent().prm['experimenter'], f) f.close() for i in range(self.parent().experimenterChooser.count()): self.parent().experimenterChooser.removeItem(0) self.parent().experimenterChooser.addItems(self.parent().prm['experimenter']['experimenter_id']) def tryApply(self, idx): self.tmpPref['experimenter']['experimenter_id'][idx] = self.experimenterChooser.itemText(idx) self.tmpPref['experimenter']['experimenter_name'][idx] = self.experimenterNameTF.text() self.tmpPref['experimenter']['experimenter_surname'][idx] = self.experimenterSurnameTF.text() self.tmpPref['experimenter']['experimenter_email'][idx] = self.experimenterEmailTF.text() self.tmpPref['experimenter']['experimenter_address'][idx] = self.experimenterAddressTF.text() self.tmpPref['experimenter']['experimenter_address2'][idx] = self.experimenterAddressTF2.text() self.tmpPref['experimenter']['experimenter_telephone'][idx] = self.experimenterTelephoneTF.text() self.tmpPref['experimenter']['experimenter_mobile'][idx] = self.experimenterMobileTF.text() def revertChanges(self): if len(self.tmpPref['experimenter']['experimenter_id']) != len(self.parent().prm['experimenter']['experimenter_id']): #experimenter was added, reverting for i in range(self.experimenterChooser.count()): self.experimenterChooser.removeItem(0) self.experimenterChooser.addItems(self.parent().prm['experimenter']['experimenter_id']) self.tmpPref['experimenter'] = copy.deepcopy(self.parent().prm['experimenter']) def onExperimenterChange(self, experimenterSelected): self.prevIdx = self.currIdx self.currIdx = self.tmpPref['experimenter']['experimenter_id'].index(experimenterSelected) self.tryApply(self.prevIdx) if self.tmpPref['experimenter'] != self.parent().prm['experimenter']: conf = applyChanges(self) if conf.exec_(): self.permanentApply() else: self.revertChanges() self.experimenterNameTF.setText(self.prm['experimenter']['experimenter_name'][self.currIdx]) self.experimenterSurnameTF.setText(self.prm['experimenter']['experimenter_surname'][self.currIdx]) self.experimenterEmailTF.setText(self.prm['experimenter']['experimenter_email'][self.currIdx]) self.experimenterAddressTF.setText(self.prm['experimenter']['experimenter_address'][self.currIdx]) self.experimenterAddressTF2.setText(self.prm['experimenter']['experimenter_address2'][self.currIdx]) self.experimenterTelephoneTF.setText(self.prm['experimenter']['experimenter_telephone'][self.currIdx]) self.experimenterMobileTF.setText(self.prm['experimenter']['experimenter_mobile'][self.currIdx]) def onClickAddExpButton(self): self.tryApply(self.currIdx) if self.tmpPref['experimenter'] != self.parent().prm['experimenter']: conf = applyChanges(self) if conf.exec_(): self.permanentApply() else: self.revertChanges() msg = self.tr("Experimenter's Identifier:") name, ok = QInputDialog.getText(self, self.tr('Input Dialog'), msg) if ok: self.tmpPref['experimenter']['defaultExperimenter'].append('') self.tmpPref['experimenter']['experimenter_id'].append(name) self.tmpPref['experimenter']['experimenter_name'].append('') self.tmpPref['experimenter']['experimenter_surname'].append('') self.tmpPref['experimenter']['experimenter_email'].append('') self.tmpPref['experimenter']['experimenter_address'].append('') self.tmpPref['experimenter']['experimenter_address2'].append('') self.tmpPref['experimenter']['experimenter_telephone'].append('') self.tmpPref['experimenter']['experimenter_mobile'].append('') self.permanentApply() self.currIdx = self.experimenterChooser.count() self.experimenterNameTF.setText(self.tmpPref['experimenter']['experimenter_name'][self.currIdx]) self.experimenterSurnameTF.setText(self.tmpPref['experimenter']['experimenter_surname'][self.currIdx]) self.experimenterEmailTF.setText(self.tmpPref['experimenter']['experimenter_email'][self.currIdx]) self.experimenterAddressTF.setText(self.tmpPref['experimenter']['experimenter_address'][self.currIdx]) self.experimenterAddressTF2.setText(self.tmpPref['experimenter']['experimenter_address2'][self.currIdx]) self.experimenterTelephoneTF.setText(self.tmpPref['experimenter']['experimenter_telephone'][self.currIdx]) self.experimenterMobileTF.setText(self.tmpPref['experimenter']['experimenter_mobile'][self.currIdx]) self.experimenterChooser.addItem(name) self.experimenterChooser.setCurrentIndex(self.currIdx) def onClickRemoveExpButton(self): self.tryApply(self.currIdx) if self.tmpPref['experimenter'] != self.parent().prm['experimenter']: conf = applyChanges(self) if conf.exec_(): self.permanentApply() else: self.revertChanges() if self.experimenterChooser.count() > 1: reply = QMessageBox.warning(self, self.tr('Message'), "Remove experimenter? This action cannot be undone!", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: self.tmpPref['experimenter']['defaultExperimenter'].pop(self.currIdx) self.tmpPref['experimenter']['experimenter_id'].pop(self.currIdx) self.tmpPref['experimenter']['experimenter_name'].pop(self.currIdx) self.tmpPref['experimenter']['experimenter_surname'].pop(self.currIdx) self.tmpPref['experimenter']['experimenter_email'].pop(self.currIdx) self.tmpPref['experimenter']['experimenter_address'].pop(self.currIdx) self.tmpPref['experimenter']['experimenter_address2'].pop(self.currIdx) self.tmpPref['experimenter']['experimenter_telephone'].pop(self.currIdx) self.tmpPref['experimenter']['experimenter_mobile'].pop(self.currIdx) self.experimenterChooser.removeItem(self.currIdx) self.currIdx = self.experimenterChooser.currentIndex() self.permanentApply() self.experimenterNameTF.setText(self.tmpPref['experimenter']['experimenter_name'][self.currIdx]) self.experimenterSurnameTF.setText(self.tmpPref['experimenter']['experimenter_surname'][self.currIdx]) self.experimenterEmailTF.setText(self.tmpPref['experimenter']['experimenter_email'][self.currIdx]) self.experimenterAddressTF.setText(self.tmpPref['experimenter']['experimenter_address'][self.currIdx]) self.experimenterAddressTF2.setText(self.tmpPref['experimenter']['experimenter_address2'][self.currIdx]) self.experimenterTelephoneTF.setText(self.tmpPref['experimenter']['experimenter_telephone'][self.currIdx]) self.experimenterMobileTF.setText(self.tmpPref['experimenter']['experimenter_mobile'][self.currIdx]) else: QMessageBox.warning(self, self.tr('Message'), self.tr("Only one experimenter left. Experimenter cannot be removed!"), QMessageBox.Ok) def onClickChangeIdButton(self): self.tryApply(self.currIdx) if self.tmpPref['experimenter'] != self.parent().prm['experimenter']: conf = applyChanges(self) if conf.exec_(): self.permanentApply() else: self.revertChanges() msg = self.tr("Experimenter's Identifier:") name, ok = QInputDialog.getText(self, self.tr('Input Dialog'), msg) if ok: self.tmpPref['experimenter']['experimenter_id'][self.currIdx] = name self.experimenterChooser.setItemText(self.currIdx, name) self.permanentApply() def onClickSetAsDefaultButton(self): idx = self.experimenterChooser.currentIndex() print(idx) self.tryApply(self.currIdx) if self.tmpPref['experimenter'] != self.parent().prm['experimenter']: conf = applyChanges(self) if conf.exec_(): self.permanentApply() else: self.revertChanges() for i in range(len(self.parent().prm['experimenter']["defaultExperimenter"])): if i == idx: self.tmpPref['experimenter']["defaultExperimenter"][i] = "\u2713" else: self.tmpPref['experimenter']["defaultExperimenter"][i] = "\u2012" print(self.tmpPref) self.permanentApply()
class ActionBar(QFrame): """ SIGNALS: @changeCurrent(PyQt_PyObject) @runFile(QString) @reopenTab(QString) @recentTabsModified() """ def __init__(self, main_combo=False): super(ActionBar, self).__init__() self.setObjectName("actionbar") hbox = QHBoxLayout(self) hbox.setContentsMargins(1, 1, 1, 1) hbox.setSpacing(1) self.lbl_checks = QLabel('') self.lbl_checks.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.lbl_checks.setFixedWidth(48) self.lbl_checks.setVisible(False) hbox.addWidget(self.lbl_checks) self.combo = QComboBox() self.combo.setIconSize(QSize(16, 16)) #model = QStandardItemModel() #self.combo.setModel(model) #self.combo.view().setDragDropMode(QAbstractItemView.InternalMove) self.combo.setMaximumWidth(300) self.combo.setObjectName("combotab") self.connect(self.combo, SIGNAL("currentIndexChanged(int)"), self.current_changed) self.combo.setToolTip(translations.TR_COMBO_FILE_TOOLTIP) self.combo.setContextMenuPolicy(Qt.CustomContextMenu) self.connect(self.combo, SIGNAL( "customContextMenuRequested(const QPoint &)"), self._context_menu_requested) hbox.addWidget(self.combo) self.symbols_combo = QComboBox() self.symbols_combo.setIconSize(QSize(16, 16)) self.symbols_combo.setObjectName("combo_symbols") self.connect(self.symbols_combo, SIGNAL("activated(int)"), self.current_symbol_changed) hbox.addWidget(self.symbols_combo) self.code_navigator = CodeNavigator() hbox.addWidget(self.code_navigator) self._pos_text = "Line: %d, Col: %d" self.lbl_position = QLabel(self._pos_text % (0, 0)) self.lbl_position.setObjectName("position") self.lbl_position.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) hbox.addWidget(self.lbl_position) self.btn_close = QPushButton( self.style().standardIcon(QStyle.SP_DialogCloseButton), '') self.btn_close.setIconSize(QSize(16, 16)) if main_combo: self.btn_close.setObjectName('navigation_button') self.btn_close.setToolTip(translations.TR_CLOSE_FILE) self.connect(self.btn_close, SIGNAL("clicked()"), self.about_to_close_file) else: self.btn_close.setObjectName('close_split') self.btn_close.setToolTip(translations.TR_CLOSE_SPLIT) self.connect(self.btn_close, SIGNAL("clicked()"), self.close_split) self.btn_close.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) hbox.addWidget(self.btn_close) def resizeEvent(self, event): super(ActionBar, self).resizeEvent(event) if event.size().width() < 350: self.symbols_combo.hide() self.code_navigator.hide() self.lbl_position.hide() else: self.symbols_combo.show() self.code_navigator.show() self.lbl_position.show() def add_item(self, text, neditable): """Add a new item to the combo and add the neditable data.""" self.combo.addItem(text, neditable) self.combo.setCurrentIndex(self.combo.count() - 1) def get_editables(self): editables = [] for index in range(self.combo.count()): neditable = self.combo.itemData(index) editables.append(neditable) return editables def add_symbols(self, symbols): """Add the symbols to the symbols's combo.""" self.symbols_combo.clear() for symbol in symbols: data = symbol[1] if data[1] == 'f': icon = QIcon(":img/function") else: icon = QIcon(":img/class") self.symbols_combo.addItem(icon, data[0]) def set_current_symbol(self, index): self.symbols_combo.setCurrentIndex(index) def update_item_icon(self, neditable, icon): index = self.combo.findData(neditable) self.combo.setItemIcon(index, icon) def update_item_text(self, neditable, text): index = self.combo.findData(neditable) self.combo.setItemText(index, text) def current_changed(self, index): """Change the current item in the combo.""" neditable = self.combo.itemData(index) self.emit(SIGNAL("changeCurrent(PyQt_PyObject, int)"), neditable, index) def current_symbol_changed(self, index): """Change the current symbol in the combo.""" self.emit(SIGNAL("goToSymbol(int)"), index) def update_line_col(self, line, col): """Update the line and column position.""" self.lbl_position.setText(self._pos_text % (line, col)) def _context_menu_requested(self, point): """Display context menu for the combo file.""" if self.combo.count() == 0: # If there is not an Editor opened, don't show the menu return menu = QMenu() actionAdd = menu.addAction(translations.TR_ADD_TO_PROJECT) actionRun = menu.addAction(translations.TR_RUN_FILE) menuSyntax = menu.addMenu(translations.TR_CHANGE_SYNTAX) self._create_menu_syntax(menuSyntax) menu.addSeparator() actionClose = menu.addAction(translations.TR_CLOSE_FILE) actionCloseAll = menu.addAction(translations.TR_CLOSE_ALL_FILES) actionCloseAllNotThis = menu.addAction( translations.TR_CLOSE_OTHER_FILES) menu.addSeparator() actionSplitH = menu.addAction(translations.TR_SPLIT_VERTICALLY) actionSplitV = menu.addAction(translations.TR_SPLIT_HORIZONTALLY) menu.addSeparator() actionCopyPath = menu.addAction( translations.TR_COPY_FILE_PATH_TO_CLIPBOARD) actionReopen = menu.addAction(translations.TR_REOPEN_FILE) actionUndock = menu.addAction(translations.TR_UNDOCK_EDITOR) if len(settings.LAST_OPENED_FILES) == 0: actionReopen.setEnabled(False) #Connect actions self.connect(actionSplitH, SIGNAL("triggered()"), lambda: self._split(False)) self.connect(actionSplitV, SIGNAL("triggered()"), lambda: self._split(True)) self.connect(actionRun, SIGNAL("triggered()"), self._run_this_file) self.connect(actionAdd, SIGNAL("triggered()"), self._add_to_project) self.connect(actionClose, SIGNAL("triggered()"), self.about_to_close_file) self.connect(actionCloseAllNotThis, SIGNAL("triggered()"), self._close_all_files_except_this) self.connect(actionCloseAll, SIGNAL("triggered()"), self._close_all_files) self.connect(actionCopyPath, SIGNAL("triggered()"), self._copy_file_location) self.connect(actionReopen, SIGNAL("triggered()"), self._reopen_last_tab) self.connect(actionUndock, SIGNAL("triggered()"), self._undock_editor) menu.exec_(QCursor.pos()) def _create_menu_syntax(self, menuSyntax): """Create Menu with the list of syntax supported.""" syntax = list(settings.SYNTAX.keys()) syntax.sort() for syn in syntax: menuSyntax.addAction(syn) self.connect(menuSyntax, SIGNAL("triggered(QAction*)"), self._reapply_syntax) def _reapply_syntax(self, syntaxAction): #TODO if [self.currentIndex(), syntaxAction] != self._resyntax: self._resyntax = [self.currentIndex(), syntaxAction] self.emit(SIGNAL("syntaxChanged(QWidget, QString)"), self.currentWidget(), syntaxAction.text()) def set_current_file(self, neditable): index = self.combo.findData(neditable) self.combo.setCurrentIndex(index) def set_current_by_index(self, index): self.combo.setCurrentIndex(index) def about_to_close_file(self, index=None): """Close the NFile object.""" if index is None: index = self.combo.currentIndex() neditable = self.combo.itemData(index) if neditable: neditable.nfile.close() def close_split(self): self.emit(SIGNAL("closeSplit()")) def close_file(self, neditable): """Receive the confirmation to close the file.""" index = self.combo.findData(neditable) self.combo.removeItem(index) return index def _run_this_file(self): """Execute the current file.""" neditable = self.combo.itemData(self.combo.currentIndex()) self.emit(SIGNAL("runFile(QString)"), neditable.file_path) def _add_to_project(self): """Emit a signal to let someone handle the inclusion of the file inside a project.""" neditable = self.combo.itemData(self.combo.currentIndex()) self.emit(SIGNAL("addToProject(QString)"), neditable.file_path) def _reopen_last_tab(self): self.emit(SIGNAL("reopenTab(QString)"), settings.LAST_OPENED_FILES.pop()) self.emit(SIGNAL("recentTabsModified()")) def _undock_editor(self): self.emit(SIGNAL("undockEditor()")) def _split(self, orientation): self.emit(SIGNAL("splitEditor(bool)"), orientation) def _copy_file_location(self): """Copy the path of the current opened file to the clipboard.""" neditable = self.combo.itemData(self.combo.currentIndex()) QApplication.clipboard().setText(neditable.file_path, QClipboard.Clipboard) def _close_all_files(self): """Close all the files opened.""" for i in range(self.combo.count()): self.about_to_close_file(0) def _close_all_files_except_this(self): """Close all the files except the current one.""" neditable = self.combo.itemData(self.combo.currentIndex()) for i in reversed(list(range(self.combo.count()))): ne = self.combo.itemData(i) if ne is not neditable: self.about_to_close_file(i)
class ComboBoxPanel(QWidget): def __init__(self, parent, editable=False, spacerItemMove=False): QWidget.__init__(self, parent) while not isinstance(parent, QDialog): parent = parent.parent() self.setObjectName("ComboBoxPanel" + str(len(parent.findChildren(ComboBoxPanel)))) self.hLayoutBoxPanel = QHBoxLayout(self) self.hLayoutBoxPanel.setSpacing(0) self.hLayoutBoxPanel.setContentsMargins(0, 0, 0, 0) self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel")) self.frameBoxPanel = QFrame(self) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.frameBoxPanel.sizePolicy().hasHeightForWidth()) self.frameBoxPanel.setSizePolicy(sizePolicy) self.frameBoxPanel.setFrameShape(QFrame.NoFrame) self.frameBoxPanel.setFrameShadow(QFrame.Raised) self.frameBoxPanel.setObjectName(("frameBoxPanel")) self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel) self.hLayoutframeBoxPanel.setSpacing(0) self.hLayoutframeBoxPanel.setMargin(0) self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel")) self.captionLabel = QLabel(self.frameBoxPanel) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.captionLabel.sizePolicy().hasHeightForWidth()) self.captionLabel.setSizePolicy(sizePolicy) self.captionLabel.setMinimumSize(QSize(200, 0)) self.captionLabel.setMaximumSize(QSize(200, 16777215)) font = QFont() font.setBold(False) font.setWeight(50) self.captionLabel.setFont(font) self.captionLabel.setObjectName(("captionLabel")) self.hLayoutframeBoxPanel.addWidget(self.captionLabel) self.comboBox = QComboBox(self.frameBoxPanel) self.comboBox.setEnabled(True) font = QFont() font.setBold(False) font.setWeight(50) self.comboBox.setFont(font) self.comboBox.setObjectName(self.objectName() + "_comboBox") self.comboBox.setMinimumWidth(70) # self.comboBox.setMaximumWidth(70) # self.hLayoutframeBoxPanel.addWidget(self.lineEdit) self.hLayoutframeBoxPanel.addWidget(self.comboBox) self.imageButton = QToolButton(self.frameBoxPanel) self.imageButton.setText(("")) icon = QIcon() icon.addPixmap(QPixmap(("Resource/convex_hull.png")), QIcon.Normal, QIcon.Off) self.imageButton.setIcon(icon) self.imageButton.setObjectName(("imageButton")) self.imageButton.setVisible(False) self.hLayoutframeBoxPanel.addWidget(self.imageButton) self.hLayoutBoxPanel.addWidget(self.frameBoxPanel) if not spacerItemMove: spacerItem = QSpacerItem(10, 10, QSizePolicy.Expanding, QSizePolicy.Minimum) self.hLayoutBoxPanel.addItem(spacerItem) self.comboBox.currentIndexChanged.connect(self.comboBoxChanged) # self.comboBox.editTextChanged.connect(self.comboBoxEditTextChanged) self.imageButton.clicked.connect(self.imageButtonClicked) self.captionUnits = "" self.hasObject = False self.objectList = [] if editable == True: self.lineEdit = QLineEdit(self.frameBoxPanel) self.lineEdit.setObjectName("lineEdit") self.hLayoutframeBoxPanel.insertWidget(1, self.lineEdit) self.comboBox.setLineEdit(self.lineEdit) self.lineEdit.returnPressed.connect(self.comboBoxEditTextChanged) def FindString(self, string): return self.comboBox.findText(string) def comboBoxEditTextChanged(self): self.comboBox.showPopup() def get_Count(self): return self.comboBox.count() Count = property(get_Count, None, None, None) def method_0(self): return self.comboBox.currentIndex( ) >= 0 and self.SelectedItem != None and self.SelectedItem != "" def method_3(self, string_0): return self.comboBox.findText(string_0) def method_11(self, string_0): if (self.IsEmpty): return "%s%s\t" % (string_0, self.Caption) return "%s%s\t%s %s" % (string_0, self.Caption, self.Value, self.CaptionUnits) def comboBoxChanged(self): self.emit(SIGNAL("Event_0"), self) def IndexOf(self, item): if isinstance(item, str) or isinstance(item, QString): return self.comboBox.findText(item) else: return self.comboBox.findText(item.ToString()) def Contains(self, item): compStr = None if isinstance(item, str): compStr = item elif isinstance(item, float) or isinstance(item, int): compStr = str(item) else: compStr = item.ToString() for i in range(self.comboBox.count()): comboItemstr = self.comboBox.itemText(i) if compStr == comboItemstr: return True return False def Clear(self): self.comboBox.clear() self.objectList = [] self.hasObject = False def Add(self, item): if not isinstance(item, str) and not isinstance(item, QString): self.comboBox.addItem(item.ToString()) self.objectList.append(item) self.hasObject = True return self.comboBox.addItem(item) self.hasObject = False def Insert(self, index, item): if not isinstance(item, str) and not isinstance(item, QString): self.comboBox.insertItem(index, item.ToString()) self.objectList.insert(index, item) self.hasObject = True return self.comboBox.insertItem(index, item) self.hasObject = False def imageButtonClicked(self): self.emit(SIGNAL("Event_3"), self) def get_Caption(self): caption = self.captionLabel.text() findIndex = caption.indexOf("(") if findIndex > 0: val = caption.left(findIndex) return val return caption def set_Caption(self, captionStr): if captionStr == "": self.captionLabel.setText("") self.LabelWidth = 0 return if self.CaptionUnits != "" and self.CaptionUnits != None: self.captionLabel.setText(captionStr + "(" + QString(self.CaptionUnits) + ")" + ":") else: self.captionLabel.setText(captionStr + ":") Caption = property(get_Caption, set_Caption, None, None) def get_CaptionUnits(self): return self.captionUnits def set_CaptionUnits(self, captionUnits): self.captionUnits = captionUnits CaptionUnits = property(get_CaptionUnits, set_CaptionUnits, None, None) def set_ButtonVisible(self, bool): self.imageButton.setVisible(bool) ButtonVisible = property(None, set_ButtonVisible, None, None) # def get_Value(self): # return self.comboBox.currentIndex() # def set_Value(self, value): # try: # self.comboBox.setCurrentIndex(value) # except: # self.textBox.setText("") # Value = property(get_Value, set_Value, None, None) def get_IsEmpty(self): return self.comboBox.currentText() == "" or self.comboBox.currentIndex( ) == -1 IsEmpty = property(get_IsEmpty, None, None, None) def get_ReadOnly(self): return self.textBox.isReadOnly() # def set_ReadOnly(self, bool): # self.comboBox.setR.setReadOnly(bool) # ReadOnly = property(get_ReadOnly, set_ReadOnly, None, None) def set_LabelWidth(self, width): self.captionLabel.setMinimumSize(QSize(width, 0)) self.captionLabel.setMaximumSize(QSize(width, 16777215)) LabelWidth = property(None, set_LabelWidth, None, None) def set_Width(self, width): self.comboBox.setMinimumSize(QSize(width, 0)) self.comboBox.setMaximumSize(QSize(width, 16777215)) Width = property(None, set_Width, None, None) def set_Button(self, imageName): if imageName == None or imageName == "": self.imageButton.setVisible(False) return icon = QIcon() icon.addPixmap(QPixmap(("Resource/" + imageName)), QIcon.Normal, QIcon.Off) self.imageButton.setIcon(icon) self.imageButton.setVisible(True) Button = property(None, set_Button, None, None) def get_SelectedIndex(self): return self.comboBox.currentIndex() def set_SelectedIndex(self, index): if self.comboBox.count() == 0: return if index > self.comboBox.count() - 1: self.comboBox.setCurrentIndex(0) else: self.comboBox.setCurrentIndex(index) SelectedIndex = property(get_SelectedIndex, set_SelectedIndex, None, None) def get_Value(self): return self.comboBox.currentIndex() def set_Value(self, valueStr): if self.comboBox.count() == 0: return if valueStr == None: self.SelectedIndex = -1 return self.comboBox.setCurrentIndex(self.comboBox.findText(str(valueStr))) Value = property(get_Value, set_Value, None, None) def get_Items(self): # if self.hasObject: # return self.objectList itemList = [] if self.comboBox.count() > 0: for i in range(self.comboBox.count()): itemList.append(self.comboBox.itemText(i)) return itemList def set_AddItems(self, strList): self.Clear() if len(strList) != 0 and (not isinstance(strList[0], str) and not isinstance(strList[0], QString)): for obj in strList: self.comboBox.addItem(obj.ToString()) self.objectList.append(obj) self.hasObject = True return self.comboBox.addItems(strList) Items = property(get_Items, set_AddItems, None, None) def get_Enabled(self): return self.comboBox.isEnabled() def set_Enabled(self, bool): self.comboBox.setEnabled(bool) Enabled = property(get_Enabled, set_Enabled, None, None) def get_Visible(self): return self.isVisible() def set_Visible(self, bool): self.setVisible(bool) Visible = property(get_Visible, set_Visible, None, None) def get_Editable(self): return self.comboBox.isEditable() def set_Editable(self, bool): self.comboBox.setEditable(bool) Editable = property(get_Editable, set_Editable, None, None) def get_SelectedItem(self): if self.comboBox.count() == 0: return None if self.hasObject: return self.objectList[self.SelectedIndex] return self.comboBox.currentText() def set_SelectedItem(self, val): index = self.comboBox.findText(val) self.comboBox.setCurrentIndex(index) SelectedItem = property(get_SelectedItem, set_SelectedItem, None, None)