forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdf_view_web_plugin.cc
2003 lines (1638 loc) · 67.2 KB
/
pdf_view_web_plugin.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_web_plugin.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/callback.h"
#include "base/check_op.h"
#include "base/containers/fixed_flat_map.h"
#include "base/containers/queue.h"
#include "base/debug/crash_logging.h"
#include "base/i18n/char_iterator.h"
#include "base/i18n/string_search.h"
#include "base/i18n/time_formatting.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/no_destructor.h"
#include "base/notreached.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/strcat.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/thread_annotations.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/threading/thread_checker.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/values.h"
#include "cc/paint/paint_canvas.h"
#include "cc/paint/paint_flags.h"
#include "cc/paint/paint_image.h"
#include "cc/paint/paint_image_builder.h"
#include "net/cookies/site_for_cookies.h"
#include "pdf/accessibility_structs.h"
#include "pdf/buildflags.h"
#include "pdf/content_restriction.h"
#include "pdf/document_layout.h"
#include "pdf/loader/result_codes.h"
#include "pdf/loader/url_loader.h"
#include "pdf/metrics_handler.h"
#include "pdf/mojom/pdf.mojom.h"
#include "pdf/paint_ready_rect.h"
#include "pdf/parsed_params.h"
#include "pdf/pdf_accessibility_data_handler.h"
#include "pdf/pdf_engine.h"
#include "pdf/pdf_init.h"
#include "pdf/pdfium/pdfium_engine.h"
#include "pdf/post_message_receiver.h"
#include "pdf/ui/document_properties.h"
#include "pdf/ui/file_name.h"
#include "pdf/ui/thumbnail.h"
#include "printing/metafile_skia.h"
#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/input/web_coalesced_input_event.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/input/web_keyboard_event.h"
#include "third_party/blink/public/common/metrics/document_update_reason.h"
#include "third_party/blink/public/mojom/input/focus_type.mojom-shared.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_input_event_result.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/platform/web_text_input_type.h"
#include "third_party/blink/public/platform/web_url.h"
#include "third_party/blink/public/platform/web_url_error.h"
#include "third_party/blink/public/platform/web_url_response.h"
#include "third_party/blink/public/web/web_associated_url_loader.h"
#include "third_party/blink/public/web/web_associated_url_loader_options.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_frame.h"
#include "third_party/blink/public/web/web_plugin_container.h"
#include "third_party/blink/public/web/web_plugin_params.h"
#include "third_party/blink/public/web/web_print_params.h"
#include "third_party/blink/public/web/web_print_preset_options.h"
#include "third_party/blink/public/web/web_view.h"
#include "third_party/blink/public/web/web_widget.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkColor.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkImageInfo.h"
#include "third_party/skia/include/core/SkRect.h"
#include "third_party/skia/include/core/SkRefCnt.h"
#include "third_party/skia/include/core/SkSize.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/base/text/bytes_formatting.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/blink/blink_event_util.h"
#include "ui/events/keycodes/keyboard_codes.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 "ui/gfx/range/range.h"
#include "url/gurl.h"
#include "v8/include/v8.h"
namespace chrome_pdf {
namespace {
// The minimum zoom level allowed.
constexpr double kMinZoom = 0.01;
constexpr base::TimeDelta kFindResultCooldown = base::Milliseconds(100);
constexpr base::StringPiece kChromeExtensionHost =
"chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/";
// Print Preview base URL.
constexpr base::StringPiece kChromePrintHost = "chrome://print/";
// Untrusted Print Preview base URL.
constexpr base::StringPiece kChromeUntrustedPrintHost =
"chrome-untrusted://print/";
// 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.ts.
enum class PinchPhase {
kNone = 0,
kStart = 1,
kUpdateZoomOut = 2,
kUpdateZoomIn = 3,
kEnd = 4,
};
// Initialization performed per renderer process. Initialization may be
// triggered from multiple plugin instances, but should only execute once.
//
// TODO(crbug.com/1123621): We may be able to simplify this once we've figured
// out exactly which processes need to initialize and shutdown PDFium.
class PerProcessInitializer final {
public:
static PerProcessInitializer& GetInstance() {
static base::NoDestructor<PerProcessInitializer,
base::AllowForTriviallyDestructibleType>
instance;
return *instance;
}
void Acquire() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK_GE(init_count_, 0);
if (init_count_++ > 0)
return;
DCHECK(!IsSDKInitializedViaPlugin());
InitializeSDK(/*enable_v8=*/true, FontMappingMode::kBlink);
SetIsSDKInitializedViaPlugin(true);
}
void Release() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK_GT(init_count_, 0);
if (--init_count_ > 0)
return;
DCHECK(IsSDKInitializedViaPlugin());
ShutdownSDK();
SetIsSDKInitializedViaPlugin(false);
}
private:
int init_count_ GUARDED_BY_CONTEXT(thread_checker_) = 0;
// TODO(crbug.com/1123731): Assuming PDFium is thread-hostile for now, and
// must use one thread exclusively.
THREAD_CHECKER(thread_checker_);
};
base::Value::Dict DictFromRect(const gfx::Rect& rect) {
base::Value::Dict dict;
dict.Set("x", rect.x());
dict.Set("y", rect.y());
dict.Set("width", rect.width());
dict.Set("height", rect.height());
return dict;
}
bool IsPrintPreviewUrl(base::StringPiece url) {
return base::StartsWith(url, 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(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;
}
// 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::Dict PrepareReplyMessage(base::StringPiece reply_type,
const base::Value::Dict& message) {
DCHECK_EQ(reply_type, *message.FindString("type") + "Reply");
base::Value::Dict reply;
reply.Set("type", reply_type);
reply.Set("messageId", *message.FindString("messageId"));
return reply;
}
} // namespace
std::unique_ptr<PDFiumEngine> PdfViewWebPlugin::Client::CreateEngine(
PDFEngine::Client* client,
PDFiumFormFiller::ScriptOption script_option) {
return std::make_unique<PDFiumEngine>(client, script_option);
}
std::unique_ptr<PdfAccessibilityDataHandler>
PdfViewWebPlugin::Client::CreateAccessibilityDataHandler(
PdfAccessibilityActionHandler* action_handler) {
return nullptr;
}
PdfViewWebPlugin::PdfViewWebPlugin(
std::unique_ptr<Client> client,
mojo::AssociatedRemote<pdf::mojom::PdfService> pdf_service,
const blink::WebPluginParams& params)
: client_(std::move(client)),
pdf_service_(std::move(pdf_service)),
initial_params_(params),
pdf_accessibility_data_handler_(
client_->CreateAccessibilityDataHandler(this)) {
DCHECK(pdf_service_);
pdf_service_->SetListener(listener_receiver_.BindNewPipeAndPassRemote());
}
PdfViewWebPlugin::~PdfViewWebPlugin() = default;
std::unique_ptr<PDFiumEngine> PdfViewWebPlugin::CreateEngine(
PDFEngine::Client* client,
PDFiumFormFiller::ScriptOption script_option) {
return client_->CreateEngine(client, script_option);
}
// TODO(crbug.com/1302059): Delete after merging with `PdfViewPluginBase`.
const PDFiumEngine* PdfViewWebPlugin::engine() const {
return engine_.get();
}
// TODO(crbug.com/1302059): Delete after merging with `PdfViewPluginBase`.
PDFiumEngine* PdfViewWebPlugin::engine() {
return engine_.get();
}
bool PdfViewWebPlugin::Initialize(blink::WebPluginContainer* container) {
DCHECK(container);
client_->SetPluginContainer(container);
DCHECK_EQ(container->Plugin(), this);
return InitializeCommon();
}
bool PdfViewWebPlugin::InitializeForTesting() {
return InitializeCommon();
}
bool PdfViewWebPlugin::InitializeCommon() {
// Allow the plugin to handle touch events.
client_->RequestTouchEventType(
blink::WebPluginContainer::kTouchEventRequestTypeRaw);
// Allow the plugin to handle find requests.
client_->UsePluginAsFindHandler();
absl::optional<ParsedParams> params = ParseWebPluginParams(initial_params_);
// The contents of `initial_params_` are no longer needed.
initial_params_ = {};
if (!params.has_value())
return false;
// Sets crash keys like `ppapi::proxy::PDFResource::SetCrashData()`. Note that
// we don't set the active URL from the top-level URL, as unlike within a
// plugin process, the active URL changes frequently within a renderer process
// (see crbug.com/1266050 for details).
//
// TODO(crbug.com/1266087): If multiple PDF plugin instances share the same
// renderer process, the crash key will be overwritten by the newest value.
static base::debug::CrashKeyString* subresource_url =
base::debug::AllocateCrashKeyString("subresource_url",
base::debug::CrashKeySize::Size256);
base::debug::SetCrashKeyString(subresource_url, params->original_url);
PerProcessInitializer::GetInstance().Acquire();
// 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 creating the plugin (see
// `pdf::CreateInternalPlugin()`), so we just `CHECK` for defense-in-depth.
const std::string& embedder_origin = client_->GetEmbedderOriginString();
is_print_preview_ = (embedder_origin == kChromePrintHost);
CHECK(IsPrintPreview() || embedder_origin == kChromeExtensionHost);
full_frame_ = params->full_frame;
background_color_ = params->background_color;
engine_ = CreateEngine(this, params->script_option);
DCHECK(engine_);
SendSetSmoothScrolling();
// Skip the remaining initialization when in Print Preview mode. Loading will
// continue after the plugin receives a "resetPrintPreviewMode" message.
if (IsPrintPreview())
return true;
set_last_progress_sent(0);
LoadUrl(params->src_url, base::BindOnce(&PdfViewWebPlugin::DidOpen,
weak_factory_.GetWeakPtr()));
url_ = params->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_ = params->has_edits;
#if !BUILDFLAG(ENABLE_INK)
DCHECK(!edit_mode_);
#endif // !BUILDFLAG(ENABLE_INK)
metrics_handler_ = std::make_unique<MetricsHandler>();
return true;
}
void PdfViewWebPlugin::SendSetSmoothScrolling() {
base::Value::Dict message;
message.Set("type", "setSmoothScrolling");
message.Set("smoothScrolling",
blink::Platform::Current()->IsScrollAnimatorEnabled());
SendMessage(std::move(message));
}
void PdfViewWebPlugin::DidOpen(std::unique_ptr<UrlLoader> loader,
int32_t result) {
if (result == kSuccess) {
if (!engine_->HandleDocumentLoad(std::move(loader), url_)) {
set_document_load_state(DocumentLoadState::kLoading);
DocumentLoadFailed();
}
} else if (result != kErrorAborted) {
DocumentLoadFailed();
}
}
void PdfViewWebPlugin::Destroy() {
if (client_->PluginContainer()) {
// Explicitly destroy the PDFEngine during destruction as it may call back
// into this object.
preview_engine_.reset();
engine_.reset();
PerProcessInitializer::GetInstance().Release();
client_->SetPluginContainer(nullptr);
}
delete this;
}
blink::WebPluginContainer* PdfViewWebPlugin::Container() const {
return client_->PluginContainer();
}
v8::Local<v8::Object> PdfViewWebPlugin::V8ScriptableObject(
v8::Isolate* isolate) {
if (scriptable_receiver_.IsEmpty()) {
// TODO(crbug.com/1123731): Messages should not be handled on the renderer
// main thread.
scriptable_receiver_.Reset(
isolate, PostMessageReceiver::Create(
isolate, client_->GetWeakPtr(), weak_factory_.GetWeakPtr(),
base::SequencedTaskRunnerHandle::Get()));
}
return scriptable_receiver_.Get(isolate);
}
bool PdfViewWebPlugin::SupportsKeyboardFocus() const {
return !IsPrintPreview();
}
void PdfViewWebPlugin::UpdateAllLifecyclePhases(
blink::DocumentUpdateReason reason) {}
void PdfViewWebPlugin::Paint(cc::PaintCanvas* canvas, const gfx::Rect& rect) {
// Clip the intersection of the paint rect and the plugin rect, so that
// painting outside the plugin or the paint rect area can be avoided.
// Note: `rect` is in CSS pixels. We need to use `css_plugin_rect_`
// to calculate the intersection.
SkRect invalidate_rect =
gfx::RectToSkRect(gfx::IntersectRects(css_plugin_rect_, rect));
cc::PaintCanvasAutoRestore auto_restore(canvas, /*save=*/true);
canvas->clipRect(invalidate_rect);
// Paint with the plugin's background color if the snapshot is not ready.
if (snapshot_.GetSkImageInfo().isEmpty()) {
cc::PaintFlags flags;
flags.setBlendMode(SkBlendMode::kSrc);
flags.setColor(GetBackgroundColor());
canvas->drawRect(invalidate_rect, flags);
return;
}
// Layer translate is independent of scaling, so apply first.
if (!total_translate_.IsZero())
canvas->translate(total_translate_.x(), total_translate_.y());
if (device_to_css_scale_ != 1.0f)
canvas->scale(device_to_css_scale_, device_to_css_scale_);
// Position layer at plugin origin before layer scaling.
if (!plugin_rect_.origin().IsOrigin())
canvas->translate(plugin_rect_.x(), plugin_rect_.y());
if (snapshot_scale_ != 1.0f)
canvas->scale(snapshot_scale_, snapshot_scale_);
canvas->drawImage(snapshot_, 0, 0);
}
void PdfViewWebPlugin::PrepareForFirstPaint(
std::vector<PaintReadyRect>& ready) {
if (!first_paint_)
return;
// Fill the image data buffer with the background color.
first_paint_ = false;
image_data().eraseColor(background_color_);
ready.emplace_back(gfx::SkIRectToRect(image_data().bounds()),
image_data().asImage(), /*flush_now=*/true);
}
void PdfViewWebPlugin::UpdateGeometry(const gfx::Rect& window_rect,
const gfx::Rect& clip_rect,
const gfx::Rect& unobscured_rect,
bool is_visible) {
// An empty `window_rect` can be received here in the following cases:
// - If the embedded plugin size is 0.
// - If the embedded plugin size is not 0, it can come from re-layouts during
// the plugin initialization.
// For either case, there is no need to create a graphic device to display
// a PDF in an empty window. Since an empty `window_rect` can cause failure
// to create the graphic device, avoid all updates on the geometries and the
// device scales used by the plugin, the PaintManager and the PDFiumEngine
// unless a non-empty `window_rect` is received.
if (window_rect.IsEmpty())
return;
OnViewportChanged(window_rect, client_->DeviceScaleFactor());
gfx::PointF scroll_position = client_->GetScrollPosition();
// Convert back to CSS pixels.
scroll_position.Scale(1.0f / device_scale_);
UpdateScroll(scroll_position);
}
void PdfViewWebPlugin::UpdateScroll(const gfx::PointF& scroll_position) {
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);
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());
}
void PdfViewWebPlugin::UpdateFocus(bool focused,
blink::mojom::FocusType focus_type) {
if (has_focus_ != focused) {
engine_->UpdateFocus(focused);
client_->UpdateTextInputState();
client_->UpdateSelectionBounds();
}
has_focus_ = focused;
if (!has_focus_ || !SupportsKeyboardFocus())
return;
if (focus_type != blink::mojom::FocusType::kBackward &&
focus_type != blink::mojom::FocusType::kForward) {
return;
}
const int modifiers = focus_type == blink::mojom::FocusType::kForward
? blink::WebInputEvent::kNoModifiers
: blink::WebInputEvent::kShiftKey;
blink::WebKeyboardEvent simulated_event(blink::WebInputEvent::Type::kKeyDown,
modifiers, base::TimeTicks());
simulated_event.windows_key_code = ui::KeyboardCode::VKEY_TAB;
HandleWebInputEvent(simulated_event);
}
void PdfViewWebPlugin::UpdateVisibility(bool visibility) {}
blink::WebInputEventResult PdfViewWebPlugin::HandleInputEvent(
const blink::WebCoalescedInputEvent& event,
ui::Cursor* cursor) {
// TODO(crbug.com/1302059): The input events received by the Pepper plugin
// already have the viewport-to-DIP scale applied. The scaling done here
// should be moved into `HandleWebInputEvent()` once the Pepper plugin is
// removed.
std::unique_ptr<blink::WebInputEvent> scaled_event =
ui::ScaleWebInputEvent(event.Event(), viewport_to_dip_scale_);
const blink::WebInputEvent& event_to_handle =
scaled_event ? *scaled_event : event.Event();
const blink::WebInputEventResult result =
HandleWebInputEvent(event_to_handle)
? blink::WebInputEventResult::kHandledApplication
: blink::WebInputEventResult::kNotHandled;
*cursor = cursor_type_;
return result;
}
void PdfViewWebPlugin::DidReceiveResponse(
const blink::WebURLResponse& response) {}
void PdfViewWebPlugin::DidReceiveData(const char* data, size_t data_length) {}
void PdfViewWebPlugin::DidFinishLoading() {}
void PdfViewWebPlugin::DidFailLoading(const blink::WebURLError& error) {}
bool PdfViewWebPlugin::SupportsPaginatedPrint() {
return true;
}
bool PdfViewWebPlugin::GetPrintPresetOptionsFromDocument(
blink::WebPrintPresetOptions* print_preset_options) {
print_preset_options->is_scaling_disabled = !engine_->GetPrintScaling();
print_preset_options->copies = engine_->GetCopiesToPrint();
print_preset_options->duplex_mode = engine_->GetDuplexMode();
print_preset_options->uniform_page_size = engine_->GetUniformPageSizePoints();
return true;
}
int PdfViewWebPlugin::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;
if (!engine_->HasPermission(DocumentPermission::kPrintLowQuality))
return 0;
print_params_ = print_params;
if (!engine_->HasPermission(DocumentPermission::kPrintHighQuality))
print_params_->rasterize_pdf = true;
engine_->PrintBegin();
return ret;
}
void PdfViewWebPlugin::PrintPage(int page_number, cc::PaintCanvas* canvas) {
// The entire document goes into one metafile. However, it is impossible to
// know if a call to `PrintPage()` is the last call. Thus, `PrintPage()` just
// stores the pages to print and the metafile. Eventually, the printed output
// is generated in `PrintEnd()` and copied over to the metafile.
// Every `canvas` passed to this method should have a valid `metafile`.
printing::MetafileSkia* metafile = canvas->GetPrintingMetafile();
DCHECK(metafile);
// `pages_to_print_` should be empty iff `printing_metafile_` is not set.
DCHECK_EQ(pages_to_print_.empty(), !printing_metafile_);
// The metafile should be the same across all calls for a given print job.
DCHECK(!printing_metafile_ || (printing_metafile_ == metafile));
if (!printing_metafile_)
printing_metafile_ = metafile;
pages_to_print_.push_back(page_number);
}
void PdfViewWebPlugin::PrintEnd() {
if (pages_to_print_.empty())
return;
print_pages_called_ = true;
printing_metafile_->InitFromData(
engine_->PrintPages(pages_to_print_, print_params_.value()));
if (print_pages_called_)
UserMetricsRecordAction("PDF.PrintPage");
print_pages_called_ = false;
print_params_.reset();
engine_->PrintEnd();
printing_metafile_ = nullptr;
pages_to_print_.clear();
}
bool PdfViewWebPlugin::HasSelection() const {
return !selected_text_.IsEmpty();
}
blink::WebString PdfViewWebPlugin::SelectionAsText() const {
return selected_text_;
}
blink::WebString PdfViewWebPlugin::SelectionAsMarkup() const {
return selected_text_;
}
bool PdfViewWebPlugin::CanEditText() const {
return engine_->CanEditText();
}
bool PdfViewWebPlugin::HasEditableText() const {
return engine_->HasEditableText();
}
bool PdfViewWebPlugin::CanUndo() const {
return engine_->CanUndo();
}
bool PdfViewWebPlugin::CanRedo() const {
return engine_->CanRedo();
}
bool PdfViewWebPlugin::CanCopy() const {
return engine_->HasPermission(DocumentPermission::kCopy);
}
bool PdfViewWebPlugin::ExecuteEditCommand(const blink::WebString& name,
const blink::WebString& value) {
if (name == "SelectAll")
return SelectAll();
if (name == "Cut")
return Cut();
if (name == "Paste" || name == "PasteAndMatchStyle")
return Paste(value);
if (name == "Undo")
return Undo();
if (name == "Redo")
return Redo();
return false;
}
blink::WebURL PdfViewWebPlugin::LinkAtPosition(
const gfx::Point& /*position*/) const {
return GURL(link_under_cursor_);
}
bool PdfViewWebPlugin::StartFind(const blink::WebString& search_text,
bool case_sensitive,
int identifier) {
ResetRecentlySentFindUpdate();
find_identifier_ = identifier;
engine_->StartFind(search_text.Utf8(), case_sensitive);
return true;
}
void PdfViewWebPlugin::SelectFindResult(bool forward, int identifier) {
find_identifier_ = identifier;
engine_->SelectFindResult(forward);
}
void PdfViewWebPlugin::StopFind() {
find_identifier_ = -1;
engine_->StopFind();
tickmarks_.clear();
client_->ReportFindInPageTickmarks(tickmarks_);
}
bool PdfViewWebPlugin::CanRotateView() {
return !IsPrintPreview();
}
void PdfViewWebPlugin::RotateView(blink::WebPlugin::RotationType type) {
DCHECK(CanRotateView());
switch (type) {
case blink::WebPlugin::RotationType::k90Clockwise:
engine_->RotateClockwise();
break;
case blink::WebPlugin::RotationType::k90Counterclockwise:
engine_->RotateCounterclockwise();
break;
}
}
bool PdfViewWebPlugin::ShouldDispatchImeEventsToPlugin() {
return true;
}
blink::WebTextInputType PdfViewWebPlugin::GetPluginTextInputType() {
return text_input_type_;
}
gfx::Rect PdfViewWebPlugin::GetPluginCaretBounds() {
return caret_rect_;
}
void PdfViewWebPlugin::ImeSetCompositionForPlugin(
const blink::WebString& text,
const std::vector<ui::ImeTextSpan>& /*ime_text_spans*/,
const gfx::Range& /*replacement_range*/,
int /*selection_start*/,
int /*selection_end*/) {
composition_text_ = text;
}
void PdfViewWebPlugin::ImeCommitTextForPlugin(
const blink::WebString& text,
const std::vector<ui::ImeTextSpan>& /*ime_text_spans*/,
const gfx::Range& /*replacement_range*/,
int /*relative_cursor_pos*/) {
HandleImeCommit(text);
}
void PdfViewWebPlugin::ImeFinishComposingTextForPlugin(
bool /*keep_selection*/) {
HandleImeCommit(composition_text_);
}
void PdfViewWebPlugin::ProposeDocumentLayout(const DocumentLayout& layout) {
base::Value::Dict message;
message.Set("type", "documentDimensions");
message.Set("width", layout.size().width());
message.Set("height", layout.size().height());
message.Set("layoutOptions", layout.options().ToValue());
base::Value::List page_dimensions;
for (size_t i = 0; i < layout.page_count(); ++i)
page_dimensions.Append(DictFromRect(layout.page_rect(i)));
message.Set("pageDimensions", std::move(page_dimensions));
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 PdfViewWebPlugin::UpdateCursor(ui::mojom::CursorType new_cursor_type) {
cursor_type_ = new_cursor_type;
}
void PdfViewWebPlugin::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 PdfViewWebPlugin::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;
// After stopping search and setting `find_identifier_` to -1 there still may
// be a NotifyNumberOfFindResultsChanged notification pending from engine.
// Just ignore them.
if (find_identifier_ != -1) {
client_->ReportFindInPageMatchCount(find_identifier_, total, final_result);
}
client_->ReportFindInPageTickmarks(tickmarks_);
if (final_result)
return;
recently_sent_find_update_ = true;
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&PdfViewWebPlugin::ResetRecentlySentFindUpdate,
weak_factory_.GetWeakPtr()),
kFindResultCooldown);
}
void PdfViewWebPlugin::NotifySelectedFindResultChanged(int current_find_index,
bool final_result) {
if (find_identifier_ == -1 || !client_->PluginContainer())
return;
DCHECK_GE(current_find_index, -1);
client_->ReportFindInPageSelection(find_identifier_, current_find_index + 1,
final_result);
}
void PdfViewWebPlugin::CaretChanged(const gfx::Rect& caret_rect) {
caret_rect_ = gfx::ScaleToEnclosingRect(
caret_rect + available_area().OffsetFromOrigin(), device_to_css_scale_);
}
void PdfViewWebPlugin::GetDocumentPassword(
base::OnceCallback<void(const std::string&)> callback) {
DCHECK(password_callback_.is_null());
password_callback_ = std::move(callback);
base::Value::Dict message;
message.Set("type", "getPassword");
SendMessage(std::move(message));
}
void PdfViewWebPlugin::Beep() {
base::Value::Dict message;
message.Set("type", "beep");
SendMessage(std::move(message));
}
void PdfViewWebPlugin::Alert(const std::string& message) {
client_->Alert(blink::WebString::FromUTF8(message));
}
bool PdfViewWebPlugin::Confirm(const std::string& message) {
return client_->Confirm(blink::WebString::FromUTF8(message));
}
std::string PdfViewWebPlugin::Prompt(const std::string& question,
const std::string& default_answer) {
return client_
->Prompt(blink::WebString::FromUTF8(question),
blink::WebString::FromUTF8(default_answer))
.Utf8();
}
std::string PdfViewWebPlugin::GetURL() {
return url_;
}
void PdfViewWebPlugin::LoadUrl(base::StringPiece url,
LoadUrlCallback callback) {
UrlRequest request;
request.url = std::string(url);
request.method = "GET";
request.ignore_redirects = true;
auto loader = std::make_unique<UrlLoader>(weak_factory_.GetWeakPtr());
UrlLoader* raw_loader = loader.get();
raw_loader->Open(request,
base::BindOnce(std::move(callback), std::move(loader)));
}
void PdfViewWebPlugin::Print() {
if (!engine_)
return;
const bool can_print =
engine_->HasPermission(DocumentPermission::kPrintLowQuality) ||
engine_->HasPermission(DocumentPermission::kPrintHighQuality);
if (!can_print)
return;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&PdfViewWebPlugin::OnInvokePrintDialog,
weak_factory_.GetWeakPtr()));
}
void PdfViewWebPlugin::SubmitForm(const std::string& url,
const void* data,
int length) {
// `url` might be a relative URL. Resolve it against the document's URL.
// TODO(crbug.com/1322928): Probably redundant with `Client::CompleteURL()`.
GURL resolved_url = GURL(url_).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_ = std::make_unique<UrlLoader>(weak_factory_.GetWeakPtr());
form_loader_->Open(request, base::BindOnce(&PdfViewWebPlugin::DidFormOpen,
weak_factory_.GetWeakPtr()));
}
void PdfViewWebPlugin::DidFormOpen(int32_t result) {
// TODO(crbug.com/719344): Process response.
LOG_IF(ERROR, result != kSuccess) << "DidFormOpen failed: " << result;
form_loader_.reset();
}
std::unique_ptr<UrlLoader> PdfViewWebPlugin::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 std::make_unique<UrlLoader>(weak_factory_.GetWeakPtr());
}
std::vector<PDFEngine::Client::SearchStringResult>
PdfViewWebPlugin::SearchString(const char16_t* string,
const char16_t* term,
bool case_sensitive) {
base::i18n::RepeatingStringSearch searcher(
/*find_this=*/term, /*in_this=*/string, case_sensitive);
std::vector<SearchStringResult> results;
int match_index;
int match_length;
while (searcher.NextMatchResult(match_index, match_length))
results.push_back({.start_index = match_index, .length = match_length});
return results;
}
void PdfViewWebPlugin::DocumentHasUnsupportedFeature(
const std::string& feature) {
DCHECK(!feature.empty());
std::string metric = base::StrCat({"PDF_Unsupported_", feature});
if (unsupported_features_reported_.insert(metric).second)
client_->RecordComputedAction(metric);
if (!full_frame() || notified_browser_about_unsupported_feature_)
return;
notified_browser_about_unsupported_feature_ = true;
pdf_service_->HasUnsupportedFeature();
}
bool PdfViewWebPlugin::IsPrintPreview() const {
return is_print_preview_;
}
SkColor PdfViewWebPlugin::GetBackgroundColor() const {
return background_color_;
}
void PdfViewWebPlugin::EnteredEditMode() {
edit_mode_ = true;
pdf_service_->SetPluginCanSave(true);