def __init__(self, game): SelectRuleset.__init__(self) self.game = game Players.load() self.setWindowTitle(m18n('Select four players') + ' - Kajongg') self.names = None self.nameWidgets = [] for idx, wind in enumerate(WINDS): cbName = QComboBox() cbName.manualSelect = False # increase width, we want to see the full window title cbName.setMinimumWidth(350) # is this good for all platforms? cbName.addItems(Players.humanNames.values()) self.grid.addWidget(cbName, idx + 1, 1) self.nameWidgets.append(cbName) self.grid.addWidget(WindLabel(wind), idx + 1, 0) cbName.currentIndexChanged.connect(self.slotValidate) query = Query( "select p0,p1,p2,p3 from game where seed is null and game.id = (select max(id) from game)" ) if len(query.records): for pidx, playerId in enumerate(query.records[0]): try: playerName = Players.humanNames[playerId] cbName = self.nameWidgets[pidx] playerIdx = cbName.findText(playerName) if playerIdx >= 0: cbName.setCurrentIndex(playerIdx) except KeyError: logError('database is inconsistent: player with id %d is in game but not in player' \ % playerId) self.slotValidate()
class ConfigWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) layout = QFormLayout() self.setLayout(layout) self.label = QLabel("Audio Input") self.inputLayout = QHBoxLayout() self.combobox = QComboBox() self.combobox.setMinimumWidth(150) self.inputSettingsToolButton = QToolButton() self.inputSettingsToolButton.setText("Settings") configIcon = QIcon.fromTheme("preferences-other") self.inputSettingsToolButton.setIcon(configIcon) self.inputSettingsToolButton.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) self.inputSettingsToolButton.setToolButtonStyle(Qt.ToolButtonIconOnly) self.inputSettingsStack = QStackedWidget() blankWidget = QWidget() self.inputSettingsStack.addWidget(blankWidget) self.inputSettingsStack.addWidget(self.inputSettingsToolButton) self.inputLayout.addWidget(self.combobox) self.inputLayout.addWidget(self.inputSettingsStack) layout.addRow(self.label, self.inputLayout)
def __init__(self, game): SelectRuleset.__init__(self) self.game = game Players.load() self.setWindowTitle(m18n('Select four players') + ' - Kajongg') self.names = None self.nameWidgets = [] for idx, wind in enumerate(WINDS): cbName = QComboBox() cbName.manualSelect = False # increase width, we want to see the full window title cbName.setMinimumWidth(350) # is this good for all platforms? cbName.addItems(Players.humanNames.values()) self.grid.addWidget(cbName, idx+1, 1) self.nameWidgets.append(cbName) self.grid.addWidget(WindLabel(wind), idx+1, 0) cbName.currentIndexChanged.connect(self.slotValidate) query = Query("select p0,p1,p2,p3 from game where seed is null and game.id = (select max(id) from game)") if len(query.records): for pidx, playerId in enumerate(query.records[0]): try: playerName = Players.humanNames[playerId] cbName = self.nameWidgets[pidx] playerIdx = cbName.findText(playerName) if playerIdx >= 0: cbName.setCurrentIndex(playerIdx) except KeyError: logError('database is inconsistent: player with id %d is in game but not in player' \ % playerId) self.slotValidate()
class ConfigWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) layout = QFormLayout() self.setLayout(layout) self.label = QLabel("Audio Input") self.inputLayout = QHBoxLayout() self.combobox = QComboBox() self.combobox.setMinimumWidth(150) self.inputSettingsToolButton = QToolButton() self.inputSettingsToolButton.setText("Settings") configIcon = QIcon.fromTheme("preferences-other") self.inputSettingsToolButton.setIcon(configIcon) self.inputSettingsToolButton.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) self.inputSettingsToolButton.setToolButtonStyle(Qt.ToolButtonIconOnly) self.inputSettingsStack = QStackedWidget() blankWidget = QWidget() self.inputSettingsStack.addWidget(blankWidget) self.inputSettingsStack.addWidget(self.inputSettingsToolButton) self.inputLayout.addWidget(self.combobox) self.inputLayout.addWidget(self.inputSettingsStack) layout.addRow(self.label, self.inputLayout)
class ConfigWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) layout = QFormLayout() self.setLayout(layout) self.devicesLabel = QLabel("Video Device") self.devicesCombobox = QComboBox() self.devicesCombobox.setMinimumWidth(150) layout.addRow(self.devicesLabel, self.devicesCombobox)
class ConfigWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) layout = QFormLayout() self.setLayout(layout) self.devicesLabel = QLabel("Video Device") self.devicesCombobox = QComboBox() self.devicesCombobox.setMinimumWidth(150) layout.addRow(self.devicesLabel, self.devicesCombobox)
class AudioVideoTab(QWidget): def __init__(self, parent): super(AudioVideoTab, self).__init__(parent) self.parent = parent self.name = "AudioVideo" self.defaultStr = self.tr("Default") self.DisableStream = self.tr("Disable") self.formats = config.video_formats frequency_values = [self.defaultStr] + config.video_frequency_values bitrate_values = [self.defaultStr] + config.video_bitrate_values rotation_options = [ self.tr("None"), "90 " + self.tr("clockwise"), "90 " + self.tr("clockwise") + " + " + self.tr("vertical flip"), "90 " + self.tr("counter clockwise"), "90 " + self.tr("counter clockwise") + " + " + self.tr("vertical flip"), "180", self.tr("horizontal flip"), self.tr("vertical flip"), ] digits_validator = QRegExpValidator(QRegExp(r"[1-9]\d*"), self) digits_validator_wzero = QRegExpValidator(QRegExp(r"\d*"), self) digits_validator_minus = QRegExpValidator(QRegExp(r"(-1|[1-9]\d*)"), self) time_validator = QRegExpValidator(QRegExp(r"\d{1,2}:\d{1,2}:\d{1,2}\.\d+"), self) converttoQL = QLabel(self.tr("Convert to:")) self.extQCB = QComboBox() self.extQCB.setMinimumWidth(100) vidcodecQL = QLabel("Video codec:") self.vidcodecQCB = QComboBox() self.vidcodecQCB.setMinimumWidth(110) audcodecQL = QLabel("Audio codec:") self.audcodecQCB = QComboBox() self.audcodecQCB.setMinimumWidth(110) hlayout1 = utils.add_to_layout( "h", converttoQL, self.extQCB, QSpacerItem(180, 20), vidcodecQL, self.vidcodecQCB, audcodecQL, self.audcodecQCB, ) commandQL = QLabel(self.tr("Command:")) self.commandQLE = QLineEdit() self.presetQPB = QPushButton(self.tr("Preset")) self.defaultQPB = QPushButton(self.defaultStr) hlayout2 = utils.add_to_layout("h", commandQL, self.commandQLE, self.presetQPB, self.defaultQPB) sizeQL = QLabel(self.tr("Video Size:")) aspectQL = QLabel(self.tr("Aspect:")) frameQL = QLabel(self.tr("Frame Rate (fps):")) bitrateQL = QLabel(self.tr("Video Bitrate (kbps):")) self.widthQLE = utils.create_LineEdit((70, 16777215), digits_validator_minus, 4) self.heightQLE = utils.create_LineEdit((70, 16777215), digits_validator_minus, 4) label = QLabel('<html><p align="center">x</p></html>') layout1 = utils.add_to_layout("h", self.widthQLE, label, self.heightQLE) self.aspect1QLE = utils.create_LineEdit((50, 16777215), digits_validator, 2) self.aspect2QLE = utils.create_LineEdit((50, 16777215), digits_validator, 2) label = QLabel('<html><p align="center">:</p></html>') layout2 = utils.add_to_layout("h", self.aspect1QLE, label, self.aspect2QLE) self.frameQLE = utils.create_LineEdit((120, 16777215), digits_validator, 4) self.bitrateQLE = utils.create_LineEdit((130, 16777215), digits_validator, 6) labels = [sizeQL, aspectQL, frameQL, bitrateQL] widgets = [layout1, layout2, self.frameQLE, self.bitrateQLE] self.preserveaspectQChB = QCheckBox(self.tr("Preserve aspect ratio")) self.preservesizeQChB = QCheckBox(self.tr("Preserve video size")) preserve_layout = utils.add_to_layout("v", self.preserveaspectQChB, self.preservesizeQChB) videosettings_layout = QHBoxLayout() for a, b in zip(labels, widgets): a.setText('<html><p align="center">{0}</p></html>'.format(a.text())) layout = utils.add_to_layout("v", a, b) videosettings_layout.addLayout(layout) if a == aspectQL: # add vidaspectCB in layout after aspectQL videosettings_layout.addLayout(preserve_layout) freqQL = QLabel(self.tr("Frequency (Hz):")) chanQL = QLabel(self.tr("Audio Channels:")) bitrateQL = QLabel(self.tr("Audio Bitrate (kbps):")) threadsQL = QLabel(self.tr("Threads:")) self.freqQCB = QComboBox() self.freqQCB.addItems(frequency_values) self.chan1QRB = QRadioButton("1") self.chan1QRB.setMaximumSize(QSize(51, 16777215)) self.chan2QRB = QRadioButton("2") self.chan2QRB.setMaximumSize(QSize(51, 16777215)) self.group = QButtonGroup() self.group.addButton(self.chan1QRB) self.group.addButton(self.chan2QRB) spcr1 = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum) spcr2 = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum) chanlayout = utils.add_to_layout("h", spcr1, self.chan1QRB, self.chan2QRB, spcr2) self.audbitrateQCB = QComboBox() self.audbitrateQCB.addItems(bitrate_values) self.threadsQLE = utils.create_LineEdit((50, 16777215), digits_validator_wzero, 1) labels = [freqQL, bitrateQL, chanQL, threadsQL] widgets = [self.freqQCB, self.audbitrateQCB, chanlayout, self.threadsQLE] audiosettings_layout = QHBoxLayout() for a, b in zip(labels, widgets): a.setText('<html><p align="center">{0}</p></html>'.format(a.text())) layout = utils.add_to_layout("v", a, b) audiosettings_layout.addLayout(layout) time_format = " (hh:mm:ss):" beginQL = QLabel(self.tr("Split file. Begin time") + time_format) self.beginQLE = utils.create_LineEdit(None, time_validator, None) durationQL = QLabel(self.tr("Duration") + time_format) self.durationQLE = utils.create_LineEdit(None, time_validator, None) hlayout4 = utils.add_to_layout("h", beginQL, self.beginQLE, durationQL, self.durationQLE) embedQL = QLabel(self.tr("Embed subtitle:")) self.embedQLE = QLineEdit() self.embedQTB = QToolButton() self.embedQTB.setText("...") rotateQL = QLabel(self.tr("Rotate:")) self.rotateQCB = QComboBox() self.rotateQCB.addItems(rotation_options) hlayout5 = utils.add_to_layout("h", rotateQL, self.rotateQCB, embedQL, self.embedQLE, self.embedQTB) hidden_layout = utils.add_to_layout("v", videosettings_layout, audiosettings_layout, hlayout4, hlayout5) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.moreQPB = QPushButton(QApplication.translate("Tab", "More")) self.moreQPB.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.moreQPB.setCheckable(True) hlayout3 = utils.add_to_layout("h", line, self.moreQPB) self.frame = QFrame() self.frame.setLayout(hidden_layout) self.frame.hide() final_layout = utils.add_to_layout("v", hlayout1, hlayout2, hlayout3, self.frame) self.setLayout(final_layout) self.presetQPB.clicked.connect(self.choose_preset) self.defaultQPB.clicked.connect(self.set_default_command) self.embedQTB.clicked.connect(self.open_subtitle_file) self.moreQPB.toggled.connect(self.frame.setVisible) self.moreQPB.toggled.connect(lambda: QTimer.singleShot(100, self.resize_parent)) self.widthQLE.textChanged.connect(self.command_update_size) self.heightQLE.textChanged.connect(self.command_update_size) self.aspect1QLE.textChanged.connect(self.command_update_aspect) self.aspect2QLE.textChanged.connect(self.command_update_aspect) self.frameQLE.textChanged.connect(self.command_update_frames) self.bitrateQLE.textChanged.connect(self.command_update_vidbitrate) self.threadsQLE.textChanged.connect(self.command_update_threads) self.beginQLE.textChanged.connect(self.command_update_begin_time) self.durationQLE.textChanged.connect(self.command_update_duration) self.embedQLE.textChanged.connect(self.command_update_subtitles) self.vidcodecQCB.currentIndexChanged.connect(self.command_update_vcodec) self.audcodecQCB.currentIndexChanged.connect(self.command_update_acodec) self.freqQCB.currentIndexChanged.connect(self.command_update_frequency) self.rotateQCB.currentIndexChanged.connect(self.command_update_rotation) self.audbitrateQCB.currentIndexChanged.connect(self.command_update_audbitrate) self.chan1QRB.clicked.connect(lambda: self.command_update_channels("1")) self.chan2QRB.clicked.connect(lambda: self.command_update_channels("2")) self.preserveaspectQChB.toggled.connect(self.command_update_preserve_aspect) self.preservesizeQChB.toggled.connect(self.command_update_preserve_size) def resize_parent(self): """Give MainWindow its default size.""" self.parent.setMinimumSize(self.parent.sizeHint()) self.parent.resize(self.parent.sizeHint()) def clear(self): """Clear all values of graphical widgets.""" lines = [ self.commandQLE, self.widthQLE, self.heightQLE, self.aspect1QLE, self.aspect2QLE, self.frameQLE, self.bitrateQLE, self.threadsQLE, self.beginQLE, self.embedQLE, self.durationQLE, ] for i in lines: i.clear() self.vidcodecQCB.setCurrentIndex(0) self.audcodecQCB.setCurrentIndex(0) self.freqQCB.setCurrentIndex(0) self.audbitrateQCB.setCurrentIndex(0) self.rotateQCB.setCurrentIndex(0) self.preserveaspectQChB.setChecked(False) self.preservesizeQChB.setChecked(False) self.group.setExclusive(False) self.chan1QRB.setChecked(False) self.chan2QRB.setChecked(False) self.group.setExclusive(True) # setExclusive(False) in order to be able to uncheck checkboxes and # then setExclusive(True) so only one radio button can be set def fill_video_comboboxes(self, vcodecs, acodecs, extraformats): vcodecs = [i for i in vcodecs.split("\n")] if vcodecs else [] acodecs = [i for i in acodecs.split("\n")] if acodecs else [] extraformats = [i for i in extraformats.split("\n")] if extraformats else [] self.vidcodecQCB.currentIndexChanged.disconnect() self.audcodecQCB.currentIndexChanged.disconnect() self.vidcodecQCB.clear() self.audcodecQCB.clear() self.extQCB.clear() self.vidcodecQCB.addItems([self.defaultStr, self.DisableStream] + vcodecs) self.audcodecQCB.addItems([self.defaultStr, self.DisableStream] + acodecs) self.extQCB.addItems(sorted(self.formats + extraformats)) self.vidcodecQCB.currentIndexChanged.connect(self.command_update_vcodec) self.audcodecQCB.currentIndexChanged.connect(self.command_update_acodec) def ok_to_continue(self): """ Check if everything is ok with audiovideotab to continue conversion. Check if: - Either ffmpeg or avconv are installed. Return True if all tests pass, else False. """ if self.parent.vidconverter is None: QMessageBox.warning( self, "FF Multi Converter - " + self.tr("Error!"), self.tr( "Neither ffmpeg nor libav are installed." "\nYou will not be able to convert audio/video files until you" " install one of them." ), ) return False return True def open_subtitle_file(self): """ Get the filename using standard QtDialog and update embedQLE's text. """ fname = QFileDialog.getOpenFileName( self, "FF Multi Converter - " + self.tr("Choose File"), config.home, "Subtitles (*.srt *.sub *.ssa *.ass)" ) if fname: self.embedQLE.setText(fname) def set_default_command(self): """Set the default value to self.commandQLE.""" self.clear() self.commandQLE.setText(self.parent.default_command) def choose_preset(self): """ Open the presets dialog and update self.commandQLE, and self.extQCB and with the appropriate values. """ dialog = presets_dlgs.ShowPresets(choose=True) if dialog.exec_() and dialog.the_command is not None: self.clear() self.commandQLE.setText(dialog.the_command) self.commandQLE.home(False) find = self.extQCB.findText(dialog.the_extension) if find >= 0: self.extQCB.setCurrentIndex(find) def command_update_size(self): command = self.commandQLE.text() text1 = self.widthQLE.text() text2 = self.heightQLE.text() if not (text1 == "-1" or text2 == "-1"): self.preserveaspectQChB.setChecked(False) if (text1 or text2) and not (text1 and text2) or (text1 == "-" or text2 == "-"): return regex = r"(\s+|^)-s(:v){0,1}\s+\d+x\d+(\s+|$)" if re.search(regex, command): command = re.sub(regex, "", command) regex = r"(,*\s*){0,1}(scale=-?\d+:-?\d+)(\s*,*\s*){0,1}" _filter = "scale={0}:{1}".format(text1, text2) if text1 and text2 else "" self.commandQLE.setText(utils.update_cmdline_text(command, _filter, regex, bool(text1 and text2), 0, 2)) def command_update_preserve_size(self): checked = self.preservesizeQChB.isChecked() self.widthQLE.setEnabled(not checked) self.heightQLE.setEnabled(not checked) if checked: self.widthQLE.clear() self.heightQLE.clear() # command_update_size() is triggered here command = self.commandQLE.text() regex = r"(\s+|^)-s\s+\d+x\d+(\s+|$)" command = re.sub(" +", " ", re.sub(regex, " ", command)).strip() self.commandQLE.setText(command) def command_update_aspect(self): command = self.commandQLE.text() text1 = self.aspect1QLE.text() text2 = self.aspect2QLE.text() if (text1 or text2) and not (text1 and text2): return regex = r"(\s+|^)-aspect\s+\d+:\d+(\s+|$)" s = " -aspect {0}:{1} ".format(text1, text2) if text1 and text2 else " " if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(" +", " ", command).strip() self.commandQLE.setText(command) def command_update_preserve_aspect(self): command = self.commandQLE.text() checked = self.preserveaspectQChB.isChecked() self.aspect1QLE.setEnabled(not checked) self.aspect2QLE.setEnabled(not checked) if checked: self.aspect1QLE.clear() self.aspect2QLE.clear() # self.command_update_aspect() is triggered here regex = r"(,*\s*){0,1}(scale=(-?\d+):(-?\d+))(\s*,*\s*){0,1}" search = re.search(regex, command) if search: width = search.groups()[2] height = search.groups()[3] if not (width == "-1" or height == "-1"): s = "scale=-1:{0}".format(height) command = re.sub(regex, r"\1{0}\5".format(s), command) self.widthQLE.setText("-1") self.heightQLE.setText(height) regex = r"(\s+|^)-aspect\s+\d+:\d+(\s+|$)" command = re.sub(" +", " ", re.sub(regex, " ", command)).strip() self.commandQLE.setText(command) def command_update_frames(self): command = self.commandQLE.text() text = self.frameQLE.text() regex = r"(\s+|^)-r\s+\d+(\s+|$)" s = " -r {0} ".format(text) if text else " " if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(" +", " ", command).strip() self.commandQLE.setText(command) def command_update_vidbitrate(self): command = self.commandQLE.text() text = self.bitrateQLE.text() regex = r"(\s+|^)-b(:v){0,1}\s+\d+[kKmM](\s+|$)" s = " -b:v {0}k ".format(text) if text else " " if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub("-sameq", "", command) command = re.sub(" +", " ", command).strip() self.commandQLE.setText(command) def command_update_frequency(self): command = self.commandQLE.text() text = self.freqQCB.currentText() regex = r"(\s+|^)-ar\s+\d+(\s+|$)" s = " -ar {0} ".format(text) if self.freqQCB.currentIndex() != 0 else " " if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(" +", " ", command).strip() self.commandQLE.setText(command) def command_update_audbitrate(self): command = self.commandQLE.text() text = self.audbitrateQCB.currentText() regex = r"(\s+|^)-(ab|b:a)\s+\d+[kKmM](\s+|$)" if self.audbitrateQCB.currentIndex() != 0: s = " -b:a {0}k ".format(text) else: s = " " if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(" +", " ", command).strip() self.commandQLE.setText(command) def command_update_channels(self, channel): command = self.commandQLE.text() regex = r"(\s+|^)-ac\s+\d+(\s+|$)" s = " -ac {0} ".format(channel) if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(" +", " ", command).strip() self.commandQLE.setText(command) def command_update_threads(self): command = self.commandQLE.text() text = self.threadsQLE.text() regex = r"(\s+|^)-threads\s+\d+(\s+|$)" s = " -threads {0} ".format(text) if text else " " if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(" +", " ", command).strip() self.commandQLE.setText(command) def command_update_begin_time(self): command = self.commandQLE.text() text = self.beginQLE.text() regex = r"(\s+|^)-ss\s+\S+(\s+|$)" s = " -ss {0} ".format(text) if text else " " if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(" +", " ", command).strip() self.commandQLE.setText(command) def command_update_duration(self): command = self.commandQLE.text() text = self.durationQLE.text() regex = r"(\s+|^)-t\s+\S+(\s+|$)" s = " -t {0} ".format(text) if text else " " if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(" +", " ", command).strip() self.commandQLE.setText(command) def command_update_vcodec(self): command = self.commandQLE.text() text = self.vidcodecQCB.currentText() regex = r"(\s+|^)-(vcodec|c:v)\s+\S+(\s+|$)" regex_vn = r"(\s+|^)-vn(\s+|$)" if self.vidcodecQCB.currentIndex() == 1: s = " -vn ".format(text) elif self.vidcodecQCB.currentIndex() == 0: s = " " else: s = " -vcodec {0} ".format(text) if re.search(regex, command): command = re.sub(regex, s, command) elif re.search(regex_vn, command): command = re.sub(regex_vn, s, command) else: command += s command = re.sub(" +", " ", command).strip() self.commandQLE.setText(command) def command_update_acodec(self): command = self.commandQLE.text() text = self.audcodecQCB.currentText() regex = r"(\s+|^)-(acodec|c:a)\s+\S+(\s+|$)" regex_an = r"(\s+|^)-an(\s+|$)" if self.audcodecQCB.currentIndex() == 1: s = " -an ".format(text) elif self.audcodecQCB.currentIndex() == 0: s = " " else: s = " -acodec {0} ".format(text) if re.search(regex, command): command = re.sub(regex, s, command) elif re.search(regex_an, command): command = re.sub(regex_an, s, command) else: command += s command = re.sub(" +", " ", command).strip() self.commandQLE.setText(command) def command_update_subtitles(self): command = self.commandQLE.text() regex = r"(,*\s*){0,1}(subtitles=\'.*\')(\s*,*\s*){0,1}" text = self.embedQLE.text() _filter = "subtitles='{0}'".format(text) if text else "" self.commandQLE.setText(utils.update_cmdline_text(command, _filter, regex, bool(text), 0, 2)) def command_update_rotation(self): command = self.commandQLE.text() regex = r"(,*\s*){0,1}(transpose=\d(,\s*transpose=\d)*|vflip|hflip)(\s*,*\s*){0,1}" rotate = self.rotateQCB.currentIndex() if rotate == 0: # none _filter = "" elif rotate == 1: # 90 clockwise _filter = "transpose=1" elif rotate == 2: # 90 clockwise + vertical flip _filter = "transpose=3" elif rotate == 3: # 90 counter clockwise _filter = "transpose=2" elif rotate == 4: # 90 counter clockwise + vertical flip _filter = "transpose=0" elif rotate == 5: # 180 _filter = "transpose=2,transpose=2" elif rotate == 6: # horizontal flip _filter = "hflip" elif rotate == 7: # vertical flip _filter = "vflip" self.commandQLE.setText(utils.update_cmdline_text(command, _filter, regex, bool(rotate != 0), 0, 3))
class AudioVideoTab(QWidget): def __init__(self, parent): super(AudioVideoTab, self).__init__(parent) self.parent = parent self.name = 'AudioVideo' self.formats = [ '3gp', 'aac', 'ac3', 'afc', 'aiff', 'amr', 'asf', 'au', 'avi', 'dvd', 'flac', 'flv', 'mka', 'mkv', 'mmf', 'mov', 'mp3', 'mp4', 'mpg', 'ogg', 'ogv', 'psp', 'rm', 'spx', 'vob', 'wav', 'webm', 'wma', 'wmv' ] self.extra_formats = [ 'aifc', 'm2t', 'm4a', 'm4v', 'mp2', 'mpeg', 'ra', 'ts' ] nochange = self.tr('No Change') frequency_values = [nochange, '22050', '44100', '48000'] bitrate_values = [ nochange, '32', '96', '112', '128', '160', '192', '256', '320' ] pattern = QRegExp(r'^[1-9]\d*') validator = QRegExpValidator(pattern, self) converttoLabel = QLabel(self.tr('Convert to:')) self.extComboBox = QComboBox() self.extComboBox.addItems(self.formats + [self.tr('Other')]) self.extComboBox.setMinimumWidth(130) self.extLineEdit = QLineEdit() self.extLineEdit.setMaximumWidth(85) self.extLineEdit.setEnabled(False) hlayout1 = pyqttools.add_to_layout(QHBoxLayout(), converttoLabel, None, self.extComboBox, self.extLineEdit) commandLabel = QLabel(self.tr('Command:')) self.commandLineEdit = QLineEdit() self.presetButton = QPushButton(self.tr('Preset')) self.defaultButton = QPushButton(self.tr('Default')) hlayout2 = pyqttools.add_to_layout(QHBoxLayout(), commandLabel, self.commandLineEdit, self.presetButton, self.defaultButton) sizeLabel = QLabel(self.tr('Video Size:')) aspectLabel = QLabel(self.tr('Aspect:')) frameLabel = QLabel(self.tr('Frame Rate (fps):')) bitrateLabel = QLabel(self.tr('Video Bitrate (kbps):')) self.widthLineEdit = pyqttools.create_LineEdit((50, 16777215), validator, 4) self.heightLineEdit = pyqttools.create_LineEdit((50, 16777215), validator, 4) label = QLabel('x') layout1 = pyqttools.add_to_layout(QHBoxLayout(), self.widthLineEdit, label, self.heightLineEdit) self.aspect1LineEdit = pyqttools.create_LineEdit((35, 16777215), validator, 2) self.aspect2LineEdit = pyqttools.create_LineEdit((35, 16777215), validator, 2) label = QLabel(':') layout2 = pyqttools.add_to_layout(QHBoxLayout(), self.aspect1LineEdit, label, self.aspect2LineEdit) self.frameLineEdit = pyqttools.create_LineEdit(None, validator, 4) self.bitrateLineEdit = pyqttools.create_LineEdit(None, validator, 6) labels = [sizeLabel, aspectLabel, frameLabel, bitrateLabel] widgets = [layout1, layout2, self.frameLineEdit, self.bitrateLineEdit] videosettings_layout = QHBoxLayout() for a, b in zip(labels, widgets): text = a.text() a.setText('<html><p align="center">{0}</p></html>'.format(text)) layout = pyqttools.add_to_layout(QVBoxLayout(), a, b) videosettings_layout.addLayout(layout) freqLabel = QLabel(self.tr('Frequency (Hz):')) chanLabel = QLabel(self.tr('Channels:')) bitrateLabel = QLabel(self.tr('Audio Bitrate (kbps):')) self.freqComboBox = QComboBox() self.freqComboBox.addItems(frequency_values) self.chan1RadioButton = QRadioButton('1') self.chan1RadioButton.setMaximumSize(QSize(51, 16777215)) self.chan2RadioButton = QRadioButton('2') self.chan2RadioButton.setMaximumSize(QSize(51, 16777215)) self.group = QButtonGroup() self.group.addButton(self.chan1RadioButton) self.group.addButton(self.chan2RadioButton) spcr1 = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum) spcr2 = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum) chanlayout = pyqttools.add_to_layout(QHBoxLayout(), spcr1, self.chan1RadioButton, self.chan2RadioButton, spcr2) self.audio_bitrateComboBox = QComboBox() self.audio_bitrateComboBox.addItems(bitrate_values) labels = [freqLabel, chanLabel, bitrateLabel] widgets = [self.freqComboBox, chanlayout, self.audio_bitrateComboBox] audiosettings_layout = QHBoxLayout() for a, b in zip(labels, widgets): text = a.text() a.setText('<html><p align="center">{0}</p></html>'.format(text)) layout = pyqttools.add_to_layout(QVBoxLayout(), a, b) audiosettings_layout.addLayout(layout) hidden_layout = pyqttools.add_to_layout(QVBoxLayout(), videosettings_layout, audiosettings_layout) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.moreButton = QPushButton(QApplication.translate('Tab', 'More')) self.moreButton.setSizePolicy(QSizePolicy(QSizePolicy.Fixed)) self.moreButton.setCheckable(True) hlayout3 = pyqttools.add_to_layout(QHBoxLayout(), line, self.moreButton) self.frame = QFrame() self.frame.setLayout(hidden_layout) self.frame.hide() final_layout = pyqttools.add_to_layout(QVBoxLayout(), hlayout1, hlayout2, hlayout3, self.frame) self.setLayout(final_layout) self.presetButton.clicked.connect(self.choose_preset) self.defaultButton.clicked.connect(self.set_default_command) self.moreButton.toggled.connect(self.frame.setVisible) self.moreButton.toggled.connect(self.resize_parent) self.extComboBox.currentIndexChanged.connect( lambda: self.extLineEdit.setEnabled(self.extComboBox.currentIndex( ) == len(self.formats))) self.widthLineEdit.textChanged.connect( lambda: self.command_elements_change('size')) self.heightLineEdit.textChanged.connect( lambda: self.command_elements_change('size')) self.aspect1LineEdit.textChanged.connect( lambda: self.command_elements_change('aspect')) self.aspect2LineEdit.textChanged.connect( lambda: self.command_elements_change('aspect')) self.frameLineEdit.textChanged.connect( lambda: self.command_elements_change('frames')) self.bitrateLineEdit.textChanged.connect( lambda: self.command_elements_change('video_bitrate')) self.freqComboBox.currentIndexChanged.connect( lambda: self.command_elements_change('frequency')) self.audio_bitrateComboBox.currentIndexChanged.connect( lambda: self.command_elements_change('audio_bitrate')) self.chan1RadioButton.clicked.connect( lambda: self.command_elements_change('channels1')) self.chan2RadioButton.clicked.connect( lambda: self.command_elements_change('channels2')) def resize_parent(self): """Resize MainWindow.""" height = MAIN_FIXED_HEIGHT if self.frame.isVisible() else MAIN_HEIGHT self.parent.setMinimumSize(MAIN_WIDTH, height) self.parent.resize(MAIN_WIDTH, height) def clear(self): """Clear all values of graphical widgets.""" lines = [ self.commandLineEdit, self.widthLineEdit, self.heightLineEdit, self.aspect1LineEdit, self.aspect2LineEdit, self.frameLineEdit, self.bitrateLineEdit, self.extLineEdit ] for i in lines: i.clear() self.freqComboBox.setCurrentIndex(0) self.audio_bitrateComboBox.setCurrentIndex(0) self.group.setExclusive(False) self.chan1RadioButton.setChecked(False) self.chan2RadioButton.setChecked(False) self.group.setExclusive(True) # setExclusive(False) in order to be able to uncheck checkboxes and # then setExclusive(True) so only one radio button can be set def ok_to_continue(self): """ Check if everything is ok with audiovideotab to continue conversion. Check if: - Either ffmpeg or avconv are installed. - Desired extension is valid. - self.commandLineEdit is empty. Return True if all tests pass, else False. """ if not self.parent.ffmpeg and not self.parent.avconv: QMessageBox.warning( self, 'FF Multi Converter - ' + self.tr('Error!'), self. tr('Neither ffmpeg nor avconv are installed.' '\nYou will not be able to convert audio/video files until you' ' install one of them.')) return False if self.extLineEdit.isEnabled(): text = str(self.extLineEdit.text()).strip() if len(text.split()) != 1 or text[0] == '.': QMessageBox.warning( self, 'FF Multi Converter - ' + self.tr('Error!'), self.tr('Extension must be one word and must ' 'not start with a dot.')) self.extLineEdit.selectAll() self.extLineEdit.setFocus() return False if not self.commandLineEdit.text(): QMessageBox.warning( self, 'FF Multi Converter - ' + self.tr('Error!'), self.tr('The command LineEdit may not be empty.')) self.commandLineEdit.setFocus() return False return True def set_default_command(self): """Set the default value to self.commandLineEdit.""" self.clear() self.commandLineEdit.setText(self.parent.default_command) def choose_preset(self): """ Open the presets dialog and update self.commandLineEdit, self.extComboBox and self.extLineEdit with the appropriate values. """ dialog = presets_dlgs.ShowPresets() if dialog.exec_() and dialog.the_command is not None: self.commandLineEdit.setText(dialog.the_command) self.commandLineEdit.home(False) find = self.extComboBox.findText(dialog.the_extension) if find >= 0: self.extComboBox.setCurrentIndex(find) else: self.extComboBox.setCurrentIndex(len(self.formats)) self.extLineEdit.setText(dialog.the_extension) def remove_consecutive_spaces(self, string): """Remove any consecutive spaces from a string and return it.""" temp = string string = '' for i in temp.split(): if i: string += i + ' ' return string[:-1] def command_elements_change(self, widget): """Fill self.commandLineEdit with the appropriate command parameters.""" command = str(self.commandLineEdit.text()) if widget == 'size': text1 = self.widthLineEdit.text() text2 = self.heightLineEdit.text() if (text1 or text2) and not (text1 and text2): return f = re.sub(r'^.*(-s\s+\d+x\d+).*$', r'\1', command) if re.match(r'^.*(-s\s+\d+x\d+).*$', f): command = command.replace(f, '').strip() if text1 and text2: command += ' -s {0}x{1}'.format(text1, text2) elif widget == 'aspect': text1 = self.aspect1LineEdit.text() text2 = self.aspect2LineEdit.text() if (text1 or text2) and not (text1 and text2): return f = re.sub(r'^.*(-aspect\s+\d+:\d+).*$', r'\1', command) if re.match(r'^.*(-aspect\s+\d+:\d+).*$', f): command = command.replace(f, '').strip() if text1 and text2: command += ' -aspect {0}:{1}'.format(text1, text2) elif widget == 'frames': text = self.frameLineEdit.text() f = re.sub(r'^.*(-r\s+\d+).*$', r'\1', command) if re.match(r'^.*(-r\s+\d+).*$', f): command = command.replace(f, '').strip() if text: command += ' -r {0}'.format(text) elif widget == 'video_bitrate': text = self.bitrateLineEdit.text() f = re.sub(r'^.*(-b\s+\d+k).*$', r'\1', command) if re.match(r'^.*(-b\s+\d+k).*$', f): command = command.replace(f, '') if text: command += ' -b {0}k'.format(text) command = command.replace('-sameq', '').strip() elif widget == 'frequency': text = self.freqComboBox.currentText() f = re.sub(r'^.*(-ar\s+\d+).*$', r'\1', command) if re.match(r'^.*(-ar\s+\d+).*$', f): command = command.replace(f, '').strip() if text != 'No Change': command += ' -ar {0}'.format(text) elif widget == 'audio_bitrate': text = self.audio_bitrateComboBox.currentText() f = re.sub(r'^.*(-ab\s+\d+k).*$', r'\1', command) if re.match(r'^.*(-ab\s+\d+k).*$', f): command = command.replace(f, '').strip() if text != 'No Change': command += ' -ab {0}k'.format(text) elif widget in ('channels1', 'channels2'): text = self.chan1RadioButton.text() if widget == 'channels1' \ else self.chan2RadioButton.text() f = re.sub(r'^.*(-ac\s+\d+).*$', r'\1', command) if re.match(r'^.*(-ac\s+\d+).*$', f): command = command.replace(f, '').strip() command += ' -ac {0}'.format(text) self.commandLineEdit.clear() self.commandLineEdit.setText(self.remove_consecutive_spaces(command))
class FilteringModule(PreprocessorModule): DEFAULT_SETTINGS = { 'is_enabled': True, 'methods': [True, False, False], 'recent_sw_files': [], 'min_df': None, 'max_df': None, } English, Custom, DocumentFrequency = 0, 1, 2 filtering_values = { English: 'english', Custom: [], DocumentFrequency: (None, None), } filter_names = { English: 'English stop words', Custom: 'Custom stop words', DocumentFrequency: 'Filter by token frequency', } filtering_methods = [True, False, False] dlgFormats = 'Only text files (*.txt)' recent_sw_files = [] def __init__(self, data): data = data or self.DEFAULT_SETTINGS PreprocessorModule.__init__( self, 'Token filtering', True, data.get('is_enabled') ) self.group = QButtonGroup(self, exclusive=False) # --- English --- cb = QCheckBox(self, text=self.filter_names[self.English]) self.add_to_content_area(cb) self.group.addButton(cb, self.English) # --- Custom --- cb = QCheckBox(self, text=self.filter_names[self.Custom]) self.add_to_content_area(cb) self.group.addButton(cb, self.Custom) # File browser. file_browser_layout = QHBoxLayout() file_browser_layout.setContentsMargins(20, 0, 0, 0) self.sw_file_combo = QComboBox() self.sw_file_combo.setMinimumWidth(200) file_browser_layout.addWidget(self.sw_file_combo) self.sw_file_combo.activated[int].connect(self.select_file) self.browse_button = QPushButton(self) self.browse_button.clicked.connect(self.browse_file) self.browse_button.setIcon(self.style() .standardIcon(QStyle.SP_DirOpenIcon)) self.browse_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) file_browser_layout.addWidget(self.browse_button) # Reload button self.reload_button = QPushButton(self) self.reload_button.clicked.connect(self.on_reload_button_clicked) self.reload_button.setIcon(self.style() .standardIcon(QStyle.SP_BrowserReload)) self.reload_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) file_browser_layout.addWidget(self.reload_button) self.add_layout_to_content_area(file_browser_layout) # --- DF --- df_info_text = """ Remove all tokens that appear in less than 'min-df' documents. Remove all tokens that appear in more than 'max-df' documents. Values can be either integers or floats (ratio of documents). """ cb = QCheckBox(self, text=self.filter_names[self.DocumentFrequency]) self.add_to_content_area(cb) self.group.addButton(cb, self.DocumentFrequency) df_info_text = QLabel(df_info_text) df_info_text.setContentsMargins(0,0,0,0) df_info_text.setStyleSheet(""" font-size: 11px; font-style: italic; """) self.add_to_content_area(df_info_text) # Min/Max-Df setter. df_setter_layout = QHBoxLayout() df_setter_layout.setContentsMargins(20, 0, 0, 0) self.min_df_input = QLineEdit() self.min_df_input.textChanged.connect(self.update_df_parameters) self.max_df_input = QLineEdit() self.max_df_input.textChanged.connect(self.update_df_parameters) df_setter_layout.addWidget(QLabel('Min-df:')) df_setter_layout.addWidget(self.min_df_input) df_setter_layout.addWidget(QLabel('Max-df:')) df_setter_layout.addWidget(self.max_df_input) self.add_layout_to_content_area(df_setter_layout) self.group.buttonClicked.connect(self.group_button_clicked) # Restore the widget to its previous state. self.restore_data(data) def str_to_num(self, s): if not s: return None try: return int(s) except ValueError: pass # Not an int. Continue. try: return float(s) except ValueError: # Not a float either. self.send_message('Input "{}" cannot be cast into a number.' .format(s)) return None def send_message(self, message): # Sends a message with the "message" signal, to the main widget. self.error_signal.emit(message) # --- File selection. def select_file(self, n): if n < len(self.recent_sw_files): name = self.recent_sw_files[n] del self.recent_sw_files[n] self.recent_sw_files.insert(0, name) if len(self.recent_sw_files) > 0: self.set_file_list() self.open_file(self.recent_sw_files[0]) def set_file_list(self): self.sw_file_combo.clear() if not self.recent_sw_files: self.sw_file_combo.addItem('(none)') else: for file in self.recent_sw_files: self.sw_file_combo.addItem(os.path.split(file)[1]) def browse_file(self): # Opens the file browser, starting at the home directory. start_file = os.path.expanduser('~/') # Get the file path from the browser window. path = QFileDialog.getOpenFileName(self, 'Open a stop words source', start_file, self.dlgFormats) if not path: return if path in self.recent_sw_files: self.recent_sw_files.remove(path) self.recent_sw_files.insert(0, path) self.set_file_list() self.open_file(path) def update_df_parameters(self): min_df = None if not self.min_df_input.text() else self.min_df_input.text() max_df = None if not self.max_df_input.text() else self.max_df_input.text() self.filtering_values[self.DocumentFrequency] = (min_df, max_df) self.notify_on_change() def open_file(self, path): try: with open(path) as f: # Read most recent. self.filtering_values[self.Custom] = [sw.strip() for sw in f.read().splitlines()] self.notify_on_change() except Exception: # Raise an exception otherwise. self.send_message('Could not open "{}".' .format(path)) def on_reload_button_clicked(self): if self.recent_sw_files: self.select_file(0) # END File selection. def group_button_clicked(self): self.filtering_methods = [ch_box.isChecked() for ch_box in self.group.buttons()] self.enable_choice_settings() # Emit the signal. self.notify_on_change() def enable_choice_settings(self): self.sw_file_combo.setEnabled(self.filtering_methods[1]) self.browse_button.setEnabled(self.filtering_methods[1]) self.reload_button.setEnabled(self.filtering_methods[1]) self.min_df_input.setEnabled(self.filtering_methods[2]) self.max_df_input.setEnabled(self.filtering_methods[2]) def get_pp_setting(self): flag_english = self.filtering_methods[0] flag_custom = self.filtering_methods[1] flag_df = self.filtering_methods[2] if flag_english and flag_custom: # Use custom. stop_words = { 'stop_words': stopwords.words('english') + self.filtering_values[self.Custom] } elif flag_english and not flag_custom: stop_words = { 'stop_words': 'english' } elif flag_custom: stop_words = { 'stop_words': self.filtering_values[self.Custom] } else: stop_words = {} if flag_df: stop_words.update({ 'min_df': self.str_to_num(self.min_df_input.text()), 'max_df': self.str_to_num(self.max_df_input.text()), }) return stop_words def restore_data(self, data): self.recent_sw_files = data.get('recent_sw_files') self.min_df_input.setText(data.get('min_df')) self.max_df_input.setText(data.get('max_df')) self.filtering_methods = data.get('methods') for flag, ch_box in zip(self.filtering_methods, self.group.buttons()): ch_box.setChecked(flag) self.enable_choice_settings() # Enable the settings if set. self.set_file_list() # Fill the combo box with the recent sw files. self.select_file(0) # Select the first file. def export_data(self): return { 'is_enabled': self.enabled, 'methods': self.filtering_methods, 'recent_sw_files': self.recent_sw_files, 'min_df': self.min_df_input.text(), 'max_df': self.max_df_input.text(), }
class AudioVideoTab(QWidget): def __init__(self, parent): super(AudioVideoTab, self).__init__(parent) self.parent = parent self.name = 'AudioVideo' self.formats = ['3gp', 'aac', 'ac3', 'afc', 'aiff', 'amr', 'asf', 'au', 'avi', 'dvd', 'flac', 'flv', 'mka', 'mkv', 'mmf', 'mov', 'mp3', 'mp4', 'mpg', 'ogg', 'ogv', 'psp', 'rm', 'spx', 'vob', 'wav', 'webm', 'wma', 'wmv'] self.extra_formats = ['aifc', 'm2t', 'm4a', 'm4v', 'mp2', 'mpeg', 'ra', 'ts'] nochange = self.tr('No Change') frequency_values = [nochange, '22050', '44100', '48000'] bitrate_values = [nochange, '32', '96', '112', '128', '160', '192', '256', '320'] pattern = QRegExp(r'^[1-9]\d*') validator = QRegExpValidator(pattern, self) converttoLabel = QLabel(self.tr('Convert to:')) self.extComboBox = QComboBox() self.extComboBox.addItems(self.formats + [self.tr('Other')]) self.extComboBox.setMinimumWidth(130) self.extLineEdit = QLineEdit() self.extLineEdit.setMaximumWidth(85) self.extLineEdit.setEnabled(False) hlayout1 = pyqttools.add_to_layout(QHBoxLayout(), converttoLabel, None, self.extComboBox, self.extLineEdit) commandLabel = QLabel(self.tr('Command:')) self.commandLineEdit = QLineEdit() self.presetButton = QPushButton(self.tr('Preset')) self.defaultButton = QPushButton(self.tr('Default')) hlayout2 = pyqttools.add_to_layout(QHBoxLayout(), commandLabel, self.commandLineEdit, self.presetButton, self.defaultButton) sizeLabel = QLabel(self.tr('Video Size:')) aspectLabel = QLabel(self.tr('Aspect:')) frameLabel = QLabel(self.tr('Frame Rate (fps):')) bitrateLabel = QLabel(self.tr('Video Bitrate (kbps):')) self.widthLineEdit = pyqttools.create_LineEdit((50, 16777215), validator, 4) self.heightLineEdit = pyqttools.create_LineEdit((50, 16777215), validator,4) label = QLabel('x') layout1 = pyqttools.add_to_layout(QHBoxLayout(), self.widthLineEdit, label, self.heightLineEdit) self.aspect1LineEdit = pyqttools.create_LineEdit((35, 16777215), validator,2) self.aspect2LineEdit = pyqttools.create_LineEdit((35, 16777215), validator,2) label = QLabel(':') layout2 = pyqttools.add_to_layout(QHBoxLayout(), self.aspect1LineEdit, label, self.aspect2LineEdit) self.frameLineEdit = pyqttools.create_LineEdit(None, validator, 4) self.bitrateLineEdit = pyqttools.create_LineEdit(None, validator, 6) labels = [sizeLabel, aspectLabel, frameLabel, bitrateLabel] widgets = [layout1, layout2, self.frameLineEdit, self.bitrateLineEdit] videosettings_layout = QHBoxLayout() for a, b in zip(labels, widgets): text = a.text() a.setText('<html><p align="center">{0}</p></html>'.format(text)) layout = pyqttools.add_to_layout(QVBoxLayout(), a, b) videosettings_layout.addLayout(layout) freqLabel = QLabel(self.tr('Frequency (Hz):')) chanLabel = QLabel(self.tr('Channels:')) bitrateLabel = QLabel(self.tr('Audio Bitrate (kbps):')) self.freqComboBox = QComboBox() self.freqComboBox.addItems(frequency_values) self.chan1RadioButton = QRadioButton('1') self.chan1RadioButton.setMaximumSize(QSize(51, 16777215)) self.chan2RadioButton = QRadioButton('2') self.chan2RadioButton.setMaximumSize(QSize(51, 16777215)) self.group = QButtonGroup() self.group.addButton(self.chan1RadioButton) self.group.addButton(self.chan2RadioButton) spcr1 = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum) spcr2 = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum) chanlayout = pyqttools.add_to_layout(QHBoxLayout(), spcr1, self.chan1RadioButton, self.chan2RadioButton, spcr2) self.audio_bitrateComboBox = QComboBox() self.audio_bitrateComboBox.addItems(bitrate_values) labels = [freqLabel, chanLabel, bitrateLabel] widgets = [self.freqComboBox, chanlayout, self.audio_bitrateComboBox] audiosettings_layout = QHBoxLayout() for a, b in zip(labels, widgets): text = a.text() a.setText('<html><p align="center">{0}</p></html>'.format(text)) layout = pyqttools.add_to_layout(QVBoxLayout(), a, b) audiosettings_layout.addLayout(layout) hidden_layout = pyqttools.add_to_layout(QVBoxLayout(), videosettings_layout, audiosettings_layout) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.moreButton = QPushButton(QApplication.translate('Tab', 'More')) self.moreButton.setSizePolicy(QSizePolicy(QSizePolicy.Fixed)) self.moreButton.setCheckable(True) hlayout3 = pyqttools.add_to_layout(QHBoxLayout(), line, self.moreButton) self.frame = QFrame() self.frame.setLayout(hidden_layout) self.frame.hide() final_layout = pyqttools.add_to_layout(QVBoxLayout(), hlayout1, hlayout2, hlayout3, self.frame) self.setLayout(final_layout) self.presetButton.clicked.connect(self.choose_preset) self.defaultButton.clicked.connect(self.set_default_command) self.moreButton.toggled.connect(self.frame.setVisible) self.moreButton.toggled.connect(self.resize_parent) self.extComboBox.currentIndexChanged.connect( lambda: self.extLineEdit.setEnabled( self.extComboBox.currentIndex() == len(self.formats))) self.widthLineEdit.textChanged.connect( lambda: self.command_elements_change('size')) self.heightLineEdit.textChanged.connect( lambda: self.command_elements_change('size')) self.aspect1LineEdit.textChanged.connect( lambda: self.command_elements_change('aspect')) self.aspect2LineEdit.textChanged.connect( lambda: self.command_elements_change('aspect')) self.frameLineEdit.textChanged.connect( lambda: self.command_elements_change('frames')) self.bitrateLineEdit.textChanged.connect( lambda: self.command_elements_change('video_bitrate')) self.freqComboBox.currentIndexChanged.connect( lambda: self.command_elements_change('frequency')) self.audio_bitrateComboBox.currentIndexChanged.connect( lambda: self.command_elements_change('audio_bitrate')) self.chan1RadioButton.clicked.connect( lambda: self.command_elements_change('channels1')) self.chan2RadioButton.clicked.connect( lambda: self.command_elements_change('channels2')) def resize_parent(self): """Resize MainWindow.""" height = MAIN_FIXED_HEIGHT if self.frame.isVisible() else MAIN_HEIGHT self.parent.setMinimumSize(MAIN_WIDTH, height) self.parent.resize(MAIN_WIDTH, height) def clear(self): """Clear all values of graphical widgets.""" lines = [self.commandLineEdit, self.widthLineEdit, self.heightLineEdit, self.aspect1LineEdit, self.aspect2LineEdit, self.frameLineEdit, self.bitrateLineEdit, self.extLineEdit] for i in lines: i.clear() self.freqComboBox.setCurrentIndex(0) self.audio_bitrateComboBox.setCurrentIndex(0) self.group.setExclusive(False) self.chan1RadioButton.setChecked(False) self.chan2RadioButton.setChecked(False) self.group.setExclusive(True) # setExclusive(False) in order to be able to uncheck checkboxes and # then setExclusive(True) so only one radio button can be set def ok_to_continue(self): """ Check if everything is ok with audiovideotab to continue conversion. Check if: - Either ffmpeg or avconv are installed. - Desired extension is valid. - self.commandLineEdit is empty. Return True if all tests pass, else False. """ if not self.parent.ffmpeg and not self.parent.avconv: QMessageBox.warning(self, 'FF Multi Converter - ' + self.tr( 'Error!'), self.tr('Neither ffmpeg nor avconv are installed.' '\nYou will not be able to convert audio/video files until you' ' install one of them.')) return False if self.extLineEdit.isEnabled(): text = str(self.extLineEdit.text()).strip() if len(text.split()) != 1 or text[0] == '.': QMessageBox.warning(self, 'FF Multi Converter - ' + self.tr( 'Error!'), self.tr('Extension must be one word and must ' 'not start with a dot.')) self.extLineEdit.selectAll() self.extLineEdit.setFocus() return False if not self.commandLineEdit.text(): QMessageBox.warning(self, 'FF Multi Converter - ' + self.tr( 'Error!'), self.tr('The command LineEdit may not be empty.')) self.commandLineEdit.setFocus() return False return True def set_default_command(self): """Set the default value to self.commandLineEdit.""" self.clear() self.commandLineEdit.setText(self.parent.default_command) def choose_preset(self): """ Open the presets dialog and update self.commandLineEdit, self.extComboBox and self.extLineEdit with the appropriate values. """ dialog = presets_dlgs.ShowPresets() if dialog.exec_() and dialog.the_command is not None: self.commandLineEdit.setText(dialog.the_command) self.commandLineEdit.home(False) find = self.extComboBox.findText(dialog.the_extension) if find >= 0: self.extComboBox.setCurrentIndex(find) else: self.extComboBox.setCurrentIndex(len(self.formats)) self.extLineEdit.setText(dialog.the_extension) def remove_consecutive_spaces(self, string): """Remove any consecutive spaces from a string and return it.""" temp = string string = '' for i in temp.split(): if i: string += i + ' ' return string[:-1] def command_elements_change(self, widget): """Fill self.commandLineEdit with the appropriate command parameters.""" command = str(self.commandLineEdit.text()) if widget == 'size': text1 = self.widthLineEdit.text() text2 = self.heightLineEdit.text() if (text1 or text2) and not (text1 and text2): return f = re.sub(r'^.*(-s\s+\d+x\d+).*$', r'\1', command) if re.match(r'^.*(-s\s+\d+x\d+).*$', f): command = command.replace(f, '').strip() if text1 and text2: command += ' -s {0}x{1}'.format(text1, text2) elif widget == 'aspect': text1 = self.aspect1LineEdit.text() text2 = self.aspect2LineEdit.text() if (text1 or text2) and not (text1 and text2): return f = re.sub(r'^.*(-aspect\s+\d+:\d+).*$', r'\1', command) if re.match(r'^.*(-aspect\s+\d+:\d+).*$', f): command = command.replace(f, '').strip() if text1 and text2: command += ' -aspect {0}:{1}'.format(text1, text2) elif widget == 'frames': text = self.frameLineEdit.text() f = re.sub(r'^.*(-r\s+\d+).*$', r'\1', command) if re.match(r'^.*(-r\s+\d+).*$', f): command = command.replace(f, '').strip() if text: command += ' -r {0}'.format(text) elif widget == 'video_bitrate': text = self.bitrateLineEdit.text() f = re.sub(r'^.*(-b\s+\d+k).*$', r'\1', command) if re.match(r'^.*(-b\s+\d+k).*$', f): command = command.replace(f, '') if text: command += ' -b {0}k'.format(text) command = command.replace('-sameq', '').strip() elif widget == 'frequency': text = self.freqComboBox.currentText() f = re.sub(r'^.*(-ar\s+\d+).*$', r'\1', command) if re.match(r'^.*(-ar\s+\d+).*$', f): command = command.replace(f, '').strip() if text != 'No Change': command += ' -ar {0}'.format(text) elif widget == 'audio_bitrate': text = self.audio_bitrateComboBox.currentText() f = re.sub(r'^.*(-ab\s+\d+k).*$', r'\1', command) if re.match(r'^.*(-ab\s+\d+k).*$', f): command = command.replace(f, '').strip() if text != 'No Change': command += ' -ab {0}k'.format(text) elif widget in ('channels1', 'channels2'): text = self.chan1RadioButton.text() if widget == 'channels1' \ else self.chan2RadioButton.text() f = re.sub(r'^.*(-ac\s+\d+).*$', r'\1', command) if re.match(r'^.*(-ac\s+\d+).*$', f): command = command.replace(f, '').strip() command += ' -ac {0}'.format(text) self.commandLineEdit.clear() self.commandLineEdit.setText(self.remove_consecutive_spaces(command))
class ImportJobsDialog(QDialog): def __init__(self, jobs): """ Constructor :param jobs: all the jobs available for import """ QDialog.__init__(self) self.__jobs = jobs self.setWindowTitle( QCoreApplication.translate("VDLTools", "Choose job")) self.resize(300, 100) self.__layout = QGridLayout() self.__okButton = QPushButton( QCoreApplication.translate("VDLTools", "OK")) self.__okButton.setMinimumHeight(20) self.__okButton.setMinimumWidth(100) self.__cancelButton = QPushButton( QCoreApplication.translate("VDLTools", "Cancel")) self.__cancelButton.setMinimumHeight(20) self.__cancelButton.setMinimumWidth(100) self.__layout.addWidget(self.__okButton, 100, 1) self.__layout.addWidget(self.__cancelButton, 100, 2) label = QLabel(QCoreApplication.translate("VDLTools", "Job : ")) label.setMinimumHeight(20) label.setMinimumWidth(50) self.__layout.addWidget(label, 0, 1) self.__jobCombo = QComboBox() self.__jobCombo.setMinimumHeight(20) self.__jobCombo.setMinimumWidth(50) self.__jobCombo.addItem("") for job in self.__jobs: self.__jobCombo.addItem(job) self.__layout.addWidget(self.__jobCombo, 0, 2) self.__jobCombo.currentIndexChanged.connect(self.__jobComboChanged) self.setLayout(self.__layout) def __jobComboChanged(self): """ When the selected job has changed """ if self.__pointCombo.itemText(0) == "": self.__pointCombo.removeItem(0) def okButton(self): """ To get the ok button instance :return: ok button instance """ return self.__okButton def cancelButton(self): """ To get the cancel button instance :return: cancel button instance """ return self.__cancelButton def job(self): """ To get the selected job :return: selected job """ index = self.__jobCombo.currentIndex() if self.__jobCombo.itemText(index) == "": return None else: return self.__jobs[index]
class StyleChooser(QWidget): def __init__(self, line_style_set=STYLESET_DEFAULT): QWidget.__init__(self) self._style = PlotStyle("StyleChooser Internal Style") self._styles = STYLES['default'] if not line_style_set in STYLES else STYLES[line_style_set] self.setMinimumWidth(140) self.setMaximumHeight(25) layout = QHBoxLayout() layout.setMargin(0) layout.setSpacing(2) self.line_chooser = QComboBox() self.line_chooser.setToolTip("Select line style.") for style in self._styles: self.line_chooser.addItem(*style) self.marker_chooser = QComboBox() self.marker_chooser.setToolTip("Select marker style.") for marker in MARKERS: self.marker_chooser.addItem(*marker) self.thickness_spinner = QDoubleSpinBox() self.thickness_spinner.setToolTip("Line thickness") self.thickness_spinner.setMinimum(0.1) self.thickness_spinner.setDecimals(1) self.thickness_spinner.setSingleStep(0.1) self.size_spinner = QDoubleSpinBox() self.size_spinner.setToolTip("Marker Size") self.size_spinner.setMinimum(0.1) self.size_spinner.setDecimals(1) self.size_spinner.setSingleStep(0.1) # the text content of the spinner varies, but shouldn't push the control out of boundaries self.line_chooser.setMinimumWidth(110) layout.addWidget(self.line_chooser) layout.addWidget(self.thickness_spinner) layout.addWidget(self.marker_chooser) layout.addWidget(self.size_spinner) self.setLayout(layout) self.line_chooser.currentIndexChanged.connect(self._updateStyle) self.marker_chooser.currentIndexChanged.connect(self._updateStyle) self.thickness_spinner.valueChanged.connect(self._updateStyle) self.size_spinner.valueChanged.connect(self._updateStyle) self._updateLineStyleAndMarker(self._style.line_style, self._style.marker, self._style.width, self._style.size) self._layout = layout def getItemSizes(self): line_style_combo_width = self._layout.itemAt(0).sizeHint().width() thickness_spinner_width = self._layout.itemAt(1).sizeHint().width() marker_combo_width = self._layout.itemAt(2).sizeHint().width() size_spinner_width = self._layout.itemAt(3).sizeHint().width() return line_style_combo_width, thickness_spinner_width, marker_combo_width, size_spinner_width def _findLineStyleIndex(self, line_style): for index, style in enumerate(self._styles): if style[1] == line_style: return index elif style[1] is None and line_style == "": return index return -1 def _findMarkerStyleIndex(self, marker): for index, style in enumerate(MARKERS): if style[1] == marker: return index elif style[1] is None and marker == "": return index return -1 def _updateLineStyleAndMarker(self, line_style, marker, thickness, size): self.line_chooser.setCurrentIndex(self._findLineStyleIndex(line_style)) self.marker_chooser.setCurrentIndex(self._findMarkerStyleIndex(marker)) self.thickness_spinner.setValue(thickness) self.size_spinner.setValue(size) def _updateStyle(self): self.marker_chooser.setEnabled(self.line_chooser.currentText() != "Area") line_style = self.line_chooser.itemData(self.line_chooser.currentIndex()) marker_style = self.marker_chooser.itemData(self.marker_chooser.currentIndex()) thickness = float(self.thickness_spinner.value()) size = float(self.size_spinner.value()) self._style.line_style = str(line_style.toString()) self._style.marker = str(marker_style.toString()) self._style.width = thickness self._style.size = size def setStyle(self, style): """ @type style: PlotStyle """ self._style.copyStyleFrom(style) self._updateLineStyleAndMarker(style.line_style, style.marker, style.width, style.size) def getStyle(self): """ @rtype: PlotStyle """ style = PlotStyle("Generated Style from StyleChooser") style.copyStyleFrom(self._style) return style def createLabelLayout(self, layout=None): if layout is None: layout = QHBoxLayout() titles = ["Line Style", "Width", "Marker Style", "Size"] sizes = self.getItemSizes() for title, size in zip(titles, sizes): label = QLabel(title) label.setFixedWidth(size) layout.addWidget(label) return layout
class ShowSettingsDialog(QDialog): """ Dialog class for plugin settings """ def __init__(self, iface, memoryPointsLayer, memoryLinesLayer, importConfigTable, importUriDb, importSchemaDb, controlConfigTable, controlUriDb, controlSchemaDb, mntUrl, refLayers, adjLayers, levelAtt, levelVal, drawdowmLayer, pipeDiam, moreTools): """ Constructor :param iface: interface :param memoryPointsLayer: working memory points layer :param memoryLinesLayer: working memory lines layer :param importConfigTable: config table selected for import :param importUriDb: database for import :param importSchemaDb: db schema for import :param controlConfigTable: config table selected for control :param controlUriDb: database for control :param controlSchemaDb: db schema for control :param mntUrl: url to get mnt :param refLayers: reference layers for drawdown :param adjLayers: adjustement layers for drawdown :param levelAtt: level attribute for drawdown :param levelVal: level value for drawdown :param drawdowmLayer: line layer for drawdown :param pipeDiam: pipe diameter for drawdown :param moreTools: if more tools or not """ QDialog.__init__(self) self.__iface = iface self.__memoryPointsLayer = memoryPointsLayer self.__memoryLinesLayer = memoryLinesLayer self.__importConfigTable = importConfigTable self.__importUriDb = importUriDb self.__importSchemaDb = importSchemaDb self.__controlConfigTable = controlConfigTable self.__controlUriDb = controlUriDb self.__controlSchemaDb = controlSchemaDb self.__mntUrl = mntUrl self.__refLayers = refLayers self.__adjLayers = adjLayers self.__levelAtt = levelAtt self.__levelVal = levelVal self.__drawdowmLayer = drawdowmLayer self.__pipeDiam = pipeDiam self.setWindowTitle(QCoreApplication.translate("VDLTools", "Settings")) self.__pointsLayers = [] self.__linesLayers = [] self.__refAvailableLayers = [] self.__drawdownLayers = [] self.__tables = [] self.__schemas = [] self.__pipeDiamFields = [] self.__levelAttFields = [] self.__dbs = DBConnector.getUsedDatabases() self.__refLabels = [] self.__refChecks = [] self.__adjChecks = [] for layer in list(QgsMapLayerRegistry.instance().mapLayers().values()): if layer is not None and layer.type() == QgsMapLayer.VectorLayer: if layer.providerType() == "memory": if layer.geometryType() == QGis.Point: self.__pointsLayers.append(layer) if layer.geometryType() == QGis.Line: self.__linesLayers.append(layer) if QGis.fromOldWkbType( layer.wkbType()) == QgsWKBTypes.LineStringZ: self.__drawdownLayers.append(layer) if QGis.fromOldWkbType(layer.wkbType()) == QgsWKBTypes.PointZ: self.__refAvailableLayers.append(layer) self.resize(600, 500) self.__layout = QGridLayout() self.__scrollLayout = QGridLayout() line = 0 intersectLabel = QLabel( QCoreApplication.translate("VDLTools", "Intersect ")) self.__scrollLayout.addWidget(intersectLabel, line, 0) line += 1 pointLabel = QLabel( QCoreApplication.translate("VDLTools", "Working points layer : ")) self.__scrollLayout.addWidget(pointLabel, line, 1) self.__pointCombo = QComboBox() self.__pointCombo.setMinimumHeight(20) self.__pointCombo.setMinimumWidth(50) self.__pointCombo.addItem("") for layer in self.__pointsLayers: self.__pointCombo.addItem(layer.name()) self.__scrollLayout.addWidget(self.__pointCombo, line, 2) self.__pointCombo.currentIndexChanged.connect(self.__pointComboChanged) if self.__memoryPointsLayer is not None: if self.__memoryPointsLayer in self.__pointsLayers: self.__pointCombo.setCurrentIndex( self.__pointsLayers.index(self.__memoryPointsLayer) + 1) line += 1 lineLabel = QLabel( QCoreApplication.translate("VDLTools", "Working lines layer : ")) self.__scrollLayout.addWidget(lineLabel, line, 1) self.__lineCombo = QComboBox() self.__lineCombo.setMinimumHeight(20) self.__lineCombo.setMinimumWidth(50) self.__lineCombo.addItem("") for layer in self.__linesLayers: self.__lineCombo.addItem(layer.name()) self.__scrollLayout.addWidget(self.__lineCombo, line, 2) self.__lineCombo.currentIndexChanged.connect(self.__lineComboChanged) if self.__memoryLinesLayer is not None: if self.__memoryLinesLayer in self.__linesLayers: self.__lineCombo.setCurrentIndex( self.__linesLayers.index(self.__memoryLinesLayer) + 1) line += 1 profilesLabel = QLabel( QCoreApplication.translate("VDLTools", "Profiles ")) self.__scrollLayout.addWidget(profilesLabel, line, 0) line += 1 mntLabel = QLabel( QCoreApplication.translate("VDLTools", "Url for MNT : ")) self.__scrollLayout.addWidget(mntLabel, line, 1) self.__mntText = QLineEdit() if self.__mntUrl is None or self.__mntUrl == "None": self.__mntText.insert( 'https://map.lausanne.ch/prod/wsgi/profile.json') else: self.__mntText.insert(self.__mntUrl) self.__mntText.setMinimumHeight(20) self.__mntText.setMinimumWidth(100) self.__scrollLayout.addWidget(self.__mntText, line, 2) line += 1 ddLabel = QLabel(QCoreApplication.translate("VDLTools", "Drawdown ")) self.__scrollLayout.addWidget(ddLabel, line, 0) line += 1 self.__scrollLayout.addWidget( QLabel(QCoreApplication.translate("VDLTools", "Layer")), line, 1) namesLayout = QHBoxLayout() namesWidget = QWidget() namesLayout.addWidget( QLabel(QCoreApplication.translate("VDLTools", "Reference"))) namesLayout.addWidget( QLabel(QCoreApplication.translate("VDLTools", "Adjustable"))) namesLayout.setContentsMargins(0, 0, 0, 0) namesWidget.setLayout(namesLayout) self.__scrollLayout.addWidget(namesWidget, line, 2) line += 1 for layer in self.__refAvailableLayers: refLabel = QLabel(" - " + layer.name()) self.__refLabels.append(refLabel) self.__scrollLayout.addWidget(refLabel, line, 1) checksLayout = QHBoxLayout() checksLayout.setContentsMargins(0, 0, 0, 0) checksWidget = QWidget() refCheck = QCheckBox() self.__refChecks.append(refCheck) refCheck.stateChanged.connect(self.__refBoxesChanged) checksLayout.addWidget(refCheck) adjCheck = QCheckBox() self.__adjChecks.append(adjCheck) checksLayout.addWidget(adjCheck) checksWidget.setLayout(checksLayout) self.__scrollLayout.addWidget(checksWidget, line, 2) line += 1 levelAttLabel = QLabel( QCoreApplication.translate("VDLTools", "Code(s) on pipe : ")) self.__scrollLayout.addWidget(levelAttLabel, line, 1) self.__levelAttCombo = QComboBox() self.__levelAttCombo.setMinimumHeight(20) self.__levelAttCombo.setMinimumWidth(50) self.__levelAttCombo.addItem("") self.__scrollLayout.addWidget(self.__levelAttCombo, line, 2) self.__levelAttCombo.currentIndexChanged.connect( self.__levelAttComboChanged) i = 0 for layer in self.__refAvailableLayers: if layer in self.__refLayers: self.__refChecks[i].setChecked(True) if layer in self.__adjLayers: self.__adjChecks[i].setChecked(True) i += 1 line += 1 levelValLabel = QLabel( QCoreApplication.translate("VDLTools", "Point code attribute : ")) self.__scrollLayout.addWidget(levelValLabel, line, 1) self.__levelValText = QLineEdit() if self.__levelVal is not None and self.__levelVal != "None": self.__levelValText.insert(self.__levelVal) self.__levelValText.setMinimumHeight(20) self.__levelValText.setMinimumWidth(100) self.__scrollLayout.addWidget(self.__levelValText, line, 2) line += 1 drawdownLabel = QLabel( QCoreApplication.translate("VDLTools", "drawdown layer : ")) self.__scrollLayout.addWidget(drawdownLabel, line, 1) self.__drawdownCombo = QComboBox() self.__drawdownCombo.setMinimumHeight(20) self.__drawdownCombo.setMinimumWidth(50) self.__drawdownCombo.addItem("") for layer in self.__drawdownLayers: self.__drawdownCombo.addItem(layer.name()) self.__scrollLayout.addWidget(self.__drawdownCombo, line, 2) line += 1 pipeDiamLabel = QLabel( QCoreApplication.translate("VDLTools", "Pipe diameter attribute [cm] : ")) self.__scrollLayout.addWidget(pipeDiamLabel, line, 1) self.__pipeDiamCombo = QComboBox() self.__pipeDiamCombo.setMinimumHeight(20) self.__pipeDiamCombo.setMinimumWidth(50) self.__pipeDiamCombo.addItem("") self.__scrollLayout.addWidget(self.__pipeDiamCombo, line, 2) self.__drawdownCombo.currentIndexChanged.connect( self.__drawdownComboChanged) self.__pipeDiamCombo.currentIndexChanged.connect( self.__pipeDiamComboChanged) if self.__drawdowmLayer is not None: if self.__drawdowmLayer in self.__drawdownLayers: self.__drawdownCombo.setCurrentIndex( self.__drawdownLayers.index(self.__drawdowmLayer) + 1) line += 1 controlLabel = QLabel( QCoreApplication.translate("VDLTools", "Control ")) self.__scrollLayout.addWidget(controlLabel, line, 0) line += 1 controlDbLabel = QLabel( QCoreApplication.translate("VDLTools", "Control database : ")) self.__scrollLayout.addWidget(controlDbLabel, line, 1) self.__controlDbCombo = QComboBox() self.__controlDbCombo.setMinimumHeight(20) self.__controlDbCombo.setMinimumWidth(50) self.__controlDbCombo.addItem("") for db in list(self.__dbs.keys()): self.__controlDbCombo.addItem(db) self.__scrollLayout.addWidget(self.__controlDbCombo, line, 2) line += 1 controlSchemaLabel = QLabel( QCoreApplication.translate("VDLTools", "Control database schema : ")) self.__scrollLayout.addWidget(controlSchemaLabel, line, 1) self.__controlSchemaCombo = QComboBox() self.__controlSchemaCombo.setMinimumHeight(20) self.__controlSchemaCombo.setMinimumWidth(50) self.__controlSchemaCombo.addItem("") self.__scrollLayout.addWidget(self.__controlSchemaCombo, line, 2) line += 1 controlTableLabel = QLabel( QCoreApplication.translate("VDLTools", "Control config table : ")) self.__scrollLayout.addWidget(controlTableLabel, line, 1) self.__controlTableCombo = QComboBox() self.__controlTableCombo.setMinimumHeight(20) self.__controlTableCombo.setMinimumWidth(50) self.__controlTableCombo.addItem("") self.__scrollLayout.addWidget(self.__controlTableCombo, line, 2) self.__controlDbCombo.currentIndexChanged.connect( self.__controlDbComboChanged) self.__controlSchemaCombo.currentIndexChanged.connect( self.__controlSchemaComboChanged) self.__controlTableCombo.currentIndexChanged.connect( self.__controlTableComboChanged) if self.__controlUriDb is not None: if self.__controlUriDb.database() in list(self.__dbs.keys()): self.__controlDbCombo.setCurrentIndex( list(self.__dbs.keys()).index( self.__controlUriDb.database()) + 1) if moreTools: line += 1 importLabel = QLabel( QCoreApplication.translate("VDLTools", "Import ")) self.__scrollLayout.addWidget(importLabel, line, 0) line += 1 importDbLabel = QLabel( QCoreApplication.translate("VDLTools", "Import database : ")) self.__scrollLayout.addWidget(importDbLabel, line, 1) self.__importDbCombo = QComboBox() self.__importDbCombo.setMinimumHeight(20) self.__importDbCombo.setMinimumWidth(50) self.__importDbCombo.addItem("") for db in list(self.__dbs.keys()): self.__importDbCombo.addItem(db) self.__scrollLayout.addWidget(self.__importDbCombo, line, 2) line += 1 importSchemaLabel = QLabel( QCoreApplication.translate("VDLTools", "Import database schema : ")) self.__scrollLayout.addWidget(importSchemaLabel, line, 1) self.__importSchemaCombo = QComboBox() self.__importSchemaCombo.setMinimumHeight(20) self.__importSchemaCombo.setMinimumWidth(50) self.__importSchemaCombo.addItem("") self.__scrollLayout.addWidget(self.__importSchemaCombo, line, 2) line += 1 importTableLabel = QLabel( QCoreApplication.translate("VDLTools", "Import config table : ")) self.__scrollLayout.addWidget(importTableLabel, line, 1) self.__importTableCombo = QComboBox() self.__importTableCombo.setMinimumHeight(20) self.__importTableCombo.setMinimumWidth(50) self.__importTableCombo.addItem("") self.__scrollLayout.addWidget(self.__importTableCombo, line, 2) self.__importDbCombo.currentIndexChanged.connect( self.__importDbComboChanged) self.__importSchemaCombo.currentIndexChanged.connect( self.__importSchemaComboChanged) self.__importTableCombo.currentIndexChanged.connect( self.__importTableComboChanged) if self.__importUriDb is not None: if self.__importUriDb.database() in list(self.__dbs.keys()): self.__importDbCombo.setCurrentIndex( list(self.__dbs.keys()).index( self.__importUriDb.database()) + 1) else: self.__importDbCombo = None self.__importSchemaCombo = None self.__importTableCombo = None widget = QWidget() widget.setLayout(self.__scrollLayout) scroll = QScrollArea() scroll.setWidgetResizable(True) scroll.setWidget(widget) self.__layout.addWidget(scroll, 1, 0, 1, 2) self.__okButton = QPushButton( QCoreApplication.translate("VDLTools", "OK")) self.__okButton.setMinimumHeight(20) self.__okButton.setMinimumWidth(100) self.__cancelButton = QPushButton( QCoreApplication.translate("VDLTools", "Cancel")) self.__cancelButton.setMinimumHeight(20) self.__cancelButton.setMinimumWidth(100) self.__layout.addWidget(self.__okButton, 100, 0) self.__layout.addWidget(self.__cancelButton, 100, 1) self.setLayout(self.__layout) @staticmethod def __resetCombo(combo): """ To reset a combo list :param combo: concerned combo """ while combo.count() > 0: combo.removeItem(combo.count() - 1) def __setSchemaCombo(self, uriDb, schemaCombo, schemaComboChanged, schemaDb): """ To fill the schema combo list :param uriDb: selected database uri :param schemaCombo: concerned schema combo :param schemaComboChanged: concerned schema combo change event :param schemaDb: selected schema db """ connector = DBConnector(uriDb, self.__iface) db = connector.setConnection() if db: Signal.safelyDisconnect(schemaCombo.currentIndexChanged, schemaComboChanged) self.__resetCombo(schemaCombo) schemaCombo.addItem("") self.__schemas = [] query = db.exec_( """SELECT DISTINCT table_schema FROM information_schema.tables WHERE table_schema NOT IN ('pg_catalog', 'information_schema', 'topology') AND table_type = 'BASE TABLE' AND table_name NOT IN (SELECT f_table_name FROM geometry_columns)""") if query.lastError().isValid(): self.__iface.messageBar().pushMessage( query.lastError().text(), level=QgsMessageBar.CRITICAL, duration=0) else: while next(query): self.__schemas.append(query.value(0)) db.close() for schema in self.__schemas: schemaCombo.addItem(schema) schemaCombo.currentIndexChanged.connect(schemaComboChanged) if schemaDb is not None: if schemaDb in self.__schemas: schemaCombo.setCurrentIndex( self.__schemas.index(schemaDb) + 1) def __setTableCombo(self, uriDb, schema, tableCombo, tableComboChanged, configTable): """ To fill the table combo list :param uriDb: selected database uri :param schema: selected database schema :param tableCombo: concerned table combo :param tableComboChanged: concerned table combo change event :param configTable: selected config table """ connector = DBConnector(uriDb, self.__iface) db = connector.setConnection() if db: Signal.safelyDisconnect(tableCombo.currentIndexChanged, tableComboChanged) self.__resetCombo(tableCombo) tableCombo.addItem("") self.__tables = [] query = db.exec_( """SELECT table_name FROM information_schema.tables WHERE table_schema = '""" + schema + """' ORDER BY table_name""") if query.lastError().isValid(): self.__iface.messageBar().pushMessage( query.lastError().text(), level=QgsMessageBar.CRITICAL, duration=0) else: while next(query): self.__tables.append(query.value(0)) db.close() for table in self.__tables: if tableCombo.findText(table) == -1: tableCombo.addItem(table) tableCombo.currentIndexChanged.connect(tableComboChanged) if configTable is not None: if configTable in self.__tables: tableCombo.setCurrentIndex( self.__tables.index(configTable) + 1) def __setPipeDiamCombo(self, drawdownLayer): """ To fill the pipe diameter combo list :param drawdownLayer: choosen drawdown layer """ Signal.safelyDisconnect(self.__pipeDiamCombo.currentIndexChanged, self.__pipeDiamComboChanged) self.__resetCombo(self.__pipeDiamCombo) self.__pipeDiamCombo.addItem("") fields = drawdownLayer.fields() self.__pipeDiamFields = [] for field in fields: self.__pipeDiamFields.append(field.name()) self.__pipeDiamCombo.addItem(field.name()) self.__pipeDiamCombo.currentIndexChanged.connect( self.__pipeDiamComboChanged) if self.__pipeDiam is not None: if self.__pipeDiam in self.__pipeDiamFields: self.__pipeDiamCombo.setCurrentIndex( self.__pipeDiamFields.index(self.__pipeDiam) + 1) def __setLevelAttCombo(self, refLayers): """ To fill the level attribute combo list :param refLayers: choosen reference layers """ Signal.safelyDisconnect(self.__levelAttCombo.currentIndexChanged, self.__levelAttComboChanged) self.__resetCombo(self.__levelAttCombo) self.__levelAttCombo.addItem("") self.__levelAttFields = [] num = 0 for layer in refLayers: fields = layer.fields() if num == 0: for field in fields: self.__levelAttFields.append(field.name()) num = 1 else: names = [] for field in fields: names.append(field.name()) news = [] for name in self.__levelAttFields: if name in names: news.append(name) self.__levelAttFields = news for name in self.__levelAttFields: self.__levelAttCombo.addItem(name) self.__levelAttCombo.currentIndexChanged.connect( self.__levelAttComboChanged) if self.__levelAtt is not None: if self.__levelAtt in self.__levelAttFields: self.__levelAttCombo.setCurrentIndex( self.__levelAttFields.index(self.__levelAtt) + 1) def __lineComboChanged(self): """ To remove blank item when another one is selected """ if self.__lineCombo.itemText(0) == "": self.__lineCombo.removeItem(0) def __pointComboChanged(self): """ To remove blank item when another one is selected """ if self.__pointCombo.itemText(0) == "": self.__pointCombo.removeItem(0) def __refBoxesChanged(self): """ To update level attribute combo when reference layers have changed """ if self.refLayers() is not None: self.__setLevelAttCombo(self.refLayers()) def __drawdownComboChanged(self): """ To remove blank item when another one is selected and update pipe diamete combo when drawdown layer has changed """ if self.__drawdownCombo.itemText(0) == "": self.__drawdownCombo.removeItem(0) if self.drawdownLayer() is not None: self.__setPipeDiamCombo(self.drawdownLayer()) def __controlTableComboChanged(self): """ To remove blank item when another one is selected """ if self.__controlTableCombo.itemText(0) == "": self.__controlTableCombo.removeItem(0) def __importTableComboChanged(self): """ To remove blank item when another one is selected """ if self.__importTableCombo.itemText(0) == "": self.__importTableCombo.removeItem(0) def __controlDbComboChanged(self): """ When the selection in db combo has changed """ if self.__controlDbCombo.itemText(0) == "": self.__controlDbCombo.removeItem(0) if self.controlUriDb() is not None: self.__setSchemaCombo(self.controlUriDb(), self.__controlSchemaCombo, self.__controlSchemaComboChanged, self.__controlSchemaDb) def __importDbComboChanged(self): """ When the selection in db combo has changed """ if self.__importDbCombo.itemText(0) == "": self.__importDbCombo.removeItem(0) if self.importUriDb() is not None: self.__setSchemaCombo(self.importUriDb(), self.__importSchemaCombo, self.__importSchemaComboChanged, self.__importSchemaDb) def __controlSchemaComboChanged(self): """ When the selection in schema combo has changed """ if self.__controlSchemaCombo.itemText(0) == "": self.__controlSchemaCombo.removeItem(0) if self.controlSchemaDb() is not None: self.__setTableCombo(self.controlUriDb(), self.controlSchemaDb(), self.__controlTableCombo, self.__controlTableComboChanged, self.__controlConfigTable) def __importSchemaComboChanged(self): """ When the selection in schema combo has changed """ if self.__importSchemaaCombo.itemText(0) == "": self.__importSchemaCombo.removeItem(0) if self.importSchemaDb() is not None: self.__setTableCombo(self.importUriDb(), self.importSchemaDb(), self.__importTableCombo, self.__importTableComboChanged, self.__importConfigTable) def __pipeDiamComboChanged(self): """ When the selection in schema combo has changed """ if self.__pipeDiamCombo.itemText(0) == "": self.__pipeDiamCombo.removeItem(0) def __levelAttComboChanged(self): """ When the selection in schema combo has changed """ if self.__levelAttCombo.itemText(0) == "": self.__levelAttCombo.removeItem(0) def okButton(self): """ To get the ok button instance :return: ok button instance """ return self.__okButton def cancelButton(self): """ To get the cancel button instance :return: cancel button instance """ return self.__cancelButton def pointsLayer(self): """ To get the selected memory points layer :return: selected memory points layer, or none """ index = self.__pointCombo.currentIndex() if self.__pointCombo.itemText(index) == "": return None else: return self.__pointsLayers[index] def linesLayer(self): """ To get the selected memory lines layer :return: selected memory lines layer, or none """ index = self.__lineCombo.currentIndex() if self.__lineCombo.itemText(index) == "": return None else: return self.__linesLayers[index] def refLayers(self): """ To get the selected reference layers :return: selected reference layers, or none """ layers = [] i = 0 for check in self.__refChecks: if check.isChecked(): layers.append(self.__refAvailableLayers[i]) i += 1 return layers def adjLayers(self): """ To get the selected ajustable layers :return: selected adjustable layers, or none """ layers = [] i = 0 for check in self.__adjChecks: if check.isChecked(): layers.append(self.__refAvailableLayers[i]) i += 1 return layers def levelAtt(self): """ To get the selected level attribute :return: selected level attribute, or none """ if self.__levelAttCombo is None: return None index = self.__levelAttCombo.currentIndex() if self.__levelAttCombo.itemText(index) == "": return None else: return self.__levelAttFields[index] def levelVal(self): """ To get the filled level value :return: filled level value """ return self.__levelValText.text() def drawdownLayer(self): """ To get the selected drawdown layer :return: selected drawdown layer, or none """ index = self.__drawdownCombo.currentIndex() if self.__drawdownCombo.itemText(index) == "": return None else: return self.__drawdownLayers[index] def pipeDiam(self): """ To get the selected pipe diameter :return: selected pipe diameter, or none """ if self.__pipeDiamCombo is None: return None index = self.__pipeDiamCombo.currentIndex() if self.__pipeDiamCombo.itemText(index) == "": return None else: return self.__pipeDiamFields[index] def controlConfigTable(self): """ To get the selected config table :return: selected config table, or none """ if self.__controlTableCombo is None: return None index = self.__controlTableCombo.currentIndex() if self.__controlTableCombo.itemText(index) == "": return None else: return self.__tables[index] def importConfigTable(self): """ To get the selected config table :return: selected config table, or none """ if self.__importTableCombo is None: return None index = self.__importTableCombo.currentIndex() if self.__importTableCombo.itemText(index) == "": return None else: return self.__tables[index] def controlUriDb(self): """ To get selected import database uri :return: import database uri """ if self.__controlDbCombo is None: return None index = self.__controlDbCombo.currentIndex() if self.__controlDbCombo.itemText(index) == "": return None else: return self.__dbs[list(self.__dbs.keys())[index]] def importUriDb(self): """ To get selected import database uri :return: import database uri """ if self.__importDbCombo is None: return None index = self.__importDbCombo.currentIndex() if self.__importDbCombo.itemText(index) == "": return None else: return self.__dbs[list(self.__dbs.keys())[index]] def controlSchemaDb(self): """ To get selected import database schema :return: import database schema """ if self.__controlSchemaCombo is None: return None index = self.__controlSchemaCombo.currentIndex() if self.__controlSchemaCombo.itemText(index) == "": return None else: return self.__schemas[index] def importSchemaDb(self): """ To get selected import database schema :return: import database schema """ if self.__importSchemaCombo is None: return None index = self.__importSchemaCombo.currentIndex() if self.__importSchemaCombo.itemText(index) == "": return None else: return self.__schemas[index] def mntUrl(self): """ To get selected MN url :return: MN url """ return self.__mntText.text()
class OptionsDialog(QtHelper.EnhancedQDialog, Logger.ClassLogger): """ Update locations dialog """ def __init__(self, parent=None): """ Dialog to rename file or folder @param currentName: @type currentName: @param folder: @type folder: @param parent: @type parent: """ super(OptionsDialog, self).__init__(parent) self.createDialog() self.createConnections() def createDialog (self): """ Create qt dialog """ self.TIMEOUT_ANDROID_ACTION = Settings.instance().readValue( key = 'TestGenerator/timeout-android-action' ) self.timeoutAndroidLine = QLineEdit() self.timeoutAndroidLine.setText(str(self.TIMEOUT_ANDROID_ACTION)) validatorAndroid = QDoubleValidator(self) validatorAndroid.setNotation(QDoubleValidator.StandardNotation) self.timeoutAndroidLine.setValidator(validatorAndroid) self.timeoutAndroidLine.installEventFilter(self) self.agentNameLineAndroid = QLineEdit("AGENT_ANDROID") self.agentsAndroidList = QComboBox() self.agentsAndroidList.setMinimumWidth(300) optionAndroidLayout = QGridLayout() optionAndroidLayout.addWidget(QLabel( self.tr("Max time to run action:") ), 1, 0) optionAndroidLayout.addWidget(self.timeoutAndroidLine, 1, 1) optionAndroidLayout.addWidget(QLabel( self.tr("Agent Key Name:") ), 3, 0) optionAndroidLayout.addWidget(self.agentNameLineAndroid, 3, 1) optionAndroidLayout.addWidget(QLabel( self.tr("Agent:") ), 4, 0) optionAndroidLayout.addWidget(self.agentsAndroidList, 4, 1) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setStyleSheet( """QDialogButtonBox { dialogbuttonbox-buttons-have-icons: 1; dialog-ok-icon: url(:/ok.png); dialog-cancel-icon: url(:/ko.png); }""") self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) mainLayout = QVBoxLayout() mainLayout.addLayout(optionAndroidLayout) mainLayout.addWidget(self.buttonBox) self.setLayout(mainLayout) self.setWindowTitle(self.tr("Android Options")) def createConnections (self): """ Create qt connections """ self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject)
class fileFolderRenamerCreater(QtGui.QMainWindow): '''========================================================================================================================================== GUI Class. ==========================================================================================================================================''' def __init__(self): '''---------------------------------------------------------------------------------------------------------------------------------- GUI Window ----------------------------------------------------------------------------------------------------------------------------------''' QtGui.QMainWindow.__init__(self) self.resize(600, 100) self.setWindowTitle("Renamer") self.central_widget = QWidget(self) self.setCentralWidget(self.central_widget) self.main_layout = QGridLayout(self.central_widget) '''---------------------------------------------------------------------------------------------------------------------------------- Layout of the GUI. ----------------------------------------------------------------------------------------------------------------------------------''' self.window_layer_01 = QGridLayout() self.main_layout.addLayout(self.window_layer_01, 0, 0, 1, 1) self.window_layer_02 = QGridLayout() self.main_layout.addLayout(self.window_layer_02, 1, 0, 1, 1) self.window_layer_03 = QGridLayout() self.main_layout.addLayout(self.window_layer_03, 2, 0, 1, 1) self.window_layer_04 = QGridLayout() self.main_layout.addLayout(self.window_layer_04, 3, 0, 1, 1) self.window_layer_05 = QGridLayout() self.main_layout.addLayout(self.window_layer_05, 4, 0, 1, 1) self.window_layer_05 = QGridLayout() self.main_layout.addLayout(self.window_layer_05, 5, 0, 1, 1) self.window_layer_06 = QGridLayout() self.main_layout.addLayout(self.window_layer_06, 6, 0, 1, 1) self.window_layer_07 = QGridLayout() self.main_layout.addLayout(self.window_layer_07, 7, 0, 1, 1) self.window_column_02 =QHBoxLayout() self.main_layout.addLayout(self.window_column_02, 4, 1, 1, 1) self.window_column_03 =QHBoxLayout() self.main_layout.addLayout(self.window_column_03, 2, 1, 1, 1) self.window_column_04 =QHBoxLayout() self.main_layout.addLayout(self.window_column_04, 3, 1, 1, 1) '''---------------------------------------------------------------------------------------------------------------------------------- Widgets ----------------------------------------------------------------------------------------------------------------------------------''' self.asset_name_label_01 = QLabel("Project") self.asset_name_label_01.setMinimumWidth(70) self.asset_name_label_01.setMaximumWidth(70) self.window_layer_02.addWidget(self.asset_name_label_01, 0, 0, 1, 1) self.project_name_folder = QComboBox() self.project_name_folder.setMinimumWidth(200) self.project_name_folder.setMaximumWidth(200) self.window_layer_02.addWidget(self.project_name_folder, 0, 1, 1, 1) srcfileName = os.listdir(ProjectMasterFolder) getFolders=[(each) for each in srcfileName if "." not in each] firstPick=["Pick Project"] self.project_name_folder.addItems(firstPick) self.project_name_folder.addItems(getFolders) self.asset_name_label_01 = QLabel("AssetName") self.asset_name_label_01.setMinimumWidth(70) self.asset_name_label_01.setMaximumWidth(70) self.window_layer_02.addWidget(self.asset_name_label_01, 0, 2, 1, 1) self.asset_name_field_01 = QtGui.QLineEdit() self.asset_name_field_01.setText("") self.asset_name_field_01.setMinimumHeight(25) self.asset_name_field_01.setMaximumHeight(50) self.asset_name_field_01.setMinimumWidth(100) self.asset_name_field_01.setMaximumWidth(100) self.window_layer_02.addWidget(self.asset_name_field_01, 0, 3, 1, 1) self.asset_label = QLabel("Category") self.asset_label.setMinimumWidth(120) self.asset_label.setMaximumWidth(120) self.window_layer_02.addWidget(self.asset_label, 0, 4, 1, 1) self.asset_dropdown_01 = QComboBox() self.asset_dropdown_01.setMinimumWidth(120) self.asset_dropdown_01.setMaximumWidth(120) self.window_layer_02.addWidget(self.asset_dropdown_01, 0, 5, 1, 1) self.asset_dropdown_01.addItems(Asset) #self.populateSequence(spinner=self.asset_dropdown_01) #self.asset_dropdown_01.currentIndexChanged[str].connect(self.on_langComboBox_IndexChanged) self.type_label = QLabel("Type") self.type_label.setMinimumWidth(120) self.type_label.setMaximumWidth(120) self.window_layer_02.addWidget(self.type_label, 0, 6, 1, 1) self.type_dropdown_01 = QComboBox() self.type_dropdown_01.setMinimumWidth(120) self.type_dropdown_01.setMaximumWidth(120) self.window_layer_02.addWidget(self.type_dropdown_01, 0, 7, 1, 1) self.type_dropdown_01.addItems(Type) #self.populateSequence(spinner=self.type_dropdown_01) #self.type_dropdown_01.currentIndexChanged[str].connect(self.on_langComboBox_IndexChanged) self.ep_name_label = QLabel("Episode") self.ep_name_label.setMinimumWidth(70) self.ep_name_label.setMaximumWidth(70) self.window_layer_02.addWidget(self.ep_name_label, 0, 8, 1, 1) self.ep_name_field = QtGui.QLineEdit() self.ep_name_field.setText("802") self.ep_name_field.setMinimumHeight(25) self.ep_name_field.setMaximumHeight(50) self.ep_name_field.setMinimumWidth(100) self.ep_name_field.setMaximumWidth(100) self.window_layer_02.addWidget(self.ep_name_field, 0, 9, 1, 1) self.dest_label_01 = QLabel("new path:") self.dest_label_01.setMinimumWidth(100) self.dest_label_01.setMaximumWidth(100) self.window_layer_05.addWidget(self.dest_label_01, 0, 0, 1, 1) self.dest_folder_field_01 = QtGui.QLineEdit() self.dest_folder_field_01.setText(mayaFolder) #self.dest_folder_field_01.setText(mayaFolder) self.dest_folder_field_01.setMinimumHeight(25) self.dest_folder_field_01.setMaximumHeight(50) self.dest_folder_field_01.setMinimumWidth(450) self.dest_folder_field_01.setMaximumWidth(450) self.window_layer_05.addWidget(self.dest_folder_field_01, 0, 1, 1, 1) self.get_src_button = QPushButton("refresh") self.get_src_button.setMinimumHeight(25) self.get_dest_button = QPushButton("refresh") self.get_dest_button.setMinimumHeight(25) self.get_dest_button.setMaximumHeight(50) self.get_dest_button.setMinimumWidth(100) self.get_dest_button.setMaximumWidth(100) self.connect(self.get_dest_button, SIGNAL('clicked()'), self._refresh) self.window_layer_05.addWidget(self.get_dest_button, 0, 4, 1, 1) self.get_src_button = QPushButton("open folder") self.get_src_button.setMinimumHeight(25) self.get_dest_button = QPushButton("open folder") self.get_dest_button.setMinimumHeight(25) self.get_dest_button.setMaximumHeight(50) self.get_dest_button.setMinimumWidth(100) self.get_dest_button.setMaximumWidth(100) self.connect(self.get_dest_button, SIGNAL('clicked()'), self._open_destination) self.window_layer_05.addWidget(self.get_dest_button, 0, 5, 1, 1) self.do_it_buttton = QPushButton("Create!") self.do_it_buttton.setMinimumHeight(25) self.do_it_buttton.setMaximumHeight(50) self.do_it_buttton.setMinimumWidth(100) self.do_it_buttton.setMaximumWidth(150) #self.do_it_buttton.clicked.connect(self._start) self.connect(self.do_it_buttton, SIGNAL('clicked()'), self._operation) self.window_layer_06.addWidget(self.do_it_buttton, 0, 0, 1, 1) ################################################ # def on_comboBoxParent_currentIndexChanged(self, index): # '''---------------------------------------------------------------------------------------------------------------------------------- # Once the source sequence is chosen, # this will populate the source shot spinner # ----------------------------------------------------------------------------------------------------------------------------------''' # sourceSequence=self.sourceSequenceSpinner # getText=sourceSequence.currentText() # sourceShot=self.sourceShotSpinner # shotContainer=self._getShotFolder(getText) # shotContainer.append('') # shotContainer.reverse() # noshow="select sequence" # sourceShot.clear() # sourceShot.addItems(shotContainer) # # def deston_comboBoxParent_currentIndexChanged(self, index): # '''---------------------------------------------------------------------------------------------------------------------------------- # Once the destination sequence is chosen, # this will populate the destination shot spinner # ----------------------------------------------------------------------------------------------------------------------------------''' # srcfileName=[] # for (root, directories, files) in os.walk(ProjectMasterFolder): # for filename in files: # srcfileName.append(filename) # destinationShot=self.destinationSequenceSpinner # destinationShot.clear() # destinationShot.addItems(srcfileName) def _refresh(self): Project=self.project_name_folder Project=Project.currentText() Project=str(Project) Asset=self.asset_dropdown_01 Asset=Asset.currentText() Asset=str(Asset) Type=self.type_dropdown_01 Type=Type.currentText() Type=str(Type) AssetName=self.asset_name_field_01 AssetName=AssetName.text() AssetName=str(AssetName) Episode=self.ep_name_field Episode=Episode.text() Episode=str(Episode) destination=self.dest_folder_field_01 destination=destination.text() destination=str(destination) if Project =="Pick Project": print "You must assign a project" return elif len(AssetName)==0: print "you must give the asset a name" return elif Asset =="Pick Category": print "You must pick a Category" return elif Type=="Pick Asset Type": print "you much pick an Asset Type" return elif Type =="Episodic" and len(Episode)==0: print "if asset is episodic, you must fill in the episode field" return else: try: makeMayaFile=AssetName.split("_")[1] except: print "AssetName does not have a number assigned. Please give it a number EG:'01_'" return if Type=="Episodic": folderPath=ProjectMasterFolder+Project+mayaFolder+Asset+"\\"+Type+"\\"+Episode+"\\"+AssetName+"\\" self.dest_folder_field_01.setText(folderPath) elif Type=="Series": folderPath=ProjectMasterFolder+Project+mayaFolder+Asset+"\\"+Type+"\\"+AssetName+"\\" self.dest_folder_field_01.setText(folderPath) def _open_destination(self): dest_field_01=self.dest_folder_field_01 destImagePath=dest_field_01.text() destImagePath=str(destImagePath) self.get_path(destImagePath) def get_path(self, path): try: if '\\\\' in path: newpath=re.sub(r'\\\\',r'\\', path) os.startfile(r'\\'+newpath[1:]) else: os.startfile(path) except: print "cannot open path. check if it exists" return def _operation(self): Project=self.project_name_folder Project=Project.currentText() Project=str(Project) Asset=self.asset_dropdown_01 Asset=Asset.currentText() Asset=str(Asset) Type=self.type_dropdown_01 Type=Type.currentText() Type=str(Type) AssetName=self.asset_name_field_01 AssetName=AssetName.text() AssetName=str(AssetName) Episode=self.ep_name_field Episode=Episode.text() Episode=str(Episode) destination=self.dest_folder_field_01 destination=destination.text() destination=str(destination) if Project =="Pick Project": print "You must assign a project" return elif len(AssetName)==0: print "you must give the asset a name" return elif Asset =="Pick Category": print "You must pick a Category" return elif Type=="Pick Asset Type": print "you much pick an Asset Type" return elif Type =="Episodic" and len(Episode)==0: print "if asset is episodic, you must fill in the episode field" return else: try: makeMayaFile=AssetName.split("_")[1] except: print "AssetName does not have a number assigned. Please give it a number EG:'01_Name'" return if Type=="Episodic": folderPath=ProjectMasterFolder+Project+mayaFolder+Asset+"\\"+Type+"\\"+Episode+"\\"+AssetName for each in ProductionFolders: makeProject=folderPath+"\\"+each for item in ProductionSubFolders: getAssetNameSuf=item.split("\\")[0] ProjectBuild=makeProject+"\\"+item newFile="LA0095_"+makeMayaFile+"_"+getAssetNameSuf+".txt" fname = ProjectBuild+"\\"+newFile if not os.path.exists(ProjectBuild): os.makedirs(ProjectBuild) if not fname: inp=open(fname, 'w+') inp.write("hi"+'\r\n') inp.close() thisFile = fname base = os.path.splitext(thisFile)[0] os.rename(thisFile, base + ".ma") print fname+" has been created" else: pass else: folderPath=ProjectMasterFolder+Project+mayaFolder+Asset+"\\"+Type+"\\"+AssetName for each in ProductionFolders: makeProject=folderPath+"\\"+each for item in ProductionSubFolders: getAssetNameSuf=item.split("\\")[0] ProjectBuild=makeProject+"\\"+item newFile="LA0095_"+makeMayaFile+"_"+getAssetNameSuf+".txt" fname = ProjectBuild+"\\"+newFile if not os.path.exists(ProjectBuild): os.makedirs(ProjectBuild) if not fname: inp=open(fname, 'w+') inp.write("hi"+'\r\n') inp.close() thisFile = fname base = os.path.splitext(thisFile)[0] os.rename(thisFile, base + ".ma") print fname+" has been created" else: pass def copying(self, root, filename, filepath, dstfolderPath): for each in filename: filepath = os.path.join(root, each) shutil.copy(filepath, dstfolderPath) def renaming(self, root, filename, oldNamePart, newNamePart): for each in filename: filepath = os.path.join(root, each) print filepath os.rename(filepath, filepath.replace(oldNamePart, newNamePart)) # def on_langComboBox_IndexChanged(self): # '''---------------------------------------------------------------------------------------------------------------------------------- # This changes the functions of the interface dependent on whether language has been selected # ----------------------------------------------------------------------------------------------------------------------------------''' # interfaceWidgetsAccess=[self.size_field_01, # self.r_field_01, # self.g_field_01, # self.b_field_01, # self.textMode, # self.imageMode, # self.source_folder_field_01, # self.source_button, # self.source_dropdown_01, # self.number_field_01, # self.suf_name_field_01, # self.format_name_field_01, # self.srcImage_field_01 # ] # langDrop=self.lang_dropdown_01 # languageType=langDrop.currentText() # getSrcWidget=self.source_folder_field_01 # srcFolderStuff=self.source_dropdown_01 # if languageType!="none": # if languageType =="ES": # langIndex="Placeholder_ES.png" # self.language_lock_down(langIndex, interfaceWidgetsAccess) # elif languageType=="ZH": # langIndex="Placeholder_ZH.png" # self.language_lock_down(langIndex, interfaceWidgetsAccess) # elif languageType=="FR": # langIndex="Placeholder_FR.png" # self.language_lock_down(langIndex, interfaceWidgetsAccess) # else: # for eachWidget in interfaceWidgetsAccess: # eachWidget.setEnabled(True) # self.dest_field_01.setText(dummyfolder) # self.source_folder_field_01.clear() # self.source_folder_field_01.setText(mayaFolder) # self.r_field_01.setText(redColour) # self.g_field_01.setText(greenColour) # self.b_field_01.setText(blueColour) # getIndex=srcFolderStuff.findText(defaultImage) # srcFolderStuff.setCurrentIndex(getIndex) def error(self): print "name required to change"
class ShowSettingsDialog(QDialog): """ Dialog class for plugin settings """ def __init__(self, iface, memoryPointsLayer, memoryLinesLayer, ctllDb, configTable, uriDb, schemaDb, mntUrl): """ Constructor :param iface: interface :param memoryPointsLayer: working memory points layer :param memoryLinesLayer: working memory lines layer :param configTable: config table selected for import """ QDialog.__init__(self) self.__iface = iface self.__memoryPointsLayer = memoryPointsLayer self.__memoryLinesLayer = memoryLinesLayer self.__ctlDb = ctllDb self.__configTable = configTable self.__uriDb = uriDb self.__schemaDb = schemaDb self.__mntUrl = mntUrl self.setWindowTitle(QCoreApplication.translate("VDLTools", "Settings")) self.__pointsLayers = [] self.__linesLayers = [] self.__tables = [] self.__schemas = [] self.__dbs = DBConnector.getUsedDatabases() for layer in list(QgsMapLayerRegistry.instance().mapLayers().values()): if layer is not None and layer.type( ) == QgsMapLayer.VectorLayer and layer.providerType() == "memory": if layer.geometryType() == QGis.Point: self.__pointsLayers.append(layer) if layer.geometryType() == QGis.Line: self.__linesLayers.append(layer) self.resize(450, 200) self.__layout = QGridLayout() pointLabel = QLabel( QCoreApplication.translate("VDLTools", "Working points layer : ")) pointLabel.setMinimumHeight(20) pointLabel.setMinimumWidth(50) self.__layout.addWidget(pointLabel, 0, 1) self.__pointCombo = QComboBox() self.__pointCombo.setMinimumHeight(20) self.__pointCombo.setMinimumWidth(50) self.__pointCombo.addItem("") for layer in self.__pointsLayers: self.__pointCombo.addItem(layer.name()) self.__layout.addWidget(self.__pointCombo, 0, 2) self.__pointCombo.currentIndexChanged.connect(self.__pointComboChanged) if self.__memoryPointsLayer is not None: if self.__memoryPointsLayer in self.__pointsLayers: self.__pointCombo.setCurrentIndex( self.__pointsLayers.index(self.__memoryPointsLayer) + 1) lineLabel = QLabel( QCoreApplication.translate("VDLTools", "Working lines layer : ")) lineLabel.setMinimumHeight(20) lineLabel.setMinimumWidth(50) self.__layout.addWidget(lineLabel, 1, 1) self.__lineCombo = QComboBox() self.__lineCombo.setMinimumHeight(20) self.__lineCombo.setMinimumWidth(50) self.__lineCombo.addItem("") for layer in self.__linesLayers: self.__lineCombo.addItem(layer.name()) self.__layout.addWidget(self.__lineCombo, 1, 2) self.__lineCombo.currentIndexChanged.connect(self.__lineComboChanged) if self.__memoryLinesLayer is not None: if self.__memoryLinesLayer in self.__linesLayers: self.__lineCombo.setCurrentIndex( self.__linesLayers.index(self.__memoryLinesLayer) + 1) dbLabel = QLabel( QCoreApplication.translate("VDLTools", "Import database : ")) dbLabel.setMinimumHeight(20) dbLabel.setMinimumWidth(50) self.__layout.addWidget(dbLabel, 2, 1) self.__dbCombo = QComboBox() self.__dbCombo.setMinimumHeight(20) self.__dbCombo.setMinimumWidth(50) self.__dbCombo.addItem("") for db in list(self.__dbs.keys()): self.__dbCombo.addItem(db) self.__layout.addWidget(self.__dbCombo, 2, 2) schemaLabel = QLabel( QCoreApplication.translate("VDLTools", "Database schema : ")) schemaLabel.setMinimumHeight(20) schemaLabel.setMinimumWidth(50) self.__layout.addWidget(schemaLabel, 3, 1) self.__schemaCombo = QComboBox() self.__schemaCombo.setMinimumHeight(20) self.__schemaCombo.setMinimumWidth(50) self.__schemaCombo.addItem("") self.__layout.addWidget(self.__schemaCombo, 3, 2) tableLabel = QLabel( QCoreApplication.translate("VDLTools", "Config table : ")) tableLabel.setMinimumHeight(20) tableLabel.setMinimumWidth(50) self.__layout.addWidget(tableLabel, 4, 1) self.__tableCombo = QComboBox() self.__tableCombo.setMinimumHeight(20) self.__tableCombo.setMinimumWidth(50) self.__tableCombo.addItem("") self.__layout.addWidget(self.__tableCombo, 4, 2) mntLabel = QLabel( QCoreApplication.translate("VDLTools", "Url for MNT : ")) schemaLabel.setMinimumHeight(20) schemaLabel.setMinimumWidth(50) self.__layout.addWidget(mntLabel, 5, 1) self.__mntText = QLineEdit() if self.__mntUrl is None or self.__mntUrl == "None": self.__mntText.insert( 'http://map.lausanne.ch/main/wsgi/profile.json') else: self.__mntText.insert(self.__mntUrl) self.__mntText.setMinimumHeight(20) self.__mntText.setMinimumWidth(100) self.__layout.addWidget(self.__mntText, 5, 2) ctlLabel = QLabel( QCoreApplication.translate("VDLTools", "Control database : ")) ctlLabel.setMinimumHeight(20) ctlLabel.setMinimumWidth(50) self.__layout.addWidget(ctlLabel, 6, 1) self.__ctlCombo = QComboBox() self.__ctlCombo.setMinimumHeight(20) self.__ctlCombo.setMinimumWidth(50) self.__ctlCombo.addItem("") for db in list(self.__dbs.keys()): self.__ctlCombo.addItem(db) self.__layout.addWidget(self.__ctlCombo, 6, 2) self.__okButton = QPushButton( QCoreApplication.translate("VDLTools", "OK")) self.__okButton.setMinimumHeight(20) self.__okButton.setMinimumWidth(100) self.__cancelButton = QPushButton( QCoreApplication.translate("VDLTools", "Cancel")) self.__cancelButton.setMinimumHeight(20) self.__cancelButton.setMinimumWidth(100) self.__layout.addWidget(self.__okButton, 100, 1) self.__layout.addWidget(self.__cancelButton, 100, 2) self.setLayout(self.__layout) self.__dbCombo.currentIndexChanged.connect(self.__dbComboChanged) self.__schemaCombo.currentIndexChanged.connect( self.__schemaComboChanged) self.__tableCombo.currentIndexChanged.connect(self.__tableComboChanged) self.__ctlCombo.currentIndexChanged.connect(self.__ctlComboChanged) if self.__uriDb is not None: if self.__uriDb.database() in list(self.__dbs.keys()): self.__dbCombo.setCurrentIndex( list(self.__dbs.keys()).index(self.__uriDb.database()) + 1) if self.__ctlDb is not None: if self.__ctlDb.database() in list(self.__dbs.keys()): self.__ctlCombo.setCurrentIndex( list(self.__dbs.keys()).index(self.__ctlDb.database()) + 1) @staticmethod def __resetCombo(combo): """ To reset a combo list :param combo: concerned combo """ while combo.count() > 0: combo.removeItem(combo.count() - 1) def __setSchemaCombo(self, uriDb): """ To fill the schema combo list :param uriDb: selected database uri """ connector = DBConnector(uriDb, self.__iface) db = connector.setConnection() if db: Signal.safelyDisconnect(self.__schemaCombo.currentIndexChanged, self.__schemaComboChanged) self.__resetCombo(self.__schemaCombo) self.__schemaCombo.addItem("") self.__schemas = [] query = db.exec_( """SELECT DISTINCT table_schema FROM information_schema.tables WHERE table_schema NOT IN ('pg_catalog', 'information_schema', 'topology') AND table_type = 'BASE TABLE' AND table_name NOT IN (SELECT f_table_name FROM geometry_columns)""") if query.lastError().isValid(): self.__iface.messageBar().pushMessage( query.lastError().text(), level=QgsMessageBar.CRITICAL, duration=0) else: while next(query): self.__schemas.append(query.value(0)) db.close() for schema in self.__schemas: self.__schemaCombo.addItem(schema) self.__schemaCombo.currentIndexChanged.connect( self.__schemaComboChanged) if self.__schemaDb is not None: if self.__schemaDb in self.__schemas: self.__schemaCombo.setCurrentIndex( self.__schemas.index(self.__schemaDb) + 1) def __setTableCombo(self, uriDb, schema): """ To fill the table combo list :param uriDb: selected database uri :param schema: selected database schema """ connector = DBConnector(uriDb, self.__iface) db = connector.setConnection() if db: Signal.safelyDisconnect(self.__tableCombo.currentIndexChanged, self.__tableComboChanged) self.__resetCombo(self.__tableCombo) self.__tableCombo.addItem("") self.__tables = [] query = db.exec_( """SELECT table_name FROM information_schema.tables WHERE table_schema = '""" + schema + """' ORDER BY table_name""") if query.lastError().isValid(): self.__iface.messageBar().pushMessage( query.lastError().text(), level=QgsMessageBar.CRITICAL, duration=0) else: while next(query): self.__tables.append(query.value(0)) db.close() for table in self.__tables: if self.__tableCombo.findText(table) == -1: self.__tableCombo.addItem(table) self.__tableCombo.currentIndexChanged.connect( self.__tableComboChanged) if self.__configTable is not None: if self.__configTable in self.__tables: self.__tableCombo.setCurrentIndex( self.__tables.index(self.__configTable) + 1) def __lineComboChanged(self): """ To remove blank item when another one is selected """ if self.__lineCombo.itemText(0) == "": self.__lineCombo.removeItem(0) def __pointComboChanged(self): """ To remove blank item when another one is selected """ if self.__pointCombo.itemText(0) == "": self.__pointCombo.removeItem(0) def __tableComboChanged(self): """ To remove blank item when another one is selected """ if self.__tableCombo.itemText(0) == "": self.__tableCombo.removeItem(0) def __dbComboChanged(self): """ When the selection in db combo has changed """ if self.__dbCombo.itemText(0) == "": self.__dbCombo.removeItem(0) if self.uriDb() is not None: self.__setSchemaCombo(self.uriDb()) def __schemaComboChanged(self): """ When the selection in schema combo has changed """ if self.__schemaCombo.itemText(0) == "": self.__schemaCombo.removeItem(0) if self.schemaDb() is not None: self.__setTableCombo(self.uriDb(), self.schemaDb()) def __ctlComboChanged(self): """ When the selection in ctl combo has changed """ if self.__ctlCombo.itemText(0) == "": self.__ctlCombo.removeItem(0) def okButton(self): """ To get the ok button instance :return: ok button instance """ return self.__okButton def cancelButton(self): """ To get the cancel button instance :return: cancel button instance """ return self.__cancelButton def pointsLayer(self): """ To get the selected memory points layer :return: selected memeory points layer, or none """ index = self.__pointCombo.currentIndex() if self.__pointCombo.itemText(index) == "": return None else: return self.__pointsLayers[index] def linesLayer(self): """ To get the selected memory lines layer :return: selected memory lines layer, or none """ index = self.__lineCombo.currentIndex() if self.__lineCombo.itemText(index) == "": return None else: return self.__linesLayers[index] def configTable(self): """ To get the selected config table :return: selected config table, or none """ index = self.__tableCombo.currentIndex() if self.__tableCombo.itemText(index) == "": return None else: return self.__tables[index] def uriDb(self): """ To get selected import database uri :return: import database uri """ index = self.__dbCombo.currentIndex() if self.__dbCombo.itemText(index) == "": return None else: return self.__dbs[list(self.__dbs.keys())[index]] def schemaDb(self): """ To get selected import database schema :return: import database schema """ index = self.__schemaCombo.currentIndex() if self.__schemaCombo.itemText(index) == "": return None else: return self.__schemas[index] def mntUrl(self): """ To get selected MN url :return: MN url """ return self.__mntText.text() def ctlDb(self): """ To get selected control database uri :return: control database uri """ index = self.__ctlCombo.currentIndex() if self.__ctlCombo.itemText(index) == "": return None else: return self.__dbs[list(self.__dbs.keys())[index]]
def addGuiItem(self, ParentClass, parameters, width): """Defines a new set of Label and a box that can be a ComboBox, RComboBox, LineEdit, TextEdit or DoubleSpinBox.""" widgetType=parameters[1] #check if there are default values: if len(parameters)>2: default=parameters[2] else: default="" skip = False notnull=parameters[3] #setting the right type of widget if widgetType=="comboBox": widget = QComboBox(ParentClass) widget.addItems(default.split(';')) widget.setFixedHeight(26) elif widgetType=="RComboBox": widget = RComboBox(ParentClass, default.split(';')) widget.setFixedHeight(26) self.hasRComboBox = True widget.setEditable(True) elif widgetType=="RListWidget": widget = RListWidget(ParentClass, default.split(';'), notnull) widget.setMinimumHeight(116) self.hasRComboBox = True widget.setSelectionMode( QAbstractItemView.ExtendedSelection) elif widgetType=="doubleSpinBox": widget = QDoubleSpinBox(ParentClass) widget.setValue(float(default)) widget.setFixedHeight(26) widget.setMaximum(999999.9999) widget.setDecimals(4) elif widgetType=="textEdit": widget = QTextEdit(ParentClass) widget.setPlainText(default) widget.setMinimumHeight(116) elif widgetType=="helpString": self.helpString = default skip = True else: #if unknown assumes lineEdit widget = QLineEdit(ParentClass) widget.setText(default) widget.setFixedHeight(26) if not skip: hbox = QHBoxLayout() name="widget"+unicode(self.widgetCounter) widget.setObjectName(name) widget.setMinimumWidth(250) self.widgets.append(widget) name="label"+unicode(self.widgetCounter) self.widgetCounter += 1 label = QLabel(ParentClass) label.setObjectName(name) label.setFixedWidth(width*8) label.setText(parameters[0]) hbox.addWidget(label) hbox.addWidget(widget) self.vbox.addLayout(hbox)
class ShowSettingsDialog(QDialog): """ Dialog class for plugin settings """ def __init__(self, iface, configTable, uriDb, schemaDb): """ Constructor :param iface: interface :param memoryPointsLayer: working memory points layer :param memoryLinesLayer: working memory lines layer :param configTable: config table selected for import """ QDialog.__init__(self) self.__iface = iface self.__configTable = configTable self.__uriDb = uriDb self.__schemaDb = schemaDb self.setWindowTitle( QCoreApplication.translate("VDLNetwork", "Settings")) self.__tables = [] self.__schemas = [] self.__dbs = DBConnector.getUsedDatabases() self.resize(450, 200) self.__layout = QGridLayout() dbLabel = QLabel( QCoreApplication.translate("VDLNetwork", "Control database : ")) dbLabel.setMinimumHeight(20) dbLabel.setMinimumWidth(50) self.__layout.addWidget(dbLabel, 0, 1) self.__dbCombo = QComboBox() self.__dbCombo.setMinimumHeight(20) self.__dbCombo.setMinimumWidth(50) self.__dbCombo.addItem("") for db in list(self.__dbs.keys()): self.__dbCombo.addItem(db) self.__layout.addWidget(self.__dbCombo, 0, 2) schemaLabel = QLabel( QCoreApplication.translate("VDLNetwork", "Control schema : ")) schemaLabel.setMinimumHeight(20) schemaLabel.setMinimumWidth(50) self.__layout.addWidget(schemaLabel, 1, 1) self.__schemaCombo = QComboBox() self.__schemaCombo.setMinimumHeight(20) self.__schemaCombo.setMinimumWidth(50) self.__schemaCombo.addItem("") self.__layout.addWidget(self.__schemaCombo, 1, 2) tableLabel = QLabel( QCoreApplication.translate("VDLNetwork", "Control table : ")) tableLabel.setMinimumHeight(20) tableLabel.setMinimumWidth(50) self.__layout.addWidget(tableLabel, 2, 1) self.__tableCombo = QComboBox() self.__tableCombo.setMinimumHeight(20) self.__tableCombo.setMinimumWidth(50) self.__tableCombo.addItem("") self.__layout.addWidget(self.__tableCombo, 2, 2) self.__okButton = QPushButton( QCoreApplication.translate("VDLNetwork", "OK")) self.__okButton.setMinimumHeight(20) self.__okButton.setMinimumWidth(100) self.__cancelButton = QPushButton( QCoreApplication.translate("VDLNetwork", "Cancel")) self.__cancelButton.setMinimumHeight(20) self.__cancelButton.setMinimumWidth(100) self.__layout.addWidget(self.__okButton, 100, 1) self.__layout.addWidget(self.__cancelButton, 100, 2) self.setLayout(self.__layout) self.__dbCombo.currentIndexChanged.connect(self.__dbComboChanged) self.__schemaCombo.currentIndexChanged.connect( self.__schemaComboChanged) self.__tableCombo.currentIndexChanged.connect(self.__tableComboChanged) if self.__uriDb is not None: if self.__uriDb.database() in list(self.__dbs.keys()): self.__dbCombo.setCurrentIndex( list(self.__dbs.keys()).index(self.__uriDb.database()) + 1) @staticmethod def __resetCombo(combo): """ To reset a combo list :param combo: concerned combo """ while combo.count() > 0: combo.removeItem(combo.count() - 1) def __setSchemaCombo(self, uriDb): """ To fill the schema combo list :param uriDb: selected database uri """ connector = DBConnector(uriDb, self.__iface) db = connector.setConnection() if db: Signal.safelyDisconnect(self.__schemaCombo.currentIndexChanged, self.__schemaComboChanged) self.__resetCombo(self.__schemaCombo) self.__schemaCombo.addItem("") self.__schemas = [] query = db.exec_( """SELECT DISTINCT table_schema FROM information_schema.tables WHERE table_schema NOT IN ('pg_catalog', 'information_schema', 'topology') AND table_type = 'BASE TABLE' AND table_name NOT IN (SELECT f_table_name FROM geometry_columns)""") if query.lastError().isValid(): self.__iface.messageBar().pushMessage( query.lastError().text(), level=QgsMessageBar.CRITICAL, duration=0) else: while next(query): self.__schemas.append(query.value(0)) db.close() for schema in self.__schemas: self.__schemaCombo.addItem(schema) self.__schemaCombo.currentIndexChanged.connect( self.__schemaComboChanged) if self.__schemaDb is not None: if self.__schemaDb in self.__schemas: self.__schemaCombo.setCurrentIndex( self.__schemas.index(self.__schemaDb) + 1) def __setTableCombo(self, uriDb, schema): """ To fill the table combo list :param uriDb: selected database uri :param schema: selected database schema """ connector = DBConnector(uriDb, self.__iface) db = connector.setConnection() if db: Signal.safelyDisconnect(self.__tableCombo.currentIndexChanged, self.__tableComboChanged) self.__resetCombo(self.__tableCombo) self.__tableCombo.addItem("") self.__tables = [] query = db.exec_( """SELECT table_name FROM information_schema.tables WHERE table_schema = '""" + schema + """' ORDER BY table_name""") if query.lastError().isValid(): self.__iface.messageBar().pushMessage( query.lastError().text(), level=QgsMessageBar.CRITICAL, duration=0) else: while next(query): self.__tables.append(query.value(0)) db.close() for table in self.__tables: if self.__tableCombo.findText(table) == -1: self.__tableCombo.addItem(table) self.__tableCombo.currentIndexChanged.connect( self.__tableComboChanged) if self.__configTable is not None: if self.__configTable in self.__tables: self.__tableCombo.setCurrentIndex( self.__tables.index(self.__configTable) + 1) def __tableComboChanged(self): """ To remove blank item when another one is selected """ if self.__tableCombo.itemText(0) == "": self.__tableCombo.removeItem(0) def __dbComboChanged(self): """ When the selection in db combo has changed """ if self.__dbCombo.itemText(0) == "": self.__dbCombo.removeItem(0) if self.uriDb() is not None: self.__setSchemaCombo(self.uriDb()) def __schemaComboChanged(self): """ When the selection in schema combo has changed """ if self.__schemaCombo.itemText(0) == "": self.__schemaCombo.removeItem(0) if self.schemaDb() is not None: self.__setTableCombo(self.uriDb(), self.schemaDb()) def okButton(self): """ To get the ok button instance :return: ok button instance """ return self.__okButton def cancelButton(self): """ To get the cancel button instance :return: cancel button instance """ return self.__cancelButton def configTable(self): """ To get the selected config table :return: selected config table, or none """ index = self.__tableCombo.currentIndex() if self.__tableCombo.itemText(index) == "": return None else: return self.__tables[index] def uriDb(self): """ To get selected import database uri :return: import database uri """ index = self.__dbCombo.currentIndex() if self.__dbCombo.itemText(index) == "": return None else: return self.__dbs[list(self.__dbs.keys())[index]] def schemaDb(self): """ To get selected import database schema :return: import database schema """ index = self.__schemaCombo.currentIndex() if self.__schemaCombo.itemText(index) == "": return None else: return self.__schemas[index]
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)
class BrowserMatPlotFrame(QtGui.QWidget): "定义画图的页面" def __init__(self, parent = None): QtGui.QWidget.__init__(self) self.parent = parent self.status_bar = parent.status_bar #State self.draw_node_labels_tf = True self.draw_axis_units_tf = False self.draw_grid_tf = False self.g = None #PATH used in drawing STEP hierarchy, co-occurence, context self.step_path = parent.step_path #MPL figure self.dpi = 100 self.fig = Figure((5.0, 4.0), dpi=self.dpi) self.fig.subplots_adjust(left=0,right=1,top=1,bottom=0) #QT canvas self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self) self.canvas.mpl_connect('pick_event', self.on_pick) #used when selectingpyth canvas objects self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.axes = self.fig.add_subplot(111) #self.axes.hold(False) #clear the axes every time plot() is called self.mpl_toolbar = NavigationToolbar(self.canvas, self) #GUI controls self.mode_combo = QComboBox() self.mode_combo.addItems(["Graph Test", "Graph Test Numpy", "STEP Hierarchy", "STEP Co-occurence", "STEP Context"]) self.mode_combo.setMinimumWidth(200) self.draw_button = QPushButton("&Draw/Refresh") self.connect(self.draw_button, QtCore.SIGNAL('clicked()'), self.on_draw) self.node_size = QSpinBox(self) self.node_size.setSingleStep(5) self.node_size.setMaximum(100) self.node_size.setValue(25) self.node_size_label = QLabel('Node Size (%):') # connection set in on_draw() method #Horizontal layout hbox = QtGui.QHBoxLayout() #Adding matplotlib widgets for w in [self.mode_combo, 's', self.node_size_label, self.node_size, self.draw_button]: if w == 's': hbox.addStretch() else: hbox.addWidget(w) hbox.setAlignment(w, Qt.AlignVCenter) #Vertical layout. Adding all other widgets, and hbox layout. vbox = QtGui.QVBoxLayout() vbox.addWidget(self.mpl_toolbar) vbox.addWidget(self.canvas) vbox.addLayout(hbox) self.setLayout(vbox) self.canvas.setFocus(True) def draw_axis_units(self): fw = self.fig.get_figwidth() fh = self.fig.get_figheight() l_margin = .4 / fw #.4in b_margin = .3 / fh #.3in if self.draw_axis_units_tf == True: self.fig.subplots_adjust(left=l_margin,right=1,top=1,bottom=b_margin) else: self.fig.subplots_adjust(left=0,right=1,top=1,bottom=0) self.canvas.draw() def draw_grid(self): if self.draw_grid_tf == False: self.draw_grid_tf = True else: self.draw_grid_tf = False self.axes.grid(self.draw_grid_tf) self.canvas.draw() def on_draw(self): draw_mode = self.mode_combo.currentText() self.axes.clear() if self.g != None: if hasattr(self.g, 'destruct'): self.g.destruct() if draw_mode == "Graph Test": self.g = GraphTest(self) elif draw_mode == "Graph Test Numpy": self.g = GraphTestNumPy(self) elif draw_mode == "STEP Hierarchy": self.g = GraphHierarchy(self) elif draw_mode == "STEP Co-occurence": self.g = GraphCoOccurrence(self) elif draw_mode == "STEP Context": self.g = GraphCoOccurrence(self) self.connect(self.node_size, QtCore.SIGNAL('valueChanged(int)'), self.g.set_node_mult) self.axes.grid(self.draw_grid_tf) self.canvas.draw() def on_pick(self, args): print "in matplotframe: ", args def resizeEvent(self, ev): self.draw_axis_units() def set_step_path(self, path): self.step_path = path self.parent.set_step_path(path) def toggle_axis_units(self): if self.draw_axis_units_tf == False: self.draw_axis_units_tf = True else: self.draw_axis_units_tf = False self.draw_axis_units() def toggle_node_labels(self): if self.draw_node_labels_tf == False: self.draw_node_labels_tf = True else: self.draw_node_labels_tf = False if self.g != None: self.g.redraw()
class StyleChooser(QWidget): def __init__(self, line_style_set=STYLESET_DEFAULT): QWidget.__init__(self) self._style = PlotStyle("StyleChooser Internal Style") self._styles = STYLES[ 'default'] if not line_style_set in STYLES else STYLES[ line_style_set] self.setMinimumWidth(140) self.setMaximumHeight(25) layout = QHBoxLayout() layout.setMargin(0) layout.setSpacing(2) self.line_chooser = QComboBox() self.line_chooser.setToolTip("Select line style.") for style in self._styles: self.line_chooser.addItem(*style) self.marker_chooser = QComboBox() self.marker_chooser.setToolTip("Select marker style.") for marker in MARKERS: self.marker_chooser.addItem(*marker) self.thickness_spinner = QDoubleSpinBox() self.thickness_spinner.setToolTip("Line thickness") self.thickness_spinner.setMinimum(0.1) self.thickness_spinner.setDecimals(1) self.thickness_spinner.setSingleStep(0.1) self.size_spinner = QDoubleSpinBox() self.size_spinner.setToolTip("Marker Size") self.size_spinner.setMinimum(0.1) self.size_spinner.setDecimals(1) self.size_spinner.setSingleStep(0.1) # the text content of the spinner varies, but shouldn't push the control out of boundaries self.line_chooser.setMinimumWidth(110) layout.addWidget(self.line_chooser) layout.addWidget(self.thickness_spinner) layout.addWidget(self.marker_chooser) layout.addWidget(self.size_spinner) self.setLayout(layout) self.line_chooser.currentIndexChanged.connect(self._updateStyle) self.marker_chooser.currentIndexChanged.connect(self._updateStyle) self.thickness_spinner.valueChanged.connect(self._updateStyle) self.size_spinner.valueChanged.connect(self._updateStyle) self._updateLineStyleAndMarker(self._style.line_style, self._style.marker, self._style.width, self._style.size) self._layout = layout def getItemSizes(self): line_style_combo_width = self._layout.itemAt(0).sizeHint().width() thickness_spinner_width = self._layout.itemAt(1).sizeHint().width() marker_combo_width = self._layout.itemAt(2).sizeHint().width() size_spinner_width = self._layout.itemAt(3).sizeHint().width() return line_style_combo_width, thickness_spinner_width, marker_combo_width, size_spinner_width def _findLineStyleIndex(self, line_style): for index, style in enumerate(self._styles): if style[1] == line_style: return index elif style[1] is None and line_style == "": return index return -1 def _findMarkerStyleIndex(self, marker): for index, style in enumerate(MARKERS): if style[1] == marker: return index elif style[1] is None and marker == "": return index return -1 def _updateLineStyleAndMarker(self, line_style, marker, thickness, size): self.line_chooser.setCurrentIndex(self._findLineStyleIndex(line_style)) self.marker_chooser.setCurrentIndex(self._findMarkerStyleIndex(marker)) self.thickness_spinner.setValue(thickness) self.size_spinner.setValue(size) def _updateStyle(self): self.marker_chooser.setEnabled( self.line_chooser.currentText() != "Area") line_style = self.line_chooser.itemData( self.line_chooser.currentIndex()) marker_style = self.marker_chooser.itemData( self.marker_chooser.currentIndex()) thickness = float(self.thickness_spinner.value()) size = float(self.size_spinner.value()) self._style.line_style = str(line_style.toString()) self._style.marker = str(marker_style.toString()) self._style.width = thickness self._style.size = size def setStyle(self, style): """ @type style: PlotStyle """ self._style.copyStyleFrom(style) self._updateLineStyleAndMarker(style.line_style, style.marker, style.width, style.size) def getStyle(self): """ @rtype: PlotStyle """ style = PlotStyle("Generated Style from StyleChooser") style.copyStyleFrom(self._style) return style def createLabelLayout(self, layout=None): if layout is None: layout = QHBoxLayout() titles = ["Line Style", "Width", "Marker Style", "Size"] sizes = self.getItemSizes() for title, size in zip(titles, sizes): label = QLabel(title) label.setFixedWidth(size) layout.addWidget(label) return layout
class Plugin(QObject): def __init__(self, iface): QObject.__init__(self) self.__iface = iface self.__shortcuts = [] self.__current_section = QComboBox() self.__current_section.setMinimumWidth(150) self.__current_graph = QComboBox() self.__current_graph.setMinimumWidth(150) self.__toolbar = None self.__axis_layer = None self.__menu = None self.__log_strati = None def initGui(self): for keyseq, slot in ( (Qt.CTRL + Qt.ALT + Qt.Key_K, self.__create_group), (Qt.CTRL + Qt.ALT + Qt.Key_S, self.__select_next_group), (Qt.CTRL + Qt.ALT + Qt.Key_N, self.__next_section), (Qt.CTRL + Qt.ALT + Qt.Key_B, self.__previous_section) ): short = QShortcut(QKeySequence(keyseq), self.__iface.mainWindow()) short.setContext(Qt.ApplicationShortcut) short.activated.connect(slot) self.__shortcuts.append(short) self.__menu = QMenu("Albion") self.__menu.aboutToShow.connect(self.__create_menu_entries) self.__iface.mainWindow().menuBar().addMenu(self.__menu) self.__toolbar = QToolBar('Albion') self.__iface.addToolBar(self.__toolbar) self.__toolbar.addAction(icon('log_strati.svg'), 'stratigraphic log').triggered.connect(self.__log_strati_clicked) self.__toolbar.addWidget(self.__current_graph) self.__current_graph.currentIndexChanged[unicode].connect(self.__current_graph_changed) self.__toolbar.addWidget(self.__current_section) self.__current_section.currentIndexChanged[unicode].connect(self.__current_section_changed) self.__toolbar.addAction(icon('previous_line.svg'), 'previous section (Ctrl+Alt+b)').triggered.connect(self.__previous_section) self.__toolbar.addAction(icon('next_line.svg'), 'next section (Ctrl+Alt+n)').triggered.connect(self.__next_section) self.__toolbar.addAction(icon('line_from_selected.svg'), 'create temporary section').triggered.connect(self.__section_from_selection) self.__viewer3d = QDockWidget('3D') self.__viewer3d.setWidget(Viewer3d()) self.__iface.addDockWidget(Qt.LeftDockWidgetArea, self.__viewer3d) self.__iface.mainWindow().tabifyDockWidget( self.__iface.mainWindow().findChild(QDockWidget, "Layers"), self.__viewer3d) self.__viewer3d_ctrl = QToolBar('3D controls') self.__viewer3d_ctrl.addWidget(ViewerControls(self.__viewer3d.widget())) self.__iface.addToolBar(self.__viewer3d_ctrl) QgsProject.instance().readProject.connect(self.__qgis__project__loaded) self.__qgis__project__loaded() # case of reload def unload(self): for s in self.__shortcuts: s.setParent(None) self.__toolbar and self.__toolbar.setParent(None) self.__menu and self.__menu.setParent(None) self.__viewer3d and self.__viewer3d.setParent(None) self.__viewer3d_ctrl and self.__viewer3d_ctrl.setParent(None) def __add_menu_entry(self, name, callback, enabled=True, help_str=''): act = self.__menu.addAction(name) if callback is not None: act.triggered.connect(callback) act.setEnabled(enabled) act.setToolTip(help_str) else: act.setEnabled(False) act.setToolTip("NOT INMPLEMENTED "+help_str) return act def __create_menu_entries(self): self.__menu.clear() self.__add_menu_entry('New &Project', self.__new_project) self.__add_menu_entry('Import Project', self.__import_project) self.__add_menu_entry('Upgrade Project', self.__upgrade_project) self.__menu.addSeparator() self.__add_menu_entry('&Import Data', self.__import_data, self.project is not None, "Import data from directory. The data files are in ") self.__menu.addSeparator() self.__add_menu_entry('Create cells', self.__create_cells, self.project is not None and self.project.has_collar, "Create Delaunay triangulation of collar layer.") self.__add_menu_entry('Refresh all edges', self.__refresh_all_edge, self.project is not None and self.project.has_cell, "Refresh materialized view of all cell edges used by graph possible edges.") self.__menu.addSeparator() #self.__add_menu_entry(u'Create section views 0° and 90°', self.__create_section_view_0_90, # False and self.project is not None and self.project.has_hole, # "Create section views (i.e. cut directions) to work West-East and South-North for this project") #self.__add_menu_entry(u'Create section views -45° and 45°', None, # False and self.project is not None and self.project.has_hole, # "Create section views (i.e. cut directions) to work SE-NW and SW-NE for this project") # #self.__menu.addSeparator() self.__add_menu_entry('Create sections', self.__create_sections, self.project is not None and self.project.has_group_cell, "Once cell groups have been defined, create section lines.") self.__menu.addSeparator() self.__add_menu_entry('Compute &Mineralization', self.__compute_mineralization, self.project is not None and self.project.has_radiometry, "") self.__menu.addSeparator() self.__add_menu_entry('New &Graph', self.__new_graph, self.project is not None, "Create a new grap.h") self.__add_menu_entry('Delete Graph', self.__delete_graph, self.project is not None) self.__menu.addSeparator() self.__add_menu_entry('Create volumes', self.__create_volumes, self.project is not None and bool(self.__current_graph.currentText()), "Create volumes associated with current graph.") self.__menu.addSeparator() self.__add_menu_entry('Create terminations', self.__create_terminations, self.project is not None and bool(self.__current_graph.currentText()), "Create terminations associated with current graph.") self.__menu.addSeparator() self.__add_menu_entry('Toggle axis', self.__toggle_axis) self.__menu.addSeparator() self.__add_menu_entry('Export Project', self.__export_project, self.project is not None) self.__add_menu_entry('Export Sections', None, self.project is not None and self.project.has_section, "Export triangulated section in .obj or .dxf format") self.__add_menu_entry('Export Volume', self.__export_volume, self.project is not None and bool(self.__current_graph.currentText()), "Export volume of current graph in .obj or .dxf format") self.__menu.addSeparator() self.__menu.addAction('Help').triggered.connect(self.open_help) def __current_graph_changed(self, graph_id): if self.project is None: return self.__viewer3d.widget().set_graph(graph_id) def __getattr__(self, name): if name == "project": project_name = QgsProject.instance().readEntry("albion", "project_name", "")[0] return Project(project_name) if project_name else None else: raise AttributeError(name) def __refresh_all_edge(self): if self.project is None: return self.project.refresh_all_edge() def __create_terminations(self): if self.project is None: return self.project.create_terminations(self.__current_graph.currentText()) self.__viewer3d.widget().refresh_data() self.__refresh_layers('section') def __create_volumes(self): if self.project is None: return self.project.create_volumes(self.__current_graph.currentText()) self.__viewer3d.widget().refresh_data() def __next_section(self): if self.project is None: return self.project.next_section(self.__current_section.currentText()) self.__refresh_layers('section') self.__viewer3d.widget().scene.update('section') self.__viewer3d.widget().update() def __previous_section(self): if self.project is None: return self.project.previous_section(self.__current_section.currentText()) self.__refresh_layers('section') self.__viewer3d.widget().scene.update('section') self.__viewer3d.widget().update() def __refresh_layers(self, name=None): for layer in self.__iface.mapCanvas().layers(): if name is None or layer.name().find(name) != -1: layer.triggerRepaint() def __current_section_changed(self, section_id): layers = QgsMapLayerRegistry.instance().mapLayersByName(u"group_cell") if len(layers): layers[0].setSubsetString("section_id='{}'".format(section_id)) self.__refresh_layers('section') def __select_next_group(self): if self.project and self.__iface.activeLayer() and self.__iface.activeLayer().name() == u"cell": self.__iface.activeLayer().removeSelection() self.__iface.activeLayer().selectByExpression( "id in ({})".format(",".join(project.next_group_ids()))) def __create_group(self): if self.project and self.__iface.activeLayer() and self.__iface.activeLayer().name() == u"cell": if self.__iface.activeLayer().selectedFeatureCount(): section = self.__current_section.currentText() self.project.create_group(section, [f['id'] for f in self.__iface.activeLayer().selectedFeatures()]) self.__iface.activeLayer().removeSelection() self.__refresh_layers('group_cell') def __qgis__project__loaded(self): if self.project is None: return self.__current_graph.clear() self.__current_section.clear() self.__current_section.addItems(self.project.sections()) self.__current_graph.addItems(self.project.graphs()) layers = QgsMapLayerRegistry.instance().mapLayersByName('section.anchor') if len(layers): layers[0].editingStopped.connect(self.__update_section_list) self.__viewer3d.widget().resetScene(self.project) def __update_section_list(self): self.__current_section.clear() self.__current_section.addItems(self.project.sections()) def __upgrade_project(self): project_name, ok = QInputDialog.getText(self.__iface.mainWindow(), "Database name", "Database name:", QLineEdit.Normal, '') if not ok: return Project(project_name).update() def __new_project(self): # @todo open dialog to configure project name and srid fil = QFileDialog.getSaveFileName(None, u"New project name (no space, plain ascii)", QgsProject.instance().readEntry("albion", "last_dir", "")[0], "QGIS poject file (*.qgs)") if not fil: return fil = fil if len(fil)>4 and fil[-4:]=='.qgs' else fil+'.qgs' fil = fil.replace(' ','_') try: fil.decode('ascii') except UnicodeDecodeError: self.__iface.messageBar().pushError('Albion:', "project name may only contain asci character (no accent)") return srid, ok = QInputDialog.getText(self.__iface.mainWindow(), "Project SRID", "Project SRID EPSG:", QLineEdit.Normal, '32632') if not ok: return srid = int(srid) project_name = str(os.path.split(fil)[1][:-4]) if Project.exists(project_name): if QMessageBox.Yes != QMessageBox(QMessageBox.Information, "Delete existing DB", "Database {} exits, to you want to delete it ?".format(project_name), QMessageBox.Yes|QMessageBox.No).exec_(): return Project.delete(project_name) self.__iface.messageBar().pushInfo('Albion:', "creating project...") Project.create(project_name, srid) # load template open(fil, 'w').write( open(resource('template_project.qgs')).read().replace('template_project', project_name)) self.__iface.newProject() QgsProject.instance().setFileName(fil) QgsProject.instance().read() QgsProject.instance().writeEntry("albion", "project_name", project_name) QgsProject.instance().writeEntry("albion", "srid", srid) QgsProject.instance().write() self.__qgis__project__loaded() def __import_data(self): if self.project is None: return if not QgsProject.instance().readEntry("albion", "conn_info", "")[0]: return dir_ = QFileDialog.getExistingDirectory(None, u"Data directory", QgsProject.instance().readEntry("albion", "last_dir", "")[0]) if not dir_: return QgsProject.instance().writeEntry("albion", "last_dir", dir_), progressMessageBar = self.__iface.messageBar().createMessage("Loading {}...".format(dir_)) progress = QProgressBar() progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) self.__iface.messageBar().pushWidget(progressMessageBar, self.__iface.messageBar().INFO) self.project.import_data(dir_, ProgressBar(progress)) self.project.triangulate() self.project.create_section_view_0_90(4) self.__iface.messageBar().clearWidgets() collar = QgsMapLayerRegistry.instance().mapLayersByName('collar')[0] collar.reload() collar.updateExtents() self.__iface.setActiveLayer(collar) QApplication.instance().processEvents() while self.__iface.mapCanvas().isDrawing(): QApplication.instance().processEvents() self.__iface.zoomToActiveLayer() self.__iface.actionSaveProject().trigger() self.__viewer3d.widget().resetScene(self.project) self.__current_section.clear() self.__current_section.addItems(self.project.sections()) def __new_graph(self): if self.project is None: return graph, ok = QInputDialog.getText(self.__iface.mainWindow(), "Graph", "Graph name:", QLineEdit.Normal, 'test_graph') if not ok: return parent, ok = QInputDialog.getText(self.__iface.mainWindow(), "Parent Graph", "Parent Graph name:", QLineEdit.Normal, '') if not ok: return self.project.new_graph(graph, parent) self.__current_graph.addItem(graph) self.__current_graph.setCurrentIndex(self.__current_graph.findText(graph)) def __delete_graph(self): if self.project is None: return graph, ok = QInputDialog.getText(self.__iface.mainWindow(), "Graph", "Graph name:", QLineEdit.Normal, self.__current_graph.currentText()) if not ok: return self.__current_graph.removeItem(self.__current_graph.findText(graph)) def __toggle_axis(self): if self.__axis_layer: pass QgsMapLayerRegistry.instance().removeMapLayer(self.__axis_layer.id()) self.__axis_layer = None else: self.__axis_layer = AxisLayer(self.__iface.mapCanvas().mapSettings().destinationCrs()) QgsMapLayerRegistry.instance().addMapLayer(self.__axis_layer) self.__refresh_layers() def __create_cells(self): if self.project is None: return self.project.triangulate() self.__refresh_layers('cells') def __create_sections(self): if self.project is None: return self.project.create_sections() def __compute_mineralization(self): MineralizationDialog(self.project).exec_() def __export_volume(self): if self.project is None: return fil = QFileDialog.getSaveFileName(None, u"Export volume for current graph", QgsProject.instance().readEntry("albion", "last_dir", "")[0], "File formats (*.dxf *.obj)") if not fil: return QgsProject.instance().writeEntry("albion", "last_dir", os.path.dirname(fil)), if fil[-4:] == '.obj': self.project.export_obj(self.__current_graph.currentText(), fil) elif fil[-4:] == '.dxf': self.project.export_dxf(self.__current_graph.currentText(), fil) else: self.__iface.messageBar().pushWarning('Albion', 'unsupported extension for volume export') def __import_project(self): fil = QFileDialog.getOpenFileName(None, u"Import project from file", QgsProject.instance().readEntry("albion", "last_dir", "")[0], "File formats (*.zip)") if not fil: return QgsProject.instance().writeEntry("albion", "last_dir", os.path.dirname(fil)), if fil[-4:] != '.zip': self.__iface.messageBar().pushWarning('Albion', 'unsupported extension for import') project_name = os.path.split(fil)[1][:-4] dir_ = tempfile.gettempdir() with zipfile.ZipFile(fil, "r") as z: z.extractall(dir_) dump = find_in_dir(dir_, '.dump') prj = find_in_dir(dir_, '.qgs') self.__iface.messageBar().pushInfo('Albion', 'loading {} from {}'.format(project_name, dump)) if Project.exists(project_name): if QMessageBox.Yes != QMessageBox(QMessageBox.Information, "Delete existing DB", "Database {} exits, to you want to delete it ?".format(project_name), QMessageBox.Yes|QMessageBox.No).exec_(): return Project.delete(project_name) project = Project.import_(project_name, dump) QgsProject.instance().read(QFileInfo(prj)) def __export_project(self): if self.project is None: return fil = QFileDialog.getSaveFileName(None, u"Export project", QgsProject.instance().readEntry("albion", "last_dir", "")[0], "Data files(*.zip)") if not fil: return QgsProject.instance().writeEntry("albion", "last_dir", os.path.dirname(fil)), if os.path.exists(fil): os.remove(fil) with zipfile.ZipFile(fil, 'w') as project: dump = tempfile.mkstemp()[1] self.project.export(dump) project.write(dump, self.project.name+'.dump') project.write(QgsProject.instance().fileName(), os.path.split(QgsProject.instance().fileName())[1]) def __create_section_view_0_90(self): if self.project is None: return self.project.create_section_view_0_90() def __log_strati_clicked(self): #@todo switch behavior when in section view -> ortho self.__click_tool = QgsMapToolEmitPoint(self.__iface.mapCanvas()) self.__iface.mapCanvas().setMapTool(self.__click_tool) self.__click_tool.canvasClicked.connect(self.__map_log_clicked) def __map_log_clicked(self, point, button): self.__click_tool.setParent(None) self.__click_tool = None if self.project is None: self.__log_strati and self.__log_strati.setParent(None) self.__log_strati = None return if self.__log_strati is None: self.__log_strati = QDockWidget('Stratigraphic Log') self.__log_strati.setWidget(BoreHoleWindow(self.project)) self.__iface.addDockWidget(Qt.LeftDockWidgetArea, self.__log_strati) self.__iface.mainWindow().tabifyDockWidget( self.__iface.mainWindow().findChild(QDockWidget, "Layers"), self.__log_strati) res = self.project.closest_hole_id(point.x(), point.y()) if res: self.__log_strati.widget().scene.set_current_id(res) self.__log_strati.show() self.__log_strati.raise_() def __section_from_selection(self): if self.project is None: return if self.__iface.activeLayer() and self.__iface.activeLayer().name() == u"collar" \ and self.__iface.activeLayer().selectedFeatures(): collar = self.__iface.activeLayer() selection = collar.selectedFeatures() if len(selection) < 2: return def align(l): assert len(l) >= 2 res = numpy.array(l[:2]) for p in l[2:]: u, v = res[0] - res[1], p - res[1] if numpy.dot(u,v) < 0: res[1] = p elif numpy.dot(u, u) < numpy.dot(v,v): res[0] = p # align with ref direction sqrt2 = math.sqrt(2.)/2 l = l[numpy.argsort(numpy.dot(l-res[0], res[1]-res[0]))] d = numpy.array(l[-1] - l[0]) dr = numpy.array([(0,1),(sqrt2, sqrt2),(1,0), (sqrt2, -sqrt2)]) i = numpy.argmax(numpy.abs(dr.dot(d))) return l if (dr.dot(d))[i] > 0 else l[::-1] line = LineString(align(numpy.array([f.geometry().asPoint() for f in selection]))) collar.removeSelection() self.project.set_section_geom(self.__current_section.currentText(), line) self.__refresh_layers('section') self.__viewer3d.widget().scene.update('section') self.__viewer3d.widget().update() def open_help(self): QDesktopServices.openUrl(QUrl.fromLocalFile(os.path.join(os.path.dirname(__file__), 'doc', 'build', 'html', 'index.html')))
class AudioVideoTab(QWidget): def __init__(self, parent): super(AudioVideoTab, self).__init__(parent) self.parent = parent self.name = 'AudioVideo' self.defaultStr = self.tr('Default') self.DisableStream = self.tr('Disable') self.formats = config.video_formats frequency_values = [self.defaultStr] + config.video_frequency_values bitrate_values = [self.defaultStr] + config.video_bitrate_values rotation_options = [ self.tr('None'), '90 ' + self.tr('clockwise'), '90 ' + self.tr('clockwise') + ' + ' + self.tr('vertical flip'), '90 ' + self.tr('counter clockwise'), '90 ' + self.tr('counter clockwise') + ' + ' + self.tr('vertical flip'), '180', self.tr('horizontal flip'), self.tr('vertical flip') ] digits_validator = QRegExpValidator(QRegExp(r'[1-9]\d*'), self) digits_validator_wzero = QRegExpValidator(QRegExp(r'\d*'), self) digits_validator_minus = QRegExpValidator(QRegExp(r'(-1|[1-9]\d*)'), self) time_validator = QRegExpValidator( QRegExp(r'\d{1,2}:\d{1,2}:\d{1,2}\.\d+'), self) converttoQL = QLabel(self.tr('Convert to:')) self.extQCB = QComboBox() self.extQCB.setMinimumWidth(100) vidcodecQL = QLabel('Video codec:') self.vidcodecQCB = QComboBox() self.vidcodecQCB.setMinimumWidth(110) audcodecQL = QLabel('Audio codec:') self.audcodecQCB = QComboBox() self.audcodecQCB.setMinimumWidth(110) hlayout1 = utils.add_to_layout('h', converttoQL, self.extQCB, QSpacerItem(180, 20), vidcodecQL, self.vidcodecQCB, audcodecQL, self.audcodecQCB) commandQL = QLabel(self.tr('Command:')) self.commandQLE = QLineEdit() self.presetQPB = QPushButton(self.tr('Preset')) self.defaultQPB = QPushButton(self.defaultStr) hlayout2 = utils.add_to_layout('h', commandQL, self.commandQLE, self.presetQPB, self.defaultQPB) sizeQL = QLabel(self.tr('Video Size:')) aspectQL = QLabel(self.tr('Aspect:')) frameQL = QLabel(self.tr('Frame Rate (fps):')) bitrateQL = QLabel(self.tr('Video Bitrate (kbps):')) self.widthQLE = utils.create_LineEdit((70, 16777215), digits_validator_minus, 4) self.heightQLE = utils.create_LineEdit((70, 16777215), digits_validator_minus, 4) label = QLabel('<html><p align="center">x</p></html>') layout1 = utils.add_to_layout('h', self.widthQLE, label, self.heightQLE) self.aspect1QLE = utils.create_LineEdit((50, 16777215), digits_validator, 2) self.aspect2QLE = utils.create_LineEdit((50, 16777215), digits_validator, 2) label = QLabel('<html><p align="center">:</p></html>') layout2 = utils.add_to_layout('h', self.aspect1QLE, label, self.aspect2QLE) self.frameQLE = utils.create_LineEdit((120, 16777215), digits_validator, 4) self.bitrateQLE = utils.create_LineEdit((130, 16777215), digits_validator, 6) labels = [sizeQL, aspectQL, frameQL, bitrateQL] widgets = [layout1, layout2, self.frameQLE, self.bitrateQLE] self.preserveaspectQChB = QCheckBox(self.tr("Preserve aspect ratio")) self.preservesizeQChB = QCheckBox(self.tr("Preserve video size")) preserve_layout = utils.add_to_layout('v', self.preserveaspectQChB, self.preservesizeQChB) videosettings_layout = QHBoxLayout() for a, b in zip(labels, widgets): a.setText('<html><p align="center">{0}</p></html>'.format( a.text())) layout = utils.add_to_layout('v', a, b) videosettings_layout.addLayout(layout) if a == aspectQL: # add vidaspectCB in layout after aspectQL videosettings_layout.addLayout(preserve_layout) freqQL = QLabel(self.tr('Frequency (Hz):')) chanQL = QLabel(self.tr('Audio Channels:')) bitrateQL = QLabel(self.tr('Audio Bitrate (kbps):')) threadsQL = QLabel(self.tr('Threads:')) self.freqQCB = QComboBox() self.freqQCB.addItems(frequency_values) self.chan1QRB = QRadioButton('1') self.chan1QRB.setMaximumSize(QSize(51, 16777215)) self.chan2QRB = QRadioButton('2') self.chan2QRB.setMaximumSize(QSize(51, 16777215)) self.group = QButtonGroup() self.group.addButton(self.chan1QRB) self.group.addButton(self.chan2QRB) spcr1 = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum) spcr2 = QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Minimum) chanlayout = utils.add_to_layout('h', spcr1, self.chan1QRB, self.chan2QRB, spcr2) self.audbitrateQCB = QComboBox() self.audbitrateQCB.addItems(bitrate_values) self.threadsQLE = utils.create_LineEdit((50, 16777215), digits_validator_wzero, 1) labels = [freqQL, bitrateQL, chanQL, threadsQL] widgets = [ self.freqQCB, self.audbitrateQCB, chanlayout, self.threadsQLE ] audiosettings_layout = QHBoxLayout() for a, b in zip(labels, widgets): a.setText('<html><p align="center">{0}</p></html>'.format( a.text())) layout = utils.add_to_layout('v', a, b) audiosettings_layout.addLayout(layout) time_format = " (hh:mm:ss):" beginQL = QLabel(self.tr("Split file. Begin time") + time_format) self.beginQLE = utils.create_LineEdit(None, time_validator, None) durationQL = QLabel(self.tr("Duration") + time_format) self.durationQLE = utils.create_LineEdit(None, time_validator, None) hlayout4 = utils.add_to_layout('h', beginQL, self.beginQLE, durationQL, self.durationQLE) embedQL = QLabel(self.tr("Embed subtitle:")) self.embedQLE = QLineEdit() self.embedQTB = QToolButton() self.embedQTB.setText("...") rotateQL = QLabel(self.tr("Rotate:")) self.rotateQCB = QComboBox() self.rotateQCB.addItems(rotation_options) hlayout5 = utils.add_to_layout('h', rotateQL, self.rotateQCB, embedQL, self.embedQLE, self.embedQTB) hidden_layout = utils.add_to_layout('v', videosettings_layout, audiosettings_layout, hlayout4, hlayout5) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.moreQPB = QPushButton(QApplication.translate('Tab', 'More')) self.moreQPB.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.moreQPB.setCheckable(True) hlayout3 = utils.add_to_layout('h', line, self.moreQPB) self.frame = QFrame() self.frame.setLayout(hidden_layout) self.frame.hide() final_layout = utils.add_to_layout('v', hlayout1, hlayout2, hlayout3, self.frame) self.setLayout(final_layout) self.presetQPB.clicked.connect(self.choose_preset) self.defaultQPB.clicked.connect(self.set_default_command) self.embedQTB.clicked.connect(self.open_subtitle_file) self.moreQPB.toggled.connect(self.frame.setVisible) self.moreQPB.toggled.connect( lambda: QTimer.singleShot(100, self.resize_parent)) self.widthQLE.textChanged.connect(self.command_update_size) self.heightQLE.textChanged.connect(self.command_update_size) self.aspect1QLE.textChanged.connect(self.command_update_aspect) self.aspect2QLE.textChanged.connect(self.command_update_aspect) self.frameQLE.textChanged.connect(self.command_update_frames) self.bitrateQLE.textChanged.connect(self.command_update_vidbitrate) self.threadsQLE.textChanged.connect(self.command_update_threads) self.beginQLE.textChanged.connect(self.command_update_begin_time) self.durationQLE.textChanged.connect(self.command_update_duration) self.embedQLE.textChanged.connect(self.command_update_subtitles) self.vidcodecQCB.currentIndexChanged.connect( self.command_update_vcodec) self.audcodecQCB.currentIndexChanged.connect( self.command_update_acodec) self.freqQCB.currentIndexChanged.connect(self.command_update_frequency) self.rotateQCB.currentIndexChanged.connect( self.command_update_rotation) self.audbitrateQCB.currentIndexChanged.connect( self.command_update_audbitrate) self.chan1QRB.clicked.connect( lambda: self.command_update_channels('1')) self.chan2QRB.clicked.connect( lambda: self.command_update_channels('2')) self.preserveaspectQChB.toggled.connect( self.command_update_preserve_aspect) self.preservesizeQChB.toggled.connect( self.command_update_preserve_size) def resize_parent(self): """Give MainWindow its default size.""" self.parent.setMinimumSize(self.parent.sizeHint()) self.parent.resize(self.parent.sizeHint()) def clear(self): """Clear all values of graphical widgets.""" lines = [ self.commandQLE, self.widthQLE, self.heightQLE, self.aspect1QLE, self.aspect2QLE, self.frameQLE, self.bitrateQLE, self.threadsQLE, self.beginQLE, self.embedQLE, self.durationQLE ] for i in lines: i.clear() self.vidcodecQCB.setCurrentIndex(0) self.audcodecQCB.setCurrentIndex(0) self.freqQCB.setCurrentIndex(0) self.audbitrateQCB.setCurrentIndex(0) self.rotateQCB.setCurrentIndex(0) self.preserveaspectQChB.setChecked(False) self.preservesizeQChB.setChecked(False) self.group.setExclusive(False) self.chan1QRB.setChecked(False) self.chan2QRB.setChecked(False) self.group.setExclusive(True) # setExclusive(False) in order to be able to uncheck checkboxes and # then setExclusive(True) so only one radio button can be set def fill_video_comboboxes(self, vcodecs, acodecs, extraformats): vcodecs = [i for i in vcodecs.split("\n")] if vcodecs else [] acodecs = [i for i in acodecs.split("\n")] if acodecs else [] extraformats = [i for i in extraformats.split("\n") ] if extraformats else [] self.vidcodecQCB.currentIndexChanged.disconnect() self.audcodecQCB.currentIndexChanged.disconnect() self.vidcodecQCB.clear() self.audcodecQCB.clear() self.extQCB.clear() self.vidcodecQCB.addItems([self.defaultStr, self.DisableStream] + vcodecs) self.audcodecQCB.addItems([self.defaultStr, self.DisableStream] + acodecs) self.extQCB.addItems(sorted(self.formats + extraformats)) self.vidcodecQCB.currentIndexChanged.connect( self.command_update_vcodec) self.audcodecQCB.currentIndexChanged.connect( self.command_update_acodec) def ok_to_continue(self): """ Check if everything is ok with audiovideotab to continue conversion. Check if: - Either ffmpeg or avconv are installed. Return True if all tests pass, else False. """ if self.parent.vidconverter is None: QMessageBox.warning( self, 'FF Multi Converter - ' + self.tr('Error!'), self. tr('Neither ffmpeg nor libav are installed.' '\nYou will not be able to convert audio/video files until you' ' install one of them.')) return False return True def open_subtitle_file(self): """ Get the filename using standard QtDialog and update embedQLE's text. """ fname = QFileDialog.getOpenFileName( self, 'FF Multi Converter - ' + self.tr('Choose File'), config.home, 'Subtitles (*.srt *.sub *.ssa *.ass)') if fname: self.embedQLE.setText(fname) def set_default_command(self): """Set the default value to self.commandQLE.""" self.clear() self.commandQLE.setText(self.parent.default_command) def choose_preset(self): """ Open the presets dialog and update self.commandQLE, and self.extQCB and with the appropriate values. """ dialog = presets_dlgs.ShowPresets(choose=True) if dialog.exec_() and dialog.the_command is not None: self.clear() self.commandQLE.setText(dialog.the_command) self.commandQLE.home(False) find = self.extQCB.findText(dialog.the_extension) if find >= 0: self.extQCB.setCurrentIndex(find) def command_update_size(self): command = self.commandQLE.text() text1 = self.widthQLE.text() text2 = self.heightQLE.text() if not (text1 == '-1' or text2 == '-1'): self.preserveaspectQChB.setChecked(False) if (text1 or text2) and not (text1 and text2) or (text1 == '-' or text2 == '-'): return regex = r'(\s+|^)-s(:v){0,1}\s+\d+x\d+(\s+|$)' if re.search(regex, command): command = re.sub(regex, '', command) regex = r'(,*\s*){0,1}(scale=-?\d+:-?\d+)(\s*,*\s*){0,1}' _filter = "scale={0}:{1}".format(text1, text2) if text1 and text2 else '' self.commandQLE.setText( utils.update_cmdline_text(command, _filter, regex, bool(text1 and text2), 0, 2)) def command_update_preserve_size(self): checked = self.preservesizeQChB.isChecked() self.widthQLE.setEnabled(not checked) self.heightQLE.setEnabled(not checked) if checked: self.widthQLE.clear() self.heightQLE.clear() # command_update_size() is triggered here command = self.commandQLE.text() regex = r'(\s+|^)-s\s+\d+x\d+(\s+|$)' command = re.sub(' +', ' ', re.sub(regex, ' ', command)).strip() self.commandQLE.setText(command) def command_update_aspect(self): command = self.commandQLE.text() text1 = self.aspect1QLE.text() text2 = self.aspect2QLE.text() if (text1 or text2) and not (text1 and text2): return regex = r'(\s+|^)-aspect\s+\d+:\d+(\s+|$)' s = ' -aspect {0}:{1} '.format(text1, text2) if text1 and text2 else ' ' if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_preserve_aspect(self): command = self.commandQLE.text() checked = self.preserveaspectQChB.isChecked() self.aspect1QLE.setEnabled(not checked) self.aspect2QLE.setEnabled(not checked) if checked: self.aspect1QLE.clear() self.aspect2QLE.clear() # self.command_update_aspect() is triggered here regex = r'(,*\s*){0,1}(scale=(-?\d+):(-?\d+))(\s*,*\s*){0,1}' search = re.search(regex, command) if search: width = search.groups()[2] height = search.groups()[3] if not (width == '-1' or height == '-1'): s = "scale=-1:{0}".format(height) command = re.sub(regex, r'\1{0}\5'.format(s), command) self.widthQLE.setText('-1') self.heightQLE.setText(height) regex = r'(\s+|^)-aspect\s+\d+:\d+(\s+|$)' command = re.sub(' +', ' ', re.sub(regex, ' ', command)).strip() self.commandQLE.setText(command) def command_update_frames(self): command = self.commandQLE.text() text = self.frameQLE.text() regex = r'(\s+|^)-r\s+\d+(\s+|$)' s = ' -r {0} '.format(text) if text else ' ' if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_vidbitrate(self): command = self.commandQLE.text() text = self.bitrateQLE.text() regex = r'(\s+|^)-b(:v){0,1}\s+\d+[kKmM](\s+|$)' s = ' -b:v {0}k '.format(text) if text else ' ' if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub('-sameq', '', command) command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_frequency(self): command = self.commandQLE.text() text = self.freqQCB.currentText() regex = r'(\s+|^)-ar\s+\d+(\s+|$)' s = ' -ar {0} '.format( text) if self.freqQCB.currentIndex() != 0 else ' ' if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_audbitrate(self): command = self.commandQLE.text() text = self.audbitrateQCB.currentText() regex = r'(\s+|^)-(ab|b:a)\s+\d+[kKmM](\s+|$)' if self.audbitrateQCB.currentIndex() != 0: s = ' -b:a {0}k '.format(text) else: s = ' ' if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_channels(self, channel): command = self.commandQLE.text() regex = r'(\s+|^)-ac\s+\d+(\s+|$)' s = ' -ac {0} '.format(channel) if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_threads(self): command = self.commandQLE.text() text = self.threadsQLE.text() regex = r'(\s+|^)-threads\s+\d+(\s+|$)' s = ' -threads {0} '.format(text) if text else ' ' if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_begin_time(self): command = self.commandQLE.text() text = self.beginQLE.text() regex = r'(\s+|^)-ss\s+\S+(\s+|$)' s = ' -ss {0} '.format(text) if text else ' ' if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_duration(self): command = self.commandQLE.text() text = self.durationQLE.text() regex = r'(\s+|^)-t\s+\S+(\s+|$)' s = ' -t {0} '.format(text) if text else ' ' if re.search(regex, command): command = re.sub(regex, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_vcodec(self): command = self.commandQLE.text() text = self.vidcodecQCB.currentText() regex = r'(\s+|^)-(vcodec|c:v)\s+\S+(\s+|$)' regex_vn = r'(\s+|^)-vn(\s+|$)' if self.vidcodecQCB.currentIndex() == 1: s = ' -vn '.format(text) elif self.vidcodecQCB.currentIndex() == 0: s = ' ' else: s = ' -vcodec {0} '.format(text) if re.search(regex, command): command = re.sub(regex, s, command) elif re.search(regex_vn, command): command = re.sub(regex_vn, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_acodec(self): command = self.commandQLE.text() text = self.audcodecQCB.currentText() regex = r'(\s+|^)-(acodec|c:a)\s+\S+(\s+|$)' regex_an = r'(\s+|^)-an(\s+|$)' if self.audcodecQCB.currentIndex() == 1: s = ' -an '.format(text) elif self.audcodecQCB.currentIndex() == 0: s = ' ' else: s = ' -acodec {0} '.format(text) if re.search(regex, command): command = re.sub(regex, s, command) elif re.search(regex_an, command): command = re.sub(regex_an, s, command) else: command += s command = re.sub(' +', ' ', command).strip() self.commandQLE.setText(command) def command_update_subtitles(self): command = self.commandQLE.text() regex = r'(,*\s*){0,1}(subtitles=\'.*\')(\s*,*\s*){0,1}' text = self.embedQLE.text() _filter = "subtitles='{0}'".format(text) if text else '' self.commandQLE.setText( utils.update_cmdline_text(command, _filter, regex, bool(text), 0, 2)) def command_update_rotation(self): command = self.commandQLE.text() regex = r'(,*\s*){0,1}(transpose=\d(,\s*transpose=\d)*|vflip|hflip)(\s*,*\s*){0,1}' rotate = self.rotateQCB.currentIndex() if rotate == 0: # none _filter = '' elif rotate == 1: # 90 clockwise _filter = 'transpose=1' elif rotate == 2: # 90 clockwise + vertical flip _filter = 'transpose=3' elif rotate == 3: # 90 counter clockwise _filter = 'transpose=2' elif rotate == 4: # 90 counter clockwise + vertical flip _filter = 'transpose=0' elif rotate == 5: # 180 _filter = 'transpose=2,transpose=2' elif rotate == 6: # horizontal flip _filter = 'hflip' elif rotate == 7: # vertical flip _filter = 'vflip' self.commandQLE.setText( utils.update_cmdline_text(command, _filter, regex, bool(rotate != 0), 0, 3))
class ShowSettingsDialog(QDialog): def __init__(self, iface, memoryPointsLayer, memoryLinesLayer, configTable): """ Constructor :param iface: interface :param memoryPointsLayer: working memory points layer :param memoryLinesLayer: working memory lines layer :param configTable: config table selected for import """ QDialog.__init__(self) self.__iface = iface self.__memoryPointsLayer = memoryPointsLayer self.__memoryLinesLayer = memoryLinesLayer self.__configTable = configTable self.setWindowTitle(QCoreApplication.translate("VDLTools", "Settings")) self.__pointsLayers = [] self.__linesLayers = [] self.__tables = [] # dataSource = QgsDataSourceURI(self.__layer.source()) # db = DBConnector.setConnection(dataSource.database(), self.__iface) # if db: # query = db.exec_("""SELECT table_name FROM information_schema.tables WHERE table_schema NOT IN # ('pg_catalog', 'information_schema', 'topology') AND table_type = 'BASE TABLE' AND table_name NOT IN # (SELECT f_table_name FROM geometry_columns)""") # while query.next(): # self.__tables.append(query.value(0)) # db.close() for layer in self.__iface.mapCanvas().layers(): if layer is not None \ and layer.type() == QgsMapLayer.VectorLayer \ and layer.providerType() == "memory": if layer.geometryType() == QGis.Point: self.__pointsLayers.append(layer) if layer.geometryType() == QGis.Line: self.__linesLayers.append(layer) self.resize(400, 200) self.__layout = QGridLayout() pointLabel = QLabel( QCoreApplication.translate("VDLTools", "Working points layer : ")) pointLabel.setMinimumHeight(20) pointLabel.setMinimumWidth(50) self.__layout.addWidget(pointLabel, 0, 1) self.__pointCombo = QComboBox() self.__pointCombo.setMinimumHeight(20) self.__pointCombo.setMinimumWidth(50) self.__pointCombo.addItem("") for layer in self.__pointsLayers: self.__pointCombo.addItem(layer.name()) self.__layout.addWidget(self.__pointCombo, 0, 2) self.__pointCombo.currentIndexChanged.connect(self.__pointComboChanged) if self.__memoryPointsLayer is not None: if self.__memoryPointsLayer in self.__pointsLayers: self.__pointCombo.setCurrentIndex( self.__pointsLayers.index(self.__memoryPointsLayer) + 1) lineLabel = QLabel( QCoreApplication.translate("VDLTools", "Working lines layer : ")) lineLabel.setMinimumHeight(20) lineLabel.setMinimumWidth(50) self.__layout.addWidget(lineLabel, 1, 1) self.__lineCombo = QComboBox() self.__lineCombo.setMinimumHeight(20) self.__lineCombo.setMinimumWidth(50) self.__lineCombo.addItem("") for layer in self.__linesLayers: self.__lineCombo.addItem(layer.name()) self.__layout.addWidget(self.__lineCombo, 1, 2) self.__lineCombo.currentIndexChanged.connect(self.__lineComboChanged) if self.__memoryLinesLayer is not None: if self.__memoryLinesLayer in self.__linesLayers: self.__lineCombo.setCurrentIndex( self.__linesLayers.index(self.__memoryLinesLayer) + 1) tableLabel = QLabel( QCoreApplication.translate("VDLTools", "Config table : ")) tableLabel.setMinimumHeight(20) tableLabel.setMinimumWidth(50) self.__layout.addWidget(tableLabel, 2, 1) self.__tableCombo = QComboBox() self.__tableCombo.setMinimumHeight(20) self.__tableCombo.setMinimumWidth(50) self.__tableCombo.addItem("") for table in self.__tables: self.__tableCombo.addItem(table) self.__layout.addWidget(self.__tableCombo, 2, 2) self.__tableCombo.currentIndexChanged.connect(self.__tableComboChanged) if self.__configTable is not None: if self.__configTable in self.__tables: self.__tableCombo.setCurrentIndex( self.__tables.index(self.__configTable) + 1) self.__okButton = QPushButton( QCoreApplication.translate("VDLTools", "OK")) self.__okButton.setMinimumHeight(20) self.__okButton.setMinimumWidth(100) self.__cancelButton = QPushButton( QCoreApplication.translate("VDLTools", "Cancel")) self.__cancelButton.setMinimumHeight(20) self.__cancelButton.setMinimumWidth(100) self.__layout.addWidget(self.__okButton, 100, 1) self.__layout.addWidget(self.__cancelButton, 100, 2) self.setLayout(self.__layout) def __lineComboChanged(self): """ To remove blank item when another one is selected """ if self.__lineCombo.itemText(0) == "": self.__lineCombo.removeItem(0) def __pointComboChanged(self): """ To remove blank item when another one is selected """ if self.__pointCombo.itemText(0) == "": self.__pointCombo.removeItem(0) def __tableComboChanged(self): """ To remove blank item when another one is selected """ if self.__tableCombo.itemText(0) == "": self.__tableCombo.removeItem(0) def okButton(self): """ To get the ok button instance :return: ok button instance """ return self.__okButton def cancelButton(self): """ To get the cancel button instance :return: cancel button instance """ return self.__cancelButton def pointsLayer(self): """ To get the selected memory points layer :return: selected memeory points layer, or none """ index = self.__pointCombo.currentIndex() if self.__pointCombo.itemText(index) == "": return None else: return self.__pointsLayers[index] def linesLayer(self): """ To get the selected memory lines layer :return: selected memory lines layer, or none """ index = self.__lineCombo.currentIndex() if self.__lineCombo.itemText(index) == "": return None else: return self.__linesLayers[index] def configTable(self): """ To get the selected config table :return: selected config table, or none """ index = self.__tableCombo.currentIndex() if self.__tableCombo.itemText(index) == "": return None else: return self.__tables[index]
class FilteringModule(PreprocessorModule): DEFAULT_SETTINGS = { 'is_enabled': True, 'methods': [True, False, False], 'recent_sw_files': [], 'min_df': None, 'max_df': None, } English, Custom, DocumentFrequency = 0, 1, 2 filtering_values = { English: 'english', Custom: [], DocumentFrequency: (None, None), } filter_names = { English: 'English stop words', Custom: 'Custom stop words', DocumentFrequency: 'Filter by token frequency', } filtering_methods = [True, False, False] dlgFormats = 'Only text files (*.txt)' recent_sw_files = [] def __init__(self, data): data = data or self.DEFAULT_SETTINGS PreprocessorModule.__init__(self, 'Token filtering', True, data.get('is_enabled')) self.group = QButtonGroup(self, exclusive=False) # --- English --- cb = QCheckBox(self, text=self.filter_names[self.English]) self.add_to_content_area(cb) self.group.addButton(cb, self.English) # --- Custom --- cb = QCheckBox(self, text=self.filter_names[self.Custom]) self.add_to_content_area(cb) self.group.addButton(cb, self.Custom) # File browser. file_browser_layout = QHBoxLayout() file_browser_layout.setContentsMargins(20, 0, 0, 0) self.sw_file_combo = QComboBox() self.sw_file_combo.setMinimumWidth(200) file_browser_layout.addWidget(self.sw_file_combo) self.sw_file_combo.activated[int].connect(self.select_file) self.browse_button = QPushButton(self) self.browse_button.clicked.connect(self.browse_file) self.browse_button.setIcon(self.style().standardIcon( QStyle.SP_DirOpenIcon)) self.browse_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) file_browser_layout.addWidget(self.browse_button) # Reload button self.reload_button = QPushButton(self) self.reload_button.clicked.connect(self.on_reload_button_clicked) self.reload_button.setIcon(self.style().standardIcon( QStyle.SP_BrowserReload)) self.reload_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) file_browser_layout.addWidget(self.reload_button) self.add_layout_to_content_area(file_browser_layout) # --- DF --- df_info_text = """ Remove all tokens that appear in less than 'min-df' documents. Remove all tokens that appear in more than 'max-df' documents. Values can be either integers or floats (ratio of documents). """ cb = QCheckBox(self, text=self.filter_names[self.DocumentFrequency]) self.add_to_content_area(cb) self.group.addButton(cb, self.DocumentFrequency) df_info_text = QLabel(df_info_text) df_info_text.setContentsMargins(0, 0, 0, 0) df_info_text.setStyleSheet(""" font-size: 11px; font-style: italic; """) self.add_to_content_area(df_info_text) # Min/Max-Df setter. df_setter_layout = QHBoxLayout() df_setter_layout.setContentsMargins(20, 0, 0, 0) self.min_df_input = QLineEdit() self.min_df_input.textChanged.connect(self.update_df_parameters) self.max_df_input = QLineEdit() self.max_df_input.textChanged.connect(self.update_df_parameters) df_setter_layout.addWidget(QLabel('Min-df:')) df_setter_layout.addWidget(self.min_df_input) df_setter_layout.addWidget(QLabel('Max-df:')) df_setter_layout.addWidget(self.max_df_input) self.add_layout_to_content_area(df_setter_layout) self.group.buttonClicked.connect(self.group_button_clicked) # Restore the widget to its previous state. self.restore_data(data) def str_to_num(self, s): if not s: return None try: return int(s) except ValueError: pass # Not an int. Continue. try: return float(s) except ValueError: # Not a float either. self.send_message( 'Input "{}" cannot be cast into a number.'.format(s)) return None def send_message(self, message): # Sends a message with the "message" signal, to the main widget. self.error_signal.emit(message) # --- File selection. def select_file(self, n): if n < len(self.recent_sw_files): name = self.recent_sw_files[n] del self.recent_sw_files[n] self.recent_sw_files.insert(0, name) if len(self.recent_sw_files) > 0: self.set_file_list() self.open_file(self.recent_sw_files[0]) def set_file_list(self): self.sw_file_combo.clear() if not self.recent_sw_files: self.sw_file_combo.addItem('(none)') else: for file in self.recent_sw_files: self.sw_file_combo.addItem(os.path.split(file)[1]) def browse_file(self): # Opens the file browser, starting at the home directory. start_file = os.path.expanduser('~/') # Get the file path from the browser window. path = QFileDialog.getOpenFileName(self, 'Open a stop words source', start_file, self.dlgFormats) if not path: return if path in self.recent_sw_files: self.recent_sw_files.remove(path) self.recent_sw_files.insert(0, path) self.set_file_list() self.open_file(path) def update_df_parameters(self): min_df = None if not self.min_df_input.text( ) else self.min_df_input.text() max_df = None if not self.max_df_input.text( ) else self.max_df_input.text() self.filtering_values[self.DocumentFrequency] = (min_df, max_df) self.notify_on_change() def open_file(self, path): try: with open(path) as f: # Read most recent. self.filtering_values[self.Custom] = [ sw.strip() for sw in f.read().splitlines() ] self.notify_on_change() except Exception: # Raise an exception otherwise. self.send_message('Could not open "{}".'.format(path)) def on_reload_button_clicked(self): if self.recent_sw_files: self.select_file(0) # END File selection. def group_button_clicked(self): self.filtering_methods = [ ch_box.isChecked() for ch_box in self.group.buttons() ] self.enable_choice_settings() # Emit the signal. self.notify_on_change() def enable_choice_settings(self): self.sw_file_combo.setEnabled(self.filtering_methods[1]) self.browse_button.setEnabled(self.filtering_methods[1]) self.reload_button.setEnabled(self.filtering_methods[1]) self.min_df_input.setEnabled(self.filtering_methods[2]) self.max_df_input.setEnabled(self.filtering_methods[2]) def get_pp_setting(self): flag_english = self.filtering_methods[0] flag_custom = self.filtering_methods[1] flag_df = self.filtering_methods[2] if flag_english and flag_custom: # Use custom. stop_words = { 'stop_words': stopwords.words('english') + self.filtering_values[self.Custom] } elif flag_english and not flag_custom: stop_words = {'stop_words': 'english'} elif flag_custom: stop_words = {'stop_words': self.filtering_values[self.Custom]} else: stop_words = {} if flag_df: stop_words.update({ 'min_df': self.str_to_num(self.min_df_input.text()), 'max_df': self.str_to_num(self.max_df_input.text()), }) return stop_words def restore_data(self, data): self.recent_sw_files = data.get('recent_sw_files') self.min_df_input.setText(data.get('min_df')) self.max_df_input.setText(data.get('max_df')) self.filtering_methods = data.get('methods') for flag, ch_box in zip(self.filtering_methods, self.group.buttons()): ch_box.setChecked(flag) self.enable_choice_settings() # Enable the settings if set. self.set_file_list() # Fill the combo box with the recent sw files. self.select_file(0) # Select the first file. def export_data(self): return { 'is_enabled': self.enabled, 'methods': self.filtering_methods, 'recent_sw_files': self.recent_sw_files, 'min_df': self.min_df_input.text(), 'max_df': self.max_df_input.text(), }
class ShowSettingsDialog(QDialog): """ Dialog class for plugin settings """ def __init__(self, iface, memoryPointsLayer, memoryLinesLayer, ctllDb, configTable, uriDb, schemaDb, mntUrl, refLayers, adjLayers, levelAtt, levelVal, drawdowmLayer, pipeDiam, moreTools): """ Constructor :param iface: interface :param memoryPointsLayer: working memory points layer :param memoryLinesLayer: working memory lines layer :param configTable: config table selected for import """ QDialog.__init__(self) self.__iface = iface self.__memoryPointsLayer = memoryPointsLayer self.__memoryLinesLayer = memoryLinesLayer self.__ctlDb = ctllDb self.__configTable = configTable self.__uriDb = uriDb self.__schemaDb = schemaDb self.__mntUrl = mntUrl self.__refLayers = refLayers self.__adjLayers = adjLayers self.__levelAtt = levelAtt self.__levelVal = levelVal self.__drawdowmLayer = drawdowmLayer self.__pipeDiam = pipeDiam self.setWindowTitle(QCoreApplication.translate("VDLTools", "Settings")) self.__pointsLayers = [] self.__linesLayers = [] self.__refAvailableLayers = [] self.__drawdownLayers = [] self.__tables = [] self.__schemas = [] self.__pipeDiamFields = [] self.__levelAttFields = [] self.__dbs = DBConnector.getUsedDatabases() self.__refLabels = [] self.__refChecks = [] self.__adjChecks = [] for layer in list(QgsMapLayerRegistry.instance().mapLayers().values()): if layer is not None and layer.type() == QgsMapLayer.VectorLayer: if layer.providerType() == "memory": if layer.geometryType() == QGis.Point: self.__pointsLayers.append(layer) if layer.geometryType() == QGis.Line: self.__linesLayers.append(layer) if QGis.fromOldWkbType(layer.wkbType()) == QgsWKBTypes.LineStringZ: self.__drawdownLayers.append(layer) if QGis.fromOldWkbType(layer.wkbType()) == QgsWKBTypes.PointZ: self.__refAvailableLayers.append(layer) # self.resize(450, 400) self.__layout = QGridLayout() line = 0 intersectLabel = QLabel(QCoreApplication.translate("VDLTools", "Intersect ")) self.__layout.addWidget(intersectLabel, line, 0) line += 1 pointLabel = QLabel(QCoreApplication.translate("VDLTools", "Working points layer : ")) self.__layout.addWidget(pointLabel, line, 1) self.__pointCombo = QComboBox() self.__pointCombo.setMinimumHeight(20) self.__pointCombo.setMinimumWidth(50) self.__pointCombo.addItem("") for layer in self.__pointsLayers: self.__pointCombo.addItem(layer.name()) self.__layout.addWidget(self.__pointCombo, line, 2) self.__pointCombo.currentIndexChanged.connect(self.__pointComboChanged) if self.__memoryPointsLayer is not None: if self.__memoryPointsLayer in self.__pointsLayers: self.__pointCombo.setCurrentIndex(self.__pointsLayers.index(self.__memoryPointsLayer)+1) line += 1 lineLabel = QLabel(QCoreApplication.translate("VDLTools", "Working lines layer : ")) self.__layout.addWidget(lineLabel, line, 1) self.__lineCombo = QComboBox() self.__lineCombo.setMinimumHeight(20) self.__lineCombo.setMinimumWidth(50) self.__lineCombo.addItem("") for layer in self.__linesLayers: self.__lineCombo.addItem(layer.name()) self.__layout.addWidget(self.__lineCombo, line, 2) self.__lineCombo.currentIndexChanged.connect(self.__lineComboChanged) if self.__memoryLinesLayer is not None: if self.__memoryLinesLayer in self.__linesLayers: self.__lineCombo.setCurrentIndex(self.__linesLayers.index(self.__memoryLinesLayer)+1) line += 1 profilesLabel = QLabel(QCoreApplication.translate("VDLTools", "Profiles ")) self.__layout.addWidget(profilesLabel, line, 0) line += 1 mntLabel = QLabel(QCoreApplication.translate("VDLTools", "Url for MNT : ")) self.__layout.addWidget(mntLabel, line, 1) self.__mntText = QLineEdit() if self.__mntUrl is None or self.__mntUrl == "None": self.__mntText.insert('https://map.lausanne.ch/prod/wsgi/profile.json') else: self.__mntText.insert(self.__mntUrl) self.__mntText.setMinimumHeight(20) self.__mntText.setMinimumWidth(100) self.__layout.addWidget(self.__mntText, line, 2) line += 1 ddLabel = QLabel(QCoreApplication.translate("VDLTools", "Drawdown ")) self.__layout.addWidget(ddLabel, line, 0) line += 1 self.__layout.addWidget(QLabel(QCoreApplication.translate("VDLTools", "Layer")), line, 1) namesLayout = QHBoxLayout() namesWidget = QWidget() namesLayout.addWidget(QLabel(QCoreApplication.translate("VDLTools", "Reference"))) namesLayout.addWidget(QLabel(QCoreApplication.translate("VDLTools", "Adjustable"))) namesLayout.setContentsMargins(0,0,0,0) namesWidget.setLayout(namesLayout) self.__layout.addWidget(namesWidget, line, 2) line += 1 for layer in self.__refAvailableLayers: refLabel = QLabel(" - " + layer.name()) self.__refLabels.append(refLabel) self.__layout.addWidget(refLabel, line, 1) checksLayout = QHBoxLayout() checksLayout.setContentsMargins(0,0,0,0) checksWidget = QWidget() refCheck = QCheckBox() self.__refChecks.append(refCheck) refCheck.stateChanged.connect(self.__refBoxesChanged) checksLayout.addWidget(refCheck) adjCheck = QCheckBox() self.__adjChecks.append(adjCheck) checksLayout.addWidget(adjCheck) checksWidget.setLayout(checksLayout) self.__layout.addWidget(checksWidget, line, 2) line += 1 levelAttLabel = QLabel(QCoreApplication.translate("VDLTools", "Code(s) on pipe : ")) self.__layout.addWidget(levelAttLabel, line, 1) self.__levelAttCombo = QComboBox() self.__levelAttCombo.setMinimumHeight(20) self.__levelAttCombo.setMinimumWidth(50) self.__levelAttCombo.addItem("") self.__layout.addWidget(self.__levelAttCombo, line, 2) self.__levelAttCombo.currentIndexChanged.connect(self.__levelAttComboChanged) i = 0 for layer in self.__refAvailableLayers: if layer in self.__refLayers: self.__refChecks[i].setChecked(True) if layer in self.__adjLayers: self.__adjChecks[i].setChecked(True) i += 1 line += 1 levelValLabel = QLabel(QCoreApplication.translate("VDLTools", "Point code attribute : ")) self.__layout.addWidget(levelValLabel, line, 1) self.__levelValText = QLineEdit() if self.__levelVal is not None and self.__levelVal != "None": self.__levelValText.insert(self.__levelVal) self.__levelValText.setMinimumHeight(20) self.__levelValText.setMinimumWidth(100) self.__layout.addWidget(self.__levelValText, line, 2) line += 1 drawdownLabel = QLabel(QCoreApplication.translate("VDLTools", "drawdown layer : ")) self.__layout.addWidget(drawdownLabel, line, 1) self.__drawdownCombo = QComboBox() self.__drawdownCombo.setMinimumHeight(20) self.__drawdownCombo.setMinimumWidth(50) self.__drawdownCombo.addItem("") for layer in self.__drawdownLayers: self.__drawdownCombo.addItem(layer.name()) self.__layout.addWidget(self.__drawdownCombo, line, 2) line += 1 pipeDiamLabel = QLabel(QCoreApplication.translate("VDLTools", "Pipe diameter attribute [cm] : ")) self.__layout.addWidget(pipeDiamLabel, line, 1) self.__pipeDiamCombo = QComboBox() self.__pipeDiamCombo.setMinimumHeight(20) self.__pipeDiamCombo.setMinimumWidth(50) self.__pipeDiamCombo.addItem("") self.__layout.addWidget(self.__pipeDiamCombo, line, 2) self.__drawdownCombo.currentIndexChanged.connect(self.__drawdownComboChanged) self.__pipeDiamCombo.currentIndexChanged.connect(self.__pipeDiamComboChanged) if self.__drawdowmLayer is not None: if self.__drawdowmLayer in self.__drawdownLayers: self.__drawdownCombo.setCurrentIndex(self.__drawdownLayers.index(self.__drawdowmLayer)+1) if moreTools: line += 1 importLabel = QLabel(QCoreApplication.translate("VDLTools", "Import ")) self.__layout.addWidget(importLabel, line, 0) line += 1 dbLabel = QLabel(QCoreApplication.translate("VDLTools", "Import database : ")) self.__layout.addWidget(dbLabel, line, 1) self.__dbCombo = QComboBox() self.__dbCombo.setMinimumHeight(20) self.__dbCombo.setMinimumWidth(50) self.__dbCombo.addItem("") for db in list(self.__dbs.keys()): self.__dbCombo.addItem(db) self.__layout.addWidget(self.__dbCombo, line, 2) line += 1 schemaLabel = QLabel(QCoreApplication.translate("VDLTools", "Database schema : ")) self.__layout.addWidget(schemaLabel, line, 1) self.__schemaCombo = QComboBox() self.__schemaCombo.setMinimumHeight(20) self.__schemaCombo.setMinimumWidth(50) self.__schemaCombo.addItem("") self.__layout.addWidget(self.__schemaCombo, line, 2) line += 1 tableLabel = QLabel(QCoreApplication.translate("VDLTools", "Config table : ")) self.__layout.addWidget(tableLabel, line, 1) self.__tableCombo = QComboBox() self.__tableCombo.setMinimumHeight(20) self.__tableCombo.setMinimumWidth(50) self.__tableCombo.addItem("") self.__layout.addWidget(self.__tableCombo, line, 2) line += 1 controlLabel = QLabel(QCoreApplication.translate("VDLTools", "Control ")) self.__layout.addWidget(controlLabel, line, 0) line += 1 ctlLabel = QLabel(QCoreApplication.translate("VDLTools", "Control database : ")) self.__layout.addWidget(ctlLabel, line, 1) self.__ctlCombo = QComboBox() self.__ctlCombo.setMinimumHeight(20) self.__ctlCombo.setMinimumWidth(50) self.__ctlCombo.addItem("") for db in list(self.__dbs.keys()): self.__ctlCombo.addItem(db) self.__layout.addWidget(self.__ctlCombo, line, 2) self.__dbCombo.currentIndexChanged.connect(self.__dbComboChanged) self.__schemaCombo.currentIndexChanged.connect(self.__schemaComboChanged) self.__tableCombo.currentIndexChanged.connect(self.__tableComboChanged) self.__ctlCombo.currentIndexChanged.connect(self.__ctlComboChanged) if self.__uriDb is not None: if self.__uriDb.database() in list(self.__dbs.keys()): self.__dbCombo.setCurrentIndex(list(self.__dbs.keys()).index(self.__uriDb.database()) + 1) if self.__ctlDb is not None: if self.__ctlDb.database() in list(self.__dbs.keys()): self.__ctlCombo.setCurrentIndex(list(self.__dbs.keys()).index(self.__ctlDb.database()) + 1) else: self.__dbCombo = None self.__schemaCombo = None self.__tableCombo = None self.__ctlCombo = None self.__okButton = QPushButton(QCoreApplication.translate("VDLTools", "OK")) self.__okButton.setMinimumHeight(20) self.__okButton.setMinimumWidth(100) self.__cancelButton = QPushButton(QCoreApplication.translate("VDLTools", "Cancel")) self.__cancelButton.setMinimumHeight(20) self.__cancelButton.setMinimumWidth(100) self.__layout.addWidget(self.__okButton, 100, 1) self.__layout.addWidget(self.__cancelButton, 100, 2) self.setLayout(self.__layout) @staticmethod def __resetCombo(combo): """ To reset a combo list :param combo: concerned combo """ while combo.count() > 0: combo.removeItem(combo.count()-1) def __setSchemaCombo(self, uriDb): """ To fill the schema combo list :param uriDb: selected database uri """ connector = DBConnector(uriDb, self.__iface) db = connector.setConnection() if db: Signal.safelyDisconnect(self.__schemaCombo.currentIndexChanged, self.__schemaComboChanged) self.__resetCombo(self.__schemaCombo) self.__schemaCombo.addItem("") self.__schemas = [] query = db.exec_("""SELECT DISTINCT table_schema FROM information_schema.tables WHERE table_schema NOT IN ('pg_catalog', 'information_schema', 'topology') AND table_type = 'BASE TABLE' AND table_name NOT IN (SELECT f_table_name FROM geometry_columns)""") if query.lastError().isValid(): self.__iface.messageBar().pushMessage(query.lastError().text(), level=QgsMessageBar.CRITICAL, duration=0) else: while next(query): self.__schemas.append(query.value(0)) db.close() for schema in self.__schemas: self.__schemaCombo.addItem(schema) self.__schemaCombo.currentIndexChanged.connect(self.__schemaComboChanged) if self.__schemaDb is not None: if self.__schemaDb in self.__schemas: self.__schemaCombo.setCurrentIndex(self.__schemas.index(self.__schemaDb) + 1) def __setTableCombo(self, uriDb, schema): """ To fill the table combo list :param uriDb: selected database uri :param schema: selected database schema """ connector = DBConnector(uriDb, self.__iface) db = connector.setConnection() if db: Signal.safelyDisconnect(self.__tableCombo.currentIndexChanged, self.__tableComboChanged) self.__resetCombo(self.__tableCombo) self.__tableCombo.addItem("") self.__tables = [] query = db.exec_("""SELECT table_name FROM information_schema.tables WHERE table_schema = '""" + schema + """' ORDER BY table_name""") if query.lastError().isValid(): self.__iface.messageBar().pushMessage(query.lastError().text(), level=QgsMessageBar.CRITICAL, duration=0) else: while next(query): self.__tables.append(query.value(0)) db.close() for table in self.__tables: if self.__tableCombo.findText(table) == -1: self.__tableCombo.addItem(table) self.__tableCombo.currentIndexChanged.connect(self.__tableComboChanged) if self.__configTable is not None: if self.__configTable in self.__tables: self.__tableCombo.setCurrentIndex(self.__tables.index(self.__configTable) + 1) def __setPipeDiamCombo(self, drawdownLayer): """ To fill the pipe diameter combo list :param drawdownLayer: choosen drawdown layer """ Signal.safelyDisconnect(self.__pipeDiamCombo.currentIndexChanged, self.__pipeDiamComboChanged) self.__resetCombo(self.__pipeDiamCombo) self.__pipeDiamCombo.addItem("") fields = drawdownLayer.fields() self.__pipeDiamFields = [] for field in fields: self.__pipeDiamFields.append(field.name()) self.__pipeDiamCombo.addItem(field.name()) self.__pipeDiamCombo.currentIndexChanged.connect(self.__pipeDiamComboChanged) if self.__pipeDiam is not None: if self.__pipeDiam in self.__pipeDiamFields: self.__pipeDiamCombo.setCurrentIndex(self.__pipeDiamFields.index(self.__pipeDiam) + 1) def __setLevelAttCombo(self, refLayers): """ To fill the level attribute combo list :param refLayers: choosen reference layers """ Signal.safelyDisconnect(self.__levelAttCombo.currentIndexChanged, self.__levelAttComboChanged) self.__resetCombo(self.__levelAttCombo) self.__levelAttCombo.addItem("") self.__levelAttFields = [] num = 0 for layer in refLayers: fields = layer.fields() if num == 0: for field in fields: self.__levelAttFields.append(field.name()) num = 1 else: names = [] for field in fields: names.append(field.name()) news = [] for name in self.__levelAttFields: if name in names: news.append(name) self.__levelAttFields = news for name in self.__levelAttFields: self.__levelAttCombo.addItem(name) self.__levelAttCombo.currentIndexChanged.connect(self.__levelAttComboChanged) if self.__levelAtt is not None: if self.__levelAtt in self.__levelAttFields: self.__levelAttCombo.setCurrentIndex(self.__levelAttFields.index(self.__levelAtt) + 1) def __lineComboChanged(self): """ To remove blank item when another one is selected """ if self.__lineCombo.itemText(0) == "": self.__lineCombo.removeItem(0) def __pointComboChanged(self): """ To remove blank item when another one is selected """ if self.__pointCombo.itemText(0) == "": self.__pointCombo.removeItem(0) def __refBoxesChanged(self): """ To update level attribute combo when reference layers have changed """ if self.refLayers() is not None: self.__setLevelAttCombo(self.refLayers()) def __drawdownComboChanged(self): """ To remove blank item when another one is selected and update pipe diamete combo when drawdown layer has changed """ if self.__drawdownCombo.itemText(0) == "": self.__drawdownCombo.removeItem(0) if self.drawdownLayer() is not None: self.__setPipeDiamCombo(self.drawdownLayer()) def __tableComboChanged(self): """ To remove blank item when another one is selected """ if self.__tableCombo.itemText(0) == "": self.__tableCombo.removeItem(0) def __dbComboChanged(self): """ When the selection in db combo has changed """ if self.__dbCombo.itemText(0) == "": self.__dbCombo.removeItem(0) if self.uriDb() is not None: self.__setSchemaCombo(self.uriDb()) def __schemaComboChanged(self): """ When the selection in schema combo has changed """ if self.__schemaCombo.itemText(0) == "": self.__schemaCombo.removeItem(0) if self.schemaDb() is not None: self.__setTableCombo(self.uriDb(), self.schemaDb()) def __pipeDiamComboChanged(self): """ When the selection in schema combo has changed """ if self.__pipeDiamCombo.itemText(0) == "": self.__pipeDiamCombo.removeItem(0) def __levelAttComboChanged(self): """ When the selection in schema combo has changed """ if self.__levelAttCombo.itemText(0) == "": self.__levelAttCombo.removeItem(0) def __ctlComboChanged(self): """ When the selection in ctl combo has changed """ if self.__ctlCombo.itemText(0) == "": self.__ctlCombo.removeItem(0) def okButton(self): """ To get the ok button instance :return: ok button instance """ return self.__okButton def cancelButton(self): """ To get the cancel button instance :return: cancel button instance """ return self.__cancelButton def pointsLayer(self): """ To get the selected memory points layer :return: selected memory points layer, or none """ index = self.__pointCombo.currentIndex() if self.__pointCombo.itemText(index) == "": return None else: return self.__pointsLayers[index] def linesLayer(self): """ To get the selected memory lines layer :return: selected memory lines layer, or none """ index = self.__lineCombo.currentIndex() if self.__lineCombo.itemText(index) == "": return None else: return self.__linesLayers[index] def refLayers(self): """ To get the selected reference layers :return: selected reference layers, or none """ layers = [] i = 0 for check in self.__refChecks: if check.isChecked(): layers.append(self.__refAvailableLayers[i]) i += 1 return layers def adjLayers(self): """ To get the selected ajustable layers :return: selected adjustable layers, or none """ layers = [] i = 0 for check in self.__adjChecks: if check.isChecked(): layers.append(self.__refAvailableLayers[i]) i += 1 return layers def levelAtt(self): """ To get the selected level attribute :return: selected level attribute, or none """ if self.__levelAttCombo is None: return None index = self.__levelAttCombo.currentIndex() if self.__levelAttCombo.itemText(index) == "": return None else: return self.__levelAttFields[index] def levelVal(self): """ To get the filled level value :return: filled level value """ return self.__levelValText.text() def drawdownLayer(self): """ To get the selected drawdown layer :return: selected drawdown layer, or none """ index = self.__drawdownCombo.currentIndex() if self.__drawdownCombo.itemText(index) == "": return None else: return self.__drawdownLayers[index] def pipeDiam(self): """ To get the selected pipe diameter :return: selected pipe diameter, or none """ if self.__pipeDiamCombo is None: return None index = self.__pipeDiamCombo.currentIndex() if self.__pipeDiamCombo.itemText(index) == "": return None else: return self.__pipeDiamFields[index] def configTable(self): """ To get the selected config table :return: selected config table, or none """ if self.__tableCombo is None: return None index = self.__tableCombo.currentIndex() if self.__tableCombo.itemText(index) == "": return None else: return self.__tables[index] def uriDb(self): """ To get selected import database uri :return: import database uri """ if self.__dbCombo is None: return None index = self.__dbCombo.currentIndex() if self.__dbCombo.itemText(index) == "": return None else: return self.__dbs[list(self.__dbs.keys())[index]] def schemaDb(self): """ To get selected import database schema :return: import database schema """ if self.__schemaCombo is None: return None index = self.__schemaCombo.currentIndex() if self.__schemaCombo.itemText(index) == "": return None else: return self.__schemas[index] def mntUrl(self): """ To get selected MN url :return: MN url """ return self.__mntText.text() def ctlDb(self): """ To get selected control database uri :return: control database uri """ if self.__ctlCombo is None: return None index = self.__ctlCombo.currentIndex() if self.__ctlCombo.itemText(index) == "": return None else: return self.__dbs[list(self.__dbs.keys())[index]]
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 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 Ui_dev_client(object): def setupUi(self, dev_client): dev_client.resize(935, 660) dev_client.setWindowTitle(QApplication.translate("dev_client", "DevClient")) self.centralwidget = QWidget(dev_client) dev_client.setCentralWidget(self.centralwidget) main_layout = QGridLayout(self.centralwidget) main_layout.setContentsMargins(5, 5, 5, 3) main_layout.setSpacing(3) main_layout.setColumnStretch(0, 1) main_layout.setRowStretch(1, 1) top_layout = QHBoxLayout() top_layout.setContentsMargins(0, 0, 0, 0) top_layout.setSpacing(5) top_label_conn = QLabel() top_label_conn.setText(QApplication.translate("dev_client", "Connection")) top_layout.addWidget(top_label_conn) self.list_conn = QComboBox() self.list_conn.setFixedSize(145, 26) self.list_conn.setFocusPolicy(Qt.NoFocus) top_layout.addWidget(self.list_conn) self.list_account = QComboBox() self.list_account.setFixedSize(145, 26) self.list_account.setFocusPolicy(Qt.NoFocus) top_layout.addWidget(self.list_account) top_layout.addItem(QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)) top_label_account = QLabel() top_label_account.setText(QApplication.translate("dev_client", "Account")) top_layout.addWidget(top_label_account) self.button_connect = QPushButton() self.button_connect.setFixedSize(105, 26) self.button_connect.setFocusPolicy(Qt.NoFocus) self.button_connect.setIcon(QIcon(":/images/connect.png")) self.button_connect.setIconSize(QSize(16, 16)) self.button_connect.setText(QApplication.translate("dev_client", "Connect")) top_layout.addWidget(self.button_connect) self.button_option = QPushButton() self.button_option.setFixedSize(105, 26) self.button_option.setFocusPolicy(Qt.NoFocus) self.button_option.setIcon(QIcon(":/images/option.png")) self.button_option.setIconSize(QSize(16, 16)) self.button_option.setText(QApplication.translate("dev_client", "Option")) top_layout.addWidget(self.button_option) main_layout.addLayout(top_layout, 0, 0) right_layout = QVBoxLayout() right_layout.setContentsMargins(0, 0, 0, 0) right_layout.addItem(QSpacerItem(40, 29, QSizePolicy.Minimum, QSizePolicy.Fixed)) self.rightpanel = QWidget() self.rightpanel.setMinimumWidth(225) right_layout.addWidget(self.rightpanel) main_layout.addLayout(right_layout, 0, 1, 3, 1) self.output_splitter = QSplitter(self.centralwidget) self.output_splitter.setOrientation(Qt.Vertical) self.output_splitter.setHandleWidth(3) self.output_splitter.setChildrenCollapsible(False) self.text_output = QTextEdit(self.output_splitter) self.text_output.setMinimumWidth(690) self.text_output.setFocusPolicy(Qt.NoFocus) self.text_output.setAutoFillBackground(True) self.text_output.setUndoRedoEnabled(False) self.text_output.setReadOnly(True) self.text_output_noscroll = QTextEdit(self.output_splitter) self.text_output_noscroll.setMinimumWidth(690) self.text_output_noscroll.setFocusPolicy(Qt.NoFocus) self.text_output_noscroll.setAutoFillBackground(True) self.text_output_noscroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.text_output_noscroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.text_output_noscroll.setUndoRedoEnabled(False) self.text_output_noscroll.setReadOnly(True) main_layout.addWidget(self.output_splitter, 1, 0) bottom_layout = QHBoxLayout() bottom_layout.setContentsMargins(0, 0, 0, 0) bottom_layout.setSpacing(5) self.text_input = QComboBox() self.text_input.setMinimumWidth(660) self.text_input.setFixedHeight(25) self.text_input.setEditable(True) self.text_input.addItem("") bottom_layout.addWidget(self.text_input) self.toggle_splitter = QPushButton() self.toggle_splitter.setFixedSize(25, 25) self.toggle_splitter.setFocusPolicy(Qt.NoFocus) self.toggle_splitter.setIcon(QIcon(":/images/split-window.png")) bottom_layout.addWidget(self.toggle_splitter) main_layout.addLayout(bottom_layout, 2, 0)