Skip to content

Commit 2f48b97

Browse files
src/: use message() for all diagnostics.
[Avoiding direct writes to stdout/stderr from C++ may help with pyinstaller problem in #3467.]
1 parent fecacd3 commit 2f48b97

2 files changed

Lines changed: 100 additions & 107 deletions

File tree

src/__init__.py

Lines changed: 32 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ def message(text=''):
8585
def exception_info():
8686
import traceback
8787
log(f'exception_info:')
88-
traceback.print_exc(file=sys.stdout)
88+
traceback.print_exc(file=_g_out_log)
8989

9090

9191
# PDF names must not contain these characters:
@@ -339,7 +339,7 @@ def _get_redact_values(self):
339339
try:
340340
obj = mupdf.pdf_dict_gets(mupdf.pdf_annot_obj(annot), "RO")
341341
if obj.m_internal:
342-
JM_Warning("Ignoring redaction key '/RO'.")
342+
message_warning("Ignoring redaction key '/RO'.")
343343
xref = mupdf.pdf_to_num(obj)
344344
values[dictkey_xref] = xref
345345
obj = mupdf.pdf_dict_gets(mupdf.pdf_annot_obj(annot), "OverlayText")
@@ -464,7 +464,7 @@ def _update_appearance(self, opacity=-1, blend_mode=None, fill_color=None, rotat
464464
mupdf.pdf_dict_put( annot_obj, PDF_NAME('IC'), col)
465465
except Exception as e:
466466
if g_exceptions_verbose: exception_info()
467-
message( f'cannot update annot: {e}', file=sys.stderr)
467+
message( f'cannot update annot: {e}')
468468
raise
469469

470470
if (opacity < 0 or opacity >= 1) and not blend_mode: # no opacity, no blend_mode
@@ -501,7 +501,7 @@ def _update_appearance(self, opacity=-1, blend_mode=None, fill_color=None, rotat
501501

502502
except Exception as e:
503503
if g_exceptions_verbose: exception_info()
504-
message( f'cannot set opacity or blend mode\n: {e}', file=sys.stderr)
504+
message( f'cannot set opacity or blend mode\n: {e}')
505505
raise
506506

507507
return True
@@ -1194,7 +1194,7 @@ def set_line_ends(self, start, end):
11941194
if mupdf.pdf_annot_has_line_ending_styles(annot):
11951195
mupdf.pdf_set_annot_line_ending_styles(annot, start, end)
11961196
else:
1197-
JM_Warning("bad annot type for line ends")
1197+
message_warning("bad annot type for line ends")
11981198

11991199
def set_name(self, name):
12001200
"""Set /Name (icon) of annotation."""
@@ -3660,7 +3660,7 @@ def convert_to_pdf(self, from_page=0, to_page=-1, rotate=0):
36603660
doc = JM_convert_to_pdf(fz_doc, fp, tp, rotate)
36613661
len1 = len(JM_mupdf_warnings_store)
36623662
for i in range(len0, len1):
3663-
PySys_WriteStderr(f'{JM_mupdf_warnings_store[i]}\n')
3663+
message(f'{JM_mupdf_warnings_store[i]}')
36643664
return doc
36653665

36663666
def copy_page(self, pno: int, to: int =-1):
@@ -7680,15 +7680,15 @@ def _addAnnot_FromString(self, linklist):
76807680
txtpy = linklist[i]
76817681
text = JM_StrAsChar(txtpy)
76827682
if not text:
7683-
PySys_WriteStderr("skipping bad link / annot item %i.\n", i)
7683+
message("skipping bad link / annot item %i.", i)
76847684
continue
76857685
try:
76867686
annot = mupdf.pdf_add_object( page.doc(), JM_pdf_obj_from_str( page.doc(), text))
76877687
ind_obj = mupdf.pdf_new_indirect( page.doc(), mupdf.pdf_to_num( annot), 0)
76887688
mupdf.pdf_array_push( annots, ind_obj)
76897689
except Exception:
76907690
if g_exceptions_verbose: exception_info()
7691-
message("skipping bad link / annot item %i.\n" % i, file=sys.stderr)
7691+
message("skipping bad link / annot item %i.\n" % i)
76927692

76937693
def _addWidget(self, field_type, field_name):
76947694
page = self._pdf_page()
@@ -8545,7 +8545,7 @@ def bound(self):
85458545
w, h = h, w
85468546
val = Rect(0, 0, w, h)
85478547
msg = TOOLS.mupdf_warnings(reset=False).splitlines()[-1]
8548-
message(msg, file=sys.stderr)
8548+
message(msg)
85498549

85508550
return val
85518551

@@ -10056,7 +10056,7 @@ def gamma_with(self, gamma):
1005610056
"""Apply correction with some float.
1005710057
gamma=1 is a no-op."""
1005810058
if not mupdf.fz_pixmap_colorspace( self.this):
10059-
JM_Warning("colorspace invalid for function")
10059+
message_warning("colorspace invalid for function")
1006010060
return
1006110061
mupdf.fz_gamma_pixmap( self.this, gamma)
1006210062

@@ -10069,7 +10069,7 @@ def invert_irect(self, bbox=None):
1006910069
"""Invert the colors inside a bbox."""
1007010070
pm = self.this
1007110071
if not mupdf.fz_pixmap_colorspace(pm):
10072-
JM_Warning("ignored for stencil pixmap")
10072+
message_warning("ignored for stencil pixmap")
1007310073
return False
1007410074
r = JM_irect_from_py(bbox)
1007510075
if mupdf.fz_is_infinite_irect(r):
@@ -10457,7 +10457,7 @@ def shrink(self, factor):
1045710457
"""Divide width and height by 2**factor.
1045810458
E.g. factor=1 shrinks to 25% of original size (in place)."""
1045910459
if factor < 1:
10460-
JM_Warning("ignoring shrink factor < 1")
10460+
message_warning("ignoring shrink factor < 1")
1046110461
return
1046210462
mupdf.fz_subsample_pixmap( self.this, factor)
1046310463
# Pixmap has changed so clear our memory view.
@@ -11965,7 +11965,6 @@ def document( self):
1196511965
def draw( self, device, matrix=None):
1196611966
ctm2 = JM_matrix_from_py( matrix)
1196711967
dev = device.this if device else mupdf.FzDevice( None)
11968-
sys.stdout.flush()
1196911968
mupdf.fz_draw_story( self.this, dev, ctm2)
1197011969

1197111970
def element_positions( self, function, args=None):
@@ -12178,7 +12177,6 @@ def fit(self, fn, pmin=None, pmax=None, delta=0.001, verbose=False):
1217812177
def log(text):
1217912178
assert verbose
1218012179
message(f'fit(): {text}')
12181-
sys.stdout.flush()
1218212180

1218312181
assert isinstance(pmin, (int, float)) or pmin is None
1218412182
assert isinstance(pmax, (int, float)) or pmax is None
@@ -15765,7 +15763,7 @@ def JM_get_fontextension(doc, xref):
1576515763
if obj.m_internal:
1576615764
obj = mupdf.pdf_dict_get(obj, PDF_NAME('Subtype'))
1576715765
if obj.m_internal and not mupdf.pdf_is_name(obj):
15768-
PySys_WriteStdout("invalid font descriptor subtype")
15766+
message("invalid font descriptor subtype")
1576915767
return "n/a"
1577015768
if mupdf.pdf_name_eq(obj, PDF_NAME('Type1C')):
1577115769
return "cff"
@@ -15774,7 +15772,7 @@ def JM_get_fontextension(doc, xref):
1577415772
elif mupdf.pdf_name_eq(obj, PDF_NAME('OpenType')):
1577515773
return "otf"
1577615774
else:
15777-
PySys_WriteStdout("unhandled font type '%s'", mupdf.pdf_to_name(obj))
15775+
message("unhandled font type '%s'", mupdf.pdf_to_name(obj))
1577815776

1577915777
return "n/a"
1578015778

@@ -15924,19 +15922,9 @@ def JM_image_profile( imagedata, keep_image):
1592415922
if not imagedata:
1592515923
return None # nothing given
1592615924

15927-
#if (PyBytes_Check(imagedata)) {
15928-
# c = PyBytes_AS_STRING(imagedata);
15929-
# len = PyBytes_GET_SIZE(imagedata);
15930-
#} else if (PyByteArray_Check(imagedata)) {
15931-
# c = PyByteArray_AS_STRING(imagedata);
15932-
# len = PyByteArray_GET_SIZE(imagedata);
15933-
#} else {
15934-
# PySys_WriteStderr("bad image data\n");
15935-
# Py_RETURN_NONE;
15936-
#}
1593715925
len_ = len( imagedata)
1593815926
if len_ < 8:
15939-
sys.stderr.write( "bad image data\n")
15927+
message( "bad image data")
1594015928
return None
1594115929
c = imagedata
1594215930
#log( 'calling mfz_recognize_image_format with {c!r=}')
@@ -16577,7 +16565,7 @@ def JM_merge_range(
1657716565
page_merge(doc_des, doc_src, page, afterpage, rotate, links, annots, graft_map)
1657816566
counter += 1
1657916567
if show_progress > 0 and counter % show_progress == 0:
16580-
sys.stdout.write("Inserted %i of %i pages.\n", counter, total)
16568+
message(f"Inserted {counter} of {total} pages.")
1658116569
page += 1
1658216570
afterpage += 1
1658316571
else:
@@ -16586,7 +16574,7 @@ def JM_merge_range(
1658616574
page_merge(doc_des, doc_src, page, afterpage, rotate, links, annots, graft_map)
1658716575
counter += 1
1658816576
if show_progress > 0 and counter % show_progress == 0:
16589-
sys.stdout.write("Inserted %i of %i pages.\n", counter, total)
16577+
message(f"Inserted {counter} of {total} pages.")
1659016578
page -= 1
1659116579
afterpage += 1
1659216580

@@ -16655,20 +16643,19 @@ def JM_merge_resources( page, temp_res):
1665516643
return (max_alp, max_fonts) # next available numbers
1665616644

1665716645

16658-
def JM_mupdf_warning( message):
16646+
def JM_mupdf_warning( text):
1665916647
'''
1666016648
redirect MuPDF warnings
1666116649
'''
16662-
sys.stderr.flush()
16663-
JM_mupdf_warnings_store.append(message)
16650+
JM_mupdf_warnings_store.append(text)
1666416651
if JM_mupdf_show_warnings:
16665-
sys.stderr.write(f'MuPDF warning: {message}\n')
16652+
message(f'MuPDF warning: {text}')
1666616653

1666716654

16668-
def JM_mupdf_error( message):
16669-
JM_mupdf_warnings_store.append(message)
16655+
def JM_mupdf_error( text):
16656+
JM_mupdf_warnings_store.append(text)
1667016657
if JM_mupdf_show_errors:
16671-
sys.stderr.write(f'MuPDF error: {message}\n')
16658+
message(f'MuPDF error: {text}\n')
1667216659

1667316660

1667416661
def JM_new_bbox_device(rc, inc_layers):
@@ -17628,11 +17615,11 @@ def JM_UnicodeFromBuffer(buff):
1762817615
return val
1762917616

1763017617

17631-
def JM_Warning(id):
17618+
def message_warning(text):
1763217619
'''
17633-
put a warning on Python-stdout
17620+
Generate a warning.
1763417621
'''
17635-
sys.stdout.write(f'warning: {id}\n')
17622+
message(f'warning: {text}')
1763617623

1763717624

1763817625
def JM_update_stream(doc, obj, buffer_, compress):
@@ -18112,7 +18099,7 @@ def get_tessdata() -> str:
1811218099
if os.path.exists(tessdata): # all ok?
1811318100
return tessdata
1811418101
else: # should not happen!
18115-
message("unexpected: Tesseract-OCR has no 'tessdata' folder", file=sys.stderr)
18102+
message("unexpected: Tesseract-OCR has no 'tessdata' folder")
1811618103
return False
1811718104

1811818105
# Unix-like systems:
@@ -18132,10 +18119,7 @@ def get_tessdata() -> str:
1813218119
if tessdata is not None:
1813318120
return tessdata
1813418121
else:
18135-
message(
18136-
"unexpected: tesseract-ocr has no 'tessdata' folder",
18137-
file=sys.stderr,
18138-
)
18122+
message("unexpected: tesseract-ocr has no 'tessdata' folder")
1813918123
return False
1814018124
return False
1814118125

@@ -18296,7 +18280,7 @@ def jm_append_merge(dev):
1829618280
#log(f'calling {dev.out=} {dev.method=} {dev.pathdict=}')
1829718281
resp = getattr(dev.out, dev.method)(dev.pathdict)
1829818282
if not resp:
18299-
message("calling cdrawings callback function/method failed!", file=sys.stderr)
18283+
message("calling cdrawings callback function/method failed!")
1830018284
dev.pathdict = None
1830118285
return
1830218286

@@ -18340,7 +18324,7 @@ def append():
1834018324
prev[ dictkey_type] = 'fs'
1834118325
dev.pathdict.clear()
1834218326
else:
18343-
message("could not merge stroke and fill path", file=sys.stderr)
18327+
message("could not merge stroke and fill path")
1834418328
append()
1834518329

1834618330

@@ -18551,9 +18535,6 @@ def jm_trace_text_span(dev, span, type_, ctm, colorspace, color, alpha, seqno):
1855118535
if dir.x == -1: # left-right flip
1855218536
rot.d = 1
1855318537

18554-
# PySys_WriteStdout("mat: (%g, %g, %g, %g)\n", mat.a, mat.b, mat.c, mat.d);
18555-
# PySys_WriteStdout("rot: (%g, %g, %g, %g)\n", rot.a, rot.b, rot.c, rot.d);
18556-
1855718538
chars = []
1855818539
for i in range( span.m_internal.len):
1855918540
adv = 0
@@ -20949,14 +20930,6 @@ def unicode_to_glyph_name(ch: int) -> str:
2094920930
return _adobe_glyphs.get(ch, ".notdef")
2095020931

2095120932

20952-
def PySys_WriteStdout(text):
20953-
sys.stdout.write(text)
20954-
20955-
20956-
def PySys_WriteStderr(text):
20957-
sys.stderr.write(text)
20958-
20959-
2096020933
def vdist(dir, a, b):
2096120934
dx = b.x - a.x
2096220935
dy = b.y - a.y
@@ -21675,10 +21648,10 @@ def showthis(msg, cat, filename, lineno, file=None, line=None):
2167521648
text = warnings.formatwarning(msg, cat, filename, lineno, line=line)
2167621649
s = text.find("FitzDeprecation")
2167721650
if s < 0:
21678-
log(text, file=sys.stderr)
21651+
log(text)
2167921652
return
2168021653
text = text[s:].splitlines()[0][4:]
21681-
log(text, file=sys.stderr)
21654+
log(text)
2168221655

2168321656
warnings.showwarning = showthis
2168421657

0 commit comments

Comments
 (0)