forked from StarCrossPortal/bug-hunting-101
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pdfium_page.cc
1588 lines (1364 loc) · 54.1 KB
/
pdfium_page.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 (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "pdf/pdfium/pdfium_page.h"
#include <math.h>
#include <stddef.h>
#include <algorithm>
#include <memory>
#include <utility>
#include "base/bind.h"
#include "base/callback.h"
#include "base/check_op.h"
#include "base/metrics/histogram_functions.h"
#include "base/notreached.h"
#include "base/numerics/math_constants.h"
#include "base/numerics/safe_math.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "pdf/accessibility_structs.h"
#include "pdf/pdfium/pdfium_api_string_buffer_adapter.h"
#include "pdf/pdfium/pdfium_engine.h"
#include "pdf/pdfium/pdfium_unsupported_features.h"
#include "pdf/ppapi_migration/geometry_conversions.h"
#include "pdf/thumbnail.h"
#include "ppapi/c/private/ppb_pdf.h"
#include "printing/units.h"
#include "third_party/pdfium/public/cpp/fpdf_scopers.h"
#include "third_party/pdfium/public/fpdf_annot.h"
#include "third_party/pdfium/public/fpdf_catalog.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/geometry/size_f.h"
#include "ui/gfx/geometry/vector2d.h"
#include "ui/gfx/geometry/vector2d_f.h"
#include "ui/gfx/range/range.h"
using printing::ConvertUnitDouble;
using printing::kPixelsPerInch;
using printing::kPointsPerInch;
namespace chrome_pdf {
namespace {
constexpr float k45DegreesInRadians = base::kPiFloat / 4;
constexpr float k90DegreesInRadians = base::kPiFloat / 2;
constexpr float k180DegreesInRadians = base::kPiFloat;
constexpr float k270DegreesInRadians = 3 * base::kPiFloat / 2;
constexpr float k360DegreesInRadians = 2 * base::kPiFloat;
gfx::RectF FloatPageRectToPixelRect(FPDF_PAGE page, const gfx::RectF& input) {
int output_width = FPDF_GetPageWidthF(page);
int output_height = FPDF_GetPageHeightF(page);
int min_x;
int min_y;
int max_x;
int max_y;
if (!FPDF_PageToDevice(page, 0, 0, output_width, output_height, 0, input.x(),
input.y(), &min_x, &min_y)) {
return gfx::RectF();
}
if (!FPDF_PageToDevice(page, 0, 0, output_width, output_height, 0,
input.right(), input.bottom(), &max_x, &max_y)) {
return gfx::RectF();
}
if (max_x < min_x)
std::swap(min_x, max_x);
if (max_y < min_y)
std::swap(min_y, max_y);
// Make sure small but non-zero dimensions for |input| does not get rounded
// down to 0.
int width = max_x - min_x;
int height = max_y - min_y;
if (width == 0 && input.width())
width = 1;
if (height == 0 && input.height())
height = 1;
gfx::RectF output_rect(
ConvertUnitDouble(min_x, kPointsPerInch, kPixelsPerInch),
ConvertUnitDouble(min_y, kPointsPerInch, kPixelsPerInch),
ConvertUnitDouble(width, kPointsPerInch, kPixelsPerInch),
ConvertUnitDouble(height, kPointsPerInch, kPixelsPerInch));
return output_rect;
}
gfx::RectF GetFloatCharRectInPixels(FPDF_PAGE page,
FPDF_TEXTPAGE text_page,
int index) {
double left;
double right;
double bottom;
double top;
if (!FPDFText_GetCharBox(text_page, index, &left, &right, &bottom, &top))
return gfx::RectF();
if (right < left)
std::swap(left, right);
if (bottom < top)
std::swap(top, bottom);
gfx::RectF page_coords(left, top, right - left, bottom - top);
return FloatPageRectToPixelRect(page, page_coords);
}
int GetFirstNonUnicodeWhiteSpaceCharIndex(FPDF_TEXTPAGE text_page,
int start_char_index,
int chars_count) {
int i = start_char_index;
while (i < chars_count &&
base::IsUnicodeWhitespace(FPDFText_GetUnicode(text_page, i))) {
i++;
}
return i;
}
AccessibilityTextDirection GetDirectionFromAngle(float angle) {
// Rotating the angle by 45 degrees to simplify the conditions statements.
// It's like if we rotated the whole cartesian coordinate system like below.
// X X
// X IV X
// X X
// X X
// X X
// III X I
// X X
// X X
// X X
// X II X
// X X
angle = fmodf(angle + k45DegreesInRadians, k360DegreesInRadians);
// Quadrant I.
if (angle >= 0 && angle <= k90DegreesInRadians)
return AccessibilityTextDirection::kLeftToRight;
// Quadrant II.
if (angle > k90DegreesInRadians && angle <= k180DegreesInRadians)
return AccessibilityTextDirection::kTopToBottom;
// Quadrant III.
if (angle > k180DegreesInRadians && angle <= k270DegreesInRadians)
return AccessibilityTextDirection::kRightToLeft;
// Quadrant IV.
return AccessibilityTextDirection::kBottomToTop;
}
void AddCharSizeToAverageCharSize(gfx::SizeF new_size,
gfx::SizeF* avg_size,
int* count) {
// Some characters sometimes have a bogus empty bounding box. We don't want
// them to impact the average.
if (!new_size.IsEmpty()) {
avg_size->set_width((avg_size->width() * *count + new_size.width()) /
(*count + 1));
avg_size->set_height((avg_size->height() * *count + new_size.height()) /
(*count + 1));
(*count)++;
}
}
float GetRotatedCharWidth(float angle, const gfx::SizeF& size) {
return fabsf(cosf(angle) * size.width()) + fabsf(sinf(angle) * size.height());
}
float GetAngleOfVector(const gfx::Vector2dF& v) {
float angle = atan2f(v.y(), v.x());
if (angle < 0)
angle += k360DegreesInRadians;
return angle;
}
float GetAngleDifference(float a, float b) {
// This is either the difference or (360 - difference).
float x = fmodf(fabsf(b - a), k360DegreesInRadians);
return x > k180DegreesInRadians ? k360DegreesInRadians - x : x;
}
bool FloatEquals(float f1, float f2) {
// The idea behind this is to use this fraction of the larger of the
// two numbers as the limit of the difference. This breaks down near
// zero, so we reuse this as the minimum absolute size we will use
// for the base of the scale too.
static constexpr float kEpsilonScale = 0.00001f;
return fabsf(f1 - f2) <
kEpsilonScale * fmaxf(fmaxf(fabsf(f1), fabsf(f2)), kEpsilonScale);
}
// Count overlaps across text annotations.
template <typename T, typename U>
uint32_t CountOverlaps(const std::vector<T>& first_set,
const std::vector<U>& second_set) {
// This method assumes vectors passed are sorted by |start_char_index|.
uint32_t overlaps = 0;
// Count overlaps between |first_set| and |second_set|.
for (const auto& first_set_object : first_set) {
gfx::Range first_range(
first_set_object.start_char_index,
first_set_object.start_char_index + first_set_object.char_count);
for (const auto& second_set_object : second_set) {
gfx::Range second_range(
second_set_object.start_char_index,
second_set_object.start_char_index + second_set_object.char_count);
if (first_range.Intersects(second_range)) {
overlaps++;
} else if (first_range.start() < second_range.start()) {
// Both range vectors are sorted by |start_char_index|. In case they
// don't overlap, and the |second_range| starts after the |first_range|,
// then all successive |second_set_object| will not overlap with
// |first_range|.
break;
}
}
}
return overlaps;
}
// Count overlaps within text annotations.
template <typename T>
uint32_t CountInternalTextOverlaps(const std::vector<T>& text_objects) {
// This method assumes text_objects is sorted by |start_char_index|.
uint32_t overlaps = 0;
for (size_t i = 0; i < text_objects.size(); ++i) {
gfx::Range range1(
text_objects[i].start_char_index,
text_objects[i].start_char_index + text_objects[i].char_count);
for (size_t j = i + 1; j < text_objects.size(); ++j) {
DCHECK_GE(text_objects[j].start_char_index,
text_objects[i].start_char_index);
gfx::Range range2(
text_objects[j].start_char_index,
text_objects[j].start_char_index + text_objects[j].char_count);
if (range1.Intersects(range2)) {
overlaps++;
} else {
// The input is sorted by |start_char_index|. In case |range1| and
// |range2| do not overlap, and |range2| starts after |range1|, then
// successive ranges in the inner loop will also not overlap with
// |range1|.
break;
}
}
}
return overlaps;
}
bool IsRadioButtonOrCheckBox(int button_type) {
return button_type == FPDF_FORMFIELD_CHECKBOX ||
button_type == FPDF_FORMFIELD_RADIOBUTTON;
}
} // namespace
PDFiumPage::LinkTarget::LinkTarget() : page(-1) {}
PDFiumPage::LinkTarget::LinkTarget(const LinkTarget& other) = default;
PDFiumPage::LinkTarget::~LinkTarget() = default;
PDFiumPage::PDFiumPage(PDFiumEngine* engine, int i)
: engine_(engine), index_(i), available_(false) {}
PDFiumPage::PDFiumPage(PDFiumPage&& that) = default;
PDFiumPage::~PDFiumPage() {
DCHECK_EQ(0, preventing_unload_count_);
}
void PDFiumPage::Unload() {
// Do not unload while in the middle of a load.
if (preventing_unload_count_)
return;
text_page_.reset();
if (page_) {
if (engine_->form()) {
FORM_OnBeforeClosePage(page(), engine_->form());
}
page_.reset();
}
}
FPDF_PAGE PDFiumPage::GetPage() {
ScopedUnsupportedFeature scoped_unsupported_feature(engine_);
if (!available_)
return nullptr;
if (!page_) {
ScopedUnloadPreventer scoped_unload_preventer(this);
page_.reset(FPDF_LoadPage(engine_->doc(), index_));
if (page_ && engine_->form()) {
FORM_OnAfterLoadPage(page(), engine_->form());
}
}
return page();
}
FPDF_TEXTPAGE PDFiumPage::GetTextPage() {
if (!available_)
return nullptr;
if (!text_page_) {
ScopedUnloadPreventer scoped_unload_preventer(this);
text_page_.reset(FPDFText_LoadPage(GetPage()));
}
return text_page();
}
void PDFiumPage::CalculatePageObjectTextRunBreaks() {
if (calculated_page_object_text_run_breaks_)
return;
calculated_page_object_text_run_breaks_ = true;
int chars_count = FPDFText_CountChars(GetTextPage());
if (chars_count == 0)
return;
CalculateLinks();
for (const auto& link : links_) {
if (link.start_char_index >= 0 && link.start_char_index < chars_count) {
page_object_text_run_breaks_.insert(link.start_char_index);
int next_text_run_break_index = link.start_char_index + link.char_count;
// Don't insert a break if the link is at the end of the page text.
if (next_text_run_break_index < chars_count) {
page_object_text_run_breaks_.insert(next_text_run_break_index);
}
}
}
PopulateAnnotations();
for (const auto& highlight : highlights_) {
if (highlight.start_char_index >= 0 &&
highlight.start_char_index < chars_count) {
page_object_text_run_breaks_.insert(highlight.start_char_index);
int next_text_run_break_index =
highlight.start_char_index + highlight.char_count;
// Don't insert a break if the highlight is at the end of the page text.
if (next_text_run_break_index < chars_count) {
page_object_text_run_breaks_.insert(next_text_run_break_index);
}
}
}
}
void PDFiumPage::CalculateTextRunStyleInfo(
int char_index,
AccessibilityTextStyleInfo& style_info) {
FPDF_TEXTPAGE text_page = GetTextPage();
style_info.font_size = FPDFText_GetFontSize(text_page, char_index);
int flags = 0;
size_t buffer_size =
FPDFText_GetFontInfo(text_page, char_index, nullptr, 0, &flags);
if (buffer_size > 0) {
PDFiumAPIStringBufferAdapter<std::string> api_string_adapter(
&style_info.font_name, buffer_size, true);
void* data = api_string_adapter.GetData();
size_t bytes_written =
FPDFText_GetFontInfo(text_page, char_index, data, buffer_size, nullptr);
// Trim the null character.
api_string_adapter.Close(bytes_written);
}
style_info.font_weight = FPDFText_GetFontWeight(text_page, char_index);
// As defined in PDF 1.7 table 5.20.
constexpr int kFlagItalic = (1 << 6);
// Bold text is considered bold when greater than or equal to 700.
constexpr int kStandardBoldValue = 700;
style_info.is_italic = (flags & kFlagItalic);
style_info.is_bold = style_info.font_weight >= kStandardBoldValue;
unsigned int fill_r;
unsigned int fill_g;
unsigned int fill_b;
unsigned int fill_a;
if (FPDFText_GetFillColor(text_page, char_index, &fill_r, &fill_g, &fill_b,
&fill_a)) {
style_info.fill_color = MakeARGB(fill_a, fill_r, fill_g, fill_b);
} else {
style_info.fill_color = MakeARGB(0xff, 0, 0, 0);
}
unsigned int stroke_r;
unsigned int stroke_g;
unsigned int stroke_b;
unsigned int stroke_a;
if (FPDFText_GetStrokeColor(text_page, char_index, &stroke_r, &stroke_g,
&stroke_b, &stroke_a)) {
style_info.stroke_color = MakeARGB(stroke_a, stroke_r, stroke_g, stroke_b);
} else {
style_info.stroke_color = MakeARGB(0xff, 0, 0, 0);
}
int render_mode = FPDFText_GetTextRenderMode(text_page, char_index);
DCHECK_GE(render_mode,
static_cast<int>(AccessibilityTextRenderMode::kUnknown));
DCHECK_LE(render_mode,
static_cast<int>(AccessibilityTextRenderMode::kMaxValue));
style_info.render_mode =
static_cast<AccessibilityTextRenderMode>(render_mode);
}
bool PDFiumPage::AreTextStyleEqual(int char_index,
const AccessibilityTextStyleInfo& style) {
AccessibilityTextStyleInfo char_style;
CalculateTextRunStyleInfo(char_index, char_style);
return char_style.font_name == style.font_name &&
char_style.font_weight == style.font_weight &&
char_style.render_mode == style.render_mode &&
FloatEquals(char_style.font_size, style.font_size) &&
char_style.fill_color == style.fill_color &&
char_style.stroke_color == style.stroke_color &&
char_style.is_italic == style.is_italic &&
char_style.is_bold == style.is_bold;
}
void PDFiumPage::LogOverlappingAnnotations() {
if (logged_overlapping_annotations_)
return;
logged_overlapping_annotations_ = true;
DCHECK(calculated_page_object_text_run_breaks_);
std::vector<Link> links = links_;
std::sort(links.begin(), links.end(), [](const Link& a, const Link& b) {
return a.start_char_index < b.start_char_index;
});
uint32_t overlap_count = CountLinkHighlightOverlaps(links, highlights_);
// We log this overlap count per page of the PDF. Typically we expect only a
// few overlaps because intersecting links/highlights are not that common.
base::UmaHistogramCustomCounts("PDF.LinkHighlightOverlapsInPage",
overlap_count, 1, 100, 50);
}
base::Optional<AccessibilityTextRunInfo> PDFiumPage::GetTextRunInfo(
int start_char_index) {
FPDF_PAGE page = GetPage();
FPDF_TEXTPAGE text_page = GetTextPage();
int chars_count = FPDFText_CountChars(text_page);
// Check to make sure |start_char_index| is within bounds.
if (start_char_index < 0 || start_char_index >= chars_count)
return base::nullopt;
int actual_start_char_index = GetFirstNonUnicodeWhiteSpaceCharIndex(
text_page, start_char_index, chars_count);
// Check to see if GetFirstNonUnicodeWhiteSpaceCharIndex() iterated through
// all the characters.
if (actual_start_char_index >= chars_count) {
// If so, |info.len| needs to take the number of characters
// iterated into account.
DCHECK_GT(actual_start_char_index, start_char_index);
AccessibilityTextRunInfo info;
info.len = chars_count - start_char_index;
return info;
}
// If the first character in a text run is a space, we need to start
// |text_run_bounds| from the space character instead of the first
// non-space unicode character.
gfx::RectF text_run_bounds =
actual_start_char_index > start_char_index
? GetFloatCharRectInPixels(page, text_page, start_char_index)
: gfx::RectF();
// Pdfium trims more than 1 consecutive spaces to 1 space.
DCHECK_LE(actual_start_char_index - start_char_index, 1);
int char_index = actual_start_char_index;
// Set text run's style info from the first character of the text run.
AccessibilityTextRunInfo info;
CalculateTextRunStyleInfo(char_index, info.style);
gfx::RectF start_char_rect =
GetFloatCharRectInPixels(page, text_page, char_index);
float text_run_font_size = info.style.font_size;
// Heuristic: Initialize the average character size to one-third of the font
// size to avoid having the first few characters misrepresent the average.
// Without it, if a text run starts with a '.', its small bounding box could
// lead to a break in the text run after only one space. Ex: ". Hello World"
// would be split in two runs: "." and "Hello World".
double font_size_minimum = FPDFText_GetFontSize(text_page, char_index) / 3.0;
gfx::SizeF avg_char_size(font_size_minimum, font_size_minimum);
int non_whitespace_chars_count = 1;
AddCharSizeToAverageCharSize(start_char_rect.size(), &avg_char_size,
&non_whitespace_chars_count);
// Add first non-space char to text run.
text_run_bounds.Union(start_char_rect);
AccessibilityTextDirection char_direction =
GetDirectionFromAngle(FPDFText_GetCharAngle(text_page, char_index));
if (char_index < chars_count)
char_index++;
gfx::RectF prev_char_rect = start_char_rect;
float estimated_font_size =
std::max(start_char_rect.width(), start_char_rect.height());
// The angle of the vector starting at the first character center-point and
// ending at the current last character center-point.
float text_run_angle = 0;
CalculatePageObjectTextRunBreaks();
const auto breakpoint_iter =
std::lower_bound(page_object_text_run_breaks_.begin(),
page_object_text_run_breaks_.end(), char_index);
int breakpoint_index = breakpoint_iter != page_object_text_run_breaks_.end()
? *breakpoint_iter
: -1;
// Continue adding characters until heuristics indicate we should end the text
// run.
while (char_index < chars_count) {
// Split a text run when it encounters a page object like links or images.
if (char_index == breakpoint_index)
break;
unsigned int character = FPDFText_GetUnicode(text_page, char_index);
gfx::RectF char_rect =
GetFloatCharRectInPixels(page, text_page, char_index);
if (!base::IsUnicodeWhitespace(character)) {
// Heuristic: End the text run if the text style of the current character
// is different from the text run's style.
if (!AreTextStyleEqual(char_index, info.style))
break;
// Heuristic: End text run if character isn't going in the same direction.
if (char_direction !=
GetDirectionFromAngle(FPDFText_GetCharAngle(text_page, char_index)))
break;
// Heuristic: End the text run if the difference between the text run
// angle and the angle between the center-points of the previous and
// current characters is greater than 90 degrees.
float current_angle = GetAngleOfVector(char_rect.CenterPoint() -
prev_char_rect.CenterPoint());
if (start_char_rect != prev_char_rect) {
text_run_angle = GetAngleOfVector(prev_char_rect.CenterPoint() -
start_char_rect.CenterPoint());
if (GetAngleDifference(text_run_angle, current_angle) >
k90DegreesInRadians) {
break;
}
}
// Heuristic: End the text run if the center-point distance to the
// previous character is less than 2.5x the average character size.
AddCharSizeToAverageCharSize(char_rect.size(), &avg_char_size,
&non_whitespace_chars_count);
float avg_char_width = GetRotatedCharWidth(current_angle, avg_char_size);
float distance =
(char_rect.CenterPoint() - prev_char_rect.CenterPoint()).Length() -
GetRotatedCharWidth(current_angle, char_rect.size()) / 2 -
GetRotatedCharWidth(current_angle, prev_char_rect.size()) / 2;
if (distance > 2.5f * avg_char_width)
break;
text_run_bounds.Union(char_rect);
prev_char_rect = char_rect;
}
if (!char_rect.IsEmpty()) {
// Update the estimated font size if needed.
float char_largest_side = std::max(char_rect.height(), char_rect.width());
estimated_font_size = std::max(char_largest_side, estimated_font_size);
}
char_index++;
}
// Some PDFs have missing or obviously bogus font sizes; substitute the
// font size by the width or height (whichever's the largest) of the bigger
// character in the current text run.
if (text_run_font_size <= 1 || text_run_font_size < estimated_font_size / 2 ||
text_run_font_size > estimated_font_size * 2) {
text_run_font_size = estimated_font_size;
}
info.len = char_index - start_char_index;
info.style.font_size = text_run_font_size;
info.bounds = text_run_bounds;
// Infer text direction from first and last character of the text run. We
// can't base our decision on the character direction, since a character of a
// RTL language will have an angle of 0 when not rotated, just like a
// character in a LTR language.
info.direction = char_index - actual_start_char_index > 1
? GetDirectionFromAngle(text_run_angle)
: AccessibilityTextDirection::kNone;
return info;
}
uint32_t PDFiumPage::GetCharUnicode(int char_index) {
FPDF_TEXTPAGE text_page = GetTextPage();
return FPDFText_GetUnicode(text_page, char_index);
}
gfx::RectF PDFiumPage::GetCharBounds(int char_index) {
FPDF_PAGE page = GetPage();
FPDF_TEXTPAGE text_page = GetTextPage();
return GetFloatCharRectInPixels(page, text_page, char_index);
}
std::vector<PDFEngine::AccessibilityLinkInfo> PDFiumPage::GetLinkInfo() {
std::vector<PDFEngine::AccessibilityLinkInfo> link_info;
if (!available_)
return link_info;
CalculateLinks();
link_info.reserve(links_.size());
for (const Link& link : links_) {
PDFEngine::AccessibilityLinkInfo cur_info;
cur_info.url = link.target.url;
cur_info.start_char_index = link.start_char_index;
cur_info.char_count = link.char_count;
gfx::Rect link_rect;
for (const auto& rect : link.bounding_rects)
link_rect.Union(rect);
cur_info.bounds = gfx::RectF(link_rect.x(), link_rect.y(),
link_rect.width(), link_rect.height());
link_info.push_back(std::move(cur_info));
}
return link_info;
}
std::vector<PDFEngine::AccessibilityImageInfo> PDFiumPage::GetImageInfo() {
std::vector<PDFEngine::AccessibilityImageInfo> image_info;
if (!available_)
return image_info;
CalculateImages();
image_info.reserve(images_.size());
for (const Image& image : images_) {
PDFEngine::AccessibilityImageInfo cur_info;
cur_info.alt_text = image.alt_text;
cur_info.bounds =
gfx::RectF(image.bounding_rect.x(), image.bounding_rect.y(),
image.bounding_rect.width(), image.bounding_rect.height());
image_info.push_back(std::move(cur_info));
}
return image_info;
}
std::vector<PDFEngine::AccessibilityHighlightInfo>
PDFiumPage::GetHighlightInfo() {
std::vector<PDFEngine::AccessibilityHighlightInfo> highlight_info;
if (!available_)
return highlight_info;
PopulateAnnotations();
highlight_info.reserve(highlights_.size());
for (const Highlight& highlight : highlights_) {
PDFEngine::AccessibilityHighlightInfo cur_info;
cur_info.start_char_index = highlight.start_char_index;
cur_info.char_count = highlight.char_count;
cur_info.bounds = gfx::RectF(
highlight.bounding_rect.x(), highlight.bounding_rect.y(),
highlight.bounding_rect.width(), highlight.bounding_rect.height());
cur_info.color = highlight.color;
cur_info.note_text = highlight.note_text;
highlight_info.push_back(std::move(cur_info));
}
return highlight_info;
}
std::vector<PDFEngine::AccessibilityTextFieldInfo>
PDFiumPage::GetTextFieldInfo() {
std::vector<PDFEngine::AccessibilityTextFieldInfo> text_field_info;
if (!available_)
return text_field_info;
PopulateAnnotations();
text_field_info.reserve(text_fields_.size());
for (const TextField& text_field : text_fields_) {
PDFEngine::AccessibilityTextFieldInfo cur_info;
cur_info.name = text_field.name;
cur_info.value = text_field.value;
cur_info.is_read_only = !!(text_field.flags & FPDF_FORMFLAG_READONLY);
cur_info.is_required = !!(text_field.flags & FPDF_FORMFLAG_REQUIRED);
cur_info.is_password = !!(text_field.flags & FPDF_FORMFLAG_TEXT_PASSWORD);
cur_info.bounds = gfx::RectF(
text_field.bounding_rect.x(), text_field.bounding_rect.y(),
text_field.bounding_rect.width(), text_field.bounding_rect.height());
text_field_info.push_back(std::move(cur_info));
}
return text_field_info;
}
PDFiumPage::Area PDFiumPage::GetLinkTargetAtIndex(int link_index,
LinkTarget* target) {
if (!available_ || link_index < 0)
return NONSELECTABLE_AREA;
CalculateLinks();
if (link_index >= static_cast<int>(links_.size()))
return NONSELECTABLE_AREA;
*target = links_[link_index].target;
return target->url.empty() ? DOCLINK_AREA : WEBLINK_AREA;
}
PDFiumPage::Area PDFiumPage::GetLinkTarget(FPDF_LINK link, LinkTarget* target) {
FPDF_DEST dest_link = FPDFLink_GetDest(engine_->doc(), link);
if (dest_link)
return GetDestinationTarget(dest_link, target);
FPDF_ACTION action = FPDFLink_GetAction(link);
if (!action)
return NONSELECTABLE_AREA;
switch (FPDFAction_GetType(action)) {
case PDFACTION_GOTO: {
FPDF_DEST dest_action = FPDFAction_GetDest(engine_->doc(), action);
if (dest_action)
return GetDestinationTarget(dest_action, target);
// TODO(crbug.com/55776): We don't fully support all types of the
// in-document links.
return NONSELECTABLE_AREA;
}
case PDFACTION_URI:
return GetURITarget(action, target);
// TODO(crbug.com/767191): Support PDFACTION_LAUNCH.
// TODO(crbug.com/142344): Support PDFACTION_REMOTEGOTO.
case PDFACTION_LAUNCH:
case PDFACTION_REMOTEGOTO:
default:
return NONSELECTABLE_AREA;
}
}
PDFiumPage::Area PDFiumPage::GetCharIndex(const gfx::Point& point,
PageOrientation orientation,
int* char_index,
int* form_type,
LinkTarget* target) {
if (!available_)
return NONSELECTABLE_AREA;
gfx::Point device_point = point - rect_.OffsetFromOrigin();
double new_x;
double new_y;
FPDF_BOOL ret =
FPDF_DeviceToPage(GetPage(), 0, 0, rect_.width(), rect_.height(),
ToPDFiumRotation(orientation), device_point.x(),
device_point.y(), &new_x, &new_y);
DCHECK(ret);
// hit detection tolerance, in points.
constexpr double kTolerance = 20.0;
int rv = FPDFText_GetCharIndexAtPos(GetTextPage(), new_x, new_y, kTolerance,
kTolerance);
*char_index = rv;
FPDF_LINK link = FPDFLink_GetLinkAtPoint(GetPage(), new_x, new_y);
int control =
FPDFPage_HasFormFieldAtPoint(engine_->form(), GetPage(), new_x, new_y);
// If there is a control and link at the same point, figure out their z-order
// to determine which is on top.
if (link && control > FPDF_FORMFIELD_UNKNOWN) {
int control_z_order = FPDFPage_FormFieldZOrderAtPoint(
engine_->form(), GetPage(), new_x, new_y);
int link_z_order = FPDFLink_GetLinkZOrderAtPoint(GetPage(), new_x, new_y);
DCHECK_NE(control_z_order, link_z_order);
if (control_z_order > link_z_order) {
*form_type = control;
return FormTypeToArea(*form_type);
}
// We don't handle all possible link types of the PDF. For example,
// launch actions, cross-document links, etc.
// In that case, GetLinkTarget() will return NONSELECTABLE_AREA
// and we should proceed with area detection.
Area area = GetLinkTarget(link, target);
if (area != NONSELECTABLE_AREA)
return area;
} else if (link) {
// We don't handle all possible link types of the PDF. For example,
// launch actions, cross-document links, etc.
// See identical block above.
Area area = GetLinkTarget(link, target);
if (area != NONSELECTABLE_AREA)
return area;
} else if (control > FPDF_FORMFIELD_UNKNOWN) {
*form_type = control;
return FormTypeToArea(*form_type);
}
if (rv < 0)
return NONSELECTABLE_AREA;
return GetLink(*char_index, target) != -1 ? WEBLINK_AREA : TEXT_AREA;
}
// static
PDFiumPage::Area PDFiumPage::FormTypeToArea(int form_type) {
switch (form_type) {
case FPDF_FORMFIELD_COMBOBOX:
case FPDF_FORMFIELD_TEXTFIELD:
#if defined(PDF_ENABLE_XFA)
// TODO(bug_353450): figure out selection and copying for XFA fields.
case FPDF_FORMFIELD_XFA_COMBOBOX:
case FPDF_FORMFIELD_XFA_TEXTFIELD:
#endif
return FORM_TEXT_AREA;
default:
return NONSELECTABLE_AREA;
}
}
base::char16 PDFiumPage::GetCharAtIndex(int index) {
if (!available_)
return L'\0';
return static_cast<base::char16>(FPDFText_GetUnicode(GetTextPage(), index));
}
int PDFiumPage::GetCharCount() {
if (!available_)
return 0;
return FPDFText_CountChars(GetTextPage());
}
bool PDFiumPage::IsCharIndexInBounds(int index) {
return index >= 0 && index < GetCharCount();
}
PDFiumPage::Area PDFiumPage::GetDestinationTarget(FPDF_DEST destination,
LinkTarget* target) {
if (!target)
return NONSELECTABLE_AREA;
int page_index = FPDFDest_GetDestPageIndex(engine_->doc(), destination);
if (page_index < 0)
return NONSELECTABLE_AREA;
target->page = page_index;
base::Optional<gfx::PointF> xy;
GetPageDestinationTarget(destination, &xy, &target->zoom);
if (xy) {
gfx::PointF point = TransformPageToScreenXY(xy.value());
target->x_in_pixels = point.x();
target->y_in_pixels = point.y();
}
return DOCLINK_AREA;
}
void PDFiumPage::GetPageDestinationTarget(FPDF_DEST destination,
base::Optional<gfx::PointF>* xy,
base::Optional<float>* zoom_value) {
*xy = base::nullopt;
*zoom_value = base::nullopt;
if (!available_)
return;
FPDF_BOOL has_x_coord;
FPDF_BOOL has_y_coord;
FPDF_BOOL has_zoom;
FS_FLOAT x;
FS_FLOAT y;
FS_FLOAT zoom;
FPDF_BOOL success = FPDFDest_GetLocationInPage(
destination, &has_x_coord, &has_y_coord, &has_zoom, &x, &y, &zoom);
if (!success)
return;
if (has_x_coord && has_y_coord)
*xy = gfx::PointF(x, y);
if (has_zoom)
*zoom_value = zoom;
}
gfx::PointF PDFiumPage::TransformPageToScreenXY(const gfx::PointF& xy) {
if (!available_)
return gfx::PointF();
gfx::RectF page_rect(xy.x(), xy.y(), 0, 0);
gfx::RectF pixel_rect(FloatPageRectToPixelRect(GetPage(), page_rect));
return gfx::PointF(pixel_rect.x(), pixel_rect.y());
}
PDFiumPage::Area PDFiumPage::GetURITarget(FPDF_ACTION uri_action,
LinkTarget* target) const {
if (target) {
std::string url = CallPDFiumStringBufferApi(
base::BindRepeating(&FPDFAction_GetURIPath, engine_->doc(), uri_action),
/*check_expected_size=*/true);
if (!url.empty())
target->url = url;
}
return WEBLINK_AREA;
}
int PDFiumPage::GetLink(int char_index, LinkTarget* target) {
if (!available_)
return -1;
CalculateLinks();
// Get the bounding box of the rect again, since it might have moved because
// of the tolerance above.
double left;
double right;
double bottom;
double top;
if (!FPDFText_GetCharBox(GetTextPage(), char_index, &left, &right, &bottom,
&top)) {
return -1;
}
gfx::Point origin = PageToScreen(gfx::Point(), 1.0, left, top, right, bottom,
PageOrientation::kOriginal)
.origin();
for (size_t i = 0; i < links_.size(); ++i) {
for (const auto& rect : links_[i].bounding_rects) {
if (rect.Contains(origin)) {
if (target)
target->url = links_[i].target.url;
return i;
}
}
}
return -1;
}
void PDFiumPage::CalculateLinks() {
if (calculated_links_)
return;
calculated_links_ = true;
PopulateWebLinks();
PopulateAnnotationLinks();
}
void PDFiumPage::PopulateWebLinks() {
ScopedFPDFPageLink links(FPDFLink_LoadWebLinks(GetTextPage()));
int count = FPDFLink_CountWebLinks(links.get());
for (int i = 0; i < count; ++i) {
// WARNING: FPDFLink_GetURL() is not compatible with
// CallPDFiumWideStringBufferApi().
base::string16 url;
int url_length = FPDFLink_GetURL(links.get(), i, nullptr, 0);
if (url_length > 0) {
PDFiumAPIStringBufferAdapter<base::string16> api_string_adapter(
&url, url_length, true);
unsigned short* data =
reinterpret_cast<unsigned short*>(api_string_adapter.GetData());
int actual_length = FPDFLink_GetURL(links.get(), i, data, url_length);
api_string_adapter.Close(actual_length);
}
Link link;
link.target.url = base::UTF16ToUTF8(url);
if (!engine_->IsValidLink(link.target.url))
continue;
// Make sure all the characters in the URL are valid per RFC 1738.
// http://crbug.com/340326 has a sample bad PDF.
// GURL does not work correctly, e.g. it just strips \t \r \n.
bool is_invalid_url = false;
for (size_t j = 0; j < link.target.url.length(); ++j) {
// Control characters are not allowed.
// 0x7F is also a control character.
// 0x80 and above are not in US-ASCII.
if (link.target.url[j] < ' ' || link.target.url[j] >= '\x7F') {
is_invalid_url = true;
break;
}
}
if (is_invalid_url)
continue;
int rect_count = FPDFLink_CountRects(links.get(), i);
for (int j = 0; j < rect_count; ++j) {
double left;
double top;
double right;
double bottom;
FPDFLink_GetRect(links.get(), i, j, &left, &top, &right, &bottom);
gfx::Rect rect = PageToScreen(gfx::Point(), 1.0, left, top, right, bottom,
PageOrientation::kOriginal);
if (rect.IsEmpty())
continue;
link.bounding_rects.push_back(rect);