Debian Codegraph @

texk/texlive/linked_scripts/extractbb/extractbb.lua

raw symbols SCIP
1 #!/usr/bin/env texlua
2 -- extractbb-lua
3 -- https://github.com/gucci-on-fleek/extractbb
4 -- SPDX-License-Identifier: MPL-2.0+
5 -- SPDX-FileCopyrightText: 2024--2025 Max Chernoff
6 --
7 -- Inclusion Methods
8 -- =================
9 --
10 -- This script can use two different methods to extract bounding boxes from
11 -- images: the "img" module and the "pdfe" module. The "img" module will be
12 -- automatically selected in most cases and supports all image types that are
13 -- supported by the original "extractbb" program. If and only if the "img"
14 -- module fails to load, the "pdfe" module will be used as a fallback. However,
15 -- the "pdfe" module only supports PDF files. Both modules are built in to the
16 -- LuaTeX binaries, however due to some technical issues, the "img" module may
17 -- fail to load on some more exotic platforms.
18 --
19 --
20 -- Compatibility
21 -- =============
22 --
23 -- Based off of my testing, this Lua script is 100% compatible with the original
24 -- C-based "extractbb" program, with the following exceptions:
25 --
26 -- * When running in "img" mode, the PDF version is always reported as "1.5".
27 --
28 -- * When running in "img" mode, if the requested bounding box is not found,
29 -- the script will fallback to the Crop box or the Media box, instead of
30 -- following the original fallback order. (In practice, almost all PDFs set
31 -- all their bounding boxes equal to each other, and even if the boxes are
32 -- set to different values, the script will still return the requested box,
33 -- provided that it is set in the PDF.)
34 --
35 -- * When running in "pdfe" mode, only PDF files are supported.
36 --
37 -- All of these issues are very unlikely to affect any real-world documents.
38 --
39 --
40 -- Security
41 -- ========
42 --
43 -- This script is designed to be safely ran from restricted shell escape. A few
44 -- security features:
45 --
46 -- * The majority of this script runs inside a sandboxed Lua environment,
47 -- which only exposes a very restricted set of functions.
48 --
49 -- * All file-related functions available inside the sandbox first check with
50 -- kpathsea to ensure that the file is allowed to be opened.
51 --
52 -- * In the event of any errors, the script immediately exits.
53 --
54 -- * This script does not run (fork/exec) any external programs.
55 --
56 -- * This script is written entirely in Lua, so overflow/use-after-free
57 -- vulnerabilities are not possible.
58 --
59 -- Some potential security concerns:
60 --
61 -- * This script has not been audited or reviewed by anyone other than myself.
62 --
63 -- * The underlying LuaTeX modules may themselves have security
64 -- vulnerabilities, which would be inherited by this script.
65
66
67 ----------------------
68 --- Initialization ---
69 ----------------------
70
71 -- Pre-sandbox variables/constants
72 local show_errors = true
73 local SOURCE_DATE_EPOCH = tonumber(os.getenv("SOURCE_DATE_EPOCH"))
74 local version = "extractbb.lua v1.1.0 (2025-02-11)" --%%version %%dashdate
75
76 -- Required for any kpathsea calls to work.
77 kpse.set_program_name("texlua", "extractbb")
78
79 -- Required to use the "img" module from texlua, but only works for LuaTeX
80 -- versions >= 1.21.0.
81 if not (status.development_id >= 7661) then
82 error("LuaTeX version is too old, cannot proceed.")
83 end
84 texconfig.texlua_img = true
85
86 -- We need to set \outputmode to PDF to be able to use most of the "img" module
87 -- functions, but to set \outputmode, we need to initialize the TeX interpreter.
88 tex.initialize()
89 _G.tex = package.loaded.tex
90 tex.enableprimitives("", tex.extraprimitives())
91 tex.outputmode = 1
92 tex.interactionmode = 0
93
94 -- "pdf" module
95 _G.pdf = package.loaded.pdf
96 pdf.setignoreunknownimages(1)
97 pdf.setmajorversion(2)
98 pdf.setminorversion(0)
99
100
101 ------------------
102 --- Sandboxing ---
103 ------------------
104
105 -- Prepare the sandbox for the rest of the script.
106 local env = {
107 arg = arg,
108 io = { stdout = io.stdout, },
109 ipairs = ipairs,
110 math = math,
111 os = { date = os.date, exit = os.exit, },
112 pairs = pairs,
113 pdfe = pdfe,
114 print = print,
115 select = select,
116 table = table,
117 tonumber = tonumber,
118 type = type,
119 }
120
121 do
122 -- Saved global functions
123 local debug_traceback = debug.traceback
124 local find_file = kpse.find_file
125 local img_scan = img.scan
126 local io_open = io.open
127 local io_stderr = io.stderr
128 local kpse_in_name_ok = kpse.in_name_ok
129 local kpse_out_name_ok = kpse.out_name_ok
130 local kpse_var_value = kpse.var_value
131 local lfs_attributes = lfs.attributes
132 local os_exit = os.exit
133 local os_setenv = os.setenv
134 local pdfe_open = pdfe.open
135 local select = select
136 local tostring = tostring
137
138 -- Error messages
139 local function error(...)
140 if show_errors then
141 -- Header
142 io_stderr:write("! extractbb ERROR: ")
143
144 -- Message
145 for i = 1, select("#", ...) do
146 io_stderr:write(tostring(select(i, ...)), " ")
147 end
148
149 -- Traceback
150 io_stderr:write("\n", "\n")
151 io_stderr:write(debug_traceback(nil, 2), "\n")
152 end
153
154 -- Flush and exit
155 io_stderr:flush()
156 os_exit(1)
157 end
158
159 env.error = error
160
161 -- Make sure that "openin_any" is at least "restricted", and that
162 -- "openout_any" is at least "paranoid".
163 local initial_openin = kpse_var_value("openin_any")
164 local initial_openout = kpse_var_value("openout_any")
165
166 if (initial_openin ~= "r") or (initial_openout ~= "p") then
167 os_setenv("openin_any", "r")
168 end
169
170 if (initial_openout ~= "p") then
171 os_setenv("openout_any", "p")
172 end
173
174 -- Check the input paths.
175 local function resolve_input_name(file_name)
176 local file_path = find_file(file_name, "graphic/figure", true)
177 if not file_path then
178 error("Cannot find input file:", file_name)
179 end
180
181 local allowed = kpse_in_name_ok(file_path)
182 if not allowed then
183 error("Input file is not allowed:", file_path)
184 end
185
186 local mode = lfs_attributes(file_path, "mode")
187 if mode ~= "file" then
188 error("Input file is not a regular file:", file_path)
189 end
190
191 return file_path
192 end
193
194 -- Check the output paths.
195 local function resolve_output_name(file_name)
196 local allowed = kpse_out_name_ok(file_name)
197 if not allowed then
198 error("Output file is not allowed:", file_name)
199 end
200
201 local name, extension = file_name:match("(.+)%.([^.]-)$")
202
203 if (not name) or (not extension) or
204 (name == "") or (extension == "")
205 then
206 error("Output file has no extension:", file_name)
207 end
208
209 if (extension ~= "xbb") and (extension ~= "bb") then
210 error("Output file has an invalid extension:", file_name)
211 end
212
213 -- We shouldn't allow files with weird characters in their names.
214 if name:match("[%c%%\t\r\n><*|]") then
215 error("Output file has an invalid name:", file_name)
216 end
217
218 return file_name
219 end
220
221 -- Opens a file.
222 function env.open_file(file_name, read_write, binary_text)
223 local file_path, mode
224 if read_write == "read" then
225 file_path = resolve_input_name(file_name)
226 mode = "r"
227 elseif read_write == "write" then
228 file_path = resolve_output_name(file_name)
229 mode = "w"
230 else
231 error("Invalid read/write mode:", read_write)
232 end
233
234 if binary_text == "binary" then
235 mode = mode .. "b"
236 elseif binary_text == "text" then
237 mode = mode .. ""
238 else
239 error("Invalid binary/text mode:", binary_text)
240 end
241
242 local file, message = io_open(file_path, mode)
243
244 if not file then
245 error("Cannot open file:", file_path, message)
246 end
247
248 return file
249 end
250
251 -- Open an PDF file.
252 function env.pdfe.open(file_name)
253 local file_path = resolve_input_name(file_name)
254 return pdfe_open(file_path)
255 end
256
257 -- Open an image file.
258 function env.open_image(file_name, page, box)
259 local file_path = resolve_input_name(file_name)
260 return img_scan {
261 filename = file_path,
262 filepath = file_path,
263 page = page,
264 pagebox = box,
265 }
266 end
267
268 if not img_scan then
269 env.open_image = false
270 end
271 end
272
273 -- Prevent trying to change the environment.
274 local function bad_index(...)
275 env.error("Attempt to access an undefined index:", select(2, ...))
276 end
277
278 setmetatable(env, {
279 __index = bad_index,
280 __metatable = false,
281 __newindex = bad_index,
282 })
283
284 -- Set the environment.
285 _ENV = env
286
287
288 -----------------------------------
289 --- Post-Sandbox Initialization ---
290 -----------------------------------
291
292 -- Constants
293 local BP_TO_SP = 65781.76
294 local IN_TO_BP = 72
295 local DATE_FORMAT = "%a %b %d %H:%M:%S %Y" -- "%c"
296
297 -- Save often-used globals for a slight speed boost.
298 local floor = math.floor
299 local insert = table.insert
300 local remove = table.remove
301 local script_arguments = arg
302 local unpack = table.unpack
303
304 -- General-purpose functions
305 local function round(number)
306 return floor(number +0.5)
307 end
308
309
310 -------------------------
311 --- Argument Handling ---
312 -------------------------
313
314 -- Define the argument handling functions.
315 local process_arguments = {}
316
317 -- > Specify a PDF pagebox for bounding box
318 -- > pagebox=cropbox, mediabox, artbox, trimbox, bleedbox
319 local bbox_option = "auto"
320 function process_arguments.B(script_arguments)
321 bbox_option = remove(script_arguments, 1)
322 end
323
324 -- > Show this help message and exit
325 function process_arguments.h(script_arguments)
326 print [[
327 Usage: extractbb [-B pagebox] [-p page] [-q|-v] [-O] [-m|-x] FILE...
328 extractbb --help|--version
329 Extract bounding box from PDF, PNG, JPEG, JP2, or BMP file; default output below.
330
331 Options:
332 -B pagebox Specify a PDF pagebox for bounding box
333 pagebox=cropbox, mediabox, artbox, trimbox, bleedbox
334 -h | --help Show this help message and exit
335 --version Output version information and exit
336 -p page Specify a PDF page to extract bounding box
337 -q Be quiet
338 -v Be verbose
339 -O Write output to stdout
340 -m Output .bb file used in DVIPDFM (default)
341 -x Output .xbb file used in DVIPDFMx
342 ]]
343 os.exit(0)
344 end
345
346 process_arguments["-help"] = process_arguments.h
347
348 -- > Output version information and exit
349 function process_arguments.V(script_arguments)
350 print(version)
351 os.exit(0)
352 end
353
354 process_arguments["-version"] = process_arguments.V
355
356 -- > Specify a PDF page to extract bounding box
357 local page_number = 1
358 function process_arguments.p(script_arguments)
359 page_number = tonumber(remove(script_arguments, 1))
360 end
361
362 -- > Be quiet
363 function process_arguments.q(script_arguments)
364 show_errors = false
365 end
366
367 -- > Be verbose
368 function process_arguments.v(script_arguments)
369 show_errors = true
370 end
371
372 -- > Write output to stdout
373 local output_file
374 function process_arguments.O(script_arguments)
375 output_file = io.stdout
376 end
377
378 -- Output format
379 local output_format = "xbb"
380
381 if script_arguments[0]:match("ebb") then
382 output_format = "bb"
383 end
384
385 -- > Output .bb file used in DVIPDFM (default)
386 function process_arguments.m(script_arguments)
387 output_format = "bb"
388 end
389
390 -- > Output .xbb file used in DVIPDFMx
391 function process_arguments.x(script_arguments)
392 output_format = "xbb"
393 end
394
395 -- Get the input file name.
396 local input_name
397 function process_arguments.i(script_arguments)
398 input_name = remove(script_arguments, 1)
399 end
400
401 process_arguments["-input-name"] = process_arguments.i
402
403 -- Clear the interpreter and script names.
404 script_arguments[-1] = nil
405 script_arguments[0] = nil
406
407 -- Process the arguments.
408 while script_arguments[1] do
409 -- Get the next argument.
410 local arg = remove(script_arguments, 1)
411 local cmd = arg:match("^%-(.*)$")
412
413 -- Default to "--input-name" if no command is given.
414 if not cmd then
415 insert(script_arguments, 1, arg)
416 cmd = "-input-name"
417 end
418
419 -- Handle multi-character arguments.
420 if (cmd:len() >= 2) and (not cmd:match("^%-")) then
421 local i = 0
422 for char in cmd:gmatch(".") do
423 i = i + 1
424 insert(script_arguments, i, "-" .. char)
425 end
426
427 goto continue
428 end
429
430 -- Get the function to process the argument and run it.
431 local func = process_arguments[cmd]
432
433 if not func then
434 error("Invalid argument:", arg)
435 end
436
437 func(script_arguments)
438
439 ::continue::
440 end
441
442 -- Validate the arguments.
443 if not type(page_number) == "number" then
444 error("Invalid page number:", page_number)
445 end
446
447 if not input_name then
448 error("No input file specified.")
449 end
450
451 -- Validate the bounding box type. We need this rather crazy fallback scheme
452 -- to match the behaviour of "extractbb".
453 local bbox_orders = {}
454 bbox_orders.mediabox = {
455 { img = "media", pdfe = "MediaBox" },
456 }
457 bbox_orders.cropbox = {
458 { img = "crop", pdfe = "CropBox" }, unpack(bbox_orders.mediabox)
459 }
460 bbox_orders.artbox = {
461 { img = "art", pdfe = "ArtBox" }, unpack(bbox_orders.cropbox)
462 }
463 bbox_orders.trimbox = {
464 { img = "trim", pdfe = "TrimBox" }, unpack(bbox_orders.artbox)
465 }
466 bbox_orders.bleedbox = {
467 { img = "bleed", pdfe = "BleedBox" }, unpack(bbox_orders.trimbox)
468 }
469 bbox_orders.auto = {
470 bbox_orders.cropbox[1], bbox_orders.artbox[1], bbox_orders.trimbox[1],
471 bbox_orders.bleedbox[1], bbox_orders.mediabox[1],
472 }
473
474 local bbox_order = bbox_orders[bbox_option]
475
476 if not bbox_order then
477 error("Invalid PDF box type:", bbox_option)
478 end
479
480 -- Set the default pixel resolution.
481 local default_dpi
482 if output_format == "xbb" then
483 default_dpi = 72
484 elseif output_format == "bb" then
485 default_dpi = 100
486 else
487 error("Invalid output format:", output_format)
488 end
489
490 -- Open the output file.
491 if not output_file then
492 local base_name = input_name:match("(.+)%.([^.]-)$") or input_name
493 local output_name = base_name .. "." .. output_format
494 output_file = open_file(output_name, "write", "text")
495 end
496
497
498 ------------------------
499 --- Image Processing ---
500 ------------------------
501
502 local x_min, y_min, x_max, y_max
503 local num_pages, image_type
504 local pdf_major_version, pdf_minor_version
505
506 if open_image then
507 -- Check the number of pages.
508 local image = open_image(input_name)
509 num_pages = image.pages
510
511 if page_number > num_pages then
512 error("Invalid page number:", page_number)
513 end
514
515 -- Open the image to the specified page and bounding box. If the requested
516 -- bounding box is not available, LuaTeX will fall back to the crop box
517 -- or the media box.
518 image = open_image(input_name, page_number, bbox_order[1].img)
519
520 if not image then
521 error("Cannot open image:", input_name)
522 end
523
524 -- Get the image metadata.
525 image_type = image.imagetype
526 local bounding_box = image.bbox
527
528 if not bounding_box then
529 error("Cannot get bounding box:", page_number)
530 end
531
532 local x_resolution = image.xres
533 local y_resolution = image.yres
534
535 if (x_resolution or 0) == 0 then
536 x_resolution = default_dpi
537 end
538
539 if (y_resolution or 0) == 0 then
540 y_resolution = default_dpi
541 end
542
543 -- Convert the bounding box to PostScript points.
544 for i, dimen in ipairs(bounding_box) do
545 if image_type == "pdf" then
546 dimen = dimen / BP_TO_SP
547 else
548 if i % 2 == 1 then
549 dimen = dimen / x_resolution * IN_TO_BP
550 else
551 dimen = dimen / y_resolution * IN_TO_BP
552 end
553 end
554
555 bounding_box[i] = dimen
556 end
557
558 -- Save the bounding box.
559 x_min, y_min, x_max, y_max = unpack(bounding_box)
560
561 -- We can't get the PDF version with the "img" library, so we'll just
562 -- pretend that it's v1.5 (which supports most features).
563 pdf_major_version = 1
564 pdf_minor_version = 5
565 else
566 -- Fallback to PDFs only.
567 image_type = "pdf"
568 local document = pdfe.open(input_name)
569
570 if pdfe.getstatus(document) ~= 0 then
571 error("Cannot open PDF file:", input_name)
572 end
573
574 -- Check the number of pages.
575 num_pages = pdfe.getnofpages(document)
576
577 if type(num_pages) ~= "number" then
578 error("Invalid number of pages:", num_pages)
579 end
580
581 if page_number > num_pages then
582 error("Invalid page number:", page_number)
583 end
584
585 -- Get the page.
586 local page = pdfe.getpage(document, page_number)
587
588 if not page then
589 error("Cannot get page:", page_number)
590 end
591
592 -- Get the bounding box. Here, we check the boxes in the exact same order
593 -- that "extractbb" does.
594 local bounding_box
595 for _, bbox in ipairs(bbox_order) do
596 bounding_box = pdfe.getbox(page, bbox.pdfe)
597
598 if bounding_box then
599 break
600 end
601 end
602
603 if not bounding_box then
604 error("Cannot get bounding box:", page_number)
605 end
606
607 -- Save the bounding box.
608 x_min, y_min, x_max, y_max = unpack(bounding_box)
609
610 -- Get the PDF version.
611 pdf_major_version, pdf_minor_version = pdfe.getversion(document)
612 end
613
614 -- Validate the bounding box.
615 for _, dimen in ipairs { x_min, y_min, x_max, y_max } do
616 if type(dimen) ~= "number" then
617 error("Invalid bounding box:", x_min, y_min, x_max, y_max)
618 end
619 end
620
621
622 --------------
623 --- Output ---
624 --------------
625
626 -- Get the output fields and values.
627 local lines = {}
628
629 insert(lines, ("Title: %s"):format(input_name))
630 insert(lines, ("Creator: %s"):format(version))
631 insert(lines,
632 ("BoundingBox: %d %d %d %d")
633 :format(round(x_min), round(y_min), round(x_max), round(y_max)))
634
635 if output_format == "xbb" then
636 insert(lines,
637 ("HiResBoundingBox: %0.6f %0.6f %0.6f %0.6f")
638 :format(x_min, y_min, x_max, y_max))
639
640 if image_type == "pdf" then
641 insert(lines,
642 ("PDFVersion: %d.%d")
643 :format(pdf_major_version, pdf_minor_version))
644
645 insert(lines, ("Pages: %d"):format(num_pages))
646 end
647
648 end
649
650 insert(lines, ("CreationDate: %s"):format(os.date(DATE_FORMAT, SOURCE_DATE_EPOCH)))
651
652 -- Create the output text.
653 local begin_line = "%%"
654 local end_line = "\n"
655
656 local text = begin_line ..
657 table.concat(lines, end_line .. begin_line) ..
658 end_line .. end_line
659
660 -- Write the output text.
661 output_file:write(text)
662 output_file:close()
663
664 -- Everything is done, so now we can exit.
665 os.exit(0)