BirdyNet/addons/0.documentViewer.QTextBrowser.py
2021-03-25 22:29:38 +01:00

82 lines
2.4 KiB
Python

global html
import html.parser
global browserDoc
class browserDoc(QTextBrowser):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.setOpenLinks(False)
style = ""
if (config["accessibility"]["colorBackground"] != "default"):
style += "background-color: " +config["accessibility"]["colorBackground"] + ";"
if (config["accessibility"]["colorText"] != "default"):
style += "color: " +config["accessibility"]["colorText"]+ ";"
self.setStyleSheet("QTextBrowser { " +style+ " }")
self.anchorClicked.connect(self.cAnchorClicked)
class cHtmlParser(html.parser.HTMLParser):
def __init__(self):
html.parser.HTMLParser.__init__(self)
self.output = ""
self.voidElements = ["area","base","br","col","hr","img","input","link","meta","param","command","keygen","source"]
self.blackList = ["img","script","style"]
self.tagDir = []
def handle_starttag(self,tag,attrs):
if not tag in self.voidElements:
self.tagDir.append(tag)
if tag in self.blackList: return
self.output += "<" +html.escape(tag)
for attr in attrs:
self.output += " " +html.escape(attr[0])
if attr[1] != None:
self.output += '="' +html.escape(attr[1])+ '"'
self.output += ">"
def handle_endtag(self,tag):
if not tag in self.voidElements:
index = len(self.tagDir) - 1
while index >= 0:
if self.tagDir[index] == tag:
self.tagDir = self.tagDir[index + 1:]
break
index -= 1
self.output += "</" +html.escape(tag)+ ">"
def handle_data(self,data):
curTag = ""
if len(self.tagDir) > 0:
curTag = self.tagDir[-1]
if curTag in self.blackList: return
self.output += html.escape(data)
def cRenderHtml(self,htm,contentType):
if contentType != "text/html":
self.clear()
self.insertHtml("<html><body><pre>" +html.escape(htm)+ "</pre></body></html>")
self.update()
return
parser = self.cHtmlParser()
parser.feed(htm)
self.clear()
self.insertHtml(parser.output)
self.update()
def cAnchorClicked(self,url):
url = str(url.toEncoded(),"utf-8")
browserWindow = self.parent()
curUrl = browserWindow.cDocumentInfo["url"]
navType, url, urlParsed = navigateLink(curUrl,url)
refresh = True
if navType == 0: refresh = False
browserWindow.cUrlBar.setText(url)
browserWindow.cNavigate(forceRefresh = refresh)
def cScrollToAnchor(self,anchor):
self.scrollToAnchor(anchor)