forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpdf_view_plugin_base.cc
1794 lines (1484 loc) · 62.6 KB
/
pdf_view_plugin_base.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 2020 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/pdf_view_plugin_base.h"
#include <algorithm>
#include <cmath>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include "base/auto_reset.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/check.h"
#include "base/check_op.h"
#include "base/containers/contains.h"
#include "base/containers/fixed_flat_map.h"
#include "base/containers/flat_set.h"
#include "base/containers/span.h"
#include "base/cxx17_backports.h"
#include "base/feature_list.h"
#include "base/i18n/rtl.h"
#include "base/i18n/time_formatting.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/notreached.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/chromeos_buildflags.h"
#include "net/base/escape.h"
#include "pdf/accessibility.h"
#include "pdf/accessibility_structs.h"
#include "pdf/buildflags.h"
#include "pdf/content_restriction.h"
#include "pdf/document_layout.h"
#include "pdf/document_metadata.h"
#include "pdf/paint_ready_rect.h"
#include "pdf/pdf_engine.h"
#include "pdf/pdf_features.h"
#include "pdf/pdfium/pdfium_engine.h"
#include "pdf/pdfium/pdfium_form_filler.h"
#include "pdf/ppapi_migration/image.h"
#include "pdf/ppapi_migration/result_codes.h"
#include "pdf/ppapi_migration/url_loader.h"
#include "pdf/ui/document_properties.h"
#include "pdf/ui/file_name.h"
#include "pdf/ui/thumbnail.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/input/web_mouse_event.h"
#include "third_party/blink/public/common/input/web_touch_event.h"
#include "third_party/blink/public/web/web_print_preset_options.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/text/bytes_formatting.h"
#include "ui/events/blink/blink_event_util.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/gfx/geometry/vector2d.h"
#include "ui/gfx/geometry/vector2d_f.h"
#include "url/gurl.h"
namespace chrome_pdf {
namespace {
// The minimum zoom level allowed.
constexpr double kMinZoom = 0.01;
// A delay to wait between each accessibility page to keep the system
// responsive.
constexpr base::TimeDelta kAccessibilityPageDelay = base::Milliseconds(100);
constexpr base::TimeDelta kFindResultCooldown = base::Milliseconds(100);
constexpr char kChromeExtensionHost[] =
"chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/";
// Same value as printing::COMPLETE_PREVIEW_DOCUMENT_INDEX.
constexpr int kCompletePDFIndex = -1;
// A different negative value to differentiate itself from `kCompletePDFIndex`.
constexpr int kInvalidPDFIndex = -2;
// Enumeration of pinch states.
// This should match PinchPhase enum in chrome/browser/resources/pdf/viewport.js
enum class PinchPhase {
kNone = 0,
kStart = 1,
kUpdateZoomOut = 2,
kUpdateZoomIn = 3,
kEnd = 4,
};
// Prepares messages from the plugin that reply to messages from the embedder.
// If the "type" value of `message` is "foo", then the `reply_type` must be
// "fooReply". The `message` from the embedder must have a "messageId" value
// that will be copied to the reply message.
base::Value PrepareReplyMessage(base::StringPiece reply_type,
const base::Value& message) {
DCHECK_EQ(reply_type, *message.FindStringKey("type") + "Reply");
base::Value reply(base::Value::Type::DICTIONARY);
reply.SetStringKey("type", reply_type);
reply.SetStringKey("messageId", *message.FindStringKey("messageId"));
return reply;
}
bool IsPrintPreviewUrl(base::StringPiece url) {
return base::StartsWith(url, PdfViewPluginBase::kChromeUntrustedPrintHost);
}
int ExtractPrintPreviewPageIndex(base::StringPiece src_url) {
// Sample `src_url` format: chrome-untrusted://print/id/page_index/print.pdf
// The page_index is zero-based, but can be negative with special meanings.
std::vector<base::StringPiece> url_substr = base::SplitStringPiece(
src_url.substr(PdfViewPluginBase::kChromeUntrustedPrintHost.size()), "/",
base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
if (url_substr.size() != 3)
return kInvalidPDFIndex;
if (url_substr[2] != "print.pdf")
return kInvalidPDFIndex;
int page_index = 0;
if (!base::StringToInt(url_substr[1], &page_index))
return kInvalidPDFIndex;
return page_index;
}
bool IsPreviewingPDF(int print_preview_page_count) {
return print_preview_page_count == 0;
}
} // namespace
// static
constexpr base::StringPiece PdfViewPluginBase::kChromePrintHost;
// static
constexpr base::StringPiece PdfViewPluginBase::kChromeUntrustedPrintHost;
PdfViewPluginBase::PdfViewPluginBase() = default;
PdfViewPluginBase::~PdfViewPluginBase() = default;
void PdfViewPluginBase::InitializeBase(std::unique_ptr<PDFiumEngine> engine,
base::StringPiece embedder_origin,
base::StringPiece src_url,
base::StringPiece original_url,
bool full_frame,
SkColor background_color,
bool has_edits) {
// Check if the PDF is being loaded in the PDF chrome extension. We only allow
// the plugin to be loaded in the extension and print preview to avoid
// exposing sensitive APIs directly to external websites.
//
// This is enforced before launching the plugin process (see
// ChromeContentBrowserClient::ShouldAllowPluginCreation), so below we just do
// a CHECK as a defense-in-depth.
is_print_preview_ = (embedder_origin == kChromePrintHost);
CHECK(IsPrintPreview() || embedder_origin == kChromeExtensionHost);
full_frame_ = full_frame;
background_color_ = background_color;
DCHECK(engine);
engine_ = std::move(engine);
// If we're in print preview mode we don't need to load the document yet.
// A `kJSResetPrintPreviewModeType` message will be sent to the plugin letting
// it know the url to load. By not loading here we avoid loading the same
// document twice.
if (IsPrintPreview())
return;
LoadUrl(src_url, /*is_print_preview=*/false);
url_ = std::string(original_url);
// Not all edits go through the PDF plugin's form filler. The plugin instance
// can be restarted by exiting annotation mode on ChromeOS, which can set the
// document to an edited state.
edit_mode_ = has_edits;
#if !BUILDFLAG(ENABLE_INK)
DCHECK(!edit_mode_);
#endif // !BUILDFLAG(ENABLE_INK)
}
void PdfViewPluginBase::ProposeDocumentLayout(const DocumentLayout& layout) {
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "documentDimensions");
message.SetIntKey("width", layout.size().width());
message.SetIntKey("height", layout.size().height());
message.SetKey("layoutOptions", layout.options().ToValue());
base::Value page_dimensions_list(base::Value::Type::LIST);
for (size_t i = 0; i < layout.page_count(); ++i)
page_dimensions_list.Append(base::Value(DictFromRect(layout.page_rect(i))));
message.SetKey("pageDimensions", std::move(page_dimensions_list));
SendMessage(std::move(message));
// Reload the accessibility tree on layout changes because the relative page
// bounds are no longer valid.
if (layout.dirty() && accessibility_state_ == AccessibilityState::kLoaded)
LoadAccessibility();
}
void PdfViewPluginBase::Invalidate(const gfx::Rect& rect) {
if (in_paint_) {
deferred_invalidates_.push_back(rect);
return;
}
gfx::Rect offset_rect = rect + available_area_.OffsetFromOrigin();
paint_manager_.InvalidateRect(offset_rect);
}
void PdfViewPluginBase::DidScroll(const gfx::Vector2d& offset) {
if (!image_data_.drawsNothing())
paint_manager_.ScrollRect(available_area_, offset);
}
void PdfViewPluginBase::ScrollToX(int x_screen_coords) {
const float x_scroll_pos = x_screen_coords / device_scale_;
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "setScrollPosition");
message.SetDoubleKey("x", x_scroll_pos);
SendMessage(std::move(message));
}
void PdfViewPluginBase::ScrollToY(int y_screen_coords) {
const float y_scroll_pos = y_screen_coords / device_scale_;
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "setScrollPosition");
message.SetDoubleKey("y", y_scroll_pos);
SendMessage(std::move(message));
}
void PdfViewPluginBase::ScrollBy(const gfx::Vector2d& delta) {
const float x_delta = delta.x() / device_scale_;
const float y_delta = delta.y() / device_scale_;
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "scrollBy");
message.SetDoubleKey("x", x_delta);
message.SetDoubleKey("y", y_delta);
SendMessage(std::move(message));
}
void PdfViewPluginBase::ScrollToPage(int page) {
if (!engine_ || engine_->GetNumberOfPages() == 0)
return;
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "goToPage");
message.SetIntKey("page", page);
SendMessage(std::move(message));
}
void PdfViewPluginBase::NavigateTo(const std::string& url,
WindowOpenDisposition disposition) {
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "navigate");
message.SetStringKey("url", url);
message.SetIntKey("disposition", static_cast<int>(disposition));
SendMessage(std::move(message));
}
void PdfViewPluginBase::NavigateToDestination(int page,
const float* x,
const float* y,
const float* zoom) {
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "navigateToDestination");
message.SetIntKey("page", page);
if (x)
message.SetDoubleKey("x", *x);
if (y)
message.SetDoubleKey("y", *y);
if (zoom)
message.SetDoubleKey("zoom", *zoom);
SendMessage(std::move(message));
}
void PdfViewPluginBase::UpdateTickMarks(
const std::vector<gfx::Rect>& tickmarks) {
float inverse_scale = 1.0f / device_scale_;
tickmarks_.clear();
tickmarks_.reserve(tickmarks.size());
std::transform(tickmarks.begin(), tickmarks.end(),
std::back_inserter(tickmarks_),
[inverse_scale](const gfx::Rect& t) -> gfx::Rect {
return gfx::ScaleToEnclosingRect(t, inverse_scale);
});
}
void PdfViewPluginBase::NotifyNumberOfFindResultsChanged(int total,
bool final_result) {
// We don't want to spam the renderer with too many updates to the number of
// find results. Don't send an update if we sent one too recently. If it's the
// final update, we always send it though.
if (recently_sent_find_update_ && !final_result)
return;
NotifyFindResultsChanged(total, final_result);
NotifyFindTickmarks(tickmarks_);
if (final_result)
return;
recently_sent_find_update_ = true;
ScheduleTaskOnMainThread(
FROM_HERE,
base::BindOnce(&PdfViewPluginBase::ResetRecentlySentFindUpdate,
GetWeakPtr()),
/*result=*/0, kFindResultCooldown);
}
void PdfViewPluginBase::NotifyTouchSelectionOccurred() {
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "touchSelectionOccurred");
SendMessage(std::move(message));
}
void PdfViewPluginBase::GetDocumentPassword(
base::OnceCallback<void(const std::string&)> callback) {
DCHECK(password_callback_.is_null());
password_callback_ = std::move(callback);
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "getPassword");
SendMessage(std::move(message));
}
void PdfViewPluginBase::Beep() {
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "beep");
SendMessage(std::move(message));
}
std::string PdfViewPluginBase::GetURL() {
return url_;
}
void PdfViewPluginBase::Email(const std::string& to,
const std::string& cc,
const std::string& bcc,
const std::string& subject,
const std::string& body) {
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "email");
message.SetStringKey("to", net::EscapeUrlEncodedData(to, false));
message.SetStringKey("cc", net::EscapeUrlEncodedData(cc, false));
message.SetStringKey("bcc", net::EscapeUrlEncodedData(bcc, false));
message.SetStringKey("subject", net::EscapeUrlEncodedData(subject, false));
message.SetStringKey("body", net::EscapeUrlEncodedData(body, false));
SendMessage(std::move(message));
}
void PdfViewPluginBase::Print() {
if (!engine_)
return;
const bool can_print =
engine_->HasPermission(DocumentPermission::kPrintLowQuality) ||
engine_->HasPermission(DocumentPermission::kPrintHighQuality);
if (!can_print)
return;
InvokePrintDialog();
}
void PdfViewPluginBase::SubmitForm(const std::string& url,
const void* data,
int length) {
// `url` might be a relative URL. Resolve it against the document's URL.
GURL resolved_url = GURL(GetURL()).Resolve(url);
if (!resolved_url.is_valid())
return;
UrlRequest request;
request.url = resolved_url.spec();
request.method = "POST";
request.body.assign(static_cast<const char*>(data), length);
form_loader_ = CreateUrlLoaderInternal();
form_loader_->Open(
request, base::BindOnce(&PdfViewPluginBase::DidFormOpen, GetWeakPtr()));
}
std::unique_ptr<UrlLoader> PdfViewPluginBase::CreateUrlLoader() {
if (full_frame_) {
DidStartLoading();
// Disable save and print until the document is fully loaded, since they
// would generate an incomplete document. This needs to be done each time
// DidStartLoading() is called because that resets the content restrictions.
SetContentRestrictions(kContentRestrictionSave | kContentRestrictionPrint);
}
return CreateUrlLoaderInternal();
}
void PdfViewPluginBase::DocumentLoadComplete() {
DCHECK_EQ(DocumentLoadState::kLoading, document_load_state_);
document_load_state_ = DocumentLoadState::kComplete;
UserMetricsRecordAction("PDF.LoadSuccess");
RecordDocumentMetrics();
// Clear the focus state for on-screen keyboards.
FormTextFieldFocusChange(false);
if (IsPrintPreview())
OnPrintPreviewLoaded();
SendAttachments();
SendBookmarks();
SendMetadata();
if (accessibility_state_ == AccessibilityState::kPending)
LoadAccessibility();
if (!full_frame_)
return;
DidStopLoading();
SetContentRestrictions(GetContentRestrictions());
}
void PdfViewPluginBase::DocumentLoadFailed() {
DCHECK_EQ(DocumentLoadState::kLoading, document_load_state_);
document_load_state_ = DocumentLoadState::kFailed;
UserMetricsRecordAction("PDF.LoadFailure");
// Send a progress value of -1 to indicate a failure.
SendLoadingProgress(-1);
DidStopLoading();
paint_manager_.InvalidateRect(gfx::Rect(plugin_rect_.size()));
}
void PdfViewPluginBase::DocumentHasUnsupportedFeature(
const std::string& feature) {
DCHECK(!feature.empty());
const std::string metric = "PDF_Unsupported_" + feature;
bool inserted = unsupported_features_reported_.insert(metric).second;
if (inserted)
UserMetricsRecordAction(metric);
if (!full_frame() || notified_browser_about_unsupported_feature_)
return;
NotifyUnsupportedFeature();
notified_browser_about_unsupported_feature_ = true;
}
void PdfViewPluginBase::DocumentLoadProgress(uint32_t available,
uint32_t doc_size) {
double progress = 0.0;
if (doc_size > 0) {
progress = 100.0 * static_cast<double>(available) / doc_size;
} else {
// Use heuristics when the document size is unknown.
// Progress logarithmically from 0 to 100M.
static const double kFactor = std::log(100'000'000.0) / 100.0;
if (available > 0)
progress =
std::min(std::log(static_cast<double>(available)) / kFactor, 100.0);
}
// DocumentLoadComplete() will send the 100% load progress.
if (progress >= 100)
return;
// Avoid sending too many progress messages over PostMessage.
if (progress <= last_progress_sent_ + 1)
return;
SendLoadingProgress(progress);
}
void PdfViewPluginBase::FormTextFieldFocusChange(bool in_focus) {
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "formFocusChange");
message.SetBoolKey("focused", in_focus);
SendMessage(std::move(message));
SetFormFieldInFocus(in_focus);
}
bool PdfViewPluginBase::IsPrintPreview() const {
return is_print_preview_;
}
SkColor PdfViewPluginBase::GetBackgroundColor() {
return background_color_;
}
void PdfViewPluginBase::SetIsSelecting(bool is_selecting) {
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "setIsSelecting");
message.SetBoolKey("isSelecting", is_selecting);
SendMessage(std::move(message));
}
void PdfViewPluginBase::SelectionChanged(const gfx::Rect& left,
const gfx::Rect& right) {
const gfx::Rect left_with_offset = left + plugin_rect_.OffsetFromOrigin();
const gfx::Rect right_with_offset = right + plugin_rect_.OffsetFromOrigin();
gfx::PointF left_point(left_with_offset.x() + available_area_.x(),
left_with_offset.y());
gfx::PointF right_point(right_with_offset.x() + available_area_.x(),
right_with_offset.y());
const float inverse_scale = 1.0f / device_scale_;
left_point.Scale(inverse_scale);
right_point.Scale(inverse_scale);
NotifySelectionChanged(left_point, left_with_offset.height(), right_point,
right_with_offset.height());
if (accessibility_state_ == AccessibilityState::kLoaded)
PrepareAndSetAccessibilityViewportInfo();
}
void PdfViewPluginBase::EnteredEditMode() {
edit_mode_ = true;
SetPluginCanSave(true);
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "setIsEditing");
SendMessage(std::move(message));
}
void PdfViewPluginBase::DocumentFocusChanged(bool document_has_focus) {
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "documentFocusChanged");
message.SetBoolKey("hasFocus", document_has_focus);
SendMessage(std::move(message));
}
void PdfViewPluginBase::SetLinkUnderCursor(
const std::string& link_under_cursor) {
if (link_under_cursor_ == link_under_cursor)
return;
link_under_cursor_ = link_under_cursor;
NotifyLinkUnderCursor();
}
// TODO(crbug.com/1191817): Add tests for input events. Unit testing should be
// feasible now that the Pepper dependency is removed for input events.
bool PdfViewPluginBase::HandleInputEvent(const blink::WebInputEvent& event) {
// Ignore user input in read-only mode.
if (engine()->IsReadOnly())
return false;
// `engine()` expects input events in device coordinates.
std::unique_ptr<blink::WebInputEvent> transformed_event =
ui::TranslateAndScaleWebInputEvent(
event, gfx::Vector2dF(-available_area_.x() / device_scale_, 0),
device_scale_);
const blink::WebInputEvent& event_to_handle =
transformed_event ? *transformed_event : event;
if (engine()->HandleInputEvent(event_to_handle))
return true;
// Middle click is used for scrolling and is handled by the container page.
if (blink::WebInputEvent::IsMouseEventType(event_to_handle.GetType()) &&
static_cast<const blink::WebMouseEvent&>(event_to_handle).button ==
blink::WebPointerProperties::Button::kMiddle) {
return false;
}
// Return true for unhandled clicks so the plugin takes focus.
return event_to_handle.GetType() == blink::WebInputEvent::Type::kMouseDown;
}
void PdfViewPluginBase::HandleMessage(const base::Value& message) {
using MessageHandler = void (PdfViewPluginBase::*)(const base::Value&);
static constexpr auto kMessageHandlers =
base::MakeFixedFlatMap<base::StringPiece, MessageHandler>({
{"displayAnnotations",
&PdfViewPluginBase::HandleDisplayAnnotationsMessage},
{"getNamedDestination",
&PdfViewPluginBase::HandleGetNamedDestinationMessage},
{"getPasswordComplete",
&PdfViewPluginBase::HandleGetPasswordCompleteMessage},
{"getSelectedText", &PdfViewPluginBase::HandleGetSelectedTextMessage},
{"getThumbnail", &PdfViewPluginBase::HandleGetThumbnailMessage},
{"print", &PdfViewPluginBase::HandlePrintMessage},
{"loadPreviewPage", &PdfViewPluginBase::HandleLoadPreviewPageMessage},
{"resetPrintPreviewMode",
&PdfViewPluginBase::HandleResetPrintPreviewModeMessage},
{"rotateClockwise", &PdfViewPluginBase::HandleRotateClockwiseMessage},
{"rotateCounterclockwise",
&PdfViewPluginBase::HandleRotateCounterclockwiseMessage},
{"save", &PdfViewPluginBase::HandleSaveMessage},
{"saveAttachment", &PdfViewPluginBase::HandleSaveAttachmentMessage},
{"selectAll", &PdfViewPluginBase::HandleSelectAllMessage},
{"setBackgroundColor",
&PdfViewPluginBase::HandleSetBackgroundColorMessage},
{"setReadOnly", &PdfViewPluginBase::HandleSetReadOnlyMessage},
{"setTwoUpView", &PdfViewPluginBase::HandleSetTwoUpViewMessage},
{"stopScrolling", &PdfViewPluginBase::HandleStopScrollingMessage},
{"updateScroll", &PdfViewPluginBase::HandleUpdateScrollMessage},
{"viewport", &PdfViewPluginBase::HandleViewportMessage},
});
MessageHandler handler = kMessageHandlers.at(*message.FindStringKey("type"));
(this->*handler)(message);
}
void PdfViewPluginBase::SaveToBuffer(const std::string& token) {
engine()->KillFormFocus();
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "saveData");
message.SetStringKey("token", token);
message.SetStringKey("fileName", GetFileNameForSaveFromUrl(url_));
// Expose `edit_mode_` state for integration testing.
message.SetBoolKey("editModeForTesting", edit_mode_);
base::Value data_to_save;
if (edit_mode_) {
base::Value::BlobStorage data = engine()->GetSaveData();
if (IsSaveDataSizeValid(data.size()))
data_to_save = base::Value(std::move(data));
} else {
#if BUILDFLAG(ENABLE_INK)
uint32_t length = engine()->GetLoadedByteSize();
if (IsSaveDataSizeValid(length)) {
base::Value::BlobStorage data(length);
if (engine()->ReadLoadedBytes(length, data.data()))
data_to_save = base::Value(std::move(data));
}
#else
NOTREACHED();
#endif // BUILDFLAG(ENABLE_INK)
}
message.SetKey("dataToSave", std::move(data_to_save));
SendMessage(std::move(message));
}
void PdfViewPluginBase::ConsumeSaveToken(const std::string& token) {
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "consumeSaveToken");
message.SetStringKey("token", token);
SendMessage(std::move(message));
}
void PdfViewPluginBase::SendLoadingProgress(double percentage) {
DCHECK(percentage == -1 || (percentage >= 0 && percentage <= 100));
last_progress_sent_ = percentage;
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "loadProgress");
message.SetDoubleKey("progress", percentage);
SendMessage(std::move(message));
}
void PdfViewPluginBase::SendPrintPreviewLoadedNotification() {
base::Value message(base::Value::Type::DICTIONARY);
message.SetStringKey("type", "printPreviewLoaded");
SendMessage(std::move(message));
}
void PdfViewPluginBase::OnPaint(const std::vector<gfx::Rect>& paint_rects,
std::vector<PaintReadyRect>& ready,
std::vector<gfx::Rect>& pending) {
base::AutoReset<bool> auto_reset_in_paint(&in_paint_, true);
DoPaint(paint_rects, ready, pending);
}
void PdfViewPluginBase::PreviewDocumentLoadComplete() {
if (preview_document_load_state_ != DocumentLoadState::kLoading ||
preview_pages_info_.empty()) {
return;
}
preview_document_load_state_ = DocumentLoadState::kComplete;
int dest_page_index = preview_pages_info_.front().second;
DCHECK_GT(dest_page_index, 0);
preview_pages_info_.pop();
DCHECK(preview_engine_);
engine()->AppendPage(preview_engine_.get(), dest_page_index);
++print_preview_loaded_page_count_;
LoadNextPreviewPage();
}
void PdfViewPluginBase::PreviewDocumentLoadFailed() {
UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
if (preview_document_load_state_ != DocumentLoadState::kLoading ||
preview_pages_info_.empty()) {
return;
}
// Even if a print preview page failed to load, keep going.
preview_document_load_state_ = DocumentLoadState::kFailed;
preview_pages_info_.pop();
++print_preview_loaded_page_count_;
LoadNextPreviewPage();
}
void PdfViewPluginBase::EnableAccessibility() {
if (accessibility_state_ == AccessibilityState::kLoaded)
return;
if (accessibility_state_ == AccessibilityState::kOff)
accessibility_state_ = AccessibilityState::kPending;
if (document_load_state_ == DocumentLoadState::kComplete)
LoadAccessibility();
}
void PdfViewPluginBase::HandleAccessibilityAction(
const AccessibilityActionData& action_data) {
engine_->HandleAccessibilityAction(action_data);
}
int PdfViewPluginBase::GetContentRestrictions() const {
int content_restrictions = kContentRestrictionCut | kContentRestrictionPaste;
if (!engine()->HasPermission(DocumentPermission::kCopy))
content_restrictions |= kContentRestrictionCopy;
if (!engine()->HasPermission(DocumentPermission::kPrintLowQuality) &&
!engine()->HasPermission(DocumentPermission::kPrintHighQuality)) {
content_restrictions |= kContentRestrictionPrint;
}
return content_restrictions;
}
AccessibilityDocInfo PdfViewPluginBase::GetAccessibilityDocInfo() const {
AccessibilityDocInfo doc_info;
doc_info.page_count = engine()->GetNumberOfPages();
doc_info.text_accessible =
engine()->HasPermission(DocumentPermission::kCopyAccessible);
doc_info.text_copyable = engine()->HasPermission(DocumentPermission::kCopy);
return doc_info;
}
bool PdfViewPluginBase::UnsupportedFeatureIsReportedForTesting(
const std::string& feature) const {
return base::Contains(unsupported_features_reported_, feature);
}
void PdfViewPluginBase::InitializeEngineForTesting(
std::unique_ptr<PDFiumEngine> engine) {
DCHECK(engine);
engine_ = std::move(engine);
}
std::unique_ptr<PDFiumEngine> PdfViewPluginBase::CreateEngine(
PDFEngine::Client* client,
PDFiumFormFiller::ScriptOption script_option) {
return std::make_unique<PDFiumEngine>(client, script_option);
}
void PdfViewPluginBase::DestroyEngine() {
engine_.reset();
}
void PdfViewPluginBase::DestroyPreviewEngine() {
preview_engine_.reset();
}
void PdfViewPluginBase::LoadUrl(base::StringPiece url, bool is_print_preview) {
// `last_progress_sent_` should only be reset for the primary load.
if (!is_print_preview)
last_progress_sent_ = 0;
UrlRequest request;
request.url = RewriteRequestUrl(url);
request.method = "GET";
request.ignore_redirects = true;
std::unique_ptr<UrlLoader> loader = CreateUrlLoaderInternal();
UrlLoader* raw_loader = loader.get();
raw_loader->Open(
request,
base::BindOnce(is_print_preview ? &PdfViewPluginBase::DidOpenPreview
: &PdfViewPluginBase::DidOpen,
GetWeakPtr(), std::move(loader)));
}
std::string PdfViewPluginBase::RewriteRequestUrl(base::StringPiece url) const {
return std::string(url);
}
void PdfViewPluginBase::InvalidateAfterPaintDone() {
if (deferred_invalidates_.empty())
return;
ScheduleTaskOnMainThread(
FROM_HERE,
base::BindOnce(&PdfViewPluginBase::ClearDeferredInvalidates,
GetWeakPtr()),
/*result=*/0, base::TimeDelta());
}
void PdfViewPluginBase::OnGeometryChanged(double old_zoom,
float old_device_scale) {
RecalculateAreas(old_zoom, old_device_scale);
if (accessibility_state_ == AccessibilityState::kLoaded)
PrepareAndSetAccessibilityViewportInfo();
}
blink::WebPrintPresetOptions PdfViewPluginBase::GetPrintPresetOptions() {
blink::WebPrintPresetOptions options;
options.is_scaling_disabled = !engine_->GetPrintScaling();
options.copies = engine_->GetCopiesToPrint();
options.duplex_mode = engine_->GetDuplexMode();
options.uniform_page_size = engine_->GetUniformPageSizePoints();
return options;
}
int PdfViewPluginBase::PrintBegin(const blink::WebPrintParams& print_params) {
// The returned value is always equal to the number of pages in the PDF
// document irrespective of the printable area.
int32_t ret = engine()->GetNumberOfPages();
if (!ret)
return 0;
const bool can_print =
engine()->HasPermission(DocumentPermission::kPrintHighQuality) ||
(print_params.rasterize_pdf &&
engine()->HasPermission(DocumentPermission::kPrintLowQuality));
if (!can_print)
return 0;
print_params_ = print_params;
engine()->PrintBegin();
return ret;
}
std::vector<uint8_t> PdfViewPluginBase::PrintPages(
const std::vector<int>& page_numbers) {
print_pages_called_ = true;
return engine()->PrintPages(page_numbers, print_params_.value());
}
void PdfViewPluginBase::PrintEnd() {
if (print_pages_called_)
UserMetricsRecordAction("PDF.PrintPage");
print_pages_called_ = false;
print_params_.reset();
engine_->PrintEnd();
}
void PdfViewPluginBase::UpdateGeometryOnPluginRectChanged(
const gfx::Rect& new_plugin_rect,
float new_device_scale) {
DCHECK_GT(new_device_scale, 0.0f);
if (new_device_scale == device_scale_ && new_plugin_rect == plugin_rect_)
return;
const float old_device_scale = device_scale_;
device_scale_ = new_device_scale;
plugin_rect_ = new_plugin_rect;
// TODO(crbug.com/1250173): For the Pepper-free plugin, `plugin_dip_size_` is
// calculated from the `window_rect` in PdfViewWebPlugin::UpdateGeometry().
// We should try to avoid the downscaling during this calculation process and
// maybe migrate off `plugin_dip_size_`.
plugin_dip_size_ =
gfx::ScaleToEnclosingRectSafe(new_plugin_rect, 1.0f / new_device_scale)
.size();
paint_manager_.SetSize(plugin_rect_.size(), device_scale_);
// Initialize the image data buffer if the context size changes.
const gfx::Size old_image_size = gfx::SkISizeToSize(image_data_.dimensions());
const gfx::Size new_image_size =
PaintManager::GetNewContextSize(old_image_size, plugin_rect_.size());
if (new_image_size != old_image_size) {
InitImageData(new_image_size);
first_paint_ = true;
}
// Skip updating the geometry if the new image data buffer is empty.
if (image_data_.drawsNothing())
return;
OnGeometryChanged(zoom_, old_device_scale);
}
Image PdfViewPluginBase::GetPluginImageData() const {
return Image(image_data_);
}
void PdfViewPluginBase::RecalculateAreas(double old_zoom,
float old_device_scale) {
if (zoom_ != old_zoom || device_scale_ != old_device_scale)
engine()->ZoomUpdated(zoom_ * device_scale_);
available_area_ = gfx::Rect(plugin_rect_.size());
int doc_width = GetDocumentPixelWidth();
if (doc_width < available_area_.width()) {
// Center the document horizontally inside the plugin rectangle.
available_area_.Offset((plugin_rect_.width() - doc_width) / 2, 0);
available_area_.set_width(doc_width);
}
// The distance between top of the plugin and the bottom of the document in
// pixels.
int bottom_of_document = GetDocumentPixelHeight();
if (bottom_of_document < plugin_rect_.height())
available_area_.set_height(bottom_of_document);
CalculateBackgroundParts();
engine()->PageOffsetUpdated(available_area_.OffsetFromOrigin());
engine()->PluginSizeUpdated(available_area_.size());
if (document_size_.IsEmpty())
return;
paint_manager_.InvalidateRect(gfx::Rect(plugin_rect_.size()));
}
void PdfViewPluginBase::CalculateBackgroundParts() {
background_parts_.clear();
int left_width = available_area_.x();
int right_start = available_area_.right();
int right_width = std::abs(plugin_rect_.width() - available_area_.right());
int bottom = std::min(available_area_.bottom(), plugin_rect_.height());
// Note: we assume the display of the PDF document is always centered
// horizontally, but not necessarily centered vertically.
// Add the left rectangle.
BackgroundPart part = {gfx::Rect(left_width, bottom), GetBackgroundColor()};
if (!part.location.IsEmpty())
background_parts_.push_back(part);
// Add the right rectangle.
part.location = gfx::Rect(right_start, 0, right_width, bottom);
if (!part.location.IsEmpty())
background_parts_.push_back(part);
// Add the bottom rectangle.
part.location = gfx::Rect(0, bottom, plugin_rect_.width(),
plugin_rect_.height() - bottom);
if (!part.location.IsEmpty())
background_parts_.push_back(part);
}
void PdfViewPluginBase::UpdateScroll(const gfx::Vector2dF& scroll_offset) {
if (stop_scrolling_)
return;
float max_x = std::max(document_size_.width() * static_cast<float>(zoom_) -
plugin_dip_size_.width(),
0.0f);
float max_y = std::max(document_size_.height() * static_cast<float>(zoom_) -
plugin_dip_size_.height(),
0.0f);
// TODO(crbug.com/1256965): Right-to-left scrolling currently is not
// compatible with the PDF viewer's "scroller" element.
gfx::PointF scroll_position;
if (ui_direction_ == base::i18n::RIGHT_TO_LEFT && IsPrintPreview())
scroll_position.set_x(max_x);
scroll_position += scroll_offset;
gfx::PointF scaled_scroll_position(
base::clamp(scroll_position.x(), 0.0f, max_x),
base::clamp(scroll_position.y(), 0.0f, max_y));
scaled_scroll_position.Scale(device_scale_);
engine()->ScrolledToXPosition(scaled_scroll_position.x());
engine()->ScrolledToYPosition(scaled_scroll_position.y());
}
int PdfViewPluginBase::GetDocumentPixelWidth() const {