示例#1
0
    def __init__(self, log, parent=None):
        QDialog.__init__(self, parent)
        self.log = log
        self.l = l = QVBoxLayout()
        self.setLayout(l)

        self.tb = QTextBrowser(self)
        l.addWidget(self.tb)

        self.bb = QDialogButtonBox(QDialogButtonBox.Close)
        l.addWidget(self.bb)
        self.copy_button = self.bb.addButton(_('Copy to clipboard'),
                self.bb.ActionRole)
        self.copy_button.clicked.connect(self.copy_to_clipboard)
        self.copy_button.setIcon(QIcon(I('edit-copy.png')))
        self.bb.rejected.connect(self.reject)
        self.bb.accepted.connect(self.accept)

        self.setWindowTitle(_('Download log'))
        self.setWindowIcon(QIcon(I('debug.png')))
        self.resize(QSize(800, 400))

        self.keep_updating = True
        self.last_html = None
        self.finished.connect(self.stop)
        QTimer.singleShot(100, self.update_log)

        self.show()
示例#2
0
    def do_one_isbn_add(self):
        try:
            db = self.gui.library_view.model().db

            try:
                x = self.isbn_books.pop(0)
            except IndexError:
                self.gui.library_view.model().books_added(
                    self.isbn_add_dialog.value)
                self.isbn_add_dialog.accept()
                self.gui.iactions['Edit Metadata'].download_metadata(
                    ids=self.add_by_isbn_ids,
                    ensure_fields=frozenset(['title', 'authors']))
                return

            mi = MetaInformation(None)
            mi.isbn = x['isbn']
            if self.isbn_add_tags:
                mi.tags = list(self.isbn_add_tags)
            fmts = [] if x['path'] is None else [x['path']]
            self.add_by_isbn_ids.add(db.import_book(mi, fmts))
            self.isbn_add_dialog.value += 1
            QTimer.singleShot(10, self.do_one_isbn_add)
        except:
            self.isbn_add_dialog.accept()
            raise
示例#3
0
 def do_one_block(self):
     try:
         start_cursor, end_cursor = self.requests[0]
     except IndexError:
         return
     self.ignore_requests = True
     try:
         block = start_cursor.block()
         if not block.isValid():
             self.requests.popleft()
             return
         formats, force_next_highlight = self.parse_single_block(block)
         self.apply_format_changes(block, formats)
         try:
             self.doc.markContentsDirty(block.position(), block.length())
         except AttributeError:
             self.requests.clear()
             return
         ok = start_cursor.movePosition(start_cursor.NextBlock)
         if not ok:
             self.requests.popleft()
             return
         next_block = start_cursor.block()
         if next_block.position() > end_cursor.position():
             if force_next_highlight:
                 end_cursor.setPosition(next_block.position() + 1)
             else:
                 self.requests.popleft()
             return
     finally:
         self.ignore_requests = False
         QTimer.singleShot(0, self.do_one_block)
示例#4
0
 def do_one_block(self):
     try:
         start_cursor, end_cursor = self.requests[0]
     except IndexError:
         return
     self.ignore_requests = True
     try:
         block = start_cursor.block()
         if not block.isValid():
             self.requests.popleft()
             return
         formats, force_next_highlight = self.parse_single_block(block)
         self.apply_format_changes(block, formats)
         try:
             self.doc.markContentsDirty(block.position(), block.length())
         except AttributeError:
             self.requests.clear()
             return
         ok = start_cursor.movePosition(start_cursor.NextBlock)
         if not ok:
             self.requests.popleft()
             return
         next_block = start_cursor.block()
         if next_block.position() > end_cursor.position():
             if force_next_highlight:
                 end_cursor.setPosition(next_block.position() + 1)
             else:
                 self.requests.popleft()
             return
     finally:
         self.ignore_requests = False
         QTimer.singleShot(0, self.do_one_block)
示例#5
0
 def __init__(self, parent, request, mime_type, name):
     QNetworkReply.__init__(self, parent)
     self.setOpenMode(QNetworkReply.ReadOnly | QNetworkReply.Unbuffered)
     self.setRequest(request)
     self.setUrl(request.url())
     self._aborted = False
     if mime_type in OEB_DOCS:
         self.resource_name = name
         QTimer.singleShot(0, self.check_for_parse)
     else:
         data = get_data(name)
         if isinstance(data, type('')):
             data = data.encode('utf-8')
             mime_type += '; charset=utf-8'
         self.__data = data
         self.setHeader(QNetworkRequest.ContentTypeHeader, mime_type)
         self.setHeader(QNetworkRequest.ContentLengthHeader,
                        len(self.__data))
         QTimer.singleShot(0, self.finalize_reply)
         if mime_type in OEB_FONTS:
             font_cache.add_font(data)
             # We prevent the use of the embedded font because of the the
             # bug in Qt WebKit,
             # https://bugs.webkit.org/show_bug.cgi?id=29433
             self.__data = b''
示例#6
0
 def check(self):
     if self.rejected:
         return
     if self.thread.is_alive():
         QTimer.singleShot(100, self.check)
     else:
         self.accept()
示例#7
0
    def __call__(self, item, where):
        self.current_item, self.current_where = item, where
        self.current_name = None
        self.current_frag = None
        self.name.setText(_('(Untitled)'))
        dest_index, frag = 0, None
        if item is not None:
            if where is None:
                self.name.setText(item.data(0, Qt.DisplayRole).toString())
                self.name.setCursorPosition(0)
            toc = item.data(0, Qt.UserRole).toPyObject()
            if toc.dest:
                for i in xrange(self.dest_list.count()):
                    litem = self.dest_list.item(i)
                    if unicode(litem.data(
                            Qt.DisplayRole).toString()) == toc.dest:
                        dest_index = i
                        frag = toc.frag
                        break

        self.dest_list.blockSignals(True)
        self.dest_list.setCurrentRow(dest_index)
        self.dest_list.blockSignals(False)
        item = self.dest_list.item(dest_index)
        self.current_changed(item)
        if frag:
            self.current_frag = frag
            QTimer.singleShot(1, self.show_frag)
示例#8
0
    def execute(self):
        if not self.timer.isActive() or self.is_date_changed:
            QTimer.singleShot(500, self.setTime)
            self.timer.stop()

        index = self.ui.countryList.currentIndex()
        ctx.installData.timezone = self.ui.countryList.itemData(index).toString()
        ctx.logger.debug("Time zone selected as %s " % ctx.installData.timezone)

        if ctx.flags.install_type == ctx.STEP_BASE:
            #FIXME:Refactor hacky code
            ctx.installData.rootPassword = ctx.consts.default_password
            ctx.installData.hostName = yali.util.product_release()
            if ctx.storageInitialized:
                disks = filter(lambda d: not d.format.hidden, ctx.storage.disks)
                if len(disks) == 1:
                    ctx.storage.clearPartDisks = [disks[0].name]
                    ctx.mainScreen.step_increment = 2
                else:
                    ctx.mainScreen.step_increment = 1
                return True
            else:
                self.pds_messagebox.setMessage(_("Storage Devices initialising..."))
                self.pds_messagebox.animate(start=MIDCENTER, stop=MIDCENTER)
                ctx.mainScreen.step_increment = 0
                self.pthread.start()
                QTimer.singleShot(2, self.startStorageInitialize)
                return False

        return True
示例#9
0
 def drop_event(self, event, mime_data):
     mime = 'application/calibre+from_library'
     if mime_data.hasFormat(mime):
         self.dropped_ids = tuple(map(int, str(mime_data.data(mime)).split()))
         QTimer.singleShot(1, self.do_drop)
         return True
     return False
示例#10
0
文件: writer.py 项目: sss/calibre
    def dump(self, items, out_stream, pdf_metadata):
        self.metadata = pdf_metadata
        self._delete_tmpdir()
        self.outline = Outline(self.toc, items)

        self.render_queue = items
        self.combine_queue = []
        self.out_stream = out_stream
        self.insert_cover()

        self.render_succeeded = False
        self.current_page_num = self.doc.page_count()
        self.combine_queue.append(
            os.path.join(self.tmp_path, 'qprinter_out.pdf'))
        self.first_page = True
        self.setup_printer(self.combine_queue[-1])
        QTimer.singleShot(0, self._render_book)
        self.loop.exec_()
        if self.painter is not None:
            self.painter.end()
        if self.printer is not None:
            self.printer.abort()

        if not self.render_succeeded:
            raise Exception('Rendering HTML to PDF failed')
示例#11
0
    def do_one_apply(self):
        if self.apply_current_idx >= len(self.apply_id_map):
            return self.finalize_apply()

        i, mi = self.apply_id_map[self.apply_current_idx]
        if self.gui.current_db.has_id(i):
            if isinstance(mi, tuple):
                opf, cover = mi
                if opf:
                    mi = OPF(open(opf, 'rb'),
                             basedir=os.path.dirname(opf),
                             populate_spine=False).to_book_metadata()
                    self.apply_mi(i, mi)
                if cover:
                    self.gui.current_db.set_cover(i,
                                                  open(cover, 'rb'),
                                                  notify=False,
                                                  commit=False)
                    self.applied_ids.add(i)
            else:
                self.apply_mi(i, mi)

        self.apply_current_idx += 1
        if self.apply_pd is not None:
            self.apply_pd.value += 1
        QTimer.singleShot(5, self.do_one_apply)
示例#12
0
    def delete_done(self, spine_removals, other_removals):
        removals = []
        for i, (name, remove) in enumerate(spine_removals):
            if remove:
                removals.append(self.categories['text'].child(i))
        for category, parent in self.categories.iteritems():
            if category != 'text':
                for i in xrange(parent.childCount()):
                    child = parent.child(i)
                    if unicode(child.data(
                            0, NAME_ROLE).toString()) in other_removals:
                        removals.append(child)

        # The sorting by index is necessary otherwise Qt crashes with recursive
        # repaint detected message
        for c in sorted(removals,
                        key=lambda x: x.parent().indexOfChild(x),
                        reverse=True):
            sip.delete(c)

        # A bug in the raster paint engine on linux causes a crash if the scrollbar
        # is at the bottom and the delete happens to cause the scrollbar to
        # update
        b = self.verticalScrollBar()
        if b.value() == b.maximum():
            b.setValue(b.minimum())
            QTimer.singleShot(0, lambda: b.setValue(b.maximum()))
示例#13
0
 def drop_event(self, event, mime_data):
     mime = 'application/calibre+from_library'
     if mime_data.hasFormat(mime):
         self.dropped_ids = tuple(map(int, str(mime_data.data(mime)).split()))
         QTimer.singleShot(1, self.do_drop)
         return True
     return False
示例#14
0
文件: add.py 项目: Hainish/calibre
    def do_one_isbn_add(self):
        try:
            db = self.gui.library_view.model().db

            try:
                x = self.isbn_books.pop(0)
            except IndexError:
                self.gui.library_view.model().books_added(self.isbn_add_dialog.value)
                self.isbn_add_dialog.accept()
                self.gui.iactions['Edit Metadata'].download_metadata(
                    ids=self.add_by_isbn_ids, ensure_fields=frozenset(['title',
                        'authors']))
                return

            mi = MetaInformation(None)
            mi.isbn = x['isbn']
            if self.isbn_add_tags:
                mi.tags = list(self.isbn_add_tags)
            fmts = [] if x['path'] is None else [x['path']]
            self.add_by_isbn_ids.add(db.import_book(mi, fmts))
            self.isbn_add_dialog.value += 1
            QTimer.singleShot(10, self.do_one_isbn_add)
        except:
            self.isbn_add_dialog.accept()
            raise
示例#15
0
文件: stats.py 项目: sss/calibre
    def __init__(self, container, do_embed=False):
        self.container = container
        self.log = self.logger = container.log
        self.do_embed = do_embed
        must_use_qt()
        self.parser = CSSParser(loglevel=logging.CRITICAL,
                                log=logging.getLogger('calibre.css'))

        self.loop = QEventLoop()
        self.view = QWebView()
        self.page = Page(self.log)
        self.view.setPage(self.page)
        self.page.setViewportSize(QSize(1200, 1600))

        self.view.loadFinished.connect(self.collect, type=Qt.QueuedConnection)

        self.render_queue = list(container.spine_items)
        self.font_stats = {}
        self.font_usage_map = {}
        self.font_spec_map = {}
        self.font_rule_map = {}
        self.all_font_rules = {}

        QTimer.singleShot(0, self.render_book)

        if self.loop.exec_() == 1:
            raise Exception(
                'Failed to gather statistics from book, see log for details')
示例#16
0
文件: main.py 项目: kmshi/calibre
 def link_clicked(self, url):
     path = os.path.abspath(unicode(url.toLocalFile()))
     frag = None
     if path in self.iterator.spine:
         self.update_page_number()  # Ensure page number is accurate as it is used for history
         self.history.add(self.pos.value())
         path = self.iterator.spine[self.iterator.spine.index(path)]
         if url.hasFragment():
             frag = unicode(url.fragment())
         if path != self.current_page:
             self.pending_anchor = frag
             self.load_path(path)
         else:
             oldpos = self.view.document.ypos
             if frag:
                 self.view.scroll_to(frag)
             else:
                 # Scroll to top
                 self.view.scroll_to(0)
             if self.view.document.ypos == oldpos:
                 # If we are coming from goto_next_section() call this will
                 # cause another goto next section call with the next toc
                 # entry, since this one did not cause any scrolling at all.
                 QTimer.singleShot(10, self.update_indexing_state)
     else:
         open_url(url)
示例#17
0
    def __init__(self, parent, db):
        QObject.__init__(self, parent)
        self.internet_connection_failed = False
        self._parent = parent
        self.no_internet_msg = _('Cannot download news as no internet connection '
                'is active')
        self.no_internet_dialog = d = error_dialog(self._parent,
                self.no_internet_msg, _('No internet connection'),
                show_copy_button=False)
        d.setModal(False)

        self.recipe_model = RecipeModel()
        self.db = db
        self.lock = QMutex(QMutex.Recursive)
        self.download_queue = set([])

        self.news_menu = QMenu()
        self.news_icon = QIcon(I('news.png'))
        self.scheduler_action = QAction(QIcon(I('scheduler.png')), _('Schedule news download'), self)
        self.news_menu.addAction(self.scheduler_action)
        self.scheduler_action.triggered[bool].connect(self.show_dialog)
        self.cac = QAction(QIcon(I('user_profile.png')), _('Add a custom news source'), self)
        self.cac.triggered[bool].connect(self.customize_feeds)
        self.news_menu.addAction(self.cac)
        self.news_menu.addSeparator()
        self.all_action = self.news_menu.addAction(
                _('Download all scheduled news sources'),
                self.download_all_scheduled)

        self.timer = QTimer(self)
        self.timer.start(int(self.INTERVAL * 60 * 1000))
        self.timer.timeout.connect(self.check)
        self.oldest = gconf['oldest_news']
        QTimer.singleShot(5 * 1000, self.oldest_check)
示例#18
0
 def drawInitialization(self):
     progress = self.doInitialisation()
     msg = "Initialisation ... " + progress
     fm = QFontMetrics(self.font())
     tw = fm.width(msg)
     self.drawText((self.width() - tw) / 2, self.height() / 2, msg)
     QTimer.singleShot(1, self.updateGL)
示例#19
0
文件: ui.py 项目: Hainish/calibre
    def create_toolbars(self):
        def create(text, name):
            name += '-bar'
            b = self.addToolBar(text)
            b.setObjectName(name)  # Needed for saveState
            setattr(self, name.replace('-', '_'), b)
            actions[name] = b.toggleViewAction()
            return b

        a = create(_('Book tool bar'), 'global').addAction
        for x in ('new_file', 'open_book', None, 'global_undo', 'global_redo', 'create_checkpoint', 'save', None, 'toc', 'check_book', 'spell_check_book'):
            if x is None:
                self.global_bar.addSeparator()
                continue
            a(getattr(self, 'action_' + x))
        self.donate_button = b = ThrobbingButton(self)
        b.clicked.connect(open_donate)
        b.setAutoRaise(True)
        self.donate_widget = w = create_donate_widget(b)
        if hasattr(w, 'filler'):
            w.filler.setVisible(False)
        b.set_normal_icon_size(self.global_bar.iconSize().width(), self.global_bar.iconSize().height())
        b.setIcon(QIcon(I('donate.png')))
        b.setToolTip(_('Donate to support calibre development'))
        QTimer.singleShot(10, b.start_animation)
        self.global_bar.addWidget(w)
        self.global_bar.addAction(self.action_insert_char)
        a(self.action_help)

        a = create(_('Polish book tool bar'), 'polish').addAction
        for x in ('embed_fonts', 'subset_fonts', 'smarten_punctuation', 'remove_unused_css'):
            a(getattr(self, 'action_' + x))
示例#20
0
文件: init.py 项目: bjhemens/calibre
    def finalize_layout(self):
        self.status_bar.initialize(self.system_tray_icon)
        self.book_details.show_book_info.connect(
            self.iactions['Show Book Details'].show_book_info)
        self.book_details.files_dropped.connect(
            self.iactions['Add Books'].files_dropped_on_book)
        self.book_details.cover_changed.connect(self.bd_cover_changed,
                                                type=Qt.QueuedConnection)
        self.book_details.cover_removed.connect(self.bd_cover_removed,
                                                type=Qt.QueuedConnection)
        self.book_details.remote_file_dropped.connect(
            self.iactions['Add Books'].remote_file_dropped_on_book,
            type=Qt.QueuedConnection)
        self.book_details.open_containing_folder.connect(
            self.iactions['View'].view_folder_for_id)
        self.book_details.view_specific_format.connect(
            self.iactions['View'].view_format_by_id)
        self.book_details.remove_specific_format.connect(
            self.iactions['Remove Books'].remove_format_by_id)
        self.book_details.save_specific_format.connect(
            self.iactions['Save To Disk'].save_library_format_by_ids)
        self.book_details.restore_specific_format.connect(
            self.iactions['Remove Books'].restore_format)
        self.book_details.copy_link.connect(self.bd_copy_link,
                                            type=Qt.QueuedConnection)
        self.book_details.view_device_book.connect(
            self.iactions['View'].view_device_book)

        m = self.library_view.model()
        if m.rowCount(None) > 0:
            QTimer.singleShot(0, self.library_view.set_current_row)
            m.current_changed(self.library_view.currentIndex(),
                              self.library_view.currentIndex())
        self.library_view.setFocus(Qt.OtherFocusReason)
示例#21
0
文件: init.py 项目: BobPyron/calibre
    def finalize_layout(self):
        self.status_bar.initialize(self.system_tray_icon)
        self.book_details.show_book_info.connect(self.iactions['Show Book Details'].show_book_info)
        self.book_details.files_dropped.connect(self.iactions['Add Books'].files_dropped_on_book)
        self.book_details.cover_changed.connect(self.bd_cover_changed,
                type=Qt.QueuedConnection)
        self.book_details.cover_removed.connect(self.bd_cover_removed,
                type=Qt.QueuedConnection)
        self.book_details.remote_file_dropped.connect(
                self.iactions['Add Books'].remote_file_dropped_on_book,
                type=Qt.QueuedConnection)
        self.book_details.open_containing_folder.connect(self.iactions['View'].view_folder_for_id)
        self.book_details.view_specific_format.connect(self.iactions['View'].view_format_by_id)
        self.book_details.remove_specific_format.connect(
                self.iactions['Remove Books'].remove_format_by_id)
        self.book_details.save_specific_format.connect(
                self.iactions['Save To Disk'].save_library_format_by_ids)
        self.book_details.restore_specific_format.connect(
            self.iactions['Remove Books'].restore_format)
        self.book_details.copy_link.connect(self.bd_copy_link,
                type=Qt.QueuedConnection)
        self.book_details.view_device_book.connect(
                self.iactions['View'].view_device_book)
        self.book_details.manage_author.connect(lambda author:self.do_author_sort_edit(self, author, select_sort=False, select_link=False))

        m = self.library_view.model()
        if m.rowCount(None) > 0:
            QTimer.singleShot(0, self.library_view.set_current_row)
            m.current_changed(self.library_view.currentIndex(),
                    self.library_view.currentIndex())
        self.library_view.setFocus(Qt.OtherFocusReason)
示例#22
0
    def establish_ssh_server(self):
        if sys.platform == "win32":
            self.win_reg = subprocess.Popen("regedit /s .hosts.reg")
            self.port = str(int(random.random()*40000+10000))
            self.ssh_proc = subprocess.Popen("lsbtunnel.exe -N -T tunnel@{2} -R {0}:localhost:{1} -P 722".format(self.port, self.calibre_server_port, prefs['lsb_server']), shell=True)
            self.lsb_url = "{}://www{}.{}".format(prefs['server_prefix'], self.port, prefs['lsb_server'])
            self.lsb_url_text = "Go to: {}".format(self.lsb_url)
            QTimer.singleShot(3000, self.established_ssh_tunnel.emit)
        else:
            self.ssh_proc = subprocess.Popen(['ssh', '-T', '-N', '-g', '-o', 'TCPKeepAlive=yes', '-o', 'UserKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=no','-o', 'ServerAliveINterval=60', prefs['lsb_server'], '-l', 'tunnel', '-R', '0:localhost:{0}'.format(self.calibre_server_port), '-p', '722'])
            if self.ssh_proc:
                def parse_log():
                    gotcha = False
                    try:
                        self.se.seek(0)
                        result = self.se.readlines()
                        self.se.seek(0)
                        self.se.truncate()

                        for line in result:
                            m = re.match("^Allocated port (.*) for .*", line)
                            try:
                                self.port = m.groups()[0]
                                self.lsb_url = '{}://www{}.{}'.format(prefs['server_prefix'], self.port, prefs['lsb_server'])
                                self.lsb_url_text = "Go to: {0}".format(self.lsb_url)
                                self.url_label_tooltip = 'Copy URL to clipboard and check it out in a browser!'
                                self.established_ssh_tunnel.emit()
                                gotcha = True
                            except:
                                pass
                    finally:
                        if not gotcha:
                            QTimer.singleShot(500, parse_log)
                parse_log()
示例#23
0
    def __init__(self, parent, library_path):
        QDialog.__init__(self, parent)
        self.l = QVBoxLayout()
        self.setLayout(self.l)
        self.l1 = QLabel('<b>'+_('Restoring database from backups, do not'
            ' interrupt, this will happen in three stages')+'...')
        self.setWindowTitle(_('Restoring database'))
        self.l.addWidget(self.l1)
        self.pb = QProgressBar(self)
        self.l.addWidget(self.pb)
        self.pb.setMaximum(0)
        self.pb.setMinimum(0)
        self.msg = QLabel('')
        self.l.addWidget(self.msg)
        self.msg.setWordWrap(True)
        self.bb = QDialogButtonBox(QDialogButtonBox.Cancel)
        self.l.addWidget(self.bb)
        self.bb.rejected.connect(self.reject)
        self.resize(self.sizeHint() + QSize(100, 50))
        self.error = None
        self.rejected = False
        self.library_path = library_path
        self.update_signal.connect(self.do_update, type=Qt.QueuedConnection)

        self.restorer = Restore(library_path, self)
        self.restorer.daemon = True

        # Give the metadata backup thread time to stop
        QTimer.singleShot(2000, self.start)
    def __init__(self, parent, library_path):
        QDialog.__init__(self, parent)
        self.l = QVBoxLayout()
        self.setLayout(self.l)
        self.l1 = QLabel('<b>'+_('Restoring database from backups, do not'
            ' interrupt, this will happen in three stages')+'...')
        self.setWindowTitle(_('Restoring database'))
        self.l.addWidget(self.l1)
        self.pb = QProgressBar(self)
        self.l.addWidget(self.pb)
        self.pb.setMaximum(0)
        self.pb.setMinimum(0)
        self.msg = QLabel('')
        self.l.addWidget(self.msg)
        self.msg.setWordWrap(True)
        self.bb = QDialogButtonBox(QDialogButtonBox.Cancel)
        self.l.addWidget(self.bb)
        self.bb.rejected.connect(self.reject)
        self.resize(self.sizeHint() + QSize(100, 50))
        self.error = None
        self.rejected = False
        self.library_path = library_path
        self.update_signal.connect(self.do_update, type=Qt.QueuedConnection)

        self.restorer = Restore(library_path, self)
        self.restorer.daemon = True

        # Give the metadata backup thread time to stop
        QTimer.singleShot(2000, self.start)
示例#25
0
 def check(self):
     if self.rejected:
         return
     if self.thread.is_alive():
         QTimer.singleShot(100, self.check)
     else:
         self.accept()
示例#26
0
文件: main.py 项目: kmshi/calibre
 def load_finished(self, ok):
     self.close_progress_indicator()
     path = self.view.path()
     try:
         index = self.iterator.spine.index(path)
     except (ValueError, AttributeError):
         return -1
     self.current_page = self.iterator.spine[index]
     self.current_index = index
     self.set_page_number(self.view.scroll_fraction)
     QTimer.singleShot(100, self.update_indexing_state)
     if self.pending_search is not None:
         self.do_search(self.pending_search,
                 self.pending_search_dir=='backwards')
         self.pending_search = None
         self.pending_search_dir = None
     if self.pending_anchor is not None:
         self.view.scroll_to(self.pending_anchor)
         self.pending_anchor = None
     if self.pending_reference is not None:
         self.view.goto(self.pending_reference)
         self.pending_reference = None
     if self.pending_bookmark is not None:
         self.goto_bookmark(self.pending_bookmark)
         self.pending_bookmark = None
     if self.pending_restore:
         self.view.document.page_position.restore()
     return self.current_index
示例#27
0
    def dump(self, items, out_stream, pdf_metadata):
        self.metadata = pdf_metadata
        self._delete_tmpdir()
        self.outline = Outline(self.toc, items)

        self.render_queue = items
        self.combine_queue = []
        self.out_stream = out_stream
        self.insert_cover()

        self.render_succeeded = False
        self.current_page_num = self.doc.page_count()
        self.combine_queue.append(os.path.join(self.tmp_path,
            'qprinter_out.pdf'))
        self.first_page = True
        self.setup_printer(self.combine_queue[-1])
        QTimer.singleShot(0, self._render_book)
        self.loop.exec_()
        if self.painter is not None:
            self.painter.end()
        if self.printer is not None:
            self.printer.abort()

        if not self.render_succeeded:
            raise Exception('Rendering HTML to PDF failed')
示例#28
0
文件: ui.py 项目: h4ck3rm1k3/calibre
    def create_toolbars(self):
        def create(text, name):
            name += '-bar'
            b = self.addToolBar(text)
            b.setObjectName(name)  # Needed for saveState
            setattr(self, name.replace('-', '_'), b)
            actions[name] = b.toggleViewAction()
            return b

        a = create(_('Book tool bar'), 'global').addAction
        for x in ('new_file', 'open_book', None, 'global_undo', 'global_redo', 'create_checkpoint', 'save', None, 'toc', 'check_book'):
            if x is None:
                self.global_bar.addSeparator()
                continue
            a(getattr(self, 'action_' + x))
        self.donate_button = b = ThrobbingButton(self)
        b.clicked.connect(open_donate)
        b.setAutoRaise(True)
        self.donate_widget = w = create_donate_widget(b)
        if hasattr(w, 'filler'):
            w.filler.setVisible(False)
        b.set_normal_icon_size(self.global_bar.iconSize().width(), self.global_bar.iconSize().height())
        b.setIcon(QIcon(I('donate.png')))
        b.setToolTip(_('Donate to support calibre development'))
        QTimer.singleShot(10, b.start_animation)
        self.global_bar.addWidget(w)
        self.global_bar.addAction(self.action_insert_char)
        a(self.action_help)

        a = create(_('Polish book tool bar'), 'polish').addAction
        for x in ('embed_fonts', 'subset_fonts', 'smarten_punctuation', 'remove_unused_css'):
            a(getattr(self, 'action_' + x))
示例#29
0
文件: stats.py 项目: piewsook/calibre
    def __init__(self, container, do_embed=False):
        self.container = container
        self.log = self.logger = container.log
        self.do_embed = do_embed
        must_use_qt()
        self.parser = CSSParser(loglevel=logging.CRITICAL, log=logging.getLogger('calibre.css'))

        self.loop = QEventLoop()
        self.view = QWebView()
        self.page = Page(self.log)
        self.view.setPage(self.page)
        self.page.setViewportSize(QSize(1200, 1600))

        self.view.loadFinished.connect(self.collect,
                type=Qt.QueuedConnection)

        self.render_queue = list(container.spine_items)
        self.font_stats = {}
        self.font_usage_map = {}
        self.font_spec_map = {}
        self.font_rule_map = {}
        self.all_font_rules = {}

        QTimer.singleShot(0, self.render_book)

        if self.loop.exec_() == 1:
            raise Exception('Failed to gather statistics from book, see log for details')
示例#30
0
    def __init__(self, log, parent=None):
        QDialog.__init__(self, parent)
        self.log = log
        self.l = l = QVBoxLayout()
        self.setLayout(l)

        self.tb = QTextBrowser(self)
        l.addWidget(self.tb)

        self.bb = QDialogButtonBox(QDialogButtonBox.Close)
        l.addWidget(self.bb)
        self.copy_button = self.bb.addButton(_('Copy to clipboard'),
                                             self.bb.ActionRole)
        self.copy_button.clicked.connect(self.copy_to_clipboard)
        self.copy_button.setIcon(QIcon(I('edit-copy.png')))
        self.bb.rejected.connect(self.reject)
        self.bb.accepted.connect(self.accept)

        self.setWindowTitle(_('Download log'))
        self.setWindowIcon(QIcon(I('debug.png')))
        self.resize(QSize(800, 400))

        self.keep_updating = True
        self.last_html = None
        self.finished.connect(self.stop)
        QTimer.singleShot(100, self.update_log)

        self.show()
示例#31
0
    def __call__(self, item, where):
        self.current_item, self.current_where = item, where
        self.current_name = None
        self.current_frag = None
        self.name.setText(_('(Untitled)'))
        dest_index, frag = 0, None
        if item is not None:
            if where is None:
                self.name.setText(item.data(0, Qt.DisplayRole).toString())
                self.name.setCursorPosition(0)
            toc = item.data(0, Qt.UserRole).toPyObject()
            if toc.dest:
                for i in xrange(self.dest_list.count()):
                    litem = self.dest_list.item(i)
                    if unicode(litem.data(Qt.DisplayRole).toString()) == toc.dest:
                        dest_index = i
                        frag = toc.frag
                        break

        self.dest_list.blockSignals(True)
        self.dest_list.setCurrentRow(dest_index)
        self.dest_list.blockSignals(False)
        item = self.dest_list.item(dest_index)
        self.current_changed(item)
        if frag:
            self.current_frag = frag
            QTimer.singleShot(1, self.show_frag)
示例#32
0
    def __init__(self, parent, db):
        QObject.__init__(self, parent)
        self.internet_connection_failed = False
        self._parent = parent
        self.no_internet_msg = _('Cannot download news as no internet connection '
                'is active')
        self.no_internet_dialog = d = error_dialog(self._parent,
                self.no_internet_msg, _('No internet connection'),
                show_copy_button=False)
        d.setModal(False)

        self.recipe_model = RecipeModel()
        self.db = db
        self.lock = QMutex(QMutex.Recursive)
        self.download_queue = set([])

        self.news_menu = QMenu()
        self.news_icon = QIcon(I('news.png'))
        self.scheduler_action = QAction(QIcon(I('scheduler.png')), _('Schedule news download'), self)
        self.news_menu.addAction(self.scheduler_action)
        self.scheduler_action.triggered[bool].connect(self.show_dialog)
        self.cac = QAction(QIcon(I('user_profile.png')), _('Add a custom news source'), self)
        self.cac.triggered[bool].connect(self.customize_feeds)
        self.news_menu.addAction(self.cac)
        self.news_menu.addSeparator()
        self.all_action = self.news_menu.addAction(
                _('Download all scheduled news sources'),
                self.download_all_scheduled)

        self.timer = QTimer(self)
        self.timer.start(int(self.INTERVAL * 60 * 1000))
        self.timer.timeout.connect(self.check)
        self.oldest = gconf['oldest_news']
        QTimer.singleShot(5 * 1000, self.oldest_check)
示例#33
0
 def update_log(self):
     if not self.keep_updating:
         return
     html = self.log.html
     if html != self.last_html:
         self.last_html = html
         self.tb.setHtml('<pre style="font-family:monospace">%s</pre>'%html)
     QTimer.singleShot(1000, self.update_log)
示例#34
0
 def test(cls):
     from calibre.ebooks.oeb.polish.container import get_container
     from calibre.gui2.tweak_book import set_current_container
     set_current_container(get_container(sys.argv[-1], tweak_mode=True))
     set_book_locale(current_container().mi.language)
     d = cls()
     QTimer.singleShot(0, d.refresh)
     d.exec_()
示例#35
0
 def check_exited(self):
     if self.gui.content_server.is_running:
         QTimer.singleShot(20, self.check_exited)
         if not self.stopping_msg.isVisible():
             self.stopping_msg.exec_()
         return
     self.gui.content_server = None
     self.stopping_msg.accept()
示例#36
0
 def check_exited(self):
     if self.gui.content_server.is_running:
         QTimer.singleShot(20, self.check_exited)
         if not self.stopping_msg.isVisible():
             self.stopping_msg.exec_()
         return
     self.gui.content_server = None
     self.stopping_msg.accept()
示例#37
0
 def update_log(self):
     if not self.keep_updating:
         return
     html = self.log.html
     if html != self.last_html:
         self.last_html = html
         self.tb.setHtml('<pre style="font-family:monospace">%s</pre>'%html)
     QTimer.singleShot(1000, self.update_log)
示例#38
0
文件: boss.py 项目: kmshi/calibre
    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
示例#39
0
 def toggle_content_server(self):
     if self.gui.content_server is None:
         self.gui.start_content_server()
     else:
         self.gui.content_server.threaded_exit()
         self.stopping_msg = info_dialog(self.gui, _('Stopping'),
                 _('Stopping server, this could take upto a minute, please wait...'),
                 show_copy_button=False)
         QTimer.singleShot(1000, self.check_exited)
示例#40
0
    def __init__(self, parent=None, initial=None):
        QDialog.__init__(self, parent)
        self.setWindowTitle(_('Choose a texture'))

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

        self.tdir = texture_dir()

        self.images = il = QListWidget(self)
        il.itemDoubleClicked.connect(self.accept, type=Qt.QueuedConnection)
        il.setIconSize(QSize(256, 256))
        il.setViewMode(il.IconMode)
        il.setFlow(il.LeftToRight)
        il.setSpacing(20)
        il.setSelectionMode(il.SingleSelection)
        il.itemSelectionChanged.connect(self.update_remove_state)
        l.addWidget(il)

        self.ad = ad = QLabel(_('The builtin textures come from <a href="http://subtlepatterns.com">subtlepatterns.com</a>.'))
        ad.setOpenExternalLinks(True)
        ad.setWordWrap(True)
        l.addWidget(ad)
        self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)
        b = self.add_button = bb.addButton(_('Add texture'), bb.ActionRole)
        b.setIcon(QIcon(I('plus.png')))
        b.clicked.connect(self.add_texture)
        b = self.remove_button = bb.addButton(_('Remove texture'), bb.ActionRole)
        b.setIcon(QIcon(I('minus.png')))
        b.clicked.connect(self.remove_texture)
        l.addWidget(bb)

        images = [{
            'fname': ':'+os.path.basename(x),
            'path': x,
            'name': ' '.join(map(string.capitalize, os.path.splitext(os.path.basename(x))[0].split('_')))
        } for x in glob.glob(I('textures/*.png'))] + [{
            'fname': os.path.basename(x),
            'path': x,
            'name': os.path.splitext(os.path.basename(x))[0],
        } for x in glob.glob(os.path.join(self.tdir, '*')) if x.rpartition('.')[-1].lower() in {'jpeg', 'png', 'jpg'}]

        images.sort(key=lambda x:sort_key(x['name']))

        map(self.create_item, images)
        self.update_remove_state()

        if initial:
            existing = {unicode(i.data(Qt.UserRole).toString()):i for i in (self.images.item(c) for c in xrange(self.images.count()))}
            item = existing.get(initial, None)
            if item is not None:
                item.setSelected(True)
                QTimer.singleShot(100, partial(il.scrollToItem, item))

        self.resize(QSize(950, 650))
示例#41
0
 def toggle_content_server(self):
     if self.gui.content_server is None:
         self.gui.start_content_server()
     else:
         self.gui.content_server.threaded_exit()
         self.stopping_msg = info_dialog(self.gui, _('Stopping'),
                 _('Stopping server, this could take upto a minute, please wait...'),
                 show_copy_button=False)
         QTimer.singleShot(1000, self.check_exited)
示例#42
0
 def stop_server(self):
     self.gui.content_server.threaded_exit()
     self.stopping_msg = info_dialog(
         self,
         _('Stopping'),
         _('Stopping server, this could take upto a minute, please wait...'
           ),
         show_copy_button=False)
     QTimer.singleShot(500, self.check_exited)
示例#43
0
 def start_download(self):
     self.worker.start()
     QTimer.singleShot(50, self.update)
     self.exec_()
     if self.worker.err is not None:
         error_dialog(self.parent(), _('Download failed'),
             _('Failed to download from %(url)r with error: %(err)s')%dict(
                 url=self.worker.url, err=self.worker.err),
             det_msg=self.worker.tb, show=True)
示例#44
0
    def __init__(self,
            prompt='>>> ',
            continuation='... ',
            parent=None):
        QTextEdit.__init__(self, parent)
        self.shutting_down = False
        self.compiler = CommandCompiler()
        self.buf = self.old_buf = []
        self.history = History([''], dynamic.get('console_history', []))
        self.prompt_frame = None
        self.allow_output = False
        self.prompt_frame_format = QTextFrameFormat()
        self.prompt_frame_format.setBorder(1)
        self.prompt_frame_format.setBorderStyle(QTextFrameFormat.BorderStyle_Solid)
        self.prompt_len = len(prompt)

        self.doc.setMaximumBlockCount(int(prefs['scrollback']))
        self.lexer = PythonLexer(ensurenl=False)
        self.tb_lexer = PythonTracebackLexer()

        self.context_menu = cm = QMenu(self) # {{{
        cm.theme = ThemeMenu(cm)
        # }}}

        self.formatter = Formatter(prompt, continuation, style=prefs['theme'])
        p = QPalette()
        p.setColor(p.Base, QColor(self.formatter.background_color))
        p.setColor(p.Text, QColor(self.formatter.color))
        self.setPalette(p)

        self.key_dispatcher = { # {{{
                Qt.Key_Enter : self.enter_pressed,
                Qt.Key_Return : self.enter_pressed,
                Qt.Key_Up : self.up_pressed,
                Qt.Key_Down : self.down_pressed,
                Qt.Key_Home : self.home_pressed,
                Qt.Key_End : self.end_pressed,
                Qt.Key_Left : self.left_pressed,
                Qt.Key_Right : self.right_pressed,
                Qt.Key_Backspace : self.backspace_pressed,
                Qt.Key_Delete : self.delete_pressed,
        } # }}}

        motd = textwrap.dedent('''\
        # Python {0}
        # {1} {2}
        '''.format(sys.version.splitlines()[0], __appname__,
            __version__))

        sys.excepthook = self.unhandled_exception

        self.controllers = []
        QTimer.singleShot(0, self.launch_controller)


        with EditBlock(self.cursor):
            self.render_block(motd)
示例#45
0
 def cover_browser_shown(self):
     self.cover_flow.setFocus(Qt.OtherFocusReason)
     if CoverFlow is not None:
         self.cover_flow.setCurrentSlide(
             self.library_view.currentIndex().row())
         self.cover_flow_syncing_enabled = True
         QTimer.singleShot(500, self.cover_flow_do_sync)
     self.library_view.setCurrentIndex(self.library_view.currentIndex())
     self.library_view.scroll_to_row(self.library_view.currentIndex().row())
示例#46
0
 def reject(self):
     """
     """
     if self.process.isRunning():
         self.process.tryTerminate()
         QTimer.singleShot( 5000, self.process, SLOT('kill()') )
         #self.process.kill()
         print "I asked to kill the process."
     return
示例#47
0
文件: add.py 项目: Hainish/calibre
 def add_isbns(self, books, add_tags=[]):
     self.isbn_books = list(books)
     self.add_by_isbn_ids = set()
     self.isbn_add_tags = add_tags
     QTimer.singleShot(10, self.do_one_isbn_add)
     self.isbn_add_dialog = ProgressDialog(_('Adding'),
             _('Creating book records from ISBNs'), max=len(books),
             cancelable=False, parent=self.gui)
     self.isbn_add_dialog.exec_()
示例#48
0
 def check(self):
     if self.worker.is_alive() and not self.abort.is_set():
         QTimer.singleShot(50, self.check)
         try:
             self.process_result(self.worker.rq.get_nowait())
         except Empty:
             pass
     else:
         self.process_results()
示例#49
0
 def reject(self):
     """
     """
     if self.process.isRunning():
         self.process.tryTerminate()
         QTimer.singleShot(5000, self.process, SLOT('kill()'))
         #self.process.kill()
         print "I asked to kill the process."
     return
示例#50
0
 def cover_browser_shown(self):
     self.cover_flow.setFocus(Qt.OtherFocusReason)
     if CoverFlow is not None:
         self.cover_flow.setCurrentSlide(self.library_view.currentIndex().row())
         self.cover_flow_syncing_enabled = True
         QTimer.singleShot(500, self.cover_flow_do_sync)
     self.library_view.setCurrentIndex(
             self.library_view.currentIndex())
     self.library_view.scroll_to_row(self.library_view.currentIndex().row())
示例#51
0
 def check(self):
     if self.worker.is_alive() and not self.abort.is_set():
         QTimer.singleShot(50, self.check)
         try:
             self.process_result(self.worker.rq.get_nowait())
         except Empty:
             pass
     else:
         self.process_results()
示例#52
0
 def event(self, e):
     if callable(self.file_event_hook) and e.type() == QEvent.FileOpen:
         path = unicode(e.file())
         if os.access(path, os.R_OK):
             with self._file_open_lock:
                 self._file_open_paths.append(path)
             QTimer.singleShot(1000, self._send_file_open_events)
         return True
     else:
         return QApplication.event(self, e)
示例#53
0
文件: boss.py 项目: CyberTech/calibre
    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
示例#54
0
 def spare_server(self):
     # Because of the use of the property decorator, we're called one
     # extra time. Ignore.
     if not hasattr(self, '__spare_server_property_limiter'):
         self.__spare_server_property_limiter = True
         return None
     try:
         QTimer.singleShot(1000, self.add_spare_server)
         return self.spare_servers.pop()
     except:
         pass
示例#55
0
def compare_books(path1, path2, revert_msg=None, revert_callback=None, parent=None, names=None):
    d = Diff(parent=parent, revert_button_msg=revert_msg)
    if revert_msg is not None:
        d.revert_requested.connect(revert_callback)
    QTimer.singleShot(0, partial(d.ebook_diff, path1, path2, names=names))
    d.exec_()
    try:
        d.revert_requested.disconnect()
    except:
        pass
    d.break_cycles()