Repository navigation
Expand file tree
/
Copy pathpdftextlayout.cpp
More file actions
1795 lines (1502 loc) · 61.7 KB
/
Copy pathpdftextlayout.cpp
File metadata and controls
1795 lines (1502 loc) · 61.7 KB
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
// MIT License
//
// Copyright (c) 2018-2026 Jakub Melka and Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "pdftextlayout.h"
#include "pdfutils.h"
#include "pdfexecutionpolicy.h"
#include "pdfcms.h"
#include <QtMath>
#include <QMutex>
#include <QPainter>
#include <QIODevice>
#include <QMutexLocker>
#include <QRegularExpression>
#include "pdfdbgheap.h"
#include <execution>
namespace pdf
{
/// Spatial 2D index for indexing of text characters. It is a R-tree like structure,
/// build over an array of text characters. Array is modified (structure is build over
/// array).
class PDFTextCharacterSpatialIndex
{
public:
explicit PDFTextCharacterSpatialIndex(TextCharacters* characters, size_t leafSize) :
m_characters(characters),
m_leafSize(leafSize),
m_epsilon(0.0)
{
m_nodes.reserve(2 * characters->size() / leafSize);
// Calculate epsilon from the bounding box. We must use epsilon to avoid empty
// rectangles, which can occur, if text is on a single line.
QRectF boundingBox = getBoundingBox(characters->begin(), characters->end());
if (boundingBox.isValid())
{
qreal edge = qMax(boundingBox.width(), boundingBox.height());
m_epsilon = edge * 0.001;
}
else
{
m_epsilon = 0.01;
}
build(characters->begin(), characters->end());
}
using Iterator = TextCharacters::iterator;
/// Builds structure over range of iterators. Array is build in O(n * log^2 (n)) time.
/// Index to internal nodes array is returned.
/// \param it1 Start iterator
/// \param it2 End iterator
size_t build(Iterator it1, Iterator it2);
/// Returns bounding box of character positions over given iterator range.
/// If iterator range is empty, then empty bounding box is returned.
/// \param it1 Start iterator
/// \param it2 End iterator
QRectF getBoundingBox(Iterator it1, Iterator it2) const;
/// Performs query on structure - finds all characters, which are in given
/// rectangle, and returns intersection size. If \p result parameter is set
/// to valid pointer, all intersected characters are inserted into the result
/// array.
/// \param rect Query rectangle
/// \param result Result of query (can be nullptr)
/// \returns Size of intersection
size_t query(const QRectF& rect, TextCharacters* result) const;
/// Finds character array, which contains at least \p minimalSize characters,
/// with some extra characters, which must be filtered out.
/// \param minimalSize Minimal size
/// \param sample Sample character
/// \param result Result
void queryNearestEstimate(size_t minimalSize, const TextCharacter& sample, TextCharacters* result) const;
private:
size_t queryImpl(size_t nodeIndex, const QRectF& rect, TextCharacters* result) const;
struct Node
{
bool isLeaf = false;
size_t index1 = 0;
size_t index2 = 0;
QRectF boundingBox;
};
using Nodes = std::vector<Node>;
TextCharacters* m_characters;
Nodes m_nodes;
size_t m_leafSize;
qreal m_epsilon;
};
size_t PDFTextCharacterSpatialIndex::build(Iterator it1, Iterator it2)
{
size_t nodeIndex = m_nodes.size();
if (size_t(std::distance(it1, it2)) < m_leafSize)
{
// Create leaf node
Node node;
node.isLeaf = true;
node.index1 = std::distance(m_characters->begin(), it1);
node.index2 = std::distance(m_characters->begin(), it2);
node.boundingBox = getBoundingBox(it1, it2);
m_nodes.push_back(qMove(node));
}
else
{
// Jakub Melka: split array of nodes into half, using larger side.
// It is like in R-tree structure.
m_nodes.push_back(Node());
QRectF boundingBox = getBoundingBox(it1, it2);
if (boundingBox.width() > boundingBox.height())
{
// Split using x-axis
std::sort(it1, it2, [](const TextCharacter& l, const TextCharacter& r) { return l.position.x() < r.position.x(); });
}
else
{
// Split using y-axis
std::sort(it1, it2, [](const TextCharacter& l, const TextCharacter& r) { return l.position.y() < r.position.y(); });
}
const size_t distance = std::distance(it1, it2);
Iterator itMid = std::next(it1, distance / 2);
const size_t index1 = build(it1, itMid);
const size_t index2 = build(itMid, it2);
Node& node = m_nodes[nodeIndex];
node.isLeaf = false;
node.index1 = index1;
node.index2 = index2;
node.boundingBox = boundingBox;
}
return nodeIndex;
}
QRectF PDFTextCharacterSpatialIndex::getBoundingBox(Iterator it1, Iterator it2) const
{
if (it1 != it2)
{
qreal x_min = qInf();
qreal x_max = -qInf();
qreal y_min = qInf();
qreal y_max = -qInf();
for (Iterator it = it1; it != it2; ++it)
{
const TextCharacter& character = *it;
x_min = qMin(x_min, character.position.x() - m_epsilon);
x_max = qMax(x_max, character.position.x() + m_epsilon);
y_min = qMin(y_min, character.position.y() - m_epsilon);
y_max = qMax(y_max, character.position.y() + m_epsilon);
}
return QRectF(x_min, y_min, x_max - x_min, y_max - y_min);
}
return QRectF();
}
size_t PDFTextCharacterSpatialIndex::query(const QRectF& rect, TextCharacters* result) const
{
if (!m_nodes.empty())
{
return queryImpl(0, rect, result);
}
return 0;
}
void PDFTextCharacterSpatialIndex::queryNearestEstimate(size_t minimalSize, const TextCharacter& sample, TextCharacters* result) const
{
if (m_characters->size() <= minimalSize)
{
*result = *m_characters;
}
else
{
// Query result
qreal querySizeEstimate = qMax(qMax(m_nodes[0].boundingBox.width(), m_nodes[0].boundingBox.height()) * 0.01, sample.advance * minimalSize * 0.5);
QRectF rect(sample.position, QSizeF(querySizeEstimate, querySizeEstimate));
rect.translate(-querySizeEstimate * 0.5, -querySizeEstimate * 0.5);
while (query(rect, nullptr) < minimalSize)
{
qreal expansion = rect.width() * 0.5;
rect.adjust(-expansion, -expansion, expansion, expansion);
}
qreal expansion = rect.width() * (qSqrt(2.0) - 1.0);
rect.adjust(-expansion, -expansion, expansion, expansion);
query(rect, result);
}
}
size_t PDFTextCharacterSpatialIndex::queryImpl(size_t nodeIndex, const QRectF& rect, TextCharacters* result) const
{
const Node& node = m_nodes[nodeIndex];
if (!node.boundingBox.intersects(rect))
{
// Node is not intersected, just return
return 0;
}
if (!node.isLeaf)
{
return queryImpl(node.index1, rect, result) + queryImpl(node.index2, rect, result);
}
else
{
// Jakub Melka: it is a leaf...
auto isInside = [&rect](const TextCharacter& character)
{
return rect.contains(character.position);
};
auto itStart = std::next(m_characters->begin(), node.index1);
auto itEnd = std::next(m_characters->begin(), node.index2);
if (result)
{
const size_t oldSize = result->size();
std::copy_if(itStart, itEnd, std::back_inserter(*result), isInside);
return result->size() - oldSize;
}
return std::count_if(itStart, itEnd, isInside);
}
}
PDFTextLayout::PDFTextLayout()
{
}
void PDFTextLayout::addCharacter(const PDFTextCharacterInfo& info)
{
TextCharacter character;
// Fill the basic info. For computing the angle, we must consider, if we are
// in vertical writing system. If yes, take vertical edge of the character,
// otherwise take horizontal edge.
character.character = info.character;
character.position = info.matrix.map(QPointF(0.0, 0.0));
QLineF testLine(QPointF(0.0, 0.0), QPointF(info.isVerticalWritingSystem ? 0.0 : info.advance, !info.isVerticalWritingSystem ? 0.0 : info.advance));
QLineF mappedLine = info.matrix.map(testLine);
character.advance = mappedLine.length();
// Jakub Melka: angle must be normalized to the range [0, 360). QLineF::angle()
// returns a value from the range [0, 360), but rounding of an angle slightly
// below 360 gives 360, which would be a different group than the angle 0,
// even though these two angles are the same.
character.angle = qRound(mappedLine.angle());
if (character.angle >= 360.0)
{
character.angle -= 360.0;
}
QLineF fontTestLine(QPointF(0.0, 0.0), QPointF(0.0, info.fontSize));
QLineF fontMappedLine = info.matrix.map(fontTestLine);
character.fontSize = fontMappedLine.length();
QRectF boundingBox = info.outline.boundingRect();
character.boundingBox.addPolygon(info.matrix.map(boundingBox));
m_characters.emplace_back(qMove(character));
m_angles.insert(character.angle);
}
void PDFTextLayout::perform()
{
for (const auto& angleGroup : getAngleGroups())
{
performDoLayout(angleGroup.first, angleGroup.second);
}
}
std::vector<std::pair<PDFReal, std::set<PDFReal>>> PDFTextLayout::getAngleGroups() const
{
std::vector<std::pair<PDFReal, std::set<PDFReal>>> result;
if (m_angles.empty())
{
return result;
}
// Count the characters for each angle - the most frequent angle of the group
// is used as the representative angle of the whole group.
std::map<PDFReal, size_t> characterCounts;
for (const TextCharacter& character : m_characters)
{
++characterCounts[character.angle];
}
// Angles are stored in an ordered set, so we can just walk through them and
// start a new group, when its total angular span would become too large.
// Comparing only adjacent angles would merge arbitrarily different writing
// directions through a chain of small differences.
std::vector<std::set<PDFReal>> groups;
for (PDFReal angle : m_angles)
{
if (!groups.empty() && angle - *groups.back().cbegin() <= m_settings.angleSensitivity)
{
groups.back().insert(angle);
}
else
{
groups.push_back({ angle });
}
}
// Angles are cyclic - the last group can be a continuation of the first one
// (for example angles 359 and 0 are almost the same angle).
if (groups.size() > 1 && (*groups.front().crbegin() + 360.0) - *groups.back().cbegin() <= m_settings.angleSensitivity)
{
groups.front().insert(groups.back().cbegin(), groups.back().cend());
groups.pop_back();
}
for (const std::set<PDFReal>& group : groups)
{
Q_ASSERT(!group.empty());
auto comparator = [&characterCounts](PDFReal left, PDFReal right)
{
return std::make_pair(characterCounts[left], -left) < std::make_pair(characterCounts[right], -right);
};
const PDFReal representativeAngle = *std::max_element(group.cbegin(), group.cend(), comparator);
result.emplace_back(representativeAngle, group);
}
return result;
}
void PDFTextLayout::optimize()
{
m_characters.shrink_to_fit();
}
qint64 PDFTextLayout::getMemoryConsumptionEstimate() const
{
qint64 estimate = sizeof(*this);
estimate += sizeof(decltype(m_characters)::value_type) * m_characters.capacity();
estimate += sizeof(decltype(m_angles)::value_type) * m_angles.size();
return estimate;
}
bool PDFTextLayout::isHoveringOverTextBlock(const QPointF& point) const
{
for (const PDFTextBlock& block : m_blocks)
{
if (block.getBoundingBox().contains(point))
{
return true;
}
}
return false;
}
PDFTextSelection PDFTextLayout::createTextSelection(PDFInteger pageIndex, const QPointF& point1, const QPointF& point2, QColor selectionColor, bool strictSelection)
{
PDFTextSelection selection;
// Jakub Melka: We must treat each block in its own coordinate system. Because texts can
// have different angles, we will treat each block separately.
size_t blockId = 0;
for (PDFTextBlock& block : m_blocks)
{
QTransform angleMatrix;
angleMatrix.rotate(block.getAngle());
block.applyTransform(angleMatrix);
QPointF pointA = angleMatrix.map(point1);
QPointF pointB = angleMatrix.map(point2);
const qreal xMin = qMin(pointA.x(), pointB.x());
const qreal yMin = qMin(pointA.y(), pointB.y());
const qreal xMax = qMax(pointA.x(), pointB.x());
const qreal yMax = qMax(pointA.y(), pointB.y());
QRectF rect(xMin, yMin, xMax - xMin, yMax - yMin);
QPainterPath rectPath;
rectPath.addRect(rect);
const QPainterPath& boundingBoxPath = block.getBoundingBox();
QPainterPath intersectionPath = boundingBoxPath.intersected(rectPath);
if (!intersectionPath.isEmpty())
{
QRectF intersectionRect = intersectionPath.boundingRect();
Q_ASSERT(intersectionRect.isValid());
bool isTopPointAboveText = false;
bool isBottomPointBelowText = false;
const PDFTextLines& lines = block.getLines();
auto itLineA = std::find_if(lines.cbegin(), lines.cend(), [pointA](const PDFTextLine& line) { return line.getBoundingBox().contains(pointA); });
auto itLineB = std::find_if(lines.cbegin(), lines.cend(), [pointB](const PDFTextLine& line) { return line.getBoundingBox().contains(pointB); });
if (itLineA == itLineB && itLineA != lines.cend())
{
// Both points are in the same line. We consider point with lesser
// horizontal coordinate as start selection point, and point with greater
// horizontal coordinate as end selection point.
if (pointA.x() > pointB.x())
{
std::swap(pointA, pointB);
}
}
else
{
// Otherwise points are not in the same line. Then start point will be
// point top of the second point. Bottom point will mark end of selection.
if (pointA.y() < pointB.y())
{
std::swap(pointA, pointB);
}
QRectF boundingBoxPathBBRect = boundingBoxPath.controlPointRect();
// If start point is above the text block, move start point to the left.
if (!strictSelection && boundingBoxPathBBRect.bottom() < pointA.y())
{
pointA.setX(boundingBoxPathBBRect.left());
isTopPointAboveText = true;
}
if (!strictSelection && boundingBoxPathBBRect.top() > pointB.y())
{
pointB.setX(boundingBoxPathBBRect.right());
isBottomPointBelowText = true;
}
}
// Now, we have pointA as start point and pointB as end point. We must found
// nearest character to the right of point A, and nearest character to the
// left of point B (with respect to point A/B).
qreal maxDistanceA = std::numeric_limits<qreal>::infinity();
qreal maxDistanceB = std::numeric_limits<qreal>::infinity();
PDFCharacterPointer ptrA;
PDFCharacterPointer ptrB;
for (size_t lineId = 0, linesCount = lines.size(); lineId < linesCount; ++lineId)
{
const PDFTextLine& line = lines[lineId];
QRectF lineBoundingRect = line.getBoundingBox().boundingRect();
// We skip lines, which are not in the range (pointB.y(), pointA.y),
// i.e. are above or below.
if (lineBoundingRect.bottom() < pointB.y() ||
lineBoundingRect.top() > pointA.y())
{
continue;
}
const TextCharacters& characters = line.getCharacters();
for (size_t characterId = 0, characterCount = characters.size(); characterId < characterCount; ++characterId)
{
const TextCharacter& character = characters[characterId];
QPointF characterCenter = character.boundingBox.boundingRect().center();
qreal distanceA = QLineF(pointA, characterCenter).length();
qreal distanceB = QLineF(pointB, characterCenter).length();
if (distanceA < maxDistanceA && characterCenter.x() > pointA.x())
{
maxDistanceA = distanceA;
ptrA.pageIndex = pageIndex;
ptrA.blockIndex = blockId;
ptrA.lineIndex = lineId;
ptrA.characterIndex = characterId;
}
if (distanceB < maxDistanceB && characterCenter.x() < pointB.x())
{
maxDistanceB = distanceB;
ptrB.pageIndex = pageIndex;
ptrB.blockIndex = blockId;
ptrB.lineIndex = lineId;
ptrB.characterIndex = characterId;
}
}
}
if (isTopPointAboveText && !lines.empty())
{
ptrA.pageIndex = pageIndex;
ptrA.blockIndex = blockId;
ptrA.lineIndex = 0;
ptrA.characterIndex = 0;
}
if (isBottomPointBelowText && !lines.empty())
{
ptrB.pageIndex = pageIndex;
ptrB.blockIndex = blockId;
ptrB.lineIndex = lines.size() - 1;
ptrB.characterIndex = lines.back().getCharacters().size() - 1;
}
// If we have filled the pointers, add them to the selection
if (ptrA.isValid() && ptrB.isValid())
{
if (ptrA < ptrB)
{
selection.addItems({ PDFTextSelectionItem(ptrA, ptrB) }, selectionColor);
}
else
{
selection.addItems({ PDFTextSelectionItem(ptrB, ptrA) }, selectionColor);
}
}
}
// Increment block index
++blockId;
// Apply backward transformation to restore original coordinate system
block.applyTransform(angleMatrix.inverted());
}
selection.build();
return selection;
}
PDFTextSelection PDFTextLayout::selectBlock(const size_t blockIndex, PDFInteger pageIndex, QColor color) const
{
PDFTextSelection selection;
if (blockIndex >= m_blocks.size())
{
return selection;
}
const PDFTextBlock& textBlock = m_blocks[blockIndex];
if (textBlock.getLines().empty())
{
return selection;
}
PDFCharacterPointer ptrA;
PDFCharacterPointer ptrB;
ptrA.pageIndex = pageIndex;
ptrA.blockIndex = blockIndex;
ptrA.lineIndex = 0;
ptrA.characterIndex = 0;
ptrB.pageIndex = pageIndex;
ptrB.blockIndex = blockIndex;
ptrB.lineIndex = textBlock.getLines().size() - 1;
ptrB.characterIndex = textBlock.getLines().back().getCharacters().size() - 1;
selection.addItems({ PDFTextSelectionItem(ptrA, ptrB) }, color);
selection.build();
return selection;
}
PDFTextSelection PDFTextLayout::selectLineInBlock(const size_t blockIndex, const size_t lineIndex, PDFInteger pageIndex, QColor color) const
{
PDFTextSelection selection;
if (blockIndex >= m_blocks.size())
{
return selection;
}
const PDFTextBlock& textBlock = m_blocks[blockIndex];
if (lineIndex >= textBlock.getLines().size())
{
return selection;
}
PDFCharacterPointer ptrA;
PDFCharacterPointer ptrB;
ptrA.pageIndex = pageIndex;
ptrA.blockIndex = blockIndex;
ptrA.lineIndex = lineIndex;
ptrA.characterIndex = 0;
ptrB.pageIndex = pageIndex;
ptrB.blockIndex = blockIndex;
ptrB.lineIndex = lineIndex;
ptrB.characterIndex = textBlock.getLines()[lineIndex].getCharacters().size() - 1;
selection.addItems({ PDFTextSelectionItem(ptrA, ptrB) }, color);
selection.build();
return selection;
}
QString PDFTextLayout::getTextFromSelection(PDFTextSelection::iterator itBegin, PDFTextSelection::iterator itEnd, PDFInteger pageIndex) const
{
QStringList text;
if (itBegin != itEnd)
{
PDFTextFlows flows = PDFTextFlow::createTextFlows(*this, PDFTextFlow::RemoveSoftHyphen, pageIndex);
Q_ASSERT(flows.size() < 2);
if (!flows.empty())
{
const PDFTextFlow& textFlow = flows.front();
for (auto it = itBegin; it != itEnd; ++it)
{
text << textFlow.getText(it->start, it->end);
}
}
}
return text.join("\n");
}
QString PDFTextLayout::getTextFromSelection(const PDFTextSelection& selection, PDFInteger pageIndex) const
{
return getTextFromSelection(selection.begin(pageIndex), selection.end(pageIndex), pageIndex);
}
QDataStream& operator>>(QDataStream& stream, PDFTextLayout& layout)
{
stream >> layout.m_characters;
stream >> layout.m_angles;
stream >> layout.m_settings;
stream >> layout.m_blocks;
return stream;
}
QDataStream& operator<<(QDataStream& stream, const PDFTextLayout& layout)
{
stream << layout.m_characters;
stream << layout.m_angles;
stream << layout.m_settings;
stream << layout.m_blocks;
return stream;
}
struct NearestCharacterInfo
{
size_t index = std::numeric_limits<size_t>::max();
PDFReal distance = std::numeric_limits<PDFReal>::infinity();
inline bool operator<(const NearestCharacterInfo& other) const { return distance < other.distance; }
};
void PDFTextLayout::performDoLayout(PDFReal angle, const std::set<PDFReal>& angles)
{
// We will implement variation of 'docstrum' algorithm, we have divided characters by angles,
// for each angle we get characters for that particular angle, and run 'docstrum' algorithm.
// We will do following steps:
// 1) Rotate the plane with characters so that they are all in horizontal line
// 2) Find k-nearest characters for each character (so each character will have
// k pointers to the nearest characters)
// 3) Find text lines. We will do that by creating transitive closure of characters, i.e.
// characters, which are close and are on horizontal line, are marked as in one text line.
// Consider also font size and empty space size between different characters.
// 4) Merge text lines into text blocks using various criteria, such as overlap,
// distance between the lines, and also using again, transitive closure.
// 5) Sort blocks using topological ordering
TextCharacters characters = getCharactersForAngles(angles);
// Lines and blocks use the first character's angle to construct selection
// geometry. Store the common layout angle so a skewed first glyph cannot
// rotate the selection away from the baseline used to arrange the text.
for (TextCharacter& character : characters)
{
character.angle = angle;
}
// Step 1) - rotate blocks
QTransform angleMatrix;
angleMatrix.rotate(angle);
applyTransform(characters, angleMatrix);
// Create spatial index
PDFTextCharacterSpatialIndex spatialIndex(&characters, 16);
for (size_t i = 0, count = characters.size(); i < count; ++i)
{
characters[i].index = i;
}
// Step 2) - find k-nearest characters
const size_t characterCount = characters.size();
const size_t bucketSize = m_settings.samples + 1;
std::vector<NearestCharacterInfo> nearestCharacters(bucketSize * characters.size(), NearestCharacterInfo());
auto findNearestCharacters = [this, bucketSize, &characters, &spatialIndex, &nearestCharacters](size_t currentCharacterIndex)
{
// It will be iterator to the start of the nearest neighbour sequence
auto it = std::next(nearestCharacters.begin(), currentCharacterIndex * bucketSize);
auto itLast = std::next(it, m_settings.samples);
NearestCharacterInfo& insertInfo = *itLast;
QPointF currentPoint = characters[currentCharacterIndex].position;
TextCharacters nearestPointSamples;
spatialIndex.queryNearestEstimate(m_settings.samples, characters[currentCharacterIndex], &nearestPointSamples);
for (size_t i = 0, count = nearestPointSamples.size(); i < count; ++i)
{
if (nearestPointSamples[i].index == currentCharacterIndex)
{
continue;
}
insertInfo.index = nearestPointSamples[i].index;
insertInfo.distance = QLineF(currentPoint, nearestPointSamples[i].position).length();
// Now, use insert sort to sort the array of samples + 1 elements (#samples elements
// are sorted, we use only insert sort on the last element).
auto itLeft = std::prev(itLast);
auto itRight = itLast;
while (true)
{
if (*itRight < *itLeft)
{
std::swap(*itRight, *itLeft);
itRight = itLeft;
if (itLeft == it)
{
// We have reached the end
break;
}
--itLeft;
}
else
{
// We have proper order, break the cycle
break;
}
}
}
};
auto range = PDFIntegerRange<size_t>(0, characterCount);
PDFExecutionPolicy::execute(PDFExecutionPolicy::Scope::Content, range.begin(), range.end(), findNearestCharacters);
// Step 3) - detect lines
PDFUnionFindAlgorithm<size_t> textLinesUF(characterCount);
for (size_t i = 0; i < characterCount; ++i)
{
auto it = std::next(nearestCharacters.begin(), i * bucketSize);
auto itEnd = std::next(it, m_settings.samples);
for (; it != itEnd; ++it)
{
const NearestCharacterInfo& info = *it;
if (info.index == std::numeric_limits<size_t>::max())
{
// We have reached the end - or we do not have enough characters
break;
}
// Criteria:
// 1) Distance of characters is not too large
// 2) Characters are approximately at same line
// 3) Font size of characters are approximately equal
PDFReal fontSizeMax = qMax(characters[i].fontSize, characters[info.index].fontSize);
PDFReal fontSizeMin = qMin(characters[i].fontSize, characters[info.index].fontSize);
if (info.distance < m_settings.distanceSensitivity * characters[i].advance && // 1)
std::fabs(characters[i].position.y() - characters[info.index].position.y()) < fontSizeMin * m_settings.charactersOnLineSensitivity && // 2)
fontSizeMax / fontSizeMin < m_settings.fontSensitivity) // 3)
{
textLinesUF.unify(i, info.index);
}
}
}
std::map<size_t, TextCharacters> lineToCharactersMap;
for (size_t i = 0; i < characterCount; ++i)
{
lineToCharactersMap[textLinesUF.find(i)].push_back(characters[i]);
}
PDFTextLines lines;
lines.reserve(lineToCharactersMap.size());
for (auto& item : lineToCharactersMap)
{
lines.emplace_back(qMove(item.second));
}
// Step 4) - detect text blocks
const size_t lineCount = lines.size();
PDFUnionFindAlgorithm<size_t> textBlocksUF(lineCount);
for (size_t i = 0; i < lineCount; ++i)
{
for (size_t j = i + 1; j < lineCount; ++j)
{
QRectF bb1 = lines[i].getBoundingBox().boundingRect();
QRectF bb2 = lines[j].getBoundingBox().boundingRect();
// Jakub Melka: we will join two blocks, if these two conditions both holds:
// 1) bounding boxes overlap horizontally by large portion
// 2) vertical space between bounding boxes is not too large
QRectF bbUnion = bb1.united(bb2);
const PDFReal height = bbUnion.height();
const PDFReal heightLimit = (bb1.height() + bb2.height()) * m_settings.blockVerticalSensitivity;
const PDFReal overlap = qMax(0.0, bb1.width() + bb2.width() - bbUnion.width());
const PDFReal minimalOverlap = qMin(bb1.width(), bb2.width()) * m_settings.blockOverlapSensitivity;
if (height < heightLimit && overlap > minimalOverlap)
{
textBlocksUF.unify(i, j);
}
}
}
std::map<size_t, PDFTextLines> blockToLines;
for (size_t i = 0; i < lineCount; ++i)
{
blockToLines[textBlocksUF.find(i)].push_back(qMove(lines[i]));
}
PDFTextBlocks blocks;
blocks.reserve(blockToLines.size());
for (auto& item : blockToLines)
{
blocks.emplace_back(qMove(item.second));
}
// 5) Sort block by topological ordering. We will use approache described in paper
// "High Performance Document Layout Analysis", T.M. Breuel, 2003, where are described
// two rules, which are used to determine block precedence.
//
// Rule 1: a<b, if:
// - blocks a,b have overlap in x-axis
// - block a is above block b
//
// Rule 2: a<b, if:
// - block a is entirely on left side of block b
// - there doesn't exist block c, which is between a,b in y-axis
// and moreover, overlaps both a and b in x-axis.
auto isBeforeByRule1 = [&blocks](const size_t aIndex, const size_t bIndex)
{
QRectF aBB = blocks[aIndex].getBoundingBox().boundingRect();
QRectF bBB = blocks[bIndex].getBoundingBox().boundingRect();
const bool isOverlappedOnHorizontalAxis = isRectangleHorizontallyOverlapped(aBB, bBB);
const bool isAoverB = aBB.bottom() > bBB.top();
return isOverlappedOnHorizontalAxis && isAoverB;
};
auto isBeforeByRule2 = [&blocks](const size_t aIndex, const size_t bIndex)
{
QRectF aBB = blocks[aIndex].getBoundingBox().boundingRect();
QRectF bBB = blocks[bIndex].getBoundingBox().boundingRect();
QRectF abBB = aBB.united(bBB);
if (aBB.right() < bBB.left())
{
// Check, if 'c' block doesn't exist
for (size_t i = 0, count = blocks.size(); i < count; ++i)
{
if (i == aIndex || i == bIndex)
{
continue;
}
QRectF cBB = blocks[i].getBoundingBox().boundingRect();
if (cBB.top() >= abBB.top() && cBB.bottom() <= abBB.bottom())
{
const bool isAOverlappedOnHorizontalAxis = isRectangleHorizontallyOverlapped(aBB, cBB);
const bool isBOverlappedOnHorizontalAxis = isRectangleHorizontallyOverlapped(bBB, cBB);
if (isAOverlappedOnHorizontalAxis && isBOverlappedOnHorizontalAxis)
{
return false;
}
}
}
return true;
}
return false;
};
// Order blocks using topological sort (https://en.wikipedia.org/wiki/Topological_sorting,
// Kahn's algorithm is used)
std::set<size_t> workBlocks;
std::vector<size_t> ordering;
std::vector<std::set<size_t>> orderingEdges(blocks.size(), std::set<size_t>());
ordering.reserve(blocks.size());
for (size_t i = 0; i < blocks.size(); ++i)
{
workBlocks.insert(workBlocks.end(), i);
for (size_t j = 0; j < blocks.size(); ++j)
{
if (i != j && (isBeforeByRule1(j, i) || isBeforeByRule2(j, i)))
{
orderingEdges[i].insert(j);
}
}
}
// Topological sort
QTransform invertedAngleMatrix = angleMatrix.inverted();
while (!workBlocks.empty())
{
auto it = std::min_element(workBlocks.begin(), workBlocks.end(), [&orderingEdges](const size_t l, const size_t r) { return orderingEdges[l].size() < orderingEdges[r].size(); });
ordering.push_back(*it);
for (std::set<size_t>& edges : orderingEdges)
{
edges.erase(*it);
}
blocks[*it].applyTransform(invertedAngleMatrix);
m_blocks.emplace_back(qMove(blocks[*it]));
workBlocks.erase(it);
}
}
TextCharacters PDFTextLayout::getCharactersForAngles(const std::set<PDFReal>& angles) const
{
TextCharacters result;
std::copy_if(m_characters.cbegin(), m_characters.cend(), std::back_inserter(result), [&angles](const TextCharacter& character) { return angles.count(character.angle) > 0; });
return result;
}
void PDFTextLayout::applyTransform(TextCharacters& characters, const QTransform& matrix)
{
for (TextCharacter& character : characters)
{
character.position = matrix.map(character.position);
character.boundingBox = matrix.map(character.boundingBox);
}
}
PDFTextLine::PDFTextLine(TextCharacters characters) :
m_characters(qMove(characters))
{
std::sort(m_characters.begin(), m_characters.end(), [](const TextCharacter& l, const TextCharacter& r) { return l.position.x() < r.position.x(); });
QRectF boundingBox;
for (const TextCharacter& character : m_characters)
{
boundingBox = boundingBox.united(character.boundingBox.boundingRect());
}
m_boundingBox.addRect(boundingBox);
m_topLeft = boundingBox.topLeft();
}
PDFReal PDFTextLine::getAngle() const
{
if (!m_characters.empty())
{
return m_characters.front().angle;
}
return 0.0;
}
void PDFTextLine::applyTransform(const QTransform& matrix)
{
m_boundingBox = matrix.map(m_boundingBox);
m_topLeft = matrix.map(m_topLeft);
for (TextCharacter& character : m_characters)
{
character.applyTransform(matrix);
}
}
QDataStream& operator>>(QDataStream& stream, PDFTextLine& line)
{
stream >> line.m_characters;
stream >> line.m_boundingBox;
stream >> line.m_topLeft;