forked from pymupdf/PyMuPDF
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextra.i
4285 lines (3907 loc) · 137 KB
/
extra.i
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
%module fitz_extra
%pythoncode %{
# pylint: disable=all
%}
%begin
%{
#define SWIG_PYTHON_INTERPRETER_NO_DEBUG
/* This seems to be necessary on some Windows machines with Py_LIMITED_API,
otherwise compilation can fail because free() and malloc() are not declared. */
#include <stdlib.h>
%}
%init
%{
/* Initialise some globals that require Python functions.
[Prior to 2023-08-18 we initialised these global variables inline,
but this causes a SEGV on Windows with Python-3.10 for `dictkey_c`
(actually any string of length 1 failed).] */
dictkey_align = PyUnicode_InternFromString("align");
dictkey_ascender = PyUnicode_InternFromString("ascender");
dictkey_bidi = PyUnicode_InternFromString("bidi");
dictkey_bbox = PyUnicode_InternFromString("bbox");
dictkey_blocks = PyUnicode_InternFromString("blocks");
dictkey_bpc = PyUnicode_InternFromString("bpc");
dictkey_c = PyUnicode_InternFromString("c");
dictkey_chars = PyUnicode_InternFromString("chars");
dictkey_color = PyUnicode_InternFromString("color");
dictkey_colorspace = PyUnicode_InternFromString("colorspace");
dictkey_content = PyUnicode_InternFromString("content");
dictkey_creationDate = PyUnicode_InternFromString("creationDate");
dictkey_cs_name = PyUnicode_InternFromString("cs-name");
dictkey_da = PyUnicode_InternFromString("da");
dictkey_dashes = PyUnicode_InternFromString("dashes");
dictkey_desc = PyUnicode_InternFromString("descender");
dictkey_descender = PyUnicode_InternFromString("descender");
dictkey_dir = PyUnicode_InternFromString("dir");
dictkey_effect = PyUnicode_InternFromString("effect");
dictkey_ext = PyUnicode_InternFromString("ext");
dictkey_filename = PyUnicode_InternFromString("filename");
dictkey_fill = PyUnicode_InternFromString("fill");
dictkey_flags = PyUnicode_InternFromString("flags");
dictkey_char_flags = PyUnicode_InternFromString("char_flags"); /* Only used with mupdf >= 1.25.2. */
dictkey_font = PyUnicode_InternFromString("font");
dictkey_glyph = PyUnicode_InternFromString("glyph");
dictkey_height = PyUnicode_InternFromString("height");
dictkey_id = PyUnicode_InternFromString("id");
dictkey_image = PyUnicode_InternFromString("image");
dictkey_items = PyUnicode_InternFromString("items");
dictkey_length = PyUnicode_InternFromString("length");
dictkey_lines = PyUnicode_InternFromString("lines");
dictkey_matrix = PyUnicode_InternFromString("transform");
dictkey_modDate = PyUnicode_InternFromString("modDate");
dictkey_name = PyUnicode_InternFromString("name");
dictkey_number = PyUnicode_InternFromString("number");
dictkey_origin = PyUnicode_InternFromString("origin");
dictkey_rect = PyUnicode_InternFromString("rect");
dictkey_size = PyUnicode_InternFromString("size");
dictkey_smask = PyUnicode_InternFromString("smask");
dictkey_spans = PyUnicode_InternFromString("spans");
dictkey_stroke = PyUnicode_InternFromString("stroke");
dictkey_style = PyUnicode_InternFromString("style");
dictkey_subject = PyUnicode_InternFromString("subject");
dictkey_text = PyUnicode_InternFromString("text");
dictkey_title = PyUnicode_InternFromString("title");
dictkey_type = PyUnicode_InternFromString("type");
dictkey_ufilename = PyUnicode_InternFromString("ufilename");
dictkey_width = PyUnicode_InternFromString("width");
dictkey_wmode = PyUnicode_InternFromString("wmode");
dictkey_xref = PyUnicode_InternFromString("xref");
dictkey_xres = PyUnicode_InternFromString("xres");
dictkey_yres = PyUnicode_InternFromString("yres");
%}
%include std_string.i
%include exception.i
%exception {
try {
$action
}
/* this might not be ok on windows.
catch (Swig::DirectorException &e) {
SWIG_fail;
}*/
catch(std::exception& e) {
SWIG_exception(SWIG_RuntimeError, e.what());
}
catch(...) {
SWIG_exception(SWIG_RuntimeError, "Unknown exception");
}
}
%{
#include "mupdf/classes2.h"
#include "mupdf/exceptions.h"
#include "mupdf/internal.h"
#include <algorithm>
#include <float.h>
#define MAKE_MUPDF_VERSION_INT(major, minor, patch) ((major << 16) + (minor << 8) + (patch << 0))
#define MUPDF_VERSION_INT MAKE_MUPDF_VERSION_INT(FZ_VERSION_MAJOR, FZ_VERSION_MINOR, FZ_VERSION_PATCH)
#define MUPDF_VERSION_GE(major, minor, patch) \
MUPDF_VERSION_INT >= MAKE_MUPDF_VERSION_INT(major, minor, patch)
/* Define a wrapper for PDF_NAME that returns a mupdf::PdfObj instead of a
pdf_obj*. This avoids implicit construction of a mupdf::PdfObj, which is
deliberately prohibited (with `explicit` on constructors) by recent MuPDF. */
#define PDF_NAME2(X) mupdf::PdfObj(PDF_NAME(X))
/* Returns equivalent of `repr(x)`. */
static std::string repr(PyObject* x)
{
PyObject* repr = PyObject_Repr(x);
PyObject* repr_str = PyUnicode_AsEncodedString(repr, "utf-8", "~E~");
#ifdef Py_LIMITED_API
const char* repr_str_s = PyBytes_AsString(repr_str);
#else
const char* repr_str_s = PyBytes_AS_STRING(repr_str);
#endif
std::string ret = repr_str_s;
Py_DECREF(repr_str);
Py_DECREF(repr);
return ret;
}
#ifdef Py_LIMITED_API
static PyObject* PySequence_ITEM(PyObject* o, Py_ssize_t i)
{
return PySequence_GetItem(o, i);
}
static const char* PyUnicode_AsUTF8(PyObject* o)
{
static PyObject* string = nullptr;
Py_XDECREF(string);
string = PyUnicode_AsUTF8String(o);
return PyBytes_AsString(string);
}
#endif
/* These are also in pymupdf/__init__.py. */
const char MSG_BAD_ANNOT_TYPE[] = "bad annot type";
const char MSG_BAD_APN[] = "bad or missing annot AP/N";
const char MSG_BAD_ARG_INK_ANNOT[] = "arg must be seq of seq of float pairs";
const char MSG_BAD_ARG_POINTS[] = "bad seq of points";
const char MSG_BAD_BUFFER[] = "bad type: 'buffer'";
const char MSG_BAD_COLOR_SEQ[] = "bad color sequence";
const char MSG_BAD_DOCUMENT[] = "cannot open broken document";
const char MSG_BAD_FILETYPE[] = "bad filetype";
const char MSG_BAD_LOCATION[] = "bad location";
const char MSG_BAD_OC_CONFIG[] = "bad config number";
const char MSG_BAD_OC_LAYER[] = "bad layer number";
const char MSG_BAD_OC_REF[] = "bad 'oc' reference";
const char MSG_BAD_PAGEID[] = "bad page id";
const char MSG_BAD_PAGENO[] = "bad page number(s)";
const char MSG_BAD_PDFROOT[] = "PDF has no root";
const char MSG_BAD_RECT[] = "rect is infinite or empty";
const char MSG_BAD_TEXT[] = "bad type: 'text'";
const char MSG_BAD_XREF[] = "bad xref";
const char MSG_COLOR_COUNT_FAILED[] = "color count failed";
const char MSG_FILE_OR_BUFFER[] = "need font file or buffer";
const char MSG_FONT_FAILED[] = "cannot create font";
const char MSG_IS_NO_ANNOT[] = "is no annotation";
const char MSG_IS_NO_IMAGE[] = "is no image";
const char MSG_IS_NO_PDF[] = "is no PDF";
const char MSG_IS_NO_DICT[] = "object is no PDF dict";
const char MSG_PIX_NOALPHA[] = "source pixmap has no alpha";
const char MSG_PIXEL_OUTSIDE[] = "pixel(s) outside image";
#define JM_BOOL(x) PyBool_FromLong((long) (x))
static PyObject *JM_UnicodeFromStr(const char *c);
#ifdef _WIN32
/* These functions are not provided on Windows. */
int vasprintf(char** str, const char* fmt, va_list ap)
{
va_list ap2;
va_copy(ap2, ap);
int len = vsnprintf(nullptr, 0, fmt, ap2);
va_end(ap2);
char* buffer = (char*) malloc(len + 1);
if (!buffer)
{
*str = nullptr;
return -1;
}
va_copy(ap2, ap);
int len2 = vsnprintf(buffer, len + 1, fmt, ap2);
va_end(ap2);
assert(len2 == len);
*str = buffer;
return len;
}
int asprintf(char** str, const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
int ret = vasprintf(str, fmt, ap);
va_end(ap);
return ret;
}
#endif
static void messagev(const char* format, va_list va)
{
static PyObject* pymupdf_module = PyImport_ImportModule("pymupdf");
static PyObject* message_fn = PyObject_GetAttrString(pymupdf_module, "message");
char* text;
vasprintf(&text, format, va);
PyObject* text_py = PyString_FromString(text);
PyObject* args = PyTuple_Pack(1, text_py);
PyObject* ret = PyObject_CallObject(message_fn, args);
Py_XDECREF(ret);
Py_XDECREF(args);
Py_XDECREF(text_py);
free(text);
}
static void messagef(const char* format, ...)
{
va_list args;
va_start(args, format);
messagev(format, args);
va_end(args);
}
PyObject* JM_EscapeStrFromStr(const char* c)
{
if (!c) return PyUnicode_FromString("");
PyObject* val = PyUnicode_DecodeRawUnicodeEscape(c, (Py_ssize_t) strlen(c), "replace");
if (!val)
{
val = PyUnicode_FromString("");
PyErr_Clear();
}
return val;
}
PyObject* JM_EscapeStrFromBuffer(fz_buffer* buff)
{
if (!buff) return PyUnicode_FromString("");
unsigned char* s = nullptr;
size_t len = mupdf::ll_fz_buffer_storage(buff, &s);
PyObject* val = PyUnicode_DecodeRawUnicodeEscape((const char*) s, (Py_ssize_t) len, "replace");
if (!val)
{
val = PyUnicode_FromString("");
PyErr_Clear();
}
return val;
}
//----------------------------------------------------------------------------
// Deep-copies a source page to the target.
// Modified version of function of pdfmerge.c: we also copy annotations, but
// we skip some subtypes. In addition we rotate output.
//----------------------------------------------------------------------------
static void page_merge(
mupdf::PdfDocument& doc_des,
mupdf::PdfDocument& doc_src,
int page_from,
int page_to,
int rotate,
int links,
int copy_annots,
mupdf::PdfGraftMap& graft_map
)
{
// list of object types (per page) we want to copy
/* Fixme: on linux these get destructed /after/
mupdf/platform/c++/implementation/internal.cpp:s_thread_state, which causes
problems - s_thread_state::m_ctx will have been freed. We have a hack
that sets s_thread_state::m_ctx when destructed, so it mostly works when
s_thread_state.get_context() is called after destruction, but this causes
memento leaks and is clearly incorrect.
Perhaps we could use pdf_obj* known_page_objs[] = {...} and create PdfObj
wrappers as used - this would avoid any cleanup at exit. And it's a general
solution to problem of ordering of cleanup of globals.
*/
static 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 known_page_objs_num = sizeof(known_page_objs) / sizeof(known_page_objs[0]);
mupdf::PdfObj page_ref = mupdf::pdf_lookup_page_obj(doc_src, page_from);
// make new page dict in dest doc
mupdf::PdfObj page_dict = mupdf::pdf_new_dict(doc_des, 4);
mupdf::pdf_dict_put(page_dict, PDF_NAME2(Type), PDF_NAME2(Page));
for (int i = 0; i < known_page_objs_num; ++i)
{
mupdf::PdfObj known_page_obj(known_page_objs[i]);
mupdf::PdfObj obj = mupdf::pdf_dict_get_inheritable(page_ref, known_page_obj);
if (obj.m_internal)
{
mupdf::pdf_dict_put(
page_dict,
known_page_obj,
mupdf::pdf_graft_mapped_object(graft_map, obj)
);
}
}
// Copy annotations, but skip Link, Popup, IRT, Widget types
// If selected, remove dict keys P (parent) and Popup
if (copy_annots)
{
mupdf::PdfObj old_annots = mupdf::pdf_dict_get(page_ref, PDF_NAME2(Annots));
int n = mupdf::pdf_array_len(old_annots);
if (n > 0)
{
mupdf::PdfObj new_annots = mupdf::pdf_dict_put_array(page_dict, PDF_NAME2(Annots), n);
for (int i = 0; i < n; i++)
{
mupdf::PdfObj o = mupdf::pdf_array_get(old_annots, i);
if (!o.m_internal || !mupdf::pdf_is_dict(o)) // skip non-dict items
{
continue; // skip invalid/null/non-dict items
}
if (mupdf::pdf_dict_get(o, PDF_NAME2(IRT)).m_internal) continue;
mupdf::PdfObj subtype = mupdf::pdf_dict_get(o, PDF_NAME2(Subtype));
if (mupdf::pdf_name_eq(subtype, PDF_NAME2(Link))) continue;
if (mupdf::pdf_name_eq(subtype, PDF_NAME2(Popup))) continue;
if (mupdf::pdf_name_eq(subtype, PDF_NAME2(Widget))) continue;
mupdf::pdf_dict_del(o, PDF_NAME2(Popup));
mupdf::pdf_dict_del(o, PDF_NAME2(P));
mupdf::PdfObj copy_o = mupdf::pdf_graft_mapped_object(graft_map, o);
mupdf::PdfObj annot = mupdf::pdf_new_indirect(
doc_des,
mupdf::pdf_to_num(copy_o),
0
);
mupdf::pdf_array_push(new_annots, annot);
}
}
}
// rotate the page
if (rotate != -1)
{
mupdf::pdf_dict_put_int(page_dict, PDF_NAME2(Rotate), rotate);
}
// Now add the page dictionary to dest PDF
mupdf::PdfObj ref = mupdf::pdf_add_object(doc_des, page_dict);
// Insert new page at specified location
mupdf::pdf_insert_page(doc_des, page_to, ref);
}
//-----------------------------------------------------------------------------
// 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.
//-----------------------------------------------------------------------------
static void JM_merge_range(
mupdf::PdfDocument& doc_des,
mupdf::PdfDocument& doc_src,
int spage,
int epage,
int apage,
int rotate,
int links,
int annots,
int show_progress,
mupdf::PdfGraftMap& graft_map
)
{
int afterpage = apage;
int counter = 0; // copied pages counter
int total = mupdf::ll_fz_absi(epage - spage) + 1; // total pages to copy
if (spage < epage)
{
for (int page = spage; page <= epage; page++, afterpage++)
{
page_merge(doc_des, doc_src, page, afterpage, rotate, links, annots, graft_map);
counter++;
if (show_progress > 0 && counter % show_progress == 0)
{
messagef("Inserted %i of %i pages.", counter, total);
}
}
}
else
{
for (int page = spage; page >= epage; page--, afterpage++)
{
page_merge(doc_des, doc_src, page, afterpage, rotate, links, annots, graft_map);
counter++;
if (show_progress > 0 && counter % show_progress == 0)
{
messagef("Inserted %i of %i pages.", counter, total);
}
}
}
}
static bool JM_have_operation(mupdf::PdfDocument& pdf)
{
// Ensure valid journalling state
if (pdf.m_internal->journal and !mupdf::pdf_undoredo_step(pdf, 0))
{
return 0;
}
return 1;
}
static void JM_ensure_operation(mupdf::PdfDocument& pdf)
{
if (!JM_have_operation(pdf))
{
throw std::runtime_error("No journalling operation started");
}
}
static void FzDocument_insert_pdf(
mupdf::FzDocument& doc,
mupdf::FzDocument& src,
int from_page,
int to_page,
int start_at,
int rotate,
int links,
int annots,
int show_progress,
int final,
mupdf::PdfGraftMap& graft_map
)
{
//std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "\n";
mupdf::PdfDocument pdfout = mupdf::pdf_specifics(doc);
mupdf::PdfDocument pdfsrc = mupdf::pdf_specifics(src);
int outCount = mupdf::fz_count_pages(doc);
int srcCount = mupdf::fz_count_pages(src);
// local copies of page numbers
int fp = from_page;
int tp = to_page;
int sa = start_at;
// normalize page numbers
fp = std::max(fp, 0); // -1 = first page
fp = std::min(fp, srcCount - 1); // but do not exceed last page
if (tp < 0) tp = srcCount - 1; // -1 = last page
tp = std::min(tp, srcCount - 1); // but do not exceed last page
if (sa < 0) sa = outCount; // -1 = behind last page
sa = std::min(sa, outCount); // but that is also the limit
if (!pdfout.m_internal || !pdfsrc.m_internal)
{
throw std::runtime_error("source or target not a PDF");
}
JM_ensure_operation(pdfout);
JM_merge_range(pdfout, pdfsrc, fp, tp, sa, rotate, links, annots, show_progress, graft_map);
}
static int page_xref(mupdf::FzDocument& this_doc, int pno)
{
int page_count = mupdf::fz_count_pages(this_doc);
int n = pno;
while (n < 0)
{
n += page_count;
}
mupdf::PdfDocument pdf = mupdf::pdf_specifics(this_doc);
assert(pdf.m_internal);
int xref = 0;
if (n >= page_count)
{
throw std::runtime_error(MSG_BAD_PAGENO);//, PyExc_ValueError);
}
xref = mupdf::pdf_to_num(mupdf::pdf_lookup_page_obj(pdf, n));
return xref;
}
static void _newPage(mupdf::PdfDocument& pdf, int pno=-1, float width=595, float height=842)
{
if (!pdf.m_internal)
{
throw std::runtime_error("is no PDF");
}
mupdf::FzRect mediabox(0, 0, width, height);
if (pno < -1)
{
throw std::runtime_error("bad page number(s)"); // Should somehow be Python ValueError
}
JM_ensure_operation(pdf);
// create /Resources and /Contents objects
mupdf::PdfObj resources = mupdf::pdf_add_new_dict(pdf, 1);
mupdf::FzBuffer contents;
mupdf::PdfObj page_obj = mupdf::pdf_add_page(pdf, mediabox, 0, resources, contents);
mupdf::pdf_insert_page(pdf, pno, page_obj);
}
static void _newPage(mupdf::FzDocument& self, int pno=-1, float width=595, float height=842)
{
mupdf::PdfDocument pdf = mupdf::pdf_specifics(self);
_newPage(pdf, pno, width, height);
}
//------------------------------------------------------------------------
// return the annotation names (list of /NM entries)
//------------------------------------------------------------------------
static std::vector< std::string> JM_get_annot_id_list(mupdf::PdfPage& page)
{
std::vector< std::string> names;
mupdf::PdfObj annots = mupdf::pdf_dict_get(page.obj(), PDF_NAME2(Annots));
if (!annots.m_internal) return names;
int n = mupdf::pdf_array_len(annots);
for (int i = 0; i < n; i++)
{
mupdf::PdfObj annot_obj = mupdf::pdf_array_get(annots, i);
mupdf::PdfObj name = mupdf::pdf_dict_gets(annot_obj, "NM");
if (name.m_internal)
{
names.push_back(mupdf::pdf_to_text_string(name));
}
}
return names;
}
//------------------------------------------------------------------------
// Add a unique /NM key to an annotation or widget.
// Append a number to 'stem' such that the result is a unique name.
//------------------------------------------------------------------------
static void JM_add_annot_id(mupdf::PdfAnnot& annot, const char* stem)
{
mupdf::PdfPage page = mupdf::pdf_annot_page(annot);
mupdf::PdfObj annot_obj = mupdf::pdf_annot_obj(annot);
std::vector< std::string> names = JM_get_annot_id_list(page);
char* stem_id = nullptr;
for (int i=0; ; ++i)
{
free(stem_id);
asprintf(&stem_id, "fitz-%s%d", stem, i);
if (std::find(names.begin(), names.end(), stem_id) == names.end())
{
break;
}
}
mupdf::PdfObj name = mupdf::pdf_new_string(stem_id, strlen(stem_id));
free(stem_id);
mupdf::pdf_dict_puts(annot_obj, "NM", name);
page.m_internal->doc->resynth_required = 0;
}
//----------------------------------------------------------------
// page add_caret_annot
//----------------------------------------------------------------
static mupdf::PdfAnnot _add_caret_annot(mupdf::PdfPage& page, mupdf::FzPoint& point)
{
mupdf::PdfAnnot annot = mupdf::pdf_create_annot(page, ::PDF_ANNOT_CARET);
mupdf::FzPoint p = point;
mupdf::FzRect r = mupdf::pdf_annot_rect(annot);
r = mupdf::fz_make_rect(p.x, p.y, p.x + r.x1 - r.x0, p.y + r.y1 - r.y0);
mupdf::pdf_set_annot_rect(annot, r);
mupdf::pdf_update_annot(annot);
JM_add_annot_id(annot, "A");
return annot;
}
static mupdf::PdfAnnot _add_caret_annot(mupdf::FzPage& page, mupdf::FzPoint& point)
{
mupdf::PdfPage pdf_page = mupdf::pdf_page_from_fz_page(page);
return _add_caret_annot(pdf_page, point);
}
static const char* Tools_parse_da(mupdf::PdfAnnot& this_annot)
{
const char* da_str = nullptr;
mupdf::PdfObj this_annot_obj = mupdf::pdf_annot_obj(this_annot);
mupdf::PdfDocument pdf = mupdf::pdf_get_bound_document(this_annot_obj);
try
{
mupdf::PdfObj da = mupdf::pdf_dict_get_inheritable(this_annot_obj, PDF_NAME2(DA));
if (!da.m_internal)
{
mupdf::PdfObj trailer = mupdf::pdf_trailer(pdf);
da = mupdf::pdf_dict_getl(
&trailer,
PDF_NAME(Root),
PDF_NAME(AcroForm),
PDF_NAME(DA),
nullptr
);
}
da_str = mupdf::pdf_to_text_string(da);
}
catch (std::exception&)
{
return nullptr;
}
return da_str;
}
//----------------------------------------------------------------------------
// Turn fz_buffer into a Python bytes object
//----------------------------------------------------------------------------
static PyObject* JM_BinFromBuffer(fz_buffer* buffer)
{
if (!buffer)
{
return PyBytes_FromStringAndSize("", 0);
}
unsigned char* c = nullptr;
size_t len = mupdf::ll_fz_buffer_storage(buffer, &c);
return PyBytes_FromStringAndSize((const char*) c, len);
}
static PyObject* JM_BinFromBuffer(mupdf::FzBuffer& buffer)
{
return JM_BinFromBuffer( buffer.m_internal);
}
static PyObject* Annot_getAP(mupdf::PdfAnnot& annot)
{
mupdf::PdfObj annot_obj = mupdf::pdf_annot_obj(annot);
mupdf::PdfObj ap = mupdf::pdf_dict_getl(
&annot_obj,
PDF_NAME(AP),
PDF_NAME(N),
nullptr
);
if (mupdf::pdf_is_stream(ap))
{
mupdf::FzBuffer res = mupdf::pdf_load_stream(ap);
return JM_BinFromBuffer(res);
}
return PyBytes_FromStringAndSize("", 0);
}
void Tools_update_da(mupdf::PdfAnnot& this_annot, const char* da_str)
{
mupdf::PdfObj this_annot_obj = mupdf::pdf_annot_obj(this_annot);
mupdf::pdf_dict_put_text_string(this_annot_obj, PDF_NAME2(DA), da_str);
mupdf::pdf_dict_del(this_annot_obj, PDF_NAME2(DS)); /* not supported */
mupdf::pdf_dict_del(this_annot_obj, PDF_NAME2(RC)); /* not supported */
}
static int
jm_float_item(PyObject* obj, Py_ssize_t idx, double* result)
{
PyObject* temp = PySequence_ITEM(obj, idx);
if (!temp) return 1;
*result = PyFloat_AsDouble(temp);
Py_DECREF(temp);
if (PyErr_Occurred())
{
PyErr_Clear();
return 1;
}
return 0;
}
static mupdf::FzPoint JM_point_from_py(PyObject* p)
{
fz_point p0 = fz_make_point(FZ_MIN_INF_RECT, FZ_MIN_INF_RECT);
if (!p || !PySequence_Check(p) || PySequence_Size(p) != 2)
{
return p0;
}
double x;
double y;
if (jm_float_item(p, 0, &x) == 1) return p0;
if (jm_float_item(p, 1, &y) == 1) return p0;
if (x < FZ_MIN_INF_RECT) x = FZ_MIN_INF_RECT;
if (y < FZ_MIN_INF_RECT) y = FZ_MIN_INF_RECT;
if (x > FZ_MAX_INF_RECT) x = FZ_MAX_INF_RECT;
if (y > FZ_MAX_INF_RECT) y = FZ_MAX_INF_RECT;
return fz_make_point(x, y);
}
static int s_list_append_drop(PyObject* list, PyObject* item)
{
if (!list || !PyList_Check(list) || !item)
{
return -2;
}
int rc = PyList_Append(list, item);
Py_DECREF(item);
return rc;
}
static int LIST_APPEND_DROP(PyObject *list, PyObject *item)
{
if (!list || !PyList_Check(list) || !item) return -2;
int rc = PyList_Append(list, item);
Py_DECREF(item);
return rc;
}
static int LIST_APPEND(PyObject *list, PyObject *item)
{
if (!list || !PyList_Check(list) || !item) return -2;
int rc = PyList_Append(list, item);
return rc;
}
static int DICT_SETITEM_DROP(PyObject *dict, PyObject *key, PyObject *value)
{
if (!dict || !PyDict_Check(dict) || !key || !value) return -2;
int rc = PyDict_SetItem(dict, key, value);
Py_DECREF(value);
return rc;
}
static int DICT_SETITEMSTR_DROP(PyObject *dict, const char *key, PyObject *value)
{
if (!dict || !PyDict_Check(dict) || !key || !value) return -2;
int rc = PyDict_SetItemString(dict, key, value);
Py_DECREF(value);
return rc;
}
//-----------------------------------------------------------------------------
// Functions converting between PySequences and pymupdf geometry objects
//-----------------------------------------------------------------------------
static int
jm_init_item(PyObject* obj, Py_ssize_t idx, int* result)
{
PyObject* temp = PySequence_ITEM(obj, idx);
if (!temp)
{
return 1;
}
if (PyLong_Check(temp))
{
*result = (int) PyLong_AsLong(temp);
Py_DECREF(temp);
}
else if (PyFloat_Check(temp))
{
*result = (int) PyFloat_AsDouble(temp);
Py_DECREF(temp);
}
else
{
Py_DECREF(temp);
return 1;
}
if (PyErr_Occurred())
{
PyErr_Clear();
return 1;
}
return 0;
}
// TODO: ------------------------------------------------------------------
// This is a temporary solution and should be replaced by a C++ extension:
// There is no way in Python specify an array of fz_point - as is required
// for function pdf_set_annot_callout_line().
static void JM_set_annot_callout_line(mupdf::PdfAnnot& annot, PyObject *callout, int count)
{
fz_point points[3];
mupdf::FzPoint p;
for (int i = 0; i < count; i++)
{
p = JM_point_from_py(PyTuple_GetItem(callout, (Py_ssize_t) i));
points[i] = fz_make_point(p.x, p.y);
}
mupdf::pdf_set_annot_callout_line(annot, points, count);
}
//----------------------------------------------------------------------------
// Return list of outline xref numbers. Recursive function. Arguments:
// 'obj' first OL item
// 'xrefs' empty Python list
//----------------------------------------------------------------------------
static PyObject* JM_outline_xrefs(mupdf::PdfObj obj, PyObject* xrefs)
{
if (!obj.m_internal)
{
return xrefs;
}
PyObject* newxref = nullptr;
mupdf::PdfObj thisobj = obj;
while (thisobj.m_internal)
{
int nxr = mupdf::pdf_to_num(thisobj);
newxref = PyLong_FromLong((long) nxr);
if (PySequence_Contains(xrefs, newxref)
or mupdf::pdf_dict_get(thisobj, PDF_NAME2(Type)).m_internal
)
{
// circular ref or top of chain: terminate
Py_DECREF(newxref);
break;
}
s_list_append_drop(xrefs, newxref);
mupdf::PdfObj first = mupdf::pdf_dict_get(thisobj, PDF_NAME2(First)); // try go down
if (mupdf::pdf_is_dict(first))
{
xrefs = JM_outline_xrefs(first, xrefs);
}
thisobj = mupdf::pdf_dict_get(thisobj, PDF_NAME2(Next)); // try go next
mupdf::PdfObj parent = mupdf::pdf_dict_get(thisobj, PDF_NAME2(Parent)); // get parent
if (!mupdf::pdf_is_dict(thisobj))
{
thisobj = parent;
}
}
return xrefs;
}
PyObject* dictkey_align = NULL;
PyObject* dictkey_ascender = NULL;
PyObject* dictkey_bidi = NULL;
PyObject* dictkey_bbox = NULL;
PyObject* dictkey_blocks = NULL;
PyObject* dictkey_bpc = NULL;
PyObject* dictkey_c = NULL;
PyObject* dictkey_chars = NULL;
PyObject* dictkey_color = NULL;
PyObject* dictkey_colorspace = NULL;
PyObject* dictkey_content = NULL;
PyObject* dictkey_creationDate = NULL;
PyObject* dictkey_cs_name = NULL;
PyObject* dictkey_da = NULL;
PyObject* dictkey_dashes = NULL;
PyObject* dictkey_desc = NULL;
PyObject* dictkey_descender = NULL;
PyObject* dictkey_dir = NULL;
PyObject* dictkey_effect = NULL;
PyObject* dictkey_ext = NULL;
PyObject* dictkey_filename = NULL;
PyObject* dictkey_fill = NULL;
PyObject* dictkey_flags = NULL;
PyObject* dictkey_char_bidi = NULL;
PyObject* dictkey_char_flags = NULL;
PyObject* dictkey_font = NULL;
PyObject* dictkey_glyph = NULL;
PyObject* dictkey_height = NULL;
PyObject* dictkey_id = NULL;
PyObject* dictkey_image = NULL;
PyObject* dictkey_items = NULL;
PyObject* dictkey_length = NULL;
PyObject* dictkey_lines = NULL;
PyObject* dictkey_matrix = NULL;
PyObject* dictkey_modDate = NULL;
PyObject* dictkey_name = NULL;
PyObject* dictkey_number = NULL;
PyObject* dictkey_origin = NULL;
PyObject* dictkey_rect = NULL;
PyObject* dictkey_size = NULL;
PyObject* dictkey_smask = NULL;
PyObject* dictkey_spans = NULL;
PyObject* dictkey_stroke = NULL;
PyObject* dictkey_style = NULL;
PyObject* dictkey_subject = NULL;
PyObject* dictkey_text = NULL;
PyObject* dictkey_title = NULL;
PyObject* dictkey_type = NULL;
PyObject* dictkey_ufilename = NULL;
PyObject* dictkey_width = NULL;
PyObject* dictkey_wmode = NULL;
PyObject* dictkey_xref = NULL;
PyObject* dictkey_xres = NULL;
PyObject* dictkey_yres = NULL;
static int dict_setitem_drop(PyObject* dict, PyObject* key, PyObject* value)
{
if (!dict || !PyDict_Check(dict) || !key || !value)
{
return -2;
}
int rc = PyDict_SetItem(dict, key, value);
Py_DECREF(value);
return rc;
}
static int dict_setitemstr_drop(PyObject* dict, const char* key, PyObject* value)
{
if (!dict || !PyDict_Check(dict) || !key || !value)
{
return -2;
}
int rc = PyDict_SetItemString(dict, key, value);
Py_DECREF(value);
return rc;
}
static void Document_extend_toc_items(mupdf::PdfDocument& pdf, PyObject* items)
{
PyObject* item=nullptr;
PyObject* itemdict=nullptr;
PyObject* xrefs=nullptr;
PyObject* bold = PyUnicode_FromString("bold");
PyObject* italic = PyUnicode_FromString("italic");
PyObject* collapse = PyUnicode_FromString("collapse");
PyObject* zoom = PyUnicode_FromString("zoom");
try
{
/* Need to define these things early because later code uses
`goto`; otherwise we get compiler warnings 'jump bypasses variable
initialization' */
int xref = 0;
mupdf::PdfObj root;
mupdf::PdfObj olroot;
mupdf::PdfObj first;
Py_ssize_t n;
Py_ssize_t m;
root = mupdf::pdf_dict_get(mupdf::pdf_trailer(pdf), PDF_NAME2(Root));
if (!root.m_internal) goto end;
olroot = mupdf::pdf_dict_get(root, PDF_NAME2(Outlines));
if (!olroot.m_internal) goto end;
first = mupdf::pdf_dict_get(olroot, PDF_NAME2(First));
if (!first.m_internal) goto end;
xrefs = PyList_New(0); // pre-allocate an empty list
xrefs = JM_outline_xrefs(first, xrefs);
n = PySequence_Size(xrefs);
m = PySequence_Size(items);
if (!n) goto end;
if (n != m)
{
throw std::runtime_error("internal error finding outline xrefs");
}
// update all TOC item dictionaries
for (int i = 0; i < n; i++)
{
jm_init_item(xrefs, i, &xref);
item = PySequence_ITEM(items, i);
itemdict = PySequence_ITEM(item, 3);
if (!itemdict || !PyDict_Check(itemdict))
{
throw std::runtime_error("need non-simple TOC format");
}
PyDict_SetItem(itemdict, dictkey_xref, PySequence_ITEM(xrefs, i));
mupdf::PdfObj bm = mupdf::pdf_load_object(pdf, xref);
int flags = mupdf::pdf_to_int(mupdf::pdf_dict_get(bm, PDF_NAME2(F)));
if (flags == 1)
{
PyDict_SetItem(itemdict, italic, Py_True);
}
else if (flags == 2)
{
PyDict_SetItem(itemdict, bold, Py_True);
}
else if (flags == 3)
{
PyDict_SetItem(itemdict, italic, Py_True);
PyDict_SetItem(itemdict, bold, Py_True);
}
int count = mupdf::pdf_to_int(mupdf::pdf_dict_get(bm, PDF_NAME2(Count)));
if (count < 0)
{
PyDict_SetItem(itemdict, collapse, Py_True);
}
else if (count > 0)
{
PyDict_SetItem(itemdict, collapse, Py_False);
}
mupdf::PdfObj col = mupdf::pdf_dict_get(bm, PDF_NAME2(C));