From b1e87e7ece9f5d6055d1ecdcd94c689bf73eb8f9 Mon Sep 17 00:00:00 2001 From: Julian Smith Date: Fri, 27 Nov 2026 16:01:26 +0000 Subject: [PATCH 1/7] src/: make Annot.rect use pdf_annot_rect() instead of pdf_bound_annot(). Fixes #4755. This makes Annot.rect symmetrical with Annot.set_rect(). Added Annot.bounds, which returns what Annot.rect used to return, based on pdf_bound_annot(). Added fallback behaviour: * If pdf_annot_rect() raises an exception (typically because the underlying annotation uses quads instead of a single rectangle), default is to fall back to Annot.bounds. * This is disabled when running test, to force fixing of our code. * Controlled by _globals.annot_rect_fallback. Changed various occurrencies of Annot.rect to Annot.bounds to avoid changing behaviour. --- src/__init__.py | 42 ++++++++++++++++++++++++++++++++---------- src/extra.i | 4 ++-- 2 files changed, 34 insertions(+), 12 deletions(-) diff --git a/src/__init__.py b/src/__init__.py index f55990c1c..a8a4d9978 100644 --- a/src/__init__.py +++ b/src/__init__.py @@ -334,6 +334,13 @@ def __init__(self): self.small_glyph_heights = 0 self.subset_fontnames = 0 self.skip_quad_corrections = 0 + + # We default to making Annot.rect fallback to Annot.bounds if + # pdf_annot_rect() raises an exception. + # + # However this is set to false when running tests, so that we don't + # rely on it in our code (see conftest.py). + self.annot_rect_fallback = True _globals = _Globals() @@ -900,6 +907,14 @@ def border(self): ao = mupdf.pdf_annot_obj(self.this) ret = JM_annot_border(ao) return ret + + @property + def bounds(self): + val = mupdf.pdf_bound_annot(self.this) + val = Rect(val) + p = self.get_parent() + val *= p.derotation_matrix + return val def clean_contents(self, sanitize=1): """Clean appearance contents stream.""" @@ -1279,11 +1294,18 @@ def popup_xref(self): @property def rect(self): """annotation rectangle""" - if g_use_extra: - val = extra.Annot_rect3( self.this) - else: - val = mupdf.pdf_bound_annot(self.this) - val = Rect(val) + try: + if g_use_extra: + val = extra.Annot_rect3( self.this) + else: + val = mupdf.pdf_annot_rect(self.this) + val = Rect(val) + except Exception as e: + if _globals.annot_rect_fallback: + warnings.warn(f'Annot.rect: using annot bounds because no rect available: {e}') + return self.bounds + else: + raise # Caching self.parent_() reduces 1000x from 0.07 to 0.04. # @@ -1816,7 +1838,7 @@ def color_string(cs, code): TOOLS._le_slash) le_funcs_range = range(1, len(le_funcs)) d = 2 * max(1, self.border["width"]) - rect = self.rect + (-d, -d, d, d) + rect = self.bounds + (-d, -d, d, d) ap_updated = True points = self.vertices if line_end_le in le_funcs_range: @@ -1858,18 +1880,18 @@ def color_string(cs, code): if rot == -1: # nothing to change return - M = (self.rect.tl + self.rect.br) / 2 # center of annot rect + M = (self.bounds.tl + self.bounds.br) / 2 # center of annot rect if rot == 0: # undo rotations if abs(apnmat - Matrix(1, 1)) < 1e-5: return # matrix already is a no-op - quad = self.rect.morph(M, ~apnmat) # derotate rect + quad = self.bounds.morph(M, ~apnmat) # derotate rect self.set_rect(quad.rect) self.set_apn_matrix(Matrix(1, 1)) # appearance matrix = no-op return mat = Matrix(rot) - quad = self.rect.morph(M, mat) + quad = self.bounds.morph(M, mat) self.set_rect(quad.rect) self.set_apn_matrix(apnmat * mat) @@ -12557,7 +12579,7 @@ def remove_rotation(self): state = { "annot": annot, "type": annot_type, - "rect": Rect(annot.rect), + "rect": Rect(annot.bounds), "apn_matrix": Matrix(annot.apn_matrix), } if annot_type == mupdf.PDF_ANNOT_FREE_TEXT: diff --git a/src/extra.i b/src/extra.i index 705f04efa..23058fc59 100644 --- a/src/extra.i +++ b/src/extra.i @@ -1090,13 +1090,13 @@ JM_py_from_quad(fz_quad q) //---------------------------------------------------------------- static mupdf::FzRect Annot_rect(mupdf::PdfAnnot& annot) { - mupdf::FzRect rect = mupdf::pdf_bound_annot(annot); + mupdf::FzRect rect = mupdf::pdf_annot_rect(annot); return rect; } static PyObject* Annot_rect3(mupdf::PdfAnnot& annot) { - fz_rect rect = mupdf::ll_pdf_bound_annot(annot.m_internal); + fz_rect rect = mupdf::ll_pdf_annot_rect(annot.m_internal); return JM_py_from_rect(rect); } From 575d083467c592ede7098723855dec24fd793097 Mon Sep 17 00:00:00 2001 From: Julian Smith Date: Fri, 27 Nov 2026 17:55:14 +0000 Subject: [PATCH 2/7] tests/conftest.py: run tests with pymupdf._globals.annot_rect_fallback set to false. This ensures that pymupdf's code does not rely on the fallback. --- tests/conftest.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/conftest.py b/tests/conftest.py index 20536c41f..beab7f97f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -145,7 +145,11 @@ def get_members(a): v = getattr(a, n) ret[n] = v return ret - + + # We test without Annot.rect fallback to Annot.bounds, so that we avoid + # relying on the fallback in the main code and in tests. + pymupdf._globals.annot_rect_fallback = False + # Allow post-test checking that pymupdf._globals has not changed. _globals_pre = get_members(pymupdf._globals) From c750b7ac147ba23bff25aa563c0edc2f50b322ce Mon Sep 17 00:00:00 2001 From: Julian Smith Date: Fri, 27 Nov 2026 13:36:38 +0000 Subject: [PATCH 3/7] tests/test_annots.pytest_4755(): updated to check newly fixed behaviour. Also check new annot.bounds attribute works as expected. Also check behaviour of Annot.rect falling back to Annot.bounds (by temporarily setting pymupdf._globals.annot_rect_fallback to true). --- tests/test_annots.py | 55 ++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 5 deletions(-) diff --git a/tests/test_annots.py b/tests/test_annots.py index 0785dd9fe..3892d2b6a 100644 --- a/tests/test_annots.py +++ b/tests/test_annots.py @@ -682,6 +682,8 @@ def test_4755(): path = os.path.normpath(f'{__file__}/../../tests/resources/test_4755.pdf') path_out = os.path.normpath(f'{__file__}/../../tests/test_4755_out.pdf') + errors = list() + bounds = list() with pymupdf.open(path) as document: for page_i, page in enumerate(document): print(f'{page_i=}') @@ -694,9 +696,30 @@ def test_4755(): ] for annot_i, annot in enumerate(page.annots()): print(f'{annot_i=}') - #if annot_i != 2: - # continue - before_rect = copy.deepcopy(annot.rect) + bounds.append(annot.bounds) + e = None + + try: + before_rect = copy.deepcopy(annot.rect) + except Exception as ee: + e = ee + print(f'{annot_i=} {e=}') + if annot_i == 0: + assert e and 'StrikeOut annotations have no Rect property' in str(e), ( + f'Did not receive expected exception with {annot_i=}.' + ) + + # Check that setting pymupdf._globals.annot_rect_fallback to true allows + # annot.rect to succeed. + # + assert not pymupdf._globals.annot_rect_fallback + pymupdf._globals.annot_rect_fallback = True + before_rect = copy.deepcopy(annot.rect) + pymupdf._globals.annot_rect_fallback = False + + continue + else: + assert not e, f'Received unexpected exception with {annot_i=}: {e}' def draw_rectangle(rect, c, w): drect = page.add_freetext_annot(rect, str(annot_i), text_color=c) @@ -707,17 +730,39 @@ def draw_rectangle(rect, c, w): print(f'{colour=}') draw_rectangle(annot.rect, colour, .3) - print(f'before: {annot.rect}=') + print(f'before: {annot.rect=}') annot.set_rect(annot.rect) - print(f' after: {annot.rect}=') + print(f' after: {annot.rect=}') print(f'difference: {annot.rect-before_rect=}') + errors.append(annot.rect != before_rect) draw_rectangle(annot.rect, (0, 1, 0), .3) print() document.save(path_out) print(f' {path=}.') print(f'{path_out=}.') + + print(f'Bounds:') + for i, r in enumerate(bounds): + print(f' {i}: {r}') + + bounds_expected = [ + pymupdf.Rect(177.4219970703125, 119.0980224609375, 187.93299865722656, 127.93499755859375), + pymupdf.Rect(185.28199768066406, 123.5159912109375, 190.58399963378906, 132.35302734375), + pymupdf.Rect(49.0, 50.5, 69.0, 64.5), + ] + print(f'Bounds rms:') + assert len(bounds) == len(bounds_expected) + for i, (bounds_rect_expected, bounds_rect) in enumerate(zip(bounds_expected, bounds, strict=True)): + rms = gentle_compare.rms(bounds_rect_expected, bounds_rect) + print(f' {i}: {rms=}') + assert rms < 0.1 + assert bounds == bounds_expected + + print(f'{errors=}') + # Expect the current broken behaviour. + assert errors == [False, False] def test_4944(): From 8589e932a08c861b4b222602f791a30f98939461 Mon Sep 17 00:00:00 2001 From: Julian Smith Date: Fri, 27 Nov 2026 16:07:41 +0000 Subject: [PATCH 4/7] tests/test_remove-rotation.py: test_5059(): also save before/after pixmaps, and pixmap diff. --- tests/test_remove-rotation.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/tests/test_remove-rotation.py b/tests/test_remove-rotation.py index 9ed5e2160..6ea527601 100644 --- a/tests/test_remove-rotation.py +++ b/tests/test_remove-rotation.py @@ -6,7 +6,7 @@ import pymupdf -from gentle_compare import gentle_compare, rms +import gentle_compare scriptdir = os.path.dirname(__file__) @@ -35,7 +35,7 @@ def test_remove_rotation(): words1 = doc[i].get_text("words") words1.sort(key=lambda w: w[4]) # sort by word strings assert pix1.digest == pix0.digest, f"{pix1.digest}/{pix0.digest}" - assert gentle_compare(words0, words1) + assert gentle_compare.gentle_compare(words0, words1) def test_5077(): @@ -151,7 +151,14 @@ def test_5059(): pix_orig = page.get_pixmap(colorspace=pymupdf.csGRAY) page.remove_rotation() pix_rot0 = page.get_pixmap(colorspace=pymupdf.csGRAY) - rms_val = rms(pix_orig.samples, pix_rot0.samples, verbose=False) + + path = os.path.relpath(os.path.normpath(f'{__file__}/../../tests/test_5059')) + pix_orig.save(f'{path}_orig.png') + pix_rot0.save(f'{path}_rot0.png') + pix_diff = gentle_compare.pixmaps_diff(pix_orig, pix_rot0) + pix_diff.save(f'{path}_diff.png') + + rms_val = gentle_compare.rms(pix_orig.samples, pix_rot0.samples, verbose=False) assert rms_val < 0.05, f"RMS diff for rotation {rot}: {rms_val}" From 0d712d4be3dca992cc728a19511951016b6fc159 Mon Sep 17 00:00:00 2001 From: Julian Smith Date: Fri, 27 Nov 2026 16:13:14 +0000 Subject: [PATCH 5/7] docs/annot.rst: updated docs for Annot.rect and Annot.bounds to match latest code. --- docs/annot.rst | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/annot.rst b/docs/annot.rst index 0af3a398a..158349520 100644 --- a/docs/annot.rst +++ b/docs/annot.rst @@ -41,6 +41,7 @@ There is a parent-child relationship between an annotation and its page. If the :meth:`Annot.update` apply accumulated annot changes :attr:`Annot.blendmode` annotation BlendMode :attr:`Annot.border` border details +:attr:`Annot.bounds` the boundary rect. :attr:`Annot.colors` border / background and fill colors :attr:`Annot.file_info` get attached file information :attr:`Annot.flags` annotation flags @@ -460,6 +461,18 @@ There is a parent-child relationship between an annotation and its page. If the The rectangle containing the annotation. :rtype: :ref:`Rect` + + * Changed in version 2.3: + + * The returned rect is now consistent with the rect set by `set_rect()`. + * It may differ slightly from earlier versions: + + * Internally we now use ``pdf_annot_rect()`` instead of ``pdf_bound_annot()``. + * This applies the same (usually small) ``pdf_annot_rect_diff()`` correction as `set_rect()`. + * Some attributes are defined by quads so do not have a rect attribute (e.g. StrikeOut). + In this case we return the bounds rect. + + * Also see the (new in 2.3) `bound` attribute. .. attribute:: next @@ -579,6 +592,11 @@ There is a parent-child relationship between an annotation and its page. If the :rtype: dict + .. attribute:: bounds + + The attribute's boundary rect. + + :rtype: :ref:`Rect` .. _mupdficons: From 264433ac617401b35c2d78b285774740fafe1a79 Mon Sep 17 00:00:00 2001 From: Julian Smith Date: Fri, 27 Nov 2026 17:07:48 +0000 Subject: [PATCH 6/7] docs/samples/new-annots.py: updated to work with new Annot.rect behaviour. We now use Annot.bounds instead of Annot.rect. --- docs/samples/new-annots.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/samples/new-annots.py b/docs/samples/new-annots.py index bb661e3c7..8650d13cc 100644 --- a/docs/samples/new-annots.py +++ b/docs/samples/new-annots.py @@ -45,7 +45,7 @@ def print_descr(annot): """Print a short description to the right of each annot rect.""" annot.parent.insert_text( - annot.rect.br + (10, -5), f"{annot.type[1]} annotation", color=red) + annot.bounds.br + (10, -5), f"{annot.type[1]} annotation", color=red) doc = pymupdf.open() @@ -70,13 +70,13 @@ def print_descr(annot): annot.update(text_color=blue, fill_color=gold) print_descr(annot) -r = annot.rect + displ +r = annot.bounds + displ annot = page.add_text_annot(r.tl, t1) print_descr(annot) # Adding text marker annotations: # first insert a unique text, then search for it, then mark it -pos = annot.rect.tl + displ.tl +pos = annot.bounds.tl + displ.tl page.insert_text( pos, # insertion point highlight, # inserted text @@ -86,25 +86,25 @@ def print_descr(annot): annot = page.add_highlight_annot(rl[0]) print_descr(annot) -pos = annot.rect.bl # next insertion point +pos = annot.bounds.bl # next insertion point page.insert_text(pos, underline, morph=(pos, pymupdf.Matrix(-10))) rl = page.search_for(underline, quads=True) annot = page.add_underline_annot(rl[0]) print_descr(annot) -pos = annot.rect.bl +pos = annot.bounds.bl page.insert_text(pos, strikeout, morph=(pos, pymupdf.Matrix(-15))) rl = page.search_for(strikeout, quads=True) annot = page.add_strikeout_annot(rl[0]) print_descr(annot) -pos = annot.rect.bl +pos = annot.bounds.bl page.insert_text(pos, squiggled, morph=(pos, pymupdf.Matrix(-20))) rl = page.search_for(squiggled, quads=True) annot = page.add_squiggly_annot(rl[0]) print_descr(annot) -pos = annot.rect.bl +pos = annot.bounds.bl r = pymupdf.Rect(pos, pos.x + 75, pos.y + 35) + (0, 20, 0, 20) annot = page.add_polyline_annot([r.bl, r.tr, r.br, r.tl]) # 'Polyline' annot.set_border(width=0.3, dashes=[2]) @@ -147,7 +147,7 @@ def print_descr(annot): annot = page.add_file_annot( r.tl, b"just anything for testing", "testdata.txt" # 'FileAttachment' ) -print_descr(annot) # annot.rect +print_descr(annot) # annot.bounds r += displ annot = page.add_stamp_annot(r, stamp=10) # 'Stamp' From 4746398ba7c93cbfa08f0132286cd1e9dc47ad60 Mon Sep 17 00:00:00 2001 From: Julian Smith Date: Fri, 27 Nov 2026 16:15:14 +0000 Subject: [PATCH 7/7] changes.txt: updated with changes to Annot.rect and Annot.bounds. --- changes.txt | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/changes.txt b/changes.txt index 92e136fdb..137e1d24e 100644 --- a/changes.txt +++ b/changes.txt @@ -1,6 +1,19 @@ Change Log ========== + +**Changes in next version** + +Fixed issues: + +* **Fixed** `4755 `_: Unexpected behavior of annot.set_rect() with carets and strikeouts + +Other: + +* Modified return value from `Annot.rect` attribute. +* Added `Annot.bounds` attribute. + + **Changes in version 2.2** (2026-11-26) New features: