forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathout_of_process_instance.cc
2089 lines (1797 loc) · 73.4 KB
/
out_of_process_instance.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) 2012 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/out_of_process_instance.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm> // for min/max()
#include <cmath> // for log() and pow()
#include <list>
#include <memory>
#include "base/feature_list.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/content_restriction.h"
#include "net/base/escape.h"
#include "pdf/pdf.h"
#include "ppapi/c/dev/ppb_cursor_control_dev.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/c/pp_rect.h"
#include "ppapi/c/private/ppb_instance_private.h"
#include "ppapi/c/private/ppp_pdf.h"
#include "ppapi/c/trusted/ppb_url_loader_trusted.h"
#include "ppapi/cpp/core.h"
#include "ppapi/cpp/dev/memory_dev.h"
#include "ppapi/cpp/dev/text_input_dev.h"
#include "ppapi/cpp/dev/url_util_dev.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/point.h"
#include "ppapi/cpp/private/pdf.h"
#include "ppapi/cpp/private/var_private.h"
#include "ppapi/cpp/rect.h"
#include "ppapi/cpp/resource.h"
#include "ppapi/cpp/url_request_info.h"
#include "ppapi/cpp/var_array.h"
#include "ppapi/cpp/var_array_buffer.h"
#include "ppapi/cpp/var_dictionary.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/gfx/geometry/point_f.h"
#include "url/gurl.h"
namespace chrome_pdf {
namespace {
const base::Feature kSaveEditedPDFFormExperiment{
"SaveEditedPDFForm", base::FEATURE_DISABLED_BY_DEFAULT};
constexpr char kChromePrint[] = "chrome://print/";
constexpr char kChromeExtension[] =
"chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai";
// Constants used in handling postMessage() messages.
constexpr char kType[] = "type";
constexpr char kJSId[] = "id";
// Beep messge arguments. (Plugin -> Page).
constexpr char kJSBeepType[] = "beep";
// Viewport message arguments. (Page -> Plugin).
constexpr char kJSViewportType[] = "viewport";
constexpr char kJSUserInitiated[] = "userInitiated";
constexpr char kJSXOffset[] = "xOffset";
constexpr char kJSYOffset[] = "yOffset";
constexpr char kJSZoom[] = "zoom";
constexpr char kJSPinchPhase[] = "pinchPhase";
// kJSPinchX and kJSPinchY represent the center of the pinch gesture.
constexpr char kJSPinchX[] = "pinchX";
constexpr char kJSPinchY[] = "pinchY";
// kJSPinchVector represents the amount of panning caused by the pinch gesture.
constexpr char kJSPinchVectorX[] = "pinchVectorX";
constexpr char kJSPinchVectorY[] = "pinchVectorY";
// Stop scrolling message (Page -> Plugin)
constexpr char kJSStopScrollingType[] = "stopScrolling";
// Document dimension arguments (Plugin -> Page).
constexpr char kJSDocumentDimensionsType[] = "documentDimensions";
constexpr char kJSDocumentWidth[] = "width";
constexpr char kJSDocumentHeight[] = "height";
constexpr char kJSPageDimensions[] = "pageDimensions";
constexpr char kJSPageX[] = "x";
constexpr char kJSPageY[] = "y";
constexpr char kJSPageWidth[] = "width";
constexpr char kJSPageHeight[] = "height";
// Document load progress arguments (Plugin -> Page)
constexpr char kJSLoadProgressType[] = "loadProgress";
constexpr char kJSProgressPercentage[] = "progress";
// Document print preview loaded (Plugin -> Page)
constexpr char kJSPreviewLoadedType[] = "printPreviewLoaded";
// Metadata
constexpr char kJSMetadataType[] = "metadata";
constexpr char kJSBookmarks[] = "bookmarks";
constexpr char kJSTitle[] = "title";
// Get password (Plugin -> Page)
constexpr char kJSGetPasswordType[] = "getPassword";
// Get password complete arguments (Page -> Plugin)
constexpr char kJSGetPasswordCompleteType[] = "getPasswordComplete";
constexpr char kJSPassword[] = "password";
// Print (Page -> Plugin)
constexpr char kJSPrintType[] = "print";
// Save (Page -> Plugin)
constexpr char kJSSaveType[] = "save";
constexpr char kJSToken[] = "token";
// Save Data (Plugin -> Page)
constexpr char kJSSaveDataType[] = "saveData";
constexpr char kJSFileName[] = "fileName";
constexpr char kJSDataToSave[] = "dataToSave";
// Consume save token (Plugin -> Page)
constexpr char kJSConsumeSaveTokenType[] = "consumeSaveToken";
// Go to page (Plugin -> Page)
constexpr char kJSGoToPageType[] = "goToPage";
constexpr char kJSPageNumber[] = "page";
// Reset print preview mode (Page -> Plugin)
constexpr char kJSResetPrintPreviewModeType[] = "resetPrintPreviewMode";
constexpr char kJSPrintPreviewUrl[] = "url";
constexpr char kJSPrintPreviewGrayscale[] = "grayscale";
constexpr char kJSPrintPreviewPageCount[] = "pageCount";
// Load preview page (Page -> Plugin)
constexpr char kJSLoadPreviewPageType[] = "loadPreviewPage";
constexpr char kJSPreviewPageUrl[] = "url";
constexpr char kJSPreviewPageIndex[] = "index";
// Set scroll position (Plugin -> Page)
constexpr char kJSSetScrollPositionType[] = "setScrollPosition";
constexpr char kJSPositionX[] = "x";
constexpr char kJSPositionY[] = "y";
// Scroll by (Plugin -> Page)
constexpr char kJSScrollByType[] = "scrollBy";
// Cancel the stream URL request (Plugin -> Page)
constexpr char kJSCancelStreamUrlType[] = "cancelStreamUrl";
// Navigate to the given URL (Plugin -> Page)
constexpr char kJSNavigateType[] = "navigate";
constexpr char kJSNavigateUrl[] = "url";
constexpr char kJSNavigateWindowOpenDisposition[] = "disposition";
// Open the email editor with the given parameters (Plugin -> Page)
constexpr char kJSEmailType[] = "email";
constexpr char kJSEmailTo[] = "to";
constexpr char kJSEmailCc[] = "cc";
constexpr char kJSEmailBcc[] = "bcc";
constexpr char kJSEmailSubject[] = "subject";
constexpr char kJSEmailBody[] = "body";
// Rotation (Page -> Plugin)
constexpr char kJSRotateClockwiseType[] = "rotateClockwise";
constexpr char kJSRotateCounterclockwiseType[] = "rotateCounterclockwise";
// Select all text in the document (Page -> Plugin)
constexpr char kJSSelectAllType[] = "selectAll";
// Get the selected text in the document (Page -> Plugin)
constexpr char kJSGetSelectedTextType[] = "getSelectedText";
// Reply with selected text (Plugin -> Page)
constexpr char kJSGetSelectedTextReplyType[] = "getSelectedTextReply";
constexpr char kJSSelectedText[] = "selectedText";
// Get the named destination with the given name (Page -> Plugin)
constexpr char kJSGetNamedDestinationType[] = "getNamedDestination";
constexpr char kJSGetNamedDestination[] = "namedDestination";
// Reply with the page number of the named destination (Plugin -> Page)
constexpr char kJSGetNamedDestinationReplyType[] = "getNamedDestinationReply";
constexpr char kJSNamedDestinationPageNumber[] = "pageNumber";
constexpr char kJSTransformPagePointType[] = "transformPagePoint";
constexpr char kJSTransformPagePointReplyType[] = "transformPagePointReply";
// Selecting text in document (Plugin -> Page)
constexpr char kJSSetIsSelectingType[] = "setIsSelecting";
constexpr char kJSIsSelecting[] = "isSelecting";
// Notify when a form field is focused (Plugin -> Page)
constexpr char kJSFieldFocusType[] = "formFocusChange";
constexpr char kJSFieldFocus[] = "focused";
constexpr int kFindResultCooldownMs = 100;
// Do not save forms with over 100 MB. This cap should be kept in sync with and
// is also enforced in chrome/browser/resources/pdf/pdf_viewer.js.
constexpr size_t kMaximumSavedFileSize = 100u * 1000u * 1000u;
// 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;
// A delay to wait between each accessibility page to keep the system
// responsive.
constexpr int kAccessibilityPageDelayMs = 100;
constexpr double kMinZoom = 0.01;
constexpr char kPPPPdfInterface[] = PPP_PDF_INTERFACE_1;
// Used for UMA. Do not delete entries, and keep in sync with histograms.xml.
enum PDFFeatures {
LOADED_DOCUMENT = 0,
HAS_TITLE = 1,
HAS_BOOKMARKS = 2,
FEATURES_COUNT
};
// Used for UMA. Do not delete entries, and keep in sync with histograms.xml
// and pdfium/public/fpdf_annot.h.
constexpr int kAnnotationTypesCount = 28;
PP_Var GetLinkAtPosition(PP_Instance instance, PP_Point point) {
pp::Var var;
void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
if (object) {
var = static_cast<OutOfProcessInstance*>(object)->GetLinkAtPosition(
pp::Point(point));
}
return var.Detach();
}
void Transform(PP_Instance instance, PP_PrivatePageTransformType type) {
void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
if (object) {
auto* obj_instance = static_cast<OutOfProcessInstance*>(object);
switch (type) {
case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW:
obj_instance->RotateClockwise();
break;
case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW:
obj_instance->RotateCounterclockwise();
break;
}
}
}
PP_Bool GetPrintPresetOptionsFromDocument(
PP_Instance instance,
PP_PdfPrintPresetOptions_Dev* options) {
void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
if (object) {
auto* obj_instance = static_cast<OutOfProcessInstance*>(object);
obj_instance->GetPrintPresetOptionsFromDocument(options);
}
return PP_TRUE;
}
void EnableAccessibility(PP_Instance instance) {
void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
if (object) {
auto* obj_instance = static_cast<OutOfProcessInstance*>(object);
obj_instance->EnableAccessibility();
}
}
void SetCaretPosition(PP_Instance instance, const PP_FloatPoint* position) {
void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
if (object) {
auto* obj_instance = static_cast<OutOfProcessInstance*>(object);
obj_instance->SetCaretPosition(*position);
}
}
void MoveRangeSelectionExtent(PP_Instance instance,
const PP_FloatPoint* extent) {
void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
if (object) {
auto* obj_instance = static_cast<OutOfProcessInstance*>(object);
obj_instance->MoveRangeSelectionExtent(*extent);
}
}
void SetSelectionBounds(PP_Instance instance,
const PP_FloatPoint* base,
const PP_FloatPoint* extent) {
void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
if (object) {
auto* obj_instance = static_cast<OutOfProcessInstance*>(object);
obj_instance->SetSelectionBounds(*base, *extent);
}
}
PP_Bool CanEditText(PP_Instance instance) {
void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
if (!object)
return PP_FALSE;
auto* obj_instance = static_cast<OutOfProcessInstance*>(object);
return PP_FromBool(obj_instance->CanEditText());
}
PP_Bool HasEditableText(PP_Instance instance) {
void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
if (!object)
return PP_FALSE;
auto* obj_instance = static_cast<OutOfProcessInstance*>(object);
return PP_FromBool(obj_instance->HasEditableText());
}
void ReplaceSelection(PP_Instance instance, const char* text) {
void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
if (object) {
auto* obj_instance = static_cast<OutOfProcessInstance*>(object);
obj_instance->ReplaceSelection(text);
}
}
PP_Bool CanUndo(PP_Instance instance) {
void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
if (!object)
return PP_FALSE;
auto* obj_instance = static_cast<OutOfProcessInstance*>(object);
return PP_FromBool(obj_instance->CanUndo());
}
PP_Bool CanRedo(PP_Instance instance) {
void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
if (!object)
return PP_FALSE;
auto* obj_instance = static_cast<OutOfProcessInstance*>(object);
return PP_FromBool(obj_instance->CanRedo());
}
void Undo(PP_Instance instance) {
void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
if (object) {
auto* obj_instance = static_cast<OutOfProcessInstance*>(object);
obj_instance->Undo();
}
}
void Redo(PP_Instance instance) {
void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
if (object) {
auto* obj_instance = static_cast<OutOfProcessInstance*>(object);
obj_instance->Redo();
}
}
int32_t PdfPrintBegin(PP_Instance instance,
const PP_PrintSettings_Dev* print_settings,
const PP_PdfPrintSettings_Dev* pdf_print_settings) {
void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface);
if (!object)
return 0;
auto* obj_instance = static_cast<OutOfProcessInstance*>(object);
return obj_instance->PdfPrintBegin(print_settings, pdf_print_settings);
}
const PPP_Pdf ppp_private = {
&GetLinkAtPosition,
&Transform,
&GetPrintPresetOptionsFromDocument,
&EnableAccessibility,
&SetCaretPosition,
&MoveRangeSelectionExtent,
&SetSelectionBounds,
&CanEditText,
&HasEditableText,
&ReplaceSelection,
&CanUndo,
&CanRedo,
&Undo,
&Redo,
&PdfPrintBegin,
};
int ExtractPrintPreviewPageIndex(base::StringPiece src_url) {
// Sample |src_url| format: chrome://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(strlen(kChromePrint)), "/",
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 IsPrintPreviewUrl(base::StringPiece url) {
return url.starts_with(kChromePrint);
}
bool IsPreviewingPDF(int print_preview_page_count) {
return print_preview_page_count == 0;
}
void ScaleFloatPoint(float scale, pp::FloatPoint* point) {
point->set_x(point->x() * scale);
point->set_y(point->y() * scale);
}
void ScalePoint(float scale, pp::Point* point) {
point->set_x(static_cast<int>(point->x() * scale));
point->set_y(static_cast<int>(point->y() * scale));
}
void ScaleRect(float scale, pp::Rect* rect) {
int left = static_cast<int>(floorf(rect->x() * scale));
int top = static_cast<int>(floorf(rect->y() * scale));
int right = static_cast<int>(ceilf((rect->x() + rect->width()) * scale));
int bottom = static_cast<int>(ceilf((rect->y() + rect->height()) * scale));
rect->SetRect(left, top, right - left, bottom - top);
}
} // namespace
OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance)
: pp::Instance(instance),
pp::Find_Private(this),
pp::Printing_Dev(this),
cursor_(PP_CURSORTYPE_POINTER),
zoom_(1.0),
needs_reraster_(true),
last_bitmap_smaller_(false),
device_scale_(1.0),
full_(false),
paint_manager_(this, this, true),
first_paint_(true),
document_load_state_(LOAD_STATE_LOADING),
preview_document_load_state_(LOAD_STATE_COMPLETE),
uma_(this),
told_browser_about_unsupported_feature_(false),
font_substitution_reported_(false),
print_preview_page_count_(-1),
print_preview_loaded_page_count_(-1),
last_progress_sent_(0),
recently_sent_find_update_(false),
received_viewport_message_(false),
did_call_start_loading_(false),
stop_scrolling_(false),
background_color_(0),
top_toolbar_height_in_viewport_coords_(0),
accessibility_state_(ACCESSIBILITY_STATE_OFF),
is_print_preview_(false) {
callback_factory_.Initialize(this);
pp::Module::Get()->AddPluginInterface(kPPPPdfInterface, &ppp_private);
AddPerInstanceObject(kPPPPdfInterface, this);
RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_MOUSE);
RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD);
RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH);
for (size_t i = 0; i < PDFACTION_BUCKET_BOUNDARY; i++)
preview_action_recorded_[i] = false;
}
OutOfProcessInstance::~OutOfProcessInstance() {
RemovePerInstanceObject(kPPPPdfInterface, this);
// Explicitly reset the PDFEngine during destruction as it may call back into
// this object.
engine_.reset();
}
bool OutOfProcessInstance::Init(uint32_t argc,
const char* argn[],
const char* argv[]) {
// 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.
pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this);
if (!document_url_var.is_string())
return false;
std::string document_url = document_url_var.AsString();
base::StringPiece document_url_piece(document_url);
is_print_preview_ = IsPrintPreviewUrl(document_url_piece);
if (!document_url_piece.starts_with(kChromeExtension) && !is_print_preview_)
return false;
// Check if the plugin is full frame. This is passed in from JS.
for (uint32_t i = 0; i < argc; ++i) {
if (strcmp(argn[i], "full-frame") == 0) {
full_ = true;
break;
}
}
// Allow the plugin to handle find requests.
SetPluginToHandleFindRequests();
text_input_ = std::make_unique<pp::TextInput_Dev>(this);
bool enable_javascript = false;
const char* stream_url = nullptr;
const char* original_url = nullptr;
const char* top_level_url = nullptr;
const char* headers = nullptr;
for (uint32_t i = 0; i < argc; ++i) {
bool success = true;
if (strcmp(argn[i], "src") == 0) {
original_url = argv[i];
} else if (strcmp(argn[i], "stream-url") == 0) {
stream_url = argv[i];
} else if (strcmp(argn[i], "top-level-url") == 0) {
top_level_url = argv[i];
} else if (strcmp(argn[i], "headers") == 0) {
headers = argv[i];
} else if (strcmp(argn[i], "background-color") == 0) {
success = base::HexStringToUInt(argv[i], &background_color_);
} else if (strcmp(argn[i], "top-toolbar-height") == 0) {
success =
base::StringToInt(argv[i], &top_toolbar_height_in_viewport_coords_);
} else if (strcmp(argn[i], "javascript") == 0) {
enable_javascript = (strcmp(argv[i], "allow") == 0);
}
if (!success)
return false;
}
if (!original_url)
return false;
if (!stream_url)
stream_url = original_url;
if (!engine_) {
// TODO(tsepez): fix lifetime issue, conditionalize javascript.
engine_ = PDFEngine::Create(this, true);
}
// 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 true;
LoadUrl(stream_url, /*is_print_preview=*/false);
url_ = original_url;
pp::PDF::SetCrashData(GetPluginInstance(), original_url, top_level_url);
return engine_->New(original_url, headers);
}
void OutOfProcessInstance::HandleMessage(const pp::Var& message) {
pp::VarDictionary dict(message);
if (!dict.Get(kType).is_string()) {
NOTREACHED();
return;
}
std::string type = dict.Get(kType).AsString();
if (type == kJSViewportType) {
if (!(dict.Get(pp::Var(kJSXOffset)).is_number() &&
dict.Get(pp::Var(kJSYOffset)).is_number() &&
dict.Get(pp::Var(kJSZoom)).is_number() &&
dict.Get(pp::Var(kJSPinchPhase)).is_number())) {
NOTREACHED();
return;
}
received_viewport_message_ = true;
stop_scrolling_ = false;
PinchPhase pinch_phase =
static_cast<PinchPhase>(dict.Get(pp::Var(kJSPinchPhase)).AsInt());
double zoom = dict.Get(pp::Var(kJSZoom)).AsDouble();
double zoom_ratio = zoom / zoom_;
pp::FloatPoint scroll_offset(dict.Get(pp::Var(kJSXOffset)).AsDouble(),
dict.Get(pp::Var(kJSYOffset)).AsDouble());
if (pinch_phase == PINCH_START) {
scroll_offset_at_last_raster_ = scroll_offset;
last_bitmap_smaller_ = false;
needs_reraster_ = false;
return;
}
// When zooming in, we set a layer transform to avoid unneeded rerasters.
// Also, if we're zooming out and the last time we rerastered was when
// we were even further zoomed out (i.e. we pinch zoomed in and are now
// pinch zooming back out in the same gesture), we update the layer
// transform instead of rerastering.
if (pinch_phase == PINCH_UPDATE_ZOOM_IN ||
(pinch_phase == PINCH_UPDATE_ZOOM_OUT && zoom_ratio > 1.0)) {
if (!(dict.Get(pp::Var(kJSPinchX)).is_number() &&
dict.Get(pp::Var(kJSPinchY)).is_number() &&
dict.Get(pp::Var(kJSPinchVectorX)).is_number() &&
dict.Get(pp::Var(kJSPinchVectorY)).is_number())) {
NOTREACHED();
return;
}
pp::Point pinch_center(dict.Get(pp::Var(kJSPinchX)).AsDouble(),
dict.Get(pp::Var(kJSPinchY)).AsDouble());
// Pinch vector is the panning caused due to change in pinch
// center between start and end of the gesture.
pp::Point pinch_vector =
pp::Point(dict.Get(kJSPinchVectorX).AsDouble() * zoom_ratio,
dict.Get(kJSPinchVectorY).AsDouble() * zoom_ratio);
pp::Point scroll_delta;
// If the rendered document doesn't fill the display area we will
// use |paint_offset| to anchor the paint vertically into the same place.
// We use the scroll bars instead of the pinch vector to get the actual
// position on screen of the paint.
pp::Point paint_offset;
if (plugin_size_.width() > GetDocumentPixelWidth() * zoom_ratio) {
// We want to keep the paint in the middle but it must stay in the same
// position relative to the scroll bars.
paint_offset = pp::Point(0, (1 - zoom_ratio) * pinch_center.y());
scroll_delta =
pp::Point(0, (scroll_offset.y() -
scroll_offset_at_last_raster_.y() * zoom_ratio));
pinch_vector = pp::Point();
last_bitmap_smaller_ = true;
} else if (last_bitmap_smaller_) {
pinch_center = pp::Point((plugin_size_.width() / device_scale_) / 2,
(plugin_size_.height() / device_scale_) / 2);
const double zoom_when_doc_covers_plugin_width =
zoom_ * plugin_size_.width() / GetDocumentPixelWidth();
paint_offset = pp::Point(
(1 - zoom / zoom_when_doc_covers_plugin_width) * pinch_center.x(),
(1 - zoom_ratio) * pinch_center.y());
pinch_vector = pp::Point();
scroll_delta =
pp::Point((scroll_offset.x() -
scroll_offset_at_last_raster_.x() * zoom_ratio),
(scroll_offset.y() -
scroll_offset_at_last_raster_.y() * zoom_ratio));
}
paint_manager_.SetTransform(zoom_ratio, pinch_center,
pinch_vector + paint_offset + scroll_delta,
true);
needs_reraster_ = false;
return;
}
if (pinch_phase == PINCH_UPDATE_ZOOM_OUT || pinch_phase == PINCH_END) {
// We reraster on pinch zoom out in order to solve the invalid regions
// that appear after zooming out.
// On pinch end the scale is again 1.f and we request a reraster
// in the new position.
paint_manager_.ClearTransform();
last_bitmap_smaller_ = false;
needs_reraster_ = true;
// If we're rerastering due to zooming out, we need to update
// |scroll_offset_at_last_raster_|, in case the user continues the
// gesture by zooming in.
scroll_offset_at_last_raster_ = scroll_offset;
}
// Bound the input parameters.
zoom = std::max(kMinZoom, zoom);
DCHECK(dict.Get(pp::Var(kJSUserInitiated)).is_bool());
if (dict.Get(pp::Var(kJSUserInitiated)).AsBool())
PrintPreviewHistogramEnumeration(UPDATE_ZOOM);
SetZoom(zoom);
scroll_offset = BoundScrollOffsetToDocument(scroll_offset);
engine_->ScrolledToXPosition(scroll_offset.x() * device_scale_);
engine_->ScrolledToYPosition(scroll_offset.y() * device_scale_);
} else if (type == kJSGetPasswordCompleteType) {
if (!dict.Get(pp::Var(kJSPassword)).is_string()) {
NOTREACHED();
return;
}
if (password_callback_) {
pp::CompletionCallbackWithOutput<pp::Var> callback = *password_callback_;
password_callback_.reset();
*callback.output() = dict.Get(pp::Var(kJSPassword)).pp_var();
callback.Run(PP_OK);
} else {
NOTREACHED();
}
} else if (type == kJSPrintType) {
Print();
} else if (type == kJSSaveType) {
if (!dict.Get(pp::Var(kJSToken)).is_string()) {
NOTREACHED();
return;
}
Save(dict.Get(pp::Var(kJSToken)).AsString());
} else if (type == kJSRotateClockwiseType) {
RotateClockwise();
} else if (type == kJSRotateCounterclockwiseType) {
RotateCounterclockwise();
} else if (type == kJSSelectAllType) {
engine_->SelectAll();
} else if (type == kJSResetPrintPreviewModeType) {
if (!(dict.Get(pp::Var(kJSPrintPreviewUrl)).is_string() &&
dict.Get(pp::Var(kJSPrintPreviewGrayscale)).is_bool() &&
dict.Get(pp::Var(kJSPrintPreviewPageCount)).is_int())) {
NOTREACHED();
return;
}
// For security reasons, crash if the URL that is trying to be loaded here
// isn't a print preview one.
std::string url = dict.Get(pp::Var(kJSPrintPreviewUrl)).AsString();
CHECK(IsPrintPreview());
CHECK(IsPrintPreviewUrl(url));
int print_preview_page_count =
dict.Get(pp::Var(kJSPrintPreviewPageCount)).AsInt();
if (print_preview_page_count < 0) {
NOTREACHED();
return;
}
// The page count is zero if the print preview source is a PDF. In which
// case, the page index for |url| should be at |kCompletePDFIndex|.
// When the page count is not zero, then the source is not PDF. In which
// case, the page index for |url| should be non-negative.
bool is_previewing_pdf = IsPreviewingPDF(print_preview_page_count);
int page_index = ExtractPrintPreviewPageIndex(url);
if (is_previewing_pdf) {
if (page_index != kCompletePDFIndex) {
NOTREACHED();
return;
}
} else {
if (page_index < 0) {
NOTREACHED();
return;
}
}
print_preview_page_count_ = print_preview_page_count;
print_preview_loaded_page_count_ = 0;
url_ = url;
preview_pages_info_ = base::queue<PreviewPageInfo>();
preview_document_load_state_ = LOAD_STATE_COMPLETE;
document_load_state_ = LOAD_STATE_LOADING;
LoadUrl(url_, /*is_print_preview=*/false);
preview_engine_.reset();
engine_ = PDFEngine::Create(this, false);
engine_->SetGrayscale(dict.Get(pp::Var(kJSPrintPreviewGrayscale)).AsBool());
engine_->New(url_.c_str(), nullptr /* empty header */);
paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
PrintPreviewHistogramEnumeration(PRINT_PREVIEW_SHOWN);
} else if (type == kJSLoadPreviewPageType) {
if (!(dict.Get(pp::Var(kJSPreviewPageUrl)).is_string() &&
dict.Get(pp::Var(kJSPreviewPageIndex)).is_int())) {
NOTREACHED();
return;
}
std::string url = dict.Get(pp::Var(kJSPreviewPageUrl)).AsString();
// For security reasons we crash if the URL that is trying to be loaded here
// isn't a print preview one.
CHECK(IsPrintPreview());
CHECK(IsPrintPreviewUrl(url));
ProcessPreviewPageInfo(url, dict.Get(pp::Var(kJSPreviewPageIndex)).AsInt());
} else if (type == kJSStopScrollingType) {
stop_scrolling_ = true;
} else if (type == kJSGetSelectedTextType) {
std::string selected_text = engine_->GetSelectedText();
// Always return unix newlines to JS.
base::ReplaceChars(selected_text, "\r", std::string(), &selected_text);
pp::VarDictionary reply;
reply.Set(pp::Var(kType), pp::Var(kJSGetSelectedTextReplyType));
reply.Set(pp::Var(kJSSelectedText), selected_text);
PostMessage(reply);
} else if (type == kJSGetNamedDestinationType) {
if (!dict.Get(pp::Var(kJSGetNamedDestination)).is_string()) {
NOTREACHED();
return;
}
base::Optional<PDFEngine::NamedDestination> named_destination =
engine_->GetNamedDestination(
dict.Get(pp::Var(kJSGetNamedDestination)).AsString());
pp::VarDictionary reply;
reply.Set(pp::Var(kType), pp::Var(kJSGetNamedDestinationReplyType));
reply.Set(
pp::Var(kJSNamedDestinationPageNumber),
named_destination ? static_cast<int>(named_destination->page) : -1);
PostMessage(reply);
} else if (type == kJSTransformPagePointType) {
if (!(dict.Get(pp::Var(kJSPageNumber)).is_int() &&
dict.Get(pp::Var(kJSPageX)).is_int() &&
dict.Get(pp::Var(kJSPageY)).is_int() &&
dict.Get(pp::Var(kJSId)).is_int())) {
NOTREACHED();
return;
}
gfx::PointF page_xy(dict.Get(pp::Var(kJSPageX)).AsInt(),
dict.Get(pp::Var(kJSPageY)).AsInt());
gfx::PointF device_xy = engine_->TransformPagePoint(
dict.Get(pp::Var(kJSPageNumber)).AsInt(), page_xy);
pp::VarDictionary reply;
reply.Set(pp::Var(kType), pp::Var(kJSTransformPagePointReplyType));
reply.Set(pp::Var(kJSPositionX), device_xy.x());
reply.Set(pp::Var(kJSPositionY), device_xy.y());
reply.Set(pp::Var(kJSId), dict.Get(pp::Var(kJSId)).AsInt());
PostMessage(reply);
} else {
NOTREACHED();
}
}
bool OutOfProcessInstance::HandleInputEvent(const pp::InputEvent& event) {
// To simplify things, convert the event into device coordinates.
pp::InputEvent event_device_res(event);
{
pp::MouseInputEvent mouse_event(event);
if (!mouse_event.is_null()) {
pp::Point point = mouse_event.GetPosition();
pp::Point movement = mouse_event.GetMovement();
ScalePoint(device_scale_, &point);
point.set_x(point.x() - available_area_.x());
ScalePoint(device_scale_, &movement);
mouse_event =
pp::MouseInputEvent(this, event.GetType(), event.GetTimeStamp(),
event.GetModifiers(), mouse_event.GetButton(),
point, mouse_event.GetClickCount(), movement);
event_device_res = mouse_event;
}
}
{
pp::TouchInputEvent touch_event(event);
if (!touch_event.is_null()) {
pp::TouchInputEvent new_touch_event = pp::TouchInputEvent(
this, touch_event.GetType(), touch_event.GetTimeStamp(),
touch_event.GetModifiers());
for (uint32_t i = 0;
i < touch_event.GetTouchCount(PP_TOUCHLIST_TYPE_TARGETTOUCHES);
i++) {
pp::TouchPoint touch_point =
touch_event.GetTouchByIndex(PP_TOUCHLIST_TYPE_TARGETTOUCHES, i);
pp::FloatPoint point = touch_point.position();
ScaleFloatPoint(device_scale_, &point);
point.set_x(point.x() - available_area_.x());
new_touch_event.AddTouchPoint(
PP_TOUCHLIST_TYPE_TARGETTOUCHES,
{touch_point.id(), point, touch_point.radii(),
touch_point.rotation_angle(), touch_point.pressure()});
}
event_device_res = new_touch_event;
}
}
if (engine_->HandleEvent(event_device_res))
return true;
// Middle click is used for scrolling and is handled by the container page.
pp::MouseInputEvent mouse_event(event_device_res);
if (!mouse_event.is_null() &&
mouse_event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_MIDDLE) {
return false;
}
// Return true for unhandled clicks so the plugin takes focus.
return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
}
void OutOfProcessInstance::DidChangeView(const pp::View& view) {
pp::Rect view_rect(view.GetRect());
float old_device_scale = device_scale_;
float device_scale = view.GetDeviceScale();
pp::Size view_device_size(view_rect.width() * device_scale,
view_rect.height() * device_scale);
if (view_device_size != plugin_size_ || device_scale != device_scale_) {
device_scale_ = device_scale;
plugin_dip_size_ = view_rect.size();
plugin_size_ = view_device_size;
paint_manager_.SetSize(view_device_size, device_scale_);
pp::Size new_image_data_size =
PaintManager::GetNewContextSize(image_data_.size(), plugin_size_);
if (new_image_data_size != image_data_.size()) {
image_data_ = pp::ImageData(this, PP_IMAGEDATAFORMAT_BGRA_PREMUL,
new_image_data_size, false);
first_paint_ = true;
}
if (image_data_.is_null()) {
DCHECK(plugin_size_.IsEmpty());
return;
}
OnGeometryChanged(zoom_, old_device_scale);
}
if (!stop_scrolling_) {
scroll_offset_ = view.GetScrollOffset();
// Because view messages come from the DOM, the coordinates of the viewport
// are 0-based (i.e. they do not correspond to the viewport's coordinates in
// JS), so we need to subtract the toolbar height to convert them into
// viewport coordinates.
pp::FloatPoint scroll_offset_float(
scroll_offset_.x(),
scroll_offset_.y() - top_toolbar_height_in_viewport_coords_);
scroll_offset_float = BoundScrollOffsetToDocument(scroll_offset_float);
engine_->ScrolledToXPosition(scroll_offset_float.x() * device_scale_);
engine_->ScrolledToYPosition(scroll_offset_float.y() * device_scale_);
}
}
void OutOfProcessInstance::DidChangeFocus(bool has_focus) {
if (!has_focus)
engine_->KillFormFocus();
}
void OutOfProcessInstance::GetPrintPresetOptionsFromDocument(
PP_PdfPrintPresetOptions_Dev* options) {
options->is_scaling_disabled = PP_FromBool(IsPrintScalingDisabled());
options->duplex =
static_cast<PP_PrivateDuplexMode_Dev>(engine_->GetDuplexType());
options->copies = engine_->GetCopiesToPrint();
pp::Size uniform_page_size;
options->is_page_size_uniform =
PP_FromBool(engine_->GetPageSizeAndUniformity(&uniform_page_size));
options->uniform_page_size = uniform_page_size;
}
void OutOfProcessInstance::EnableAccessibility() {
if (accessibility_state_ == ACCESSIBILITY_STATE_LOADED)
return;
if (accessibility_state_ == ACCESSIBILITY_STATE_OFF)
accessibility_state_ = ACCESSIBILITY_STATE_PENDING;
if (document_load_state_ == LOAD_STATE_COMPLETE)
LoadAccessibility();
}
void OutOfProcessInstance::LoadAccessibility() {
accessibility_state_ = ACCESSIBILITY_STATE_LOADED;
PP_PrivateAccessibilityDocInfo doc_info;
doc_info.page_count = engine_->GetNumberOfPages();
doc_info.text_accessible = PP_FromBool(
engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE));
doc_info.text_copyable =
PP_FromBool(engine_->HasPermission(PDFEngine::PERMISSION_COPY));
pp::PDF::SetAccessibilityDocInfo(GetPluginInstance(), &doc_info);
// If the document contents isn't accessible, don't send anything more.
if (!(engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE))) {
return;
}
SendAccessibilityViewportInfo();
// Schedule loading the first page.
pp::CompletionCallback callback = callback_factory_.NewCallback(
&OutOfProcessInstance::SendNextAccessibilityPage);
pp::Module::Get()->core()->CallOnMainThread(kAccessibilityPageDelayMs,
callback, 0);
}
void OutOfProcessInstance::SendNextAccessibilityPage(int32_t page_index) {
int page_count = engine_->GetNumberOfPages();
if (page_index < 0 || page_index >= page_count)
return;
int char_count = engine_->GetCharCount(page_index);
// Treat a char count of -1 (error) as 0 (an empty page), since
// other pages might have valid content.
if (char_count < 0)
char_count = 0;
PP_PrivateAccessibilityPageInfo page_info;
page_info.page_index = page_index;
page_info.bounds = engine_->GetPageBoundsRect(page_index);
page_info.char_count = char_count;
std::vector<PP_PrivateAccessibilityCharInfo> chars(page_info.char_count);
for (uint32_t i = 0; i < page_info.char_count; ++i) {
chars[i].unicode_character = engine_->GetCharUnicode(page_index, i);
}
std::vector<PP_PrivateAccessibilityTextRunInfo> text_runs;
int char_index = 0;
while (char_index < char_count) {
PP_PrivateAccessibilityTextRunInfo text_run_info;
pp::FloatRect bounds;
engine_->GetTextRunInfo(page_index, char_index, &text_run_info.len,
&text_run_info.font_size, &bounds);
DCHECK_LE(char_index + text_run_info.len,
static_cast<uint32_t>(char_count));
text_run_info.direction = PP_PRIVATEDIRECTION_LTR;
text_run_info.bounds = bounds;
text_runs.push_back(text_run_info);
// We need to provide enough information to draw a bounding box
// around any arbitrary text range, but the bounding boxes of characters
// we get from PDFium don't necessarily "line up". Walk through the
// characters in each text run and let the width of each character be
// the difference between the x coordinate of one character and the
// x coordinate of the next. The rest of the bounds of each character
// can be computed from the bounds of the text run.
pp::FloatRect char_bounds = engine_->GetCharBounds(page_index, char_index);