Пример #1
0
    def polish(self, action, name):
        self.commit_all_editors_to_container()
        with BusyCursor():
            self.add_savepoint(name)
            try:
                report = tweak_polish(current_container(), {action: True})
            except:
                self.rewind_savepoint()
                raise
            self.apply_container_update_to_gui()
            from calibre.ebooks.markdown import markdown

            report = markdown("# %s\n\n" % self.current_metadata.title + "\n\n".join(report), output_format="html4")
        d = QDialog(self.gui)
        d.l = QVBoxLayout()
        d.setLayout(d.l)
        d.e = QTextBrowser(d)
        d.l.addWidget(d.e)
        d.e.setHtml(report)
        d.bb = QDialogButtonBox(QDialogButtonBox.Close)
        d.l.addWidget(d.bb)
        d.bb.rejected.connect(d.reject)
        d.bb.accepted.connect(d.accept)
        d.resize(600, 400)
        d.exec_()
Пример #2
0
 def polish(self, action, name):
     self.commit_all_editors_to_container()
     with BusyCursor():
         self.add_savepoint(name)
         try:
             report = tweak_polish(current_container(), {action: True})
         except:
             self.rewind_savepoint()
             raise
         self.apply_container_update_to_gui()
         from calibre.ebooks.markdown import markdown
         report = markdown('# %s\n\n' % self.current_metadata.title +
                           '\n\n'.join(report),
                           output_format='html4')
     d = QDialog(self.gui)
     d.l = QVBoxLayout()
     d.setLayout(d.l)
     d.e = QTextBrowser(d)
     d.l.addWidget(d.e)
     d.e.setHtml(report)
     d.bb = QDialogButtonBox(QDialogButtonBox.Close)
     d.l.addWidget(d.bb)
     d.bb.rejected.connect(d.reject)
     d.bb.accepted.connect(d.accept)
     d.resize(600, 400)
     d.exec_()
Пример #3
0
    def settings_dialog(self):
        try:
            device_id = self.get_client().get_device_id()
        except BaseException as e:
            self.window.show_message(str(e))
            return
        get_label = lambda: self.get_client().features.label
        update_label = lambda: current_label_label.setText("Label: %s" %
                                                           get_label())
        d = QDialog()
        layout = QGridLayout(d)
        layout.addWidget(QLabel("KeepKey Options"), 0, 0)
        layout.addWidget(QLabel("ID:"), 1, 0)
        layout.addWidget(QLabel(" %s" % device_id), 1, 1)

        def modify_label():
            response = QInputDialog().getText(
                None, "Set New KeepKey Label",
                "New KeepKey Label:  (upon submission confirm on KeepKey)")
            if not response[1]:
                return
            new_label = str(response[0])
            self.handler.show_message("Please confirm label change on KeepKey")
            status = self.get_client().apply_settings(label=new_label)
            self.handler.stop()
            update_label()

        current_label_label = QLabel()
        update_label()
        change_label_button = QPushButton("Modify")
        change_label_button.clicked.connect(modify_label)
        layout.addWidget(current_label_label, 3, 0)
        layout.addWidget(change_label_button, 3, 1)
        d.exec_()
Пример #4
0
    def settings_dialog(self):
        try:
            device_id = self.get_client().get_device_id()
        except BaseException as e:
            self.window.show_message(str(e))
            return
        get_label = lambda: self.get_client().features.label
        update_label = lambda: current_label_label.setText("Label: %s" % get_label())
        d = QDialog()
        layout = QGridLayout(d)
        layout.addWidget(QLabel("Trezor Options"), 0, 0)
        layout.addWidget(QLabel("ID:"), 1, 0)
        layout.addWidget(QLabel(" %s" % device_id), 1, 1)

        def modify_label():
            response = QInputDialog().getText(
                None, "Set New Trezor Label", "New Trezor Label:  (upon submission confirm on Trezor)"
            )
            if not response[1]:
                return
            new_label = str(response[0])
            self.handler.show_message("Please confirm label change on Trezor")
            status = self.get_client().apply_settings(label=new_label)
            self.handler.stop()
            update_label()

        current_label_label = QLabel()
        update_label()
        change_label_button = QPushButton("Modify")
        change_label_button.clicked.connect(modify_label)
        layout.addWidget(current_label_label, 3, 0)
        layout.addWidget(change_label_button, 3, 1)
        d.exec_()
Пример #5
0
def test():
    app = QApplication([])
    app
    d = QDialog()
    d.setLayout(QVBoxLayout())
    d.layout().addWidget(FontFamilyChooser(d))
    d.layout().addWidget(QFontComboBox(d))
    d.exec_()
Пример #6
0
def test():
    app = QApplication([])
    app
    d = QDialog()
    d.setLayout(QVBoxLayout())
    d.layout().addWidget(FontFamilyChooser(d))
    d.layout().addWidget(QFontComboBox(d))
    d.exec_()
Пример #7
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 PyQt4.Qt import (QDialog, QDialogButtonBox, QVBoxLayout, QLabel,
                              Qt, QLineEdit, QCheckBox)

        config_dialog = QDialog(parent)
        button_box = QDialogButtonBox(QDialogButtonBox.Ok
                                      | QDialogButtonBox.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.LinksAccessibleByMouse
                                          | Qt.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.Accepted:
            sc = unicode(sc.text()).strip()
            if bf.isChecked():
                sc += '|bf'
            customize_plugin(self, sc)

        return config_dialog.result()
Пример #8
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 PyQt4.Qt import (QDialog, QDialogButtonBox, QVBoxLayout,
                QLabel, Qt, QLineEdit, QCheckBox)

        config_dialog = QDialog(parent)
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.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.LinksAccessibleByMouse
                | Qt.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.Accepted:
            sc = unicode(sc.text()).strip()
            if bf.isChecked():
                sc += '|bf'
            customize_plugin(self, sc)

        return config_dialog.result()
Пример #9
0
 def setup(self, comment=None):
     '''Show Comment dialog with currect comment text. 
     <comment> - the comment node object.
     '''
     self.comment = comment
     
     if self.comment:
         self.comment_textedit.setPlainText(self.comment.get_text())
             # Load comment text.
         qt4todo('self.comment_textedit.moveCursor(QTextEdit.MoveEnd, False)')
             # Sets cursor position to the end of the textedit document.
     
     QDialog.exec_(self)
Пример #10
0
    def setup(self, comment=None):
        '''Show Comment dialog with currect comment text. 
        <comment> - the comment node object.
        '''
        self.comment = comment

        if self.comment:
            self.comment_textedit.setPlainText(self.comment.get_text())
            # Load comment text.
            qt4todo(
                'self.comment_textedit.moveCursor(QTextEdit.MoveEnd, False)')
            # Sets cursor position to the end of the textedit document.

        QDialog.exec_(self)
Пример #11
0
def get_bulk_rename_settings(parent, number, msg=None, sanitize=sanitize_file_name_unicode, leading_zeros=True):  # {{{
    d = QDialog(parent)
    d.l = l = QFormLayout(d)
    d.setLayout(l)
    d.prefix = p = QLineEdit(d)
    p.setText(_('Chapter-'))
    p.selectAll()
    d.la = la = QLabel(msg or _(
        'All selected files will be renamed to the form prefix-number'))
    l.addRow(la)
    l.addRow(_('&Prefix:'), p)
    d.num = num = QSpinBox(d)
    num.setMinimum(0), num.setValue(1), num.setMaximum(1000)
    l.addRow(_('Starting &number:'), num)
    d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
    bb.accepted.connect(d.accept), bb.rejected.connect(d.reject)
    l.addRow(bb)

    if d.exec_() == d.Accepted:
        prefix = sanitize(unicode(d.prefix.text()))
        num = d.num.value()
        fmt = '%d'
        if leading_zeros:
            largest = num + number - 1
            fmt = '%0{0}d'.format(len(str(largest)))
        return prefix + fmt, num
    return None, None
Пример #12
0
    def settings_dialog(self):
        get_label = lambda: self.wallet.get_client().features.label
        update_label = lambda: current_label_label.setText("Label: %s" % get_label())

        d = QDialog()
        layout = QGridLayout(d)
        layout.addWidget(QLabel("Trezor Options"),0,0)
        layout.addWidget(QLabel("ID:"),1,0)
        layout.addWidget(QLabel(" %s" % self.wallet.get_client().get_device_id()),1,1)

        def modify_label():
            response = QInputDialog().getText(None, "Set New Trezor Label", "New Trezor Label:  (upon submission confirm on Trezor)")
            if not response[1]:
                return
            new_label = str(response[0])
            twd.start("Please confirm label change on Trezor")
            status = self.wallet.get_client().apply_settings(label=new_label)
            twd.stop()
            update_label()

        current_label_label = QLabel()
        update_label()
        change_label_button = QPushButton("Modify")
        change_label_button.clicked.connect(modify_label)
        layout.addWidget(current_label_label,3,0)
        layout.addWidget(change_label_button,3,1)

        if d.exec_():
            return True
        else:
            return False
Пример #13
0
    def setup(self, comment = None):
        """
        Show Comment dialog with current Comment text, for editing
        properties of an existing Comment node or creating a new one.

        @param comment: the comment node to edit, or None to create a new one.
        """
        self.comment = comment

        if self.comment:
            self.comment_textedit.setPlainText(self.comment.get_text())
                # Load comment text.
            qt4todo("self.comment_textedit.moveCursor(QTextEdit.MoveEnd, False)")
                # Sets cursor position to the end of the textedit document.

        QDialog.exec_(self)
Пример #14
0
 def setup(self, comment = None):
     """
     Show Comment dialog with current Comment text, for editing
     properties of an existing Comment node or creating a new one.
     
     @param comment: the comment node to edit, or None to create a new one.
     """
     self.comment = comment
     
     if self.comment:
         self.comment_textedit.setPlainText(self.comment.get_text())
             # Load comment text.
         qt4todo("self.comment_textedit.moveCursor(QTextEdit.MoveEnd, False)")
             # Sets cursor position to the end of the textedit document.
     
     QDialog.exec_(self)
Пример #15
0
    def link_stylesheets(self, names):
        s = self.categories['styles']
        sheets = [unicode(s.child(i).data(0, NAME_ROLE).toString()) for i in xrange(s.childCount())]
        if not sheets:
            return error_dialog(self, _('No stylesheets'), _(
                'This book currently has no stylesheets. You must first create a stylesheet'
                ' before linking it.'), show=True)
        d = QDialog(self)
        d.l = l = QVBoxLayout(d)
        d.setLayout(l)
        d.setWindowTitle(_('Choose stylesheets'))
        d.la = la = QLabel(_('Choose the stylesheets to link. Drag and drop to re-arrange'))

        la.setWordWrap(True)
        l.addWidget(la)
        d.s = s = QListWidget(d)
        l.addWidget(s)
        s.setDragEnabled(True)
        s.setDropIndicatorShown(True)
        s.setDragDropMode(self.InternalMove)
        s.setAutoScroll(True)
        s.setDefaultDropAction(Qt.MoveAction)
        for name in sheets:
            i = QListWidgetItem(name, s)
            flags = Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsDragEnabled | Qt.ItemIsSelectable
            i.setFlags(flags)
            i.setCheckState(Qt.Checked)
        d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        bb.accepted.connect(d.accept), bb.rejected.connect(d.reject)
        l.addWidget(bb)
        if d.exec_() == d.Accepted:
            sheets = [unicode(s.item(i).text()) for i in xrange(s.count()) if s.item(i).checkState() == Qt.Checked]
            if sheets:
                self.link_stylesheets_requested.emit(names, sheets)
Пример #16
0
 def request_bulk_rename(self):
     names = {unicode(item.data(0, NAME_ROLE).toString()) for item in self.selectedItems()}
     bad = names & current_container().names_that_must_not_be_changed
     if bad:
         return error_dialog(self, _('Cannot rename'),
                      _('The file(s) %s cannot be renamed.') % ('<b>%s</b>' % ', '.join(bad)), show=True)
     names = sorted(names, key=self.index_of_name)
     d = QDialog(self)
     d.l = l = QFormLayout(d)
     d.setLayout(l)
     d.prefix = p = QLineEdit(d)
     p.setText(_('Chapter-'))
     p.selectAll()
     d.la = la = QLabel(_(
         'All selected files will be renamed to the form prefix-number'))
     l.addRow(la)
     l.addRow(_('&Prefix:'), p)
     d.num = num = QSpinBox(d)
     num.setMinimum(0), num.setValue(1), num.setMaximum(1000)
     l.addRow(_('Starting &number:'), num)
     d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
     bb.accepted.connect(d.accept), bb.rejected.connect(d.reject)
     l.addRow(bb)
     if d.exec_() == d.Accepted:
         prefix = sanitize_file_name_unicode(unicode(d.prefix.text()))
         num = d.num.value()
         largest = num + len(names) - 1
         fmt = '%0{0}d'.format(len(str(largest)))
         def change_name(name, num):
             parts = name.split('/')
             base, ext = parts[-1].rpartition('.')[0::2]
             parts[-1] = prefix + (fmt % num) + '.' + ext
             return '/'.join(parts)
         name_map = {n:change_name(n, num + i) for i, n in enumerate(names)}
         self.bulk_rename_requested.emit(name_map)
Пример #17
0
    def settings_dialog(self):
        get_label = lambda: self.wallet.get_client().features.label
        update_label = lambda: current_label_label.setText("Label: %s" %
                                                           get_label())

        d = QDialog()
        layout = QGridLayout(d)
        layout.addWidget(QLabel("Trezor Options"), 0, 0)
        layout.addWidget(QLabel("ID:"), 1, 0)
        layout.addWidget(
            QLabel(" %s" % self.wallet.get_client().get_device_id()), 1, 1)

        def modify_label():
            response = QInputDialog().getText(
                None, "Set New Trezor Label",
                "New Trezor Label:  (upon submission confirm on Trezor)")
            if not response[1]:
                return
            new_label = str(response[0])
            twd.start("Please confirm label change on Trezor")
            status = self.wallet.get_client().apply_settings(label=new_label)
            twd.stop()
            update_label()

        current_label_label = QLabel()
        update_label()
        change_label_button = QPushButton("Modify")
        change_label_button.clicked.connect(modify_label)
        layout.addWidget(current_label_label, 3, 0)
        layout.addWidget(change_label_button, 3, 1)

        if d.exec_():
            return True
        else:
            return False
Пример #18
0
def get_bulk_rename_settings(parent,
                             number,
                             msg=None,
                             sanitize=sanitize_file_name_unicode,
                             leading_zeros=True):  # {{{
    d = QDialog(parent)
    d.l = l = QFormLayout(d)
    d.setLayout(l)
    d.prefix = p = QLineEdit(d)
    p.setText(_('Chapter-'))
    p.selectAll()
    d.la = la = QLabel(
        msg
        or _('All selected files will be renamed to the form prefix-number'))
    l.addRow(la)
    l.addRow(_('&Prefix:'), p)
    d.num = num = QSpinBox(d)
    num.setMinimum(0), num.setValue(1), num.setMaximum(1000)
    l.addRow(_('Starting &number:'), num)
    d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
    bb.accepted.connect(d.accept), bb.rejected.connect(d.reject)
    l.addRow(bb)

    if d.exec_() == d.Accepted:
        prefix = sanitize(unicode(d.prefix.text()))
        num = d.num.value()
        fmt = '%d'
        if leading_zeros:
            largest = num + number - 1
            fmt = '%0{0}d'.format(len(str(largest)))
        return prefix + fmt, num
    return None, None
Пример #19
0
    def import_words(self):
        d = QDialog(self)
        d.l = l = QFormLayout(d)
        d.setWindowTitle(_('Import list of words'))
        d.w = w = QPlainTextEdit(d)
        l.addRow(QLabel(_('Enter a list of words, one per line')))
        l.addRow(w)
        d.b = b = QPushButton(_('Paste from clipboard'))
        l.addRow(b)
        b.clicked.connect(w.paste)
        d.la = la = QLabel(_('Words in the user dictionary must have an associated language. Choose the language below:'))
        la.setWordWrap(True)
        l.addRow(la)
        d.le = le = LanguagesEdit(d)
        lc = canonicalize_lang(get_lang())
        if lc:
            le.lang_codes = [lc]
        l.addRow(_('&Language:'), le)
        d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
        l.addRow(bb)
        bb.accepted.connect(d.accept), bb.rejected.connect(d.reject)

        if d.exec_() != d.Accepted:
            return
        lc = le.lang_codes
        if not lc:
            return error_dialog(self, _('Must specify language'), _(
                'You must specify a language to import words'), show=True)
        words = set(filter(None, [x.strip() for x in unicode(w.toPlainText()).splitlines()]))
        lang = lc[0]
        words = {(w, lang) for w in words} - self.current_dictionary.words
        if dictionaries.add_to_user_dictionary(self.current_dictionary.name, words, None):
            dictionaries.clear_caches()
            self.show_current_dictionary()
            self.dictionaries_changed = True
Пример #20
0
 def add_word(self):
     d = QDialog(self)
     d.l = l = QFormLayout(d)
     d.setWindowTitle(_('Add a word'))
     d.w = w = QLineEdit(d)
     w.setPlaceholderText(_('Word to add'))
     l.addRow(_('&Word:'), w)
     d.loc = loc = LanguagesEdit(parent=d)
     l.addRow(_('&Language:'), d.loc)
     loc.lang_codes = [canonicalize_lang(get_lang())]
     d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
     bb.accepted.connect(d.accept), bb.rejected.connect(d.reject)
     l.addRow(bb)
     if d.exec_() != d.Accepted:
         return
     word = unicode(w.text())
     lang = (loc.lang_codes or [canonicalize_lang(get_lang())])[0]
     if not word:
         return
     if (word, lang) not in self.current_dictionary.words:
         dictionaries.add_to_user_dictionary(self.current_dictionary.name, word, DictionaryLocale(lang, None))
         dictionaries.clear_caches()
         self.show_current_dictionary()
         self.dictionaries_changed = True
     idx = self.find_word(word, lang)
     if idx > -1:
         self.words.scrollToItem(self.words.item(idx))
Пример #21
0
    def add_builtin_recipe(self):
        from calibre.web.feeds.recipes.collection import \
            get_builtin_recipe_collection, get_builtin_recipe_by_id
        from PyQt4.Qt import QDialog, QVBoxLayout, QListWidgetItem, \
                QListWidget, QDialogButtonBox, QSize

        d = QDialog(self)
        d.l = QVBoxLayout()
        d.setLayout(d.l)
        d.list = QListWidget(d)
        d.list.doubleClicked.connect(lambda x: d.accept())
        d.l.addWidget(d.list)
        d.bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel,
                Qt.Horizontal, d)
        d.bb.accepted.connect(d.accept)
        d.bb.rejected.connect(d.reject)
        d.l.addWidget(d.bb)
        d.setWindowTitle(_('Choose builtin recipe'))
        items = []
        for r in get_builtin_recipe_collection():
            id_ = r.get('id', '')
            title = r.get('title', '')
            lang = r.get('language', '')
            if id_ and title:
                items.append((title + ' [%s]'%lang, id_))

        items.sort(key=lambda x:sort_key(x[0]))
        for title, id_ in items:
            item = QListWidgetItem(title)
            item.setData(Qt.UserRole, id_)
            d.list.addItem(item)

        d.resize(QSize(450, 400))
        ret = d.exec_()
        d.list.doubleClicked.disconnect()
        if ret != d.Accepted:
            return

        items = list(d.list.selectedItems())
        if not items:
            return
        item = items[-1]
        id_ = unicode(item.data(Qt.UserRole).toString())
        title = unicode(item.data(Qt.DisplayRole).toString()).rpartition(' [')[0]
        profile = get_builtin_recipe_by_id(id_, download_recipe=True)
        if profile is None:
            raise Exception('Something weird happened')

        if self._model.has_title(title):
            if question_dialog(self, _('Replace recipe?'),
                _('A custom recipe named %s already exists. Do you want to '
                    'replace it?')%title):
                self._model.replace_by_title(title, profile)
            else:
                return
        else:
            self.model.add(title, profile)

        self.clear()
Пример #22
0
 def exec_(self):
     if (
         unicode(self.search_edit.text()).strip()
         or unicode(self.search_title.text()).strip()
         or unicode(self.search_author.text()).strip()
     ):
         self.do_search()
     return QDialog.exec_(self)
Пример #23
0
    def confirm_quit(self):
        if self.doing_terminal_save:
            return False
        if self.save_manager.has_tasks:
            if not question_dialog(
                    self.gui,
                    _('Are you sure?'),
                    _('The current book is being saved in the background, quitting will abort'
                      ' the save process, are you sure?'),
                    default_yes=False):
                return False

        if self.gui.action_save.isEnabled():
            d = QDialog(self.gui)
            d.l = QGridLayout(d)
            d.setLayout(d.l)
            d.setWindowTitle(_('Unsaved changes'))
            d.i = QLabel('')
            d.i.setPixmap(
                QPixmap(I('save.png')).scaledToHeight(64,
                                                      Qt.SmoothTransformation))
            d.i.setMaximumSize(QSize(d.i.pixmap().width(), 64))
            d.i.setScaledContents(True)
            d.l.addWidget(d.i, 0, 0)
            d.m = QLabel(
                _('There are unsaved changes, if you quit without saving, you will lose them.'
                  ))
            d.m.setWordWrap(True)
            d.l.addWidget(d.m, 0, 1)
            d.bb = QDialogButtonBox(QDialogButtonBox.Cancel)
            d.bb.rejected.connect(d.reject)
            d.bb.accepted.connect(d.accept)
            d.l.addWidget(d.bb, 1, 0, 1, 2)
            d.do_save = None

            def endit(x):
                d.do_save = x
                d.accept()

            b = d.bb.addButton(_('&Save and Quit'),
                               QDialogButtonBox.ActionRole)
            b.setIcon(QIcon(I('save.png')))
            b.clicked.connect(lambda *args: endit(True))
            b = d.bb.addButton(_('&Quit without saving'),
                               QDialogButtonBox.ActionRole)
            b.clicked.connect(lambda *args: endit(False))
            d.resize(d.sizeHint())
            if d.exec_() != d.Accepted or d.do_save is None:
                return False
            if d.do_save:
                self.gui.action_save.trigger()
                self.gui.blocking_job.set_msg(_('Saving, please wait...'))
                self.gui.blocking_job.start()
                self.doing_terminal_save = True
                QTimer.singleShot(50, self.check_terminal_save)
                return False

        return True
Пример #24
0
 def show_debug_info(self):
     info = self.device.device_debug_info()
     d = QDialog(self)
     d.l = l = QVBoxLayout()
     d.setLayout(l)
     d.v = v = QPlainTextEdit()
     d.setWindowTitle(self.device.get_gui_name())
     v.setPlainText(info)
     v.setMinimumWidth(400)
     v.setMinimumHeight(350)
     l.addWidget(v)
     bb = d.bb = QDialogButtonBox(QDialogButtonBox.Close)
     bb.accepted.connect(d.accept)
     bb.rejected.connect(d.reject)
     l.addWidget(bb)
     bb.addButton(_("Copy to clipboard"), bb.ActionRole)
     bb.clicked.connect(lambda: QApplication.clipboard().setText(v.toPlainText()))
     d.exec_()
Пример #25
0
    def do_config(self):
        # Save values that need to be synced between the dialog and the
        # search widget.
        self.config['open_external'] = self.open_external.isChecked()

        # Create the config dialog. It's going to put two config widgets
        # into a QTabWidget for displaying all of the settings.
        d = QDialog(self)
        button_box = QDialogButtonBox(QDialogButtonBox.Close)
        v = QVBoxLayout(d)
        button_box.accepted.connect(d.accept)
        button_box.rejected.connect(d.reject)
        d.setWindowTitle(_('Customize get books search'))

        tab_widget = QTabWidget(d)
        v.addWidget(tab_widget)
        v.addWidget(button_box)

        chooser_config_widget = StoreChooserWidget()
        search_config_widget = StoreConfigWidget(self.config)

        tab_widget.addTab(chooser_config_widget, _('Choose stores'))
        tab_widget.addTab(search_config_widget, _('Configure search'))

        # Restore dialog state.
        geometry = self.config.get('config_dialog_geometry', None)
        if geometry:
            d.restoreGeometry(geometry)
        else:
            d.resize(800, 600)
        tab_index = self.config.get('config_dialog_tab_index', 0)
        tab_index = min(tab_index, tab_widget.count() - 1)
        tab_widget.setCurrentIndex(tab_index)

        d.exec_()

        # Save dialog state.
        self.config['config_dialog_geometry'] = bytearray(d.saveGeometry())
        self.config['config_dialog_tab_index'] = tab_widget.currentIndex()

        search_config_widget.save_settings()
        self.config_changed()
        self.gui.load_store_plugins()
        self.setup_store_checks()
Пример #26
0
    def do_config(self):
        # Save values that need to be synced between the dialog and the
        # search widget.
        self.config['open_external'] = self.open_external.isChecked()

        # Create the config dialog. It's going to put two config widgets
        # into a QTabWidget for displaying all of the settings.
        d = QDialog(self)
        button_box = QDialogButtonBox(QDialogButtonBox.Close)
        v = QVBoxLayout(d)
        button_box.accepted.connect(d.accept)
        button_box.rejected.connect(d.reject)
        d.setWindowTitle(_('Customize get books search'))

        tab_widget = QTabWidget(d)
        v.addWidget(tab_widget)
        v.addWidget(button_box)

        chooser_config_widget = StoreChooserWidget()
        search_config_widget = StoreConfigWidget(self.config)

        tab_widget.addTab(chooser_config_widget, _('Choose stores'))
        tab_widget.addTab(search_config_widget, _('Configure search'))

        # Restore dialog state.
        geometry = self.config.get('config_dialog_geometry', None)
        if geometry:
            d.restoreGeometry(geometry)
        else:
            d.resize(800, 600)
        tab_index = self.config.get('config_dialog_tab_index', 0)
        tab_index = min(tab_index, tab_widget.count() - 1)
        tab_widget.setCurrentIndex(tab_index)

        d.exec_()

        # Save dialog state.
        self.config['config_dialog_geometry'] = bytearray(d.saveGeometry())
        self.config['config_dialog_tab_index'] = tab_widget.currentIndex()

        search_config_widget.save_settings()
        self.config_changed()
        self.gui.load_store_plugins()
        self.setup_store_checks()
Пример #27
0
def show_report(changed, title, report, parent, show_current_diff):
    report = format_report(title, report)
    d = QDialog(parent)
    d.l = QVBoxLayout()
    d.setLayout(d.l)
    d.e = QTextBrowser(d)
    d.l.addWidget(d.e)
    d.e.setHtml(report)
    d.bb = QDialogButtonBox(QDialogButtonBox.Close)
    if changed:
        b = d.b = d.bb.addButton(_('See what &changed'), d.bb.AcceptRole)
        b.setIcon(QIcon(I('diff.png'))), b.setAutoDefault(False)
        b.clicked.connect(partial(show_current_diff, allow_revert=True))
    d.bb.button(d.bb.Close).setDefault(True)
    d.l.addWidget(d.bb)
    d.bb.rejected.connect(d.reject)
    d.bb.accepted.connect(d.accept)
    d.resize(600, 400)
    d.exec_()
Пример #28
0
 def show_debug_info(self):
     info = self.device.device_debug_info()
     d = QDialog(self)
     d.l = l = QVBoxLayout()
     d.setLayout(l)
     d.v = v = QPlainTextEdit()
     d.setWindowTitle(self.device.get_gui_name())
     v.setPlainText(info)
     v.setMinimumWidth(400)
     v.setMinimumHeight(350)
     l.addWidget(v)
     bb = d.bb = QDialogButtonBox(QDialogButtonBox.Close)
     bb.accepted.connect(d.accept)
     bb.rejected.connect(d.reject)
     l.addWidget(bb)
     bb.addButton(_('Copy to clipboard'), bb.ActionRole)
     bb.clicked.connect(
         lambda: QApplication.clipboard().setText(v.toPlainText()))
     d.exec_()
Пример #29
0
def show_report(changed, title, report, parent, show_current_diff):
    report = format_report(title, report)
    d = QDialog(parent)
    d.l = QVBoxLayout()
    d.setLayout(d.l)
    d.e = QTextBrowser(d)
    d.l.addWidget(d.e)
    d.e.setHtml(report)
    d.bb = QDialogButtonBox(QDialogButtonBox.Close)
    if changed:
        b = d.b = d.bb.addButton(_('See what &changed'), d.bb.AcceptRole)
        b.setIcon(QIcon(I('diff.png'))), b.setAutoDefault(False)
        b.clicked.connect(partial(show_current_diff, allow_revert=True))
    d.bb.button(d.bb.Close).setDefault(True)
    d.l.addWidget(d.bb)
    d.bb.rejected.connect(d.reject)
    d.bb.accepted.connect(d.accept)
    d.resize(600, 400)
    d.exec_()
Пример #30
0
    def confirm_quit(self):
        if self.doing_terminal_save:
            return False
        if self.save_manager.has_tasks:
            if not question_dialog(
                self.gui,
                _("Are you sure?"),
                _(
                    "The current book is being saved in the background, quitting will abort"
                    " the save process, are you sure?"
                ),
                default_yes=False,
            ):
                return False

        if self.gui.action_save.isEnabled():
            d = QDialog(self.gui)
            d.l = QGridLayout(d)
            d.setLayout(d.l)
            d.setWindowTitle(_("Unsaved changes"))
            d.i = QLabel("")
            d.i.setPixmap(QPixmap(I("save.png")).scaledToHeight(64, Qt.SmoothTransformation))
            d.i.setMaximumSize(QSize(d.i.pixmap().width(), 64))
            d.i.setScaledContents(True)
            d.l.addWidget(d.i, 0, 0)
            d.m = QLabel(_("There are unsaved changes, if you quit without saving, you will lose them."))
            d.m.setWordWrap(True)
            d.l.addWidget(d.m, 0, 1)
            d.bb = QDialogButtonBox(QDialogButtonBox.Cancel)
            d.bb.rejected.connect(d.reject)
            d.bb.accepted.connect(d.accept)
            d.l.addWidget(d.bb, 1, 0, 1, 2)
            d.do_save = None

            def endit(x):
                d.do_save = x
                d.accept()

            b = d.bb.addButton(_("&Save and Quit"), QDialogButtonBox.ActionRole)
            b.setIcon(QIcon(I("save.png")))
            b.clicked.connect(lambda *args: endit(True))
            b = d.bb.addButton(_("&Quit without saving"), QDialogButtonBox.ActionRole)
            b.clicked.connect(lambda *args: endit(False))
            d.resize(d.sizeHint())
            if d.exec_() != d.Accepted or d.do_save is None:
                return False
            if d.do_save:
                self.gui.action_save.trigger()
                self.gui.blocking_job.set_msg(_("Saving, please wait..."))
                self.gui.blocking_job.start()
                self.doing_terminal_save = True
                QTimer.singleShot(50, self.check_terminal_save)
                return False

        return True
Пример #31
0
    def ask_link(self):
        d = QDialog(self)
        d.setWindowTitle(_('Create link'))
        l = QFormLayout()
        d.setLayout(l)
        d.url = QLineEdit(d)
        d.name = QLineEdit(d)
        d.treat_as_image = QCheckBox(d)
        d.setMinimumWidth(600)
        d.bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        d.br = b = QPushButton(_('&Browse'))
        b.setIcon(QIcon(I('document_open.png')))

        def cf():
            files = choose_files(d,
                                 'select link file',
                                 _('Choose file'),
                                 select_only_single_file=True)
            if files:
                path = files[0]
                d.url.setText(path)
                if path and os.path.exists(path):
                    with lopen(path, 'rb') as f:
                        q = what(f)
                    is_image = q in {'jpeg', 'png', 'gif'}
                    d.treat_as_image.setChecked(is_image)

        b.clicked.connect(cf)
        d.la = la = QLabel(
            _('Enter a URL. If you check the "Treat the URL as an image" box '
              'then the URL will be added as an image reference instead of as '
              'a link. You can also choose to create a link to a file on '
              'your computer. '
              'Note that if you create a link to a file on your computer, it '
              'will stop working if the file is moved.'))
        la.setWordWrap(True)
        la.setStyleSheet('QLabel { margin-bottom: 1.5ex }')
        l.setWidget(0, l.SpanningRole, la)
        l.addRow(_('Enter &URL:'), d.url)
        l.addRow(_('Treat the URL as an &image'), d.treat_as_image)
        l.addRow(_('Enter &name (optional):'), d.name)
        l.addRow(_('Choose a file on your computer:'), d.br)
        l.addRow(d.bb)
        d.bb.accepted.connect(d.accept)
        d.bb.rejected.connect(d.reject)
        d.resize(d.sizeHint())
        link, name, is_image = None, None, False
        if d.exec_() == d.Accepted:
            link, name = unicode(d.url.text()).strip(), unicode(
                d.name.text()).strip()
            is_image = d.treat_as_image.isChecked()
        return link, name, is_image
Пример #32
0
    def pin_dialog(self, msg):
        d = QDialog(None)
        d.setModal(1)
        d.setWindowTitle(_("Enter PIN"))
        matrix = PinMatrixWidget()

        vbox = QVBoxLayout()
        vbox.addWidget(QLabel(msg))
        vbox.addWidget(matrix)
        vbox.addLayout(ok_cancel_buttons(d))
        d.setLayout(vbox)

        if not d.exec_(): return
        return str(matrix.get_value())
Пример #33
0
    def pin_dialog(self, msg):
        d = QDialog(None)
        d.setModal(1)
        d.setWindowTitle(_("Enter PIN"))
        matrix = PinMatrixWidget()

        vbox = QVBoxLayout()
        vbox.addWidget(QLabel(msg))
        vbox.addWidget(matrix)
        vbox.addLayout(ok_cancel_buttons(d))
        d.setLayout(vbox)

        if not d.exec_(): return
        return str(matrix.get_value())
Пример #34
0
    def link_stylesheets(self, names):
        s = self.categories['styles']
        sheets = [
            unicode(s.child(i).data(0, NAME_ROLE).toString())
            for i in xrange(s.childCount())
        ]
        if not sheets:
            return error_dialog(
                self,
                _('No stylesheets'),
                _('This book currently has no stylesheets. You must first create a stylesheet'
                  ' before linking it.'),
                show=True)
        d = QDialog(self)
        d.l = l = QVBoxLayout(d)
        d.setLayout(l)
        d.setWindowTitle(_('Choose stylesheets'))
        d.la = la = QLabel(
            _('Choose the stylesheets to link. Drag and drop to re-arrange'))

        la.setWordWrap(True)
        l.addWidget(la)
        d.s = s = QListWidget(d)
        l.addWidget(s)
        s.setDragEnabled(True)
        s.setDropIndicatorShown(True)
        s.setDragDropMode(self.InternalMove)
        s.setAutoScroll(True)
        s.setDefaultDropAction(Qt.MoveAction)
        for name in sheets:
            i = QListWidgetItem(name, s)
            flags = Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsDragEnabled | Qt.ItemIsSelectable
            i.setFlags(flags)
            i.setCheckState(Qt.Checked)
        d.r = r = QCheckBox(_('Remove existing links to stylesheets'))
        r.setChecked(tprefs['remove_existing_links_when_linking_sheets'])
        l.addWidget(r)
        d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)
        bb.accepted.connect(d.accept), bb.rejected.connect(d.reject)
        l.addWidget(bb)
        if d.exec_() == d.Accepted:
            tprefs['remove_existing_links_when_linking_sheets'] = r.isChecked()
            sheets = [
                unicode(s.item(il).text()) for il in xrange(s.count())
                if s.item(il).checkState() == Qt.Checked
            ]
            if sheets:
                self.link_stylesheets_requested.emit(names, sheets,
                                                     r.isChecked())
Пример #35
0
 def polish(self, action, name):
     if not self.check_dirtied():
         return
     self.add_savepoint(name)
     try:
         report = tweak_polish(current_container(), {action:True})
     except:
         self.rewind_savepoint()
         raise
     self.apply_container_update_to_gui()
     from calibre.ebooks.markdown import markdown
     report = markdown('# %s\n\n'%self.current_metadata.title + '\n\n'.join(report), output_format='html4')
     d = QDialog(self.gui)
     d.l = QVBoxLayout()
     d.setLayout(d.l)
     d.e = QTextBrowser(d)
     d.l.addWidget(d.e)
     d.e.setHtml(report)
     d.bb = QDialogButtonBox(QDialogButtonBox.Close)
     d.l.addWidget(d.bb)
     d.bb.rejected.connect(d.reject)
     d.bb.accepted.connect(d.accept)
     d.resize(600, 400)
     d.exec_()
Пример #36
0
 def pin_dialog(self):
     d = QDialog(None)
     d.setModal(1)
     d.setWindowTitle(_("Enter PIN"))
     d.setWindowFlags(d.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)
     matrix = PinMatrixWidget()
     vbox = QVBoxLayout()
     vbox.addWidget(QLabel(self.message))
     vbox.addWidget(matrix)
     vbox.addLayout(Buttons(CancelButton(d), OkButton(d)))
     d.setLayout(vbox)
     if not d.exec_():
         self.response = None
     self.response = str(matrix.get_value())
     self.done.set()
Пример #37
0
 def pin_dialog(self):
     d = QDialog(None)
     d.setModal(1)
     d.setWindowTitle(_("Enter PIN"))
     d.setWindowFlags(d.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)
     matrix = PinMatrixWidget()
     vbox = QVBoxLayout()
     vbox.addWidget(QLabel(self.message))
     vbox.addWidget(matrix)
     vbox.addLayout(Buttons(CancelButton(d), OkButton(d)))
     d.setLayout(vbox)
     if not d.exec_():
         self.response = None
     self.response = str(matrix.get_value())
     self.done.set()
Пример #38
0
    def ask_link(self):
        d = QDialog(self)
        d.setWindowTitle(_('Create link'))
        l = QFormLayout()
        d.setLayout(l)
        d.url = QLineEdit(d)
        d.name = QLineEdit(d)
        d.treat_as_image = QCheckBox(d)
        d.setMinimumWidth(600)
        d.bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
        d.br = b = QPushButton(_('&Browse'))
        b.setIcon(QIcon(I('document_open.png')))
        def cf():
            files = choose_files(d, 'select link file', _('Choose file'), select_only_single_file=True)
            if files:
                path = files[0]
                d.url.setText(path)
                if path and os.path.exists(path):
                    with lopen(path, 'rb') as f:
                        q = what(f)
                    is_image = q in {'jpeg', 'png', 'gif'}
                    d.treat_as_image.setChecked(is_image)

        b.clicked.connect(cf)
        d.la = la = QLabel(_(
            'Enter a URL. If you check the "Treat the URL as an image" box '
            'then the URL will be added as an image reference instead of as '
            'a link. You can also choose to create a link to a file on '
            'your computer. '
            'Note that if you create a link to a file on your computer, it '
            'will stop working if the file is moved.'))
        la.setWordWrap(True)
        la.setStyleSheet('QLabel { margin-bottom: 1.5ex }')
        l.setWidget(0, l.SpanningRole, la)
        l.addRow(_('Enter &URL:'), d.url)
        l.addRow(_('Treat the URL as an &image'), d.treat_as_image)
        l.addRow(_('Enter &name (optional):'), d.name)
        l.addRow(_('Choose a file on your computer:'), d.br)
        l.addRow(d.bb)
        d.bb.accepted.connect(d.accept)
        d.bb.rejected.connect(d.reject)
        d.resize(d.sizeHint())
        link, name, is_image = None, None, False
        if d.exec_() == d.Accepted:
            link, name = unicode(d.url.text()).strip(), unicode(d.name.text()).strip()
            is_image = d.treat_as_image.isChecked()
        return link, name, is_image
Пример #39
0
    def request_bulk_rename(self):
        names = {
            unicode(item.data(0, NAME_ROLE).toString())
            for item in self.selectedItems()
        }
        bad = names & current_container().names_that_must_not_be_changed
        if bad:
            return error_dialog(self,
                                _('Cannot rename'),
                                _('The file(s) %s cannot be renamed.') %
                                ('<b>%s</b>' % ', '.join(bad)),
                                show=True)
        names = sorted(names, key=self.index_of_name)
        d = QDialog(self)
        d.l = l = QFormLayout(d)
        d.setLayout(l)
        d.prefix = p = QLineEdit(d)
        p.setText(_('Chapter-'))
        p.selectAll()
        d.la = la = QLabel(
            _('All selected files will be renamed to the form prefix-number'))
        l.addRow(la)
        l.addRow(_('&Prefix:'), p)
        d.num = num = QSpinBox(d)
        num.setMinimum(0), num.setValue(1), num.setMaximum(1000)
        l.addRow(_('Starting &number:'), num)
        d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)
        bb.accepted.connect(d.accept), bb.rejected.connect(d.reject)
        l.addRow(bb)
        if d.exec_() == d.Accepted:
            prefix = sanitize_file_name_unicode(unicode(d.prefix.text()))
            num = d.num.value()
            largest = num + len(names) - 1
            fmt = '%0{0}d'.format(len(str(largest)))

            def change_name(name, num):
                parts = name.split('/')
                base, ext = parts[-1].rpartition('.')[0::2]
                parts[-1] = prefix + (fmt % num) + '.' + ext
                return '/'.join(parts)

            name_map = {
                n: change_name(n, num + i)
                for i, n in enumerate(names)
            }
            self.bulk_rename_requested.emit(name_map)
Пример #40
0
 def ask_link(self):
     d = QDialog(self)
     d.setWindowTitle(_('Create link'))
     l = QFormLayout()
     d.setLayout(l)
     d.url = QLineEdit(d)
     d.name = QLineEdit(d)
     d.bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
     l.addRow(_('Enter &URL:'), d.url)
     l.addRow(_('Enter name (optional):'), d.name)
     l.addRow(d.bb)
     d.bb.accepted.connect(d.accept)
     d.bb.rejected.connect(d.reject)
     link, name = None, None
     if d.exec_() == d.Accepted:
         link, name = unicode(d.url.text()).strip(), unicode(d.name.text()).strip()
     return link, name
Пример #41
0
 def ask_link(self):
     d = QDialog(self)
     d.setWindowTitle(_('Create link'))
     l = QFormLayout()
     d.setLayout(l)
     d.url = QLineEdit(d)
     d.name = QLineEdit(d)
     d.bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
     l.addRow(_('Enter &URL:'), d.url)
     l.addRow(_('Enter name (optional):'), d.name)
     l.addRow(d.bb)
     d.bb.accepted.connect(d.accept)
     d.bb.rejected.connect(d.reject)
     link, name = None, None
     if d.exec_() == d.Accepted:
         link, name = unicode(d.url.text()).strip(), unicode(
             d.name.text()).strip()
     return link, name
Пример #42
0
def customize_remove_unused_css(name, parent, ans):
    d = QDialog(parent)
    d.l = l = QVBoxLayout()
    d.setLayout(d.l)
    d.setWindowTitle(_('Remove unused CSS'))
    d.la = la = QLabel(_(
        'This will remove all CSS rules that do not match any actual content. You'
        ' can also have it automatically remove any class attributes from the HTML'
        ' that do not match any CSS rules, by using the check box below:'))
    la.setWordWrap(True), l.addWidget(la)
    d.c = c = QCheckBox(_('Remove unused &class attributes'))
    c.setChecked(tprefs['remove_unused_classes'])
    l.addWidget(c)
    d.bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
    d.l.addWidget(d.bb)
    d.bb.rejected.connect(d.reject)
    d.bb.accepted.connect(d.accept)
    if d.exec_() != d.Accepted:
        raise Abort()
    ans['remove_unused_classes'] = tprefs['remove_unused_classes'] = c.isChecked()
Пример #43
0
def customize_remove_unused_css(name, parent, ans):
    d = QDialog(parent)
    d.l = l = QVBoxLayout()
    d.setLayout(d.l)
    d.setWindowTitle(_('Remove unused CSS'))
    d.la = la = QLabel(
        _('This will remove all CSS rules that do not match any actual content. You'
          ' can also have it automatically remove any class attributes from the HTML'
          ' that do not match any CSS rules, by using the check box below:'))
    la.setWordWrap(True), l.addWidget(la)
    d.c = c = QCheckBox(_('Remove unused &class attributes'))
    c.setChecked(tprefs['remove_unused_classes'])
    l.addWidget(c)
    d.bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
    d.l.addWidget(d.bb)
    d.bb.rejected.connect(d.reject)
    d.bb.accepted.connect(d.accept)
    if d.exec_() != d.Accepted:
        raise Abort()
    ans['remove_unused_classes'] = tprefs[
        'remove_unused_classes'] = c.isChecked()
Пример #44
0
    def textChanged(self):
        return self.lineEdit().textChanged

    def clear(self):
        self.lineEdit().clear()
        EnComboBox.clear(self)

    def eventFilter(self, obj, e):
        try:
            c = self.lineEdit().mcompleter
        except AttributeError:
            return False
        etype = e.type()
        if self.eat_focus_out and self is obj and etype == e.FocusOut:
            if c.isVisible():
                return True
        return EnComboBox.eventFilter(self, obj, e)

if __name__ == '__main__':
    from PyQt4.Qt import QDialog, QVBoxLayout
    app = QApplication([])
    d = QDialog()
    d.setLayout(QVBoxLayout())
    le = EditWithComplete(d)
    d.layout().addWidget(le)
    items = ['one', 'otwo', 'othree', 'ooone', 'ootwo',
        'oothree', 'a1', 'a2',u'Edgas', u'Èdgar', u'Édgaq', u'Edgar', u'Édgar']
    le.update_items_cache(items)
    le.show_initial_value('')
    d.exec_()
Пример #45
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 PyQt4.Qt import QDialog, QDialogButtonBox, QVBoxLayout, \
                QLabel, Qt, QLineEdit
        from calibre.gui2 import gprefs

        prefname = 'plugin config dialog:'+self.type + ':' + self.name
        geom = gprefs.get(prefname, None)

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

        def size_dialog():
            if geom is None:
                config_dialog.resize(config_dialog.sizeHint())
            else:
                config_dialog.restoreGeometry(geom)

        button_box.accepted.connect(config_dialog.accept)
        button_box.rejected.connect(config_dialog.reject)
        config_dialog.setWindowTitle(_('Customize') + ' ' + self.name)
        try:
            config_widget = self.config_widget()
        except NotImplementedError:
            config_widget = None

        if isinstance(config_widget, tuple):
            from calibre.gui2 import warning_dialog
            warning_dialog(parent, _('Cannot configure'), config_widget[0],
                    det_msg=config_widget[1], show=True)
            return False

        if config_widget is not None:
            v.addWidget(config_widget)
            v.addWidget(button_box)
            size_dialog()
            config_dialog.exec_()

            if config_dialog.result() == QDialog.Accepted:
                if hasattr(config_widget, 'validate'):
                    if config_widget.validate():
                        self.save_settings(config_widget)
                else:
                    self.save_settings(config_widget)
        else:
            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.LinksAccessibleByMouse
                    | Qt.LinksAccessibleByKeyboard)
            help_text.setOpenExternalLinks(True)
            v.addWidget(help_text)
            sc = plugin_customization(self)
            if not sc:
                sc = ''
            sc = sc.strip()
            sc = QLineEdit(sc, config_dialog)
            v.addWidget(sc)
            v.addWidget(button_box)
            size_dialog()
            config_dialog.exec_()

            if config_dialog.result() == QDialog.Accepted:
                sc = unicode(sc.text()).strip()
                customize_plugin(self, sc)

        geom = bytearray(config_dialog.saveGeometry())
        gprefs[prefname] = geom

        return config_dialog.result()
Пример #46
0
 def exec_(self):
     QTimer.singleShot(0, self.setCentered)
     return QDialog.exec_(self)
Пример #47
0
 def exec_(self):
     self.thread = Thread(target=self.do_it)
     self.thread.start()
     self.pi.startAnimation()
     return QDialog.exec_(self)
Пример #48
0
    def add_builtin_recipe(self):
        from calibre.web.feeds.recipes.collection import \
            get_builtin_recipe_collection, get_builtin_recipe_by_id
        from PyQt4.Qt import QDialog, QVBoxLayout, QListWidgetItem, \
                QListWidget, QDialogButtonBox, QSize

        d = QDialog(self)
        d.l = QVBoxLayout()
        d.setLayout(d.l)
        d.list = QListWidget(d)
        d.list.doubleClicked.connect(lambda x: d.accept())
        d.l.addWidget(d.list)
        d.bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
                                Qt.Horizontal, d)
        d.bb.accepted.connect(d.accept)
        d.bb.rejected.connect(d.reject)
        d.l.addWidget(d.bb)
        d.setWindowTitle(_('Choose builtin recipe'))
        items = []
        for r in get_builtin_recipe_collection():
            id_ = r.get('id', '')
            title = r.get('title', '')
            lang = r.get('language', '')
            if id_ and title:
                items.append((title + ' [%s]' % lang, id_))

        items.sort(key=lambda x: sort_key(x[0]))
        for title, id_ in items:
            item = QListWidgetItem(title)
            item.setData(Qt.UserRole, id_)
            d.list.addItem(item)

        d.resize(QSize(450, 400))
        ret = d.exec_()
        d.list.doubleClicked.disconnect()
        if ret != d.Accepted:
            return

        items = list(d.list.selectedItems())
        if not items:
            return
        item = items[-1]
        id_ = unicode(item.data(Qt.UserRole).toString())
        title = unicode(item.data(
            Qt.DisplayRole).toString()).rpartition(' [')[0]
        profile = get_builtin_recipe_by_id(id_, download_recipe=True)
        if profile is None:
            raise Exception('Something weird happened')

        if self._model.has_title(title):
            if question_dialog(
                    self, _('Replace recipe?'),
                    _('A custom recipe named %s already exists. Do you want to '
                      'replace it?') % title):
                self._model.replace_by_title(title, profile)
            else:
                return
        else:
            self.model.add(title, profile)

        self.clear()
Пример #49
0
    def clear(self):
        self.lineEdit().clear()
        EnComboBox.clear(self)

    def eventFilter(self, obj, e):
        try:
            c = self.lineEdit().mcompleter
        except AttributeError:
            return False
        etype = e.type()
        if self.eat_focus_out and self is obj and etype == e.FocusOut:
            if c.isVisible():
                return True
        return EnComboBox.eventFilter(self, obj, e)


if __name__ == '__main__':
    from PyQt4.Qt import QDialog, QVBoxLayout
    app = QApplication([])
    d = QDialog()
    d.setLayout(QVBoxLayout())
    le = EditWithComplete(d)
    d.layout().addWidget(le)
    items = [
        'one', 'otwo', 'othree', 'ooone', 'ootwo', 'oothree', 'a1', 'a2',
        u'Edgas', u'Èdgar', u'Édgaq', u'Edgar', u'Édgar'
    ]
    le.update_items_cache(items)
    le.show_initial_value('')
    d.exec_()
Пример #50
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 PyQt4.Qt import QDialog, QDialogButtonBox, QVBoxLayout, \
                QLabel, Qt, QLineEdit
        from calibre.gui2 import gprefs

        prefname = 'plugin config dialog:' + self.type + ':' + self.name
        geom = gprefs.get(prefname, None)

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

        def size_dialog():
            if geom is None:
                config_dialog.resize(config_dialog.sizeHint())
            else:
                config_dialog.restoreGeometry(geom)

        button_box.accepted.connect(config_dialog.accept)
        button_box.rejected.connect(config_dialog.reject)
        config_dialog.setWindowTitle(_('Customize') + ' ' + self.name)
        try:
            config_widget = self.config_widget()
        except NotImplementedError:
            config_widget = None

        if isinstance(config_widget, tuple):
            from calibre.gui2 import warning_dialog
            warning_dialog(parent,
                           _('Cannot configure'),
                           config_widget[0],
                           det_msg=config_widget[1],
                           show=True)
            return False

        if config_widget is not None:
            v.addWidget(config_widget)
            v.addWidget(button_box)
            size_dialog()
            config_dialog.exec_()

            if config_dialog.result() == QDialog.Accepted:
                if hasattr(config_widget, 'validate'):
                    if config_widget.validate():
                        self.save_settings(config_widget)
                else:
                    self.save_settings(config_widget)
        else:
            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.LinksAccessibleByMouse
                                              | Qt.LinksAccessibleByKeyboard)
            help_text.setOpenExternalLinks(True)
            v.addWidget(help_text)
            sc = plugin_customization(self)
            if not sc:
                sc = ''
            sc = sc.strip()
            sc = QLineEdit(sc, config_dialog)
            v.addWidget(sc)
            v.addWidget(button_box)
            size_dialog()
            config_dialog.exec_()

            if config_dialog.result() == QDialog.Accepted:
                sc = unicode(sc.text()).strip()
                customize_plugin(self, sc)

        geom = bytearray(config_dialog.saveGeometry())
        gprefs[prefname] = geom

        return config_dialog.result()
Пример #51
0
 def exec_(self):
     QTimer.singleShot(0, self.setCentered)
     return QDialog.exec_(self)
Пример #52
0
        dev = self.parent().device_manager.connected_device
        dev.highlight_ignored_folders = True
        self.parent().configure_connected_device()
        dev.highlight_ignored_folders = False


if __name__ == "__main__":
    from calibre.gui2 import Application
    from calibre.devices.mtp.driver import MTP_DEVICE
    from calibre.devices.scanner import DeviceScanner

    s = DeviceScanner()
    s.scan()
    app = Application([])
    dev = MTP_DEVICE(None)
    dev.startup()
    cd = dev.detect_managed_devices(s.devices)
    dev.open(cd, "test")
    cw = dev.config_widget()
    d = QDialog()
    d.l = QVBoxLayout()
    d.setLayout(d.l)
    d.l.addWidget(cw)
    bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
    d.l.addWidget(bb)
    bb.accepted.connect(d.accept)
    bb.rejected.connect(d.reject)
    if d.exec_() == d.Accepted:
        cw.commit()
    dev.shutdown()
 def exec_(self):
     self.completed = 0
     self.canceled = False
     QDialog.exec_(self)
Пример #54
0
        QDialog.accept(self)
        dev = self.parent().device_manager.connected_device
        dev.highlight_ignored_folders = True
        self.parent().configure_connected_device()
        dev.highlight_ignored_folders = False


if __name__ == '__main__':
    from calibre.gui2 import Application
    from calibre.devices.mtp.driver import MTP_DEVICE
    from calibre.devices.scanner import DeviceScanner
    s = DeviceScanner()
    s.scan()
    app = Application([])
    dev = MTP_DEVICE(None)
    dev.startup()
    cd = dev.detect_managed_devices(s.devices)
    dev.open(cd, 'test')
    cw = dev.config_widget()
    d = QDialog()
    d.l = QVBoxLayout()
    d.setLayout(d.l)
    d.l.addWidget(cw)
    bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
    d.l.addWidget(bb)
    bb.accepted.connect(d.accept)
    bb.rejected.connect(d.reject)
    if d.exec_() == d.Accepted:
        cw.commit()
    dev.shutdown()
Пример #55
0
def ask_about_cc_mismatch(gui, db, newdb, missing_cols, incompatible_cols):  # {{{
    source_metadata = db.field_metadata.custom_field_metadata(include_composites=True)
    ndbname = os.path.basename(newdb.library_path)

    d = QDialog(gui)
    d.setWindowTitle(_('Different custom columns'))
    l = QFormLayout()
    tl = QVBoxLayout()
    d.setLayout(tl)
    d.s = QScrollArea(d)
    tl.addWidget(d.s)
    d.w = QWidget(d)
    d.s.setWidget(d.w)
    d.s.setWidgetResizable(True)
    d.w.setLayout(l)
    d.setMinimumWidth(600)
    d.setMinimumHeight(500)
    d.bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)

    msg = _('The custom columns in the <i>{0}</i> library are different from the '
        'custom columns in the <i>{1}</i> library. As a result, some metadata might not be copied.').format(
        os.path.basename(db.library_path), ndbname)
    d.la = la = QLabel(msg)
    la.setWordWrap(True)
    la.setStyleSheet('QLabel { margin-bottom: 1.5ex }')
    l.addRow(la)
    if incompatible_cols:
        la = d.la2 = QLabel(_('The following columns are incompatible - they have the same name'
                ' but different data types. They will be ignored: ') +
                    ', '.join(sorted(incompatible_cols, key=sort_key)))
        la.setWordWrap(True)
        la.setStyleSheet('QLabel { margin-bottom: 1.5ex }')
        l.addRow(la)

    missing_widgets = []
    if missing_cols:
        la = d.la3 = QLabel(_('The following columns are missing in the <i>{0}</i> library.'
                                ' You can choose to add them automatically below.').format(
                                    ndbname))
        la.setWordWrap(True)
        l.addRow(la)
        for k in missing_cols:
            widgets = (k, QCheckBox(_('Add to the %s library') % ndbname))
            l.addRow(QLabel(k), widgets[1])
            missing_widgets.append(widgets)
    d.la4 = la = QLabel(_('This warning is only shown once per library, per session'))
    la.setWordWrap(True)
    tl.addWidget(la)

    tl.addWidget(d.bb)
    d.bb.accepted.connect(d.accept)
    d.bb.rejected.connect(d.reject)
    d.resize(d.sizeHint())
    if d.exec_() == d.Accepted:
        for k, cb in missing_widgets:
            if cb.isChecked():
                col_meta = source_metadata[k]
                newdb.create_custom_column(
                            col_meta['label'], col_meta['name'], col_meta['datatype'],
                            len(col_meta['is_multiple']) > 0,
                            col_meta['is_editable'], col_meta['display'])
        return True
    return False
Пример #56
0
 def exec_(self):
     if unicode(self.search_edit.text()).strip():
         self.do_search()
     return QDialog.exec_(self)
Пример #57
0
def ask_about_cc_mismatch(gui, db, newdb, missing_cols, incompatible_cols):  # {{{
    source_metadata = db.field_metadata.custom_field_metadata(include_composites=True)
    ndbname = os.path.basename(newdb.library_path)

    d = QDialog(gui)
    d.setWindowTitle(_('Different custom columns'))
    l = QFormLayout()
    tl = QVBoxLayout()
    d.setLayout(tl)
    d.s = QScrollArea(d)
    tl.addWidget(d.s)
    d.w = QWidget(d)
    d.s.setWidget(d.w)
    d.s.setWidgetResizable(True)
    d.w.setLayout(l)
    d.setMinimumWidth(600)
    d.setMinimumHeight(500)
    d.bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)

    msg = _('The custom columns in the <i>{0}</i> library are different from the '
        'custom columns in the <i>{1}</i> library. As a result, some metadata might not be copied.').format(
        os.path.basename(db.library_path), ndbname)
    d.la = la = QLabel(msg)
    la.setWordWrap(True)
    la.setStyleSheet('QLabel { margin-bottom: 1.5ex }')
    l.addRow(la)
    if incompatible_cols:
        la = d.la2 = QLabel(_('The following columns are incompatible - they have the same name'
                ' but different data types. They will be ignored: ') +
                    ', '.join(sorted(incompatible_cols, key=sort_key)))
        la.setWordWrap(True)
        la.setStyleSheet('QLabel { margin-bottom: 1.5ex }')
        l.addRow(la)

    missing_widgets = []
    if missing_cols:
        la = d.la3 = QLabel(_('The following columns are missing in the <i>{0}</i> library.'
                                ' You can choose to add them automatically below.').format(
                                    ndbname))
        la.setWordWrap(True)
        l.addRow(la)
        for k in missing_cols:
            widgets = (k, QCheckBox(_('Add to the %s library') % ndbname))
            l.addRow(QLabel(k), widgets[1])
            missing_widgets.append(widgets)
    d.la4 = la = QLabel(_('This warning is only shown once per library, per session'))
    la.setWordWrap(True)
    tl.addWidget(la)

    tl.addWidget(d.bb)
    d.bb.accepted.connect(d.accept)
    d.bb.rejected.connect(d.reject)
    d.resize(d.sizeHint())
    if d.exec_() == d.Accepted:
        for k, cb in missing_widgets:
            if cb.isChecked():
                col_meta = source_metadata[k]
                newdb.create_custom_column(
                            col_meta['label'], col_meta['name'], col_meta['datatype'],
                            len(col_meta['is_multiple']) > 0,
                            col_meta['is_editable'], col_meta['display'])
        return True
    return False