versao compilada
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-15 17:37:00 +02:00
parent 9a96ee8dfe
commit c13f250b87
935 changed files with 210656 additions and 272 deletions
@@ -0,0 +1,6 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
from pypdfium2.internal.bases import *
from pypdfium2.internal.consts import *
from pypdfium2.internal.utils import *
@@ -0,0 +1,186 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
__all__ = ("AutoCastable", "AutoCloseable", "ObjectTracker", "LIBRARY_AVAILABLE", "DEBUG_AUTOCLOSE", "_debug_close", "_warn_close")
import os
import sys
import enum
import uuid
import weakref
import logging
from collections import defaultdict
import pypdfium2_cfg
from pypdfium2_cfg import DEBUG_AUTOCLOSE # bw compat
from pypdfium2_cfg.stl import cached_property
logger = logging.getLogger(__name__)
LIBRARY_AVAILABLE = pypdfium2_cfg._Mutable(False) # set to true on library init
ObjectTracker = defaultdict(set)
def _debug_close(msg, prio=logging.DEBUG): # pragma: no cover
# try to use os.write() rather than print() or logger.whatever() to avoid "reentrant call" or "I/O operation on closed file" exceptions on shutdown (see https://stackoverflow.com/q/75367828/15547292)
if prio < DEBUG_AUTOCLOSE.value:
return
try:
os.write(sys.stderr.fileno(), (msg+"\n").encode())
except Exception: # e.g. io.UnsupportedOperation
print(msg, file=sys.stderr)
def _warn_close(msg):
_debug_close(msg, logging.WARNING)
class _STATE (enum.Enum):
INVALID = -1
AUTO = 0
EXPLICIT = 1
BYPARENT = 2
# class _Dataclass:
#
# def _iter_fields(self):
# for slot in self.__slots__:
# yield getattr(self, slot)
#
# def __repr__(self):
# return f"{type(self).__name__}{tuple(self._iter_fields())}"
class _FinalizerInfo: # (_Dataclass)
__slots__ = ("close_func", "args", "kwargs", "tracked", "state")
def __init__(self, close_func, args, kwargs, tracked):
self.close_func = close_func
self.args, self.kwargs = args, kwargs
self.tracked = tracked
self.state = _STATE.AUTO
class _FinalizerOwner: # (_Dataclass)
__slots__ = ("raw", "parent", "wref", "type", "repr")
def __init__(self, raw, parent, wref, type, repr):
self.raw, self.parent = raw, parent
self.wref, self.type, self.repr = wref, type, repr
def _close_template(info, owner):
# This function must not pull in a reference to the object being finalized!
# https://docs.python.org/3/library/weakref.html#weakref.finalize
# > It is important to ensure that func, args and kwargs do not own any references to obj, either directly or indirectly, since otherwise obj will never be garbage collected. In particular, func should not be a bound method of obj.
_debug_close(f"Close ({info.state.name.lower()}) {owner.repr}")
if not LIBRARY_AVAILABLE: # pragma: no cover
_warn_close(f"-> Cannot close {owner.repr}; pdfium library is destroyed. This may cause a memory leak.")
return
assert info.state != _STATE.INVALID
parent = owner.parent
if parent is not None:
assert not parent._tree_closed()
if info.tracked:
assert owner.wref in parent._kids, f"{owner.repr} {owner.wref}, {parent} {parent._kids}"
parent._kids.remove(owner.wref)
info.close_func(owner.raw, *info.args, **info.kwargs)
ObjectTracker[owner.type].remove(owner.wref)
class AutoCastable:
@property
def _as_parameter_(self):
# trust in the caller not to invoke APIs on an object after .close()
# if not self.raw:
# raise RuntimeError("bool(obj.raw) must evaluate to True for use as C function parameter")
return self.raw
@cached_property
def _wref_to_self(self):
return weakref.ref(self)
class AutoCloseable (AutoCastable):
def __init__(self, close_func, *args, obj=None, needs_free=True, tracked=True, **kwargs):
# proactively prevent accidental double initialization
assert not hasattr(self, "_finalizer")
self._fin_info = _FinalizerInfo(close_func, args, kwargs, tracked)
self._fin_obj = obj
self._finalizer = None
if needs_free:
self._attach_finalizer()
@cached_property
def _kids(self):
return set()
@cached_property
def _uuid(self):
return uuid.uuid4() if DEBUG_AUTOCLOSE.value < logging.WARNING else None
def __repr__(self):
identifier = hex(id(self)) if self._uuid is None else self._uuid.hex[:14]
return f"<{type(self).__name__} {identifier}>"
def _attach_finalizer(self):
assert self._finalizer is None
# note, this captures the object's parent, repr and so on at finalizer installation time
# in case they ever change, we'd have to store the owner in an attribute and update it
owner = _FinalizerOwner(self.raw, self.parent, self._wref_to_self, type(self), repr(self))
obj = self if self._fin_obj is None else self._fin_obj
self._finalizer = weakref.finalize(obj, _close_template, self._fin_info, owner)
ObjectTracker[type(self)].add(self._wref_to_self)
def _detach_finalizer(self):
self._finalizer.detach()
self._finalizer = None
ObjectTracker[type(self)].remove(self._wref_to_self)
def _tree_closed(self):
if self.raw is None:
return True
if self.parent is not None:
return self.parent._tree_closed()
return False
def _add_kid(self, kid):
# assuming kid is also AutoCloseable
self._kids.add( kid._wref_to_self )
def close(self, _by_parent=False):
if not self.raw:
return False
# a finalizer's __bool__ still evaluates to true when .alive is False
if not self._finalizer or not self._finalizer.alive:
self.raw = None
return False
# only need to check this in manual closing, with finalizers the API contract promises the order of invocation
need_close = []
for k_wref in self._kids:
k = k_wref()
if k and k.raw:
# closing a child will remove it from the parent's kids set, so again outsource the actual closing to avoid "RuntimeError: Set changed size during iteration"
need_close.append(k)
for k in need_close:
k.close(_by_parent=True)
if self._kids:
logger.warning(f"Some kids weakrefs have not been cleaned up: {self._kids}")
self._kids.clear()
self._fin_info.state = _STATE.BYPARENT if _by_parent else _STATE.EXPLICIT
self._finalizer()
self._fin_info.state = _STATE.INVALID
self.raw = None
self._finalizer = None
return True
@@ -0,0 +1,186 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
import pypdfium2.raw as pdfium_c
from pypdfium2.version import PDFIUM_INFO
class _fallback_dict (dict):
def get(self, key, default_prefix="Unhandled constant"):
return dict.get(self, key, f"{default_prefix} {key}")
def copy(self):
return _fallback_dict(self) # dict constructor copies
#: Convert a rotation value in degrees to a PDFium constant.
RotationToConst = {
0: 0,
90: 1,
180: 2,
270: 3,
}
#: Convert a PDFium rotation constant to a value in degrees. Inversion of :data:`.RotationToConst`.
RotationToDegrees = {v: k for k, v in RotationToConst.items()}
#: Get the number of channels for a PDFium bitmap format. (:attr:`FPDFBitmap_Unknown` is deliberately not handled.)
BitmapTypeToNChannels = {
pdfium_c.FPDFBitmap_Gray: 1,
pdfium_c.FPDFBitmap_BGR: 3,
pdfium_c.FPDFBitmap_BGRx: 4,
pdfium_c.FPDFBitmap_BGRA: 4,
pdfium_c.FPDFBitmap_BGRA_Premul: 4,
}
#: Convert a PDFium bitmap format to string, assuming BGR byte order. (:attr:`FPDFBitmap_Unknown` is deliberately not handled.)
BitmapTypeToStr = {
pdfium_c.FPDFBitmap_Gray: "L",
pdfium_c.FPDFBitmap_BGR: "BGR",
pdfium_c.FPDFBitmap_BGRx: "BGRX",
pdfium_c.FPDFBitmap_BGRA: "BGRA",
pdfium_c.FPDFBitmap_BGRA_Premul: "BGRa"
}
#: Convert a PDFium bitmap format to string, assuming RGB byte order. (:attr:`FPDFBitmap_Unknown` is deliberately not handled.)
BitmapTypeToStrReverse = {
pdfium_c.FPDFBitmap_Gray: "L",
pdfium_c.FPDFBitmap_BGR: "RGB",
pdfium_c.FPDFBitmap_BGRx: "RGBX",
pdfium_c.FPDFBitmap_BGRA: "RGBA",
pdfium_c.FPDFBitmap_BGRA_Premul: "RGBa"
}
# TODO consider a bi-directional dict in the future?
#: Convert a string to PDFium bitmap format, assuming BGR byte order. Inversion of :data:`BitmapTypeToStr`.
BitmapStrToConst = {v: k for k, v in BitmapTypeToStr.items()}
#: Convert a string to PDFium bitmap format, assuming RGB byte order. Inversion of :data:`BitmapTypeToStrReverse`.
BitmapStrReverseToConst = {v: k for k, v in BitmapTypeToStrReverse.items()}
#: Convert a PDFium form type (:attr:`FORMTYPE_*`) to string.
FormTypeToStr = _fallback_dict({
pdfium_c.FORMTYPE_NONE: "None",
pdfium_c.FORMTYPE_ACRO_FORM: "AcroForm",
pdfium_c.FORMTYPE_XFA_FULL: "XFA",
pdfium_c.FORMTYPE_XFA_FOREGROUND: "XFAF",
})
#: Convert a PDFium color space constant (:attr:`FPDF_COLORSPACE_*`) to string.
ColorspaceToStr = _fallback_dict({
pdfium_c.FPDF_COLORSPACE_UNKNOWN: "?",
pdfium_c.FPDF_COLORSPACE_DEVICEGRAY: "DeviceGray",
pdfium_c.FPDF_COLORSPACE_DEVICERGB: "DeviceRGB",
pdfium_c.FPDF_COLORSPACE_DEVICECMYK: "DeviceCMYK",
pdfium_c.FPDF_COLORSPACE_CALGRAY: "CalGray",
pdfium_c.FPDF_COLORSPACE_CALRGB: "CalRGB",
pdfium_c.FPDF_COLORSPACE_LAB: "Lab",
pdfium_c.FPDF_COLORSPACE_ICCBASED: "ICCBased",
pdfium_c.FPDF_COLORSPACE_SEPARATION: "Separation",
pdfium_c.FPDF_COLORSPACE_DEVICEN: "DeviceN",
pdfium_c.FPDF_COLORSPACE_INDEXED: "Indexed", # i.e. palettized
pdfium_c.FPDF_COLORSPACE_PATTERN: "Pattern",
})
#: Convert a PDFium view mode constant (:attr:`PDFDEST_VIEW_*`) to string.
ViewmodeToStr = _fallback_dict({
pdfium_c.PDFDEST_VIEW_UNKNOWN_MODE: "?",
pdfium_c.PDFDEST_VIEW_XYZ: "XYZ",
pdfium_c.PDFDEST_VIEW_FIT: "Fit",
pdfium_c.PDFDEST_VIEW_FITH: "FitH",
pdfium_c.PDFDEST_VIEW_FITV: "FitV",
pdfium_c.PDFDEST_VIEW_FITR: "FitR",
pdfium_c.PDFDEST_VIEW_FITB: "FitB",
pdfium_c.PDFDEST_VIEW_FITBH: "FitBH",
pdfium_c.PDFDEST_VIEW_FITBV: "FitBV",
})
#: Convert a PDFium object type constant (:attr:`FPDF_PAGEOBJ_*`) to string.
ObjectTypeToStr = _fallback_dict({
pdfium_c.FPDF_PAGEOBJ_UNKNOWN: "?",
pdfium_c.FPDF_PAGEOBJ_TEXT: "text",
pdfium_c.FPDF_PAGEOBJ_PATH: "path",
pdfium_c.FPDF_PAGEOBJ_IMAGE: "image",
pdfium_c.FPDF_PAGEOBJ_SHADING: "shading",
pdfium_c.FPDF_PAGEOBJ_FORM: "form",
})
#: Convert an object type string to a PDFium constant. Inversion of :data:`.ObjectTypeToStr`.
ObjectTypeToConst = {v: k for k, v in ObjectTypeToStr.items()}
#: Convert a PDFium page mode constant (:attr:`PAGEMODE_*`) to string.
PageModeToStr = _fallback_dict({
pdfium_c.PAGEMODE_UNKNOWN: "?",
pdfium_c.PAGEMODE_USENONE: "None",
pdfium_c.PAGEMODE_USEOUTLINES: "Outline",
pdfium_c.PAGEMODE_USETHUMBS: "Thumbnails",
pdfium_c.PAGEMODE_FULLSCREEN: "Full-screen",
pdfium_c.PAGEMODE_USEOC: "Layers",
pdfium_c.PAGEMODE_USEATTACHMENTS: "Attachments",
})
#: Convert a PDFium error constant (:attr:`FPDF_ERR_*`) to string.
ErrorToStr = _fallback_dict({
pdfium_c.FPDF_ERR_SUCCESS: "Success",
pdfium_c.FPDF_ERR_UNKNOWN: "Unknown error",
pdfium_c.FPDF_ERR_FILE: "File access error",
pdfium_c.FPDF_ERR_FORMAT: "Data format error",
pdfium_c.FPDF_ERR_PASSWORD: "Incorrect password error",
pdfium_c.FPDF_ERR_SECURITY: "Unsupported security scheme error",
pdfium_c.FPDF_ERR_PAGE: "Page not found or content error",
})
if "XFA" in PDFIUM_INFO.flags: # pragma: no cover
#: [XFA builds only] Convert a PDFium XFA error constant (:attr:`FPDF_ERR_XFA*`) to string.
XFAErrorToStr = _fallback_dict({
pdfium_c.FPDF_ERR_XFALOAD: "Load error",
pdfium_c.FPDF_ERR_XFALAYOUT: "Layout error",
})
#: Convert a PDFium unsupported constant (:attr:`FPDF_UNSP_*`) to string.
UnsupportedInfoToStr = _fallback_dict({
pdfium_c.FPDF_UNSP_DOC_XFAFORM: "XFA form",
pdfium_c.FPDF_UNSP_DOC_PORTABLECOLLECTION: "Portable collection",
# https://crbug.com/pdfium/1945
pdfium_c.FPDF_UNSP_DOC_ATTACHMENT: "Attachment (incomplete support)",
pdfium_c.FPDF_UNSP_DOC_SECURITY: "Security",
pdfium_c.FPDF_UNSP_DOC_SHAREDREVIEW: "Shared review",
pdfium_c.FPDF_UNSP_DOC_SHAREDFORM_ACROBAT: "Shared form (acrobat)",
pdfium_c.FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM: "Shared form (filesystem)",
pdfium_c.FPDF_UNSP_DOC_SHAREDFORM_EMAIL: "Shared form (email)",
pdfium_c.FPDF_UNSP_ANNOT_3DANNOT: "3D annotation",
pdfium_c.FPDF_UNSP_ANNOT_MOVIE: "Movie annotation",
pdfium_c.FPDF_UNSP_ANNOT_SOUND: "Sound annotation",
pdfium_c.FPDF_UNSP_ANNOT_SCREEN_MEDIA: "Screen media annotation",
pdfium_c.FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA: "Screen rich media annotation",
pdfium_c.FPDF_UNSP_ANNOT_ATTACHMENT: "Attachment annotation",
pdfium_c.FPDF_UNSP_ANNOT_SIG: "Signature annotation",
})
#: Convert a PDFium charset type constant (:attr:`FXFONT_*_CHARSET`) to string.
CharsetToStr = _fallback_dict({
pdfium_c.FXFONT_ANSI_CHARSET: "ANSI",
pdfium_c.FXFONT_DEFAULT_CHARSET: "Default",
pdfium_c.FXFONT_SYMBOL_CHARSET: "Symbol",
pdfium_c.FXFONT_SHIFTJIS_CHARSET: "ShiftJIS",
pdfium_c.FXFONT_HANGEUL_CHARSET: "Hangeul",
pdfium_c.FXFONT_GB2312_CHARSET: "GB2312",
pdfium_c.FXFONT_CHINESEBIG5_CHARSET: "ChineseBig5",
pdfium_c.FXFONT_GREEK_CHARSET: "Greek",
pdfium_c.FXFONT_VIETNAMESE_CHARSET: "Vietnamese",
pdfium_c.FXFONT_HEBREW_CHARSET: "Hebrew",
pdfium_c.FXFONT_ARABIC_CHARSET: "Arabic",
pdfium_c.FXFONT_CYRILLIC_CHARSET: "Cyrillic",
pdfium_c.FXFONT_THAI_CHARSET: "Thai",
pdfium_c.FXFONT_EASTERNEUROPEAN_CHARSET: "EasternEuropean",
})
RenderStatusToStr = _fallback_dict({
pdfium_c.FPDF_RENDER_READY: "ready",
pdfium_c.FPDF_RENDER_TOBECONTINUED: "to be continued",
pdfium_c.FPDF_RENDER_DONE: "done",
pdfium_c.FPDF_RENDER_FAILED: "failed",
})
@@ -0,0 +1,105 @@
# SPDX-FileCopyrightText: 2026 geisserml <geisserml@gmail.com>
# SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause
import os
import ctypes
import pypdfium2.raw as pdfium_c
def color_tohex(color, rev_byteorder):
if not all(0 <= c <= 255 for c in color):
raise ValueError("Color value exceeds boundaries.")
# different color interpretation with FPDF_REVERSE_BYTE_ORDER might be a bug? at least it's not documented.
r, g, b, a = color
channels = (a, b, g, r) if rev_byteorder else (a, r, g, b)
c_color = 0
shift = 24
for c in channels:
c_color |= c << shift
shift -= 8
return c_color
def set_callback(struct, fname, callback):
setattr(struct, fname, type(getattr(struct, fname))(callback))
def set_callbacks(struct, **kwargs):
for fname, callback in kwargs.items():
setattr(struct, fname, type(getattr(struct, fname))(callback))
def is_stream(buf, spec="r"):
methods = []
assert set(spec).issubset( set("rw") )
if "r" in spec:
methods += ("seek", "tell", "read", "readinto")
if "w" in spec:
methods.append("write")
return all(callable(getattr(buf, a, None)) for a in methods)
def get_buffer(ptr, size):
obj = ptr.contents
return (type(obj) * size).from_address( ctypes.addressof(obj) )
class _buffer_reader:
def __init__(self, py_buffer):
self.py_buffer = py_buffer
def __call__(self, _, position, p_buf_first, size):
c_buffer = get_buffer(p_buf_first, size)
self.py_buffer.seek(position)
# compare requested and read size to ensure we never pass on uninitialized memory without reporting error, in case readinto() might have failed to consume enough input
read_size = self.py_buffer.readinto(c_buffer)
return int(read_size == size)
class _buffer_writer:
def __init__(self, py_buffer):
self.py_buffer = py_buffer
def __call__(self, _, p_data_first, size):
# c_void_p has no .contents, need to cast
p_data_first = ctypes.cast(p_data_first, ctypes.POINTER(ctypes.c_ubyte))
c_buffer = get_buffer(p_data_first, size)
self.py_buffer.write(c_buffer)
return 1
def get_bufreader(buffer):
file_len = buffer.seek(0, os.SEEK_END)
buffer.seek(0)
reader = pdfium_c.FPDF_FILEACCESS()
reader.m_FileLen = file_len
set_callback(reader, "m_GetBlock", _buffer_reader(buffer))
reader.m_Param = None
to_hold = (reader.m_GetBlock, )
return reader, to_hold
def get_bufwriter(buffer):
writer = pdfium_c.FPDF_FILEWRITE(version=1)
set_callback(writer, "WriteBlock", _buffer_writer(buffer))
return writer
def pages_c_array(pages):
if not pages:
return None, 0
count = len(pages)
c_array = (pdfium_c.FPDF_PAGE * count)(*(p.raw for p in pages))
return c_array, count
FPDF_WCHAR_size = ctypes.sizeof(pdfium_c.FPDF_WCHAR)