-
Notifications
You must be signed in to change notification settings - Fork 21
/
document.py
274 lines (229 loc) · 9.8 KB
/
document.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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# Copyright (C) 2020 Davis Remmel
# Copyright 2021 Robert Schroll
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import gc
import json
import logging
from reportlab.graphics import renderPDF
from svglib.svglib import svg2rlg
from . import lines, pens
from .constants import DISPLAY, PDFHEIGHT, PDFWIDTH, PTPERPX, TEMPLATE_PATH
log = logging.getLogger(__name__)
class DocumentPage:
# A single page in a document
def __init__(self, source, pid, pagenum):
# Page 0 is the first page!
self.source = source
self.num = pagenum
# On disk, these files are named by a UUID
self.rmpath = f'{{ID}}/{pid}.rm'
if not source.exists(self.rmpath):
# From the API, these files are just numbered
pid = str(pagenum)
self.rmpath = f'{{ID}}/{pid}.rm'
# Try to load page metadata
self.metadict = None
metafilepath = f'{{ID}}/{pid}-metadata.json'
if source.exists(metafilepath):
with source.open(metafilepath, 'r') as f:
self.metadict = json.load(f)
# Try to load template
self.template = None
template_names = []
pagedatapath = '{ID}.pagedata'
if source.exists(pagedatapath):
with source.open(pagedatapath, 'r') as f:
template_names = f.read().splitlines()
if template_names:
# I have encountered an issue with some PDF files, where the
# rM won't save the page template for later pages. In this
# case, just take the last-available page template, which
# is usually 'Blank'.
template_name = template_names[max(self.num, len(template_names) - 1)]
template_path = TEMPLATE_PATH / f'{template_name}.svg'
if template_name != 'Blank' and template_path.exists():
self.template = str(template_path)
# Load layers
self.layers = []
self.load_layers()
def get_grouped_annotations(self):
# Return the annotations grouped by proximity. If they are
# within a distance of each other, count them as a single
# annotation.
# Annotations should be delivered in an array, where each
# index is a tuple (LayerName,
annotations = []
for layer in self.layers:
annotations.append(layer.get_grouped_annotations())
return annotations
def load_layers(self):
# Loads layers from the .rm files
if not self.source.exists(self.rmpath):
# no layers, obv
return
# Load reMy version of page layers
pagelayers = None
with self.source.open(self.rmpath, 'rb') as f:
_, pagelayers = lines.readLines(f)
# Load layer data
for i in range(0, len(pagelayers)):
layerstrokes = pagelayers[i]
try:
name = self.metadict['layers'][i]['name']
except:
name = 'Layer ' + str(i + 1)
layer = DocumentPageLayer(self, name=name)
layer.strokes = layerstrokes
self.layers.append(layer)
def render_to_painter(self, canvas, vector, template_alpha):
# Render template layer
if self.template:
if template_alpha > 0:
background = svg2rlg(self.template)
background.scale(PDFWIDTH / background.width, PDFWIDTH / background.width)
renderPDF.draw(background, canvas, 0, 0)
if template_alpha < 1:
canvas.saveState()
canvas.setFillColorRGB(1., 1., 1.)
canvas.setFillAlpha(1 - template_alpha)
canvas.rect(0, 0, PDFWIDTH, PDFHEIGHT, fill=True, stroke=False)
canvas.restoreState()
# Bitmaps are rendered into the PDF as XObjects, which are
# easy to pick out for layers. Vectors will render
# everything inline, and so we need to add a 'magic point'
# to mark the end of the template layer.
if False and vector: #TODO
pen = GenericPen(color=Qt.transparent, vector=vector)
painter.setPen(pen)
painter.drawPoint(800, 85)
# The annotation coordinate system is upside down compared to the PDF
# coordinate system, so offset the bottom to the top and then flip
# vertically along the old bottom / new top to place the annotations
# correctly.
canvas.translate(0, PDFHEIGHT)
canvas.scale(PTPERPX, -PTPERPX)
# Render user layers
for layer in self.layers:
# Bitmaps are rendered into the PDF as XObjects, which are
# easy to pick out for layers. Vectors will render
# everything inline, and so we need to add a 'magic point'
# to mark the beginning of layers.
if False and vector: #TODO
pen = GenericPen(color=Qt.transparent, vector=vector)
painter.setPen(pen)
painter.drawPoint(420, 69)
layer.render_to_painter(canvas, vector)
canvas.showPage()
class DocumentPageLayer:
pen_widths = []
def __init__(self, page, name=None):
self.page = page
self.name = name
self.colors = [
#QSettings().value('pane/notebooks/export_pdf_blackink'),
#QSettings().value('pane/notebooks/export_pdf_grayink'),
#QSettings().value('pane/notebooks/export_pdf_whiteink')
(0, 0, 0),
(0.5, 0.5, 0.5),
(1, 1, 1)
]
# Set this from the calling func
self.strokes = None
# Store PDF annotations with the layer, in case actual
# PDF layers are ever implemented.
self.annot_paths = []
def get_grouped_annotations(self):
# return: (LayerName, [(AnnotType, minX, minY, maxX, maxY)])
# Compare all the annot_paths to each other. If any overlap,
# they will be grouped together. This is done recursively.
def grouping_func(pathset):
newset = []
for p in pathset:
annotype = p[0]
path = p[1]
did_fit = False
for i, g in enumerate(newset):
gannotype = g[0]
group = g[1]
# Only compare annotations of the same type
if gannotype != annotype:
continue
if path.intersects(group):
did_fit = True
newset[i] = (annotype, group.united(path))
break
if did_fit:
continue
# Didn't fit, so place into a new group
newset.append(p)
if len(newset) != len(pathset):
# Might have stuff left to group
return grouping_func(newset)
else:
# Nothing was grouped, so done
return newset
grouped = grouping_func(self.annot_paths)
# Get the bounding rect of each group, which sets the PDF
# annotation geometry.
annot_rects = []
for p in grouped:
annotype = p[0]
path = p[1]
rect = path.boundingRect()
annot = (annotype,
float(rect.x()),
float(rect.y()),
float(rect.x() + rect.width()),
float(rect.y() + rect.height()))
annot_rects.append(annot)
return (self.name, annot_rects)
def paint_strokes(self, canvas, vector):
for stroke in self.strokes:
pen, color, unk1, width, unk2, segments = stroke
penclass = pens.PEN_MAPPING.get(pen)
if penclass is None:
log.error("Unknown pen code %d" % pen)
penclass = pens.GenericPen
qpen = penclass(vector=vector,
layer=self,
color=self.colors[color])
# Do the needful
qpen.paint_stroke(canvas, stroke)
def render_to_painter(self, painter, vector):
if vector: # Turn this on with vector otherwise off to get hybrid
self.paint_strokes(painter, vector=vector)
return
assert False
# I was having problems with QImage corruption (garbage data)
# and memory leaking on large notebooks. I fixed this by giving
# the QImage a reference array to pre-allocate RAM, then reset
# the reference count after I'm done with it, so that it gets
# cleaned up by the python garbage collector.
devpx = DISPLAY['screenwidth'] \
* DISPLAY['screenheight']
bytepp = 4 # ARGB32
qimage = QImage(b'\0' * devpx * bytepp,
DISPLAY['screenwidth'],
DISPLAY['screenheight'],
QImage.Format_ARGB32)
imgpainter = QPainter(qimage)
imgpainter.setRenderHint(QPainter.Antialiasing)
#imgpainter.setRenderHint(QPainter.LosslessImageRendering)
self.paint_strokes(imgpainter, vector=vector)
imgpainter.end()
painter.drawImage(0, 0, qimage)
del imgpainter
del qimage
gc.collect()