def dirbrowser_html(path): """Get the directory browser web page. Args: path: The directory path. Return: The HTML of the web page. """ title = "Browse directory: {}".format(path) if is_root(path): parent = None else: parent = parent_dir(path) try: all_files = os.listdir(path) except OSError as e: html = jinja.render('error.html', title="Error while reading directory", url='file:///{}'.format(path), error=str(e)) return html.encode('UTF-8', errors='xmlcharrefreplace') files = get_file_list(path, all_files, os.path.isfile) directories = get_file_list(path, all_files, os.path.isdir) html = jinja.render('dirbrowser.html', title=title, url=path, parent=parent, files=files, directories=directories) return html.encode('UTF-8', errors='xmlcharrefreplace')
def glimpse_warning(url): """Handler for glimpse://warning.""" path = url.path() if path == '/old-qt': src = jinja.render('warning-old-qt.html', title='Old Qt warning', qt_version=qVersion()) elif path == '/webkit': src = jinja.render('warning-webkit.html', title='QtWebKit backend warning') else: raise NotFoundError("Invalid warning page {}".format(path)) return 'text/html', src
def test_data_url(): """Test data_url() which can be used from templates.""" data = jinja.render('test3.html') print(data) url = QUrl(data) assert url.isValid() assert data == 'data:text/plain;base64,Zm9v' # 'foo'
def _on_renderer_process_terminated(self, tab, status, code): """Show an error when a renderer process terminated.""" if status == browsertab.TerminationStatus.normal: return messages = { browsertab.TerminationStatus.abnormal: "Renderer process exited with status {}".format(code), browsertab.TerminationStatus.crashed: "Renderer process crashed", browsertab.TerminationStatus.killed: "Renderer process was killed", browsertab.TerminationStatus.unknown: "Renderer process did not start", } msg = messages[status] def show_error_page(html): tab.set_html(html) log.webview.error(msg) if qtutils.version_check('5.9', compiled=False): url_string = tab.url(requested=True).toDisplayString() error_page = jinja.render( 'error.html', title="Error loading {}".format(url_string), url=url_string, error=msg) QTimer.singleShot(100, lambda: show_error_page(error_page)) else: # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-58698 message.error(msg) self._remove_tab(tab, crashed=True) if self.widget.count() == 0: self.tabopen(QUrl('about:blank'))
def glimpse_version(_url): """Handler for glimpse://version.""" src = jinja.render('version.html', title='Version info', version=version.version(), copyright=glimpsebrowser.__copyright__) return 'text/html', src
def glimpse_settings(url): """Handler for glimpse://settings. View/change glimpse configuration.""" global csrf_token if url.path() == '/set': if url.password() != csrf_token: message.error("Invalid CSRF token for glimpse://settings!") raise RequestDeniedError("Invalid CSRF token!") return _glimpse_settings_set(url) # Requests to glimpse://settings/set should only be allowed from # glimpse://settings. As an additional security precaution, we generate a CSRF # token to use here. if secrets: csrf_token = secrets.token_urlsafe() else: # On Python < 3.6, from secrets.py token = base64.urlsafe_b64encode(os.urandom(32)) csrf_token = token.rstrip(b'=').decode('ascii') src = jinja.render('settings.html', title='settings', configdata=configdata, confget=config.instance.get_str, csrf_token=csrf_token) return 'text/html', src
def generate_pdfjs_page(filename, url): """Return the html content of a page that displays a file with pdfjs. Returns a string. Args: filename: The filename of the PDF to open. url: The URL being opened. """ if not is_available(): pdfjs_dir = os.path.join(standarddir.data(), 'pdfjs') return jinja.render('no_pdfjs.html', url=url.toDisplayString(), title="PDF.js not found", pdfjs_dir=pdfjs_dir) html = get_pdfjs_res('web/viewer.html').decode('utf-8') script = _generate_pdfjs_script(filename) html = html.replace('</body>', '</body><script>{}</script>'.format(script)) # WORKAROUND for the fact that PDF.js tries to use the Fetch API even with # glimpse:// URLs. pdfjs_script = '<script src="../build/pdf.js"></script>' html = html.replace(pdfjs_script, '<script>window.Response = undefined;</script>\n' + pdfjs_script) return html
def test_not_found(caplog): """Test with a template which does not exist.""" with caplog.at_level(logging.ERROR): data = jinja.render('does_not_exist.html') assert "The does_not_exist.html template could not be found!" in data assert caplog.messages[0].startswith("The does_not_exist.html template" " could not be loaded from")
def glimpse_back(url): """Handler for glimpse://back. Simple page to free ram / lazy load a site, goes back on focusing the tab. """ src = jinja.render('back.html', title='Suspended: ' + urllib.parse.unquote(url.fragment())) return 'text/html', src
def test_utf8(): """Test rendering with an UTF8 template. This was an attempt to get a failing test case for #127 but it seems the issue is elsewhere. https://github.com/glimpsebrowser/glimpsebrowser/issues/127 """ data = jinja.render('test.html', var='\u2603') assert data == "Hello \u2603"
def glimpse_bindings(_url): """Handler for glimpse://bindings. View keybindings.""" bindings = {} defaults = config.val.bindings.default modes = set(defaults.keys()).union(config.val.bindings.commands) modes.remove('normal') modes = ['normal'] + sorted(list(modes)) for mode in modes: bindings[mode] = config.key_instance.get_bindings_for(mode) src = jinja.render('bindings.html', title='Bindings', bindings=bindings) return 'text/html', src
def glimpse_bookmarks(_url): """Handler for glimpse://bookmarks. Display all quickmarks / bookmarks.""" bookmarks = sorted(objreg.get('bookmark-manager').marks.items(), key=lambda x: x[1]) # Sort by title quickmarks = sorted(objreg.get('quickmark-manager').marks.items(), key=lambda x: x[0]) # Sort by name src = jinja.render('bookmarks.html', title='Bookmarks', bookmarks=bookmarks, quickmarks=quickmarks) return 'text/html', src
def glimpse_plainlog(url): """Handler for glimpse://plainlog. An optional query parameter specifies the minimum log level to print. For example, glimpse://log?level=warning prints warnings and errors. Level can be one of: vdebug, debug, info, warning, error, critical. """ if log.ram_handler is None: text = "Log output was disabled." else: level = QUrlQuery(url).queryItemValue('level') if not level: level = 'vdebug' text = log.ram_handler.dump_log(html=False, level=level) src = jinja.render('pre.html', title='log', content=text) return 'text/html', src
def test_resource_url(): """Test resource_url() which can be used from templates.""" data = jinja.render('test2.html') print(data) url = QUrl(data) assert url.isValid() assert url.scheme() == 'file' path = url.path() if utils.is_windows: path = path.lstrip('/') path = path.replace('/', os.sep) with open(path, 'r', encoding='utf-8') as f: assert f.read().splitlines()[0] == "Hello World!"
def glimpse_tabs(_url): """Handler for glimpse://tabs. Display information about all open tabs.""" tabs = collections.defaultdict(list) for win_id, window in objreg.window_registry.items(): if sip.isdeleted(window): continue tabbed_browser = objreg.get('tabbed-browser', scope='window', window=win_id) for tab in tabbed_browser.widgets(): if tab.url() not in [ QUrl("glimpse://tabs/"), QUrl("glimpse://tabs") ]: urlstr = tab.url().toDisplayString() tabs[str(win_id)].append((tab.title(), urlstr)) src = jinja.render('tabs.html', title='Tabs', tab_list_by_window=tabs) return 'text/html', src
def glimpse_history(url): """Handler for glimpse://history. Display and serve history.""" if url.path() == '/data': try: offset = QUrlQuery(url).queryItemValue("offset") offset = int(offset) if offset else None except ValueError: raise UrlInvalidError("Query parameter offset is invalid") # Use start_time in query or current time. try: start_time = QUrlQuery(url).queryItemValue("start_time") start_time = float(start_time) if start_time else time.time() except ValueError: raise UrlInvalidError("Query parameter start_time is invalid") return 'text/html', json.dumps(history_data(start_time, offset)) else: return 'text/html', jinja.render( 'history.html', title='History', gap_interval=config.val.history_gap_interval)
def _handle_errorpage(self, info, errpage): """Display an error page if needed. Loosely based on Helpviewer/HelpBrowserWV.py from eric5 (line 260 @ 5d937eb378dd) Args: info: The QWebPage.ErrorPageExtensionOption instance. errpage: The QWebPage.ErrorPageExtensionReturn instance, where the error page will get written to. Return: False if no error page should be displayed, True otherwise. """ ignored_errors = [ (QWebPage.QtNetwork, QNetworkReply.OperationCanceledError), # "Loading is handled by the media engine" (QWebPage.WebKit, 203), # "Frame load interrupted by policy change" (QWebPage.WebKit, 102), ] errpage.baseUrl = info.url urlstr = info.url.toDisplayString() if (info.domain, info.error) == (QWebPage.QtNetwork, QNetworkReply.ProtocolUnknownError): # For some reason, we get a segfault when we use # QDesktopServices::openUrl with info.url directly - however it # works when we construct a copy of it. url = QUrl(info.url) scheme = url.scheme() message.confirm_async( title="Open external application for {}-link?".format(scheme), text="URL: <b>{}</b>".format(html.escape( url.toDisplayString())), yes_action=functools.partial(QDesktopServices.openUrl, url), url=info.url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)) return True elif (info.domain, info.error) in ignored_errors: log.webview.debug("Ignored error on {}: {} (error domain: {}, " "error code: {})".format(urlstr, info.errorString, info.domain, info.error)) return False else: error_str = info.errorString if error_str == networkmanager.HOSTBLOCK_ERROR_STRING: # We don't set error_occurred in this case. error_str = "Request blocked by host blocker." main_frame = info.frame.page().mainFrame() if info.frame != main_frame: # Content in an iframe -> Hide the frame so it doesn't use # any space. We can't hide the frame's documentElement # directly though. for elem in main_frame.documentElement().findAll('iframe'): if QUrl(elem.attribute('src')) == info.url: elem.setAttribute('style', 'display: none') return False else: self._ignore_load_started = True self.error_occurred = True log.webview.error("Error while loading {}: {}".format( urlstr, error_str)) log.webview.debug("Error domain: {}, error code: {}".format( info.domain, info.error)) title = "Error loading page: {}".format(urlstr) error_html = jinja.render('error.html', title=title, url=urlstr, error=error_str) errpage.content = error_html.encode('utf-8') errpage.encoding = 'utf-8' return True
def test_undefined_function(caplog): """Make sure undefined attributes crash since we preload resources..""" with pytest.raises(jinja2.exceptions.UndefinedError): jinja.render('undef.html')
def test_attribute_error(): """Make sure accessing an unknown attribute fails.""" with pytest.raises(AttributeError): jinja.render('attributeerror.html', obj=object())
def test_simple_template(): """Test with a simple template.""" data = jinja.render('test.html', var='World') assert data == "Hello World"
def glimpse_spawn_output(_url): """Handler for glimpse://spawn-output.""" src = jinja.render('pre.html', title='spawn output', content=spawn_output) return 'text/html', src
def glimpse_pyeval(_url): """Handler for glimpse://pyeval.""" src = jinja.render('pre.html', title='pyeval', content=pyeval_output) return 'text/html', src