Repository navigation
PI: Index named destinations when appending a document #4360
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kholdrex
wants to merge
7
commits into
py-pdf:main
Choose a base branch
from
kholdrex:named-destinations-index
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+183
−8
Open
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
8178a59
PI: Index named destinations when appending a document
kholdrex 24cef9e
Merge remote-tracking branch 'origin/main' into named-destinations-index
kholdrex 176fb34
Merge branch 'main' into named-destinations-index
kholdrex d6e82cb
Merge branch 'main' into named-destinations-index
kholdrex 0a28d5e
Address review comments
kholdrex 1c8aab7
Merge remote-tracking branch 'fork/named-destinations-index' into nam…
kholdrex 654f603
Merge branch 'main' into named-destinations-index
kholdrex File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -35,7 +35,7 @@ | |
| import sys | ||
| from collections.abc import Callable, Iterable, Mapping, Sequence | ||
| from io import BytesIO, FileIO, IOBase | ||
| from itertools import compress | ||
| from itertools import compress, pairwise | ||
| from pathlib import Path | ||
| from re import Pattern | ||
| from types import TracebackType | ||
|
|
@@ -137,6 +137,84 @@ class ObjectDeletionFlag(enum.IntFlag): | |
| IMAGES = XOBJECT_IMAGES | INLINE_IMAGES | DRAWING_IMAGES | ||
|
|
||
|
|
||
| # Building the index reads the whole /Names array, which costs more than it saves | ||
| # when a document adds only a few named destinations. | ||
| _NAMED_DESTINATION_INDEX_MINIMUM = 32 | ||
|
|
||
|
|
||
| class _NamedDestinationIndex: | ||
| """ | ||
| Look up and insert named destinations in a ``/Names`` array without scanning it. | ||
|
|
||
| ``PdfWriter.merge`` adds the named destinations of a document one by one, and both | ||
| looking each one up in the growing array and inserting it there take quadratic time. | ||
| The string entries are kept in a set instead, as only strings compare equal to a title. | ||
| If the keys are sorted strings, the new destinations are collected and sorted into the | ||
| array once by ``flush``: inserting each one before the first greater key gives the same | ||
| order as this stable sort. Other arrays are scanned as before. | ||
| """ | ||
|
|
||
| def __init__(self, *, is_enabled: bool) -> None: | ||
| self._is_enabled = is_enabled | ||
| self._array: list[Any] | None = None | ||
| self._length = 0 | ||
| self._strings: set[str] = set() | ||
| self._is_sorted = False | ||
| self._pending: list[tuple[str, Any]] = [] | ||
|
|
||
| def _update(self, array: list[Any]) -> None: | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Are we able to avoid the name
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Renamed it to |
||
| if array is self._array and len(array) == self._length: | ||
| return | ||
| self.flush() | ||
| self._array = array | ||
| self._length = len(array) | ||
| self._strings = {entry for entry in array if isinstance(entry, str)} | ||
| keys = array[::2] | ||
| self._is_sorted = ( | ||
| self._length % 2 == 0 | ||
| and all(isinstance(key, str) for key in keys) | ||
| and all(previous <= key for previous, key in pairwise(keys)) | ||
| ) | ||
|
|
||
| def contains(self, container: Any, title: Any) -> bool: | ||
| if isinstance(container, IndirectObject): | ||
| container = container.get_object() | ||
| if not self._is_enabled or not isinstance(container, list) or not isinstance(title, str): | ||
| return title in container | ||
| self._update(container) | ||
| return title in self._strings | ||
|
|
||
| def insert(self, array: list[Any], title: Any, destination: Any) -> bool: | ||
| """Insert like ``PdfWriter.add_named_destination_array``; return False if the array has to be scanned.""" | ||
| if not self._is_enabled: | ||
| return False | ||
| self._update(array) | ||
| if not self._is_sorted or not isinstance(title, str): | ||
| self.flush() | ||
| return False | ||
| self._pending.append((title, destination)) | ||
| self._strings.add(title) | ||
| return True | ||
|
|
||
| def record_insertion(self, array: list[Any], title: Any) -> None: | ||
| """Update the index after ``add_named_destination_array`` inserted ``title`` into ``array``.""" | ||
| if array is self._array and isinstance(title, str): | ||
| self._strings.add(title) | ||
| self._length = len(array) | ||
|
|
||
| def flush(self) -> None: | ||
| if not self._pending: | ||
| return | ||
| array = self._array | ||
| assert array is not None, "mypy" | ||
| pairs = [(array[i], array[i + 1]) for i in range(0, len(array), 2)] | ||
| pairs += [(TextStringObject(title), destination) for title, destination in self._pending] | ||
| pairs.sort(key=lambda pair: pair[0]) | ||
| array[:] = [entry for pair in pairs for entry in pair] | ||
| self._pending = [] | ||
| self._length = len(array) | ||
|
|
||
|
|
||
| class PdfWriter(PdfDocCommon): | ||
| """ | ||
| Write a PDF file out, given pages produced by another class or through | ||
|
|
@@ -2830,8 +2908,17 @@ def merge( | |
|
|
||
| arr: Any | ||
|
|
||
| for dest in reader._named_destinations.values(): | ||
| self._merge__process_named_dests(dest=dest, reader=reader, srcpages=srcpages) | ||
| named_destinations = _NamedDestinationIndex( | ||
| is_enabled=len(reader._named_destinations) >= _NAMED_DESTINATION_INDEX_MINIMUM | ||
| ) | ||
| # Keep the destinations added before an error, as adding them one by one did. | ||
| try: | ||
| for dest in reader._named_destinations.values(): | ||
| self._merge__process_named_dests( | ||
| dest=dest, reader=reader, srcpages=srcpages, named_destinations=named_destinations | ||
| ) | ||
| finally: | ||
| named_destinations.flush() | ||
|
|
||
| outline_item_typ: TreeObject | ||
| if outline_item is not None: | ||
|
|
@@ -2912,14 +2999,20 @@ def merge( | |
| if "/B" not in excluded_fields: | ||
| self.add_filtered_articles("", srcpages, reader) | ||
|
|
||
| def _merge__process_named_dests(self, dest: Any, reader: PdfDocCommon, srcpages: dict[int, PageObject]) -> None: | ||
| def _merge__process_named_dests( | ||
| self, | ||
| dest: Any, | ||
| reader: PdfDocCommon, | ||
| srcpages: dict[int, PageObject], | ||
| named_destinations: _NamedDestinationIndex, | ||
| ) -> None: | ||
| arr: Any = dest.dest_array | ||
| if "/Names" in self._root_object and dest["/Title"] in cast( | ||
| list[Any], | ||
| if "/Names" in self._root_object and named_destinations.contains( | ||
| cast( | ||
| DictionaryObject, | ||
| cast(DictionaryObject, self._root_object["/Names"]).get("/Dests", DictionaryObject()), | ||
| ).get("/Names", DictionaryObject()), | ||
| dest["/Title"], | ||
| ): | ||
| # already exists: should not duplicate it | ||
| pass | ||
|
|
@@ -2937,14 +3030,22 @@ def _merge__process_named_dests(self, dest: Any, reader: PdfDocCommon, srcpages: | |
| arr[NumberObject(0)] = NumberObject( | ||
| srcpages[p.indirect_reference.idnum].page_number | ||
| ) | ||
| self.add_named_destination_array(dest["/Title"], arr) | ||
| self._add_named_destination_array_indexed(dest["/Title"], arr, named_destinations) | ||
| except KeyError: | ||
| pass | ||
| elif dest["/Page"].indirect_reference.idnum in srcpages: | ||
| arr[NumberObject(0)] = srcpages[ | ||
| dest["/Page"].indirect_reference.idnum | ||
| ].indirect_reference | ||
| self.add_named_destination_array(dest["/Title"], arr) | ||
| self._add_named_destination_array_indexed(dest["/Title"], arr, named_destinations) | ||
|
|
||
| def _add_named_destination_array_indexed( | ||
| self, title: Any, destination: Any, named_destinations: _NamedDestinationIndex | ||
| ) -> None: | ||
| names = self.get_named_dest_root() | ||
| if not named_destinations.insert(names, title, destination): | ||
| self.add_named_destination_array(title, destination) | ||
| named_destinations.record_insertion(names, title) | ||
|
|
||
| def _add_articles_thread( | ||
| self, | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would there be any benefits to subclass
listor similar here and re-use the common API?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't think it would help much: the index doesn't own the
/Namesarray, theArrayObjectstays in the document and the index only sits next to it during onemerge(). A list subclass would mean swapping that object in the document, whileadd_named_destination_array()andget_named_dest_root()keep working on the original. Happy to change it if you see a cleaner way.