示例#1
0
    def __init__(self, parent, view, row, link_delegate):
        QDialog.__init__(self, parent)
        Ui_BookInfo.__init__(self)
        self.setupUi(self)
        self.gui = parent
        self.cover_pixmap = None
        self.details.sizeHint = self.details_size_hint
        self.details.page().setLinkDelegationPolicy(self.details.page().DelegateAllLinks)
        self.details.linkClicked.connect(self.link_clicked)
        self.css = P('templates/book_details.css', data=True).decode('utf-8')
        self.link_delegate = link_delegate
        self.details.setAttribute(Qt.WA_OpaquePaintEvent, False)
        palette = self.details.palette()
        self.details.setAcceptDrops(False)
        palette.setBrush(QPalette.Base, Qt.transparent)
        self.details.page().setPalette(palette)


        self.view = view
        self.current_row = None
        self.fit_cover.setChecked(dynamic.get('book_info_dialog_fit_cover',
            True))
        self.refresh(row)
        self.connect(self.view.selectionModel(), SIGNAL('currentChanged(QModelIndex,QModelIndex)'), self.slave)
        self.connect(self.next_button, SIGNAL('clicked()'), self.next)
        self.connect(self.previous_button, SIGNAL('clicked()'), self.previous)
        self.fit_cover.stateChanged.connect(self.toggle_cover_fit)
        self.cover.resizeEvent = self.cover_view_resized
        self.cover.cover_changed.connect(self.cover_changed)

        desktop = QCoreApplication.instance().desktop()
        screen_height = desktop.availableGeometry().height() - 100
        self.resize(self.size().width(), screen_height)
示例#2
0
    def setup_ui(self):
        self.l = l = QFormLayout(self)
        l.addRow(
            QLabel(_('Print %s to a PDF file') % elided_text(self.book_title)))
        self.h = h = QHBoxLayout()
        self.file_name = f = QLineEdit(self)
        val = dynamic.get(self.OUTPUT_NAME, None)
        if not val:
            val = expanduser('~')
        else:
            val = os.path.dirname(val)
        f.setText(os.path.abspath(os.path.join(val, self.default_file_name)))
        self.browse_button = b = QToolButton(self)
        b.setIcon(QIcon(I('document_open.png'))), b.setToolTip(
            _('Choose location for PDF file'))
        b.clicked.connect(self.choose_file)
        h.addWidget(f), h.addWidget(b)
        f.setMinimumWidth(350)
        w = QLabel(_('&File:'))
        l.addRow(w, h), w.setBuddy(f)

        self.paper_size = ps = QComboBox(self)
        ps.addItems([
            a.upper()
            for a in sorted(self.paper_size_map, key=numeric_sort_key)
        ])
        previous_size = vprefs.get('print-to-pdf-page-size', None)
        if previous_size not in self.paper_size_map:
            previous_size = (QPrinter().pageLayout().pageSize().name()
                             or '').lower()
        if previous_size not in self.paper_size_map:
            previous_size = 'a4'
        ps.setCurrentIndex(ps.findText(previous_size.upper()))
        l.addRow(_('Paper &size:'), ps)
        tmap = {
            'left': _('&Left margin:'),
            'top': _('&Top margin:'),
            'right': _('&Right margin:'),
            'bottom': _('&Bottom margin:'),
        }
        for edge in 'left top right bottom'.split():
            m = QDoubleSpinBox(self)
            m.setSuffix(' ' + _('inches'))
            m.setMinimum(0), m.setMaximum(3), m.setSingleStep(0.1)
            val = vprefs.get('print-to-pdf-%s-margin' % edge, 1)
            m.setValue(val)
            setattr(self, '%s_margin' % edge, m)
            l.addRow(tmap[edge], m)
        self.pnum = pnum = QCheckBox(_('Add page &number to printed pages'),
                                     self)
        pnum.setChecked(vprefs.get('print-to-pdf-page-numbers', True))
        l.addRow(pnum)

        self.show_file = sf = QCheckBox(_('&Open PDF file after printing'),
                                        self)
        sf.setChecked(vprefs.get('print-to-pdf-show-file', True))
        l.addRow(sf)

        l.addRow(self.bb)
示例#3
0
    def setup_ui(self):
        self.vl = vl = QVBoxLayout(self)
        self.l = l = QFormLayout()
        vl.addLayout(l)
        l.setContentsMargins(0, 0, 0, 0)
        l.addRow(
            QLabel(_('Print %s to a PDF file') % elided_text(self.book_title)))
        self.h = h = QHBoxLayout()
        self.file_name = f = QLineEdit(self)
        val = dynamic.get(self.OUTPUT_NAME, None)
        if not val:
            val = expanduser('~')
        else:
            val = os.path.dirname(val)
        f.setText(os.path.abspath(os.path.join(val, self.default_file_name)))
        self.browse_button = b = QToolButton(self)
        b.setIcon(QIcon(I('document_open.png'))), b.setToolTip(
            _('Choose location for PDF file'))
        b.clicked.connect(self.choose_file)
        h.addWidget(f), h.addWidget(b)
        f.setMinimumWidth(350)
        w = QLabel(_('&File:'))
        l.addRow(w, h), w.setBuddy(f)

        self.paper_size = ps = PaperSizes(self)
        ps.initialize()
        ps.set_value_for_config = vprefs.get('print-to-pdf-page-size', None)
        l.addRow(_('Paper &size:'), ps)
        tmap = {
            'left': _('&Left margin:'),
            'top': _('&Top margin:'),
            'right': _('&Right margin:'),
            'bottom': _('&Bottom margin:'),
        }
        for edge in 'left top right bottom'.split():
            m = QDoubleSpinBox(self)
            m.setSuffix(' ' + _('inches'))
            m.setMinimum(0), m.setMaximum(3), m.setSingleStep(0.1)
            val = vprefs.get('print-to-pdf-%s-margin' % edge, 1)
            m.setValue(val)
            setattr(self, '%s_margin' % edge, m)
            l.addRow(tmap[edge], m)
        self.pnum = pnum = QCheckBox(_('Add page &number to printed pages'),
                                     self)
        pnum.setChecked(vprefs.get('print-to-pdf-page-numbers', True))
        l.addRow(pnum)

        self.show_file = sf = QCheckBox(_('&Open PDF file after printing'),
                                        self)
        sf.setChecked(vprefs.get('print-to-pdf-show-file', True))
        l.addRow(sf)

        vl.addStretch(10)
        vl.addWidget(self.bb)
示例#4
0
    def setup_ui(self):
        self.l = l = QFormLayout(self)
        l.addRow(QLabel(_('Print %s to a PDF file') % elided_text(self.book_title)))
        self.h = h = QHBoxLayout()
        self.file_name = f = QLineEdit(self)
        val = dynamic.get(self.OUTPUT_NAME, None)
        if not val:
            val = expanduser('~')
        else:
            val = os.path.dirname(val)
        f.setText(os.path.abspath(os.path.join(val, self.default_file_name)))
        self.browse_button = b = QToolButton(self)
        b.setIcon(QIcon(I('document_open.png'))), b.setToolTip(_('Choose location for PDF file'))
        b.clicked.connect(self.choose_file)
        h.addWidget(f), h.addWidget(b)
        f.setMinimumWidth(350)
        w = QLabel(_('&File:'))
        l.addRow(w, h), w.setBuddy(f)

        self.paper_size = ps = QComboBox(self)
        ps.addItems([a.upper() for a in sorted(self.paper_size_map, key=numeric_sort_key)])
        previous_size = vprefs.get('print-to-pdf-page-size', None)
        if previous_size not in self.paper_size_map:
            previous_size = (QPrinter().pageLayout().pageSize().name() or '').lower()
        if previous_size not in self.paper_size_map:
            previous_size = 'a4'
        ps.setCurrentIndex(ps.findText(previous_size.upper()))
        l.addRow(_('Paper &size:'), ps)
        tmap = {
                'left':_('&Left margin:'),
                'top':_('&Top margin:'),
                'right':_('&Right margin:'),
                'bottom':_('&Bottom margin:'),
        }
        for edge in 'left top right bottom'.split():
            m = QDoubleSpinBox(self)
            m.setSuffix(' ' + _('inches'))
            m.setMinimum(0), m.setMaximum(3), m.setSingleStep(0.1)
            val = vprefs.get('print-to-pdf-%s-margin' % edge, 1)
            m.setValue(val)
            setattr(self, '%s_margin' % edge, m)
            l.addRow(tmap[edge], m)
        self.pnum = pnum = QCheckBox(_('Add page &number to printed pages'), self)
        pnum.setChecked(vprefs.get('print-to-pdf-page-numbers', True))
        l.addRow(pnum)

        self.show_file = sf = QCheckBox(_('Open PDF file after printing'), self)
        sf.setChecked(vprefs.get('print-to-pdf-show-file', True))
        l.addRow(sf)

        l.addRow(self.bb)
示例#5
0
    def update_found(self,
                     calibre_version,
                     number_of_plugin_updates,
                     force=False,
                     no_show_popup=False):
        self.last_newest_calibre_version = calibre_version
        has_calibre_update = calibre_version != NO_CALIBRE_UPDATE
        has_plugin_updates = number_of_plugin_updates > 0
        self.plugin_update_found(number_of_plugin_updates)
        version_url = binascii.hexlify(
            cPickle.dumps((calibre_version, number_of_plugin_updates), -1))
        calibre_version = u'.'.join(map(unicode, calibre_version))

        if not has_calibre_update and not has_plugin_updates:
            self.status_bar.update_label.setVisible(False)
            return
        if has_calibre_update:
            plt = u''
            if has_plugin_updates:
                plt = ngettext(
                    ' (one plugin update)', ' ({} plugin updates)',
                    number_of_plugin_updates).format(number_of_plugin_updates)
            msg = (u'<span style="color:green; font-weight: bold">%s: '
                   u'<a href="update:%s">%s%s</a></span>') % (
                       _('Update found'), version_url, calibre_version, plt)
        else:
            plt = ngettext('updated plugin', 'updated plugins',
                           number_of_plugin_updates)
            msg = (u'<a href="update:%s">%d %s</a>') % (
                version_url, number_of_plugin_updates, plt)
        self.status_bar.update_label.setText(msg)
        self.status_bar.update_label.setVisible(True)

        if has_calibre_update:
            if (force
                    or (config.get('new_version_notification') and dynamic.get(
                        'update to version %s' % calibre_version, True))):
                if not no_show_popup:
                    self._update_notification__ = UpdateNotification(
                        calibre_version, number_of_plugin_updates, parent=self)
                    self._update_notification__.show()
        elif has_plugin_updates:
            if force:
                from calibre.gui2.dialogs.plugin_updater import (
                    PluginUpdaterDialog, FILTER_UPDATE_AVAILABLE)
                d = PluginUpdaterDialog(self,
                                        initial_filter=FILTER_UPDATE_AVAILABLE)
                d.exec_()
                if d.do_restart:
                    self.quit(restart=True)
示例#6
0
def confirm(msg, name, parent=None, pixmap='dialog_warning.png', title=None,
        show_cancel_button=True, confirm_msg=None):
    if not dynamic.get(confirm_config_name(name), True):
        return True
    d = Dialog(msg, name, parent)
    d.label.setPixmap(QPixmap(I(pixmap)))
    d.setWindowIcon(QIcon(I(pixmap)))
    if title is not None:
        d.setWindowTitle(title)
    if not show_cancel_button:
        d.buttonBox.button(d.buttonBox.Cancel).setVisible(False)
    if confirm_msg is not None:
        d.again.setText(confirm_msg)
    d.resize(d.sizeHint())
    return d.exec_() == d.Accepted
示例#7
0
    def update_found(self, version, force=False, no_show_popup=False):
        try:
            calibre_version, plugin_updates = version.split(VSEP)
            plugin_updates = int(plugin_updates)
        except:
            traceback.print_exc()
            return
        self.last_newest_calibre_version = calibre_version
        has_calibre_update = calibre_version and calibre_version != NO_CALIBRE_UPDATE
        has_plugin_updates = plugin_updates > 0
        self.plugin_update_found(plugin_updates)

        if not has_calibre_update and not has_plugin_updates:
            self.status_bar.update_label.setVisible(False)
            return
        if has_calibre_update:
            plt = u''
            if has_plugin_updates:
                plt = _(' (%d plugin updates)')%plugin_updates
            msg = (u'<span style="color:green; font-weight: bold">%s: '
                    u'<a href="update:%s">%s%s</a></span>') % (
                        _('Update found'), version, calibre_version, plt)
        else:
            msg = (u'<a href="update:%s">%d %s</a>')%(version, plugin_updates,
                    _('updated plugins'))
        self.status_bar.update_label.setText(msg)
        self.status_bar.update_label.setVisible(True)


        if has_calibre_update:
            if (force or (config.get('new_version_notification') and
                    dynamic.get('update to version %s'%calibre_version, True))):
                if not no_show_popup:
                    self._update_notification__ = UpdateNotification(calibre_version,
                            plugin_updates, parent=self)
                    self._update_notification__.show()
        elif has_plugin_updates:
            if force:
                from calibre.gui2.dialogs.plugin_updater import (PluginUpdaterDialog,
                    FILTER_UPDATE_AVAILABLE)
                d = PluginUpdaterDialog(self,
                        initial_filter=FILTER_UPDATE_AVAILABLE)
                d.exec_()
                if d.do_restart:
                    self.quit(restart=True)
示例#8
0
文件: update.py 项目: sss/calibre
    def update_found(self, version, force=False, no_show_popup=False):
        try:
            calibre_version, plugin_updates = version.split(VSEP)
            plugin_updates = int(plugin_updates)
        except:
            traceback.print_exc()
            return
        self.last_newest_calibre_version = calibre_version
        has_calibre_update = calibre_version and calibre_version != NO_CALIBRE_UPDATE
        has_plugin_updates = plugin_updates > 0
        self.plugin_update_found(plugin_updates)

        if not has_calibre_update and not has_plugin_updates:
            self.status_bar.update_label.setVisible(False)
            return
        if has_calibre_update:
            plt = u''
            if has_plugin_updates:
                plt = _(' (%d plugin updates)') % plugin_updates
            msg = (u'<span style="color:green; font-weight: bold">%s: '
                   u'<a href="update:%s">%s%s</a></span>') % (
                       _('Update found'), version, calibre_version, plt)
        else:
            msg = (u'<a href="update:%s">%d %s</a>') % (
                version, plugin_updates, _('updated plugins'))
        self.status_bar.update_label.setText(msg)
        self.status_bar.update_label.setVisible(True)

        if has_calibre_update:
            if (force
                    or (config.get('new_version_notification') and dynamic.get(
                        'update to version %s' % calibre_version, True))):
                if not no_show_popup:
                    self._update_notification__ = UpdateNotification(
                        calibre_version, plugin_updates, parent=self)
                    self._update_notification__.show()
        elif has_plugin_updates:
            if force:
                from calibre.gui2.dialogs.plugin_updater import (
                    PluginUpdaterDialog, FILTER_UPDATE_AVAILABLE)
                d = PluginUpdaterDialog(self,
                                        initial_filter=FILTER_UPDATE_AVAILABLE)
                d.exec_()
                if d.do_restart:
                    self.quit(restart=True)
示例#9
0
    def __init__(self, parent, view, row, link_delegate):
        QDialog.__init__(self, parent)
        Ui_BookInfo.__init__(self)
        self.setupUi(self)
        self.gui = parent
        self.cover_pixmap = None
        self.details.sizeHint = self.details_size_hint
        self.details.page().setLinkDelegationPolicy(self.details.page().DelegateAllLinks)
        self.details.linkClicked.connect(self.link_clicked)
        self.css = P('templates/book_details.css', data=True).decode('utf-8')
        self.link_delegate = link_delegate
        self.details.setAttribute(Qt.WA_OpaquePaintEvent, False)
        palette = self.details.palette()
        self.details.setAcceptDrops(False)
        palette.setBrush(QPalette.Base, Qt.transparent)
        self.details.page().setPalette(palette)


        self.view = view
        self.current_row = None
        self.fit_cover.setChecked(dynamic.get('book_info_dialog_fit_cover',
            True))
        self.refresh(row)
        self.connect(self.view.selectionModel(), SIGNAL('currentChanged(QModelIndex,QModelIndex)'), self.slave)
        self.connect(self.next_button, SIGNAL('clicked()'), self.next)
        self.connect(self.previous_button, SIGNAL('clicked()'), self.previous)
        self.fit_cover.stateChanged.connect(self.toggle_cover_fit)
        self.cover.resizeEvent = self.cover_view_resized
        self.cover.cover_changed.connect(self.cover_changed)
        self.ns = QShortcut(QKeySequence('Alt+Right'), self)
        self.ns.activated.connect(self.next)
        self.ps = QShortcut(QKeySequence('Alt+Left'), self)
        self.ps.activated.connect(self.previous)
        self.next_button.setToolTip(_('Next [%s]')%
                unicode(self.ns.key().toString(QKeySequence.NativeText)))
        self.previous_button.setToolTip(_('Previous [%s]')%
                unicode(self.ps.key().toString(QKeySequence.NativeText)))

        desktop = QCoreApplication.instance().desktop()
        screen_height = desktop.availableGeometry().height() - 100
        self.resize(self.size().width(), screen_height)
示例#10
0
    def update_found(self, calibre_version, number_of_plugin_updates, force=False, no_show_popup=False):
        self.last_newest_calibre_version = calibre_version
        has_calibre_update = calibre_version != NO_CALIBRE_UPDATE
        has_plugin_updates = number_of_plugin_updates > 0
        self.plugin_update_found(number_of_plugin_updates)
        version_url = binascii.hexlify(cPickle.dumps((calibre_version, number_of_plugin_updates), -1))
        calibre_version = u'.'.join(map(unicode, calibre_version))

        if not has_calibre_update and not has_plugin_updates:
            self.status_bar.update_label.setVisible(False)
            return
        if has_calibre_update:
            plt = u''
            if has_plugin_updates:
                plt = _(' (%d plugin updates)')%number_of_plugin_updates
            msg = (u'<span style="color:green; font-weight: bold">%s: '
                    u'<a href="update:%s">%s%s</a></span>') % (
                        _('Update found'), version_url, calibre_version, plt)
        else:
            msg = (u'<a href="update:%s">%d %s</a>')%(version_url, number_of_plugin_updates,
                    _('updated plugins'))
        self.status_bar.update_label.setText(msg)
        self.status_bar.update_label.setVisible(True)

        if has_calibre_update:
            if (force or (config.get('new_version_notification') and
                    dynamic.get('update to version %s'%calibre_version, True))):
                if not no_show_popup:
                    self._update_notification__ = UpdateNotification(calibre_version,
                            number_of_plugin_updates, parent=self)
                    self._update_notification__.show()
        elif has_plugin_updates:
            if force:
                from calibre.gui2.dialogs.plugin_updater import (PluginUpdaterDialog,
                    FILTER_UPDATE_AVAILABLE)
                d = PluginUpdaterDialog(self,
                        initial_filter=FILTER_UPDATE_AVAILABLE)
                d.exec_()
                if d.do_restart:
                    self.quit(restart=True)
示例#11
0
    def __init__(self, parent, dbspec, ids, db):
        import re, io
        from calibre import prints as info
        from PyQt5.uic import compileUi

        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.dbspec, self.ids = dbspec, ids

        # Display the number of books we've been passed
        self.count.setText(unicode_type(self.count.text()).format(len(ids)))

        # Display the last-used title
        self.title.setText(dynamic.get('catalog_last_used_title',
            _('My books')))

        self.fmts, self.widgets = [], []

        for plugin in catalog_plugins():
            if plugin.name in config['disabled_plugins']:
                continue

            name = plugin.name.lower().replace(' ', '_')
            if getattr(plugin, 'plugin_path', None) is None:
                try:
                    catalog_widget = importlib.import_module('calibre.gui2.catalog.'+name)
                    pw = catalog_widget.PluginWidget()
                    pw.parent_ref = weakref.ref(self)
                    pw.initialize(name, db)
                    pw.ICON = I('forward.png')
                    self.widgets.append(pw)
                    [self.fmts.append([file_type.upper(), pw.sync_enabled,pw]) for file_type in plugin.file_types]
                except ImportError:
                    info("ImportError initializing %s" % name)
                    continue
            else:
                # Load dynamic tab
                form = os.path.join(plugin.resources_path,'%s.ui' % name)
                klass = os.path.join(plugin.resources_path,'%s.py' % name)
                compiled_form = os.path.join(plugin.resources_path,'%s_ui.py' % name)

                if os.path.exists(form) and os.path.exists(klass):
                    # info("Adding widget for user-installed Catalog plugin %s" % plugin.name)

                    # Compile the .ui form provided in plugin.zip
                    if not os.path.exists(compiled_form):
                        # info('\tCompiling form', form)
                        buf = io.BytesIO()
                        compileUi(form, buf)
                        dat = buf.getvalue()
                        dat = re.compile(r'QtGui.QApplication.translate\(.+?,\s+"(.+?)(?<!\\)",.+?\)',
                                         re.DOTALL).sub(r'_("\1")', dat)
                        open(compiled_form, 'wb').write(dat)

                    # Import the dynamic PluginWidget() from .py file provided in plugin.zip
                    try:
                        sys.path.insert(0, plugin.resources_path)
                        catalog_widget = importlib.import_module(name)
                        pw = catalog_widget.PluginWidget()
                        pw.initialize(name)
                        pw.ICON = I('forward.png')
                        self.widgets.append(pw)
                        [self.fmts.append([file_type.upper(), pw.sync_enabled,pw]) for file_type in plugin.file_types]
                    except ImportError:
                        info("ImportError with %s" % name)
                        continue
                    finally:
                        sys.path.remove(plugin.resources_path)

                else:
                    info("No dynamic tab resources found for %s" % name)

        self.widgets = sorted(self.widgets, key=lambda x: x.TITLE)

        # Generate a sorted list of installed catalog formats/sync_enabled pairs
        fmts = sorted([x[0] for x in self.fmts])

        self.sync_enabled_formats = []
        for fmt in self.fmts:
            if fmt[1]:
                self.sync_enabled_formats.append(fmt[0])

        # Callbacks when format, title changes
        self.format.currentIndexChanged.connect(self.format_changed)
        self.format.currentIndexChanged.connect(self.settings_changed)
        self.title.editingFinished.connect(self.settings_changed)

        # Add the installed catalog format list to the format QComboBox
        self.format.blockSignals(True)
        self.format.addItems(fmts)

        pref = dynamic.get('catalog_preferred_format', 'CSV')
        idx = self.format.findText(pref)
        if idx > -1:
            self.format.setCurrentIndex(idx)
        self.format.blockSignals(False)

        if self.sync.isEnabled():
            self.sync.setChecked(dynamic.get('catalog_sync_to_device', True))
        self.add_to_library.setChecked(dynamic.get('catalog_add_to_library', True))

        self.format.currentIndexChanged.connect(self.show_plugin_tab)
        self.buttonBox.button(self.buttonBox.Apply).clicked.connect(self.apply)
        self.buttonBox.button(self.buttonBox.Help).clicked.connect(self.help)
        self.show_plugin_tab(None)

        geom = dynamic.get('catalog_window_geom', None)
        if geom is not None:
            self.restoreGeometry(bytes(geom))
        else:
            self.resize(self.sizeHint())
        d = QCoreApplication.instance().desktop()
        g = d.availableGeometry(d.screenNumber(self))
        self.setMaximumWidth(g.width() - 50)
        self.setMaximumHeight(g.height() - 50)
示例#12
0
    def __init__(self, parent, dbspec, ids, db):
        import re, cStringIO
        from calibre import prints as info
        from PyQt5.uic import compileUi

        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.dbspec, self.ids = dbspec, ids

        # Display the number of books we've been passed
        self.count.setText(unicode(self.count.text()).format(len(ids)))

        # Display the last-used title
        self.title.setText(
            dynamic.get('catalog_last_used_title', _('My Books')))

        self.fmts, self.widgets = [], []

        for plugin in catalog_plugins():
            if plugin.name in config['disabled_plugins']:
                continue

            name = plugin.name.lower().replace(' ', '_')
            if getattr(plugin, 'plugin_path', None) is None:
                try:
                    catalog_widget = importlib.import_module(
                        'calibre.gui2.catalog.' + name)
                    pw = catalog_widget.PluginWidget()
                    pw.initialize(name, db)
                    pw.ICON = I('forward.png')
                    self.widgets.append(pw)
                    [
                        self.fmts.append(
                            [file_type.upper(), pw.sync_enabled, pw])
                        for file_type in plugin.file_types
                    ]
                except ImportError:
                    info("ImportError initializing %s" % name)
                    continue
            else:
                # Load dynamic tab
                form = os.path.join(plugin.resources_path, '%s.ui' % name)
                klass = os.path.join(plugin.resources_path, '%s.py' % name)
                compiled_form = os.path.join(plugin.resources_path,
                                             '%s_ui.py' % name)

                if os.path.exists(form) and os.path.exists(klass):
                    # info("Adding widget for user-installed Catalog plugin %s" % plugin.name)

                    # Compile the .ui form provided in plugin.zip
                    if not os.path.exists(compiled_form):
                        # info('\tCompiling form', form)
                        buf = cStringIO.StringIO()
                        compileUi(form, buf)
                        dat = buf.getvalue()
                        dat = re.compile(
                            r'QtGui.QApplication.translate\(.+?,\s+"(.+?)(?<!\\)",.+?\)',
                            re.DOTALL).sub(r'_("\1")', dat)
                        open(compiled_form, 'wb').write(dat)

                    # Import the dynamic PluginWidget() from .py file provided in plugin.zip
                    try:
                        sys.path.insert(0, plugin.resources_path)
                        catalog_widget = importlib.import_module(name)
                        pw = catalog_widget.PluginWidget()
                        pw.initialize(name)
                        pw.ICON = I('forward.png')
                        self.widgets.append(pw)
                        [
                            self.fmts.append(
                                [file_type.upper(), pw.sync_enabled, pw])
                            for file_type in plugin.file_types
                        ]
                    except ImportError:
                        info("ImportError with %s" % name)
                        continue
                    finally:
                        sys.path.remove(plugin.resources_path)

                else:
                    info("No dynamic tab resources found for %s" % name)

        self.widgets = sorted(self.widgets,
                              cmp=lambda x, y: cmp(x.TITLE, y.TITLE))

        # Generate a sorted list of installed catalog formats/sync_enabled pairs
        fmts = sorted([x[0] for x in self.fmts])

        self.sync_enabled_formats = []
        for fmt in self.fmts:
            if fmt[1]:
                self.sync_enabled_formats.append(fmt[0])

        # Callbacks when format, title changes
        self.format.currentIndexChanged.connect(self.format_changed)
        self.format.currentIndexChanged.connect(self.settings_changed)
        self.title.editingFinished.connect(self.settings_changed)

        # Add the installed catalog format list to the format QComboBox
        self.format.blockSignals(True)
        self.format.addItems(fmts)

        pref = dynamic.get('catalog_preferred_format', 'CSV')
        idx = self.format.findText(pref)
        if idx > -1:
            self.format.setCurrentIndex(idx)
        self.format.blockSignals(False)

        if self.sync.isEnabled():
            self.sync.setChecked(dynamic.get('catalog_sync_to_device', True))
        self.add_to_library.setChecked(
            dynamic.get('catalog_add_to_library', True))

        self.format.currentIndexChanged.connect(self.show_plugin_tab)
        self.buttonBox.button(self.buttonBox.Apply).clicked.connect(self.apply)
        self.buttonBox.button(self.buttonBox.Help).clicked.connect(self.help)
        self.show_plugin_tab(None)

        geom = dynamic.get('catalog_window_geom', None)
        if geom is not None:
            self.restoreGeometry(bytes(geom))
        else:
            self.resize(self.sizeHint())
示例#13
0
    def __init__(
        self, title=_('Choose Files'),
        filters=[],
        add_all_files_filter=True,
        parent=None,
        modal=True,
        name='',
        mode=QFileDialog.ExistingFiles,
        default_dir=u'~',
        no_save_dir=False,
        combine_file_and_saved_dir=False
    ):
        from calibre.gui2 import dynamic, sanitize_env_vars
        from calibre.gui2.ui import get_gui
        gui = get_gui()
        adapt_menubar = gui.bars_manager.adapt_menu_bar_for_dialog if gui is not None else Dummy()
        QObject.__init__(self)
        ftext = ''
        if filters:
            for filter in filters:
                text, extensions = filter
                extensions = ['*'+(i if i.startswith('.') else '.'+i) for i in
                        extensions]
                ftext += '%s (%s);;'%(text, ' '.join(extensions))
        if add_all_files_filter or not ftext:
            ftext += 'All files (*)'
        if ftext.endswith(';;'):
            ftext = ftext[:-2]

        self.dialog_name = dialog_name(name, title)
        self.selected_files = None
        self.fd = None

        if combine_file_and_saved_dir:
            bn = os.path.basename(default_dir)
            prev = dynamic.get(self.dialog_name,
                    os.path.expanduser(u'~'))
            if os.path.exists(prev):
                if os.path.isfile(prev):
                    prev = os.path.dirname(prev)
            else:
                prev = os.path.expanduser(u'~')
            initial_dir = os.path.join(prev, bn)
        elif no_save_dir:
            initial_dir = os.path.expanduser(default_dir)
        else:
            initial_dir = dynamic.get(self.dialog_name,
                    os.path.expanduser(default_dir))
        if not isinstance(initial_dir, string_or_bytes):
            initial_dir = os.path.expanduser(default_dir)
        if not initial_dir or (not os.path.exists(initial_dir) and not (
                mode == QFileDialog.AnyFile and (no_save_dir or combine_file_and_saved_dir))):
            initial_dir = select_initial_dir(initial_dir)
        self.selected_files = []
        use_native_dialog = 'CALIBRE_NO_NATIVE_FILEDIALOGS' not in os.environ
        with sanitize_env_vars():
            opts = QFileDialog.Option()
            if not use_native_dialog:
                opts |= QFileDialog.DontUseNativeDialog
            if mode == QFileDialog.AnyFile:
                with adapt_menubar:
                    f = QFileDialog.getSaveFileName(parent, title,
                        initial_dir, ftext, "", opts)
                if f and f[0]:
                    self.selected_files.append(f[0])
            elif mode == QFileDialog.ExistingFile:
                with adapt_menubar:
                    f = QFileDialog.getOpenFileName(parent, title,
                        initial_dir, ftext, "", opts)
                if f and f[0] and os.path.exists(f[0]):
                    self.selected_files.append(f[0])
            elif mode == QFileDialog.ExistingFiles:
                with adapt_menubar:
                    fs = QFileDialog.getOpenFileNames(parent, title, initial_dir,
                            ftext, "", opts)
                if fs and fs[0]:
                    for f in fs[0]:
                        f = unicode_type(f)
                        if not f:
                            continue
                        if not os.path.exists(f):
                            # QFileDialog for some reason quotes spaces
                            # on linux if there is more than one space in a row
                            f = unquote(f)
                        if f and os.path.exists(f):
                            self.selected_files.append(f)
            else:
                if mode == QFileDialog.Directory:
                    opts |= QFileDialog.ShowDirsOnly
                with adapt_menubar:
                    f = unicode_type(QFileDialog.getExistingDirectory(parent, title, initial_dir, opts))
                if os.path.exists(f):
                    self.selected_files.append(f)
        if self.selected_files:
            self.selected_files = [unicode_type(q) for q in self.selected_files]
            saved_loc = self.selected_files[0]
            if os.path.isfile(saved_loc):
                saved_loc = os.path.dirname(saved_loc)
            if not no_save_dir:
                dynamic[self.dialog_name] = saved_loc
        self.accepted = bool(self.selected_files)
示例#14
0
def save_version_notified(calibre_version):
    done = dynamic.get('notified-version-updates') or set()
    done.add(version_key(calibre_version))
    dynamic.set('notified-version-updates', done)
示例#15
0
def is_version_notified(calibre_version):
    key = version_key(calibre_version)
    done = dynamic.get('notified-version-updates') or set()
    return key in done
示例#16
0
    def __init__(self, title=_('Choose Files'),
                       filters=[],
                       add_all_files_filter=True,
                       parent=None,
                       modal=True,
                       name='',
                       mode=QFileDialog.ExistingFiles,
                       default_dir=u'~',
                       no_save_dir=False,
                       combine_file_and_saved_dir=False
                       ):
        from calibre.gui2 import dynamic, sanitize_env_vars
        QObject.__init__(self)
        ftext = ''
        if filters:
            for filter in filters:
                text, extensions = filter
                extensions = ['*'+(i if i.startswith('.') else '.'+i) for i in
                        extensions]
                ftext += '%s (%s);;'%(text, ' '.join(extensions))
        if add_all_files_filter or not ftext:
            ftext += 'All files (*)'
        if ftext.endswith(';;'):
            ftext = ftext[:-2]

        self.dialog_name = dialog_name(name, title)
        self.selected_files = None
        self.fd = None

        if combine_file_and_saved_dir:
            bn = os.path.basename(default_dir)
            prev = dynamic.get(self.dialog_name,
                    expanduser(u'~'))
            if os.path.exists(prev):
                if os.path.isfile(prev):
                    prev = os.path.dirname(prev)
            else:
                prev = expanduser(u'~')
            initial_dir = os.path.join(prev, bn)
        elif no_save_dir:
            initial_dir = expanduser(default_dir)
        else:
            initial_dir = dynamic.get(self.dialog_name,
                    expanduser(default_dir))
        if not isinstance(initial_dir, basestring):
            initial_dir = expanduser(default_dir)
        if not initial_dir or (not os.path.exists(initial_dir) and not (
                mode == QFileDialog.AnyFile and (no_save_dir or combine_file_and_saved_dir))):
            initial_dir = select_initial_dir(initial_dir)
        self.selected_files = []
        use_native_dialog = 'CALIBRE_NO_NATIVE_FILEDIALOGS' not in os.environ
        with sanitize_env_vars():
            opts = QFileDialog.Option()
            if not use_native_dialog:
                opts |= QFileDialog.DontUseNativeDialog
            if mode == QFileDialog.AnyFile:
                f = QFileDialog.getSaveFileName(parent, title,
                    initial_dir, ftext, "", opts)
                if f and f[0]:
                    self.selected_files.append(f[0])
            elif mode == QFileDialog.ExistingFile:
                f = QFileDialog.getOpenFileName(parent, title,
                    initial_dir, ftext, "", opts)
                if f and f[0] and os.path.exists(f[0]):
                    self.selected_files.append(f[0])
            elif mode == QFileDialog.ExistingFiles:
                fs = QFileDialog.getOpenFileNames(parent, title, initial_dir,
                        ftext, "", opts)
                if fs and fs[0]:
                    for f in fs[0]:
                        f = unicode(f)
                        if not f:
                            continue
                        if not os.path.exists(f):
                            # QFileDialog for some reason quotes spaces
                            # on linux if there is more than one space in a row
                            f = unquote(f)
                        if f and os.path.exists(f):
                            self.selected_files.append(f)
            else:
                if mode == QFileDialog.Directory:
                    opts |= QFileDialog.ShowDirsOnly
                f = unicode(QFileDialog.getExistingDirectory(parent, title, initial_dir, opts))
                if os.path.exists(f):
                    self.selected_files.append(f)
        if self.selected_files:
            self.selected_files = [unicode(q) for q in self.selected_files]
            saved_loc = self.selected_files[0]
            if os.path.isfile(saved_loc):
                saved_loc = os.path.dirname(saved_loc)
            if not no_save_dir:
                dynamic[self.dialog_name] = saved_loc
        self.accepted = bool(self.selected_files)
示例#17
0
    def __init__(self, parent, dbspec, ids, db):
        import re, cStringIO
        from calibre import prints as info
        from PyQt5.uic import compileUi

        ResizableDialog.__init__(self, parent)
        self.dbspec, self.ids = dbspec, ids

        # Display the number of books we've been passed
        self.count.setText(unicode(self.count.text()).format(len(ids)))

        # Display the last-used title
        self.title.setText(dynamic.get("catalog_last_used_title", _("My Books")))

        self.fmts, self.widgets = [], []

        for plugin in catalog_plugins():
            if plugin.name in config["disabled_plugins"]:
                continue

            name = plugin.name.lower().replace(" ", "_")
            if getattr(plugin, "plugin_path", None) is None:
                try:
                    catalog_widget = importlib.import_module("calibre.gui2.catalog." + name)
                    pw = catalog_widget.PluginWidget()
                    pw.initialize(name, db)
                    pw.ICON = I("forward.png")
                    self.widgets.append(pw)
                    [self.fmts.append([file_type.upper(), pw.sync_enabled, pw]) for file_type in plugin.file_types]
                except ImportError:
                    info("ImportError initializing %s" % name)
                    continue
            else:
                # Load dynamic tab
                form = os.path.join(plugin.resources_path, "%s.ui" % name)
                klass = os.path.join(plugin.resources_path, "%s.py" % name)
                compiled_form = os.path.join(plugin.resources_path, "%s_ui.py" % name)

                if os.path.exists(form) and os.path.exists(klass):
                    # info("Adding widget for user-installed Catalog plugin %s" % plugin.name)

                    # Compile the .ui form provided in plugin.zip
                    if not os.path.exists(compiled_form):
                        # info('\tCompiling form', form)
                        buf = cStringIO.StringIO()
                        compileUi(form, buf)
                        dat = buf.getvalue()
                        dat = re.compile(r'QtGui.QApplication.translate\(.+?,\s+"(.+?)(?<!\\)",.+?\)', re.DOTALL).sub(
                            r'_("\1")', dat
                        )
                        open(compiled_form, "wb").write(dat)

                    # Import the dynamic PluginWidget() from .py file provided in plugin.zip
                    try:
                        sys.path.insert(0, plugin.resources_path)
                        catalog_widget = importlib.import_module(name)
                        pw = catalog_widget.PluginWidget()
                        pw.initialize(name)
                        pw.ICON = I("forward.png")
                        self.widgets.append(pw)
                        [self.fmts.append([file_type.upper(), pw.sync_enabled, pw]) for file_type in plugin.file_types]
                    except ImportError:
                        info("ImportError with %s" % name)
                        continue
                    finally:
                        sys.path.remove(plugin.resources_path)

                else:
                    info("No dynamic tab resources found for %s" % name)

        self.widgets = sorted(self.widgets, cmp=lambda x, y: cmp(x.TITLE, y.TITLE))

        # Generate a sorted list of installed catalog formats/sync_enabled pairs
        fmts = sorted([x[0] for x in self.fmts])

        self.sync_enabled_formats = []
        for fmt in self.fmts:
            if fmt[1]:
                self.sync_enabled_formats.append(fmt[0])

        # Callbacks when format, title changes
        self.format.currentIndexChanged.connect(self.format_changed)
        self.format.currentIndexChanged.connect(self.settings_changed)
        self.title.editingFinished.connect(self.settings_changed)

        # Add the installed catalog format list to the format QComboBox
        self.format.blockSignals(True)
        self.format.addItems(fmts)

        pref = dynamic.get("catalog_preferred_format", "CSV")
        idx = self.format.findText(pref)
        if idx > -1:
            self.format.setCurrentIndex(idx)
        self.format.blockSignals(False)

        if self.sync.isEnabled():
            self.sync.setChecked(dynamic.get("catalog_sync_to_device", True))

        self.format.currentIndexChanged.connect(self.show_plugin_tab)
        self.buttonBox.button(self.buttonBox.Apply).clicked.connect(self.apply)
        self.buttonBox.button(self.buttonBox.Help).clicked.connect(self.help)
        self.show_plugin_tab(None)

        geom = dynamic.get("catalog_window_geom", None)
        if geom is not None:
            self.restoreGeometry(bytes(geom))