This repository has been archived by the owner on Jan 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
main.cc
1829 lines (1719 loc) · 52.6 KB
/
main.cc
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
/* Copyright © 2007-2022 Jakub Wilk <[email protected]>
* Copyright © 2009 Mateusz Turcza
*
* This file is part of pdf2djvu.
*
* pdf2djvu is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* pdf2djvu is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
#include <algorithm>
#include <cassert>
#include <cerrno>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <memory>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#if _OPENMP
#include <omp.h>
#endif
#include "config.hh"
#include "debug.hh"
#include "djvu-const.hh"
#include "djvu-outline.hh"
#include "i18n.hh"
#include "image-filter.hh"
#include "paths.hh"
#include "pdf-backend.hh"
#include "pdf-document-map.hh"
#include "pdf-dpi.hh"
#include "pdf-unicode.hh"
#include "sexpr.hh"
#include "string-format.hh"
#include "string-printf.hh"
#include "string-utils.hh"
#include "system.hh"
#include "version.hh"
#include "xmp.hh"
#ifdef USE_HEAP_PROFILING
#include <gperftools/heap-profiler.h>
#endif
static Config config;
static inline DebugStream &debug(int n)
{
return debug(n, config.verbose);
}
class NoLinkDestination : public std::runtime_error
{
public:
NoLinkDestination()
: std::runtime_error(_("Cannot find link destination"))
{ }
};
static int get_page_for_goto_link(pdf::link::GoTo *goto_link, pdf::Catalog *catalog)
{
std::unique_ptr<pdf::link::Destination> dest;
#if POPPLER_VERSION >= 6400
const
#endif
pdf::link::Destination *orig_dest = goto_link->getDest();
if (orig_dest == nullptr)
{
#if POPPLER_VERSION >= 8600
dest = catalog->findDest(goto_link->getNamedDest());
#else
dest.reset(catalog->findDest(goto_link->getNamedDest()));
#endif
}
else
dest.reset(new pdf::link::Destination(*orig_dest));
if (dest.get() != nullptr)
{
int page;
if (dest->isPageRef())
{
pdf::Ref pageref = dest->getPageRef();
page = pdf::find_page(catalog, pageref);
}
else
page = dest->getPageNum();
return page;
}
else
throw NoLinkDestination();
}
static bool is_foreground_color_map(pdf::gfx::ImageColorMap *color_map)
{
return (color_map->getNumPixelComps() <= 1 && color_map->getBits() <= 1);
}
class PageMap : protected std::map<int, int>
{
protected:
int max;
public:
PageMap()
{
this->max = std::numeric_limits<int>::min();
}
int get_max() const
{
return this->max;
}
int get(int n) const
{
const_iterator it = this->find(n);
if (it == this->end())
throw std::logic_error(_("Page not found"));
return it->second;
}
int get(int n, int m) const
{
const_iterator it = this->find(n);
if (it == this->end())
return m;
return it->second;
}
void set(int n, int m)
{
if (m > this->max)
this->max = m;
(*this)[n] = m;
}
};
class Component
{
protected:
std::string title;
bool title_set;
File *file;
public:
explicit Component(File &file, const std::string &title = "")
: title(title), title_set(false),
file(&file)
{
file.close();
}
Component(const Component &component)
: title(component.title),
title_set(component.title_set),
file(component.file)
{
}
const std::string & get_title() const
{
assert(this->title_set);
return this->title;
}
const std::string & set_title(const std::string &title)
{
this->title = title;
// TODO: issue a warning if the title contains null bytes
string::replace_all(
this->title, '\0',
"\xEF\xBF\xBD" // U+FFFD REPLACEMENT CHARACTER
);
this->title_set = true;
return this->title;
}
const std::string & get_basename() const
{
return this->file->get_basename();
}
std::streamoff size()
{
std::streamoff result;
this->file->reopen();
result = this->file->size();
this->file->close();
return result;
}
friend std::ostream &operator <<(std::ostream &, const Component &);
friend Command &operator <<(Command &, const Component &);
};
Command &operator <<(Command &command, const Component &component)
{
command << *component.file;
return command;
}
std::ostream &operator <<(std::ostream &stream, const Component &component)
{
stream << *component.file;
return stream;
}
class ComponentList
{
protected:
std::vector<File*> files;
std::vector<Component*> components;
const PageMap &page_map;
ComponentList(int n, const PageMap &page_map)
: files(n), components(n), page_map(page_map)
{ }
void clean_files()
{
for (auto &component : this->components)
{
delete component;
component = nullptr;
}
for (auto &file : this->files)
{
delete file;
file = nullptr;
}
}
string_format::Bindings get_bindings(int n) const
{
string_format::Bindings bindings;
bindings["max_spage"] = this->files.size();
bindings["spage"] = n;
bindings["max_page"] = this->files.size();
bindings["page"] = n;
bindings["max_dpage"] = this->page_map.get_max();
bindings["dpage"] = this->page_map.get(n, 0);
return bindings;
}
virtual File *create_file(const std::string &id)
= 0;
public:
std::string get_title(int n, const std::string &label) const
{
string_format::Bindings bindings = this->get_bindings(n);
bindings["label"] = label;
return config.page_title_template->format(bindings);
}
virtual Component &operator[](int n)
{
std::vector<Component*>::reference tmpfile_ptr = this->components.at(n - 1);
if (tmpfile_ptr == nullptr)
{
this->files[n - 1] = this->create_file(this->get_file_name(n));
tmpfile_ptr = new Component(*this->files[n - 1]);
}
return *tmpfile_ptr;
}
std::string get_file_name(int n) const
{
string_format::Bindings bindings = this->get_bindings(n);
return config.page_id_template->format(bindings);
}
virtual ~ComponentList()
{
this->clean_files();
}
};
typedef pdf::Renderer MainRenderer;
class MutedRenderer: public pdf::Renderer
{
protected:
std::unique_ptr<std::ostringstream> text_comments;
std::vector<sexpr::Ref> annotations;
const ComponentList &page_files;
bool skipped_elements;
void add_text_comment(int ox, int oy, int dx, int dy, int x, int y, int w, int h, const Unicode *unistr, int len)
{
while (len > 0 && *unistr == ' ')
{
unistr++;
len--;
}
if (len == 0)
return;
*(this->text_comments)
<< std::dec << std::noshowpos
<< "\x01 \x02 " /* special characters will be replaced later */
<< ox << ":" << oy << " "
<< dx << ":" << dy << " "
<< w << "\x03" << h << std::showpos << x << y << " "
<< "("
<< std::oct;
for (; len > 0; len--, unistr++)
{
if (*unistr < 0x20 || *unistr == ')' || *unistr == '\\')
*(this->text_comments) << "\\" << std::setw(3) << static_cast<unsigned int>(*unistr);
else
pdf::write_as_utf8(*(this->text_comments), *unistr);
}
*(this->text_comments) << ")" << std::endl;
}
public:
bool needNonText()
{
return !config.no_render;
}
void drawImageMask(pdf::gfx::State *state, pdf::Object *object, pdf::Stream *stream, int width, int height,
bool invert, bool interpolate, bool inline_image)
{
this->skipped_elements = true;
return;
}
#if POPPLER_VERSION >= 8200
void drawImage(pdf::gfx::State *state, pdf::Object *object, pdf::Stream *stream, int width, int height,
pdf::gfx::ImageColorMap *color_map, bool interpolate, const int *mask_colors, bool inline_image)
#else
void drawImage(pdf::gfx::State *state, pdf::Object *object, pdf::Stream *stream, int width, int height,
pdf::gfx::ImageColorMap *color_map, bool interpolate, int *mask_colors, bool inline_image)
#endif
{
if (is_foreground_color_map(color_map) || config.no_render)
{
this->skipped_elements = true;
return;
}
Renderer::drawImage(state, object, stream, width, height, color_map,
interpolate, mask_colors, inline_image);
}
void drawMaskedImage(pdf::gfx::State *state, pdf::Object *object, pdf::Stream *stream, int width, int height,
pdf::gfx::ImageColorMap *color_map, bool interpolate,
pdf::Stream *mask_stream, int mask_width, int mask_height, bool mask_invert, bool mask_interpolate)
{
if (is_foreground_color_map(color_map) || config.no_render)
{
this->skipped_elements = true;
return;
}
Renderer::drawMaskedImage(state, object, stream, width, height,
color_map, interpolate,
mask_stream, mask_width, mask_height, mask_invert, mask_interpolate);
}
void drawSoftMaskedImage(pdf::gfx::State *state, pdf::Object *object, pdf::Stream *stream,
int width, int height, pdf::gfx::ImageColorMap *color_map, bool interpolate,
pdf::Stream *mask_stream, int mask_width, int mask_height,
pdf::gfx::ImageColorMap *mask_color_map, bool mask_interpolate)
{
if (is_foreground_color_map(color_map) || config.no_render)
{
this->skipped_elements = true;
return;
}
Renderer::drawSoftMaskedImage(state, object, stream, width, height,
color_map, interpolate,
mask_stream, mask_width, mask_height, mask_color_map, mask_interpolate);
}
bool interpretType3Chars() { return false; }
#if POPPLER_VERSION >= 8200
void drawChar(pdf::gfx::State *state, double x, double y, double dx, double dy, double origin_x, double origin_y,
CharCode code, int n_bytes, const Unicode *unistr, int length)
#else
void drawChar(pdf::gfx::State *state, double x, double y, double dx, double dy, double origin_x, double origin_y,
CharCode code, int n_bytes, Unicode *unistr, int length)
#endif
{
double pox, poy, pdx, pdy, px, py, pw, ph;
x -= origin_x; y -= origin_y;
state->transform(x, y, &pox, &poy);
state->transformDelta(dx, dy, &pdx, &pdy);
int old_render = state->getRender();
/* Setting the following rendering mode disallows drawing text, but allows
* fonts to be set up properly nevertheless:
*/
state->setRender(0x103);
this->skipped_elements = true;
this->Renderer::drawChar(state, x, y, dx, dy, origin_x, origin_y, code, n_bytes, unistr, length);
state->setRender(old_render);
pdf::splash::Font *font = this->getCurrentFont();
pdf::splash::GlyphBitmap glyph;
px = pox; py = poy;
if (pdf::get_glyph(this->getSplash(), font, pox, poy, code, &glyph))
{
px -= glyph.x;
py -= glyph.y;
pw = glyph.w;
ph = glyph.h;
}
else
{
/* Ideally, this should never happen. Some heuristics is required to
* determine character width/height: */
pw = pdx; ph = pdy;
double font_size = state->getTransformedFontSize();
if (pw * 4.0 < font_size)
pw = font_size;
if (ph * 4.0 < font_size)
ph = font_size;
py -= ph;
}
pw = std::max(pw, 1.0);
ph = std::max(ph, 1.0);
if (config.text_crop)
{
int bitmap_width = this->getBitmapWidth();
int bitmap_height = this->getBitmapHeight();
if (px + pw < 0 || py + ph < 0 || px >= bitmap_width || py >= bitmap_height)
return;
}
std::unique_ptr<pdf::NFKC> nfkc;
if (config.text_nfkc)
nfkc.reset(new pdf::FullNFKC(unistr, length));
else
nfkc.reset(new pdf::MinimalNFKC(unistr, length));
add_text_comment(
static_cast<int>(pox),
static_cast<int>(poy),
static_cast<int>(pdx),
static_cast<int>(pdy),
static_cast<int>(px),
static_cast<int>(py),
static_cast<int>(pw),
static_cast<int>(ph),
*nfkc, nfkc->length()
);
}
void draw_link(pdf::link::Link *link, const std::string &border_color)
{
if (!config.hyperlinks.extract)
return;
sexpr::Guard guard;
double x1, y1, x2, y2;
pdf::link::Action *link_action = link->getAction();
if (link_action == nullptr)
{
debug(1) << _("Warning: Unable to convert link without an action") << std::endl;
return;
}
std::string uri;
link->getRect(&x1, &y1, &x2, &y2);
switch (link_action->getKind())
{
case actionURI:
#if POPPLER_VERSION >= 8600
uri = dynamic_cast<pdf::link::URI*>(link_action)->getURI();
#else
uri += pdf::get_c_string(dynamic_cast<pdf::link::URI*>(link_action)->getURI());
#endif
break;
case actionGoTo:
{
int page;
try
{
page = get_page_for_goto_link(dynamic_cast<pdf::link::GoTo*>(link_action), this->catalog);
}
catch (const NoLinkDestination &ex)
{
debug(1) << string_printf(_("Warning: %s"), ex.what()) << std::endl;
return;
}
std::ostringstream strstream;
strstream << "#" << this->page_files.get_file_name(page);
uri = strstream.str();
break;
}
case actionGoToR:
debug(1) << _("Warning: Unable to convert link with a remote go-to action") << std::endl;
return;
case actionNamed:
debug(1) << _("Warning: Unable to convert link with a named action") << std::endl;
return;
case actionLaunch:
debug(1) << _("Warning: Unable to convert link with a launch action") << std::endl;
return;
case actionMovie:
case actionSound:
case actionRendition:
debug(1) << _("Warning: Unable to convert link with a multimedia action") << std::endl;
return;
case actionJavaScript:
debug(1) << _("Warning: Unable to convert link with a JavaScript action") << std::endl;
return;
case actionOCGState:
// L10N: OCG stands for “Optional Content Group” (see PDF Reference v1.7, §4.10.1)
debug(1) << _("Warning: Unable to convert link with a set-OCG-state action") << std::endl;
return;
#if POPPLER_VERSION >= 6400
case actionHide:
debug(1) << _("Warning: Unable to convert link with a hide action") << std::endl;
return;
#endif
#if POPPLER_VERSION >= 8900
case actionResetForm:
debug(1) << _("Warning: Unable to convert link with a reset-form action") << std::endl;
return;
#endif
case actionUnknown:
default:
debug(1) << _("Warning: Unknown link action") << std::endl;
return;
}
int x, y, w, h;
this->cvtUserToDev(x1, y1, &x, &y);
this->cvtUserToDev(x2, y2, &w, &h);
w -= x;
h = y - h;
y = this->getBitmapHeight() - y;
static sexpr::Ref symbol_xor = sexpr::symbol("xor");
static sexpr::Ref symbol_border = sexpr::symbol("border");
static sexpr::Ref symbol_rect = sexpr::symbol("rect");
static sexpr::Ref symbol_maparea = sexpr::symbol("maparea");
sexpr::Ref expr = sexpr::nil;
if (config.hyperlinks.border_always_visible)
{
static sexpr::Ref symbol_border_avis = sexpr::symbol("border_avis");
sexpr::Ref item = sexpr::cons(sexpr::symbol("border_avis"), sexpr::nil);
expr = sexpr::cons(item, expr);
}
if (config.hyperlinks.border_color.length() > 0)
{
static sexpr::Ref symbol_border = sexpr::symbol("border");
sexpr::Ref item = sexpr::cons(sexpr::symbol(config.hyperlinks.border_color), sexpr::nil);
item = sexpr::cons(symbol_border, item);
expr = sexpr::cons(item, expr);
}
else
{
sexpr::Ref bexpr = sexpr::nil;
if (border_color.empty())
bexpr = sexpr::cons(symbol_xor, bexpr);
else
{
bexpr = sexpr::cons(sexpr::symbol(border_color), bexpr);
bexpr = sexpr::cons(symbol_border, bexpr);
}
expr = sexpr::cons(bexpr, expr);
}
{
sexpr::Ref rexpr = sexpr::nil;
rexpr = sexpr::cons(sexpr::integer(h), rexpr);
rexpr = sexpr::cons(sexpr::integer(w), rexpr);
rexpr = sexpr::cons(sexpr::integer(y), rexpr);
rexpr = sexpr::cons(sexpr::integer(x), rexpr);
rexpr = sexpr::cons(symbol_rect, rexpr);
expr = sexpr::cons(rexpr, expr);
}
expr = sexpr::cons(sexpr::empty_string, expr);
expr = sexpr::cons(sexpr::string(uri), expr);
expr = sexpr::cons(symbol_maparea, expr);
annotations.push_back(expr);
}
bool useDrawChar()
{
return true;
}
void stroke(pdf::gfx::State *state)
{
this->skipped_elements = true;
}
void fill(pdf::gfx::State *state)
{
if (config.no_render)
{
this->skipped_elements = true;
return;
}
pdf::splash::Path path;
this->convert_path(state, path);
double area = pdf::get_path_area(path);
if (area / this->getBitmapHeight() / this->getBitmapWidth() >= 0.8)
Renderer::fill(state);
else
this->skipped_elements = true;
}
void eoFill(pdf::gfx::State *state)
{
this->fill(state);
}
MutedRenderer(pdf::splash::Color &paper_color, bool monochrome, const ComponentList &page_files)
: Renderer(paper_color, monochrome), page_files(page_files)
{
this->clear();
}
const std::vector<sexpr::Ref> &get_annotations() const
{
return annotations;
}
void clear_annotations()
{
annotations.clear();
}
const std::string get_texts() const
{
std::string texts = this->text_comments->str();
if (config.text_filter_command_line.length() > 0)
texts = Command::filter(config.text_filter_command_line, texts);
for (char &c : texts)
switch (c)
{
case '\x01':
c = '#'; break;
case '\x02':
c = 'T'; break;
case '\x03':
c = 'x'; break;
}
return texts;
}
void clear_texts()
{
this->text_comments.reset(new std::ostringstream);
*(this->text_comments) << std::setfill('0');
}
void clear()
{
this->skipped_elements = 0;
this->clear_texts();
this->clear_annotations();
}
bool has_skipped_elements()
{
return this->skipped_elements;
}
};
class BookmarkError : public std::runtime_error
{
public:
explicit BookmarkError(const std::string &message)
: std::runtime_error(message)
{ }
};
class NoPageForBookmark : public BookmarkError
{
public:
explicit NoPageForBookmark()
: BookmarkError(_("No page for a bookmark"))
{ }
};
class NoTitleForBookmark : public BookmarkError
{
public:
NoTitleForBookmark()
: BookmarkError(_("No title for a bookmark"))
{ }
};
static const int pdf_outline_max_depth = 0x100;
static void pdf_outline_to_djvu_outline(pdf::Object *node, pdf::Catalog *catalog,
djvu::OutlineBase &djvu_outline, const ComponentList &page_files,
int depth)
{
if (depth > pdf_outline_max_depth)
/* DjVu specification puts no limit on outline depth,
* but we want to avoid stack overflow because of very deep recursion. */
throw djvu::OutlineError();
pdf::Object current, next;
if (!pdf::dict_lookup(node, "First", ¤t)->isDict())
return;
while (current.isDict())
{
try
{
std::string title_str;
{
pdf::Object title;
if (!pdf::dict_lookup(current, "Title", &title)->isString())
throw NoTitleForBookmark();
title_str = pdf::string_as_utf8(title);
}
int page;
{
pdf::Object destination;
std::unique_ptr<pdf::link::Action> link_action;
if (!pdf::dict_lookup(current, "Dest", &destination)->isNull())
{
#if POPPLER_VERSION >= 8600
link_action = pdf::link::Action::parseDest(&destination);
#else
link_action.reset(pdf::link::Action::parseDest(&destination));
#endif
}
else if (!pdf::dict_lookup(current, "A", &destination)->isNull())
{
#if POPPLER_VERSION >= 8600
link_action = pdf::link::Action::parseAction(&destination);
#else
link_action.reset(pdf::link::Action::parseAction(&destination));
#endif
}
else
throw NoPageForBookmark();
if (link_action.get() == nullptr || link_action->getKind() != actionGoTo)
throw NoPageForBookmark();
try
{
page = get_page_for_goto_link(
dynamic_cast<pdf::link::GoTo*>(link_action.get()),
catalog
);
}
catch (const NoLinkDestination &)
{
throw NoPageForBookmark();
}
}
{
djvu::OutlineItem &djvu_outline_item = djvu_outline.add(
title_str,
std::string("#") + page_files.get_file_name(page)
);
pdf_outline_to_djvu_outline(¤t, catalog, djvu_outline_item, page_files, depth + 1);
}
}
catch (const BookmarkError &ex)
{
debug(1) << string_printf(_("Warning: %s"), ex.what()) << std::endl;
}
pdf::dict_lookup(current, "Next", &next);
current = std::move(next);
}
}
static void pdf_outline_to_djvu_outline(pdf::Document &doc, djvu::Outline &djvu_outline,
const ComponentList &page_files)
/* Convert the PDF outline to DjVu outline.
*
* Return ``true`` if the outline exist and is non-empty.
* Return ``false`` otherwise.
*/
{
pdf::Catalog *catalog = doc.getCatalog();
pdf::Object *pdf_outline = catalog->getOutline();
if (!pdf_outline->isDict())
return;
pdf_outline_to_djvu_outline(pdf_outline, catalog, djvu_outline, page_files, 0);
}
static void add_meta_string(const char *key, const std::string &value, std::ostream &stream)
{
sexpr::Ref expr = sexpr::string(value);
stream << key << "\t" << expr << std::endl;
}
static void add_meta_date(const char *key, const pdf::Timestamp &value, std::ostream &stream)
{
try
{
sexpr::Ref sexpr = sexpr::string(value.format(' '));
stream << key << "\t" << sexpr << std::endl;
}
catch (const pdf::Timestamp::Invalid &)
{
debug(1) << string_printf(_("Warning: metadata[%s] is not a valid date"), key) << std::endl;
}
}
static void pdf_metadata_to_djvu_metadata(const pdf::Metadata &metadata, std::ostream &stream)
{
metadata.iterate<std::ostream>(add_meta_string, add_meta_date, stream);
}
class TemporaryComponentList : public ComponentList
{
private:
TemporaryComponentList(const TemporaryComponentList&) = delete;
TemporaryComponentList& operator=(const TemporaryComponentList&) = delete;
protected:
std::unique_ptr<const TemporaryDirectory> directory;
std::unique_ptr<TemporaryFile> shared_ant_file;
virtual File *create_file(const std::string &page_id)
{
return new TemporaryFile(*this->directory, page_id);
}
public:
explicit TemporaryComponentList(int n, const PageMap &page_map)
: ComponentList(n, page_map),
directory(new TemporaryDirectory()),
shared_ant_file(new TemporaryFile(*directory, djvu::shared_ant_file_name))
{
shared_ant_file->write("AT&TFORM\0\0\0\4DJVI", 16);
shared_ant_file->close();
}
virtual ~TemporaryComponentList()
{
this->clean_files();
}
};
class IndirectComponentList : public ComponentList
{
private:
IndirectComponentList(const IndirectComponentList&) = delete;
IndirectComponentList& operator=(const IndirectComponentList&) = delete;
protected:
const Directory &directory;
virtual File *create_file(const std::string &page_id)
{
return new File(this->directory, page_id);
}
public:
IndirectComponentList(int n, const PageMap &page_map, const Directory &directory)
: ComponentList(n, page_map), directory(directory)
{ }
};
class DjVuCommand : public Command
{
protected:
static std::string dir_name;
static std::string full_path(const std::string &base_name)
{
return DjVuCommand::dir_name + "/" + base_name;
}
public:
explicit DjVuCommand(const std::string &base_name)
: Command(full_path(base_name))
{ }
};
#if WIN32
std::string DjVuCommand::dir_name(program_dir);
#else
std::string DjVuCommand::dir_name(paths::djvulibre_bindir);
#endif
class DuplicatePage : public std::runtime_error
{
public:
explicit DuplicatePage(int n)
: std::runtime_error(string_printf(_("Duplicate page: %d"), n))
{ }
};
class DjVm
{
protected:
std::set<std::string> known_ids;
class DuplicateId : public std::runtime_error
{
public:
explicit DuplicateId(const std::string &id)
: std::runtime_error(string_printf(_("Duplicate page identifier: %s"), id.c_str()))
{ }
};
void remember(const Component &component);
public:
virtual void add(const Component &component) = 0;
virtual void commit() = 0;
DjVm &operator <<(const Component &component)
{
this->add(component);
return *this;
}
virtual void set_outline(const djvu::Outline &outline) = 0;
virtual void set_metadata(File &metadata_sed_file) = 0;
virtual ~DjVm() { /* just to silence compilers */ }
};
void DjVm::remember(const Component &component)
{
std::string id;
id = component.get_basename();
if (this->known_ids.count(id) > 0)
throw DuplicateId(id);
this->known_ids.insert(id);
}
class IndirectDjVm;
class BundledDjVm : public DjVm
{
protected:
size_t size;
File &output_file;
DjVuCommand converter;
std::unique_ptr<IndirectDjVm> indirect_djvm;
std::unique_ptr<TemporaryFile> index_file;
public:
explicit BundledDjVm(File &output_file)
: size(0),
output_file(output_file),
converter("djvmcvt")
{ }
~BundledDjVm()
{ }
virtual void add(const Component &component);
virtual void set_outline(const djvu::Outline &outline);
virtual void set_metadata(File &metadata_sed_file);
virtual void commit();
};
class IndirectDjVm : public DjVm
{
protected:
File &index_file;
std::vector<Component> components;
bool needs_shared_ant;
std::unique_ptr<std::ostringstream> outline_stream;
class UnexpectedDjvuSedOutput : public std::runtime_error
{
public:
UnexpectedDjvuSedOutput()
: std::runtime_error(_("Unexpected output from djvused"))
{ }
};
void create_bare(const std::vector<Component> &components);
void create(const std::vector<Component> &components, bool bare=false);
public:
explicit IndirectDjVm(File &index_file)
: index_file(index_file),
needs_shared_ant(false)
{ }
virtual ~IndirectDjVm()
{ }
virtual void add(const Component &component)
{
this->remember(component);
this->components.push_back(component);
}
virtual void set_outline(const djvu::Outline &outline)
{
if (!outline)
{
this->outline_stream.reset(nullptr);
return;
}
this->outline_stream.reset(new std::ostringstream);
*this->outline_stream << outline;
}
virtual void set_metadata(File &metadata_sed_file)
{
size_t size = this->components.size();
{
/* Using ``djvused`` to add shared annotations to an indirect multi-page
* document could be unacceptably slow:
* https://sourceforge.net/p/djvu/bugs/100/
*
* We need to work around this bug.
*/
debug(3) << _("setting metadata with `djvused`") << std::endl;
std::vector<Component> dummy_components;
TemporaryFile dummy_sed_file;