@floless/app 0.174.0 → 0.174.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/dist/floless-server.cjs
3
- size: 34052660 bytes
4
- sha256: ef38d288ebee9583328e93df0032befd6acd8eab5a4c5ba0c325d9352ba9b426
3
+ size: 34156712 bytes
4
+ sha256: ce5e44472648dc533086443f0924adeb551e4726d617e4bed729134b948ba06b
@@ -0,0 +1,49 @@
1
+ """FloLess's PDF module (plan docs/superpowers/specs/2026-11-20-pdf-engine-pypdfium2-PLAN.md, section 3.1).
2
+
3
+ One API, two backends: `pymupdf` (a pass-through, the reference while readers migrate) and `pdfium` (pypdfium2).
4
+ A script never picks an engine itself: the server's engine table (server/pdf-engine.ts) decides, the runner passes
5
+ the choice in the script's JSON request, and the script hands it to `open`. Every result reports `doc.engine`, the
6
+ engine that actually ran, so the runner can check it against the one it asked for.
7
+
8
+ This file is the canonical source. Copies (the managed runtime's, a skill's) are generated from it by the build and
9
+ digest-checked by `verify:pdf-engine`; never edit a copy.
10
+ """
11
+ from . import images
12
+ from .geometry import IDENTITY, Matrix, Point, Rect, rotation_matrix
13
+
14
+ ENGINES = ("pymupdf", "pdfium")
15
+ API_VERSION = 1
16
+
17
+
18
+ class EngineUnavailable(ImportError):
19
+ """The engine asked for is not installed in this Python. The server's readiness check names what is missing."""
20
+
21
+
22
+ def _backend(engine):
23
+ if engine == "pymupdf":
24
+ try:
25
+ from . import backend_pymupdf as b
26
+ except ImportError as error:
27
+ raise EngineUnavailable("pymupdf: %s" % error) from error
28
+ return b
29
+ if engine == "pdfium":
30
+ try:
31
+ from . import backend_pdfium as b
32
+ except ImportError as error:
33
+ raise EngineUnavailable("pdfium: %s" % error) from error
34
+ return b
35
+ raise ValueError("unknown PDF engine %r (expected one of %s)" % (engine, ", ".join(ENGINES)))
36
+
37
+
38
+ def open(source, engine): # noqa: A001 - the module's own verb, as the readers call it
39
+ """Open a PDF (a path or its bytes) with the named engine. Raises PermissionError for a password-locked PDF."""
40
+ return _backend(engine).Document(source)
41
+
42
+
43
+ def versions(engine):
44
+ """The library versions an engine runs on, without opening anything."""
45
+ return _backend(engine).versions()
46
+
47
+
48
+ __all__ = ["API_VERSION", "ENGINES", "EngineUnavailable", "IDENTITY", "Matrix", "Point", "Rect", "images", "open",
49
+ "rotation_matrix", "versions"]
@@ -0,0 +1,544 @@
1
+ """The pdfium backend: pypdfium2 (PDFium), written fresh for FloLess (plan section 3.1).
2
+
3
+ What it reads, and where it deliberately differs from MuPDF (the D numbers are the plan's, section 1):
4
+
5
+ - Coordinates: unrotated page space, origin at the crop box's top-left, y down, as the pymupdf backend gives them.
6
+ - Text: PDFium's characters with their boxes; lines, spaces and words come from FloLess's own rules (textrules.py),
7
+ never from PDFium's segmentation (D2, D3). Text printed several times on itself is read once (D12).
8
+ - Linework: every path object, Form XObjects included, with its matrix, colours, width, dash and layer. A fill and
9
+ a stroke of the same outline, one after the other on one layer, are one "fs" drawing as MuPDF reads them (D4). A
10
+ path's extent is trimmed to its clip (D8). Mid-grey is PDFium's #808080 (D5).
11
+ - Markups: annotation appearances are not read (D1, owner ruling 2026-11-20); every drawing and char says
12
+ `markup: False`, and the rendered picture still shows them.
13
+ - Layers: the optional content an object sits in, by its layer name; content under a membership dictionary (OCMD)
14
+ is in the first layer the dictionary names. The document's layer list comes from pypdf.
15
+ """
16
+ import ctypes
17
+ import math
18
+
19
+ import pypdfium2 as pdfium
20
+ import pypdfium2.raw as R
21
+
22
+ from . import images, textrules
23
+ from .geometry import Matrix, Point, Rect, rotation_matrix
24
+
25
+ NAME = "pdfium"
26
+
27
+
28
+ def versions():
29
+ return {"pypdfium2": str(pdfium.PYPDFIUM_INFO.version), "pdfium": str(pdfium.PDFIUM_INFO.build)}
30
+
31
+
32
+ _BUF = (ctypes.c_ushort * 1024)()
33
+
34
+
35
+ def _wide(fn, *args):
36
+ n = ctypes.c_ulong()
37
+ if not fn(*args, _BUF, ctypes.sizeof(_BUF), ctypes.byref(n)):
38
+ return None
39
+ return bytes(_BUF)[:max(0, n.value - 2)].decode("utf-16-le", "replace")
40
+
41
+
42
+ def _obj_matrix(obj):
43
+ m = R.FS_MATRIX()
44
+ R.FPDFPageObj_GetMatrix(obj, m)
45
+ return Matrix(m.a, m.b, m.c, m.d, m.e, m.f)
46
+
47
+
48
+ def _rgb(fn, obj):
49
+ r, g, b, a = ctypes.c_uint(), ctypes.c_uint(), ctypes.c_uint(), ctypes.c_uint()
50
+ if not fn(obj, r, g, b, a):
51
+ return None
52
+ return (r.value / 255.0, g.value / 255.0, b.value / 255.0)
53
+
54
+
55
+ def _same_items(a, b):
56
+ def key(items):
57
+ out = []
58
+ for it in items:
59
+ out.append((it[0],) + tuple(v for p in it[1:] for v in ((round(p.x, 3), round(p.y, 3)) if isinstance(p, Point)
60
+ else (tuple(round(x, 3) for x in p.as_tuple()) if isinstance(p, Rect) else (p,)))))
61
+ return out
62
+ return key(a) == key(b)
63
+
64
+
65
+ class Page:
66
+ def __init__(self, doc, number):
67
+ self._doc = doc
68
+ self._p = doc._pdf[number]
69
+ self.number = number
70
+ cx0, cy0, cx1, cy1 = self._p.get_cropbox()
71
+ w, h = cx1 - cx0, cy1 - cy0
72
+ self._ctm = Matrix(1, 0, 0, -1, -cx0, cy1) # PDF user space -> unrotated page space (y down)
73
+ self.rotation = self._p.get_rotation() % 360
74
+ self.unrotated_size = (w, h)
75
+ self.size = (h, w) if self.rotation in (90, 270) else (w, h)
76
+ self.rotation_matrix = rotation_matrix(self.rotation, w, h)
77
+ self._tp = None
78
+ self._layer_cache = {}
79
+ self._tree_cache = None
80
+
81
+ # ---- layers -------------------------------------------------------------------------------------------------
82
+ def _layer(self, obj):
83
+ """The layer an object is in: the innermost optional-content mark around it ('' outside any layer)."""
84
+ return self._oc(obj)[0]
85
+
86
+ def _hidden(self, obj):
87
+ """True when the object sits in a layer the default configuration turns off; MuPDF does not read those."""
88
+ return self._oc(obj)[1]
89
+
90
+ def _oc(self, obj):
91
+ """(layer, hidden) of an object: its own optional-content marks, inside whatever the Forms around it give
92
+ (a Form's own /OC entry, or the marks around the Form), as MuPDF reads them."""
93
+ key = ctypes.addressof(obj.contents) if obj else 0
94
+ if key in self._layer_cache:
95
+ return self._layer_cache[key]
96
+ own_name, own_hidden = self._marks(obj)
97
+ inh_name, inh_hidden = self._tree()[1].get(key, ("", False))
98
+ self._layer_cache[key] = (own_name or inh_name, own_hidden or inh_hidden)
99
+ return self._layer_cache[key]
100
+
101
+ def _marks(self, obj):
102
+ """(layer, hidden) from an object's own optional-content marks only."""
103
+ name, hidden = "", False
104
+ if not obj:
105
+ return name, hidden
106
+ for i in range(R.FPDFPageObj_CountMarks(obj)):
107
+ mark = R.FPDFPageObj_GetMark(obj, i)
108
+ if _wide(R.FPDFPageObjMark_GetName, mark) != "OC":
109
+ continue
110
+ n = ctypes.c_ulong()
111
+ if R.FPDFPageObjMark_GetParamStringValue(mark, b"Name", _BUF, ctypes.sizeof(_BUF), ctypes.byref(n)):
112
+ name = bytes(_BUF)[:max(0, n.value - 2)].decode("utf-16-le", "replace")
113
+ hidden = hidden or name in self._doc._off_names()
114
+ else:
115
+ ocmd_name, ocmd_hidden = self._doc._ocmd_layer(self.number, mark)
116
+ name = ocmd_name or name
117
+ hidden = hidden or ocmd_hidden
118
+ return name, hidden
119
+
120
+ def _tree(self):
121
+ """Every path object with its matrices, and the layer each object inside a Form inherits from it.
122
+
123
+ PDFium hands over a Form's children but not the Form's own /OC entry, so the Forms a content stream paints are
124
+ read through pypdf, in order, and paired with PDFium's Form objects at the same level. Where the two counts
125
+ disagree the pairing is not trusted and that level inherits only the marks around its Forms (a stated limit)."""
126
+ if self._tree_cache is not None:
127
+ return self._tree_cache
128
+ paths, inherited = [], {}
129
+ top = None
130
+ reader = self._doc._reader()
131
+ if reader is not None:
132
+ try:
133
+ pg = reader.pages[self.number]
134
+ top = (pg.get_contents(), pg.get("/Resources"))
135
+ except Exception: # noqa: BLE001 - the page still reads, without Form layers
136
+ top = None
137
+
138
+ def walk(parent, in_form, chain, inh, stream):
139
+ n = R.FPDFFormObj_CountObjects(parent) if in_form else R.FPDFPage_CountObjects(parent)
140
+ children = [R.FPDFFormObj_GetObject(parent, i) if in_form else R.FPDFPage_GetObject(parent, i) for i in range(n)]
141
+ form_children = [o for o in children if R.FPDFPageObj_GetType(o) == R.FPDF_PAGEOBJ_FORM]
142
+ xobjects = None
143
+ if stream is not None:
144
+ try:
145
+ xobjects = self._doc._form_xobjects(*stream)
146
+ except Exception: # noqa: BLE001 - unpaired: marks only
147
+ xobjects = None
148
+ if xobjects is not None and len(xobjects) != len(form_children):
149
+ xobjects = None
150
+ k = 0
151
+ for obj in children:
152
+ if inh != ("", False):
153
+ inherited[ctypes.addressof(obj.contents)] = inh
154
+ t = R.FPDFPageObj_GetType(obj)
155
+ if t == R.FPDF_PAGEOBJ_FORM:
156
+ xobj = xobjects[k] if xobjects is not None else None
157
+ k += 1
158
+ mark_name, mark_hidden = self._marks(obj)
159
+ oc_name, oc_hidden = self._doc._form_oc(xobj) if xobj is not None else ("", False)
160
+ child = (oc_name or mark_name or inh[0], inh[1] or mark_hidden or oc_hidden)
161
+ sub = None
162
+ if xobj is not None:
163
+ sub = (xobj, xobj.get("/Resources") if xobj.get("/Resources") is not None else stream[1])
164
+ walk(obj, True, _obj_matrix(obj).then(chain), child, sub)
165
+ elif t == R.FPDF_PAGEOBJ_PATH:
166
+ paths.append((obj, _obj_matrix(obj).then(chain), chain))
167
+ walk(self._p.raw, False, self._ctm, ("", False), top)
168
+ self._tree_cache = (paths, inherited)
169
+ return self._tree_cache
170
+
171
+ # ---- text ---------------------------------------------------------------------------------------------------
172
+ def _textpage(self):
173
+ if self._tp is None:
174
+ self._tp = self._p.get_textpage()
175
+ return self._tp
176
+
177
+ def _raw_chars(self):
178
+ raw = self._textpage().raw
179
+ rect = R.FS_RECTF()
180
+ fr, fg, fb, fa = ctypes.c_uint(), ctypes.c_uint(), ctypes.c_uint(), ctypes.c_uint()
181
+ ox, oy = ctypes.c_double(), ctypes.c_double()
182
+ tm = R.FS_MATRIX()
183
+ fonts = {}
184
+ out = []
185
+ for i in range(R.FPDFText_CountChars(raw)):
186
+ u = R.FPDFText_GetUnicode(raw, i)
187
+ generated = R.FPDFText_IsGenerated(raw, i) == 1
188
+ c = chr(u) if u else ""
189
+ if c in ("\r", "\n") or u == 0xFFFE:
190
+ out.append({"c": "\n", "generated": True})
191
+ continue
192
+ R.FPDFText_GetLooseCharBox(raw, i, rect)
193
+ box = Rect(rect.left, rect.top, rect.right, rect.bottom).transform(self._ctm)
194
+ obj = R.FPDFText_GetTextObject(raw, i)
195
+ key = ctypes.addressof(obj.contents) if obj else 0
196
+ if key not in fonts:
197
+ fonts[key] = self._font_of(obj)
198
+ font, flags, layer = fonts[key]
199
+ if obj and self._hidden(obj):
200
+ continue
201
+ R.FPDFText_GetFillColor(raw, i, fr, fg, fb, fa)
202
+ R.FPDFText_GetCharOrigin(raw, i, ox, oy)
203
+ R.FPDFText_GetMatrix(raw, i, tm)
204
+ out.append({"c": c, "generated": generated, "box": box,
205
+ "origin": Point(*self._ctm.apply(ox.value, oy.value)),
206
+ "size": R.FPDFText_GetFontSize(raw, i),
207
+ "angle": round(math.atan2(-tm.b, tm.a), 4),
208
+ "font": font, "flags": flags, "layer": layer, "markup": False,
209
+ "color": (fr.value << 16) | (fg.value << 8) | fb.value})
210
+ return out
211
+
212
+ def _font_of(self, obj):
213
+ if not obj:
214
+ return ("", 0, "")
215
+ font = R.FPDFTextObj_GetFont(obj)
216
+ name, flags = "", 0
217
+ if font:
218
+ buf = ctypes.create_string_buffer(256)
219
+ R.FPDFFont_GetBaseFontName(font, buf, 256)
220
+ name = buf.value.decode("latin-1", "replace")
221
+ pdf_flags = R.FPDFFont_GetFlags(font)
222
+ # MuPDF's span flags: 2 italic, 4 serif, 8 monospaced, 16 bold (from the font descriptor and its weight).
223
+ flags = (2 if pdf_flags & (1 << 6) else 0) | (4 if pdf_flags & (1 << 1) else 0) \
224
+ | (8 if pdf_flags & 1 else 0) | (16 if R.FPDFFont_GetWeight(font) >= 600 or pdf_flags & (1 << 18) else 0)
225
+ return (name, flags, self._layer(obj))
226
+
227
+ def chars(self):
228
+ return [c for c in self._raw_chars() if c["c"] != "\n"]
229
+
230
+ def lines(self):
231
+ out = []
232
+ for ln in textrules.lines(self._raw_chars()):
233
+ out.append({"bbox": ln["bbox"], "dir": ln["dir"], "spans": [
234
+ {"text": s["text"], "bbox": s["bbox"], "size": s["size"], "font": s["font"], "color": s["color"],
235
+ "flags": s["flags"], "origin": s["origin"]} for s in ln["spans"]]})
236
+ return out
237
+
238
+ def words(self):
239
+ return [(w[0], w[1], w[2], w[3], w[4], 0, w[5], w[6]) for w in textrules.words(self._raw_chars())]
240
+
241
+ def text(self):
242
+ return "\n".join(" ".join(s["text"] for s in ln["spans"]).strip() for ln in self.lines()) + ("\n" if self.lines() else "")
243
+
244
+ # ---- linework -----------------------------------------------------------------------------------------------
245
+ def _paths(self):
246
+ return self._tree()[0]
247
+
248
+ def _clip_rect(self, obj, chain):
249
+ """The bounding box of an object's clip, in page space; None when it has none (D8)."""
250
+ clip = R.FPDFPageObj_GetClipPath(obj)
251
+ if not clip:
252
+ return None
253
+ x, y = ctypes.c_float(), ctypes.c_float()
254
+ box = None
255
+ for i in range(R.FPDFClipPath_CountPaths(clip)):
256
+ pts = []
257
+ for s in range(R.FPDFClipPath_CountPathSegments(clip, i)):
258
+ seg = R.FPDFClipPath_GetPathSegment(clip, i, s)
259
+ if seg and R.FPDFPathSegment_GetPoint(seg, x, y):
260
+ pts.append(Point(*chain.apply(x.value, y.value)))
261
+ if pts:
262
+ r = Rect.around(pts)
263
+ box = r if box is None else box.intersect(r)
264
+ return box
265
+
266
+ def drawings(self):
267
+ out = []
268
+ x, y = ctypes.c_float(), ctypes.c_float()
269
+ mode, stroke = ctypes.c_int(), ctypes.c_int()
270
+ for obj, m, chain in self._paths():
271
+ R.FPDFPath_GetDrawMode(obj, mode, stroke)
272
+ fill, strk = mode.value != 0, bool(stroke.value)
273
+ if not fill and not strk:
274
+ continue
275
+ if self._hidden(obj):
276
+ continue
277
+ items = _path_items(obj, m, x, y)
278
+ if not items:
279
+ continue
280
+ pts = []
281
+ for it in items:
282
+ if it[0] == "re":
283
+ pts += [Point(it[1].x0, it[1].y0), Point(it[1].x1, it[1].y1)]
284
+ else:
285
+ pts += list(it[1:])
286
+ rect = Rect.around(pts)
287
+ clip = self._clip_rect(obj, chain)
288
+ layer = self._layer(obj)
289
+ width = color = dashes = None
290
+ if strk:
291
+ w = ctypes.c_float()
292
+ R.FPDFPageObj_GetStrokeWidth(obj, w)
293
+ width = w.value * m.expansion
294
+ color = _rgb(R.FPDFPageObj_GetStrokeColor, obj)
295
+ dashes = _dashes(obj, m.expansion)
296
+ prev = out[-1] if out else None
297
+ if strk and not fill and prev is not None and prev["type"] == "f" and prev["layer"] == layer \
298
+ and _same_items(prev["items"], items):
299
+ prev.update({"type": "fs", "width": width, "color": color, "dashes": dashes}) # D4
300
+ continue
301
+ out.append({"type": "fs" if fill and strk else ("f" if fill else "s"), "items": items, "rect": rect,
302
+ "clip": clip, "visible": rect.intersect(clip) if clip is not None else rect,
303
+ "width": width, "color": color, "fill": _rgb(R.FPDFPageObj_GetFillColor, obj) if fill else None,
304
+ "dashes": dashes, "even_odd": (mode.value == R.FPDF_FILLMODE_ALTERNATE) if fill else None,
305
+ "closePath": False, "layer": layer, "markup": False})
306
+ return out
307
+
308
+ # ---- pictures -----------------------------------------------------------------------------------------------
309
+ def render(self, scale=None, dpi=None, clip=None):
310
+ k = (float(dpi) / 72.0) if dpi is not None else float(scale or 1.0)
311
+ crop = (0, 0, 0, 0)
312
+ if clip is not None:
313
+ w, h = self.size
314
+ x0, y0, x1, y1 = clip
315
+ crop = (max(0.0, x0), max(0.0, h - y1), max(0.0, w - x1), max(0.0, y0))
316
+ bitmap = self._p.render(scale=k, crop=crop, fill_color=(255, 255, 255, 255), draw_annots=True,
317
+ may_draw_forms=True)
318
+ return images.to_rgb(bitmap.to_pil())
319
+
320
+ def render_jpeg(self, scale=None, dpi=None, clip=None, quality=images.JPEG_QUALITY):
321
+ img = self.render(scale, dpi, clip)
322
+ return images.encode_jpeg(img, quality), img.size
323
+
324
+ def render_png(self, scale=None, dpi=None, clip=None):
325
+ img = self.render(scale, dpi, clip)
326
+ return images.encode_png(img), img.size
327
+
328
+
329
+ def _dashes(obj, k):
330
+ n = R.FPDFPageObj_GetDashCount(obj)
331
+ phase = ctypes.c_float()
332
+ R.FPDFPageObj_GetDashPhase(obj, phase)
333
+ if n <= 0:
334
+ return "[] 0"
335
+ arr = (ctypes.c_float * n)()
336
+ R.FPDFPageObj_GetDashArray(obj, arr, n)
337
+ return "[ %s ] %g" % (" ".join("%g" % (arr[i] * k) for i in range(n)), phase.value * k)
338
+
339
+
340
+ def _path_items(obj, m, x, y):
341
+ """A path's segments as MuPDF reports them: lines, curves, and a closed four-line subpath as a rectangle when it
342
+ is axis-aligned or a quad when it is not. A line to the current point is dropped unless it follows a move."""
343
+ items, sub, start, cur, bez = [], [], None, None, []
344
+
345
+ def flush(closed):
346
+ lines = [it for it in sub if it[0] == "l"]
347
+ if closed and len(sub) == 4 and len(lines) == 4:
348
+ p = [it[1] for it in sub]
349
+ xs = {round(q.x, 3) for q in p}
350
+ ys = {round(q.y, 3) for q in p}
351
+ if len(xs) == 2 and len(ys) == 2:
352
+ area = sum(p[i].x * p[(i + 1) % 4].y - p[(i + 1) % 4].x * p[i].y for i in range(4))
353
+ items.append(("re", Rect.around(p), 1 if area <= 0 else -1))
354
+ else:
355
+ items.append(("qu", p[0], p[3], p[1], p[2]))
356
+ else:
357
+ items.extend(sub)
358
+ sub.clear()
359
+
360
+ for s in range(R.FPDFPath_CountSegments(obj)):
361
+ seg = R.FPDFPath_GetPathSegment(obj, s)
362
+ R.FPDFPathSegment_GetPoint(seg, x, y)
363
+ p = Point(*m.apply(x.value, y.value))
364
+ kind = R.FPDFPathSegment_GetType(seg)
365
+ closes = bool(R.FPDFPathSegment_GetClose(seg))
366
+ if kind == R.FPDF_SEGMENT_MOVETO:
367
+ if sub:
368
+ flush(False)
369
+ start = cur = p
370
+ elif kind == R.FPDF_SEGMENT_LINETO:
371
+ if not (sub and abs(p.x - cur.x) < 1e-6 and abs(p.y - cur.y) < 1e-6):
372
+ sub.append(("l", cur, p))
373
+ cur = p
374
+ elif kind == R.FPDF_SEGMENT_BEZIERTO:
375
+ bez.append(p)
376
+ if len(bez) == 3:
377
+ sub.append(("c", cur, bez[0], bez[1], bez[2]))
378
+ cur, bez = bez[2], []
379
+ if closes and start is not None:
380
+ if abs(cur.x - start.x) > 1e-6 or abs(cur.y - start.y) > 1e-6:
381
+ sub.append(("l", cur, start))
382
+ cur = start
383
+ flush(True)
384
+ if sub:
385
+ flush(False)
386
+ return items
387
+
388
+
389
+ class Document:
390
+ def __init__(self, source):
391
+ self._source = source
392
+ try:
393
+ self._pdf = pdfium.PdfDocument(bytes(source) if isinstance(source, (bytes, bytearray)) else source)
394
+ except pdfium.PdfiumError as error:
395
+ if "password" in str(error).lower():
396
+ raise PermissionError("the PDF needs a password") from error
397
+ raise
398
+ self.page_count = len(self._pdf)
399
+ self.engine = {"name": NAME, **versions()}
400
+ self._struct = None
401
+
402
+ def page(self, number):
403
+ if not 0 <= number < self.page_count:
404
+ raise IndexError("page %d of %d" % (number + 1, self.page_count))
405
+ return Page(self, number)
406
+
407
+ def _structure(self):
408
+ """The document's structure through pypdf (layers and their membership dictionaries); PDFium has no call."""
409
+ if self._struct is None:
410
+ import io
411
+ src = io.BytesIO(bytes(self._source)) if isinstance(self._source, (bytes, bytearray)) else self._source
412
+ try:
413
+ import pypdf # noqa: PLC0415 - the layer structure needs it; without it the pages read with no layers
414
+ reader = pypdf.PdfReader(src, strict=False)
415
+ if reader.is_encrypted:
416
+ reader.decrypt("")
417
+ props = reader.trailer["/Root"].get("/OCProperties")
418
+ props = props.get_object() if props is not None else None
419
+ except Exception as error: # noqa: BLE001 - nothing refuses: the page still reads, labelled
420
+ # PDFium opened (and repaired) a file pypdf cannot parse. Its text and linework still read; it reads as
421
+ # having no layers, and `structure_error` says so for the reader to label.
422
+ self._pypdf = None
423
+ self._struct = {"layers": [], "error": type(error).__name__}
424
+ return self._struct
425
+ self._pypdf = reader
426
+ def ref(o):
427
+ return getattr(o, "idnum", None) or id(o.get_object())
428
+ ocgs, off = [], set()
429
+ if props is not None:
430
+ ocgs = list(props.get("/OCGs", []))
431
+ d = props.get("/D")
432
+ if d is not None:
433
+ d = d.get_object()
434
+ if str(d.get("/BaseState", "/ON")) == "/OFF":
435
+ # Every layer starts off; /ON turns some back on (/OFF is then redundant).
436
+ on = {ref(o) for o in d.get("/ON", [])}
437
+ off = {ref(o) for o in ocgs} - on
438
+ else:
439
+ off = {ref(o) for o in d.get("/OFF", [])}
440
+ self._struct = {"layers": [{"name": str(o.get_object().get("/Name", "")), "on": ref(o) not in off}
441
+ for o in ocgs]}
442
+ return self._struct
443
+
444
+ def _ocmd_layer(self, number, mark):
445
+ """The layer of content under a membership dictionary (OCMD). PDFium names the mark's keys but does not hand
446
+ over its /OCGs array, so the page's OCMDs are read through pypdf and matched by their /P policy. The name is
447
+ the LAST layer the OCMD lists, as MuPDF reads it. Two OCMDs on one page with the same policy and different
448
+ layers cannot be told apart this way; such content reads as outside any layer (a stated limit)."""
449
+ n = ctypes.c_ulong()
450
+ policy = "AnyOn"
451
+ if R.FPDFPageObjMark_GetParamStringValue(mark, b"P", _BUF, ctypes.sizeof(_BUF), ctypes.byref(n)):
452
+ policy = bytes(_BUF)[:max(0, n.value - 2)].decode("utf-16-le", "replace").lstrip("/")
453
+ found = {(name, hidden) for p, name, hidden in self._ocmds(number) if p == policy}
454
+ return found.pop() if len(found) == 1 else ("", False)
455
+
456
+ def _ocmds(self, number):
457
+ cache = self._structure().setdefault("ocmds", {})
458
+ if number not in cache:
459
+ found = []
460
+ reader = self._reader()
461
+ if reader is None: # pypdf could not parse the file: no membership dictionaries to read
462
+ cache[number] = found
463
+ return found
464
+ page = reader.pages[number]
465
+
466
+ def visit(resources, depth):
467
+ if resources is None or depth > 8:
468
+ return
469
+ resources = resources.get_object()
470
+ for value in (resources.get("/Properties") or {}).values():
471
+ d = value.get_object()
472
+ if d.get("/Type") == "/OCMD":
473
+ state = self._ocmd_state(d)
474
+ if state is not None:
475
+ found.append(state)
476
+ for x in (resources.get("/XObject") or {}).values():
477
+ x = x.get_object()
478
+ if x.get("/Subtype") == "/Form":
479
+ visit(x.get("/Resources"), depth + 1)
480
+ visit(page.get("/Resources"), 0)
481
+ cache[number] = found
482
+ return cache[number]
483
+
484
+ def _ocmd_state(self, d):
485
+ """(policy, layer name, hidden) of a membership dictionary; None when it lists no layer."""
486
+ ocgs = d.get("/OCGs")
487
+ ocgs = ocgs.get_object() if ocgs is not None else []
488
+ ocgs = list(ocgs) if isinstance(ocgs, list) else [ocgs]
489
+ if not ocgs:
490
+ return None
491
+ policy = str(d.get("/P", "/AnyOn")).lstrip("/")
492
+ off = self._off_names()
493
+ state = [str(o.get_object().get("/Name", "")) not in off for o in ocgs]
494
+ visible = {"AnyOn": any(state), "AllOn": all(state), "AnyOff": not all(state),
495
+ "AllOff": not any(state)}.get(policy, any(state))
496
+ return policy, str(ocgs[-1].get_object().get("/Name", "")), not visible
497
+
498
+ def _form_oc(self, xobj):
499
+ """(layer, hidden) a Form XObject's own /OC entry gives its content ('' and False when it has none)."""
500
+ oc = xobj.get("/OC")
501
+ if oc is None:
502
+ return "", False
503
+ d = oc.get_object()
504
+ if d.get("/Type") == "/OCMD":
505
+ state = self._ocmd_state(d)
506
+ return ("", False) if state is None else (state[1], state[2])
507
+ name = str(d.get("/Name", ""))
508
+ return name, name in self._off_names()
509
+
510
+ def _form_xobjects(self, contents, resources):
511
+ """The Form XObjects one content stream paints, in the order it paints them (pypdf objects)."""
512
+ from pypdf.generic import ContentStream # noqa: PLC0415
513
+ if contents is None:
514
+ return []
515
+ res = resources.get_object() if resources is not None else {}
516
+ xobjs = res.get("/XObject") if res is not None else None
517
+ xobjs = xobjs.get_object() if xobjs is not None else {}
518
+ cs = contents if isinstance(contents, ContentStream) else ContentStream(contents.get_object(), self._pypdf)
519
+ out = []
520
+ for operands, op in cs.operations:
521
+ if op == b"Do" and operands:
522
+ x = xobjs.get(operands[0])
523
+ x = x.get_object() if x is not None else None
524
+ if x is not None and x.get("/Subtype") == "/Form":
525
+ out.append(x)
526
+ return out
527
+
528
+ def _off_names(self):
529
+ return {l["name"] for l in self._structure()["layers"] if not l["on"]}
530
+
531
+ def _reader(self):
532
+ self._structure()
533
+ return self._pypdf
534
+
535
+ def layers(self):
536
+ return list(self._structure()["layers"])
537
+
538
+ def structure_error(self):
539
+ """Why the layer structure could not be read (pypdf's error class), or None. The pages still read, without
540
+ layers; a reader labels its result with this instead of refusing."""
541
+ return self._structure().get("error")
542
+
543
+ def close(self):
544
+ self._pdf.close()