def process_rule(self, rule, is_ancestor, maximum_specificities): selector = rule['selector'] sheet_index = rule['sheet_index'] rule_address = rule['rule_address'] or () if selector is not None: try: specificity = [0] + list(parse(selector)[0].specificity()) except (AttributeError, TypeError, SelectorError): specificity = [0, 0, 0, 0] else: # style attribute specificity = [1, 0, 0, 0] specificity.extend((sheet_index, tuple(rule_address))) ancestor_specificity = 0 if is_ancestor else 1 properties = [] for prop in rule['properties']: important = 1 if prop[-1] == 'important' else 0 p = Property(prop, [ancestor_specificity] + [important] + specificity) properties.append(p) if p.specificity > maximum_specificities.get(p.name, (0,0,0,0,0,0)): maximum_specificities[p.name] = p.specificity rule['properties'] = properties href = rule['href'] if hasattr(href, 'startswith') and href.startswith('%s://%s' % (FAKE_PROTOCOL, FAKE_HOST)): qurl = QUrl(href) name = qurl.path()[1:] if name: rule['href'] = name
def render_html(path_to_html, width=590, height=750, as_xhtml=True): from PyQt5.QtWebKitWidgets import QWebPage from PyQt5.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 get_proxy_auth_credentials(qurl, authenticator, proxy_host, parent=None): qurl = QUrl(qurl) qurl.setFragment(None) d = Credentials(_('Please specify a password for {0} at the proxy: {1}').format(qurl.toString(), proxy_host), parent) if d.exec_() == d.Accepted: username, password = d.credentials authenticator.setUser(username) authenticator.setPassword(password)
def urls_from_md(md): ans = list(md.urls()) if md.hasText(): # Chromium returns the url as text/plain on drag and drop of image text = md.text() if text and text.lstrip().partition(':')[0] in {'http', 'https', 'ftp'}: u = QUrl(text.strip()) if u.isValid(): ans.append(u) return ans
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(self, url = ''): p = re.compile('(^file:\/\/)|(^http:\/\/)|(^https:\/\/)|(^data:)') if url and p.match(url) == None: url = QUrl.fromLocalFile(os.path.abspath(url)) else: url = QUrl(url) super(WebView, self).load(url)
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 load_html(path, view, codec='utf-8', mime_type=None, pre_load_callback=lambda x:None, path_is_html=False, force_as_html=False, loading_url=None): from PyQt5.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 = cleanup_html(html) loading_url = loading_url or QUrl.fromLocalFile(path) pre_load_callback(loading_url) if force_as_html or load_as_html(html): 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 open_local_file(path): if iswindows: with sanitize_env_vars(): os.startfile(os.path.normpath(path)) else: url = QUrl.fromLocalFile(path) open_url(url)
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 PyQt5.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 and '<![CDATA[' not in html: 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 load_footnote_data(self, current_url): fd = self.footnote_data_cache[current_url] = {} try: raw = self.view.document.javascript('window.calibre_extract.get_footnote_data()', typ='string') for x in json.loads(raw or '{}'): if x not in fd: qu = QUrl(x) path = qu.toLocalFile() spath = self.spine_path(path) if spath is not None: target = qu.fragment(QUrl.FullyDecoded) fd[qu.toString()] = (spath, target, qu) self.known_footnote_targets[spath].add(target) except Exception: prints('Failed to get footnote data, with error:') import traceback traceback.print_exc() return fd
def set_html(mi, html, web_view): from calibre.gui2.ui import get_gui gui = get_gui() book_id = getattr(mi, 'id', None) if gui and book_id is not None: path = gui.current_db.abspath(book_id, index_is_id=True) if path: web_view.setHtml(html, QUrl.fromLocalFile(os.path.join(path, 'metadata.html'))) return web_view.setHtml(html)
def _paste_and_go(window, in_current_tab=True): c = QApplication.clipboard() for mode in c.Clipboard, c.Selection: text = c.text(mode).strip() if text: if text.partition(':')[0].lower() in {'file', 'http', 'https', 'about'}: qurl = QUrl.fromUserInput(text) if qurl.isValid() and not qurl.isEmpty(): window.open_url(qurl, in_current_tab=in_current_tab) return window.show_status_message(_('No URL in clipboard'), 2, 'success')
def current_changed(self, current, previous): link = current.data(Qt.UserRole) if link is None: return url = None if link.is_external: if link.href: frag = ('#' + link.anchor.id) if link.anchor.id else '' url = QUrl(link.href + frag) elif link.anchor.location: path = current_container().name_to_abspath(link.anchor.location.name) if path and os.path.exists(path): url = QUrl.fromLocalFile(path) if link.anchor.id: url.setFragment(link.anchor.id) if url is None: self.view.setHtml('<p>' + _('No destination found for this link')) self.current_url = url elif url != self.current_url: self.current_url = url self.view.setUrl(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", b"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 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 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)) self.refresh_starting.emit() if current_url != self.view.url(): # The container was changed self.view.setUrl(current_url) else: self.view.refresh() self.refreshed.emit()
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 set_message(self, text, color_, bold=False, is_permanent=False): from vise.view import certificate_error_domains key = (text, color_.name(), bold, is_permanent) if key == self.current_key: return self.current_key = key self.is_permanent = is_permanent prefix = text.partition(':')[0] self.is_address = self.is_permanent and prefix.lower() in {'http', 'https', 'vise'} self.is_secure = prefix.lower() in {'https', 'vise'} color_ = color_ or self.palette().color(self.palette().WindowText) if self.is_address: qurl = QUrl(text) if self.is_secure and qurl.host() in certificate_error_domains: self.is_secure = False if qurl.scheme() == 'vise': host = qurl.path() rest = '' sep = ':' else: host = qurl.host() rest = qurl.toDisplayString(QUrl.PrettyDecoded | QUrl.RemoveScheme | QUrl.RemoveAuthority) sep = '://' self.static_text = QStaticText( '<span style="white-space:nowrap; color: {fg}">' '<span style="color:{emph}; font-weight:bold">{scheme}</span><span style="color:{dull}">{sep}</span>' '<span style="color:{fg}">{host}</span>' '<span style="color:{dull}">{rest}</span>'.format( fg=color_.name(), emph='green' if self.is_secure else 'red', scheme=escape(qurl.scheme()), host=escape(host), dull=color('status bar dull foreground', 'gray'), sep=sep, rest=escape(rest) )) else: self.static_text = QStaticText('<span style="color:{}; font-weight: {}; white-space:nowrap">{}</span>'.format( color_.name(), ('bold' if bold else 'normal'), escape(text))) to = QTextOption(Qt.AlignLeft | Qt.AlignTop) to.setWrapMode(to.NoWrap) self.static_text.setTextOption(to) self.static_text.prepare(font=self.font()) self.update()
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 get_http_auth_credentials(qurl, authenticator, parent=None): qurl = QUrl(qurl) qurl.setFragment(None) realm = authenticator.realm() trealm = (' (%s)' % realm) if realm else '' ac = parent and parent.get_login_credentials(qurl.toString()) d = Credentials(_('Please specify a password for {0}{1}').format(qurl.toString(), trealm), parent) if ac is not None: if ac['autologin']: authenticator.setUser(ac['username']) authenticator.setPassword(ac['password']) return d.credentials = ac['username'], ac['password'] if d.exec_() == d.Accepted: username, password = d.credentials authenticator.setUser(username) authenticator.setPassword(password) if parent is not None: parent.on_login_form_submit(qurl.toString(), username, password) else: if parent is not None: parent.setHtml('<p style="font-family:sans-serif">{} {}</p>'.format( _('Authentication required to access: '), '<a href="{0}">{0}</a>'.format(qurl.toDisplayString())))
def as_url(self, abspath): name = os.path.relpath(abspath, self.root).replace('\\', '/') ans = QUrl() ans.setScheme(FAKE_PROTOCOL), ans.setAuthority(FAKE_HOST), ans.setPath('/' + name) return ans
def path_to_url(path): return QUrl.fromLocalFile(path).toString()
def url(self, url): self.setUrl(QUrl(url))
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 openMail(self): QDesktopServices.openUrl( QUrl("mailto:[email protected]?subject=Error&body=REPORTAR ERROR :" ))
def create_actions(self): group = _('Global actions') def reg(icon, text, target, sid, keys, description, toolbar_allowed=False): if not isinstance(icon, QIcon): icon = QIcon(I(icon)) ac = actions[sid] = QAction(icon, text, self) if icon else QAction( text, self) ac.setObjectName('action-' + sid) if toolbar_allowed: toolbar_actions[sid] = ac if target is not None: ac.triggered.connect(target) if isinstance(keys, type('')): keys = (keys, ) self.keyboard.register_shortcut(sid, unicode(ac.text()).replace( '&', ''), default_keys=keys, description=description, action=ac, group=group) self.addAction(ac) return ac def treg(icon, text, target, sid, keys, description): return reg(icon, text, target, sid, keys, description, toolbar_allowed=icon is not None) self.action_new_file = treg('document-new.png', _('&New file (images/fonts/HTML/etc.)'), self.boss.add_file, 'new-file', (), _('Create a new file in the current book')) self.action_import_files = treg('document-import.png', _('&Import files into book'), self.boss.add_files, 'new-files', (), _('Import files into book')) self.action_open_book = treg('document_open.png', _('&Open book'), self.boss.open_book, 'open-book', 'Ctrl+O', _('Open a new book')) self.action_open_book_folder = treg( 'mimetypes/dir.png', _('Open &folder (unzipped EPUB) as book'), partial(self.boss.open_book, open_folder=True), 'open-folder-as-book', (), _('Open a folder (unzipped EPUB) as a book')) # Qt does not generate shortcut overrides for cmd+arrow on os x which # means these shortcuts interfere with editing self.action_global_undo = treg( 'back.png', _('&Revert to before'), self.boss.do_global_undo, 'global-undo', () if isosx else 'Ctrl+Left', _('Revert book to before the last action (Undo)')) self.action_global_redo = treg( 'forward.png', _('&Revert to after'), self.boss.do_global_redo, 'global-redo', () if isosx else 'Ctrl+Right', _('Revert book state to after the next action (Redo)')) self.action_save = treg('save.png', _('&Save'), self.boss.save_book, 'save-book', 'Ctrl+S', _('Save book')) self.action_save.setEnabled(False) self.action_save_copy = treg('save.png', _('Save a ©'), self.boss.save_copy, 'save-copy', 'Ctrl+Alt+S', _('Save a copy of the book')) self.action_quit = treg('window-close.png', _('&Quit'), self.boss.quit, 'quit', 'Ctrl+Q', _('Quit')) self.action_preferences = treg('config.png', _('&Preferences'), self.boss.preferences, 'preferences', 'Ctrl+P', _('Preferences')) self.action_new_book = treg('plus.png', _('Create &new, empty book'), self.boss.new_book, 'new-book', (), _('Create a new, empty book')) self.action_import_book = treg( 'add_book.png', _('&Import an HTML or DOCX file as a new book'), self.boss.import_book, 'import-book', (), _('Import an HTML or DOCX file as a new book')) self.action_quick_edit = treg( 'modified.png', _('&Quick open a file to edit'), self.boss.quick_open, 'quick-open', ('Ctrl+T'), _('Quickly open a file from the book to edit it')) # Editor actions group = _('Editor actions') self.action_editor_undo = reg('edit-undo.png', _('&Undo'), self.boss.do_editor_undo, 'editor-undo', 'Ctrl+Z', _('Undo typing')) self.action_editor_redo = reg('edit-redo.png', _('R&edo'), self.boss.do_editor_redo, 'editor-redo', 'Ctrl+Y', _('Redo typing')) self.action_editor_cut = reg('edit-cut.png', _('Cut &text'), self.boss.do_editor_cut, 'editor-cut', ( 'Ctrl+X', 'Shift+Delete', ), _('Cut text')) self.action_editor_copy = reg('edit-copy.png', _('&Copy to clipboard'), self.boss.do_editor_copy, 'editor-copy', ('Ctrl+C', 'Ctrl+Insert'), _('Copy to clipboard')) self.action_editor_paste = reg('edit-paste.png', _('P&aste from clipboard'), self.boss.do_editor_paste, 'editor-paste', ( 'Ctrl+V', 'Shift+Insert', ), _('Paste from clipboard')) self.action_editor_cut.setEnabled(False) self.action_editor_copy.setEnabled(False) self.action_editor_undo.setEnabled(False) self.action_editor_redo.setEnabled(False) # Tool actions group = _('Tools') self.action_toc = treg('toc.png', _('&Edit Table of Contents'), self.boss.edit_toc, 'edit-toc', (), _('Edit Table of Contents')) self.action_inline_toc = treg('chapters.png', _('&Insert inline Table of Contents'), self.boss.insert_inline_toc, 'insert-inline-toc', (), _('Insert inline Table of Contents')) self.action_fix_html_current = reg('html-fix.png', _('&Fix HTML'), partial(self.boss.fix_html, True), 'fix-html-current', (), _('Fix HTML in the current file')) self.action_fix_html_all = treg('html-fix.png', _('&Fix HTML - all files'), partial(self.boss.fix_html, False), 'fix-html-all', (), _('Fix HTML in all files')) self.action_pretty_current = reg('beautify.png', _('&Beautify current file'), partial(self.boss.pretty_print, True), 'pretty-current', (), _('Beautify current file')) self.action_pretty_all = treg('beautify.png', _('&Beautify all files'), partial(self.boss.pretty_print, False), 'pretty-all', (), _('Beautify all files')) self.action_insert_char = treg('character-set.png', _('&Insert special character'), self.boss.insert_character, 'insert-character', (), _('Insert special character')) self.action_rationalize_folders = treg('mimetypes/dir.png', _('&Arrange into folders'), self.boss.rationalize_folders, 'rationalize-folders', (), _('Arrange into folders')) self.action_set_semantics = treg('tags.png', _('Set &semantics'), self.boss.set_semantics, 'set-semantics', (), _('Set semantics')) self.action_filter_css = treg('filter.png', _('&Filter style information'), self.boss.filter_css, 'filter-css', (), _('Filter style information')) self.action_manage_fonts = treg('font.png', _('&Manage fonts'), self.boss.manage_fonts, 'manage-fonts', (), _('Manage fonts in the book')) self.action_add_cover = treg('default_cover.png', _('Add &cover'), self.boss.add_cover, 'add-cover', (), _('Add a cover to the book')) self.action_reports = treg( 'reports.png', _('&Reports'), self.boss.show_reports, 'show-reports', ('Ctrl+Shift+R', ), _('Show a report on various aspects of the book')) self.action_check_external_links = treg( 'insert-link.png', _('Check &external links'), self.boss.check_external_links, 'check-external-links', (), _('Check external links in the book')) self.action_compress_images = treg('compress-image.png', _('C&ompress images losslessly'), self.boss.compress_images, 'compress-images', (), _('Compress images losslessly')) self.action_transform_styles = treg( 'wizard.png', _('Transform &styles'), self.boss.transform_styles, 'transform-styles', (), _('Transform styles used in the book')) self.action_get_ext_resources = treg( 'download-metadata.png', _('Download external &resources'), self.boss.get_external_resources, 'get-external-resources', (), _('Download external resources in the book (images/stylesheets/etc/ that are not included in the book)' )) def ereg(icon, text, target, sid, keys, description): return reg(icon, text, partial(self.boss.editor_action, target), sid, keys, description) register_text_editor_actions(ereg, self.palette()) # Polish actions group = _('Polish book') self.action_subset_fonts = treg( 'subset-fonts.png', _('&Subset embedded fonts'), partial(self.boss.polish, 'subset', _('Subset fonts')), 'subset-fonts', (), _('Subset embedded fonts')) self.action_embed_fonts = treg( 'embed-fonts.png', _('&Embed referenced fonts'), partial(self.boss.polish, 'embed', _('Embed fonts')), 'embed-fonts', (), _('Embed referenced fonts')) self.action_smarten_punctuation = treg( 'smarten-punctuation.png', _('&Smarten punctuation (works best for English)'), partial(self.boss.polish, 'smarten_punctuation', _('Smarten punctuation')), 'smarten-punctuation', (), _('Smarten punctuation')) self.action_remove_unused_css = treg( 'edit-clear.png', _('Remove &unused CSS rules'), partial(self.boss.polish, 'remove_unused_css', _('Remove unused CSS rules')), 'remove-unused-css', (), _('Remove unused CSS rules')) self.action_remove_unused_css = treg( 'arrow-up.png', _('&Upgrade book internals'), partial(self.boss.polish, 'upgrade_book', _('Upgrade book internals')), 'upgrade-book', (), _('Upgrade book internals')) # Preview actions group = _('Preview') self.action_auto_reload_preview = reg('auto-reload.png', _('Auto reload preview'), None, 'auto-reload-preview', (), _('Auto reload preview')) self.action_auto_sync_preview = reg( 'sync-right.png', _('Sync preview position to editor position'), None, 'sync-preview-to-editor', (), _('Sync preview position to editor position')) self.action_reload_preview = reg('view-refresh.png', _('Refresh preview'), None, 'reload-preview', ('F5', ), _('Refresh preview')) self.action_split_in_preview = reg( 'document-split.png', _('Split this file'), None, 'split-in-preview', (), _('Split file in the preview panel')) self.action_find_next_preview = reg('arrow-down.png', _('Find next'), None, 'find-next-preview', (), _('Find next in preview')) self.action_find_prev_preview = reg('arrow-up.png', _('Find previous'), None, 'find-prev-preview', (), _('Find previous in preview')) # Search actions group = _('Search') self.action_find = treg('search.png', _('&Find/replace'), self.boss.show_find, 'find-replace', ('Ctrl+F', ), _('Show the Find/replace panel')) def sreg(name, text, action, overrides={}, keys=(), description=None, icon=None): return reg( icon, text, partial(self.boss.search_action_triggered, action, overrides), name, keys, description or text.replace('&', '')) self.action_find_next = sreg('find-next', _('Find &next'), 'find', {'direction': 'down'}, ('F3', 'Ctrl+G'), _('Find next match')) self.action_find_previous = sreg('find-previous', _('Find &previous'), 'find', {'direction': 'up'}, ('Shift+F3', 'Shift+Ctrl+G'), _('Find previous match')) self.action_replace = sreg('replace', _('&Replace'), 'replace', keys=('Ctrl+R'), description=_('Replace current match')) self.action_replace_next = sreg( 'replace-next', _('&Replace and find next'), 'replace-find', {'direction': 'down'}, ('Ctrl+]'), _('Replace current match and find next')) self.action_replace_previous = sreg( 'replace-previous', _('R&eplace and find previous'), 'replace-find', {'direction': 'up'}, ('Ctrl+['), _('Replace current match and find previous')) self.action_replace_all = sreg('replace-all', _('Replace &all'), 'replace-all', keys=('Ctrl+A'), description=_('Replace all matches')) self.action_count = sreg('count-matches', _('&Count all'), 'count', keys=('Ctrl+N'), description=_('Count number of matches')) self.action_mark = reg( None, _('&Mark selected text'), self.boss.mark_selected_text, 'mark-selected-text', ('Ctrl+Shift+M', ), _('Mark selected text or unmark already marked text')) self.action_mark.default_text = self.action_mark.text() self.action_go_to_line = reg(None, _('Go to &line'), self.boss.go_to_line_number, 'go-to-line-number', ('Ctrl+.', ), _('Go to line number')) self.action_saved_searches = treg('folder_saved_search.png', _('Sa&ved searches'), self.boss.saved_searches, 'saved-searches', (), _('Show the saved searches dialog')) self.action_text_search = treg('view.png', _('&Search ignoring HTML markup'), self.boss.show_text_search, 'text-search', (), _('Show the text search panel')) # Check Book actions group = _('Check book') self.action_check_book = treg('debug.png', _('&Check book'), self.boss.check_requested, 'check-book', ('F7'), _('Check book for errors')) self.action_spell_check_book = treg( 'spell-check.png', _('Check &spelling'), self.boss.spell_check_requested, 'spell-check-book', ('Alt+F7'), _('Check book for spelling errors')) self.action_check_book_next = reg( 'forward.png', _('&Next error'), partial(self.check_book.next_error, delta=1), 'check-book-next', ('Ctrl+F7'), _('Show next error')) self.action_check_book_previous = reg( 'back.png', _('&Previous error'), partial(self.check_book.next_error, delta=-1), 'check-book-previous', ('Ctrl+Shift+F7'), _('Show previous error')) self.action_spell_check_next = reg('forward.png', _('&Next spelling mistake'), self.boss.next_spell_error, 'spell-next', ('F8'), _('Go to next spelling mistake')) # Miscellaneous actions group = _('Miscellaneous') self.action_create_checkpoint = treg( 'marked.png', _('&Create checkpoint'), self.boss.create_checkpoint, 'create-checkpoint', (), _('Create a checkpoint with the current state of the book')) self.action_close_current_tab = reg('window-close.png', _('&Close current tab'), self.central.close_current_editor, 'close-current-tab', 'Ctrl+W', _('Close the currently open tab')) self.action_close_all_but_current_tab = reg( 'edit-clear.png', _('&Close other tabs'), self.central.close_all_but_current_editor, 'close-all-but-current-tab', 'Ctrl+Alt+W', _('Close all tabs except the current tab')) self.action_help = treg( 'help.png', _('User &Manual'), lambda: open_url( QUrl( localize_user_manual_link( 'https://manual.calibre-ebook.com/edit.html'))), 'user-manual', 'F1', _('Show User Manual')) self.action_browse_images = treg( 'view-image.png', _('&Browse images in book'), self.boss.browse_images, 'browse-images', (), _('Browse images in the books visually')) self.action_multiple_split = treg( 'document-split.png', _('&Split at multiple locations'), self.boss.multisplit, 'multisplit', (), _('Split HTML file at multiple locations')) self.action_compare_book = treg('diff.png', _('Compare to &another book'), self.boss.compare_book, 'compare-book', (), _('Compare to another book')) self.action_manage_snippets = treg('snippets.png', _('Manage &Snippets'), self.boss.manage_snippets, 'manage-snippets', (), _('Manage user created snippets')) self.plugin_menu_actions = [] create_plugin_actions(actions, toolbar_actions, self.plugin_menu_actions)
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.ConnectionType.QueuedConnection) d() def cleanup(self): for d in tuple(self.dialogs): if not d.isVisible(): self.dialogs.remove(d) if __name__ == '__main__': import sys from calibre.gui2 import Application app = Application([]) p = QPixmap() p.load(sys.argv[-1]) u = QUrl.fromLocalFile(sys.argv[-1]) d = ImageView(None, p, u) d() app.exec_()
def _openUrlInNewWindow(self, url=QUrl()): url = not url.isEmpty() and url or self._ui.historyTree.selectedUrl() gVar.app.createWindow(const.BW_NewWindow, url) self._window.weView().loadByUrl(url)
def donate(self, *args): from calibre.utils.localization import localize_website_link open_url( QUrl(localize_website_link('https://calibre-ebook.com/donate')))
def _openUrl(self, url=QUrl()): url = not url.isEmpty() and url or self._ui.historyTree.selectedUrl() self._window.weView().loadByUrl(url)
def _openUrlInNewTab(self, url=QUrl()): url = not url.isEmpty() and url or self._ui.historyTree.selectedUrl() self._window.tabWidget().addView(url, gVar.appSettings.newTabPosition)
def accept(self): open_url(QUrl(get_download_url())) QDialog.accept(self)
def pyecharts_update12(self, show_all, show_prim, prim_dele,prim_add ,show_Kruskal, Kruskal_dele,Kruskal_add): # def diff_set(a, b): a_, b_ = map(lambda x: {frozenset(k): k for k in x}, [a, b]) return [a_[k] for k in a_.keys() - b_.keys()] place = list(zip(self.new_kr.place_name, range(self.new_kr.m))) self.bian = list( (self.new_kr.place_name[x], self.new_kr.place_name[y]) for x in range(self.new_kr.m) for y in # 算一下边 range(x + 1, self.new_kr.m) if self.new_kr.matrix[x][y] != float('inf')) attr1 = self.bian if show_all: attr2 = [] attr3 = attr1 self.i1=self.i2=0 elif show_prim: if self.flag1 == 0: self.ans_path.clear() attr2 = self.ans_path attr3 = diff_set(attr1, attr2) print('prim路径数量为',len(attr2)) elif show_Kruskal: if self.flag2 == 0: self.ans_path2.clear() attr2 = self.ans_path2 attr3 = diff_set(attr1, attr2) print('克鲁斯卡尔路径数量为', len(attr2)) elif prim_add: self.i1+=1 if self.i1>self.new_kr.m-1: self.i1 =0 attr2 = self.ans_path[:self.i1] attr3 = diff_set(attr1, attr2) print('prim',self.i1) elif prim_dele: self.i1 -= 1 if self.i1 < 0: self.i1 = self.new_kr.m-1 attr2 = self.ans_path[:self.i1] attr3 = diff_set(attr1, attr2) print('prim',self.i1) elif Kruskal_add: self.i2+=1 if self.i2>self.new_kr.m-1: self.i2=0 attr2 = self.ans_path2[:self.i2] attr3 = diff_set(attr1, attr2) print('Kruskal',self.i2) elif Kruskal_dele: self.i2 -= 1 if self.i2 < 0: self.i2 = self.new_kr.m-1 attr2 = self.ans_path2[:self.i2] attr3 = diff_set(attr1, attr2) print('Kruskal',self.i2) geo = ( Geo(init_opts={"width": 1300, "bg_color": "#2a59"}) .add_schema( maptype="china", itemstyle_opts=opts.ItemStyleOpts(color="#323c48", border_color="#111"), # label_opts=opts.LabelOpts(is_show=True) ) .add( # 这个不用动 "", place, type_=ChartType.EFFECT_SCATTER, color="green", label_opts=opts.LabelOpts(is_show=True) ) .add( # 路径以外的边 "", attr3, type_=ChartType.LINES, linestyle_opts=opts.LineStyleOpts(curve=0.2, color='red'), ) .add( # 路径的边 "", attr2, type_=ChartType.LINES, linestyle_opts=opts.LineStyleOpts(curve=0.2, color='white'), ) .set_series_opts(label_opts=opts.LabelOpts(is_show=False)) .set_global_opts(title_opts=opts.TitleOpts(title="城市交通图")) ) geo.render(path='D:/pycharm/untitled/GUI/图.html') self.browser.load(QUrl("file:///D:/pycharm/untitled/GUI/图.html"))
def createList(self): hoy = str(datetime.datetime.now().year) + str(datetime.datetime.now().month) + str(datetime.datetime.now().day) + str(datetime.datetime.now().hour) + str(datetime.datetime.now().minute) + str(datetime.datetime.now().second) nombrePdf = '../archivos/' + str(hoy + 'LIST') + '.pdf' listTable = "" for lista in self.listFinal: listTable += """ <tr height="80"> <td width="40%" align="center" > <br>""" + str(lista[0]) + """<br> </td> <td width="40%" > <br> """ + str(lista[1]) + """<br> </td> <td width="20%" > <br> """ + str(lista[2]) + """<br> </td> </tr> """ subtitle = "Listado de clientes con deudas : " if self.type == 'PROV': subtitle = "Listado de deudas a proveedores : " fecha = str(datetime.datetime.now()) html = """ <table width="600"> <tr width="600" color="#000000"> <td width="80%"> </td> <td width="20%" align="right"> <IMG SRC="kde1.png"> </td> </tr> </table> <hr> <br> <p> """+ subtitle + """ </p> <br> <table width="600" height="0" style="border-color: black; border-width: 0.5px; border-spacing: 0;"> <tr style=" background-color: gray; border-style: inset;"> <td width="40%" align="center" valign="middle"> <b> APELLIDO </b> </td> <td width="40%" align="center" valign="middle"> <b> NOMBRE </b> </td> <td width="20%" align="center" valign="middle"> <b> DEUDA </b> </td> </tr> </table> <br> <br> <table width="600" height="0" style="border-color: black; border-width: 0.5px; border-spacing: 0;"> """ + listTable + """ </table> <br> <br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br> <hr> <br> <table width="600"> <tr> <td align="right" width="100%"> FECHA/HORA : """+ fecha + """ </td> </tr> </table> <hr> """ doc = QTextDocument() doc.setHtml(html) printer = QPrinter() printer.setOutputFileName(nombrePdf) printer.setOutputFormat(QPrinter.PdfFormat) doc.print(printer) printer.newPage() url = QUrl url = QUrl(nombrePdf) QDesktopServices.openUrl(url)
def search_engine(q): ans = QUrl('https://google.com/search') qq = QUrlQuery() qq.addQueryItem('q', q) ans.setQuery(qq) return ans
def as_url(self, abspath): name = os.path.relpath(abspath, self.root).replace('\\', '/') ans = QUrl() ans.setScheme(FAKE_PROTOCOL), ans.setAuthority(FAKE_HOST), ans.setPath( '/' + name) return ans
def open_donate(): open_url(QUrl(localize_website_link('https://calibre-ebook.com/donate')))
def open(self, parent=None, detail_item=None, external=False): store_link = (DETAILS_URL + detail_item) if detail_item else STORE_LINK open_url(QUrl(store_link))
def open_donate(): open_url(QUrl('https://calibre-ebook.com/donate'))
def donate(self, *args): open_url(QUrl('http://calibre-ebook.com/donate'))
def __init__(self, parent): self.current_img = QPixmap() self.current_url = QUrl() self.parent = parent self.dialogs = []
def browse(url): try: safe_open_url(QUrl(url, QUrl.TolerantMode)) except Exception: import traceback traceback.print_exc()
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net> import base64 from PyQt5.Qt import QUrl, QByteArray from .constants import WELCOME_URL as WU from .resources import get_icon, get_data WELCOME_URL = QUrl(WU) def welcome_icon(): if not hasattr(welcome_icon, 'icon'): welcome_icon.icon = get_icon('vise.svg') return welcome_icon.icon def get_welcome_html(): if not hasattr(get_welcome_html, 'html'): d = get_data('welcome.html').decode('utf-8') ic = get_data('images/vise.svg') d = d.replace( 'VISE_ICON', 'data:image/svg+xml;base64,' + base64.standard_b64encode(ic).decode('ascii')) get_welcome_html.html = QByteArray(d.encode('utf-8')) return get_welcome_html.html
def _donate_clicked(self): plugin = self._selected_display_plugin() if plugin and plugin.donation_link: open_url(QUrl(plugin.donation_link))
def analyze(self, url_to_request, timeout=10, current_depth=None, method="GET", data={}): try: url_to_request = url_to_request.toString() except AttributeError: url_to_request = url_to_request logging.debug("Start analyzing the url {}...".format(url_to_request)) self._timing_requests = [] self._new_clickables = [] self._timeming_events = [] self._current_timeming_event = None self._loading_complete = False self._analyzing_finished = False self.response_code = {} if method == "GET": self.mainFrame().load(QUrl(url_to_request)) else: request = self.make_request(url_to_request) data = self.post_data_to_array(data) request.setRawHeader( 'Content-Type', QByteArray('application/x-www-form-urlencoded')) self.mainFrame().load(request, QNetworkAccessManager.PostOperation, data) t = 0 while (not self._loading_complete and t < timeout): # Waiting for finish processing self._wait(self.wait_for_processing) t += self.wait_for_processing videos = self.mainFrame().findAllElements("video") if len(videos) > 0: logging.debug("{} videos found... removing them") for video in videos: video.removeFromDocument() overall_waiting_time = t buffer = 250 while len( self._timeming_events) > 0 and overall_waiting_time < timeout: self._current_timeming_event = self._timeming_events.pop( 0) # Take the first event(ordered by needed time self._waiting_for = self._current_timeming_event[ 'event_type'] # Setting kind of event waiting_time_in_milliseconds = ( self._current_timeming_event["time"] - overall_waiting_time ) # Taking waiting time and convert it from milliseconds to seconds waiting_time_in_milliseconds = ( (waiting_time_in_milliseconds + buffer) / 1000.0) if waiting_time_in_milliseconds < 0.0: waiting_time_in_milliseconds = 0 self._wait(waiting_time_in_milliseconds ) # Waiting for 100 millisecond before expected event overall_waiting_time += waiting_time_in_milliseconds if overall_waiting_time < 0.5: self._wait((0.5 - overall_waiting_time)) # Just for debugging #f = open("text.txt", "w", encoding="utf-8") #f.write(self.mainFrame().toHtml()) #f.close() base_url = self.mainFrame().findFirstElement("base") if base_url is not None: base_url = base_url.attribute("href") links, clickables = extract_links(self.mainFrame(), url_to_request) forms = extract_forms(self.mainFrame()) elements_with_event_properties = property_helper(self.mainFrame()) self.mainFrame().evaluateJavaScript(self._property_obs_js) self._wait(0.1) self._analyzing_finished = True html_after_timeouts = self.mainFrame().toHtml() response_url = self.mainFrame().url().toString() self.mainFrame().setHtml(None) self._new_clickables.extend(clickables) self._new_clickables.extend(elements_with_event_properties) self._new_clickables = purge_dublicates(self._new_clickables) response_code = None try: response_code = self.response_code[url_to_request] except KeyError: response_code = 200 if response_code is None: response_code = 200 try: current_page = WebPage(self.parent().get_next_page_id(), response_url, html_after_timeouts) except AttributeError: #Attacker don't need this function... current_page = WebPage(42, response_url, html_after_timeouts) current_page.timing_requests = self._timing_requests current_page.clickables = self._new_clickables current_page.links = links current_page.forms = forms if base_url is not None and base_url != "": current_page.base_url = base_url return response_code, current_page
def _forum_label_activated(self): if self.forum_link: open_url(QUrl(self.forum_link))
def openManual(self): url = QUrl url = QUrl("../Recursos/Manual.pdf") QDesktopServices.openUrl(url)
def show_html(self, html, in_current_tab=True): if isinstance(html, bytes): html = html.decode('utf-8') tab = self.get_tab_for_load(in_current_tab=in_current_tab) tab.setHtml(html, QUrl.fromLocalFile(os.path.expanduser('~')))
def name_to_qurl(self, name=None): name = name or self.current_name qurl = QUrl() qurl.setScheme(FAKE_PROTOCOL), qurl.setAuthority(FAKE_HOST), qurl.setPath('/' + name) return qurl
def initialize(self, book_id): path = self.db.abspath(book_id, index_is_id=True) if path: self._tb.set_base_url(QUrl.fromLocalFile(os.path.join(path, 'metadata.html'))) return Base.initialize(self, book_id)
def localUrl(self, path = ''): return QUrl.fromLocalFile(path).toString()
def open_local_file(path): if iswindows: os.startfile(os.path.normpath(path)) else: url = QUrl.fromLocalFile(path) open_url(url)
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 load_path(self, path, frag=None): self._page.current_frag = frag self.setUrl(QUrl.fromLocalFile(path))
def load_url(self, url): self.dom_loaded = False url = QUrl(url) self.mainFrame().load(url) self.ready_state # Without this, DOMContentLoaded does not fire for file:// URLs
def name_to_qurl(self, name=None): name = name or self.current_name qurl = QUrl() qurl.setScheme(FAKE_PROTOCOL), qurl.setAuthority( FAKE_HOST), qurl.setPath('/' + name) return qurl
def _openUrlInNewPrivateWindow(self, url=QUrl()): url = not url.isEmpty() and url or self._ui.historyTree.selectedUrl() gVar.app.startPrivateBrowsing(url)
def show_help(self): self._log_location() path = os.path.join(self.parent.resources_path, 'help', 'marvin.html') open_url(QUrl.fromLocalFile(path))