forked from ArtifexSoftware/mupdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fitz_wrap_c.py
5063 lines (4967 loc) · 176 KB
/
fitz_wrap_c.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#/* ----------------------------------------------------------------------------
# * This file was automatically generated by SWIG (http://www.swig.org).
# * Version 3.0.12
# *
# * This file is not intended to be easily readable and contains a number of
# * coding conventions designed to improve portability and efficiency. Do not make
# * changes to this file unless you know what you are doing--modify the SWIG
# * interface file instead.
# * ----------------------------------------------------------------------------- */
from fitz_i import *
import mupdf
#----------------------------------------------------------------------------
# colorspace identifiers
#----------------------------------------------------------------------------
CS_RGB = 1
CS_GRAY = 2
CS_CMYK = 3
# General text flags
TEXT_FONT_SUPERSCRIPT = 1
TEXT_FONT_ITALIC = 2
TEXT_FONT_SERIFED = 4
TEXT_FONT_MONOSPACED = 8
TEXT_FONT_BOLD = 16
def SWIG_From_int(value):
return int(value)
#-----------------------------------------------------------------------------
# Functions converting betwenn PySequences and fitz geometry objects
#-----------------------------------------------------------------------------
def JM_INT_ITEM(obj, idx):
'''
Unlike original C version, this returns the item and raises an exception if
<idx> is out of range.
So code liks this:
if (JM_INT_ITEM(page_id, 1, &pno) == 1) {
THROWMSG(gctx, "bad page id");
}
becomes:
pno = JM_INT_ITEM(page_id, 1)
'''
if idx > len(obj):
raise Exception(f'Bad idx={idx}, len(obj)={len(obj)}')
return int(obj[idx])
def JM_FLOAT_ITEM(obj, idx):
if idx > len(obj):
raise Exception(f'Bad idx={idx}, len(obj)={len(obj)}')
return float(obj[idx])
def PySequence_Check(r):
return isinstance(r, (list, tuple))
def PySequence_Size(r):
return len(r)
#-----------------------------------------------------------------------------
# PySequence to fz_rect. Default: infinite rect
#-----------------------------------------------------------------------------
def JM_rect_from_py(r):
if not r or not PySequence_Check(r) or PySequence_Size(r) != 4:
return Rect(Rect.Fixed_INFINITE)
f = [0, 0, 0, 0]
for i in range(4):
f[i] = JM_FLOAT_ITEM(r, i)
return mfz_make_rect(f[0], f[1], f[2], f[3])
#-----------------------------------------------------------------------------
# PySequence from fz_rect
#-----------------------------------------------------------------------------
def JM_py_from_rect(r):
return r.x0, r.y0, r.x1, r.y1
#-----------------------------------------------------------------------------
# PySequence to fz_irect. Default: infinite irect
#-----------------------------------------------------------------------------
def JM_irect_from_py(r):
if not PySequence_Check(r) or PySequence_Size(r) != 4:
return fz_infinite_irect
x = [0, 0, 0, 0]
for i in range(4):
x[i] = JM_INT_ITEM(r, i)
return mfz_make_irect(x[0], x[1], x[2], x[3])
#-----------------------------------------------------------------------------
# PySequence from fz_irect
#-----------------------------------------------------------------------------
def JM_py_from_irect(r):
return r.x0, r.y0, r.x1, r.y1
#-----------------------------------------------------------------------------
# PySequence to fz_point. Default: (0, 0)
#-----------------------------------------------------------------------------
def JM_point_from_py(p):
p0 = mfz_make_point(0, 0)
if not p or not PySequence_Check(p) or PySequence_Size(p) != 2:
return p0
x = JM_FLOAT_ITEM(p, 0)
y = JM_FLOAT_ITEM(p, 1)
return mfz_make_point(x, y)
#-----------------------------------------------------------------------------
# PySequence from fz_point
#-----------------------------------------------------------------------------
def JM_py_from_point(p):
return p.x, p.y
#-----------------------------------------------------------------------------
# PySequence to fz_matrix. Default: fz_identity
#-----------------------------------------------------------------------------
def JM_matrix_from_py(m):
if not m or not PySequence_Check(m) or PySequence_Size(m) != 6:
return fz_identity;
return mfz_make_matrix(m[0], m[1], m[2], m[3], m[4], m[5])
#-----------------------------------------------------------------------------
# PySequence from fz_matrix
#-----------------------------------------------------------------------------
def JM_py_from_matrix(m):
return m.a, m.b, m.c, m.d, m.e, m.f
#-----------------------------------------------------------------------------
# fz_quad from PySequence. Four floats are treated as rect.
# Else must be four pairs of floats.
#-----------------------------------------------------------------------------
def JM_quad_from_py(r):
q = mfz_make_quad(0, 0, 0, 0, 0, 0, 0, 0)
p = [0, 0, 0, 0]
if not r or not PySequence_Check(r) or PySequence_Size(r) != 4:
return q
try:
test = JM_FLOAT_ITEM(r, 0)
except Exception:
return mfz_quad_from_rect(JM_rect_from_py(r))
for i in range(4):
obj = PySequence_ITEM(r, i); # next point item
if not obj or not PySequence_Check(obj) or PySequence_Size(obj) != 2:
return q # invalid: cancel the rest
try:
p[i].x = JM_FLOAT_ITEM(obj, 0)
p[i].y = JM_FLOAT_ITEM(obj, 1)
except Exception:
return q
q.ul = p[0];
q.ur = p[1];
q.ll = p[2];
q.lr = p[3];
return q
#-----------------------------------------------------------------------------
# PySequence from fz_quad.
#-----------------------------------------------------------------------------
def JM_py_from_quad(quad):
return (
JM_py_from_point(quad.ul),
JM_py_from_point(quad.ur),
JM_py_from_point(quad.ll),
JM_py_from_point(quad.lr),
)
def LIST_APPEND_DROP(list_, item):
list_.append(item)
def DICT_SETITEM_DROP(dict_, key, value):
dict_[key] = value
def DICT_SETITEMSTR_DROP(dict_, key, value):
dict_[key] = value
def JM_get_page_labels(liste, nums):
n = pdf_array_len(ctx, nums);
for i in range(n, 2):
key = mpdf_resolve_indirect(mpdf_array_get(nums, i))
pno = mpdf_to_int(key)
val = mpdf_resolve_indirect(mpdf_array_get(nums, i + 1))
res = JM_object_to_buffer(ctx, val, 1, 0);
c = mfz_buffer_storage(res)
LIST_APPEND_DROP(liste, (pno, c))
def JM_EscapeStrFromBuffer(buff):
if not buff.m_internal:
return ''
bytes_ = buffer_extract(buff)
return bytes_.decode('utf-8')
def JM_UnicodeFromBuffer(buff):
if not buff.m_internal:
return b''
bytes_ = buffer_extract(buff)
return bytes_
def JM_UnicodeFromStr(c):
return c.encode('utf-8')
def JM_EscapeStrFromStr(c):
return c
# list of valid unicodes of a fz_font
#def JM_valid_chars(fz_font *font, void *arr):
def JM_valid_chars(font, arr):
assert 0, 'Not implemented'
'''
{
FT_Face face = font.m_internal.ft_face
FT_ULong ucs;
FT_UInt gid;
long *table = (long *)arr;
fz_lock(ctx, FZ_LOCK_FREETYPE);
ucs = FT_Get_First_Char(face, &gid);
while (gid > 0)
{
if (gid < (FT_ULong)face->num_glyphs && face->num_glyphs > 0)
table[gid] = (long)ucs;
ucs = FT_Get_Next_Char(face, ucs, &gid);
}
fz_unlock(ctx, FZ_LOCK_FREETYPE);
return;
}
'''
# redirect MuPDF warnings
def JM_mupdf_warning(user, message):
LIST_APPEND_DROP(JM_mupdf_warnings_store, JM_EscapeStrFromStr(message))
def PySys_WriteStderr(text):
sys.stderr.write(text)
def PySys_WriteStdout(text):
sys.stdout.write(text)
# redirect MuPDF errors
def JM_mupdf_error(user, message):
LIST_APPEND_DROP(JM_mupdf_warnings_store, JM_EscapeStrFromStr(message))
if JM_mupdf_show_errors:
PySys_WriteStderr("mupdf: %s\n", message)
# a simple tracer
def JM_TRACE(id):
PySys_WriteStdout("%s\n", id);
# put a warning on Python-stdout
def JM_Warning(id):
PySys_WriteStdout("warning: %s\n", id)
#if JM_MEMORY == 1
#-----------------------------------------------------------------------------
# The following 3 functions replace MuPDF standard memory allocation.
# This will ensure, that MuPDF memory handling becomes part of Python's
# memory management.
#-----------------------------------------------------------------------------
'''
static void *JM_Py_Malloc(void *opaque, size_t size)
{
void *mem = PyMem_Malloc((Py_ssize_t) size);
if (mem) return mem;
fz_throw(gctx, FZ_ERROR_MEMORY, "malloc of %zu bytes failed", size);
}
static void *JM_Py_Realloc(void *opaque, void *old, size_t size)
{
void *mem = PyMem_Realloc(old, (Py_ssize_t) size);
if (mem) return mem;
fz_throw(gctx, FZ_ERROR_MEMORY, "realloc of %zu bytes failed", size);
}
static void JM_PY_Free(void *opaque, void *ptr)
{
PyMem_Free(ptr);
}
const fz_alloc_context JM_Alloc_Context =
{
NULL,
JM_Py_Malloc,
JM_Py_Realloc,
JM_PY_Free
};
#endif
'''
# return Python bool for a given integer
def JM_BOOL(v):
return True if v else False
'''
PyObject *JM_fitz_config()
{
#if defined(TOFU)
#define have_TOFU JM_BOOL(0)
#else
#define have_TOFU JM_BOOL(1)
#endif
#if defined(TOFU_CJK)
#define have_TOFU_CJK JM_BOOL(0)
#else
#define have_TOFU_CJK JM_BOOL(1)
#endif
#if defined(TOFU_CJK_EXT)
#define have_TOFU_CJK_EXT JM_BOOL(0)
#else
#define have_TOFU_CJK_EXT JM_BOOL(1)
#endif
#if defined(TOFU_CJK_LANG)
#define have_TOFU_CJK_LANG JM_BOOL(0)
#else
#define have_TOFU_CJK_LANG JM_BOOL(1)
#endif
#if defined(TOFU_EMOJI)
#define have_TOFU_EMOJI JM_BOOL(0)
#else
#define have_TOFU_EMOJI JM_BOOL(1)
#endif
#if defined(TOFU_HISTORIC)
#define have_TOFU_HISTORIC JM_BOOL(0)
#else
#define have_TOFU_HISTORIC JM_BOOL(1)
#endif
#if defined(TOFU_SYMBOL)
#define have_TOFU_SYMBOL JM_BOOL(0)
#else
#define have_TOFU_SYMBOL JM_BOOL(1)
#endif
#if defined(TOFU_SIL)
#define have_TOFU_SIL JM_BOOL(0)
#else
#define have_TOFU_SIL JM_BOOL(1)
#endif
#if defined(TOFU_BASE14)
#define have_TOFU_BASE14 JM_BOOL(0)
#else
#define have_TOFU_BASE14 JM_BOOL(1)
#endif
PyObject *dict = PyDict_New();
DICT_SETITEMSTR_DROP(dict, "plotter-g", JM_BOOL(FZ_PLOTTERS_G));
DICT_SETITEMSTR_DROP(dict, "plotter-rgb", JM_BOOL(FZ_PLOTTERS_RGB));
DICT_SETITEMSTR_DROP(dict, "plotter-cmyk", JM_BOOL(FZ_PLOTTERS_CMYK));
DICT_SETITEMSTR_DROP(dict, "plotter-n", JM_BOOL(FZ_PLOTTERS_N));
DICT_SETITEMSTR_DROP(dict, "pdf", JM_BOOL(FZ_ENABLE_PDF));
DICT_SETITEMSTR_DROP(dict, "xps", JM_BOOL(FZ_ENABLE_XPS));
DICT_SETITEMSTR_DROP(dict, "svg", JM_BOOL(FZ_ENABLE_SVG));
DICT_SETITEMSTR_DROP(dict, "cbz", JM_BOOL(FZ_ENABLE_CBZ));
DICT_SETITEMSTR_DROP(dict, "img", JM_BOOL(FZ_ENABLE_IMG));
DICT_SETITEMSTR_DROP(dict, "html", JM_BOOL(FZ_ENABLE_HTML));
DICT_SETITEMSTR_DROP(dict, "epub", JM_BOOL(FZ_ENABLE_EPUB));
DICT_SETITEMSTR_DROP(dict, "jpx", JM_BOOL(FZ_ENABLE_JPX));
DICT_SETITEMSTR_DROP(dict, "js", JM_BOOL(FZ_ENABLE_JS));
DICT_SETITEMSTR_DROP(dict, "tofu", have_TOFU);
DICT_SETITEMSTR_DROP(dict, "tofu-cjk", have_TOFU_CJK);
DICT_SETITEMSTR_DROP(dict, "tofu-cjk-ext", have_TOFU_CJK_EXT);
DICT_SETITEMSTR_DROP(dict, "tofu-cjk-lang", have_TOFU_CJK_LANG);
DICT_SETITEMSTR_DROP(dict, "tofu-emoji", have_TOFU_EMOJI);
DICT_SETITEMSTR_DROP(dict, "tofu-historic", have_TOFU_HISTORIC);
DICT_SETITEMSTR_DROP(dict, "tofu-symbol", have_TOFU_SYMBOL);
DICT_SETITEMSTR_DROP(dict, "tofu-sil", have_TOFU_SIL);
DICT_SETITEMSTR_DROP(dict, "icc", JM_BOOL(FZ_ENABLE_ICC));
DICT_SETITEMSTR_DROP(dict, "base14", have_TOFU_BASE14);
DICT_SETITEMSTR_DROP(dict, "py-memory", JM_BOOL(JM_MEMORY));
return dict;
}
'''
#----------------------------------------------------------------------------
# Update a color float array with values from a Python sequence.
# Any error condition is treated as a no-op.
#----------------------------------------------------------------------------
def JM_color_FromSequence(color, col):
if not color or (not PySequence_Check(color) and not PyFloat_Check(color)):
return 1
if PyFloat_Check(color): # maybe just a single float
c = float(color)
if not INRANGE(c, 0, 1):
return 1
col[0] = c
return 1
len_ = PySequence_Size(color)
if not INRANGE(len, 1, 4) or len_ == 2:
return 1
for i in range(len_):
col[i] = color[i]
return len_
# return extension for fitz image type
def JM_image_extension(type_):
if type_ == FZ_IMAGE_RAW: return "raw"
if type_ == FZ_IMAGE_FLATE: return "flate"
if type_ == FZ_IMAGE_LZW: return "lzw"
if type_ == FZ_IMAGE_RLD: return "rld"
if type_ == FZ_IMAGE_BMP: return "bmp"
if type_ == FZ_IMAGE_GIF: return "gif"
if type_ == FZ_IMAGE_JBIG2: return "jb2"
if type_ == FZ_IMAGE_JPEG: return "jpeg"
if type_ == FZ_IMAGE_JPX: return "jpx"
if type_ == FZ_IMAGE_JXR: return "jxr"
if type_ == FZ_IMAGE_PNG: return "png"
if type_ == FZ_IMAGE_PNM: return "pnm"
if type_ == FZ_IMAGE_TIFF: return "tiff"
return "n/a"
#----------------------------------------------------------------------------
# Turn fz_buffer into a Python bytes object
#----------------------------------------------------------------------------
def JM_BinFromBuffer(buffer_):
if not buffer_.m_internal:
return b''
return buffer_.buffer_extract()
#----------------------------------------------------------------------------
# Turn fz_buffer into a Python bytearray object
#----------------------------------------------------------------------------
def JM_BArrayFromBuffer(buffer_):
return bytearray(JM_BinFromBuffer(buffer_))
#----------------------------------------------------------------------------
# compress char* into a new buffer
#----------------------------------------------------------------------------
def JM_compress_buffer(inbuffer):
compressed_data, compressed_length = mfz_new_deflated_data_from_buffer(inbuffer, FZ_DEFLATE_BEST)
if compressed_length == 0:
return
buf = mfz_new_buffer_from_data(compressed_data, compressed_length)
mfz_resize_buffer(buf, compressed_length)
return buf
#----------------------------------------------------------------------------
# update a stream object
# compress stream when beneficial
#----------------------------------------------------------------------------
#void JM_update_stream(fz_context *ctx, pdf_document *doc, pdf_obj *obj, fz_buffer *buffer, int compress)
def JM_update_stream(doc, obj, buffer_, compress):
len_, _ = mfz_buffer_storage(buffer_)
nlen = len_
if len_ > 30: # ignore small stuff
nres = JM_compress_buffer(buffer_)
nlen, _ = mfz_buffer_storage(nres)
if nlen < len_ and compress==1: # was it worth the effort?
mpdf_dict_put(obj, PDF_NAME(Filter), PDF_NAME(FlateDecode))
mpdf_update_stream(doc, obj, nres, 1)
else:
mpdf_update_stream(doc, obj, buffer_, 0)
#-----------------------------------------------------------------------------
# return hex characters for n characters in input 'in'
#-----------------------------------------------------------------------------
def hexlify(n, in_):
hdigit = "0123456789abcedf"
out = ''
for i in range(n):
c = ord(in_[i])
out += hdigit(c / 16)
out += hdigit(c % 16)
return out
#----------------------------------------------------------------------------
# Make fz_buffer from a PyBytes, PyByteArray, io.BytesIO object
#----------------------------------------------------------------------------
#fz_buffer *JM_BufferFromBytes(fz_context *ctx, PyObject *stream)
def JM_BufferFromBytes(stream):
if not stream:
return None
if isinstance(stream, bytes):
res = mfz_new_buffer_from_copied_data(python_bytes_data(stream), len(stream))
return res
assert 0, f'Not implemented type(stream)={type(stream)}'
'''
char *c = NULL;
PyObject *mybytes = NULL;
size_t len = 0;
fz_buffer *res = NULL;
fz_var(res);
fz_try(ctx) {
if (PyBytes_Check(stream)) {
c = PyBytes_AS_STRING(stream);
len = (size_t) PyBytes_GET_SIZE(stream);
} else if (PyByteArray_Check(stream)) {
c = PyByteArray_AS_STRING(stream);
len = (size_t) PyByteArray_GET_SIZE(stream);
} else if (PyObject_HasAttrString(stream, "getvalue")) {
// we assume here that this delivers what we expect
mybytes = PyObject_CallMethod(stream, "getvalue", NULL);
c = PyBytes_AS_STRING(mybytes);
len = (size_t) PyBytes_GET_SIZE(mybytes);
}
// all the above leave c as NULL pointer if unsuccessful
if (c) res = fz_new_buffer_from_copied_data(ctx, (const unsigned char *) c, len);
}
fz_always(ctx) {
Py_CLEAR(mybytes);
PyErr_Clear();
}
fz_catch(ctx) {
fz_drop_buffer(ctx, res);
fz_rethrow(ctx);
}
return res;
'''
##----------------------------------------------------------------------------
## Deep-copies a specified source page to the target location.
## Modified copy of function of pdfmerge.c: we also copy annotations, but
## we skip **link** annotations. In addition we rotate output.
##----------------------------------------------------------------------------
#static void
#page_merge(fz_context *ctx, pdf_document *doc_des, pdf_document *doc_src, int page_from, int page_to, int #rotate, int links, int copy_annots, pdf_graft_map *graft_map)
#{
# pdf_obj *page_ref = NULL;
# pdf_obj *page_dict = NULL;
# pdf_obj *obj = NULL, *ref = NULL;
#
# // list of object types (per page) we want to copy
# pdf_obj *known_page_objs[] = {
# PDF_NAME(Contents),
# PDF_NAME(Resources),
# PDF_NAME(MediaBox),
# PDF_NAME(CropBox),
# PDF_NAME(BleedBox),
# PDF_NAME(TrimBox),
# PDF_NAME(ArtBox),
# PDF_NAME(Rotate),
# PDF_NAME(UserUnit)
# };
# int i, n = (int) nelem(known_page_objs); // number of list elements
# fz_var(ref);
# fz_var(page_dict);
# fz_try(ctx) {
# page_ref = pdf_lookup_page_obj(ctx, doc_src, page_from);
# pdf_flatten_inheritable_page_items(ctx, page_ref);
#
# // make new page dict in dest doc
# page_dict = pdf_new_dict(ctx, doc_des, 4);
# pdf_dict_put(ctx, page_dict, PDF_NAME(Type), PDF_NAME(Page));
#
# // copy objects of source page into it
# for (i = 0; i < n; i++) {
# obj = pdf_dict_get(ctx, page_ref, known_page_objs[i]);
# if (obj != NULL) {
# pdf_dict_put_drop(ctx, page_dict, known_page_objs[i], pdf_graft_mapped_object(ctx, #graft_map, obj));
# }
# }
#
# // Copy the annotations, but skip types Link, Popup, IRT.
# // Remove dict keys P (parent) and Popup from copied annot.
# if (copy_annots) {
# pdf_obj *old_annots = pdf_dict_get(ctx, page_ref, PDF_NAME(Annots));
# if (old_annots) {
# n = pdf_array_len(ctx, old_annots);
# pdf_obj *new_annots = pdf_dict_put_array(ctx, page_dict, PDF_NAME(Annots), n);
# for (i = 0; i < n; i++) {
# pdf_obj *o = pdf_array_get(ctx, old_annots, i);
# if (pdf_dict_gets(ctx, o, "IRT")) continue;
# pdf_obj *subtype = pdf_dict_get(ctx, o, PDF_NAME(Subtype));
# if (pdf_name_eq(ctx, subtype, PDF_NAME(Link))) continue;
# if (pdf_name_eq(ctx, subtype, PDF_NAME(Popup))) continue;
# pdf_dict_del(ctx, o, PDF_NAME(Popup));
# pdf_dict_del(ctx, o, PDF_NAME(P));
# pdf_obj *copy_o = pdf_graft_mapped_object(ctx, graft_map, o);
# pdf_obj *annot = pdf_new_indirect(ctx, doc_des,
# pdf_to_num(ctx, copy_o), 0);
# pdf_array_push_drop(ctx, new_annots, annot);
# pdf_drop_obj(ctx, copy_o);
# }
# }
# }
# // rotate the page
# if (rotate != -1) {
# pdf_dict_put_int(ctx, page_dict, PDF_NAME(Rotate), (int64_t) rotate);
# }
# // Now add the page dictionary to dest PDF
# ref = pdf_add_object(ctx, doc_des, page_dict);
#
# // Insert new page at specified location
# pdf_insert_page(ctx, doc_des, page_to, ref);
#
# }
# fz_always(ctx) {
# pdf_drop_obj(ctx, ref);
# pdf_drop_obj(ctx, page_dict);
# }
# fz_catch(ctx) {
# fz_rethrow(ctx);
# }
#}
#
##-----------------------------------------------------------------------------
## Copy a range of pages (spage, epage) from a source PDF to a specified
## location (apage) of the target PDF.
## If spage > epage, the sequence of source pages is reversed.
##-----------------------------------------------------------------------------
#void JM_merge_range(fz_context *ctx, pdf_document *doc_des, pdf_document *doc_src, int spage, int epage, #int apage, int rotate, int links, int annots, int show_progress, pdf_graft_map *graft_map)
#{
# int page, afterpage;
# afterpage = apage;
# int counter = 0; // copied pages counter
# int total = fz_absi(epage - spage) + 1; // total pages to copy
#
# fz_try(ctx) {
# if (spage < epage) {
# for (page = spage; page <= epage; page++, afterpage++) {
# page_merge(ctx, doc_des, doc_src, page, afterpage, rotate, links, annots, graft_map);
# counter++;
# if (show_progress > 0 && counter % show_progress == 0) {
# PySys_WriteStdout("Inserted %i of %i pages.\n", counter, total);
# }
# }
# } else {
# for (page = spage; page >= epage; page--, afterpage++) {
# page_merge(ctx, doc_des, doc_src, page, afterpage, rotate, links, annots, graft_map);
# counter++;
# if (show_progress > 0 && counter % show_progress == 0) {
# PySys_WriteStdout("Inserted %i of %i pages.\n", counter, total);
# }
# }
# }
# }
#
# fz_catch(ctx) {
# fz_rethrow(ctx);
# }
#}
#
##----------------------------------------------------------------------------
## Return list of outline xref numbers. Recursive function. Arguments:
## 'obj' first OL item
## 'xrefs' empty Python list
##----------------------------------------------------------------------------
#PyObject *JM_outline_xrefs(fz_context *ctx, pdf_obj *obj, PyObject *xrefs)
#{
# pdf_obj *first, *parent, *thisobj;
# if (!obj) return xrefs;
# thisobj = obj;
# while (thisobj) {
# LIST_APPEND_DROP(xrefs, Py_BuildValue("i", pdf_to_num(ctx, thisobj)));
# first = pdf_dict_get(ctx, thisobj, PDF_NAME(First)); // try go down
# if (first) xrefs = JM_outline_xrefs(ctx, first, xrefs);
# thisobj = pdf_dict_get(ctx, thisobj, PDF_NAME(Next)); // try go next
# parent = pdf_dict_get(ctx, thisobj, PDF_NAME(Parent)); // get parent
# if (!thisobj) thisobj = parent; // goto parent if no next
# }
# return xrefs;
#}
#
#
##-----------------------------------------------------------------------------
## Return the contents of a font file, identified by xref
##-----------------------------------------------------------------------------
#fz_buffer *JM_get_fontbuffer(fz_context *ctx, pdf_document *doc, int xref)
#{
# if (xref < 1) return NULL;
# pdf_obj *o, *obj = NULL, *desft, *stream = NULL;
# o = pdf_load_object(ctx, doc, xref);
# desft = pdf_dict_get(ctx, o, PDF_NAME(DescendantFonts));
# char *ext = NULL;
# if (desft) {
# obj = pdf_resolve_indirect(ctx, pdf_array_get(ctx, desft, 0));
# obj = pdf_dict_get(ctx, obj, PDF_NAME(FontDescriptor));
# } else {
# obj = pdf_dict_get(ctx, o, PDF_NAME(FontDescriptor));
# }
#
# if (!obj) {
# pdf_drop_obj(ctx, o);
# PySys_WriteStdout("invalid font - FontDescriptor missing");
# return NULL;
# }
# pdf_drop_obj(ctx, o);
# o = obj;
#
# obj = pdf_dict_get(ctx, o, PDF_NAME(FontFile));
# if (obj) stream = obj; // ext = "pfa"
#
# obj = pdf_dict_get(ctx, o, PDF_NAME(FontFile2));
# if (obj) stream = obj; // ext = "ttf"
#
# obj = pdf_dict_get(ctx, o, PDF_NAME(FontFile3));
# if (obj) {
# stream = obj;
#
# obj = pdf_dict_get(ctx, obj, PDF_NAME(Subtype));
# if (obj && !pdf_is_name(ctx, obj)) {
# PySys_WriteStdout("invalid font descriptor subtype");
# return NULL;
# }
#
# if (pdf_name_eq(ctx, obj, PDF_NAME(Type1C)))
# ext = "cff";
# else if (pdf_name_eq(ctx, obj, PDF_NAME(CIDFontType0C)))
# ext = "cid";
# else if (pdf_name_eq(ctx, obj, PDF_NAME(OpenType)))
# ext = "otf";
# else
# PySys_WriteStdout("warning: unhandled font type '%s'", pdf_to_name(ctx, obj));
# }
#
# if (!stream) {
# PySys_WriteStdout("warning: unhandled font type");
# return NULL;
# }
#
# return pdf_load_stream(ctx, stream);
#}
#
##-----------------------------------------------------------------------------
## Return the file extension of a font file, identified by xref
##-----------------------------------------------------------------------------
#char *JM_get_fontextension(fz_context *ctx, pdf_document *doc, int xref)
#{
# if (xref < 1) return "n/a";
# pdf_obj *o, *obj = NULL, *desft;
# o = pdf_load_object(ctx, doc, xref);
# desft = pdf_dict_get(ctx, o, PDF_NAME(DescendantFonts));
# if (desft) {
# obj = pdf_resolve_indirect(ctx, pdf_array_get(ctx, desft, 0));
# obj = pdf_dict_get(ctx, obj, PDF_NAME(FontDescriptor));
# } else {
# obj = pdf_dict_get(ctx, o, PDF_NAME(FontDescriptor));
# }
#
# pdf_drop_obj(ctx, o);
# if (!obj) return "n/a"; // this is a base-14 font
#
# o = obj; // we have the FontDescriptor
#
# obj = pdf_dict_get(ctx, o, PDF_NAME(FontFile));
# if (obj) return "pfa";
#
# obj = pdf_dict_get(ctx, o, PDF_NAME(FontFile2));
# if (obj) return "ttf";
#
# obj = pdf_dict_get(ctx, o, PDF_NAME(FontFile3));
# if (obj) {
# obj = pdf_dict_get(ctx, obj, PDF_NAME(Subtype));
# if (obj && !pdf_is_name(ctx, obj)) {
# PySys_WriteStdout("invalid font descriptor subtype");
# return "n/a";
# }
# if (pdf_name_eq(ctx, obj, PDF_NAME(Type1C)))
# return "cff";
# else if (pdf_name_eq(ctx, obj, PDF_NAME(CIDFontType0C)))
# return "cid";
# else if (pdf_name_eq(ctx, obj, PDF_NAME(OpenType)))
# return "otf";
# else
# PySys_WriteStdout("unhandled font type '%s'", pdf_to_name(ctx, obj));
# }
#
# return "n/a";
#}
#
#
##-----------------------------------------------------------------------------
## create PDF object from given string (new in v1.14.0: MuPDF dropped it)
##-----------------------------------------------------------------------------
#pdf_obj *JM_pdf_obj_from_str(fz_context *ctx, pdf_document *doc, char *src)
#{
# pdf_obj *result = NULL;
# pdf_lexbuf lexbuf;
# fz_stream *stream = fz_open_memory(ctx, (unsigned char *)src, strlen(src));
#
# pdf_lexbuf_init(ctx, &lexbuf, PDF_LEXBUF_SMALL);
#
# fz_try(ctx) {
# result = pdf_parse_stm_obj(ctx, doc, stream, &lexbuf);
# }
#
# fz_always(ctx) {
# pdf_lexbuf_fin(ctx, &lexbuf);
# fz_drop_stream(ctx, stream);
# }
#
# fz_catch(ctx) {
# fz_rethrow(ctx);
# }
#
# return result;
#
#}
#
##----------------------------------------------------------------------------
## return normalized /Rotate value
##----------------------------------------------------------------------------
#int JM_norm_rotation(int rotate)
#{
# while (rotate < 0) rotate += 360;
# while (rotate >= 360) rotate -= 360;
# if (rotate % 90 != 0) return 0;
# return rotate;
#}
#
#
##----------------------------------------------------------------------------
## return a PDF page's /Rotate value: one of (0, 90, 180, 270)
##----------------------------------------------------------------------------
#int JM_page_rotation(fz_context *ctx, pdf_page *page)
#{
# int rotate = 0;
# fz_try(ctx)
# {
# rotate = pdf_to_int(ctx,
# pdf_dict_get_inheritable(ctx, page->obj, PDF_NAME(Rotate)));
# rotate = JM_norm_rotation(rotate);
# }
# fz_catch(ctx) return 0;
# return rotate;
#}
#
#
##----------------------------------------------------------------------------
## return a PDF page's MediaBox
##----------------------------------------------------------------------------
#fz_rect JM_mediabox(fz_context *ctx, pdf_obj *page_obj)
#{
# fz_rect mediabox, page_mediabox;
#
# mediabox = pdf_to_rect(ctx, pdf_dict_get_inheritable(ctx, page_obj,
# PDF_NAME(MediaBox)));
# if (fz_is_empty_rect(mediabox) or fz_is_infinite_rect(mediabox))
# {
# mediabox.x0 = 0;
# mediabox.y0 = 0;
# mediabox.x1 = 612;
# mediabox.y1 = 792;
# }
#
# page_mediabox.x0 = fz_min(mediabox.x0, mediabox.x1);
# page_mediabox.y0 = fz_min(mediabox.y0, mediabox.y1);
# page_mediabox.x1 = fz_max(mediabox.x0, mediabox.x1);
# page_mediabox.y1 = fz_max(mediabox.y0, mediabox.y1);
#
# if (page_mediabox.x1 - page_mediabox.x0 < 1 ||
# page_mediabox.y1 - page_mediabox.y0 < 1)
# page_mediabox = fz_unit_rect;
#
# return page_mediabox;
#}
#
#
##----------------------------------------------------------------------------
## return a PDF page's CropBox
##----------------------------------------------------------------------------
#fz_rect JM_cropbox(fz_context *ctx, pdf_obj *page_obj)
#{
# fz_rect mediabox = JM_mediabox(ctx, page_obj);
# fz_rect cropbox = pdf_to_rect(ctx,
# pdf_dict_get_inheritable(ctx, page_obj, PDF_NAME(CropBox)));
# if (fz_is_infinite_rect(cropbox) or fz_is_empty_rect(cropbox))
# return mediabox;
# float y0 = mediabox.y1 - cropbox.y1;
# float y1 = mediabox.y1 - cropbox.y0;
# cropbox.y0 = y0;
# cropbox.y1 = y1;
# return cropbox;
#}
#
#
##----------------------------------------------------------------------------
## calculate width and height of the UNROTATED page
##----------------------------------------------------------------------------
#fz_point JM_cropbox_size(fz_context *ctx, pdf_obj *page_obj)
#{
# fz_point size;
# fz_try(ctx)
# {
# fz_rect rect = JM_cropbox(ctx, page_obj);
# float w = (rect.x0 < rect.x1 ? rect.x1 - rect.x0 : rect.x0 - rect.x1);
# float h = (rect.y0 < rect.y1 ? rect.y1 - rect.y0 : rect.y0 - rect.y1);
# size = fz_make_point(w, h);
# }
# fz_catch(ctx) fz_rethrow(ctx);
# return size;
#}
#
#
##----------------------------------------------------------------------------
## calculate page rotation matrices
##----------------------------------------------------------------------------
#fz_matrix JM_rotate_page_matrix(fz_context *ctx, pdf_page *page)
#{
# if (!page) return fz_identity; // no valid pdf page given
# int rotation = JM_page_rotation(ctx, page);
# if (rotation == 0) return fz_identity; // no rotation
# fz_matrix m;
# fz_point cb_size = JM_cropbox_size(ctx, page->obj);
# float w = cb_size.x;
# float h = cb_size.y;
# if (rotation == 90)
# m = fz_make_matrix(0, 1, -1, 0, h, 0);
# else if (rotation == 180)
# m = fz_make_matrix(-1, 0, 0, -1, w, h);
# else
# m = fz_make_matrix(0, -1, 1, 0, 0, w);
# return m;
#}
#
#
#fz_matrix JM_derotate_page_matrix(fz_context *ctx, pdf_page *page)
#{ // just the inverse of rotation
# return fz_invert_matrix(JM_rotate_page_matrix(ctx, page));
#}
#
#
##-----------------------------------------------------------------------------
## dummy structure for various tools and utilities
##-----------------------------------------------------------------------------
#struct Tools {int index;};
#
#typedef struct fz_item fz_item;
#
#struct fz_item
#{
# void *key;
# fz_storable *val;
# size_t size;
# fz_item *next;
# fz_item *prev;
# fz_store *store;
# const fz_store_type *type;
#};
#
#struct fz_store
#{
# int refs;
#
# /* Every item in the store is kept in a doubly linked list, ordered
# * by usage (so LRU entries are at the end). */
# fz_item *head;
# fz_item *tail;
#
# /* We have a hash table that allows to quickly find a subset of the
# * entries (those whose keys are indirect objects). */
# fz_hash_table *hash;
#
# /* We keep track of the size of the store, and keep it below max. */
# size_t max;
# size_t size;
#
# int defer_reap_count;
# int needs_reaping;
#};
#
#
#
#
##-----------------------------------------------------------------------------
## pixmap helper functions
##-----------------------------------------------------------------------------
#
##-----------------------------------------------------------------------------
## Clear a pixmap rectangle - my version also supports non-alpha pixmaps
##-----------------------------------------------------------------------------
#int
#JM_clear_pixmap_rect_with_value(fz_context *ctx, fz_pixmap *dest, int value, fz_irect b)
#{
# unsigned char *destp;