def __init__(self, prompt='>>> ', continuation='... ', parent=None): QTextEdit.__init__(self, parent) self.shutting_down = False self.compiler = CommandCompiler() self.buf = self.old_buf = [] self.history = History([''], dynamic.get('console_history', [])) self.prompt_frame = None self.allow_output = False self.prompt_frame_format = QTextFrameFormat() self.prompt_frame_format.setBorder(1) self.prompt_frame_format.setBorderStyle(QTextFrameFormat.BorderStyle_Solid) self.prompt_len = len(prompt) self.doc.setMaximumBlockCount(int(prefs['scrollback'])) self.lexer = PythonLexer(ensurenl=False) self.tb_lexer = PythonTracebackLexer() self.context_menu = cm = QMenu(self) # {{{ cm.theme = ThemeMenu(cm) # }}} self.formatter = Formatter(prompt, continuation, style=prefs['theme']) p = QPalette() p.setColor(p.Base, QColor(self.formatter.background_color)) p.setColor(p.Text, QColor(self.formatter.color)) self.setPalette(p) self.key_dispatcher = { # {{{ Qt.Key_Enter : self.enter_pressed, Qt.Key_Return : self.enter_pressed, Qt.Key_Up : self.up_pressed, Qt.Key_Down : self.down_pressed, Qt.Key_Home : self.home_pressed, Qt.Key_End : self.end_pressed, Qt.Key_Left : self.left_pressed, Qt.Key_Right : self.right_pressed, Qt.Key_Backspace : self.backspace_pressed, Qt.Key_Delete : self.delete_pressed, } # }}} motd = textwrap.dedent('''\ # Python {0} # {1} {2} '''.format(sys.version.splitlines()[0], __appname__, __version__)) sys.excepthook = self.unhandled_exception self.controllers = [] QTimer.singleShot(0, self.launch_controller) with EditBlock(self.cursor): self.render_block(motd)
def keyPressEvent(self, ev): text = unicode(ev.text()) key = ev.key() action = self.key_dispatcher.get(key, None) if callable(action): action() elif key in (Qt.Key_Escape,): QTextEdit.keyPressEvent(self, ev) elif text: self.text_typed(text) else: QTextEdit.keyPressEvent(self, ev)
def setup_ui(self): self.splitter = QSplitter(self) self.l = l = QVBoxLayout(self) l.addWidget(self.splitter) l.addWidget(self.bb) self.w = w = QGroupBox(_('Theme Metadata'), self) self.splitter.addWidget(w) l = w.l = QFormLayout(w) self.missing_icons_group = mg = QGroupBox(self) self.mising_icons = mi = QListWidget(mg) mi.setSelectionMode(mi.NoSelection) mg.l = QVBoxLayout(mg) mg.l.addWidget(mi) self.splitter.addWidget(mg) self.title = QLineEdit(self) l.addRow(_('&Title:'), self.title) self.author = QLineEdit(self) l.addRow(_('&Author:'), self.author) self.version = v = QSpinBox(self) v.setMinimum(1), v.setMaximum(1000000) l.addRow(_('&Version:'), v) self.description = QTextEdit(self) l.addRow(self.description) self.refresh_button = rb = self.bb.addButton(_('&Refresh'), self.bb.ActionRole) rb.setIcon(QIcon(I('view-refresh.png'))) rb.clicked.connect(self.refresh) self.apply_report()
def _init_controls(self): layout = QVBoxLayout(self) self.setLayout(layout) ml = QHBoxLayout() layout.addLayout(ml, 1) self.keys_list = QListWidget(self) self.keys_list.setSelectionMode(QAbstractItemView.SingleSelection) self.keys_list.setFixedWidth(150) self.keys_list.setAlternatingRowColors(True) ml.addWidget(self.keys_list) self.value_text = QTextEdit(self) self.value_text.setTabStopWidth(24) self.value_text.setReadOnly(False) ml.addWidget(self.value_text, 1) button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) button_box.accepted.connect(self._apply_changes) button_box.rejected.connect(self.reject) self.clear_button = button_box.addButton('Clear', QDialogButtonBox.ResetRole) self.clear_button.setIcon(get_icon('trash.png')) self.clear_button.setToolTip('Clear all settings for this plugin') self.clear_button.clicked.connect(self._clear_settings) layout.addWidget(button_box)
class VersionHistoryDialog(SizePersistedDialog): def __init__(self, parent, plugin_name, html): SizePersistedDialog.__init__(self, parent, 'Plugin Updater plugin:version history dialog') self.setWindowTitle(_('Version History for %s')%plugin_name) layout = QVBoxLayout(self) self.setLayout(layout) self.notes = QTextEdit(html, self) self.notes.setReadOnly(True) layout.addWidget(self.notes) self.button_box = QDialogButtonBox(QDialogButtonBox.Close) self.button_box.rejected.connect(self.reject) layout.addWidget(self.button_box) # Cause our dialog size to be restored from prefs or created on first usage self.resize_dialog()
def __init__(self, parent=None): super(EditQDialog, self).__init__(parent) self.setWindowTitle('Edit Dialog') self.setWindowFlags(Qt.FramelessWindowHint) self.setStyleSheet(settings.css_style) self.setWindowIcon(QIcon(settings.get_image('icon'))) self.setObjectName('dialog') self.setFixedSize(300, 300) # Fields self.text_edit = QTextEdit() self.old_text = ''
def __init__(self, src, dest): QMainWindow.__init__(self) self.setMinimumSize(QSize(640, 160)) self.setWindowTitle("Copy Images") self.centralWidget = QWidget(self) self.setCentralWidget(self.centralWidget) self.layout = QVBoxLayout(self.centralWidget) self.source = QPushButton("Select src file (.txt list file of images)") self.layout.addWidget(self.source) self.source.released.connect(self.selectSource) self.destination = QPushButton( "Select dest folder to copy the images to") self.layout.addWidget(self.destination) self.destination.released.connect(self.selectDestination) run = QPushButton("Start copy process") self.layout.addWidget(run) run.released.connect(self.copyFiles) self.textOutput = QTextEdit() self.layout.addWidget(self.textOutput) self.sourcePath = None self.destinationPath = None if None != src: self.selectSource(src) if None != dest: self.selectDestination(dest) self.copyThread = copyThread(src, dest) self.copyThread.newText.connect(self.writeText)
def _init_controls(self): layout = QVBoxLayout(self) self.setLayout(layout) ml = QHBoxLayout() layout.addLayout(ml, 1) self.keys_list = QListWidget(self) self.keys_list.setSelectionMode(QAbstractItemView.SingleSelection) self.keys_list.setFixedWidth(150) self.keys_list.setAlternatingRowColors(True) ml.addWidget(self.keys_list) self.value_text = QTextEdit(self) self.value_text.setReadOnly(True) ml.addWidget(self.value_text, 1) button_box = QDialogButtonBox(QDialogButtonBox.Ok) button_box.accepted.connect(self.accept) self.clear_button = button_box.addButton(_('Clear'), QDialogButtonBox.ResetRole) self.clear_button.setIcon(get_icon('trash.png')) self.clear_button.setToolTip(_('Clear all settings for this plugin')) self.clear_button.clicked.connect(self._clear_settings) if DEBUG: self.edit_button = button_box.addButton(_('Edit'), QDialogButtonBox.ResetRole) self.edit_button.setIcon(get_icon('edit_input.png')) self.edit_button.setToolTip(_('Edit settings.')) self.edit_button.clicked.connect(self._edit_settings) self.save_button = button_box.addButton(_('Save'), QDialogButtonBox.ResetRole) self.save_button.setIcon(get_icon('save.png')) self.save_button.setToolTip(_('Save setting for this plugin')) self.save_button.clicked.connect(self._save_settings) self.save_button.setEnabled(False) layout.addWidget(button_box)
def keyPressEvent(self, ev): if ev.matches(QKeySequence.StandardKey.Bold): ev.accept() self.action_bold.toggle(), self.action_bold.trigger() return if ev.matches(QKeySequence.StandardKey.Italic): ev.accept() self.action_italic.toggle(), self.action_italic.trigger() return if ev.matches(QKeySequence.StandardKey.Underline): ev.accept() self.action_underline.toggle(), self.action_underline.trigger() return return QTextEdit.keyPressEvent(self, ev)
def setup_ui(self): self.splitter = QSplitter(self) self.l = l = QVBoxLayout(self) l.addWidget(self.splitter) l.addWidget(self.bb) self.w = w = QGroupBox(_('Theme Metadata'), self) self.splitter.addWidget(w) l = w.l = QFormLayout(w) l.setFieldGrowthPolicy(l.ExpandingFieldsGrow) self.missing_icons_group = mg = QGroupBox(self) self.mising_icons = mi = QListWidget(mg) mi.setSelectionMode(mi.NoSelection) mg.l = QVBoxLayout(mg) mg.l.addWidget(mi) self.splitter.addWidget(mg) self.title = QLineEdit(self) l.addRow(_('&Title:'), self.title) self.author = QLineEdit(self) l.addRow(_('&Author:'), self.author) self.version = v = QSpinBox(self) v.setMinimum(1), v.setMaximum(1000000) l.addRow(_('&Version:'), v) self.license = lc = QLineEdit(self) l.addRow(_('&License:'), lc) self.url = QLineEdit(self) l.addRow(_('&URL:'), self.url) lc.setText( _('The license for the icons in this theme. Common choices are' ' Creative Commons or Public Domain.')) self.description = QTextEdit(self) l.addRow(self.description) self.refresh_button = rb = self.bb.addButton(_('&Refresh'), self.bb.ActionRole) rb.setIcon(QIcon(I('view-refresh.png'))) rb.clicked.connect(self.refresh) self.apply_report()
class LineTextWidget(QFrame): def __init__(self, cur_pos_label, *args): QFrame.__init__(self, *args) self.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) self.edit = QTextEdit() self.edit.setFrameStyle(QFrame.NoFrame) self.edit.setAcceptRichText(False) self.edit.cursorPositionChanged.connect(self.cursorPositionChanged) self.number_bar = NumberBar() self.number_bar.setTextEdit(self.edit) hbox = QHBoxLayout(self) hbox.setSpacing(0) hbox.setContentsMargins(0, 0, 0, 0) hbox.addWidget(self.number_bar) hbox.addWidget(self.edit) self.edit.installEventFilter(self) self.edit.viewport().installEventFilter(self) self.cur_pos_label = cur_pos_label def eventFilter(self, object, event): if object in (self.edit, self.edit.viewport()): self.number_bar.update() return False return QFrame.eventFilter(object, event) def cursorPositionChanged(self): cur_cursor = self.edit.textCursor() self.cur_pos_label.setText(f'Ln {self.edit.textCursor().blockNumber()}, Col {self.edit.textCursor().columnNumber()}') def getTextEdit(self): return self.edit
def do_test(self): selections = [] self.match_locs = [] if self.regex_valid(): text = unicode(self.preview.toPlainText()) regex = unicode(self.regex.text()) cursor = QTextCursor(self.preview.document()) extsel = QTextEdit.ExtraSelection() extsel.cursor = cursor extsel.format.setBackground(QBrush(Qt.yellow)) try: for match in re.finditer(regex, text): es = QTextEdit.ExtraSelection(extsel) es.cursor.setPosition(match.start(), QTextCursor.MoveAnchor) es.cursor.setPosition(match.end(), QTextCursor.KeepAnchor) selections.append(es) self.match_locs.append((match.start(), match.end())) except: pass self.preview.setExtraSelections(selections) if self.match_locs: self.next.setEnabled(True) self.previous.setEnabled(True) self.occurrences.setText(str(len(self.match_locs)))
def createDescriptionFile(self, name, path_file): file_name = "description.html" file = open(os.path.join(Config().instance.settings.value("global/resources_path"),"template_profil.html")) ddd = file.read() print ('ooooo',type(ddd)) ddd = ddd.replace("tname",name) print ('mmmm',ddd) chemin = os.path.join(path_file,file_name) if (not os.path.exists(chemin)): self.textEdit = QTextEdit() self.textEdit.setText(ddd) writer = QTextDocumentWriter(chemin) success = writer.write(self.textEdit.document())
def setup_ui(self, window): window.setObjectName("MainWindow") window.showMaximized() bt = QPushButton('Submit', window) bt.move(480, 480) bt.setToolTip("This is a <a style=\"color:red\">button</a>!") bt.clicked.connect(lambda: print("Hi,mouse.")) bt.show() text_box = QTextEdit(window) text_box.move(180, 50) text_box.resize(700, 400) text_box.show() timer = QtCore.QTimer(window) timer.timeout.connect(lambda: print("aaa")) timer.start(1000) timer.timeout.connect(lambda: print("aaa"))
def _init_controls(self): layout = QVBoxLayout(self) self.setLayout(layout) ml = QHBoxLayout() layout.addLayout(ml, 1) self.keys_list = QListWidget(self) self.keys_list.setSelectionMode(QAbstractItemView.SingleSelection) self.keys_list.setFixedWidth(150) self.keys_list.setAlternatingRowColors(True) ml.addWidget(self.keys_list) self.value_text = QTextEdit(self) self.value_text.setTabStopWidth(24) self.value_text.setReadOnly(True) ml.addWidget(self.value_text, 1) button_box = QDialogButtonBox(QDialogButtonBox.Ok) button_box.accepted.connect(self.accept) self.clear_button = button_box.addButton('Clear', QDialogButtonBox.ResetRole) self.clear_button.setIcon(get_icon('trash.png')) self.clear_button.setToolTip('Clear all settings for this plugin') self.clear_button.clicked.connect(self._clear_settings) layout.addWidget(button_box)
def __init__(self, parent=None): super(DownQDialog, self).__init__(parent) self.setWindowTitle(_('Request a Downtime')) self.setWindowFlags(Qt.FramelessWindowHint) self.setStyleSheet(settings.css_style) self.setWindowIcon(QIcon(settings.get_image('icon'))) self.setMinimumSize(360, 460) self.setObjectName('dialog') # Fields self.fixed = True self.fixed_toggle_btn = ToggleQWidgetButton() self.duration = QTimeEdit() self.start_time = QDateTimeEdit() self.end_time = QDateTimeEdit() self.comment_edit = QTextEdit() self.offset = None
def add_tag(tag): a = QTextEdit.ExtraSelection() a.cursor, a.format = editor.textCursor(), editor.match_paren_format a.cursor.setPosition( tag.start_block.position()), a.cursor.movePosition( a.cursor.EndOfBlock, a.cursor.KeepAnchor) text = unicode(a.cursor.selectedText()) start_pos = utf16_length(text[:tag.start_offset]) a.cursor.setPosition( tag.end_block.position()), a.cursor.movePosition( a.cursor.EndOfBlock, a.cursor.KeepAnchor) text = unicode(a.cursor.selectedText()) end_pos = utf16_length(text[:tag.end_offset + 1]) a.cursor.setPosition(tag.start_block.position() + start_pos) a.cursor.setPosition(tag.end_block.position() + end_pos, a.cursor.KeepAnchor) ans.append(a)
def highlight_cursor_line(self): sel = QTextEdit.ExtraSelection() sel.format.setBackground(self.palette().alternateBase()) sel.format.setProperty(QTextFormat.FullWidthSelection, True) sel.cursor = self.textCursor() sel.cursor.clearSelection() self.current_cursor_line = sel self.update_extra_selections(instant=False) # Update the cursor line's line number in the line number area try: self.line_number_area.update(0, self.last_current_lnum[0], self.line_number_area.width(), self.last_current_lnum[1]) except AttributeError: pass block = self.textCursor().block() top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top()) height = int(self.blockBoundingRect(block).height()) self.line_number_area.update(0, top, self.line_number_area.width(), height)
class Example(TestableWidget): # ------------------------------------------------------------------------- def __init__(self): TestableWidget.__init__(self, None) self.text = QTextEdit() self.btn_msgbox = QPushButton("QMessageBox") self.btn_mydlg = QPushButton("My Dlg") self.init_ui() # ------------------------------------------------------------------------- def init_ui(self): self.setGeometry(900, 300, 500, 320) self.setWindowTitle('Simple APP') v = QVBoxLayout() self.text.setText( "In ten hours a day you have time to fall twice as far " + "behind your commitments as in five hours a day.\n" + "CORRECT:\n" + "Data expands to fill the space available for storage.") self.btn_msgbox.clicked.connect(self.msgbox) self.btn_mydlg.clicked.connect(self.mydlg) v.addWidget(self.text, alignment=Qt.Alignment()) v.addWidget(self.btn_msgbox, alignment=Qt.Alignment()) v.addWidget(self.btn_mydlg, alignment=Qt.Alignment()) self.setLayout(v) # ------------------------------------------------------------------------- def msgbox(self): msg = TestableMessageBox() msg.setIcon(QMessageBox.Information) text = self.text.textCursor().selection().toPlainText() msg.setText(text) msg.setWindowTitle("MessageBox") msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) retval = msg.exec_() if retval == QMessageBox.Ok: self.text.textCursor().insertText("ERROR for computers") # ------------------------------------------------------------------------- def mydlg(self): dlg = ExampleDlg(self) dlg.exec_() if dlg.result: self.text.textCursor().insertText(dlg.text.toPlainText())
class _ResponsesTab(QTabWidget): """Tab which shows all module and shell responses.""" def __init__(self): super().__init__() layout = QVBoxLayout() self._output_field = QTextEdit() self._output_field.setTextInteractionFlags(Qt.NoTextInteraction) self._output_field.setPlaceholderText("Please wait for responses...") layout.addWidget(self._output_field) self.setLayout(layout) def clear(self): """Clears all output.""" self._output_field.clear() def output(self, text: str): """Adds a line to the output field.""" self._output_field.append(text)
def manual_input(self): self.status_label.setText("") edit_dialog = QDialog(self) verticalLayout = QVBoxLayout(edit_dialog) title_input = QLineEdit('title here', edit_dialog) editor = QTextEdit(edit_dialog) verticalLayout.addWidget(title_input) verticalLayout.addWidget(editor) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.manual_input_text = "" self.manual_input_title = "" def editor_accepted(): if editor.toPlainText(): self.manual_input_text = editor.toHtml() self.manual_input_title = title_input.text().strip() edit_dialog.close() def editor_rejected(): edit_dialog.close() buttonBox.accepted.connect(editor_accepted) buttonBox.rejected.connect(editor_rejected) verticalLayout.addWidget(buttonBox) edit_dialog.exec_() if self.manual_input_text: existing_doc_id_list_part = [] # existing feed id between now and mark conn = sqlite3.connect(get_path("user_files", "doc.db"), detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES) cur = conn.cursor() cur.execute("select feed_id from doc where feed_id between ? and ?", (int(time.time()*1000), int(time.time()*1000)+10000)) while True: doc_id = int(time.time()*1000) if doc_id not in existing_doc_id_list_part: break cur.execute("""insert into doc (doc_id, title, descr, doc_type) values (?, ?, ?, 'mi')""", (doc_id, self.manual_input_title, self.manual_input_text)) conn.commit() conn.close() self.manual_input_text = "" self.status_label.setText("Manual Load Completed")
def setup_ui(self): self.splitter = QSplitter(self) self.l = l = QVBoxLayout(self) l.addWidget(self.splitter) l.addWidget(self.bb) self.w = w = QGroupBox(_('Theme Metadata'), self) self.splitter.addWidget(w) l = w.l = QFormLayout(w) l.setFieldGrowthPolicy(l.ExpandingFieldsGrow) self.missing_icons_group = mg = QGroupBox(self) self.mising_icons = mi = QListWidget(mg) mi.setSelectionMode(mi.NoSelection) mg.l = QVBoxLayout(mg) mg.l.addWidget(mi) self.splitter.addWidget(mg) self.title = QLineEdit(self) l.addRow(_('&Title:'), self.title) self.author = QLineEdit(self) l.addRow(_('&Author:'), self.author) self.version = v = QSpinBox(self) v.setMinimum(1), v.setMaximum(1000000) l.addRow(_('&Version:'), v) self.license = lc = QLineEdit(self) l.addRow(_('&License:'), lc) self.url = QLineEdit(self) l.addRow(_('&URL:'), self.url) lc.setText(_( 'The license for the icons in this theme. Common choices are' ' Creative Commons or Public Domain.')) self.description = QTextEdit(self) l.addRow(self.description) self.refresh_button = rb = self.bb.addButton(_('&Refresh'), self.bb.ActionRole) rb.setIcon(QIcon(I('view-refresh.png'))) rb.clicked.connect(self.refresh) self.apply_report()
def _init_controls(self): layout = QVBoxLayout(self) self.setLayout(layout) ml = QHBoxLayout() layout.addLayout(ml, 1) self.keys_list = QListWidget(self) self.keys_list.setSelectionMode(QAbstractItemView.SingleSelection) self.keys_list.setFixedWidth(150) self.keys_list.setAlternatingRowColors(True) ml.addWidget(self.keys_list) self.value_text = QTextEdit(self) self.value_text.setTabStopWidth(24) self.value_text.setReadOnly(True) ml.addWidget(self.value_text, 1) button_box = QDialogButtonBox(QDialogButtonBox.Ok) button_box.accepted.connect(self.accept) self.clear_button = button_box.addButton(_('Clear'), QDialogButtonBox.ResetRole) self.clear_button.setIcon(get_icon('trash.png')) self.clear_button.setToolTip(_('Clear all settings for this plugin')) self.clear_button.clicked.connect(self._clear_settings) if DEBUG: self.edit_button = button_box.addButton(_('Edit'), QDialogButtonBox.ResetRole) self.edit_button.setIcon(get_icon('edit_input.png')) self.edit_button.setToolTip(_('Edit settings.')) self.edit_button.clicked.connect(self._edit_settings) self.save_button = button_box.addButton(_('Save'), QDialogButtonBox.ResetRole) self.save_button.setIcon(get_icon('save.png')) self.save_button.setToolTip(_('Save setting for this plugin')) self.save_button.clicked.connect(self._save_settings) self.save_button.setEnabled(False) layout.addWidget(button_box)
class PrefsViewerDialog(SizePersistedDialog): def __init__(self, gui, namespace): SizePersistedDialog.__init__(self, gui, _('Prefs Viewer dialog')) self.setWindowTitle(_('Preferences for: ')+namespace) self.gui = gui self.db = gui.current_db self.namespace = namespace self._init_controls() self.resize_dialog() self._populate_settings() if self.keys_list.count(): self.keys_list.setCurrentRow(0) def _init_controls(self): layout = QVBoxLayout(self) self.setLayout(layout) ml = QHBoxLayout() layout.addLayout(ml, 1) self.keys_list = QListWidget(self) self.keys_list.setSelectionMode(QAbstractItemView.SingleSelection) self.keys_list.setFixedWidth(150) self.keys_list.setAlternatingRowColors(True) ml.addWidget(self.keys_list) self.value_text = QTextEdit(self) self.value_text.setTabStopWidth(24) self.value_text.setReadOnly(True) ml.addWidget(self.value_text, 1) button_box = QDialogButtonBox(QDialogButtonBox.Ok) button_box.accepted.connect(self.accept) self.clear_button = button_box.addButton(_('Clear'), QDialogButtonBox.ResetRole) self.clear_button.setIcon(get_icon('trash.png')) self.clear_button.setToolTip(_('Clear all settings for this plugin')) self.clear_button.clicked.connect(self._clear_settings) if DEBUG: self.edit_button = button_box.addButton(_('Edit'), QDialogButtonBox.ResetRole) self.edit_button.setIcon(get_icon('edit_input.png')) self.edit_button.setToolTip(_('Edit settings.')) self.edit_button.clicked.connect(self._edit_settings) self.save_button = button_box.addButton(_('Save'), QDialogButtonBox.ResetRole) self.save_button.setIcon(get_icon('save.png')) self.save_button.setToolTip(_('Save setting for this plugin')) self.save_button.clicked.connect(self._save_settings) self.save_button.setEnabled(False) layout.addWidget(button_box) def _populate_settings(self): self.keys_list.clear() ns_prefix = self._get_ns_prefix() keys = sorted([k[len(ns_prefix):] for k in self.db.prefs.iterkeys() if k.startswith(ns_prefix)]) for key in keys: self.keys_list.addItem(key) self.keys_list.setMinimumWidth(self.keys_list.sizeHintForColumn(0)) self.keys_list.currentRowChanged[int].connect(self._current_row_changed) def _current_row_changed(self, new_row): if new_row < 0: self.value_text.clear() return key = unicode(self.keys_list.currentItem().text()) val = self.db.prefs.get_namespaced(self.namespace, key, '') self.value_text.setPlainText(self.db.prefs.to_raw(val)) def _get_ns_prefix(self): return 'namespaced:%s:'% self.namespace def _edit_settings(self): from calibre.gui2.dialogs.confirm_delete import confirm message = '<p>' + _('Are you sure you want to edit settings in this library for this plugin?') + '</p>' \ + '<p>' + _('The FanFicFare team does not support hand edited configurations.') + '</p>' if confirm(message, self.namespace+'_edit_settings', self): self.save_button.setEnabled(True) self.edit_button.setEnabled(False) self.value_text.setReadOnly(False) def _save_settings(self): from calibre.gui2.dialogs.confirm_delete import confirm message = '<p>' + _('Are you sure you want to save this setting in this library for this plugin?') + '</p>' \ + '<p>' + _('Any settings in other libraries or stored in a JSON file in your calibre plugins folder will not be touched.') + '</p>' \ + '<p>' + _('You must restart calibre afterwards.') + '</p>' if not confirm(message, self.namespace+'_save_settings', self): return ns_prefix = self._get_ns_prefix() key = unicode(self.keys_list.currentItem().text()) self.db.prefs.set_namespaced(self.namespace, key, self.db.prefs.raw_to_object(self.value_text.toPlainText())) d = info_dialog(self, 'Settings saved', '<p>' + _('All settings for this plugin in this library have been saved.') + '</p>' \ + '<p>' + _('Please restart calibre now.') + '</p>', show_copy_button=False) b = d.bb.addButton(_('Restart calibre now'), d.bb.AcceptRole) b.setIcon(QIcon(I('lt.png'))) d.do_restart = False def rf(): d.do_restart = True b.clicked.connect(rf) d.set_details('') d.exec_() b.clicked.disconnect() self.close() if d.do_restart: self.gui.quit(restart=True) def _clear_settings(self): from calibre.gui2.dialogs.confirm_delete import confirm message = '<p>' + _('Are you sure you want to clear your settings in this library for this plugin?') + '</p>' \ + '<p>' + _('Any settings in other libraries or stored in a JSON file in your calibre plugins folder will not be touched.') + '</p>' \ + '<p>' + _('You must restart calibre afterwards.') + '</p>' if not confirm(message, self.namespace+'_clear_settings', self): return ns_prefix = self._get_ns_prefix() keys = [k for k in self.db.prefs.iterkeys() if k.startswith(ns_prefix)] for k in keys: del self.db.prefs[k] self._populate_settings() d = info_dialog(self, 'Settings deleted', '<p>' + _('All settings for this plugin in this library have been cleared.') + '</p>' \ + '<p>' + _('Please restart calibre now.') + '</p>', show_copy_button=False) b = d.bb.addButton(_('Restart calibre now'), d.bb.AcceptRole) b.setIcon(QIcon(I('lt.png'))) d.do_restart = False def rf(): d.do_restart = True b.clicked.connect(rf) d.set_details('') d.exec_() b.clicked.disconnect() self.close() if d.do_restart: self.gui.quit(restart=True)
class Config(QDialog): ''' Configuration dialog for single book conversion. If accepted, has the following important attributes output_format - Output format (without a leading .) input_format - Input format (without a leading .) opf_path - Path to OPF file with user specified metadata cover_path - Path to user specified cover (can be None) recommendations - A pickled list of 3 tuples in the same format as the recommendations member of the Input/Output plugins. ''' def __init__(self, parent, db, book_id, preferred_input_format=None, preferred_output_format=None): QDialog.__init__(self, parent) self.setupUi() self.opt_individual_saved_settings.setVisible(False) self.db, self.book_id = db, book_id self.setup_input_output_formats(self.db, self.book_id, preferred_input_format, preferred_output_format) self.setup_pipeline() self.input_formats.currentIndexChanged[native_string_type].connect( self.setup_pipeline) self.output_formats.currentIndexChanged[native_string_type].connect( self.setup_pipeline) self.groups.setSpacing(5) self.groups.activated[(QModelIndex)].connect(self.show_pane) self.groups.clicked[(QModelIndex)].connect(self.show_pane) self.groups.entered[(QModelIndex)].connect(self.show_group_help) rb = self.buttonBox.button(self.buttonBox.RestoreDefaults) rb.setText(_('Restore &defaults')) rb.clicked.connect(self.restore_defaults) self.groups.setMouseTracking(True) geom = gprefs.get('convert_single_dialog_geom', None) if geom: self.restoreGeometry(geom) else: self.resize(self.sizeHint()) def setupUi(self): self.setObjectName("Dialog") self.resize(1024, 700) self.setWindowIcon(QIcon(I('convert.png'))) self.gridLayout = QGridLayout(self) self.gridLayout.setObjectName("gridLayout") self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.input_label = QLabel(self) self.input_label.setObjectName("input_label") self.horizontalLayout.addWidget(self.input_label) self.input_formats = QComboBox(self) self.input_formats.setSizeAdjustPolicy( QComboBox.AdjustToMinimumContentsLengthWithIcon) self.input_formats.setMinimumContentsLength(5) self.input_formats.setObjectName("input_formats") self.horizontalLayout.addWidget(self.input_formats) self.opt_individual_saved_settings = QCheckBox(self) self.opt_individual_saved_settings.setObjectName( "opt_individual_saved_settings") self.horizontalLayout.addWidget(self.opt_individual_saved_settings) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.label_2 = QLabel(self) self.label_2.setObjectName("label_2") self.horizontalLayout.addWidget(self.label_2) self.output_formats = QComboBox(self) self.output_formats.setSizeAdjustPolicy( QComboBox.AdjustToMinimumContentsLengthWithIcon) self.output_formats.setMinimumContentsLength(5) self.output_formats.setObjectName("output_formats") self.horizontalLayout.addWidget(self.output_formats) self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 2) self.groups = QListView(self) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.groups.sizePolicy().hasHeightForWidth()) self.groups.setSizePolicy(sizePolicy) self.groups.setTabKeyNavigation(True) self.groups.setIconSize(QSize(48, 48)) self.groups.setWordWrap(True) self.groups.setObjectName("groups") self.gridLayout.addWidget(self.groups, 1, 0, 3, 1) self.scrollArea = QScrollArea(self) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(4) sizePolicy.setVerticalStretch(10) sizePolicy.setHeightForWidth( self.scrollArea.sizePolicy().hasHeightForWidth()) self.scrollArea.setSizePolicy(sizePolicy) self.scrollArea.setFrameShape(QFrame.NoFrame) self.scrollArea.setLineWidth(0) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName("scrollArea") self.scrollAreaWidgetContents = QWidget() self.scrollAreaWidgetContents.setGeometry(QRect(0, 0, 810, 494)) self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") self.verticalLayout_3 = QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout_3.setContentsMargins(0, 0, 0, 0) self.verticalLayout_3.setObjectName("verticalLayout_3") self.stack = QStackedWidget(self.scrollAreaWidgetContents) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.stack.sizePolicy().hasHeightForWidth()) self.stack.setSizePolicy(sizePolicy) self.stack.setObjectName("stack") self.page = QWidget() self.page.setObjectName("page") self.stack.addWidget(self.page) self.page_2 = QWidget() self.page_2.setObjectName("page_2") self.stack.addWidget(self.page_2) self.verticalLayout_3.addWidget(self.stack) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.gridLayout.addWidget(self.scrollArea, 1, 1, 1, 1) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok | QDialogButtonBox.RestoreDefaults) self.buttonBox.setObjectName("buttonBox") self.gridLayout.addWidget(self.buttonBox, 3, 1, 1, 1) self.help = QTextEdit(self) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.help.sizePolicy().hasHeightForWidth()) self.help.setSizePolicy(sizePolicy) self.help.setMaximumHeight(80) self.help.setObjectName("help") self.gridLayout.addWidget(self.help, 2, 1, 1, 1) self.input_label.setBuddy(self.input_formats) self.label_2.setBuddy(self.output_formats) self.input_label.setText(_("&Input format:")) self.opt_individual_saved_settings.setText( _("Use &saved conversion settings for individual books")) self.label_2.setText(_("&Output format:")) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def sizeHint(self): desktop = QCoreApplication.instance().desktop() geom = desktop.availableGeometry(self) nh, nw = max(300, geom.height() - 100), max(400, geom.width() - 70) return QSize(nw, nh) def restore_defaults(self): delete_specifics(self.db, self.book_id) self.setup_pipeline() @property def input_format(self): return unicode_type(self.input_formats.currentText()).lower() @property def output_format(self): return unicode_type(self.output_formats.currentText()).lower() @property def manually_fine_tune_toc(self): for i in range(self.stack.count()): w = self.stack.widget(i) if hasattr(w, 'manually_fine_tune_toc'): return w.manually_fine_tune_toc.isChecked() def setup_pipeline(self, *args): oidx = self.groups.currentIndex().row() input_format = self.input_format output_format = self.output_format self.plumber = create_dummy_plumber(input_format, output_format) def widget_factory(cls): return cls(self.stack, self.plumber.get_option_by_name, self.plumber.get_option_help, self.db, self.book_id) self.mw = widget_factory(MetadataWidget) self.setWindowTitle( _('Convert') + ' ' + unicode_type(self.mw.title.text())) lf = widget_factory(LookAndFeelWidget) hw = widget_factory(HeuristicsWidget) sr = widget_factory(SearchAndReplaceWidget) ps = widget_factory(PageSetupWidget) sd = widget_factory(StructureDetectionWidget) toc = widget_factory(TOCWidget) from calibre.gui2.actions.toc_edit import SUPPORTED toc.manually_fine_tune_toc.setVisible( output_format.upper() in SUPPORTED) debug = widget_factory(DebugWidget) output_widget = self.plumber.output_plugin.gui_configuration_widget( self.stack, self.plumber.get_option_by_name, self.plumber.get_option_help, self.db, self.book_id) input_widget = self.plumber.input_plugin.gui_configuration_widget( self.stack, self.plumber.get_option_by_name, self.plumber.get_option_help, self.db, self.book_id) while True: c = self.stack.currentWidget() if not c: break self.stack.removeWidget(c) widgets = [self.mw, lf, hw, ps, sd, toc, sr] if input_widget is not None: widgets.append(input_widget) if output_widget is not None: widgets.append(output_widget) widgets.append(debug) for w in widgets: self.stack.addWidget(w) w.set_help_signal.connect(self.help.setPlainText) self._groups_model = GroupModel(widgets) self.groups.setModel(self._groups_model) idx = oidx if -1 < oidx < self._groups_model.rowCount() else 0 self.groups.setCurrentIndex(self._groups_model.index(idx)) self.stack.setCurrentIndex(idx) try: shutil.rmtree(self.plumber.archive_input_tdir, ignore_errors=True) except: pass def setup_input_output_formats(self, db, book_id, preferred_input_format, preferred_output_format): if preferred_output_format: preferred_output_format = preferred_output_format.upper() output_formats = get_output_formats(preferred_output_format) input_format, input_formats = get_input_format_for_book( db, book_id, preferred_input_format) preferred_output_format = preferred_output_format if \ preferred_output_format in output_formats else \ sort_formats_by_preference(output_formats, [prefs['output_format']])[0] self.input_formats.addItems( (unicode_type(x.upper()) for x in input_formats)) self.output_formats.addItems( (unicode_type(x.upper()) for x in output_formats)) self.input_formats.setCurrentIndex(input_formats.index(input_format)) self.output_formats.setCurrentIndex( output_formats.index(preferred_output_format)) def show_pane(self, index): self.stack.setCurrentIndex(index.row()) def accept(self): recs = GuiRecommendations() for w in self._groups_model.widgets: if not w.pre_commit_check(): return x = w.commit(save_defaults=False) recs.update(x) self.opf_file, self.cover_file = self.mw.opf_file, self.mw.cover_file self._recommendations = recs if self.db is not None: recs['gui_preferred_input_format'] = self.input_format save_specifics(self.db, self.book_id, recs) self.break_cycles() QDialog.accept(self) def reject(self): self.break_cycles() QDialog.reject(self) def done(self, r): if self.isVisible(): gprefs['convert_single_dialog_geom'] = \ bytearray(self.saveGeometry()) return QDialog.done(self, r) def break_cycles(self): for i in range(self.stack.count()): w = self.stack.widget(i) w.break_cycles() @property def recommendations(self): recs = [(k, v, OptionRecommendation.HIGH) for k, v in self._recommendations.items()] return recs def show_group_help(self, index): widget = self._groups_model.widgets[index.row()] self.help.setPlainText(widget.HELP)
class PrefsViewerDialog(SizePersistedDialog): def __init__(self, gui, namespace): SizePersistedDialog.__init__(self, gui, 'Prefs Viewer dialog') self.setWindowTitle('Preferences for: '+namespace) self.gui = gui self.db = gui.current_db self.namespace = namespace self._init_controls() self.resize_dialog() self._populate_settings() if self.keys_list.count(): self.keys_list.setCurrentRow(0) def _init_controls(self): layout = QVBoxLayout(self) self.setLayout(layout) ml = QHBoxLayout() layout.addLayout(ml, 1) self.keys_list = QListWidget(self) self.keys_list.setSelectionMode(QAbstractItemView.SingleSelection) self.keys_list.setFixedWidth(150) self.keys_list.setAlternatingRowColors(True) ml.addWidget(self.keys_list) self.value_text = QTextEdit(self) self.value_text.setTabStopWidth(24) self.value_text.setReadOnly(False) ml.addWidget(self.value_text, 1) button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) button_box.accepted.connect(self._apply_changes) button_box.rejected.connect(self.reject) self.clear_button = button_box.addButton('Clear', QDialogButtonBox.ResetRole) self.clear_button.setIcon(get_icon('trash.png')) self.clear_button.setToolTip('Clear all settings for this plugin') self.clear_button.clicked.connect(self._clear_settings) layout.addWidget(button_box) def _populate_settings(self): self.keys_list.clear() ns_prefix = self._get_ns_prefix() keys = sorted([k[len(ns_prefix):] for k in self.db.prefs.iterkeys() if k.startswith(ns_prefix)]) for key in keys: self.keys_list.addItem(key) self.keys_list.setMinimumWidth(self.keys_list.sizeHintForColumn(0)) self.keys_list.currentRowChanged[int].connect(self._current_row_changed) def _current_row_changed(self, new_row): if new_row < 0: self.value_text.clear() return key = unicode(self.keys_list.currentItem().text()) val = self.db.prefs.get_namespaced(self.namespace, key, '') self.value_text.setPlainText(self.db.prefs.to_raw(val)) def _get_ns_prefix(self): return 'namespaced:%s:'% self.namespace def _apply_changes(self): from calibre.gui2.dialogs.confirm_delete import confirm message = '<p>Are you sure you want to change your settings in this library for this plugin?</p>' \ '<p>Any settings in other libraries or stored in a JSON file in your calibre plugins ' \ 'folder will not be touched.</p>' \ '<p>You must restart calibre afterwards.</p>' if not confirm(message, self.namespace+'_clear_settings', self): return val = self.db.prefs.raw_to_object(unicode(self.value_text.toPlainText())) key = unicode(self.keys_list.currentItem().text()) self.db.prefs.set_namespaced(self.namespace, key, val) restart = prompt_for_restart(self, 'Settings changed', '<p>Settings for this plugin in this library have been changed.</p>' '<p>Please restart calibre now.</p>') self.close() if restart: self.gui.quit(restart=True) def _clear_settings(self): from calibre.gui2.dialogs.confirm_delete import confirm message = '<p>Are you sure you want to clear your settings in this library for this plugin?</p>' \ '<p>Any settings in other libraries or stored in a JSON file in your calibre plugins ' \ 'folder will not be touched.</p>' \ '<p>You must restart calibre afterwards.</p>' if not confirm(message, self.namespace+'_clear_settings', self): return ns_prefix = self._get_ns_prefix() keys = [k for k in self.db.prefs.iterkeys() if k.startswith(ns_prefix)] for k in keys: del self.db.prefs[k] self._populate_settings() restart = prompt_for_restart(self, 'Settings deleted', '<p>All settings for this plugin in this library have been cleared.</p>' '<p>Please restart calibre now.</p>') self.close() if restart: self.gui.quit(restart=True)
class EditQDialog(QDialog): """ Class who create Edit QDialog to edit text in Alignak-app """ def __init__(self, parent=None): super(EditQDialog, self).__init__(parent) self.setWindowTitle('Edit Dialog') self.setWindowFlags(Qt.FramelessWindowHint) self.setStyleSheet(settings.css_style) self.setWindowIcon(QIcon(settings.get_image('icon'))) self.setObjectName('dialog') self.setFixedSize(300, 300) # Fields self.text_edit = QTextEdit() self.old_text = '' def initialize(self, title, text): """ Initialize QDialog for UserNotesQDialog :param title: title of the QDialog :type title: str :param text: text to edit :type text: str """ self.old_text = text center_widget(self) # Main status_layout main_layout = QVBoxLayout(self) main_layout.setContentsMargins(0, 0, 0, 0) self.setLayout(main_layout) main_layout.addWidget(get_logo_widget(self, title)) text_title = QLabel(_("Edit your text:")) text_title.setObjectName('subtitle') main_layout.addWidget(text_title) main_layout.setAlignment(text_title, Qt.AlignCenter) main_layout.addWidget(self.get_text_widget()) def get_text_widget(self): """ Return text QWidget with QTextEdit :return: text QWidget :rtype: QWidget """ text_widget = QWidget() text_widget.setObjectName('dialog') text_layout = QVBoxLayout() text_widget.setLayout(text_layout) self.text_edit.setPlaceholderText(_('type your text...')) self.text_edit.setText(self.old_text) text_layout.addWidget(self.text_edit) # Accept button accept_btn = QPushButton(_('Confirm'), self) accept_btn.clicked.connect(self.accept_text) accept_btn.setObjectName('valid') accept_btn.setMinimumHeight(30) text_layout.addWidget(accept_btn) return text_widget def accept_text(self): """ Set Edit QDialog to Rejected or Accepted (prevent to patch for nothing) """ if self.old_text == self.text_edit.toPlainText(): self.reject() elif not self.old_text or self.old_text.isspace(): if not self.text_edit.toPlainText() or self.text_edit.toPlainText().isspace(): self.reject() else: self.accept() else: self.accept()
class CheckLibraryDialog(QDialog): def __init__(self, parent, db): QDialog.__init__(self, parent) self.db = db self.setWindowTitle(_('Check Library -- Problems Found')) self.setWindowIcon(QIcon(I('debug.png'))) self._tl = QHBoxLayout() self.setLayout(self._tl) self.splitter = QSplitter(self) self.left = QWidget(self) self.splitter.addWidget(self.left) self.helpw = QTextEdit(self) self.splitter.addWidget(self.helpw) self._tl.addWidget(self.splitter) self._layout = QVBoxLayout() self.left.setLayout(self._layout) self.helpw.setReadOnly(True) self.helpw.setText(_('''\ <h1>Help</h1> <p>calibre stores the list of your books and their metadata in a database. The actual book files and covers are stored as normal files in the calibre library folder. The database contains a list of the files and covers belonging to each book entry. This tool checks that the actual files in the library folder on your computer match the information in the database.</p> <p>The result of each type of check is shown to the left. The various checks are: </p> <ul> <li><b>Invalid titles</b>: These are files and folders appearing in the library where books titles should, but that do not have the correct form to be a book title.</li> <li><b>Extra titles</b>: These are extra files in your calibre library that appear to be correctly-formed titles, but have no corresponding entries in the database</li> <li><b>Invalid authors</b>: These are files appearing in the library where only author folders should be.</li> <li><b>Extra authors</b>: These are folders in the calibre library that appear to be authors but that do not have entries in the database</li> <li><b>Missing book formats</b>: These are book formats that are in the database but have no corresponding format file in the book's folder. <li><b>Extra book formats</b>: These are book format files found in the book's folder but not in the database. <li><b>Unknown files in books</b>: These are extra files in the folder of each book that do not correspond to a known format or cover file.</li> <li><b>Missing cover files</b>: These represent books that are marked in the database as having covers but the actual cover files are missing.</li> <li><b>Cover files not in database</b>: These are books that have cover files but are marked as not having covers in the database.</li> <li><b>Folder raising exception</b>: These represent folders in the calibre library that could not be processed/understood by this tool.</li> </ul> <p>There are two kinds of automatic fixes possible: <i>Delete marked</i> and <i>Fix marked</i>.</p> <p><i>Delete marked</i> is used to remove extra files/folders/covers that have no entries in the database. Check the box next to the item you want to delete. Use with caution.</p> <p><i>Fix marked</i> is applicable only to covers and missing formats (the three lines marked 'fixable'). In the case of missing cover files, checking the fixable box and pushing this button will tell calibre that there is no cover for all of the books listed. Use this option if you are not going to restore the covers from a backup. In the case of extra cover files, checking the fixable box and pushing this button will tell calibre that the cover files it found are correct for all the books listed. Use this when you are not going to delete the file(s). In the case of missing formats, checking the fixable box and pushing this button will tell calibre that the formats are really gone. Use this if you are not going to restore the formats from a backup.</p> ''')) self.log = QTreeWidget(self) self.log.itemChanged.connect(self.item_changed) self.log.itemExpanded.connect(self.item_expanded_or_collapsed) self.log.itemCollapsed.connect(self.item_expanded_or_collapsed) self._layout.addWidget(self.log) self.check_button = QPushButton(_('&Run the check again')) self.check_button.setDefault(False) self.check_button.clicked.connect(self.run_the_check) self.copy_button = QPushButton(_('Copy &to clipboard')) self.copy_button.setDefault(False) self.copy_button.clicked.connect(self.copy_to_clipboard) self.ok_button = QPushButton(_('&Done')) self.ok_button.setDefault(True) self.ok_button.clicked.connect(self.accept) self.mark_delete_button = QPushButton(_('Mark &all for delete')) self.mark_delete_button.setToolTip(_('Mark all deletable subitems')) self.mark_delete_button.setDefault(False) self.mark_delete_button.clicked.connect(self.mark_for_delete) self.delete_button = QPushButton(_('Delete &marked')) self.delete_button.setToolTip(_('Delete marked files (checked subitems)')) self.delete_button.setDefault(False) self.delete_button.clicked.connect(self.delete_marked) self.mark_fix_button = QPushButton(_('Mar&k all for fix')) self.mark_fix_button.setToolTip(_('Mark all fixable items')) self.mark_fix_button.setDefault(False) self.mark_fix_button.clicked.connect(self.mark_for_fix) self.fix_button = QPushButton(_('&Fix marked')) self.fix_button.setDefault(False) self.fix_button.setEnabled(False) self.fix_button.setToolTip(_('Fix marked sections (checked fixable items)')) self.fix_button.clicked.connect(self.fix_items) self.bbox = QGridLayout() self.bbox.addWidget(self.check_button, 0, 0) self.bbox.addWidget(self.copy_button, 0, 1) self.bbox.addWidget(self.ok_button, 0, 2) self.bbox.addWidget(self.mark_delete_button, 1, 0) self.bbox.addWidget(self.delete_button, 1, 1) self.bbox.addWidget(self.mark_fix_button, 2, 0) self.bbox.addWidget(self.fix_button, 2, 1) h = QHBoxLayout() ln = QLabel(_('Names to ignore:')) h.addWidget(ln) self.name_ignores = QLineEdit() self.name_ignores.setText(db.prefs.get('check_library_ignore_names', '')) self.name_ignores.setToolTip( _('Enter comma-separated standard file name wildcards, such as synctoy*.dat')) ln.setBuddy(self.name_ignores) h.addWidget(self.name_ignores) le = QLabel(_('Extensions to ignore')) h.addWidget(le) self.ext_ignores = QLineEdit() self.ext_ignores.setText(db.prefs.get('check_library_ignore_extensions', '')) self.ext_ignores.setToolTip( _('Enter comma-separated extensions without a leading dot. Used only in book folders')) le.setBuddy(self.ext_ignores) h.addWidget(self.ext_ignores) self._layout.addLayout(h) self._layout.addLayout(self.bbox) self.resize(950, 500) def do_exec(self): self.run_the_check() probs = 0 for c in self.problem_count: probs += self.problem_count[c] if probs == 0: return False self.exec_() return True def accept(self): self.db.new_api.set_pref('check_library_ignore_extensions', unicode(self.ext_ignores.text())) self.db.new_api.set_pref('check_library_ignore_names', unicode(self.name_ignores.text())) QDialog.accept(self) def box_to_list(self, txt): return [f.strip() for f in txt.split(',') if f.strip()] def run_the_check(self): checker = CheckLibrary(self.db.library_path, self.db) checker.scan_library(self.box_to_list(unicode(self.name_ignores.text())), self.box_to_list(unicode(self.ext_ignores.text()))) plaintext = [] def builder(tree, checker, check): attr, h, checkable, fixable = check list = getattr(checker, attr, None) if list is None: self.problem_count[attr] = 0 return else: self.problem_count[attr] = len(list) tl = Item() tl.setText(0, h) if fixable and list: tl.setText(1, _('(fixable)')) tl.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) tl.setCheckState(1, False) else: tl.setFlags(Qt.ItemIsEnabled) self.top_level_items[attr] = tl for problem in list: it = Item() if checkable: it.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) it.setCheckState(1, False) else: it.setFlags(Qt.ItemIsEnabled) it.setText(0, problem[0]) it.setData(0, Qt.UserRole, problem[2]) it.setText(1, problem[1]) tl.addChild(it) self.all_items.append(it) plaintext.append(','.join([h, problem[0], problem[1]])) tree.addTopLevelItem(tl) t = self.log t.clear() t.setColumnCount(2) t.setHeaderLabels([_('Name'), _('Path from library')]) self.all_items = [] self.top_level_items = {} self.problem_count = {} for check in CHECKS: builder(t, checker, check) t.resizeColumnToContents(0) t.resizeColumnToContents(1) self.delete_button.setEnabled(False) self.fix_button.setEnabled(False) self.text_results = '\n'.join(plaintext) def item_expanded_or_collapsed(self, item): self.log.resizeColumnToContents(0) self.log.resizeColumnToContents(1) def item_changed(self, item, column): self.fix_button.setEnabled(False) for it in self.top_level_items.values(): if it.checkState(1): self.fix_button.setEnabled(True) self.delete_button.setEnabled(False) for it in self.all_items: if it.checkState(1): self.delete_button.setEnabled(True) return def mark_for_fix(self): for it in self.top_level_items.values(): if it.flags() & Qt.ItemIsUserCheckable: it.setCheckState(1, Qt.Checked) def mark_for_delete(self): for it in self.all_items: if it.flags() & Qt.ItemIsUserCheckable: it.setCheckState(1, Qt.Checked) def delete_marked(self): if not confirm('<p>'+_('The marked files and folders will be ' '<b>permanently deleted</b>. Are you sure?') +'</p>', 'check_library_editor_delete', self): return # Sort the paths in reverse length order so that we can be sure that # if an item is in another item, the sub-item will be deleted first. items = sorted(self.all_items, key=lambda x: len(x.text(1)), reverse=True) for it in items: if it.checkState(1): try: p = os.path.join(self.db.library_path ,unicode(it.text(1))) if os.path.isdir(p): delete_tree(p) else: delete_file(p) except: prints('failed to delete', os.path.join(self.db.library_path, unicode(it.text(1)))) self.run_the_check() def fix_missing_formats(self): tl = self.top_level_items['missing_formats'] child_count = tl.childCount() for i in range(0, child_count): item = tl.child(i) id = int(item.data(0, Qt.UserRole)) all = self.db.formats(id, index_is_id=True, verify_formats=False) all = set([f.strip() for f in all.split(',')]) if all else set() valid = self.db.formats(id, index_is_id=True, verify_formats=True) valid = set([f.strip() for f in valid.split(',')]) if valid else set() for fmt in all-valid: self.db.remove_format(id, fmt, index_is_id=True, db_only=True) def fix_missing_covers(self): tl = self.top_level_items['missing_covers'] child_count = tl.childCount() for i in range(0, child_count): item = tl.child(i) id = int(item.data(0, Qt.UserRole)) self.db.set_has_cover(id, False) def fix_extra_covers(self): tl = self.top_level_items['extra_covers'] child_count = tl.childCount() for i in range(0, child_count): item = tl.child(i) id = int(item.data(0, Qt.UserRole)) self.db.set_has_cover(id, True) def fix_items(self): for check in CHECKS: attr = check[0] fixable = check[3] tl = self.top_level_items[attr] if fixable and tl.checkState(1): func = getattr(self, 'fix_' + attr, None) if func is not None and callable(func): func() self.run_the_check() def copy_to_clipboard(self): QApplication.clipboard().setText(self.text_results)
class LedgerAuthDialog(QDialog): def __init__(self, handler, data): '''Ask user for 2nd factor authentication. Support text, security card and paired mobile methods. Use last method from settings, but support new pairing and downgrade. ''' QDialog.__init__(self, handler.top_level_window()) self.handler = handler self.txdata = data self.idxs = self.txdata['keycardData'] if self.txdata['confirmationType'] > 1 else '' self.setMinimumWidth(600) self.setWindowTitle(_("Ledger Wallet Authentication")) self.cfg = copy.deepcopy(self.handler.win.wallet.get_keystore().cfg) self.dongle = self.handler.win.wallet.get_keystore().get_client().dongle self.ws = None self.pin = '' self.devmode = self.getDevice2FAMode() if self.devmode == 0x11 or self.txdata['confirmationType'] == 1: self.cfg['mode'] = 0 vbox = QVBoxLayout() self.setLayout(vbox) def on_change_mode(idx): if idx < 2 and self.ws: self.ws.stop() self.ws = None self.cfg['mode'] = 0 if self.devmode == 0x11 else idx if idx > 0 else 1 if self.cfg['mode'] > 1 and self.cfg['pair'] and not self.ws: self.req_validation() if self.cfg['mode'] > 0: self.handler.win.wallet.get_keystore().cfg = self.cfg self.handler.win.wallet.save_keystore() self.update_dlg() def add_pairing(): self.do_pairing() def return_pin(): self.pin = self.pintxt.text() if self.txdata['confirmationType'] == 1 else self.cardtxt.text() if self.cfg['mode'] == 1: self.pin = ''.join(chr(int(str(i),16)) for i in self.pin) self.accept() self.modebox = QWidget() modelayout = QHBoxLayout() self.modebox.setLayout(modelayout) modelayout.addWidget(QLabel(_("Method:"))) self.modes = QComboBox() modelayout.addWidget(self.modes, 2) self.addPair = QPushButton(_("Pair")) self.addPair.setMaximumWidth(60) modelayout.addWidget(self.addPair) modelayout.addStretch(1) self.modebox.setMaximumHeight(50) vbox.addWidget(self.modebox) self.populate_modes() self.modes.currentIndexChanged.connect(on_change_mode) self.addPair.clicked.connect(add_pairing) self.helpmsg = QTextEdit() self.helpmsg.setStyleSheet("QTextEdit { background-color: lightgray; }") self.helpmsg.setReadOnly(True) vbox.addWidget(self.helpmsg) self.pinbox = QWidget() pinlayout = QHBoxLayout() self.pinbox.setLayout(pinlayout) self.pintxt = QLineEdit() self.pintxt.setEchoMode(2) self.pintxt.setMaxLength(4) self.pintxt.returnPressed.connect(return_pin) pinlayout.addWidget(QLabel(_("Enter PIN:"))) pinlayout.addWidget(self.pintxt) pinlayout.addWidget(QLabel(_("NOT DEVICE PIN - see above"))) pinlayout.addStretch(1) self.pinbox.setVisible(self.cfg['mode'] == 0) vbox.addWidget(self.pinbox) self.cardbox = QWidget() card = QVBoxLayout() self.cardbox.setLayout(card) self.addrtext = QTextEdit() self.addrtext.setStyleSheet("QTextEdit { color:blue; background-color:lightgray; padding:15px 10px; border:none; font-size:20pt; }") self.addrtext.setReadOnly(True) self.addrtext.setMaximumHeight(120) card.addWidget(self.addrtext) def pin_changed(s): if len(s) < len(self.idxs): i = self.idxs[len(s)] addr = self.txdata['address'] addr = addr[:i] + '<u><b>' + addr[i:i+1] + '</u></b>' + addr[i+1:] self.addrtext.setHtml(str(addr)) else: self.addrtext.setHtml(_("Press Enter")) pin_changed('') cardpin = QHBoxLayout() cardpin.addWidget(QLabel(_("Enter PIN:"))) self.cardtxt = QLineEdit() self.cardtxt.setEchoMode(2) self.cardtxt.setMaxLength(len(self.idxs)) self.cardtxt.textChanged.connect(pin_changed) self.cardtxt.returnPressed.connect(return_pin) cardpin.addWidget(self.cardtxt) cardpin.addWidget(QLabel(_("NOT DEVICE PIN - see above"))) cardpin.addStretch(1) card.addLayout(cardpin) self.cardbox.setVisible(self.cfg['mode'] == 1) vbox.addWidget(self.cardbox) self.pairbox = QWidget() pairlayout = QVBoxLayout() self.pairbox.setLayout(pairlayout) pairhelp = QTextEdit(helpTxt[5]) pairhelp.setStyleSheet("QTextEdit { background-color: lightgray; }") pairhelp.setReadOnly(True) pairlayout.addWidget(pairhelp, 1) self.pairqr = QRCodeWidget() pairlayout.addWidget(self.pairqr, 4) self.pairbox.setVisible(False) vbox.addWidget(self.pairbox) self.update_dlg() if self.cfg['mode'] > 1 and not self.ws: self.req_validation() def populate_modes(self): self.modes.blockSignals(True) self.modes.clear() self.modes.addItem(_("Summary Text PIN (requires dongle replugging)") if self.txdata['confirmationType'] == 1 else _("Summary Text PIN is Disabled")) if self.txdata['confirmationType'] > 1: self.modes.addItem(_("Security Card Challenge")) if not self.cfg['pair']: self.modes.addItem(_("Mobile - Not paired")) else: self.modes.addItem(_("Mobile - %s") % self.cfg['pair'][1]) self.modes.blockSignals(False) def update_dlg(self): self.modes.setCurrentIndex(self.cfg['mode']) self.modebox.setVisible(True) self.addPair.setText(_("Pair") if not self.cfg['pair'] else _("Re-Pair")) self.addPair.setVisible(self.txdata['confirmationType'] > 2) self.helpmsg.setText(helpTxt[self.cfg['mode'] if self.cfg['mode'] < 2 else 2 if self.cfg['pair'] else 4]) self.helpmsg.setMinimumHeight(180 if self.txdata['confirmationType'] == 1 else 100) self.pairbox.setVisible(False) self.helpmsg.setVisible(True) self.pinbox.setVisible(self.cfg['mode'] == 0) self.cardbox.setVisible(self.cfg['mode'] == 1) self.pintxt.setFocus(True) if self.cfg['mode'] == 0 else self.cardtxt.setFocus(True) self.setMaximumHeight(200) def do_pairing(self): rng = os.urandom(16) pairID = (hexlify(rng) + hexlify(hashlib.sha256(rng).digest()[0:1])).decode('utf-8') self.pairqr.setData(pairID) self.modebox.setVisible(False) self.helpmsg.setVisible(False) self.pinbox.setVisible(False) self.cardbox.setVisible(False) self.pairbox.setVisible(True) self.pairqr.setMinimumSize(300,300) if self.ws: self.ws.stop() self.ws = LedgerWebSocket(self, pairID) self.ws.pairing_done.connect(self.pairing_done) self.ws.start() def pairing_done(self, data): if data is not None: self.cfg['pair'] = [ data['pairid'], data['name'], data['platform'] ] self.cfg['mode'] = 2 self.handler.win.wallet.get_keystore().cfg = self.cfg self.handler.win.wallet.save_keystore() self.pin = 'paired' self.accept() def req_validation(self): if self.cfg['pair'] and 'secureScreenData' in self.txdata: if self.ws: self.ws.stop() self.ws = LedgerWebSocket(self, self.cfg['pair'][0], self.txdata) self.ws.req_updated.connect(self.req_updated) self.ws.start() def req_updated(self, pin): if pin == 'accepted': self.helpmsg.setText(helpTxt[3]) else: self.pin = str(pin) self.accept() def getDevice2FAMode(self): apdu = [0xe0, 0x24, 0x01, 0x00, 0x00, 0x01] # get 2fa mode try: mode = self.dongle.exchange( bytearray(apdu) ) return mode except BTChipException as e: debug_msg('Device getMode Failed') return 0x11 def closeEvent(self, evnt): debug_msg("CLOSE - Stop WS") if self.ws: self.ws.stop() if self.pairbox.isVisible(): evnt.ignore() self.update_dlg()
class AckQDialog(QDialog): """ Class who create Acknowledge QDialog for hosts/services """ def __init__(self, parent=None): super(AckQDialog, self).__init__(parent) self.setWindowTitle(_('Request an Acknowledge')) self.setWindowFlags(Qt.FramelessWindowHint) self.setStyleSheet(settings.css_style) self.setWindowIcon(QIcon(settings.get_image('icon'))) self.setMinimumSize(370, 480) self.setObjectName('dialog') # Fields self.sticky = True self.sticky_toggle_btn = ToggleQWidgetButton() self.notify = False self.notify_toggle_btn = ToggleQWidgetButton() self.ack_comment_edit = None self.offset = None def initialize(self, item_type, item_name, comment): # pylint: disable=too-many-locals """ Initialize Acknowledge QDialog :param item_type: type of item to acknowledge : host | service :type item_type: str :param item_name: name of the item to acknowledge :type item_name: str :param comment: the default comment of action :type comment: str """ logger.debug("Create Acknowledge QDialog...") # Main status_layout center_widget(self) main_layout = QVBoxLayout(self) main_layout.setContentsMargins(0, 0, 0, 0) main_layout.addWidget(get_logo_widget(self, _('Request Acknowledge'))) ack_widget = QWidget() ack_widget.setObjectName('dialog') ack_layout = QGridLayout(ack_widget) ack_title = QLabel(_('Request an acknowledge')) ack_title.setObjectName('itemtitle') ack_layout.addWidget(ack_title, 0, 0, 1, 2) host_label = QLabel('<b>%s:</b> %s' % (item_type.capitalize(), item_name)) ack_layout.addWidget(host_label, 1, 0, 1, 1) sticky_label = QLabel(_('Acknowledge is sticky:')) sticky_label.setObjectName('subtitle') ack_layout.addWidget(sticky_label, 2, 0, 1, 1) self.sticky_toggle_btn.initialize() self.sticky_toggle_btn.update_btn_state(self.sticky) ack_layout.addWidget(self.sticky_toggle_btn, 2, 1, 1, 1) sticky_info = QLabel( _( 'If checked, ' 'the acknowledge will remain until the element returns to an "OK" state.' ) ) sticky_info.setWordWrap(True) ack_layout.addWidget(sticky_info, 3, 0, 1, 2) notify_label = QLabel(_('Acknowledge notifies:')) notify_label.setObjectName('subtitle') ack_layout.addWidget(notify_label, 4, 0, 1, 1) self.notify_toggle_btn.initialize() self.notify_toggle_btn.update_btn_state(self.notify) ack_layout.addWidget(self.notify_toggle_btn, 4, 1, 1, 1) notify_info = QLabel( _('If checked, a notification will be sent out to the concerned contacts.') ) notify_info.setWordWrap(True) ack_layout.addWidget(notify_info, 5, 0, 1, 2) ack_comment = QLabel(_('Acknowledge comment:')) ack_comment.setObjectName('subtitle') ack_layout.addWidget(ack_comment, 6, 0, 1, 1) self.ack_comment_edit = QTextEdit() self.ack_comment_edit.setText(comment) self.ack_comment_edit.setMaximumHeight(60) ack_layout.addWidget(self.ack_comment_edit, 7, 0, 1, 2) request_btn = QPushButton(_('REQUEST ACKNOWLEDGE'), self) request_btn.clicked.connect(self.accept) request_btn.setObjectName('valid') request_btn.setMinimumHeight(30) request_btn.setDefault(True) ack_layout.addWidget(request_btn, 8, 0, 1, 2) main_layout.addWidget(ack_widget) def mousePressEvent(self, event): # pragma: no cover """ QWidget.mousePressEvent(QMouseEvent) """ self.offset = event.pos() def mouseMoveEvent(self, event): # pragma: no cover """ QWidget.mousePressEvent(QMouseEvent) """ try: x = event.globalX() y = event.globalY() x_w = self.offset.x() y_w = self.offset.y() self.move(x - x_w, y - y_w) except AttributeError as e: logger.warning('Move Event %s: %s', self.objectName(), str(e))
def show_side_pane(self): if self.count() < 2 or not self.is_side_index_hidden: return if self.desired_side_size == 0: self.desired_side_size = self.initial_side_size self.apply_state((True, self.desired_side_size)) def hide_side_pane(self): if self.count() < 2 or self.is_side_index_hidden: return self.apply_state((False, self.desired_side_size)) def double_clicked(self, *args): self.toggle_side_pane() # }}} # }}} if __name__ == '__main__': from PyQt5.Qt import QTextEdit app = QApplication([]) w = QTextEdit() s = PythonHighlighter(w) # w.setSyntaxHighlighter(s) w.setText(open(__file__, 'rb').read().decode('utf-8')) w.show() app.exec_()
class ConnectionWidget(QWidget): title_changed = pyqtSignal(QWidget, str, name="title_changed") def __init__(self, parent): super().__init__(parent) # Initialize anti-recursion flag during highlighting self.is_processing_highlighting = False # Initial widget title self.title = UI.CONNECTION_TAB_DEFAULT_TITLE # Initialize data model self.model = ConnectionModel(self) self.model.connected.connect(self.on_connection_changed) # Initialize UI self.init_ui() def init_ui(self): # Declare main vertical layout layout = QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) # Initialize control toolbar control_bar = self.build_control_bar() layout.addWidget(control_bar) # Initialize workspace workspace = self.build_workspace() layout.addWidget(workspace) # Apply configured UI layout to the widget self.setLayout(layout) def build_control_bar(self): # Add control bar control_row_layout = QHBoxLayout(self) control_row_layout.setContentsMargins(0, 0, 0, 0) # DB type combo box db_combo_box = QComboBox(self) for dbname in UI.CONNECTION_STRING_SUPPORTED_DB_NAMES: db_combo_box.addItem(dbname) control_row_layout.addWidget(db_combo_box) # Connection string self.connection_line = QLineEdit(self) self.connection_line.setPlaceholderText( UI.CONNECTION_STRING_PLACEHOLDER) self.connection_line.setText(UI.CONNECTION_STRING_DEFAULT) control_row_layout.addWidget(self.connection_line) # Connection button connection_button = QPushButton(self) connection_button.setText(UI.QUERY_CONTROL_CONNECT_BUTTON_TEXT) connection_button.clicked.connect(self.on_connect_click) control_row_layout.addWidget(connection_button) # Add contol row as a first widget in a column control_row = QWidget(self) control_row.setLayout(control_row_layout) return control_row def build_workspace(self): # Create a splitter consisting of query edit and table view splitter = QSplitter(self) splitter.setOrientation(Qt.Vertical) splitter.sizePolicy().setVerticalPolicy(QSizePolicy.Maximum) # Initialize query edit query_edit = self.build_query_text_edit() # Disable query control buttons by default self.on_disconnected() splitter.addWidget(query_edit) # Initialize result desiplaying widgets results_widget = self.build_results_widget() splitter.addWidget(results_widget) splitter.setSizes([100, 900]) return splitter def build_query_text_edit(self): # Add layouts query_edit_layout = QVBoxLayout(self) query_edit_layout.setContentsMargins(0, 0, 0, 0) query_control_layout = QHBoxLayout(self) query_control_layout.setContentsMargins(0, 0, 0, 0) # Execute query button self.query_execute_button = QPushButton( UI.QUERY_CONTROL_EXECUTE_BUTTON_TEXT, self) self.query_execute_button.clicked.connect(self.on_execute_click) query_control_layout.addWidget(self.query_execute_button) # Fetch data button self.query_fetch_button = QPushButton( UI.QUERY_CONTROL_FETCH_BUTTON_TEXT, self) self.query_fetch_button.clicked.connect(self.on_fetch_click) self.model.fetch_changed.connect(self.on_fetch_changed) query_control_layout.addWidget(self.query_fetch_button) # Commit button self.query_commit_button = QPushButton( UI.QUERY_CONTROL_COMMIT_BUTTON_TEXT, self) self.query_commit_button.clicked.connect(self.on_connect_click) query_control_layout.addWidget(self.query_commit_button) # Rollback button self.query_rollback_button = QPushButton( UI.QUERY_CONTROL_ROLLBACK_BUTTON_TEXT, self) self.query_rollback_button.clicked.connect(self.on_rollback_click) query_control_layout.addWidget(self.query_rollback_button) # Build control strip widget query_control = QWidget(self) query_control.setLayout(query_control_layout) query_edit_layout.addWidget(query_control) # Initialize query edit document for text editor # and use SQL Highlighter CSS styles for it. self.query_text_edit_document = QTextDocument(self) self.query_text_edit_document.setDefaultStyleSheet( SQLHighlighter.style()) # Initialize query text editor using previously built # text edutir document. self.query_text_edit = QTextEdit(self) self.query_text_edit.setDocument(self.query_text_edit_document) self.query_text_edit.textChanged.connect(self.on_query_changed) self.query_text_edit.setText(UI.QUERY_EDITOR_DEFAULT_TEXT) query_edit_layout.addWidget(self.query_text_edit) # Connect model's connected/disconnected signals self.model.connected.connect(self.on_connected) self.model.disconnected.connect(self.on_disconnected) query_edit = QWidget(self) query_edit.setLayout(query_edit_layout) query_edit.sizePolicy().setVerticalPolicy(QSizePolicy.Minimum) return query_edit def build_results_widget(self): # Initialize QTabWidget to display table view and log # in differnt unclosable tabs results_widget = QTabWidget(self) results_widget.setTabsClosable(False) # Add table view table_view = QTableView(self) table_view.setModel(self.model) table_view.sizePolicy().setVerticalPolicy(QSizePolicy.MinimumExpanding) results_widget.addTab(table_view, UI.QUERY_RESULTS_DATA_TAB_TEXT) # Att log view log = QTextEdit(self) log.setReadOnly(True) self.model.executed.connect(log.append) results_widget.addTab(log, UI.QUERY_RESULTS_EVENTS_TAB_TEXT) return results_widget def on_query_changed(self): """Process query edits by user""" if self.is_processing_highlighting: # If we caused the invokation of this slot by set highlighted # HTML text into query editor, then ignore this call and # mark highlighting processing as finished. self.is_processing_highlighting = False else: # If changes to text were made by user, mark beginning of # highlighting process self.is_processing_highlighting = True # Get plain text query and highlight it query_text = self.query_text_edit.toPlainText() highlighted_query_text = SQLHighlighter.highlight(query_text) # After we set highlighted HTML back to QTextEdit form # the cursor will jump to the end of the text. # To avoid that we remember the current position of the cursor. current_cursor = self.query_text_edit.textCursor() current_cursor_position = current_cursor.position() # Set highlighted text back to editor which will cause the # cursor to jump to the end of the text. self.query_text_edit_document.setHtml(highlighted_query_text) # Return cursor back to the old position current_cursor.setPosition(current_cursor_position) self.query_text_edit.setTextCursor(current_cursor) def on_connect_click(self): with ErrorHandler(): connection_string = self.connection_line.text() self.model.connect(connection_string) logging.info(f"Connected: {connection_string}") def on_execute_click(self): with ErrorHandler(): query = self.query_text_edit.toPlainText() self.model.execute(query) logging.info(f"Executed: {query}") def on_fetch_click(self): with ErrorHandler(): self.model.fetch_more() logging.info("Fetch more") def on_rollback_click(self): with ErrorHandler(): self.model.rollback() logging.info("Rollback") def on_connected(self): self.query_commit_button.setEnabled(True) self.query_execute_button.setEnabled(True) self.query_fetch_button.setEnabled(False) self.query_rollback_button.setEnabled(True) self.query_text_edit.setEnabled(True) def on_disconnected(self): self.query_commit_button.setEnabled(False) self.query_execute_button.setEnabled(False) self.query_fetch_button.setEnabled(False) self.query_rollback_button.setEnabled(False) self.query_text_edit.setEnabled(False) def on_fetch_changed(self, state): self.query_fetch_button.setEnabled(state) def on_connection_changed(self, name): self.title_changed.emit(self, name)
def initialize(self, item_type, item_name, comment): # pylint: disable=too-many-locals """ Initialize Acknowledge QDialog :param item_type: type of item to acknowledge : host | service :type item_type: str :param item_name: name of the item to acknowledge :type item_name: str :param comment: the default comment of action :type comment: str """ logger.debug("Create Acknowledge QDialog...") # Main status_layout center_widget(self) main_layout = QVBoxLayout(self) main_layout.setContentsMargins(0, 0, 0, 0) main_layout.addWidget(get_logo_widget(self, _('Request Acknowledge'))) ack_widget = QWidget() ack_widget.setObjectName('dialog') ack_layout = QGridLayout(ack_widget) ack_title = QLabel(_('Request an acknowledge')) ack_title.setObjectName('itemtitle') ack_layout.addWidget(ack_title, 0, 0, 1, 2) host_label = QLabel('<b>%s:</b> %s' % (item_type.capitalize(), item_name)) ack_layout.addWidget(host_label, 1, 0, 1, 1) sticky_label = QLabel(_('Acknowledge is sticky:')) sticky_label.setObjectName('subtitle') ack_layout.addWidget(sticky_label, 2, 0, 1, 1) self.sticky_toggle_btn.initialize() self.sticky_toggle_btn.update_btn_state(self.sticky) ack_layout.addWidget(self.sticky_toggle_btn, 2, 1, 1, 1) sticky_info = QLabel( _( 'If checked, ' 'the acknowledge will remain until the element returns to an "OK" state.' ) ) sticky_info.setWordWrap(True) ack_layout.addWidget(sticky_info, 3, 0, 1, 2) notify_label = QLabel(_('Acknowledge notifies:')) notify_label.setObjectName('subtitle') ack_layout.addWidget(notify_label, 4, 0, 1, 1) self.notify_toggle_btn.initialize() self.notify_toggle_btn.update_btn_state(self.notify) ack_layout.addWidget(self.notify_toggle_btn, 4, 1, 1, 1) notify_info = QLabel( _('If checked, a notification will be sent out to the concerned contacts.') ) notify_info.setWordWrap(True) ack_layout.addWidget(notify_info, 5, 0, 1, 2) ack_comment = QLabel(_('Acknowledge comment:')) ack_comment.setObjectName('subtitle') ack_layout.addWidget(ack_comment, 6, 0, 1, 1) self.ack_comment_edit = QTextEdit() self.ack_comment_edit.setText(comment) self.ack_comment_edit.setMaximumHeight(60) ack_layout.addWidget(self.ack_comment_edit, 7, 0, 1, 2) request_btn = QPushButton(_('REQUEST ACKNOWLEDGE'), self) request_btn.clicked.connect(self.accept) request_btn.setObjectName('valid') request_btn.setMinimumHeight(30) request_btn.setDefault(True) ack_layout.addWidget(request_btn, 8, 0, 1, 2) main_layout.addWidget(ack_widget)
class MainWindow(QMainWindow): def __init__(self, src, dest): QMainWindow.__init__(self) self.setMinimumSize(QSize(640, 160)) self.setWindowTitle("Copy Images") self.centralWidget = QWidget(self) self.setCentralWidget(self.centralWidget) self.layout = QVBoxLayout(self.centralWidget) self.source = QPushButton("Select src file (.txt list file of images)") self.layout.addWidget(self.source) self.source.released.connect(self.selectSource) self.destination = QPushButton( "Select dest folder to copy the images to") self.layout.addWidget(self.destination) self.destination.released.connect(self.selectDestination) run = QPushButton("Start copy process") self.layout.addWidget(run) run.released.connect(self.copyFiles) self.textOutput = QTextEdit() self.layout.addWidget(self.textOutput) self.sourcePath = None self.destinationPath = None if None != src: self.selectSource(src) if None != dest: self.selectDestination(dest) self.copyThread = copyThread(src, dest) self.copyThread.newText.connect(self.writeText) def selectSource(self, src=None): if src == None: self.sourcePath, _ = QFileDialog.getOpenFileName( None, 'Choose the file to work with', '', 'Image list .txt (*.txt);; * (*.*)', '') else: self.sourcePath = src self.source.setText("Source: " + self.sourcePath) self.textOutput.append("Source selected: " + self.sourcePath) def selectDestination(self, dest=None): if dest == None: self.destinationPath = QFileDialog.getExistingDirectory( self, 'Choose the destination to copy to', '') else: self.destinationPath = dest self.destination.setText("Destination: " + self.destinationPath) self.textOutput.append("Destination: " + self.destinationPath) def copyFiles(self): if self.sourcePath is not None and self.destinationPath is not None: self.copyThread.sourcePath = self.sourcePath self.copyThread.destinationPath = self.destinationPath self.copyThread.start() else: self.textOutput.append( 'Please select a source file and a destination folder.') def writeText(self, line): self.textOutput.append(line) self.textOutput.ensureCursorVisible()
class GcodeUI(object): def __init__(self, ui, layout): self.main_ui = ui self.layout = layout super(GcodeUI, self).__init__() self.isOutlineMode = True self.isLaserMode = True self.handler = GcodeHandler(self) self.set_ui() self.connect_slot() self.gcode = '' def set_ui(self): self._set_up_frame_ui() self._set_middle_frame_ui() self._set_down_frame_ui() def _set_up_frame_ui(self): self.up_frame = QFrame() self.up_frame.setMinimumHeight(300) self.up_frame.setMaximumHeight(500) self.up_layout = QHBoxLayout(self.up_frame) up_left_frame = QFrame() # up_left_frame.setMinimumWidth(self.main_ui.window.geometry().width() / 2) # up_left_frame.setMaximumWidth(self.geometry().width() / 2) up_right_frame = QFrame() # up_right_frame.setMinimumWidth(self.main_ui.window.geometry().width() / 2) # up_right_frame.setMaximumWidth(self.geometry().width() / 2) self.up_left_layout = QHBoxLayout(up_left_frame) self.up_right_layout = QHBoxLayout(up_right_frame) self.up_layout.addWidget(up_left_frame) # self.up_layout.addWidget(up_right_frame) self.layout.addWidget(self.up_frame) self.label_img = QLabel() # self.label_img.setMaximumHeight(320) # self.label_img.setMaximumWidth(480) # self.label_img.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) # self.label_img.setScaledContents(True) img = QImage() if img.load(os.path.join(icon_path, 'tmp.svg')): self.label_img.setPixmap(QPixmap.fromImage(img)) with open(os.path.join(icon_path, 'tmp.svg'), 'rb') as f: self.handler.source = f.read() self.up_left_layout.addWidget(self.label_img) self.label_img_preview = QLabel() # self.label_img_preview.setMaximumHeight(320) # self.label_img_preview.setMaximumWidth(480) self.label_img_preview.setDisabled(True) # # self.label_img_preview.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) # # self.label_img_preview.setScaledContents(True) # data = np.zeros(320 * 240) # img = QImage(data, 320, 240, QImage.Format_RGB888) # pixmap = QPixmap.fromImage(img) # self.label_img_preview.setPixmap(pixmap) self.up_right_layout.addWidget(self.label_img_preview) # self.up_frame.hide() def _set_middle_frame_ui(self): middle_frame = QFrame() self.middle_layout = QHBoxLayout(middle_frame) middle_left_frame = QFrame() # middle_left_frame.setMinimumWidth(self.main_ui.window.geometry().width() / 2 - 20) middle_right_frame = QFrame() # middle_right_frame.setMinimumWidth(self.main_ui.window.geometry().width() / 2 - 20) self.middle_left_layout = QGridLayout(middle_left_frame) self.middle_right_layout = QGridLayout(middle_right_frame) self.middle_layout.addWidget(middle_left_frame) self.middle_layout.addWidget(middle_right_frame) self.layout.addWidget(middle_frame) row = 0 self.checkbox_outline = QRadioButton('OutLine') self.checkbox_gray = QRadioButton('Gray') self.checkbox_gray.hide() self.btn_load_img = QPushButton('LoadImage') self.checkbox_outline.toggle() self.isOutlineMode = True self.checkbox_outline.setDisabled(True) self.middle_left_layout.addWidget(self.checkbox_outline, row, 0) self.middle_left_layout.addWidget(self.checkbox_gray, row, 1) self.middle_left_layout.addWidget(self.btn_load_img, row, 2) row += 1 label_x_home = QLabel('x_home:') self.slider_x_home = QSlider(QtCore.Qt.Horizontal) self.slider_x_home.setMinimum(0) self.slider_x_home.setMaximum(2000) self.slider_x_home.setValue(1500) self.spinbox_x_home = QDoubleSpinBox() self.spinbox_x_home.setDecimals(1) self.spinbox_x_home.setSingleStep(0.1) self.spinbox_x_home.setMinimum(0.0) self.spinbox_x_home.setMaximum(200.0) self.spinbox_x_home.setValue(150.0) self.slider_x_home.mouseReleaseEvent = functools.partial( self.mouseReleaseEvent, source=self.slider_x_home.mouseReleaseEvent) self.spinbox_x_home.focusOutEvent = functools.partial( self.focusOutEvent, source=self.spinbox_x_home.focusOutEvent) self.middle_left_layout.addWidget(label_x_home, row, 0) self.middle_left_layout.addWidget(self.slider_x_home, row, 1) self.middle_left_layout.addWidget(self.spinbox_x_home, row, 2) row += 1 label_y_home = QLabel('y_home:') self.slider_y_home = QSlider(QtCore.Qt.Horizontal) self.slider_y_home.setMinimum(-1500) self.slider_y_home.setMaximum(1500) self.slider_y_home.setValue(0) self.spinbox_y_home = QDoubleSpinBox() self.spinbox_y_home.setDecimals(1) self.spinbox_y_home.setSingleStep(0.1) self.spinbox_y_home.setMinimum(-150.0) self.spinbox_y_home.setMaximum(150.0) self.spinbox_y_home.setValue(0.0) self.slider_y_home.mouseReleaseEvent = functools.partial( self.mouseReleaseEvent, source=self.slider_y_home.mouseReleaseEvent) self.spinbox_y_home.focusOutEvent = functools.partial( self.focusOutEvent, source=self.spinbox_y_home.focusOutEvent) self.middle_left_layout.addWidget(label_y_home, row, 0) self.middle_left_layout.addWidget(self.slider_y_home, row, 1) self.middle_left_layout.addWidget(self.spinbox_y_home, row, 2) row += 1 label_z_home = QLabel('z_home:') self.slider_z_home = QSlider(QtCore.Qt.Horizontal) self.slider_z_home.setMinimum(0) self.slider_z_home.setMaximum(1500) self.slider_z_home.setValue(900) self.spinbox_z_home = QDoubleSpinBox() self.spinbox_z_home.setDecimals(1) self.spinbox_z_home.setSingleStep(0.1) self.spinbox_z_home.setMinimum(0.0) self.spinbox_z_home.setMaximum(150.0) self.spinbox_z_home.setValue(90.0) self.slider_z_home.mouseReleaseEvent = functools.partial( self.mouseReleaseEvent, source=self.slider_z_home.mouseReleaseEvent) self.spinbox_z_home.focusOutEvent = functools.partial( self.focusOutEvent, source=self.spinbox_z_home.focusOutEvent) self.middle_left_layout.addWidget(label_z_home, row, 0) self.middle_left_layout.addWidget(self.slider_z_home, row, 1) self.middle_left_layout.addWidget(self.spinbox_z_home, row, 2) row += 1 label_x_offset = QLabel('x_offset:') self.slider_x_offset = QSlider(QtCore.Qt.Horizontal) self.slider_x_offset.setMinimum(-5000) self.slider_x_offset.setMaximum(5000) self.slider_x_offset.setValue(0) self.spinbox_x_offset = QDoubleSpinBox() self.spinbox_x_offset.setSingleStep(0.1) self.spinbox_x_offset.setDecimals(1) self.spinbox_x_offset.setMinimum(-500.0) self.spinbox_x_offset.setMaximum(500.0) self.spinbox_x_offset.setValue(0.0) self.slider_x_offset.mouseReleaseEvent = functools.partial( self.mouseReleaseEvent, source=self.slider_x_offset.mouseReleaseEvent) self.spinbox_x_offset.focusOutEvent = functools.partial( self.focusOutEvent, source=self.spinbox_x_offset.focusOutEvent) self.middle_left_layout.addWidget(label_x_offset, row, 0) self.middle_left_layout.addWidget(self.slider_x_offset, row, 1) self.middle_left_layout.addWidget(self.spinbox_x_offset, row, 2) row += 1 label_y_offset = QLabel('y_offset:') self.slider_y_offset = QSlider(QtCore.Qt.Horizontal) self.slider_y_offset.setMinimum(-5000) self.slider_y_offset.setMaximum(5000) self.slider_y_offset.setValue(0) self.spinbox_y_offset = QDoubleSpinBox() self.spinbox_y_offset.setDecimals(1) self.spinbox_y_offset.setSingleStep(0.1) self.spinbox_y_offset.setMinimum(-500.0) self.spinbox_y_offset.setMaximum(500.0) self.spinbox_y_offset.setValue(0.0) self.slider_y_offset.mouseReleaseEvent = functools.partial( self.mouseReleaseEvent, source=self.slider_y_offset.mouseReleaseEvent) self.spinbox_y_offset.focusOutEvent = functools.partial( self.focusOutEvent, source=self.spinbox_y_offset.focusOutEvent) self.middle_left_layout.addWidget(label_y_offset, row, 0) self.middle_left_layout.addWidget(self.slider_y_offset, row, 1) self.middle_left_layout.addWidget(self.spinbox_y_offset, row, 2) row += 1 label_z_offset = QLabel('z_offset:') self.slider_z_offset = QSlider(QtCore.Qt.Horizontal) self.slider_z_offset.setMinimum(-1000) self.slider_z_offset.setMaximum(1500) self.slider_z_offset.setValue(900) self.spinbox_z_offset = QDoubleSpinBox() self.spinbox_z_offset.setDecimals(1) self.spinbox_z_offset.setSingleStep(0.1) self.spinbox_z_offset.setMinimum(-100.0) self.spinbox_z_offset.setMaximum(150.0) self.spinbox_z_offset.setValue(90.0) self.slider_z_offset.mouseReleaseEvent = functools.partial( self.mouseReleaseEvent, source=self.slider_z_offset.mouseReleaseEvent) self.spinbox_z_offset.focusOutEvent = functools.partial( self.focusOutEvent, source=self.spinbox_z_offset.focusOutEvent) self.middle_left_layout.addWidget(label_z_offset, row, 0) self.middle_left_layout.addWidget(self.slider_z_offset, row, 1) self.middle_left_layout.addWidget(self.spinbox_z_offset, row, 2) row += 1 label_pen_up = QLabel('pen_up:') self.slider_pen_up = QSlider(QtCore.Qt.Horizontal) self.slider_pen_up.setMinimum(0) self.slider_pen_up.setMaximum(500) self.slider_pen_up.setValue(200) self.spinbox_pen_up = QDoubleSpinBox() self.spinbox_pen_up.setDecimals(1) self.spinbox_pen_up.setSingleStep(0.1) self.spinbox_pen_up.setMinimum(0.0) self.spinbox_pen_up.setMaximum(50.0) self.spinbox_pen_up.setValue(20.0) self.slider_pen_up.mouseReleaseEvent = functools.partial( self.mouseReleaseEvent, source=self.slider_pen_up.mouseReleaseEvent) self.spinbox_pen_up.focusOutEvent = functools.partial( self.focusOutEvent, source=self.spinbox_pen_up.focusOutEvent) self.slider_pen_up.setDisabled(True) self.spinbox_pen_up.setDisabled(True) self.middle_left_layout.addWidget(label_pen_up, row, 0) self.middle_left_layout.addWidget(self.slider_pen_up, row, 1) self.middle_left_layout.addWidget(self.spinbox_pen_up, row, 2) row = 0 self.checkbox_laser = QRadioButton('Laser') self.checkbox_pen = QRadioButton('Pen') self.checkbox_laser.toggle() self.isLaserMode = True self.middle_right_layout.addWidget(self.checkbox_laser, row, 0) self.middle_right_layout.addWidget(self.checkbox_pen, row, 1) row += 1 label_drawing_feedrate = QLabel('drawing_feedrate:') self.slider_drawing_feedrate = QSlider(QtCore.Qt.Horizontal) self.slider_drawing_feedrate.setMinimum(5) self.slider_drawing_feedrate.setMaximum(1000) self.slider_drawing_feedrate.setValue(100) self.spinbox_drawing_feedrate = QSpinBox() self.spinbox_drawing_feedrate.setMinimum(5) self.spinbox_drawing_feedrate.setMaximum(1000) self.spinbox_drawing_feedrate.setValue(100) self.slider_drawing_feedrate.mouseReleaseEvent = functools.partial( self.mouseReleaseEvent, source=self.slider_drawing_feedrate.mouseReleaseEvent) self.spinbox_drawing_feedrate.focusOutEvent = functools.partial( self.focusOutEvent, source=self.spinbox_drawing_feedrate.focusOutEvent) self.middle_right_layout.addWidget(label_drawing_feedrate, row, 0) self.middle_right_layout.addWidget(self.slider_drawing_feedrate, row, 1) self.middle_right_layout.addWidget(self.spinbox_drawing_feedrate, row, 2) row += 1 label_moving_feedrate = QLabel('moving_feedrate:') self.slider_moving_feedrate = QSlider(QtCore.Qt.Horizontal) self.slider_moving_feedrate.setMinimum(5) self.slider_moving_feedrate.setMaximum(20000) self.slider_moving_feedrate.setValue(100) self.spinbox_moving_feedrate = QSpinBox() self.spinbox_moving_feedrate.setMinimum(5) self.spinbox_moving_feedrate.setMaximum(20000) self.spinbox_moving_feedrate.setValue(100) self.slider_moving_feedrate.mouseReleaseEvent = functools.partial( self.mouseReleaseEvent, source=self.slider_moving_feedrate.mouseReleaseEvent) self.spinbox_moving_feedrate.focusOutEvent = functools.partial( self.focusOutEvent, source=self.spinbox_moving_feedrate.focusOutEvent) self.middle_right_layout.addWidget(label_moving_feedrate, row, 0) self.middle_right_layout.addWidget(self.slider_moving_feedrate, row, 1) self.middle_right_layout.addWidget(self.spinbox_moving_feedrate, row, 2) row += 1 label_scale = QLabel('scale:') self.slider_scale = QSlider(QtCore.Qt.Horizontal) self.slider_scale.setMinimum(1) self.slider_scale.setMaximum(100) self.slider_scale.setValue(10) self.spinbox_scale = QDoubleSpinBox() self.spinbox_scale.setDecimals(1) self.spinbox_scale.setSingleStep(0.1) self.spinbox_scale.setMinimum(0.1) self.spinbox_scale.setMaximum(10.0) self.spinbox_scale.setValue(1.0) # self.slider_scale.setDisabled(True) # self.spinbox_scale.setDisabled(True) self.slider_scale.mouseReleaseEvent = functools.partial( self.mouseReleaseEvent, source=self.slider_scale.mouseReleaseEvent) self.spinbox_scale.focusOutEvent = functools.partial( self.focusOutEvent, source=self.spinbox_scale.focusOutEvent) self.middle_right_layout.addWidget(label_scale, row, 0) self.middle_right_layout.addWidget(self.slider_scale, row, 1) self.middle_right_layout.addWidget(self.spinbox_scale, row, 2) row += 1 label_resolution = QLabel('resolution:') self.slider_resolution = QSlider(QtCore.Qt.Horizontal) self.slider_resolution.setMinimum(1) self.slider_resolution.setMaximum(100) self.slider_resolution.setValue(10) self.spinbox_resolution = QDoubleSpinBox() self.spinbox_resolution.setMinimum(0.1) self.spinbox_resolution.setMaximum(10.0) self.spinbox_resolution.setSingleStep(0.1) self.spinbox_resolution.setDecimals(1) self.spinbox_resolution.setValue(1.0) self.slider_resolution.setDisabled(True) self.spinbox_resolution.setDisabled(True) self.middle_right_layout.addWidget(label_resolution, row, 0) self.middle_right_layout.addWidget(self.slider_resolution, row, 1) self.middle_right_layout.addWidget(self.spinbox_resolution, row, 2) row += 1 self.btn_generate_gcode = QPushButton('Generate_Gcode') self.middle_right_layout.addWidget(self.btn_generate_gcode, row, 0) row += 1 self.label_x_min = QLabel('') self.label_x_max = QLabel('') self.middle_right_layout.addWidget(self.label_x_min, row, 0) self.middle_right_layout.addWidget(self.label_x_max, row, 1) row += 1 self.label_y_min = QLabel('') self.label_y_max = QLabel('') self.middle_right_layout.addWidget(self.label_y_min, row, 0) self.middle_right_layout.addWidget(self.label_y_max, row, 1) def _set_down_frame_ui(self): self.down_frame = QFrame() self.down_layout = QHBoxLayout(self.down_frame) self.layout.addWidget(self.down_frame) self.textEdit = QTextEdit() self.down_layout.addWidget(self.textEdit) # self.down_frame.hide() def select_engrave_mode(self, event): self.isOutlineMode = event # print('outline: {}, laser: {}'.format(self.isOutlineMode, self.isLaserMode)) def select_end_type(self, event): self.isLaserMode = event self.slider_pen_up.setDisabled(self.isLaserMode) self.spinbox_pen_up.setDisabled(self.isLaserMode) self.generate_gcode() # print('outline: {}, laser: {}'.format(self.isOutlineMode, self.isLaserMode)) def connect_slot(self): self.checkbox_outline.toggled.connect(self.select_engrave_mode) self.checkbox_laser.toggled.connect(self.select_end_type) self.btn_load_img.clicked.connect(self.load_image) self.slider_x_home.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.spinbox_x_home, scale=.1)) self.spinbox_x_home.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.slider_x_home, scale=10)) self.slider_y_home.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.spinbox_y_home, scale=.1)) self.spinbox_y_home.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.slider_y_home, scale=10)) self.slider_z_home.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.spinbox_z_home, scale=.1)) self.spinbox_z_home.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.slider_z_home, scale=10)) self.slider_x_offset.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.spinbox_x_offset, scale=.1)) self.spinbox_x_offset.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.slider_x_offset, scale=10)) self.slider_y_offset.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.spinbox_y_offset, scale=.1)) self.spinbox_y_offset.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.slider_y_offset, scale=10)) self.slider_z_offset.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.spinbox_z_offset, scale=.1)) self.spinbox_z_offset.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.slider_z_offset, scale=10)) self.slider_pen_up.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.spinbox_pen_up, scale=.1)) self.spinbox_pen_up.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.slider_pen_up, scale=10)) self.slider_scale.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.spinbox_scale, scale=.1)) self.spinbox_scale.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.slider_scale, scale=10)) self.slider_resolution.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.spinbox_resolution, scale=.1)) self.spinbox_resolution.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.slider_resolution, scale=10)) self.slider_drawing_feedrate.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.spinbox_drawing_feedrate, scale=1)) self.spinbox_drawing_feedrate.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.slider_drawing_feedrate, scale=1)) self.slider_moving_feedrate.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.spinbox_moving_feedrate, scale=1)) self.spinbox_moving_feedrate.valueChanged.connect( functools.partial(self.slider_spinbox_related, slave=self.slider_moving_feedrate, scale=1)) self.btn_generate_gcode.clicked.connect( functools.partial(self.generate_gcode, flag=True)) def slider_spinbox_related(self, value, master=None, slave=None, scale=1): try: slave.setValue(value * scale) except Exception as e: print(e) def mouseReleaseEvent(self, event, source=None): try: self.generate_gcode() except Exception as e: print(e) source(event) def focusOutEvent(self, event, source=None): try: self.generate_gcode() except Exception as e: print(e) source(event) def generate_gcode(self, flag=False): if self.handler.template is None and flag: self.handler.svg_to_gcode() if self.handler.template: pen_up = self.spinbox_pen_up.value() if not self.isLaserMode else 0 config = { 'x_home': self.spinbox_x_home.value(), 'y_home': self.spinbox_y_home.value(), 'z_home': self.spinbox_z_home.value(), 'z_offset': self.spinbox_z_offset.value(), 'pen_up': pen_up, 'z_offset_pen_up': self.spinbox_z_offset.value() + pen_up, 'moving_feedrate': self.spinbox_moving_feedrate.value(), 'drawing_feedrate': self.spinbox_drawing_feedrate.value(), } self.gcode = self.handler.template.format(**config) self.change_gcode() # self.textEdit.setText(self.gcode) def change_gcode(self): if self.gcode: x_offset = self.spinbox_x_offset.value() y_offset = self.spinbox_y_offset.value() z_offset = self.spinbox_z_offset.value() moving_feedrate = self.spinbox_moving_feedrate.value() drawing_feedrate = self.spinbox_drawing_feedrate.value() scale = self.spinbox_scale.value() lines = self.gcode.split('\n') for i, line in enumerate(lines): List = line.strip().split(' ') line = '' for l in List: if l.startswith('F'): if line.startswith(('G01', 'G1')): l = 'F{}'.format(drawing_feedrate) elif line.startswith(('G00', 'G0')): l = 'F{}'.format(moving_feedrate) elif l.startswith('X'): x = float(l[1:]) * scale + x_offset l = 'X{0:.2f}'.format(x) elif l.startswith('Y'): y = float(l[1:]) * scale + y_offset l = 'Y{0:.2f}'.format(y) # elif l.startswith('Z'): # z = float(l[1:]) + z_offset # l = 'Z{0:.2f}'.format(z) line += l + ' ' line = line.strip() lines[i] = line self.calc_gcode(lines) gcode = '\n'.join(lines) self.textEdit.setText(gcode) def calc_gcode(self, lines): x_list = [] y_list = [] for i, line in enumerate(lines): if line.startswith(tuple(['G0', 'G1', 'G00', 'G01'])): List = line.strip().split(' ') for l in List: if l.startswith('X'): x = float(l[1:]) x_list.append(x) elif l.startswith('Y'): y = float(l[1:]) y_list.append(y) if len(x_list) > 0: x_min = np.min(x_list) x_max = np.max(x_list) self.label_x_min.setText('X(min): ' + str(x_min)) self.label_x_max.setText('X(max): ' + str(x_max)) # print('x_min: {}, x_max: {}, x_distance: {}'.format(x_min, x_max, x_max - x_min)) if len(y_list) > 0: y_min = np.min(y_list) y_max = np.max(y_list) self.label_y_min.setText('Y(min): ' + str(y_min)) self.label_y_max.setText('Y(max): ' + str(y_max)) # print('y_min: {}, y_max: {}, y_distance: {}'.format(y_min, y_max, y_max - y_min)) def load_image(self): fname = QFileDialog.getOpenFileName(self.main_ui.window, 'Open file', '', '*.svg') if fname and fname[0]: img = QImage() if img.load(fname[0]): self.label_img.setPixmap(QPixmap.fromImage(img)) with open(fname[0], 'rb') as f: self.handler.source = f.read() self.handler.template = None self.gcode = None self.up_frame.show()
class DownQDialog(QDialog): """ Class who create Downtime QDialog for hosts/services """ def __init__(self, parent=None): super(DownQDialog, self).__init__(parent) self.setWindowTitle(_('Request a Downtime')) self.setWindowFlags(Qt.FramelessWindowHint) self.setStyleSheet(settings.css_style) self.setWindowIcon(QIcon(settings.get_image('icon'))) self.setMinimumSize(360, 460) self.setObjectName('dialog') # Fields self.fixed = True self.fixed_toggle_btn = ToggleQWidgetButton() self.duration = QTimeEdit() self.start_time = QDateTimeEdit() self.end_time = QDateTimeEdit() self.comment_edit = QTextEdit() self.offset = None def initialize(self, item_type, item_name, comment): # pylint: disable=too-many-locals """ Initialize Downtime QDialog :param item_type: type of item to acknowledge : host | service :type item_type: str :param item_name: name of the item to acknowledge :type item_name: str :param comment: the default comment of action :type comment: str """ logger.debug("Create Downtime QDialog...") # Main status_layout center_widget(self) main_layout = QVBoxLayout(self) main_layout.setContentsMargins(0, 0, 0, 0) main_layout.addWidget(get_logo_widget(self, _('Request Downtime'))) downtime_widget = QWidget() downtime_widget.setObjectName('dialog') downtime_layout = QGridLayout(downtime_widget) downtime_title = QLabel(_('Request a downtime')) downtime_title.setObjectName('itemtitle') downtime_layout.addWidget(downtime_title, 0, 0, 1, 3) host_label = QLabel('<b>%s:</b> %s' % (item_type.capitalize(), item_name)) downtime_layout.addWidget(host_label, 1, 0, 1, 1) options_label = QLabel(_('Downtime options:')) options_label.setObjectName('subtitle') downtime_layout.addWidget(options_label, 2, 0, 1, 1) self.fixed_toggle_btn.initialize() self.fixed_toggle_btn.update_btn_state(self.fixed) downtime_layout.addWidget(self.fixed_toggle_btn, 2, 1, 1, 1) fixed_label = QLabel(_('Fixed')) downtime_layout.addWidget(fixed_label, 2, 2, 1, 1) fixed_info = QLabel( _( 'If checked, downtime will start and end at the times specified' ' by the “start time” and “end time” fields.' ) ) fixed_info.setWordWrap(True) downtime_layout.addWidget(fixed_info, 3, 0, 1, 3) duration_label = QLabel(_('Duration')) duration_label.setObjectName('subtitle') downtime_layout.addWidget(duration_label, 4, 0, 1, 1) duration_clock = QLabel() duration_clock.setPixmap(QPixmap(settings.get_image('time'))) downtime_layout.addWidget(duration_clock, 4, 1, 1, 1) duration_clock.setFixedSize(16, 16) duration_clock.setScaledContents(True) self.duration.setTime(QTime(4, 00)) self.duration.setDisplayFormat("HH'h'mm") downtime_layout.addWidget(self.duration, 4, 2, 1, 1) duration_info = QLabel( _('Sets the duration if it is a non-fixed downtime.') ) downtime_layout.addWidget(duration_info, 5, 0, 1, 3) date_range_label = QLabel(_('Downtime date range')) date_range_label.setObjectName('subtitle') downtime_layout.addWidget(date_range_label, 6, 0, 1, 1) calendar_label = QLabel() calendar_label.setPixmap(QPixmap(settings.get_image('calendar'))) calendar_label.setFixedSize(16, 16) calendar_label.setScaledContents(True) downtime_layout.addWidget(calendar_label, 6, 1, 1, 1) start_time_label = QLabel(_('Start time:')) downtime_layout.addWidget(start_time_label, 7, 0, 1, 1) self.start_time.setCalendarPopup(True) self.start_time.setDateTime(datetime.datetime.now()) self.start_time.setDisplayFormat("dd/MM/yyyy HH'h'mm") downtime_layout.addWidget(self.start_time, 7, 1, 1, 2) end_time_label = QLabel(_('End time:')) downtime_layout.addWidget(end_time_label, 8, 0, 1, 1) self.end_time.setCalendarPopup(True) self.end_time.setDateTime(datetime.datetime.now() + datetime.timedelta(hours=2)) self.end_time.setDisplayFormat("dd/MM/yyyy HH'h'mm") downtime_layout.addWidget(self.end_time, 8, 1, 1, 2) self.comment_edit.setText(comment) self.comment_edit.setMaximumHeight(60) downtime_layout.addWidget(self.comment_edit, 9, 0, 1, 3) request_btn = QPushButton(_('REQUEST DOWNTIME'), self) request_btn.clicked.connect(self.handle_accept) request_btn.setObjectName('valid') request_btn.setMinimumHeight(30) request_btn.setDefault(True) downtime_layout.addWidget(request_btn, 10, 0, 1, 3) main_layout.addWidget(downtime_widget) def duration_to_seconds(self): """ Return "duration" QTimeEdit value in seconds :return: "duration" in seconds :rtype: int """ return QTime(0, 0).secsTo(self.duration.time()) def handle_accept(self): """ Check if end_time timestamp is not lower than start_time """ if self.start_time.dateTime().toTime_t() > self.end_time.dateTime().toTime_t(): logger.warning('Try to add Downtime with "End Time" lower than "Start Time"') else: self.accept() def mousePressEvent(self, event): # pragma: no cover """ QWidget.mousePressEvent(QMouseEvent) """ self.offset = event.pos() def mouseMoveEvent(self, event): # pragma: no cover """ QWidget.mousePressEvent(QMouseEvent) """ try: x = event.globalX() y = event.globalY() x_w = self.offset.x() y_w = self.offset.y() self.move(x - x_w, y - y_w) except AttributeError as e: logger.warning('Move Event %s: %s', self.objectName(), str(e))
def __init__(self): QWidget.__init__(self) self.setWindowTitle('exlibris preferences') row = 0 self.l = QGridLayout() self.setLayout(self.l) self.label_xhtml_filename = QLabel('Ex libris XHTML filename:') self.xhtml_filename = QLineEdit(self) self.xhtml_filename.setText(prefs['xhtml_filename']) self.button_xhtml_filename = QPushButton('Change', self) self.button_xhtml_filename.clicked.connect(self.button_xhtml_filename_handler) self.l.addWidget(self.label_xhtml_filename, row, 1) row += 1 self.l.addWidget(self.xhtml_filename, row, 1) self.l.addWidget(self.button_xhtml_filename, row, 2) row += 1 self.l.addWidget(QLabel(''), row, 1) row += 1 self.label_include_dir = QLabel('Include additional files from directory:') self.checkbox_include_dir = QCheckBox('', self) self.checkbox_include_dir.setChecked(prefs['checkbox_include_dir'] == 'True') self.include_dir = QLineEdit(self) self.include_dir.setText(prefs['include_dir']) self.button_include_dir = QPushButton('Change', self) self.button_include_dir.clicked.connect(self.button_include_dir_handler) self.l.addWidget(self.checkbox_include_dir, row, 0) self.l.addWidget(self.label_include_dir, row, 1) row += 1 self.l.addWidget(self.include_dir, row, 1) self.l.addWidget(self.button_include_dir, row, 2) row += 1 self.l.addWidget(QLabel(''), row, 1) row += 1 self.label_include_guide_text = QLabel('Include in guide with string:') self.checkbox_include_guide_text = QCheckBox('', self) self.checkbox_include_guide_text.setChecked(prefs['checkbox_include_guide_text'] == 'True') self.include_guide_text = QLineEdit(self) self.include_guide_text.setText(prefs['include_guide_text']) self.l.addWidget(self.checkbox_include_guide_text, row, 0) self.l.addWidget(self.label_include_guide_text, row, 1) row += 1 self.l.addWidget(self.include_guide_text, row, 1) row += 1 self.l.addWidget(QLabel(''), row, 1) row += 1 self.label_include_toc_text = QLabel('Include in TOC with string:') self.checkbox_include_toc_text = QCheckBox('', self) self.checkbox_include_toc_text.setChecked(prefs['checkbox_include_toc_text'] == 'True') self.include_toc_text = QLineEdit(self) self.include_toc_text.setText(prefs['include_toc_text']) self.l.addWidget(self.checkbox_include_toc_text, row, 0) self.l.addWidget(self.label_include_toc_text, row, 1) row += 1 self.l.addWidget(self.include_toc_text, row, 1) row += 1 self.l.addWidget(QLabel(''), row, 1) row += 1 self.label_ask_replace = QLabel('Ask before replacing book in library') self.checkbox_ask_replace = QCheckBox('', self) self.checkbox_ask_replace.setChecked(prefs['checkbox_ask_replace'] == 'True') self.l.addWidget(self.checkbox_ask_replace, row, 0) self.l.addWidget(self.label_ask_replace, row, 1) row += 1 self.label_disable_first_last_only = QLabel('When multiple EPUB files are selected, allow insertion points other than "1", "first", and "last"') self.checkbox_disable_first_last_only = QCheckBox('', self) self.checkbox_disable_first_last_only.setChecked(prefs['checkbox_disable_first_last_only'] == 'True') self.l.addWidget(self.checkbox_disable_first_last_only, row, 0) self.l.addWidget(self.label_disable_first_last_only, row, 1) row += 1 self.l.addWidget(QLabel(''), row, 1) row += 1 self.label_replace_strings = QLabel('Replace strings:') self.replace_strings = QTextEdit(self) self.replace_strings.setText(prefs['replace_strings']) self.label_supportedMetadata = QLabel('Supported metadata:') self.supportedMetadata = QListWidget(self) #QtCore.QObject.connect(self.supportedMetadata, QtCore.SIGNAL("doubleClicked()"), self.add_replace_string) self.supportedMetadata.doubleClicked.connect(self.add_replace_string) producer = exlibris() tags = producer.getSupportedMetadataList() for tag in tags: self.supportedMetadata.addItem(tag.decode('utf-8')) self.l.addWidget(self.label_replace_strings, row, 1) self.l.addWidget(self.label_supportedMetadata, row, 2) row += 1 self.l.addWidget(self.replace_strings, row, 1) self.l.addWidget(self.supportedMetadata, row, 2) row += 1 self.resize(self.sizeHint())
class ThemeCreateDialog(Dialog): def __init__(self, parent, report): self.report = report Dialog.__init__(self, _('Create an icon theme'), 'create-icon-theme', parent) def setup_ui(self): self.splitter = QSplitter(self) self.l = l = QVBoxLayout(self) l.addWidget(self.splitter) l.addWidget(self.bb) self.w = w = QGroupBox(_('Theme Metadata'), self) self.splitter.addWidget(w) l = w.l = QFormLayout(w) l.setFieldGrowthPolicy(l.ExpandingFieldsGrow) self.missing_icons_group = mg = QGroupBox(self) self.mising_icons = mi = QListWidget(mg) mi.setSelectionMode(mi.NoSelection) mg.l = QVBoxLayout(mg) mg.l.addWidget(mi) self.splitter.addWidget(mg) self.title = QLineEdit(self) l.addRow(_('&Title:'), self.title) self.author = QLineEdit(self) l.addRow(_('&Author:'), self.author) self.version = v = QSpinBox(self) v.setMinimum(1), v.setMaximum(1000000) l.addRow(_('&Version:'), v) self.license = lc = QLineEdit(self) l.addRow(_('&License:'), lc) self.url = QLineEdit(self) l.addRow(_('&URL:'), self.url) lc.setText(_( 'The license for the icons in this theme. Common choices are' ' Creative Commons or Public Domain.')) self.description = QTextEdit(self) l.addRow(self.description) self.refresh_button = rb = self.bb.addButton(_('&Refresh'), self.bb.ActionRole) rb.setIcon(QIcon(I('view-refresh.png'))) rb.clicked.connect(self.refresh) self.apply_report() def sizeHint(self): return QSize(900, 670) @property def metadata(self): self.report.theme.title = self.title.text().strip() # Needed for report.name to work return { 'title': self.title.text().strip(), 'author': self.author.text().strip(), 'version': self.version.value(), 'description': self.description.toPlainText().strip(), 'number': len(self.report.name_map) - len(self.report.extra), 'date': utcnow().date().isoformat(), 'name': self.report.name, 'license': self.license.text().strip() or 'Unknown', 'url': self.url.text().strip() or None, } def save_metadata(self): with open(os.path.join(self.report.path, THEME_METADATA), 'wb') as f: json.dump(self.metadata, f, indent=2) def refresh(self): self.save_metadata() self.report = read_theme_from_folder(self.report.path) self.apply_report() def apply_report(self): theme = self.report.theme self.title.setText((theme.title or '').strip()) self.author.setText((theme.author or '').strip()) self.version.setValue(theme.version or 1) self.description.setText((theme.description or '').strip()) self.license.setText((theme.license or 'Unknown').strip()) self.url.setText((theme.url or '').strip()) if self.report.missing: title = _('%d icons missing in this theme') % len(self.report.missing) else: title = _('No missing icons') self.missing_icons_group.setTitle(title) mi = self.mising_icons mi.clear() for name in sorted(self.report.missing): QListWidgetItem(QIcon(I(name, allow_user_override=False)), name, mi) def accept(self): mi = self.metadata if not mi.get('title'): return error_dialog(self, _('No title specified'), _( 'You must specify a title for this icon theme'), show=True) if not mi.get('author'): return error_dialog(self, _('No author specified'), _( 'You must specify an author for this icon theme'), show=True) return Dialog.accept(self)
class HBDDialog(QDialog): restart_required = False def __init__(self, gui, icon, do_user_config): QDialog.__init__(self, gui) self.gui = gui self.do_user_config = do_user_config self.threadpool = QThreadPool() # The current database shown in the GUI # db is an instance of the class LibraryDatabase from db/legacy.py # This class has many, many methods that allow you to do a lot of # things. For most purposes you should use db.new_api, which has # a much nicer interface from db/cache.py self.db = gui.current_db # Window properties self.setWindowTitle('Humble-Bundle Downloader') self.setWindowIcon(icon) # Create main layout self.mainlayout = QHBoxLayout() self.setLayout(self.mainlayout) # Create layout for buttons self.buttonlayout = QVBoxLayout() self.mainlayout.addLayout(self.buttonlayout) # Add label self.label = QLabel('') self.buttonlayout.addWidget(self.label) # Add config button self.conf_button = QPushButton('Configure', self) self.conf_button.clicked.connect(self.config) self.buttonlayout.addWidget(self.conf_button) # Add Sync button self.Import_button = QPushButton('Import', self) self.Import_button.clicked.connect(self.Download) self.buttonlayout.addWidget(self.Import_button) # Add 'about' button self.about_button = QPushButton('About', self) self.about_button.clicked.connect(self.about) self.buttonlayout.addWidget(self.about_button) # Add log pane self.textlog = QTextEdit(self) self.mainlayout.addWidget(self.textlog) self.textlog.setReadOnly(True) self.refresh_label() self.check_field_exists() self.resize(800, 200) def check_field_exists(self): db = self.db.new_api if HBDDialog.restart_required: self.textlog.append('Restart required before plugin can be used.') elif '#humble_filenames' in db.get_categories(): self.textlog.append('#humble_filenames field exists.') else: self.textlog.append('#humble_filenames field does not exist...') self.add_field() def add_field(self): # Reference at # https://github.com/kovidgoyal/calibre/blob/master/src/calibre/gui2/preferences/create_custom_column.py db = self.gui.library_view.model().db col = 'humble_filenames' col_heading = 'Original HB filenames' col_type = 'text' is_multiple = True display_dict = { 'description': 'Original filenames of ebooks downloaded via the HB Downloader plugin' } db.create_custom_column(label=col, name=col_heading, datatype=col_type, is_multiple=is_multiple, display=display_dict) HBDDialog.restart_required = True self.textlog.append( 'The field has been created and will be usable after a restart.') self.refresh_label() def refresh_label(self): if HBDDialog.restart_required: self.label.setText('Calibre restart required') self.Import_button.setEnabled(False) elif prefs['cookie_auth_token'] == '': self.label.setText('Authentication token not set.') self.Import_button.setEnabled(False) else: self.label.setText('Authentication token set.') self.Import_button.setEnabled(True) def Download(self): db = self.db.new_api auth_token = prefs['cookie_auth_token'] dl_loc = prefs['download_loc'] log = self.textlog I = importer(db, auth_token, dl_loc) I.signals.log.connect(self.textlog.append) I.signals.done_downloads.connect(self.Import) self.threadpool.start(I) def Import(self, download_names): paths = [prefs['download_loc'] + name for name in download_names] Adder(paths, db=self.gui.current_db, parent=self.gui, pool=self.gui.spare_pool()) def config(self): self.do_user_config(parent=self) self.refresh_label() self.textlog.append('Config changed.') def about(self): text = get_resources('about.txt') QMessageBox.about(self, 'About Humble-Bundle downloader', text.decode('utf-8'))
def __init__(self, handler, data): '''Ask user for 2nd factor authentication. Support text, security card and paired mobile methods. Use last method from settings, but support new pairing and downgrade. ''' QDialog.__init__(self, handler.top_level_window()) self.handler = handler self.txdata = data self.idxs = self.txdata['keycardData'] if self.txdata['confirmationType'] > 1 else '' self.setMinimumWidth(650) self.setWindowTitle(_("Ledger Wallet Authentication")) self.cfg = copy.deepcopy(self.handler.win.wallet.get_keystore().cfg) self.dongle = self.handler.win.wallet.get_keystore().get_client().dongle self.ws = None self.pin = '' self.devmode = self.getDevice2FAMode() if self.devmode == 0x11 or self.txdata['confirmationType'] == 1: self.cfg['mode'] = 0 vbox = QVBoxLayout() self.setLayout(vbox) def on_change_mode(idx): if idx < 2 and self.ws: self.ws.stop() self.ws = None self.cfg['mode'] = 0 if self.devmode == 0x11 else idx if idx > 0 else 1 if self.cfg['mode'] > 1 and self.cfg['pair'] and not self.ws: self.req_validation() if self.cfg['mode'] > 0: self.handler.win.wallet.get_keystore().cfg = self.cfg self.handler.win.wallet.save_keystore() self.update_dlg() def add_pairing(): self.do_pairing() def return_pin(): self.pin = self.pintxt.text() if self.txdata['confirmationType'] == 1 else self.cardtxt.text() if self.cfg['mode'] == 1: self.pin = ''.join(chr(int(str(i),16)) for i in self.pin) self.accept() self.modebox = QWidget() modelayout = QHBoxLayout() self.modebox.setLayout(modelayout) modelayout.addWidget(QLabel(_("Method:"))) self.modes = QComboBox() modelayout.addWidget(self.modes, 2) self.addPair = QPushButton(_("Pair")) self.addPair.setMaximumWidth(60) modelayout.addWidget(self.addPair) modelayout.addStretch(1) self.modebox.setMaximumHeight(50) vbox.addWidget(self.modebox) self.populate_modes() self.modes.currentIndexChanged.connect(on_change_mode) self.addPair.clicked.connect(add_pairing) self.helpmsg = QTextEdit() self.helpmsg.setStyleSheet("QTextEdit { background-color: lightgray; }") self.helpmsg.setReadOnly(True) vbox.addWidget(self.helpmsg) self.pinbox = QWidget() pinlayout = QHBoxLayout() self.pinbox.setLayout(pinlayout) self.pintxt = QLineEdit() self.pintxt.setEchoMode(2) self.pintxt.setMaxLength(4) self.pintxt.returnPressed.connect(return_pin) pinlayout.addWidget(QLabel(_("Enter PIN:"))) pinlayout.addWidget(self.pintxt) pinlayout.addWidget(QLabel(_("NOT DEVICE PIN - see above"))) pinlayout.addStretch(1) self.pinbox.setVisible(self.cfg['mode'] == 0) vbox.addWidget(self.pinbox) self.cardbox = QWidget() card = QVBoxLayout() self.cardbox.setLayout(card) self.addrtext = QTextEdit() self.addrtext.setStyleSheet("QTextEdit { color:blue; background-color:lightgray; padding:15px 10px; border:none; font-size:20pt; font-family:monospace; }") self.addrtext.setReadOnly(True) self.addrtext.setMaximumHeight(130) card.addWidget(self.addrtext) def pin_changed(s): if len(s) < len(self.idxs): i = self.idxs[len(s)] addr = self.txdata['address'] if not constants.net.TESTNET: text = addr[:i] + '<u><b>' + addr[i:i+1] + '</u></b>' + addr[i+1:] else: # pin needs to be created from mainnet address addr_mainnet = bitcoin.script_to_address(bitcoin.address_to_script(addr), net=constants.BitcoinMainnet) addr_mainnet = addr_mainnet[:i] + '<u><b>' + addr_mainnet[i:i+1] + '</u></b>' + addr_mainnet[i+1:] text = str(addr) + '\n' + str(addr_mainnet) self.addrtext.setHtml(str(text)) else: self.addrtext.setHtml(_("Press Enter")) pin_changed('') cardpin = QHBoxLayout() cardpin.addWidget(QLabel(_("Enter PIN:"))) self.cardtxt = QLineEdit() self.cardtxt.setEchoMode(2) self.cardtxt.setMaxLength(len(self.idxs)) self.cardtxt.textChanged.connect(pin_changed) self.cardtxt.returnPressed.connect(return_pin) cardpin.addWidget(self.cardtxt) cardpin.addWidget(QLabel(_("NOT DEVICE PIN - see above"))) cardpin.addStretch(1) card.addLayout(cardpin) self.cardbox.setVisible(self.cfg['mode'] == 1) vbox.addWidget(self.cardbox) self.pairbox = QWidget() pairlayout = QVBoxLayout() self.pairbox.setLayout(pairlayout) pairhelp = QTextEdit(helpTxt[5]) pairhelp.setStyleSheet("QTextEdit { background-color: lightgray; }") pairhelp.setReadOnly(True) pairlayout.addWidget(pairhelp, 1) self.pairqr = QRCodeWidget() pairlayout.addWidget(self.pairqr, 4) self.pairbox.setVisible(False) vbox.addWidget(self.pairbox) self.update_dlg() if self.cfg['mode'] > 1 and not self.ws: self.req_validation()
def __init__(self, parent=None): QTextEdit.__init__(self, parent) self.setTabChangesFocus(True) self.document().setDefaultStyleSheet(css()) font = self.font() f = QFontInfo(font) delta = tweaks['change_book_details_font_size_by'] + 1 if delta: font.setPixelSize(f.pixelSize() + delta) self.setFont(font) f = QFontMetrics(self.font()) self.em_size = f.horizontalAdvance('m') self.base_url = None self._parent = weakref.ref(parent) self.comments_pat = re.compile(r'<!--.*?-->', re.DOTALL) extra_shortcuts = { 'bold': 'Bold', 'italic': 'Italic', 'underline': 'Underline', } for rec in ( ('bold', 'format-text-bold', _('Bold'), True), ('italic', 'format-text-italic', _('Italic'), True), ('underline', 'format-text-underline', _('Underline'), True), ('strikethrough', 'format-text-strikethrough', _('Strikethrough'), True), ('superscript', 'format-text-superscript', _('Superscript'), True), ('subscript', 'format-text-subscript', _('Subscript'), True), ('ordered_list', 'format-list-ordered', _('Ordered list'), True), ('unordered_list', 'format-list-unordered', _('Unordered list'), True), ('align_left', 'format-justify-left', _('Align left'), True), ('align_center', 'format-justify-center', _('Align center'), True), ('align_right', 'format-justify-right', _('Align right'), True), ('align_justified', 'format-justify-fill', _('Align justified'), True), ('undo', 'edit-undo', _('Undo'), ), ('redo', 'edit-redo', _('Redo'), ), ('remove_format', 'edit-clear', _('Remove formatting'), ), ('copy', 'edit-copy', _('Copy'), ), ('paste', 'edit-paste', _('Paste'), ), ('paste_and_match_style', 'edit-paste', _('Paste and match style'), ), ('cut', 'edit-cut', _('Cut'), ), ('indent', 'format-indent-more', _('Increase indentation'), ), ('outdent', 'format-indent-less', _('Decrease indentation'), ), ('select_all', 'edit-select-all', _('Select all'), ), ('color', 'format-text-color', _('Foreground color')), ('background', 'format-fill-color', _('Background color')), ('insert_link', 'insert-link', _('Insert link or image'),), ('insert_hr', 'format-text-hr', _('Insert separator'),), ('clear', 'trash', _('Clear')), ): name, icon, text = rec[:3] checkable = len(rec) == 4 ac = QAction(QIcon(I(icon + '.png')), text, self) if checkable: ac.setCheckable(checkable) setattr(self, 'action_'+name, ac) ss = extra_shortcuts.get(name) if ss is not None: ac.setShortcut(QKeySequence(getattr(QKeySequence, ss))) ac.triggered.connect(getattr(self, 'do_' + name)) self.action_block_style = QAction(QIcon(I('format-text-heading.png')), _('Style text block'), self) self.action_block_style.setToolTip( _('Style the selected text block')) self.block_style_menu = QMenu(self) self.action_block_style.setMenu(self.block_style_menu) self.block_style_actions = [] h = _('Heading {0}') for text, name in ( (_('Normal'), 'p'), (h.format(1), 'h1'), (h.format(2), 'h2'), (h.format(3), 'h3'), (h.format(4), 'h4'), (h.format(5), 'h5'), (h.format(6), 'h6'), (_('Blockquote'), 'blockquote'), ): ac = QAction(text, self) self.block_style_menu.addAction(ac) ac.block_name = name ac.setCheckable(True) self.block_style_actions.append(ac) ac.triggered.connect(self.do_format_block) self.setHtml('') self.copyAvailable.connect(self.update_clipboard_actions) self.update_clipboard_actions(False) self.selectionChanged.connect(self.update_selection_based_actions) self.update_selection_based_actions() connect_lambda(self.undoAvailable, self, lambda self, yes: self.action_undo.setEnabled(yes)) connect_lambda(self.redoAvailable, self, lambda self, yes: self.action_redo.setEnabled(yes)) self.action_undo.setEnabled(False), self.action_redo.setEnabled(False) self.textChanged.connect(self.update_cursor_position_actions) self.cursorPositionChanged.connect(self.update_cursor_position_actions) self.textChanged.connect(self.data_changed) self.update_cursor_position_actions()
class GameListWidget(QWidget): def __init__(self, main): super(GameListWidget, self).__init__() self.main_win = main self.keystore_exchanged = False self.setObjectName("GameListWidget") v_layout = QVBoxLayout() h_layout1 = QHBoxLayout() self.game_list_view = QListView() self.game_list_view.setViewMode(QListView.ListMode) self.game_list_view.setEditTriggers(QAbstractItemView.NoEditTriggers) self.game_list_model = GameListModel(self.main_win.games) self.game_list_view.setModel(self.game_list_model) self.game_list_view.clicked.connect(self.list_item_onclick) h_layout1.addWidget(self.game_list_view, 1) self.game_list_view.setCurrentIndex( self.game_list_model.index(self.main_win.game_index)) self.game = self.main_win.games[self.main_win.game_index] form_layout = QFormLayout() form_layout.setContentsMargins(20, 50, 20, 50) self.game_name_value = QLineEdit() form_layout.addRow("游戏名称:", self.game_name_value) self.game_desc_value = QTextEdit() form_layout.addRow("游戏简介:", self.game_desc_value) self.game_appid_value = QLabel() self.game_appid_value.setTextInteractionFlags(Qt.TextSelectableByMouse) form_layout.addRow("游戏ID:", self.game_appid_value) self.game_appkey_value = QLabel() self.game_appkey_value.setTextInteractionFlags( Qt.TextSelectableByMouse) form_layout.addRow("客户端Key:", self.game_appkey_value) h_layout = QHBoxLayout() self.keystore_path = QLineEdit() select_key_btn = QPushButton("浏览") select_key_btn.setStyleSheet('QPushButton{border-radius: 0px;}') select_key_btn.clicked.connect(self.select_ketstore) h_layout.addWidget(self.keystore_path) h_layout.addWidget(select_key_btn) form_layout.addRow("KeyStore:", h_layout) self.keystore_pwd_value = QLineEdit() form_layout.addRow("KeyPass:"******"Alias:", self.keystore_alias_value) self.keystore_aliaspwd_value = QLineEdit() form_layout.addRow("AliasPass:"******"更换Icon") icon_exchange_btn.setFixedWidth(100) icon_exchange_btn.clicked.connect(self.exchange_icon) v_layout1.addWidget(icon_exchange_btn, alignment=Qt.AlignHCenter) v_layout1.addStretch(2) h_layout1.addLayout(v_layout1, 1) v_layout.addLayout(h_layout1) h_layout2 = QHBoxLayout() create_game_btn = QPushButton("返 回") create_game_btn.setFixedWidth(100) create_game_btn.clicked.connect(self.back) h_layout2.addWidget(create_game_btn, alignment=Qt.AlignLeft | Qt.AlignBottom) back_btn = QPushButton("创建游戏") back_btn.setFixedWidth(100) back_btn.clicked.connect(self.add_game) h_layout2.addWidget(back_btn, alignment=Qt.AlignHCenter) next_btn = QPushButton("下一步") next_btn.setFixedWidth(100) next_btn.clicked.connect(self.next) h_layout2.addWidget(next_btn, alignment=Qt.AlignRight | Qt.AlignBottom) v_layout.addLayout(h_layout2) self.setLayout(v_layout) self.set_game_info() def set_game_info(self): self.game_name_value.setText(self.game['name']) self.game_desc_value.setText(self.game['desc']) self.game_appid_value.setText(self.game['id']) self.game_appkey_value.setText(self.game['key']) self.keystore_path.setText(self.game['keystore']) self.keystore_pwd_value.setText(self.game['keypwd']) self.keystore_alias_value.setText(self.game['alias']) self.keystore_aliaspwd_value.setText(self.game['aliaspwd']) icon = Utils.get_full_path('games/' + self.game['id'] + '/icon/icon.png') if not os.path.exists(icon): icon = 'icon.png' self.icon_img.setPixmap(QPixmap(icon)) def list_item_onclick(self): self.main_win.game_index = self.game_list_view.currentIndex().row() self.game = self.main_win.games[self.main_win.game_index] self.set_game_info() def back(self): self.main_win.set_main_widget() def add_game(self): if not self.save_data(): return self.main_win.set_create_game_widget(self.main_win.games) def select_ketstore(self): fname = QFileDialog.getOpenFileName( self, '选择签名文件', Utils.get_full_path('games/' + self.game['id'] + '/keystore/')) if fname[0]: if os.path.samefile( fname[0], Utils.get_full_path('games/' + self.game['id'] + '/keystore/' + self.game['keystore'])): self.keystore_path.setText(self.game['keystore']) self.keystore_pwd_value.setText(self.game['keypwd']) self.keystore_alias_value.setText(self.game['alias']) self.keystore_aliaspwd_value.setText(self.game['aliaspwd']) self.keystore_exchanged = False else: self.keystore_path.setText(fname[0]) self.keystore_pwd_value.clear() self.keystore_alias_value.clear() self.keystore_aliaspwd_value.clear() self.keystore_exchanged = True def exchange_icon(self): fname = QFileDialog.getOpenFileName( self, '选择icon', Utils.get_full_path('games/' + self.game['id'] + '/icon/'), ("Images (*.png)")) if fname[0]: pix = QPixmap(fname[0]) if pix.width() != 512 or pix.height() != 512: QMessageBox.warning(self, "警告", "必须上传512*512.png图片") return self.icon_img.setPixmap(pix) current_icon = Utils.get_full_path('games/' + self.game['id'] + '/icon/icon.png') if os.path.exists(current_icon): if os.path.samefile(os.path.dirname(fname[0]), os.path.dirname(current_icon)): if not os.path.samefile( fname[0], current_icon ): # 如果选中的,在game的icon目录下,但不是当前icon,则进行重命名 count = 0 temp = 'icon0.png' while os.path.exists( Utils.get_full_path('games/' + self.game['id'] + '/icon/' + temp)): count += 1 temp = 'icon' + str(count) + '.png' os.renames( current_icon, Utils.get_full_path('games/' + self.game['id'] + '/icon/' + temp)) os.renames(fname[0], current_icon) else: # 如果所选的是当前icon,不做处理 return else: # 如果选中的不在game的icon目录下,则重命名当前icon,并将选中的icon复制到目录下作为当前icon count = 0 temp = 'icon0.png' while os.path.exists( Utils.get_full_path('games/' + self.game['id'] + '/icon/' + temp)): count += 1 temp = 'icon' + str(count) + '.png' os.renames( current_icon, Utils.get_full_path('games/' + self.game['id'] + '/icon/' + temp)) Utils.copy_file(fname[0], current_icon) else: Utils.copy_file(fname[0], current_icon) def save_data(self): if self.game_name_value.text().strip() == "": QMessageBox.warning(self, "警告", "游戏名称不能为空!") return False if self.keystore_path.text().strip() == "": QMessageBox.warning(self, "警告", "必须上传keystore签名文件!") return False if self.keystore_pwd_value.text().strip() == "": QMessageBox.warning(self, "警告", "keystore密码不能为空!") return False if self.keystore_alias_value.text().strip() == "": QMessageBox.warning(self, "警告", "alias不能为空!") return False if self.keystore_aliaspwd_value.text().strip() == "": QMessageBox.warning(self, "警告", "alias密码不能为空!") return False self.game['name'] = self.game_name_value.text().strip() self.game['desc'] = self.game_desc_value.toPlainText().strip() if self.keystore_exchanged: keystore = os.path.basename(self.keystore_path.text().strip()) self.game['keystore'] = keystore self.game['keypwd'] = self.keystore_pwd_value.text().strip() self.game['alias'] = self.keystore_alias_value.text().strip() self.game['aliaspwd'] = self.keystore_aliaspwd_value.text().strip() keystore_path = Utils.get_full_path('games/' + self.game['id'] + '/keystore/' + keystore) if not os.path.exists(keystore_path): Utils.copy_file(self.keystore_path.text().strip(), keystore_path) self.main_win.games[self.main_win.game_index] = self.game self.game_list_model.update_item(self.main_win.game_index, self.game) return Utils.update_games(Utils.get_full_path('games/games.xml'), self.game, self.main_win.game_index) def next(self): if not self.save_data(): return channels = Utils.get_channels( Utils.get_full_path('games/' + self.game['id'] + '/config.xml')) if channels is None: if not os.path.exists(Utils.get_full_path('channelsdk')): QMessageBox.warning( self, "警告", os.path.dirname(os.getcwd()) + " 没有channelsdk文件夹") return elif len(os.listdir(Utils.get_full_path('channelsdk'))) <= 0: QMessageBox.warning( self, "警告", "本地没有渠道sdk,请手动添加sdk文件夹到" + Utils.get_full_path('channelsdk')) return channels = [] self.main_win.set_add_channel_widget(channels) else: self.main_win.set_channel_list_widget(channels)
def __init__(self, parent, db): QDialog.__init__(self, parent) self.db = db self.setWindowTitle(_('Check Library -- Problems Found')) self.setWindowIcon(QIcon(I('debug.png'))) self._tl = QHBoxLayout() self.setLayout(self._tl) self.splitter = QSplitter(self) self.left = QWidget(self) self.splitter.addWidget(self.left) self.helpw = QTextEdit(self) self.splitter.addWidget(self.helpw) self._tl.addWidget(self.splitter) self._layout = QVBoxLayout() self.left.setLayout(self._layout) self.helpw.setReadOnly(True) self.helpw.setText(_('''\ <h1>Help</h1> <p>calibre stores the list of your books and their metadata in a database. The actual book files and covers are stored as normal files in the calibre library folder. The database contains a list of the files and covers belonging to each book entry. This tool checks that the actual files in the library folder on your computer match the information in the database.</p> <p>The result of each type of check is shown to the left. The various checks are: </p> <ul> <li><b>Invalid titles</b>: These are files and folders appearing in the library where books titles should, but that do not have the correct form to be a book title.</li> <li><b>Extra titles</b>: These are extra files in your calibre library that appear to be correctly-formed titles, but have no corresponding entries in the database</li> <li><b>Invalid authors</b>: These are files appearing in the library where only author folders should be.</li> <li><b>Extra authors</b>: These are folders in the calibre library that appear to be authors but that do not have entries in the database</li> <li><b>Missing book formats</b>: These are book formats that are in the database but have no corresponding format file in the book's folder. <li><b>Extra book formats</b>: These are book format files found in the book's folder but not in the database. <li><b>Unknown files in books</b>: These are extra files in the folder of each book that do not correspond to a known format or cover file.</li> <li><b>Missing cover files</b>: These represent books that are marked in the database as having covers but the actual cover files are missing.</li> <li><b>Cover files not in database</b>: These are books that have cover files but are marked as not having covers in the database.</li> <li><b>Folder raising exception</b>: These represent folders in the calibre library that could not be processed/understood by this tool.</li> </ul> <p>There are two kinds of automatic fixes possible: <i>Delete marked</i> and <i>Fix marked</i>.</p> <p><i>Delete marked</i> is used to remove extra files/folders/covers that have no entries in the database. Check the box next to the item you want to delete. Use with caution.</p> <p><i>Fix marked</i> is applicable only to covers and missing formats (the three lines marked 'fixable'). In the case of missing cover files, checking the fixable box and pushing this button will tell calibre that there is no cover for all of the books listed. Use this option if you are not going to restore the covers from a backup. In the case of extra cover files, checking the fixable box and pushing this button will tell calibre that the cover files it found are correct for all the books listed. Use this when you are not going to delete the file(s). In the case of missing formats, checking the fixable box and pushing this button will tell calibre that the formats are really gone. Use this if you are not going to restore the formats from a backup.</p> ''')) self.log = QTreeWidget(self) self.log.itemChanged.connect(self.item_changed) self.log.itemExpanded.connect(self.item_expanded_or_collapsed) self.log.itemCollapsed.connect(self.item_expanded_or_collapsed) self._layout.addWidget(self.log) self.check_button = QPushButton(_('&Run the check again')) self.check_button.setDefault(False) self.check_button.clicked.connect(self.run_the_check) self.copy_button = QPushButton(_('Copy &to clipboard')) self.copy_button.setDefault(False) self.copy_button.clicked.connect(self.copy_to_clipboard) self.ok_button = QPushButton(_('&Done')) self.ok_button.setDefault(True) self.ok_button.clicked.connect(self.accept) self.mark_delete_button = QPushButton(_('Mark &all for delete')) self.mark_delete_button.setToolTip(_('Mark all deletable subitems')) self.mark_delete_button.setDefault(False) self.mark_delete_button.clicked.connect(self.mark_for_delete) self.delete_button = QPushButton(_('Delete &marked')) self.delete_button.setToolTip(_('Delete marked files (checked subitems)')) self.delete_button.setDefault(False) self.delete_button.clicked.connect(self.delete_marked) self.mark_fix_button = QPushButton(_('Mar&k all for fix')) self.mark_fix_button.setToolTip(_('Mark all fixable items')) self.mark_fix_button.setDefault(False) self.mark_fix_button.clicked.connect(self.mark_for_fix) self.fix_button = QPushButton(_('&Fix marked')) self.fix_button.setDefault(False) self.fix_button.setEnabled(False) self.fix_button.setToolTip(_('Fix marked sections (checked fixable items)')) self.fix_button.clicked.connect(self.fix_items) self.bbox = QGridLayout() self.bbox.addWidget(self.check_button, 0, 0) self.bbox.addWidget(self.copy_button, 0, 1) self.bbox.addWidget(self.ok_button, 0, 2) self.bbox.addWidget(self.mark_delete_button, 1, 0) self.bbox.addWidget(self.delete_button, 1, 1) self.bbox.addWidget(self.mark_fix_button, 2, 0) self.bbox.addWidget(self.fix_button, 2, 1) h = QHBoxLayout() ln = QLabel(_('Names to ignore:')) h.addWidget(ln) self.name_ignores = QLineEdit() self.name_ignores.setText(db.prefs.get('check_library_ignore_names', '')) self.name_ignores.setToolTip( _('Enter comma-separated standard file name wildcards, such as synctoy*.dat')) ln.setBuddy(self.name_ignores) h.addWidget(self.name_ignores) le = QLabel(_('Extensions to ignore')) h.addWidget(le) self.ext_ignores = QLineEdit() self.ext_ignores.setText(db.prefs.get('check_library_ignore_extensions', '')) self.ext_ignores.setToolTip( _('Enter comma-separated extensions without a leading dot. Used only in book folders')) le.setBuddy(self.ext_ignores) h.addWidget(self.ext_ignores) self._layout.addLayout(h) self._layout.addLayout(self.bbox) self.resize(950, 500)
def __init__(self, handler, data): '''Ask user for 2nd factor authentication. Support text, security card and paired mobile methods. Use last method from settings, but support new pairing and downgrade. ''' QDialog.__init__(self, handler.top_level_window()) self.handler = handler self.txdata = data self.idxs = self.txdata['keycardData'] if self.txdata['confirmationType'] > 1 else '' self.setMinimumWidth(600) self.setWindowTitle(_("Ledger Wallet Authentication")) self.cfg = copy.deepcopy(self.handler.win.wallet.get_keystore().cfg) self.dongle = self.handler.win.wallet.get_keystore().get_client().dongle self.ws = None self.pin = '' self.devmode = self.getDevice2FAMode() if self.devmode == 0x11 or self.txdata['confirmationType'] == 1: self.cfg['mode'] = 0 vbox = QVBoxLayout() self.setLayout(vbox) def on_change_mode(idx): if idx < 2 and self.ws: self.ws.stop() self.ws = None self.cfg['mode'] = 0 if self.devmode == 0x11 else idx if idx > 0 else 1 if self.cfg['mode'] > 1 and self.cfg['pair'] and not self.ws: self.req_validation() if self.cfg['mode'] > 0: self.handler.win.wallet.get_keystore().cfg = self.cfg self.handler.win.wallet.save_keystore() self.update_dlg() def add_pairing(): self.do_pairing() def return_pin(): self.pin = self.pintxt.text() if self.txdata['confirmationType'] == 1 else self.cardtxt.text() if self.cfg['mode'] == 1: self.pin = ''.join(chr(int(str(i),16)) for i in self.pin) self.accept() self.modebox = QWidget() modelayout = QHBoxLayout() self.modebox.setLayout(modelayout) modelayout.addWidget(QLabel(_("Method:"))) self.modes = QComboBox() modelayout.addWidget(self.modes, 2) self.addPair = QPushButton(_("Pair")) self.addPair.setMaximumWidth(60) modelayout.addWidget(self.addPair) modelayout.addStretch(1) self.modebox.setMaximumHeight(50) vbox.addWidget(self.modebox) self.populate_modes() self.modes.currentIndexChanged.connect(on_change_mode) self.addPair.clicked.connect(add_pairing) self.helpmsg = QTextEdit() self.helpmsg.setStyleSheet("QTextEdit { background-color: lightgray; }") self.helpmsg.setReadOnly(True) vbox.addWidget(self.helpmsg) self.pinbox = QWidget() pinlayout = QHBoxLayout() self.pinbox.setLayout(pinlayout) self.pintxt = QLineEdit() self.pintxt.setEchoMode(2) self.pintxt.setMaxLength(4) self.pintxt.returnPressed.connect(return_pin) pinlayout.addWidget(QLabel(_("Enter PIN:"))) pinlayout.addWidget(self.pintxt) pinlayout.addWidget(QLabel(_("NOT DEVICE PIN - see above"))) pinlayout.addStretch(1) self.pinbox.setVisible(self.cfg['mode'] == 0) vbox.addWidget(self.pinbox) self.cardbox = QWidget() card = QVBoxLayout() self.cardbox.setLayout(card) self.addrtext = QTextEdit() self.addrtext.setStyleSheet("QTextEdit { color:blue; background-color:lightgray; padding:15px 10px; border:none; font-size:20pt; }") self.addrtext.setReadOnly(True) self.addrtext.setMaximumHeight(120) card.addWidget(self.addrtext) def pin_changed(s): if len(s) < len(self.idxs): i = self.idxs[len(s)] addr = self.txdata['address'] addr = addr[:i] + '<u><b>' + addr[i:i+1] + '</u></b>' + addr[i+1:] self.addrtext.setHtml(str(addr)) else: self.addrtext.setHtml(_("Press Enter")) pin_changed('') cardpin = QHBoxLayout() cardpin.addWidget(QLabel(_("Enter PIN:"))) self.cardtxt = QLineEdit() self.cardtxt.setEchoMode(2) self.cardtxt.setMaxLength(len(self.idxs)) self.cardtxt.textChanged.connect(pin_changed) self.cardtxt.returnPressed.connect(return_pin) cardpin.addWidget(self.cardtxt) cardpin.addWidget(QLabel(_("NOT DEVICE PIN - see above"))) cardpin.addStretch(1) card.addLayout(cardpin) self.cardbox.setVisible(self.cfg['mode'] == 1) vbox.addWidget(self.cardbox) self.pairbox = QWidget() pairlayout = QVBoxLayout() self.pairbox.setLayout(pairlayout) pairhelp = QTextEdit(helpTxt[5]) pairhelp.setStyleSheet("QTextEdit { background-color: lightgray; }") pairhelp.setReadOnly(True) pairlayout.addWidget(pairhelp, 1) self.pairqr = QRCodeWidget() pairlayout.addWidget(self.pairqr, 4) self.pairbox.setVisible(False) vbox.addWidget(self.pairbox) self.update_dlg() if self.cfg['mode'] > 1 and not self.ws: self.req_validation()
class LedgerAuthDialog(QDialog): def __init__(self, handler, data): '''Ask user for 2nd factor authentication. Support text, security card and paired mobile methods. Use last method from settings, but support new pairing and downgrade. ''' QDialog.__init__(self, handler.top_level_window()) self.handler = handler self.txdata = data self.idxs = self.txdata['keycardData'] if self.txdata['confirmationType'] > 1 else '' self.setMinimumWidth(650) self.setWindowTitle(_("Ledger Wallet Authentication")) self.cfg = copy.deepcopy(self.handler.win.wallet.get_keystore().cfg) self.dongle = self.handler.win.wallet.get_keystore().get_client().dongle self.ws = None self.pin = '' self.devmode = self.getDevice2FAMode() if self.devmode == 0x11 or self.txdata['confirmationType'] == 1: self.cfg['mode'] = 0 vbox = QVBoxLayout() self.setLayout(vbox) def on_change_mode(idx): if idx < 2 and self.ws: self.ws.stop() self.ws = None self.cfg['mode'] = 0 if self.devmode == 0x11 else idx if idx > 0 else 1 if self.cfg['mode'] > 1 and self.cfg['pair'] and not self.ws: self.req_validation() if self.cfg['mode'] > 0: self.handler.win.wallet.get_keystore().cfg = self.cfg self.handler.win.wallet.save_keystore() self.update_dlg() def add_pairing(): self.do_pairing() def return_pin(): self.pin = self.pintxt.text() if self.txdata['confirmationType'] == 1 else self.cardtxt.text() if self.cfg['mode'] == 1: self.pin = ''.join(chr(int(str(i),16)) for i in self.pin) self.accept() self.modebox = QWidget() modelayout = QHBoxLayout() self.modebox.setLayout(modelayout) modelayout.addWidget(QLabel(_("Method:"))) self.modes = QComboBox() modelayout.addWidget(self.modes, 2) self.addPair = QPushButton(_("Pair")) self.addPair.setMaximumWidth(60) modelayout.addWidget(self.addPair) modelayout.addStretch(1) self.modebox.setMaximumHeight(50) vbox.addWidget(self.modebox) self.populate_modes() self.modes.currentIndexChanged.connect(on_change_mode) self.addPair.clicked.connect(add_pairing) self.helpmsg = QTextEdit() self.helpmsg.setStyleSheet("QTextEdit { background-color: lightgray; }") self.helpmsg.setReadOnly(True) vbox.addWidget(self.helpmsg) self.pinbox = QWidget() pinlayout = QHBoxLayout() self.pinbox.setLayout(pinlayout) self.pintxt = QLineEdit() self.pintxt.setEchoMode(2) self.pintxt.setMaxLength(4) self.pintxt.returnPressed.connect(return_pin) pinlayout.addWidget(QLabel(_("Enter PIN:"))) pinlayout.addWidget(self.pintxt) pinlayout.addWidget(QLabel(_("NOT DEVICE PIN - see above"))) pinlayout.addStretch(1) self.pinbox.setVisible(self.cfg['mode'] == 0) vbox.addWidget(self.pinbox) self.cardbox = QWidget() card = QVBoxLayout() self.cardbox.setLayout(card) self.addrtext = QTextEdit() self.addrtext.setStyleSheet("QTextEdit { color:blue; background-color:lightgray; padding:15px 10px; border:none; font-size:20pt; font-family:monospace; }") self.addrtext.setReadOnly(True) self.addrtext.setMaximumHeight(130) card.addWidget(self.addrtext) def pin_changed(s): if len(s) < len(self.idxs): i = self.idxs[len(s)] addr = self.txdata['address'] if not constants.net.TESTNET: text = addr[:i] + '<u><b>' + addr[i:i+1] + '</u></b>' + addr[i+1:] else: # pin needs to be created from mainnet address addr_mainnet = bitcoin.script_to_address(bitcoin.address_to_script(addr), net=constants.BitcoinMainnet) addr_mainnet = addr_mainnet[:i] + '<u><b>' + addr_mainnet[i:i+1] + '</u></b>' + addr_mainnet[i+1:] text = str(addr) + '\n' + str(addr_mainnet) self.addrtext.setHtml(str(text)) else: self.addrtext.setHtml(_("Press Enter")) pin_changed('') cardpin = QHBoxLayout() cardpin.addWidget(QLabel(_("Enter PIN:"))) self.cardtxt = QLineEdit() self.cardtxt.setEchoMode(2) self.cardtxt.setMaxLength(len(self.idxs)) self.cardtxt.textChanged.connect(pin_changed) self.cardtxt.returnPressed.connect(return_pin) cardpin.addWidget(self.cardtxt) cardpin.addWidget(QLabel(_("NOT DEVICE PIN - see above"))) cardpin.addStretch(1) card.addLayout(cardpin) self.cardbox.setVisible(self.cfg['mode'] == 1) vbox.addWidget(self.cardbox) self.pairbox = QWidget() pairlayout = QVBoxLayout() self.pairbox.setLayout(pairlayout) pairhelp = QTextEdit(helpTxt[5]) pairhelp.setStyleSheet("QTextEdit { background-color: lightgray; }") pairhelp.setReadOnly(True) pairlayout.addWidget(pairhelp, 1) self.pairqr = QRCodeWidget() pairlayout.addWidget(self.pairqr, 4) self.pairbox.setVisible(False) vbox.addWidget(self.pairbox) self.update_dlg() if self.cfg['mode'] > 1 and not self.ws: self.req_validation() def populate_modes(self): self.modes.blockSignals(True) self.modes.clear() self.modes.addItem(_("Summary Text PIN (requires dongle replugging)") if self.txdata['confirmationType'] == 1 else _("Summary Text PIN is Disabled")) if self.txdata['confirmationType'] > 1: self.modes.addItem(_("Security Card Challenge")) if not self.cfg['pair']: self.modes.addItem(_("Mobile - Not paired")) else: self.modes.addItem(_("Mobile - {}").format(self.cfg['pair'][1])) self.modes.blockSignals(False) def update_dlg(self): self.modes.setCurrentIndex(self.cfg['mode']) self.modebox.setVisible(True) self.addPair.setText(_("Pair") if not self.cfg['pair'] else _("Re-Pair")) self.addPair.setVisible(self.txdata['confirmationType'] > 2) self.helpmsg.setText(helpTxt[self.cfg['mode'] if self.cfg['mode'] < 2 else 2 if self.cfg['pair'] else 4]) self.helpmsg.setMinimumHeight(180 if self.txdata['confirmationType'] == 1 else 100) self.pairbox.setVisible(False) self.helpmsg.setVisible(True) self.pinbox.setVisible(self.cfg['mode'] == 0) self.cardbox.setVisible(self.cfg['mode'] == 1) self.pintxt.setFocus(True) if self.cfg['mode'] == 0 else self.cardtxt.setFocus(True) self.setMaximumHeight(400) def do_pairing(self): rng = os.urandom(16) pairID = (hexlify(rng) + hexlify(hashlib.sha256(rng).digest()[0:1])).decode('utf-8') self.pairqr.setData(pairID) self.modebox.setVisible(False) self.helpmsg.setVisible(False) self.pinbox.setVisible(False) self.cardbox.setVisible(False) self.pairbox.setVisible(True) self.pairqr.setMinimumSize(300,300) if self.ws: self.ws.stop() self.ws = LedgerWebSocket(self, pairID) self.ws.pairing_done.connect(self.pairing_done) self.ws.start() def pairing_done(self, data): if data is not None: self.cfg['pair'] = [ data['pairid'], data['name'], data['platform'] ] self.cfg['mode'] = 2 self.handler.win.wallet.get_keystore().cfg = self.cfg self.handler.win.wallet.save_keystore() self.pin = 'paired' self.accept() def req_validation(self): if self.cfg['pair'] and 'secureScreenData' in self.txdata: if self.ws: self.ws.stop() self.ws = LedgerWebSocket(self, self.cfg['pair'][0], self.txdata) self.ws.req_updated.connect(self.req_updated) self.ws.start() def req_updated(self, pin): if pin == 'accepted': self.helpmsg.setText(helpTxt[3]) else: self.pin = str(pin) self.accept() def getDevice2FAMode(self): apdu = [0xe0, 0x24, 0x01, 0x00, 0x00, 0x01] # get 2fa mode try: mode = self.dongle.exchange( bytearray(apdu) ) return mode except BTChipException as e: debug_msg('Device getMode Failed') return 0x11 def closeEvent(self, evnt): debug_msg("CLOSE - Stop WS") if self.ws: self.ws.stop() if self.pairbox.isVisible(): evnt.ignore() self.update_dlg()
class ExportToSqlite (SqliteModel): def __init__ (self,basepath, database): super(ExportToSqlite,self).__init__(basepath) self.database = database self.defaultColorStringFaction = "0,0,255,255" self.nb_heros_inserted = [" ajout de Heros ",0] self.nb_groupes_inserted = [" ajout de Groupes",0] self.nb_kingdom_inserted = [" ajout de Royaumes ",0] self.nb_empire_inserted = [" ajout d' Empires ",0] self.nb_faction_inserted = [" ajout de Factions ",0] self.nb_heros_unchanged= [" unchanged Heros ",0] self.nb_groupes_unchanged= [" unchanged Groupes",0] self.nb_kingdom_unchanged= [" unchanged Royaumes ",0] self.nb_empire_unchanged= [" unchanged Empires ",0] self.nb_faction_unchanged= [" unchanged Factions ",0] def setDefaultValues (self, default_dict): self.defaultValues = default_dict def addFaction (self, faction_name): result = self.database.select("*","gm_faction",True,'name=="'+faction_name+'"') if result.first() == 0 : print ('faction inexistante') attribs = {"name":faction_name,'icon':faction_name+'.png'} self.database.insert("gm_faction",attribs) result = self.database.select("*","gm_faction",False,'name=="'+faction_name+'"') self.nb_faction_inserted[1] = self.nb_faction_inserted[1] + 1 else: print ('faction deja persante') self.nb_empire_unchanged[1] = self.nb_empire_unchanged[1] + 1 return result def addEmpire (self, empire_name,id_faction,empire_color=""): result = self.database.select("*","gm_empire",True,'name=="'+empire_name+'"') if result.first() == 0 : attribs = {"name":empire_name,"ID_faction":id_faction,"icon":str(empire_name)+".png","color":empire_color} self.database.insert("gm_empire",attribs) result = self.database.select("*","gm_empire",True,'name=="'+empire_name+'"') self.nb_empire_inserted[1] = self.nb_empire_inserted[1] + 1 else: self.nb_empire_unchanged[1] = self.nb_empire_unchanged[1] + 1 return result def addKingdom (self, kingdom_name, id_empire): result = self.database.select("*","gm_kingdom",True,'name=="'+kingdom_name+'"') if result.first() == 0 : default_couleur = str(self.defaultValues['kingdom_couleur'][0]) +','+ str(self.defaultValues['kingdom_couleur'][1])+','+str(self.defaultValues['kingdom_couleur'][2])+','+str(self.defaultValues['kingdom_couleur'][3]) attribs = {"name":kingdom_name,"ID_empire":id_empire,"armee":self.defaultValues['kingdom_armee'],"description":self.defaultValues['kingdom_description'],"couleur":default_couleur} self.database.insert("gm_kingdom",attribs) result = self.database.select("*","gm_kingdom",True,'name=="'+kingdom_name+'"') self.nb_kingdom_inserted[1] = self.nb_kingdom_inserted[1] + 1 else: self.nb_kingdom_unchanged[1] = self.nb_kingdom_unchanged[1] + 1 return result def addGroupe(self, group,id_kingdom,id_group_parent=0): #on suppose que chaque groupe a un nom unique pour un royaume donne result = self.database.select("*","gm_groupe",True,'name=="'+group+'" AND ID_kingdom=='+str(id_kingdom)) if result.first() == 0 : attribs = {'name':group,'ID_kingdom':id_kingdom,'description':self.defaultValues['groupe_description'],'color':self.defaultValues['groupe_color'],'rank':self.defaultValues['groupe_rank'],'parent':id_group_parent} self.database.insert("gm_groupe",attribs) result = self.database.select("*","gm_groupe",True,'name=="'+group+'" AND ID_kingdom=='+str(id_kingdom)) print ('add groupe ',group,id_kingdom) self.nb_groupes_inserted[1] = self.nb_groupes_inserted[1] + 1 else: self.nb_groupe_unchanged[1] = self.nb_groupe_unchanged[1] + 1 return result def addHeros (self,heros,id_groupe): #on suppose que chaque heros a un nom unique pour un groupe result = self.database.select("*","gm_perso",True,'name=="'+heros+'" AND ID_groupe=='+str(id_groupe)) if result.first() == 0 : attribs = {'name':heros,'ID_groupe':id_groupe,'description':self.defaultValues['heros_description'],'techniques':self.defaultValues['heros_techniques'],'historique':self.defaultValues['heros_historique'],'latitude':self.defaultValues['heros_latitude'],'longitude':self.defaultValues['heros_longitude'],'place':self.defaultValues['heros_place'],"level":"",'leader':self.defaultValues['heros_level'],'rank':self.defaultValues['heros_rank'],'status':self.defaultValues['heros_status'],'complete':1,'HP':1,'MP':1,'HP_max':1,'MP_max':1,'ATK':0,'DEF':0,'MATK':0,'MATK':0,'AGL':0,'LUCK':0} self.database.insert("gm_perso",attribs) #print ('attribs',attribs) result = self.database.select("*","gm_perso",True,'name=="'+heros+'" AND ID_groupe=='+str(id_groupe)) self.nb_heros_inserted[1] = self.nb_heros_inserted[1] + 1 else: self.nb_heros_unchanged[1] = self.nb_heros_unchanged[1] + 1 return result @staticmethod def hasSubGroup (path): sub_list = os.listdir (path) print ('hasSubGroup',sub_list) if len(sub_list)!= 0 and os.path.isdir(os.path.join(path,sub_list[0])): sub_list2 = os.listdir(os.path.join(path,sub_list[0])) print ('sub_list_2',sub_list2) if os.path.isdir(os.path.join(path,sub_list[0],sub_list2[0])): print ('return true') return True return False def process (self, faction,empire,kingdom): super(ExportToSqlite,self).process(faction,empire,kingdom) self.progress.setLabelText("Export to sqlite") self.progress.setMinimum(0) self.progress.setMaximum(self.total_heros) self.success = False nb_heros = 0 #si la faction n existe pas encore la creer result = self.addFaction (self.faction) result.next() print ('result',result.value("name")) id_faction = result.value("ID") print ('ID faction',id_faction) #si l empire n existe pas encore le creer color = "" empire = self.empire if len(self.empire.split["-"])>=2 : color = self.empire.split["-"][1] empire = self.empire.split["-"][0] result = self.addEmpire(empire,id_faction,color) result.next() id_empire= result.value("ID") print ('ID empire',id_empire) #si le royaume n existe pas encore le creer result = self.addKingdom(self.kingdom,id_empire) result.next() id_kingdom= result.value("ID") print ('ID kingdom',id_kingdom) list_group = list(filter(SqliteModel.isValid,os.listdir (self.fullPath))) for group in list_group : result = self.addGroupe(group,id_kingdom) result.next() id_groupe= result.value("ID") currentPath = os.path.join(self.fullPath,group) if (ExportToSqlite.hasSubGroup(currentPath)): list_sub_group = list(filter(SqliteModel.isValid,os.listdir(currentPath))) id_master_group = id_groupe for sub in list_sub_group : result = self.addGroupe(sub, id_kingdom, id_master_group) result.next() id_groupe= result.value("ID") list_heros = list(filter(SqliteModel.isValid,os.listdir(os.path.join(currentPath,sub)))) for heros in list_heros : self.createDescriptionFile(heros,os.path.join(currentPath,sub,heros)) self.addHeros(heros,id_groupe) nb_heros+=1 self.progress.setValue(nb_heros) else: list_heros = list(filter(SqliteModel.isValid,os.listdir(currentPath))) for heros in list_heros : self.createDescriptionFile(heros,os.path.join(currentPath,heros)) self.success = True self.addHeros(heros,id_groupe) nb_heros+=1 self.progress.setValue(nb_heros) if self.stop == True : break self.progress.setValue(self.total_heros) result_info = [self.nb_faction_inserted,self.nb_empire_inserted,self.nb_kingdom_inserted,self.nb_groupes_inserted,self.nb_heros_inserted,self.nb_faction_unchanged,self.nb_empire_unchanged,self.nb_kingdom_unchanged,self.nb_groupes_unchanged,self.nb_heros_unchanged] self.showResultInfos(result_info) def createDescriptionFile(self, name, path_file): file_name = "description.html" file = open(os.path.join(Config().instance.settings.value("global/resources_path"),"template_profil.html")) ddd = file.read() print ('ooooo',type(ddd)) ddd = ddd.replace("tname",name) print ('mmmm',ddd) chemin = os.path.join(path_file,file_name) if (not os.path.exists(chemin)): self.textEdit = QTextEdit() self.textEdit.setText(ddd) writer = QTextDocumentWriter(chemin) success = writer.write(self.textEdit.document())
class ThemeCreateDialog(Dialog): def __init__(self, parent, report): self.report = report Dialog.__init__(self, _('Create an icon theme'), 'create-icon-theme', parent) def setup_ui(self): self.splitter = QSplitter(self) self.l = l = QVBoxLayout(self) l.addWidget(self.splitter) l.addWidget(self.bb) self.w = w = QGroupBox(_('Theme Metadata'), self) self.splitter.addWidget(w) l = w.l = QFormLayout(w) l.setFieldGrowthPolicy( QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow) self.missing_icons_group = mg = QGroupBox(self) self.mising_icons = mi = QListWidget(mg) mi.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection) mg.l = QVBoxLayout(mg) mg.l.addWidget(mi) self.splitter.addWidget(mg) self.title = QLineEdit(self) l.addRow(_('&Title:'), self.title) self.author = QLineEdit(self) l.addRow(_('&Author:'), self.author) self.version = v = QSpinBox(self) v.setMinimum(1), v.setMaximum(1000000) l.addRow(_('&Version:'), v) self.license = lc = QLineEdit(self) l.addRow(_('&License:'), lc) self.url = QLineEdit(self) l.addRow(_('&URL:'), self.url) lc.setText( _('The license for the icons in this theme. Common choices are' ' Creative Commons or Public Domain.')) self.description = QTextEdit(self) l.addRow(self.description) self.refresh_button = rb = self.bb.addButton( _('&Refresh'), QDialogButtonBox.ButtonRole.ActionRole) rb.setIcon(QIcon(I('view-refresh.png'))) rb.clicked.connect(self.refresh) self.apply_report() def sizeHint(self): return QSize(900, 670) @property def metadata(self): self.report.theme.title = self.title.text().strip( ) # Needed for report.name to work return { 'title': self.title.text().strip(), 'author': self.author.text().strip(), 'version': self.version.value(), 'description': self.description.toPlainText().strip(), 'number': len(self.report.name_map) - len(self.report.extra), 'date': utcnow().date().isoformat(), 'name': self.report.name, 'license': self.license.text().strip() or 'Unknown', 'url': self.url.text().strip() or None, } def save_metadata(self): data = json.dumps(self.metadata, indent=2) if not isinstance(data, bytes): data = data.encode('utf-8') with open(os.path.join(self.report.path, THEME_METADATA), 'wb') as f: f.write(data) def refresh(self): self.save_metadata() self.report = read_theme_from_folder(self.report.path) self.apply_report() def apply_report(self): theme = self.report.theme self.title.setText((theme.title or '').strip()) self.author.setText((theme.author or '').strip()) self.version.setValue(theme.version or 1) self.description.setText((theme.description or '').strip()) self.license.setText((theme.license or 'Unknown').strip()) self.url.setText((theme.url or '').strip()) if self.report.missing: title = _('%d icons missing in this theme') % len( self.report.missing) else: title = _('No missing icons') self.missing_icons_group.setTitle(title) mi = self.mising_icons mi.clear() for name in sorted(self.report.missing): QListWidgetItem(QIcon(I(name, allow_user_override=False)), name, mi) def accept(self): mi = self.metadata if not mi.get('title'): return error_dialog( self, _('No title specified'), _('You must specify a title for this icon theme'), show=True) if not mi.get('author'): return error_dialog( self, _('No author specified'), _('You must specify an author for this icon theme'), show=True) return Dialog.accept(self)
class PrefsViewerDialog(SizePersistedDialog): def __init__(self, gui, namespace): super(PrefsViewerDialog, self).__init__(gui, _('Prefs Viewer dialog')) self.setWindowTitle(_('Preferences for: ') + namespace) self.gui = gui self.db = gui.current_db self.namespace = namespace self._init_controls() self.resize_dialog() self._populate_settings() if self.keys_list.count(): self.keys_list.setCurrentRow(0) def _init_controls(self): layout = QVBoxLayout(self) self.setLayout(layout) ml = QHBoxLayout() layout.addLayout(ml, 1) self.keys_list = QListWidget(self) self.keys_list.setSelectionMode(QAbstractItemView.SingleSelection) self.keys_list.setFixedWidth(150) self.keys_list.setAlternatingRowColors(True) ml.addWidget(self.keys_list) self.value_text = QTextEdit(self) self.value_text.setTabStopWidth(24) self.value_text.setReadOnly(False) ml.addWidget(self.value_text, 1) button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) button_box.accepted.connect(self._apply_changes) button_box.rejected.connect(self.reject) self.clear_button = button_box.addButton(_('Clear'), QDialogButtonBox.ResetRole) self.clear_button.setIcon(get_icon('trash.png')) self.clear_button.setToolTip(_('Clear all settings for this plugin')) self.clear_button.clicked.connect(self._clear_settings) layout.addWidget(button_box) def _populate_settings(self): self.keys_list.clear() ns_prefix = self._get_ns_prefix() keys = sorted([k[len(ns_prefix):] for k in list(self.db.prefs.keys()) if k.startswith(ns_prefix)]) for key in keys: self.keys_list.addItem(key) self.keys_list.setMinimumWidth(self.keys_list.sizeHintForColumn(0)) self.keys_list.currentRowChanged[int].connect(self._current_row_changed) def _current_row_changed(self, new_row): if new_row < 0: self.value_text.clear() return key = unicode(self.keys_list.currentItem().text()) val = self.db.prefs.get_namespaced(self.namespace, key, '') self.value_text.setPlainText(self.db.prefs.to_raw(val)) def _get_ns_prefix(self): return 'namespaced:%s:'% self.namespace def _apply_changes(self): from calibre.gui2.dialogs.confirm_delete import confirm message = '<p>Are you sure you want to change your settings in this library for this plugin?</p>' \ '<p>Any settings in other libraries or stored in a JSON file in your calibre plugins ' \ 'folder will not be touched.</p>' \ '<p>You must restart calibre afterwards.</p>' if not confirm(message, self.namespace+'_clear_settings', self): return val = self.db.prefs.raw_to_object(unicode(self.value_text.toPlainText())) key = unicode(self.keys_list.currentItem().text()) self.db.prefs.set_namespaced(self.namespace, key, val) restart = prompt_for_restart(self, 'Settings changed', '<p>Settings for this plugin in this library have been changed.</p>' '<p>Please restart calibre now.</p>') self.close() if restart: self.gui.quit(restart=True) def _clear_settings(self): from calibre.gui2.dialogs.confirm_delete import confirm message = '<p>Are you sure you want to clear your settings in this library for this plugin?</p>' \ '<p>Any settings in other libraries or stored in a JSON file in your calibre plugins ' \ 'folder will not be touched.</p>' \ '<p>You must restart calibre afterwards.</p>' if not confirm(message, self.namespace+'_clear_settings', self): return ns_prefix = self._get_ns_prefix() keys = [k for k in list(self.db.prefs.keys()) if k.startswith(ns_prefix)] for k in keys: del self.db.prefs[k] self._populate_settings() restart = prompt_for_restart(self, _('Settings deleted'), _('<p>All settings for this plugin in this library have been cleared.</p>') + _('<p>Please restart calibre now.</p>')) self.close() if restart: self.gui.quit(restart=True)
def __init__(self, main): super(GameListWidget, self).__init__() self.main_win = main self.keystore_exchanged = False self.setObjectName("GameListWidget") v_layout = QVBoxLayout() h_layout1 = QHBoxLayout() self.game_list_view = QListView() self.game_list_view.setViewMode(QListView.ListMode) self.game_list_view.setEditTriggers(QAbstractItemView.NoEditTriggers) self.game_list_model = GameListModel(self.main_win.games) self.game_list_view.setModel(self.game_list_model) self.game_list_view.clicked.connect(self.list_item_onclick) h_layout1.addWidget(self.game_list_view, 1) self.game_list_view.setCurrentIndex( self.game_list_model.index(self.main_win.game_index)) self.game = self.main_win.games[self.main_win.game_index] form_layout = QFormLayout() form_layout.setContentsMargins(20, 50, 20, 50) self.game_name_value = QLineEdit() form_layout.addRow("游戏名称:", self.game_name_value) self.game_desc_value = QTextEdit() form_layout.addRow("游戏简介:", self.game_desc_value) self.game_appid_value = QLabel() self.game_appid_value.setTextInteractionFlags(Qt.TextSelectableByMouse) form_layout.addRow("游戏ID:", self.game_appid_value) self.game_appkey_value = QLabel() self.game_appkey_value.setTextInteractionFlags( Qt.TextSelectableByMouse) form_layout.addRow("客户端Key:", self.game_appkey_value) h_layout = QHBoxLayout() self.keystore_path = QLineEdit() select_key_btn = QPushButton("浏览") select_key_btn.setStyleSheet('QPushButton{border-radius: 0px;}') select_key_btn.clicked.connect(self.select_ketstore) h_layout.addWidget(self.keystore_path) h_layout.addWidget(select_key_btn) form_layout.addRow("KeyStore:", h_layout) self.keystore_pwd_value = QLineEdit() form_layout.addRow("KeyPass:"******"Alias:", self.keystore_alias_value) self.keystore_aliaspwd_value = QLineEdit() form_layout.addRow("AliasPass:"******"更换Icon") icon_exchange_btn.setFixedWidth(100) icon_exchange_btn.clicked.connect(self.exchange_icon) v_layout1.addWidget(icon_exchange_btn, alignment=Qt.AlignHCenter) v_layout1.addStretch(2) h_layout1.addLayout(v_layout1, 1) v_layout.addLayout(h_layout1) h_layout2 = QHBoxLayout() create_game_btn = QPushButton("返 回") create_game_btn.setFixedWidth(100) create_game_btn.clicked.connect(self.back) h_layout2.addWidget(create_game_btn, alignment=Qt.AlignLeft | Qt.AlignBottom) back_btn = QPushButton("创建游戏") back_btn.setFixedWidth(100) back_btn.clicked.connect(self.add_game) h_layout2.addWidget(back_btn, alignment=Qt.AlignHCenter) next_btn = QPushButton("下一步") next_btn.setFixedWidth(100) next_btn.clicked.connect(self.next) h_layout2.addWidget(next_btn, alignment=Qt.AlignRight | Qt.AlignBottom) v_layout.addLayout(h_layout2) self.setLayout(v_layout) self.set_game_info()
def setupUi(self): self.setObjectName("Dialog") self.resize(1024, 700) self.setWindowIcon(QIcon(I('convert.png'))) self.gridLayout = QGridLayout(self) self.gridLayout.setObjectName("gridLayout") self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.input_label = QLabel(self) self.input_label.setObjectName("input_label") self.horizontalLayout.addWidget(self.input_label) self.input_formats = QComboBox(self) self.input_formats.setSizeAdjustPolicy( QComboBox.AdjustToMinimumContentsLengthWithIcon) self.input_formats.setMinimumContentsLength(5) self.input_formats.setObjectName("input_formats") self.horizontalLayout.addWidget(self.input_formats) self.opt_individual_saved_settings = QCheckBox(self) self.opt_individual_saved_settings.setObjectName( "opt_individual_saved_settings") self.horizontalLayout.addWidget(self.opt_individual_saved_settings) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.label_2 = QLabel(self) self.label_2.setObjectName("label_2") self.horizontalLayout.addWidget(self.label_2) self.output_formats = QComboBox(self) self.output_formats.setSizeAdjustPolicy( QComboBox.AdjustToMinimumContentsLengthWithIcon) self.output_formats.setMinimumContentsLength(5) self.output_formats.setObjectName("output_formats") self.horizontalLayout.addWidget(self.output_formats) self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 2) self.groups = QListView(self) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.groups.sizePolicy().hasHeightForWidth()) self.groups.setSizePolicy(sizePolicy) self.groups.setTabKeyNavigation(True) self.groups.setIconSize(QSize(48, 48)) self.groups.setWordWrap(True) self.groups.setObjectName("groups") self.gridLayout.addWidget(self.groups, 1, 0, 3, 1) self.scrollArea = QScrollArea(self) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(4) sizePolicy.setVerticalStretch(10) sizePolicy.setHeightForWidth( self.scrollArea.sizePolicy().hasHeightForWidth()) self.scrollArea.setSizePolicy(sizePolicy) self.scrollArea.setFrameShape(QFrame.NoFrame) self.scrollArea.setLineWidth(0) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName("scrollArea") self.scrollAreaWidgetContents = QWidget() self.scrollAreaWidgetContents.setGeometry(QRect(0, 0, 810, 494)) self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") self.verticalLayout_3 = QVBoxLayout(self.scrollAreaWidgetContents) self.verticalLayout_3.setContentsMargins(0, 0, 0, 0) self.verticalLayout_3.setObjectName("verticalLayout_3") self.stack = QStackedWidget(self.scrollAreaWidgetContents) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.stack.sizePolicy().hasHeightForWidth()) self.stack.setSizePolicy(sizePolicy) self.stack.setObjectName("stack") self.page = QWidget() self.page.setObjectName("page") self.stack.addWidget(self.page) self.page_2 = QWidget() self.page_2.setObjectName("page_2") self.stack.addWidget(self.page_2) self.verticalLayout_3.addWidget(self.stack) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.gridLayout.addWidget(self.scrollArea, 1, 1, 1, 1) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok | QDialogButtonBox.RestoreDefaults) self.buttonBox.setObjectName("buttonBox") self.gridLayout.addWidget(self.buttonBox, 3, 1, 1, 1) self.help = QTextEdit(self) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.help.sizePolicy().hasHeightForWidth()) self.help.setSizePolicy(sizePolicy) self.help.setMaximumHeight(80) self.help.setObjectName("help") self.gridLayout.addWidget(self.help, 2, 1, 1, 1) self.input_label.setBuddy(self.input_formats) self.label_2.setBuddy(self.output_formats) self.input_label.setText(_("&Input format:")) self.opt_individual_saved_settings.setText( _("Use &saved conversion settings for individual books")) self.label_2.setText(_("&Output format:")) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject)
def initialize(self, service): """ Inititialize Service QWidget :param service: service data :type service: dict """ layout = QGridLayout() self.setLayout(layout) layout.addWidget(self.get_service_icon(service['ls_state']), 0, 0, 2, 1) if service['display_name'] != '': service_name = service['display_name'] elif service['alias'] != '': service_name = service['alias'] else: service_name = service['name'] # Service name service_label = QLabel() if get_app_config('Alignak', 'webui'): service_label.setText( '<h3><a href="%s" style="color: black; text-decoration: none">%s</a></h3>' % (get_app_config('Alignak', 'webui') + '/service/' + service['_id'], service_name)) else: service_label.setText('<h3>%s</h3>' % service_name) service_label.setTextInteractionFlags(Qt.TextBrowserInteraction) service_label.setOpenExternalLinks(True) service_label.setToolTip('Service is %s. See in WebUI ?' % service['ls_state']) service_label.setObjectName(service['ls_state']) service_label.setMinimumWidth(200) service_label.setWordWrap(True) layout.addWidget(service_label, 0, 1, 2, 1) layout.setAlignment(service_label, Qt.AlignLeft) # Buttons self.acknowledge_btn = QPushButton() self.acknowledge_btn.setIcon( QIcon(get_image_path('services_acknowledge'))) self.acknowledge_btn.setFixedSize(25, 25) self.acknowledge_btn.setToolTip('Acknowledge this service') layout.addWidget(self.acknowledge_btn, 0, 2, 1, 1) self.downtime_btn = QPushButton() self.downtime_btn.setIcon(QIcon(get_image_path('services_downtime'))) self.downtime_btn.setFixedSize(25, 25) self.downtime_btn.setToolTip('Schedule a downtime for this service') layout.addWidget(self.downtime_btn, 1, 2, 1, 1) # Last check since_last_check = get_diff_since_last_check( service['ls_last_state_changed']) diff_last_check = get_diff_since_last_check(service['ls_last_check']) last_check = QLabel('<b>Since:</b> %s, <b>Last check:</b> %s' % (since_last_check, diff_last_check)) layout.addWidget(last_check, 0, 3, 1, 2) # Output date_output = get_date_from_timestamp(service['ls_last_check']) output = QTextEdit('<b>Output:</b> [%s] %s' % (date_output, service['ls_output'])) output.setObjectName('output') output.setToolTip(service['ls_output']) output.setTextInteractionFlags(Qt.TextSelectableByMouse) output.setFont(QFont('Times', 13)) layout.addWidget(output, 1, 3, 2, 4) # Service details business_impact = self.get_stars_widget(int( service['business_impact'])) layout.addWidget(business_impact, 2, 0, 1, 2) layout.setAlignment(business_impact, Qt.AlignLeft) self.add_services_details(service, layout)
class ConfigWidget(QWidget): def __init__(self): QWidget.__init__(self) self.setWindowTitle('exlibris preferences') row = 0 self.l = QGridLayout() self.setLayout(self.l) self.label_xhtml_filename = QLabel('Ex libris XHTML filename:') self.xhtml_filename = QLineEdit(self) self.xhtml_filename.setText(prefs['xhtml_filename']) self.button_xhtml_filename = QPushButton('Change', self) self.button_xhtml_filename.clicked.connect(self.button_xhtml_filename_handler) self.l.addWidget(self.label_xhtml_filename, row, 1) row += 1 self.l.addWidget(self.xhtml_filename, row, 1) self.l.addWidget(self.button_xhtml_filename, row, 2) row += 1 self.l.addWidget(QLabel(''), row, 1) row += 1 self.label_include_dir = QLabel('Include additional files from directory:') self.checkbox_include_dir = QCheckBox('', self) self.checkbox_include_dir.setChecked(prefs['checkbox_include_dir'] == 'True') self.include_dir = QLineEdit(self) self.include_dir.setText(prefs['include_dir']) self.button_include_dir = QPushButton('Change', self) self.button_include_dir.clicked.connect(self.button_include_dir_handler) self.l.addWidget(self.checkbox_include_dir, row, 0) self.l.addWidget(self.label_include_dir, row, 1) row += 1 self.l.addWidget(self.include_dir, row, 1) self.l.addWidget(self.button_include_dir, row, 2) row += 1 self.l.addWidget(QLabel(''), row, 1) row += 1 self.label_include_guide_text = QLabel('Include in guide with string:') self.checkbox_include_guide_text = QCheckBox('', self) self.checkbox_include_guide_text.setChecked(prefs['checkbox_include_guide_text'] == 'True') self.include_guide_text = QLineEdit(self) self.include_guide_text.setText(prefs['include_guide_text']) self.l.addWidget(self.checkbox_include_guide_text, row, 0) self.l.addWidget(self.label_include_guide_text, row, 1) row += 1 self.l.addWidget(self.include_guide_text, row, 1) row += 1 self.l.addWidget(QLabel(''), row, 1) row += 1 self.label_include_toc_text = QLabel('Include in TOC with string:') self.checkbox_include_toc_text = QCheckBox('', self) self.checkbox_include_toc_text.setChecked(prefs['checkbox_include_toc_text'] == 'True') self.include_toc_text = QLineEdit(self) self.include_toc_text.setText(prefs['include_toc_text']) self.l.addWidget(self.checkbox_include_toc_text, row, 0) self.l.addWidget(self.label_include_toc_text, row, 1) row += 1 self.l.addWidget(self.include_toc_text, row, 1) row += 1 self.l.addWidget(QLabel(''), row, 1) row += 1 self.label_ask_replace = QLabel('Ask before replacing book in library') self.checkbox_ask_replace = QCheckBox('', self) self.checkbox_ask_replace.setChecked(prefs['checkbox_ask_replace'] == 'True') self.l.addWidget(self.checkbox_ask_replace, row, 0) self.l.addWidget(self.label_ask_replace, row, 1) row += 1 self.label_disable_first_last_only = QLabel('When multiple EPUB files are selected, allow insertion points other than "1", "first", and "last"') self.checkbox_disable_first_last_only = QCheckBox('', self) self.checkbox_disable_first_last_only.setChecked(prefs['checkbox_disable_first_last_only'] == 'True') self.l.addWidget(self.checkbox_disable_first_last_only, row, 0) self.l.addWidget(self.label_disable_first_last_only, row, 1) row += 1 self.l.addWidget(QLabel(''), row, 1) row += 1 self.label_replace_strings = QLabel('Replace strings:') self.replace_strings = QTextEdit(self) self.replace_strings.setText(prefs['replace_strings']) self.label_supportedMetadata = QLabel('Supported metadata:') self.supportedMetadata = QListWidget(self) #QtCore.QObject.connect(self.supportedMetadata, QtCore.SIGNAL("doubleClicked()"), self.add_replace_string) self.supportedMetadata.doubleClicked.connect(self.add_replace_string) producer = exlibris() tags = producer.getSupportedMetadataList() for tag in tags: self.supportedMetadata.addItem(tag.decode('utf-8')) self.l.addWidget(self.label_replace_strings, row, 1) self.l.addWidget(self.label_supportedMetadata, row, 2) row += 1 self.l.addWidget(self.replace_strings, row, 1) self.l.addWidget(self.supportedMetadata, row, 2) row += 1 self.resize(self.sizeHint()) def add_replace_string(self): currentText = str(self.replace_strings.toPlainText()).strip() currentItem = self.supportedMetadata.currentItem().text() self.replace_strings.setText("%s\n%s=your_value_goes_here;" % (currentText, currentItem)) def button_xhtml_filename_handler(self): initial_dir = os.path.dirname(str(self.xhtml_filename.text())) new_file = QFileDialog.getOpenFileName(self, "Select ex libris XHTML file", initial_dir, "XHTML Files (*.xhtml)") if new_file: new_file = new_file[0] if isinstance(new_file, tuple) else new_file if new_file and os.path.exists(new_file): self.xhtml_filename.setText(new_file) def button_include_dir_handler(self): initial_dir = os.path.dirname(str(self.include_dir.text())) dirDialog = QFileDialog() dirDialog.setFileMode(QFileDialog.Directory) new_dir = dirDialog.getExistingDirectory(self, "Select directory", initial_dir) if (len(new_dir) > 0): self.include_dir.setText(new_dir) def save_settings(self): prefs['xhtml_filename'] = unicode(self.xhtml_filename.text()) prefs['include_dir'] = unicode(self.include_dir.text()) prefs['include_guide_text'] = unicode(self.include_guide_text.text()) prefs['include_toc_text'] = unicode(self.include_toc_text.text()) prefs['replace_strings'] = unicode(self.replace_strings.toPlainText()) prefs['checkbox_include_dir'] = unicode(self.checkbox_include_dir.isChecked()) prefs['checkbox_include_guide_text'] = unicode(self.checkbox_include_guide_text.isChecked()) prefs['checkbox_include_toc_text'] = unicode(self.checkbox_include_toc_text.isChecked()) prefs['checkbox_ask_replace'] = unicode(self.checkbox_ask_replace.isChecked()) prefs['checkbox_disable_first_last_only'] = unicode(self.checkbox_disable_first_last_only.isChecked()) # TODO: save value from main.py (?) prefs['include_spine'] = u'1' prefs['include_toc'] = u'1'