-
Notifications
You must be signed in to change notification settings - Fork 0
/
viewer.py
159 lines (125 loc) · 4.72 KB
/
viewer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# viewer.py
import sys
import re
import json
import types
from urllib.parse import urlparse, unquote
from pathlib import Path
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QUrl, Qt
from PyQt5.QtGui import QDesktopServices
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage, QWebEngineSettings, QWebEngineScript
from locations import ResourceFile
class PDFView(QWebEngineView):
"""
subclass of QWebEngineView designed to display PDFs
"""
jsfnRE = re.compile(
r'function\s*(?P<name>[A-z0-9]+)?\s*\((?P<args>(?:[^)(]+|\((?:[^)(]+|\([^)(]*\))*\)))*\)\s*\{(?P<body>(?:[^}{]+|\{(?:[^}{]+|\{[^}{]*\})*\})*)\}',
re.DOTALL
)
jsSourceFiles = [
ResourceFile('functions.js')
]
viewerHtmlPath = ResourceFile('pdfjs/web/viewer.html')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.loadFinished.connect(self.onLoad)
self.loadViewer()
if len(args) > 1:
self.loadPdf(args[1])
@staticmethod
def asUri(localpath):
p = Path(localpath)
# assert p.exists()
return p.absolute().as_uri()
@staticmethod
def fromUri(fileuri):
fullpath = unquote(urlparse(fileuri).path)
return fullpath
# ---------- INSTANCE METHODS ----------
def onLoad(self, success):
if success:
for filename in self.jsSourceFiles:
with open(filename, 'r') as f:
jsSource = f.read()
self.loadJsFunctions(jsSource)
def loadPdf(self, pdffile):
# self.load(QUrl.fromUserInput(
# '{0}?file={1}'.format(self.asUri(self.viewerHtmlPath), self.asUri(pdffile))
# ))
self.loadFile(self.asUri(pdffile))
def loadViewer(self):
self.fnsLoaded = False
self.pageObj = CustomPage(self)
self.setPage(self.pageObj)
self.load(QUrl.fromUserInput(self.asUri(self.viewerHtmlPath)))
while not self.fnsLoaded:
QApplication.processEvents()
def getCurrentFile(self):
return self.fromUri(self.getCurrentFileUri())
def isFileLoaded(self):
return len(self.getCurrentFile()) > 0
def getCurrentDir(self):
p = Path(self.getCurrentFile())
return str(p.parent)
# ---------- JS PAGE INTERACTION INSTANCE METHODS ----------
def callJsFunction(self, jsFn, *args):
callString = jsFn.constructCallString(*args)
jsFn.resetResponse()
self.page().runJavaScript(callString, jsFn.captureResponse)
while not jsFn.responseCaptured:
QApplication.processEvents()
return jsFn.response
def makeJsMethod(self, jsFn):
return lambda self, *args: self.callJsFunction(jsFn, *args)
def loadJsFunctions(self, jsSource):
self.page().runJavaScript(jsSource)
self.jsFns = [JsFn(m) for m in self.jsfnRE.finditer(jsSource) if m['name']] # list of named functions
for j in self.jsFns:
setattr(self, j.name, types.MethodType(self.makeJsMethod(j), self))
self.fnsLoaded = True
class CustomPage(QWebEnginePage):
"""
docstring for CustomPage
"""
def __init__(self, *args, **kwargs):
super(CustomPage, self).__init__(*args, **kwargs)
def acceptNavigationRequest(self, qurl, navtype, mainframe):
# print('Navigation Url: {}'.format(qurl))
# print('Navigation Type: {}'.format(navtype))
# return True
if navtype == QWebEnginePage.NavigationTypeTyped: # open in QWebEngineView
return True
else: # delegate link to default browser
QDesktopServices.openUrl(qurl)
return False
class JsFn(object):
"""
represents a callable javascript function
"""
def __init__(self, reMatch):
super().__init__()
self.name = reMatch['name']
self.args = [a.strip() for a in reMatch['args'].split(',')] if reMatch['args'] else []
self.body = reMatch['body'].strip()
def constructCallString(self, *callArgs):
if len(callArgs) != len(self.args):
raise Exception('Expected {0} arguments, but got {1}!'.format(len(self.args), len(callArgs)))
else:
argstring = ', '.join([json.dumps(a) for a in callArgs])
return '{0}({1})'.format(self.name, argstring)
def resetResponse(self):
self.responseCaptured = False
self.response = None
def captureResponse(self, response):
self.responseCaptured = True
self.response = response
if __name__ == '__main__':
app = QApplication(sys.argv)
w = QMainWindow()
p = PDFView()
w.setCentralWidget(p)
p.loadPdf('sample_toc.pdf')
w.show()
sys.exit(app.exec_())