Пример #1
0
class DemoDialog(QDialog):

    def __init__(self, gui, icon, do_user_config):
        QDialog.__init__(self, gui)
        self.gui = gui
        self.do_user_config = do_user_config

        self.db = gui.current_db

        self.l = QVBoxLayout()
        self.setLayout(self.l)

        self.setWindowTitle('Wiki Reader')
        self.setWindowIcon(icon)

        self.helpl = QLabel(
            'Enter the URL of a wikipedia article below. '
            'It will be downloaded and converted into an ebook.')
        self.helpl.setWordWrap(True)
        self.l.addWidget(self.helpl)

        self.w = QWidget(self)
        self.sa = QScrollArea(self)
        self.l.addWidget(self.sa)
        self.w.l = QVBoxLayout()
        self.w.setLayout(self.w.l)
        self.sa.setWidget(self.w)
        self.sa.setWidgetResizable(True)

        self.title = Title(self)
        self.w.l.addWidget(self.title)

        self.urls = [URL(self)]
        self.w.l.addWidget(self.urls[0])

        self.add_more_button = QPushButton(
            QIcon(I('plus.png')), 'Add another URL')
        self.l.addWidget(self.add_more_button)

        self.bb = QDialogButtonBox(self)
        self.bb.setStandardButtons(self.bb.Ok | self.bb.Cancel)
        self.bb.accepted.connect(self.accept)
        self.bb.rejected.connect(self.reject)
        self.l.addWidget(self.bb)
        self.book_button = b = self.bb.addButton(
            'Convert a Wiki&Book', self.bb.ActionRole)
        b.clicked.connect(self.wiki_book)

        self.add_more_button.clicked.connect(self.add_more)
        self.finished.connect(self.download)

        self.setMinimumWidth(500)
        self.resize(self.sizeHint())
        self.single_url = None

    def wiki_book(self):
        d = QDialog(self)
        d.l = l = QFormLayout(d)
        l.setFieldGrowthPolicy(l.ExpandingFieldsGrow)
        d.setWindowTitle('Enter WikiBook URL')
        d.la = la = QLabel(
            '<p>You can convert a pre-made WikiBook into a book here. '
            'Simply enter the URL to the WikiBook page. For a list of '
            'WikiBooks, see '
            '<a href="https://en.wikipedia.org/wiki/Special:PrefixIndex/Book:'
            '">here</a>.'
        )
        la.setMinimumWidth(400)
        la.setWordWrap(True)
        la.setOpenExternalLinks(True)
        l.addRow(la)
        d.le = le = QLineEdit(self)
        l.addRow('WikiBook &URL:', le)
        le.setText('https://')
        le.selectAll()
        d.bb = bb = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel, d)
        l.addRow(bb)
        bb.accepted.connect(d.accept), bb.rejected.connect(d.reject)
        if d.exec_() == d.Accepted:
            self.single_url = le.text()
            self.accept()

    def do_resize(self):
        a = self.sizeHint()
        b = self.w.sizeHint()
        h = min(400, b.height())
        self.resize(QSize(a.width(), h + 200))

    def scroll_to_bottom(self):
        v = self.sa.verticalScrollBar()
        v.setValue(v.maximum())

    def add_more(self):
        url = URL(self)
        self.urls.append(url)
        self.w.l.addWidget(url)
        QTimer.singleShot(0, self.do_resize)
        QTimer.singleShot(10, self.scroll_to_bottom)

    def about(self):
        # Get the about text from a file inside the plugin zip file
        # The get_resources function is a builtin function defined for all your
        # plugin code. It loads files from the plugin zip file. It returns
        # the bytes from the specified file.
        #
        # Note that if you are loading more than one file, for performance, you
        # should pass a list of names to get_resources. In this case,
        # get_resources will return a dictionary mapping names to bytes. Names
        # that are not found in the zip file will not be in the returned
        # dictionary.
        text = get_resources('about.txt')
        QMessageBox.about(self, 'About the Wiki Reader', text.decode('utf-8'))

    # def config(self):
    #     self.do_user_config(parent=self)
    # Apply the changes
    #     self.label.setText(prefs['hello_world_msg'])

    def download(self, retcode):
        if retcode != self.Accepted:
            return
        if self.single_url is None:
            urls = [x.url for x in self.urls]
            urls = [x.strip() for x in urls if x.strip()]
            urls = [
                ('http://' + x) if not urlparse(x).scheme else x for x in urls]
        else:
            urls = self.single_url
            self.single_url = None
        args, fmt, temp_files = get_recipe(urls, self.title.title)
        job = self.gui.job_manager.run_job(
            Dispatcher(self.fetched), 'gui_convert', args=args,
            description='Fetch article from Wikipedia')
        job.extra_conversion_args = (temp_files, fmt)
        # don't prompt if all OK
        # if isinstance(urls, list):
        #     info_dialog(
        #         self, 'Downloading',
        #         'Downloading %d article(s) from Wikipedia. When the download'
        #         ' completes the book will be added to your calibre library.'
        #         % len(urls), show=True, show_copy_button=False)
        # else:
        #     info_dialog(
        #         self, 'Downloading',
        #         'Downloading book from Wikipedia. When the download'
        #         ' completes the book will be added to your calibre library.',
        #         show=True, show_copy_button=False)

    def fetched(self, job):
        if job.failed:
            return self.gui.job_exception(job)
        temp_files, fmt = job.extra_conversion_args
        fname = temp_files[0].name
        self.gui.iactions['Add Books']._add_books([fname], False)
        for f in temp_files[1:]:
            try:
                os.remove(f.name)
            except:
                pass
Пример #2
0
class SearchTheInternet(QWidget):

    changed_signal = pyqtSignal()

    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self.sa = QScrollArea(self)
        self.lw = QWidget(self)
        self.l = QVBoxLayout(self.lw)
        self.sa.setWidget(self.lw), self.sa.setWidgetResizable(True)
        self.gl = gl = QVBoxLayout(self)
        self.la = QLabel(_(
            'Add new locations to search for books or authors using the "Search the internet" feature'
            ' of the Content server. The URLs should contain {author} which will be'
            ' replaced by the author name and, for book URLs, {title} which will'
            ' be replaced by the book title.'))
        self.la.setWordWrap(True)
        gl.addWidget(self.la)

        self.h = QHBoxLayout()
        gl.addLayout(self.h)
        self.add_url_button = b = QPushButton(QIcon(I('plus.png')), _('&Add URL'))
        b.clicked.connect(self.add_url)
        self.h.addWidget(b)
        self.export_button = b = QPushButton(_('Export URLs'))
        b.clicked.connect(self.export_urls)
        self.h.addWidget(b)
        self.import_button = b = QPushButton(_('Import URLs'))
        b.clicked.connect(self.import_urls)
        self.h.addWidget(b)
        self.clear_button = b = QPushButton(_('Clear'))
        b.clicked.connect(self.clear)
        self.h.addWidget(b)

        self.h.addStretch(10)
        gl.addWidget(self.sa, stretch=10)
        self.items = []

    def genesis(self):
        self.current_urls = search_the_net_urls() or []

    @property
    def current_urls(self):
        return [item.as_dict for item in self.items if not item.is_empty]

    def append_item(self, item_as_dict):
        self.items.append(URLItem(item_as_dict, self))
        self.l.addWidget(self.items[-1])

    def clear(self):
        [(self.l.removeWidget(w), w.setParent(None), w.deleteLater()) for w in self.items]
        self.items = []
        self.changed_signal.emit()

    @current_urls.setter
    def current_urls(self, val):
        self.clear()
        for entry in val:
            self.append_item(entry)

    def add_url(self):
        self.items.append(URLItem(None, self))
        self.l.addWidget(self.items[-1])
        QTimer.singleShot(100, self.scroll_to_bottom)

    def scroll_to_bottom(self):
        sb = self.sa.verticalScrollBar()
        if sb:
            sb.setValue(sb.maximum())
        self.items[-1].name_widget.setFocus(Qt.OtherFocusReason)

    @property
    def serialized_urls(self):
        return json.dumps(self.current_urls, indent=2)

    def commit(self):
        for item in self.items:
            if not item.validate():
                return False
        cu = self.current_urls
        if cu:
            with lopen(search_the_net_urls.path, 'wb') as f:
                f.write(self.serialized_urls)
        else:
            try:
                os.remove(search_the_net_urls.path)
            except EnvironmentError as err:
                if err.errno != errno.ENOENT:
                    raise
        return True

    def export_urls(self):
        path = choose_save_file(
            self, 'search-net-urls', _('Choose URLs file'),
            filters=[(_('URL files'), ['json'])], initial_filename='search-urls.json')
        if path:
            with lopen(path, 'wb') as f:
                f.write(self.serialized_urls)

    def import_urls(self):
        paths = choose_files(self, 'search-net-urls', _('Choose URLs file'),
            filters=[(_('URL files'), ['json'])], all_files=False, select_only_single_file=True)
        if paths:
            with lopen(paths[0], 'rb') as f:
                items = json.loads(f.read())
                [self.append_item(x) for x in items]
                self.changed_signal.emit()
Пример #3
0
class SearchTheInternet(QWidget):

    changed_signal = pyqtSignal()

    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self.sa = QScrollArea(self)
        self.lw = QWidget(self)
        self.l = QVBoxLayout(self.lw)
        self.sa.setWidget(self.lw), self.sa.setWidgetResizable(True)
        self.gl = gl = QVBoxLayout(self)
        self.la = QLabel(_(
            'Add new locations to search for books or authors using the "Search the internet" feature'
            ' of the Content server. The URLs should contain {author} which will be'
            ' replaced by the author name and, for book URLs, {title} which will'
            ' be replaced by the book title.'))
        self.la.setWordWrap(True)
        gl.addWidget(self.la)

        self.h = QHBoxLayout()
        gl.addLayout(self.h)
        self.add_url_button = b = QPushButton(QIcon(I('plus.png')), _('&Add URL'))
        b.clicked.connect(self.add_url)
        self.h.addWidget(b)
        self.export_button = b = QPushButton(_('Export URLs'))
        b.clicked.connect(self.export_urls)
        self.h.addWidget(b)
        self.import_button = b = QPushButton(_('Import URLs'))
        b.clicked.connect(self.import_urls)
        self.h.addWidget(b)
        self.clear_button = b = QPushButton(_('Clear'))
        b.clicked.connect(self.clear)
        self.h.addWidget(b)

        self.h.addStretch(10)
        gl.addWidget(self.sa, stretch=10)
        self.items = []

    def genesis(self):
        self.current_urls = search_the_net_urls() or []

    @property
    def current_urls(self):
        return [item.as_dict for item in self.items if not item.is_empty]

    def append_item(self, item_as_dict):
        self.items.append(URLItem(item_as_dict, self))
        self.l.addWidget(self.items[-1])

    def clear(self):
        [(self.l.removeWidget(w), w.setParent(None), w.deleteLater()) for w in self.items]
        self.items = []
        self.changed_signal.emit()

    @current_urls.setter
    def current_urls(self, val):
        self.clear()
        for entry in val:
            self.append_item(entry)

    def add_url(self):
        self.items.append(URLItem(None, self))
        self.l.addWidget(self.items[-1])
        QTimer.singleShot(100, self.scroll_to_bottom)

    def scroll_to_bottom(self):
        sb = self.sa.verticalScrollBar()
        if sb:
            sb.setValue(sb.maximum())
        self.items[-1].name_widget.setFocus(Qt.OtherFocusReason)

    @property
    def serialized_urls(self):
        return json.dumps(self.current_urls, indent=2)

    def commit(self):
        for item in self.items:
            if not item.validate():
                return False
        cu = self.current_urls
        if cu:
            with lopen(search_the_net_urls.path, 'wb') as f:
                f.write(self.serialized_urls)
        else:
            try:
                os.remove(search_the_net_urls.path)
            except EnvironmentError as err:
                if err.errno != errno.ENOENT:
                    raise
        return True

    def export_urls(self):
        path = choose_save_file(
            self, 'search-net-urls', _('Choose URLs file'),
            filters=[(_('URL files'), ['json'])], initial_filename='search-urls.json')
        if path:
            with lopen(path, 'wb') as f:
                f.write(self.serialized_urls)

    def import_urls(self):
        paths = choose_files(self, 'search-net-urls', _('Choose URLs file'),
            filters=[(_('URL files'), ['json'])], all_files=False, select_only_single_file=True)
        if paths:
            with lopen(paths[0], 'rb') as f:
                items = json.loads(f.read())
                [self.append_item(x) for x in items]
                self.changed_signal.emit()