def initialize(self): """ Initialize QWidget """ layout = QHBoxLayout() self.setLayout(layout) self.services_title.setObjectName('itemtitle') layout.addWidget(self.services_title) layout.setAlignment(self.services_title, Qt.AlignLeft) icons_widget = QWidget() icons_layout = QHBoxLayout() icons_widget.setLayout(icons_layout) for icon in Service.get_available_icons(): state = icon.replace('services_', '').upper() icon_pixmap = QIcon(settings.get_image(icon)) self.states_btns[state].setIcon(icon_pixmap) self.states_btns[state].setFixedSize(20, 20) self.states_btns[state].setToolTip(state) self.states_btns[state].setCheckable(True) self.states_btns[state].setObjectName('services') icons_layout.addWidget(self.states_btns[state]) self.nb_labels[state].setObjectName(get_icon_name_from_state('service', state)) icons_layout.addWidget(self.nb_labels[state]) layout.addWidget(icons_widget) layout.setAlignment(icons_widget, Qt.AlignRight)
def initialize(self, item): """ Initialize Actions QWidget, with ack and downtime buttons """ self.item = item layout = QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.acknowledge_btn.setIcon(QIcon(settings.get_image('acknowledge'))) self.acknowledge_btn.setFixedSize(80, 20) self.acknowledge_btn.clicked.connect(self.add_acknowledge) self.acknowledge_btn.setToolTip(_('Acknowledge the current item')) layout.addWidget(self.acknowledge_btn) self.downtime_btn.setIcon(QIcon(settings.get_image('downtime'))) self.downtime_btn.setFixedSize(80, 20) self.downtime_btn.clicked.connect(self.add_downtime) self.downtime_btn.setToolTip(_('Schedule a Downtime on current item')) layout.addWidget(self.downtime_btn) layout.setAlignment(Qt.AlignCenter)
def initialize(self): """ Initialize QWidget """ layout = QHBoxLayout() self.setLayout(layout) self.services_title.setObjectName('itemtitle') layout.addWidget(self.services_title) layout.setAlignment(self.services_title, Qt.AlignLeft) icons_widget = QWidget() icons_layout = QHBoxLayout() icons_widget.setLayout(icons_layout) for icon in Service.get_available_icons(): state = icon.replace('services_', '').upper() icon_pixmap = QIcon(settings.get_image(icon)) self.states_btns[state].setIcon(icon_pixmap) self.states_btns[state].setFixedSize(20, 20) self.states_btns[state].setToolTip(state) self.states_btns[state].setCheckable(True) self.states_btns[state].setObjectName('services') icons_layout.addWidget(self.states_btns[state]) self.nb_labels[state].setObjectName( get_icon_name_from_state('service', state)) icons_layout.addWidget(self.nb_labels[state]) layout.addWidget(icons_widget) layout.setAlignment(icons_widget, Qt.AlignRight)
class _HomeTab(QWidget): """Home tab which contains information about EvilOSX.""" def __init__(self): super().__init__() self._layout = QHBoxLayout() self.setLayout(self._layout) message_label = QLabel("""\ Welcome to <b>EvilOSX</b>:<br/> An evil RAT (Remote Administration Tool) for macOS / OS X.<br/><br/><br/> Author: Marten4n6<br/> License: GPLv3<br/> Version: <b>{}</b> """.format(VERSION)) logo_label = QLabel() logo_path = path.join(path.dirname(__file__), path.pardir, path.pardir, "data", "images", "logo_334x600.png") logo_label.setPixmap(QPixmap(logo_path)) self._layout.setAlignment(Qt.AlignCenter) self._layout.setSpacing(50) self._layout.addWidget(message_label) self._layout.addWidget(logo_label)
def initialize(self, item): """ Initialize Actions QWidget, with ack and downtime buttons """ self.item = item layout = QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) self.acknowledge_btn.setIcon(QIcon(settings.get_image('acknowledge'))) self.acknowledge_btn.setFixedSize(80, 20) self.acknowledge_btn.clicked.connect(self.add_acknowledge) self.acknowledge_btn.setToolTip(_('Acknowledge the current item')) layout.addWidget(self.acknowledge_btn) self.downtime_btn.setIcon(QIcon(settings.get_image('downtime'))) self.downtime_btn.setFixedSize(80, 20) self.downtime_btn.clicked.connect(self.add_downtime) self.downtime_btn.setToolTip(_('Schedule a Downtime on current item')) layout.addWidget(self.downtime_btn) layout.setAlignment(Qt.AlignCenter)
def get_btn_widget(self): """ Return QWidget with spy and host synthesis QPushButtons :return: widget with spy and host button :rtype: QWidget """ widget_btn = QWidget() layout_btn = QHBoxLayout() layout_btn.setContentsMargins(0, 0, 0, 5) widget_btn.setLayout(layout_btn) host_filter = QLabel(_('Filter hosts')) host_filter.setObjectName('subtitle') layout_btn.addWidget(host_filter) self.filter_hosts_btn.initialize() self.filter_hosts_btn.update_btn_state(False) self.filter_hosts_btn.toggle_btn.clicked.connect( lambda: self.update_problems_data('host')) layout_btn.addWidget(self.filter_hosts_btn) service_filter = QLabel(_('Filter services')) service_filter.setObjectName('subtitle') layout_btn.addWidget(service_filter) self.filter_services_btn.initialize() self.filter_services_btn.update_btn_state(False) self.filter_services_btn.toggle_btn.clicked.connect( lambda: self.update_problems_data('service')) layout_btn.addWidget(self.filter_services_btn) layout_btn.addStretch() self.host_btn.setIcon(QIcon(settings.get_image('host'))) self.host_btn.setFixedSize(80, 20) self.host_btn.setEnabled(False) self.host_btn.setToolTip(_('See current item in synthesis view')) layout_btn.addWidget(self.host_btn) self.spy_btn.setIcon(QIcon(settings.get_image('spy'))) self.spy_btn.setFixedSize(80, 20) self.spy_btn.setEnabled(False) self.spy_btn.setToolTip(_('Spy current host')) self.spy_btn.clicked.connect(self.add_spied_host) layout_btn.addWidget(self.spy_btn) self.actions_widget.initialize(None) self.actions_widget.acknowledge_btn.setEnabled(False) self.actions_widget.downtime_btn.setEnabled(False) layout_btn.addWidget(self.actions_widget) layout_btn.setAlignment(Qt.AlignCenter) return widget_btn
def get_btn_widget(self): """ Return QWidget with spy and host synthesis QPushButtons :return: widget with spy and host button :rtype: QWidget """ widget_btn = QWidget() layout_btn = QHBoxLayout() layout_btn.setContentsMargins(0, 0, 0, 5) widget_btn.setLayout(layout_btn) host_filter = QLabel(_('Filter hosts')) host_filter.setObjectName('subtitle') layout_btn.addWidget(host_filter) self.filter_hosts_btn.initialize() self.filter_hosts_btn.update_btn_state(False) self.filter_hosts_btn.toggle_btn.clicked.connect(lambda: self.update_problems_data('host')) layout_btn.addWidget(self.filter_hosts_btn) service_filter = QLabel(_('Filter services')) service_filter.setObjectName('subtitle') layout_btn.addWidget(service_filter) self.filter_services_btn.initialize() self.filter_services_btn.update_btn_state(False) self.filter_services_btn.toggle_btn.clicked.connect( lambda: self.update_problems_data('service') ) layout_btn.addWidget(self.filter_services_btn) layout_btn.addStretch() self.host_btn.setIcon(QIcon(settings.get_image('host'))) self.host_btn.setFixedSize(80, 20) self.host_btn.setEnabled(False) self.host_btn.setToolTip(_('See current item in synthesis view')) layout_btn.addWidget(self.host_btn) self.spy_btn.setIcon(QIcon(settings.get_image('spy'))) self.spy_btn.setFixedSize(80, 20) self.spy_btn.setEnabled(False) self.spy_btn.setToolTip(_('Spy current host')) self.spy_btn.clicked.connect(self.add_spied_host) layout_btn.addWidget(self.spy_btn) self.actions_widget.initialize(None) self.actions_widget.acknowledge_btn.setEnabled(False) self.actions_widget.downtime_btn.setEnabled(False) layout_btn.addWidget(self.actions_widget) layout_btn.setAlignment(Qt.AlignCenter) return widget_btn
def __init__(self, parent=None): QWidget.__init__(self, parent) layout = QHBoxLayout() self.sbx = QSpinBox() self.sby = QSpinBox() self.sbx.setRange(0, 1000) self.sby.setRange(0, 1000) lb = QLabel('x') lb.setSizePolicy(Qt.QSizePolicy.Minimum, Qt.QSizePolicy.Minimum) layout.addWidget(lb) self.sbx.setSizePolicy(Qt.QSizePolicy.Maximum, Qt.QSizePolicy.Maximum) layout.addWidget(self.sbx) lby = QLabel('y') lby.setSizePolicy(Qt.QSizePolicy.Minimum, Qt.QSizePolicy.Minimum) layout.addWidget(lby) layout.setAlignment(Qt.Qt.AlignLeft) layout.addWidget(self.sby) self.setLayout(layout)
def _initialize_navigation_buttons(self, v_layout, previous_button, next_button): '''Add previous, ok, cancel, and next buttons''' buttons_layout = QHBoxLayout(None) buttons_layout.setAlignment(Qt.AlignRight) if len(self._book_settings) > 1: buttons_layout.addWidget(previous_button) ok_button = QPushButton('OK') ok_button.setFixedWidth(100) ok_button.clicked.connect(self.ok_clicked) buttons_layout.addWidget(ok_button) cancel_button = QPushButton('Cancel') cancel_button.setFixedWidth(100) cancel_button.clicked.connect(self.cancel_clicked) buttons_layout.addWidget(cancel_button) if len(self._book_settings) > 1: buttons_layout.addWidget(next_button) v_layout.addLayout(buttons_layout)
def _initialize_navigation_buttons(self, v_layout, previous_button, next_button): '''Add previous, ok, cancel, and next buttons''' buttons_layout = QHBoxLayout(None) buttons_layout.setAlignment(Qt.AlignRight) if len(self._book_settings) > 1: buttons_layout.addWidget(previous_button) ok_button = QPushButton('OK') ok_button.setFixedWidth(100) ok_button.clicked.connect(self.ok_clicked) buttons_layout.addWidget(ok_button) cancel_button = QPushButton('Cancel') cancel_button.setFixedWidth(100) cancel_button.clicked.connect(self.cancel_clicked) buttons_layout.addWidget(cancel_button) if len(self._book_settings) > 1: buttons_layout.addWidget(next_button) v_layout.addLayout(buttons_layout)
def setup_ui(self): layout = QVBoxLayout() self.setLayout(layout) columns_frame = QHBoxLayout() layout.addLayout(columns_frame) # How many columns of nine items each will it take to display # a text box for each tag in taglist? col_limit = 9 num_cols = len(TAGLIST)/col_limit num_cols = int(math.ceil(num_cols)) # If the column limit and the number of columns produces a single # orphan text entry widget, reduce the column limit accordingly. if num_cols > 1 and (len(TAGLIST) - ((num_cols - 1)*col_limit)) < 2: if num_cols >= 3: col_limit -= 1 # Create an integer-indexed dictionary of QVBoxLayouts representing the number of # columns necessary. Added left to right in the parent QHBoxLayout. column = {} for i in xrange(1, num_cols+1): column[i] = QVBoxLayout() column[i].setAlignment(Qt.AlignLeft) columns_frame.addLayout(column[i]) # Create a dictionary of QLineEdit widgets (indexed by tag name) and stack them # (top to bottom) and their labels in as many columns as it takes. curr_col = 1 curr_item = 1 tooltip = _('Comma separated list of html elements (no quotes, no angle "<" brackets).') for tag in TAGLIST: # Column item limit surpassed - switch to next column. if curr_item > col_limit: column[curr_col].addStretch() curr_col += 1 curr_item = 1 # Add lable and QLineEdit widget to current column. label = QLabel(_('<b>Choices to change "{}" elements to:</b>').format(tag), self) label.setAlignment(Qt.AlignCenter) self.qlinedit_widgets[tag] = QLineEdit(', '.join(plugin_prefs['{}_changes'.format(tag)]), self) self.qlinedit_widgets[tag].setToolTip('<p>{}'.format(tooltip)) column[curr_col].addWidget(label) column[curr_col].addWidget(self.qlinedit_widgets[tag]) if not len(CHANGE_TO_MAP[tag]): self.qlinedit_widgets[tag].setDisabled(True) curr_item += 1 column[curr_col].addStretch() layout.addSpacing(10) attrs_layout = QVBoxLayout() attrs_layout.setAlignment(Qt.AlignCenter) layout.addLayout(attrs_layout) label = QLabel(_('<b>HTML attributes available to search for:</b>'), self) label.setAlignment(Qt.AlignCenter) self.attrs_txtBox = QLineEdit(', '.join(plugin_prefs['attrs']), self) self.attrs_txtBox.setToolTip('<p>{}'.format(_('Comma separated list of html attribute names (no quotes).'))) attrs_layout.addWidget(label) attrs_layout.addWidget(self.attrs_txtBox) layout.addSpacing(10) right_layout = QHBoxLayout() right_layout.setAlignment(Qt.AlignRight) layout.addLayout(right_layout) reset_button = QPushButton(_('Reset all defaults'), self) reset_button.setToolTip('<p>{}'.format(_('Reset all settings to original defaults.'))) reset_button.clicked.connect(self.reset_defaults) right_layout.addWidget(reset_button) layout.addSpacing(10) button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) button_box.accepted.connect(self.save_settings) button_box.rejected.connect(self.reject) layout.addWidget(button_box)
class ConfigWidget(QWidget): # GUI definition def __init__(self): QWidget.__init__(self) self.l = QVBoxLayout() self.setLayout(self.l) self.ll = QHBoxLayout() self.l.addLayout(self.ll) self.label_exe = QLabel(_('&Prince executable:')) self.ll.addWidget(self.label_exe) self.exe = QLineEdit(self) self.exe.setText(prefs['prince_exe']) self.exe.setToolTip( _('<qt>Executable for the Prince program (command-line interface)</qt>' )) self.ll.addWidget(self.exe) self.label_exe.setBuddy(self.exe) self.browse = QPushButton(_('&Browse') + '...', self) self.browse.setToolTip( _('<qt>Search the Prince executable in your computer</qt>')) self.browse.clicked.connect(self.select_exe) self.ll.addWidget(self.browse) self.lll = QHBoxLayout() self.l.addLayout(self.lll) self.label_fmts = QLabel(_('Preferred &formats:')) self.lll.addWidget(self.label_fmts) self.fmts = QLineEdit(self) self.fmts.setText(','.join(prefs['formats'])) self.fmts.setToolTip( _('<qt>Comma-separated list of preferred formats to use as source, the first that matches will be used</qt>' )) self.lll.addWidget(self.fmts) self.label_fmts.setBuddy(self.fmts) self.add_book = QCheckBox(_('&Add PDF to the book record')) self.add_book.setToolTip( _('<qt>Add the converted PDF to the selected book record</qt>')) self.add_book.setChecked(prefs['add_book']) self.l.addWidget(self.add_book) self.show_css = QCheckBox(_('&Show CSS in the Convert dialog')) self.show_css.setToolTip( _('<qt>Show by default the styles in the Convert dialog</qt>')) self.show_css.setChecked(prefs['show_CSS']) self.l.addWidget(self.show_css) self.css_layout = QVBoxLayout() self.llll = QHBoxLayout() self.css_layout.addLayout(self.llll) self.css_list = QComboBox() self.css_list.setToolTip( _('<qt>List of custom styles defined. Select one to edit</qt>')) self.css_list.setSizeAdjustPolicy(QComboBox.AdjustToContents) self.CSS_list = prefs['custom_CSS_list'].copy() self.default_CSS = prefs['default_CSS'] if 'custom_CSS' in prefs: self.CSS_list[_('old')] = prefs['custom_CSS'] self.default_CSS = _('old') if self.default_CSS not in self.CSS_list: self.default_CSS = sorted(self.CSS_list, key=lambda x: x.lower())[0] for key in sorted(self.CSS_list, key=lambda x: x.lower()): self.css_list.addItem(key, key) self.css_list.setCurrentIndex(self.css_list.findText(self.default_CSS)) self.css_list.currentIndexChanged.connect(self.set_css) self.llll.addWidget(self.css_list) self.css_rename = QPushButton(_('Re&name')) self.css_rename.setToolTip( _('<qt>Rename the current style to the name on the right</qt>')) self.css_rename.clicked.connect(self.rename_css) self.css_rename.setEnabled(False) self.llll.addWidget(self.css_rename) self.css_name = QLineEdit(self) self.css_name.setToolTip( _('<qt>Name for the new or renamed style</qt>')) self.css_name.setText(self.css_list.currentText()) self.css_name.textChanged.connect(self.check_names) self.llll.addWidget(self.css_name) self.css_add = QPushButton(_('A&dd')) self.css_add.setToolTip( _('<qt>Add a new empty style with the name on the left</qt>')) self.css_add.clicked.connect(self.add_css) self.css_add.setEnabled(False) self.llll.addWidget(self.css_add) self.css_remove = QPushButton(_('Re&move')) self.css_remove.setToolTip(_('<qt>Remove the current style</qt>')) self.css_remove.clicked.connect(self.remove_css) self.llll.addWidget(self.css_remove) self.llll_ = QHBoxLayout() self.css_layout.addLayout(self.llll_) self.label_args = QLabel(_('Addi&tional command-line arguments:')) self.llll_.addWidget(self.label_args) self.args = QLineEdit(self) # Make sure custom_CSS_list and custom_args_list have the same keys if 'custom_args_list' in prefs: self.args_list = prefs['custom_args_list'].copy() else: self.args_list = {} for key in self.CSS_list: if not key in self.args_list: self.args_list[key] = '' for key in self.args_list: if not key in self.CSS_list: del self.args_list[key] self.args.setText(self.args_list[unicode(self.css_list.currentText())]) self.args.setToolTip( _('<qt>Additional command-line arguments used in conversions with this style</qt>' )) self.llll_.addWidget(self.args) self.label_args.setBuddy(self.args) self.css = TextEditWithTooltip(self, expected_geometry=(80, 20)) self.css.setLineWrapMode(TextEditWithTooltip.NoWrap) self.css.load_text(self.CSS_list[unicode(self.css_list.currentText())], 'css') self.css.setToolTip( _('<qt>Custom stylesheet that will be applied, if selected, to all Prince PDF conversions</qt>' )) self.css_layout.addWidget(self.css) self.css_templates = QLabel(_('Book metadata can be used in the stylesheet. Anything between %(s1)s and %(s2)s will be processed as a calibre template. For instance, %(s3)s in the stylesheet will be replaced with the book title in the conversion.') % \ {'s1':'<span style="font-family:monospace ; font-weight:bold">@{@</span>', \ 's2':'<span style="font-family:monospace ; font-weight:bold">@}@</span>', \ 's3':'<span style="font-family:monospace ; font-weight:bold">@{@{title}@}@</span>'}) self.css_templates.setWordWrap(True) self.css_layout.addWidget(self.css_templates) self.css_box = QGroupBox(_('&Custom styles:')) self.css_box.setLayout(self.css_layout) self.l.addWidget(self.css_box) self.lllll = QHBoxLayout() self.lllll.setAlignment(Qt.AlignLeft) self.l.addLayout(self.lllll) self.defaults = QPushButton(_('&Restore defaults')) self.defaults.setToolTip(_('<qt>Restore the default settings</qt>')) self.defaults.clicked.connect(self.restore_defaults) self.lllll.addWidget(self.defaults, alignment=Qt.AlignLeft) self.warning = QLabel(_('<b>Warning</b>: Deletes modified styles')) self.lllll.addWidget(self.warning) self.adjustSize() def select_exe(self): ''' Create a dialog to select the Prince executable ''' dialog = QFileDialog() dialog.setFileMode(QFileDialog.ExistingFile) filename = dialog.getOpenFileName(self, _('Select Prince executable'), '', '') if filename: try: self.exe.setText(filename) except (TypeError): self.exe.setText(filename[0]) def restore_defaults(self): ''' Restore the default settings ''' self.exe.setText(prefs.defaults['prince_exe']) self.fmts.setText(','.join(prefs.defaults['formats']).lower()) self.show_css.setChecked(prefs.defaults['show_CSS']) self.add_book.setChecked(prefs.defaults['add_book']) self.css_list.currentIndexChanged.disconnect() self.css_list.clear() self.CSS_list = prefs.defaults['custom_CSS_list'].copy() self.args_list = prefs.defaults['custom_args_list'].copy() self.default_CSS = prefs.defaults['default_CSS'] for key in sorted(self.CSS_list, key=lambda x: x.lower()): self.css_list.addItem(key, key) self.css_list.setCurrentIndex(self.css_list.findText(self.default_CSS)) self.css_name.setText(self.default_CSS) self.css.load_text(self.CSS_list[unicode(self.css_list.currentText())], 'css') self.args.setText(self.args_list[unicode(self.css_list.currentText())]) self.css_list.currentIndexChanged.connect(self.set_css) def save_settings(self): ''' Save the current settings ''' prefs['prince_exe'] = unicode(self.exe.text()) prefs['formats'] = unicode(self.fmts.text().lower()).split(',') prefs['show_CSS'] = self.show_css.isChecked() prefs['add_book'] = self.add_book.isChecked() self.set_css() prefs['default_CSS'] = self.default_CSS prefs['custom_CSS_list'] = self.CSS_list.copy() prefs['custom_args_list'] = self.args_list.copy() if 'custom_CSS' in prefs: del prefs['custom_CSS'] def set_css(self): ''' Fill the CSS text box with the selected stylesheet, and similarly for command-line arguments ''' self.CSS_list[self.default_CSS] = unicode(self.css.toPlainText()) self.args_list[self.default_CSS] = unicode(self.args.text()) self.default_CSS = unicode(self.css_list.currentText()) self.css.load_text(self.CSS_list[self.default_CSS], 'css') self.args.setText(self.args_list[self.default_CSS]) self.css_name.setText(self.css_list.currentText()) def add_css(self): ''' Add a new style ''' from calibre.gui2 import error_dialog name = unicode(self.css_name.text()) if name in self.CSS_list: error_dialog( self, _('Cannot add style'), _('A style with the name "%s" is already defined, use a different name.' ) % name, show=True) else: self.CSS_list[name] = '' self.args_list[name] = '' self.css_list.addItem(name, name) self.css_list.setCurrentIndex(self.css_list.findText(name)) self.css_add.setEnabled(False) self.css_rename.setEnabled(False) def remove_css(self): ''' Remove an existing style ''' from calibre.gui2 import error_dialog if (self.css_list.count() > 1): self.css_list.currentIndexChanged.disconnect() self.css_list.removeItem(self.css_list.currentIndex()) del self.CSS_list[self.default_CSS] del self.args_list[self.default_CSS] self.default_CSS = unicode(self.css_list.currentText()) self.css.load_text(self.CSS_list[self.default_CSS], 'css') self.args.setText(self.args_list[self.default_CSS]) self.css_list.currentIndexChanged.connect(self.set_css) self.css_name.setText(self.css_list.currentText()) else: error_dialog( self, _('Cannot delete the last style'), _('The last style cannot be removed. You can rename it and/or remove its contents.' ), show=True) def rename_css(self): ''' Rename a style ''' from calibre.gui2 import error_dialog name = unicode(self.css_name.text()) if name in self.CSS_list: error_dialog( self, _('Cannot rename style'), _('A style with the name "%s" is already defined, use a different name.' ) % name, show=True) else: self.CSS_list[name] = self.CSS_list.pop(self.default_CSS) self.args_list[name] = self.args_list.pop(self.default_CSS) self.css_list.setItemText(self.css_list.currentIndex(), name) self.default_CSS = name def check_names(self, text): name = unicode(text) if name in self.CSS_list: self.css_add.setEnabled(False) self.css_rename.setEnabled(False) else: self.css_add.setEnabled(True) self.css_rename.setEnabled(True)
class ConfigWidget(QWidget): # GUI definition def __init__(self): QWidget.__init__(self) self.l = QVBoxLayout() self.setLayout(self.l) self.ll = QHBoxLayout() self.l.addLayout(self.ll) self.label_exe = QLabel(_('&Prince executable:')) self.ll.addWidget(self.label_exe) self.exe = QLineEdit(self) self.exe.setText(prefs['prince_exe']) self.exe.setToolTip(_('<qt>Executable for the Prince program (command-line interface)</qt>')) self.ll.addWidget(self.exe) self.label_exe.setBuddy(self.exe) self.browse = QPushButton(_('&Browse') + '...', self) self.browse.setToolTip(_('<qt>Search the Prince executable in your computer</qt>')) self.browse.clicked.connect(self.select_exe) self.ll.addWidget(self.browse) self.lll = QHBoxLayout() self.l.addLayout(self.lll) self.label_fmts = QLabel(_('Preferred &formats:')) self.lll.addWidget(self.label_fmts) self.fmts = QLineEdit(self) self.fmts.setText(','.join(prefs['formats'])) self.fmts.setToolTip(_('<qt>Comma-separated list of preferred formats to use as source, the first that matches will be used</qt>')) self.lll.addWidget(self.fmts) self.label_fmts.setBuddy(self.fmts) self.add_book = QCheckBox(_('&Add PDF to the book record')) self.add_book.setToolTip(_('<qt>Add the converted PDF to the selected book record</qt>')) self.add_book.setChecked(prefs['add_book']) self.l.addWidget(self.add_book) self.show_css = QCheckBox(_('&Show CSS in the Convert dialog')) self.show_css.setToolTip(_('<qt>Show by default the stylesheets in the Convert dialog</qt>')) self.show_css.setChecked(prefs['show_CSS']) self.l.addWidget(self.show_css) self.css_layout = QVBoxLayout() self.llll = QHBoxLayout() self.css_layout.addLayout(self.llll) self.css_list = QComboBox() self.css_list.setToolTip(_('<qt>List of custom stylesheets defined. Select one to edit</qt>')) self.css_list.setSizeAdjustPolicy(QComboBox.AdjustToContents) self.CSS_list = prefs['custom_CSS_list'].copy() self.default_CSS = prefs['default_CSS'] if 'custom_CSS' in prefs: self.CSS_list[_('old')] = prefs['custom_CSS'] self.default_CSS = _('old') if self.default_CSS not in self.CSS_list: self.default_CSS = sorted(self.CSS_list, key=lambda x: x.lower())[0] for key in sorted(self.CSS_list, key=lambda x: x.lower()): self.css_list.addItem(key, key) self.css_list.setCurrentIndex(self.css_list.findText(self.default_CSS)) self.css_list.currentIndexChanged.connect(self.set_css) self.llll.addWidget(self.css_list) self.css_rename = QPushButton(_('Re&name')) self.css_rename.setToolTip(_('<qt>Rename the current stylesheet to the name on the right</qt>')) self.css_rename.clicked.connect(self.rename_css) self.css_rename.setEnabled(False) self.llll.addWidget(self.css_rename) self.css_name = QLineEdit(self) self.css_name.setToolTip(_('<qt>Name for the new or renamed stylesheet</qt>')) self.css_name.setText(self.css_list.currentText()) self.css_name.textChanged.connect(self.check_names) self.llll.addWidget(self.css_name) self.css_add = QPushButton(_('A&dd')) self.css_add.setToolTip(_('<qt>Add a new empty stylesheet with the name on the left</qt>')) self.css_add.clicked.connect(self.add_css) self.css_add.setEnabled(False) self.llll.addWidget(self.css_add) self.css_remove = QPushButton(_('Re&move')) self.css_remove.setToolTip(_('<qt>Remove the current stylesheet</qt>')) self.css_remove.clicked.connect(self.remove_css) self.llll.addWidget(self.css_remove) self.css = TextEditWithTooltip() self.css.setLineWrapMode(TextEditWithTooltip.NoWrap) self.css.load_text(self.CSS_list[unicode(self.css_list.currentText())],'css') self.css.setToolTip(_('<qt>Custom stylesheet that will be applied, if selected, to all Prince PDF conversions</qt>')) self.css_layout.addWidget(self.css) self.css_templates = QLabel(_('Book metadata can be used in the stylesheet. Anything between %(s1)s and %(s2)s will be processed as a calibre template. For instance, %(s3)s in the stylesheet will be replaced with the book title in the conversion.') % \ {'s1':'<span style="font-family:monospace ; font-weight:bold">@{@</span>', \ 's2':'<span style="font-family:monospace ; font-weight:bold">@}@</span>', \ 's3':'<span style="font-family:monospace ; font-weight:bold">@{@{title}@}@</span>'}) self.css_templates.setWordWrap(True) self.css_layout.addWidget(self.css_templates) self.css_box = QGroupBox(_('&Custom CSS:')) self.css_box.setLayout(self.css_layout) self.l.addWidget(self.css_box) self.lllll = QHBoxLayout() self.lllll.setAlignment(Qt.AlignLeft) self.l.addLayout(self.lllll) self.defaults = QPushButton(_('&Restore defaults')) self.defaults.setToolTip(_('<qt>Restore the default settings</qt>')) self.defaults.clicked.connect(self.restore_defaults) self.lllll.addWidget(self.defaults, alignment=Qt.AlignLeft) self.warning = QLabel(_('<b>Warning</b>: Deletes modified stylesheets')) self.lllll.addWidget(self.warning) self.adjustSize() def select_exe(self): ''' Create a dialog to select the Prince executable ''' dialog = QFileDialog() dialog.setFileMode(QFileDialog.ExistingFile) filename = dialog.getOpenFileName(self, _('Select Prince executable'), '', '') if filename: try: self.exe.setText(filename) except(TypeError): self.exe.setText(filename[0]) def restore_defaults(self): ''' Restore the default settings ''' self.exe.setText(prefs.defaults['prince_exe']) self.fmts.setText(','.join(prefs.defaults['formats']).lower()) self.show_css.setChecked(prefs.defaults['show_CSS']) self.add_book.setChecked(prefs.defaults['add_book']) self.css_list.currentIndexChanged.disconnect() self.css_list.clear() self.CSS_list = prefs.defaults['custom_CSS_list'].copy() self.default_CSS = prefs.defaults['default_CSS'] for key in sorted(self.CSS_list, key=lambda x: x.lower()): self.css_list.addItem(key, key) self.css_list.setCurrentIndex(self.css_list.findText(self.default_CSS)) self.css_name.setText(self.default_CSS) self.css.load_text(self.CSS_list[unicode(self.css_list.currentText())],'css') self.css_list.currentIndexChanged.connect(self.set_css) def save_settings(self): ''' Save the current settings ''' prefs['prince_exe'] = unicode(self.exe.text()) prefs['formats'] = unicode(self.fmts.text().lower()).split(',') prefs['show_CSS'] = self.show_css.isChecked() prefs['add_book'] = self.add_book.isChecked() self.set_css() prefs['default_CSS'] = self.default_CSS prefs['custom_CSS_list'] = self.CSS_list.copy() if 'custom_CSS' in prefs: del prefs['custom_CSS'] def set_css(self): ''' Fill the CSS text box with the selected stylesheet ''' self.CSS_list[self.default_CSS] = unicode(self.css.toPlainText()) self.default_CSS = unicode(self.css_list.currentText()) self.css.load_text(self.CSS_list[self.default_CSS],'css') self.css_name.setText(self.css_list.currentText()) def add_css(self): ''' Add a new stylesheet ''' from calibre.gui2 import error_dialog name = unicode(self.css_name.text()) if name in self.CSS_list: error_dialog(self, _('Cannot add stylesheet'), _('A stylesheet with the name "%s" is already defined, use a different name.') % name, show=True) else: self.CSS_list[name] = '' self.css_list.addItem(name, name) self.css_list.setCurrentIndex(self.css_list.findText(name)) self.css_add.setEnabled(False) self.css_rename.setEnabled(False) def remove_css(self): ''' Remove an existing stylesheet ''' from calibre.gui2 import error_dialog if (self.css_list.count() > 1): self.css_list.currentIndexChanged.disconnect() self.css_list.removeItem(self.css_list.currentIndex()) del self.CSS_list[self.default_CSS] self.default_CSS = unicode(self.css_list.currentText()) self.css.load_text(self.CSS_list[self.default_CSS],'css') self.css_list.currentIndexChanged.connect(self.set_css) self.css_name.setText(self.css_list.currentText()) else: error_dialog(self, _('Cannot delete the last stylesheet'), _('The last stylesheet cannot be removed. You can rename it and/or remove its contents.'), show=True) def rename_css(self): ''' Rename a stylesheet ''' from calibre.gui2 import error_dialog name = unicode(self.css_name.text()) if name in self.CSS_list: error_dialog(self, _('Cannot rename stylesheet'), _('A stylesheet with the name "%s" is already defined, use a different name.') % name, show=True) else: self.CSS_list[name] = self.CSS_list.pop(self.default_CSS) self.css_list.setItemText(self.css_list.currentIndex(),name) self.default_CSS = name def check_names(self, text): name = unicode(text) if name in self.CSS_list: self.css_add.setEnabled(False) self.css_rename.setEnabled(False) else: self.css_add.setEnabled(True) self.css_rename.setEnabled(True)
def __init__(self, root): super().__init__(root) self.main = root self.setWindowTitle('Список протоколов Сетевого уровня') self.resize(900, 900) self.layout_tw = QVBoxLayout(self) self.layout_b = QHBoxLayout() self.tableWidget = QTableWidget() self.tableWidget.setGeometry(QRect(20, 20, 450, 81)) self.tableWidget.setColumnCount(4) hor_header = self.tableWidget.horizontalHeader() hor_header.setSectionResizeMode(0, QHeaderView.ResizeToContents) hor_header.setSectionResizeMode(1, QHeaderView.ResizeToContents) hor_header.setSectionResizeMode(2, QHeaderView.ResizeToContents) hor_header.setSectionResizeMode(3, QHeaderView.ResizeToContents) self.tableWidget.setAlternatingRowColors(True) self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows) self.tableWidget.setRowCount(1) self.layout_tw.addWidget(self.tableWidget) self.layout_tw.addLayout(self.layout_b) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(0, item) item.setText("Выбрать") item_2 = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(1, item_2) item_2.setText("Hex Код") item_3 = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(2, item_3) item_3.setText("Dec Код") item_4 = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(3, item_4) item_4.setText("Наименование") self.tableWidget.verticalHeader().setVisible(False) self.tableWidget.horizontalHeader().setFont(QFont('Arial', weight=QFont.UltraExpanded)) cell_widget = QWidget() cb = QCheckBox() lay_out = QHBoxLayout(cell_widget) lay_out.addWidget(cb) lay_out.setAlignment(Qt.AlignCenter) lay_out.setContentsMargins(0, 0, 0, 0) cell_widget.setLayout(lay_out) self.tableWidget.setCellWidget(0, 0, cell_widget) ProtFile = open('допочки\PrNmNetCatalog.txt') x = 0 for row in ProtFile: net_hcod, net_dcod, net_pr = row.split("\t") vheader = self.tableWidget.verticalHeader() vheader.setSectionResizeMode(x, QHeaderView.ResizeToContents) self.tableWidget.setItem(x, 1, QTableWidgetItem(net_hcod)) self.tableWidget.setItem(x, 2, QTableWidgetItem(net_dcod)) self.tableWidget.setItem(x, 3, QTableWidgetItem(net_pr)) x += 1 if x == 53: continue else: self.tableWidget.insertRow(x) cell_widget = QWidget() cb = QCheckBox() lay_out = QHBoxLayout(cell_widget) lay_out.addWidget(cb) lay_out.setAlignment(Qt.AlignCenter) lay_out.setContentsMargins(0, 0, 0, 0) cell_widget.setLayout(lay_out) self.tableWidget.setCellWidget(x, 0, cell_widget) self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
class ConvertDialog(QDialog): hide_text = _('&Hide styles') show_text = _('&Show styles') prince_log = '' prince_file = '' prince_css = '' # GUI definition def __init__(self, mi, fmt, opf, oeb, icon): ''' :param mi: The book metadata :param fmt: The source format used for conversion :param opf: The path to the OPF file :param oeb: An OEB object for the unpacked book :param icon: The window icon ''' self.opf = opf self.oeb = oeb self.mi = mi # The unpacked book needs to be parsed before, to read the contents # of the prince-style file, if it exists self.parse() QDialog.__init__(self) self.setAttribute(Qt.WA_DeleteOnClose) self.setWindowTitle(_('Convert to PDF with Prince')) self.setWindowIcon(icon) self.l = QVBoxLayout() self.setLayout(self.l) self.title_label = QLabel(_('<b>Title:</b> %s') % self.mi.title) self.l.addWidget(self.title_label) self.format_label = QLabel(_('<b>Source format:</b> %s') % fmt) self.l.addWidget(self.format_label) self.add_book = QCheckBox(_('&Add PDF to the book record')) self.add_book.setToolTip( _('<qt>Add the converted PDF to the selected book record</qt>')) self.add_book.setChecked(prefs['add_book']) self.add_book.stateChanged.connect(self.set_add_book) self.l.addWidget(self.add_book) self.ll = QHBoxLayout() self.ll.setAlignment(Qt.AlignLeft) self.l.addLayout(self.ll) self.label_css = QLabel(_('&Custom style:')) self.ll.addWidget(self.label_css) self.css_list = QComboBox() self.css_list.setToolTip( _('<qt>Select one style to use. Additional styles can be created in the plugin configuration</qt>' )) for key in sorted(prefs['custom_CSS_list'], key=lambda x: x.lower()): self.css_list.addItem(key, key) self.css_list.setCurrentIndex( self.css_list.findText(prefs['default_CSS'])) self.css_list.currentIndexChanged.connect(self.set_css) self.ll.addWidget(self.css_list) self.label_css.setBuddy(self.css_list) self.ll_ = QHBoxLayout() self.l.addLayout(self.ll_) self.label_args = QLabel(_('A&dditional command-line arguments:')) self.ll_.addWidget(self.label_args) self.args = QLineEdit(self) self.args.setText(prefs['custom_args_list'][prefs['default_CSS']]) self.args.setToolTip( _('<qt>Specify additional command-line arguments for the conversion</qt>' )) self.ll_.addWidget(self.args) self.label_args.setBuddy(self.args) self.css = QTabWidget() self.l.addWidget(self.css) self.css1 = TextEditWithTooltip(self, expected_geometry=(80, 20)) self.css1.setLineWrapMode(TextEditWithTooltip.NoWrap) self.css1.load_text( self.replace_templates( prefs['custom_CSS_list'][prefs['default_CSS']]), 'css') self.css1.setToolTip( _('<qt>This stylesheet can be modified<br/>The default can be configured</qt>' )) i = self.css.addTab(self.css1, _('C&ustom CSS')) self.css.setTabToolTip( i, _('<qt>Custom CSS stylesheet to be used for this conversion</qt>')) monofont = QFont('') monofont.setStyleHint(QFont.TypeWriter) if (self.prince_css): self.css2 = QPlainTextEdit() self.css2.setStyleSheet('* { font-family: monospace }') self.css2.setLineWrapMode(QPlainTextEdit.NoWrap) self.css2.setPlainText(self.prince_css) self.css2.setReadOnly(True) self.css2.setToolTip( _('<qt>This stylesheet cannot be modified</qt>')) i = self.css.addTab(self.css2, _('&Book CSS')) self.css.setTabToolTip( i, _('<qt>Book-specific CSS stylesheet included in the ebook file</qt>' )) self.ll = QHBoxLayout() self.l.addLayout(self.ll) if (prefs['show_CSS']): self.toggle = QPushButton(self.hide_text, self) else: self.toggle = QPushButton(self.show_text, self) self.toggle.setToolTip( _('<qt>Show/hide the additional styles used for the conversion</qt>' )) self.toggle.clicked.connect(self.toggle_tabs) self.convert = QPushButton(_('Con&vert'), self) self.convert.setToolTip(_('<qt>Run the conversion with Prince</qt>')) self.convert.setDefault(True) self.buttons = QDialogButtonBox(QDialogButtonBox.Cancel) self.buttons.addButton(self.toggle, QDialogButtonBox.ResetRole) self.buttons.addButton(self.convert, QDialogButtonBox.AcceptRole) self.l.addWidget(self.buttons) self.buttons.accepted.connect(self.prince_convert) self.buttons.rejected.connect(self.reject) if (not prefs['show_CSS']): self.css.hide() self.adjustSize() def toggle_tabs(self): ''' Enable/disable the CSS tabs, and store the setting ''' if (self.css.isVisible()): self.css.hide() self.label_args.hide() self.args.hide() self.toggle.setText(self.show_text) self.adjustSize() else: self.css.show() self.label_args.show() self.args.show() self.toggle.setText(self.hide_text) self.adjustSize() prefs['show_CSS'] = self.css.isVisible() def set_add_book(self): ''' Save the status of the add_book checkbox ''' prefs['add_book'] = self.add_book.isChecked() def set_css(self): ''' Fill the custom CSS text box with the selected stylesheet (and command-line arguments) ''' style = unicode(self.css_list.currentText()) self.css1.load_text( self.replace_templates(prefs['custom_CSS_list'][style]), 'css') self.args.setText(prefs['custom_args_list'][style]) prefs['default_CSS'] = style def parse(self): ''' Parse the unpacked OPF file to find and read the prince-style file ''' from calibre.constants import DEBUG from os.path import dirname, join from lxml import etree import codecs if DEBUG: print(_('Parsing book...')) opf_dir = dirname(self.opf) root = etree.parse(self.opf).getroot() metadata = root.find('{*}metadata') for meta in metadata.findall("{*}meta[@name='prince-style']"): prince_id = meta.get('content') for item in self.oeb.manifest: if (item.id == prince_id): self.prince_file = item.href break if (self.prince_file): fl = codecs.open(join(opf_dir, self.prince_file), 'rb', 'utf-8') self.prince_css = fl.read() fl.close() def replace_templates(self, text): ''' Replace templates (enclosed by '@{@', '@}@') in the input text ''' import re import json from calibre.ebooks.metadata.book.formatter import SafeFormat from calibre.constants import DEBUG matches = list(re.finditer('@{@(.+?)@}@', text, re.DOTALL)) results = {} for match in reversed(matches): result = SafeFormat().safe_format(match.group(1), self.mi, ('EXCEPTION: '), self.mi) # Escape quotes, backslashes and newlines result = re.sub(r'''['"\\]''', r'\\\g<0>', result) result = re.sub('\n', r'\\A ', result) results[match.group(1)] = result text = text[:match.start(0)] + result + text[match.end(0):] if DEBUG: print(_('Replacing templates')) for match in matches: print( _('Found: %s (%d-%d)') % (match.group(1), match.start(0), match.end(0))) print(_('Replace with: %s') % results[match.group(1)]) return text def prince_convert(self): ''' Call the actual Prince command to convert to PDF ''' from os import makedirs from os.path import dirname, join, exists from calibre.ptempfile import PersistentTemporaryFile from calibre.constants import DEBUG from shlex import split as shsplit # All files are relative to the OPF location opf_dir = dirname(self.opf) base_dir = dirname(self.pdf_file) base_dir = join(opf_dir, base_dir) try: makedirs(base_dir) except BaseException: if not exists(base_dir): raise # Create a temporary CSS file with the box contents custom_CSS = PersistentTemporaryFile(mode='w+') custom_CSS.write(unicode(self.css1.toPlainText())) custom_CSS.close() # Create a temporary file with the list of input files file_list = PersistentTemporaryFile(mode='w+') for item in self.oeb.spine: file_list.write(item.href + "\n") file_list.close() # Build the command line command = prefs['prince_exe'] args = ['-v'] if self.prince_file: args.append('-s') args.append(self.prince_file) args.append('-s') args.append(custom_CSS.name) args.append('-l') args.append(file_list.name) args.append('-o') args.append(self.pdf_file) # Additional command-line arguments args.extend(shsplit(self.args.text())) # Hide the convert button and show a busy indicator self.convert.setEnabled(False) self.progress_bar = QProgressBar() self.progress_bar.setRange(0, 0) self.progress_bar.setValue(0) self.l.addWidget(self.progress_bar) # Run the command and return the path to the PDF file if DEBUG: print(_('Converting book...')) process = QProcess(self) process.setWorkingDirectory(opf_dir) process.setProcessChannelMode(QProcess.MergedChannels) process.error.connect(self.error) process.finished.connect(self.end) self.process = process if DEBUG: from subprocess import list2cmdline line = list2cmdline([command] + args) print(_('Command line: %s') % line) process.start(command, args) def error(self, rc): ''' Show a message when there is an error in the command :param rc: The error code ''' from calibre.gui2 import error_dialog # Remove the progress bar while the error message is displayed self.progress_bar.hide() self.progress_bar.deleteLater() error_dialog( self, _('Process error'), _('<p>Error code: %s' '<p>make sure Prince (<a href="http://www.princexml.com">www.princexml.com</a>) is installed ' 'and the correct command-line-interface executable is set in the configuration of this plugin, ' 'which is usually:' '<ul><li>In Windows: <code><i>Prince_folder</i>\\Engine\\bin\\prince.exe</code>' ' <li>In Linux: <code>prince</code>' '</ul>') % rc, show=True) self.pdf_file = None self.accept() def end(self, rc): ''' Close and return the filename when the process ends :param rc: The return code (0 if successful) ''' from os.path import join self.prince_log = unicode(self.process.readAllStandardOutput().data()) opf_dir = unicode(self.process.workingDirectory()) if (rc == 0): self.pdf_file = join(opf_dir, self.pdf_file) else: self.pdf_file = None self.accept()
def __init__(self, parent, key_type_name, plugin_keys, create_key, keyfile_ext = "", wineprefix = None): QDialog.__init__(self,parent) self.parent = parent self.key_type_name = key_type_name self.plugin_keys = plugin_keys self.create_key = create_key self.keyfile_ext = keyfile_ext self.import_key = (keyfile_ext != "") self.binary_file = (keyfile_ext == "der") self.json_file = (keyfile_ext == "k4i") self.android_file = (keyfile_ext == "k4a") self.wineprefix = wineprefix self.setWindowTitle("{0} {1}: Manage {2}s".format(PLUGIN_NAME, PLUGIN_VERSION, self.key_type_name)) # Start Qt Gui dialog layout layout = QVBoxLayout(self) self.setLayout(layout) help_layout = QHBoxLayout() layout.addLayout(help_layout) # Add hyperlink to a help file at the right. We will replace the correct name when it is clicked. help_label = QLabel('<a href="http://www.foo.com/">Help</a>', self) help_label.setTextInteractionFlags(Qt.LinksAccessibleByMouse | Qt.LinksAccessibleByKeyboard) help_label.setAlignment(Qt.AlignRight) help_label.linkActivated.connect(self.help_link_activated) help_layout.addWidget(help_label) keys_group_box = QGroupBox(_("{0}s".format(self.key_type_name)), self) layout.addWidget(keys_group_box) keys_group_box_layout = QHBoxLayout() keys_group_box.setLayout(keys_group_box_layout) self.listy = QListWidget(self) self.listy.setToolTip("{0}s that will be used to decrypt ebooks".format(self.key_type_name)) self.listy.setSelectionMode(QAbstractItemView.SingleSelection) self.populate_list() keys_group_box_layout.addWidget(self.listy) button_layout = QVBoxLayout() keys_group_box_layout.addLayout(button_layout) self._add_key_button = QtGui.QToolButton(self) self._add_key_button.setIcon(QIcon(I('plus.png'))) self._add_key_button.setToolTip("Create new {0}".format(self.key_type_name)) self._add_key_button.clicked.connect(self.add_key) button_layout.addWidget(self._add_key_button) self._delete_key_button = QtGui.QToolButton(self) self._delete_key_button.setToolTip(_("Delete highlighted key")) self._delete_key_button.setIcon(QIcon(I('list_remove.png'))) self._delete_key_button.clicked.connect(self.delete_key) button_layout.addWidget(self._delete_key_button) if type(self.plugin_keys) == dict and self.import_key: self._rename_key_button = QtGui.QToolButton(self) self._rename_key_button.setToolTip(_("Rename highlighted key")) self._rename_key_button.setIcon(QIcon(I('edit-select-all.png'))) self._rename_key_button.clicked.connect(self.rename_key) button_layout.addWidget(self._rename_key_button) self.export_key_button = QtGui.QToolButton(self) self.export_key_button.setToolTip("Save highlighted key to a .{0} file".format(self.keyfile_ext)) self.export_key_button.setIcon(QIcon(I('save.png'))) self.export_key_button.clicked.connect(self.export_key) button_layout.addWidget(self.export_key_button) spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) button_layout.addItem(spacerItem) if self.wineprefix is not None: layout.addSpacing(5) wineprefix_layout = QHBoxLayout() layout.addLayout(wineprefix_layout) wineprefix_layout.setAlignment(Qt.AlignCenter) self.wp_label = QLabel("WINEPREFIX:") wineprefix_layout.addWidget(self.wp_label) self.wp_lineedit = QLineEdit(self) wineprefix_layout.addWidget(self.wp_lineedit) self.wp_label.setBuddy(self.wp_lineedit) self.wp_lineedit.setText(self.wineprefix) layout.addSpacing(5) migrate_layout = QHBoxLayout() layout.addLayout(migrate_layout) if self.import_key: migrate_layout.setAlignment(Qt.AlignJustify) self.migrate_btn = QPushButton("Import Existing Keyfiles", self) self.migrate_btn.setToolTip("Import *.{0} files (created using other tools).".format(self.keyfile_ext)) self.migrate_btn.clicked.connect(self.migrate_wrapper) migrate_layout.addWidget(self.migrate_btn) migrate_layout.addStretch() self.button_box = QDialogButtonBox(QDialogButtonBox.Close) self.button_box.rejected.connect(self.close) migrate_layout.addWidget(self.button_box) self.resize(self.sizeHint())
class ConvertDialog(QDialog): hide_text = _('&Hide styles') show_text = _('&Show styles') prince_log = '' prince_file = '' prince_css = '' # GUI definition def __init__(self, mi, fmt, opf, oeb, icon): ''' :param mi: The book metadata :param fmt: The source format used for conversion :param opf: The path to the OPF file :param oeb: An OEB object for the unpacked book :param icon: The window icon ''' self.opf = opf self.oeb = oeb self.mi = mi # The unpacked book needs to be parsed before, to read the contents # of the prince-style file, if it exists self.parse() QDialog.__init__(self) self.setAttribute(Qt.WA_DeleteOnClose) self.setWindowTitle(_('Convert to PDF with Prince')) self.setWindowIcon(icon) self.l = QVBoxLayout() self.setLayout(self.l) self.title_label = QLabel(_('<b>Title:</b> %s') % self.mi.title) self.l.addWidget(self.title_label) self.format_label = QLabel(_('<b>Source format:</b> %s') % fmt) self.l.addWidget(self.format_label) self.add_book = QCheckBox(_('&Add PDF to the book record')) self.add_book.setToolTip(_('<qt>Add the converted PDF to the selected book record</qt>')) self.add_book.setChecked(prefs['add_book']) self.add_book.stateChanged.connect(self.set_add_book) self.l.addWidget(self.add_book) self.ll = QHBoxLayout() self.ll.setAlignment(Qt.AlignLeft) self.l.addLayout(self.ll) self.label_css = QLabel(_('&Custom style:')) self.ll.addWidget(self.label_css) self.css_list = QComboBox() self.css_list.setToolTip(_('<qt>Select one style to use. Additional styles can be created in the plugin configuration</qt>')) for key in sorted(prefs['custom_CSS_list'], key=lambda x: x.lower()): self.css_list.addItem(key, key) self.css_list.setCurrentIndex(self.css_list.findText(prefs['default_CSS'])) self.css_list.currentIndexChanged.connect(self.set_css) self.ll.addWidget(self.css_list) self.label_css.setBuddy(self.css_list) self.ll_ = QHBoxLayout() self.l.addLayout(self.ll_) self.label_args = QLabel(_('A&dditional command-line arguments:')) self.ll_.addWidget(self.label_args) self.args = QLineEdit(self) self.args.setText(prefs['custom_args_list'][prefs['default_CSS']]) self.args.setToolTip(_('<qt>Specify additional command-line arguments for the conversion</qt>')) self.ll_.addWidget(self.args) self.label_args.setBuddy(self.args) self.css = QTabWidget() self.l.addWidget(self.css) self.css1 = TextEditWithTooltip(self, expected_geometry=(80,20)) self.css1.setLineWrapMode(TextEditWithTooltip.NoWrap) self.css1.load_text(self.replace_templates(prefs['custom_CSS_list'][prefs['default_CSS']]),'css') self.css1.setToolTip(_('<qt>This stylesheet can be modified<br/>The default can be configured</qt>')) i = self.css.addTab(self.css1, _('C&ustom CSS')) self.css.setTabToolTip(i, _('<qt>Custom CSS stylesheet to be used for this conversion</qt>')) monofont = QFont('') monofont.setStyleHint(QFont.TypeWriter) if (self.prince_css): self.css2 = QPlainTextEdit() self.css2.setStyleSheet('* { font-family: monospace }') self.css2.setLineWrapMode(QPlainTextEdit.NoWrap) self.css2.setPlainText(self.prince_css) self.css2.setReadOnly(True) self.css2.setToolTip(_('<qt>This stylesheet cannot be modified</qt>')) i = self.css.addTab(self.css2, _('&Book CSS')) self.css.setTabToolTip(i, _('<qt>Book-specific CSS stylesheet included in the ebook file</qt>')) self.ll = QHBoxLayout() self.l.addLayout(self.ll) if (prefs['show_CSS']): self.toggle = QPushButton(self.hide_text, self) else: self.toggle = QPushButton(self.show_text, self) self.toggle.setToolTip(_('<qt>Show/hide the additional styles used for the conversion</qt>')) self.toggle.clicked.connect(self.toggle_tabs) self.convert = QPushButton(_('Con&vert'), self) self.convert.setToolTip(_('<qt>Run the conversion with Prince</qt>')) self.convert.setDefault(True) self.buttons = QDialogButtonBox(QDialogButtonBox.Cancel) self.buttons.addButton(self.toggle, QDialogButtonBox.ResetRole) self.buttons.addButton(self.convert, QDialogButtonBox.AcceptRole) self.l.addWidget(self.buttons) self.buttons.accepted.connect(self.prince_convert) self.buttons.rejected.connect(self.reject) if (not prefs['show_CSS']): self.css.hide() self.adjustSize() def toggle_tabs(self): ''' Enable/disable the CSS tabs, and store the setting ''' if (self.css.isVisible()): self.css.hide() self.label_args.hide() self.args.hide() self.toggle.setText(self.show_text) self.adjustSize() else: self.css.show() self.label_args.show() self.args.show() self.toggle.setText(self.hide_text) self.adjustSize() prefs['show_CSS'] = self.css.isVisible() def set_add_book(self): ''' Save the status of the add_book checkbox ''' prefs['add_book'] = self.add_book.isChecked() def set_css(self): ''' Fill the custom CSS text box with the selected stylesheet (and command-line arguments) ''' style = unicode(self.css_list.currentText()) self.css1.load_text(self.replace_templates(prefs['custom_CSS_list'][style]),'css') self.args.setText(prefs['custom_args_list'][style]) prefs['default_CSS'] = style def parse(self): ''' Parse the unpacked OPF file to find and read the prince-style file ''' from calibre.constants import DEBUG from os.path import dirname, join from lxml import etree import codecs if DEBUG: print(_('Parsing book...')) opf_dir = dirname(self.opf) root = etree.parse(self.opf).getroot() metadata = root.find('{*}metadata') for meta in metadata.findall("{*}meta[@name='prince-style']"): prince_id = meta.get('content') for item in self.oeb.manifest: if (item.id == prince_id): self.prince_file = item.href break if (self.prince_file): fl = codecs.open(join(opf_dir, self.prince_file), 'rb', 'utf-8') self.prince_css = fl.read() fl.close() def replace_templates(self, text): ''' Replace templates (enclosed by '@{@', '@}@') in the input text ''' import re import json from calibre.ebooks.metadata.book.formatter import SafeFormat from calibre.constants import DEBUG matches = list(re.finditer('@{@(.+?)@}@',text,re.DOTALL)) results = {} for match in reversed(matches): result = SafeFormat().safe_format(match.group(1), self.mi, ('EXCEPTION: '), self.mi) # Escape quotes, backslashes and newlines result = re.sub(r'''['"\\]''', r'\\\g<0>', result) result = re.sub('\n', r'\A ', result) results[match.group(1)] = result text = text[:match.start(0)] + result + text[match.end(0):] if DEBUG: print(_('Replacing templates')) for match in matches: print(_('Found: %s (%d-%d)') % (match.group(1), match.start(0), match.end(0))) print(_('Replace with: %s') % results[match.group(1)]) return text def prince_convert(self): ''' Call the actual Prince command to convert to PDF ''' from os import makedirs from os.path import dirname, join, exists from calibre.ptempfile import PersistentTemporaryFile from calibre.constants import DEBUG from shlex import split as shsplit # All files are relative to the OPF location opf_dir = dirname(self.opf) base_dir = dirname(self.pdf_file) base_dir = join(opf_dir, base_dir) try: makedirs(base_dir) except BaseException: if not exists(base_dir): raise # Create a temporary CSS file with the box contents custom_CSS = PersistentTemporaryFile() custom_CSS.write(unicode(self.css1.toPlainText())) custom_CSS.close() # Create a temporary file with the list of input files file_list = PersistentTemporaryFile() for item in self.oeb.spine: file_list.write(item.href + "\n") file_list.close() # Build the command line command = prefs['prince_exe'] args = ['-v'] if self.prince_file: args.append('-s') args.append(self.prince_file) args.append('-s') args.append(custom_CSS.name) args.append('-l') args.append(file_list.name) args.append('-o') args.append(self.pdf_file) # Additional command-line arguments args.extend(shsplit(self.args.text())) # Hide the convert button and show a busy indicator self.convert.setEnabled(False) self.progress_bar = QProgressBar() self.progress_bar.setRange(0,0) self.progress_bar.setValue(0) self.l.addWidget(self.progress_bar) # Run the command and return the path to the PDF file if DEBUG: print(_('Converting book...')) process = QProcess(self) process.setWorkingDirectory(opf_dir) process.setProcessChannelMode(QProcess.MergedChannels); process.error.connect(self.error) process.finished.connect(self.end) self.process = process if DEBUG: from subprocess import list2cmdline line = list2cmdline([command] + args) print(_('Command line: %s') % line) process.start(command, args) def error(self, rc): ''' Show a message when there is an error in the command :param rc: The error code ''' from calibre.gui2 import error_dialog # Remove the progress bar while the error message is displayed self.progress_bar.hide() self.progress_bar.deleteLater() error_dialog(self, _('Process error'), _('<p>Error code: %s' '<p>make sure Prince (<a href="http://www.princexml.com">www.princexml.com</a>) is installed ' 'and the correct command-line-interface executable is set in the configuration of this plugin, ' 'which is usually:' '<ul><li>In Windows: <code><i>Prince_folder</i>\\Engine\\bin\\prince.exe</code>' ' <li>In Linux: <code>prince</code>' '</ul>') % rc, show=True) self.pdf_file = None self.accept() def end(self, rc): ''' Close and return the filename when the process ends :param rc: The return code (0 if successful) ''' from os.path import join self.prince_log = unicode(self.process.readAllStandardOutput().data()) opf_dir = unicode(self.process.workingDirectory()) if (rc == 0): self.pdf_file = join(opf_dir, self.pdf_file) else: self.pdf_file = None self.accept()
class BookConfigWidget(QDialog): def __init__(self, db, ids, parent): QDialog.__init__(self, parent) self.resize(500,500) self._index = 0 self._book_settings = [] http_proxy = get_proxies(debug=False).get('http', None) if http_proxy: self._proxy = True self._http_address = ':'.join(http_proxy.split(':')[:-1]) self._http_port = int(http_proxy.split(':')[-1]) aConnection = HTTPConnection(self._http_address, self._http_port) aConnection.set_tunnel('www.amazon.com', 80) sConnection = HTTPConnection(self._http_address, self._http_port) sConnection.set_tunnel('www.shelfari.com', 80) else: aConnection = HTTPConnection('www.amazon.com') sConnection = HTTPConnection('www.shelfari.com') for book_id in ids: self._book_settings.append(BookSettings(db, book_id, aConnection, sConnection)) self.v_layout = QVBoxLayout(self) self.setWindowTitle('title - author') # add asin and shelfari url text boxes self.asin_layout = QHBoxLayout(None) self.asin_label = QLabel('ASIN:') self.asin_label.setFixedWidth(75) self.asin_edit = QLineEdit('') self.asin_edit.textEdited.connect(self.edit_asin) self.asin_layout.addWidget(self.asin_label) self.asin_layout.addWidget(self.asin_edit) self.v_layout.addLayout(self.asin_layout) self.shelfari_layout = QHBoxLayout(None) self.shelfari_url = QLabel('Shelfari URL:') self.shelfari_url.setFixedWidth(75) self.shelfari_url_edit = QLineEdit('') self.shelfari_url_edit.textEdited.connect(self.edit_shelfari_url) self.shelfari_layout.addWidget(self.shelfari_url) self.shelfari_layout.addWidget(self.shelfari_url_edit) self.v_layout.addLayout(self.shelfari_layout) self.update_buttons_layout = QHBoxLayout(None) self.update_asin_button = QPushButton('Search for ASIN') self.update_asin_button.setFixedWidth(150) self.update_asin_button.clicked.connect(self.search_for_asin) self.update_buttons_layout.addWidget(self.update_asin_button) self.update_shelfari_url_button = QPushButton('Search for Shelfari URL') self.update_shelfari_url_button.setFixedWidth(150) self.update_shelfari_url_button.clicked.connect(self.search_for_shelfari_url) self.update_buttons_layout.addWidget(self.update_shelfari_url_button) self.update_aliases_button = QPushButton('Update Aliases from URL') self.update_aliases_button.setFixedWidth(150) self.update_aliases_button.clicked.connect(self.update_aliases) self.update_buttons_layout.addWidget(self.update_aliases_button) self.v_layout.addLayout(self.update_buttons_layout) # add scrollable area for aliases self.aliases_label = QLabel('Aliases:') self.v_layout.addWidget(self.aliases_label) self.scroll_area = QScrollArea() self.v_layout.addWidget(self.scroll_area) # add status box self.status = QLabel('') self.v_layout.addWidget(self.status) # add previous, ok, cancel, and next buttons self.buttons_layout = QHBoxLayout(None) self.buttons_layout.setAlignment(Qt.AlignRight) if len(ids) > 1: self.previous_button = QPushButton("Previous") self.previous_button.setEnabled(False) self.previous_button.setFixedWidth(100) self.previous_button.clicked.connect(self.previous) self.buttons_layout.addWidget(self.previous_button) self.OK_button = QPushButton("OK") self.OK_button.setFixedWidth(100) self.OK_button.clicked.connect(self.ok) self.buttons_layout.addWidget(self.OK_button) self.cancel_button = QPushButton("Cancel") self.cancel_button.setFixedWidth(100) self.cancel_button.clicked.connect(self.cancel) self.buttons_layout.addWidget(self.cancel_button) if len(ids) > 1: self.next_button = QPushButton("Next") self.next_button.setFixedWidth(100) self.next_button.clicked.connect(self.next) self.buttons_layout.addWidget(self.next_button) self.v_layout.addLayout(self.buttons_layout) self.setLayout(self.v_layout) self.show_book_prefs() self.show() @property def book(self): return self._book_settings[self._index] def edit_asin(self, val): self.book.asin = val def edit_shelfari_url(self, val): http_string = 'http://www.' index = 0 if val[:len(http_string)] != http_string: for i, letter in enumerate(val): if i < len(http_string): if letter == http_string[i]: index += 1 else: break else: break self.shelfari_url_edit.setText(http_string + val[index:]) self.book.shelfari_url = val def search_for_asin(self): asin = None asin = self.book.get_asin() if not asin: if self.book.prefs['asin'] != '': self.status.setText('ASIN not found. Using original asin.') self.asin_edit.setText(self.book.prefs['asin']) else: self.status.setText('ASIN not found.') self.asin_edit.setText('') else: self.status.setText('ASIN found.') self.book.asin = asin self.asin_edit.setText(asin) def search_for_shelfari_url(self): url = None if self.asin_edit.text() != '' and self.asin_edit.text() != 'ASIN not found': url = self.book.search_shelfari(self.asin_edit.text()) if not url: if self.book._prefs['asin'] != '': url = self.book.search_shelfari(self.book._prefs['asin']) if not url: if self.book.title != 'Unknown' and self.book.author != 'Unknown': url = self.book.search_shelfari(self.book.title_and_author) if url: self.status.setText('Shelfari url found.') self.update_aliases_button.setEnabled(True) self.book.shelfari_url = url self.shelfari_url_edit.setText(url) else: self.status.setText('Shelfari url not found.') self.update_aliases_button.setEnabled(False) self.shelfari_url_edit.setText('') def update_aliases(self): url = self.shelfari_url_edit.text() domain_end_index = url[7:].find('/') + 7 if domain_end_index == -1: domain_end_index = len(url) test_url = HTTPConnection(url[7:domain_end_index]) test_url.request('HEAD', url[domain_end_index:]) if test_url.getresponse().status == 200: self.book.update_aliases(overwrite=True) self.update_aliases_on_gui() self.status.setText('Aliases updated.') else: self.status.setText('Invalid shelfari url.') def edit_aliases(self, term, val): self.book.aliases = (term, val) def previous(self): self.status.setText('') self._index -= 1 self.next_button.setEnabled(True) if self._index == 0: self.previous_button.setEnabled(False) self.show_book_prefs() def ok(self): for book in self._book_settings: book.save() self.close() def cancel(self): self.close() def next(self): self.status.setText('') self._index += 1 self.previous_button.setEnabled(True) if self._index == len(self._book_settings) - 1: self.next_button.setEnabled(False) self.show_book_prefs() def show_book_prefs(self): self.setWindowTitle(self.book.title_and_author) self.asin_edit.setText(self.book.asin) self.shelfari_url_edit.setText(self.book.shelfari_url) self.update_aliases_on_gui() def update_aliases_on_gui(self): self.aliases_widget = QWidget() self.aliases_layout = QGridLayout(self.aliases_widget) self.aliases_layout.setAlignment(Qt.AlignTop) # add aliases for current book for index, aliases in enumerate(sorted(self.book.aliases.items())): label = QLabel(aliases[0] + ':') label.setFixedWidth(125) self.aliases_layout.addWidget(label, index, 0) line_edit = QLineEdit(', '.join(aliases[1])) line_edit.setFixedWidth(300) line_edit.textEdited.connect(functools.partial(self.edit_aliases, aliases[0])) self.aliases_layout.addWidget(line_edit, index, 1) self.scroll_area.setWidget(self.aliases_widget)
def __init__(self, parent, key_type_name, plugin_keys, create_key, keyfile_ext = u"", wineprefix = None): QDialog.__init__(self,parent) self.parent = parent self.key_type_name = key_type_name self.plugin_keys = plugin_keys self.create_key = create_key self.keyfile_ext = keyfile_ext self.import_key = (keyfile_ext != u"") self.binary_file = (keyfile_ext == u"der") self.json_file = (keyfile_ext == u"k4i") self.android_file = (keyfile_ext == u"k4a") self.wineprefix = wineprefix self.setWindowTitle("{0} {1}: Manage {2}s".format(PLUGIN_NAME, PLUGIN_VERSION, self.key_type_name)) # Start Qt Gui dialog layout layout = QVBoxLayout(self) self.setLayout(layout) help_layout = QHBoxLayout() layout.addLayout(help_layout) # Add hyperlink to a help file at the right. We will replace the correct name when it is clicked. help_label = QLabel('<a href="http://www.foo.com/">Help</a>', self) help_label.setTextInteractionFlags(Qt.LinksAccessibleByMouse | Qt.LinksAccessibleByKeyboard) help_label.setAlignment(Qt.AlignRight) help_label.linkActivated.connect(self.help_link_activated) help_layout.addWidget(help_label) keys_group_box = QGroupBox(_(u"{0}s".format(self.key_type_name)), self) layout.addWidget(keys_group_box) keys_group_box_layout = QHBoxLayout() keys_group_box.setLayout(keys_group_box_layout) self.listy = QListWidget(self) self.listy.setToolTip(u"{0}s that will be used to decrypt ebooks".format(self.key_type_name)) self.listy.setSelectionMode(QAbstractItemView.SingleSelection) self.populate_list() keys_group_box_layout.addWidget(self.listy) button_layout = QVBoxLayout() keys_group_box_layout.addLayout(button_layout) self._add_key_button = QtGui.QToolButton(self) self._add_key_button.setIcon(QIcon(I('plus.png'))) self._add_key_button.setToolTip(u"Create new {0}".format(self.key_type_name)) self._add_key_button.clicked.connect(self.add_key) button_layout.addWidget(self._add_key_button) self._delete_key_button = QtGui.QToolButton(self) self._delete_key_button.setToolTip(_(u"Delete highlighted key")) self._delete_key_button.setIcon(QIcon(I('list_remove.png'))) self._delete_key_button.clicked.connect(self.delete_key) button_layout.addWidget(self._delete_key_button) if type(self.plugin_keys) == dict and self.import_key: self._rename_key_button = QtGui.QToolButton(self) self._rename_key_button.setToolTip(_(u"Rename highlighted key")) self._rename_key_button.setIcon(QIcon(I('edit-select-all.png'))) self._rename_key_button.clicked.connect(self.rename_key) button_layout.addWidget(self._rename_key_button) self.export_key_button = QtGui.QToolButton(self) self.export_key_button.setToolTip(u"Save highlighted key to a .{0} file".format(self.keyfile_ext)) self.export_key_button.setIcon(QIcon(I('save.png'))) self.export_key_button.clicked.connect(self.export_key) button_layout.addWidget(self.export_key_button) spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) button_layout.addItem(spacerItem) if self.wineprefix is not None: layout.addSpacing(5) wineprefix_layout = QHBoxLayout() layout.addLayout(wineprefix_layout) wineprefix_layout.setAlignment(Qt.AlignCenter) self.wp_label = QLabel(u"WINEPREFIX:") wineprefix_layout.addWidget(self.wp_label) self.wp_lineedit = QLineEdit(self) wineprefix_layout.addWidget(self.wp_lineedit) self.wp_label.setBuddy(self.wp_lineedit) self.wp_lineedit.setText(self.wineprefix) layout.addSpacing(5) migrate_layout = QHBoxLayout() layout.addLayout(migrate_layout) if self.import_key: migrate_layout.setAlignment(Qt.AlignJustify) self.migrate_btn = QPushButton(u"Import Existing Keyfiles", self) self.migrate_btn.setToolTip(u"Import *.{0} files (created using other tools).".format(self.keyfile_ext)) self.migrate_btn.clicked.connect(self.migrate_wrapper) migrate_layout.addWidget(self.migrate_btn) migrate_layout.addStretch() self.button_box = QDialogButtonBox(QDialogButtonBox.Close) self.button_box.rejected.connect(self.close) migrate_layout.addWidget(self.button_box) self.resize(self.sizeHint())