Exemplo n.º 1
0
 def load_finished(self, ok, data):
     open_at, self.pending_open_at = self.pending_open_at, None
     if not ok:
         self.setWindowTitle(self.base_window_title)
         tb = data['tb']
         last_line = tuple(tb.strip().splitlines())[-1]
         if last_line.startswith('calibre.ebooks.DRMError'):
             DRMErrorMessage(self).exec_()
         else:
             error_dialog(self, _('Loading book failed'), _(
                 'Failed to open the book at {0}. Click "Show details" for more info.').format(data['pathtoebook']),
                 det_msg=data['tb'], show=True)
         self.loading_overlay.hide()
         self.web_view.show_home_page()
         return
     set_book_path(data['base'], data['pathtoebook'])
     self.current_book_data = data
     self.current_book_data['annotations_map'] = defaultdict(list)
     self.current_book_data['annotations_path_key'] = path_key(data['pathtoebook']) + '.json'
     self.load_book_data()
     self.update_window_title()
     initial_cfi = self.initial_cfi_for_current_book()
     initial_toc_node = None
     if open_at:
         if open_at.startswith('toc:'):
             initial_toc_node = self.toc_model.node_id_for_text(open_at[len('toc:'):])
         elif open_at.startswith('epubcfi(/'):
             initial_cfi = open_at
     self.web_view.start_book_load(initial_cfi=initial_cfi, initial_toc_node=initial_toc_node)
Exemplo n.º 2
0
 def load_finished(self, ok, data):
     cbd = self.calibre_book_data_for_first_book
     self.calibre_book_data_for_first_book = None
     if self.shutting_down:
         return
     open_at, self.pending_open_at = self.pending_open_at, None
     self.web_view.clear_caches()
     if not ok:
         self.actions_toolbar.update_action_state(False)
         self.setWindowTitle(self.base_window_title)
         tb = as_unicode(data['tb'].strip(), errors='replace')
         tb = re.split(r'^calibre\.gui2\.viewer\.convert_book\.ConversionFailure:\s*', tb, maxsplit=1, flags=re.M)[-1]
         last_line = tuple(tb.strip().splitlines())[-1]
         if last_line.startswith('calibre.ebooks.DRMError'):
             DRMErrorMessage(self).exec_()
         else:
             error_dialog(self, _('Loading book failed'), _(
                 'Failed to open the book at {0}. Click "Show details" for more info.').format(data['pathtoebook']),
                 det_msg=tb, show=True)
         self.loading_overlay.hide()
         self.web_view.show_home_page()
         return
     try:
         set_book_path(data['base'], data['pathtoebook'])
     except Exception:
         if data['reloaded']:
             raise
         self.load_ebook(data['pathtoebook'], open_at=data['open_at'], reload_book=True)
         return
     self.current_book_data = data
     get_current_book_data(self.current_book_data)
     self.current_book_data['annotations_map'] = defaultdict(list)
     self.current_book_data['annotations_path_key'] = path_key(data['pathtoebook']) + '.json'
     self.load_book_data(cbd)
     self.update_window_title()
     initial_cfi = self.initial_cfi_for_current_book()
     initial_position = {'type': 'cfi', 'data': initial_cfi} if initial_cfi else None
     if open_at:
         if open_at.startswith('toc:'):
             initial_toc_node = self.toc_model.node_id_for_text(open_at[len('toc:'):])
             initial_position = {'type': 'toc', 'data': initial_toc_node}
         elif open_at.startswith('toc-href:'):
             initial_toc_node = self.toc_model.node_id_for_href(open_at[len('toc-href:'):], exact=True)
             initial_position = {'type': 'toc', 'data': initial_toc_node}
         elif open_at.startswith('toc-href-contains:'):
             initial_toc_node = self.toc_model.node_id_for_href(open_at[len('toc-href-contains:'):], exact=False)
             initial_position = {'type': 'toc', 'data': initial_toc_node}
         elif open_at.startswith('epubcfi(/'):
             initial_position = {'type': 'cfi', 'data': open_at}
         elif open_at.startswith('ref:'):
             initial_position = {'type': 'ref', 'data': open_at[len('ref:'):]}
         elif is_float(open_at):
             initial_position = {'type': 'bookpos', 'data': float(open_at)}
     highlights = self.current_book_data['annotations_map']['highlight']
     self.highlights_widget.load(highlights)
     self.web_view.start_book_load(initial_position=initial_position, highlights=highlights, current_book_data=self.current_book_data)
     performance_monitor('webview loading requested')
Exemplo n.º 3
0
 def load_finished(self, ok, data):
     if self.shutting_down:
         return
     open_at, self.pending_open_at = self.pending_open_at, None
     self.web_view.clear_caches()
     if not ok:
         self.setWindowTitle(self.base_window_title)
         tb = data['tb'].strip()
         tb = re.split(r'^calibre\.gui2\.viewer\.convert_book\.ConversionFailure:\s*', tb, maxsplit=1, flags=re.M)[-1]
         last_line = tuple(tb.strip().splitlines())[-1]
         if last_line.startswith('calibre.ebooks.DRMError'):
             DRMErrorMessage(self).exec_()
         else:
             error_dialog(self, _('Loading book failed'), _(
                 'Failed to open the book at {0}. Click "Show details" for more info.').format(data['pathtoebook']),
                 det_msg=tb, show=True)
         self.loading_overlay.hide()
         self.web_view.show_home_page()
         return
     try:
         set_book_path(data['base'], data['pathtoebook'])
     except Exception:
         if data['reloaded']:
             raise
         self.load_ebook(data['pathtoebook'], open_at=data['open_at'], reload_book=True)
         return
     self.current_book_data = data
     self.current_book_data['annotations_map'] = defaultdict(list)
     self.current_book_data['annotations_path_key'] = path_key(data['pathtoebook']) + '.json'
     self.load_book_data()
     self.update_window_title()
     initial_cfi = self.initial_cfi_for_current_book()
     initial_toc_node = initial_bookpos = None
     if open_at:
         if open_at.startswith('toc:'):
             initial_toc_node = self.toc_model.node_id_for_text(open_at[len('toc:'):])
         elif open_at.startswith('epubcfi(/'):
             initial_cfi = open_at
         elif is_float(open_at):
             initial_bookpos = float(open_at)
     self.web_view.start_book_load(initial_cfi=initial_cfi, initial_toc_node=initial_toc_node, initial_bookpos=initial_bookpos)
Exemplo n.º 4
0
    def book_opened(self, job):
        ef = getattr(self, '_edit_file_on_open', None)
        cn = getattr(self, '_clear_notify_data', True)
        self._edit_file_on_open = None

        if job.traceback is not None:
            if 'DRMError:' in job.traceback:
                from calibre.gui2.dialogs.drm_error import DRMErrorMessage
                return DRMErrorMessage(self.gui).exec_()
            return error_dialog(
                self.gui,
                _('Failed to open book'),
                _('Failed to open book, click Show details for more information.'
                  ),
                det_msg=job.traceback,
                show=True)
        if cn:
            self.save_manager.clear_notify_data()
        parse_worker.clear()
        container = job.result
        set_current_container(container)
        with BusyCursor():
            self.current_metadata = self.gui.current_metadata = container.mi
            self.global_undo.open_book(container)
            self.gui.update_window_title()
            self.gui.file_list.current_edited_name = None
            self.gui.file_list.build(container, preserve_state=False)
            self.gui.action_save.setEnabled(False)
            self.update_global_history_actions()
            recent_books = list(tprefs.get('recent-books', []))
            path = container.path_to_ebook
            if path in recent_books:
                recent_books.remove(path)
            recent_books.insert(0, path)
            tprefs['recent-books'] = recent_books[:10]
            self.gui.update_recent_books()
            if ef:
                self.gui.file_list.request_edit(ef)
            self.gui.toc_view.update_if_visible()
Exemplo n.º 5
0
    def job_exception(self,
                      job,
                      dialog_title=_('Conversion Error'),
                      retry_func=None):
        if not hasattr(self, '_modeless_dialogs'):
            self._modeless_dialogs = []
        minz = self.is_minimized_to_tray
        if self.isVisible():
            for x in list(self._modeless_dialogs):
                if not x.isVisible():
                    self._modeless_dialogs.remove(x)
        try:
            if 'calibre.ebooks.DRMError' in job.details:
                if not minz:
                    from calibre.gui2.dialogs.drm_error import DRMErrorMessage
                    d = DRMErrorMessage(
                        self,
                        _('Cannot convert') + ' ' +
                        job.description.split(':')[-1].partition('(')[-1][:-1])
                    d.setModal(False)
                    d.show()
                    self._modeless_dialogs.append(d)
                return

            if 'calibre.ebooks.oeb.transforms.split.SplitError' in job.details:
                title = job.description.split(':')[-1].partition('(')[-1][:-1]
                msg = _('<p><b>Failed to convert: %s') % title
                msg += '<p>' + _('''
                Many older ebook reader devices are incapable of displaying
                EPUB files that have internal components over a certain size.
                Therefore, when converting to EPUB, calibre automatically tries
                to split up the EPUB into smaller sized pieces.  For some
                files that are large undifferentiated blocks of text, this
                splitting fails.
                <p>You can <b>work around the problem</b> by either increasing the
                maximum split size under EPUB Output in the conversion dialog,
                or by turning on Heuristic Processing, also in the conversion
                dialog. Note that if you make the maximum split size too large,
                your ebook reader may have trouble with the EPUB.
                        ''')
                if not minz:
                    d = error_dialog(self,
                                     _('Conversion Failed'),
                                     msg,
                                     det_msg=job.details)
                    d.setModal(False)
                    d.show()
                    self._modeless_dialogs.append(d)
                return

            if 'calibre.web.feeds.input.RecipeDisabled' in job.details:
                if not minz:
                    msg = job.details
                    msg = msg[msg.
                              find('calibre.web.feeds.input.RecipeDisabled:'):]
                    msg = msg.partition(':')[-1]
                    d = error_dialog(self, _('Recipe Disabled'),
                                     '<p>%s</p>' % msg)
                    d.setModal(False)
                    d.show()
                    self._modeless_dialogs.append(d)
                return

            if 'calibre.ebooks.conversion.ConversionUserFeedBack:' in job.details:
                if not minz:
                    import json
                    payload = job.details.rpartition(
                        'calibre.ebooks.conversion.ConversionUserFeedBack:'
                    )[-1]
                    payload = json.loads('{' + payload.partition('{')[-1])
                    d = {
                        'info': info_dialog,
                        'warn': warning_dialog,
                        'error': error_dialog
                    }.get(payload['level'], error_dialog)
                    d = d(self,
                          payload['title'],
                          '<p>%s</p>' % payload['msg'],
                          det_msg=payload['det_msg'])
                    d.setModal(False)
                    d.show()
                    self._modeless_dialogs.append(d)
                return
        except:
            pass
        if job.killed:
            return
        try:
            prints(job.details, file=sys.stderr)
        except:
            pass
        if not minz:
            self.job_error_dialog.show_error(dialog_title,
                                             _('<b>Failed</b>') + ': ' +
                                             unicode(job.description),
                                             det_msg=job.details,
                                             retry_func=retry_func)
Exemplo n.º 6
0
    def job_exception(self, job, dialog_title=_('Conversion Error'), retry_func=None):
        if not hasattr(self, '_modeless_dialogs'):
            self._modeless_dialogs = []
        minz = self.is_minimized_to_tray
        if self.isVisible():
            for x in list(self._modeless_dialogs):
                if not x.isVisible():
                    self._modeless_dialogs.remove(x)
        try:
            if 'calibre.ebooks.DRMError' in job.details:
                if not minz:
                    from calibre.gui2.dialogs.drm_error import DRMErrorMessage
                    d = DRMErrorMessage(self, _('Cannot convert') + ' ' +
                        job.description.split(':')[-1].partition('(')[-1][:-1])
                    d.setModal(False)
                    d.show()
                    self._modeless_dialogs.append(d)
                return

            if 'calibre.ebooks.oeb.transforms.split.SplitError' in job.details:
                title = job.description.split(':')[-1].partition('(')[-1][:-1]
                msg = _('<p><b>Failed to convert: %s')%title
                msg += '<p>'+_('''
                Many older ebook reader devices are incapable of displaying
                EPUB files that have internal components over a certain size.
                Therefore, when converting to EPUB, calibre automatically tries
                to split up the EPUB into smaller sized pieces.  For some
                files that are large undifferentiated blocks of text, this
                splitting fails.
                <p>You can <b>work around the problem</b> by either increasing the
                maximum split size under EPUB Output in the conversion dialog,
                or by turning on Heuristic Processing, also in the conversion
                dialog. Note that if you make the maximum split size too large,
                your ebook reader may have trouble with the EPUB.
                        ''')
                if not minz:
                    d = error_dialog(self, _('Conversion Failed'), msg,
                            det_msg=job.details)
                    d.setModal(False)
                    d.show()
                    self._modeless_dialogs.append(d)
                return

            if 'calibre.web.feeds.input.RecipeDisabled' in job.details:
                if not minz:
                    msg = job.details
                    msg = msg[msg.find('calibre.web.feeds.input.RecipeDisabled:'):]
                    msg = msg.partition(':')[-1]
                    d = error_dialog(self, _('Recipe Disabled'),
                        '<p>%s</p>'%msg)
                    d.setModal(False)
                    d.show()
                    self._modeless_dialogs.append(d)
                return

            if 'calibre.ebooks.conversion.ConversionUserFeedBack:' in job.details:
                if not minz:
                    import json
                    payload = job.details.rpartition(
                        'calibre.ebooks.conversion.ConversionUserFeedBack:')[-1]
                    payload = json.loads('{' + payload.partition('{')[-1])
                    d = {'info':info_dialog, 'warn':warning_dialog,
                            'error':error_dialog}.get(payload['level'],
                                    error_dialog)
                    d = d(self, payload['title'],
                            '<p>%s</p>'%payload['msg'],
                            det_msg=payload['det_msg'])
                    d.setModal(False)
                    d.show()
                    self._modeless_dialogs.append(d)
                return
        except:
            pass
        if job.killed:
            return
        try:
            prints(job.details, file=sys.stderr)
        except:
            pass
        if not minz:
            self.job_error_dialog.show_error(dialog_title,
                    _('<b>Failed</b>')+': '+unicode(job.description),
                    det_msg=job.details, retry_func=retry_func)
Exemplo n.º 7
0
    def load_ebook(self, pathtoebook, open_at=None):
        if self.iterator is not None:
            self.save_current_position()
            self.iterator.__exit__()
        self.iterator = EbookIterator(pathtoebook)
        self.open_progress_indicator(_('Loading ebook...'))
        worker = Worker(target=partial(self.iterator.__enter__,
            extract_embedded_fonts_for_qt=True))
        worker.start()
        while worker.isAlive():
            worker.join(0.1)
            QApplication.processEvents()
        if worker.exception is not None:
            if isinstance(worker.exception, DRMError):
                from calibre.gui2.dialogs.drm_error import DRMErrorMessage
                DRMErrorMessage(self).exec_()
            else:
                r = getattr(worker.exception, 'reason', worker.exception)
                error_dialog(self, _('Could not open ebook'),
                        as_unicode(r) or _('Unknown error'),
                        det_msg=worker.traceback, show=True)
            self.close_progress_indicator()
        else:
            self.metadata.show_opf(self.iterator.opf,
                    self.iterator.book_format)
            self.view.current_language = self.iterator.language
            title = self.iterator.opf.title
            if not title:
                title = os.path.splitext(os.path.basename(pathtoebook))[0]
            if self.iterator.toc:
                self.toc_model = TOC(self.iterator.spine, self.iterator.toc)
                self.toc.setModel(self.toc_model)
                if self.show_toc_on_open:
                    self.action_table_of_contents.setChecked(True)
            else:
                self.toc_model = TOC(self.iterator.spine)
                self.toc.setModel(self.toc_model)
                self.action_table_of_contents.setChecked(False)
            if isbytestring(pathtoebook):
                pathtoebook = force_unicode(pathtoebook, filesystem_encoding)
            vh = vprefs.get('viewer_open_history', [])
            try:
                vh.remove(pathtoebook)
            except:
                pass
            vh.insert(0, pathtoebook)
            vprefs.set('viewer_open_history', vh[:50])
            self.build_recent_menu()

            self.action_table_of_contents.setDisabled(not self.iterator.toc)
            self.current_book_has_toc = bool(self.iterator.toc)
            self.current_title = title
            self.setWindowTitle(self.base_window_title+' - '+title +
                    ' [%s]'%self.iterator.book_format)
            self.pos.setMaximum(sum(self.iterator.pages))
            self.pos.setSuffix(' / %d'%sum(self.iterator.pages))
            self.vertical_scrollbar.setMinimum(100)
            self.vertical_scrollbar.setMaximum(100*sum(self.iterator.pages))
            self.vertical_scrollbar.setSingleStep(10)
            self.vertical_scrollbar.setPageStep(100)
            self.set_vscrollbar_value(1)
            self.current_index = -1
            QApplication.instance().alert(self, 5000)
            previous = self.set_bookmarks(self.iterator.bookmarks)
            if open_at is None and previous is not None:
                self.goto_bookmark(previous)
            else:
                if open_at is None:
                    self.next_document()
                else:
                    if open_at > self.pos.maximum():
                        open_at = self.pos.maximum()
                    if open_at < self.pos.minimum():
                        open_at = self.pos.minimum()
                    self.goto_page(open_at, loaded_check=False)
Exemplo n.º 8
0
    def job_exception(self, job, dialog_title=_("Conversion Error")):
        if not hasattr(self, "_modeless_dialogs"):
            self._modeless_dialogs = []
        minz = self.is_minimized_to_tray
        if self.isVisible():
            for x in list(self._modeless_dialogs):
                if not x.isVisible():
                    self._modeless_dialogs.remove(x)
        try:
            if "calibre.ebooks.DRMError" in job.details:
                if not minz:
                    from calibre.gui2.dialogs.drm_error import DRMErrorMessage

                    d = DRMErrorMessage(
                        self, _("Cannot convert") + " " + job.description.split(":")[-1].partition("(")[-1][:-1]
                    )
                    d.setModal(False)
                    d.show()
                    self._modeless_dialogs.append(d)
                return

            if "calibre.ebooks.oeb.transforms.split.SplitError" in job.details:
                title = job.description.split(":")[-1].partition("(")[-1][:-1]
                msg = _("<p><b>Failed to convert: %s") % title
                msg += "<p>" + _(
                    """
                Many older ebook reader devices are incapable of displaying
                EPUB files that have internal components over a certain size.
                Therefore, when converting to EPUB, calibre automatically tries
                to split up the EPUB into smaller sized pieces.  For some
                files that are large undifferentiated blocks of text, this
                splitting fails.
                <p>You can <b>work around the problem</b> by either increasing the
                maximum split size under EPUB Output in the conversion dialog,
                or by turning on Heuristic Processing, also in the conversion
                dialog. Note that if you make the maximum split size too large,
                your ebook reader may have trouble with the EPUB.
                        """
                )
                if not minz:
                    d = error_dialog(self, _("Conversion Failed"), msg, det_msg=job.details)
                    d.setModal(False)
                    d.show()
                    self._modeless_dialogs.append(d)
                return

            if "calibre.web.feeds.input.RecipeDisabled" in job.details:
                if not minz:
                    msg = job.details
                    msg = msg[msg.find("calibre.web.feeds.input.RecipeDisabled:") :]
                    msg = msg.partition(":")[-1]
                    d = error_dialog(self, _("Recipe Disabled"), "<p>%s</p>" % msg)
                    d.setModal(False)
                    d.show()
                    self._modeless_dialogs.append(d)
                return

            if "calibre.ebooks.conversion.ConversionUserFeedBack:" in job.details:
                if not minz:
                    import json

                    payload = job.details.rpartition("calibre.ebooks.conversion.ConversionUserFeedBack:")[-1]
                    payload = json.loads("{" + payload.partition("{")[-1])
                    d = {"info": info_dialog, "warn": warning_dialog, "error": error_dialog}.get(
                        payload["level"], error_dialog
                    )
                    d = d(self, payload["title"], "<p>%s</p>" % payload["msg"], det_msg=payload["det_msg"])
                    d.setModal(False)
                    d.show()
                    self._modeless_dialogs.append(d)
                return
        except:
            pass
        if job.killed:
            return
        try:
            prints(job.details, file=sys.stderr)
        except:
            pass
        if not minz:
            self.job_error_dialog.show_error(
                dialog_title, _("<b>Failed</b>") + ": " + unicode(job.description), det_msg=job.details
            )