Example #1
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.l = l = QGridLayout(self)

        def add_row(*args):
            r = l.rowCount()
            if len(args) == 1:
                l.addWidget(args[0], r, 0, 1, 2)
            else:
                la = QLabel(args[0])
                l.addWidget(la, r, 0, Qt.AlignmentFlag.AlignRight), l.addWidget(args[1], r, 1)
                la.setBuddy(args[1])

        self.heading = la = QLabel('<h2>\xa0')
        add_row(la)
        self.helpl = la = QLabel(_('For help with snippets, see the <a href="%s">User Manual</a>') %
                                 localize_user_manual_link('https://manual.calibre-ebook.com/snippets.html'))
        la.setOpenExternalLinks(True)
        add_row(la)

        self.name = n = QLineEdit(self)
        n.setPlaceholderText(_('The name of this snippet'))
        add_row(_('&Name:'), n)

        self.trig = t = QLineEdit(self)
        t.setPlaceholderText(_('The text used to trigger this snippet'))
        add_row(_('Tri&gger:'), t)

        self.template = t = PlainTextEdit(self)
        la.setBuddy(t)
        add_row(_('&Template:'), t)

        self.types = t = QListWidget(self)
        t.setFlow(QListView.Flow.LeftToRight)
        t.setWrapping(True), t.setResizeMode(QListView.ResizeMode.Adjust), t.setSpacing(5)
        fm = t.fontMetrics()
        t.setMaximumHeight(2*(fm.ascent() + fm.descent()) + 25)
        add_row(_('&File types:'), t)
        t.setToolTip(_('Which file types this snippet should be active in'))

        self.frame = f = QFrame(self)
        f.setFrameShape(QFrame.Shape.HLine)
        add_row(f)
        self.test = d = SnippetTextEdit('', self)
        d.snippet_manager.snip_func = self.snip_func
        d.setToolTip(_('You can test your snippet here'))
        d.setMaximumHeight(t.maximumHeight() + 15)
        add_row(_('T&est:'), d)

        i = QListWidgetItem(_('All'), t)
        i.setData(Qt.ItemDataRole.UserRole, '*')
        i.setCheckState(Qt.CheckState.Checked)
        i.setFlags(i.flags() | Qt.ItemFlag.ItemIsUserCheckable)
        for ftype in sorted(all_text_syntaxes):
            i = QListWidgetItem(ftype, t)
            i.setData(Qt.ItemDataRole.UserRole, ftype)
            i.setCheckState(Qt.CheckState.Checked)
            i.setFlags(i.flags() | Qt.ItemFlag.ItemIsUserCheckable)

        self.creating_snippet = False
Example #2
0
 def setup_ui(self):
     self.l = l = QFormLayout(self)
     l.setFieldGrowthPolicy(
         QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
     l.addRow(
         QLabel(
             _('The key of the identifier, for example, in isbn:XXX, the key is "isbn"'
               )))
     self.key = k = QLineEdit(self)
     l.addRow(_('&Key:'), k)
     l.addRow(
         QLabel(_('The name that will appear in the Book details panel')))
     self.nw = n = QLineEdit(self)
     l.addRow(_('&Name:'), n)
     la = QLabel(
         _('The template used to create the link.'
           ' The placeholder {0} in the template will be replaced'
           ' with the actual identifier value. Use {1} to avoid the value'
           ' being quoted.').format('{id}', '{id_unquoted}'))
     la.setWordWrap(True)
     l.addRow(la)
     self.template = t = QLineEdit(self)
     l.addRow(_('&Template:'), t)
     t.selectAll()
     t.setFocus(Qt.FocusReason.OtherFocusReason)
     l.addWidget(self.bb)
Example #3
0
    def setup_ui(self):
        self.l = l = QFormLayout(self)
        self.setLayout(l)

        self.title = t = QLineEdit(self)
        l.addRow(_('&Title:'), t)
        t.setFocus(Qt.FocusReason.OtherFocusReason)

        self.authors = a = QLineEdit(self)
        l.addRow(_('&Authors:'), a)
        a.setText(tprefs.get('previous_new_book_authors', ''))

        self.languages = la = LanguagesEdit(self)
        l.addRow(_('&Language:'), la)
        la.lang_codes = (tprefs.get('previous_new_book_lang',
                                    canonicalize_lang(get_lang())), )

        bb = self.bb
        l.addRow(bb)
        bb.clear()
        bb.addButton(QDialogButtonBox.StandardButton.Cancel)
        b = bb.addButton('&EPUB', QDialogButtonBox.ButtonRole.AcceptRole)
        connect_lambda(b.clicked, self, lambda self: self.set_fmt('epub'))
        b = bb.addButton('&AZW3', QDialogButtonBox.ButtonRole.AcceptRole)
        connect_lambda(b.clicked, self, lambda self: self.set_fmt('azw3'))
Example #4
0
    def __init__(self, stats, location, parent=None):
        QDialog.__init__(self, parent)
        self.setWindowTitle(_('No library found'))
        self._l = l = QGridLayout(self)
        self.setLayout(l)
        self.stats, self.location = stats, location

        loc = self.oldloc = location.replace('/', os.sep)
        self.header = QLabel(
            _('No existing calibre library was found at %s. '
              'If the library was moved, select its new location below. '
              'Otherwise calibre will forget this library.') % loc)
        self.header.setWordWrap(True)
        ncols = 2
        l.addWidget(self.header, 0, 0, 1, ncols)
        self.cl = QLabel('<b>' + _('New location of this library:'))
        l.addWidget(self.cl, l.rowCount(), 0, 1, ncols)
        self.loc = QLineEdit(loc, self)
        l.addWidget(self.loc, l.rowCount(), 0, 1, 1)
        self.cd = QToolButton(self)
        self.cd.setIcon(QIcon(I('document_open.png')))
        self.cd.clicked.connect(self.choose_dir)
        l.addWidget(self.cd, l.rowCount() - 1, 1, 1, 1)
        self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Abort)
        b = self.bb.addButton(_('Library moved'),
                              QDialogButtonBox.ButtonRole.AcceptRole)
        b.setIcon(QIcon(I('ok.png')))
        b = self.bb.addButton(_('Forget library'),
                              QDialogButtonBox.ButtonRole.RejectRole)
        b.setIcon(QIcon(I('edit-clear.png')))
        b.clicked.connect(self.forget_library)
        self.bb.accepted.connect(self.accept)
        self.bb.rejected.connect(self.reject)
        l.addWidget(self.bb, 3, 0, 1, ncols)
        self.resize(self.sizeHint() + QSize(120, 0))
Example #5
0
    def setup_ui(self):
        self.l = l = QGridLayout()
        self.setLayout(l)

        self.la = la = QLabel(_(
            'Arrange the files in this book into sub-folders based on their types.'
            ' If you leave a folder blank, the files will be placed in the root.'))
        la.setWordWrap(True)
        l.addWidget(la, 0, 0, 1, -1)

        folders = tprefs['folders_for_types']
        for i, (typ, text) in enumerate(self.TYPE_MAP):
            la = QLabel('&' + text)
            setattr(self, '%s_label' % typ, la)
            le = QLineEdit(self)
            setattr(self, '%s_folder' % typ, le)
            val = folders.get(typ, '')
            if val and not val.endswith('/'):
                val += '/'
            le.setText(val)
            la.setBuddy(le)
            l.addWidget(la, i + 1, 0)
            l.addWidget(le, i + 1, 1)
        self.la2 = la = QLabel(_(
            'Note that this will only arrange files inside the book,'
            ' it will not affect how they are displayed in the File browser'))
        la.setWordWrap(True)
        l.addWidget(la, i + 2, 0, 1, -1)
        l.addWidget(self.bb, i + 3, 0, 1, -1)
Example #6
0
 def __init__(self, user_data, parent=None, username=None):
     QDialog.__init__(self, parent)
     self.user_data = user_data
     self.setWindowTitle(
         _('Change password for {}').format(username)
         if username else _('Add new user')
     )
     self.l = l = QFormLayout(self)
     l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
     self.uw = u = QLineEdit(self)
     l.addRow(_('&Username:'******'Set the password for this user')))
     self.p1, self.p2 = p1, p2 = QLineEdit(self), QLineEdit(self)
     l.addRow(_('&Password:'******'&Repeat password:'******'pw'])
     self.showp = sp = QCheckBox(_('&Show password'))
     sp.stateChanged.connect(self.show_password)
     l.addRow(sp)
     self.bb = bb = QDialogButtonBox(
         QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
     )
     l.addRow(bb)
     bb.accepted.connect(self.accept), bb.rejected.connect(self.reject)
     (self.uw if not username else self.p1).setFocus(Qt.FocusReason.OtherFocusReason)
Example #7
0
    def __init__(self,
                 parent=None,
                 completer_widget=None,
                 sort_func=sort_key,
                 strip_completion_entries=True):
        QLineEdit.__init__(self, parent)
        self.setClearButtonEnabled(True)

        self.sep = ','
        self.space_before_sep = False
        self.add_separator = True
        self.original_cursor_pos = None
        completer_widget = (self
                            if completer_widget is None else completer_widget)

        self.mcompleter = Completer(
            completer_widget,
            sort_func=sort_func,
            strip_completion_entries=strip_completion_entries)
        self.mcompleter.item_selected.connect(
            self.completion_selected, type=Qt.ConnectionType.QueuedConnection)
        self.mcompleter.relayout_needed.connect(self.relayout)
        self.mcompleter.setFocusProxy(completer_widget)
        self.textEdited.connect(self.text_edited)
        self.no_popup = False
Example #8
0
class MovedDialog(QDialog):  # {{{
    def __init__(self, stats, location, parent=None):
        QDialog.__init__(self, parent)
        self.setWindowTitle(_('No library found'))
        self._l = l = QGridLayout(self)
        self.setLayout(l)
        self.stats, self.location = stats, location

        loc = self.oldloc = location.replace('/', os.sep)
        self.header = QLabel(
            _('No existing calibre library was found at %s. '
              'If the library was moved, select its new location below. '
              'Otherwise calibre will forget this library.') % loc)
        self.header.setWordWrap(True)
        ncols = 2
        l.addWidget(self.header, 0, 0, 1, ncols)
        self.cl = QLabel('<b>' + _('New location of this library:'))
        l.addWidget(self.cl, l.rowCount(), 0, 1, ncols)
        self.loc = QLineEdit(loc, self)
        l.addWidget(self.loc, l.rowCount(), 0, 1, 1)
        self.cd = QToolButton(self)
        self.cd.setIcon(QIcon(I('document_open.png')))
        self.cd.clicked.connect(self.choose_dir)
        l.addWidget(self.cd, l.rowCount() - 1, 1, 1, 1)
        self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Abort)
        b = self.bb.addButton(_('Library moved'),
                              QDialogButtonBox.ButtonRole.AcceptRole)
        b.setIcon(QIcon(I('ok.png')))
        b = self.bb.addButton(_('Forget library'),
                              QDialogButtonBox.ButtonRole.RejectRole)
        b.setIcon(QIcon(I('edit-clear.png')))
        b.clicked.connect(self.forget_library)
        self.bb.accepted.connect(self.accept)
        self.bb.rejected.connect(self.reject)
        l.addWidget(self.bb, 3, 0, 1, ncols)
        self.resize(self.sizeHint() + QSize(120, 0))

    def choose_dir(self):
        d = choose_dir(self,
                       'library moved choose new loc',
                       _('New library location'),
                       default_dir=self.oldloc)
        if d is not None:
            self.loc.setText(d)

    def forget_library(self):
        self.stats.remove(self.location)

    def accept(self):
        newloc = str(self.loc.text())
        if not db_class().exists_at(newloc):
            error_dialog(self,
                         _('No library found'),
                         _('No existing calibre library found at %s') % newloc,
                         show=True)
            return
        self.stats.rename(self.location, newloc)
        self.newloc = newloc
        QDialog.accept(self)
Example #9
0
    def do_user_config(self, parent=None):
        '''
        This method shows a configuration dialog for this plugin. It returns
        True if the user clicks OK, False otherwise. The changes are
        automatically applied.
        '''
        from qt.core import (QDialog, QDialogButtonBox, QVBoxLayout, QLabel,
                             Qt, QLineEdit, QCheckBox)

        config_dialog = QDialog(parent)
        button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok
                                      | QDialogButtonBox.StandardButton.Cancel)
        v = QVBoxLayout(config_dialog)

        def size_dialog():
            config_dialog.resize(config_dialog.sizeHint())

        button_box.accepted.connect(config_dialog.accept)
        button_box.rejected.connect(config_dialog.reject)
        config_dialog.setWindowTitle(_('Customize') + ' ' + self.name)
        from calibre.customize.ui import (plugin_customization,
                                          customize_plugin)
        help_text = self.customization_help(gui=True)
        help_text = QLabel(help_text, config_dialog)
        help_text.setWordWrap(True)
        help_text.setTextInteractionFlags(
            Qt.TextInteractionFlag.LinksAccessibleByMouse
            | Qt.TextInteractionFlag.LinksAccessibleByKeyboard)
        help_text.setOpenExternalLinks(True)
        v.addWidget(help_text)
        bf = QCheckBox(_('Add linked files in breadth first order'))
        bf.setToolTip(
            _('Normally, when following links in HTML files'
              ' calibre does it depth first, i.e. if file A links to B and '
              ' C, but B links to D, the files are added in the order A, B, D, C. '
              ' With this option, they will instead be added as A, B, C, D'))
        sc = plugin_customization(self)
        if not sc:
            sc = ''
        sc = sc.strip()
        enc = sc.partition('|')[0]
        bfs = sc.partition('|')[-1]
        bf.setChecked(bfs == 'bf')
        sc = QLineEdit(enc, config_dialog)
        v.addWidget(sc)
        v.addWidget(bf)
        v.addWidget(button_box)
        size_dialog()
        config_dialog.exec()

        if config_dialog.result() == QDialog.DialogCode.Accepted:
            sc = str(sc.text()).strip()
            if bf.isChecked():
                sc += '|bf'
            customize_plugin(self, sc)

        return config_dialog.result()
Example #10
0
    def setup_ui(self):
        self.l = l = QVBoxLayout(self)
        self.setLayout(l)

        self.h = h = QHBoxLayout()
        l.addLayout(h)

        names = [n for n, linear in self.container.spine_names]
        fn, f = create_filterable_names_list(names, filter_text=_('Filter files'), parent=self)
        self.file_names, self.file_names_filter = fn, f
        fn.selectionModel().selectionChanged.connect(self.selected_file_changed)
        self.fnl = fnl = QVBoxLayout()
        self.la1 = la = QLabel(_('Choose a &file to link to:'))
        la.setBuddy(fn)
        fnl.addWidget(la), fnl.addWidget(f), fnl.addWidget(fn)
        h.addLayout(fnl), h.setStretch(0, 2)

        fn, f = create_filterable_names_list([], filter_text=_('Filter locations'), parent=self, model=AnchorsModel)
        fn.setSpacing(5)
        self.anchor_names, self.anchor_names_filter = fn, f
        fn.selectionModel().selectionChanged.connect(self.update_target)
        fn.doubleClicked.connect(self.accept, type=Qt.ConnectionType.QueuedConnection)
        self.anl = fnl = QVBoxLayout()
        self.la2 = la = QLabel(_('Choose a &location (anchor) in the file:'))
        la.setBuddy(fn)
        fnl.addWidget(la), fnl.addWidget(f), fnl.addWidget(fn)
        h.addLayout(fnl), h.setStretch(1, 1)

        self.tl = tl = QFormLayout()
        tl.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
        self.target = t = QLineEdit(self)
        t.setPlaceholderText(_('The destination (href) for the link'))
        tl.addRow(_('&Target:'), t)
        l.addLayout(tl)

        self.text_edit = t = QLineEdit(self)
        la.setBuddy(t)
        tl.addRow(_('Te&xt:'), t)
        t.setText(self.initial_text or '')
        t.setPlaceholderText(_('The (optional) text for the link'))

        self.template_edit = t = HistoryComboBox(self)
        t.lineEdit().setClearButtonEnabled(True)
        t.initialize('edit_book_insert_link_template_history')
        tl.addRow(_('Tem&plate:'), t)
        from calibre.gui2.tweak_book.editor.smarts.html import DEFAULT_LINK_TEMPLATE
        t.setText(tprefs.get('insert-hyperlink-template', None) or DEFAULT_LINK_TEMPLATE)
        t.setToolTip('<p>' + _('''
            The template to use for generating the link. In addition to {0} and {1}
            you can also use {2}, {3} and {4} variables
            in the template, they will be replaced by the source filename, the destination
            filename and the anchor, respectively.
        ''').format(
            '_TEXT_', '_TARGET_', '_SOURCE_FILENAME_', '_DEST_FILENAME_', '_ANCHOR_'))

        l.addWidget(self.bb)
Example #11
0
    def __init__(self, current_family, parent=None):
        QDialog.__init__(self, parent)
        self.setWindowTitle(_('Choose font family'))
        self.setWindowIcon(QIcon(I('font.png')))
        from calibre.utils.fonts.scanner import font_scanner
        self.font_scanner = font_scanner

        self.m = QStringListModel(self)
        self.build_font_list()
        self.l = l = QGridLayout()
        self.setLayout(l)
        self.view = FontsView(self)
        self.view.setModel(self.m)
        self.view.setCurrentIndex(self.m.index(0))
        if current_family:
            for i, val in enumerate(self.families):
                if icu_lower(val) == icu_lower(current_family):
                    self.view.setCurrentIndex(self.m.index(i))
                    break
        self.view.doubleClicked.connect(
            self.accept, type=Qt.ConnectionType.QueuedConnection)
        self.view.changed.connect(self.current_changed,
                                  type=Qt.ConnectionType.QueuedConnection)
        self.faces = Typefaces(self)
        self.bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok
                                   | QDialogButtonBox.StandardButton.Cancel)
        self.bb.accepted.connect(self.accept)
        self.bb.rejected.connect(self.reject)
        self.add_fonts_button = afb = self.bb.addButton(
            _('Add &fonts'), QDialogButtonBox.ButtonRole.ActionRole)
        afb.setIcon(QIcon(I('plus.png')))
        afb.clicked.connect(self.add_fonts)
        self.ml = QLabel(_('Choose a font family from the list below:'))
        self.search = QLineEdit(self)
        self.search.setPlaceholderText(_('Search'))
        self.search.returnPressed.connect(self.find)
        self.nb = QToolButton(self)
        self.nb.setIcon(QIcon(I('arrow-down.png')))
        self.nb.setToolTip(_('Find next'))
        self.pb = QToolButton(self)
        self.pb.setIcon(QIcon(I('arrow-up.png')))
        self.pb.setToolTip(_('Find previous'))
        self.nb.clicked.connect(self.find_next)
        self.pb.clicked.connect(self.find_previous)

        l.addWidget(self.ml, 0, 0, 1, 4)
        l.addWidget(self.search, 1, 0, 1, 1)
        l.addWidget(self.nb, 1, 1, 1, 1)
        l.addWidget(self.pb, 1, 2, 1, 1)
        l.addWidget(self.view, 2, 0, 1, 3)
        l.addWidget(self.faces, 1, 3, 2, 1)
        l.addWidget(self.bb, 3, 0, 1, 4)
        l.setAlignment(self.faces, Qt.AlignmentFlag.AlignTop)

        self.resize(800, 600)
Example #12
0
    def __init__(self, parent, device):
        super().__init__(parent, device)
        self.setTitle(_("Collections"))

        self.options_layout = QGridLayout()
        self.options_layout.setObjectName("options_layout")
        self.setLayout(self.options_layout)

        self.setCheckable(True)
        self.setChecked(device.get_pref('manage_collections'))
        self.setToolTip(
            wrap_msg(
                _('Create new bookshelves on the Kobo if they do not exist. This is only for firmware V2.0.0 or later.'
                  )))

        self.collections_columns_label = QLabel(_('Collections columns:'))
        self.collections_columns_edit = QLineEdit(self)
        self.collections_columns_edit.setToolTip(
            _('The Kobo from firmware V2.0.0 supports bookshelves.'
              ' These are created on the Kobo. '
              'Specify a tags type column for automatic management.'))
        self.collections_columns_edit.setText(
            device.get_pref('collections_columns'))

        self.create_collections_checkbox = create_checkbox(
            _("Create collections"),
            _('Create new bookshelves on the Kobo if they do not exist. This is only for firmware V2.0.0 or later.'
              ), device.get_pref('create_collections'))
        self.delete_empty_collections_checkbox = create_checkbox(
            _('Delete empty bookshelves'),
            _('Delete any empty bookshelves from the Kobo when syncing is finished. This is only for firmware V2.0.0 or later.'
              ), device.get_pref('delete_empty_collections'))

        self.ignore_collections_names_label = QLabel(_('Ignore collections:'))
        self.ignore_collections_names_edit = QLineEdit(self)
        self.ignore_collections_names_edit.setToolTip(
            _('List the names of collections to be ignored by '
              'the collection management. The collections listed '
              'will not be changed. Names are separated by commas.'))
        self.ignore_collections_names_edit.setText(
            device.get_pref('ignore_collections_names'))

        self.options_layout.addWidget(self.collections_columns_label, 1, 0, 1,
                                      1)
        self.options_layout.addWidget(self.collections_columns_edit, 1, 1, 1,
                                      1)
        self.options_layout.addWidget(self.create_collections_checkbox, 2, 0,
                                      1, 2)
        self.options_layout.addWidget(self.delete_empty_collections_checkbox,
                                      3, 0, 1, 2)
        self.options_layout.addWidget(self.ignore_collections_names_label, 4,
                                      0, 1, 1)
        self.options_layout.addWidget(self.ignore_collections_names_edit, 4, 1,
                                      1, 1)
Example #13
0
    def __init__(self):
        QWidget.__init__(self)
        self.l = QHBoxLayout()
        self.setLayout(self.l)

        self.label = QLabel('Hello world &message:')
        self.l.addWidget(self.label)

        self.msg = QLineEdit(self)
        self.msg.setText(prefs['hello_world_msg'])
        self.l.addWidget(self.msg)
        self.label.setBuddy(self.msg)
Example #14
0
class DaysOfMonth(Base):

    HELP = _('''\
                Download this periodical every month, on the specified days.
                The download will happen as soon after the specified time as
                possible on the specified days of each month. For example,
                if you choose the 1st and the 15th after 9:00 AM, the
                periodical will be downloaded on the 1st and 15th of every
                month, as soon after 9:00 AM as possible.
            ''')

    def __init__(self, parent=None):
        Base.__init__(self, parent)

        self.l1 = QLabel(_('&Days of the month:'))
        self.days = QLineEdit(self)
        self.days.setToolTip(
            _('Comma separated list of days of the month.'
              ' For example: 1, 15'))
        self.l1.setBuddy(self.days)

        self.l2 = QLabel(_('Download &after:'))
        self.time = QTimeEdit(self)
        self.time.setDisplayFormat('hh:mm AP')
        self.l2.setBuddy(self.time)

        self.l.addWidget(self.l1, 0, 0, 1, 1)
        self.l.addWidget(self.days, 0, 1, 1, 1)
        self.l.addWidget(self.l2, 1, 0, 1, 1)
        self.l.addWidget(self.time, 1, 1, 1, 1)

    def initialize(self, typ=None, val=None):
        if val is None:
            val = ((1, ), 6, 0)
        days_of_month, hour, minute = val
        self.days.setText(', '.join(map(str, map(int, days_of_month))))
        self.time.setTime(QTime(hour, minute))

    @property
    def schedule(self):
        parts = [
            x.strip() for x in unicode_type(self.days.text()).split(',')
            if x.strip()
        ]
        try:
            days_of_month = tuple(map(int, parts))
        except:
            days_of_month = (1, )
        if not days_of_month:
            days_of_month = (1, )
        t = self.time.time()
        hour, minute = t.hour(), t.minute()
        return 'days_of_month', (days_of_month, int(hour), int(minute))
Example #15
0
def create_filterable_names_list(names, filter_text=None, parent=None, model=NamesModel):
    nl = QListView(parent)
    nl.m = m = model(names, parent=nl)
    connect_lambda(m.filtered, nl, lambda nl, all_items: nl.scrollTo(m.index(0)))
    nl.setModel(m)
    if model is NamesModel:
        nl.d = NamesDelegate(nl)
        nl.setItemDelegate(nl.d)
    f = QLineEdit(parent)
    f.setPlaceholderText(filter_text or '')
    f.textEdited.connect(m.filter)
    return nl, f
Example #16
0
    def setup_ui(self):
        self.l = l = QFormLayout(self)
        self.setLayout(l)

        self.err_label = QLabel('')
        self.name_edit = QLineEdit(self)
        self.name_edit.textChanged.connect(self.verify)
        self.name_edit.setText(self.candidate)
        pos = self.candidate.rfind('.')
        if pos > -1:
            self.name_edit.setSelection(0, pos)
        l.addRow(_('File &name:'), self.name_edit)
        l.addRow(self.err_label)
        l.addRow(self.bb)
Example #17
0
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self.default_template = default_custom_list_template()
        self.l = l = QFormLayout(self)
        l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
        self.la = la = QLabel('<p>' + _(
            'Here you can create a template to control what data is shown when'
            ' using the <i>Custom list</i> mode for the book list'))
        la.setWordWrap(True)
        l.addRow(la)
        self.thumbnail = t = QCheckBox(_('Show a cover &thumbnail'))
        self.thumbnail_height = th = QSpinBox(self)
        th.setSuffix(' px'), th.setRange(60, 600)
        self.entry_height = eh = QLineEdit(self)
        l.addRow(t), l.addRow(_('Thumbnail &height:'), th)
        l.addRow(_('Entry &height:'), eh)
        t.stateChanged.connect(self.changed_signal)
        th.valueChanged.connect(self.changed_signal)
        eh.textChanged.connect(self.changed_signal)
        eh.setToolTip(textwrap.fill(_(
            'The height for each entry. The special value "auto" causes a height to be calculated'
            ' based on the number of lines in the template. Otherwise, use a CSS length, such as'
            ' 100px or 15ex')))
        t.stateChanged.connect(self.thumbnail_state_changed)
        th.setVisible(False)

        self.comments_fields = cf = QLineEdit(self)
        l.addRow(_('&Long text fields:'), cf)
        cf.setToolTip(textwrap.fill(_(
            'A comma separated list of fields that will be added at the bottom of every entry.'
            ' These fields are interpreted as containing HTML, not plain text.')))
        cf.textChanged.connect(self.changed_signal)

        self.la1 = la = QLabel('<p>' + _(
            'The template below will be interpreted as HTML and all {{fields}} will be replaced'
            ' by the actual metadata, if available. For custom columns use the column lookup'
            ' name, for example: #mytags. You can use {0} as a separator'
            ' to split a line into multiple columns.').format('|||'))
        la.setWordWrap(True)
        l.addRow(la)
        self.template = t = QPlainTextEdit(self)
        l.addRow(t)
        t.textChanged.connect(self.changed_signal)
        self.imex = bb = QDialogButtonBox(self)
        b = bb.addButton(_('&Import template'), QDialogButtonBox.ButtonRole.ActionRole)
        b.clicked.connect(self.import_template)
        b = bb.addButton(_('E&xport template'), QDialogButtonBox.ButtonRole.ActionRole)
        b.clicked.connect(self.export_template)
        l.addRow(bb)
Example #18
0
 def set_mi(self, mi, fm):
     '''
     This sets the metadata for the test result books table. It doesn't reset
     the contents of the field selectors for editing rules.
     '''
     self.fm = fm
     if mi:
         if not isinstance(mi, list):
             mi = (mi, )
     else:
         mi = Metadata(_('Title'), [_('Author')])
         mi.author_sort = _('Author Sort')
         mi.series = ngettext('Series', 'Series', 1)
         mi.series_index = 3
         mi.rating = 4.0
         mi.tags = [_('Tag 1'), _('Tag 2')]
         mi.languages = ['eng']
         mi.id = 1
         if self.fm is not None:
             mi.set_all_user_metadata(self.fm.custom_field_metadata())
         else:
             # No field metadata. Grab a copy from the current library so
             # that we can validate any custom column names. The values for
             # the columns will all be empty, which in some very unusual
             # cases might cause formatter errors. We can live with that.
             from calibre.gui2.ui import get_gui
             mi.set_all_user_metadata(get_gui(
             ).current_db.new_api.field_metadata.custom_field_metadata())
         for col in mi.get_all_user_metadata(False):
             mi.set(col, (col, ), 0)
         mi = (mi, )
     self.mi = mi
     tv = self.template_value
     tv.setColumnCount(2)
     tv.setHorizontalHeaderLabels((_('Book title'), _('Template value')))
     tv.horizontalHeader().setStretchLastSection(True)
     tv.horizontalHeader().sectionResized.connect(self.table_column_resized)
     tv.setRowCount(len(mi))
     # Set the height of the table
     h = tv.rowHeight(0) * min(len(mi), 5)
     h += 2 * tv.frameWidth() + tv.horizontalHeader().height()
     tv.setMinimumHeight(h)
     tv.setMaximumHeight(h)
     # Set the size of the title column
     if self.table_column_widths:
         tv.setColumnWidth(0, self.table_column_widths[0])
     else:
         tv.setColumnWidth(0, tv.fontMetrics().averageCharWidth() * 10)
     tv.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
     tv.setRowCount(len(mi))
     # Use our own widget to get rid of elision. setTextElideMode() doesn't work
     for r in range(0, len(mi)):
         w = QLineEdit(tv)
         w.setReadOnly(True)
         tv.setCellWidget(r, 0, w)
         w = QLineEdit(tv)
         w.setReadOnly(True)
         tv.setCellWidget(r, 1, w)
     self.display_values('')
Example #19
0
class AdvancedGroupBox(DeviceOptionsGroupBox):
    def __init__(self, parent, device):
        super(AdvancedGroupBox, self).__init__(parent, device,
                                               _("Advanced options"))
        #         self.setTitle(_("Advanced Options"))

        self.options_layout = QGridLayout()
        self.options_layout.setObjectName("options_layout")
        self.setLayout(self.options_layout)

        self.support_newer_firmware_checkbox = create_checkbox(
            _("Attempt to support newer firmware"),
            _('Kobo routinely updates the firmware and the '
              'database version. With this option calibre will attempt '
              'to perform full read-write functionality - Here be Dragons!! '
              'Enable only if you are comfortable with restoring your kobo '
              'to factory defaults and testing software. '
              'This driver supports firmware V2.x.x and DBVersion up to ') +
            unicode_type(device.supported_dbversion),
            device.get_pref('support_newer_firmware'))

        self.debugging_title_checkbox = create_checkbox(
            _("Title to test when debugging"),
            _('Part of title of a book that can be used when doing some tests for debugging. '
              'The test is to see if the string is contained in the title of a book. '
              'The better the match, the less extraneous output.'),
            device.get_pref('debugging_title'))
        self.debugging_title_label = QLabel(_('Title to test when debugging:'))
        self.debugging_title_edit = QLineEdit(self)
        self.debugging_title_edit.setToolTip(
            _('Part of title of a book that can be used when doing some tests for debugging. '
              'The test is to see if the string is contained in the title of a book. '
              'The better the match, the less extraneous output.'))
        self.debugging_title_edit.setText(device.get_pref('debugging_title'))
        self.debugging_title_label.setBuddy(self.debugging_title_edit)

        self.options_layout.addWidget(self.support_newer_firmware_checkbox, 0,
                                      0, 1, 2)
        self.options_layout.addWidget(self.debugging_title_label, 1, 0, 1, 1)
        self.options_layout.addWidget(self.debugging_title_edit, 1, 1, 1, 1)

    @property
    def support_newer_firmware(self):
        return self.support_newer_firmware_checkbox.isChecked()

    @property
    def debugging_title(self):
        return self.debugging_title_edit.text().strip()
Example #20
0
 def __init__(self,
              scheme_name,
              scheme,
              existing_names,
              edit_scheme=False,
              parent=None):
     QDialog.__init__(self, parent)
     self.existing_names, self.is_editing, self.scheme_name = existing_names, edit_scheme, scheme_name
     self.l = l = QFormLayout(self)
     self.setLayout(l)
     self.setWindowTitle(scheme_name)
     self.name = n = QLineEdit(self)
     n.setText(scheme_name if edit_scheme else '#' + ('My Color Scheme'))
     l.addRow(_('&Name:'), self.name)
     for x in 'color1 color2 contrast_color1 contrast_color2'.split():
         setattr(self, x, ColorButton(scheme[x], self))
     l.addRow(_('Color &1:'), self.color1)
     l.addRow(_('Color &2:'), self.color2)
     l.addRow(_('Contrast color &1 (mainly for text):'),
              self.contrast_color1)
     l.addRow(_('Contrast color &2 (mainly for text):'),
              self.contrast_color2)
     self.bb = bb = QDialogButtonBox(
         QDialogButtonBox.StandardButton.Ok
         | QDialogButtonBox.StandardButton.Cancel)
     bb.accepted.connect(self.accept)
     bb.rejected.connect(self.reject)
     l.addRow(bb)
Example #21
0
 def __init__(self, name, is_checked=False, path='', restriction='', parent=None, is_first=False, enable_on_checked=True):
     QWidget.__init__(self, parent)
     self.name = name
     self.enable_on_checked = enable_on_checked
     self.l = l = QVBoxLayout(self)
     l.setSizeConstraint(QLayout.SizeConstraint.SetMinAndMaxSize)
     if not is_first:
         self.border = b = QFrame(self)
         b.setFrameStyle(QFrame.Shape.HLine)
         l.addWidget(b)
     self.cw = cw = QCheckBox(name.replace('&', '&&'))
     cw.setStyleSheet('QCheckBox { font-weight: bold }')
     cw.setChecked(is_checked)
     cw.stateChanged.connect(self.state_changed)
     if path:
         cw.setToolTip(path)
     l.addWidget(cw)
     self.la = la = QLabel(_('Further &restrict access to books in this library that match:'))
     l.addWidget(la)
     self.rw = rw = QLineEdit(self)
     rw.setPlaceholderText(_('A search expression'))
     rw.setToolTip(textwrap.fill(_(
         'A search expression. If specified, access will be further restricted'
         ' to only those books that match this expression. For example:'
         ' tags:"=Share"')))
     rw.setText(restriction or '')
     rw.textChanged.connect(self.on_rchange)
     la.setBuddy(rw)
     l.addWidget(rw)
     self.state_changed()
Example #22
0
 def __init__(self, parent):
     QWidget.__init__(self, parent)
     l = QVBoxLayout(parent)
     l.addWidget(self)
     l.setContentsMargins(0, 0, 0, 0)
     l = QFormLayout(self)
     l.setContentsMargins(0, 0, 0, 0)
     l.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
     self.choices = c = QComboBox()
     c.setMinimumContentsLength(30)
     for text, data in [
             (_('Search for the author on Goodreads'), 'search-goodreads'),
             (_('Search for the author on Amazon'), 'search-amzn'),
             (_('Search for the author in your calibre library'), 'search-calibre'),
             (_('Search for the author on Wikipedia'), 'search-wikipedia'),
             (_('Search for the author on Google Books'), 'search-google'),
             (_('Search for the book on Goodreads'), 'search-goodreads-book'),
             (_('Search for the book on Amazon'), 'search-amzn-book'),
             (_('Search for the book on Google Books'), 'search-google-book'),
             (_('Use a custom search URL'), 'url'),
     ]:
         c.addItem(text, data)
     l.addRow(_('Clicking on &author names should:'), c)
     self.custom_url = u = QLineEdit(self)
     u.setToolTip(_(
         'Enter the URL to search. It should contain the string {0}'
         '\nwhich will be replaced by the author name. For example,'
         '\n{1}').format('{author}', 'https://en.wikipedia.org/w/index.php?search={author}'))
     u.textChanged.connect(self.changed_signal)
     u.setPlaceholderText(_('Enter the URL'))
     c.currentIndexChanged.connect(self.current_changed)
     l.addRow(u)
     self.current_changed()
     c.currentIndexChanged.connect(self.changed_signal)
Example #23
0
 def setupUi(self, *a):
     self.l = l = QFormLayout(self)
     self.opt_docx_page_size = QComboBox(self)
     l.addRow(_('Paper si&ze:'), self.opt_docx_page_size)
     self.opt_docx_custom_page_size = w = QLineEdit(self)
     w.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
     l.addRow(_('&Custom size:'), w)
     for i, text in enumerate(
         (_('Page &left margin'), _('Page &top margin'),
          _('Page &right margin'), _('Page &bottom margin'))):
         m = 'left top right bottom'.split()[i]
         w = QDoubleSpinBox(self)
         w.setRange(-100, 500), w.setSuffix(' pt'), w.setDecimals(1)
         setattr(self, 'opt_docx_page_margin_' + m, w)
         l.addRow(text + ':', w)
     self.opt_docx_no_toc = QCheckBox(
         _('Do not insert the &Table of Contents as a page at the start of the document'
           ))
     l.addRow(self.opt_docx_no_toc)
     self.opt_docx_no_cover = QCheckBox(
         _('Do not insert &cover as image at start of document'))
     l.addRow(self.opt_docx_no_cover)
     self.opt_preserve_cover_aspect_ratio = QCheckBox(
         _('Preserve the aspect ratio of the image inserted as cover'))
     l.addRow(self.opt_preserve_cover_aspect_ratio)
Example #24
0
    def setup_ui(self):
        from calibre.gui2.convert.look_and_feel_ui import Ui_Form
        f, w = Ui_Form(), QWidget()
        f.setupUi(w)
        self.l = l = QFormLayout(self)
        self.setLayout(l)

        l.addRow(QLabel(_('Select what style information you want completely removed:')))
        self.h = h = QHBoxLayout()

        for name, text in (
                ('fonts', _('&Fonts')), ('margins', _('&Margins')), ('padding', _('&Padding')), ('floats', _('Flo&ats')), ('colors', _('&Colors')),
            ):
            c = QCheckBox(text)
            setattr(self, 'opt_' + name, c)
            h.addWidget(c)
            c.setToolTip(getattr(f, 'filter_css_' + name).toolTip())
        l.addRow(h)

        self.others = o = QLineEdit(self)
        l.addRow(_('&Other CSS properties:'), o)
        o.setToolTip(f.filter_css_others.toolTip())

        if self.current_name is not None:
            self.filter_current = c = QCheckBox(_('Only filter CSS in the current file (%s)') % self.current_name)
            l.addRow(c)

        l.addRow(self.bb)
Example #25
0
class ConfigWidget(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.l = QHBoxLayout()
        self.setLayout(self.l)

        self.label = QLabel('Hello world &message:')
        self.l.addWidget(self.label)

        self.msg = QLineEdit(self)
        self.msg.setText(prefs['hello_world_msg'])
        self.l.addWidget(self.msg)
        self.label.setBuddy(self.msg)

    def save_settings(self):
        prefs['hello_world_msg'] = self.msg.text()
Example #26
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.l = l = QVBoxLayout()
        self.setLayout(l)
        self.la = la = QLabel(_(
            'Choose a name for the new (blank) file. To place the file in a'
            ' specific folder in the book, include the folder name, for example: <i>text/chapter1.html'))
        la.setWordWrap(True)
        self.setWindowTitle(_('Choose file'))
        l.addWidget(la)
        self.name = n = QLineEdit(self)
        n.textChanged.connect(self.update_ok)
        l.addWidget(n)
        self.link_css = lc = QCheckBox(_('Automatically add style-sheet links into new HTML files'))
        lc.setChecked(tprefs['auto_link_stylesheets'])
        l.addWidget(lc)
        self.err_label = la = QLabel('')
        la.setWordWrap(True)
        l.addWidget(la)
        self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
        l.addWidget(bb)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)
        self.imp_button = b = bb.addButton(_('Import resource file (image/font/etc.)'), QDialogButtonBox.ButtonRole.ActionRole)
        b.setIcon(QIcon(I('view-image.png')))
        b.setToolTip(_('Import a file from your computer as a new'
                       ' file into the book.'))
        b.clicked.connect(self.import_file)

        self.ok_button = bb.button(QDialogButtonBox.StandardButton.Ok)

        self.file_data = b''
        self.using_template = False
        self.setMinimumWidth(350)
Example #27
0
 def __init__(self, pa, parent):
     QDialog.__init__(self, parent)
     self.test_func = parent.test_email_settings
     self.setWindowTitle(_("Test email settings"))
     self.setWindowIcon(QIcon(I('config.ui')))
     l = QVBoxLayout(self)
     opts = smtp_prefs().parse()
     self.from_ = la = QLabel(_("Send test mail from %s to:") % opts.from_)
     l.addWidget(la)
     self.to = le = QLineEdit(self)
     if pa:
         self.to.setText(pa)
     self.test_button = b = QPushButton(_('&Test'), self)
     b.clicked.connect(self.start_test)
     self.test_done.connect(self.on_test_done,
                            type=Qt.ConnectionType.QueuedConnection)
     self.h = h = QHBoxLayout()
     h.addWidget(le), h.addWidget(b)
     l.addLayout(h)
     if opts.relay_host:
         self.la = la = QLabel(
             _('Using: %(un)s:%(pw)s@%(host)s:%(port)s and %(enc)s encryption'
               ) % dict(un=opts.relay_username,
                        pw=from_hex_unicode(opts.relay_password),
                        host=opts.relay_host,
                        port=opts.relay_port,
                        enc=opts.encryption))
         l.addWidget(la)
     self.log = QPlainTextEdit(self)
     l.addWidget(self.log)
     self.bb = bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
     bb.rejected.connect(self.reject), bb.accepted.connect(self.accept)
     l.addWidget(bb)
Example #28
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self._layout = l = QGridLayout(self)
        self.setLayout(l)
        self.setWindowIcon(QIcon(I('mail.png')))
        self.setWindowTitle(_('Select recipients'))
        self.recipients = r = QListWidget(self)
        l.addWidget(r, 0, 0, 1, -1)
        self.la = la = QLabel(_('Add a new recipient:'))
        la.setStyleSheet('QLabel { font-weight: bold }')
        l.addWidget(la, l.rowCount(), 0, 1, -1)

        self.labels = tuple(
            map(QLabel,
                (_('&Address'), _('A&lias'), _('&Formats'), _('&Subject'))))
        tooltips = (
            _('The email address of the recipient'),
            _('The optional alias (simple name) of the recipient'),
            _('Formats to email. The first matching one will be sent (comma separated list)'
              ), _('The optional subject for email sent to this recipient'))

        for i, name in enumerate(('address', 'alias', 'formats', 'subject')):
            c = i % 2
            row = l.rowCount() - c
            self.labels[i].setText(str(self.labels[i].text()) + ':')
            l.addWidget(self.labels[i], row, (2 * c))
            le = QLineEdit(self)
            le.setToolTip(tooltips[i])
            setattr(self, name, le)
            self.labels[i].setBuddy(le)
            l.addWidget(le, row, (2 * c) + 1)
        self.formats.setText(prefs['output_format'].upper())
        self.add_button = b = QPushButton(QIcon(I('plus.png')),
                                          _('&Add recipient'), self)
        b.clicked.connect(self.add_recipient)
        l.addWidget(b, l.rowCount(), 0, 1, -1)

        self.bb = bb = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok
            | QDialogButtonBox.StandardButton.Cancel)
        l.addWidget(bb, l.rowCount(), 0, 1, -1)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)
        self.setMinimumWidth(500)
        self.setMinimumHeight(400)
        self.resize(self.sizeHint())
        self.init_list()
Example #29
0
 def event(self, ev):
     # See https://bugreports.qt.io/browse/QTBUG-46911
     if ev.type() == QEvent.Type.ShortcutOverride and (
             hasattr(ev, 'key')
             and ev.key() in (Qt.Key.Key_Left, Qt.Key.Key_Right) and
         (ev.modifiers() & ~Qt.KeyboardModifier.KeypadModifier)
             == Qt.KeyboardModifier.ControlModifier):
         ev.accept()
     return QLineEdit.event(self, ev)
Example #30
0
    def __init__(self, parent=None):
        Base.__init__(self, parent)

        self.l1 = QLabel(_('&Days of the month:'))
        self.days = QLineEdit(self)
        self.days.setToolTip(
            _('Comma separated list of days of the month.'
              ' For example: 1, 15'))
        self.l1.setBuddy(self.days)

        self.l2 = QLabel(_('Download &after:'))
        self.time = QTimeEdit(self)
        self.time.setDisplayFormat('hh:mm AP')
        self.l2.setBuddy(self.time)

        self.l.addWidget(self.l1, 0, 0, 1, 1)
        self.l.addWidget(self.days, 0, 1, 1, 1)
        self.l.addWidget(self.l2, 1, 0, 1, 1)
        self.l.addWidget(self.time, 1, 1, 1, 1)