Skip to content

Commit

Permalink
pylint. improve typing
Browse files Browse the repository at this point in the history
  • Loading branch information
andersonhc committed Oct 24, 2024
1 parent 1911650 commit ccdb16a
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 55 deletions.
59 changes: 36 additions & 23 deletions fpdf/fpdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,15 @@
# * Maintainer: David Alexander ([email protected]) et al since 2017 est. *
# * Maintainer: Lucas Cimon et al since 2021 est. *
# ****************************************************************************
import hashlib, io, logging, math, os, re, sys, types, warnings
import hashlib
import io
import logging
import math
import os
import re
import sys
import types
import warnings
from collections import defaultdict
from contextlib import contextmanager
from datetime import datetime, timezone
Expand All @@ -17,11 +25,11 @@
from numbers import Number
from os.path import splitext
from pathlib import Path
from typing import Callable, Iterator, NamedTuple, Optional, Union
from typing import Callable, Dict, Iterator, NamedTuple, Optional, Union

try:
from endesive import signer
from cryptography.hazmat.primitives.serialization import pkcs12
from endesive import signer
except ImportError:
pkcs12, signer = None, None

Expand All @@ -39,26 +47,26 @@ class Image:

from .actions import URIAction
from .annotations import (
DEFAULT_ANNOT_FLAGS,
AnnotationDict,
PDFAnnotation,
PDFEmbeddedFile,
DEFAULT_ANNOT_FLAGS,
)
from .bidi import BidiParagraph, auto_detect_base_direction
from .deprecation import (
support_deprecated_txt_arg,
get_stack_level,
WarnOnDeprecatedModuleAttributes,
get_stack_level,
support_deprecated_txt_arg,
)
from .drawing import (
convert_to_device_color,
DeviceRGB,
DrawingContext,
GraphicsStateDictRegistry,
GraphicsStyle,
DrawingContext,
PaintedPath,
Point,
Transform,
convert_to_device_color,
)
from .encryption import StandardSecurityHandler
from .enums import (
Expand Down Expand Up @@ -101,13 +109,13 @@ class Image:
load_image,
preload_image,
)
from .linearization import LinearizedOutputProducer
from .line_break import Fragment, MultiLineBreak, TextLine
from .linearization import LinearizedOutputProducer
from .outline import OutlineSection
from .output import (
ZOOM_CONFIGS,
OutputProducer,
PDFPage,
ZOOM_CONFIGS,
PDFPageLabel,
stream_content_for_raster_image,
)
Expand Down Expand Up @@ -252,7 +260,9 @@ def __init__(
but is less compatible with the PDF spec.
"""
self.page = 0 # current page number
self.pages = {} # array of PDFPage objects starting at index 1
self.pages: Dict[int, PDFPage] = (
{}
) # array of PDFPage objects starting at index 1
self.fonts = {} # map font string keys to an instance of CoreFont or TTFFont
# map page numbers to a set of font indices:
self.fonts_used_per_page_number = defaultdict(set)
Expand Down Expand Up @@ -953,7 +963,11 @@ def add_page(
# END Page header

if label_style or label_prefix or label_start:
label_style = PageLabelStyle.coerce(label_style, case_sensitive=True)
label_style = (
PageLabelStyle.coerce(label_style, case_sensitive=True)
if label_style
else None
)
self.pages[self.page].set_page_label(
PDFPageLabel(label_style, label_prefix, label_start)
)
Expand Down Expand Up @@ -1025,22 +1039,21 @@ def get_page_label(self, default_page_no=True):
label_start = None

for i in range(len(self.pages), 0, -1):
if self.pages[i]._page_label:
pl: PDFPageLabel = self.pages[i]._page_label
if not label_style and not label_prefix:
if not label_style and pl._style:
label_style = pl._style
if not label_prefix and pl._prefix:
label_prefix = pl._prefix
if not label_start and pl.st:
label_start = pl.st + self.page - i
if self.pages[i].get_page_label():
pl = self.pages[i].get_page_label()
label_style = pl.get_style()
label_prefix = pl.get_prefix()
label_start = (
pl.get_start() + self.page - i
if pl.get_start()
else 1 + self.page - i
)
break

if not label_style and not label_prefix and not label_start:
return self.page_no() if default_page_no else ""

ret = label_prefix if label_prefix else ""
if not label_start:
label_start = 1
if label_style:
if label_style == PageLabelStyle.NUMBER:
ret += str(label_start)
Expand Down
76 changes: 46 additions & 30 deletions fpdf/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,36 +9,40 @@

# pylint: disable=protected-access
import logging
from collections import defaultdict, OrderedDict
from collections import OrderedDict, defaultdict
from contextlib import contextmanager
from io import BytesIO

from fontTools import subset as ftsubset

from .annotations import PDFAnnotation
from .enums import PageLabelStyle, SignatureFlag
from .errors import FPDFException
from .image_datastructures import RasterImageInfo
from .outline import build_outline_objs
from .sign import Signature, sign_content
from .syntax import (
build_obj_dict,
Name,
PDFArray,
PDFContentStream,
PDFDate,
PDFObject,
PDFString,
build_obj_dict,
)
from .syntax import create_dictionary_string as pdf_dict
from .syntax import create_list_string as pdf_list
from .syntax import iobj_ref as pdf_ref

from fontTools import subset as ftsubset

try:
from endesive import signer
except ImportError:
signer = None

from typing import TYPE_CHECKING

if TYPE_CHECKING:
from .fpdf import FPDF

LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -227,6 +231,37 @@ def __init__(
self.alternate = Name(alternate)


class PDFPageLabel:
__slots__ = ["_style", "_prefix", "st"]

def __init__(
self, label_style: PageLabelStyle, label_prefix: str, label_start: int
):
self._style: PageLabelStyle = label_style
self._prefix: str = label_prefix
self.st: int = label_start

@property
def s(self) -> Name:
return Name(self._style.value) if self._style else None

@property
def p(self) -> PDFString:
return PDFString(self._prefix) if self._prefix else None

def serialize(self) -> dict:
return build_obj_dict({key: getattr(self, key) for key in dir(self)})

def get_style(self) -> PageLabelStyle:
return self._style

def get_prefix(self) -> str:
return self._prefix

def get_start(self) -> int:
return self.st


class PDFPage(PDFObject):
__slots__ = ( # RAM usage optimization
"_id",
Expand Down Expand Up @@ -266,7 +301,7 @@ def __init__(
self.parent = None # must always be set before calling .serialize()
self._index = index
self._width_pt, self._height_pt = None, None
self._page_label = None
self._page_label: PDFPageLabel = None

def index(self):
return self._index
Expand All @@ -282,27 +317,8 @@ def set_dimensions(self, width_pt, height_pt):
def set_page_label(self, label):
self._page_label = label


class PDFPageLabel:
__slots__ = ["_style", "_prefix", "st"]

def __init__(
self, label_style: PageLabelStyle, label_prefix: str, label_start: int
):
self._style = label_style
self._prefix = label_prefix
self.st = label_start

@property
def s(self):
return Name(self._style.value) if self._style else None

@property
def p(self):
return PDFString(self._prefix) if self._prefix else None

def serialize(self):
return build_obj_dict({key: getattr(self, key) for key in dir(self)})
def get_page_label(self) -> PDFPageLabel:
return self._page_label


class PDFPagesRoot(PDFObject):
Expand Down Expand Up @@ -367,7 +383,7 @@ def serialize(self, _security_handler=None):
class OutputProducer:
"Generates the final bytearray representing the PDF document, based on a FPDF instance."

def __init__(self, fpdf):
def __init__(self, fpdf: "FPDF"):
self.fpdf = fpdf
self.pdf_objs = []
self.iccp_i_to_pdf_i = {}
Expand Down Expand Up @@ -1004,11 +1020,11 @@ def _finalize_catalog(
{"/EmbeddedFiles": pdf_dict({"/Names": pdf_list(file_spec_names)})}
)
page_labels = [
f"{seq} {pdf_dict(page[1]._page_label.serialize())}"
f"{seq} {pdf_dict(page[1].get_page_label().serialize())}"
for (seq, page) in enumerate(fpdf.pages.items())
if page[1]._page_label
if page[1].get_page_label()
]
if page_labels and not fpdf.pages[1]._page_label:
if page_labels and not fpdf.pages[1].get_page_label():
# If page labels are used, an entry for sequence 0 is mandatory
page_labels.insert(0, "0 <<>>")
if page_labels:
Expand Down
6 changes: 4 additions & 2 deletions fpdf/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
in non-backward-compatible ways.
"""

import gc, os, warnings
import gc
import os
import warnings
from numbers import Number
from tracemalloc import get_traced_memory, is_tracing
from typing import Iterable, Tuple, Union, NamedTuple
from typing import Iterable, NamedTuple, Tuple, Union

# default block size from src/libImaging/Storage.c:
PIL_MEM_BLOCK_SIZE_IN_MIB = 16
Expand Down

0 comments on commit ccdb16a

Please sign in to comment.