comparison tests/test_balance_count.py @ 3:2c135c81b16c

MERGE: upstream PyMuPDF 1.26.4 with MuPDF 1.26.7
author Franz Glasner <fzglas.hg@dom66.de>
date Mon, 15 Sep 2025 11:44:09 +0200
parents 1d09e1dec1d9
children
comparison
equal deleted inserted replaced
0:6015a75abc2d 3:2c135c81b16c
1 import pymupdf
2
3
4 def test_q_count():
5 """Testing graphics state balances and wrap_contents().
6
7 Take page's contents and generate various imbalanced graphics state
8 situations. Each time compare q-count with expected results.
9 Finally confirm we are out of balance using "is_wrapped", wrap the
10 contents object(s) via "wrap_contents()" and confirm success.
11 PDF commands "q" / "Q" stand for "push", respectively "pop".
12 """
13 doc = pymupdf.open()
14 page = doc.new_page()
15 # the page has no /Contents objects at all yet. Create one causing
16 # an initial imbalance (so prepended "q" is needed)
17 pymupdf.TOOLS._insert_contents(page, b"Q", True) # append
18 assert page._count_q_balance() == (1, 0)
19 assert page.is_wrapped is False
20
21 # Prepend more data that yield a different type of imbalanced contents:
22 # Although counts of q and Q are equal now, the unshielded 'cm' before
23 # the first 'q' makes the contents unusable for insertions.
24 pymupdf.TOOLS._insert_contents(page, b"1 0 0 -1 0 0 cm q ", False) # prepend
25 assert page.is_wrapped is False
26 if page._count_q_balance() == (0, 0):
27 print("imbalance undetected by q balance count")
28
29 text = "Hello, World!"
30 page.insert_text((100, 100), text) # establishes balance!
31
32 # this should have produced a balanced graphics state
33 assert page._count_q_balance() == (0, 0)
34 assert page.is_wrapped
35
36 # an appended "pop" must be balanced by a prepended "push"
37 pymupdf.TOOLS._insert_contents(page, b"Q", True) # append
38 assert page._count_q_balance() == (1, 0)
39
40 # a prepended "pop" yet needs another push
41 pymupdf.TOOLS._insert_contents(page, b"Q", False) # prepend
42 assert page._count_q_balance() == (2, 0)
43
44 # an appended "push" needs an additional "pop"
45 pymupdf.TOOLS._insert_contents(page, b"q", True) # append
46 assert page._count_q_balance() == (2, 1)
47
48 # wrapping the contents should yield a balanced state again
49 assert page.is_wrapped is False
50 page.wrap_contents()
51 assert page.is_wrapped is True
52 assert page._count_q_balance() == (0, 0)