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
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)
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)
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
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
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))
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
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)
def __init__(self, controller, file_path): super(MetadataWebView, self).__init__() self.controller = controller self.setWindowTitle("Nuxeo Drive: " + file_path) icon = find_icon('nuxeo_drive_icon_64.png') if icon is not None: self.setWindowIcon(QtGui.QIcon(icon)) url, token = self.controller.get_metadata_view_url(file_path) self.request = QtNetwork.QNetworkRequest(QUrl(url)) self.request.setRawHeader("X-Authentication-Token", QtCore.QByteArray(token)) self.load(self.request)
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()
def __init__(self, parent): QWebView.__init__(self, parent) self._page = Page() self._page.elem_clicked.connect(self.elem_clicked) self.setPage(self._page) raw = ''' body { background-color: white } .calibre_toc_hover:hover { cursor: pointer !important; border-top: solid 5px green !important } ''' raw = '::selection {background:#ffff00; color:#000;}\n' + raw data = 'data:text/css;charset=utf-8;base64,' data += b64encode(raw.encode('utf-8')) self.settings().setUserStyleSheetUrl(QUrl(data))
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)
def open(self, parent=None, detail_item=None, external=False): url = 'http://gutenberg.org/' if detail_item: detail_item = url_slash_cleaner(url + detail_item) if external or self.config.get('open_external', False): open_url(QUrl(detail_item if detail_item else url)) else: d = WebStoreDialog(self.gui, url, parent, detail_item) d.setWindowTitle(self.name) d.set_tags(self.config.get('tags', '')) d.exec_()
def open(self, parent=None, detail_item=None, external=False): url = 'https://cdp.pl/ksiazki' if external or self.config.get('open_external', False): open_url( QUrl(url_slash_cleaner(detail_item if detail_item else url))) else: d = WebStoreDialog(self.gui, url, parent, detail_item if detail_item else url) d.setWindowTitle(self.name) d.set_tags(self.config.get('tags', '')) d.exec_()
def visit(self, url, timeout=30.0): ''' Open the page specified in URL and wait for it to complete loading. Note that when this method returns, there may still be javascript that needs to execute (this method returns when the loadFinished() signal is called on QWebPage). This method will raise a Timeout exception if loading takes more than timeout seconds. Returns True if loading was successful, False otherwise. ''' self.current_form = None self.page.mainFrame().load(QUrl(url)) return self._wait_for_load(timeout, url)
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
def set_user_stylesheet(self, opts): bg = opts.background_color or 'white' brules = ['background-color: %s !important'%bg] prefix = ''' body { %s } '''%('; '.join(brules)) if opts.text_color: prefix += '\n\nbody, p, div { color: %s !important }'%opts.text_color raw = prefix + opts.user_css raw = '::selection {background:#ffff00; color:#000;}\n'+raw data = 'data:text/css;charset=utf-8;base64,' data += b64encode(raw.encode('utf-8')) self.settings().setUserStyleSheetUrl(QUrl(data))
def download_file(self, url_or_selector_or_qwe, timeout=60): ''' Download unsupported content: i.e. files the browser cannot handle itself or files marked for saving as files by the website. Useful if you want to download something like an epub file after authentication. You can pass in either the url to the file to be downloaded, or a selector that points to an element to be clicked on the current page which will cause the file to be downloaded. ''' ans = [False, None, []] loop = QEventLoop(self) start_time = time.time() end_time = start_time + timeout self.page.unsupportedContent.disconnect(self.page.on_unsupported_content) try: def download(reply): if ans[0]: reply.abort() # We only handle the first unsupported download return ans[0] = True while not reply.isFinished() and end_time > time.time(): if not loop.processEvents(): time.sleep(0.01) raw = bytes(bytearray(reply.readAll())) if raw: ans[-1].append(raw) if not reply.isFinished(): ans[1] = Timeout('Loading of %r took longer than %d seconds'%(url_or_selector_or_qwe, timeout)) ans[-1].append(bytes(bytearray(reply.readAll()))) self.page.unsupportedContent.connect(download) if hasattr(url_or_selector_or_qwe, 'rstrip') and re.match('[a-z]+://', url_or_selector_or_qwe) is not None: # We have a URL self.page.mainFrame().load(QUrl(url_or_selector_or_qwe)) else: self.click(url_or_selector_or_qwe, wait_for_load=False) lw = LoadWatcher(self.page) while not ans[0] and lw.is_loading and end_time > time.time(): if not loop.processEvents(): time.sleep(0.01) if not ans[0]: raise NotAFile('%r does not point to a downloadable file. You can only' ' use this method to download files that the browser cannot handle' ' natively. Or files that are marked with the ' ' content-disposition: attachment header' % url_or_selector_or_qwe) if ans[1] is not None: raise ans[1] return b''.join(ans[-1]) finally: self.page.unsupportedContent.disconnect() self.page.unsupportedContent.connect(self.page.on_unsupported_content)
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() settings = page.settings() settings.setAttribute(settings.PluginsEnabled, False) 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
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()
def open(self, parent=None, detail_item=None, external=False): aff_id = {'tag': 'charhale0a-21'} store_link = ( 'http://www.amazon.de/gp/redirect.html?ie=UTF8&site-redirect=de' '&tag=%(tag)s&linkCode=ur2&camp=1638&creative=19454' '&location=http://www.amazon.de/ebooks-kindle/b?node=530886031' ) % aff_id if detail_item: aff_id['asin'] = detail_item store_link = ( 'http://www.amazon.de/gp/redirect.html?ie=UTF8' '&location=http://www.amazon.de/dp/%(asin)s&site-redirect=de' '&tag=%(tag)s&linkCode=ur2&camp=1638&creative=6742') % aff_id open_url(QUrl(store_link))
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
def help_link_activated(self, url): def get_help_file_resource(): # Copy the HTML helpfile to the plugin directory each time the # link is clicked in case the helpfile is updated in newer plugins. help_file_name = u"{0}_{1}_Help.htm".format( PLUGIN_NAME, self.key_type_name) file_path = os.path.join(config_dir, u"plugins", u"DeDRM", u"help", help_file_name) with open(file_path, 'w') as f: f.write(self.parent.load_resource(help_file_name)) return file_path url = 'file:///' + get_help_file_resource() open_url(QUrl(url))
def open(self, parent=None, detail_item=None, external=False): pid = '44010' url = 'http://www.escapemagazine.pl/s/' + pid if external or self.config.get('open_external', False): open_url( QUrl( url_slash_cleaner(detail_item + '/s/' + pid if detail_item else url))) else: d = WebStoreDialog(self.gui, url, parent, detail_item) d.setWindowTitle(self.name) d.set_tags(self.config.get('tags', '')) d.exec_()
def handle_click(self, link): typ, _, val = link.partition(':') if typ == 'path': self.open_containing_folder.emit(int(val)) elif typ == 'format': id_, fmt = val.split(':') self.view_specific_format.emit(int(id_), fmt) elif typ == 'devpath': self.view_device_book.emit(val) else: try: open_url(QUrl(link, QUrl.TolerantMode)) except: import traceback traceback.print_exc()
def open(self, parent=None, detail_item=None, external=False): url = 'http://www.baenebooks.com/' if external or self.config.get('open_external', False): if detail_item: url = url + detail_item open_url(QUrl(url_slash_cleaner(url))) else: detail_url = None if detail_item: detail_url = url + detail_item d = WebStoreDialog(self.gui, url, parent, detail_url) d.setWindowTitle(self.name) d.set_tags(self.config.get('tags', '')) d.exec_()
def open(self, parent=None, detail_item=None, external=False): url = 'http://woblink.com/publication' detail_url = None if detail_item: detail_url = 'http://woblink.com' + detail_item if external or self.config.get('open_external', False): open_url(QUrl(url_slash_cleaner(detail_url if detail_url else url))) else: d = WebStoreDialog(self.gui, url, parent, detail_url) d.setWindowTitle(self.name) d.set_tags(self.config.get('tags', '')) d.exec_()
def open(self, parent=None, detail_item=None, external=False): google_analytics = '?utm_source=tdcalibre&utm_medium=calibre' url = 'http://www.publio.pl/' + google_analytics if external or self.config.get('open_external', False): open_url( QUrl( url_slash_cleaner(( detail_item + google_analytics) if detail_item else url))) else: d = WebStoreDialog(self.gui, url, parent, detail_item if detail_item else url) d.setWindowTitle(self.name) d.set_tags(self.config.get('tags', '')) d.exec_()
def open(self, parent=None, detail_item=None, external=False): url_details = 'http://www.awin1.com/cread.php?awinmid=1414&awinaffid=120917&clickref=&p={0}' url = 'http://www.awin1.com/awclick.php?mid=2666&id=120917' if external or self.config.get('open_external', False): if detail_item: url = url_details.format(detail_item) open_url(QUrl(url)) else: detail_url = None if detail_item: detail_url = url_details.format(detail_item) d = WebStoreDialog(self.gui, url, parent, detail_url) d.setWindowTitle(self.name) d.set_tags(self.config.get('tags', '')) d.exec_()
def open(self, parent=None, detail_item=None, external=False): url = 'http://www.legimi.com/pl/ebooks/?price=any' detail_url = None if detail_item: detail_url = detail_item if external or self.config.get('open_external', False): open_url(QUrl( url_slash_cleaner(detail_url if detail_url else url))) else: d = WebStoreDialog(self.gui, url, parent, detail_url) d.setWindowTitle(self.name) d.set_tags(self.config.get('tags', '')) d.exec_()
def open(self, parent=None, detail_item=None, external=False): url = 'http://www.whsmith.co.uk/' url_details = '' if external or self.config.get('open_external', False): if detail_item: url = url_details + detail_item open_url(QUrl(url)) else: detail_url = None if detail_item: detail_url = url_details + detail_item d = WebStoreDialog(self.gui, url, parent, detail_url) d.setWindowTitle(self.name) d.set_tags(self.config.get('tags', '')) d.exec_()
def open(self, parent=None, detail_item=None, external=False): url = 'http://clkuk.tradedoubler.com/click?p=51196&a=1951604&g=19333484' url_details = 'http://clkuk.tradedoubler.com/click?p(51196)a(1951604)g(16460516)url({0})' if external or self.config.get('open_external', False): if detail_item: url = url_details.format(detail_item) open_url(QUrl(url)) else: detail_url = None if detail_item: detail_url = url_details.format(detail_item) d = WebStoreDialog(self.gui, url, parent, detail_url) d.setWindowTitle(self.name) d.set_tags(self.config.get('tags', '')) d.exec_()
def open(self, parent=None, detail_item=None, external=False): url = 'http://www.mobileread.com/' if external or self.config.get('open_external', False): open_url(QUrl(detail_item if detail_item else url)) else: if detail_item: d = WebStoreDialog(self.gui, url, parent, detail_item) d.setWindowTitle(self.name) d.set_tags(self.config.get('tags', '')) d.exec_() else: self.update_cache(parent, 30) d = MobileReadStoreDialog(self, parent) d.setWindowTitle(self.name) d.exec_()
def open(self, parent=None, detail_item=None, external=False): url = 'http://www.awin1.com/awclick.php?mid=1150&id=120917' detail_url = 'http://www.awin1.com/cread.php?awinmid=1150&awinaffid=120917&clickref=&p=' if external or self.config.get('open_external', False): if detail_item: url = detail_url + detail_item open_url(QUrl(url_slash_cleaner(url))) else: detail_url = None if detail_item: detail_url = url + detail_item d = WebStoreDialog(self.gui, url, parent, detail_url) d.setWindowTitle(self.name) d.set_tags(self.config.get('tags', '')) d.exec_()
def open(self, parent=None, detail_item=None, external=False): url = 'http://www.ebook.nl/' url_details = ('http://www.ebook.nl/store/{0}') if external or self.config.get('open_external', False): if detail_item: url = url_details.format(detail_item) open_url(QUrl(url)) else: detail_url = None if detail_item: detail_url = url_details.format(detail_item) d = WebStoreDialog(self.gui, url, parent, detail_url) d.setWindowTitle(self.name) d.set_tags(self.config.get('tags', '')) d.exec_()
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)
def open(self, parent=None, detail_item=None, external=False): plain_url = 'http://www.legimi.com/pl/ebooki/' url = 'https://ssl.afiliant.com/affskrypt,,2f9de2,,11483,,,?u=(' + plain_url + ')' detail_url = None if detail_item: detail_url = 'https://ssl.afiliant.com/affskrypt,,2f9de2,,11483,,,?u=(' + detail_item + ')' if external or self.config.get('open_external', False): open_url(QUrl( url_slash_cleaner(detail_url if detail_url else url))) else: d = WebStoreDialog(self.gui, url, parent, detail_url) d.setWindowTitle(self.name) d.set_tags(self.config.get('tags', '')) d.exec_()
def open(self, parent=None, detail_item=None, external=False): url = 'http://klick.affiliwelt.net/klick.php?bannerid=10072&pid=32307&prid=908' url_details = ('http://klick.affiliwelt.net/klick.php?' 'bannerid=10730&pid=32307&prid=908&prodid={0}') if external or self.config.get('open_external', False): if detail_item: url = url_details.format(detail_item) open_url(QUrl(url)) else: detail_url = None if detail_item: detail_url = url_details.format(detail_item) d = WebStoreDialog(self.gui, url, parent, detail_url) d.setWindowTitle(self.name) d.set_tags(self.config.get('tags', '')) d.exec_()
def open(self, parent=None, detail_item=None, external=False): aff_root = 'https://www.a4b-tracking.com/pl/stat-click-text-link/16/58/' url = 'http://woblink.com/publication' aff_url = aff_root + str(b64encode(url)) detail_url = None if detail_item: detail_url = aff_root + str(b64encode('http://woblink.com' + detail_item)) if external or self.config.get('open_external', False): open_url(QUrl(url_slash_cleaner(detail_url if detail_url else aff_url))) else: d = WebStoreDialog(self.gui, url, parent, detail_url if detail_url else aff_url) d.setWindowTitle(self.name) d.set_tags(self.config.get('tags', '')) d.exec_()
def open(self, parent=None, detail_item=None, external=False): url = 'http://ad.zanox.com/ppc/?18817073C15644254T' url_details = ('http://ad.zanox.com/ppc/?18817073C15644254T&ULP=[[' 'http://www.ebook.de/shop/action/productDetails?artiId={0}]]') if external or self.config.get('open_external', False): if detail_item: url = url_details.format(detail_item) open_url(QUrl(url)) else: detail_url = None if detail_item: detail_url = url_details.format(detail_item) d = WebStoreDialog(self.gui, url, parent, detail_url) d.setWindowTitle(self.name) d.set_tags(self.config.get('tags', '')) d.exec_()
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)
def share(self): index = self.available_profiles.currentIndex() title, src = self._model.title(index), self._model.script(index) if not title or not src: error_dialog(self, _("No recipe selected"), _("No recipe selected")).exec_() return pt = PersistentTemporaryFile(suffix=".recipe") pt.write(src.encode("utf-8")) pt.close() body = _("The attached file: %(fname)s is a " "recipe to download %(title)s.") % dict( fname=os.path.basename(pt.name), title=title ) subject = _("Recipe for ") + title url = QUrl("mailto:") url.addQueryItem("subject", subject) url.addQueryItem("body", body) url.addQueryItem("attachment", pt.name) open_url(url)
def share(self): index = self.available_profiles.currentIndex() title, src = self._model.title(index), self._model.script(index) if not title or not src: error_dialog(self, _('No recipe selected'), _('No recipe selected')).exec_() return pt = PersistentTemporaryFile(suffix='.recipe') pt.write(src.encode('utf-8')) pt.close() body = _('The attached file: %(fname)s is a ' 'recipe to download %(title)s.')%dict( fname=os.path.basename(pt.name), title=title) subject = _('Recipe for ')+title url = QUrl('mailto:') url.addQueryItem('subject', subject) url.addQueryItem('body', body) url.addQueryItem('attachment', pt.name) open_url(url)
def search_online(self): t = unicode(self.selectedText()).strip() if t: url = 'https://www.google.com/search?q=' + QUrl().toPercentEncoding(t) open_url(QUrl.fromEncoded(url))
def popup_table(self): html = self.document.extract_node() self.table_popup(html, QUrl.fromLocalFile(self.last_loaded_path), self.document.font_magnification_step)
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_()
def open_local_file(path): if iswindows: os.startfile(os.path.normpath(path)) else: url = QUrl.fromLocalFile(path) open_url(url)
def show_help(self): self._log_location() path = os.path.join(self.parent.resources_path, 'help', 'marvin.html') open_url(QUrl.fromLocalFile(path))