@floless/app 0.174.1 → 0.175.0

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.
Files changed (85) hide show
  1. package/autostart.mjs +117 -10
  2. package/dist/floless-server.cjs +2 -2
  3. package/dist/pdf-engine/floless_pdf/__init__.py +7 -3
  4. package/dist/pdf-engine/floless_pdf/backend_pdfium.py +292 -13
  5. package/dist/pdf-engine/floless_pdf/backend_pymupdf.py +25 -3
  6. package/dist/pdf-engine/floless_pdf/images.py +4 -3
  7. package/dist/pdf-engine/floless_pdf/pages.py +136 -0
  8. package/dist/schemas/steel.model.v2.schema.json +44 -1
  9. package/dist/skills/floless-app-approval/SKILL.md +28 -3
  10. package/dist/skills/floless-app-knowledge/SKILL.md +3 -2
  11. package/dist/skills/floless-app-sketches/SKILL.md +71 -0
  12. package/dist/skills/floless-app-sketches/references/steel-plate.md +15 -0
  13. package/dist/skills/floless-app-steel-model/SKILL.md +11 -1
  14. package/dist/skills/floless-app-steel-model/references/elements.md +90 -23
  15. package/dist/skills/floless-app-steel-takeoff/SKILL.md +11 -6
  16. package/dist/web/agents.js +1 -1
  17. package/dist/web/app.css +120 -15
  18. package/dist/web/app.js +89 -38
  19. package/dist/web/aware-hold.js +10 -0
  20. package/dist/web/aware.js +405 -51
  21. package/dist/web/boot-watchdog.js +249 -0
  22. package/dist/web/card-details.js +88 -0
  23. package/dist/web/chat.css +29 -0
  24. package/dist/web/chat.js +430 -128
  25. package/dist/web/commands-connection-design.js +23 -0
  26. package/dist/web/commands-revit.js +3 -0
  27. package/dist/web/commands-shell.js +226 -10
  28. package/dist/web/commands-steel.js +93 -4
  29. package/dist/web/commands-tekla-parser.js +21 -1
  30. package/dist/web/connection-design-editor.html +71 -0
  31. package/dist/web/connection-design-editor.js +794 -61
  32. package/dist/web/connection-design-handles.js +9 -3
  33. package/dist/web/element-approval.js +74 -0
  34. package/dist/web/element-context.js +76 -6
  35. package/dist/web/element-geometry.js +8 -2
  36. package/dist/web/element-holds.js +68 -5
  37. package/dist/web/element-type-actions.js +22 -3
  38. package/dist/web/element-types.js +12 -5
  39. package/dist/web/element-words.js +15 -11
  40. package/dist/web/grid-place.js +51 -0
  41. package/dist/web/guide.js +2 -0
  42. package/dist/web/index.html +13 -16
  43. package/dist/web/instructor.js +5 -2
  44. package/dist/web/missed-routines.js +6 -1
  45. package/dist/web/model-change-findings.js +100 -30
  46. package/dist/web/model-change-review.js +411 -27
  47. package/dist/web/model-clash-check.css +100 -0
  48. package/dist/web/model-clash-check.js +681 -0
  49. package/dist/web/model-clip-box.js +204 -0
  50. package/dist/web/model-clip-list.js +153 -3
  51. package/dist/web/model-clip-session.js +3 -3
  52. package/dist/web/model-clip-three-overlay.js +135 -25
  53. package/dist/web/model-editor.css +2 -0
  54. package/dist/web/model-elements.js +273 -18
  55. package/dist/web/model-fit-checks.js +354 -0
  56. package/dist/web/model-spatial-panel.js +9 -3
  57. package/dist/web/model-spatial-tools.js +12 -3
  58. package/dist/web/model-tekla-selection.js +74 -0
  59. package/dist/web/model-view-query.js +70 -14
  60. package/dist/web/model-viewport-revit-adapter.js +8 -7
  61. package/dist/web/model-viewport-toolbar.js +8 -4
  62. package/dist/web/pages.js +78 -1
  63. package/dist/web/project-history.js +31 -1
  64. package/dist/web/revit-editor.css +34 -1
  65. package/dist/web/revit-editor.js +174 -55
  66. package/dist/web/run-history.js +8 -0
  67. package/dist/web/sketch-editor.js +141 -2
  68. package/dist/web/sketches.js +192 -6
  69. package/dist/web/start-place.js +46 -0
  70. package/dist/web/steel-3d-core.js +70 -0
  71. package/dist/web/steel-3d-view.js +288 -47
  72. package/dist/web/steel-change-review.css +28 -0
  73. package/dist/web/steel-custom-connection.js +6 -0
  74. package/dist/web/steel-editor.html +532 -33
  75. package/dist/web/steel-filter.html +8 -3
  76. package/dist/web/steel-model-checks.css +76 -0
  77. package/dist/web/steel-model-v2-commands.js +17 -0
  78. package/dist/web/steel-view-generation.js +6 -2
  79. package/dist/web/teams.js +259 -19
  80. package/dist/web/tekla-editor.html +1 -0
  81. package/dist/web/terminal-requests.js +6 -0
  82. package/dist/web/vendor/connection-engine.js +886 -91
  83. package/dist/web/workspaces.js +630 -48
  84. package/package.json +2 -1
  85. package/preferences-file.mjs +27 -0
package/autostart.mjs CHANGED
@@ -40,12 +40,13 @@
40
40
  // — if ever needed — launch.mjs (plain JS), mirroring teardown.mjs / install-path.mjs.
41
41
  // Pure logic (the XML builder) is unit-tested; the imperative wrappers (schtasks.exe)
42
42
  // are exercised by the human's real Shut-Down → power-on E2E.
43
- import { execFileSync } from 'node:child_process';
43
+ import { execFile, execFileSync } from 'node:child_process';
44
+ import { promisify } from 'node:util';
44
45
  import { writeFileSync, rmSync, appendFileSync, mkdirSync } from 'node:fs';
45
46
  import { tmpdir } from 'node:os';
46
47
  import { dirname, join } from 'node:path';
47
48
  import { RUN_KEY, RUN_VALUE } from './teardown.mjs';
48
- import { homeHasPriorUse, preferencesPath, readAutostartIntent, readAutostartStored, setAutostartIntent, withLock } from './preferences-file.mjs';
49
+ import { homeHasPriorUse, preferencesPath, readAutostartIntent, readAutostartStored, setAutostartIntent, withAsyncLock, withLock } from './preferences-file.mjs';
49
50
  import { logDir, logFilePath } from './log.mjs';
50
51
  import { distributionProfile } from './distribution-profile-active.mjs';
51
52
 
@@ -188,6 +189,21 @@ function runSchtasks(args) {
188
189
  }
189
190
  }
190
191
 
192
+ const execFileAsync = promisify(execFile);
193
+ const taskProcessOptions = { encoding: 'utf8', windowsHide: true, timeout: 2500 };
194
+
195
+ async function runSchtasksAsync(args) {
196
+ try {
197
+ const { stdout } = await execFileAsync('schtasks', args, taskProcessOptions);
198
+ return { ok: true, stdout };
199
+ } catch { return { ok: false }; }
200
+ }
201
+
202
+ async function removeLegacyRunKeyAsync() {
203
+ try { await execFileAsync('reg', ['delete', RUN_KEY, '/v', RUN_VALUE, '/f'], taskProcessOptions); }
204
+ catch { /* the legacy value may already be gone */ }
205
+ }
206
+
191
207
  const bareName = (name) => String(name).replace(/^\\+/, '').toLowerCase();
192
208
 
193
209
  /**
@@ -226,13 +242,52 @@ function writeTaskXml(xml) {
226
242
  * Returns { saved, enabled, state, ok, busy }; never throws.
227
243
  */
228
244
  export function createAutostartController({
229
- platform = process.platform, taskName = TASK_NAME, run = runSchtasks, writeXml = writeTaskXml,
230
- userId = currentUserId, removeLegacy = removeLegacyRunKey, log = logLine,
231
- intent = () => readAutostartIntent(), stored = () => readAutostartStored(), prior = () => homeHasPriorUse(), store = (enabled) => setAutostartIntent(enabled),
245
+ platform = process.platform, taskName = TASK_NAME, run = runSchtasks, runAsync = runSchtasksAsync, writeXml = writeTaskXml,
246
+ userId = currentUserId, removeLegacy = removeLegacyRunKey, removeLegacyAsync = removeLegacyRunKeyAsync, log = logLine,
247
+ intent = () => readAutostartIntent(), stored = () => readAutostartStored(), prior = () => homeHasPriorUse(),
248
+ store = (enabled, options) => setAutostartIntent(enabled, undefined, options), now = Date.now, ttlMs = 60_000,
232
249
  lockPath = () => join(dirname(preferencesPath()), 'autostart'), lockWaitMs = 3000,
233
250
  } = {}) {
234
251
  const win = platform === 'win32';
235
252
 
253
+ let cached = 'unknown';
254
+ let validUntil = -Infinity;
255
+ let pending;
256
+ let generation = 0;
257
+ let changing = 0;
258
+
259
+ function invalidate() {
260
+ generation++;
261
+ validUntil = -Infinity;
262
+ }
263
+
264
+ function remember(state) {
265
+ cached = state;
266
+ validUntil = now() + ttlMs;
267
+ }
268
+
269
+ async function stateAsync() {
270
+ if (!win) return 'unknown';
271
+ try {
272
+ if ((await runAsync(['/query', '/tn', taskName])).ok) return 'present';
273
+ } catch { /* try the listing when the named query fails */ }
274
+ try {
275
+ const listing = await runAsync(['/query', '/fo', 'CSV', '/nh']);
276
+ return listing.ok ? taskStateFromListing(listing.stdout, taskName) : 'unknown';
277
+ } catch { return 'unknown'; }
278
+ }
279
+
280
+ function read() {
281
+ if (changing || now() < validUntil) return cached;
282
+ if (!pending) {
283
+ const epoch = generation;
284
+ pending = stateAsync().then((state) => {
285
+ if (generation === epoch) remember(state);
286
+ }).finally(() => { pending = null; });
287
+ }
288
+ return cached;
289
+ }
290
+
236
291
  function state() {
237
292
  if (!win) return 'unknown';
238
293
  if (run(['/query', '/tn', taskName]).ok) return 'present';
@@ -320,13 +375,65 @@ export function createAutostartController({
320
375
  }
321
376
  }
322
377
 
323
- return { state, register, unregister, reconcile, set };
378
+ async function setAsync(enabled, exePath) {
379
+ if (!win) return { saved: false, enabled: false, state: 'unknown', ok: false, busy: false };
380
+ changing++;
381
+ invalidate();
382
+ try {
383
+ return await withAsyncLock(lockPath(), async () => {
384
+ let saved = true;
385
+ try { store(enabled, { waitMs: 0 }); }
386
+ catch (error) {
387
+ saved = false;
388
+ log(`autostart: the choice could not be stored (${error?.message ?? error})`);
389
+ }
390
+ let tmp;
391
+ let commandSucceeded = false;
392
+ try {
393
+ if (enabled) {
394
+ tmp = writeXml(buildAutostartTaskXml(exePath, userId()));
395
+ commandSucceeded = (await runAsync(['/Create', '/TN', taskName, '/XML', tmp, '/F'])).ok;
396
+ if (commandSucceeded) await removeLegacyAsync();
397
+ } else {
398
+ commandSucceeded = (await runAsync(['/delete', '/tn', taskName, '/f'])).ok;
399
+ await removeLegacyAsync();
400
+ }
401
+ } catch (error) { log(`autostart: the task could not be changed (${error?.message ?? error})`); }
402
+ finally { if (tmp) { try { rmSync(tmp, { force: true }); } catch { /* best effort */ } } }
403
+ const observed = await stateAsync();
404
+ const wanted = enabled ? 'present' : 'absent';
405
+ // A successful scheduler command confirms the change if a separate query cannot answer.
406
+ const state = observed === 'unknown' && commandSucceeded ? wanted : observed;
407
+ remember(state);
408
+ return { saved, enabled: state === 'present', state, ok: saved && state === wanted, busy: false };
409
+ }, { waitMs: lockWaitMs });
410
+ } catch (error) {
411
+ log(`autostart: not changed (${error?.message ?? error})`);
412
+ if (changing === 1) remember('unknown');
413
+ return { saved: false, enabled: false, state: 'unknown', ok: false, busy: true };
414
+ } finally {
415
+ changing--;
416
+ }
417
+ }
418
+
419
+ function readStatus() {
420
+ const state = read();
421
+ return { supported: win, state, enabled: state === 'unknown' ? null : state === 'present' };
422
+ }
423
+
424
+ return { state, register, unregister, reconcile, set, readStatus, setAsync, invalidate };
324
425
  }
325
426
 
326
427
  const controller = createAutostartController();
428
+ export const readAutostartStatus = () => controller.readStatus();
429
+ export const setAutostartAsync = (enabled, exePath) => controller.setAsync(enabled, exePath);
430
+
431
+ function invalidateAfter(write) {
432
+ try { return write(); } finally { controller.invalidate(); }
433
+ }
327
434
 
328
435
  /** Register (or refresh) the task to run `"<exe>" --supervise`, then check it is there. Throws when it is not. Win-only. */
329
- export const registerAutostart = (exePath) => controller.register(exePath);
436
+ export const registerAutostart = (exePath) => invalidateAfter(() => controller.register(exePath));
330
437
 
331
438
  /** True iff Windows lists the autostart task. */
332
439
  export const autostartPresent = () => controller.state() === 'present';
@@ -338,14 +445,14 @@ export const autostartState = () => controller.state();
338
445
  * Follow the person's stored choice (#3070): called on every packaged open and by the install/update hooks. Puts a
339
446
  * missing task back, unless they turned Start with Windows off. Never throws. Win-only.
340
447
  */
341
- export const reconcileAutostart = (exePath, context) => controller.reconcile(exePath, context);
448
+ export const reconcileAutostart = (exePath, context) => invalidateAfter(() => controller.reconcile(exePath, context));
342
449
  export const ensureAutostart = reconcileAutostart;
343
450
 
344
451
  /** The Start with Windows setting: store the choice, change the task, check the result. */
345
- export const setAutostart = (enabled, exePath) => controller.set(enabled, exePath);
452
+ export const setAutostart = (enabled, exePath) => invalidateAfter(() => controller.set(enabled, exePath));
346
453
 
347
454
  /** Remove the autostart task AND any legacy Run-key value, then check it is gone. Throws when it is not. Win-only. */
348
- export const unregisterAutostart = () => controller.unregister();
455
+ export const unregisterAutostart = () => invalidateAfter(() => controller.unregister());
349
456
 
350
457
  /**
351
458
  * What PUT /api/autostart answers for a finished change (#3070), in plain words. enabled is what Windows really has, or null when
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/dist/floless-server.cjs
3
- size: 34156712 bytes
4
- sha256: ce5e44472648dc533086443f0924adeb551e4726d617e4bed729134b948ba06b
3
+ size: 35583310 bytes
4
+ sha256: b48a37cbcb27cb3ba7b45cfab0d9a7d7b9b8a457347ceb7a29186cdb01eff284
@@ -35,9 +35,13 @@ def _backend(engine):
35
35
  raise ValueError("unknown PDF engine %r (expected one of %s)" % (engine, ", ".join(ENGINES)))
36
36
 
37
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)
38
+ def open(source, engine, count_only_if_locked=False): # 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
+
41
+ `count_only_if_locked` (the page count's own reader, as MuPDF has always let it): a locked PDF opens for its
42
+ `page_count` and nothing else, every other call raises PermissionError. Where the engine cannot tell the count
43
+ without the password (PDFium, and a file whose page tree is itself encrypted) it still raises PermissionError."""
44
+ return _backend(engine).Document(source, count_only_if_locked=count_only_if_locked)
41
45
 
42
46
 
43
47
  def versions(engine):
@@ -25,6 +25,10 @@ from .geometry import Matrix, Point, Rect, rotation_matrix
25
25
  NAME = "pdfium"
26
26
 
27
27
 
28
+ class StructureError(Exception):
29
+ """pypdf could not read the document's structure; the message is its error class name."""
30
+
31
+
28
32
  def versions():
29
33
  return {"pypdfium2": str(pdfium.PYPDFIUM_INFO.version), "pdfium": str(pdfium.PDFIUM_INFO.build)}
30
34
 
@@ -63,11 +67,19 @@ def _same_items(a, b):
63
67
 
64
68
 
65
69
  class Page:
70
+ # The whole-page picture's JPEG quality (pages.page_picture/page_pictures); tiles keep images.JPEG_QUALITY. At 88
71
+ # pdfium's optimised JPEG is within the 1.25x size bar of MuPDF's quality-95 picture on every corpus page, with no
72
+ # ink measure moving against quality 95 (slice 2b, docs/superpowers/specs/2026-11-23-pdf-engine-slice2-PLAN.md).
73
+ PAGE_JPEG_QUALITY = 88
74
+
66
75
  def __init__(self, doc, number):
67
76
  self._doc = doc
68
77
  self._p = doc._pdf[number]
69
78
  self.number = number
70
- cx0, cy0, cx1, cy1 = self._p.get_cropbox()
79
+ # PDFium's own page box: the crop box clipped to the media box, which is MuPDF's `page.rect` (a crop box larger
80
+ # than the media box shows only the media box; the raw crop box would stretch the picture and shift every
81
+ # coordinate by the overhang).
82
+ cx0, cy0, cx1, cy1 = self._p.get_bbox()
71
83
  w, h = cx1 - cx0, cy1 - cy0
72
84
  self._ctm = Matrix(1, 0, 0, -1, -cx0, cy1) # PDF user space -> unrotated page space (y down)
73
85
  self.rotation = self._p.get_rotation() % 360
@@ -77,6 +89,7 @@ class Page:
77
89
  self._tp = None
78
90
  self._layer_cache = {}
79
91
  self._tree_cache = None
92
+ self._hairlines_beveled = False
80
93
 
81
94
  # ---- layers -------------------------------------------------------------------------------------------------
82
95
  def _layer(self, obj):
@@ -307,16 +320,54 @@ class Page:
307
320
 
308
321
  # ---- pictures -----------------------------------------------------------------------------------------------
309
322
  def render(self, scale=None, dpi=None, clip=None):
323
+ """The displayed page (or the `clip` of it, in displayed page space: `size`, origin top-left) as RGB on white,
324
+ with MuPDF's pixel box: at scale s the left/top pixel edge is floor(v*s + 0.001), the right/bottom one
325
+ ceil(v*s - 0.001), so a picture or a tile has exactly the size PyMuPDF gives it (slice 2, S2-6)."""
310
326
  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
327
+ w, h = self.size
328
+ full = (0, 0, _ceil(w * k), _ceil(h * k))
329
+ if clip is None:
330
+ box = full
331
+ else:
314
332
  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)
333
+ box = (max(full[0], _floor(x0 * k)), max(full[1], _floor(y0 * k)),
334
+ min(full[2], _ceil(x1 * k)), min(full[3], _ceil(y1 * k)))
335
+ bw, bh = box[2] - box[0], box[3] - box[1]
336
+ if bw < 1 or bh < 1:
337
+ raise ValueError("the clip lies outside the page")
338
+ self._bevel_hairline_joins()
339
+ bitmap = pdfium.PdfBitmap.new_native(bw, bh, R.FPDFBitmap_BGR)
340
+ bitmap.fill_rect((255, 255, 255, 255), 0, 0, bw, bh)
341
+ # The whole displayed page is mapped onto MuPDF's full-page pixel size and shifted by the box's corner; PDFium
342
+ # applies the page's own /Rotate (rotate=0), and draws annotation appearances as MuPDF does.
343
+ R.FPDF_RenderPageBitmap(bitmap.raw, self._p.raw, -box[0], -box[1], full[2], full[3], 0, R.FPDF_ANNOT)
318
344
  return images.to_rgb(bitmap.to_pil())
319
345
 
346
+ def _bevel_hairline_joins(self):
347
+ """Draw every width-0 (hairline) stroke with bevel joins instead of miters, once per page, before the first
348
+ picture. A hairline is the thinnest line the device draws, 1 px; MuPDF and the reference viewer (pdf.js) draw
349
+ it as plain segments, but PDFium widens it to 1 px and then applies the miter join, so the sharp triangles CAD
350
+ exports fill small dots with grew spikes up to 4 px long at picture dpi: new ink nobody else paints (slice 2b,
351
+ the new-ink investigation). A bevel adds at most half a pixel at a 1 px width. Only the loaded page objects in
352
+ memory change, never the file; no reader here reports a join, so text and linework are untouched."""
353
+ if self._hairlines_beveled:
354
+ return
355
+ self._hairlines_beveled = True
356
+ width, mode, stroke = ctypes.c_float(), ctypes.c_int(), ctypes.c_int()
357
+
358
+ def walk(parent, in_form):
359
+ n = R.FPDFFormObj_CountObjects(parent) if in_form else R.FPDFPage_CountObjects(parent)
360
+ for i in range(n):
361
+ obj = R.FPDFFormObj_GetObject(parent, i) if in_form else R.FPDFPage_GetObject(parent, i)
362
+ t = R.FPDFPageObj_GetType(obj)
363
+ if t == R.FPDF_PAGEOBJ_FORM:
364
+ walk(obj, True)
365
+ elif (t == R.FPDF_PAGEOBJ_PATH and R.FPDFPageObj_GetLineJoin(obj) == R.FPDF_LINEJOIN_MITER
366
+ and R.FPDFPath_GetDrawMode(obj, mode, stroke) and stroke.value
367
+ and R.FPDFPageObj_GetStrokeWidth(obj, width) and width.value == 0):
368
+ R.FPDFPageObj_SetLineJoin(obj, R.FPDF_LINEJOIN_BEVEL)
369
+ walk(self._p.raw, False)
370
+
320
371
  def render_jpeg(self, scale=None, dpi=None, clip=None, quality=images.JPEG_QUALITY):
321
372
  img = self.render(scale, dpi, clip)
322
373
  return images.encode_jpeg(img, quality), img.size
@@ -326,6 +377,14 @@ class Page:
326
377
  return images.encode_png(img), img.size
327
378
 
328
379
 
380
+ def _floor(v):
381
+ return int(math.floor(v + 0.001))
382
+
383
+
384
+ def _ceil(v):
385
+ return int(math.ceil(v - 0.001))
386
+
387
+
329
388
  def _dashes(obj, k):
330
389
  n = R.FPDFPageObj_GetDashCount(obj)
331
390
  phase = ctypes.c_float()
@@ -386,24 +445,184 @@ def _path_items(obj, m, x, y):
386
445
  return items
387
446
 
388
447
 
448
+ def _drop_unreachable(writer):
449
+ """Keep only the objects the piece's trailer reaches. pypdf's unreferenced pass frees one level of orphans per call
450
+ (an object counts as referenced while any other object, itself orphaned or not, points at it), so a removed page's
451
+ resource dictionaries, Forms and images stayed: a 3-page piece of a 40 MB set was written at 40 MB, and MuPDF's
452
+ piece of the same pages is 6.7 MB (slice 2b profile). Reached from the catalog; the piece has no /Info and is
453
+ written unencrypted, and its /ID is a direct value."""
454
+ from pypdf.generic import ArrayObject, DictionaryObject, IndirectObject # noqa: PLC0415
455
+
456
+ reached = set()
457
+ stack = [writer._root_object.indirect_reference] # noqa: SLF001
458
+ while stack:
459
+ item = stack.pop()
460
+ if isinstance(item, IndirectObject):
461
+ if item.idnum in reached:
462
+ continue
463
+ reached.add(item.idnum)
464
+ item = writer.get_object(item.idnum)
465
+ if isinstance(item, DictionaryObject):
466
+ stack.extend(item.values())
467
+ elif isinstance(item, ArrayObject):
468
+ stack.extend(item)
469
+ objects = writer._objects # noqa: SLF001 - pypdf writes every object left in this list
470
+ for i in range(len(objects)):
471
+ if objects[i] is not None and i + 1 not in reached:
472
+ objects[i] = None
473
+
474
+
475
+ def _prune_removed_targets(writer, root):
476
+ """What still points at a removed page after pypdf's `remove_page(clean=True)`, which only turns the page into
477
+ `null`: a link or an outline item whose destination is that page goes (as MuPDF's select drops them), an outline
478
+ item with children keeps them and loses only its destination, and a form field whose widgets were all on removed
479
+ pages leaves /AcroForm (the kept pages' fields stay). Named destinations are left as they are (a stated limit)."""
480
+ from pypdf.generic import ArrayObject, IndirectObject, NameObject, NullObject, NumberObject # noqa: PLC0415
481
+
482
+ def obj(v):
483
+ return v.get_object() if isinstance(v, IndirectObject) else v
484
+
485
+ def dead(d):
486
+ d = obj(d)
487
+ if hasattr(d, "get") and not isinstance(d, list): # an action, or a destination dictionary
488
+ d = obj(d.get("/D")) if d.get("/S", "/GoTo") == "/GoTo" else None
489
+ return isinstance(d, list) and len(d) > 0 and isinstance(d[0], IndirectObject) \
490
+ and isinstance(d[0].get_object(), NullObject)
491
+
492
+ def goes_nowhere(item):
493
+ return dead(item.get("/Dest")) or ("/A" in item and dead(item["/A"]))
494
+
495
+ kept_annots = set()
496
+ for page in writer.pages:
497
+ annots = obj(page.get("/Annots"))
498
+ if not isinstance(annots, list):
499
+ continue
500
+ alive = ArrayObject(a for a in annots if not goes_nowhere(obj(a)))
501
+ if len(alive) != len(annots):
502
+ page[NameObject("/Annots")] = alive
503
+ kept_annots.update(a.idnum for a in alive if isinstance(a, IndirectObject))
504
+
505
+ outlines = obj(root.get("/Outlines"))
506
+ if outlines is not None and hasattr(outlines, "get"):
507
+ def prune(parent):
508
+ """Unlink the children that go nowhere; returns the open-descendant count for /Count."""
509
+ items, child = [], parent.get("/First")
510
+ while child is not None:
511
+ items.append(child)
512
+ child = obj(child).get("/Next")
513
+ kept, visible = [], 0
514
+ for ref in items:
515
+ item = obj(ref)
516
+ if goes_nowhere(item):
517
+ if item.get("/First") is None:
518
+ continue
519
+ for key in ("/Dest", "/A"):
520
+ if key in item:
521
+ del item[NameObject(key)]
522
+ sub = prune(item)
523
+ if "/Count" in item:
524
+ item[NameObject("/Count")] = NumberObject(sub if int(item["/Count"]) > 0 else -sub)
525
+ kept.append(ref)
526
+ visible += 1 + (sub if int(item.get("/Count", 0)) > 0 else 0)
527
+ for key in ("/First", "/Last"):
528
+ if key in parent:
529
+ del parent[NameObject(key)]
530
+ for i, ref in enumerate(kept):
531
+ item = obj(ref)
532
+ for key, other in (("/Prev", kept[i - 1] if i else None), ("/Next", kept[i + 1] if i + 1 < len(kept) else None)):
533
+ if other is None:
534
+ if key in item:
535
+ del item[NameObject(key)]
536
+ else:
537
+ item[NameObject(key)] = other
538
+ if kept:
539
+ parent[NameObject("/First")], parent[NameObject("/Last")] = kept[0], kept[-1]
540
+ return visible
541
+ visible = prune(outlines)
542
+ if visible or outlines.get("/First") is not None:
543
+ if "/Count" in outlines:
544
+ outlines[NameObject("/Count")] = NumberObject(visible)
545
+ else:
546
+ del root[NameObject("/Outlines")]
547
+
548
+ form = obj(root.get("/AcroForm"))
549
+ if form is not None and isinstance(obj(form.get("/Fields")), list):
550
+ def keep_field(ref):
551
+ field = obj(ref)
552
+ if isinstance(field, NullObject) or field is None:
553
+ return False
554
+ kids = obj(field.get("/Kids"))
555
+ if isinstance(kids, list) and len(kids):
556
+ alive = [k for k in kids if keep_field(k)]
557
+ if len(alive) != len(kids):
558
+ field[NameObject("/Kids")] = ArrayObject(alive)
559
+ return bool(alive)
560
+ if field.get("/Subtype") == "/Widget": # a widget belongs to the page whose /Annots lists it
561
+ if isinstance(ref, IndirectObject):
562
+ return ref.idnum in kept_annots
563
+ return not isinstance(obj(field.get("/P")), NullObject)
564
+ return True # a field with no widget is on no page: it stays
565
+ fields = obj(form["/Fields"])
566
+ alive = ArrayObject(f for f in fields if keep_field(f))
567
+ if len(alive) != len(fields):
568
+ form[NameObject("/Fields")] = alive
569
+
570
+
571
+ def _locked_page_count(source):
572
+ """A password-locked PDF's page count from its page tree's /Count, or None when it cannot be read without the
573
+ password (the tree sits in an encrypted object stream, or pypdf is not installed)."""
574
+ try:
575
+ import io # noqa: PLC0415
576
+ import pypdf # noqa: PLC0415
577
+ reader = pypdf.PdfReader(io.BytesIO(bytes(source)) if isinstance(source, (bytes, bytearray)) else source, strict=False)
578
+ if not reader.is_encrypted:
579
+ return None
580
+ reader._encryption = None # noqa: SLF001 - pypdf refuses every object until decrypted; /Count is not encrypted
581
+ count = reader.trailer["/Root"]["/Pages"]["/Count"]
582
+ return int(count) if isinstance(count, int) and count >= 0 else None
583
+ except Exception: # noqa: BLE001 - nothing readable: the file stays locked and the count is labelled unavailable
584
+ return None
585
+
586
+
389
587
  class Document:
390
- def __init__(self, source):
588
+ def __init__(self, source, count_only_if_locked=False):
391
589
  self._source = source
590
+ self.locked = False
591
+ self._struct = None
592
+ self.engine = {"name": NAME, **versions()}
392
593
  try:
393
594
  self._pdf = pdfium.PdfDocument(bytes(source) if isinstance(source, (bytes, bytearray)) else source)
394
595
  except pdfium.PdfiumError as error:
395
- if "password" in str(error).lower():
596
+ if "password" not in str(error).lower():
597
+ raise
598
+ # PDFium will not open a locked file at all. For the page count only, the page tree's /Count (a plain
599
+ # number, never encrypted) is read through pypdf; when that cannot be read the file stays locked.
600
+ counted = _locked_page_count(source) if count_only_if_locked else None
601
+ if counted is None:
396
602
  raise PermissionError("the PDF needs a password") from error
397
- raise
603
+ self._pdf, self.locked, self.page_count = None, True, counted
604
+ return
398
605
  self.page_count = len(self._pdf)
399
- self.engine = {"name": NAME, **versions()}
400
- self._struct = None
401
606
 
402
607
  def page(self, number):
608
+ if self.locked:
609
+ raise PermissionError("the PDF needs a password")
403
610
  if not 0 <= number < self.page_count:
404
611
  raise IndexError("page %d of %d" % (number + 1, self.page_count))
405
612
  return Page(self, number)
406
613
 
614
+ def page_size(self, number):
615
+ """A page's displayed size, `Page.size`, from the page tree alone: the crop box clipped to the media box, turned
616
+ by /Rotate. PDFium's page load parses every content object, which the page count's bounds never need."""
617
+ if self.locked:
618
+ raise PermissionError("the PDF needs a password")
619
+ if not 0 <= number < self.page_count:
620
+ raise IndexError("page %d of %d" % (number + 1, self.page_count))
621
+ size = R.FS_SIZEF()
622
+ if not R.FPDF_GetPageSizeByIndexF(self._pdf.raw, number, size):
623
+ return Page(self, number).size # PDFium could not read the box without the page: load it once
624
+ return (size.width, size.height)
625
+
407
626
  def _structure(self):
408
627
  """The document's structure through pypdf (layers and their membership dictionaries); PDFium has no call."""
409
628
  if self._struct is None:
@@ -532,6 +751,65 @@ class Document:
532
751
  self._structure()
533
752
  return self._pypdf
534
753
 
754
+ @property
755
+ def is_pdf(self):
756
+ return True # PDFium opens nothing else
757
+
758
+ def write_pages(self, numbers, out_path, source_sha256=None):
759
+ """The document narrowed to the 0-based `numbers`, in that order (plan 5.5, slice 2 S2-7): pypdf removes the
760
+ other pages from the ORIGINAL document, so its layers, their defaults, forms and names stay; `/Info` and the
761
+ XMP metadata go; the source's /ID is kept, and a source without one gets an id derived from its sha256 and the
762
+ choice (never random), so the same choice gives the same bytes. Written unencrypted. Raises StructureError
763
+ when pypdf cannot read the document (the caller decides how to go on, S2-5)."""
764
+ import hashlib # noqa: PLC0415
765
+ import io # noqa: PLC0415
766
+ try:
767
+ import pypdf # noqa: PLC0415
768
+ from pypdf.generic import ArrayObject, ByteStringObject, NameObject # noqa: PLC0415
769
+ src = io.BytesIO(bytes(self._source)) if isinstance(self._source, (bytes, bytearray)) else self._source
770
+ reader = pypdf.PdfReader(src, strict=False)
771
+ if reader.is_encrypted and not reader.decrypt(""):
772
+ raise PermissionError("the PDF needs a password")
773
+ writer = pypdf.PdfWriter(clone_from=reader)
774
+ except PermissionError:
775
+ raise
776
+ except Exception as error: # noqa: BLE001 - named for the caller's label
777
+ raise StructureError(type(error).__name__) from error
778
+ keep = list(numbers)
779
+ pages = list(writer.pages)
780
+ chosen = [pages[n].indirect_reference for n in keep]
781
+ for n in sorted(set(range(len(pages))) - set(keep), reverse=True):
782
+ writer.remove_page(n, clean=True)
783
+ if keep != sorted(keep): # the choice's own order, as MuPDF's select keeps it
784
+ kids = writer._pages.get_object()["/Kids"] # noqa: SLF001 - pypdf has no public reorder
785
+ kids.clear()
786
+ kids.extend(chosen)
787
+ root = writer._root_object # noqa: SLF001
788
+ _prune_removed_targets(writer, root)
789
+ if NameObject("/Metadata") in root:
790
+ del root[NameObject("/Metadata")]
791
+ writer._info = None # noqa: SLF001 - no /Info, no dates
792
+ if not getattr(writer, "_ID", None):
793
+ seed = hashlib.md5(("floless-piece\0%s\0%s" % (source_sha256 or "", ",".join(map(str, keep)))).encode()).digest()
794
+ writer._ID = ArrayObject([ByteStringObject(seed), ByteStringObject(seed)]) # noqa: SLF001
795
+ writer.compress_identical_objects(remove_duplicates=False, remove_unreferenced=True)
796
+ _drop_unreachable(writer)
797
+ with open(out_path, "wb") as f:
798
+ writer.write(f)
799
+ return {"pages": len(keep), "structureError": None, "labels": []}
800
+
801
+ def copy_pages(self, numbers, out_path):
802
+ """The last resort when pypdf cannot read the document and PyMuPDF is not installed: PDFium copies the pages
803
+ into a NEW document. The document's layer settings, forms and names do not come along, so a hidden layer can
804
+ show; the caller labels the piece with exactly that (S2-5)."""
805
+ new = pdfium.PdfDocument.new()
806
+ try:
807
+ new.import_pages(self._pdf, list(numbers))
808
+ new.save(out_path)
809
+ return {"pages": len(new)}
810
+ finally:
811
+ new.close()
812
+
535
813
  def layers(self):
536
814
  return list(self._structure()["layers"])
537
815
 
@@ -541,4 +819,5 @@ class Document:
541
819
  return self._structure().get("error")
542
820
 
543
821
  def close(self):
544
- self._pdf.close()
822
+ if self._pdf is not None: # None for a locked file opened for its page count only
823
+ self._pdf.close()
@@ -56,6 +56,8 @@ _NOT_MARKUP = {"Link", "Popup"}
56
56
 
57
57
 
58
58
  class Page:
59
+ PAGE_JPEG_QUALITY = 95 # MuPDF's own encoder at today's quality: the oracle's pictures stay byte-identical
60
+
59
61
  def __init__(self, doc, number):
60
62
  self._doc = doc
61
63
  self._page = doc._doc[number]
@@ -195,26 +197,46 @@ def _drawing_key(d):
195
197
 
196
198
 
197
199
  class Document:
198
- def __init__(self, source):
200
+ def __init__(self, source, count_only_if_locked=False):
199
201
  if isinstance(source, (bytes, bytearray)):
200
202
  self._doc = fitz.open(stream=bytes(source), filetype="pdf")
201
203
  else:
202
204
  self._doc = fitz.open(source)
203
- if self._doc.needs_pass:
205
+ self.locked = bool(self._doc.needs_pass)
206
+ if self.locked and not count_only_if_locked:
204
207
  self._doc.close()
205
208
  raise PermissionError("the PDF needs a password")
206
- self.page_count = self._doc.page_count
209
+ self.page_count = self._doc.page_count # MuPDF counts a locked file's pages without the password
207
210
  self.engine = {"name": NAME, **versions()}
208
211
 
209
212
  def page(self, number):
213
+ if self.locked:
214
+ raise PermissionError("the PDF needs a password")
210
215
  if not 0 <= number < self.page_count:
211
216
  raise IndexError("page %d of %d" % (number + 1, self.page_count))
212
217
  return Page(self, number)
213
218
 
219
+ def page_size(self, number):
220
+ """A page's displayed size, `Page.size` (MuPDF reads it without drawing anything)."""
221
+ return self.page(number).size
222
+
214
223
  def layers(self):
215
224
  """Every layer (optional content group) with its default visibility, in the document's own order."""
216
225
  return [{"name": v.get("name", ""), "on": bool(v.get("on"))} for _, v in sorted(self._doc.get_ocgs().items())]
217
226
 
227
+ @property
228
+ def is_pdf(self):
229
+ return bool(self._doc.is_pdf)
230
+
231
+ def write_pages(self, numbers, out_path, _source_sha256=None):
232
+ """The document narrowed to the 0-based `numbers`, in that order, written to `out_path` exactly as the
233
+ left-for-later piece always was: no metadata, no new id, unused objects dropped. Returns the page count."""
234
+ self._doc.select(list(numbers))
235
+ self._doc.set_metadata({})
236
+ self._doc.del_xml_metadata()
237
+ self._doc.save(out_path, garbage=3, deflate=True, no_new_id=True)
238
+ return {"pages": self._doc.page_count, "structureError": None, "labels": []}
239
+
218
240
  def structure_error(self):
219
241
  """Why the layer structure could not be read, or None. MuPDF reads it with the page, so always None."""
220
242
  return None
@@ -7,8 +7,9 @@ of what a reader produces:
7
7
  RGB (palette, greyscale and CMYK included) after its EXIF orientation is applied.
8
8
  - ALPHA: never kept. A transparent image is laid on white first (straight alpha), so a transparent corner is white,
9
9
  not black.
10
- - JPEG: Pillow's encoder (libjpeg-turbo in the pinned wheel), baseline (not progressive), no optimisation pass, chroma
11
- subsampling 4:2:0, quality from the caller (95 unless the reader asks for less; the Filter backdrop asks for 35).
10
+ - JPEG: Pillow's encoder (libjpeg-turbo in the pinned wheel), baseline (not progressive), optimised Huffman tables (lossless, slice 2b), chroma
11
+ subsampling 4:2:0, quality from the caller (95 unless the reader asks for less: a whole-page picture on pdfium asks for 88, the Filter
12
+ backdrop for 35).
12
13
  - PNG: Pillow's encoder, compression level 6, no optimisation pass.
13
14
  - DOWNSAMPLING: a render is made at the requested scale directly, never resampled. Making a picture smaller
14
15
  (`fit_within`) is area averaging (Pillow's BOX filter), so a hairline fades rather than vanishes or turns jagged.
@@ -43,7 +44,7 @@ def encode_jpeg(img, quality=JPEG_QUALITY):
43
44
  if not 1 <= q <= 100:
44
45
  raise ValueError("JPEG quality must be 1-100, got %r" % (quality,))
45
46
  out = io.BytesIO()
46
- to_rgb(img).save(out, "JPEG", quality=q, subsampling=JPEG_SUBSAMPLING, optimize=False, progressive=False)
47
+ to_rgb(img).save(out, "JPEG", quality=q, subsampling=JPEG_SUBSAMPLING, optimize=True, progressive=False)
47
48
  return out.getvalue()
48
49
 
49
50