def __init__(self, playersOut, playersIn, parent=None): super(confirmSubsDialog, self).__init__(parent) self.now = QDateTime.currentDateTime() self.now.setTime( QTime(self.now.time().hour(), self.now.time().minute())) self.setWindowTitle("Confirm Subs") mainVerticalLayout = QVBoxLayout(self) subsLayout = QGridLayout() mainVerticalLayout.addLayout(subsLayout) subsLayout.addWidget(QLabel("<b>Players Out</b>"), 0, 0) subsLayout.addWidget(QLabel("<b>Players In</b>"), 0, 1) for i, (playerOut, playerIn) in enumerate(zip(playersOut, playersIn)): playerOutLabel = QLabel() playerOutLabel.setText("<font color=red>{0}</font>".format( playerOut.name)) subsLayout.addWidget(playerOutLabel, i + 1, 0) playerInLabel = QLabel() playerInLabel.setText("<font color=green>{0}</font>".format( playerIn.name)) subsLayout.addWidget(playerInLabel, i + 1, 1) mainVerticalLayout.addItem( QSpacerItem(0, 15, QSizePolicy.Minimum, QSizePolicy.Expanding)) dateTimeLayout = QHBoxLayout() mainVerticalLayout.addLayout(dateTimeLayout) dateTimeLayout.addWidget(QLabel("Date and time")) self.dateTimeEdit = QDateTimeEdit(self.now) self.dateTimeEdit.setMaximumDateTime(self.now) self.dateTimeEdit.setCalendarPopup(True) self.dateTimeEdit.setDisplayFormat("d MMM yy h:mm AP") dateTimeLayout.addWidget(self.dateTimeEdit) dateTimeLayout.addStretch() mainVerticalLayout.addItem( QSpacerItem(0, 10, QSizePolicy.Minimum, QSizePolicy.Expanding)) buttonBox = QDialogButtonBox(self) buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) buttonBox.button(QDialogButtonBox.Ok).setText("&Accept") mainVerticalLayout.addWidget(buttonBox) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject)
class AddAccountDialog(QDialog): def __init__(self, parent, ok_handler, cancel_handler): super(AdminWidget.AddAccountDialog, self).__init__(parent) self.setWindowTitle("Add account") self.setFixedSize(300, 100) self.setModal(True) self.layout = QGridLayout(self) self.username_label = QLabel(self) self.username_label.setText("Username") self.edit_username = QLineEdit(self) self.buttons = QDialogButtonBox(self) self.buttons.addButton(QDialogButtonBox.Ok) self.buttons.addButton(QDialogButtonBox.Cancel) self.buttons.button(QDialogButtonBox.Ok).setText("Add") self.buttons.button(QDialogButtonBox.Cancel).setText("Cancel") self.buttons.button(QDialogButtonBox.Cancel).clicked.connect(cancel_handler) self.buttons.button(QDialogButtonBox.Ok).clicked.connect(lambda: ok_handler(self.edit_username.text())) self.layout.addWidget(self.username_label, 0, 0) self.layout.addWidget(self.edit_username, 0, 1) self.layout.addWidget(self.buttons, 1, 0, 1, 2, Qt.AlignCenter) self.setLayout(self.layout)
class ExportPdfOptionDialog(QDialog): """ Displays options UI for the PDF """ def __init__(self, parent=None): if not parent: parent = hiero.ui.mainWindow() super(ExportPdfOptionDialog, self).__init__(parent) layout = QFormLayout() self._fileNameField = FnFilenameField(False, isSaveFile=False, caption="Set PDF name", filter="*.pdf") self._fileNameField.setFilename(os.path.join(os.getenv("HOME"), "Desktop", "Sequence.pdf")) self._optionDropdown = QComboBox() self._buttonbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self._buttonbox.button(QDialogButtonBox.Ok).setText("Export") self._buttonbox.accepted.connect(self.accept) self._buttonbox.rejected.connect(self.reject) self._pdfActionSettings = {"1 Shot per page": [1, 1], "4 Shots per page)": [2, 2], "9 Shots per page)": [3, 3]} for pdfMode in sorted(self._pdfActionSettings, reverse=True): self._optionDropdown.addItem(pdfMode) layout.addRow("Save to:", self._fileNameField) layout.addRow("PDF Layout:", self._optionDropdown) layout.addRow("", self._buttonbox) self.setLayout(layout) self.setWindowTitle("Export PDF Options") self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) def numRows(self): """Returns the number of rows for the pdf""" optionText = self._optionDropdown.currentText() return self._pdfActionSettings[optionText][0] def numColumns(self): """Returns the number of columns for the pdf""" optionText = self._optionDropdown.currentText() return self._pdfActionSettings[optionText][1] def filePath(self): """Returns the filepath for the pdf""" filename = self._fileNameField.filename() if not filename.endswith(".pdf"): filename = filename + ".pdf" return filename
def __init__(self, log, parent=None): super(EditConfigurationDialog, self).__init__(parent) layout = QVBoxLayout() self._log = log self.text_edit_widget = QTextEdit() layout.addWidget(self.text_edit_widget) buttons = QDialogButtonBox() # buttons.addButton( QDialogButtonBox.StandardButton.Cancel) buttons.addButton(QDialogButtonBox.StandardButton.Save) layout.addWidget(buttons) buttons.button(QDialogButtonBox.StandardButton.Save).clicked.connect( self._save) self.setLayout(layout)
def __init__(self, playersOut, playersIn, parent=None): super(confirmSubsDialog, self).__init__(parent) self.now = QDateTime.currentDateTime() self.now.setTime(QTime(self.now.time().hour(), self.now.time().minute())) self.setWindowTitle("Confirm Subs") mainVerticalLayout = QVBoxLayout(self) subsLayout = QGridLayout() mainVerticalLayout.addLayout(subsLayout) subsLayout.addWidget(QLabel("<b>Players Out</b>"), 0, 0) subsLayout.addWidget(QLabel("<b>Players In</b>"), 0, 1) for i, (playerOut, playerIn) in enumerate(zip(playersOut, playersIn)): playerOutLabel = QLabel() playerOutLabel.setText("<font color=red>{0}</font>".format(playerOut.name)) subsLayout.addWidget(playerOutLabel, i+1, 0) playerInLabel = QLabel() playerInLabel.setText("<font color=green>{0}</font>".format(playerIn.name)) subsLayout.addWidget(playerInLabel, i+1, 1) mainVerticalLayout.addItem(QSpacerItem(0, 15, QSizePolicy.Minimum, QSizePolicy.Expanding)) dateTimeLayout = QHBoxLayout() mainVerticalLayout.addLayout(dateTimeLayout) dateTimeLayout.addWidget(QLabel("Date and time")) self.dateTimeEdit = QDateTimeEdit(self.now) self.dateTimeEdit.setMaximumDateTime(self.now) self.dateTimeEdit.setCalendarPopup(True) self.dateTimeEdit.setDisplayFormat("d MMM yy h:mm AP") dateTimeLayout.addWidget(self.dateTimeEdit) dateTimeLayout.addStretch() mainVerticalLayout.addItem(QSpacerItem(0, 10, QSizePolicy.Minimum, QSizePolicy.Expanding)) buttonBox = QDialogButtonBox(self) buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) buttonBox.button(QDialogButtonBox.Ok).setText("&Accept") mainVerticalLayout.addWidget(buttonBox) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject)
def _createButtonBox(self): box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self._okButton = box.button(QDialogButtonBox.Ok) box.accepted.connect(self.accept) box.rejected.connect(self.reject) return box
def __init__(self, players, oldFormation, newFormation, parent=None): super(changeFormationDialog, self).__init__(parent) self.players = players self.formationChanges = oldFormation - newFormation self.setWindowTitle("Change Formation") mainVerticalLayout = QVBoxLayout(self) self.allCheckBoxes = [] for i, p in enumerate(self.formationChanges): checkBoxes = {} if p > 0: outLabel = QLabel() text = "<b>Choose {0} {1}" if p > 1: text += "s" text += " to drop</b>" position = Formation.labels[i] outLabel.setText(text.format(p, position.lower())) mainVerticalLayout.addWidget(outLabel) #subsLayout.addWidget(outLabel, 0, 0) for player in [ player for player in players if player.position == position ]: checkBox = QCheckBox("{0} {1}".format( str(player), player.value)) checkBoxes[player] = checkBox mainVerticalLayout.addWidget(checkBox) self.allCheckBoxes.append(checkBoxes) buttonBox = QDialogButtonBox(self) buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) buttonBox.button(QDialogButtonBox.Ok).setText("&Accept") mainVerticalLayout.addWidget(buttonBox) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject)
def __init__(self, items): # , parent=None super(MultiListDialog, self).__init__() # parent self.resize(800, 550) self.entries = items layout = QVBoxLayout(self) self.listWidget = QListWidget(self) self.listWidget.setSelectionMode(QAbstractItemView.ExtendedSelection) self.HlineInputfiles = ConfigLineDir(u"Verzeichnis NI XML:", "dir") self.HlineOutputfiles = ConfigLineDir(u"Verzeichnis Report:", "dir") if os.path.isfile(PICKLE_TEMP_FILE): pkl_file = open(PICKLE_TEMP_FILE, 'rb') inPath = pickle.load(pkl_file) outPath = pickle.load(pkl_file) pkl_file.close() if os.path.isdir(inPath): self.HlineInputfiles.editText.setText(inPath) if os.path.isdir(outPath): self.HlineOutputfiles.editText.setText(outPath) layout.addLayout(self.HlineInputfiles) layout.addLayout(self.HlineOutputfiles) layout.addWidget(self.listWidget) layout.addWidget(QLabel("Mehrfachauswahl -> Strg + Mausklick")) # OK and Cancel buttons buttons = QDialogButtonBox(QDialogButtonBox.Apply | QDialogButtonBox.Close, Qt.Horizontal, self) # Apply before Close buttons.setStyleSheet("* { button-layout: 2 }") layout.addWidget(buttons) buttons.rejected.connect(self.close) buttons.button(QDialogButtonBox.Apply).clicked.connect(self.Apply_Clicked) self.SetListItems() self.HlineInputfiles.editText.textChanged.connect(self.RefreshList) self.HlineInputfiles.editText.textChanged.connect(self.SetListItems)
def __init__(self, players, oldFormation, newFormation, parent=None): super(changeFormationDialog, self).__init__(parent) self.players = players self.formationChanges = oldFormation-newFormation self.setWindowTitle("Change Formation") mainVerticalLayout = QVBoxLayout(self) self.allCheckBoxes = [] for i,p in enumerate(self.formationChanges): checkBoxes = {} if p > 0: outLabel = QLabel() text = "<b>Choose {0} {1}" if p > 1: text+="s" text += " to drop</b>" position = Formation.labels[i] outLabel.setText(text.format(p, position.lower())) mainVerticalLayout.addWidget(outLabel) #subsLayout.addWidget(outLabel, 0, 0) for player in [player for player in players if player.position == position]: checkBox = QCheckBox("{0} {1}".format(str(player), player.value)) checkBoxes[player] = checkBox mainVerticalLayout.addWidget(checkBox) self.allCheckBoxes.append(checkBoxes) buttonBox = QDialogButtonBox(self) buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) buttonBox.button(QDialogButtonBox.Ok).setText("&Accept") mainVerticalLayout.addWidget(buttonBox) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject)
class ChangePasswordDialog(QDialog): """Represents change password dialog window""" def __init__(self, window, ok_handler, cancel_handler): super(ChangePasswordDialog, self).__init__(window) self.setWindowTitle("Change password") self.setFixedSize(300, 160) self.setModal(True) self.layout = QGridLayout(self) self.old_password_label = QLabel(self) self.old_password_label.setText("Old password") self.edit_old_password = QLineEdit(self) self.edit_old_password.setEchoMode(QLineEdit.Password) self.password_label = QLabel(self) self.password_label.setText("New password") self.edit_password = QLineEdit(self) self.edit_password.setEchoMode(QLineEdit.Password) self.confirm_label = QLabel(self) self.confirm_label.setText("Confirm password") self.edit_confirm = QLineEdit(self) self.edit_confirm.setEchoMode(QLineEdit.Password) self.buttons = QDialogButtonBox(self) self.buttons.addButton(QDialogButtonBox.Ok) self.buttons.addButton(QDialogButtonBox.Cancel) self.buttons.button(QDialogButtonBox.Ok).setText("Change") self.buttons.button(QDialogButtonBox.Cancel).setText("Cancel") self.buttons.button(QDialogButtonBox.Cancel).clicked.connect(cancel_handler) self.buttons.button(QDialogButtonBox.Ok).clicked.connect( lambda: ok_handler(self.edit_old_password.text(), self.edit_password.text(), self.edit_confirm.text())) self.layout.addWidget(self.old_password_label, 0, 0) self.layout.addWidget(self.edit_old_password, 0, 1) self.layout.addWidget(self.password_label, 1, 0) self.layout.addWidget(self.edit_password, 1, 1) self.layout.addWidget(self.confirm_label, 2, 0) self.layout.addWidget(self.edit_confirm, 2, 1) self.layout.addWidget(self.buttons, 3, 0, 1, 2, Qt.AlignCenter) self.setLayout(self.layout)
def createButtons(self): buttonsDialog = QDialogButtonBox(self) buttonsDialog.setStandardButtons( QDialogButtonBox.Save | QDialogButtonBox.Cancel | QDialogButtonBox.Reset) self.grid.addWidget(buttonsDialog, 3, 0, 3, 9) buttonsDialog.button(QDialogButtonBox.Save).clicked.connect( self.saveFile) buttonsDialog.button(QDialogButtonBox.Reset).clicked.connect( self.PaintArea.clearImage) buttonsDialog.button(QDialogButtonBox.Cancel).clicked.connect( self.close)
class SignInDialog(QDialog): """Represents sign in dialog window""" def __init__(self, window, ok_handler, cancel_handler): super(SignInDialog, self).__init__(window) self.setWindowTitle("Login") self.setFixedSize(300, 130) self.setModal(True) self.layout = QGridLayout(self) self.username_label = QLabel(self) self.username_label.setText("Username:"******"Password:"******"Login") self.buttons.button(QDialogButtonBox.Cancel).setText("Cancel") self.buttons.button(QDialogButtonBox.Cancel).clicked.connect(cancel_handler) self.buttons.button(QDialogButtonBox.Ok).clicked.connect( lambda: ok_handler(self.edit_username.text(), self.edit_password.text())) self.layout.addWidget(self.username_label, 0, 0) self.layout.addWidget(self.edit_username, 0, 1) self.layout.addWidget(self.password_label, 1, 0) self.layout.addWidget(self.edit_password, 1, 1) self.layout.addWidget(self.buttons, 3, 0, 1, 2, Qt.AlignCenter) self.setLayout(self.layout)
class ConfigEditor(QMainWindow): def __init__(self, app, cfg, title='Config Editor'): super(ConfigEditor, self).__init__() self.app = app self.config = cfg self.title = title def setup(self): self.dirty = False self.def_cfg = copy.deepcopy(self.config) self.config.update_from_user_file() self.base_cfg = copy.deepcopy(self.config) self.categories = QListWidget() #self.categories.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.Expanding) self.settings = QStackedWidget() #self.categories.setSizePolicy(QSizePolicy.MinimumExpanding,QSizePolicy.Expanding) QObject.connect(self.categories, SIGNAL('itemSelectionChanged()'), self.category_selected) self.widget_list = {} for cat in self.config.get_categories(): self.widget_list[cat] = {} longest_cat = 0 for cat in self.config.get_categories(): if len(cat) > longest_cat: longest_cat = len(cat) self.categories.addItem(cat) settings_layout = QGridLayout() r = 0 c = 0 for setting in self.config.get_settings(cat): info = self.config.get_setting(cat, setting, True) s = QWidget() s.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Fixed) sl = QVBoxLayout() label = QLabel() if info.has_key('alias'): label.setText(info['alias']) else: label.setText(setting) if info.has_key('about'): label.setToolTip(info['about']) sl.addWidget(label) if info['type'] == constants.CT_LINEEDIT: w = LineEdit(self, self.config,cat,setting,info) elif info['type'] == constants.CT_CHECKBOX: w = CheckBox(self, self.config,cat,setting,info) elif info['type'] == constants.CT_SPINBOX: w = SpinBox(self, self.config,cat,setting,info) elif info['type'] == constants.CT_DBLSPINBOX: w = DoubleSpinBox(self, self.config,cat,setting,info) elif info['type'] == constants.CT_COMBO: w = ComboBox(self, self.config,cat,setting,info) w.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Fixed) self.widget_list[cat][setting] = w sl.addWidget(w) s.setLayout(sl) c = self.config.config[cat].index(setting) % 2 settings_layout.addWidget(s, r, c) if c == 1: r += 1 settings = QWidget() settings.setLayout(settings_layout) settings_scroller = QScrollArea() settings_scroller.setWidget(settings) settings_scroller.setWidgetResizable(True) self.settings.addWidget(settings_scroller) font = self.categories.font() fm = QFontMetrics(font) self.categories.setMaximumWidth(fm.widthChar('X')*(longest_cat+4)) self.main = QWidget() self.main_layout = QVBoxLayout() self.config_layout = QHBoxLayout() self.config_layout.addWidget(self.categories) self.config_layout.addWidget(self.settings) self.mainButtons = QDialogButtonBox(QDialogButtonBox.RestoreDefaults | QDialogButtonBox.Reset | QDialogButtonBox.Apply) self.main_apply = self.mainButtons.button(QDialogButtonBox.StandardButton.Apply) self.main_reset = self.mainButtons.button(QDialogButtonBox.StandardButton.Reset) self.main_defaults = self.mainButtons.button(QDialogButtonBox.StandardButton.LastButton) QObject.connect(self.mainButtons, SIGNAL('clicked(QAbstractButton *)'), self.mainbutton_clicked) self.dirty_check() self.main_layout.addLayout(self.config_layout) self.main_layout.addWidget(self.mainButtons) self.main.setLayout(self.main_layout) self.setCentralWidget(self.main) self.setWindowTitle(self.title) self.setUnifiedTitleAndToolBarOnMac(True) self.categories.setCurrentItem(self.categories.item(0)) self.menuBar = QMenuBar() self.filemenu = QMenu('&File') self.quitAction = QAction(self) self.quitAction.setText('&Quit') if platform.system() != 'Darwin': self.quitAction.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Q)) QObject.connect(self.quitAction, SIGNAL('triggered()'), self.quitApp) self.filemenu.addAction(self.quitAction) self.menuBar.addMenu(self.filemenu) self.setMenuBar(self.menuBar) self.show() self.activateWindow() self.raise_() self.setMinimumWidth(self.geometry().width()*1.2) screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2) def category_selected(self): self.settings.setCurrentIndex(self.config.config.index(self.categories.selectedItems()[0].text())) def mainbutton_clicked(self, button): if button == self.main_reset: for cat in self.base_cfg.get_categories(): for setting in self.base_cfg.get_settings(cat): self.widget_list[cat][setting].updateValue(self.base_cfg.get_setting(cat,setting)) elif button == self.main_defaults: for cat in self.def_cfg.get_categories(): for setting in self.def_cfg.get_settings(cat): self.widget_list[cat][setting].updateValue(self.def_cfg.get_setting(cat,setting)) elif button == self.main_apply: bad_settings = self.validate_settings() if bad_settings == []: self.save_settings() self.main_apply.setEnabled(False) self.main_reset.setEnabled(False) else: msgBox = QMessageBox() msgBox.setText("Must fix the following invalid settings before quitting:") msgBox.setStandardButtons(QMessageBox.Ok) info = '' for setting in bad_settings: new = '%s,%s<br>' % setting info = '%s%s' % (info, new) msgBox.setInformativeText(info) msgBox.exec_() def quitApp(self): self.app.closeAllWindows() def get_changes(self): enc = MyEncoder() if enc.encode(self.def_cfg.config) == enc.encode(self.config.config): return False if enc.encode(self.base_cfg.config) != enc.encode(self.config.config): newC = Config() for c in self.config.config.keys(): for s in self.config.config[c].keys(): if self.config.config[c][s]['value'] != self.def_cfg.config[c][s]['value']: newC.add_setting(c, s, self.config.config[c][s]['value'], stub=True) return json.dumps(newC.config, separators=(',',': '), indent=4, sort_keys=True) else: return None def validate_settings(self): ret = [] for cat in self.config.get_categories(): for setting in self.config.get_settings(cat): info = self.config.get_setting(cat, setting, True) if info.has_key('validate'): if not info['validate'](info): ret.append((cat,setting)) return ret def dirty_check(self): if str(self.base_cfg) != str(self.config): self.dirty = True self.main_apply.setEnabled(True) self.main_reset.setEnabled(True) else: self.dirty = False self.main_apply.setEnabled(False) self.main_reset.setEnabled(False) if str(self.def_cfg) == str(self.config): self.main_defaults.setEnabled(False) else: self.main_defaults.setEnabled(True) def save_settings(self): config = self.get_changes() if config == False: if os.path.isfile(self.config.user_file): os.remove(self.config.user_file) elif config != None: with open(self.config.user_file, 'w+') as f: f.write(config) self.base_cfg = copy.deepcopy(self.config) def closeEvent(self, event=None): self.quitApp()
class ExportPdfOptionDialog(QDialog): """ Displays options UI for the PDF """ def __init__(self, parent = None): if not parent: parent = hiero.ui.mainWindow() super(ExportPdfOptionDialog, self).__init__(parent) layout = QFormLayout() self._fileNameField = FnFilenameField(False, isSaveFile=False, caption="Set PDF name", filter='*.pdf') self._fileNameField.setFilename(os.path.join(os.getenv('HOME'), "Desktop", "Sequence.pdf")) self._pdfLayoutDropdown = QComboBox() self._pdfLayoutDropdown.setToolTip("Set the PDF page layout type.") self._thumbFrameTypeDropdown = QComboBox() self._thumbFrameTypeDropdown.setToolTip("Set which frame to take the thumbnail from.") self._buttonbox = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self._buttonbox.button(QDialogButtonBox.Ok).setText("Export") self._buttonbox.accepted.connect(self.accept) self._buttonbox.rejected.connect(self.reject) self._pdfLayouts = PDFExporter.PAGE_LAYOUTS_DICT self._thumbFrameTypes = PDFExporter.THUMB_FRAME_TYPES for pdfLayout in sorted(self._pdfLayouts, reverse=True): self._pdfLayoutDropdown.addItem(pdfLayout) for frameType in self._thumbFrameTypes: self._thumbFrameTypeDropdown.addItem(frameType) layout.addRow("Save to:", self._fileNameField) layout.addRow("PDF Layout:", self._pdfLayoutDropdown) layout.addRow("Thumbnail Frame:", self._thumbFrameTypeDropdown) layout.addRow("", self._buttonbox) self.setLayout(layout) self.setWindowTitle("Export PDF Options") self.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Fixed ) def _thumbnailFrameType(self): """Returns the currently selected thumbnail frame type""" return self._thumbFrameTypeDropdown.currentText() def _numRows(self): """Returns the number of rows for the pdf""" optionText = self._pdfLayoutDropdown.currentText() return self._pdfLayouts[optionText][0] def _numColumns(self): """Returns the number of columns for the pdf""" optionText = self._pdfLayoutDropdown.currentText() return self._pdfLayouts[optionText][1] def _filePath(self): """Returns the filepath for the pdf""" filename = self._fileNameField.filename() if not filename.endswith('.pdf'): filename = filename + ".pdf" return filename
class SettingsWindow(QDialog): def __init__(self, parent): super(self.__class__, self).__init__(parent) self.parent = parent self.lib = libserial.InitApp(self) if self.parent.receive is not None: self.boolean_config_is_ok = True else: self.boolean_config_is_ok = False self.config_parser = ConfigParser.ConfigParser() self.config_parser.read("config/profiles/profiles.ini") self.settings_parser = ConfigParser.ConfigParser() self.settings_parser.read('config/settings.ini') self.setWindowTitle(SERIAL_CHAT_SETTINGS_TITLE) self.button_box_dialog = QDialogButtonBox(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.button_box_dialog.button(QDialogButtonBox.Ok).setText(CONNECT) self.button_box_dialog.button(QDialogButtonBox.Cancel).setText(CANCEL) self.button_box_dialog.accepted.connect(self.accept) self.accepted.connect(self.apply_setting_changes) self.button_box_dialog.rejected.connect(self.reject) self.serial_dropdown = QComboBox() self.lib.init__serial() self.serial_values = self.lib.get_serials() for serials in self.serial_values: self.serial_dropdown.addItem(serials) if self.parent.serial_port is not None: self.serial_dropdown.setCurrentIndex( self.serial_dropdown.findText(self.parent.serial_port.name)) self.profiles_combobox = QComboBox() self.profiles_combobox.addItem("None") if self.parent.choosen_profile == "Custom": self.profiles_combobox.addItem("Custom") for profile in self.config_parser.sections(): self.profiles_combobox.addItem(profile) if self.parent.custom_settings: self.profiles_combobox.setCurrentIndex( self.profiles_combobox.findText('Custom')) elif self.parent.choosen_profile != 'None': self.profiles_combobox.setCurrentIndex( self.profiles_combobox.findText(self.parent.choosen_profile)) else: self.profiles_combobox.setCurrentIndex( self.profiles_combobox.findText('None')) self.profiles_combobox.currentIndexChanged.connect( self.change_custom_settings_on_profile) self.custom_settings_checkbox = QCheckBox() self.custom_settings_checkbox.stateChanged.connect( self.custom_settings_enable_disable) self.interval_time_lineedit = QLineEdit(str(self.parent.interval_time)) self.interval_time_lineedit.editingFinished.connect( self.check_if_digit) self.interval_time_lineedit.setDisabled(True) self.serial_speed_combobox = QComboBox() for sp in serial_speeds: self.serial_speed_combobox.addItem(str(sp)) if self.boolean_config_is_ok: self.serial_speed_combobox.setCurrentIndex( self.serial_speed_combobox.findText( str(self.parent.serial_port.baudrate))) else: self.serial_speed_combobox.setCurrentIndex( self.serial_speed_combobox.findText('9600')) self.serial_speed_combobox.setDisabled(True) self.databits_combobox = QComboBox() for db in bytesize_values: self.databits_combobox.addItem(str(db)) if self.boolean_config_is_ok: self.databits_combobox.setCurrentIndex( self.databits_combobox.findText( str(self.parent.serial_port.bytesize))) else: self.databits_combobox.setCurrentIndex( self.databits_combobox.findText('8')) self.databits_combobox.setDisabled(True) self.stopbits_combobox = QComboBox() for sb in stop_values: self.stopbits_combobox.addItem(str(sb)) if self.boolean_config_is_ok: sb = str(self.parent.serial_port.stopbits).replace('.', ',') self.stopbits_combobox.setCurrentIndex( self.stopbits_combobox.findText(str(sb))) else: self.stopbits_combobox.setCurrentIndex( self.stopbits_combobox.findText('1')) self.stopbits_combobox.setDisabled(True) self.parity_combobox = QComboBox() for par in parity_values: self.parity_combobox.addItem(str(par)) if self.boolean_config_is_ok: table = {'O': 'Odd', 'E': 'Even', 'N': 'None'} xxx = [ item for key, item in table.items() if self.parent.serial_port.parity == key ] self.parity_combobox.setCurrentIndex(parity_values.index(xxx[0])) else: self.parity_combobox.setCurrentIndex( self.parity_combobox.findText("None")) self.parity_combobox.setDisabled(True) self.flowcontrol_combobox = QComboBox() for fc in flow_control_values: self.flowcontrol_combobox.addItem(str(fc)) if self.boolean_config_is_ok: if self.parent.serial_port.xonxoff: self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText("XON/XOFF")) elif self.parent.serial_port.rtscts: self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText("RTS/CTS")) else: self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText("None")) else: self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText("None")) self.flowcontrol_combobox.setDisabled(True) self.nickname_lineedit = QLineEdit() if self.settings_parser.has_option('default', 'nickname'): nickname = self.settings_parser.get('default', 'nickname') if type(nickname) == str: nickname = nickname.decode('utf-8') self.nickname_lineedit.setText( self.settings_parser.get('default', 'nickname')) else: if self.parent.nickname is None: self.nickname_lineedit.setText("Guest_" + MD5.new( str(datetime.datetime.now())).digest().encode('hex')[:5]) else: self.nickname_lineedit.setText(self.parent.nickname) self.save_folder_editline = QLineEdit(self.parent.default_save_folder) self.save_folder_editline.editingFinished.connect( self.check_if_folder_exists) if self.settings_parser.has_option('default', 'default_save_folder'): folder = self.settings_parser.get('default', 'default_save_folder') if type(folder) == str: folder = folder.decode('utf-8') self.save_folder_editline.setText(folder) self.check_if_folder_exists() self.dir_browser_button = QPushButton() self.dir_browser_button.setIcon(QIcon(icons_folder + 'folder.png')) self.dir_browser_button.clicked.connect(self.choose_save_dir) self.horizontal_box_hboxlayout = QHBoxLayout() self.horizontal_box_hboxlayout.addWidget(self.save_folder_editline) self.horizontal_box_hboxlayout.addWidget(self.dir_browser_button) self.horizontal_box_container_widget = QWidget() self.horizontal_box_container_widget.setLayout( self.horizontal_box_hboxlayout) self.enable_ACP127 = QCheckBox() self.enable_ACP127.stateChanged.connect( self.enable_functionality_ACP127) if self.parent.acp127: self.enable_ACP127.setChecked(True) self.encryption_password_lineedit = QLineEdit() self.enable_encryption_checkbox = QCheckBox() self.enable_encryption_checkbox.stateChanged.connect( self.enable_functionality_encryption) if self.parent.isEncryptionEnabled: self.enable_encryption_checkbox.setChecked(True) self.encryption_password_lineedit.setEchoMode( QLineEdit.EchoMode.PasswordEchoOnEdit) if self.parent.encryption_key is not None: self.encryption_password_lineedit.setText( self.parent.encryption_key) if self.enable_encryption_checkbox.isChecked(): self.encryption_password_lineedit.setDisabled(False) else: self.encryption_password_lineedit.setDisabled(True) self.grid_form_layout = QFormLayout() self.grid_form_layout.addRow(FORMLAYOUT_SERIAL_TITLE + ":", self.serial_dropdown) self.grid_form_layout.addRow(FORMLAYOUT_PROFILE_TITLE + ":", self.profiles_combobox) self.grid_form_layout.addRow(FORMLAYOUT_CUSTOM_SERIAL_SETTINGS_TITLE, self.custom_settings_checkbox) self.grid_form_layout.addRow(FORMLAYOUT_INTERVAL_TIME_TITLE + ":", self.interval_time_lineedit) self.grid_form_layout.addRow(FORMLAYOUT_SERIAL_SPEED_TITLE + "(baud):", self.serial_speed_combobox) self.grid_form_layout.addRow(FORMLAYOUT_DATA_BITS_TITLE + ":", self.databits_combobox) self.grid_form_layout.addRow(FORMLAYOUT_STOP_BITS_TITLE + ":", self.stopbits_combobox) self.grid_form_layout.addRow(FORMLAYOUT_PARITY_TITLE + ":", self.parity_combobox) self.grid_form_layout.addRow(FORMLAYOUT_FLOWCONTROL_TITLE + ":", self.flowcontrol_combobox) self.grid_form_layout.addRow( FORMLAYOUT_ENABLE_ACP127_TITLE + " ACP-127", self.enable_ACP127) self.grid_form_layout.addRow(FORMLAYOUT_ENABLE_ENCRYPTION_TITLE, self.enable_encryption_checkbox) self.grid_form_layout.addRow(FORMLAYOUT_ENCRYPTION_KEY_TITLE, self.encryption_password_lineedit) self.grid_form_layout.addRow(FORMLAYOUT_NICKNAME_TITLE + ":", self.nickname_lineedit) self.grid_form_layout.addRow(FORMLAYOUT_SAVE_FOLDER_FILE_TITLE + ":", self.horizontal_box_container_widget) self.grid_form_layout.addRow("", self.button_box_dialog) self.setLayout(self.grid_form_layout) self.show() def enable_functionality_encryption(self): if self.enable_encryption_checkbox.isChecked(): self.encryption_password_lineedit.setDisabled(False) else: self.encryption_password_lineedit.setDisabled(True) def check_if_folder_exists(self): if not os.path.isdir(self.save_folder_editline.text()): msgBox = QMessageBox(icon=QMessageBox.Warning, text=ERROR_NO_DIR_MESSAGE) msgBox.setWindowTitle(ERROR_NO_DIR_TITLE) msgBox.exec_() self.save_folder_editline.setText(self.parent.default_save_folder) def check_if_digit(self): try: int(self.interval_time_lineedit.text()) except: msgBox = QMessageBox(icon=QMessageBox.Warning, text=ERROR_NO_INT_MESSAGE) msgBox.setWindowTitle(ERROR_NO_INT_TITLE) msgBox.exec_() self.interval_time_lineedit.setText(str(self.parent.interval_time)) def choose_save_dir(self): fname = QFileDialog(self, FILEBROWSER_SAVE_FOLDER_TITLE) fname.setFileMode(QFileDialog.Directory) looking_label = QFileDialog.DialogLabel(QFileDialog.LookIn) filename_label = QFileDialog.DialogLabel(QFileDialog.FileName) filetype_label = QFileDialog.DialogLabel(QFileDialog.FileType) fname.setLabelText(looking_label, FILEBROWSER_SAVE_FOLDER_LOOKIN) fname.setLabelText(filename_label, FILEBROWSER_SAVE_FOLDER_FOLDERNAME) fname.setLabelText(filetype_label, FILEBROWSER_SAVE_FOLDER_FOLDERTYPE) fname.setOption(QFileDialog.ShowDirsOnly) if fname.exec_(): filename = fname.selectedFiles()[0] self.save_folder_editline.setText(filename) def enable_functionality_ACP127(self): if self.enable_ACP127.isChecked(): self.parent.acp127 = True else: self.parent.acp127 = False def apply_setting_changes(self): res = None self.parent.custom_settings_enable_disable = self.custom_settings_checkbox.isChecked( ) self.parent.choosen_profile = self.profiles_combobox.currentText() if self.parent.custom_settings_enable_disable: self.parent.choosen_profile = "Custom" if self.enable_encryption_checkbox.isChecked(): self.parent.isEncryptionEnabled = True self.parent.encryption_key = self.encryption_password_lineedit.text( ) else: self.parent.isEncryptionEnabled = False self.parent.encryption_key = None if self.nickname_lineedit.text() != "": nick = self.nickname_lineedit.text().rstrip() nick = nick.replace(" ", "_") self.parent.nickname = nick if self.save_folder_editline.text() != "": if os.path.isdir(self.save_folder_editline.text()): self.parent.default_save_folder = self.save_folder_editline.text( ) self.parent.interval_time = int(self.interval_time_lineedit.text()) if self.flowcontrol_combobox.currentText() == "XON/XOFF": x_control = True else: x_control = False if self.flowcontrol_combobox.currentText() == "RTS/CTS": r_control = True else: r_control = False if self.parent.receive is None: res = self.lib.set_serial( port=self.serial_dropdown.currentText(), baudrate=self.serial_speed_combobox.currentText(), bytesize=self.databits_combobox.currentText(), stopbits=self.stopbits_combobox.currentText(), parity=self.parity_combobox.currentText(), xonxoff=x_control, rtscts=r_control) else: self.parent.receive.loop_run = False self.parent.receive.wait() self.parent.receive = None res = self.lib.set_serial( port=self.serial_dropdown.currentText(), baudrate=self.serial_speed_combobox.currentText(), bytesize=self.databits_combobox.currentText(), stopbits=self.stopbits_combobox.currentText(), parity=self.parity_combobox.currentText(), xonxoff=x_control, rtscts=r_control) if type(res) == OSError: self.parent.status_bar_widget.showMessage(str(res), 5000) msgBox = QMessageBox(icon=QMessageBox.Critical, text=str(res)) msgBox.setWindowTitle(ERROR_INTERFACE_TITLE) msgBox.exec_() if type(res) is not None and type(res) != OSError: self.parent.serial_port = res self.parent.start_threads() self.parent.status_bar_widget.showMessage( MSG_SERIAL_INT_STARTED % self.parent.serial_port.port) def change_custom_settings_on_profile(self): if self.profiles_combobox.currentText() != 'None': section = self.profiles_combobox.currentText() self.interval_time_lineedit.setText( self.config_parser.get(section, "interval")) self.serial_speed_combobox.setCurrentIndex( self.serial_speed_combobox.findText( self.config_parser.get(section, "serialspeed"))) self.databits_combobox.setCurrentIndex( self.databits_combobox.findText( self.config_parser.get(section, "bytesize"))) self.stopbits_combobox.setCurrentIndex( self.stopbits_combobox.findText( self.config_parser.get(section, "stopbits"))) self.parity_combobox.setCurrentIndex( self.parity_combobox.findText( self.config_parser.get(section, "parity"))) if self.config_parser.get(section, "xonxoff") == 'True': self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText("XON/XOFF")) elif self.config_parser.get(section, "rtscts") == 'True': self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText("RTS/CTS")) else: self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText("None")) if self.config_parser.get(section, "acp127") == "True": self.enable_ACP127.setChecked(True) else: self.enable_ACP127.setChecked(False) elif self.profiles_combobox.currentText() == "None": self.serial_speed_combobox.setCurrentIndex( self.serial_speed_combobox.findText('9600')) self.interval_time_lineedit.setText(str(self.parent.intervaltime)) self.databits_combobox.setCurrentIndex( self.databits_combobox.findText('8')) self.stopbits_combobox.setCurrentIndex( self.stopbits_combobox.findText('1')) self.parity_combobox.setCurrentIndex( self.parity_combobox.findText('None')) self.flowcontrol_combobox.setCurrentIndex( self.flowcontrol_combobox.findText('None')) self.enable_ACP127.setChecked(False) def custom_settings_enable_disable(self): if self.custom_settings_checkbox.isChecked(): self.interval_time_lineedit.setDisabled(False) self.serial_speed_combobox.setDisabled(False) self.databits_combobox.setDisabled(False) self.stopbits_combobox.setDisabled(False) self.parity_combobox.setDisabled(False) self.flowcontrol_combobox.setDisabled(False) else: self.interval_time_lineedit.setDisabled(True) self.serial_speed_combobox.setDisabled(True) self.databits_combobox.setDisabled(True) self.stopbits_combobox.setDisabled(True) self.parity_combobox.setDisabled(True) self.flowcontrol_combobox.setDisabled(True)
class FindOrderDialog(QDialog): def __init__(self,parent): global dao super(FindOrderDialog,self).__init__(parent) title = _("Find order") self.setWindowTitle(title) top_layout = QVBoxLayout() self.title_widget = TitleWidget(title,self) top_layout.addWidget(self.title_widget) hlayout = QHBoxLayout() hlayout.addWidget(QLabel(_("Search"))) self.search_criteria = QLineEdit() self.search_criteria.setObjectName("search_criteria") hlayout.addWidget(self.search_criteria) top_layout.addLayout(hlayout) self.search_results_view = QTableView() self.headers_view = QHeaderView(Qt.Orientation.Horizontal) self.header_model = make_header_model([_("Preorder Nr"),_("Order Nr"),_("Customer Nr"),_("Customer"),_("Order Part")]) self.headers_view.setModel(self.header_model) # qt's doc : The view does *not* take ownership (bt there's something with the selecion mode self.search_results_model = QStandardItemModel() self.search_results_view.setModel(self.search_results_model) self.search_results_view.setEditTriggers(QAbstractItemView.NoEditTriggers) self.search_results_view.setHorizontalHeader(self.headers_view) self.search_results_view.verticalHeader().hide() # self.search_results_view.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents) self.search_results_view.horizontalHeader().setResizeMode(3, QHeaderView.Stretch) self.search_results_view.horizontalHeader().setResizeMode(4, QHeaderView.Stretch) self.search_results_view.setSelectionBehavior(QAbstractItemView.SelectRows) self.buttons = QDialogButtonBox() self.buttons.addButton( QDialogButtonBox.StandardButton.Cancel) self.buttons.addButton( QDialogButtonBox.Ok) self.buttons.button(QDialogButtonBox.Ok).setObjectName("go_search") top_layout.addWidget(self.search_results_view) top_layout.setStretch(2,1000) top_layout.addWidget(self.buttons) self.setLayout(top_layout) self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.reject) self.search_results_view.activated.connect(self.row_activated) self.search_criteria.returnPressed.connect(self.search_criteria_submitted) self.setMinimumSize(800,640) def find_by_text(self,text): text = text.strip() try: too_many_results, res = dao.order_part_dao.find_ids_by_text(text.strip()) if too_many_results: showWarningBox(_("Too many results"),_("The query you've given brought back too many results. Only a part of them is displayed. Consider refining your query"),object_name="too_many_results") return dao.order_part_dao.find_by_ids(res) except DataException as de: if de.code == DataException.CRITERIA_IS_EMPTY: showErrorBox(_("Error in the filter !"), _("The filter can't be empty"),object_name="filter_is_empty") elif de.code == DataException.CRITERIA_IS_TOO_SHORT: showErrorBox(_("Error in the filter !"), _("The filter is too short"),object_name="filter_is_too_short") elif de.code == DataException.CRITERIA_IS_TOO_LONG: showErrorBox(_("Error in the filter !"), _("The filter is too long"),object_name="filter_is_too_long") return [] # order_part_match = [] # matches = [] # super_matches = [] # import re # re_order_part_identifier = re.compile("^([0-9]+)([A-Z]+)$") # re_label_identifier = re.compile("^[0-9]+$") # if re_order_part_identifier.match(text.upper()): # # Look for an exact (and unique) match on the order part full identifier # p = dao.order_part_dao.find_by_full_id(text.upper()) # if p: # # Mimick SQLAlchemy's KeyTuples # # FIXME It seems that I use something that's internal to SQLA # # Search SQLA's doc for KeyedTuple to find about collections.namedtuple() # from sqlalchemy.util._collections import KeyedTuple # kt = KeyedTuple([p.order_id, p.order.preorder_label, p.order.accounting_label, p.order.customer_order_name, p.order.customer.fullname, p.order.creation_date, p.description, p.order_part_id, p.label], # labels=['order_id','preorder_label','accounting_label','customer_order_name','fullname','creation_date','description','order_part_id','label']) # order_part_match = [ kt ] # if re_label_identifier.match(text): # for r in dao.order_dao.find_by_labels(int(text)): # super_matches.append(r) # for r in dao.order_dao.find_by_customer_name(text): # # mainlog.debug('customer name match on {}'.format(text)) # matches.append(r) # for r in dao.order_dao.find_by_customer_order_name(text): # # mainlog.debug('customer name match on {}'.format(text)) # matches.append(r) # for r in dao.order_part_dao.find_by_description(text): # matches.append(r) # # Finally we order the matches to bring the most relevant # # first. The "most relevant" is really a business order. # return order_part_match + super_matches + \ # sorted(matches, lambda a,b: - cmp(a.order_id,b.order_id)) def _search_results_to_array(self,search_results): array = [] for res in search_results: # mainlog.debug("_search_results_to_array {}".format(res.creation_date)) i = QStandardItem(res.preorder_part_label) row = [i, QStandardItem(res.accounting_part_label), QStandardItem(res.customer_order_name), QStandardItem(res.fullname)] if 'order_part_id' in res.__dict__: # It's an order part i.setData( res.order_part_id, Qt.UserRole) i.setData( 'order_part', Qt.UserRole+1) row.append( QStandardItem(res.description)) else: # It's an order i.setData( res.order_id, Qt.UserRole) i.setData( 'order', Qt.UserRole+1) row.append( QStandardItem()) array.append(row) return array def load_search_results(self,text=None): global dao if text is None: text = self.search_criteria.text() db_results = self.find_by_text(text) array = self._search_results_to_array(db_results) self.search_results_model.removeRows(0,self.search_results_model.rowCount()) for row in array: self.search_results_model.appendRow(row) mainlog.debug("Loaded model : {}".format(self.search_results_model.rowCount())) self.search_results_view.resizeColumnsToContents() if self.search_results_model.rowCount() > 0: self.search_results_view.setCurrentIndex(self.search_results_model.index(0,0)) self.search_results_view.setFocus(Qt.OtherFocusReason) if self.search_results_model.rowCount() == 1: self.accept() def selected_item(self): mainlog.debug("FindOrder.selected_item") ndx = self.search_results_view.currentIndex() if ndx.isValid(): ndx = self.search_results_view.model().index( ndx.row(), 0) item = ndx.data(Qt.UserRole) item_type = ndx.data(Qt.UserRole+1) if item_type == 'order': mainlog.debug("FindOrder.selected_item order_id={}".format(item)) return dao.order_dao.find_by_id(item) elif item_type == 'order_part': mainlog.debug("FindOrder.selected_item order_part_id={}".format(item)) return dao.order_part_dao.find_by_id(item) else: mainlog.error("Unsupported item type {}".format(item_type)) else: mainlog.error("Invalid index") return None @Slot() def accept(self): # mainlog.debug("accept") # self.load_search_results() # mainlog.debug("accept - done") return super(FindOrderDialog,self).accept() @Slot() def reject(self): return super(FindOrderDialog,self).reject() @Slot() def search_criteria_submitted(self): mainlog.debug("search_criteria_submitted") self.load_search_results() @Slot(QModelIndex) def row_activated(self,ndx): mainlog.debug("row_activated") self.accept() def keyPressEvent(self,event): # The goal here is to make sure the accept signal is called only # if the user clicks on the "OK" button /with the mouse/ and, # not with the keyboard if event.key() in (Qt.Key_Enter, Qt.Key_Return): return else: super(FindOrderDialog,self).keyPressEvent(event)