diff options
author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2022-05-17 17:24:03 +0200 |
---|---|---|
committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2022-06-22 07:51:41 +0000 |
commit | 774f54339e5db91f785733232d3950366db65d07 (patch) | |
tree | 068e1b47bd1af94d77094ed12b604a6b83d9c22a /chromium/pdf | |
parent | f7eaed5286974984ba5f9e3189d8f49d03e99f81 (diff) | |
download | qtwebengine-chromium-774f54339e5db91f785733232d3950366db65d07.tar.gz |
BASELINE: Update Chromium to 102.0.5005.57
Change-Id: I885f714bb40ee724c28f94ca6bd8dbdb39915158
Reviewed-by: Allan Sandfeld Jensen <allan.jensen@qt.io>
Diffstat (limited to 'chromium/pdf')
78 files changed, 1374 insertions, 4221 deletions
diff --git a/chromium/pdf/BUILD.gn b/chromium/pdf/BUILD.gn index 4594bcad3a8..0d8bc6e5ab8 100644 --- a/chromium/pdf/BUILD.gn +++ b/chromium/pdf/BUILD.gn @@ -5,6 +5,7 @@ import("//build/buildflag_header.gni") import("//build/config/features.gni") import("//pdf/features.gni") +import("//ppapi/buildflags/buildflags.gni") import("//testing/libfuzzer/fuzzer_test.gni") import("//testing/test.gni") import("//third_party/pdfium/pdfium.gni") @@ -44,25 +45,6 @@ if (enable_pdf) { ] } - static_library("pdf_ppapi") { - sources = [ "pdf_ppapi.cc" ] - - configs += [ ":strict" ] - - public = [ "pdf_ppapi.h" ] - - deps = [ - ":internal", - ":out_of_process_instance", - ":pdf", - "//base", - "//ppapi/cpp:objects", - "//ppapi/cpp/private:internal_module", - "//skia", - "//v8", - ] - } - source_set("features") { sources = [ "pdf_features.cc" ] @@ -82,7 +64,7 @@ if (enable_pdf) { # TODO(crbug.com/1158929): Eliminate chrome_find_request_manager_browsertest.cc's dependence # on document_loader_impl.h. - "//chrome/test:browser_tests", + "//chrome/test:browser_tests${exec_target_suffix}", ] sources = [ @@ -105,6 +87,8 @@ if (enable_pdf) { "draw_utils/shadow.h", "file_extension.cc", "file_extension.h", + "metrics_handler.cc", + "metrics_handler.h", "page_orientation.cc", "page_orientation.h", "paint_aggregator.cc", @@ -173,6 +157,7 @@ if (enable_pdf) { deps = [ ":accessibility", + ":buildflags", ":features", ":ppapi_migration", "//base", @@ -181,9 +166,6 @@ if (enable_pdf) { "//components/strings", "//gin", "//net", - "//pdf:buildflags", - "//ppapi/cpp:objects", - "//ppapi/cpp/private:internal_module", "//printing", "//third_party/blink/public:blink_headers", "//third_party/blink/public/common:headers", @@ -215,17 +197,13 @@ if (enable_pdf) { testonly = true - sources = [ - "pdfium/pdfium_assert_matching_enums.cc", - "ppapi_migration/ppapi_assert_matching_enums.cc", - ] + sources = [ "pdfium/pdfium_assert_matching_enums.cc" ] deps = [ ":accessibility", ":internal", ":pdf", ":ppapi_migration", - "//ppapi/c", "//third_party/blink/public/common:headers", "//third_party/pdfium", "//ui/base", @@ -235,7 +213,7 @@ if (enable_pdf) { source_set("accessibility") { visibility = [ ":*", - "//components:components_browsertests", + "//components:components_browsertests${exec_target_suffix}", "//components/pdf/renderer", "//components/pdf/renderer:unit_tests", ] @@ -253,6 +231,7 @@ if (enable_pdf) { deps = [ "//base", + "//skia", "//ui/gfx/geometry", ] } @@ -263,32 +242,17 @@ if (enable_pdf) { sources = [ "ppapi_migration/bitmap.cc", "ppapi_migration/bitmap.h", - "ppapi_migration/callback.cc", - "ppapi_migration/callback.h", - "ppapi_migration/geometry_conversions.cc", - "ppapi_migration/geometry_conversions.h", "ppapi_migration/graphics.cc", "ppapi_migration/graphics.h", - "ppapi_migration/image.cc", - "ppapi_migration/image.h", - "ppapi_migration/input_event_conversions.cc", - "ppapi_migration/input_event_conversions.h", - "ppapi_migration/printing_conversions.cc", - "ppapi_migration/printing_conversions.h", "ppapi_migration/result_codes.h", "ppapi_migration/url_loader.cc", "ppapi_migration/url_loader.h", - "ppapi_migration/value_conversions.cc", - "ppapi_migration/value_conversions.h", ] configs += [ ":strict" ] - public_deps = [ "//third_party/abseil-cpp:absl" ] - deps = [ "//base", - "//ppapi/cpp:objects", "//printing/mojom", "//skia", "//third_party/blink/public:blink", @@ -297,50 +261,17 @@ if (enable_pdf) { "//ui/base/cursor/mojom:cursor_type", "//ui/gfx", ] - - if (is_linux || is_chromeos) { - sources += [ - "ppapi_migration/pdfium_font_linux.cc", - "ppapi_migration/pdfium_font_linux.h", - ] - } - } - - source_set("out_of_process_instance") { - visibility = [ ":*" ] - - sources = [ - "out_of_process_instance.cc", - "out_of_process_instance.h", - ] - - configs += [ ":strict" ] - - public_deps = [ "//third_party/abseil-cpp:absl" ] - - deps = [ - ":accessibility", - ":internal", - ":ppapi_migration", - "//base", - "//build:chromeos_buildflags", - "//net", - "//ppapi/cpp:objects", - "//ppapi/cpp/private:internal_module", - "//skia", - "//third_party/blink/public:blink_headers", - "//third_party/blink/public/common:headers", - "//ui/base", - "//ui/base/cursor/mojom:cursor_type", - "//url", - ] } - # Eventual replacement for out_of_process_instance. static_library("pdf_view_web_plugin") { + # The PDF viewer relies on plugin infrastructure, which is currently tied to + # PPAPI support. Fuchsia does not have plugins enabled and is in a state + # where this code builds but does not work in Chrome. + # TODO(crbug.com/1306610): Remove this assert when this is no longer true. + assert(enable_plugins || is_fuchsia) + visibility = [ ":*", - "//chrome/renderer", "//components/pdf/renderer", ] @@ -350,6 +281,7 @@ if (enable_pdf) { "post_message_receiver.h", "post_message_sender.cc", "post_message_sender.h", + "v8_value_converter.h", ] configs += [ ":strict" ] @@ -365,9 +297,7 @@ if (enable_pdf) { "//base", "//base:i18n", "//cc/paint", - "//content/public/renderer", "//gin", - "//ppapi/cpp:objects", # TODO(crbug.com/1114263): PDFEngine::Client only. "//printing", "//services/network/public/mojom:url_loader_base", "//skia", @@ -401,7 +331,6 @@ if (enable_pdf) { ":internal", ":ppapi_migration", "//base", - "//ppapi/cpp:objects", "//testing/gmock", "//testing/gtest", "//third_party/blink/public/common:headers", @@ -449,9 +378,7 @@ if (enable_pdf) { "pdfium/pdfium_print_unittest.cc", "pdfium/pdfium_test_base.cc", "pdfium/pdfium_test_base.h", - "ppapi_migration/geometry_conversions_unittest.cc", "ppapi_migration/graphics_unittest.cc", - "ppapi_migration/printing_conversions_unittest.cc", "ppapi_migration/url_loader_unittest.cc", "range_set_unittest.cc", "test/run_all_unittests.cc", @@ -465,9 +392,9 @@ if (enable_pdf) { deps = [ ":accessibility", ":assert_enums", + ":buildflags", ":features", ":internal", - ":out_of_process_instance", ":pdf", ":pdf_test_utils", ":pdf_view_web_plugin", @@ -479,9 +406,6 @@ if (enable_pdf) { "//gin", "//mojo/core/embedder", "//mojo/public/cpp/bindings", - "//pdf:buildflags", - "//ppapi/c", - "//ppapi/cpp:objects", "//printing", "//skia", "//testing/gmock", @@ -511,6 +435,11 @@ if (enable_pdf) { ":pdf_unittests_pak", "//ui/resources:ui_test_pak_data", ] + + assert_no_deps = [ + "//ppapi/c/*", + "//ppapi/cpp/*", + ] } repack("pdf_unittests_pak") { @@ -535,8 +464,4 @@ if (enable_pdf) { } group("pdf") { } - group("pdf_ppapi") { - } - group("pdf_view_web_plugin") { - } } diff --git a/chromium/pdf/DEPS b/chromium/pdf/DEPS index afd5d53460d..5e76c9b7d5f 100644 --- a/chromium/pdf/DEPS +++ b/chromium/pdf/DEPS @@ -1,11 +1,9 @@ include_rules = [ "+cc/paint", - "+content/public/renderer/v8_value_converter.h", "+gin", "+mojo/core/embedder", "+mojo/public/cpp/bindings", "+net", - "+ppapi", "+printing", "+services/network/public/mojom/referrer_policy.mojom-shared.h", "+third_party/blink/public", diff --git a/chromium/pdf/accessibility_structs.cc b/chromium/pdf/accessibility_structs.cc index 6799b2d16bb..8accefc821d 100644 --- a/chromium/pdf/accessibility_structs.cc +++ b/chromium/pdf/accessibility_structs.cc @@ -76,8 +76,12 @@ AccessibilityImageInfo::AccessibilityImageInfo() = default; AccessibilityImageInfo::AccessibilityImageInfo(const std::string& alt_text, uint32_t text_run_index, - const gfx::RectF& bounds) - : alt_text(alt_text), text_run_index(text_run_index), bounds(bounds) {} + const gfx::RectF& bounds, + const SkBitmap& image_data) + : alt_text(alt_text), + text_run_index(text_run_index), + bounds(bounds), + image_data(image_data) {} AccessibilityImageInfo::AccessibilityImageInfo( const AccessibilityImageInfo& other) = default; diff --git a/chromium/pdf/accessibility_structs.h b/chromium/pdf/accessibility_structs.h index 58538f4b560..00e17e7f936 100644 --- a/chromium/pdf/accessibility_structs.h +++ b/chromium/pdf/accessibility_structs.h @@ -10,6 +10,7 @@ #include <string> #include <vector> +#include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_f.h" @@ -32,9 +33,6 @@ struct AccessibilityPageInfo { uint32_t char_count = 0; }; -// TODO(crbug.com/1144444): Remove next line comment after PDF migrates away -// from Pepper. -// Explicitly set all enum values to match enum values in PP_TextRenderingMode. // See PDF Reference 1.7, page 402, table 5.3. enum class AccessibilityTextRenderMode { kUnknown = -1, @@ -74,9 +72,6 @@ struct AccessibilityTextStyleInfo { bool is_bold = false; }; -// TODO(crbug.com/1144444): Remove next line comment after PDF migrates away -// from Pepper. -// Explicitly set all enum values to match enum values in PP_PrivateDirection. enum class AccessibilityTextDirection { kNone = 0, kLeftToRight = 1, @@ -136,18 +131,25 @@ struct AccessibilityImageInfo { AccessibilityImageInfo(); AccessibilityImageInfo(const std::string& alt_text, uint32_t text_run_index, - const gfx::RectF& bounds); + const gfx::RectF& bounds, + const SkBitmap& image_data); AccessibilityImageInfo(const AccessibilityImageInfo& other); ~AccessibilityImageInfo(); // Alternate text for the image provided by PDF. std::string alt_text; + // We anchor the image to a char index, this denotes the text run before // which the image should be inserted in the accessibility tree. The text run // at this index should contain the anchor char index. uint32_t text_run_index = 0; + // Bounding box of the image. gfx::RectF bounds; + + // Only populated if `alt_text` is empty or unavailable, and if the user has + // requested that the OCR service tag the PDF so that it is made accessible. + SkBitmap image_data; }; struct AccessibilityHighlightInfo { @@ -214,10 +216,6 @@ struct AccessibilityChoiceFieldOptionInfo { gfx::RectF bounds; }; -// TODO(crbug.com/702993): Remove next line comment after PDF migrates away -// from Pepper. -// Explicitly set all enum values to match enum values in -// PP_PrivateChoiceFieldType. enum class ChoiceFieldType { kListBox = 0, kComboBox = 1, @@ -263,9 +261,6 @@ struct AccessibilityChoiceFieldInfo { gfx::RectF bounds; }; -// TODO(crbug.com/702993): Remove next line comment after PDF migrates away -// from Pepper. -// Explicitly set all enum values to match enum values in PP_PrivateButtonType. enum class ButtonType { kPushButton = 1, kCheckBox = 2, @@ -349,10 +344,6 @@ struct AccessibilityPageObjects { AccessibilityFormFieldInfo form_fields; }; -// TODO(crbug.com/702993): Remove next line comment after PDF migrates away -// from Pepper. -// Explicitly set all enum values to match enum values in -// PP_PrivateFocusObjectType. enum class FocusObjectType { kNone = 0, kDocument = 1, @@ -380,10 +371,6 @@ struct AccessibilityViewportInfo { AccessibilityFocusInfo focus_info; }; -// TODO(crbug.com/702993): Remove next line comment after PDF migrates away -// from Pepper. -// Explicitly set all enum values to match enum values in -// PP_PdfAccessibilityAction. enum class AccessibilityAction { // No action specified. kNone = 0, @@ -399,10 +386,6 @@ enum class AccessibilityAction { kMaxValue = kSetSelection, }; -// TODO(crbug.com/702993): Remove next line comment after PDF migrates away -// from Pepper. -// Explicitly set all enum values to match enum values in -// PP_PdfAccessibilityAnnotationType. enum class AccessibilityAnnotationType { // No annotation type defined. kNone = 0, diff --git a/chromium/pdf/document_layout.cc b/chromium/pdf/document_layout.cc index 756e1cb3869..dd90361f8ef 100644 --- a/chromium/pdf/document_layout.cc +++ b/chromium/pdf/document_layout.cc @@ -32,8 +32,8 @@ int GetWidestPageWidth(const std::vector<gfx::Size>& page_sizes) { gfx::Rect InsetRect(const gfx::Rect& rect, const draw_utils::PageInsetSizes& inset_sizes) { gfx::Rect inset_rect(rect); - inset_rect.Inset(inset_sizes.left, inset_sizes.top, inset_sizes.right, - inset_sizes.bottom); + inset_rect.Inset(gfx::Insets::TLBR(inset_sizes.top, inset_sizes.left, + inset_sizes.bottom, inset_sizes.right)); return inset_rect; } @@ -50,26 +50,23 @@ DocumentLayout::Options& DocumentLayout::Options::operator=( DocumentLayout::Options::~Options() = default; -base::Value DocumentLayout::Options::ToValue() const { - base::Value dictionary(base::Value::Type::DICTIONARY); - dictionary.SetIntKey(kDirection, direction_); - dictionary.SetIntKey(kDefaultPageOrientation, - static_cast<int32_t>(default_page_orientation_)); - dictionary.SetBoolKey(kTwoUpViewEnabled, - page_spread_ == PageSpread::kTwoUpOdd); +base::Value::Dict DocumentLayout::Options::ToValue() const { + base::Value::Dict dictionary; + dictionary.Set(kDirection, direction_); + dictionary.Set(kDefaultPageOrientation, + static_cast<int>(default_page_orientation_)); + dictionary.Set(kTwoUpViewEnabled, page_spread_ == PageSpread::kTwoUpOdd); return dictionary; } -void DocumentLayout::Options::FromValue(const base::Value& value) { - DCHECK(value.is_dict()); - - int32_t direction = value.FindIntKey(kDirection).value(); +void DocumentLayout::Options::FromValue(const base::Value::Dict& value) { + int32_t direction = value.FindInt(kDirection).value(); DCHECK_GE(direction, base::i18n::UNKNOWN_DIRECTION); DCHECK_LE(direction, base::i18n::TEXT_DIRECTION_MAX); direction_ = static_cast<base::i18n::TextDirection>(direction); int32_t default_page_orientation = - value.FindIntKey(kDefaultPageOrientation).value(); + value.FindInt(kDefaultPageOrientation).value(); DCHECK_GE(default_page_orientation, static_cast<int32_t>(PageOrientation::kOriginal)); DCHECK_LE(default_page_orientation, @@ -77,7 +74,7 @@ void DocumentLayout::Options::FromValue(const base::Value& value) { default_page_orientation_ = static_cast<PageOrientation>(default_page_orientation); - page_spread_ = value.FindBoolKey(kTwoUpViewEnabled).value() + page_spread_ = value.FindBool(kTwoUpViewEnabled).value() ? PageSpread::kTwoUpOdd : PageSpread::kOneUp; } diff --git a/chromium/pdf/document_layout.h b/chromium/pdf/document_layout.h index ec57a3f0bf0..737a46dac8d 100644 --- a/chromium/pdf/document_layout.h +++ b/chromium/pdf/document_layout.h @@ -10,15 +10,12 @@ #include "base/check_op.h" #include "base/i18n/rtl.h" +#include "base/values.h" #include "pdf/draw_utils/coordinates.h" #include "pdf/page_orientation.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" -namespace base { -class Value; -} - namespace chrome_pdf { // Layout of pages within a PDF document. Pages are placed as rectangles @@ -56,11 +53,11 @@ class DocumentLayout final { return !(lhs == rhs); } - // Serializes layout options to a base::Value. - base::Value ToValue() const; + // Serializes layout options to a base::Value::Dict. + base::Value::Dict ToValue() const; - // Deserializes layout options from a base::Value. - void FromValue(const base::Value& value); + // Deserializes layout options from a base::Value::Dict. + void FromValue(const base::Value::Dict& value); // Page layout direction. This is tied to the direction of the user's UI, // rather than the direction of individual pages. diff --git a/chromium/pdf/document_layout_unittest.cc b/chromium/pdf/document_layout_unittest.cc index 115fbee29e5..a6977b3700a 100644 --- a/chromium/pdf/document_layout_unittest.cc +++ b/chromium/pdf/document_layout_unittest.cc @@ -111,7 +111,7 @@ TEST_F(DocumentLayoutOptionsTest, NotEquals) { } TEST_F(DocumentLayoutOptionsTest, ToValueDefault) { - base::Value value = options_.ToValue(); + base::Value value(options_.ToValue()); EXPECT_THAT(value, base::test::IsJson(R"({ "direction": 0, @@ -124,7 +124,7 @@ TEST_F(DocumentLayoutOptionsTest, ToValueModified) { options_.set_direction(base::i18n::LEFT_TO_RIGHT); options_.RotatePagesClockwise(); options_.set_page_spread(DocumentLayout::PageSpread::kTwoUpOdd); - base::Value value = options_.ToValue(); + base::Value value(options_.ToValue()); EXPECT_THAT(value, base::test::IsJson(R"({ "direction": 2, @@ -134,21 +134,23 @@ TEST_F(DocumentLayoutOptionsTest, ToValueModified) { } TEST_F(DocumentLayoutOptionsTest, FromValueDefault) { - options_.FromValue(base::test::ParseJson(R"({ + base::Value value = base::test::ParseJson(R"({ "direction": 0, "defaultPageOrientation": 0, "twoUpViewEnabled": false, - })")); + })"); + options_.FromValue(value.GetDict()); EXPECT_EQ(options_, DocumentLayout::Options()); } TEST_F(DocumentLayoutOptionsTest, FromValueModified) { - options_.FromValue(base::test::ParseJson(R"({ + base::Value value = base::test::ParseJson(R"({ "direction": 2, "defaultPageOrientation": 1, "twoUpViewEnabled": true, - })")); + })"); + options_.FromValue(value.GetDict()); EXPECT_EQ(options_.direction(), base::i18n::LEFT_TO_RIGHT); EXPECT_EQ(options_.default_page_orientation(), PageOrientation::kClockwise90); diff --git a/chromium/pdf/document_loader_impl_unittest.cc b/chromium/pdf/document_loader_impl_unittest.cc index af9ebce484f..36780363bac 100644 --- a/chromium/pdf/document_loader_impl_unittest.cc +++ b/chromium/pdf/document_loader_impl_unittest.cc @@ -15,7 +15,6 @@ #include "base/memory/raw_ptr.h" #include "base/test/scoped_feature_list.h" #include "pdf/pdf_features.h" -#include "pdf/ppapi_migration/callback.h" #include "pdf/url_loader_wrapper.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -99,7 +98,7 @@ class TestURLLoader : public URLLoaderWrapper { char* buffer() const { return buffer_; } int buffer_size() const { return buffer_size_; } - void SetReadCallback(ResultCallback read_callback, + void SetReadCallback(base::OnceCallback<void(int)> read_callback, char* buffer, int buffer_size) { did_read_callback_ = std::move(read_callback); @@ -107,7 +106,7 @@ class TestURLLoader : public URLLoaderWrapper { buffer_size_ = buffer_size; } - void SetOpenCallback(ResultCallback open_callback, + void SetOpenCallback(base::OnceCallback<void(int)> open_callback, gfx::Range req_byte_range) { did_open_callback_ = std::move(open_callback); set_open_byte_range(req_byte_range); @@ -124,8 +123,8 @@ class TestURLLoader : public URLLoaderWrapper { } private: - ResultCallback did_open_callback_; - ResultCallback did_read_callback_; + base::OnceCallback<void(int)> did_open_callback_; + base::OnceCallback<void(int)> did_read_callback_; raw_ptr<char> buffer_ = nullptr; int buffer_size_ = 0; @@ -178,14 +177,14 @@ class TestURLLoader : public URLLoaderWrapper { const std::string& referrer_url, uint32_t position, uint32_t size, - ResultCallback callback) override { + base::OnceCallback<void(int)> callback) override { data_->SetOpenCallback(std::move(callback), gfx::Range(position, position + size)); } void ReadResponseBody(char* buffer, int buffer_size, - ResultCallback callback) override { + base::OnceCallback<void(int)> callback) override { data_->SetReadCallback(std::move(callback), buffer, buffer_size); } diff --git a/chromium/pdf/features.gni b/chromium/pdf/features.gni index 67ce26d6189..45d167e97f3 100644 --- a/chromium/pdf/features.gni +++ b/chromium/pdf/features.gni @@ -17,9 +17,5 @@ declare_args() { # feature is enabled for the PDF viewer. enable_ink = enable_cros_media_app - # TODO(crbug.com/702993): Currently disabled on Fuchsia because the PDF Viewer - # currently depends on PPAPI. It does not make sense to port PPAPI, which is - # being deprecated, to Fuchsia. Once the PDF Viewer no longer uses PPAPI, the - # PDF Viewer should be enabled on Fuchsia, like on other desktop platforms. - enable_pdf = !is_android && !is_ios && !is_chromecast && !is_fuchsia + enable_pdf = !is_android && !is_ios && !is_chromecast } diff --git a/chromium/pdf/metrics_handler.cc b/chromium/pdf/metrics_handler.cc new file mode 100644 index 00000000000..6e191d5c26f --- /dev/null +++ b/chromium/pdf/metrics_handler.cc @@ -0,0 +1,59 @@ +// Copyright 2022 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/metrics_handler.h" + +#include <vector> + +#include "base/metrics/histogram_functions.h" +#include "pdf/document_metadata.h" +#include "pdf/file_extension.h" + +namespace chrome_pdf { + +namespace { + +// These values are persisted to logs. Entries should not be renumbered and +// numeric values should never be reused. +enum class PdfHasAttachment { + kNo = 0, + kYes = 1, + kMaxValue = kYes, +}; + +// These values are persisted to logs. Entries should not be renumbered and +// numeric values should never be reused. +enum class PdfIsTagged { + kNo = 0, + kYes = 1, + kMaxValue = kYes, +}; + +} // namespace + +MetricsHandler::MetricsHandler() = default; + +MetricsHandler::~MetricsHandler() = default; + +void MetricsHandler::RecordAttachmentTypes( + const std::vector<DocumentAttachmentInfo>& attachments) { + for (const auto& info : attachments) { + base::UmaHistogramEnumeration("PDF.AttachmentType", + FileNameToExtensionIndex(info.name)); + } +} + +void MetricsHandler::RecordDocumentMetrics(const DocumentMetadata& metadata) { + base::UmaHistogramEnumeration("PDF.Version", metadata.version); + base::UmaHistogramCustomCounts("PDF.PageCount", metadata.page_count, 1, + 1000000, 50); + base::UmaHistogramEnumeration( + "PDF.HasAttachment", metadata.has_attachments ? PdfHasAttachment::kYes + : PdfHasAttachment::kNo); + base::UmaHistogramEnumeration( + "PDF.IsTagged", metadata.tagged ? PdfIsTagged::kYes : PdfIsTagged::kNo); + base::UmaHistogramEnumeration("PDF.FormType", metadata.form_type); +} + +} // namespace chrome_pdf diff --git a/chromium/pdf/metrics_handler.h b/chromium/pdf/metrics_handler.h new file mode 100644 index 00000000000..6d6a794e6b0 --- /dev/null +++ b/chromium/pdf/metrics_handler.h @@ -0,0 +1,32 @@ +// Copyright 2022 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. + +#ifndef PDF_METRICS_HANDLER_H_ +#define PDF_METRICS_HANDLER_H_ + +#include <vector> + +#include "pdf/document_attachment_info.h" + +namespace chrome_pdf { + +struct DocumentMetadata; + +// Handles various UMA metrics. Note that action metrics are handled separately. +class MetricsHandler { + public: + MetricsHandler(); + MetricsHandler(const MetricsHandler& other) = delete; + MetricsHandler& operator=(const MetricsHandler& other) = delete; + ~MetricsHandler(); + + void RecordAttachmentTypes( + const std::vector<DocumentAttachmentInfo>& attachments); + + void RecordDocumentMetrics(const DocumentMetadata& metadata); +}; + +} // namespace chrome_pdf + +#endif // PDF_METRICS_HANDLER_H_ diff --git a/chromium/pdf/out_of_process_instance.cc b/chromium/pdf/out_of_process_instance.cc deleted file mode 100644 index bf97773d534..00000000000 --- a/chromium/pdf/out_of_process_instance.cc +++ /dev/null @@ -1,909 +0,0 @@ -// 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 <string.h> - -#include <algorithm> -#include <iterator> -#include <list> -#include <memory> -#include <string> -#include <utility> - -#include "base/bind.h" -#include "base/callback.h" -#include "base/location.h" -#include "base/memory/weak_ptr.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_util.h" -#include "base/time/time.h" -#include "base/values.h" -#include "build/build_config.h" -#include "net/base/escape.h" -#include "pdf/accessibility.h" -#include "pdf/accessibility_structs.h" -#include "pdf/document_attachment_info.h" -#include "pdf/document_metadata.h" -#include "pdf/pdfium/pdfium_engine.h" -#include "pdf/ppapi_migration/bitmap.h" -#include "pdf/ppapi_migration/geometry_conversions.h" -#include "pdf/ppapi_migration/graphics.h" -#include "pdf/ppapi_migration/image.h" -#include "pdf/ppapi_migration/input_event_conversions.h" -#include "pdf/ppapi_migration/printing_conversions.h" -#include "pdf/ppapi_migration/url_loader.h" -#include "pdf/ppapi_migration/value_conversions.h" -#include "ppapi/c/dev/ppb_cursor_control_dev.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/private/ppb_pdf.h" -#include "ppapi/cpp/core.h" -#include "ppapi/cpp/dev/buffer_dev.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/graphics_2d.h" -#include "ppapi/cpp/image_data.h" -#include "ppapi/cpp/input_event.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/point.h" -#include "ppapi/cpp/private/pdf.h" -#include "ppapi/cpp/rect.h" -#include "ppapi/cpp/resource.h" -#include "ppapi/cpp/size.h" -#include "ppapi/cpp/var_array_buffer.h" -#include "ppapi/cpp/var_dictionary.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/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/cursor/mojom/cursor_type.mojom-shared.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 "url/gurl.h" - -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) -#include "pdf/ppapi_migration/pdfium_font_linux.h" -#endif - -namespace chrome_pdf { - -namespace { - -constexpr char kPPPPdfInterface[] = PPP_PDF_INTERFACE_1; - -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); - } -} - -void SelectAll(PP_Instance instance) { - void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface); - if (object) { - auto* obj_instance = static_cast<OutOfProcessInstance*>(object); - obj_instance->SelectAll(); - } -} - -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(); - } -} - -PageCharacterIndex ToPageCharacterIndex( - const PP_PdfPageCharacterIndex& pp_page_char_index) { - return {pp_page_char_index.page_index, pp_page_char_index.char_index}; -} - -AccessibilityActionData ToAccessibilityActionData( - const PP_PdfAccessibilityActionData& pp_action_data) { - return { - static_cast<AccessibilityAction>(pp_action_data.action), - static_cast<AccessibilityAnnotationType>(pp_action_data.annotation_type), - PointFromPPPoint(pp_action_data.target_point), - RectFromPPRect(pp_action_data.target_rect), - pp_action_data.annotation_index, - pp_action_data.page_index, - static_cast<AccessibilityScrollAlignment>( - pp_action_data.horizontal_scroll_alignment), - static_cast<AccessibilityScrollAlignment>( - pp_action_data.vertical_scroll_alignment), - ToPageCharacterIndex(pp_action_data.selection_start_index), - ToPageCharacterIndex(pp_action_data.selection_end_index)}; -} - -void HandleAccessibilityAction( - PP_Instance instance, - const PP_PdfAccessibilityActionData& action_data) { - void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface); - if (object) { - auto* obj_instance = static_cast<OutOfProcessInstance*>(object); - obj_instance->HandleAccessibilityAction( - ToAccessibilityActionData(action_data)); - } -} - -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, - &SelectAll, - &CanUndo, - &CanRedo, - &Undo, - &Redo, - &HandleAccessibilityAction, - &PdfPrintBegin, -}; - -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)); -} - -PP_PrivateAccessibilityPageInfo ToPrivateAccessibilityPageInfo( - const AccessibilityPageInfo& page_info) { - PP_PrivateAccessibilityPageInfo pp_page_info; - pp_page_info.page_index = page_info.page_index; - pp_page_info.bounds = PPRectFromRect(page_info.bounds); - pp_page_info.text_run_count = page_info.text_run_count; - pp_page_info.char_count = page_info.char_count; - return pp_page_info; -} - -std::vector<PP_PrivateAccessibilityCharInfo> ToPrivateAccessibilityCharInfo( - const std::vector<AccessibilityCharInfo>& chars) { - std::vector<PP_PrivateAccessibilityCharInfo> pp_chars; - pp_chars.reserve(chars.size()); - for (const auto& char_object : chars) - pp_chars.push_back({char_object.unicode_character, char_object.char_width}); - return pp_chars; -} - -pp::PDF::PrivateAccessibilityTextStyleInfo ToPrivateAccessibilityTextStyleInfo( - const AccessibilityTextStyleInfo& style) { - pp::PDF::PrivateAccessibilityTextStyleInfo pp_style; - pp_style.font_name = style.font_name; - pp_style.font_weight = style.font_weight; - pp_style.render_mode = static_cast<PP_TextRenderingMode>(style.render_mode); - pp_style.font_size = style.font_size; - pp_style.fill_color = style.fill_color; - pp_style.stroke_color = style.stroke_color; - pp_style.is_italic = style.is_italic; - pp_style.is_bold = style.is_bold; - return pp_style; -} - -std::vector<pp::PDF::PrivateAccessibilityTextRunInfo> -ToPrivateAccessibilityCharInfo( - const std::vector<AccessibilityTextRunInfo>& text_runs) { - std::vector<pp::PDF::PrivateAccessibilityTextRunInfo> pp_text_runs; - pp_text_runs.reserve(text_runs.size()); - for (const auto& text_run : text_runs) { - pp::PDF::PrivateAccessibilityTextRunInfo pp_text_run = { - text_run.len, PPFloatRectFromRectF(text_run.bounds), - static_cast<PP_PrivateDirection>(text_run.direction), - ToPrivateAccessibilityTextStyleInfo(text_run.style)}; - pp_text_runs.push_back(std::move(pp_text_run)); - } - return pp_text_runs; -} - -pp::PDF::PrivateAccessibilityPageObjects ToPrivateAccessibilityPageObjects( - const AccessibilityPageObjects& page_objects) { - pp::PDF::PrivateAccessibilityPageObjects pp_page_objects; - - pp_page_objects.links.reserve(page_objects.links.size()); - for (const auto& link_info : page_objects.links) { - pp_page_objects.links.push_back( - {link_info.url, link_info.index_in_page, - base::checked_cast<uint32_t>(link_info.text_range.index), - link_info.text_range.count, PPFloatRectFromRectF(link_info.bounds)}); - } - - pp_page_objects.images.reserve(page_objects.images.size()); - for (const auto& image_info : page_objects.images) { - pp_page_objects.images.push_back({image_info.alt_text, - image_info.text_run_index, - PPFloatRectFromRectF(image_info.bounds)}); - } - - pp_page_objects.highlights.reserve(page_objects.highlights.size()); - for (const auto& highlight_info : page_objects.highlights) { - pp_page_objects.highlights.push_back( - {highlight_info.note_text, highlight_info.index_in_page, - base::checked_cast<uint32_t>(highlight_info.text_range.index), - highlight_info.text_range.count, - PPFloatRectFromRectF(highlight_info.bounds), highlight_info.color}); - } - - pp_page_objects.form_fields.text_fields.reserve( - page_objects.form_fields.text_fields.size()); - for (const auto& text_field_info : page_objects.form_fields.text_fields) { - pp_page_objects.form_fields.text_fields.push_back( - {text_field_info.name, text_field_info.value, - text_field_info.is_read_only, text_field_info.is_required, - text_field_info.is_password, text_field_info.index_in_page, - text_field_info.text_run_index, - PPFloatRectFromRectF(text_field_info.bounds)}); - } - - pp_page_objects.form_fields.choice_fields.reserve( - page_objects.form_fields.choice_fields.size()); - for (const auto& choice_field_info : page_objects.form_fields.choice_fields) { - std::vector<pp::PDF::PrivateAccessibilityChoiceFieldOptionInfo> - pp_choice_field_option_infos; - pp_choice_field_option_infos.reserve(choice_field_info.options.size()); - for (const auto& option : choice_field_info.options) { - pp_choice_field_option_infos.push_back( - {option.name, option.is_selected, - PPFloatRectFromRectF(option.bounds)}); - } - pp_page_objects.form_fields.choice_fields.push_back( - {choice_field_info.name, pp_choice_field_option_infos, - static_cast<PP_PrivateChoiceFieldType>(choice_field_info.type), - choice_field_info.is_read_only, choice_field_info.is_multi_select, - choice_field_info.has_editable_text_box, - choice_field_info.index_in_page, choice_field_info.text_run_index, - PPFloatRectFromRectF(choice_field_info.bounds)}); - } - - pp_page_objects.form_fields.buttons.reserve( - page_objects.form_fields.buttons.size()); - for (const auto& button_info : page_objects.form_fields.buttons) { - pp_page_objects.form_fields.buttons.push_back( - {button_info.name, button_info.value, - static_cast<PP_PrivateButtonType>(button_info.type), - button_info.is_read_only, button_info.is_checked, - button_info.control_count, button_info.control_index, - button_info.index_in_page, button_info.text_run_index, - PPFloatRectFromRectF(button_info.bounds)}); - } - - return pp_page_objects; -} - -} // namespace - -OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance) - : pp::Instance(instance), pp::Find_Private(this), pp::Printing_Dev(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); -} - -OutOfProcessInstance::~OutOfProcessInstance() { - RemovePerInstanceObject(kPPPPdfInterface, this); - // Explicitly destroy the PDFEngine during destruction as it may call back - // into this object. - DestroyPreviewEngine(); - DestroyEngine(); -} - -bool OutOfProcessInstance::Init(uint32_t argc, - const char* argn[], - const char* argv[]) { - DCHECK(!engine()); - - pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this); - if (!document_url_var.is_string()) - return false; - GURL document_url(document_url_var.AsString()); - - // Allow the plugin to handle find requests. - SetPluginToHandleFindRequests(); - - text_input_ = std::make_unique<pp::TextInput_Dev>(this); - - // Parse attributes. Keep in sync with `ParseWebPluginParams()`. - const char* src_url = nullptr; - const char* original_url = nullptr; - const char* top_level_url = nullptr; - bool full_frame = false; - SkColor background_color = SK_ColorTRANSPARENT; - PDFiumFormFiller::ScriptOption script_option = - PDFiumFormFiller::DefaultScriptOption(); - bool has_edits = false; - for (uint32_t i = 0; i < argc; ++i) { - if (strcmp(argn[i], "src") == 0) { - src_url = argv[i]; - } else if (strcmp(argn[i], "original-url") == 0) { - original_url = argv[i]; - } else if (strcmp(argn[i], "top-level-url") == 0) { - top_level_url = argv[i]; - } else if (strcmp(argn[i], "full-frame") == 0) { - full_frame = true; - } else if (strcmp(argn[i], "background-color") == 0) { - if (!base::StringToUint(argv[i], &background_color)) - return false; - } else if (strcmp(argn[i], "javascript") == 0) { - if (strcmp(argv[i], "allow") != 0) - script_option = PDFiumFormFiller::ScriptOption::kNoJavaScript; - } else if (strcmp(argn[i], "has-edits") == 0) { - has_edits = true; - } - } - - if (!src_url) - return false; - - if (!original_url) - original_url = src_url; - - pp::PDF::SetCrashData(this, original_url, top_level_url); - InitializeBase( - std::make_unique<PDFiumEngine>(this, script_option), - /*embedder_origin=*/document_url.DeprecatedGetOriginAsURL().spec(), - /*src_url=*/src_url, - /*original_url=*/original_url, - /*full_frame=*/full_frame, - /*background_color=*/background_color, - /*has_edits=*/has_edits); - return true; -} - -void OutOfProcessInstance::HandleMessage(const pp::Var& message) { - PdfViewPluginBase::HandleMessage(ValueFromVar(message)); -} - -bool OutOfProcessInstance::HandleInputEvent(const pp::InputEvent& event) { - std::unique_ptr<blink::WebInputEvent> web_event = GetWebInputEvent(event); - if (!web_event) - return false; - - return PdfViewPluginBase::HandleInputEvent(*web_event); -} - -void OutOfProcessInstance::DidChangeView(const pp::View& view) { - const gfx::Rect new_plugin_rect = gfx::ScaleToEnclosingRect( - RectFromPPRect(view.GetRect()), view.GetDeviceScale()); - UpdateGeometryOnPluginRectChanged(new_plugin_rect, view.GetDeviceScale()); -} - -void OutOfProcessInstance::DidChangeFocus(bool has_focus) { - engine()->UpdateFocus(has_focus); -} - -void OutOfProcessInstance::GetPrintPresetOptionsFromDocument( - PP_PdfPrintPresetOptions_Dev* options) { - *options = - PPPdfPrintPresetOptionsFromWebPrintPresetOptions(GetPrintPresetOptions()); -} - -void OutOfProcessInstance::SetCaretPosition(const pp::FloatPoint& position) { - PdfViewPluginBase::SetCaretPosition(PointFFromPPFloatPoint(position)); -} - -void OutOfProcessInstance::MoveRangeSelectionExtent( - const pp::FloatPoint& extent) { - PdfViewPluginBase::MoveRangeSelectionExtent(PointFFromPPFloatPoint(extent)); -} - -void OutOfProcessInstance::SetSelectionBounds(const pp::FloatPoint& base, - const pp::FloatPoint& extent) { - PdfViewPluginBase::SetSelectionBounds(PointFFromPPFloatPoint(base), - PointFFromPPFloatPoint(extent)); -} - -pp::Var OutOfProcessInstance::GetLinkAtPosition(const pp::Point& point) { - pp::Point offset_point(point); - ScalePoint(device_scale(), &offset_point); - offset_point.set_x(offset_point.x() - available_area().x()); - return engine()->GetLinkAtPosition(PointFromPPPoint(offset_point)); -} - -bool OutOfProcessInstance::CanEditText() { - return engine()->CanEditText(); -} - -bool OutOfProcessInstance::HasEditableText() { - return engine()->HasEditableText(); -} - -void OutOfProcessInstance::ReplaceSelection(const std::string& text) { - engine()->ReplaceSelection(text); -} - -void OutOfProcessInstance::SelectAll() { - engine()->SelectAll(); -} - -bool OutOfProcessInstance::CanUndo() { - return engine()->CanUndo(); -} - -bool OutOfProcessInstance::CanRedo() { - return engine()->CanRedo(); -} - -void OutOfProcessInstance::Undo() { - engine()->Undo(); -} - -void OutOfProcessInstance::Redo() { - engine()->Redo(); -} - -int32_t OutOfProcessInstance::PdfPrintBegin( - const PP_PrintSettings_Dev* print_settings, - const PP_PdfPrintSettings_Dev* pdf_print_settings) { - return PdfViewPluginBase::PrintBegin( - WebPrintParamsFromPPPrintSettings(*print_settings, *pdf_print_settings)); -} - -uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() { - if (engine()->HasPermission(DocumentPermission::kPrintHighQuality)) - return PP_PRINTOUTPUTFORMAT_PDF | PP_PRINTOUTPUTFORMAT_RASTER; - if (engine()->HasPermission(DocumentPermission::kPrintLowQuality)) - return PP_PRINTOUTPUTFORMAT_RASTER; - return 0; -} - -int32_t OutOfProcessInstance::PrintBegin( - const PP_PrintSettings_Dev& print_settings) { - // Replaced with PdfPrintBegin(); - NOTREACHED(); - return 0; -} - -pp::Resource OutOfProcessInstance::PrintPages( - const PP_PrintPageNumberRange_Dev* page_ranges, - uint32_t page_range_count) { - const std::vector<uint8_t> pdf_data = PdfViewPluginBase::PrintPages( - PageNumbersFromPPPrintPageNumberRange(page_ranges, page_range_count)); - - // Convert buffer to Pepper type. - pp::Buffer_Dev buffer; - if (!pdf_data.empty()) { - buffer = pp::Buffer_Dev(this, pdf_data.size()); - if (!buffer.is_null()) - memcpy(buffer.data(), pdf_data.data(), pdf_data.size()); - } - return buffer; -} - -void OutOfProcessInstance::PrintEnd() { - PdfViewPluginBase::PrintEnd(); -} - -bool OutOfProcessInstance::IsPrintScalingDisabled() { - return !engine()->GetPrintScaling(); -} - -bool OutOfProcessInstance::StartFind(const std::string& text, - bool case_sensitive) { - return PdfViewPluginBase::StartFind(text, case_sensitive); -} - -void OutOfProcessInstance::SelectFindResult(bool forward) { - PdfViewPluginBase::SelectFindResult(forward); -} - -void OutOfProcessInstance::StopFind() { - PdfViewPluginBase::StopFind(); -} - -void OutOfProcessInstance::SendMessage(base::Value message) { - PostMessage(VarFromValue(message)); -} - -void OutOfProcessInstance::SaveAs() { - pp::PDF::SaveAs(this); -} - -void OutOfProcessInstance::InitImageData(const gfx::Size& size) { - pepper_image_data_ = - pp::ImageData(this, PP_IMAGEDATAFORMAT_BGRA_PREMUL, PPSizeFromSize(size), - /*init_to_zero=*/false); - mutable_image_data() = SkBitmapFromPPImageData( - std::make_unique<pp::ImageData>(pepper_image_data_)); -} - -void OutOfProcessInstance::SetFormTextFieldInFocus(bool in_focus) { - if (!text_input_) - return; - - text_input_->SetTextInputType(in_focus ? PP_TEXTINPUT_TYPE_DEV_TEXT - : PP_TEXTINPUT_TYPE_DEV_NONE); -} - -void OutOfProcessInstance::UpdateCursor(ui::mojom::CursorType new_cursor_type) { - if (cursor_type() == new_cursor_type) - return; - set_cursor_type(new_cursor_type); - - const PPB_CursorControl_Dev* cursor_interface = - reinterpret_cast<const PPB_CursorControl_Dev*>( - pp::Module::Get()->GetBrowserInterface( - PPB_CURSOR_CONTROL_DEV_INTERFACE)); - - cursor_interface->SetCursor(pp_instance(), - PPCursorTypeFromCursorType(cursor_type()), - pp::ImageData().pp_resource(), nullptr); -} - -void OutOfProcessInstance::NotifySelectedFindResultChanged( - int current_find_index) { - DCHECK_GE(current_find_index, -1); - SelectedFindResultChanged(current_find_index); -} - -void OutOfProcessInstance::CaretChanged(const gfx::Rect& caret_rect) { - PP_Rect caret_viewport = - PPRectFromRect(caret_rect + available_area().OffsetFromOrigin()); - text_input_->UpdateCaretPosition(caret_viewport, caret_viewport); -} - -void OutOfProcessInstance::Alert(const std::string& message) { - pp::PDF::ShowAlertDialog(this, message.c_str()); -} - -bool OutOfProcessInstance::Confirm(const std::string& message) { - return pp::PDF::ShowConfirmDialog(this, message.c_str()); -} - -std::string OutOfProcessInstance::Prompt(const std::string& question, - const std::string& default_answer) { - pp::Var result = - pp::PDF::ShowPromptDialog(this, question.c_str(), default_answer.c_str()); - return result.is_string() ? result.AsString() : std::string(); -} - -std::vector<PDFEngine::Client::SearchStringResult> -OutOfProcessInstance::SearchString(const char16_t* string, - const char16_t* term, - bool case_sensitive) { - PP_PrivateFindResult* pp_results; - uint32_t count = 0; - pp::PDF::SearchString(this, reinterpret_cast<const unsigned short*>(string), - reinterpret_cast<const unsigned short*>(term), - case_sensitive, &pp_results, &count); - - std::vector<SearchStringResult> results(count); - for (uint32_t i = 0; i < count; ++i) { - results[i].start_index = pp_results[i].start_index; - results[i].length = pp_results[i].length; - } - - pp::Memory_Dev memory; - memory.MemFree(pp_results); - - return results; -} - -void OutOfProcessInstance::RotateClockwise() { - engine()->RotateClockwise(); -} - -void OutOfProcessInstance::RotateCounterclockwise() { - engine()->RotateCounterclockwise(); -} - -void OutOfProcessInstance::SetLastPluginInstance() { -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - SetLastPepperInstance(this); -#endif -} - -Image OutOfProcessInstance::GetPluginImageData() const { - return Image(pepper_image_data_); -} - -void OutOfProcessInstance::SetAccessibilityDocInfo( - AccessibilityDocInfo doc_info) { - PP_PrivateAccessibilityDocInfo pp_doc_info = { - doc_info.page_count, PP_FromBool(doc_info.text_accessible), - PP_FromBool(doc_info.text_copyable)}; - pp::PDF::SetAccessibilityDocInfo(this, &pp_doc_info); -} - -void OutOfProcessInstance::SetAccessibilityPageInfo( - AccessibilityPageInfo page_info, - std::vector<AccessibilityTextRunInfo> text_runs, - std::vector<AccessibilityCharInfo> chars, - AccessibilityPageObjects page_objects) { - PP_PrivateAccessibilityPageInfo pp_page_info = - ToPrivateAccessibilityPageInfo(page_info); - std::vector<PP_PrivateAccessibilityCharInfo> pp_chars = - ToPrivateAccessibilityCharInfo(chars); - std::vector<pp::PDF::PrivateAccessibilityTextRunInfo> pp_text_runs = - ToPrivateAccessibilityCharInfo(text_runs); - pp::PDF::PrivateAccessibilityPageObjects pp_page_objects = - ToPrivateAccessibilityPageObjects(page_objects); - pp::PDF::SetAccessibilityPageInfo(this, &pp_page_info, pp_text_runs, pp_chars, - pp_page_objects); -} - -void OutOfProcessInstance::SetAccessibilityViewportInfo( - AccessibilityViewportInfo viewport_info) { - PP_PrivateAccessibilityViewportInfo pp_viewport_info = { - viewport_info.zoom, - viewport_info.scale, - pp::Point(viewport_info.scroll.x(), viewport_info.scroll.y()), - pp::Point(viewport_info.offset.x(), viewport_info.offset.y()), - viewport_info.selection_start_page_index, - viewport_info.selection_start_char_index, - viewport_info.selection_end_page_index, - viewport_info.selection_end_char_index, - {static_cast<PP_PrivateFocusObjectType>( - viewport_info.focus_info.focused_object_type), - viewport_info.focus_info.focused_object_page_index, - viewport_info.focus_info.focused_annotation_index_in_page}}; - pp::PDF::SetAccessibilityViewportInfo(this, &pp_viewport_info); -} - -void OutOfProcessInstance::NotifyFindResultsChanged(int total, - bool final_result) { - NumberOfFindResultsChanged(total, final_result); -} - -void OutOfProcessInstance::NotifyFindTickmarks( - const std::vector<gfx::Rect>& tickmarks) { - std::vector<pp::Rect> pp_tickmarks; - pp_tickmarks.reserve(tickmarks.size()); - std::transform(tickmarks.begin(), tickmarks.end(), - std::back_inserter(pp_tickmarks), PPRectFromRect); - SetTickmarks(pp_tickmarks); -} - -void OutOfProcessInstance::SetPluginCanSave(bool can_save) { - pp::PDF::SetPluginCanSave(this, can_save); -} - -base::WeakPtr<PdfViewPluginBase> OutOfProcessInstance::GetWeakPtr() { - return weak_factory_.GetWeakPtr(); -} - -std::unique_ptr<UrlLoader> OutOfProcessInstance::CreateUrlLoaderInternal() { - auto loader = std::make_unique<PepperUrlLoader>(this); - loader->GrantUniversalAccess(); - return loader; -} - -std::string OutOfProcessInstance::RewriteRequestUrl( - base::StringPiece url) const { - if (IsPrintPreview()) { - // TODO(crbug.com/1238829): This is a workaround for Pepper not supporting - // chrome-untrusted://print/ URLs. Pepper issues requests through the - // embedder's URL loaders, but a WebUI loader only supports subresource - // requests to the same scheme (so chrome: only can request chrome: URLs, - // and chrome-untrusted: only can request chrome-untrusted: URLs). - // - // To work around this (for the Pepper plugin only), we'll issue - // chrome-untrusted://print/ requests to the equivalent chrome://print/ URL, - // since both schemes support the same PDF URLs. - if (base::StartsWith(url, kChromeUntrustedPrintHost)) { - return base::StrCat( - {kChromePrintHost, url.substr(kChromeUntrustedPrintHost.size())}); - } - - NOTREACHED(); - } - - return PdfViewPluginBase::RewriteRequestUrl(url); -} - -void OutOfProcessInstance::SetSelectedText(const std::string& selected_text) { - pp::PDF::SetSelectedText(this, selected_text.c_str()); -} - -bool OutOfProcessInstance::IsValidLink(const std::string& url) { - return pp::Var(url).is_string(); -} - -std::unique_ptr<Graphics> OutOfProcessInstance::CreatePaintGraphics( - const gfx::Size& size) { - auto graphics = std::make_unique<PepperGraphics>(this, size); - DCHECK(!graphics->pepper_graphics().is_null()); - return graphics; -} - -bool OutOfProcessInstance::BindPaintGraphics(Graphics& graphics) { - return BindGraphics(static_cast<PepperGraphics&>(graphics).pepper_graphics()); -} - -void OutOfProcessInstance::ScheduleTaskOnMainThread( - const base::Location& from_here, - ResultCallback callback, - int32_t result, - base::TimeDelta delay) { - int64_t delay_in_msec = delay.InMilliseconds(); - DCHECK_LE(delay_in_msec, INT32_MAX); - pp::Module::Get()->core()->CallOnMainThread( - static_cast<int32_t>(delay_in_msec), - PPCompletionCallbackFromResultCallback(std::move(callback)), result); -} - -void OutOfProcessInstance::PluginDidStartLoading() { - pp::PDF::DidStartLoading(this); -} - -void OutOfProcessInstance::PluginDidStopLoading() { - pp::PDF::DidStopLoading(this); -} - -void OutOfProcessInstance::InvokePrintDialog() { - pp::PDF::Print(this); -} - -void OutOfProcessInstance::SetContentRestrictions(int content_restrictions) { - pp::PDF::SetContentRestriction(this, content_restrictions); -} - -void OutOfProcessInstance::NotifyLinkUnderCursor() { - pp::PDF::SetLinkUnderCursor(this, link_under_cursor().c_str()); -} - -void OutOfProcessInstance::NotifySelectionChanged(const gfx::PointF& left, - int left_height, - const gfx::PointF& right, - int right_height) { - pp::PDF::SelectionChanged(this, PPFloatPointFromPointF(left), left_height, - PPFloatPointFromPointF(right), right_height); -} - -void OutOfProcessInstance::NotifyUnsupportedFeature() { - DCHECK(full_frame()); - pp::PDF::HasUnsupportedFeature(this); -} - -void OutOfProcessInstance::UserMetricsRecordAction(const std::string& action) { - // TODO(raymes): Move this function to PPB_UMA_Private. - pp::PDF::UserMetricsRecordAction(this, pp::Var(action)); -} - -} // namespace chrome_pdf diff --git a/chromium/pdf/out_of_process_instance.h b/chromium/pdf/out_of_process_instance.h deleted file mode 100644 index 058ab9c8ccc..00000000000 --- a/chromium/pdf/out_of_process_instance.h +++ /dev/null @@ -1,166 +0,0 @@ -// 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. - -#ifndef PDF_OUT_OF_PROCESS_INSTANCE_H_ -#define PDF_OUT_OF_PROCESS_INSTANCE_H_ - -#include <stdint.h> -#include <string.h> - -#include <memory> -#include <string> -#include <vector> - -#include "base/callback.h" -#include "base/memory/weak_ptr.h" -#include "pdf/pdf_view_plugin_base.h" -#include "ppapi/c/private/ppp_pdf.h" -#include "ppapi/cpp/dev/printing_dev.h" -#include "ppapi/cpp/image_data.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/private/find_private.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/gfx/geometry/rect.h" - -namespace gfx { -class Size; -} // namespace gfx - -namespace pp { -class Size; -class TextInput_Dev; -} // namespace pp - -namespace chrome_pdf { - -class Graphics; -class UrlLoader; - -class OutOfProcessInstance : public PdfViewPluginBase, - public pp::Instance, - public pp::Find_Private, - public pp::Printing_Dev { - public: - explicit OutOfProcessInstance(PP_Instance instance); - OutOfProcessInstance(const OutOfProcessInstance&) = delete; - OutOfProcessInstance& operator=(const OutOfProcessInstance&) = delete; - ~OutOfProcessInstance() override; - - // pp::Instance: - bool Init(uint32_t argc, const char* argn[], const char* argv[]) override; - void HandleMessage(const pp::Var& message) override; - bool HandleInputEvent(const pp::InputEvent& event) override; - void DidChangeView(const pp::View& view) override; - void DidChangeFocus(bool has_focus) override; - - // pp::Find_Private: - bool StartFind(const std::string& text, bool case_sensitive) override; - void SelectFindResult(bool forward) override; - void StopFind() override; - - // pp::Printing_Dev: - uint32_t QuerySupportedPrintOutputFormats() override; - int32_t PrintBegin(const PP_PrintSettings_Dev& print_settings) override; - pp::Resource PrintPages(const PP_PrintPageNumberRange_Dev* page_ranges, - uint32_t page_range_count) override; - void PrintEnd() override; - bool IsPrintScalingDisabled() override; - - // pp::Private: - pp::Var GetLinkAtPosition(const pp::Point& point); - void GetPrintPresetOptionsFromDocument(PP_PdfPrintPresetOptions_Dev* options); - void SetCaretPosition(const pp::FloatPoint& position); - void MoveRangeSelectionExtent(const pp::FloatPoint& extent); - void SetSelectionBounds(const pp::FloatPoint& base, - const pp::FloatPoint& extent); - bool CanEditText(); - bool HasEditableText(); - void ReplaceSelection(const std::string& text); - void SelectAll(); - bool CanUndo(); - bool CanRedo(); - void Undo(); - void Redo(); - int32_t PdfPrintBegin(const PP_PrintSettings_Dev* print_settings, - const PP_PdfPrintSettings_Dev* pdf_print_settings); - - void FlushCallback(int32_t result); - - // PdfViewPluginBase: - void UpdateCursor(ui::mojom::CursorType new_cursor_type) override; - void NotifySelectedFindResultChanged(int current_find_index) override; - void CaretChanged(const gfx::Rect& caret_rect) override; - void Alert(const std::string& message) override; - bool Confirm(const std::string& message) override; - std::string Prompt(const std::string& question, - const std::string& default_answer) override; - std::vector<SearchStringResult> SearchString(const char16_t* string, - const char16_t* term, - bool case_sensitive) override; - void SetLastPluginInstance() override; - void SetSelectedText(const std::string& selected_text) override; - bool IsValidLink(const std::string& url) override; - std::unique_ptr<Graphics> CreatePaintGraphics(const gfx::Size& size) override; - bool BindPaintGraphics(Graphics& graphics) override; - void ScheduleTaskOnMainThread(const base::Location& from_here, - ResultCallback callback, - int32_t result, - base::TimeDelta delay) override; - - // Helper functions for implementing PPP_PDF. - void RotateClockwise(); - void RotateCounterclockwise(); - - protected: - // PdfViewPluginBase: - base::WeakPtr<PdfViewPluginBase> GetWeakPtr() override; - std::unique_ptr<UrlLoader> CreateUrlLoaderInternal() override; - std::string RewriteRequestUrl(base::StringPiece url) const override; - void SendMessage(base::Value message) override; - void SaveAs() override; - void InitImageData(const gfx::Size& size) override; - Image GetPluginImageData() const override; - void SetFormTextFieldInFocus(bool in_focus) override; - void SetAccessibilityDocInfo(AccessibilityDocInfo doc_info) override; - void SetAccessibilityPageInfo(AccessibilityPageInfo page_info, - std::vector<AccessibilityTextRunInfo> text_runs, - std::vector<AccessibilityCharInfo> chars, - AccessibilityPageObjects page_objects) override; - void SetAccessibilityViewportInfo( - AccessibilityViewportInfo viewport_info) override; - void NotifyFindResultsChanged(int total, bool final_result) override; - void NotifyFindTickmarks(const std::vector<gfx::Rect>& tickmarks) override; - void SetContentRestrictions(int content_restrictions) override; - void SetPluginCanSave(bool can_save) override; - void PluginDidStartLoading() override; - void PluginDidStopLoading() override; - void InvokePrintDialog() override; - void NotifyLinkUnderCursor() override; - void NotifySelectionChanged(const gfx::PointF& left, - int left_height, - const gfx::PointF& right, - int right_height) override; - void NotifyUnsupportedFeature() override; - void UserMetricsRecordAction(const std::string& action) override; - - private: - bool CanSaveEdits() const; - - // The Pepper image data that is in sync with mutable_image_data(). - pp::ImageData pepper_image_data_; - - // Used for submitting forms. - std::unique_ptr<UrlLoader> form_loader_; - - // Used to signal the browser about focus changes to trigger the OSK. - // TODO(abodenha@chromium.org) Implement full IME support in the plugin. - // http://crbug.com/132565 - std::unique_ptr<pp::TextInput_Dev> text_input_; - - base::WeakPtrFactory<OutOfProcessInstance> weak_factory_{this}; -}; - -} // namespace chrome_pdf - -#endif // PDF_OUT_OF_PROCESS_INSTANCE_H_ diff --git a/chromium/pdf/paint_manager.cc b/chromium/pdf/paint_manager.cc index 5b42c62541c..b29f0a95f18 100644 --- a/chromium/pdf/paint_manager.cc +++ b/chromium/pdf/paint_manager.cc @@ -14,10 +14,8 @@ #include "base/callback.h" #include "base/check.h" #include "base/location.h" -#include "base/time/time.h" +#include "base/threading/thread_task_runner_handle.h" #include "pdf/paint_ready_rect.h" -#include "pdf/ppapi_migration/callback.h" -#include "pdf/ppapi_migration/geometry_conversions.h" #include "pdf/ppapi_migration/graphics.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" @@ -161,11 +159,9 @@ void PaintManager::EnsureCallbackPending() { if (manual_callback_pending_) return; - client_->ScheduleTaskOnMainThread( - FROM_HERE, - base::BindOnce(&PaintManager::OnManualCallbackComplete, - weak_factory_.GetWeakPtr()), - /*result=*/0, base::TimeDelta()); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(&PaintManager::OnManualCallbackComplete, + weak_factory_.GetWeakPtr())); manual_callback_pending_ = true; } @@ -276,7 +272,7 @@ void PaintManager::Flush() { DCHECK(flush_pending_); } -void PaintManager::OnFlushComplete(int32_t) { +void PaintManager::OnFlushComplete() { DCHECK(flush_pending_); flush_pending_ = false; @@ -291,7 +287,7 @@ void PaintManager::OnFlushComplete(int32_t) { } } -void PaintManager::OnManualCallbackComplete(int32_t) { +void PaintManager::OnManualCallbackComplete() { DCHECK(manual_callback_pending_); manual_callback_pending_ = false; diff --git a/chromium/pdf/paint_manager.h b/chromium/pdf/paint_manager.h index 5854c0159a4..a89f108c4f1 100644 --- a/chromium/pdf/paint_manager.h +++ b/chromium/pdf/paint_manager.h @@ -14,13 +14,8 @@ #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "pdf/paint_aggregator.h" -#include "pdf/ppapi_migration/callback.h" #include "ui/gfx/geometry/size.h" -namespace base { -class Location; -} // namespace base - namespace gfx { class Point; class Rect; @@ -73,17 +68,6 @@ class PaintManager { std::vector<PaintReadyRect>& ready, std::vector<gfx::Rect>& pending) = 0; - // Schedules work to be executed on a main thread after a specific delay. - // The `result` parameter will be passed as the argument to the `callback`. - // `result` is needed sometimes to emulate calls of some callbacks, but it's - // not always needed. `delay` should be no longer than `INT32_MAX` - // milliseconds for the Pepper plugin implementation to prevent integer - // overflow. - virtual void ScheduleTaskOnMainThread(const base::Location& from_here, - ResultCallback callback, - int32_t result, - base::TimeDelta delay) = 0; - protected: // You shouldn't be doing deleting through this interface. ~Client() = default; @@ -160,11 +144,11 @@ class PaintManager { void Flush(); // Callback for asynchronous completion of Flush. - void OnFlushComplete(int32_t); + void OnFlushComplete(); // Callback for manual scheduling of paints when there is no flush callback // pending. - void OnManualCallbackComplete(int32_t); + void OnManualCallbackComplete(); // Non-owning pointer. See the constructor. const raw_ptr<Client> client_; diff --git a/chromium/pdf/paint_ready_rect.cc b/chromium/pdf/paint_ready_rect.cc index 75afd222f8e..6879f1264a5 100644 --- a/chromium/pdf/paint_ready_rect.cc +++ b/chromium/pdf/paint_ready_rect.cc @@ -4,13 +4,13 @@ #include "pdf/paint_ready_rect.h" -#include "pdf/ppapi_migration/image.h" +#include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/geometry/rect.h" namespace chrome_pdf { PaintReadyRect::PaintReadyRect(const gfx::Rect& rect, - const Image& image, + const SkBitmap& image, bool flush_now) : rect_(rect), image_(image), flush_now_(flush_now) {} diff --git a/chromium/pdf/paint_ready_rect.h b/chromium/pdf/paint_ready_rect.h index 9db2244a126..121c4b31260 100644 --- a/chromium/pdf/paint_ready_rect.h +++ b/chromium/pdf/paint_ready_rect.h @@ -5,7 +5,7 @@ #ifndef PDF_PAINT_READY_RECT_H_ #define PDF_PAINT_READY_RECT_H_ -#include "pdf/ppapi_migration/image.h" +#include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/geometry/rect.h" namespace chrome_pdf { @@ -16,7 +16,7 @@ namespace chrome_pdf { class PaintReadyRect { public: PaintReadyRect(const gfx::Rect& rect, - const Image& image, + const SkBitmap& image, bool flush_now = false); PaintReadyRect(const PaintReadyRect& other); @@ -26,7 +26,7 @@ class PaintReadyRect { const gfx::Rect& rect() const { return rect_; } void set_rect(const gfx::Rect& rect) { rect_ = rect; } - const Image& image() const { return image_; } + const SkBitmap& image() const { return image_; } // Whether to flush to screen immediately; otherwise, when the rest of the // plugin viewport is ready. @@ -34,7 +34,7 @@ class PaintReadyRect { private: gfx::Rect rect_; - Image image_; + SkBitmap image_; bool flush_now_; }; diff --git a/chromium/pdf/parsed_params.cc b/chromium/pdf/parsed_params.cc index 63087f148d4..a6d3b343482 100644 --- a/chromium/pdf/parsed_params.cc +++ b/chromium/pdf/parsed_params.cc @@ -26,8 +26,6 @@ ParsedParams::~ParsedParams() = default; absl::optional<ParsedParams> ParseWebPluginParams( const blink::WebPluginParams& params) { - // Keep in sync with `OutOfProcessInstance::Init()`. - // TODO(crbug.com/1232152): Don't have two implementations. ParsedParams result; for (size_t i = 0; i < params.attribute_names.size(); ++i) { if (params.attribute_names[i] == "src") { diff --git a/chromium/pdf/pdf_engine.h b/chromium/pdf/pdf_engine.h index 678e4a56899..6dd44b7a256 100644 --- a/chromium/pdf/pdf_engine.h +++ b/chromium/pdf/pdf_engine.h @@ -17,7 +17,6 @@ #include "base/values.h" #include "build/build_config.h" #include "pdf/document_layout.h" -#include "pdf/ppapi_migration/callback.h" #include "printing/mojom/print.mojom-forward.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkColor.h" @@ -33,10 +32,6 @@ class SkBitmap; -namespace base { -class Location; -} // namespace base - namespace blink { class WebInputEvent; struct WebPrintParams; @@ -71,9 +66,6 @@ enum class FontMappingMode { kNoMapping, // Perform font mapping in renderer processes using Blink/content APIs. kBlink, - // Perform font mapping in plugin processes using PPAPI. - // TODO(crbug.com/702993): Remove when PPAPI is gone. - kPepper, }; enum class DocumentPermission { @@ -247,10 +239,6 @@ class PDFEngine { // Notifies the client that the document has failed to load. virtual void DocumentLoadFailed() {} - // Asks the client to set the last plugin instance when applicable. - // TODO(crbug.com/702993): Remove after migrating away from PPAPI. - virtual void SetLastPluginInstance() {} - // Notifies that an unsupported feature in the PDF was encountered. virtual void DocumentHasUnsupportedFeature(const std::string& feature) {} @@ -292,17 +280,6 @@ class PDFEngine { // viewers. // See https://crbug.com/312882 for an example. virtual bool IsValidLink(const std::string& url) = 0; - - // Schedules work to be executed on a main thread after a specific delay. - // The `result` parameter will be passed as the argument to the `callback`. - // `result` is needed sometimes to emulate calls of some callbacks, but it's - // not always needed. `delay` should be no longer than `INT32_MAX` - // milliseconds for the Pepper plugin implementation to prevent integer - // overflow. - virtual void ScheduleTaskOnMainThread(const base::Location& from_here, - ResultCallback callback, - int32_t result, - base::TimeDelta delay) = 0; }; virtual ~PDFEngine() = default; @@ -414,7 +391,10 @@ class PDFEngine { int page_index, const std::vector<AccessibilityTextRunInfo>& text_runs) = 0; // For all the images in page `page_index`, get their alt texts and bounding - // boxes. + // boxes. If the alt text is empty or unavailable, and if the user has + // requested that the OCR service tag the PDF so that it is made accessible, + // transfer the raw image pixels in the `image_data` field. Otherwise do not + // populate the `image_data` field. virtual std::vector<AccessibilityImageInfo> GetImageInfo( int page_index, uint32_t text_run_count) = 0; @@ -446,7 +426,7 @@ class PDFEngine { // - "page" - an int Value. // - "children" - a list of Values, with each entry containing // a dictionary Value of the same structure. - virtual base::Value GetBookmarks() = 0; + virtual base::Value::List GetBookmarks() = 0; // Append blank pages to make a 1-page document to a `num_pages` document. // Always retain the first page data. diff --git a/chromium/pdf/pdf_features.cc b/chromium/pdf/pdf_features.cc index 0ace4e81163..4756f3a4940 100644 --- a/chromium/pdf/pdf_features.cc +++ b/chromium/pdf/pdf_features.cc @@ -20,10 +20,6 @@ const base::Feature kPdfIncrementalLoading = { const base::Feature kPdfPartialLoading = {"PdfPartialLoading", base::FEATURE_DISABLED_BY_DEFAULT}; -// TODO(crbug.com/702993): Remove this once the PDF viewer is Pepper-free. -const base::Feature kPdfUnseasoned = {"PdfUnseasoned", - base::FEATURE_ENABLED_BY_DEFAULT}; - // Feature has no effect if Chrome is built with no XFA support. const base::Feature kPdfXfaSupport = {"PdfXfaSupport", base::FEATURE_DISABLED_BY_DEFAULT}; diff --git a/chromium/pdf/pdf_features.h b/chromium/pdf/pdf_features.h index c8400e7996e..2adf0e5b22f 100644 --- a/chromium/pdf/pdf_features.h +++ b/chromium/pdf/pdf_features.h @@ -16,7 +16,6 @@ namespace features { extern const base::Feature kAccessiblePDFForm; extern const base::Feature kPdfIncrementalLoading; extern const base::Feature kPdfPartialLoading; -extern const base::Feature kPdfUnseasoned; extern const base::Feature kPdfXfaSupport; extern const base::Feature kTabAcrossPDFAnnotations; diff --git a/chromium/pdf/pdf_ppapi.cc b/chromium/pdf/pdf_ppapi.cc deleted file mode 100644 index 22c1ad3dab6..00000000000 --- a/chromium/pdf/pdf_ppapi.cc +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2018 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_ppapi.h" - -#include <memory> - -#include "pdf/out_of_process_instance.h" -#include "pdf/pdf.h" -#include "pdf/pdf_init.h" -#include "ppapi/c/ppp.h" -#include "ppapi/cpp/private/internal_module.h" -#include "ppapi/cpp/private/pdf.h" -#include "v8/include/v8.h" - -namespace chrome_pdf { - -namespace { - -class PDFModule : public pp::Module { - public: - PDFModule(); - ~PDFModule() override; - - // pp::Module implementation. - bool Init() override; - pp::Instance* CreateInstance(PP_Instance instance) override; -}; - -PDFModule::PDFModule() = default; - -PDFModule::~PDFModule() { - if (IsSDKInitializedViaPlugin()) { - ShutdownSDK(); - SetIsSDKInitializedViaPlugin(false); - } -} - -bool PDFModule::Init() { - return true; -} - -pp::Instance* PDFModule::CreateInstance(PP_Instance instance) { - if (!IsSDKInitializedViaPlugin()) { - v8::StartupData snapshot; - pp::PDF::GetV8ExternalSnapshotData(pp::InstanceHandle(instance), - &snapshot.data, &snapshot.raw_size); - if (snapshot.data) { - v8::V8::SetSnapshotDataBlob(&snapshot); - } - - InitializeSDK(/*enable_v8=*/true, FontMappingMode::kPepper); - SetIsSDKInitializedViaPlugin(true); - } - - return new OutOfProcessInstance(instance); -} - -} // namespace - -int32_t PPP_InitializeModule(PP_Module module_id, - PPB_GetInterface get_browser_interface) { - auto module = std::make_unique<PDFModule>(); - if (!module->InternalInit(module_id, get_browser_interface)) - return PP_ERROR_FAILED; - - pp::InternalSetModuleSingleton(module.release()); - return PP_OK; -} - -void PPP_ShutdownModule() { - delete pp::Module::Get(); - pp::InternalSetModuleSingleton(nullptr); -} - -const void* PPP_GetInterface(const char* interface_name) { - auto* module = pp::Module::Get(); - return module ? module->GetPluginInterface(interface_name) : nullptr; -} - -} // namespace chrome_pdf diff --git a/chromium/pdf/pdf_ppapi.h b/chromium/pdf/pdf_ppapi.h deleted file mode 100644 index ffde3009851..00000000000 --- a/chromium/pdf/pdf_ppapi.h +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2018 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. - -#ifndef PDF_PDF_PPAPI_H_ -#define PDF_PDF_PPAPI_H_ - -#include "base/component_export.h" -#include "ppapi/c/pp_module.h" -#include "ppapi/c/ppb.h" - -namespace chrome_pdf { - -int PPP_InitializeModule(PP_Module module_id, - PPB_GetInterface get_browser_interface); -void PPP_ShutdownModule(); -const void* PPP_GetInterface(const char* interface_name); - -} // namespace chrome_pdf - -#endif // PDF_PDF_PPAPI_H_ diff --git a/chromium/pdf/pdf_view_plugin_base.cc b/chromium/pdf/pdf_view_plugin_base.cc index 430268400b8..c383a11f6b5 100644 --- a/chromium/pdf/pdf_view_plugin_base.cc +++ b/chromium/pdf/pdf_view_plugin_base.cc @@ -24,17 +24,16 @@ #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/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "base/values.h" #include "net/base/escape.h" @@ -44,16 +43,13 @@ #include "pdf/content_restriction.h" #include "pdf/document_layout.h" #include "pdf/document_metadata.h" -#include "pdf/file_extension.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" @@ -63,7 +59,6 @@ #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_conversions.h" @@ -86,8 +81,6 @@ constexpr double kMinZoom = 0.01; // responsive. constexpr base::TimeDelta kAccessibilityPageDelay = base::Milliseconds(100); -constexpr base::TimeDelta kFindResultCooldown = base::Milliseconds(100); - constexpr char kChromeExtensionHost[] = "chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/"; @@ -110,13 +103,13 @@ enum class PinchPhase { // 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::Dict PrepareReplyMessage(base::StringPiece reply_type, + const base::Value::Dict& message) { + DCHECK_EQ(reply_type, *message.FindString("type") + "Reply"); - base::Value reply(base::Value::Type::DICTIONARY); - reply.SetStringKey("type", reply_type); - reply.SetStringKey("messageId", *message.FindStringKey("messageId")); + base::Value::Dict reply; + reply.Set("type", reply_type); + reply.Set("messageId", *message.FindString("messageId")); return reply; } @@ -201,15 +194,15 @@ void PdfViewPluginBase::InitializeBase(std::unique_ptr<PDFiumEngine> engine, } 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); + 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_list.Append(base::Value(DictFromRect(layout.page_rect(i)))); - message.SetKey("pageDimensions", std::move(page_dimensions_list)); + page_dimensions.Append(base::Value(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 @@ -236,18 +229,18 @@ void PdfViewPluginBase::DidScroll(const gfx::Vector2d& 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); + base::Value::Dict message; + message.Set("type", "setScrollPosition"); + message.Set("x", static_cast<double>(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); + base::Value::Dict message; + message.Set("type", "setScrollPosition"); + message.Set("y", static_cast<double>(y_scroll_pos)); SendMessage(std::move(message)); } @@ -255,10 +248,10 @@ 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); + base::Value::Dict message; + message.Set("type", "scrollBy"); + message.Set("x", static_cast<double>(x_delta)); + message.Set("y", static_cast<double>(y_delta)); SendMessage(std::move(message)); } @@ -266,18 +259,18 @@ 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); + base::Value::Dict message; + message.Set("type", "goToPage"); + message.Set("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)); + base::Value::Dict message; + message.Set("type", "navigate"); + message.Set("url", url); + message.Set("disposition", static_cast<int>(disposition)); SendMessage(std::move(message)); } @@ -285,55 +278,21 @@ 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); + base::Value::Dict message; + message.Set("type", "navigateToDestination"); + message.Set("page", page); if (x) - message.SetDoubleKey("x", *x); + message.Set("x", static_cast<double>(*x)); if (y) - message.SetDoubleKey("y", *y); + message.Set("y", static_cast<double>(*y)); if (zoom) - message.SetDoubleKey("zoom", *zoom); + message.Set("zoom", static_cast<double>(*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"); + base::Value::Dict message; + message.Set("type", "touchSelectionOccurred"); SendMessage(std::move(message)); } @@ -342,14 +301,14 @@ void PdfViewPluginBase::GetDocumentPassword( DCHECK(password_callback_.is_null()); password_callback_ = std::move(callback); - base::Value message(base::Value::Type::DICTIONARY); - message.SetStringKey("type", "getPassword"); + base::Value::Dict message; + message.Set("type", "getPassword"); SendMessage(std::move(message)); } void PdfViewPluginBase::Beep() { - base::Value message(base::Value::Type::DICTIONARY); - message.SetStringKey("type", "beep"); + base::Value::Dict message; + message.Set("type", "beep"); SendMessage(std::move(message)); } @@ -362,13 +321,13 @@ void PdfViewPluginBase::Email(const std::string& to, 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)); + base::Value::Dict message; + message.Set("type", "email"); + message.Set("to", net::EscapeUrlEncodedData(to, false)); + message.Set("cc", net::EscapeUrlEncodedData(cc, false)); + message.Set("bcc", net::EscapeUrlEncodedData(bcc, false)); + message.Set("subject", net::EscapeUrlEncodedData(subject, false)); + message.Set("body", net::EscapeUrlEncodedData(body, false)); SendMessage(std::move(message)); } @@ -421,7 +380,6 @@ void PdfViewPluginBase::DocumentLoadComplete() { document_load_state_ = DocumentLoadState::kComplete; UserMetricsRecordAction("PDF.LoadSuccess"); - RecordDocumentMetrics(); // Clear the focus state for on-screen keyboards. FormFieldFocusChange(PDFEngine::FocusFieldType::kNoFocus); @@ -429,9 +387,7 @@ void PdfViewPluginBase::DocumentLoadComplete() { if (IsPrintPreview()) OnPrintPreviewLoaded(); - SendAttachments(); - SendBookmarks(); - SendMetadata(); + OnDocumentLoadComplete(); if (accessibility_state_ == AccessibilityState::kPending) LoadAccessibility(); @@ -498,9 +454,9 @@ void PdfViewPluginBase::DocumentLoadProgress(uint32_t available, } void PdfViewPluginBase::FormFieldFocusChange(PDFEngine::FocusFieldType type) { - base::Value message(base::Value::Type::DICTIONARY); - message.SetStringKey("type", "formFocusChange"); - message.SetBoolKey("focused", type != PDFEngine::FocusFieldType::kNoFocus); + base::Value::Dict message; + message.Set("type", "formFocusChange"); + message.Set("focused", type != PDFEngine::FocusFieldType::kNoFocus); SendMessage(std::move(message)); SetFormTextFieldInFocus(type == PDFEngine::FocusFieldType::kText); @@ -515,9 +471,9 @@ SkColor PdfViewPluginBase::GetBackgroundColor() { } void PdfViewPluginBase::SetIsSelecting(bool is_selecting) { - base::Value message(base::Value::Type::DICTIONARY); - message.SetStringKey("type", "setIsSelecting"); - message.SetBoolKey("isSelecting", is_selecting); + base::Value::Dict message; + message.Set("type", "setIsSelecting"); + message.Set("isSelecting", is_selecting); SendMessage(std::move(message)); } @@ -547,25 +503,21 @@ void PdfViewPluginBase::EnteredEditMode() { edit_mode_ = true; SetPluginCanSave(true); - base::Value message(base::Value::Type::DICTIONARY); - message.SetStringKey("type", "setIsEditing"); + base::Value::Dict message; + message.Set("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); + base::Value::Dict message; + message.Set("type", "documentFocusChanged"); + message.Set("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(); } bool PdfViewPluginBase::HandleInputEvent(const blink::WebInputEvent& event) { @@ -596,8 +548,8 @@ bool PdfViewPluginBase::HandleInputEvent(const blink::WebInputEvent& event) { return event_to_handle.GetType() == blink::WebInputEvent::Type::kMouseDown; } -void PdfViewPluginBase::HandleMessage(const base::Value& message) { - using MessageHandler = void (PdfViewPluginBase::*)(const base::Value&); +void PdfViewPluginBase::HandleMessage(const base::Value::Dict& message) { + using MessageHandler = void (PdfViewPluginBase::*)(const base::Value::Dict&); static constexpr auto kMessageHandlers = base::MakeFixedFlatMap<base::StringPiece, MessageHandler>({ {"displayAnnotations", @@ -623,24 +575,23 @@ void PdfViewPluginBase::HandleMessage(const base::Value& message) { {"setReadOnly", &PdfViewPluginBase::HandleSetReadOnlyMessage}, {"setTwoUpView", &PdfViewPluginBase::HandleSetTwoUpViewMessage}, {"stopScrolling", &PdfViewPluginBase::HandleStopScrollingMessage}, - {"updateScroll", &PdfViewPluginBase::HandleUpdateScrollMessage}, {"viewport", &PdfViewPluginBase::HandleViewportMessage}, }); - MessageHandler handler = kMessageHandlers.at(*message.FindStringKey("type")); + MessageHandler handler = kMessageHandlers.at(*message.FindString("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_)); + base::Value::Dict message; + message.Set("type", "saveData"); + message.Set("token", token); + message.Set("fileName", GetFileNameForSaveFromUrl(url_)); // Expose `edit_mode_` state for integration testing. - message.SetBoolKey("editModeForTesting", edit_mode_); + message.Set("editModeForTesting", edit_mode_); base::Value data_to_save; if (edit_mode_) { @@ -660,14 +611,14 @@ void PdfViewPluginBase::SaveToBuffer(const std::string& token) { #endif // BUILDFLAG(ENABLE_INK) } - message.SetKey("dataToSave", std::move(data_to_save)); + message.Set("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); + base::Value::Dict message; + message.Set("type", "consumeSaveToken"); + message.Set("token", token); SendMessage(std::move(message)); } @@ -675,15 +626,15 @@ 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); + base::Value::Dict message; + message.Set("type", "loadProgress"); + message.Set("progress", percentage); SendMessage(std::move(message)); } void PdfViewPluginBase::SendPrintPreviewLoadedNotification() { - base::Value message(base::Value::Type::DICTIONARY); - message.SetStringKey("type", "printPreviewLoaded"); + base::Value::Dict message; + message.Set("type", "printPreviewLoaded"); SendMessage(std::move(message)); } @@ -795,7 +746,7 @@ void PdfViewPluginBase::LoadUrl(base::StringPiece url, bool is_print_preview) { last_progress_sent_ = 0; UrlRequest request; - request.url = RewriteRequestUrl(url); + request.url = static_cast<std::string>(url); request.method = "GET"; request.ignore_redirects = true; @@ -808,19 +759,13 @@ void PdfViewPluginBase::LoadUrl(base::StringPiece url, bool is_print_preview) { 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()); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(&PdfViewPluginBase::ClearDeferredInvalidates, + GetWeakPtr())); } void PdfViewPluginBase::OnGeometryChanged(double old_zoom, @@ -847,15 +792,13 @@ int PdfViewPluginBase::PrintBegin(const blink::WebPrintParams& print_params) { if (!ret) return 0; - const bool can_print = - engine()->HasPermission(DocumentPermission::kPrintHighQuality) || - (print_params.rasterize_pdf && - engine()->HasPermission(DocumentPermission::kPrintLowQuality)); - - if (!can_print) + 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; } @@ -911,8 +854,8 @@ void PdfViewPluginBase::UpdateGeometryOnPluginRectChanged( OnGeometryChanged(zoom_, old_device_scale); } -Image PdfViewPluginBase::GetPluginImageData() const { - return Image(image_data_); +SkBitmap PdfViewPluginBase::GetPluginImageData() const { + return image_data_; } void PdfViewPluginBase::RecalculateAreas(double old_zoom, @@ -938,10 +881,6 @@ void PdfViewPluginBase::RecalculateAreas(double old_zoom, 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() { @@ -1050,11 +989,11 @@ void PdfViewPluginBase::PrepareAndSetAccessibilityPageInfo(int32_t page_index) { std::move(chars), std::move(page_objects)); // Schedule loading the next page. - ScheduleTaskOnMainThread( + base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&PdfViewPluginBase::PrepareAndSetAccessibilityPageInfo, - GetWeakPtr()), - /*result=*/page_index + 1, kAccessibilityPageDelay); + GetWeakPtr(), page_index + 1), + kAccessibilityPageDelay); } void PdfViewPluginBase::PrepareAndSetAccessibilityViewportInfo() { @@ -1076,22 +1015,6 @@ void PdfViewPluginBase::PrepareAndSetAccessibilityViewportInfo() { SetAccessibilityViewportInfo(std::move(viewport_info)); } -bool PdfViewPluginBase::StartFind(const std::string& text, - bool case_sensitive) { - engine_->StartFind(text, case_sensitive); - return true; -} - -void PdfViewPluginBase::SelectFindResult(bool forward) { - engine_->SelectFindResult(forward); -} - -void PdfViewPluginBase::StopFind() { - engine_->StopFind(); - tickmarks_.clear(); - NotifyFindTickmarks(tickmarks_); -} - gfx::Vector2d PdfViewPluginBase::plugin_offset_in_frame() const { return plugin_rect_.OffsetFromOrigin(); } @@ -1099,7 +1022,10 @@ gfx::Vector2d PdfViewPluginBase::plugin_offset_in_frame() const { void PdfViewPluginBase::SetZoom(double scale) { double old_zoom = zoom_; zoom_ = scale; + OnGeometryChanged(old_zoom, device_scale_); + if (!document_size_.IsEmpty()) + paint_manager_.InvalidateRect(gfx::Rect(plugin_rect_.size())); } // static @@ -1114,21 +1040,22 @@ base::Value::DictStorage PdfViewPluginBase::DictFromRect( } void PdfViewPluginBase::HandleDisplayAnnotationsMessage( - const base::Value& message) { - engine()->DisplayAnnotations(message.FindBoolKey("display").value()); + const base::Value::Dict& message) { + engine()->DisplayAnnotations(message.FindBool("display").value()); } void PdfViewPluginBase::HandleGetNamedDestinationMessage( - const base::Value& message) { + const base::Value::Dict& message) { absl::optional<PDFEngine::NamedDestination> named_destination = - engine()->GetNamedDestination(*message.FindStringKey("namedDestination")); + engine()->GetNamedDestination(*message.FindString("namedDestination")); const int page_number = named_destination.has_value() ? base::checked_cast<int>(named_destination->page) : -1; - base::Value reply = PrepareReplyMessage("getNamedDestinationReply", message); - reply.SetIntKey("pageNumber", page_number); + base::Value::Dict reply = + PrepareReplyMessage("getNamedDestinationReply", message); + reply.Set("pageNumber", page_number); if (named_destination.has_value() && !named_destination->view.empty()) { std::ostringstream view_stream; @@ -1140,32 +1067,34 @@ void PdfViewPluginBase::HandleGetNamedDestinationMessage( view_stream << "," << named_destination->xyz_params; } - reply.SetStringKey("namedDestinationView", view_stream.str()); + reply.Set("namedDestinationView", view_stream.str()); } SendMessage(std::move(reply)); } void PdfViewPluginBase::HandleGetPasswordCompleteMessage( - const base::Value& message) { + const base::Value::Dict& message) { DCHECK(password_callback_); - std::move(password_callback_).Run(*message.FindStringKey("password")); + std::move(password_callback_).Run(*message.FindString("password")); } void PdfViewPluginBase::HandleGetSelectedTextMessage( - const base::Value& message) { + const base::Value::Dict& message) { // Always return unix newlines to JavaScript. std::string selected_text; base::RemoveChars(engine()->GetSelectedText(), "\r", &selected_text); - base::Value reply = PrepareReplyMessage("getSelectedTextReply", message); - reply.SetStringKey("selectedText", selected_text); + base::Value::Dict reply = + PrepareReplyMessage("getSelectedTextReply", message); + reply.Set("selectedText", selected_text); SendMessage(std::move(reply)); } -void PdfViewPluginBase::HandleGetThumbnailMessage(const base::Value& message) { - const int page_index = message.FindIntKey("page").value(); - base::Value reply = PrepareReplyMessage("getThumbnailReply", message); +void PdfViewPluginBase::HandleGetThumbnailMessage( + const base::Value::Dict& message) { + const int page_index = message.FindInt("page").value(); + base::Value::Dict reply = PrepareReplyMessage("getThumbnailReply", message); engine()->RequestThumbnail(page_index, device_scale_, base::BindOnce(&PdfViewPluginBase::SendThumbnail, @@ -1173,9 +1102,9 @@ void PdfViewPluginBase::HandleGetThumbnailMessage(const base::Value& message) { } void PdfViewPluginBase::HandleLoadPreviewPageMessage( - const base::Value& message) { - const std::string& url = *message.FindStringKey("url"); - int index = message.FindIntKey("index").value(); + const base::Value::Dict& message) { + const std::string& url = *message.FindString("url"); + int index = message.FindInt("index").value(); // For security reasons, crash if `url` is not for Print Preview. CHECK(IsPrintPreview()); @@ -1183,15 +1112,16 @@ void PdfViewPluginBase::HandleLoadPreviewPageMessage( ProcessPreviewPageInfo(url, index); } -void PdfViewPluginBase::HandlePrintMessage(const base::Value& /*message*/) { +void PdfViewPluginBase::HandlePrintMessage( + const base::Value::Dict& /*message*/) { Print(); } void PdfViewPluginBase::HandleResetPrintPreviewModeMessage( - const base::Value& message) { - const std::string& url = *message.FindStringKey("url"); - bool is_grayscale = message.FindBoolKey("grayscale").value(); - int print_preview_page_count = message.FindIntKey("pageCount").value(); + const base::Value::Dict& message) { + const std::string& url = *message.FindString("url"); + bool is_grayscale = message.FindBool("grayscale").value(); + int print_preview_page_count = message.FindInt("pageCount").value(); // For security reasons, crash if `url` is not for Print Preview. CHECK(IsPrintPreview()); @@ -1230,18 +1160,18 @@ void PdfViewPluginBase::HandleResetPrintPreviewModeMessage( } void PdfViewPluginBase::HandleRotateClockwiseMessage( - const base::Value& /*message*/) { + const base::Value::Dict& /*message*/) { engine()->RotateClockwise(); } void PdfViewPluginBase::HandleRotateCounterclockwiseMessage( - const base::Value& /*message*/) { + const base::Value::Dict& /*message*/) { engine()->RotateCounterclockwise(); } -void PdfViewPluginBase::HandleSaveMessage(const base::Value& message) { - const std::string& token = *message.FindStringKey("token"); - int request_type = message.FindIntKey("saveRequestType").value(); +void PdfViewPluginBase::HandleSaveMessage(const base::Value::Dict& message) { + const std::string& token = *message.FindString("token"); + int request_type = message.FindInt("saveRequestType").value(); DCHECK_GE(request_type, static_cast<int>(SaveRequestType::kAnnotation)); DCHECK_LE(request_type, static_cast<int>(SaveRequestType::kEdited)); @@ -1268,8 +1198,8 @@ void PdfViewPluginBase::HandleSaveMessage(const base::Value& message) { } void PdfViewPluginBase::HandleSaveAttachmentMessage( - const base::Value& message) { - const int index = message.FindIntKey("attachmentIndex").value(); + const base::Value::Dict& message) { + const int index = message.FindInt("attachmentIndex").value(); const std::vector<DocumentAttachmentInfo>& list = engine()->GetDocumentAttachmentInfoList(); @@ -1282,42 +1212,41 @@ void PdfViewPluginBase::HandleSaveAttachmentMessage( base::Value data_to_save( IsSaveDataSizeValid(data.size()) ? data : std::vector<uint8_t>()); - base::Value reply = PrepareReplyMessage("saveAttachmentReply", message); - reply.SetKey("dataToSave", std::move(data_to_save)); + base::Value::Dict reply = PrepareReplyMessage("saveAttachmentReply", message); + reply.Set("dataToSave", std::move(data_to_save)); SendMessage(std::move(reply)); } -void PdfViewPluginBase::HandleSelectAllMessage(const base::Value& /*message*/) { +void PdfViewPluginBase::HandleSelectAllMessage( + const base::Value::Dict& /*message*/) { engine()->SelectAll(); } void PdfViewPluginBase::HandleSetBackgroundColorMessage( - const base::Value& message) { + const base::Value::Dict& message) { background_color_ = - base::checked_cast<SkColor>(message.FindDoubleKey("color").value()); + base::checked_cast<SkColor>(message.FindDouble("color").value()); } -void PdfViewPluginBase::HandleSetReadOnlyMessage(const base::Value& message) { - engine()->SetReadOnly(message.FindBoolKey("enableReadOnly").value()); +void PdfViewPluginBase::HandleSetReadOnlyMessage( + const base::Value::Dict& message) { + engine()->SetReadOnly(message.FindBool("enableReadOnly").value()); } -void PdfViewPluginBase::HandleSetTwoUpViewMessage(const base::Value& message) { - engine()->SetTwoUpView(message.FindBoolKey("enableTwoUpView").value()); +void PdfViewPluginBase::HandleSetTwoUpViewMessage( + const base::Value::Dict& message) { + engine()->SetTwoUpView(message.FindBool("enableTwoUpView").value()); } void PdfViewPluginBase::HandleStopScrollingMessage( - const base::Value& /*message*/) { + const base::Value::Dict& /*message*/) { stop_scrolling_ = true; } -void PdfViewPluginBase::HandleUpdateScrollMessage(const base::Value& message) { - UpdateScroll(GetScrollPositionFromOffset(gfx::Vector2dF( - message.FindDoubleKey("x").value(), message.FindDoubleKey("y").value()))); -} - -void PdfViewPluginBase::HandleViewportMessage(const base::Value& message) { - const base::Value* layout_options_value = - message.FindDictKey("layoutOptions"); +void PdfViewPluginBase::HandleViewportMessage( + const base::Value::Dict& message) { + const base::Value::Dict* layout_options_value = + message.FindDict("layoutOptions"); if (layout_options_value) { DocumentLayout::Options layout_options; layout_options.FromValue(*layout_options_value); @@ -1326,7 +1255,10 @@ void PdfViewPluginBase::HandleViewportMessage(const base::Value& message) { // TODO(crbug.com/1013800): Eliminate need to get document size from here. document_size_ = engine()->ApplyDocumentLayout(layout_options); + OnGeometryChanged(zoom_, device_scale_); + if (!document_size_.IsEmpty()) + paint_manager_.InvalidateRect(gfx::Rect(plugin_rect_.size())); // Send 100% loading progress only after initial layout negotiated. if (last_progress_sent_ < 100 && @@ -1335,11 +1267,11 @@ void PdfViewPluginBase::HandleViewportMessage(const base::Value& message) { } } - gfx::Vector2dF scroll_offset(*message.FindDoubleKey("xOffset"), - *message.FindDoubleKey("yOffset")); - double new_zoom = *message.FindDoubleKey("zoom"); + gfx::Vector2dF scroll_offset(*message.FindDouble("xOffset"), + *message.FindDouble("yOffset")); + double new_zoom = *message.FindDouble("zoom"); const PinchPhase pinch_phase = - static_cast<PinchPhase>(*message.FindIntKey("pinchPhase")); + static_cast<PinchPhase>(*message.FindInt("pinchPhase")); received_viewport_message_ = true; stop_scrolling_ = false; @@ -1360,14 +1292,14 @@ void PdfViewPluginBase::HandleViewportMessage(const base::Value& message) { if (pinch_phase == PinchPhase::kUpdateZoomIn || (pinch_phase == PinchPhase::kUpdateZoomOut && zoom_ratio > 1.0)) { // Get the coordinates of the center of the pinch gesture. - const double pinch_x = *message.FindDoubleKey("pinchX"); - const double pinch_y = *message.FindDoubleKey("pinchY"); + const double pinch_x = *message.FindDouble("pinchX"); + const double pinch_y = *message.FindDouble("pinchY"); gfx::Point pinch_center(pinch_x, pinch_y); // Get the pinch vector which represents the panning caused by the change in // pinch center between the start and the end of the gesture. - const double pinch_vector_x = *message.FindDoubleKey("pinchVectorX"); - const double pinch_vector_y = *message.FindDoubleKey("pinchVectorY"); + const double pinch_vector_x = *message.FindDouble("pinchVectorX"); + const double pinch_vector_y = *message.FindDouble("pinchVectorY"); gfx::Vector2d pinch_vector = gfx::Vector2d(pinch_vector_x * zoom_ratio, pinch_vector_y * zoom_ratio); @@ -1429,7 +1361,7 @@ void PdfViewPluginBase::HandleViewportMessage(const base::Value& message) { // Bound the input parameters. new_zoom = std::max(kMinZoom, new_zoom); - DCHECK(message.FindBoolKey("userInitiated").has_value()); + DCHECK(message.FindBool("userInitiated").has_value()); SetZoom(new_zoom); UpdateScroll(GetScrollPositionFromOffset(scroll_offset)); @@ -1539,112 +1471,21 @@ void PdfViewPluginBase::PrepareForFirstPaint( PaintReadyRect(rect, GetPluginImageData(), /*flush_now=*/true)); } -void PdfViewPluginBase::ClearDeferredInvalidates( - int32_t /*unused_but_required*/) { +void PdfViewPluginBase::ClearDeferredInvalidates() { DCHECK(!in_paint_); for (const gfx::Rect& rect : deferred_invalidates_) Invalidate(rect); deferred_invalidates_.clear(); } -void PdfViewPluginBase::SendAttachments() { - const std::vector<DocumentAttachmentInfo>& attachment_infos = - engine()->GetDocumentAttachmentInfoList(); - if (attachment_infos.empty()) - return; - - base::Value attachments(base::Value::Type::LIST); - for (const DocumentAttachmentInfo& attachment_info : attachment_infos) { - // Send `size` as -1 to indicate that the attachment is too large to be - // downloaded. - const int size = attachment_info.size_bytes <= kMaximumSavedFileSize - ? static_cast<int>(attachment_info.size_bytes) - : -1; - - base::Value attachment(base::Value::Type::DICTIONARY); - attachment.SetStringKey("name", attachment_info.name); - attachment.SetIntKey("size", size); - attachment.SetBoolKey("readable", attachment_info.is_readable); - attachments.Append(std::move(attachment)); - } - - base::Value message(base::Value::Type::DICTIONARY); - message.SetStringKey("type", "attachments"); - message.SetKey("attachmentsData", std::move(attachments)); - SendMessage(std::move(message)); -} - -void PdfViewPluginBase::SendBookmarks() { - base::Value bookmarks = engine()->GetBookmarks(); - if (bookmarks.GetListDeprecated().empty()) - return; - - base::Value message(base::Value::Type::DICTIONARY); - message.SetStringKey("type", "bookmarks"); - message.SetKey("bookmarksData", std::move(bookmarks)); - SendMessage(std::move(message)); -} - -void PdfViewPluginBase::SendMetadata() { - base::Value metadata(base::Value::Type::DICTIONARY); - const DocumentMetadata& document_metadata = engine()->GetDocumentMetadata(); - - const std::string version = FormatPdfVersion(document_metadata.version); - if (!version.empty()) - metadata.SetStringKey("version", version); +void PdfViewPluginBase::SendThumbnail(base::Value::Dict reply, + Thumbnail thumbnail) { + DCHECK_EQ(*reply.FindString("type"), "getThumbnailReply"); + DCHECK(reply.FindString("messageId")); - metadata.SetStringKey("fileSize", - ui::FormatBytes(document_metadata.size_bytes)); - - metadata.SetBoolKey("linearized", document_metadata.linearized); - - if (!document_metadata.title.empty()) - metadata.SetStringKey("title", document_metadata.title); - - if (!document_metadata.author.empty()) - metadata.SetStringKey("author", document_metadata.author); - - if (!document_metadata.subject.empty()) - metadata.SetStringKey("subject", document_metadata.subject); - - if (!document_metadata.keywords.empty()) - metadata.SetStringKey("keywords", document_metadata.keywords); - - if (!document_metadata.creator.empty()) - metadata.SetStringKey("creator", document_metadata.creator); - - if (!document_metadata.producer.empty()) - metadata.SetStringKey("producer", document_metadata.producer); - - if (!document_metadata.creation_date.is_null()) { - metadata.SetStringKey("creationDate", base::TimeFormatShortDateAndTime( - document_metadata.creation_date)); - } - - if (!document_metadata.mod_date.is_null()) { - metadata.SetStringKey("modDate", base::TimeFormatShortDateAndTime( - document_metadata.mod_date)); - } - - metadata.SetStringKey("pageSize", - FormatPageSize(engine()->GetUniformPageSizePoints())); - - metadata.SetBoolKey("canSerializeDocument", - IsSaveDataSizeValid(engine()->GetLoadedByteSize())); - - base::Value message(base::Value::Type::DICTIONARY); - message.SetStringKey("type", "metadata"); - message.SetKey("metadataData", std::move(metadata)); - SendMessage(std::move(message)); -} - -void PdfViewPluginBase::SendThumbnail(base::Value reply, Thumbnail thumbnail) { - DCHECK_EQ(*reply.FindStringKey("type"), "getThumbnailReply"); - DCHECK(reply.FindStringKey("messageId")); - - reply.SetKey("imageData", base::Value(thumbnail.TakeData())); - reply.SetIntKey("width", thumbnail.image_size().width()); - reply.SetIntKey("height", thumbnail.image_size().height()); + reply.Set("imageData", thumbnail.TakeData()); + reply.Set("width", thumbnail.image_size().width()); + reply.Set("height", thumbnail.image_size().height()); SendMessage(std::move(reply)); } @@ -1666,77 +1507,11 @@ void PdfViewPluginBase::LoadAccessibility() { PrepareAndSetAccessibilityViewportInfo(); // Schedule loading the first page. - ScheduleTaskOnMainThread( + base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&PdfViewPluginBase::PrepareAndSetAccessibilityPageInfo, - GetWeakPtr()), - /*result=*/0, kAccessibilityPageDelay); -} - -void PdfViewPluginBase::ResetRecentlySentFindUpdate( - int32_t /*unused_but_required*/) { - recently_sent_find_update_ = false; -} - -namespace { - -// These values are persisted to logs. Entries should not be renumbered and -// numeric values should never be reused. -enum class PdfHasAttachment { - kNo = 0, - kYes = 1, - kMaxValue = kYes, -}; - -// These values are persisted to logs. Entries should not be renumbered and -// numeric values should never be reused. -enum class PdfIsTagged { - kNo = 0, - kYes = 1, - kMaxValue = kYes, -}; - -} // namespace - -void PdfViewPluginBase::RecordAttachmentTypes() { - const std::vector<DocumentAttachmentInfo>& list = - engine()->GetDocumentAttachmentInfoList(); - for (const auto& info : list) { - HistogramEnumeration("PDF.AttachmentType", - FileNameToExtensionIndex(info.name)); - } -} - -void PdfViewPluginBase::RecordDocumentMetrics() { - const DocumentMetadata& document_metadata = engine()->GetDocumentMetadata(); - HistogramEnumeration("PDF.Version", document_metadata.version); - HistogramCustomCounts("PDF.PageCount", document_metadata.page_count, 1, - 1000000, 50); - HistogramEnumeration("PDF.HasAttachment", document_metadata.has_attachments - ? PdfHasAttachment::kYes - : PdfHasAttachment::kNo); - HistogramEnumeration("PDF.IsTagged", document_metadata.tagged - ? PdfIsTagged::kYes - : PdfIsTagged::kNo); - HistogramEnumeration("PDF.FormType", document_metadata.form_type); - RecordAttachmentTypes(); -} - -template <typename T> -void PdfViewPluginBase::HistogramEnumeration(const char* name, T sample) { - if (IsPrintPreview()) - return; - base::UmaHistogramEnumeration(name, sample); -} - -void PdfViewPluginBase::HistogramCustomCounts(const char* name, - int32_t sample, - int32_t min, - int32_t max, - uint32_t bucket_count) { - if (IsPrintPreview()) - return; - base::UmaHistogramCustomCounts(name, sample, min, max, bucket_count); + GetWeakPtr(), /*page_index=*/0), + kAccessibilityPageDelay); } void PdfViewPluginBase::DidOpen(std::unique_ptr<UrlLoader> loader, @@ -1777,7 +1552,10 @@ void PdfViewPluginBase::OnPrintPreviewLoaded() { print_preview_loaded_page_count_ = 1; AppendBlankPrintPreviewPages(); } + OnGeometryChanged(0, 0); + if (!document_size_.IsEmpty()) + paint_manager_.InvalidateRect(gfx::Rect(plugin_rect_.size())); } void PdfViewPluginBase::AppendBlankPrintPreviewPages() { diff --git a/chromium/pdf/pdf_view_plugin_base.h b/chromium/pdf/pdf_view_plugin_base.h index 4a5384aa7a6..498d8ed7248 100644 --- a/chromium/pdf/pdf_view_plugin_base.h +++ b/chromium/pdf/pdf_view_plugin_base.h @@ -44,7 +44,6 @@ class Vector2d; namespace chrome_pdf { -class Image; class PDFiumEngine; class Thumbnail; class UrlLoader; @@ -56,14 +55,11 @@ struct AccessibilityPageObjects; struct AccessibilityTextRunInfo; struct AccessibilityViewportInfo; -// Common base to share code between the two plugin implementations, -// `OutOfProcessInstance` (Pepper) and `PdfViewWebPlugin` (Blink). +// TODO(crbug.com/1302059): Merge with PdfViewWebPlugin. class PdfViewPluginBase : public PDFEngine::Client, public PaintManager::Client, public PreviewModeClient::Client { public: - using PDFEngine::Client::ScheduleTaskOnMainThread; - // Do not save files with over 100 MB. This cap should be kept in sync with // and is also enforced in chrome/browser/resources/pdf/pdf_viewer.js. static constexpr size_t kMaximumSavedFileSize = 100 * 1000 * 1000; @@ -87,7 +83,7 @@ class PdfViewPluginBase : public PDFEngine::Client, kFailed, }; - // Must match `SaveRequestType` in chrome/browser/resources/pdf/constants.js. + // Must match `SaveRequestType` in chrome/browser/resources/pdf/constants.ts. enum class SaveRequestType { kAnnotation = 0, kOriginal = 1, @@ -111,8 +107,6 @@ class PdfViewPluginBase : public PDFEngine::Client, const float* x, const float* y, const float* zoom) override; - void UpdateTickMarks(const std::vector<gfx::Rect>& tickmarks) override; - void NotifyNumberOfFindResultsChanged(int total, bool final_result) override; void NotifyTouchSelectionOccurred() override; void GetDocumentPassword( base::OnceCallback<void(const std::string&)> callback) override; @@ -230,21 +224,18 @@ class PdfViewPluginBase : public PDFEngine::Client, // frame's origin. virtual std::unique_ptr<UrlLoader> CreateUrlLoaderInternal() = 0; - // Rewrites the request URL just before sending to the URL loader. - // - // TODO(crbug.com/1238829): This is a workaround for Pepper not supporting - // chrome-untrusted://print/ URLs. - virtual std::string RewriteRequestUrl(base::StringPiece url) const; + // Runs when document load completes. + virtual void OnDocumentLoadComplete() = 0; bool HandleInputEvent(const blink::WebInputEvent& event); // Handles `postMessage()` calls from the embedder. - void HandleMessage(const base::Value& message); + void HandleMessage(const base::Value::Dict& message); // Enqueues a "message" event carrying `message` to the embedder. Messages are // guaranteed to be received in the order that they are sent. This method is // non-blocking. - virtual void SendMessage(base::Value message) = 0; + virtual void SendMessage(base::Value::Dict message) = 0; // Invokes the "SaveAs" dialog. virtual void SaveAs() = 0; @@ -272,7 +263,7 @@ class PdfViewPluginBase : public PDFEngine::Client, void OnGeometryChanged(double old_zoom, float old_device_scale); // Returns the plugin-specific image data buffer. - virtual Image GetPluginImageData() const; + virtual SkBitmap GetPluginImageData() const; // Updates the geometry of the plugin and its image data if the plugin rect // or the device scale has changed. `new_plugin_rect` must be in device @@ -330,17 +321,6 @@ class PdfViewPluginBase : public PDFEngine::Client, virtual void SetAccessibilityViewportInfo( AccessibilityViewportInfo viewport_info) = 0; - // Find handlers. - bool StartFind(const std::string& text, bool case_sensitive); - void SelectFindResult(bool forward); - void StopFind(); - - // Notify the plugin container about the total matches for a find request. - virtual void NotifyFindResultsChanged(int total, bool final_result) = 0; - - // Notify the frame about the tickmarks for the find request. - virtual void NotifyFindTickmarks(const std::vector<gfx::Rect>& tickmarks) = 0; - // Returns the print preset options for the document. blink::WebPrintPresetOptions GetPrintPresetOptions(); @@ -375,11 +355,6 @@ class PdfViewPluginBase : public PDFEngine::Client, // document. virtual void InvokePrintDialog() = 0; - // Notifies the embedder about a new link under the cursor. - // TODO(crbug.com/702993): This is only needed by `OutOfProcessInstance`. - // Remove this method when that class ceases to exist. - virtual void NotifyLinkUnderCursor() {} - // Notifies the embedder of the top-left and bottom-right coordinates of the // current selection. virtual void NotifySelectionChanged(const gfx::PointF& left, @@ -441,25 +416,25 @@ class PdfViewPluginBase : public PDFEngine::Client, const gfx::Vector2dF& scroll_offset) const; // Message handlers. - void HandleDisplayAnnotationsMessage(const base::Value& message); - void HandleGetNamedDestinationMessage(const base::Value& message); - void HandleGetPasswordCompleteMessage(const base::Value& message); - void HandleGetSelectedTextMessage(const base::Value& message); - void HandleGetThumbnailMessage(const base::Value& message); - void HandleLoadPreviewPageMessage(const base::Value& message); - void HandlePrintMessage(const base::Value& /*message*/); - void HandleResetPrintPreviewModeMessage(const base::Value& message); - void HandleRotateClockwiseMessage(const base::Value& /*message*/); - void HandleRotateCounterclockwiseMessage(const base::Value& /*message*/); - void HandleSaveMessage(const base::Value& message); - void HandleSaveAttachmentMessage(const base::Value& message); - void HandleSelectAllMessage(const base::Value& /*message*/); - void HandleSetBackgroundColorMessage(const base::Value& message); - void HandleSetReadOnlyMessage(const base::Value& message); - void HandleSetTwoUpViewMessage(const base::Value& message); - void HandleStopScrollingMessage(const base::Value& /*message*/); - void HandleUpdateScrollMessage(const base::Value& message); - void HandleViewportMessage(const base::Value& message); + void HandleDisplayAnnotationsMessage(const base::Value::Dict& message); + void HandleGetNamedDestinationMessage(const base::Value::Dict& message); + void HandleGetPasswordCompleteMessage(const base::Value::Dict& message); + void HandleGetSelectedTextMessage(const base::Value::Dict& message); + void HandleGetThumbnailMessage(const base::Value::Dict& message); + void HandleLoadPreviewPageMessage(const base::Value::Dict& message); + void HandlePrintMessage(const base::Value::Dict& /*message*/); + void HandleResetPrintPreviewModeMessage(const base::Value::Dict& message); + void HandleRotateClockwiseMessage(const base::Value::Dict& /*message*/); + void HandleRotateCounterclockwiseMessage( + const base::Value::Dict& /*message*/); + void HandleSaveMessage(const base::Value::Dict& message); + void HandleSaveAttachmentMessage(const base::Value::Dict& message); + void HandleSelectAllMessage(const base::Value::Dict& /*message*/); + void HandleSetBackgroundColorMessage(const base::Value::Dict& message); + void HandleSetReadOnlyMessage(const base::Value::Dict& message); + void HandleSetTwoUpViewMessage(const base::Value::Dict& message); + void HandleStopScrollingMessage(const base::Value::Dict& /*message*/); + void HandleViewportMessage(const base::Value::Dict& message); // Sends start/stop loading notifications to the plugin's render frame // depending on `did_call_start_loading_`. @@ -480,44 +455,14 @@ class PdfViewPluginBase : public PDFEngine::Client, void PrepareForFirstPaint(std::vector<PaintReadyRect>& ready); // Callback to clear deferred invalidates after painting finishes. - void ClearDeferredInvalidates(int32_t /*unused_but_required*/); - - // Sends the attachments data. - void SendAttachments(); - - // Sends the bookmarks data. - void SendBookmarks(); - - // Send document metadata data. - void SendMetadata(); + void ClearDeferredInvalidates(); // Sends the thumbnail image data. - void SendThumbnail(base::Value reply, Thumbnail thumbnail); + void SendThumbnail(base::Value::Dict reply, Thumbnail thumbnail); // Starts loading accessibility information. void LoadAccessibility(); - void ResetRecentlySentFindUpdate(int32_t /*unused_but_required*/); - - // Records metrics about the attachment types. - void RecordAttachmentTypes(); - - // Records metrics about the document metadata. - void RecordDocumentMetrics(); - - // Adds a sample to an enumerated histogram and filters out print preview - // usage. - template <typename T> - void HistogramEnumeration(const char* name, T sample); - - // Adds a sample to a custom counts histogram and filters out print preview - // usage. - void HistogramCustomCounts(const char* name, - int32_t sample, - int32_t min, - int32_t max, - uint32_t bucket_count); - // Handles `LoadUrl()` result. void DidOpen(std::unique_ptr<UrlLoader> loader, int32_t result); @@ -616,10 +561,10 @@ class PdfViewPluginBase : public PDFEngine::Client, // transformations are applied. gfx::Vector2dF scroll_offset_at_last_raster_; - // If this is true, then don't scroll the plugin in response to the messages - // from DidChangeView() or HandleUpdateScrollMessage(). This will be true when - // the extension page is in the process of zooming the plugin so that - // flickering doesn't occur while zooming. + // If this is true, then don't scroll the plugin in response to calls to + // `UpdateScroll()`. This will be true when the extension page is in the + // process of zooming the plugin so that flickering doesn't occur while + // zooming. bool stop_scrolling_ = false; // Whether the plugin has received a viewport changed message. Nothing should @@ -647,13 +592,6 @@ class PdfViewPluginBase : public PDFEngine::Client, // reconstructing the tree for new document layouts. int32_t next_accessibility_page_index_ = 0; - // Whether an update to the number of find results found was sent less than - // `kFindResultCooldownMs` milliseconds ago. - bool recently_sent_find_update_ = false; - - // Stores the tickmarks to be shown for the current find results. - std::vector<gfx::Rect> tickmarks_; - // Keeps track of which unsupported features have been reported to avoid // spamming the metrics if a feature shows up many times per document. base::flat_set<std::string> unsupported_features_reported_; diff --git a/chromium/pdf/pdf_view_plugin_base_unittest.cc b/chromium/pdf/pdf_view_plugin_base_unittest.cc index be3fcd0c806..2cee225b1e6 100644 --- a/chromium/pdf/pdf_view_plugin_base_unittest.cc +++ b/chromium/pdf/pdf_view_plugin_base_unittest.cc @@ -9,7 +9,6 @@ #include <utility> #include <vector> -#include "base/cxx17_backports.h" #include "base/memory/weak_ptr.h" #include "base/strings/string_piece.h" #include "base/test/icu_test_util.h" @@ -24,7 +23,6 @@ #include "pdf/document_metadata.h" #include "pdf/pdf_engine.h" #include "pdf/pdfium/pdfium_form_filler.h" -#include "pdf/ppapi_migration/callback.h" #include "pdf/ppapi_migration/graphics.h" #include "pdf/ppapi_migration/url_loader.h" #include "pdf/test/test_pdfium_engine.h" @@ -43,9 +41,14 @@ namespace chrome_pdf { namespace { +using blink::WebPrintParams; using ::testing::ByMove; using ::testing::ElementsAre; +using ::testing::Field; +using ::testing::InSequence; using ::testing::IsEmpty; +using ::testing::IsFalse; +using ::testing::IsTrue; using ::testing::NiceMock; using ::testing::Return; using ::testing::SaveArg; @@ -55,104 +58,22 @@ using ::testing::StrEq; // net::GetSuggestedFilename(). constexpr char kDefaultDownloadFileName[] = "download"; -class TestPDFiumEngineWithDocInfo : public TestPDFiumEngine { - public: - explicit TestPDFiumEngineWithDocInfo(PDFEngine::Client* client) - : TestPDFiumEngine(client) {} - - base::Value GetBookmarks() override { - // Create `bookmark1` which navigates to an in-doc position. This bookmark - // will be in the top-level bookmark list. - base::Value bookmark1(base::Value::Type::DICTIONARY); - bookmark1.SetStringKey("title", "Bookmark 1"); - bookmark1.SetIntKey("page", 2); - bookmark1.SetIntKey("x", 10); - bookmark1.SetIntKey("y", 20); - bookmark1.SetDoubleKey("zoom", 2.0); - - // Create `bookmark2` which navigates to a web page. This bookmark will be a - // child of `bookmark1`. - base::Value bookmark2(base::Value::Type::DICTIONARY); - bookmark2.SetStringKey("title", "Bookmark 2"); - bookmark2.SetStringKey("uri", "test.com"); - - base::Value children_of_bookmark1(base::Value::Type::LIST); - children_of_bookmark1.Append(std::move(bookmark2)); - bookmark1.SetKey("children", std::move(children_of_bookmark1)); - - // Create the top-level bookmark list. - base::Value bookmarks(base::Value::Type::LIST); - bookmarks.Append(std::move(bookmark1)); - return bookmarks; - } - - absl::optional<gfx::Size> GetUniformPageSizePoints() override { - return gfx::Size(1000, 1200); - } - - // Initialize attachments, metadata for testing. - void InitializeDocument() { - InitializeDocumentAttachments(); - InitializeDocumentMetadata(); - } - - private: - void InitializeDocumentAttachments() { - doc_attachment_info_list().resize(3); - - // A regular attachment. - doc_attachment_info_list()[0].name = u"attachment1.txt"; - doc_attachment_info_list()[0].creation_date = u"D:20170712214438-07'00'"; - doc_attachment_info_list()[0].modified_date = u"D:20160115091400"; - doc_attachment_info_list()[0].is_readable = true; - doc_attachment_info_list()[0].size_bytes = 13u; - - // An unreadable attachment. - doc_attachment_info_list()[1].name = u"attachment2.pdf"; - doc_attachment_info_list()[1].is_readable = false; - - // A readable attachment that exceeds download size limit. - doc_attachment_info_list()[2].name = u"attachment3.mov"; - doc_attachment_info_list()[2].is_readable = true; - doc_attachment_info_list()[2].size_bytes = - PdfViewPluginBase::kMaximumSavedFileSize + 1; - } - - void InitializeDocumentMetadata() { - metadata().version = PdfVersion::k1_7; - metadata().size_bytes = 13u; - metadata().page_count = 13u; - metadata().linearized = true; - metadata().has_attachments = true; - metadata().tagged = true; - metadata().form_type = FormType::kAcroForm; - metadata().title = "Title"; - metadata().author = "Author"; - metadata().subject = "Subject"; - metadata().keywords = "Keywords"; - metadata().creator = "Creator"; - metadata().producer = "Producer"; - ASSERT_TRUE(base::Time::FromUTCString("2021-05-04 11:12:13", - &metadata().creation_date)); - ASSERT_TRUE( - base::Time::FromUTCString("2021-06-04 15:16:17", &metadata().mod_date)); - } -}; - class MockUrlLoader : public UrlLoader { public: MOCK_METHOD(void, GrantUniversalAccess, (), (override)); - MOCK_METHOD(void, Open, (const UrlRequest&, ResultCallback), (override)); + MOCK_METHOD(void, + Open, + (const UrlRequest&, base::OnceCallback<void(int)>), + (override)); MOCK_METHOD(void, ReadResponseBody, - (base::span<char>, ResultCallback), + (base::span<char>, base::OnceCallback<void(int)>), (override)); MOCK_METHOD(void, Close, (), (override)); }; -// This test approach relies on PdfViewPluginBase continuing to exist. -// PdfViewPluginBase and PdfViewWebPlugin are going to merge once -// OutOfProcessInstance is deprecated. +// TODO(crbug.com/1302059): Overhaul this when PdfViewPluginBase merges with +// PdfViewWebPlugin. class FakePdfViewPluginBase : public PdfViewPluginBase { public: FakePdfViewPluginBase() { @@ -168,6 +89,9 @@ class FakePdfViewPluginBase : public PdfViewPluginBase { using PdfViewPluginBase::HandleInputEvent; using PdfViewPluginBase::HandleMessage; using PdfViewPluginBase::LoadUrl; + using PdfViewPluginBase::PrintBegin; + using PdfViewPluginBase::PrintEnd; + using PdfViewPluginBase::PrintPages; using PdfViewPluginBase::SetCaretPosition; using PdfViewPluginBase::SetZoom; using PdfViewPluginBase::UpdateGeometryOnPluginRectChanged; @@ -202,11 +126,6 @@ class FakePdfViewPluginBase : public PdfViewPluginBase { MOCK_METHOD(bool, BindPaintGraphics, (Graphics&), (override)); - MOCK_METHOD(void, - ScheduleTaskOnMainThread, - (const base::Location&, ResultCallback, int32_t, base::TimeDelta), - (override)); - MOCK_METHOD(std::unique_ptr<PDFiumEngine>, CreateEngine, (PDFEngine::Client*, PDFiumFormFiller::ScriptOption), @@ -221,8 +140,10 @@ class FakePdfViewPluginBase : public PdfViewPluginBase { (), (override)); - void SendMessage(base::Value message) override { - sent_messages_.push_back(std::move(message)); + MOCK_METHOD(void, OnDocumentLoadComplete, (), (override)); + + void SendMessage(base::Value::Dict message) override { + sent_messages_.push_back(base::Value(std::move(message))); } MOCK_METHOD(void, SaveAs, (), (override)); @@ -249,13 +170,6 @@ class FakePdfViewPluginBase : public PdfViewPluginBase { (AccessibilityViewportInfo), (override)); - MOCK_METHOD(void, NotifyFindResultsChanged, (int, bool), (override)); - - MOCK_METHOD(void, - NotifyFindTickmarks, - (const std::vector<gfx::Rect>&), - (override)); - MOCK_METHOD(void, SetContentRestrictions, (int), (override)); MOCK_METHOD(void, SetPluginCanSave, (bool), (override)); @@ -288,111 +202,39 @@ class FakePdfViewPluginBase : public PdfViewPluginBase { }; base::Value CreateExpectedFormTextFieldFocusChangeResponse() { - base::Value message(base::Value::Type::DICTIONARY); - message.SetStringKey("type", "formFocusChange"); - message.SetBoolKey("focused", false); - return message; -} - -base::Value CreateExpectedAttachmentsResponse() { - base::Value attachments(base::Value::Type::LIST); - { - base::Value attachment(base::Value::Type::DICTIONARY); - attachment.SetStringKey("name", "attachment1.txt"); - attachment.SetIntKey("size", 13); - attachment.SetBoolKey("readable", true); - attachments.Append(std::move(attachment)); - } - { - base::Value attachment(base::Value::Type::DICTIONARY); - attachment.SetStringKey("name", "attachment2.pdf"); - attachment.SetIntKey("size", 0); - attachment.SetBoolKey("readable", false); - attachments.Append(std::move(attachment)); - } - { - base::Value attachment(base::Value::Type::DICTIONARY); - attachment.SetStringKey("name", "attachment3.mov"); - attachment.SetIntKey("size", -1); - attachment.SetBoolKey("readable", true); - attachments.Append(std::move(attachment)); - } - - base::Value message(base::Value::Type::DICTIONARY); - message.SetStringKey("type", "attachments"); - message.SetKey("attachmentsData", std::move(attachments)); - return message; -} - -base::Value CreateExpectedBookmarksResponse(base::Value bookmarks) { - base::Value message(base::Value::Type::DICTIONARY); - message.SetStringKey("type", "bookmarks"); - message.SetKey("bookmarksData", std::move(bookmarks)); - return message; -} - -base::Value CreateExpectedMetadataResponse() { - base::Value metadata(base::Value::Type::DICTIONARY); - metadata.SetStringKey("version", "1.7"); - metadata.SetStringKey("fileSize", "13 B"); - metadata.SetBoolKey("linearized", true); - - metadata.SetStringKey("title", "Title"); - metadata.SetStringKey("author", "Author"); - metadata.SetStringKey("subject", "Subject"); - metadata.SetStringKey("keywords", "Keywords"); - metadata.SetStringKey("creator", "Creator"); - metadata.SetStringKey("producer", "Producer"); - metadata.SetStringKey("creationDate", "5/4/21, 4:12:13 AM"); - metadata.SetStringKey("modDate", "6/4/21, 8:16:17 AM"); - metadata.SetStringKey("pageSize", "13.89 × 16.67 in (portrait)"); - metadata.SetBoolKey("canSerializeDocument", true); - - base::Value message(base::Value::Type::DICTIONARY); - message.SetStringKey("type", "metadata"); - message.SetKey("metadataData", std::move(metadata)); - return message; + base::Value::Dict message; + message.Set("type", "formFocusChange"); + message.Set("focused", false); + return base::Value(std::move(message)); } -base::Value CreateExpectedNoMetadataResponse() { - base::Value metadata(base::Value::Type::DICTIONARY); - metadata.SetStringKey("fileSize", "0 B"); - metadata.SetBoolKey("linearized", false); - metadata.SetStringKey("pageSize", "Varies"); - metadata.SetBoolKey("canSerializeDocument", true); - - base::Value message(base::Value::Type::DICTIONARY); - message.SetStringKey("type", "metadata"); - message.SetKey("metadataData", std::move(metadata)); - return message; -} - -base::Value CreateSaveRequestMessage(PdfViewPluginBase::SaveRequestType type, - const std::string& token) { - base::Value message(base::Value::Type::DICTIONARY); - message.SetStringKey("type", "save"); - message.SetIntKey("saveRequestType", static_cast<int>(type)); - message.SetStringKey("token", token); +base::Value::Dict CreateSaveRequestMessage( + PdfViewPluginBase::SaveRequestType type, + const std::string& token) { + base::Value::Dict message; + message.Set("type", "save"); + message.Set("saveRequestType", static_cast<int>(type)); + message.Set("token", token); return message; } base::Value CreateExpectedSaveToBufferResponse(const std::string& token, bool edit_mode) { - base::Value expected_response(base::Value::Type::DICTIONARY); - expected_response.SetStringKey("type", "saveData"); - expected_response.SetStringKey("token", token); - expected_response.SetStringKey("fileName", kDefaultDownloadFileName); - expected_response.SetBoolKey("editModeForTesting", edit_mode); - expected_response.SetKey( + base::Value::Dict expected_response; + expected_response.Set("type", "saveData"); + expected_response.Set("token", token); + expected_response.Set("fileName", kDefaultDownloadFileName); + expected_response.Set("editModeForTesting", edit_mode); + expected_response.Set( "dataToSave", base::Value(base::make_span(TestPDFiumEngine::kSaveData))); - return expected_response; + return base::Value(std::move(expected_response)); } base::Value CreateExpectedSaveToFileResponse(const std::string& token) { - base::Value expected_response(base::Value::Type::DICTIONARY); - expected_response.SetStringKey("type", "consumeSaveToken"); - expected_response.SetStringKey("token", token); - return expected_response; + base::Value::Dict expected_response; + expected_response.Set("type", "consumeSaveToken"); + expected_response.Set("token", token); + return base::Value(std::move(expected_response)); } } // namespace @@ -411,7 +253,7 @@ class PdfViewPluginBaseWithEngineTest : public PdfViewPluginBaseTest { protected: void SendDefaultViewportMessage() { - fake_plugin_.HandleMessage(base::test::ParseJson(R"({ + base::Value message = base::test::ParseJson(R"({ "type": "viewport", "userInitiated": false, "zoom": 1, @@ -423,7 +265,8 @@ class PdfViewPluginBaseWithEngineTest : public PdfViewPluginBaseTest { "xOffset": 0, "yOffset": 0, "pinchPhase": 0, - })")); + })"); + fake_plugin_.HandleMessage(message.GetDict()); } }; @@ -434,20 +277,6 @@ class PdfViewPluginBaseWithScopedLocaleTest base::test::ScopedRestoreDefaultTimezone la_time_{"America/Los_Angeles"}; }; -class PdfViewPluginBaseWithDocInfoTest - : public PdfViewPluginBaseWithScopedLocaleTest { - public: - void SetUp() override { - std::unique_ptr<TestPDFiumEngineWithDocInfo> engine = - std::make_unique<TestPDFiumEngineWithDocInfo>(&fake_plugin_); - fake_plugin_.InitializeEngineForTesting(std::move(engine)); - - // Initialize some arbitrary document information for the engine. - static_cast<TestPDFiumEngineWithDocInfo*>(fake_plugin_.engine()) - ->InitializeDocument(); - } -}; - using PdfViewPluginBaseWithoutDocInfoTest = PdfViewPluginBaseWithScopedLocaleTest; @@ -555,7 +384,7 @@ TEST_F(PdfViewPluginBaseTest, CreateUrlLoaderWithoutFullFrame) { EXPECT_FALSE(fake_plugin_.GetDidCallStartLoadingForTesting()); } -TEST_F(PdfViewPluginBaseWithDocInfoTest, +TEST_F(PdfViewPluginBaseWithoutDocInfoTest, DocumentLoadCompleteInFullFramePdfViewerWithAccessibilityEnabled) { // Notify the render frame about document loading. fake_plugin_.set_full_frame_for_testing(true); @@ -587,18 +416,12 @@ TEST_F(PdfViewPluginBaseWithDocInfoTest, fake_plugin_.accessibility_state()); // Check all the sent messages. - ASSERT_EQ(4u, fake_plugin_.sent_messages().size()); + ASSERT_EQ(1u, fake_plugin_.sent_messages().size()); EXPECT_EQ(CreateExpectedFormTextFieldFocusChangeResponse(), fake_plugin_.sent_messages()[0]); - EXPECT_EQ(CreateExpectedAttachmentsResponse(), - fake_plugin_.sent_messages()[1]); - EXPECT_EQ( - CreateExpectedBookmarksResponse(fake_plugin_.engine()->GetBookmarks()), - fake_plugin_.sent_messages()[2]); - EXPECT_EQ(CreateExpectedMetadataResponse(), fake_plugin_.sent_messages()[3]); } -TEST_F(PdfViewPluginBaseWithDocInfoTest, +TEST_F(PdfViewPluginBaseWithoutDocInfoTest, DocumentLoadCompleteInFullFramePdfViewerWithAccessibilityDisabled) { // Notify the render frame about document loading. fake_plugin_.set_full_frame_for_testing(true); @@ -627,18 +450,12 @@ TEST_F(PdfViewPluginBaseWithDocInfoTest, fake_plugin_.accessibility_state()); // Check all the sent messages. - ASSERT_EQ(4u, fake_plugin_.sent_messages().size()); + ASSERT_EQ(1u, fake_plugin_.sent_messages().size()); EXPECT_EQ(CreateExpectedFormTextFieldFocusChangeResponse(), fake_plugin_.sent_messages()[0]); - EXPECT_EQ(CreateExpectedAttachmentsResponse(), - fake_plugin_.sent_messages()[1]); - EXPECT_EQ( - CreateExpectedBookmarksResponse(fake_plugin_.engine()->GetBookmarks()), - fake_plugin_.sent_messages()[2]); - EXPECT_EQ(CreateExpectedMetadataResponse(), fake_plugin_.sent_messages()[3]); } -TEST_F(PdfViewPluginBaseWithDocInfoTest, +TEST_F(PdfViewPluginBaseWithoutDocInfoTest, DocumentLoadCompleteInNonFullFramePdfViewer) { ASSERT_FALSE(fake_plugin_.full_frame()); fake_plugin_.CreateUrlLoader(); @@ -659,37 +476,9 @@ TEST_F(PdfViewPluginBaseWithDocInfoTest, fake_plugin_.document_load_state_for_testing()); // Check all the sent messages. - ASSERT_EQ(4u, fake_plugin_.sent_messages().size()); - EXPECT_EQ(CreateExpectedFormTextFieldFocusChangeResponse(), - fake_plugin_.sent_messages()[0]); - EXPECT_EQ(CreateExpectedAttachmentsResponse(), - fake_plugin_.sent_messages()[1]); - EXPECT_EQ( - CreateExpectedBookmarksResponse(fake_plugin_.engine()->GetBookmarks()), - fake_plugin_.sent_messages()[2]); - EXPECT_EQ(CreateExpectedMetadataResponse(), fake_plugin_.sent_messages()[3]); -} - -TEST_F(PdfViewPluginBaseWithoutDocInfoTest, DocumentLoadCompletePostMessages) { - fake_plugin_.CreateUrlLoader(); - - ASSERT_FALSE(fake_plugin_.IsPrintPreview()); - ASSERT_EQ(PdfViewPluginBase::DocumentLoadState::kLoading, - fake_plugin_.document_load_state_for_testing()); - EXPECT_CALL(fake_plugin_, UserMetricsRecordAction("PDF.LoadSuccess")); - EXPECT_CALL(fake_plugin_, SetFormTextFieldInFocus(false)); - - fake_plugin_.DocumentLoadComplete(); - EXPECT_EQ(PdfViewPluginBase::DocumentLoadState::kComplete, - fake_plugin_.document_load_state_for_testing()); - - // Check the sent messages when the document doesn't have any metadata, - // attachments or bookmarks. - ASSERT_EQ(2u, fake_plugin_.sent_messages().size()); + ASSERT_EQ(1u, fake_plugin_.sent_messages().size()); EXPECT_EQ(CreateExpectedFormTextFieldFocusChangeResponse(), fake_plugin_.sent_messages()[0]); - EXPECT_EQ(CreateExpectedNoMetadataResponse(), - fake_plugin_.sent_messages()[1]); } TEST_F(PdfViewPluginBaseTest, DocumentLoadFailedWithNotifiedRenderFrame) { @@ -810,12 +599,13 @@ TEST_F(PdfViewPluginBaseTest, EnteredEditMode) { EXPECT_CALL(fake_plugin_, SetPluginCanSave(true)); fake_plugin_.EnteredEditMode(); - base::Value expected_response(base::Value::Type::DICTIONARY); - expected_response.SetStringKey("type", "setIsEditing"); + base::Value::Dict expected_response; + expected_response.Set("type", "setIsEditing"); EXPECT_TRUE(fake_plugin_.edit_mode_for_testing()); ASSERT_EQ(1u, fake_plugin_.sent_messages().size()); - EXPECT_EQ(expected_response, fake_plugin_.sent_messages()[0]); + EXPECT_EQ(base::Value(std::move(expected_response)), + fake_plugin_.sent_messages()[0]); } using PdfViewPluginBaseSaveTest = PdfViewPluginBaseWithEngineTest; @@ -826,7 +616,7 @@ TEST_F(PdfViewPluginBaseSaveTest, SaveAnnotationInNonEditMode) { static constexpr char kSaveAnnotInNonEditModeToken[] = "save-annot-in-non-edit-mode-token"; - base::Value message = + base::Value::Dict message = CreateSaveRequestMessage(PdfViewPluginBase::SaveRequestType::kAnnotation, kSaveAnnotInNonEditModeToken); base::Value expected_response = @@ -846,7 +636,7 @@ TEST_F(PdfViewPluginBaseSaveTest, SaveAnnotationInEditMode) { static constexpr char kSaveAnnotInEditModeToken[] = "save-annot-in-edit-mode-token"; - base::Value message = + base::Value::Dict message = CreateSaveRequestMessage(PdfViewPluginBase::SaveRequestType::kAnnotation, kSaveAnnotInEditModeToken); base::Value expected_response = @@ -866,7 +656,7 @@ TEST_F(PdfViewPluginBaseSaveTest, SaveOriginalInNonEditMode) { static constexpr char kSaveOriginalInNonEditModeToken[] = "save-original-in-non-edit-mode-token"; - base::Value message = + base::Value::Dict message = CreateSaveRequestMessage(PdfViewPluginBase::SaveRequestType::kOriginal, kSaveOriginalInNonEditModeToken); base::Value expected_response = @@ -887,7 +677,7 @@ TEST_F(PdfViewPluginBaseSaveTest, SaveOriginalInEditMode) { static constexpr char kSaveOriginalInEditModeToken[] = "save-original-in-edit-mode-token"; - base::Value message = + base::Value::Dict message = CreateSaveRequestMessage(PdfViewPluginBase::SaveRequestType::kOriginal, kSaveOriginalInEditModeToken); base::Value expected_response = @@ -909,7 +699,7 @@ TEST_F(PdfViewPluginBaseSaveTest, SaveEditedInNonEditMode) { static constexpr char kSaveEditedInNonEditModeToken[] = "save-edited-in-non-edit-mode"; - base::Value message = + base::Value::Dict message = CreateSaveRequestMessage(PdfViewPluginBase::SaveRequestType::kEdited, kSaveEditedInNonEditModeToken); base::Value expected_response = @@ -929,7 +719,7 @@ TEST_F(PdfViewPluginBaseSaveTest, SaveEditedInEditMode) { static constexpr char kSaveEditedInEditModeToken[] = "save-edited-in-edit-mode-token"; - base::Value message = CreateSaveRequestMessage( + base::Value::Dict message = CreateSaveRequestMessage( PdfViewPluginBase::SaveRequestType::kEdited, kSaveEditedInEditModeToken); base::Value expected_response = CreateExpectedSaveToBufferResponse(kSaveEditedInEditModeToken, @@ -945,9 +735,9 @@ TEST_F(PdfViewPluginBaseTest, HandleSetBackgroundColorMessage) { const SkColor kNewBackgroundColor = SK_ColorGREEN; ASSERT_NE(kNewBackgroundColor, fake_plugin_.GetBackgroundColor()); - base::Value message(base::Value::Type::DICTIONARY); - message.SetStringKey("type", "setBackgroundColor"); - message.SetDoubleKey("color", kNewBackgroundColor); + base::Value::Dict message; + message.Set("type", "setBackgroundColor"); + message.Set("color", static_cast<double>(kNewBackgroundColor)); fake_plugin_.HandleMessage(message); EXPECT_EQ(kNewBackgroundColor, fake_plugin_.GetBackgroundColor()); @@ -958,7 +748,7 @@ TEST_F(PdfViewPluginBaseWithEngineTest, auto* engine = static_cast<TestPDFiumEngine*>(fake_plugin_.engine()); EXPECT_CALL(*engine, ApplyDocumentLayout(DocumentLayout::Options())); - fake_plugin_.HandleMessage(base::test::ParseJson(R"({ + base::Value message = base::test::ParseJson(R"({ "type": "viewport", "userInitiated": false, "zoom": 1, @@ -970,7 +760,8 @@ TEST_F(PdfViewPluginBaseWithEngineTest, "xOffset": 0, "yOffset": 0, "pinchPhase": 0, - })")); + })"); + fake_plugin_.HandleMessage(message.GetDict()); EXPECT_THAT(fake_plugin_.sent_messages(), IsEmpty()); } @@ -983,7 +774,7 @@ TEST_F(PdfViewPluginBaseWithEngineTest, fake_plugin_.DocumentLoadComplete(); fake_plugin_.clear_sent_messages(); - fake_plugin_.HandleMessage(base::test::ParseJson(R"({ + base::Value message = base::test::ParseJson(R"({ "type": "viewport", "userInitiated": false, "zoom": 1, @@ -995,7 +786,8 @@ TEST_F(PdfViewPluginBaseWithEngineTest, "xOffset": 0, "yOffset": 0, "pinchPhase": 0, - })")); + })"); + fake_plugin_.HandleMessage(message.GetDict()); EXPECT_THAT(fake_plugin_.sent_messages(), ElementsAre(base::test::IsJson(R"({ "type": "loadProgress", @@ -1006,7 +798,7 @@ TEST_F(PdfViewPluginBaseWithEngineTest, TEST_F(PdfViewPluginBaseWithEngineTest, HandleViewportMessageSubsequently) { auto* engine = static_cast<TestPDFiumEngine*>(fake_plugin_.engine()); - fake_plugin_.HandleMessage(base::test::ParseJson(R"({ + base::Value message1 = base::test::ParseJson(R"({ "type": "viewport", "userInitiated": false, "zoom": 1, @@ -1018,14 +810,15 @@ TEST_F(PdfViewPluginBaseWithEngineTest, HandleViewportMessageSubsequently) { "xOffset": 0, "yOffset": 0, "pinchPhase": 0, - })")); + })"); + fake_plugin_.HandleMessage(message1.GetDict()); fake_plugin_.clear_sent_messages(); DocumentLayout::Options two_up_options; two_up_options.set_page_spread(DocumentLayout::PageSpread::kTwoUpOdd); EXPECT_CALL(*engine, ApplyDocumentLayout(two_up_options)); - fake_plugin_.HandleMessage(base::test::ParseJson(R"({ + base::Value message2 = base::test::ParseJson(R"({ "type": "viewport", "userInitiated": false, "zoom": 1, @@ -1037,7 +830,8 @@ TEST_F(PdfViewPluginBaseWithEngineTest, HandleViewportMessageSubsequently) { "xOffset": 0, "yOffset": 0, "pinchPhase": 0, - })")); + })"); + fake_plugin_.HandleMessage(message2.GetDict()); EXPECT_THAT(fake_plugin_.sent_messages(), IsEmpty()); } @@ -1049,7 +843,7 @@ TEST_F(PdfViewPluginBaseWithEngineTest, HandleViewportMessageScroll) { EXPECT_CALL(*engine, ScrolledToXPosition(2)); EXPECT_CALL(*engine, ScrolledToYPosition(3)); - fake_plugin_.HandleMessage(base::test::ParseJson(R"({ + base::Value message = base::test::ParseJson(R"({ "type": "viewport", "userInitiated": false, "zoom": 1, @@ -1061,7 +855,8 @@ TEST_F(PdfViewPluginBaseWithEngineTest, HandleViewportMessageScroll) { "xOffset": 2, "yOffset": 3, "pinchPhase": 0, - })")); + })"); + fake_plugin_.HandleMessage(message.GetDict()); } TEST_F(PdfViewPluginBaseWithEngineTest, @@ -1072,7 +867,7 @@ TEST_F(PdfViewPluginBaseWithEngineTest, EXPECT_CALL(*engine, ScrolledToXPosition(2)); EXPECT_CALL(*engine, ScrolledToYPosition(3)); - fake_plugin_.HandleMessage(base::test::ParseJson(R"({ + base::Value message = base::test::ParseJson(R"({ "type": "viewport", "userInitiated": false, "zoom": 1, @@ -1084,7 +879,8 @@ TEST_F(PdfViewPluginBaseWithEngineTest, "xOffset": 2, "yOffset": 3, "pinchPhase": 0, - })")); + })"); + fake_plugin_.HandleMessage(message.GetDict()); } TEST_F(PdfViewPluginBaseWithEngineTest, @@ -1096,7 +892,7 @@ TEST_F(PdfViewPluginBaseWithEngineTest, EXPECT_CALL(*engine, ScrolledToYPosition(3)); EXPECT_CALL(fake_plugin_, IsPrintPreview).WillRepeatedly(Return(true)); - fake_plugin_.HandleMessage(base::test::ParseJson(R"({ + base::Value message = base::test::ParseJson(R"({ "type": "viewport", "userInitiated": false, "zoom": 1, @@ -1108,7 +904,8 @@ TEST_F(PdfViewPluginBaseWithEngineTest, "xOffset": -2, "yOffset": 3, "pinchPhase": 0, - })")); + })"); + fake_plugin_.HandleMessage(message.GetDict()); } TEST_F(PdfViewPluginBaseWithEngineTest, UpdateScroll) { @@ -1124,9 +921,10 @@ TEST_F(PdfViewPluginBaseWithEngineTest, UpdateScrollStopped) { EXPECT_CALL(*engine, ScrolledToXPosition).Times(0); EXPECT_CALL(*engine, ScrolledToYPosition).Times(0); - fake_plugin_.HandleMessage(base::test::ParseJson(R"({ + base::Value message = base::test::ParseJson(R"({ "type": "stopScrolling", - })")); + })"); + fake_plugin_.HandleMessage(message.GetDict()); fake_plugin_.UpdateScroll({0, 0}); } @@ -1298,12 +1096,13 @@ TEST_F(PdfViewPluginBaseTest, HandleResetPrintPreviewModeMessage) { PDFiumFormFiller::ScriptOption::kNoJavaScript)) .WillOnce(Return(ByMove(std::move(engine)))); - fake_plugin_.HandleMessage(base::test::ParseJson(R"({ + base::Value message = base::test::ParseJson(R"({ "type": "resetPrintPreviewMode", "url": "chrome-untrusted://print/0/0/print.pdf", "grayscale": false, "pageCount": 1, - })")); + })"); + fake_plugin_.HandleMessage(message.GetDict()); } TEST_F(PdfViewPluginBaseTest, HandleResetPrintPreviewModeMessageSetGrayscale) { @@ -1316,12 +1115,80 @@ TEST_F(PdfViewPluginBaseTest, HandleResetPrintPreviewModeMessageSetGrayscale) { PDFiumFormFiller::ScriptOption::kNoJavaScript)) .WillOnce(Return(ByMove(std::move(engine)))); - fake_plugin_.HandleMessage(base::test::ParseJson(R"({ + base::Value message = base::test::ParseJson(R"({ "type": "resetPrintPreviewMode", "url": "chrome-untrusted://print/0/0/print.pdf", "grayscale": true, "pageCount": 1, - })")); + })"); + fake_plugin_.HandleMessage(message.GetDict()); +} + +TEST_F(PdfViewPluginBaseWithEngineTest, NormalPrinting) { + WebPrintParams params; + const std::vector<int> kPageNumbers = {0}; + + auto* engine = static_cast<TestPDFiumEngine*>(fake_plugin_.engine()); + engine->SetPermissions({DocumentPermission::kPrintHighQuality, + DocumentPermission::kPrintLowQuality}); + + InSequence sequence; + EXPECT_CALL(*engine, + PrintPages(kPageNumbers, + Field(&WebPrintParams::rasterize_pdf, IsFalse()))) + .Times(1); + EXPECT_CALL( + *engine, + PrintPages(kPageNumbers, Field(&WebPrintParams::rasterize_pdf, IsTrue()))) + .Times(1); + + ASSERT_EQ(static_cast<int>(TestPDFiumEngine::kPageNumber), + fake_plugin_.PrintBegin(params)); + fake_plugin_.PrintPages(kPageNumbers); + fake_plugin_.PrintEnd(); + + params.rasterize_pdf = true; + ASSERT_EQ(static_cast<int>(TestPDFiumEngine::kPageNumber), + fake_plugin_.PrintBegin(params)); + fake_plugin_.PrintPages(kPageNumbers); + fake_plugin_.PrintEnd(); +} + +// Regression test for crbug.com/1307219. +TEST_F(PdfViewPluginBaseWithEngineTest, LowQualityPrinting) { + WebPrintParams params; + const std::vector<int> kPageNumbers = {0}; + + auto* engine = static_cast<TestPDFiumEngine*>(fake_plugin_.engine()); + engine->SetPermissions({DocumentPermission::kPrintLowQuality}); + + EXPECT_CALL( + *engine, + PrintPages(kPageNumbers, Field(&WebPrintParams::rasterize_pdf, IsTrue()))) + .Times(2); + + ASSERT_EQ(static_cast<int>(TestPDFiumEngine::kPageNumber), + fake_plugin_.PrintBegin(params)); + fake_plugin_.PrintPages(kPageNumbers); + fake_plugin_.PrintEnd(); + + params.rasterize_pdf = true; + ASSERT_EQ(static_cast<int>(TestPDFiumEngine::kPageNumber), + fake_plugin_.PrintBegin(params)); + fake_plugin_.PrintPages(kPageNumbers); + fake_plugin_.PrintEnd(); +} + +TEST_F(PdfViewPluginBaseWithEngineTest, NoPrinting) { + WebPrintParams params; + + auto* engine = static_cast<TestPDFiumEngine*>(fake_plugin_.engine()); + engine->SetPermissions({}); + + EXPECT_EQ(0, fake_plugin_.PrintBegin(params)); + + params.rasterize_pdf = true; + EXPECT_EQ(0, fake_plugin_.PrintBegin(params)); } TEST_F(PdfViewPluginBaseWithEngineTest, GetContentRestrictions) { @@ -1428,7 +1295,7 @@ class PdfViewPluginBaseSubmitFormTest : public PdfViewPluginBaseTest { void SubmitFailingForm(const std::string& url) { EXPECT_CALL(fake_plugin_, CreateUrlLoaderInternal).Times(0); constexpr char kFormData[] = "form data"; - fake_plugin_.SubmitForm(url, kFormData, base::size(kFormData)); + fake_plugin_.SubmitForm(url, kFormData, std::size(kFormData)); } protected: diff --git a/chromium/pdf/pdf_view_web_plugin.cc b/chromium/pdf/pdf_view_web_plugin.cc index 34af3f2e846..e29bee6cc82 100644 --- a/chromium/pdf/pdf_view_web_plugin.cc +++ b/chromium/pdf/pdf_view_web_plugin.cc @@ -16,6 +16,7 @@ #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/memory/raw_ptr.h" #include "base/no_destructor.h" #include "base/notreached.h" @@ -23,6 +24,7 @@ #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" @@ -31,6 +33,7 @@ #include "cc/paint/paint_image_builder.h" #include "net/cookies/site_for_cookies.h" #include "pdf/accessibility_structs.h" +#include "pdf/metrics_handler.h" #include "pdf/mojom/pdf.mojom.h" #include "pdf/parsed_params.h" #include "pdf/pdf_accessibility_data_handler.h" @@ -38,10 +41,12 @@ #include "pdf/pdf_init.h" #include "pdf/pdfium/pdfium_engine.h" #include "pdf/post_message_receiver.h" +#include "pdf/post_message_sender.h" #include "pdf/ppapi_migration/bitmap.h" #include "pdf/ppapi_migration/graphics.h" #include "pdf/ppapi_migration/result_codes.h" #include "pdf/ppapi_migration/url_loader.h" +#include "pdf/ui/document_properties.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" @@ -78,6 +83,7 @@ #include "third_party/skia/include/core/SkRefCnt.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/display/screen_info.h" #include "ui/events/base_event_utils.h" #include "ui/events/blink/blink_event_util.h" @@ -96,6 +102,8 @@ namespace chrome_pdf { namespace { +constexpr base::TimeDelta kFindResultCooldown = base::Milliseconds(100); + // Initialization performed per renderer process. Initialization may be // triggered from multiple plugin instances, but should only execute once. // @@ -144,9 +152,12 @@ class PerProcessInitializer final { class BlinkContainerWrapper final : public PdfViewWebPlugin::ContainerWrapper { public: - explicit BlinkContainerWrapper(blink::WebPluginContainer* container) - : container_(container) { + BlinkContainerWrapper(blink::WebPluginContainer* container, + V8ValueConverter* v8_value_converter) + : container_(container), + post_message_sender_(container_, v8_value_converter) { DCHECK(container_); + DCHECK(v8_value_converter); } BlinkContainerWrapper(const BlinkContainerWrapper&) = delete; BlinkContainerWrapper& operator=(const BlinkContainerWrapper&) = delete; @@ -193,6 +204,14 @@ class BlinkContainerWrapper final : public PdfViewWebPlugin::ContainerWrapper { return GetFrame()->GetScrollOffset(); } + void PostMessage(base::Value::Dict message) override { + post_message_sender_.Post(std::move(message)); + } + + void UsePluginAsFindHandler() override { + container_->UsePluginAsFindHandler(); + } + void SetReferrerForRequest(blink::WebURLRequest& request, const blink::WebURL& referrer_url) override { GetFrame()->SetReferrerForRequest(request, referrer_url); @@ -271,6 +290,7 @@ class BlinkContainerWrapper final : public PdfViewWebPlugin::ContainerWrapper { private: const raw_ptr<blink::WebPluginContainer> container_; + PostMessageSender post_message_sender_; }; } // namespace @@ -281,10 +301,6 @@ PdfViewWebPlugin::Client::CreateAccessibilityDataHandler( return nullptr; } -bool PdfViewWebPlugin::Client::IsUseZoomForDSFEnabled() const { - return false; -} - PdfViewWebPlugin::PdfViewWebPlugin( std::unique_ptr<Client> client, mojo::AssociatedRemote<pdf::mojom::PdfService> pdf_service_remote, @@ -303,30 +319,30 @@ PdfViewWebPlugin::~PdfViewWebPlugin() = default; bool PdfViewWebPlugin::Initialize(blink::WebPluginContainer* container) { DCHECK_EQ(container->Plugin(), this); - return InitializeCommon(std::make_unique<BlinkContainerWrapper>(container), - nullptr); + return InitializeCommon( + std::make_unique<BlinkContainerWrapper>(container, client_.get()), + /*engine_override=*/nullptr); } bool PdfViewWebPlugin::InitializeForTesting( std::unique_ptr<ContainerWrapper> container_wrapper, - std::unique_ptr<PDFiumEngine> engine) { + std::unique_ptr<PDFiumEngine> engine, + std::unique_ptr<UrlLoader> loader) { + test_loader_ = std::move(loader); return InitializeCommon(std::move(container_wrapper), std::move(engine)); } -// Modeled on `OutOfProcessInstance::Init()`. bool PdfViewWebPlugin::InitializeCommon( std::unique_ptr<ContainerWrapper> container_wrapper, - std::unique_ptr<PDFiumEngine> engine) { + std::unique_ptr<PDFiumEngine> engine_override) { container_wrapper_ = std::move(container_wrapper); - post_message_sender_.set_container(Container()); // Allow the plugin to handle touch events. container_wrapper_->RequestTouchEventType( blink::WebPluginContainer::kTouchEventRequestTypeRaw); // Allow the plugin to handle find requests. - if (Container()) - Container()->UsePluginAsFindHandler(); + container_wrapper_->UsePluginAsFindHandler(); absl::optional<ParsedParams> params = ParseWebPluginParams(initial_params_); @@ -350,8 +366,9 @@ bool PdfViewWebPlugin::InitializeCommon( PerProcessInitializer::GetInstance().Acquire(); InitializeBase( - engine ? std::move(engine) - : std::make_unique<PDFiumEngine>(this, params->script_option), + engine_override + ? std::move(engine_override) + : std::make_unique<PDFiumEngine>(this, params->script_option), /*embedder_origin=*/container_wrapper_->GetEmbedderOriginString(), /*src_url=*/params->src_url, /*original_url=*/params->original_url, @@ -360,14 +377,18 @@ bool PdfViewWebPlugin::InitializeCommon( /*has_edits=*/params->has_edits); SendSetSmoothScrolling(); + + if (!IsPrintPreview()) + metrics_handler_ = std::make_unique<MetricsHandler>(); + return true; } void PdfViewWebPlugin::SendSetSmoothScrolling() { - base::Value message(base::Value::Type::DICTIONARY); - message.SetStringKey("type", "setSmoothScrolling"); - message.SetBoolKey("smoothScrolling", - blink::Platform::Current()->IsScrollAnimatorEnabled()); + base::Value::Dict message; + message.Set("type", "setSmoothScrolling"); + message.Set("smoothScrolling", + blink::Platform::Current()->IsScrollAnimatorEnabled()); SendMessage(std::move(message)); } @@ -378,7 +399,6 @@ void PdfViewWebPlugin::Destroy() { DestroyPreviewEngine(); DestroyEngine(); PerProcessInitializer::GetInstance().Release(); - post_message_sender_.set_container(nullptr); container_wrapper_.reset(); } @@ -395,9 +415,9 @@ v8::Local<v8::Object> PdfViewWebPlugin::V8ScriptableObject( // TODO(crbug.com/1123731): Messages should not be handled on the renderer // main thread. scriptable_receiver_.Reset( - isolate, - PostMessageReceiver::Create(isolate, weak_factory_.GetWeakPtr(), - base::SequencedTaskRunnerHandle::Get())); + isolate, PostMessageReceiver::Create( + isolate, client_->GetWeakPtr(), weak_factory_.GetWeakPtr(), + base::SequencedTaskRunnerHandle::Get())); } return scriptable_receiver_.Get(isolate); @@ -465,10 +485,8 @@ void PdfViewWebPlugin::UpdateGeometry(const gfx::Rect& window_rect, OnViewportChanged(window_rect, container_wrapper_->DeviceScaleFactor()); gfx::PointF scroll_position = container_wrapper_->GetScrollPosition(); - if (client_->IsUseZoomForDSFEnabled()) { - // Convert back to CSS pixels. - scroll_position.Scale(1.0f / device_scale()); - } + // Convert back to CSS pixels. + scroll_position.Scale(1.0f / device_scale()); UpdateScroll(scroll_position); } @@ -637,17 +655,20 @@ bool PdfViewWebPlugin::StartFind(const blink::WebString& search_text, bool case_sensitive, int identifier) { find_identifier_ = identifier; - return PdfViewPluginBase::StartFind(search_text.Utf8(), case_sensitive); + engine()->StartFind(search_text.Utf8(), case_sensitive); + return true; } void PdfViewWebPlugin::SelectFindResult(bool forward, int identifier) { find_identifier_ = identifier; - PdfViewPluginBase::SelectFindResult(forward); + engine()->SelectFindResult(forward); } void PdfViewWebPlugin::StopFind() { find_identifier_ = -1; - PdfViewPluginBase::StopFind(); + engine()->StopFind(); + tickmarks_.clear(); + container_wrapper_->ReportFindInPageTickmarks(tickmarks_); } bool PdfViewWebPlugin::CanRotateView() { @@ -705,6 +726,47 @@ void PdfViewWebPlugin::UpdateCursor(ui::mojom::CursorType new_cursor_type) { set_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) { + container_wrapper_->ReportFindInPageMatchCount(find_identifier_, total, + final_result); + } + + container_wrapper_->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) { if (find_identifier_ == -1 || !container_wrapper_) return; @@ -774,14 +836,6 @@ bool PdfViewWebPlugin::BindPaintGraphics(Graphics& graphics) { return false; } -void PdfViewWebPlugin::ScheduleTaskOnMainThread(const base::Location& from_here, - ResultCallback callback, - int32_t result, - base::TimeDelta delay) { - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - from_here, base::BindOnce(std::move(callback), result), delay); -} - void PdfViewWebPlugin::SetCaretPosition(const gfx::PointF& position) { PdfViewPluginBase::SetCaretPosition(position); } @@ -822,7 +876,7 @@ PdfViewWebPlugin::CreateAssociatedURLLoader( return container_wrapper_->CreateAssociatedURLLoader(options); } -void PdfViewWebPlugin::OnMessage(const base::Value& message) { +void PdfViewWebPlugin::OnMessage(const base::Value::Dict& message) { PdfViewPluginBase::HandleMessage(message); } @@ -839,19 +893,13 @@ void PdfViewWebPlugin::UpdateSnapshot(sk_sp<SkImage> snapshot) { void PdfViewWebPlugin::UpdateScaledValues() { total_translate_ = snapshot_translate_; - // Scale translate to compensate for use-zoom-for-DSF. if (viewport_to_dip_scale_ != 1.0f) total_translate_.Scale(1.0f / viewport_to_dip_scale_); } void PdfViewWebPlugin::UpdateScale(float scale) { - if (client_->IsUseZoomForDSFEnabled()) { - viewport_to_dip_scale_ = scale; - device_to_css_scale_ = 1.0f; - } else { - viewport_to_dip_scale_ = 1.0f; - device_to_css_scale_ = scale; - } + viewport_to_dip_scale_ = scale; + device_to_css_scale_ = 1.0f; UpdateScaledValues(); } @@ -876,13 +924,24 @@ base::WeakPtr<PdfViewPluginBase> PdfViewWebPlugin::GetWeakPtr() { } std::unique_ptr<UrlLoader> PdfViewWebPlugin::CreateUrlLoaderInternal() { + if (test_loader_) + return std::move(test_loader_); + auto loader = std::make_unique<BlinkUrlLoader>(weak_factory_.GetWeakPtr()); loader->GrantUniversalAccess(); return loader; } -void PdfViewWebPlugin::SendMessage(base::Value message) { - post_message_sender_.Post(std::move(message)); +void PdfViewWebPlugin::OnDocumentLoadComplete() { + RecordDocumentMetrics(); + + SendAttachments(); + SendBookmarks(); + SendMetadata(); +} + +void PdfViewWebPlugin::SendMessage(base::Value::Dict message) { + container_wrapper_->PostMessage(std::move(message)); } void PdfViewWebPlugin::SaveAs() { @@ -931,22 +990,6 @@ void PdfViewWebPlugin::SetAccessibilityViewportInfo( weak_factory_.GetWeakPtr(), std::move(viewport_info))); } -void PdfViewWebPlugin::NotifyFindResultsChanged(int total, bool final_result) { - // 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 || !container_wrapper_) - return; - - container_wrapper_->ReportFindInPageMatchCount(find_identifier_, total, - final_result); -} - -void PdfViewWebPlugin::NotifyFindTickmarks( - const std::vector<gfx::Rect>& tickmarks) { - container_wrapper_->ReportFindInPageTickmarks(tickmarks); -} - void PdfViewWebPlugin::SetContentRestrictions(int content_restrictions) { auto* service = GetPdfService(); if (!service) @@ -980,11 +1023,9 @@ void PdfViewWebPlugin::PluginDidStopLoading() { } void PdfViewWebPlugin::InvokePrintDialog() { - ScheduleTaskOnMainThread( - FROM_HERE, - base::BindOnce(&PdfViewWebPlugin::OnInvokePrintDialog, - weak_factory_.GetWeakPtr()), - /*result=*/0, base::TimeDelta()); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(&PdfViewWebPlugin::OnInvokePrintDialog, + weak_factory_.GetWeakPtr())); } void PdfViewWebPlugin::NotifySelectionChanged(const gfx::PointF& left, @@ -1018,11 +1059,7 @@ void PdfViewWebPlugin::OnViewportChanged( // `plugin_rect_in_css_pixel` needs to be converted to device pixels before // getting passed into PdfViewPluginBase::UpdateGeometryOnPluginRectChanged(). - UpdateGeometryOnPluginRectChanged( - gfx::ScaleToEnclosingRect( - plugin_rect_in_css_pixel, - client_->IsUseZoomForDSFEnabled() ? 1.0f : new_device_scale), - new_device_scale); + UpdateGeometryOnPluginRectChanged(plugin_rect_in_css_pixel, new_device_scale); } void PdfViewWebPlugin::InvalidatePluginContainer() { @@ -1095,7 +1132,7 @@ void PdfViewWebPlugin::HandleImeCommit(const blink::WebString& text) { } } -void PdfViewWebPlugin::OnInvokePrintDialog(int32_t /*result*/) { +void PdfViewWebPlugin::OnInvokePrintDialog() { client_->Print(Container()->GetElement()); } @@ -1131,4 +1168,107 @@ pdf::mojom::PdfService* PdfViewWebPlugin::GetPdfService() { return pdf_service_remote_.is_bound() ? pdf_service_remote_.get() : nullptr; } +void PdfViewWebPlugin::ResetRecentlySentFindUpdate() { + recently_sent_find_update_ = false; +} + +void PdfViewWebPlugin::RecordDocumentMetrics() { + if (!metrics_handler_) + return; + + metrics_handler_->RecordDocumentMetrics(engine()->GetDocumentMetadata()); + metrics_handler_->RecordAttachmentTypes( + engine()->GetDocumentAttachmentInfoList()); +} + +void PdfViewWebPlugin::SendAttachments() { + const std::vector<DocumentAttachmentInfo>& attachment_infos = + engine()->GetDocumentAttachmentInfoList(); + if (attachment_infos.empty()) + return; + + base::Value::List attachments; + for (const DocumentAttachmentInfo& attachment_info : attachment_infos) { + // Send `size` as -1 to indicate that the attachment is too large to be + // downloaded. + const int size = attachment_info.size_bytes <= kMaximumSavedFileSize + ? static_cast<int>(attachment_info.size_bytes) + : -1; + + base::Value::Dict attachment; + attachment.Set("name", attachment_info.name); + attachment.Set("size", size); + attachment.Set("readable", attachment_info.is_readable); + attachments.Append(std::move(attachment)); + } + + base::Value::Dict message; + message.Set("type", "attachments"); + message.Set("attachmentsData", std::move(attachments)); + SendMessage(std::move(message)); +} + +void PdfViewWebPlugin::SendBookmarks() { + base::Value::List bookmarks = engine()->GetBookmarks(); + if (bookmarks.empty()) + return; + + base::Value::Dict message; + message.Set("type", "bookmarks"); + message.Set("bookmarksData", std::move(bookmarks)); + SendMessage(std::move(message)); +} + +void PdfViewWebPlugin::SendMetadata() { + base::Value::Dict metadata; + const DocumentMetadata& document_metadata = engine()->GetDocumentMetadata(); + + const std::string version = FormatPdfVersion(document_metadata.version); + if (!version.empty()) + metadata.Set("version", version); + + metadata.Set("fileSize", ui::FormatBytes(document_metadata.size_bytes)); + + metadata.Set("linearized", document_metadata.linearized); + + if (!document_metadata.title.empty()) + metadata.Set("title", document_metadata.title); + + if (!document_metadata.author.empty()) + metadata.Set("author", document_metadata.author); + + if (!document_metadata.subject.empty()) + metadata.Set("subject", document_metadata.subject); + + if (!document_metadata.keywords.empty()) + metadata.Set("keywords", document_metadata.keywords); + + if (!document_metadata.creator.empty()) + metadata.Set("creator", document_metadata.creator); + + if (!document_metadata.producer.empty()) + metadata.Set("producer", document_metadata.producer); + + if (!document_metadata.creation_date.is_null()) { + metadata.Set("creationDate", base::TimeFormatShortDateAndTime( + document_metadata.creation_date)); + } + + if (!document_metadata.mod_date.is_null()) { + metadata.Set("modDate", + base::TimeFormatShortDateAndTime(document_metadata.mod_date)); + } + + metadata.Set("pageSize", + FormatPageSize(engine()->GetUniformPageSizePoints())); + + metadata.Set("canSerializeDocument", + IsSaveDataSizeValid(engine()->GetLoadedByteSize())); + + base::Value::Dict message; + message.Set("type", "metadata"); + message.Set("metadataData", std::move(metadata)); + SendMessage(std::move(message)); +} + } // namespace chrome_pdf diff --git a/chromium/pdf/pdf_view_web_plugin.h b/chromium/pdf/pdf_view_web_plugin.h index 4eb0e682204..632b4df1f78 100644 --- a/chromium/pdf/pdf_view_web_plugin.h +++ b/chromium/pdf/pdf_view_web_plugin.h @@ -20,9 +20,9 @@ #include "pdf/pdf_accessibility_action_handler.h" #include "pdf/pdf_view_plugin_base.h" #include "pdf/post_message_receiver.h" -#include "pdf/post_message_sender.h" #include "pdf/ppapi_migration/graphics.h" #include "pdf/ppapi_migration/url_loader.h" +#include "pdf/v8_value_converter.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/web/web_plugin.h" @@ -53,10 +53,10 @@ class MetafileSkia; namespace chrome_pdf { +class MetricsHandler; class PDFiumEngine; class PdfAccessibilityDataHandler; -// Skeleton for a `blink::WebPlugin` to replace `OutOfProcessInstance`. class PdfViewWebPlugin final : public PdfViewPluginBase, public blink::WebPlugin, public pdf::mojom::PdfListener, @@ -96,6 +96,12 @@ class PdfViewWebPlugin final : public PdfViewPluginBase, // Gets the scroll position. virtual gfx::PointF GetScrollPosition() = 0; + // Enqueues a "message" event carrying `message` to the plugin embedder. + virtual void PostMessage(base::Value::Dict message) = 0; + + // Tells the embedder to allow the plugin to handle find requests. + virtual void UsePluginAsFindHandler() = 0; + // Calls underlying WebLocalFrame::SetReferrerForRequest(). virtual void SetReferrerForRequest(blink::WebURLRequest& request, const blink::WebURL& referrer_url) = 0; @@ -142,10 +148,12 @@ class PdfViewWebPlugin final : public PdfViewPluginBase, }; // Allows for dependency injections into `PdfViewWebPlugin`. - class Client { + class Client : public V8ValueConverter { public: virtual ~Client() = default; + virtual base::WeakPtr<Client> GetWeakPtr() = 0; + // Prints the given `element`. virtual void Print(const blink::WebElement& element) {} @@ -159,9 +167,6 @@ class PdfViewWebPlugin final : public PdfViewPluginBase, virtual std::unique_ptr<PdfAccessibilityDataHandler> CreateAccessibilityDataHandler( PdfAccessibilityActionHandler* action_handler); - - // Indicates whether to use zoom for DSF (device scale factor). - virtual bool IsUseZoomForDSFEnabled() const; }; PdfViewWebPlugin( @@ -232,10 +237,11 @@ class PdfViewWebPlugin final : public PdfViewPluginBase, int relative_cursor_pos) override; void ImeFinishComposingTextForPlugin(bool keep_selection) override; - // PdfViewPluginBase: + // PDFEngine::Client: void UpdateCursor(ui::mojom::CursorType new_cursor_type) override; + void UpdateTickMarks(const std::vector<gfx::Rect>& tickmarks) override; + void NotifyNumberOfFindResultsChanged(int total, bool final_result) override; void NotifySelectedFindResultChanged(int current_find_index) override; - void CaretChanged(const gfx::Rect& caret_rect) override; void Alert(const std::string& message) override; bool Confirm(const std::string& message) override; std::string Prompt(const std::string& question, @@ -243,14 +249,13 @@ class PdfViewWebPlugin final : public PdfViewPluginBase, std::vector<SearchStringResult> SearchString(const char16_t* string, const char16_t* term, bool case_sensitive) override; + void CaretChanged(const gfx::Rect& caret_rect) override; void SetSelectedText(const std::string& selected_text) override; bool IsValidLink(const std::string& url) override; + + // PdfViewPluginBase: std::unique_ptr<Graphics> CreatePaintGraphics(const gfx::Size& size) override; bool BindPaintGraphics(Graphics& graphics) override; - void ScheduleTaskOnMainThread(const base::Location& from_here, - ResultCallback callback, - int32_t result, - base::TimeDelta delay) override; // pdf::mojom::PdfListener: void SetCaretPosition(const gfx::PointF& position) override; @@ -268,7 +273,7 @@ class PdfViewWebPlugin final : public PdfViewPluginBase, const blink::WebAssociatedURLLoaderOptions& options) override; // PostMessageReceiver::Client: - void OnMessage(const base::Value& message) override; + void OnMessage(const base::Value::Dict& message) override; // SkiaGraphics::Client: void UpdateSnapshot(sk_sp<SkImage> snapshot) override; @@ -282,9 +287,10 @@ class PdfViewWebPlugin final : public PdfViewPluginBase, const AccessibilityActionData& action_data) override; // Initializes the plugin using the `container_wrapper` and `engine` provided - // by tests. + // by tests. Lets CreateUrlLoaderInternal() return `loader` on its first call. bool InitializeForTesting(std::unique_ptr<ContainerWrapper> container_wrapper, - std::unique_ptr<PDFiumEngine> engine); + std::unique_ptr<PDFiumEngine> engine, + std::unique_ptr<UrlLoader> loader); const gfx::Rect& GetPluginRectForTesting() const { return plugin_rect(); } @@ -294,7 +300,8 @@ class PdfViewWebPlugin final : public PdfViewPluginBase, // PdfViewPluginBase: base::WeakPtr<PdfViewPluginBase> GetWeakPtr() override; std::unique_ptr<UrlLoader> CreateUrlLoaderInternal() override; - void SendMessage(base::Value message) override; + void OnDocumentLoadComplete() override; + void SendMessage(base::Value::Dict message) override; void SaveAs() override; void InitImageData(const gfx::Size& size) override; void SetFormTextFieldInFocus(bool in_focus) override; @@ -305,8 +312,6 @@ class PdfViewWebPlugin final : public PdfViewPluginBase, AccessibilityPageObjects page_objects) override; void SetAccessibilityViewportInfo( AccessibilityViewportInfo viewport_info) override; - void NotifyFindResultsChanged(int total, bool final_result) override; - void NotifyFindTickmarks(const std::vector<gfx::Rect>& tickmarks) override; void SetContentRestrictions(int content_restrictions) override; void SetPluginCanSave(bool can_save) override; void PluginDidStartLoading() override; @@ -324,8 +329,10 @@ class PdfViewWebPlugin final : public PdfViewPluginBase, // Call `Destroy()` instead. ~PdfViewWebPlugin() override; + // Passing in a null `engine_override` allows InitializeCommon() to create a + // PDFiumEngine normally. Otherwise, `engine_override` is used. bool InitializeCommon(std::unique_ptr<ContainerWrapper> container_wrapper, - std::unique_ptr<PDFiumEngine> engine); + std::unique_ptr<PDFiumEngine> engine_override); // Sends whether to do smooth scrolling. void SendSetSmoothScrolling(); @@ -356,7 +363,7 @@ class PdfViewWebPlugin final : public PdfViewPluginBase, // see crbug.com/66334. // TODO(crbug.com/1217012): Re-evaluate the need for a callback when parts of // the plugin are moved off the main thread. - void OnInvokePrintDialog(int32_t /*result*/); + void OnInvokePrintDialog(); // Callback to set the document information in the accessibility tree // asynchronously. @@ -377,6 +384,20 @@ class PdfViewWebPlugin final : public PdfViewPluginBase, // May be null in unit tests. pdf::mojom::PdfService* GetPdfService(); + void ResetRecentlySentFindUpdate(); + + // Records metrics about the document metadata. + void RecordDocumentMetrics(); + + // Sends the attachments data. + void SendAttachments(); + + // Sends the bookmarks data. + void SendBookmarks(); + + // Send document metadata data. + void SendMetadata(); + blink::WebString selected_text_; std::unique_ptr<Client> const client_; @@ -406,7 +427,6 @@ class PdfViewWebPlugin final : public PdfViewPluginBase, std::unique_ptr<ContainerWrapper> container_wrapper_; v8::Persistent<v8::Object> scriptable_receiver_; - PostMessageSender post_message_sender_; // The current image snapshot. cc::PaintImage snapshot_; @@ -433,6 +453,16 @@ class PdfViewWebPlugin final : public PdfViewPluginBase, std::unique_ptr<PdfAccessibilityDataHandler> const pdf_accessibility_data_handler_; + // Whether an update to the number of find results found was sent less than + // `kFindResultCooldown` TimeDelta ago. + bool recently_sent_find_update_ = false; + + // Stores the tickmarks to be shown for the current find results. + std::vector<gfx::Rect> tickmarks_; + + // Only instantiated when not print previewing. + std::unique_ptr<MetricsHandler> metrics_handler_; + // The metafile in which to save the printed output. Assigned a value only // between `PrintBegin()` and `PrintEnd()` calls. raw_ptr<printing::MetafileSkia> printing_metafile_ = nullptr; @@ -440,6 +470,10 @@ class PdfViewWebPlugin final : public PdfViewPluginBase, // The indices of pages to print. std::vector<int> pages_to_print_; + // If non-null, the UrlLoader that CreateUrlLoaderInternal() returns for + // testing purposes. + std::unique_ptr<UrlLoader> test_loader_; + base::WeakPtrFactory<PdfViewWebPlugin> weak_factory_{this}; }; diff --git a/chromium/pdf/pdf_view_web_plugin_unittest.cc b/chromium/pdf/pdf_view_web_plugin_unittest.cc index 8477158ef6a..8e54e842918 100644 --- a/chromium/pdf/pdf_view_web_plugin_unittest.cc +++ b/chromium/pdf/pdf_view_web_plugin_unittest.cc @@ -4,6 +4,7 @@ #include "pdf/pdf_view_web_plugin.h" +#include <functional> #include <memory> #include <string> #include <utility> @@ -11,6 +12,7 @@ #include "base/location.h" #include "base/memory/raw_ptr.h" +#include "base/memory/weak_ptr.h" #include "base/run_loop.h" #include "base/strings/string_piece.h" #include "base/test/bind.h" @@ -49,12 +51,14 @@ #include "ui/gfx/geometry/size.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/geometry/vector2d_f.h" +#include "ui/gfx/range/range.h" #include "ui/latency/latency_info.h" namespace chrome_pdf { namespace { +using ::testing::Eq; using ::testing::InSequence; using ::testing::Invoke; using ::testing::MockFunction; @@ -170,6 +174,10 @@ class FakeContainerWrapper : public PdfViewWebPlugin::ContainerWrapper { MOCK_METHOD(gfx::PointF, GetScrollPosition, (), (override)); + MOCK_METHOD(void, PostMessage, (base::Value::Dict), (override)); + + MOCK_METHOD(void, UsePluginAsFindHandler, (), (override)); + MOCK_METHOD(void, SetReferrerForRequest, (blink::WebURLRequest&, const blink::WebURL&), @@ -208,11 +216,10 @@ class FakeContainerWrapper : public PdfViewWebPlugin::ContainerWrapper { return nullptr; } - // TODO(https://crbug.com/1207575): Container() should not be used for testing - // since it doesn't have a valid blink::WebPluginContainer. Make this method - // fail once ContainerWrapper instead of blink::WebPluginContainer is used for - // initializing `PostMessageSender`. - blink::WebPluginContainer* Container() override { return nullptr; } + blink::WebPluginContainer* Container() override { + ADD_FAILURE(); + return nullptr; + } blink::WebTextInputType widget_text_input_type() const { return widget_text_input_type_; @@ -242,7 +249,32 @@ class FakePdfViewWebPluginClient : public PdfViewWebPlugin::Client { ~FakePdfViewWebPluginClient() override = default; // PdfViewWebPlugin::Client: - MOCK_METHOD(bool, IsUseZoomForDSFEnabled, (), (const, override)); + MOCK_METHOD(std::unique_ptr<base::Value>, + FromV8Value, + (v8::Local<v8::Value>, v8::Local<v8::Context>), + (override)); + MOCK_METHOD(v8::Local<v8::Value>, + ToV8Value, + (const base::Value&, v8::Local<v8::Context>), + (override)); + MOCK_METHOD(base::WeakPtr<Client>, GetWeakPtr, (), (override)); + + private: + base::WeakPtrFactory<FakePdfViewWebPluginClient> weak_factory_{this}; +}; + +class MockUrlLoader : public UrlLoader { + public: + MOCK_METHOD(void, GrantUniversalAccess, (), (override)); + MOCK_METHOD(void, + Open, + (const UrlRequest&, base::OnceCallback<void(int)>), + (override)); + MOCK_METHOD(void, + ReadResponseBody, + (base::span<char>, base::OnceCallback<void(int)>), + (override)); + MOCK_METHOD(void, Close, (), (override)); }; } // namespace @@ -295,8 +327,8 @@ class PdfViewWebPluginTest : public PdfViewWebPluginWithoutInitializeTest { wrapper_ptr_ = wrapper.get(); auto engine = CreateEngine(); engine_ptr_ = engine.get(); - EXPECT_TRUE( - plugin_->InitializeForTesting(std::move(wrapper), std::move(engine))); + EXPECT_TRUE(plugin_->InitializeForTesting( + std::move(wrapper), std::move(engine), CreateLoader())); } void TearDown() override { @@ -310,10 +342,13 @@ class PdfViewWebPluginTest : public PdfViewWebPluginWithoutInitializeTest { return std::make_unique<NiceMock<TestPDFiumEngine>>(plugin_.get()); } + // Allow derived test classes to create their own custom loaders. + virtual std::unique_ptr<UrlLoader> CreateLoader() { return nullptr; } + void SetDocumentDimensions(const gfx::Size& dimensions) { EXPECT_CALL(*engine_ptr_, ApplyDocumentLayout) .WillRepeatedly(Return(dimensions)); - plugin_->OnMessage(base::test::ParseJson(R"({ + base::Value message = base::test::ParseJson(R"({ "type": "viewport", "userInitiated": false, "zoom": 1, @@ -325,7 +360,8 @@ class PdfViewWebPluginTest : public PdfViewWebPluginWithoutInitializeTest { "xOffset": 0, "yOffset": 0, "pinchPhase": 0, - })")); + })"); + plugin_->OnMessage(message.GetDict()); } void UpdatePluginGeometry(float device_scale, const gfx::Rect& window_rect) { @@ -333,11 +369,8 @@ class PdfViewWebPluginTest : public PdfViewWebPluginWithoutInitializeTest { // Waits for main thread callback scheduled by `PaintManager`. base::RunLoop run_loop; - plugin_->ScheduleTaskOnMainThread( - FROM_HERE, base::BindLambdaForTesting([&run_loop](int32_t /*result*/) { - run_loop.Quit(); - }), - /*result=*/0, base::TimeDelta()); + base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, + run_loop.QuitClosure()); run_loop.Run(); } @@ -428,13 +461,11 @@ TEST_F(PdfViewWebPluginWithoutInitializeTest, Initialize) { RequestTouchEventType( blink::WebPluginContainer::kTouchEventRequestTypeRaw)); - EXPECT_TRUE( - plugin_->InitializeForTesting(std::move(wrapper), std::move(engine))); + EXPECT_TRUE(plugin_->InitializeForTesting( + std::move(wrapper), std::move(engine), /*loader=*/nullptr)); } -TEST_F(PdfViewWebPluginTest, UpdateGeometrySetsPluginRectUseZoomForDSFEnabled) { - EXPECT_CALL(*client_ptr_, IsUseZoomForDSFEnabled) - .WillRepeatedly(Return(true)); +TEST_F(PdfViewWebPluginTest, UpdateGeometrySetsPluginRect) { EXPECT_CALL(*engine_ptr_, ZoomUpdated(2.0f)); TestUpdateGeometrySetsPluginRect( /*device_scale=*/2.0f, /*window_rect=*/gfx::Rect(4, 4, 12, 12), @@ -443,17 +474,6 @@ TEST_F(PdfViewWebPluginTest, UpdateGeometrySetsPluginRectUseZoomForDSFEnabled) { } TEST_F(PdfViewWebPluginTest, - UpdateGeometrySetsPluginRectUseZoomForDSFDisabled) { - EXPECT_CALL(*client_ptr_, IsUseZoomForDSFEnabled) - .WillRepeatedly(Return(false)); - EXPECT_CALL(*engine_ptr_, ZoomUpdated(2.0f)); - TestUpdateGeometrySetsPluginRect( - /*device_scale=*/2.0f, /*window_rect=*/gfx::Rect(4, 4, 12, 12), - /*expected_device_scale=*/2.0f, - /*expected_plugin_rect=*/gfx::Rect(8, 8, 24, 24)); -} - -TEST_F(PdfViewWebPluginTest, UpdateGeometrySetsPluginRectOnVariousDeviceScales) { struct UpdateGeometryParams { // The plugin container's device scale. @@ -469,10 +489,6 @@ TEST_F(PdfViewWebPluginTest, gfx::Rect expected_plugin_rect; }; - // Keep the using zoom for DSF setting consistent within the test. - EXPECT_CALL(*client_ptr_, IsUseZoomForDSFEnabled) - .WillRepeatedly(Return(true)); - static constexpr UpdateGeometryParams kUpdateGeometryParams[] = { {1.0f, gfx::Rect(3, 4, 5, 6), 1.0f, gfx::Rect(3, 4, 5, 6)}, {2.0f, gfx::Rect(3, 4, 5, 6), 2.0f, gfx::Rect(3, 4, 5, 6)}, @@ -485,9 +501,7 @@ TEST_F(PdfViewWebPluginTest, } } -TEST_F(PdfViewWebPluginTest, UpdateGeometryScrollsUseZoomForDSFEnabled) { - EXPECT_CALL(*client_ptr_, IsUseZoomForDSFEnabled) - .WillRepeatedly(Return(true)); +TEST_F(PdfViewWebPluginTest, UpdateGeometryScroll) { SetDocumentDimensions({100, 200}); EXPECT_CALL(*wrapper_ptr_, GetScrollPosition) @@ -497,38 +511,14 @@ TEST_F(PdfViewWebPluginTest, UpdateGeometryScrollsUseZoomForDSFEnabled) { UpdatePluginGeometryWithoutWaiting(2.0f, gfx::Rect(3, 4, 5, 6)); } -TEST_F(PdfViewWebPluginTest, UpdateGeometryScrollsUseZoomForDSFDisabled) { - EXPECT_CALL(*client_ptr_, IsUseZoomForDSFEnabled) - .WillRepeatedly(Return(false)); - SetDocumentDimensions({100, 200}); - - EXPECT_CALL(*wrapper_ptr_, GetScrollPosition) - .WillRepeatedly(Return(gfx::PointF(2.0f, 3.0f))); - EXPECT_CALL(*engine_ptr_, ScrolledToXPosition(4)); - EXPECT_CALL(*engine_ptr_, ScrolledToYPosition(6)); - UpdatePluginGeometryWithoutWaiting(2.0f, gfx::Rect(3, 4, 5, 6)); -} - -class PdfViewWebPluginTestUseZoomForDSF - : public PdfViewWebPluginTest, - public testing::WithParamInterface<bool> { - public: - void SetUp() override { - PdfViewWebPluginTest::SetUp(); - ON_CALL(*client_ptr_, IsUseZoomForDSFEnabled) - .WillByDefault(Return(GetParam())); - } -}; - -TEST_P(PdfViewWebPluginTestUseZoomForDSF, - UpdateGeometrySetsPluginRectWithEmptyWindow) { +TEST_F(PdfViewWebPluginTest, UpdateGeometrySetsPluginRectWithEmptyWindow) { EXPECT_CALL(*engine_ptr_, ZoomUpdated).Times(0); TestUpdateGeometrySetsPluginRect( /*device_scale=*/2.0f, /*window_rect=*/gfx::Rect(2, 2, 0, 0), /*expected_device_scale=*/1.0f, /*expected_plugin_rect=*/gfx::Rect()); } -TEST_P(PdfViewWebPluginTestUseZoomForDSF, SetCaretPositionIgnoresOrigin) { +TEST_F(PdfViewWebPluginTest, SetCaretPositionIgnoresOrigin) { SetDocumentDimensions({16, 9}); UpdatePluginGeometryWithoutWaiting(1.0f, {10, 20, 20, 5}); @@ -536,22 +526,21 @@ TEST_P(PdfViewWebPluginTestUseZoomForDSF, SetCaretPositionIgnoresOrigin) { plugin_->SetCaretPosition({4.0f, 3.0f}); } -TEST_P(PdfViewWebPluginTestUseZoomForDSF, PaintEmptySnapshots) { +TEST_F(PdfViewWebPluginTest, PaintEmptySnapshots) { TestPaintEmptySnapshots(/*device_scale=*/4.0f, /*window_rect=*/gfx::Rect(10, 10, 20, 20), /*paint_rect=*/gfx::Rect(5, 5, 15, 15), /*expected_clipped_rect=*/gfx::Rect(10, 10, 10, 10)); } -TEST_P(PdfViewWebPluginTestUseZoomForDSF, PaintSnapshots) { +TEST_F(PdfViewWebPluginTest, PaintSnapshots) { TestPaintSnapshots(/*device_scale=*/4.0f, /*window_rect=*/gfx::Rect(10, 10, 20, 20), /*paint_rect=*/gfx::Rect(5, 5, 15, 15), /*expected_clipped_rect=*/gfx::Rect(10, 10, 10, 10)); } -TEST_P(PdfViewWebPluginTestUseZoomForDSF, - PaintSnapshotsWithVariousDeviceScales) { +TEST_F(PdfViewWebPluginTest, PaintSnapshotsWithVariousDeviceScales) { static constexpr PaintParams kPaintWithVariousScalesParams[] = { {0.4f, gfx::Rect(8, 8, 30, 30), gfx::Rect(10, 10, 30, 30), gfx::Rect(10, 10, 28, 28)}, @@ -567,8 +556,7 @@ TEST_P(PdfViewWebPluginTestUseZoomForDSF, } } -TEST_P(PdfViewWebPluginTestUseZoomForDSF, - PaintSnapshotsWithVariousRectPositions) { +TEST_F(PdfViewWebPluginTest, PaintSnapshotsWithVariousRectPositions) { static constexpr PaintParams kPaintWithVariousPositionsParams[] = { // The window origin falls outside the `paint_rect` area. {4.0f, gfx::Rect(10, 10, 20, 20), gfx::Rect(5, 5, 15, 15), @@ -584,7 +572,7 @@ TEST_P(PdfViewWebPluginTestUseZoomForDSF, } } -TEST_P(PdfViewWebPluginTestUseZoomForDSF, UpdateLayerTransformWithIdentity) { +TEST_F(PdfViewWebPluginTest, UpdateLayerTransformWithIdentity) { plugin_->UpdateLayerTransform(1.0f, gfx::Vector2dF()); TestPaintSnapshots(/*device_scale=*/4.0f, /*window_rect=*/gfx::Rect(10, 10, 20, 20), @@ -592,7 +580,7 @@ TEST_P(PdfViewWebPluginTestUseZoomForDSF, UpdateLayerTransformWithIdentity) { /*expected_clipped_rect=*/gfx::Rect(10, 10, 20, 20)); } -TEST_P(PdfViewWebPluginTestUseZoomForDSF, UpdateLayerTransformWithScale) { +TEST_F(PdfViewWebPluginTest, UpdateLayerTransformWithScale) { plugin_->UpdateLayerTransform(0.5f, gfx::Vector2dF()); TestPaintSnapshots(/*device_scale=*/4.0f, /*window_rect=*/gfx::Rect(10, 10, 20, 20), @@ -600,23 +588,7 @@ TEST_P(PdfViewWebPluginTestUseZoomForDSF, UpdateLayerTransformWithScale) { /*expected_clipped_rect=*/gfx::Rect(10, 10, 10, 10)); } -TEST_F(PdfViewWebPluginTest, - UpdateLayerTransformWithTranslateUseZoomForDSFDisabled) { - EXPECT_CALL(*client_ptr_, IsUseZoomForDSFEnabled) - .WillRepeatedly(Return(false)); - - plugin_->UpdateLayerTransform(1.0f, gfx::Vector2dF(-5, 5)); - TestPaintSnapshots(/*device_scale=*/4.0f, - /*window_rect=*/gfx::Rect(10, 10, 20, 20), - /*paint_rect=*/gfx::Rect(10, 10, 20, 20), - /*expected_clipped_rect=*/gfx::Rect(10, 15, 15, 15)); -} - -TEST_F(PdfViewWebPluginTest, - UpdateLayerTransformWithTranslateUseZoomForDSFEnabled) { - EXPECT_CALL(*client_ptr_, IsUseZoomForDSFEnabled) - .WillRepeatedly(Return(true)); - +TEST_F(PdfViewWebPluginTest, UpdateLayerTransformWithTranslate) { plugin_->UpdateLayerTransform(1.0f, gfx::Vector2dF(-1.25, 1.25)); TestPaintSnapshots(/*device_scale=*/4.0f, /*window_rect=*/gfx::Rect(10, 10, 20, 20), @@ -624,23 +596,7 @@ TEST_F(PdfViewWebPluginTest, /*expected_clipped_rect=*/gfx::Rect(10, 15, 15, 15)); } -TEST_F(PdfViewWebPluginTest, - UpdateLayerTransformWithScaleAndTranslateUseZoomForDSFDisabled) { - EXPECT_CALL(*client_ptr_, IsUseZoomForDSFEnabled) - .WillRepeatedly(Return(false)); - - plugin_->UpdateLayerTransform(0.5f, gfx::Vector2dF(-5, 5)); - TestPaintSnapshots(/*device_scale=*/4.0f, - /*window_rect=*/gfx::Rect(10, 10, 20, 20), - /*paint_rect=*/gfx::Rect(10, 10, 20, 20), - /*expected_clipped_rect=*/gfx::Rect(10, 15, 5, 10)); -} - -TEST_F(PdfViewWebPluginTest, - UpdateLayerTransformWithScaleAndTranslateUseZoomForDSFEnabled) { - EXPECT_CALL(*client_ptr_, IsUseZoomForDSFEnabled) - .WillRepeatedly(Return(true)); - +TEST_F(PdfViewWebPluginTest, UpdateLayerTransformWithScaleAndTranslate) { plugin_->UpdateLayerTransform(0.5f, gfx::Vector2dF(-1.25, 1.25)); TestPaintSnapshots(/*device_scale=*/4.0f, /*window_rect=*/gfx::Rect(10, 10, 20, 20), @@ -648,10 +604,6 @@ TEST_F(PdfViewWebPluginTest, /*expected_clipped_rect=*/gfx::Rect(10, 15, 5, 10)); } -INSTANTIATE_TEST_SUITE_P(All, - PdfViewWebPluginTestUseZoomForDSF, - testing::Bool()); - class PdfViewWebPluginMouseEventsTest : public PdfViewWebPluginTest { public: class TestPDFiumEngineForMouseEvents : public TestPDFiumEngine { @@ -690,11 +642,7 @@ class PdfViewWebPluginMouseEventsTest : public PdfViewWebPluginTest { } }; -TEST_F(PdfViewWebPluginMouseEventsTest, - HandleInputEventWithUseZoomForDSFEnabled) { - // Test when using zoom for DSF is enabled. - EXPECT_CALL(*client_ptr_, IsUseZoomForDSFEnabled) - .WillRepeatedly(Return(true)); +TEST_F(PdfViewWebPluginMouseEventsTest, HandleInputEvent) { wrapper_ptr_->set_device_scale(kDeviceScale); UpdatePluginGeometry(kDeviceScale, gfx::Rect(20, 20)); @@ -709,25 +657,6 @@ TEST_F(PdfViewWebPluginMouseEventsTest, EXPECT_EQ(gfx::PointF(-10.0f, 0.0f), event->PositionInWidget()); } -TEST_F(PdfViewWebPluginMouseEventsTest, - HandleInputEventWithUseZoomForDSFDisabled) { - // Test when using zoom for DSF is disabled. - EXPECT_CALL(*client_ptr_, IsUseZoomForDSFEnabled) - .WillRepeatedly(Return(false)); - wrapper_ptr_->set_device_scale(kDeviceScale); - UpdatePluginGeometry(kDeviceScale, gfx::Rect(20, 20)); - - ui::Cursor dummy_cursor; - plugin_->HandleInputEvent( - blink::WebCoalescedInputEvent(CreateDefaultMouseDownEvent(), - ui::LatencyInfo()), - &dummy_cursor); - - const blink::WebMouseEvent* event = engine()->GetScaledMouseEvent(); - ASSERT_TRUE(event); - EXPECT_EQ(gfx::PointF(-20.0f, 0.0f), event->PositionInWidget()); -} - class PdfViewWebPluginImeTest : public PdfViewWebPluginTest { public: void TestImeSetCompositionForPlugin(const blink::WebString& text) { @@ -939,9 +868,7 @@ TEST_F(PdfViewWebPluginTest, ShouldDispatchImeEventsToPlugin) { ASSERT_TRUE(plugin_->ShouldDispatchImeEventsToPlugin()); } -TEST_F(PdfViewWebPluginTest, CaretChangeUseZoomForDSFEnabled) { - EXPECT_CALL(*client_ptr_, IsUseZoomForDSFEnabled) - .WillRepeatedly(Return(true)); +TEST_F(PdfViewWebPluginTest, CaretChange) { EXPECT_CALL(*engine_ptr_, ZoomUpdated(2.0f)); UpdatePluginGeometry( /*device_scale=*/2.0f, /*window_rect=*/gfx::Rect(12, 24, 36, 48)); @@ -949,16 +876,6 @@ TEST_F(PdfViewWebPluginTest, CaretChangeUseZoomForDSFEnabled) { EXPECT_EQ(gfx::Rect(28, 20, 30, 40), plugin_->GetPluginCaretBounds()); } -TEST_F(PdfViewWebPluginTest, CaretChangeUseZoomForDSFDisabled) { - EXPECT_CALL(*client_ptr_, IsUseZoomForDSFEnabled) - .WillRepeatedly(Return(false)); - EXPECT_CALL(*engine_ptr_, ZoomUpdated(2.0f)); - UpdatePluginGeometry( - /*device_scale=*/2.0f, /*window_rect=*/gfx::Rect(12, 24, 36, 48)); - plugin_->CaretChanged(gfx::Rect(10, 20, 30, 40)); - EXPECT_EQ(gfx::Rect(23, 10, 15, 20), plugin_->GetPluginCaretBounds()); -} - TEST_F(PdfViewWebPluginTest, NotifyNumberOfFindResultsChanged) { plugin_->StartFind("x", /*case_sensitive=*/false, /*identifier=*/123); @@ -970,4 +887,196 @@ TEST_F(PdfViewWebPluginTest, NotifyNumberOfFindResultsChanged) { plugin_->NotifyNumberOfFindResultsChanged(/*total=*/5, /*final_result=*/true); } +class PdfViewWebPluginWithoutDocInfoTest : public PdfViewWebPluginTest { + public: + std::unique_ptr<UrlLoader> CreateLoader() override { + return std::make_unique<NiceMock<MockUrlLoader>>(); + } + + static base::Value::Dict CreateExpectedNoMetadataResponse() { + base::Value::Dict metadata; + metadata.Set("fileSize", "0 B"); + metadata.Set("linearized", false); + metadata.Set("pageSize", "Varies"); + metadata.Set("canSerializeDocument", true); + + base::Value::Dict message; + message.Set("type", "metadata"); + message.Set("metadataData", std::move(metadata)); + return message; + } +}; + +TEST_F(PdfViewWebPluginWithoutDocInfoTest, DocumentLoadCompletePostMessages) { + const base::Value::Dict expect_metadata = CreateExpectedNoMetadataResponse(); + EXPECT_CALL(*wrapper_ptr_, PostMessage); + EXPECT_CALL(*wrapper_ptr_, PostMessage(Eq(std::ref(expect_metadata)))); + plugin_->DocumentLoadComplete(); +} + +class PdfViewWebPluginWithDocInfoTest : public PdfViewWebPluginTest { + public: + class TestPDFiumEngineWithDocInfo : public TestPDFiumEngine { + public: + explicit TestPDFiumEngineWithDocInfo(PDFEngine::Client* client) + : TestPDFiumEngine(client) { + InitializeDocumentAttachments(); + InitializeDocumentMetadata(); + } + + base::Value::List GetBookmarks() override { + // Create `bookmark1` which navigates to an in-doc position. This bookmark + // will be in the top-level bookmark list. + base::Value::Dict bookmark1; + bookmark1.Set("title", "Bookmark 1"); + bookmark1.Set("page", 2); + bookmark1.Set("x", 10); + bookmark1.Set("y", 20); + bookmark1.Set("zoom", 2.0); + + // Create `bookmark2` which navigates to a web page. This bookmark will be + // a child of `bookmark1`. + base::Value::Dict bookmark2; + bookmark2.Set("title", "Bookmark 2"); + bookmark2.Set("uri", "test.com"); + + base::Value::List children_of_bookmark1; + children_of_bookmark1.Append(std::move(bookmark2)); + bookmark1.Set("children", std::move(children_of_bookmark1)); + + // Create the top-level bookmark list. + base::Value::List bookmarks; + bookmarks.Append(std::move(bookmark1)); + return bookmarks; + } + + absl::optional<gfx::Size> GetUniformPageSizePoints() override { + return gfx::Size(1000, 1200); + } + + private: + void InitializeDocumentAttachments() { + doc_attachment_info_list().resize(3); + + // A regular attachment. + doc_attachment_info_list()[0].name = u"attachment1.txt"; + doc_attachment_info_list()[0].creation_date = u"D:20170712214438-07'00'"; + doc_attachment_info_list()[0].modified_date = u"D:20160115091400"; + doc_attachment_info_list()[0].is_readable = true; + doc_attachment_info_list()[0].size_bytes = 13u; + + // An unreadable attachment. + doc_attachment_info_list()[1].name = u"attachment2.pdf"; + doc_attachment_info_list()[1].is_readable = false; + + // A readable attachment that exceeds download size limit. + doc_attachment_info_list()[2].name = u"attachment3.mov"; + doc_attachment_info_list()[2].is_readable = true; + doc_attachment_info_list()[2].size_bytes = + PdfViewPluginBase::kMaximumSavedFileSize + 1; + } + + void InitializeDocumentMetadata() { + metadata().version = PdfVersion::k1_7; + metadata().size_bytes = 13u; + metadata().page_count = 13u; + metadata().linearized = true; + metadata().has_attachments = true; + metadata().tagged = true; + metadata().form_type = FormType::kAcroForm; + metadata().title = "Title"; + metadata().author = "Author"; + metadata().subject = "Subject"; + metadata().keywords = "Keywords"; + metadata().creator = "Creator"; + metadata().producer = "Producer"; + ASSERT_TRUE(base::Time::FromUTCString("2021-05-04 11:12:13", + &metadata().creation_date)); + ASSERT_TRUE(base::Time::FromUTCString("2021-06-04 15:16:17", + &metadata().mod_date)); + } + }; + + std::unique_ptr<TestPDFiumEngine> CreateEngine() override { + return std::make_unique<TestPDFiumEngineWithDocInfo>(plugin_.get()); + } + std::unique_ptr<UrlLoader> CreateLoader() override { + return std::make_unique<NiceMock<MockUrlLoader>>(); + } + + static base::Value::Dict CreateExpectedAttachmentsResponse() { + base::Value::List attachments; + { + base::Value::Dict attachment; + attachment.Set("name", "attachment1.txt"); + attachment.Set("size", 13); + attachment.Set("readable", true); + attachments.Append(std::move(attachment)); + } + { + base::Value::Dict attachment; + attachment.Set("name", "attachment2.pdf"); + attachment.Set("size", 0); + attachment.Set("readable", false); + attachments.Append(std::move(attachment)); + } + { + base::Value::Dict attachment; + attachment.Set("name", "attachment3.mov"); + attachment.Set("size", -1); + attachment.Set("readable", true); + attachments.Append(std::move(attachment)); + } + + base::Value::Dict message; + message.Set("type", "attachments"); + message.Set("attachmentsData", std::move(attachments)); + return message; + } + + static base::Value::Dict CreateExpectedBookmarksResponse( + base::Value::List bookmarks) { + base::Value::Dict message; + message.Set("type", "bookmarks"); + message.Set("bookmarksData", std::move(bookmarks)); + return message; + } + + static base::Value::Dict CreateExpectedMetadataResponse() { + base::Value::Dict metadata; + metadata.Set("version", "1.7"); + metadata.Set("fileSize", "13 B"); + metadata.Set("linearized", true); + + metadata.Set("title", "Title"); + metadata.Set("author", "Author"); + metadata.Set("subject", "Subject"); + metadata.Set("keywords", "Keywords"); + metadata.Set("creator", "Creator"); + metadata.Set("producer", "Producer"); + metadata.Set("creationDate", "5/4/21, 4:12:13 AM"); + metadata.Set("modDate", "6/4/21, 8:16:17 AM"); + metadata.Set("pageSize", "13.89 × 16.67 in (portrait)"); + metadata.Set("canSerializeDocument", true); + + base::Value::Dict message; + message.Set("type", "metadata"); + message.Set("metadataData", std::move(metadata)); + return message; + } +}; + +TEST_F(PdfViewWebPluginWithDocInfoTest, DocumentLoadCompletePostMessages) { + const base::Value::Dict expect_attachments = + CreateExpectedAttachmentsResponse(); + const base::Value::Dict expect_bookmarks = + CreateExpectedBookmarksResponse(engine_ptr_->GetBookmarks()); + const base::Value::Dict expect_metadata = CreateExpectedMetadataResponse(); + EXPECT_CALL(*wrapper_ptr_, PostMessage); + EXPECT_CALL(*wrapper_ptr_, PostMessage(Eq(std::ref(expect_attachments)))); + EXPECT_CALL(*wrapper_ptr_, PostMessage(Eq(std::ref(expect_bookmarks)))); + EXPECT_CALL(*wrapper_ptr_, PostMessage(Eq(std::ref(expect_metadata)))); + plugin_->DocumentLoadComplete(); +} + } // namespace chrome_pdf diff --git a/chromium/pdf/pdfium/DEPS b/chromium/pdf/pdfium/DEPS index cdf6a23128c..cdf346fd37c 100644 --- a/chromium/pdf/pdfium/DEPS +++ b/chromium/pdf/pdfium/DEPS @@ -1,5 +1,6 @@ include_rules = [ "+components/services/font/public/cpp", "+third_party/pdfium/public", + "+ui/accessibility", "+ui/gfx/codec", ] diff --git a/chromium/pdf/pdfium/accessibility_unittest.cc b/chromium/pdf/pdfium/accessibility_unittest.cc index 8280895d9fc..c2d347779bd 100644 --- a/chromium/pdf/pdfium/accessibility_unittest.cc +++ b/chromium/pdf/pdfium/accessibility_unittest.cc @@ -54,7 +54,7 @@ TEST_F(AccessibilityTest, GetAccessibilityPage) { {15, 12, 26.666666f, 189.333328f, 84.000008f, 13.333344f}, {15, 16, 28.000000f, 117.333334f, 152.000000f, 19.999992f}, }; - static_assert(base::size(kExpectedTextRuns) == kExpectedTextRunCount, + static_assert(std::size(kExpectedTextRuns) == kExpectedTextRunCount, "Bad test expectation count"); static constexpr size_t kExpectedCharCount = 30; @@ -66,7 +66,7 @@ TEST_F(AccessibilityTest, GetAccessibilityPage) { {'y', 12}, {'e', 12}, {',', 4}, {' ', 6.6666}, {'w', 16}, {'o', 12}, {'r', 8}, {'l', 4}, {'d', 12}, {'!', 2.6666}, }; - static_assert(base::size(kExpectedChars) == kExpectedCharCount, + static_assert(std::size(kExpectedChars) == kExpectedCharCount, "Bad test expectation count"); TestClient client; @@ -114,9 +114,9 @@ TEST_F(AccessibilityTest, GetAccessibilityPage) { TEST_F(AccessibilityTest, GetAccessibilityImageInfo) { static const AccessibilityImageInfo kExpectedImageInfo[] = { - {"Image 1", 0, {380, 78, 67, 68}}, - {"Image 2", 0, {380, 385, 27, 28}}, - {"Image 3", 0, {380, 678, 1, 1}}}; + {"Image 1", 0, {380, 78, 67, 68}, {}}, + {"Image 2", 0, {380, 385, 27, 28}, {}}, + {"Image 3", 0, {380, 678, 1, 1}, {}}}; TestClient client; std::unique_ptr<PDFiumEngine> engine = @@ -134,7 +134,7 @@ TEST_F(AccessibilityTest, GetAccessibilityImageInfo) { EXPECT_EQ(gfx::Rect(5, 3, 816, 1056), page_info.bounds); EXPECT_EQ(text_runs.size(), page_info.text_run_count); EXPECT_EQ(chars.size(), page_info.char_count); - ASSERT_EQ(page_objects.images.size(), base::size(kExpectedImageInfo)); + ASSERT_EQ(page_objects.images.size(), std::size(kExpectedImageInfo)); for (size_t i = 0; i < page_objects.images.size(); ++i) { EXPECT_EQ(page_objects.images[i].alt_text, kExpectedImageInfo[i].alt_text); @@ -452,7 +452,7 @@ TEST_F(AccessibilityTest, GetAccessibilityLinkInfo) { EXPECT_EQ(gfx::Rect(5, 3, 533, 266), page_info.bounds); EXPECT_EQ(text_runs.size(), page_info.text_run_count); EXPECT_EQ(chars.size(), page_info.char_count); - ASSERT_EQ(page_objects.links.size(), base::size(expected_link_info)); + ASSERT_EQ(page_objects.links.size(), std::size(expected_link_info)); for (size_t i = 0; i < page_objects.links.size(); ++i) { const AccessibilityLinkInfo& link_info = page_objects.links[i]; @@ -491,7 +491,7 @@ TEST_F(AccessibilityTest, GetAccessibilityHighlightInfo) { EXPECT_EQ(gfx::Rect(5, 3, 533, 266), page_info.bounds); EXPECT_EQ(text_runs.size(), page_info.text_run_count); EXPECT_EQ(chars.size(), page_info.char_count); - ASSERT_EQ(page_objects.highlights.size(), base::size(kExpectedHighlightInfo)); + ASSERT_EQ(page_objects.highlights.size(), std::size(kExpectedHighlightInfo)); for (size_t i = 0; i < page_objects.highlights.size(); ++i) { const AccessibilityHighlightInfo& highlight_info = @@ -539,7 +539,7 @@ TEST_F(AccessibilityTest, GetAccessibilityTextFieldInfo) { EXPECT_EQ(text_runs.size(), page_info.text_run_count); EXPECT_EQ(chars.size(), page_info.char_count); ASSERT_EQ(page_objects.form_fields.text_fields.size(), - base::size(kExpectedTextFieldInfo)); + std::size(kExpectedTextFieldInfo)); for (size_t i = 0; i < page_objects.form_fields.text_fields.size(); ++i) { const AccessibilityTextFieldInfo& text_field_info = diff --git a/chromium/pdf/pdfium/fuzzers/BUILD.gn b/chromium/pdf/pdfium/fuzzers/BUILD.gn index 7916e221adf..bd4e616dbcd 100644 --- a/chromium/pdf/pdfium/fuzzers/BUILD.gn +++ b/chromium/pdf/pdfium/fuzzers/BUILD.gn @@ -59,9 +59,9 @@ group("pdf_fuzzers") { ":pdf_cfx_barcode_fuzzer", ":pdf_codec_jpeg_fuzzer", ":pdf_css_fuzzer", - ":pdf_fm2js_fuzzer", ":pdf_formcalc_context_fuzzer", ":pdf_formcalc_fuzzer", + ":pdf_formcalc_translate_fuzzer", ":pdfium_xfa_fuzzer", ":pdfium_xfa_lpm_fuzzer", ] @@ -195,10 +195,6 @@ if (pdf_enable_v8) { dict = "dicts/pdf_css.dict" } - pdfium_fuzzer_test("pdf_fm2js_fuzzer") { - dict = "dicts/pdf_formcalc.dict" - } - pdfium_fuzzer_test("pdf_formcalc_context_fuzzer") { dict = "dicts/pdf_xfa_js.dict" } @@ -207,6 +203,10 @@ if (pdf_enable_v8) { dict = "dicts/pdf_formcalc.dict" } + pdfium_fuzzer_test("pdf_formcalc_translate_fuzzer") { + dict = "dicts/pdf_formcalc.dict" + } + if (pdf_enable_xfa_gif) { pdfium_fuzzer_test("pdf_lzw_fuzzer") { } diff --git a/chromium/pdf/pdfium/pdfium_assert_matching_enums.cc b/chromium/pdf/pdfium/pdfium_assert_matching_enums.cc index 5f21e49d5bb..fa3671a668b 100644 --- a/chromium/pdf/pdfium/pdfium_assert_matching_enums.cc +++ b/chromium/pdf/pdfium/pdfium_assert_matching_enums.cc @@ -6,9 +6,6 @@ #include "pdf/accessibility_structs.h" #include "pdf/content_restriction.h" #include "pdf/document_metadata.h" -#include "ppapi/c/pp_input_event.h" -#include "ppapi/c/private/ppb_pdf.h" -#include "ppapi/c/private/ppp_pdf.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/pdfium/public/fpdf_edit.h" #include "third_party/pdfium/public/fpdf_formfill.h" @@ -216,47 +213,12 @@ STATIC_ASSERT_ENUM(ui::VKEY_PA1, FWL_VKEY_PA1); STATIC_ASSERT_ENUM(ui::VKEY_OEM_CLEAR, FWL_VKEY_OEM_Clear); STATIC_ASSERT_ENUM(ui::VKEY_UNKNOWN, FWL_VKEY_Unknown); -STATIC_ASSERT_ENUM(PP_PRIVATEFONTCHARSET_ANSI, FXFONT_ANSI_CHARSET); -STATIC_ASSERT_ENUM(PP_PRIVATEFONTCHARSET_DEFAULT, FXFONT_DEFAULT_CHARSET); -STATIC_ASSERT_ENUM(PP_PRIVATEFONTCHARSET_SYMBOL, FXFONT_SYMBOL_CHARSET); -STATIC_ASSERT_ENUM(PP_PRIVATEFONTCHARSET_SHIFTJIS, FXFONT_SHIFTJIS_CHARSET); -STATIC_ASSERT_ENUM(PP_PRIVATEFONTCHARSET_HANGUL, FXFONT_HANGEUL_CHARSET); -STATIC_ASSERT_ENUM(PP_PRIVATEFONTCHARSET_GB2312, FXFONT_GB2312_CHARSET); -STATIC_ASSERT_ENUM(PP_PRIVATEFONTCHARSET_CHINESEBIG5, - FXFONT_CHINESEBIG5_CHARSET); - -STATIC_ASSERT_ENUM(PP_PRIVATEDUPLEXMODE_NONE, DuplexUndefined); -STATIC_ASSERT_ENUM(PP_PRIVATEDUPLEXMODE_SIMPLEX, Simplex); -STATIC_ASSERT_ENUM(PP_PRIVATEDUPLEXMODE_SHORT_EDGE, DuplexFlipShortEdge); -STATIC_ASSERT_ENUM(PP_PRIVATEDUPLEXMODE_LONG_EDGE, DuplexFlipLongEdge); - -STATIC_ASSERT_ENUM(PP_TEXTRENDERINGMODE_UNKNOWN, FPDF_TEXTRENDERMODE_UNKNOWN); -STATIC_ASSERT_ENUM(PP_TEXTRENDERINGMODE_FIRST, FPDF_TEXTRENDERMODE_UNKNOWN); -STATIC_ASSERT_ENUM(PP_TEXTRENDERINGMODE_FILL, FPDF_TEXTRENDERMODE_FILL); -STATIC_ASSERT_ENUM(PP_TEXTRENDERINGMODE_STROKE, FPDF_TEXTRENDERMODE_STROKE); -STATIC_ASSERT_ENUM(PP_TEXTRENDERINGMODE_FILLSTROKE, - FPDF_TEXTRENDERMODE_FILL_STROKE); -STATIC_ASSERT_ENUM(PP_TEXTRENDERINGMODE_INVISIBLE, - FPDF_TEXTRENDERMODE_INVISIBLE); -STATIC_ASSERT_ENUM(PP_TEXTRENDERINGMODE_FILLCLIP, - FPDF_TEXTRENDERMODE_FILL_CLIP); -STATIC_ASSERT_ENUM(PP_TEXTRENDERINGMODE_STROKECLIP, - FPDF_TEXTRENDERMODE_STROKE_CLIP); -STATIC_ASSERT_ENUM(PP_TEXTRENDERINGMODE_FILLSTROKECLIP, - FPDF_TEXTRENDERMODE_FILL_STROKE_CLIP); -STATIC_ASSERT_ENUM(PP_TEXTRENDERINGMODE_CLIP, FPDF_TEXTRENDERMODE_CLIP); -STATIC_ASSERT_ENUM(PP_TEXTRENDERINGMODE_LAST, FPDF_TEXTRENDERMODE_LAST); - STATIC_ASSERT_ENUM(FormType::kNone, FORMTYPE_NONE); STATIC_ASSERT_ENUM(FormType::kAcroForm, FORMTYPE_ACRO_FORM); STATIC_ASSERT_ENUM(FormType::kXFAFull, FORMTYPE_XFA_FULL); STATIC_ASSERT_ENUM(FormType::kXFAForeground, FORMTYPE_XFA_FOREGROUND); STATIC_ASSERT_ENUM(FormType::kMaxValue, FORMTYPE_COUNT - 1); -STATIC_ASSERT_ENUM(PP_PRIVATEBUTTON_PUSHBUTTON, FPDF_FORMFIELD_PUSHBUTTON); -STATIC_ASSERT_ENUM(PP_PRIVATEBUTTON_CHECKBOX, FPDF_FORMFIELD_CHECKBOX); -STATIC_ASSERT_ENUM(PP_PRIVATEBUTTON_RADIOBUTTON, FPDF_FORMFIELD_RADIOBUTTON); - #if BUILDFLAG(IS_WIN) STATIC_ASSERT_ENUM(kEmf, FPDF_PRINTMODE_EMF); STATIC_ASSERT_ENUM(kTextOnly, FPDF_PRINTMODE_TEXTONLY); diff --git a/chromium/pdf/pdfium/pdfium_engine.cc b/chromium/pdf/pdfium/pdfium_engine.cc index 0f8171dd0dd..c015d4b06a4 100644 --- a/chromium/pdf/pdfium/pdfium_engine.cc +++ b/chromium/pdf/pdfium/pdfium_engine.cc @@ -48,8 +48,6 @@ #include "pdf/pdfium/pdfium_mem_buffer_file_write.h" #include "pdf/pdfium/pdfium_permissions.h" #include "pdf/pdfium/pdfium_unsupported_features.h" -#include "pdf/ppapi_migration/bitmap.h" -#include "pdf/ppapi_migration/geometry_conversions.h" #include "pdf/ppapi_migration/url_loader.h" #include "pdf/url_loader_wrapper_impl.h" #include "printing/mojom/print.mojom-shared.h" @@ -550,9 +548,6 @@ PDFiumEngine::PDFiumEngine(PDFEngine::Client* client, IFSDK_PAUSE::version = 1; IFSDK_PAUSE::user = nullptr; IFSDK_PAUSE::NeedToPauseNow = Pause_NeedToPauseNow; - - // PreviewModeClient does not know its pp::Instance. - SetLastInstance(); } PDFiumEngine::~PDFiumEngine() { @@ -593,11 +588,9 @@ void PDFiumEngine::PluginSizeUpdated(const gfx::Size& size) { // asynchronously to avoid observable differences between this path and the // normal loading path. document_pending_ = false; - client_->ScheduleTaskOnMainThread( - FROM_HERE, - base::BindOnce(&PDFiumEngine::FinishLoadingDocument, - weak_factory_.GetWeakPtr()), - /*result=*/0, base::TimeDelta()); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(&PDFiumEngine::FinishLoadingDocument, + weak_factory_.GetWeakPtr())); } } @@ -824,7 +817,7 @@ void PDFiumEngine::OnNewDataReceived() { void PDFiumEngine::OnDocumentComplete() { if (doc()) - return FinishLoadingDocument(0); + return FinishLoadingDocument(); document_->file_access().m_FileLen = doc_loader_->GetDocumentSize(); if (!fpdf_availability()) { @@ -841,7 +834,7 @@ void PDFiumEngine::OnDocumentCanceled() { OnDocumentComplete(); } -void PDFiumEngine::FinishLoadingDocument(int32_t /*unused_but_required*/) { +void PDFiumEngine::FinishLoadingDocument() { // Note that doc_loader_->IsDocumentComplete() may not be true here if // called via `OnDocumentCanceled()`. DCHECK(doc()); @@ -1016,8 +1009,6 @@ std::vector<uint8_t> PDFiumEngine::PrintPagesAsRasterPdf( KillFormFocus(); - SetLastInstance(); - return print_.PrintPagesAsPdf(page_numbers, print_params); } @@ -1820,11 +1811,10 @@ void PDFiumEngine::StartFind(const std::string& text, bool case_sensitive) { if (doc_loader_set_for_testing_) { ContinueFind(case_sensitive ? 1 : 0); } else { - client_->ScheduleTaskOnMainThread( - FROM_HERE, - base::BindOnce(&PDFiumEngine::ContinueFind, - find_weak_factory_.GetWeakPtr()), - case_sensitive ? 1 : 0, base::TimeDelta()); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(&PDFiumEngine::ContinueFind, + find_weak_factory_.GetWeakPtr(), + case_sensitive ? 1 : 0)); } } @@ -2364,29 +2354,27 @@ int PDFiumEngine::GetNumberOfPages() const { return pages_.size(); } -base::Value PDFiumEngine::GetBookmarks() { - base::Value dict = TraverseBookmarks(nullptr, 0); - DCHECK(dict.is_dict()); +base::Value::List PDFiumEngine::GetBookmarks() { + base::Value::Dict dict = TraverseBookmarks(nullptr, 0); // The root bookmark contains no useful information. - base::Value* children = dict.FindListKey("children"); - DCHECK(children); + base::Value::List* children = dict.FindList("children"); return std::move(*children); } -base::Value PDFiumEngine::TraverseBookmarks(FPDF_BOOKMARK bookmark, - unsigned int depth) { - base::Value dict(base::Value::Type::DICTIONARY); +base::Value::Dict PDFiumEngine::TraverseBookmarks(FPDF_BOOKMARK bookmark, + unsigned int depth) { + base::Value::Dict dict; std::u16string title = CallPDFiumWideStringBufferApi( base::BindRepeating(&FPDFBookmark_GetTitle, bookmark), /*check_expected_size=*/true); - dict.SetStringKey("title", title); + dict.Set("title", title); FPDF_DEST dest = FPDFBookmark_GetDest(doc(), bookmark); // Some bookmarks don't have a page to select. if (dest) { int page_index = FPDFDest_GetDestPageIndex(doc(), dest); if (PageIndexInBounds(page_index)) { - dict.SetIntKey("page", page_index); + dict.Set("page", page_index); absl::optional<float> x; absl::optional<float> y; @@ -2394,11 +2382,11 @@ base::Value PDFiumEngine::TraverseBookmarks(FPDF_BOOKMARK bookmark, pages_[page_index]->GetPageDestinationTarget(dest, &x, &y, &zoom); if (x) - dict.SetIntKey("x", static_cast<int>(x.value())); + dict.Set("x", static_cast<int>(x.value())); if (y) - dict.SetIntKey("y", static_cast<int>(y.value())); + dict.Set("y", static_cast<int>(y.value())); if (zoom) - dict.SetDoubleKey("zoom", zoom.value()); + dict.Set("zoom", static_cast<double>(zoom.value())); } } else { // Extract URI for bookmarks linking to an external page. @@ -2407,10 +2395,10 @@ base::Value PDFiumEngine::TraverseBookmarks(FPDF_BOOKMARK bookmark, base::BindRepeating(&FPDFAction_GetURIPath, doc(), action), /*check_expected_size=*/true); if (!uri.empty()) - dict.SetStringKey("uri", uri); + dict.Set("uri", uri); } - base::Value children(base::Value::Type::LIST); + base::Value::List children; // Don't trust PDFium to handle circular bookmarks. constexpr unsigned int kMaxDepth = 128; @@ -2427,7 +2415,7 @@ base::Value PDFiumEngine::TraverseBookmarks(FPDF_BOOKMARK bookmark, children.Append(TraverseBookmarks(child_bookmark, depth + 1)); } } - dict.SetKey("children", std::move(children)); + dict.Set("children", std::move(children)); return dict; } @@ -2592,10 +2580,7 @@ absl::optional<AccessibilityTextRunInfo> PDFiumEngine::GetTextRunInfo( int page_index, int start_char_index) { DCHECK(PageIndexInBounds(page_index)); - auto info = pages_[page_index]->GetTextRunInfo(start_char_index); - if (!client_->IsPrintPreview() && start_char_index >= 0) - pages_[page_index]->LogOverlappingAnnotations(); - return info; + return pages_[page_index]->GetTextRunInfo(start_char_index); } std::vector<AccessibilityLinkInfo> PDFiumEngine::GetLinkInfo( @@ -2794,7 +2779,7 @@ void PDFiumEngine::ContinueLoadingDocument(const std::string& password) { LoadBody(); if (doc_loader_->IsDocumentComplete()) - FinishLoadingDocument(0); + FinishLoadingDocument(); } void PDFiumEngine::LoadPageInfo() { @@ -2951,7 +2936,7 @@ void PDFiumEngine::LoadForm() { static constexpr FPDF_ANNOTATION_SUBTYPE kFocusableAnnotSubtypes[] = { FPDF_ANNOT_LINK, FPDF_ANNOT_HIGHLIGHT, FPDF_ANNOT_WIDGET}; FPDF_BOOL ret = FPDFAnnot_SetFocusableSubtypes( - form(), kFocusableAnnotSubtypes, base::size(kFocusableAnnotSubtypes)); + form(), kFocusableAnnotSubtypes, std::size(kFocusableAnnotSubtypes)); DCHECK(ret); } } @@ -3113,10 +3098,11 @@ void PDFiumEngine::InsetPage(const DocumentLayout::Options& layout_options, gfx::Rect& rect) const { draw_utils::PageInsetSizes inset_sizes = GetInsetSizes(layout_options, page_index, num_of_pages); - rect.Inset(static_cast<int>(ceil(inset_sizes.left * multiplier)), - static_cast<int>(ceil(inset_sizes.top * multiplier)), - static_cast<int>(ceil(inset_sizes.right * multiplier)), - static_cast<int>(ceil(inset_sizes.bottom * multiplier))); + rect.Inset(gfx::Insets::TLBR( + static_cast<int>(ceil(inset_sizes.top * multiplier)), + static_cast<int>(ceil(inset_sizes.left * multiplier)), + static_cast<int>(ceil(inset_sizes.bottom * multiplier)), + static_cast<int>(ceil(inset_sizes.right * multiplier)))); } absl::optional<size_t> PDFiumEngine::GetAdjacentPageIndexForTwoUpView( @@ -3149,7 +3135,6 @@ bool PDFiumEngine::ContinuePaint(int progressive_index, SkBitmap& image_data) { DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size()); last_progressive_start_time_ = base::Time::Now(); - SetLastInstance(); int page_index = progressive_paints_[progressive_index].page_index(); DCHECK(PageIndexInBounds(page_index)); @@ -3568,7 +3553,7 @@ PDFiumEngine::SelectionChangeInvalidator::GetVisibleSelections() const { void PDFiumEngine::SelectionChangeInvalidator::Invalidate( const gfx::Rect& selection) { gfx::Rect expanded_selection = selection; - expanded_selection.Inset(-1, -1); + expanded_selection.Inset(-1); engine_->client_->Invalidate(expanded_selection); } @@ -3647,7 +3632,6 @@ void PDFiumEngine::SetCurrentPage(int index) { FORM_DoPageAAction(old_page, form(), FPDFPAGE_AACTION_CLOSE); } most_visible_page_ = index; - SetLastInstance(); if (most_visible_page_ != -1 && called_do_document_action_) { FPDF_PAGE new_page = pages_[most_visible_page_]->GetPage(); FORM_DoPageAAction(new_page, form(), FPDFPAGE_AACTION_OPEN); @@ -4316,10 +4300,6 @@ void PDFiumEngine::MaybeRequestPendingThumbnail(int page_index) { pending_thumbnails_.erase(it); } -void PDFiumEngine::SetLastInstance() { - client_->SetLastPluginInstance(); -} - PDFiumEngine::ProgressivePaint::ProgressivePaint(int index, const gfx::Rect& rect) : page_index_(index), rect_(rect) {} diff --git a/chromium/pdf/pdfium/pdfium_engine.h b/chromium/pdf/pdfium/pdfium_engine.h index 4e91b64891f..3c6f6b44aca 100644 --- a/chromium/pdf/pdfium/pdfium_engine.h +++ b/chromium/pdf/pdfium/pdfium_engine.h @@ -136,7 +136,7 @@ class PDFiumEngine : public PDFEngine, std::vector<uint8_t> GetAttachmentData(size_t index) override; const DocumentMetadata& GetDocumentMetadata() const override; int GetNumberOfPages() const override; - base::Value GetBookmarks() override; + base::Value::List GetBookmarks() override; absl::optional<PDFEngine::NamedDestination> GetNamedDestination( const std::string& destination) override; int GetMostVisiblePage() override; @@ -294,7 +294,7 @@ class PDFiumEngine : public PDFEngine, // This should only be called after `doc_` has been loaded and the document is // fully downloaded. // If this has been run once, it will not notify the client again. - void FinishLoadingDocument(int32_t /*unused_but_required*/); + void FinishLoadingDocument(); // Loads information about the pages in the document and performs layout. void LoadPageInfo(); @@ -575,11 +575,12 @@ class PDFiumEngine : public PDFEngine, void KillTouchTimer(); void HandleLongPress(const blink::WebTouchEvent& event); - // Returns a base::Value (representing a bookmark), which in turn contains - // child base::Value dictionaries (representing the child bookmarks). - // If nullptr is passed in as the bookmark then we traverse from the "root". - // Note that the "root" bookmark contains no useful information. - base::Value TraverseBookmarks(FPDF_BOOKMARK bookmark, unsigned int depth); + // Returns a dictionary representing a bookmark, which in turn contains child + // dictionaries representing the child bookmarks. If `bookmark` is null, then + // this method traverses from the root of the bookmarks tree. Note that the + // root bookmark contains no useful information. + base::Value::Dict TraverseBookmarks(FPDF_BOOKMARK bookmark, + unsigned int depth); void ScrollBasedOnScrollAlignment( const gfx::Rect& scroll_rect, @@ -651,10 +652,6 @@ class PDFiumEngine : public PDFEngine, // requests the thumbnail for that page. void MaybeRequestPendingThumbnail(int page_index); - // Keeps track of the most recently used plugin instance. - // TODO(crbug.com/702993): Remove when PPAPI is gone. - void SetLastInstance(); - const raw_ptr<PDFEngine::Client> client_; // The current document layout. diff --git a/chromium/pdf/pdfium/pdfium_engine_exports.cc b/chromium/pdf/pdfium/pdfium_engine_exports.cc index a3aadad71a7..7e705ec8919 100644 --- a/chromium/pdf/pdfium/pdfium_engine_exports.cc +++ b/chromium/pdf/pdfium/pdfium_engine_exports.cc @@ -160,23 +160,23 @@ base::Value RecursiveGetStructTree(FPDF_STRUCTELEMENT struct_elem) { if (!opt_type) return base::Value(base::Value::Type::NONE); - base::Value result(base::Value::Type::DICTIONARY); - result.SetStringKey("type", *opt_type); + base::Value::Dict result; + result.Set("type", *opt_type); absl::optional<std::u16string> opt_alt = CallPDFiumWideStringBufferApiAndReturnOptional( base::BindRepeating(FPDF_StructElement_GetAltText, struct_elem), true); if (opt_alt) - result.SetStringKey("alt", *opt_alt); + result.Set("alt", *opt_alt); absl::optional<std::u16string> opt_lang = CallPDFiumWideStringBufferApiAndReturnOptional( base::BindRepeating(FPDF_StructElement_GetLang, struct_elem), true); if (opt_lang) - result.SetStringKey("lang", *opt_lang); + result.Set("lang", *opt_lang); - base::Value children(base::Value::Type::LIST); + base::Value::List children; for (int i = 0; i < children_count; i++) { FPDF_STRUCTELEMENT child_elem = FPDF_StructElement_GetChildAtIndex(struct_elem, i); @@ -189,10 +189,10 @@ base::Value RecursiveGetStructTree(FPDF_STRUCTELEMENT struct_elem) { // use "~children" instead of "children" because we pretty-print the // result of this as JSON and the keys are sorted; it's much easier to // understand when the children are the last key. - if (!children.GetListDeprecated().empty()) - result.SetKey("~children", std::move(children)); + if (!children.empty()) + result.Set("~children", std::move(children)); - return result; + return base::Value(std::move(result)); } } // namespace diff --git a/chromium/pdf/pdfium/pdfium_engine_unittest.cc b/chromium/pdf/pdfium/pdfium_engine_unittest.cc index 465c2ab7836..fcb71e80b41 100644 --- a/chromium/pdf/pdfium/pdfium_engine_unittest.cc +++ b/chromium/pdf/pdfium/pdfium_engine_unittest.cc @@ -10,11 +10,13 @@ #include "base/callback.h" #include "base/hash/md5.h" +#include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/test/gmock_move_support.h" #include "base/test/gtest_util.h" #include "base/test/mock_callback.h" #include "base/test/scoped_feature_list.h" +#include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "build/build_config.h" #include "pdf/document_attachment_info.h" @@ -23,7 +25,6 @@ #include "pdf/pdf_features.h" #include "pdf/pdfium/pdfium_page.h" #include "pdf/pdfium/pdfium_test_base.h" -#include "pdf/ppapi_migration/callback.h" #include "pdf/test/test_client.h" #include "pdf/test/test_document_loader.h" #include "pdf/ui/thumbnail.h" @@ -73,13 +74,6 @@ class MockTestClient : public TestClient { (const DocumentLayout& layout), (override)); MOCK_METHOD(void, ScrollToPage, (int page), (override)); - MOCK_METHOD(void, - ScheduleTaskOnMainThread, - (const base::Location& from_here, - ResultCallback callback, - int32_t result, - base::TimeDelta delay), - (override)); MOCK_METHOD(void, DocumentFocusChanged, (bool), (override)); MOCK_METHOD(void, SetLinkUnderCursor, (const std::string&), (override)); }; @@ -134,15 +128,13 @@ class PDFiumEngineTest : public PDFiumTestBase { return loaded_incrementally; } - void FinishWithPluginSizeUpdated(MockTestClient& client, - PDFiumEngine& engine) { - ResultCallback callback; - EXPECT_CALL(client, ScheduleTaskOnMainThread) - .WillOnce(MoveArg<1>(&callback)); + void FinishWithPluginSizeUpdated(PDFiumEngine& engine) { engine.PluginSizeUpdated({}); - ASSERT_TRUE(callback); - std::move(callback).Run(0); + base::RunLoop run_loop; + base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, + run_loop.QuitClosure()); + run_loop.Run(); } // Counts the number of available pages. Returns `int` instead of `size_t` for @@ -279,7 +271,7 @@ TEST_F(PDFiumEngineTest, ApplyDocumentLayoutBeforePluginSizeUpdated) { EXPECT_EQ(gfx::Size(343, 1664), engine.ApplyDocumentLayout(options)); EXPECT_CALL(client, ScrollToPage(-1)).Times(1); - ASSERT_NO_FATAL_FAILURE(FinishWithPluginSizeUpdated(client, engine)); + FinishWithPluginSizeUpdated(engine); } TEST_F(PDFiumEngineTest, ApplyDocumentLayoutAvoidsInfiniteLoop) { @@ -511,7 +503,7 @@ TEST_F(PDFiumEngineTest, PluginSizeUpdatedAfterLoad) { PDFiumEngine& engine = *initialize_result.engine; initialize_result.FinishLoading(); - ASSERT_NO_FATAL_FAILURE(FinishWithPluginSizeUpdated(client, engine)); + FinishWithPluginSizeUpdated(engine); EXPECT_EQ(engine.GetNumberOfPages(), CountAvailablePages(engine)); } diff --git a/chromium/pdf/pdfium/pdfium_font_linux.cc b/chromium/pdf/pdfium/pdfium_font_linux.cc index f24c26d7de1..1cb3756011a 100644 --- a/chromium/pdf/pdfium/pdfium_font_linux.cc +++ b/chromium/pdf/pdfium/pdfium_font_linux.cc @@ -18,7 +18,6 @@ #include "components/services/font/public/cpp/font_loader.h" #include "pdf/font_table_linux.h" #include "pdf/pdfium/pdfium_engine.h" -#include "pdf/ppapi_migration/pdfium_font_linux.h" #include "third_party/blink/public/platform/web_font_description.h" #include "third_party/pdfium/public/fpdf_sysfontinfo.h" @@ -46,12 +45,19 @@ class BlinkFontMapper { FontId MapFont(const blink::WebFontDescription& desc, int charset) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + // If there was never a SkFontConfigInterface::SetGlobal() call, then `fci` + // defaults to the direct interface, which is not suitable, as it does not + // provide MatchFontWithFallback(). This only happens in unit tests, so just + // refuse to map fonts there. + auto* fci = SkFontConfigInterface::RefGlobal().get(); + if (fci == SkFontConfigInterface::GetSingletonDirectInterface()) + return nullptr; + auto font_file = std::make_unique<base::File>(); // In RendererBlinkPlatform, SkFontConfigInterface::SetGlobal() only ever // sets the global to a FontLoader. Thus it is safe to assume the returned // result is just that. - auto* font_loader = reinterpret_cast<font_service::FontLoader*>( - SkFontConfigInterface::RefGlobal().get()); + auto* font_loader = reinterpret_cast<font_service::FontLoader*>(fci); font_loader->MatchFontWithFallback( desc.family.Utf8(), desc.weight >= blink::WebFontDescription::kWeightBold, desc.italic, @@ -204,7 +210,7 @@ void* MapFont(FPDF_SYSFONTINFO*, // Map from the standard PDF fonts to TrueType font names. size_t i; - for (i = 0; i < base::size(kPdfFontSubstitutions); ++i) { + for (i = 0; i < std::size(kPdfFontSubstitutions); ++i) { if (strcmp(face, kPdfFontSubstitutions[i].pdf_name) == 0) { font_family = kPdfFontSubstitutions[i].face; if (kPdfFontSubstitutions[i].bold) @@ -215,7 +221,7 @@ void* MapFont(FPDF_SYSFONTINFO*, } } - if (i == base::size(kPdfFontSubstitutions)) { + if (i == std::size(kPdfFontSubstitutions)) { // Convert to UTF-8 and make sure it is valid. std::string face_utf8; if (base::IsStringUTF8(face)) { @@ -236,9 +242,6 @@ void* MapFont(FPDF_SYSFONTINFO*, desc.italic = italic > 0; } - if (PDFiumEngine::GetFontMappingMode() == FontMappingMode::kPepper) - return MapPepperFont(desc, font_family, charset); - DCHECK_EQ(PDFiumEngine::GetFontMappingMode(), FontMappingMode::kBlink); desc.family = blink::WebString::FromUTF8(font_family); return GetBlinkFontMapper().MapFont(desc, charset); @@ -249,19 +252,11 @@ unsigned long GetFontData(FPDF_SYSFONTINFO*, unsigned int table, unsigned char* buffer, unsigned long buf_size) { - if (PDFiumEngine::GetFontMappingMode() == FontMappingMode::kPepper) - return GetPepperFontData(font_id, table, buffer, buf_size); - DCHECK_EQ(PDFiumEngine::GetFontMappingMode(), FontMappingMode::kBlink); return GetBlinkFontMapper().GetFontData(font_id, table, buffer, buf_size); } void DeleteFont(FPDF_SYSFONTINFO*, void* font_id) { - if (PDFiumEngine::GetFontMappingMode() == FontMappingMode::kPepper) { - DeletePepperFont(font_id); - return; - } - DCHECK_EQ(PDFiumEngine::GetFontMappingMode(), FontMappingMode::kBlink); GetBlinkFontMapper().DeleteFont(font_id); } diff --git a/chromium/pdf/pdfium/pdfium_form_filler_unittest.cc b/chromium/pdf/pdfium/pdfium_form_filler_unittest.cc index 9a0401938f4..76927d48e02 100644 --- a/chromium/pdf/pdfium/pdfium_form_filler_unittest.cc +++ b/chromium/pdf/pdfium/pdfium_form_filler_unittest.cc @@ -6,7 +6,6 @@ #include <vector> -#include "base/cxx17_backports.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "gin/public/isolate_holder.h" @@ -227,7 +226,7 @@ TEST_F(FormFillerJavaScriptTest, IsolateScoping) { TEST_F(FormFillerJavaScriptTest, GetFilePath) { constexpr char kTestPath[] = "https://www.example.com/path/to/the.pdf"; - constexpr int kTestPathSize = static_cast<int>(base::size(kTestPath)); + constexpr int kTestPathSize = static_cast<int>(std::size(kTestPath)); FormFillerTestClient client; EXPECT_CALL(client, GetURL).Times(2).WillRepeatedly(Return(kTestPath)); @@ -258,7 +257,7 @@ TEST_F(FormFillerJavaScriptTest, GetFilePathEmpty) { TEST_F(FormFillerJavaScriptTest, GetFilePathShortBuffer) { constexpr char kTestPath[] = "https://www.example.com/path/to/the.pdf"; - constexpr int kTestPathSize = static_cast<int>(base::size(kTestPath)); + constexpr int kTestPathSize = static_cast<int>(std::size(kTestPath)); FormFillerTestClient client; EXPECT_CALL(client, GetURL).WillRepeatedly(Return(kTestPath)); diff --git a/chromium/pdf/pdfium/pdfium_page.cc b/chromium/pdf/pdfium/pdfium_page.cc index ee556eb2dce..91fbadf2a5a 100644 --- a/chromium/pdf/pdfium/pdfium_page.cc +++ b/chromium/pdf/pdfium/pdfium_page.cc @@ -26,12 +26,14 @@ #include "pdf/pdfium/pdfium_api_string_buffer_adapter.h" #include "pdf/pdfium/pdfium_engine.h" #include "pdf/pdfium/pdfium_unsupported_features.h" -#include "pdf/ppapi_migration/geometry_conversions.h" #include "pdf/ui/thumbnail.h" #include "printing/units.h" #include "third_party/pdfium/public/cpp/fpdf_scopers.h" #include "third_party/pdfium/public/fpdf_annot.h" #include "third_party/pdfium/public/fpdf_catalog.h" +#include "third_party/skia/include/core/SkImageInfo.h" +#include "third_party/skia/include/core/SkPixmap.h" +#include "ui/accessibility/accessibility_features.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/rect.h" @@ -192,64 +194,6 @@ bool FloatEquals(float f1, float f2) { kEpsilonScale * fmaxf(fmaxf(fabsf(f1), fabsf(f2)), kEpsilonScale); } -// Count overlaps across text annotations. -template <typename T, typename U> -uint32_t CountOverlaps(const std::vector<T>& first_set, - const std::vector<U>& second_set) { - // This method assumes vectors passed are sorted by `start_char_index`. - uint32_t overlaps = 0; - // Count overlaps between `first_set` and `second_set`. - for (const auto& first_set_object : first_set) { - gfx::Range first_range( - first_set_object.start_char_index, - first_set_object.start_char_index + first_set_object.char_count); - for (const auto& second_set_object : second_set) { - gfx::Range second_range( - second_set_object.start_char_index, - second_set_object.start_char_index + second_set_object.char_count); - if (first_range.Intersects(second_range)) { - overlaps++; - } else if (first_range.start() < second_range.start()) { - // Both range vectors are sorted by `start_char_index`. In case they - // don't overlap, and the `second_range` starts after the `first_range`, - // then all successive `second_set_object` will not overlap with - // `first_range`. - break; - } - } - } - return overlaps; -} - -// Count overlaps within text annotations. -template <typename T> -uint32_t CountInternalTextOverlaps(const std::vector<T>& text_objects) { - // This method assumes text_objects is sorted by `start_char_index`. - uint32_t overlaps = 0; - for (size_t i = 0; i < text_objects.size(); ++i) { - gfx::Range range1( - text_objects[i].start_char_index, - text_objects[i].start_char_index + text_objects[i].char_count); - for (size_t j = i + 1; j < text_objects.size(); ++j) { - DCHECK_GE(text_objects[j].start_char_index, - text_objects[i].start_char_index); - gfx::Range range2( - text_objects[j].start_char_index, - text_objects[j].start_char_index + text_objects[j].char_count); - if (range1.Intersects(range2)) { - overlaps++; - } else { - // The input is sorted by `start_char_index`. In case `range1` and - // `range2` do not overlap, and `range2` starts after `range1`, then - // successive ranges in the inner loop will also not overlap with - // `range1`. - break; - } - } - } - return overlaps; -} - bool IsRadioButtonOrCheckBox(int button_type) { return button_type == FPDF_FORMFIELD_CHECKBOX || button_type == FPDF_FORMFIELD_RADIOBUTTON; @@ -427,24 +371,6 @@ void PDFiumPage::CalculatePageObjectTextRunBreaks() { } } -void PDFiumPage::LogOverlappingAnnotations() { - if (logged_overlapping_annotations_) - return; - logged_overlapping_annotations_ = true; - - DCHECK(calculated_page_object_text_run_breaks_); - - std::vector<Link> links = links_; - std::sort(links.begin(), links.end(), [](const Link& a, const Link& b) { - return a.start_char_index < b.start_char_index; - }); - uint32_t overlap_count = CountLinkHighlightOverlaps(links, highlights_); - // We log this overlap count per page of the PDF. Typically we expect only a - // few overlaps because intersecting links/highlights are not that common. - base::UmaHistogramCustomCounts("PDF.LinkHighlightOverlapsInPage", - overlap_count, 1, 100, 50); -} - absl::optional<AccessibilityTextRunInfo> PDFiumPage::GetTextRunInfo( int start_char_index) { FPDF_PAGE page = GetPage(); @@ -684,6 +610,7 @@ std::vector<AccessibilityImageInfo> PDFiumPage::GetImageInfo( cur_info.bounds = gfx::RectF(image.bounding_rect.x(), image.bounding_rect.y(), image.bounding_rect.width(), image.bounding_rect.height()); + cur_info.image_data = image.image_data; image_info.push_back(std::move(cur_info)); } return image_info; @@ -1161,6 +1088,7 @@ void PDFiumPage::CalculateImages() { continue; Image image; + image.page_object_index = i; image.bounding_rect = PageToScreen(gfx::Point(), 1.0, left, top, right, bottom, PageOrientation::kOriginal); @@ -1183,6 +1111,33 @@ void PDFiumPage::CalculateImages() { if (!marked_content_id_image_map.empty()) PopulateImageAltText(marked_content_id_image_map); + + if (!features::IsPdfOcrEnabled()) + return; + + // If requested by the user, we store the raw image data so that the OCR + // service can try and retrieve textual and layout information from the image. + // This is because alt text might be empty, or the PDF might simply be + // untagged for accessibility. + for (Image& image : images_) { + if (!image.alt_text.empty()) + continue; + + FPDF_PAGEOBJECT page_object = + FPDFPage_GetObject(page, image.page_object_index); + ScopedFPDFBitmap bitmap( + FPDFImageObj_GetRenderedBitmap(engine_->doc(), page, page_object)); + if (!bitmap) + continue; + + SkImageInfo info = SkImageInfo::Make( + FPDFBitmap_GetWidth(bitmap.get()), FPDFBitmap_GetHeight(bitmap.get()), + kBGRA_8888_SkColorType, kOpaque_SkAlphaType); + const size_t row_bytes = FPDFBitmap_GetStride(bitmap.get()); + SkPixmap pixels(info, FPDFBitmap_GetBuffer(bitmap.get()), row_bytes); + if (image.image_data.tryAllocPixels(info, row_bytes)) + image.image_data.writePixels(pixels); + } } void PDFiumPage::PopulateImageAltText( @@ -1653,12 +1608,4 @@ PDFiumPage::Button::Button(const Button& that) = default; PDFiumPage::Button::~Button() = default; -// static -uint32_t PDFiumPage::CountLinkHighlightOverlaps( - const std::vector<Link>& links, - const std::vector<Highlight>& highlights) { - return CountOverlaps(links, highlights) + CountInternalTextOverlaps(links) + - CountInternalTextOverlaps(highlights); -} - } // namespace chrome_pdf diff --git a/chromium/pdf/pdfium/pdfium_page.h b/chromium/pdf/pdfium/pdfium_page.h index 78e06960fcf..f2e9d4d1117 100644 --- a/chromium/pdf/pdfium/pdfium_page.h +++ b/chromium/pdf/pdfium/pdfium_page.h @@ -21,6 +21,7 @@ #include "third_party/pdfium/public/fpdf_doc.h" #include "third_party/pdfium/public/fpdf_formfill.h" #include "third_party/pdfium/public/fpdf_text.h" +#include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/rect.h" @@ -56,9 +57,6 @@ class PDFiumPage { // Returns FPDF_TEXTPAGE for the page, loading and parsing it if necessary. FPDF_TEXTPAGE GetTextPage(); - // Log overlaps between annotations in the page. - void LogOverlappingAnnotations(); - // See definition of PDFEngine::GetTextRunInfo(). absl::optional<AccessibilityTextRunInfo> GetTextRunInfo(int start_char_index); @@ -75,8 +73,11 @@ class PDFiumPage { // bounding boxes. std::vector<AccessibilityLinkInfo> GetLinkInfo( const std::vector<AccessibilityTextRunInfo>& text_runs); - - // For all the images on the page, get their alt texts and bounding boxes. + // For all the images on the page, get their alt texts and bounding boxes. If + // the alt text is empty or unavailable, and if the user has requested that + // the OCR service tag the PDF so that it is made accessible, transfer the raw + // image pixels in the `image_data` field. Otherwise do not populate the + // `image_data` field. std::vector<AccessibilityImageInfo> GetImageInfo(uint32_t text_run_count); // For all the highlights on the page, get their underlying text ranges and @@ -220,6 +221,7 @@ class PDFiumPage { FRIEND_TEST_ALL_PREFIXES(PDFiumPageHighlightTest, PopulateHighlights); FRIEND_TEST_ALL_PREFIXES(PDFiumPageImageTest, CalculateImages); FRIEND_TEST_ALL_PREFIXES(PDFiumPageImageTest, ImageAltText); + FRIEND_TEST_ALL_PREFIXES(PDFiumPageImageDataTest, ImageData); FRIEND_TEST_ALL_PREFIXES(PDFiumPageLinkTest, AnnotLinkGeneration); FRIEND_TEST_ALL_PREFIXES(PDFiumPageLinkTest, GetLinkTarget); FRIEND_TEST_ALL_PREFIXES(PDFiumPageLinkTest, LinkGeneration); @@ -256,9 +258,13 @@ class PDFiumPage { Image(const Image& other); ~Image(); - gfx::Rect bounding_rect; - // Alt text is available only for tagged PDFs. + int page_object_index; + // Alt text is available only for PDFs that are tagged for accessibility. std::string alt_text; + gfx::Rect bounding_rect; + // Image data is only stored if the user has requested that the OCR service + // try to retrieve textual and layout information from this image. + SkBitmap image_data; }; // Represents a highlight within the page. @@ -395,9 +401,6 @@ class PDFiumPage { const MarkedContentIdToImageMap& marked_content_id_image_map, FPDF_STRUCTELEMENT current_element, std::set<FPDF_STRUCTELEMENT>* visited_elements); - static uint32_t CountLinkHighlightOverlaps( - const std::vector<Link>& links, - const std::vector<Highlight>& highlights); bool PopulateFormFieldProperties(FPDF_ANNOTATION annot, FormField* form_field); // Generates and sends the thumbnail using `send_callback`. @@ -419,7 +422,6 @@ class PDFiumPage { std::vector<TextField> text_fields_; std::vector<ChoiceField> choice_fields_; std::vector<Button> buttons_; - bool logged_overlapping_annotations_ = false; bool calculated_page_object_text_run_breaks_ = false; // The set of character indices on which text runs need to be broken for page // objects. diff --git a/chromium/pdf/pdfium/pdfium_page_unittest.cc b/chromium/pdf/pdfium/pdfium_page_unittest.cc index 14ac5a1a89d..e90f6a4ded5 100644 --- a/chromium/pdf/pdfium/pdfium_page_unittest.cc +++ b/chromium/pdf/pdfium/pdfium_page_unittest.cc @@ -11,12 +11,12 @@ #include "base/files/file_path.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" +#include "base/test/scoped_feature_list.h" #include "cc/test/pixel_comparator.h" #include "cc/test/pixel_test_utils.h" #include "pdf/accessibility_structs.h" #include "pdf/pdfium/pdfium_engine.h" #include "pdf/pdfium/pdfium_test_base.h" -#include "pdf/ppapi_migration/geometry_conversions.h" #include "pdf/test/test_client.h" #include "pdf/test/test_helpers.h" #include "pdf/ui/thumbnail.h" @@ -24,6 +24,7 @@ #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/pdfium/public/fpdf_formfill.h" #include "third_party/skia/include/core/SkBitmap.h" +#include "ui/accessibility/accessibility_features.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/geometry/size_f.h" @@ -178,7 +179,7 @@ TEST_F(PDFiumPageLinkTest, AnnotLinkGeneration) { if (UsingTestFonts()) { expected_links[0].bounding_rects[0] = {99, 436, 236, 14}; } - static constexpr size_t kExpectedLinkCount = base::size(expected_links); + static constexpr size_t kExpectedLinkCount = std::size(expected_links); TestClient client; std::unique_ptr<PDFiumEngine> engine = @@ -284,6 +285,39 @@ TEST_F(PDFiumPageImageTest, ImageAltText) { EXPECT_EQ("", page.images_[2].alt_text); } +class PDFiumPageImageDataTest : public PDFiumPageImageTest { + public: + PDFiumPageImageDataTest() : enable_pdf_ocr_({features::kPdfOcr}) {} + + PDFiumPageImageDataTest(const PDFiumPageImageDataTest&) = delete; + PDFiumPageImageDataTest& operator=(const PDFiumPageImageDataTest&) = delete; + ~PDFiumPageImageDataTest() override = default; + + private: + base::test::ScopedFeatureList enable_pdf_ocr_; +}; + +TEST_F(PDFiumPageImageDataTest, ImageData) { + TestClient client; + std::unique_ptr<PDFiumEngine> engine = + InitializeEngine(&client, FILE_PATH_LITERAL("text_with_image.pdf")); + ASSERT_TRUE(engine); + ASSERT_EQ(1, engine->GetNumberOfPages()); + + PDFiumPage& page = GetPDFiumPageForTest(*engine, 0); + page.CalculateImages(); + ASSERT_EQ(3u, page.images_.size()); + + ASSERT_FALSE(page.images_[0].alt_text.empty()); + EXPECT_TRUE(page.images_[0].image_data.drawsNothing()); + EXPECT_EQ(page.images_[0].image_data.width(), 0); + EXPECT_EQ(page.images_[0].image_data.height(), 0); + + ASSERT_TRUE(page.images_[2].alt_text.empty()); + EXPECT_EQ(page.images_[1].image_data.width(), 20); + EXPECT_EQ(page.images_[1].image_data.height(), 20); +} + using PDFiumPageTextTest = PDFiumTestBase; TEST_F(PDFiumPageTextTest, TextRunBounds) { @@ -501,7 +535,7 @@ TEST_F(PDFiumPageHighlightTest, PopulateHighlights) { PDFiumPage& page = GetPDFiumPageForTest(*engine, 0); page.PopulateAnnotations(); - ASSERT_EQ(base::size(kExpectedHighlights), page.highlights_.size()); + ASSERT_EQ(std::size(kExpectedHighlights), page.highlights_.size()); for (size_t i = 0; i < page.highlights_.size(); ++i) { ASSERT_EQ(kExpectedHighlights[i].start_char_index, @@ -539,7 +573,7 @@ TEST_F(PDFiumPageTextFieldTest, PopulateTextFields) { PDFiumPage& page = GetPDFiumPageForTest(*engine, 0); page.PopulateAnnotations(); size_t text_fields_count = page.text_fields_.size(); - ASSERT_EQ(base::size(kExpectedTextFields), text_fields_count); + ASSERT_EQ(std::size(kExpectedTextFields), text_fields_count); for (size_t i = 0; i < text_fields_count; ++i) { EXPECT_EQ(kExpectedTextFields[i].name, page.text_fields_[i].name); @@ -618,12 +652,12 @@ TEST_F(PDFiumPageChoiceFieldTest, PopulateChoiceFields) { PDFiumPage& page = GetPDFiumPageForTest(*engine, 0); page.PopulateAnnotations(); size_t choice_fields_count = page.choice_fields_.size(); - ASSERT_EQ(base::size(kExpectedChoiceFields), choice_fields_count); + ASSERT_EQ(std::size(kExpectedChoiceFields), choice_fields_count); for (size_t i = 0; i < choice_fields_count; ++i) { EXPECT_EQ(kExpectedChoiceFields[i].name, page.choice_fields_[i].name); size_t choice_field_options_count = page.choice_fields_[i].options.size(); - ASSERT_EQ(base::size(kExpectedChoiceFields[i].options), + ASSERT_EQ(std::size(kExpectedChoiceFields[i].options), choice_field_options_count); for (size_t j = 0; j < choice_field_options_count; ++j) { EXPECT_EQ(kExpectedChoiceFields[i].options[j].name, @@ -701,7 +735,7 @@ TEST_F(PDFiumPageButtonTest, PopulateButtons) { PDFiumPage& page = GetPDFiumPageForTest(*engine, 0); page.PopulateAnnotations(); size_t buttons_count = page.buttons_.size(); - ASSERT_EQ(base::size(kExpectedButtons), buttons_count); + ASSERT_EQ(std::size(kExpectedButtons), buttons_count); for (size_t i = 0; i < buttons_count; ++i) { EXPECT_EQ(kExpectedButtons[i].name, page.buttons_[i].name); @@ -718,37 +752,6 @@ TEST_F(PDFiumPageButtonTest, PopulateButtons) { } } -using PDFiumPageOverlappingTest = PDFiumTestBase; - -// The following scenarios are covered across both test cases: -// 1. Links overlapping amongst themselves. -// 2. Highlights overlapping amongst themselves. -// 3. Links partially and completely overlapping with highlights. -// 4. Adjacent annotations. -TEST_F(PDFiumPageOverlappingTest, CountPartialOverlaps) { - static const std::vector<gfx::Range> kLinkRanges = { - {0, 10}, {13, 25}, {37, 52}, {71, 84}, {93, 113}}; - static const std::vector<gfx::Range> kHighlightRanges = { - {4, 13}, {8, 15}, {14, 22}, {37, 73}, {49, 95}, {80, 101}}; - std::vector<PDFiumPage::Link> links; - std::vector<PDFiumPage::Highlight> highlights; - PopulateTextObjects(kLinkRanges, &links); - PopulateTextObjects(kHighlightRanges, &highlights); - ASSERT_EQ(15u, PDFiumPage::CountLinkHighlightOverlaps(links, highlights)); -} - -TEST_F(PDFiumPageOverlappingTest, CountCompleteOverlaps) { - static const std::vector<gfx::Range> kLinkRanges = { - {0, 15}, {25, 40}, {30, 50}, {50, 67}, {61, 72}, {67, 81}}; - static const std::vector<gfx::Range> kHighlightRanges = { - {6, 25}, {25, 40}, {30, 50}, {50, 83}}; - std::vector<PDFiumPage::Link> links; - std::vector<PDFiumPage::Highlight> highlights; - PopulateTextObjects(kLinkRanges, &links); - PopulateTextObjects(kHighlightRanges, &highlights); - ASSERT_EQ(12u, PDFiumPage::CountLinkHighlightOverlaps(links, highlights)); -} - class PDFiumPageThumbnailTest : public PDFiumTestBase { public: PDFiumPageThumbnailTest() = default; diff --git a/chromium/pdf/post_message_receiver.cc b/chromium/pdf/post_message_receiver.cc index c97d9b40a9b..ee9e96c305f 100644 --- a/chromium/pdf/post_message_receiver.cc +++ b/chromium/pdf/post_message_receiver.cc @@ -16,13 +16,13 @@ #include "base/memory/weak_ptr.h" #include "base/task/sequenced_task_runner.h" #include "base/values.h" -#include "content/public/renderer/v8_value_converter.h" #include "gin/function_template.h" #include "gin/handle.h" #include "gin/interceptor.h" #include "gin/object_template_builder.h" #include "gin/public/wrapper_info.h" #include "gin/wrappable.h" +#include "pdf/v8_value_converter.h" #include "v8/include/v8.h" namespace chrome_pdf { @@ -39,11 +39,13 @@ gin::WrapperInfo PostMessageReceiver::kWrapperInfo = {gin::kEmbedderNativeGin}; // static v8::Local<v8::Object> PostMessageReceiver::Create( v8::Isolate* isolate, + base::WeakPtr<V8ValueConverter> v8_value_converter, base::WeakPtr<Client> client, scoped_refptr<base::SequencedTaskRunner> client_task_runner) { return gin::CreateHandle( - isolate, new PostMessageReceiver(isolate, std::move(client), - std::move(client_task_runner))) + isolate, new PostMessageReceiver( + isolate, std::move(v8_value_converter), + std::move(client), std::move(client_task_runner))) .ToV8() .As<v8::Object>(); } @@ -52,9 +54,11 @@ PostMessageReceiver::~PostMessageReceiver() = default; PostMessageReceiver::PostMessageReceiver( v8::Isolate* isolate, + base::WeakPtr<V8ValueConverter> v8_value_converter, base::WeakPtr<Client> client, scoped_refptr<base::SequencedTaskRunner> client_task_runner) : gin::NamedPropertyInterceptor(isolate, this), + v8_value_converter_(std::move(v8_value_converter)), isolate_(isolate), client_(std::move(client)), client_task_runner_(std::move(client_task_runner)) {} @@ -113,26 +117,19 @@ v8::Local<v8::FunctionTemplate> PostMessageReceiver::GetFunctionTemplate() { return function_template_.Get(isolate_); } -std::unique_ptr<base::Value> PostMessageReceiver::ConvertMessage( - v8::Local<v8::Value> message) { - if (!v8_value_converter_) - v8_value_converter_ = content::V8ValueConverter::Create(); - - return v8_value_converter_->FromV8Value(message, - isolate_->GetCurrentContext()); -} - void PostMessageReceiver::PostMessage(v8::Local<v8::Value> message) { - if (!client_) + if (!client_ || !v8_value_converter_) return; - std::unique_ptr<base::Value> converted_message = ConvertMessage(message); - DCHECK(converted_message) << "The PDF Viewer UI should not be sending " - "messages that cannot be converted."; + std::unique_ptr<base::Value> converted_message = + v8_value_converter_->FromV8Value(message, isolate_->GetCurrentContext()); + // The PDF Viewer UI should not be sending messages that cannot be converted. + DCHECK(converted_message); + DCHECK(converted_message->is_dict()); - client_task_runner_->PostTask(FROM_HERE, - base::BindOnce(&Client::OnMessage, client_, - std::move(*converted_message))); + client_task_runner_->PostTask( + FROM_HERE, base::BindOnce(&Client::OnMessage, client_, + std::move(converted_message->GetDict()))); } } // namespace chrome_pdf diff --git a/chromium/pdf/post_message_receiver.h b/chromium/pdf/post_message_receiver.h index e255c75c10f..5b4ac33987f 100644 --- a/chromium/pdf/post_message_receiver.h +++ b/chromium/pdf/post_message_receiver.h @@ -10,6 +10,7 @@ #include "base/memory/raw_ptr.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" +#include "base/values.h" #include "gin/interceptor.h" #include "gin/public/wrapper_info.h" #include "gin/wrappable.h" @@ -17,19 +18,16 @@ namespace base { class SequencedTaskRunner; -class Value; } // namespace base -namespace content { -class V8ValueConverter; -} // namespace content - namespace gin { class ObjectTemplateBuilder; } // namespace gin namespace chrome_pdf { +class V8ValueConverter; + // Implements the `postMessage()` API exposed to the plugin embedder. The // received messages are converted and forwarded to the `Client`. // `PostMessageReceiver`'s lifetime is managed by the V8 garbage collector, @@ -42,7 +40,7 @@ class PostMessageReceiver final : public gin::Wrappable<PostMessageReceiver>, class Client { public: // Handles converted messages from the embedder. - virtual void OnMessage(const base::Value& message) = 0; + virtual void OnMessage(const base::Value::Dict& message) = 0; protected: Client() = default; @@ -55,6 +53,7 @@ class PostMessageReceiver final : public gin::Wrappable<PostMessageReceiver>, // Messages are posted asynchronously to `client` using `client_task_runner`. static v8::Local<v8::Object> Create( v8::Isolate* isolate, + base::WeakPtr<V8ValueConverter> v8_value_converter, base::WeakPtr<Client> client, scoped_refptr<base::SequencedTaskRunner> client_task_runner); @@ -67,6 +66,7 @@ class PostMessageReceiver final : public gin::Wrappable<PostMessageReceiver>, private: PostMessageReceiver( v8::Isolate* isolate, + base::WeakPtr<V8ValueConverter> v8_value_converter, base::WeakPtr<Client> client, scoped_refptr<base::SequencedTaskRunner> client_task_runner); @@ -84,13 +84,10 @@ class PostMessageReceiver final : public gin::Wrappable<PostMessageReceiver>, // Lazily creates and retrieves `function_template_`. v8::Local<v8::FunctionTemplate> GetFunctionTemplate(); - // Converts `message` so it can be consumed by `client_`. - std::unique_ptr<base::Value> ConvertMessage(v8::Local<v8::Value> message); - // Implements the `postMessage()` method called by the embedder. void PostMessage(v8::Local<v8::Value> message); - std::unique_ptr<content::V8ValueConverter> v8_value_converter_; + base::WeakPtr<V8ValueConverter> v8_value_converter_; v8::Persistent<v8::FunctionTemplate> function_template_; diff --git a/chromium/pdf/post_message_sender.cc b/chromium/pdf/post_message_sender.cc index 16fa76860d6..2e9d4709a0e 100644 --- a/chromium/pdf/post_message_sender.cc +++ b/chromium/pdf/post_message_sender.cc @@ -8,7 +8,7 @@ #include "base/check_op.h" #include "base/values.h" -#include "content/public/renderer/v8_value_converter.h" +#include "pdf/v8_value_converter.h" #include "third_party/blink/public/web/blink.h" #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_dom_message_event.h" @@ -19,7 +19,13 @@ namespace chrome_pdf { -PostMessageSender::PostMessageSender() : isolate_(blink::MainThreadIsolate()) {} +PostMessageSender::PostMessageSender(blink::WebPluginContainer* container, + V8ValueConverter* v8_value_converter) + : v8_value_converter_(v8_value_converter), + isolate_(blink::MainThreadIsolate()), + container_(container) { + DCHECK(container_); +} PostMessageSender::~PostMessageSender() = default; @@ -28,11 +34,7 @@ PostMessageSender::~PostMessageSender() = default; // When that happens, the body of this method needs to be posted to the main // thread as a task because that's where the Blink and V8 interactions need to // occur. -void PostMessageSender::Post(base::Value message) { - // Drop messages if there is no container. - if (!container_) - return; - +void PostMessageSender::Post(base::Value::Dict message) { v8::Isolate::Scope isolate_scope(isolate_); v8::HandleScope handle_scope(isolate_); v8::Local<v8::Context> context = @@ -40,11 +42,8 @@ void PostMessageSender::Post(base::Value message) { DCHECK_EQ(isolate_, context->GetIsolate()); v8::Context::Scope context_scope(context); - if (!v8_value_converter_) - v8_value_converter_ = content::V8ValueConverter::Create(); - v8::Local<v8::Value> converted_message = - v8_value_converter_->ToV8Value(&message, context); + v8_value_converter_->ToV8Value(base::Value(std::move(message)), context); container_->EnqueueMessageEvent( blink::WebSerializedScriptValue::Serialize(isolate_, converted_message)); diff --git a/chromium/pdf/post_message_sender.h b/chromium/pdf/post_message_sender.h index f04097d9103..4114d3d92bd 100644 --- a/chromium/pdf/post_message_sender.h +++ b/chromium/pdf/post_message_sender.h @@ -5,53 +5,36 @@ #ifndef PDF_POST_MESSAGE_SENDER_H_ #define PDF_POST_MESSAGE_SENDER_H_ -#include <memory> - #include "base/memory/raw_ptr.h" - -namespace base { -class Value; -} // namespace base +#include "base/values.h" +#include "v8/include/v8-forward.h" namespace blink { class WebPluginContainer; } // namespace blink -namespace content { -class V8ValueConverter; -} // namespace content - -namespace v8 { -class Isolate; -} // namespace v8 - namespace chrome_pdf { +class V8ValueConverter; + // Manages messages sent from the plugin to its embedder. class PostMessageSender final { public: - PostMessageSender(); + PostMessageSender(blink::WebPluginContainer* container, + V8ValueConverter* v8_value_converter); PostMessageSender(const PostMessageSender&) = delete; PostMessageSender& operator=(const PostMessageSender&) = delete; ~PostMessageSender(); // Enqueues a "message" event carrying `message` to the plugin embedder. - // Nothing is enqueued if `container_` is null. - void Post(base::Value message); - - // Sets the plugin container that enqueues the messages. This method should be - // called by the owning plugin whenever its container is set or unset to - // mirror the initialized lifetime of the plugin. - void set_container(blink::WebPluginContainer* container) { - container_ = container; - } + void Post(base::Value::Dict message); private: - std::unique_ptr<content::V8ValueConverter> v8_value_converter_; + const raw_ptr<V8ValueConverter> v8_value_converter_; - raw_ptr<v8::Isolate> isolate_; + const raw_ptr<v8::Isolate> isolate_; - raw_ptr<blink::WebPluginContainer> container_ = nullptr; + raw_ptr<blink::WebPluginContainer> const container_; }; } // namespace chrome_pdf diff --git a/chromium/pdf/ppapi_migration/bitmap.cc b/chromium/pdf/ppapi_migration/bitmap.cc index 6171235dd27..cbba223d054 100644 --- a/chromium/pdf/ppapi_migration/bitmap.cc +++ b/chromium/pdf/ppapi_migration/bitmap.cc @@ -4,55 +4,16 @@ #include "pdf/ppapi_migration/bitmap.h" -#include <stdint.h> - -#include <memory> - -#include "base/check_op.h" -#include "ppapi/cpp/image_data.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkImageInfo.h" #include "third_party/skia/include/core/SkSize.h" namespace chrome_pdf { -namespace { - -// Releases pp::ImageData associated with the SkPixelRef. The pp::ImageData acts -// like a shared pointer to memory provided by Pepper, and must be retained for -// the life of the SkPixelRef. -void ReleaseImageData(void* addr, void* context) { - pp::ImageData* image_data = static_cast<pp::ImageData*>(context); - DCHECK_EQ(addr, image_data->data()); - delete image_data; -} - -} // namespace - SkBitmap CreateN32PremulSkBitmap(const SkISize& size) { SkBitmap bitmap; bitmap.allocPixels(SkImageInfo::MakeN32Premul(size)); return bitmap; } -SkBitmap SkBitmapFromPPImageData(std::unique_ptr<pp::ImageData> image_data) { - if (image_data->is_null()) { - return SkBitmap(); - } - - // Note that we unconditionally use BGRA_PREMUL with PDFium. - DCHECK_EQ(image_data->format(), PP_IMAGEDATAFORMAT_BGRA_PREMUL); - SkImageInfo info = - SkImageInfo::Make(image_data->size().width(), image_data->size().height(), - kBGRA_8888_SkColorType, kPremul_SkAlphaType); - void* data = image_data->data(); - int32_t stride = image_data->stride(); - - SkBitmap bitmap; - bool success = bitmap.installPixels(info, data, stride, ReleaseImageData, - image_data.release()); - DCHECK(success); - return bitmap; -} - } // namespace chrome_pdf diff --git a/chromium/pdf/ppapi_migration/bitmap.h b/chromium/pdf/ppapi_migration/bitmap.h index 0c37f85689c..504625c347b 100644 --- a/chromium/pdf/ppapi_migration/bitmap.h +++ b/chromium/pdf/ppapi_migration/bitmap.h @@ -5,31 +5,15 @@ #ifndef PDF_PPAPI_MIGRATION_BITMAP_H_ #define PDF_PPAPI_MIGRATION_BITMAP_H_ -#include <memory> - #include "third_party/skia/include/core/SkSize.h" class SkBitmap; -namespace pp { -class ImageData; -} // namespace pp - namespace chrome_pdf { // Creates an SkBitmap of a given `size`. SkBitmap CreateN32PremulSkBitmap(const SkISize& size); -// Creates an SkBitmap from a pp::ImageData. The SkBitmap takes ownership of the -// pp::ImageData, and shares ownership of the underlying pixel memory. (Note -// that it's easy to make a shallow copy of a pp::ImageData.) -// -// In case of an error, returns an empty SkBitmap. -// -// TODO(kmoon): Skia is trying to get rid of SkBitmap in favor of immutable -// types like SkImage, so we should migrate once PDFium is ready for Skia. -SkBitmap SkBitmapFromPPImageData(std::unique_ptr<pp::ImageData> image_data); - } // namespace chrome_pdf #endif // PDF_PPAPI_MIGRATION_BITMAP_H_ diff --git a/chromium/pdf/ppapi_migration/callback.cc b/chromium/pdf/ppapi_migration/callback.cc deleted file mode 100644 index adc58a71b88..00000000000 --- a/chromium/pdf/ppapi_migration/callback.cc +++ /dev/null @@ -1,33 +0,0 @@ -// 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/ppapi_migration/callback.h" - -#include <stdint.h> - -#include <memory> -#include <utility> - -#include "base/callback.h" -#include "ppapi/cpp/completion_callback.h" - -namespace chrome_pdf { - -namespace { - -void RunAndDeleteResultCallback(void* user_data, int32_t result) { - std::unique_ptr<ResultCallback> callback( - static_cast<ResultCallback*>(user_data)); - std::move(*callback).Run(result); -} - -} // namespace - -pp::CompletionCallback PPCompletionCallbackFromResultCallback( - ResultCallback callback) { - return pp::CompletionCallback(RunAndDeleteResultCallback, - new ResultCallback(std::move(callback))); -} - -} // namespace chrome_pdf diff --git a/chromium/pdf/ppapi_migration/callback.h b/chromium/pdf/ppapi_migration/callback.h deleted file mode 100644 index 8af63336a3c..00000000000 --- a/chromium/pdf/ppapi_migration/callback.h +++ /dev/null @@ -1,35 +0,0 @@ -// 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. - -#ifndef PDF_PPAPI_MIGRATION_CALLBACK_H_ -#define PDF_PPAPI_MIGRATION_CALLBACK_H_ - -#include <stdint.h> - -#include "base/callback_forward.h" - -namespace pp { -class CompletionCallback; -} // namespace pp - -namespace chrome_pdf { - -// A `base::OnceCallback` compatible with `pp::CompletionCallback`. Accepts an -// `int32_t` result. -using ResultCallback = base::OnceCallback<void(int32_t)>; - -// Adapts a `ResultCallback` to be invoked as a `pp::CompletionCallback`. -// -// Note that the `ResultCallback` will be deleted only when the -// `pp::CompletionCallback` runs. This implies that the `pp::CompletionCallback` -// must always be run exactly once. -// -// Also note that there is no replacement for `pp::CompletionCallbackFactory`; -// use a `base::WeakPtrFactory` on the receiver object instead. -pp::CompletionCallback PPCompletionCallbackFromResultCallback( - ResultCallback callback); - -} // namespace chrome_pdf - -#endif // PDF_PPAPI_MIGRATION_CALLBACK_H_ diff --git a/chromium/pdf/ppapi_migration/geometry_conversions.cc b/chromium/pdf/ppapi_migration/geometry_conversions.cc deleted file mode 100644 index ed7be090b62..00000000000 --- a/chromium/pdf/ppapi_migration/geometry_conversions.cc +++ /dev/null @@ -1,53 +0,0 @@ -// 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/ppapi_migration/geometry_conversions.h" - -#include "ppapi/c/pp_point.h" -#include "ppapi/c/pp_rect.h" -#include "ppapi/c/pp_size.h" -#include "ui/gfx/geometry/point.h" -#include "ui/gfx/geometry/point_f.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/geometry/rect_f.h" -#include "ui/gfx/geometry/size.h" -#include "ui/gfx/geometry/vector2d.h" - -namespace chrome_pdf { - -gfx::Point PointFromPPPoint(const PP_Point& pp_point) { - return gfx::Point(pp_point.x, pp_point.y); -} - -gfx::PointF PointFFromPPFloatPoint(const PP_FloatPoint& pp_point) { - return gfx::PointF(pp_point.x, pp_point.y); -} - -PP_FloatPoint PPFloatPointFromPointF(const gfx::PointF& point) { - return PP_MakeFloatPoint(point.x(), point.y()); -} - -gfx::Rect RectFromPPRect(const PP_Rect& pp_rect) { - return gfx::Rect(pp_rect.point.x, pp_rect.point.y, pp_rect.size.width, - pp_rect.size.height); -} - -PP_Rect PPRectFromRect(const gfx::Rect& rect) { - return PP_MakeRectFromXYWH(rect.x(), rect.y(), rect.width(), rect.height()); -} - -PP_FloatRect PPFloatRectFromRectF(const gfx::RectF& rect) { - return PP_MakeFloatRectFromXYWH(rect.x(), rect.y(), rect.width(), - rect.height()); -} - -gfx::Size SizeFromPPSize(const PP_Size& pp_size) { - return gfx::Size(pp_size.width, pp_size.height); -} - -PP_Size PPSizeFromSize(const gfx::Size& size) { - return PP_MakeSize(size.width(), size.height()); -} - -} // namespace chrome_pdf diff --git a/chromium/pdf/ppapi_migration/geometry_conversions.h b/chromium/pdf/ppapi_migration/geometry_conversions.h deleted file mode 100644 index df0b1277fac..00000000000 --- a/chromium/pdf/ppapi_migration/geometry_conversions.h +++ /dev/null @@ -1,39 +0,0 @@ -// 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. - -#ifndef PDF_PPAPI_MIGRATION_GEOMETRY_CONVERSIONS_H_ -#define PDF_PPAPI_MIGRATION_GEOMETRY_CONVERSIONS_H_ - -struct PP_FloatPoint; -struct PP_FloatRect; -struct PP_Point; -struct PP_Rect; -struct PP_Size; - -namespace gfx { -class Point; -class PointF; -class Rect; -class RectF; -class Size; -} // namespace gfx - -namespace chrome_pdf { - -gfx::Point PointFromPPPoint(const PP_Point& pp_point); - -gfx::PointF PointFFromPPFloatPoint(const PP_FloatPoint& pp_point); -PP_FloatPoint PPFloatPointFromPointF(const gfx::PointF& point); - -gfx::Rect RectFromPPRect(const PP_Rect& pp_rect); -PP_Rect PPRectFromRect(const gfx::Rect& rect); - -PP_FloatRect PPFloatRectFromRectF(const gfx::RectF& rect); - -gfx::Size SizeFromPPSize(const PP_Size& pp_size); -PP_Size PPSizeFromSize(const gfx::Size& size); - -} // namespace chrome_pdf - -#endif // PDF_PPAPI_MIGRATION_GEOMETRY_CONVERSIONS_H_ diff --git a/chromium/pdf/ppapi_migration/geometry_conversions_unittest.cc b/chromium/pdf/ppapi_migration/geometry_conversions_unittest.cc deleted file mode 100644 index 1e1bca7c888..00000000000 --- a/chromium/pdf/ppapi_migration/geometry_conversions_unittest.cc +++ /dev/null @@ -1,107 +0,0 @@ -// 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/ppapi_migration/geometry_conversions.h" - -#include "ppapi/c/pp_point.h" -#include "ppapi/c/pp_rect.h" -#include "ppapi/c/pp_size.h" -#include "ppapi/cpp/point.h" -#include "ppapi/cpp/rect.h" -#include "ppapi/cpp/size.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/gfx/geometry/point.h" -#include "ui/gfx/geometry/point_f.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/geometry/rect_f.h" -#include "ui/gfx/geometry/size.h" -#include "ui/gfx/geometry/vector2d.h" - -namespace chrome_pdf { - -TEST(GeometryConversionsTest, PointFromPPPoint) { - gfx::Point point = PointFromPPPoint(pp::Point(-1, 2)); - EXPECT_EQ(point, gfx::Point(-1, 2)); - - point = PointFromPPPoint(PP_MakePoint(2, -1)); - EXPECT_EQ(point, gfx::Point(2, -1)); -} - -TEST(GeometryConversionsTest, PointFFromPPFloatPoint) { - gfx::PointF float_point = PointFFromPPFloatPoint(pp::FloatPoint(-1.2f, 2.2f)); - EXPECT_EQ(float_point, gfx::PointF(-1.2f, 2.2f)); - - float_point = PointFFromPPFloatPoint(PP_MakeFloatPoint(-2.2f, 1.2f)); - EXPECT_EQ(float_point, gfx::PointF(-2.2f, 1.2f)); -} - -TEST(GeometryConversionsTest, PPFloatPointFromPointF) { - pp::FloatPoint pp_cpp_float_point = - PPFloatPointFromPointF(gfx::PointF(-1.2f, 2.2f)); - EXPECT_EQ(pp_cpp_float_point.x(), -1.2f); - EXPECT_EQ(pp_cpp_float_point.y(), 2.2f); - - PP_FloatPoint pp_c_float_point = - PPFloatPointFromPointF(gfx::PointF(-2.2f, 1.2f)); - EXPECT_EQ(pp_c_float_point.x, -2.2f); - EXPECT_EQ(pp_c_float_point.y, 1.2f); -} - -TEST(GeometryConversionsTest, RectFromPPRect) { - gfx::Rect rect = RectFromPPRect(pp::Rect(-1, 2, 3, 4)); - EXPECT_EQ(rect, gfx::Rect(-1, 2, 3, 4)); - - rect = RectFromPPRect(PP_MakeRectFromXYWH(2, -1, 4, 3)); - EXPECT_EQ(rect, gfx::Rect(2, -1, 4, 3)); -} - -TEST(GeometryConversionsTest, PPRectFromRect) { - pp::Rect pp_cpp_rect = PPRectFromRect(gfx::Rect(-1, 2, 3, 4)); - EXPECT_EQ(pp_cpp_rect.x(), -1); - EXPECT_EQ(pp_cpp_rect.y(), 2); - EXPECT_EQ(pp_cpp_rect.width(), 3); - EXPECT_EQ(pp_cpp_rect.height(), 4); - - PP_Rect pp_c_rect = PPRectFromRect(gfx::Rect(2, -1, 4, 3)); - EXPECT_EQ(pp_c_rect.point.x, 2); - EXPECT_EQ(pp_c_rect.point.y, -1); - EXPECT_EQ(pp_c_rect.size.width, 4); - EXPECT_EQ(pp_c_rect.size.height, 3); -} - -TEST(GeometryConversionsTest, PPFloatRectFromRectF) { - pp::FloatRect pp_cpp_rect = - PPFloatRectFromRectF(gfx::RectF(-1.1f, 2.3f, 3.5f, 4.7f)); - EXPECT_EQ(pp_cpp_rect.x(), -1.1f); - EXPECT_EQ(pp_cpp_rect.y(), 2.3f); - EXPECT_EQ(pp_cpp_rect.width(), 3.5f); - EXPECT_EQ(pp_cpp_rect.height(), 4.7f); - - PP_FloatRect pp_c_rect = - PPFloatRectFromRectF(gfx::RectF(2.2f, -1.4f, 4.6f, 3.8f)); - EXPECT_EQ(pp_c_rect.point.x, 2.2f); - EXPECT_EQ(pp_c_rect.point.y, -1.4f); - EXPECT_EQ(pp_c_rect.size.width, 4.6f); - EXPECT_EQ(pp_c_rect.size.height, 3.8f); -} - -TEST(GeometryConversionsTest, SizeFromPPSize) { - gfx::Size size = SizeFromPPSize(pp::Size(3, 4)); - EXPECT_EQ(size, gfx::Size(3, 4)); - - size = SizeFromPPSize(PP_MakeSize(4, 3)); - EXPECT_EQ(size, gfx::Size(4, 3)); -} - -TEST(GeometryConversionsTest, PPSizeFromSize) { - pp::Size pp_cpp_size = PPSizeFromSize(gfx::Size(3, 4)); - EXPECT_EQ(pp_cpp_size.width(), 3); - EXPECT_EQ(pp_cpp_size.height(), 4); - - PP_Size pp_c_size = PPSizeFromSize(gfx::Size(4, 3)); - EXPECT_EQ(pp_c_size.width, 4); - EXPECT_EQ(pp_c_size.height, 3); -} - -} // namespace chrome_pdf diff --git a/chromium/pdf/ppapi_migration/graphics.cc b/chromium/pdf/ppapi_migration/graphics.cc index f6263641677..1f4b9a46b26 100644 --- a/chromium/pdf/ppapi_migration/graphics.cc +++ b/chromium/pdf/ppapi_migration/graphics.cc @@ -15,14 +15,8 @@ #include "base/memory/ptr_util.h" #include "base/notreached.h" #include "base/threading/sequenced_task_runner_handle.h" -#include "pdf/ppapi_migration/callback.h" -#include "pdf/ppapi_migration/geometry_conversions.h" -#include "pdf/ppapi_migration/image.h" #include "pdf/ppapi_migration/result_codes.h" -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/instance_handle.h" -#include "ppapi/cpp/point.h" -#include "ppapi/cpp/rect.h" +#include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h" #include "ui/gfx/blit.h" #include "ui/gfx/geometry/point.h" @@ -36,56 +30,6 @@ namespace chrome_pdf { Graphics::Graphics(const gfx::Size& size) : size_(size) {} -PepperGraphics::PepperGraphics(const pp::InstanceHandle& instance, - const gfx::Size& size) - : Graphics(size), - pepper_graphics_(instance, - PPSizeFromSize(size), - /*is_always_opaque=*/true) {} - -PepperGraphics::~PepperGraphics() = default; - -bool PepperGraphics::Flush(ResultCallback callback) { - pp::CompletionCallback pp_callback = - PPCompletionCallbackFromResultCallback(std::move(callback)); - int32_t result = pepper_graphics_.Flush(pp_callback); - if (result == PP_OK_COMPLETIONPENDING) { - return true; - } - - // Should only happen if pp::Graphics2D::Flush() is called while a callback is - // still pending, which should never happen if PaintManager is managing all - // flushes. - DCHECK_EQ(Result::kSuccess, result); - pp_callback.Run(result); - return false; -} - -void PepperGraphics::PaintImage(const Image& image, const gfx::Rect& src_rect) { - pepper_graphics_.PaintImageData(image.pepper_image(), pp::Point(), - PPRectFromRect(src_rect)); -} - -void PepperGraphics::Scroll(const gfx::Rect& clip, - const gfx::Vector2d& amount) { - pepper_graphics_.Scroll(PPRectFromRect(clip), - pp::Point(amount.x(), amount.y())); -} - -void PepperGraphics::SetScale(float scale) { - bool result = pepper_graphics_.SetScale(scale); - DCHECK(result); -} - -void PepperGraphics::SetLayerTransform(float scale, - const gfx::Point& origin, - const gfx::Vector2d& translate) { - bool result = pepper_graphics_.SetLayerTransform( - scale, pp::Point(origin.x(), origin.y()), - pp::Point(translate.x(), translate.y())); - DCHECK(result); -} - // static std::unique_ptr<SkiaGraphics> SkiaGraphics::Create(Client* client, const gfx::Size& size) { @@ -107,23 +51,26 @@ SkiaGraphics::~SkiaGraphics() = default; // TODO(https://crbug.com/1099020): After completely switching to non-Pepper // plugin, make Flush() return false since there is no pending action for // syncing the client's snapshot. -bool SkiaGraphics::Flush(ResultCallback callback) { +bool SkiaGraphics::Flush(base::OnceClosure callback) { sk_sp<SkImage> snapshot = skia_graphics_->makeImageSnapshot(); skia_graphics_->getCanvas()->drawImage( snapshot.get(), /*x=*/0, /*y=*/0, SkSamplingOptions(), /*paint=*/nullptr); client_->UpdateSnapshot(std::move(snapshot)); - base::SequencedTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(std::move(callback), 0)); + base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE, + std::move(callback)); return true; } -void SkiaGraphics::PaintImage(const Image& image, const gfx::Rect& src_rect) { +void SkiaGraphics::PaintImage(const SkBitmap& image, + const gfx::Rect& src_rect) { SkRect skia_rect = RectToSkRect(src_rect); + + // TODO(crbug.com/1284255): Avoid inefficient `SkBitmap::asImage()`. skia_graphics_->getCanvas()->drawImageRect( - image.skia_image().asImage(), skia_rect, skia_rect, SkSamplingOptions(), - nullptr, SkCanvas::kStrict_SrcRectConstraint); + image.asImage(), skia_rect, skia_rect, SkSamplingOptions(), nullptr, + SkCanvas::kStrict_SrcRectConstraint); } void SkiaGraphics::Scroll(const gfx::Rect& clip, const gfx::Vector2d& amount) { diff --git a/chromium/pdf/ppapi_migration/graphics.h b/chromium/pdf/ppapi_migration/graphics.h index 8432e59550b..0b11bb5b80f 100644 --- a/chromium/pdf/ppapi_migration/graphics.h +++ b/chromium/pdf/ppapi_migration/graphics.h @@ -7,13 +7,13 @@ #include <memory> +#include "base/callback_forward.h" #include "base/memory/raw_ptr.h" -#include "pdf/ppapi_migration/callback.h" -#include "ppapi/cpp/graphics_2d.h" #include "third_party/skia/include/core/SkRefCnt.h" #include "third_party/skia/include/core/SkSurface.h" #include "ui/gfx/geometry/size.h" +class SkBitmap; class SkImage; namespace gfx { @@ -23,14 +23,8 @@ class Vector2d; class Vector2dF; } // namespace gfx -namespace pp { -class InstanceHandle; -} // namespace pp - namespace chrome_pdf { -class Image; - // Abstraction for a Pepper or Skia graphics device. // TODO(crbug.com/1099020): Implement the Skia graphics device. class Graphics { @@ -41,11 +35,11 @@ class Graphics { // Flushes pending operations, invoking the callback on completion. Returns // `true` if the callback is still pending. - virtual bool Flush(ResultCallback callback) = 0; + virtual bool Flush(base::OnceClosure callback) = 0; // Paints the `src_rect` region of `image` to the graphics device. The image // must be compatible with the concrete `Graphics` implementation. - virtual void PaintImage(const Image& image, const gfx::Rect& src_rect) = 0; + virtual void PaintImage(const SkBitmap& image, const gfx::Rect& src_rect) = 0; // Shifts the `clip` region of the graphics device by `amount`. virtual void Scroll(const gfx::Rect& clip, const gfx::Vector2d& amount) = 0; @@ -65,29 +59,6 @@ class Graphics { gfx::Size size_; }; -// A Pepper graphics device. -class PepperGraphics final : public Graphics { - public: - PepperGraphics(const pp::InstanceHandle& instance, const gfx::Size& size); - ~PepperGraphics() override; - - bool Flush(ResultCallback callback) override; - - void PaintImage(const Image& image, const gfx::Rect& src_rect) override; - - void Scroll(const gfx::Rect& clip, const gfx::Vector2d& amount) override; - void SetScale(float scale) override; - void SetLayerTransform(float scale, - const gfx::Point& origin, - const gfx::Vector2d& translate) override; - - // Gets the underlying pp::Graphics2D. - pp::Graphics2D& pepper_graphics() { return pepper_graphics_; } - - private: - pp::Graphics2D pepper_graphics_; -}; - // A Skia graphics device. class SkiaGraphics final : public Graphics { public: @@ -114,9 +85,9 @@ class SkiaGraphics final : public Graphics { ~SkiaGraphics() override; - bool Flush(ResultCallback callback) override; + bool Flush(base::OnceClosure callback) override; - void PaintImage(const Image& image, const gfx::Rect& src_rect) override; + void PaintImage(const SkBitmap& image, const gfx::Rect& src_rect) override; void Scroll(const gfx::Rect& clip, const gfx::Vector2d& amount) override; void SetScale(float scale) override; diff --git a/chromium/pdf/ppapi_migration/graphics_unittest.cc b/chromium/pdf/ppapi_migration/graphics_unittest.cc index ae43adcf423..e2e7a727c62 100644 --- a/chromium/pdf/ppapi_migration/graphics_unittest.cc +++ b/chromium/pdf/ppapi_migration/graphics_unittest.cc @@ -10,8 +10,6 @@ #include "cc/test/pixel_comparator.h" #include "cc/test/pixel_test_utils.h" #include "pdf/ppapi_migration/bitmap.h" -#include "pdf/ppapi_migration/callback.h" -#include "pdf/ppapi_migration/image.h" #include "pdf/test/test_helpers.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -121,7 +119,7 @@ class SkiaGraphicsScrollTest : public SkiaGraphicsTest { // Paint a nonuniform SkBitmap to graphics. initial_bitmap_ = CreateNonuniformBitmap(kGraphicsRect.width(), kGraphicsRect.height()); - graphics_->PaintImage(Image(initial_bitmap_), kGraphicsRect); + graphics_->PaintImage(initial_bitmap_, kGraphicsRect); graphics_->Flush(base::DoNothing()); SkBitmap initial_snapshot; ASSERT_TRUE(client_.snapshot->asLegacyBitmap(&initial_snapshot)); @@ -135,7 +133,7 @@ class SkiaGraphicsScrollTest : public SkiaGraphicsTest { if (!graphics_) return; - graphics_->PaintImage(Image(initial_bitmap_), kGraphicsRect); + graphics_->PaintImage(initial_bitmap_, kGraphicsRect); graphics_->Scroll(kGraphicsRect, scroll_amount); graphics_->Flush(base::DoNothing()); } diff --git a/chromium/pdf/ppapi_migration/image.cc b/chromium/pdf/ppapi_migration/image.cc deleted file mode 100644 index f1fc88fa449..00000000000 --- a/chromium/pdf/ppapi_migration/image.cc +++ /dev/null @@ -1,23 +0,0 @@ -// 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/ppapi_migration/image.h" - -#include "ppapi/cpp/image_data.h" -#include "third_party/abseil-cpp/absl/types/variant.h" -#include "third_party/skia/include/core/SkBitmap.h" - -namespace chrome_pdf { - -Image::Image(const pp::ImageData& pepper_image) : image_(pepper_image) {} - -Image::Image(const SkBitmap& skia_image) : image_(skia_image) {} - -Image::Image(const Image& other) = default; - -Image& Image::operator=(const Image& other) = default; - -Image::~Image() = default; - -} // namespace chrome_pdf diff --git a/chromium/pdf/ppapi_migration/image.h b/chromium/pdf/ppapi_migration/image.h deleted file mode 100644 index 35c2ffbc6f0..00000000000 --- a/chromium/pdf/ppapi_migration/image.h +++ /dev/null @@ -1,38 +0,0 @@ -// 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. - -#ifndef PDF_PPAPI_MIGRATION_IMAGE_H_ -#define PDF_PPAPI_MIGRATION_IMAGE_H_ - -#include "ppapi/cpp/image_data.h" -#include "third_party/abseil-cpp/absl/types/variant.h" -#include "third_party/skia/include/core/SkBitmap.h" - -namespace chrome_pdf { - -// Holder for an image in either Pepper or Skia format. -// -// Note that both Pepper and Skia images retain shared ownership of any -// underlying pixel memory, so this class may be copied freely. -class Image final { - public: - explicit Image(const pp::ImageData& pepper_image); - explicit Image(const SkBitmap& skia_image); - Image(const Image& other); - Image& operator=(const Image& other); - ~Image(); - - const pp::ImageData& pepper_image() const { - return absl::get<pp::ImageData>(image_); - } - - const SkBitmap& skia_image() const { return absl::get<SkBitmap>(image_); } - - private: - absl::variant<pp::ImageData, SkBitmap> image_; -}; - -} // namespace chrome_pdf - -#endif // PDF_PPAPI_MIGRATION_IMAGE_H_ diff --git a/chromium/pdf/ppapi_migration/input_event_conversions.cc b/chromium/pdf/ppapi_migration/input_event_conversions.cc deleted file mode 100644 index 16cc97a3fab..00000000000 --- a/chromium/pdf/ppapi_migration/input_event_conversions.cc +++ /dev/null @@ -1,191 +0,0 @@ -// 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/ppapi_migration/input_event_conversions.h" - -#include <stdint.h> - -#include <algorithm> -#include <memory> - -#include "base/check_op.h" -#include "base/notreached.h" -#include "base/strings/utf_string_conversions.h" -#include "base/time/time.h" -#include "pdf/ppapi_migration/geometry_conversions.h" -#include "ppapi/c/dev/pp_cursor_type_dev.h" -#include "ppapi/cpp/input_event.h" -#include "ppapi/cpp/var.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/input/web_mouse_event.h" -#include "third_party/blink/public/common/input/web_pointer_properties.h" -#include "third_party/blink/public/common/input/web_touch_event.h" -#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" - -namespace chrome_pdf { - -namespace { - -blink::WebInputEvent::Type GetWebInputEventType(PP_InputEvent_Type event_type) { - switch (event_type) { - case PP_INPUTEVENT_TYPE_MOUSEDOWN: - return blink::WebInputEvent::Type::kMouseDown; - case PP_INPUTEVENT_TYPE_MOUSEUP: - return blink::WebInputEvent::Type::kMouseUp; - case PP_INPUTEVENT_TYPE_MOUSEMOVE: - return blink::WebInputEvent::Type::kMouseMove; - case PP_INPUTEVENT_TYPE_MOUSEENTER: - return blink::WebInputEvent::Type::kMouseEnter; - case PP_INPUTEVENT_TYPE_MOUSELEAVE: - return blink::WebInputEvent::Type::kMouseLeave; - case PP_INPUTEVENT_TYPE_WHEEL: - return blink::WebInputEvent::Type::kMouseWheel; - case PP_INPUTEVENT_TYPE_RAWKEYDOWN: - return blink::WebInputEvent::Type::kRawKeyDown; - case PP_INPUTEVENT_TYPE_KEYDOWN: - return blink::WebInputEvent::Type::kKeyDown; - case PP_INPUTEVENT_TYPE_KEYUP: - return blink::WebInputEvent::Type::kKeyUp; - case PP_INPUTEVENT_TYPE_CHAR: - return blink::WebInputEvent::Type::kChar; - case PP_INPUTEVENT_TYPE_CONTEXTMENU: - return blink::WebInputEvent::Type::kContextMenu; - case PP_INPUTEVENT_TYPE_TOUCHSTART: - return blink::WebInputEvent::Type::kTouchStart; - case PP_INPUTEVENT_TYPE_TOUCHMOVE: - return blink::WebInputEvent::Type::kTouchMove; - case PP_INPUTEVENT_TYPE_TOUCHEND: - return blink::WebInputEvent::Type::kTouchEnd; - case PP_INPUTEVENT_TYPE_TOUCHCANCEL: - return blink::WebInputEvent::Type::kTouchCancel; - default: - NOTREACHED(); - return blink::WebInputEvent::Type::kUndefined; - } -} - -blink::WebPointerProperties::Button GetWebPointerPropertiesButton( - const PP_InputEvent_MouseButton& button_type) { - switch (button_type) { - case PP_INPUTEVENT_MOUSEBUTTON_LEFT: - return blink::WebPointerProperties::Button::kLeft; - case PP_INPUTEVENT_MOUSEBUTTON_MIDDLE: - return blink::WebPointerProperties::Button::kMiddle; - case PP_INPUTEVENT_MOUSEBUTTON_RIGHT: - return blink::WebPointerProperties::Button::kRight; - default: - // No other mouse button type is handled by the PDF plugin. - return blink::WebPointerProperties::Button::kNoButton; - } -} - -std::unique_ptr<blink::WebMouseEvent> GetWebMouseEvent( - const pp::MouseInputEvent& event) { - const blink::WebInputEvent::Type type = GetWebInputEventType(event.GetType()); - DCHECK(blink::WebInputEvent::IsMouseEventType(type)); - DCHECK_NE(type, blink::WebInputEvent::Type::kContextMenu); - - auto mouse_event = std::make_unique<blink::WebMouseEvent>( - type, event.GetModifiers(), - base::TimeTicks() + base::Seconds(event.GetTimeStamp())); - - mouse_event->button = GetWebPointerPropertiesButton(event.GetButton()); - mouse_event->click_count = event.GetClickCount(); - - const pp::Point& position = event.GetPosition(); - mouse_event->SetPositionInWidget(position.x(), position.y()); - - return mouse_event; -} - -std::unique_ptr<blink::WebKeyboardEvent> GetWebKeyboardEvent( - const pp::KeyboardInputEvent& event) { - const blink::WebInputEvent::Type type = GetWebInputEventType(event.GetType()); - DCHECK(blink::WebInputEvent::IsKeyboardEventType(type)); - - auto keyboard_event = std::make_unique<blink::WebKeyboardEvent>( - type, event.GetModifiers(), - base::TimeTicks() + base::Seconds(event.GetTimeStamp())); - - keyboard_event->windows_key_code = event.GetKeyCode(); - - const std::u16string text16 = - base::UTF8ToUTF16(event.GetCharacterText().AsString()); - const size_t text_len = - std::min(blink::WebKeyboardEvent::kTextLengthCap, text16.size()); - std::copy_n(text16.begin(), text_len, keyboard_event->text); - std::fill_n(keyboard_event->text + text_len, - blink::WebKeyboardEvent::kTextLengthCap - text_len, L'\0'); - - return keyboard_event; -} - -std::unique_ptr<blink::WebTouchEvent> GetWebTouchEvent( - const pp::TouchInputEvent& event) { - const blink::WebInputEvent::Type type = GetWebInputEventType(event.GetType()); - DCHECK(blink::WebInputEvent::IsTouchEventType(type)); - DCHECK_NE(type, blink::WebInputEvent::Type::kTouchScrollStarted); - - auto touch_event = std::make_unique<blink::WebTouchEvent>( - type, event.GetModifiers(), - base::TimeTicks() + base::Seconds(event.GetTimeStamp())); - - // The PDF plugin only cares about the first touch and the number of touches, - // but copy over all the touches so that `touch_event->touches_length` - // accurately stores the length of `touches`. - touch_event->touches_length = - std::min<uint32_t>(blink::WebTouchEvent::kTouchesLengthCap, - event.GetTouchCount(PP_TOUCHLIST_TYPE_TARGETTOUCHES)); - for (size_t i = 0; i < touch_event->touches_length; ++i) { - touch_event->touches[i].SetPositionInWidget(PointFFromPPFloatPoint( - event.GetTouchByIndex(PP_TOUCHLIST_TYPE_TARGETTOUCHES, i).position())); - } - - return touch_event; -} - -} // namespace - -std::unique_ptr<blink::WebInputEvent> GetWebInputEvent( - const pp::InputEvent& event) { - switch (GetWebInputEventType(event.GetType())) { - case blink::WebInputEvent::Type::kMouseDown: - case blink::WebInputEvent::Type::kMouseUp: - case blink::WebInputEvent::Type::kMouseMove: - case blink::WebInputEvent::Type::kMouseEnter: - case blink::WebInputEvent::Type::kMouseLeave: - return GetWebMouseEvent(pp::MouseInputEvent(event)); - case blink::WebInputEvent::Type::kRawKeyDown: - case blink::WebInputEvent::Type::kKeyDown: - case blink::WebInputEvent::Type::kKeyUp: - case blink::WebInputEvent::Type::kChar: - return GetWebKeyboardEvent(pp::KeyboardInputEvent(event)); - case blink::WebInputEvent::Type::kTouchStart: - case blink::WebInputEvent::Type::kTouchMove: - case blink::WebInputEvent::Type::kTouchEnd: - case blink::WebInputEvent::Type::kTouchCancel: - return GetWebTouchEvent(pp::TouchInputEvent(event)); - default: - // Don't bother converting event types not handled by the PDF plugin. - return nullptr; - } -} - -PP_CursorType_Dev PPCursorTypeFromCursorType( - ui::mojom::CursorType cursor_type) { - switch (cursor_type) { - case ui::mojom::CursorType::kPointer: - return PP_CURSORTYPE_POINTER; - case ui::mojom::CursorType::kHand: - return PP_CURSORTYPE_HAND; - case ui::mojom::CursorType::kIBeam: - return PP_CURSORTYPE_IBEAM; - default: - NOTREACHED(); - return PP_CURSORTYPE_POINTER; - } -} - -} // namespace chrome_pdf diff --git a/chromium/pdf/ppapi_migration/input_event_conversions.h b/chromium/pdf/ppapi_migration/input_event_conversions.h deleted file mode 100644 index e5fcafdb146..00000000000 --- a/chromium/pdf/ppapi_migration/input_event_conversions.h +++ /dev/null @@ -1,33 +0,0 @@ -// 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. - -#ifndef PDF_PPAPI_MIGRATION_INPUT_EVENT_CONVERSIONS_H_ -#define PDF_PPAPI_MIGRATION_INPUT_EVENT_CONVERSIONS_H_ - -#include <stdint.h> - -#include <memory> -#include <string> - -#include "ppapi/c/dev/pp_cursor_type_dev.h" -#include "ui/base/cursor/mojom/cursor_type.mojom-forward.h" - -namespace blink { -class WebInputEvent; -} // namespace blink - -namespace pp { -class InputEvent; -} // namespace pp - -namespace chrome_pdf { - -std::unique_ptr<blink::WebInputEvent> GetWebInputEvent( - const pp::InputEvent& event); - -PP_CursorType_Dev PPCursorTypeFromCursorType(ui::mojom::CursorType cursor_type); - -} // namespace chrome_pdf - -#endif // PDF_PPAPI_MIGRATION_INPUT_EVENT_CONVERSIONS_H_ diff --git a/chromium/pdf/ppapi_migration/pdfium_font_linux.cc b/chromium/pdf/ppapi_migration/pdfium_font_linux.cc deleted file mode 100644 index ab840af4b81..00000000000 --- a/chromium/pdf/ppapi_migration/pdfium_font_linux.cc +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2021 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/ppapi_migration/pdfium_font_linux.h" - -#include "base/check.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/private/pdf.h" -#include "ppapi/cpp/trusted/browser_font_trusted.h" -#include "third_party/blink/public/platform/web_font_description.h" - -namespace chrome_pdf { - -namespace { - -PP_Instance g_last_instance_id; - -constexpr PP_BrowserFont_Trusted_Weight ToPepperWeight( - blink::WebFontDescription::Weight w) { - return static_cast<PP_BrowserFont_Trusted_Weight>(w); -} - -#define FONT_WEIGHT_MATCH_ASSERT(x) \ - static_assert(PP_BROWSERFONT_TRUSTED_WEIGHT_##x == \ - ToPepperWeight(blink::WebFontDescription::kWeight##x), \ - "Font weight mismatch.") -FONT_WEIGHT_MATCH_ASSERT(100); -FONT_WEIGHT_MATCH_ASSERT(200); -FONT_WEIGHT_MATCH_ASSERT(300); -FONT_WEIGHT_MATCH_ASSERT(400); -FONT_WEIGHT_MATCH_ASSERT(500); -FONT_WEIGHT_MATCH_ASSERT(600); -FONT_WEIGHT_MATCH_ASSERT(700); -FONT_WEIGHT_MATCH_ASSERT(800); -FONT_WEIGHT_MATCH_ASSERT(900); -#undef FONT_WEIGHT_MATCH_ASSERT - -} // namespace - -void* MapPepperFont(const blink::WebFontDescription& desc, - const std::string& font_family, - int charset) { - DCHECK(pp::PDF::IsAvailable()); - DCHECK(desc.family.IsEmpty()); - - pp::BrowserFontDescription description; - - if (desc.generic_family == - blink::WebFontDescription::kGenericFamilyMonospace) { - description.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_MONOSPACE); - } else if (desc.generic_family == - blink::WebFontDescription::kGenericFamilySerif) { - description.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_SERIF); - } - - description.set_face(font_family); - description.set_weight(ToPepperWeight(desc.weight)); - description.set_italic(desc.italic); - - PP_Resource font_resource = pp::PDF::GetFontFileWithFallback( - pp::InstanceHandle(g_last_instance_id), - &description.pp_font_description(), - static_cast<PP_PrivateFontCharset>(charset)); - long res_id = font_resource; - return reinterpret_cast<void*>(res_id); -} - -unsigned long GetPepperFontData(void* font_id, - unsigned int table, - unsigned char* buffer, - unsigned long buf_size) { - DCHECK(pp::PDF::IsAvailable()); - - uint32_t size = buf_size; - long res_id = reinterpret_cast<long>(font_id); - if (!pp::PDF::GetFontTableForPrivateFontFile(res_id, table, buffer, &size)) - return 0; - return size; -} - -void DeletePepperFont(void* font_id) { - long res_id = reinterpret_cast<long>(font_id); - pp::Module::Get()->core()->ReleaseResource(res_id); -} - -void SetLastPepperInstance(pp::Instance* last_instance) { - if (last_instance) - g_last_instance_id = last_instance->pp_instance(); -} - -} // namespace chrome_pdf diff --git a/chromium/pdf/ppapi_migration/pdfium_font_linux.h b/chromium/pdf/ppapi_migration/pdfium_font_linux.h deleted file mode 100644 index 8f140743bef..00000000000 --- a/chromium/pdf/ppapi_migration/pdfium_font_linux.h +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2021 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. - -#ifndef PDF_PPAPI_MIGRATION_PDFIUM_FONT_LINUX_H_ -#define PDF_PPAPI_MIGRATION_PDFIUM_FONT_LINUX_H_ - -#include <string> - -namespace blink { -struct WebFontDescription; -} - -namespace pp { -class Instance; -} - -namespace chrome_pdf { - -// Returns a handle to the font mapped based on `desc`, `font_family`, and -// `charset`. The handle is for use as the `font_id` in `GetPepperFontData()` -// and `DeletePepperFont()` below. -void* MapPepperFont(const blink::WebFontDescription& desc, - const std::string& font_family, - int charset); - -// Reads data from the `font_id` handle for `table` into a `buffer` of -// `buf_size`. Returns the amount of data read on success, or 0 on failure. If -// `buffer` is null, then just return the required size for the buffer. -unsigned long GetPepperFontData(void* font_id, - unsigned int table, - unsigned char* buffer, - unsigned long buf_size); - -// Releases resources allocated by MapPepperFont(). -void DeletePepperFont(void* font_id); - -// Keeps track of the most recently used plugin instance. This is a no-op if -// `last_instance` is null. -void SetLastPepperInstance(pp::Instance* last_instance); - -} // namespace chrome_pdf - -#endif // PDF_PPAPI_MIGRATION_PDFIUM_FONT_LINUX_H_ diff --git a/chromium/pdf/ppapi_migration/ppapi_assert_matching_enums.cc b/chromium/pdf/ppapi_migration/ppapi_assert_matching_enums.cc deleted file mode 100644 index 6653485882f..00000000000 --- a/chromium/pdf/ppapi_migration/ppapi_assert_matching_enums.cc +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2021 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/accessibility_structs.h" -#include "pdf/content_restriction.h" -#include "pdf/ppapi_migration/result_codes.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/private/ppb_pdf.h" -#include "ppapi/c/private/ppp_pdf.h" - -namespace chrome_pdf { - -#define STATIC_ASSERT_ENUM(a, b) \ - static_assert(static_cast<int>(a) == static_cast<int>(b), \ - "mismatching enums: " #a) - -STATIC_ASSERT_ENUM(AccessibilityTextRenderMode::kUnknown, - PP_TEXTRENDERINGMODE_UNKNOWN); -STATIC_ASSERT_ENUM(AccessibilityTextRenderMode::kFill, - PP_TEXTRENDERINGMODE_FILL); -STATIC_ASSERT_ENUM(AccessibilityTextRenderMode::kStroke, - PP_TEXTRENDERINGMODE_STROKE); -STATIC_ASSERT_ENUM(AccessibilityTextRenderMode::kFillStroke, - PP_TEXTRENDERINGMODE_FILLSTROKE); -STATIC_ASSERT_ENUM(AccessibilityTextRenderMode::kInvisible, - PP_TEXTRENDERINGMODE_INVISIBLE); -STATIC_ASSERT_ENUM(AccessibilityTextRenderMode::kFillClip, - PP_TEXTRENDERINGMODE_FILLCLIP); -STATIC_ASSERT_ENUM(AccessibilityTextRenderMode::kStrokeClip, - PP_TEXTRENDERINGMODE_STROKECLIP); -STATIC_ASSERT_ENUM(AccessibilityTextRenderMode::kFillStrokeClip, - PP_TEXTRENDERINGMODE_FILLSTROKECLIP); -STATIC_ASSERT_ENUM(AccessibilityTextRenderMode::kClip, - PP_TEXTRENDERINGMODE_CLIP); -STATIC_ASSERT_ENUM(AccessibilityTextRenderMode::kMaxValue, - PP_TEXTRENDERINGMODE_LAST); - -STATIC_ASSERT_ENUM(AccessibilityTextDirection::kNone, PP_PRIVATEDIRECTION_NONE); -STATIC_ASSERT_ENUM(AccessibilityTextDirection::kLeftToRight, - PP_PRIVATEDIRECTION_LTR); -STATIC_ASSERT_ENUM(AccessibilityTextDirection::kRightToLeft, - PP_PRIVATEDIRECTION_RTL); -STATIC_ASSERT_ENUM(AccessibilityTextDirection::kTopToBottom, - PP_PRIVATEDIRECTION_TTB); -STATIC_ASSERT_ENUM(AccessibilityTextDirection::kBottomToTop, - PP_PRIVATEDIRECTION_BTT); -STATIC_ASSERT_ENUM(AccessibilityTextDirection::kMaxValue, - PP_PRIVATEDIRECTION_LAST); - -STATIC_ASSERT_ENUM(ChoiceFieldType::kListBox, PP_PRIVATECHOICEFIELD_LISTBOX); -STATIC_ASSERT_ENUM(ChoiceFieldType::kComboBox, PP_PRIVATECHOICEFIELD_COMBOBOX); -STATIC_ASSERT_ENUM(ChoiceFieldType::kMaxValue, PP_PRIVATECHOICEFIELD_LAST); - -STATIC_ASSERT_ENUM(ButtonType::kPushButton, PP_PRIVATEBUTTON_PUSHBUTTON); -STATIC_ASSERT_ENUM(ButtonType::kPushButton, PP_PRIVATEBUTTON_FIRST); -STATIC_ASSERT_ENUM(ButtonType::kCheckBox, PP_PRIVATEBUTTON_CHECKBOX); -STATIC_ASSERT_ENUM(ButtonType::kRadioButton, PP_PRIVATEBUTTON_RADIOBUTTON); -STATIC_ASSERT_ENUM(ButtonType::kMaxValue, PP_PRIVATEBUTTON_LAST); - -STATIC_ASSERT_ENUM(FocusObjectType::kNone, PP_PRIVATEFOCUSOBJECT_NONE); -STATIC_ASSERT_ENUM(FocusObjectType::kDocument, PP_PRIVATEFOCUSOBJECT_DOCUMENT); -STATIC_ASSERT_ENUM(FocusObjectType::kLink, PP_PRIVATEFOCUSOBJECT_LINK); -STATIC_ASSERT_ENUM(FocusObjectType::kHighlight, - PP_PRIVATEFOCUSOBJECT_HIGHLIGHT); -STATIC_ASSERT_ENUM(FocusObjectType::kTextField, - PP_PRIVATEFOCUSOBJECT_TEXT_FIELD); -STATIC_ASSERT_ENUM(FocusObjectType::kMaxValue, PP_PRIVATEFOCUSOBJECT_LAST); - -STATIC_ASSERT_ENUM(AccessibilityAction::kNone, PP_PDF_ACTION_NONE); -STATIC_ASSERT_ENUM(AccessibilityAction::kScrollToMakeVisible, - PP_PDF_SCROLL_TO_MAKE_VISIBLE); -STATIC_ASSERT_ENUM(AccessibilityAction::kDoDefaultAction, - PP_PDF_DO_DEFAULT_ACTION); -STATIC_ASSERT_ENUM(AccessibilityAction::kScrollToGlobalPoint, - PP_PDF_SCROLL_TO_GLOBAL_POINT); -STATIC_ASSERT_ENUM(AccessibilityAction::kSetSelection, PP_PDF_SET_SELECTION); -STATIC_ASSERT_ENUM(AccessibilityAction::kMaxValue, - PP_PDF_ACCESSIBILITYACTION_LAST); - -STATIC_ASSERT_ENUM(AccessibilityAnnotationType::kNone, PP_PDF_TYPE_NONE); -STATIC_ASSERT_ENUM(AccessibilityAnnotationType::kLink, PP_PDF_LINK); -STATIC_ASSERT_ENUM(AccessibilityAnnotationType::kMaxValue, - PP_PDF_ACCESSIBILITY_ANNOTATIONTYPE_LAST); - -STATIC_ASSERT_ENUM(AccessibilityScrollAlignment::kNone, PP_PDF_SCROLL_NONE); -STATIC_ASSERT_ENUM(AccessibilityScrollAlignment::kCenter, - PP_PDF_SCROLL_ALIGNMENT_CENTER); -STATIC_ASSERT_ENUM(AccessibilityScrollAlignment::kTop, - PP_PDF_SCROLL_ALIGNMENT_TOP); -STATIC_ASSERT_ENUM(AccessibilityScrollAlignment::kBottom, - PP_PDF_SCROLL_ALIGNMENT_BOTTOM); -STATIC_ASSERT_ENUM(AccessibilityScrollAlignment::kLeft, - PP_PDF_SCROLL_ALIGNMENT_LEFT); -STATIC_ASSERT_ENUM(AccessibilityScrollAlignment::kRight, - PP_PDF_SCROLL_ALIGNMENT_RIGHT); -STATIC_ASSERT_ENUM(AccessibilityScrollAlignment::kClosestToEdge, - PP_PDF_SCROLL_ALIGNMENT_CLOSEST_EDGE); -STATIC_ASSERT_ENUM(AccessibilityScrollAlignment::kMaxValue, - PP_PDF_ACCESSIBILITYSCROLLALIGNMENT_LAST); - -STATIC_ASSERT_ENUM(kContentRestrictionCopy, PP_CONTENT_RESTRICTION_COPY); -STATIC_ASSERT_ENUM(kContentRestrictionCut, PP_CONTENT_RESTRICTION_CUT); -STATIC_ASSERT_ENUM(kContentRestrictionPaste, PP_CONTENT_RESTRICTION_PASTE); -STATIC_ASSERT_ENUM(kContentRestrictionPrint, PP_CONTENT_RESTRICTION_PRINT); -STATIC_ASSERT_ENUM(kContentRestrictionSave, PP_CONTENT_RESTRICTION_SAVE); - -STATIC_ASSERT_ENUM(Result::kSuccess, PP_OK); -STATIC_ASSERT_ENUM(Result::kErrorFailed, PP_ERROR_FAILED); -STATIC_ASSERT_ENUM(Result::kErrorAborted, PP_ERROR_ABORTED); -STATIC_ASSERT_ENUM(Result::kErrorBadArgument, PP_ERROR_BADARGUMENT); -STATIC_ASSERT_ENUM(Result::kErrorNoAccess, PP_ERROR_NOACCESS); - -} // namespace chrome_pdf diff --git a/chromium/pdf/ppapi_migration/printing_conversions.cc b/chromium/pdf/ppapi_migration/printing_conversions.cc deleted file mode 100644 index 254c8fa3df0..00000000000 --- a/chromium/pdf/ppapi_migration/printing_conversions.cc +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2021 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/ppapi_migration/printing_conversions.h" - -#include <stdint.h> - -#include <vector> - -#include "base/check.h" -#include "pdf/ppapi_migration/geometry_conversions.h" -#include "ppapi/c/dev/pp_print_settings_dev.h" -#include "ppapi/c/dev/ppp_printing_dev.h" -#include "ppapi/c/pp_bool.h" -#include "ppapi/c/private/ppp_pdf.h" -#include "printing/mojom/print.mojom.h" -#include "third_party/blink/public/web/web_print_params.h" -#include "third_party/blink/public/web/web_print_preset_options.h" - -namespace chrome_pdf { - -std::vector<int> PageNumbersFromPPPrintPageNumberRange( - const PP_PrintPageNumberRange_Dev* page_ranges, - uint32_t page_range_count) { - DCHECK(page_range_count); - - std::vector<int> page_numbers; - for (uint32_t i = 0; i < page_range_count; ++i) { - for (uint32_t page_number = page_ranges[i].first_page_number; - page_number <= page_ranges[i].last_page_number; ++page_number) { - page_numbers.push_back(page_number); - } - } - - return page_numbers; -} - -PP_PdfPrintPresetOptions_Dev PPPdfPrintPresetOptionsFromWebPrintPresetOptions( - const blink::WebPrintPresetOptions& print_preset_options) { - PP_PdfPrintPresetOptions_Dev options; - options.is_scaling_disabled = - PP_FromBool(print_preset_options.is_scaling_disabled); - options.copies = print_preset_options.copies; - - switch (print_preset_options.duplex_mode) { - case printing::mojom::DuplexMode::kUnknownDuplexMode: - options.duplex = PP_PRIVATEDUPLEXMODE_NONE; - break; - case printing::mojom::DuplexMode::kSimplex: - options.duplex = PP_PRIVATEDUPLEXMODE_SIMPLEX; - break; - case printing::mojom::DuplexMode::kLongEdge: - options.duplex = PP_PRIVATEDUPLEXMODE_LONG_EDGE; - break; - case printing::mojom::DuplexMode::kShortEdge: - options.duplex = PP_PRIVATEDUPLEXMODE_SHORT_EDGE; - break; - } - - options.is_page_size_uniform = - PP_FromBool(print_preset_options.uniform_page_size.has_value()); - options.uniform_page_size = PPSizeFromSize( - print_preset_options.uniform_page_size.value_or(gfx::Size())); - - return options; -} - -blink::WebPrintParams WebPrintParamsFromPPPrintSettings( - const PP_PrintSettings_Dev& print_settings, - const PP_PdfPrintSettings_Dev& pdf_print_settings) { - blink::WebPrintParams params; - params.print_content_area = RectFromPPRect(print_settings.content_area); - params.printable_area = RectFromPPRect(print_settings.printable_area); - params.paper_size = SizeFromPPSize(print_settings.paper_size); - params.printer_dpi = print_settings.dpi; - params.scale_factor = pdf_print_settings.scale_factor; - params.rasterize_pdf = print_settings.format & PP_PRINTOUTPUTFORMAT_RASTER; - params.print_scaling_option = - static_cast<printing::mojom::PrintScalingOption>( - print_settings.print_scaling_option); - params.pages_per_sheet = pdf_print_settings.pages_per_sheet; - return params; -} - -} // namespace chrome_pdf diff --git a/chromium/pdf/ppapi_migration/printing_conversions.h b/chromium/pdf/ppapi_migration/printing_conversions.h deleted file mode 100644 index 7408872e895..00000000000 --- a/chromium/pdf/ppapi_migration/printing_conversions.h +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2021 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. - -#ifndef PDF_PPAPI_MIGRATION_PRINTING_CONVERSIONS_H_ -#define PDF_PPAPI_MIGRATION_PRINTING_CONVERSIONS_H_ - -#include <stdint.h> - -#include <vector> - -struct PP_PrintPageNumberRange_Dev; -struct PP_PrintSettings_Dev; -struct PP_PdfPrintPresetOptions_Dev; -struct PP_PdfPrintSettings_Dev; - -namespace blink { -struct WebPrintParams; -struct WebPrintPresetOptions; -} // namespace blink - -namespace chrome_pdf { - -std::vector<int> PageNumbersFromPPPrintPageNumberRange( - const PP_PrintPageNumberRange_Dev* page_ranges, - uint32_t page_range_count); - -PP_PdfPrintPresetOptions_Dev PPPdfPrintPresetOptionsFromWebPrintPresetOptions( - const blink::WebPrintPresetOptions& print_preset_options); - -blink::WebPrintParams WebPrintParamsFromPPPrintSettings( - const PP_PrintSettings_Dev& print_settings, - const PP_PdfPrintSettings_Dev& pdf_print_settings); - -} // namespace chrome_pdf - -#endif // PDF_PPAPI_MIGRATION_PRINTING_CONVERSIONS_H_ diff --git a/chromium/pdf/ppapi_migration/printing_conversions_unittest.cc b/chromium/pdf/ppapi_migration/printing_conversions_unittest.cc deleted file mode 100644 index 0bd0e1f0763..00000000000 --- a/chromium/pdf/ppapi_migration/printing_conversions_unittest.cc +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2021 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/ppapi_migration/printing_conversions.h" - -#include <stdint.h> - -#include <vector> - -#include "base/cxx17_backports.h" -#include "ppapi/c/dev/ppp_printing_dev.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace chrome_pdf { - -namespace { - -using ::testing::ElementsAre; -using ::testing::IsEmpty; - -} // namespace - -TEST(PrintingConversionsTest, SingleOnePageRange) { - static constexpr PP_PrintPageNumberRange_Dev kRanges[] = {{1, 1}}; - EXPECT_THAT( - PageNumbersFromPPPrintPageNumberRange(kRanges, base::size(kRanges)), - ElementsAre(1)); -} - -TEST(PrintingConversionsTest, SingleMultiPageRange) { - static constexpr PP_PrintPageNumberRange_Dev kRanges[] = {{1, 3}}; - EXPECT_THAT( - PageNumbersFromPPPrintPageNumberRange(kRanges, base::size(kRanges)), - ElementsAre(1, 2, 3)); -} - -TEST(PrintingConversionsTest, MultipleOnePageRange) { - static constexpr PP_PrintPageNumberRange_Dev kRanges[] = {{1, 1}, {3, 3}}; - EXPECT_THAT( - PageNumbersFromPPPrintPageNumberRange(kRanges, base::size(kRanges)), - ElementsAre(1, 3)); -} - -TEST(PrintingConversionsTest, MultipleMultiPageRange) { - static constexpr PP_PrintPageNumberRange_Dev kRanges[] = {{1, 3}, {5, 6}}; - EXPECT_THAT( - PageNumbersFromPPPrintPageNumberRange(kRanges, base::size(kRanges)), - ElementsAre(1, 2, 3, 5, 6)); -} - -TEST(PrintingConversionsTest, OverlappingPageRange) { - static constexpr PP_PrintPageNumberRange_Dev kRanges[] = {{1, 3}, {2, 4}}; - EXPECT_THAT( - PageNumbersFromPPPrintPageNumberRange(kRanges, base::size(kRanges)), - ElementsAre(1, 2, 3, 2, 3, 4)); -} - -} // namespace chrome_pdf diff --git a/chromium/pdf/ppapi_migration/url_loader.cc b/chromium/pdf/ppapi_migration/url_loader.cc index ce1d01c7b5a..0b66662341f 100644 --- a/chromium/pdf/ppapi_migration/url_loader.cc +++ b/chromium/pdf/ppapi_migration/url_loader.cc @@ -19,16 +19,7 @@ #include "net/base/net_errors.h" #include "net/cookies/site_for_cookies.h" #include "net/http/http_util.h" -#include "pdf/ppapi_migration/callback.h" #include "pdf/ppapi_migration/result_codes.h" -#include "ppapi/c/trusted/ppb_url_loader_trusted.h" -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/instance_handle.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/url_loader.h" -#include "ppapi/cpp/url_request_info.h" -#include "ppapi/cpp/url_response_info.h" -#include "ppapi/cpp/var.h" #include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-shared.h" #include "third_party/blink/public/platform/web_data.h" #include "third_party/blink/public/platform/web_http_body.h" @@ -96,7 +87,8 @@ void BlinkUrlLoader::GrantUniversalAccess() { } // Modeled on `content::PepperURLLoaderHost::OnHostMsgOpen()`. -void BlinkUrlLoader::Open(const UrlRequest& request, ResultCallback callback) { +void BlinkUrlLoader::Open(const UrlRequest& request, + base::OnceCallback<void(int)> callback) { DCHECK_EQ(state_, LoadingState::kWaitingToOpen); DCHECK(callback); state_ = LoadingState::kOpening; @@ -159,7 +151,7 @@ void BlinkUrlLoader::Open(const UrlRequest& request, ResultCallback callback) { // Modeled on `ppapi::proxy::URLLoaderResource::ReadResponseBody()`. void BlinkUrlLoader::ReadResponseBody(base::span<char> buffer, - ResultCallback callback) { + base::OnceCallback<void(int)> callback) { // Can be in `kLoadComplete` if still reading after loading finished. DCHECK(state_ == LoadingState::kStreamingData || state_ == LoadingState::kLoadComplete) @@ -327,76 +319,4 @@ void BlinkUrlLoader::SetLoadComplete(int32_t result) { blink_loader_.reset(); } -PepperUrlLoader::PepperUrlLoader(pp::InstanceHandle plugin_instance) - : plugin_instance_(plugin_instance), pepper_loader_(plugin_instance) {} - -PepperUrlLoader::~PepperUrlLoader() = default; - -void PepperUrlLoader::GrantUniversalAccess() { - const PPB_URLLoaderTrusted* trusted_interface = - static_cast<const PPB_URLLoaderTrusted*>( - pp::Module::Get()->GetBrowserInterface( - PPB_URLLOADERTRUSTED_INTERFACE)); - if (trusted_interface) - trusted_interface->GrantUniversalAccess(pepper_loader_.pp_resource()); -} - -void PepperUrlLoader::Open(const UrlRequest& request, ResultCallback callback) { - pp::URLRequestInfo pp_request(plugin_instance_); - pp_request.SetURL(request.url); - pp_request.SetMethod(request.method); - pp_request.SetCustomReferrerURL(request.url); - - if (request.ignore_redirects) - pp_request.SetFollowRedirects(false); - - if (!request.custom_referrer_url.empty()) - pp_request.SetCustomReferrerURL(request.custom_referrer_url); - - if (!request.headers.empty()) - pp_request.SetHeaders(request.headers); - - if (!request.body.empty()) - pp_request.AppendDataToBody(request.body.data(), request.body.size()); - - pp::CompletionCallback pp_callback = PPCompletionCallbackFromResultCallback( - base::BindOnce(&PepperUrlLoader::DidOpen, weak_factory_.GetWeakPtr(), - std::move(callback))); - int32_t result = pepper_loader_.Open(pp_request, pp_callback); - if (result != PP_OK_COMPLETIONPENDING) - pp_callback.Run(result); -} - -void PepperUrlLoader::ReadResponseBody(base::span<char> buffer, - ResultCallback callback) { - pp::CompletionCallback pp_callback = - PPCompletionCallbackFromResultCallback(std::move(callback)); - int32_t result = pepper_loader_.ReadResponseBody(buffer.data(), buffer.size(), - pp_callback); - if (result != PP_OK_COMPLETIONPENDING) - pp_callback.Run(result); -} - -void PepperUrlLoader::Close() { - pepper_loader_.Close(); -} - -void PepperUrlLoader::DidOpen(ResultCallback callback, int32_t result) { - pp::URLResponseInfo pp_response = pepper_loader_.GetResponseInfo(); - if (pp_response.is_null()) { - DCHECK_NE(result, kSuccess); - } else { - mutable_response().status_code = pp_response.GetStatusCode(); - - pp::Var headers_var = pp_response.GetHeaders(); - if (headers_var.is_string()) { - mutable_response().headers = headers_var.AsString(); - } else { - mutable_response().headers.clear(); - } - } - - std::move(callback).Run(result); -} - } // namespace chrome_pdf diff --git a/chromium/pdf/ppapi_migration/url_loader.h b/chromium/pdf/ppapi_migration/url_loader.h index ac641af3bfa..00d4be7919b 100644 --- a/chromium/pdf/ppapi_migration/url_loader.h +++ b/chromium/pdf/ppapi_migration/url_loader.h @@ -15,9 +15,6 @@ #include "base/containers/circular_deque.h" #include "base/containers/span.h" #include "base/memory/weak_ptr.h" -#include "pdf/ppapi_migration/callback.h" -#include "ppapi/cpp/instance_handle.h" -#include "ppapi/cpp/url_loader.h" #include "third_party/blink/public/web/web_associated_url_loader_client.h" namespace blink { @@ -102,9 +99,10 @@ class UrlLoader { virtual void GrantUniversalAccess() = 0; // Mimic `pp::URLLoader`: - virtual void Open(const UrlRequest& request, ResultCallback callback) = 0; + virtual void Open(const UrlRequest& request, + base::OnceCallback<void(int)> callback) = 0; virtual void ReadResponseBody(base::span<char> buffer, - ResultCallback callback) = 0; + base::OnceCallback<void(int)> callback) = 0; virtual void Close() = 0; // Returns the URL response (not including the body). Only valid after @@ -163,9 +161,10 @@ class BlinkUrlLoader final : public UrlLoader, // UrlLoader: void GrantUniversalAccess() override; - void Open(const UrlRequest& request, ResultCallback callback) override; + void Open(const UrlRequest& request, + base::OnceCallback<void(int)> callback) override; void ReadResponseBody(base::span<char> buffer, - ResultCallback callback) override; + base::OnceCallback<void(int)> callback) override; void Close() override; // blink::WebAssociatedURLLoaderClient: @@ -214,7 +213,7 @@ class BlinkUrlLoader final : public UrlLoader, std::unique_ptr<blink::WebAssociatedURLLoader> blink_loader_; bool ignore_redirects_ = false; - ResultCallback open_callback_; + base::OnceCallback<void(int)> open_callback_; // Thresholds control buffer throttling, as defined in `UrlRequest`. size_t buffer_lower_threshold_ = 0; @@ -222,34 +221,10 @@ class BlinkUrlLoader final : public UrlLoader, bool deferring_loading_ = false; base::circular_deque<char> buffer_; - ResultCallback read_callback_; + base::OnceCallback<void(int)> read_callback_; base::span<char> client_buffer_; }; -// A Pepper URL loader. -class PepperUrlLoader final : public UrlLoader { - public: - explicit PepperUrlLoader(pp::InstanceHandle plugin_instance); - PepperUrlLoader(const PepperUrlLoader&) = delete; - PepperUrlLoader& operator=(const PepperUrlLoader&) = delete; - ~PepperUrlLoader() override; - - // UrlLoader: - void GrantUniversalAccess() override; - void Open(const UrlRequest& request, ResultCallback callback) override; - void ReadResponseBody(base::span<char> buffer, - ResultCallback callback) override; - void Close() override; - - private: - void DidOpen(ResultCallback callback, int32_t result); - - pp::InstanceHandle plugin_instance_; - pp::URLLoader pepper_loader_; - - base::WeakPtrFactory<PepperUrlLoader> weak_factory_{this}; -}; - } // namespace chrome_pdf #endif // PDF_PPAPI_MIGRATION_URL_LOADER_H_ diff --git a/chromium/pdf/ppapi_migration/url_loader_unittest.cc b/chromium/pdf/ppapi_migration/url_loader_unittest.cc index b4d1559c14c..18a4a8cd868 100644 --- a/chromium/pdf/ppapi_migration/url_loader_unittest.cc +++ b/chromium/pdf/ppapi_migration/url_loader_unittest.cc @@ -22,7 +22,6 @@ #include "base/test/mock_callback.h" #include "net/base/net_errors.h" #include "net/cookies/site_for_cookies.h" -#include "pdf/ppapi_migration/callback.h" #include "pdf/ppapi_migration/result_codes.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -181,7 +180,7 @@ class BlinkUrlLoaderTest : public testing::Test { } FakeBlinkUrlLoaderClient fake_client_; - NiceMock<base::MockCallback<ResultCallback>> mock_callback_; + NiceMock<base::MockCallback<base::OnceCallback<void(int)>>> mock_callback_; std::unique_ptr<BlinkUrlLoader> loader_; // Becomes invalid if `loader_` is closed or destructed. diff --git a/chromium/pdf/ppapi_migration/value_conversions.cc b/chromium/pdf/ppapi_migration/value_conversions.cc deleted file mode 100644 index 7cdf31fdd2e..00000000000 --- a/chromium/pdf/ppapi_migration/value_conversions.cc +++ /dev/null @@ -1,109 +0,0 @@ -// 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/ppapi_migration/value_conversions.h" - -#include <algorithm> - -#include "base/containers/span.h" -#include "base/notreached.h" -#include "base/values.h" -#include "ppapi/cpp/var.h" -#include "ppapi/cpp/var_array.h" -#include "ppapi/cpp/var_array_buffer.h" -#include "ppapi/cpp/var_dictionary.h" - -namespace chrome_pdf { - -pp::Var VarFromValue(const base::Value& value) { - switch (value.type()) { - case base::Value::Type::NONE: - return pp::Var::Null(); - case base::Value::Type::BOOLEAN: - return pp::Var(value.GetBool()); - case base::Value::Type::INTEGER: - return pp::Var(value.GetInt()); - case base::Value::Type::DOUBLE: - return pp::Var(value.GetDouble()); - case base::Value::Type::STRING: - return pp::Var(value.GetString()); - case base::Value::Type::BINARY: { - const base::Value::BlobStorage& blob = value.GetBlob(); - pp::VarArrayBuffer buffer(blob.size()); - std::copy(blob.begin(), blob.end(), static_cast<uint8_t*>(buffer.Map())); - return buffer; - } - case base::Value::Type::DICTIONARY: { - pp::VarDictionary var_dict; - for (auto value_pair : value.DictItems()) { - var_dict.Set(value_pair.first, VarFromValue(value_pair.second)); - } - return var_dict; - } - case base::Value::Type::LIST: { - pp::VarArray var_array; - uint32_t i = 0; - for (const auto& val : value.GetListDeprecated()) { - var_array.Set(i, VarFromValue(val)); - i++; - } - return var_array; - } - } -} - -base::Value ValueFromVar(const pp::Var& var) { - switch (var.pp_var().type) { - case PP_VARTYPE_UNDEFINED: - return base::Value(); - case PP_VARTYPE_NULL: - return base::Value(); - case PP_VARTYPE_BOOL: - return base::Value(var.AsBool()); - case PP_VARTYPE_INT32: - return base::Value(var.AsInt()); - case PP_VARTYPE_DOUBLE: - return base::Value(var.AsDouble()); - case PP_VARTYPE_STRING: - return base::Value(var.AsString()); - case PP_VARTYPE_OBJECT: - // There is no valid conversion from PP_VARTYPE_OBJECT to a base::Value - // type. This should not be called to convert this type. - NOTREACHED(); - return base::Value(); - case PP_VARTYPE_ARRAY: { - pp::VarArray var_array(var); - base::Value::ListStorage list_storage(var_array.GetLength()); - for (uint32_t i = 0; i < var_array.GetLength(); ++i) { - list_storage[i] = ValueFromVar(var_array.Get(i)); - } - return base::Value(std::move(list_storage)); - } - case PP_VARTYPE_DICTIONARY: { - base::Value val_dictionary(base::Value::Type::DICTIONARY); - pp::VarDictionary var_dict(var); - pp::VarArray dict_keys = var_dict.GetKeys(); - for (uint32_t i = 0; i < dict_keys.GetLength(); ++i) { - pp::Var key = dict_keys.Get(i); - val_dictionary.SetKey(key.AsString(), ValueFromVar(var_dict.Get(key))); - } - return val_dictionary; - } - case PP_VARTYPE_ARRAY_BUFFER: { - pp::VarArrayBuffer var_array_buffer(var); - base::Value value( - base::make_span(static_cast<uint8_t*>(var_array_buffer.Map()), - var_array_buffer.ByteLength())); - var_array_buffer.Unmap(); - return value; - } - case PP_VARTYPE_RESOURCE: - // There is no valid conversion from PP_VARTYPE_RESOURCE to a base::Value - // type. This should not be called to convert this type. - NOTREACHED(); - return base::Value(); - } -} - -} // namespace chrome_pdf diff --git a/chromium/pdf/ppapi_migration/value_conversions.h b/chromium/pdf/ppapi_migration/value_conversions.h deleted file mode 100644 index edfea999812..00000000000 --- a/chromium/pdf/ppapi_migration/value_conversions.h +++ /dev/null @@ -1,23 +0,0 @@ -// 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. - -#ifndef PDF_PPAPI_MIGRATION_VALUE_CONVERSIONS_H_ -#define PDF_PPAPI_MIGRATION_VALUE_CONVERSIONS_H_ - -namespace base { -class Value; -} // namespace base - -namespace pp { -class Var; -} // namespace pp - -namespace chrome_pdf { - -pp::Var VarFromValue(const base::Value& value); -base::Value ValueFromVar(const pp::Var& var); - -} // namespace chrome_pdf - -#endif // PDF_PPAPI_MIGRATION_VALUE_CONVERSIONS_H_ diff --git a/chromium/pdf/preview_mode_client.cc b/chromium/pdf/preview_mode_client.cc index 6971c81e9f3..1d3bb1ad639 100644 --- a/chromium/pdf/preview_mode_client.cc +++ b/chromium/pdf/preview_mode_client.cc @@ -173,12 +173,4 @@ bool PreviewModeClient::IsValidLink(const std::string& url) { return false; } -void PreviewModeClient::ScheduleTaskOnMainThread( - const base::Location& from_here, - ResultCallback callback, - int32_t result, - base::TimeDelta delay) { - NOTREACHED(); -} - } // namespace chrome_pdf diff --git a/chromium/pdf/preview_mode_client.h b/chromium/pdf/preview_mode_client.h index ee609e6034a..05f1cb8d7e8 100644 --- a/chromium/pdf/preview_mode_client.h +++ b/chromium/pdf/preview_mode_client.h @@ -71,10 +71,6 @@ class PreviewModeClient : public PDFEngine::Client { void SetSelectedText(const std::string& selected_text) override; void SetLinkUnderCursor(const std::string& link_under_cursor) override; bool IsValidLink(const std::string& url) override; - void ScheduleTaskOnMainThread(const base::Location& from_here, - ResultCallback callback, - int32_t result, - base::TimeDelta delay) override; private: const raw_ptr<Client> client_; diff --git a/chromium/pdf/ui/thumbnail.cc b/chromium/pdf/ui/thumbnail.cc index b45225e801b..b3b794db255 100644 --- a/chromium/pdf/ui/thumbnail.cc +++ b/chromium/pdf/ui/thumbnail.cc @@ -38,7 +38,7 @@ constexpr int kMaxThumbnailPixels = 255 * 1024 / kImageColorChannels; // Maximum CSS dimensions are set to match UX specifications. // These constants should be kept in sync with `PORTRAIT_WIDTH` and // `LANDSCAPE_WIDTH` in -// chrome/browser/resources/pdf/elements/viewer-thumbnail.js. +// chrome/browser/resources/pdf/elements/viewer-thumbnail.ts. constexpr int kMaxWidthPortraitPx = 108; constexpr int kMaxWidthLandscapePx = 140; diff --git a/chromium/pdf/url_loader_wrapper.h b/chromium/pdf/url_loader_wrapper.h index c2f21fce350..592a38204c7 100644 --- a/chromium/pdf/url_loader_wrapper.h +++ b/chromium/pdf/url_loader_wrapper.h @@ -9,7 +9,7 @@ #include <string> -#include "pdf/ppapi_migration/callback.h" +#include "base/callback_forward.h" namespace chrome_pdf { @@ -50,14 +50,14 @@ class URLLoaderWrapper { const std::string& referrer_url, uint32_t position, uint32_t size, - ResultCallback callback) = 0; + base::OnceCallback<void(int)> callback) = 0; // Read the response body. The size of the buffer must be large enough to // hold the specified number of bytes to read. // This function might perform a partial read. virtual void ReadResponseBody(char* buffer, int buffer_size, - ResultCallback callback) = 0; + base::OnceCallback<void(int)> callback) = 0; }; } // namespace chrome_pdf diff --git a/chromium/pdf/url_loader_wrapper_impl.cc b/chromium/pdf/url_loader_wrapper_impl.cc index 1a87bf2e16e..9cb596e666e 100644 --- a/chromium/pdf/url_loader_wrapper_impl.cc +++ b/chromium/pdf/url_loader_wrapper_impl.cc @@ -154,16 +154,17 @@ void URLLoaderWrapperImpl::OpenRange(const std::string& url, const std::string& referrer_url, uint32_t position, uint32_t size, - ResultCallback callback) { + base::OnceCallback<void(int)> callback) { url_loader_->Open( MakeRangeRequest(url, referrer_url, position, size), base::BindOnce(&URLLoaderWrapperImpl::DidOpen, weak_factory_.GetWeakPtr(), std::move(callback))); } -void URLLoaderWrapperImpl::ReadResponseBody(char* buffer, - int buffer_size, - ResultCallback callback) { +void URLLoaderWrapperImpl::ReadResponseBody( + char* buffer, + int buffer_size, + base::OnceCallback<void(int)> callback) { buffer_ = buffer; buffer_size_ = buffer_size; read_starter_.Start( @@ -172,7 +173,8 @@ void URLLoaderWrapperImpl::ReadResponseBody(char* buffer, base::Unretained(this), std::move(callback))); } -void URLLoaderWrapperImpl::ReadResponseBodyImpl(ResultCallback callback) { +void URLLoaderWrapperImpl::ReadResponseBodyImpl( + base::OnceCallback<void(int)> callback) { url_loader_->ReadResponseBody( base::make_span(buffer_.get(), buffer_size_), base::BindOnce(&URLLoaderWrapperImpl::DidRead, weak_factory_.GetWeakPtr(), @@ -231,12 +233,14 @@ void URLLoaderWrapperImpl::ParseHeaders(const std::string& response_headers) { } } -void URLLoaderWrapperImpl::DidOpen(ResultCallback callback, int32_t result) { +void URLLoaderWrapperImpl::DidOpen(base::OnceCallback<void(int)> callback, + int32_t result) { SetHeadersFromLoader(); std::move(callback).Run(result); } -void URLLoaderWrapperImpl::DidRead(ResultCallback callback, int32_t result) { +void URLLoaderWrapperImpl::DidRead(base::OnceCallback<void(int)> callback, + int32_t result) { if (multi_part_processed_) { // Reset this flag so we look inside the buffer in calls of DidRead for this // response only once. Note that this code DOES NOT handle multi part diff --git a/chromium/pdf/url_loader_wrapper_impl.h b/chromium/pdf/url_loader_wrapper_impl.h index 471267dabb0..ac363591597 100644 --- a/chromium/pdf/url_loader_wrapper_impl.h +++ b/chromium/pdf/url_loader_wrapper_impl.h @@ -10,10 +10,10 @@ #include <memory> #include <string> +#include "base/callback_forward.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/timer/timer.h" -#include "pdf/ppapi_migration/callback.h" #include "pdf/url_loader_wrapper.h" #include "ui/gfx/range/range.h" @@ -42,18 +42,18 @@ class URLLoaderWrapperImpl : public URLLoaderWrapper { const std::string& referrer_url, uint32_t position, uint32_t size, - ResultCallback callback) override; + base::OnceCallback<void(int)> callback) override; void ReadResponseBody(char* buffer, int buffer_size, - ResultCallback callback) override; + base::OnceCallback<void(int)> callback) override; private: void SetHeadersFromLoader(); void ParseHeaders(const std::string& response_headers); - void DidOpen(ResultCallback callback, int32_t result); - void DidRead(ResultCallback callback, int32_t result); + void DidOpen(base::OnceCallback<void(int)> callback, int32_t result); + void DidRead(base::OnceCallback<void(int)> callback, int32_t result); - void ReadResponseBodyImpl(ResultCallback callback); + void ReadResponseBodyImpl(base::OnceCallback<void(int)> callback); std::unique_ptr<UrlLoader> url_loader_; diff --git a/chromium/pdf/v8_value_converter.h b/chromium/pdf/v8_value_converter.h new file mode 100644 index 00000000000..4b36afee492 --- /dev/null +++ b/chromium/pdf/v8_value_converter.h @@ -0,0 +1,37 @@ +// Copyright 2022 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. + +#ifndef PDF_V8_VALUE_CONVERTER_H_ +#define PDF_V8_VALUE_CONVERTER_H_ + +#include <memory> + +#include "v8/include/v8-forward.h" + +namespace base { +class Value; +} // namespace base + +namespace chrome_pdf { + +// Abstraction layer for base::Value from/to V8::Value conversions. +// Necessary because //pdf should not directly depend on //content. If the V8 +// V8 value conversion code ever moves into Blink, remove this and use the +// conversion code from Blink directly. + +class V8ValueConverter { + public: + virtual std::unique_ptr<base::Value> FromV8Value( + v8::Local<v8::Value> value, + v8::Local<v8::Context> context) = 0; + virtual v8::Local<v8::Value> ToV8Value(const base::Value& value, + v8::Local<v8::Context> context) = 0; + + protected: + ~V8ValueConverter() = default; +}; + +} // namespace chrome_pdf + +#endif // PDF_V8_VALUE_CONVERTER_H_ |