コード例 #1
0
ファイル: __init__.py プロジェクト: yeyanchao/calibre
def render_html(path_to_html, width=590, height=750, as_xhtml=True):
    from PyQt4.QtWebKit import QWebPage
    from PyQt4.Qt import QEventLoop, QPalette, Qt, QUrl, QSize
    from calibre.gui2 import is_ok_to_use_qt
    if not is_ok_to_use_qt(): return None
    path_to_html = os.path.abspath(path_to_html)
    with CurrentDir(os.path.dirname(path_to_html)):
        page = QWebPage()
        pal = page.palette()
        pal.setBrush(QPalette.Background, Qt.white)
        page.setPalette(pal)
        page.setViewportSize(QSize(width, height))
        page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff)
        page.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)
        loop = QEventLoop()
        renderer = HTMLRenderer(page, loop)
        page.loadFinished.connect(renderer, type=Qt.QueuedConnection)
        if as_xhtml:
            page.mainFrame().setContent(open(path_to_html, 'rb').read(),
                    'application/xhtml+xml', QUrl.fromLocalFile(path_to_html))
        else:
            page.mainFrame().load(QUrl.fromLocalFile(path_to_html))
        loop.exec_()
    renderer.loop = renderer.page = None
    page.loadFinished.disconnect()
    del page
    del loop
    if isinstance(renderer.exception, ParserError) and as_xhtml:
        return render_html(path_to_html, width=width, height=height,
                as_xhtml=False)
    return renderer
コード例 #2
0
 def show_help(self):
     '''
     Display strftime help file
     '''
     from calibre.gui2 import open_url
     path = os.path.join(self.parent.resources_path, 'help/timestamp_formats.html')
     open_url(QUrl.fromLocalFile(path))
コード例 #3
0
ファイル: webview.py プロジェクト: iwannafly/calibre
def load_html(path, view, codec='utf-8', mime_type=None,
              pre_load_callback=lambda x:None, path_is_html=False,
              force_as_html=False):
    from PyQt4.Qt import QUrl, QByteArray
    if mime_type is None:
        mime_type = guess_type(path)[0]
        if not mime_type:
            mime_type = 'text/html'
    if path_is_html:
        html = path
    else:
        with open(path, 'rb') as f:
            html = f.read().decode(codec, 'replace')

    html = EntityDeclarationProcessor(html).processed_html
    self_closing_pat = re.compile(r'<\s*([:A-Za-z0-9-]+)([^>]*)/\s*>')
    html = self_closing_pat.sub(self_closing_sub, html)

    loading_url = QUrl.fromLocalFile(path)
    pre_load_callback(loading_url)

    if force_as_html or re.search(r'<[:a-zA-Z0-9-]*svg', html) is None:
        view.setHtml(html, loading_url)
    else:
        view.setContent(QByteArray(html.encode(codec)), mime_type,
                loading_url)
        mf = view.page().mainFrame()
        elem = mf.findFirstElement('parsererror')
        if not elem.isNull():
            return False
    return True
コード例 #4
0
ファイル: preview.py プロジェクト: Kielek/calibre
 def show(self, name):
     if name != self.current_name:
         self.refresh_timer.stop()
         self.current_name = name
         parse_worker.add_request(name)
         self.view.setUrl(QUrl.fromLocalFile(current_container().name_to_abspath(name)))
         return True
コード例 #5
0
ファイル: webview.py プロジェクト: Eksmo/calibre
def load_html(path, view, codec='utf-8', mime_type=None,
        pre_load_callback=lambda x:None, path_is_html=False):
    from PyQt4.Qt import QUrl, QByteArray
    if mime_type is None:
        mime_type = guess_type(path)[0]
    if path_is_html:
        html = path
    else:
        with open(path, 'rb') as f:
            html = f.read().decode(codec, 'replace')

    html = EntityDeclarationProcessor(html).processed_html
    has_svg = re.search(r'<[:a-zA-Z]*svg', html) is not None
    if 'xhtml' in mime_type:
        self_closing_pat = re.compile(r'<([a-z1-6]+)\s+([^>]+)/>',
                re.IGNORECASE)
        html = self_closing_pat.sub(self_closing_sub, html)

    html = re.sub(ur'<\s*title\s*/\s*>', u'', html, flags=re.IGNORECASE)
    loading_url = QUrl.fromLocalFile(path)
    pre_load_callback(loading_url)

    if has_svg:
        view.setContent(QByteArray(html.encode(codec)), mime_type,
                loading_url)
    else:
        view.setHtml(html, loading_url)
コード例 #6
0
ファイル: MainWindow.py プロジェクト: kernsuite-debian/purr
 def setDocument(self, filename, empty=""):
     """Sets the HTML text to be displayed. """
     self._source = QUrl.fromLocalFile(filename)
     if os.path.exists(filename):
         self.viewer.setSource(self._source)
     else:
         self.viewer.setText(empty)
コード例 #7
0
ファイル: MainWindow.py プロジェクト: kernsuite-debian/purr
 def mimeData(self, itemlist):
     mimedata = QMimeData()
     urls = []
     for item in itemlist:
         dp = getattr(item, "_dp", None)
         dp and urls.append(QUrl.fromLocalFile(dp.fullpath or dp.sourcepath))
     mimedata.setUrls(urls)
     return mimedata
コード例 #8
0
ファイル: preview.py プロジェクト: Kielek/calibre
 def refresh(self):
     if self.current_name:
         self.refresh_timer.stop()
         # This will check if the current html has changed in its editor,
         # and re-parse it if so
         parse_worker.add_request(self.current_name)
         # Tell webkit to reload all html and associated resources
         current_url = QUrl.fromLocalFile(current_container().name_to_abspath(self.current_name))
         if current_url != self.view.url():
             # The container was changed
             self.view.setUrl(current_url)
         else:
             self.view.refresh()
コード例 #9
0
ファイル: main.py プロジェクト: 089git/calibre
 def toc_clicked(self, index, force=False):
     if force or QApplication.mouseButtons() & Qt.LeftButton:
         item = self.toc_model.itemFromIndex(index)
         if item.abspath is not None:
             if not os.path.exists(item.abspath):
                 return error_dialog(self, _('No such location'),
                         _('The location pointed to by this item'
                             ' does not exist.'), det_msg=item.abspath, show=True)
             url = QUrl.fromLocalFile(item.abspath)
             if item.fragment:
                 url.setFragment(item.fragment)
             self.link_clicked(url)
     self.view.setFocus(Qt.OtherFocusReason)
コード例 #10
0
    def parse_link(self, link):
        link = link.strip()
        if link and os.path.exists(link):
            return QUrl.fromLocalFile(link)
        has_schema = re.match(r'^[a-zA-Z]+:', link)
        if has_schema is not None:
            url = QUrl(link, QUrl.TolerantMode)
            if url.isValid():
                return url
        if os.path.exists(link):
            return QUrl.fromLocalFile(link)

        if has_schema is None:
            first, _, rest = link.partition('.')
            prefix = 'http'
            if first == 'ftp':
                prefix = 'ftp'
            url = QUrl(prefix +'://'+link, QUrl.TolerantMode)
            if url.isValid():
                return url

        return QUrl(link, QUrl.TolerantMode)
コード例 #11
0
ファイル: views.py プロジェクト: john-peterson/calibre
 def drag_data(self):
     m = self.model()
     rows = self.selectionModel().selectedRows()
     paths = [force_unicode(p, enc=filesystem_encoding) for p in m.paths(rows) if p]
     md = QMimeData()
     md.setData("application/calibre+from_device", "dummy")
     md.setUrls([QUrl.fromLocalFile(p) for p in paths])
     drag = QDrag(self)
     drag.setMimeData(md)
     cover = self.drag_icon(m.cover(self.currentIndex().row()), len(paths) > 1)
     drag.setHotSpot(QPoint(-15, -15))
     drag.setPixmap(cover)
     return drag
コード例 #12
0
ファイル: preview.py プロジェクト: siebert/calibre
 def refresh(self):
     if self.current_name:
         self.refresh_timer.stop()
         # This will check if the current html has changed in its editor,
         # and re-parse it if so
         parse_worker.add_request(self.current_name)
         # Tell webkit to reload all html and associated resources
         current_url = QUrl.fromLocalFile(
             current_container().name_to_abspath(self.current_name))
         if current_url != self.view.url():
             # The container was changed
             self.view.setUrl(current_url)
         else:
             self.view.refresh()
コード例 #13
0
ファイル: __init__.py プロジェクト: kmshi/calibre
def render_html(path_to_html, width=590, height=750, as_xhtml=True):
    from PyQt4.QtWebKit import QWebPage
    from PyQt4.Qt import QEventLoop, QPalette, Qt, QUrl, QSize
    from calibre.gui2 import is_ok_to_use_qt
    if not is_ok_to_use_qt():
        return None
    path_to_html = os.path.abspath(path_to_html)
    with CurrentDir(os.path.dirname(path_to_html)):
        page = QWebPage()
        pal = page.palette()
        pal.setBrush(QPalette.Background, Qt.white)
        page.setPalette(pal)
        page.setViewportSize(QSize(width, height))
        page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff)
        page.mainFrame().setScrollBarPolicy(Qt.Horizontal,
                                            Qt.ScrollBarAlwaysOff)
        loop = QEventLoop()
        renderer = HTMLRenderer(page, loop)
        page.loadFinished.connect(renderer, type=Qt.QueuedConnection)
        if as_xhtml:
            page.mainFrame().setContent(
                open(path_to_html, 'rb').read(), 'application/xhtml+xml',
                QUrl.fromLocalFile(path_to_html))
        else:
            page.mainFrame().load(QUrl.fromLocalFile(path_to_html))
        loop.exec_()
    renderer.loop = renderer.page = None
    page.loadFinished.disconnect()
    del page
    del loop
    if isinstance(renderer.exception, ParserError) and as_xhtml:
        return render_html(path_to_html,
                           width=width,
                           height=height,
                           as_xhtml=False)
    return renderer
コード例 #14
0
 def toc_clicked(self, index, force=False):
     if force or QApplication.mouseButtons() & Qt.LeftButton:
         item = self.toc_model.itemFromIndex(index)
         if item.abspath is not None:
             if not os.path.exists(item.abspath):
                 return error_dialog(
                     self,
                     _('No such location'),
                     _('The location pointed to by this item'
                       ' does not exist.'),
                     show=True)
             url = QUrl.fromLocalFile(item.abspath)
             if item.fragment:
                 url.setFragment(item.fragment)
             self.link_clicked(url)
     self.view.setFocus(Qt.OtherFocusReason)
コード例 #15
0
 def drag_data(self):
     m = self.model()
     rows = self.selectionModel().selectedRows()
     paths = [
         force_unicode(p, enc=filesystem_encoding) for p in m.paths(rows)
         if p
     ]
     md = QMimeData()
     md.setData('application/calibre+from_device', 'dummy')
     md.setUrls([QUrl.fromLocalFile(p) for p in paths])
     drag = QDrag(self)
     drag.setMimeData(md)
     cover = self.drag_icon(m.cover(self.currentIndex().row()),
                            len(paths) > 1)
     drag.setHotSpot(QPoint(-15, -15))
     drag.setPixmap(cover)
     return drag
コード例 #16
0
 def url_for_id(i):
     try:
         ans = db.format_path(i, fmt, index_is_id=True)
     except:
         ans = None
     if ans is None:
         fmts = db.formats(i, index_is_id=True)
         if fmts:
             fmts = fmts.split(',')
         else:
             fmts = []
         for f in fmts:
             try:
                 ans = db.format_path(i, f, index_is_id=True)
             except:
                 ans = None
     if ans is None:
         ans = db.abspath(i, index_is_id=True)
     return QUrl.fromLocalFile(ans)
コード例 #17
0
ファイル: alternate_views.py プロジェクト: shamray/calibre
 def url_for_id(i):
     try:
         ans = db.format_path(i, fmt, index_is_id=True)
     except:
         ans = None
     if ans is None:
         fmts = db.formats(i, index_is_id=True)
         if fmts:
             fmts = fmts.split(',')
         else:
             fmts = []
         for f in fmts:
             try:
                 ans = db.format_path(i, f, index_is_id=True)
             except:
                 ans = None
     if ans is None:
         ans = db.abspath(i, index_is_id=True)
     return QUrl.fromLocalFile(ans)
コード例 #18
0
    def parse_link(self, link):
        link = link.strip()
        has_schema = re.match(r'^[a-zA-Z]+:', link)
        if has_schema is not None:
            url = QUrl(link, QUrl.TolerantMode)
            if url.isValid():
                return url
        if os.path.exists(link):
            return QUrl.fromLocalFile(link)

        if has_schema is None:
            first, _, rest = link.partition('.')
            prefix = 'http'
            if first == 'ftp':
                prefix = 'ftp'
            url = QUrl(prefix + '://' + link, QUrl.TolerantMode)
            if url.isValid():
                return url

        return QUrl(link, QUrl.TolerantMode)
コード例 #19
0
ファイル: documentview.py プロジェクト: alfaniel/calibre
 def popup_table(self):
     html = self.document.extract_node()
     self.table_popup(html, QUrl.fromLocalFile(self.last_loaded_path),
                      self.document.font_magnification_step)
コード例 #20
0
 def show_help(self):
     self._log_location()
     path = os.path.join(self.parent.resources_path, 'help', 'marvin.html')
     open_url(QUrl.fromLocalFile(path))
コード例 #21
0
ファイル: __init__.py プロジェクト: piewsook/calibre
def open_local_file(path):
    if iswindows:
        os.startfile(os.path.normpath(path))
    else:
        url = QUrl.fromLocalFile(path)
        open_url(url)
コード例 #22
0
ファイル: image_popup.py プロジェクト: iwannafly/calibre
class ImagePopup(object):

    def __init__(self, parent):
        self.current_img = QPixmap()
        self.current_url = QUrl()
        self.parent = parent
        self.dialogs = []

    def __call__(self):
        if self.current_img.isNull():
            return
        d = ImageView(self.parent, self.current_img, self.current_url)
        self.dialogs.append(d)
        d.finished.connect(self.cleanup, type=Qt.QueuedConnection)
        d()

    def cleanup(self):
        for d in tuple(self.dialogs):
            if not d.isVisible():
                self.dialogs.remove(d)

if __name__ == '__main__':
    import sys
    app = QApplication([])
    p = QPixmap()
    p.load(sys.argv[-1])
    u = QUrl.fromLocalFile(sys.argv[-1])
    d = ImageView(None, p, u)
    d()
    app.exec_()
コード例 #23
0
def open_local_file(path):
    if iswindows:
        os.startfile(os.path.normpath(path))
    else:
        url = QUrl.fromLocalFile(path)
        open_url(url)
コード例 #24
0
 def show_help(self):
     self._log_location()
     path = os.path.join(self.parent.resources_path, 'help', 'marvin.html')
     open_url(QUrl.fromLocalFile(path))
コード例 #25
0
ファイル: preview.py プロジェクト: Gondulf/calibre
 def show(self, name):
     if name != self.current_name:
         self.refresh_timer.stop()
         self.current_name = name
         parse_worker.add_request(name)
         self.view.setUrl(QUrl.fromLocalFile(current_container().name_to_abspath(name)))
コード例 #26
0
ファイル: documentview.py プロジェクト: kmshi/calibre
 def popup_table(self):
     html = self.document.extract_node()
     self.table_popup(html, QUrl.fromLocalFile(self.last_loaded_path),
                      self.document.font_magnification_step)
コード例 #27
0
ファイル: image_popup.py プロジェクト: 089git/calibre
class ImagePopup(object):

    def __init__(self, parent):
        self.current_img = QPixmap()
        self.current_url = QUrl()
        self.parent = parent
        self.dialogs = []

    def __call__(self):
        if self.current_img.isNull():
            return
        d = ImageView(self.parent, self.current_img, self.current_url)
        self.dialogs.append(d)
        d.finished.connect(self.cleanup, type=Qt.QueuedConnection)
        d()

    def cleanup(self):
        for d in tuple(self.dialogs):
            if not d.isVisible():
                self.dialogs.remove(d)

if __name__ == '__main__':
    import sys
    app = QApplication([])
    p = QPixmap()
    p.load(sys.argv[-1])
    u = QUrl.fromLocalFile(sys.argv[-1])
    d = ImageView(None, p, u)
    d()
    app.exec_()