summaryrefslogtreecommitdiff
path: root/chromium/pdf
diff options
context:
space:
mode:
authorPaulo Pinheiro <paulovap.os@gmail.com>2016-04-07 11:32:51 -0300
committerPaulo Pinheiro <paulovap.os@gmail.com>2016-04-13 13:15:37 +0000
commite692e2497792ab1afe57353aa700270859ebadf7 (patch)
tree0b6d73b53b4f889e27a6f8466795cc1e1aaf3877 /chromium/pdf
parentf65c42f8a6395a5fd85719adda57ada167b0dab6 (diff)
downloadqtwebengine-chromium-e692e2497792ab1afe57353aa700270859ebadf7.tar.gz
Added PDF related files to Chromium snapshot.
Adds all the files needed to build the PPAPI PDF plugin. The plugin is needed to enable Chrome's internal PDF viewer. Change-Id: I30dcf2048b3f5fc3dc93d557c3c3bec9309961c3 Reviewed-by: Michael BrĂ¼ning <michael.bruning@theqtcompany.com>
Diffstat (limited to 'chromium/pdf')
-rw-r--r--chromium/pdf/BUILD.gn67
-rw-r--r--chromium/pdf/DEPS12
-rw-r--r--chromium/pdf/OWNERS5
-rw-r--r--chromium/pdf/chunk_stream.cc175
-rw-r--r--chromium/pdf/chunk_stream.h53
-rw-r--r--chromium/pdf/document_loader.cc545
-rw-r--r--chromium/pdf/document_loader.h136
-rw-r--r--chromium/pdf/draw_utils.cc357
-rw-r--r--chromium/pdf/draw_utils.h99
-rw-r--r--chromium/pdf/out_of_process_instance.cc1445
-rw-r--r--chromium/pdf/out_of_process_instance.h350
-rw-r--r--chromium/pdf/paint_aggregator.cc291
-rw-r--r--chromium/pdf/paint_aggregator.h130
-rw-r--r--chromium/pdf/paint_manager.cc304
-rw-r--r--chromium/pdf/paint_manager.h207
-rw-r--r--chromium/pdf/pdf.cc182
-rw-r--r--chromium/pdf/pdf.h113
-rw-r--r--chromium/pdf/pdf_engine.h345
-rw-r--r--chromium/pdf/pdfium/pdfium_api_string_buffer_adapter.cc88
-rw-r--r--chromium/pdf/pdfium/pdfium_api_string_buffer_adapter.h101
-rw-r--r--chromium/pdf/pdfium/pdfium_assert_matching_enums.cc213
-rw-r--r--chromium/pdf/pdfium/pdfium_engine.cc3953
-rw-r--r--chromium/pdf/pdfium/pdfium_engine.h757
-rw-r--r--chromium/pdf/pdfium/pdfium_mem_buffer_file_read.cc35
-rw-r--r--chromium/pdf/pdfium/pdfium_mem_buffer_file_read.h31
-rw-r--r--chromium/pdf/pdfium/pdfium_mem_buffer_file_write.cc33
-rw-r--r--chromium/pdf/pdfium/pdfium_mem_buffer_file_write.h36
-rw-r--r--chromium/pdf/pdfium/pdfium_page.cc534
-rw-r--r--chromium/pdf/pdfium/pdfium_page.h147
-rw-r--r--chromium/pdf/pdfium/pdfium_range.cc82
-rw-r--r--chromium/pdf/pdfium/pdfium_range.h54
-rw-r--r--chromium/pdf/preview_mode_client.cc167
-rw-r--r--chromium/pdf/preview_mode_client.h80
33 files changed, 11127 insertions, 0 deletions
diff --git a/chromium/pdf/BUILD.gn b/chromium/pdf/BUILD.gn
new file mode 100644
index 00000000000..5582fb01455
--- /dev/null
+++ b/chromium/pdf/BUILD.gn
@@ -0,0 +1,67 @@
+# Copyright 2014 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.
+
+import("//build/config/features.gni")
+import("//third_party/pdfium/pdfium.gni")
+
+assert(enable_pdf)
+
+pdf_engine = 0 # 0 PDFium
+
+static_library("pdf") {
+ deps = [
+ "//base",
+ "//gin",
+ "//net",
+ "//ppapi/cpp:objects",
+ "//ppapi/cpp/private:internal_module",
+ ]
+
+ sources = [
+ "chunk_stream.cc",
+ "chunk_stream.h",
+ "document_loader.cc",
+ "document_loader.h",
+ "draw_utils.cc",
+ "draw_utils.h",
+ "out_of_process_instance.cc",
+ "out_of_process_instance.h",
+ "paint_aggregator.cc",
+ "paint_aggregator.h",
+ "paint_manager.cc",
+ "paint_manager.h",
+ "pdf.cc",
+ "pdf.h",
+ "pdf_engine.h",
+ "preview_mode_client.cc",
+ "preview_mode_client.h",
+ ]
+
+ # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.
+ configs += [ "//build/config/compiler:no_size_t_to_int_warning" ]
+
+ if (pdf_engine == 0) {
+ deps += [ "//third_party/pdfium" ]
+
+ sources += [
+ "pdfium/pdfium_api_string_buffer_adapter.cc",
+ "pdfium/pdfium_api_string_buffer_adapter.h",
+ "pdfium/pdfium_assert_matching_enums.cc",
+ "pdfium/pdfium_engine.cc",
+ "pdfium/pdfium_engine.h",
+ "pdfium/pdfium_mem_buffer_file_read.cc",
+ "pdfium/pdfium_mem_buffer_file_read.h",
+ "pdfium/pdfium_mem_buffer_file_write.cc",
+ "pdfium/pdfium_mem_buffer_file_write.h",
+ "pdfium/pdfium_page.cc",
+ "pdfium/pdfium_page.h",
+ "pdfium/pdfium_range.cc",
+ "pdfium/pdfium_range.h",
+ ]
+ }
+
+ if (pdf_enable_xfa) {
+ defines = [ "PDF_ENABLE_XFA" ]
+ }
+}
diff --git a/chromium/pdf/DEPS b/chromium/pdf/DEPS
new file mode 100644
index 00000000000..cbfcfbfe9f6
--- /dev/null
+++ b/chromium/pdf/DEPS
@@ -0,0 +1,12 @@
+include_rules = [
+ "+chrome/common/content_restriction.h",
+ "+gin",
+ "+net",
+ "+ppapi",
+ "+printing/pdf_transform.h",
+ "+printing/units.h",
+ "+third_party/pdfium/public",
+ "+ui/events/keycodes/keyboard_codes.h",
+ "+ui/gfx/geometry/rect.h",
+ "+v8/include/v8.h"
+]
diff --git a/chromium/pdf/OWNERS b/chromium/pdf/OWNERS
new file mode 100644
index 00000000000..bdb1ac3cac8
--- /dev/null
+++ b/chromium/pdf/OWNERS
@@ -0,0 +1,5 @@
+gene@chromium.org
+jam@chromium.org
+jochen@chromium.org
+raymes@chromium.org
+thestig@chromium.org
diff --git a/chromium/pdf/chunk_stream.cc b/chromium/pdf/chunk_stream.cc
new file mode 100644
index 00000000000..adb3cb6edaf
--- /dev/null
+++ b/chromium/pdf/chunk_stream.cc
@@ -0,0 +1,175 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "pdf/chunk_stream.h"
+
+#include <stddef.h>
+#include <string.h>
+
+#define __STDC_LIMIT_MACROS
+#ifdef _WIN32
+#include <limits.h>
+#else
+#include <stdint.h>
+#endif
+
+#include <algorithm>
+
+namespace chrome_pdf {
+
+ChunkStream::ChunkStream() : stream_size_(0) {
+}
+
+ChunkStream::~ChunkStream() {
+}
+
+void ChunkStream::Clear() {
+ chunks_.clear();
+ data_.clear();
+ stream_size_ = 0;
+}
+
+void ChunkStream::Preallocate(size_t stream_size) {
+ data_.reserve(stream_size);
+ stream_size_ = stream_size;
+}
+
+size_t ChunkStream::GetSize() const {
+ return data_.size();
+}
+
+bool ChunkStream::WriteData(size_t offset, void* buffer, size_t size) {
+ if (SIZE_MAX - size < offset)
+ return false;
+
+ if (data_.size() < offset + size)
+ data_.resize(offset + size);
+
+ memcpy(&data_[offset], buffer, size);
+
+ if (chunks_.empty()) {
+ chunks_[offset] = size;
+ return true;
+ }
+
+ std::map<size_t, size_t>::iterator start = chunks_.upper_bound(offset);
+ if (start != chunks_.begin())
+ --start; // start now points to the key equal or lower than offset.
+ if (start->first + start->second < offset)
+ ++start; // start element is entirely before current chunk, skip it.
+
+ std::map<size_t, size_t>::iterator end = chunks_.upper_bound(offset + size);
+ if (start == end) { // No chunks to merge.
+ chunks_[offset] = size;
+ return true;
+ }
+
+ --end;
+
+ size_t new_offset = std::min<size_t>(start->first, offset);
+ size_t new_size =
+ std::max<size_t>(end->first + end->second, offset + size) - new_offset;
+
+ chunks_.erase(start, ++end);
+
+ chunks_[new_offset] = new_size;
+
+ return true;
+}
+
+bool ChunkStream::ReadData(size_t offset, size_t size, void* buffer) const {
+ if (!IsRangeAvailable(offset, size))
+ return false;
+
+ memcpy(buffer, &data_[offset], size);
+ return true;
+}
+
+bool ChunkStream::GetMissedRanges(
+ size_t offset, size_t size,
+ std::vector<std::pair<size_t, size_t> >* ranges) const {
+ if (IsRangeAvailable(offset, size))
+ return false;
+
+ ranges->clear();
+ if (chunks_.empty()) {
+ ranges->push_back(std::pair<size_t, size_t>(offset, size));
+ return true;
+ }
+
+ std::map<size_t, size_t>::const_iterator start = chunks_.upper_bound(offset);
+ if (start != chunks_.begin())
+ --start; // start now points to the key equal or lower than offset.
+ if (start->first + start->second < offset)
+ ++start; // start element is entirely before current chunk, skip it.
+
+ std::map<size_t, size_t>::const_iterator end =
+ chunks_.upper_bound(offset + size);
+ if (start == end) { // No data in the current range available.
+ ranges->push_back(std::pair<size_t, size_t>(offset, size));
+ return true;
+ }
+
+ size_t cur_offset = offset;
+ std::map<size_t, size_t>::const_iterator it;
+ for (it = start; it != end; ++it) {
+ if (cur_offset < it->first) {
+ size_t new_size = it->first - cur_offset;
+ ranges->push_back(std::pair<size_t, size_t>(cur_offset, new_size));
+ cur_offset = it->first + it->second;
+ } else if (cur_offset < it->first + it->second) {
+ cur_offset = it->first + it->second;
+ }
+ }
+
+ // Add last chunk.
+ if (cur_offset < offset + size)
+ ranges->push_back(std::pair<size_t, size_t>(cur_offset,
+ offset + size - cur_offset));
+
+ return true;
+}
+
+bool ChunkStream::IsRangeAvailable(size_t offset, size_t size) const {
+ if (chunks_.empty())
+ return false;
+
+ if (SIZE_MAX - size < offset)
+ return false;
+
+ std::map<size_t, size_t>::const_iterator it = chunks_.upper_bound(offset);
+ if (it == chunks_.begin())
+ return false; // No chunks includes offset byte.
+
+ --it; // Now it starts equal or before offset.
+ return (it->first + it->second) >= (offset + size);
+}
+
+size_t ChunkStream::GetFirstMissingByte() const {
+ if (chunks_.empty())
+ return 0;
+ std::map<size_t, size_t>::const_iterator begin = chunks_.begin();
+ return begin->first > 0 ? 0 : begin->second;
+}
+
+size_t ChunkStream::GetFirstMissingByteInInterval(size_t offset) const {
+ if (chunks_.empty())
+ return 0;
+ std::map<size_t, size_t>::const_iterator it = chunks_.upper_bound(offset);
+ if (it == chunks_.begin())
+ return 0;
+ --it;
+ return it->first + it->second;
+}
+
+size_t ChunkStream::GetLastMissingByteInInterval(size_t offset) const {
+ if (chunks_.empty())
+ return stream_size_ - 1;
+ std::map<size_t, size_t>::const_iterator it = chunks_.upper_bound(offset);
+ if (it == chunks_.end())
+ return stream_size_ - 1;
+ return it->first - 1;
+}
+
+} // namespace chrome_pdf
diff --git a/chromium/pdf/chunk_stream.h b/chromium/pdf/chunk_stream.h
new file mode 100644
index 00000000000..d2d8d2a13d4
--- /dev/null
+++ b/chromium/pdf/chunk_stream.h
@@ -0,0 +1,53 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef PDF_CHUNK_STREAM_H_
+#define PDF_CHUNK_STREAM_H_
+
+#include <stddef.h>
+
+#include <map>
+#include <utility>
+#include <vector>
+
+namespace chrome_pdf {
+
+// This class collects a chunks of data into one data stream. Client can check
+// if data in certain range is available, and get missing chunks of data.
+class ChunkStream {
+ public:
+ ChunkStream();
+ ~ChunkStream();
+
+ void Clear();
+
+ void Preallocate(size_t stream_size);
+ size_t GetSize() const;
+
+ bool WriteData(size_t offset, void* buffer, size_t size);
+ bool ReadData(size_t offset, size_t size, void* buffer) const;
+
+ // Returns vector of pairs where first is an offset, second is a size.
+ bool GetMissedRanges(size_t offset, size_t size,
+ std::vector<std::pair<size_t, size_t> >* ranges) const;
+ bool IsRangeAvailable(size_t offset, size_t size) const;
+ size_t GetFirstMissingByte() const;
+
+ // Finds the first byte of the missing byte interval that offset belongs to.
+ size_t GetFirstMissingByteInInterval(size_t offset) const;
+ // Returns the last byte of the missing byte interval that offset belongs to.
+ size_t GetLastMissingByteInInterval(size_t offset) const;
+
+ private:
+ std::vector<unsigned char> data_;
+
+ // Pair, first - begining of the chunk, second - size of the chunk.
+ std::map<size_t, size_t> chunks_;
+
+ size_t stream_size_;
+};
+
+}; // namespace chrome_pdf
+
+#endif // PDF_CHUNK_STREAM_H_
diff --git a/chromium/pdf/document_loader.cc b/chromium/pdf/document_loader.cc
new file mode 100644
index 00000000000..3117d08fffc
--- /dev/null
+++ b/chromium/pdf/document_loader.cc
@@ -0,0 +1,545 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "pdf/document_loader.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include "base/logging.h"
+#include "base/strings/string_util.h"
+#include "net/http/http_util.h"
+#include "ppapi/c/pp_errors.h"
+#include "ppapi/cpp/url_loader.h"
+#include "ppapi/cpp/url_request_info.h"
+#include "ppapi/cpp/url_response_info.h"
+
+namespace chrome_pdf {
+
+namespace {
+
+// If the headers have a byte-range response, writes the start and end
+// positions and returns true if at least the start position was parsed.
+// The end position will be set to 0 if it was not found or parsed from the
+// response.
+// Returns false if not even a start position could be parsed.
+bool GetByteRange(const std::string& headers, uint32_t* start, uint32_t* end) {
+ net::HttpUtil::HeadersIterator it(headers.begin(), headers.end(), "\n");
+ while (it.GetNext()) {
+ if (base::LowerCaseEqualsASCII(it.name(), "content-range")) {
+ std::string range = it.values().c_str();
+ if (base::StartsWith(range, "bytes",
+ base::CompareCase::INSENSITIVE_ASCII)) {
+ range = range.substr(strlen("bytes"));
+ std::string::size_type pos = range.find('-');
+ std::string range_end;
+ if (pos != std::string::npos)
+ range_end = range.substr(pos + 1);
+ base::TrimWhitespaceASCII(range, base::TRIM_LEADING, &range);
+ base::TrimWhitespaceASCII(range_end, base::TRIM_LEADING, &range_end);
+ *start = atoi(range.c_str());
+ *end = atoi(range_end.c_str());
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+// If the headers have a multi-part response, returns the boundary name.
+// Otherwise returns an empty string.
+std::string GetMultiPartBoundary(const std::string& headers) {
+ net::HttpUtil::HeadersIterator it(headers.begin(), headers.end(), "\n");
+ while (it.GetNext()) {
+ if (base::LowerCaseEqualsASCII(it.name(), "content-type")) {
+ std::string type = base::ToLowerASCII(it.values());
+ if (base::StartsWith(type, "multipart/", base::CompareCase::SENSITIVE)) {
+ const char* boundary = strstr(type.c_str(), "boundary=");
+ if (!boundary) {
+ NOTREACHED();
+ break;
+ }
+
+ return std::string(boundary + 9);
+ }
+ }
+ }
+ return std::string();
+}
+
+bool IsValidContentType(const std::string& type) {
+ return (base::EndsWith(type, "/pdf", base::CompareCase::INSENSITIVE_ASCII) ||
+ base::EndsWith(type, ".pdf", base::CompareCase::INSENSITIVE_ASCII) ||
+ base::EndsWith(type, "/x-pdf",
+ base::CompareCase::INSENSITIVE_ASCII) ||
+ base::EndsWith(type, "/*", base::CompareCase::INSENSITIVE_ASCII) ||
+ base::EndsWith(type, "/acrobat",
+ base::CompareCase::INSENSITIVE_ASCII) ||
+ base::EndsWith(type, "/unknown",
+ base::CompareCase::INSENSITIVE_ASCII));
+}
+
+} // namespace
+
+DocumentLoader::Client::~Client() {
+}
+
+DocumentLoader::DocumentLoader(Client* client)
+ : client_(client), partial_document_(false), request_pending_(false),
+ current_pos_(0), current_chunk_size_(0), current_chunk_read_(0),
+ document_size_(0), header_request_(true), is_multipart_(false) {
+ loader_factory_.Initialize(this);
+}
+
+DocumentLoader::~DocumentLoader() {
+}
+
+bool DocumentLoader::Init(const pp::URLLoader& loader,
+ const std::string& url,
+ const std::string& headers) {
+ DCHECK(url_.empty());
+ url_ = url;
+ loader_ = loader;
+
+ std::string response_headers;
+ if (!headers.empty()) {
+ response_headers = headers;
+ } else {
+ pp::URLResponseInfo response = loader_.GetResponseInfo();
+ pp::Var headers_var = response.GetHeaders();
+
+ if (headers_var.is_string()) {
+ response_headers = headers_var.AsString();
+ }
+ }
+
+ bool accept_ranges_bytes = false;
+ bool content_encoded = false;
+ uint32_t content_length = 0;
+ std::string type;
+ std::string disposition;
+
+ // This happens for PDFs not loaded from http(s) sources.
+ if (response_headers == "Content-Type: text/plain") {
+ if (!base::StartsWith(url, "http://",
+ base::CompareCase::INSENSITIVE_ASCII) &&
+ !base::StartsWith(url, "https://",
+ base::CompareCase::INSENSITIVE_ASCII)) {
+ type = "application/pdf";
+ }
+ }
+ if (type.empty() && !response_headers.empty()) {
+ net::HttpUtil::HeadersIterator it(response_headers.begin(),
+ response_headers.end(), "\n");
+ while (it.GetNext()) {
+ if (base::LowerCaseEqualsASCII(it.name(), "content-length")) {
+ content_length = atoi(it.values().c_str());
+ } else if (base::LowerCaseEqualsASCII(it.name(), "accept-ranges")) {
+ accept_ranges_bytes = base::LowerCaseEqualsASCII(it.values(), "bytes");
+ } else if (base::LowerCaseEqualsASCII(it.name(), "content-encoding")) {
+ content_encoded = true;
+ } else if (base::LowerCaseEqualsASCII(it.name(), "content-type")) {
+ type = it.values();
+ size_t semi_colon_pos = type.find(';');
+ if (semi_colon_pos != std::string::npos) {
+ type = type.substr(0, semi_colon_pos);
+ }
+ TrimWhitespaceASCII(type, base::TRIM_ALL, &type);
+ } else if (base::LowerCaseEqualsASCII(it.name(), "content-disposition")) {
+ disposition = it.values();
+ }
+ }
+ }
+ if (!type.empty() && !IsValidContentType(type))
+ return false;
+ if (base::StartsWith(disposition, "attachment",
+ base::CompareCase::INSENSITIVE_ASCII))
+ return false;
+
+ if (content_length > 0)
+ chunk_stream_.Preallocate(content_length);
+
+ document_size_ = content_length;
+ requests_count_ = 0;
+
+ // Enable partial loading only if file size is above the threshold.
+ // It will allow avoiding latency for multiple requests.
+ if (content_length > kMinFileSize &&
+ accept_ranges_bytes &&
+ !content_encoded) {
+ LoadPartialDocument();
+ } else {
+ LoadFullDocument();
+ }
+ return true;
+}
+
+void DocumentLoader::LoadPartialDocument() {
+ // The current request is a full request (not a range request) so it starts at
+ // 0 and ends at |document_size_|.
+ current_chunk_size_ = document_size_;
+ current_pos_ = 0;
+ current_request_offset_ = 0;
+ current_request_size_ = 0;
+ current_request_extended_size_ = document_size_;
+ request_pending_ = true;
+
+ partial_document_ = true;
+ header_request_ = true;
+ ReadMore();
+}
+
+void DocumentLoader::LoadFullDocument() {
+ partial_document_ = false;
+ chunk_buffer_.clear();
+ ReadMore();
+}
+
+bool DocumentLoader::IsDocumentComplete() const {
+ if (document_size_ == 0) // Document size unknown.
+ return false;
+ return IsDataAvailable(0, document_size_);
+}
+
+uint32_t DocumentLoader::GetAvailableData() const {
+ if (document_size_ == 0) { // If document size is unknown.
+ return current_pos_;
+ }
+
+ std::vector<std::pair<size_t, size_t> > ranges;
+ chunk_stream_.GetMissedRanges(0, document_size_, &ranges);
+ uint32_t available = document_size_;
+ for (const auto& range : ranges)
+ available -= range.second;
+ return available;
+}
+
+void DocumentLoader::ClearPendingRequests() {
+ pending_requests_.erase(pending_requests_.begin(),
+ pending_requests_.end());
+}
+
+bool DocumentLoader::GetBlock(uint32_t position,
+ uint32_t size,
+ void* buf) const {
+ return chunk_stream_.ReadData(position, size, buf);
+}
+
+bool DocumentLoader::IsDataAvailable(uint32_t position, uint32_t size) const {
+ return chunk_stream_.IsRangeAvailable(position, size);
+}
+
+void DocumentLoader::RequestData(uint32_t position, uint32_t size) {
+ DCHECK(partial_document_);
+
+ // We have some artefact request from
+ // PDFiumEngine::OnDocumentComplete() -> FPDFAvail_IsPageAvail after
+ // document is complete.
+ // We need this fix in PDFIum. Adding this as a work around.
+ // Bug: http://code.google.com/p/chromium/issues/detail?id=79996
+ // Test url:
+ // http://www.icann.org/en/correspondence/holtzman-to-jeffrey-02mar11-en.pdf
+ if (IsDocumentComplete())
+ return;
+
+ pending_requests_.push_back(std::pair<size_t, size_t>(position, size));
+ DownloadPendingRequests();
+}
+
+void DocumentLoader::RemoveCompletedRanges() {
+ // Split every request that has been partially downloaded already into smaller
+ // requests.
+ std::vector<std::pair<size_t, size_t> > ranges;
+ auto it = pending_requests_.begin();
+ while (it != pending_requests_.end()) {
+ chunk_stream_.GetMissedRanges(it->first, it->second, &ranges);
+ pending_requests_.insert(it, ranges.begin(), ranges.end());
+ ranges.clear();
+ pending_requests_.erase(it++);
+ }
+}
+
+void DocumentLoader::DownloadPendingRequests() {
+ if (request_pending_)
+ return;
+
+ uint32_t pos;
+ uint32_t size;
+ if (pending_requests_.empty()) {
+ // If the document is not complete and we have no outstanding requests,
+ // download what's left for as long as no other request gets added to
+ // |pending_requests_|.
+ pos = chunk_stream_.GetFirstMissingByte();
+ if (pos >= document_size_) {
+ // We're done downloading the document.
+ return;
+ }
+ // Start with size 0, we'll set |current_request_extended_size_| to > 0.
+ // This way this request will get cancelled as soon as the renderer wants
+ // another portion of the document.
+ size = 0;
+ } else {
+ RemoveCompletedRanges();
+
+ pos = pending_requests_.front().first;
+ size = pending_requests_.front().second;
+ if (IsDataAvailable(pos, size)) {
+ ReadComplete();
+ return;
+ }
+ }
+
+ size_t last_byte_before = chunk_stream_.GetFirstMissingByteInInterval(pos);
+ if (size < kDefaultRequestSize) {
+ // Try to extend before pos, up to size |kDefaultRequestSize|.
+ if (pos + size - last_byte_before > kDefaultRequestSize) {
+ pos += size - kDefaultRequestSize;
+ size = kDefaultRequestSize;
+ } else {
+ size += pos - last_byte_before;
+ pos = last_byte_before;
+ }
+ }
+ if (pos - last_byte_before < kDefaultRequestSize) {
+ // Don't leave a gap smaller than |kDefaultRequestSize|.
+ size += pos - last_byte_before;
+ pos = last_byte_before;
+ }
+
+ current_request_offset_ = pos;
+ current_request_size_ = size;
+
+ // Extend the request until the next downloaded byte or the end of the
+ // document.
+ size_t last_missing_byte =
+ chunk_stream_.GetLastMissingByteInInterval(pos + size - 1);
+ current_request_extended_size_ = last_missing_byte - pos + 1;
+
+ request_pending_ = true;
+
+ // Start downloading first pending request.
+ loader_.Close();
+ loader_ = client_->CreateURLLoader();
+ pp::CompletionCallback callback =
+ loader_factory_.NewCallback(&DocumentLoader::DidOpen);
+ pp::URLRequestInfo request = GetRequest(pos, current_request_extended_size_);
+ requests_count_++;
+ int rv = loader_.Open(request, callback);
+ if (rv != PP_OK_COMPLETIONPENDING)
+ callback.Run(rv);
+}
+
+pp::URLRequestInfo DocumentLoader::GetRequest(uint32_t position,
+ uint32_t size) const {
+ pp::URLRequestInfo request(client_->GetPluginInstance());
+ request.SetURL(url_);
+ request.SetMethod("GET");
+ request.SetFollowRedirects(true);
+ request.SetCustomReferrerURL(url_);
+
+ const size_t kBufSize = 100;
+ char buf[kBufSize];
+ // According to rfc2616, byte range specifies position of the first and last
+ // bytes in the requested range inclusively. Therefore we should subtract 1
+ // from the position + size, to get index of the last byte that needs to be
+ // downloaded.
+ base::snprintf(buf, kBufSize, "Range: bytes=%d-%d", position,
+ position + size - 1);
+ pp::Var header(buf);
+ request.SetHeaders(header);
+
+ return request;
+}
+
+void DocumentLoader::DidOpen(int32_t result) {
+ if (result != PP_OK) {
+ NOTREACHED();
+ return;
+ }
+
+ int32_t http_code = loader_.GetResponseInfo().GetStatusCode();
+ if (http_code >= 400 && http_code < 500) {
+ // Error accessing resource. 4xx error indicate subsequent requests
+ // will fail too.
+ // E.g. resource has been removed from the server while loading it.
+ // https://code.google.com/p/chromium/issues/detail?id=414827
+ return;
+ }
+
+ is_multipart_ = false;
+ current_chunk_size_ = 0;
+ current_chunk_read_ = 0;
+
+ pp::Var headers_var = loader_.GetResponseInfo().GetHeaders();
+ std::string headers;
+ if (headers_var.is_string())
+ headers = headers_var.AsString();
+
+ std::string boundary = GetMultiPartBoundary(headers);
+ if (!boundary.empty()) {
+ // Leave position untouched for now, when we read the data we'll get it.
+ is_multipart_ = true;
+ multipart_boundary_ = boundary;
+ } else {
+ // Need to make sure that the server returned a byte-range, since it's
+ // possible for a server to just ignore our byte-range request and just
+ // return the entire document even if it supports byte-range requests.
+ // i.e. sniff response to
+ // http://www.act.org/compass/sample/pdf/geometry.pdf
+ current_pos_ = 0;
+ uint32_t start_pos, end_pos;
+ if (GetByteRange(headers, &start_pos, &end_pos)) {
+ current_pos_ = start_pos;
+ if (end_pos && end_pos > start_pos)
+ current_chunk_size_ = end_pos - start_pos + 1;
+ } else {
+ partial_document_ = false;
+ }
+ }
+
+ ReadMore();
+}
+
+void DocumentLoader::ReadMore() {
+ pp::CompletionCallback callback =
+ loader_factory_.NewCallback(&DocumentLoader::DidRead);
+ int rv = loader_.ReadResponseBody(buffer_, sizeof(buffer_), callback);
+ if (rv != PP_OK_COMPLETIONPENDING)
+ callback.Run(rv);
+}
+
+void DocumentLoader::DidRead(int32_t result) {
+ if (result > 0) {
+ char* start = buffer_;
+ size_t length = result;
+ if (is_multipart_ && result > 2) {
+ for (int i = 2; i < result; ++i) {
+ if ((buffer_[i - 1] == '\n' && buffer_[i - 2] == '\n') ||
+ (i >= 4 &&
+ buffer_[i - 1] == '\n' && buffer_[i - 2] == '\r' &&
+ buffer_[i - 3] == '\n' && buffer_[i - 4] == '\r')) {
+ uint32_t start_pos, end_pos;
+ if (GetByteRange(std::string(buffer_, i), &start_pos, &end_pos)) {
+ current_pos_ = start_pos;
+ start += i;
+ length -= i;
+ if (end_pos && end_pos > start_pos)
+ current_chunk_size_ = end_pos - start_pos + 1;
+ }
+ break;
+ }
+ }
+
+ // Reset this flag so we don't look inside the buffer in future calls of
+ // DidRead for this response. Note that this code DOES NOT handle multi-
+ // part responses with more than one part (we don't issue them at the
+ // moment, so they shouldn't arrive).
+ is_multipart_ = false;
+ }
+
+ if (current_chunk_size_ &&
+ current_chunk_read_ + length > current_chunk_size_)
+ length = current_chunk_size_ - current_chunk_read_;
+
+ if (length) {
+ if (document_size_ > 0) {
+ chunk_stream_.WriteData(current_pos_, start, length);
+ } else {
+ // If we did not get content-length in the response, we can't
+ // preallocate buffer for the entire document. Resizing array causing
+ // memory fragmentation issues on the large files and OOM exceptions.
+ // To fix this, we collect all chunks of the file to the list and
+ // concatenate them together after request is complete.
+ std::vector<unsigned char> buf(length);
+ memcpy(buf.data(), start, length);
+ chunk_buffer_.push_back(std::move(buf));
+ }
+ current_pos_ += length;
+ current_chunk_read_ += length;
+ client_->OnNewDataAvailable();
+ }
+
+ // Only call the renderer if we allow partial loading.
+ if (!partial_document_) {
+ ReadMore();
+ return;
+ }
+
+ UpdateRendering();
+ RemoveCompletedRanges();
+
+ if (!pending_requests_.empty()) {
+ // If there are pending requests and the current content we're downloading
+ // doesn't satisfy any of these requests, cancel the current request to
+ // fullfill those more important requests.
+ bool satisfying_pending_request =
+ SatisfyingRequest(current_request_offset_, current_request_size_);
+ for (const auto& pending_request : pending_requests_) {
+ if (SatisfyingRequest(pending_request.first, pending_request.second)) {
+ satisfying_pending_request = true;
+ break;
+ }
+ }
+ // Cancel the request as it's not satisfying any request from the
+ // renderer, unless the current request is finished in which case we let
+ // it finish cleanly.
+ if (!satisfying_pending_request &&
+ current_pos_ < current_request_offset_ +
+ current_request_extended_size_) {
+ loader_.Close();
+ }
+ }
+
+ ReadMore();
+ } else if (result == PP_OK || result == PP_ERROR_ABORTED) {
+ ReadComplete();
+ } else {
+ NOTREACHED();
+ }
+}
+
+bool DocumentLoader::SatisfyingRequest(size_t offset, size_t size) const {
+ return offset <= current_pos_ + kDefaultRequestSize &&
+ current_pos_ < offset + size;
+}
+
+void DocumentLoader::ReadComplete() {
+ if (!partial_document_) {
+ if (document_size_ == 0) {
+ // For the document with no 'content-length" specified we've collected all
+ // the chunks already. Let's allocate final document buffer and copy them
+ // over.
+ chunk_stream_.Preallocate(current_pos_);
+ uint32_t pos = 0;
+ for (auto& chunk : chunk_buffer_) {
+ chunk_stream_.WriteData(pos, chunk.data(), chunk.size());
+ pos += chunk.size();
+ }
+ chunk_buffer_.clear();
+ }
+ document_size_ = current_pos_;
+ client_->OnDocumentComplete();
+ return;
+ }
+
+ request_pending_ = false;
+
+ if (IsDocumentComplete()) {
+ client_->OnDocumentComplete();
+ return;
+ }
+
+ UpdateRendering();
+ DownloadPendingRequests();
+}
+
+void DocumentLoader::UpdateRendering() {
+ if (header_request_)
+ client_->OnPartialDocumentLoaded();
+ else
+ client_->OnPendingRequestComplete();
+ header_request_ = false;
+}
+
+} // namespace chrome_pdf
diff --git a/chromium/pdf/document_loader.h b/chromium/pdf/document_loader.h
new file mode 100644
index 00000000000..af39390e975
--- /dev/null
+++ b/chromium/pdf/document_loader.h
@@ -0,0 +1,136 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef PDF_DOCUMENT_LOADER_H_
+#define PDF_DOCUMENT_LOADER_H_
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include <list>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "pdf/chunk_stream.h"
+#include "ppapi/cpp/url_loader.h"
+#include "ppapi/utility/completion_callback_factory.h"
+
+namespace chrome_pdf {
+
+class DocumentLoader {
+ public:
+ class Client {
+ public:
+ virtual ~Client();
+
+ // Gets the pp::Instance object.
+ virtual pp::Instance* GetPluginInstance() = 0;
+ // Creates new URLLoader based on client settings.
+ virtual pp::URLLoader CreateURLLoader() = 0;
+ // Notification called when partial information about document is available.
+ // Only called for urls that returns full content size and supports byte
+ // range requests.
+ virtual void OnPartialDocumentLoaded() = 0;
+ // Notification called when all outstanding pending requests are complete.
+ virtual void OnPendingRequestComplete() = 0;
+ // Notification called when new data is available.
+ virtual void OnNewDataAvailable() = 0;
+ // Notification called when document is fully loaded.
+ virtual void OnDocumentComplete() = 0;
+ };
+
+ explicit DocumentLoader(Client* client);
+ ~DocumentLoader();
+
+ bool Init(const pp::URLLoader& loader,
+ const std::string& url,
+ const std::string& headers);
+
+ // Data access interface. Return true is successful.
+ bool GetBlock(uint32_t position, uint32_t size, void* buf) const;
+
+ // Data availability interface. Return true data avaialble.
+ bool IsDataAvailable(uint32_t position, uint32_t size) const;
+
+ // Data availability interface. Return true data avaialble.
+ void RequestData(uint32_t position, uint32_t size);
+
+ bool IsDocumentComplete() const;
+ uint32_t document_size() const { return document_size_; }
+
+ // Return number of bytes available.
+ uint32_t GetAvailableData() const;
+
+ // Clear pending requests from the queue.
+ void ClearPendingRequests();
+
+ bool is_partial_document() const { return partial_document_; }
+
+ private:
+ // Called by the completion callback of the document's URLLoader.
+ void DidOpen(int32_t result);
+ // Call to read data from the document's URLLoader.
+ void ReadMore();
+ // Called by the completion callback of the document's URLLoader.
+ void DidRead(int32_t result);
+
+ // Called when we detect that partial document load is possible.
+ void LoadPartialDocument();
+ // Called when we have to load full document.
+ void LoadFullDocument();
+ // Download pending requests.
+ void DownloadPendingRequests();
+ // Remove completed ranges.
+ void RemoveCompletedRanges();
+ // Returns true if we are already in progress satisfying the request, or just
+ // about ready to start. This helps us avoid expensive jumping around, and
+ // even worse leaving tiny gaps in the byte stream that might have to be
+ // filled later.
+ bool SatisfyingRequest(size_t pos, size_t size) const;
+ // Called when we complete server request and read all data from it.
+ void ReadComplete();
+ // Creates request to download size byte of data data starting from position.
+ pp::URLRequestInfo GetRequest(uint32_t position, uint32_t size) const;
+ // Updates the rendering by the Client.
+ void UpdateRendering();
+
+ // Document below size will be downloaded in one chunk.
+ static const uint32_t kMinFileSize = 64 * 1024;
+ // Number was chosen in crbug.com/78264#c8
+ enum { kDefaultRequestSize = 65536 };
+
+ Client* const client_;
+ std::string url_;
+ pp::URLLoader loader_;
+ pp::CompletionCallbackFactory<DocumentLoader> loader_factory_;
+ ChunkStream chunk_stream_;
+ bool partial_document_;
+ bool request_pending_;
+ typedef std::list<std::pair<size_t, size_t> > PendingRequests;
+ PendingRequests pending_requests_;
+ // The starting position of the HTTP request currently being processed.
+ size_t current_request_offset_;
+ // The size of the byte range the current HTTP request must download before
+ // being cancelled.
+ size_t current_request_size_;
+ // The actual byte range size of the current HTTP request. This may be larger
+ // than |current_request_size_| and the request may be cancelled before
+ // reaching |current_request_offset_| + |current_request_extended_size_|.
+ size_t current_request_extended_size_;
+ char buffer_[kDefaultRequestSize];
+ uint32_t current_pos_;
+ uint32_t current_chunk_size_;
+ uint32_t current_chunk_read_;
+ uint32_t document_size_;
+ bool header_request_;
+ bool is_multipart_;
+ std::string multipart_boundary_;
+ uint32_t requests_count_;
+ std::vector<std::vector<unsigned char> > chunk_buffer_;
+};
+
+} // namespace chrome_pdf
+
+#endif // PDF_DOCUMENT_LOADER_H_
diff --git a/chromium/pdf/draw_utils.cc b/chromium/pdf/draw_utils.cc
new file mode 100644
index 00000000000..5d13077e118
--- /dev/null
+++ b/chromium/pdf/draw_utils.cc
@@ -0,0 +1,357 @@
+// Copyright (c) 2011 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/draw_utils.h"
+
+#include <math.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <algorithm>
+#include <vector>
+
+#include "base/logging.h"
+#include "base/numerics/safe_math.h"
+
+namespace chrome_pdf {
+
+inline uint8_t GetBlue(const uint32_t& pixel) {
+ return static_cast<uint8_t>(pixel & 0xFF);
+}
+
+inline uint8_t GetGreen(const uint32_t& pixel) {
+ return static_cast<uint8_t>((pixel >> 8) & 0xFF);
+}
+
+inline uint8_t GetRed(const uint32_t& pixel) {
+ return static_cast<uint8_t>((pixel >> 16) & 0xFF);
+}
+
+inline uint8_t GetAlpha(const uint32_t& pixel) {
+ return static_cast<uint8_t>((pixel >> 24) & 0xFF);
+}
+
+inline uint32_t MakePixel(uint8_t red,
+ uint8_t green,
+ uint8_t blue,
+ uint8_t alpha) {
+ return (static_cast<uint32_t>(alpha) << 24) |
+ (static_cast<uint32_t>(red) << 16) |
+ (static_cast<uint32_t>(green) << 8) |
+ static_cast<uint32_t>(blue);
+}
+
+inline uint8_t GradientChannel(uint8_t start, uint8_t end, double ratio) {
+ double new_channel = start - (static_cast<double>(start) - end) * ratio;
+ if (new_channel < 0)
+ return 0;
+ if (new_channel > 255)
+ return 255;
+ return static_cast<uint8_t>(new_channel + 0.5);
+}
+
+inline uint8_t ProcessColor(uint8_t src_color,
+ uint8_t dest_color,
+ uint8_t alpha) {
+ uint32_t processed = static_cast<uint32_t>(src_color) * alpha +
+ static_cast<uint32_t>(dest_color) * (0xFF - alpha);
+ return static_cast<uint8_t>((processed / 0xFF) & 0xFF);
+}
+
+inline bool ImageDataContainsRect(const pp::ImageData& image_data,
+ const pp::Rect& rect) {
+ return rect.width() >= 0 && rect.height() >= 0 &&
+ pp::Rect(image_data.size()).Contains(rect);
+}
+
+void AlphaBlend(const pp::ImageData& src,
+ const pp::Rect& src_rc,
+ pp::ImageData* dest,
+ const pp::Point& dest_origin,
+ uint8_t alpha_adjustment) {
+ if (src_rc.IsEmpty() || !ImageDataContainsRect(src, src_rc))
+ return;
+
+ pp::Rect dest_rc(dest_origin, src_rc.size());
+ if (dest_rc.IsEmpty() || !ImageDataContainsRect(*dest, dest_rc))
+ return;
+
+ const uint32_t* src_origin_pixel = src.GetAddr32(src_rc.point());
+ uint32_t* dest_origin_pixel = dest->GetAddr32(dest_origin);
+
+ int height = src_rc.height();
+ int width = src_rc.width();
+ for (int y = 0; y < height; y++) {
+ const uint32_t* src_pixel = src_origin_pixel;
+ uint32_t* dest_pixel = dest_origin_pixel;
+ for (int x = 0; x < width; x++) {
+ uint8_t alpha =
+ static_cast<uint8_t>(static_cast<uint32_t>(alpha_adjustment) *
+ GetAlpha(*src_pixel) / 0xFF);
+ uint8_t red =
+ ProcessColor(GetRed(*src_pixel), GetRed(*dest_pixel), alpha);
+ uint8_t green =
+ ProcessColor(GetGreen(*src_pixel), GetGreen(*dest_pixel), alpha);
+ uint8_t blue =
+ ProcessColor(GetBlue(*src_pixel), GetBlue(*dest_pixel), alpha);
+ *dest_pixel = MakePixel(red, green, blue, GetAlpha(*dest_pixel));
+
+ src_pixel++;
+ dest_pixel++;
+ }
+ src_origin_pixel = reinterpret_cast<const uint32_t*>(
+ reinterpret_cast<const char*>(src_origin_pixel) + src.stride());
+ dest_origin_pixel = reinterpret_cast<uint32_t*>(
+ reinterpret_cast<char*>(dest_origin_pixel) + dest->stride());
+ }
+}
+
+void GradientFill(pp::ImageData* image,
+ const pp::Rect& rc,
+ uint32_t start_color,
+ uint32_t end_color,
+ bool horizontal) {
+ std::vector<uint32_t> colors;
+ colors.resize(horizontal ? rc.width() : rc.height());
+ for (size_t i = 0; i < colors.size(); ++i) {
+ double ratio = static_cast<double>(i) / colors.size();
+ colors[i] = MakePixel(
+ GradientChannel(GetRed(start_color), GetRed(end_color), ratio),
+ GradientChannel(GetGreen(start_color), GetGreen(end_color), ratio),
+ GradientChannel(GetBlue(start_color), GetBlue(end_color), ratio),
+ GradientChannel(GetAlpha(start_color), GetAlpha(end_color), ratio));
+ }
+
+ if (horizontal) {
+ const void* data = &(colors[0]);
+ size_t size = colors.size() * 4;
+ uint32_t* origin_pixel = image->GetAddr32(rc.point());
+ for (int y = 0; y < rc.height(); y++) {
+ memcpy(origin_pixel, data, size);
+ origin_pixel = reinterpret_cast<uint32_t*>(
+ reinterpret_cast<char*>(origin_pixel) + image->stride());
+ }
+ } else {
+ uint32_t* origin_pixel = image->GetAddr32(rc.point());
+ for (int y = 0; y < rc.height(); y++) {
+ uint32_t* pixel = origin_pixel;
+ for (int x = 0; x < rc.width(); x++) {
+ *pixel = colors[y];
+ pixel++;
+ }
+ origin_pixel = reinterpret_cast<uint32_t*>(
+ reinterpret_cast<char*>(origin_pixel) + image->stride());
+ }
+ }
+}
+
+void GradientFill(pp::Instance* instance,
+ pp::ImageData* image,
+ const pp::Rect& dirty_rc,
+ const pp::Rect& gradient_rc,
+ uint32_t start_color,
+ uint32_t end_color,
+ bool horizontal,
+ uint8_t transparency) {
+ pp::Rect draw_rc = gradient_rc.Intersect(dirty_rc);
+ if (draw_rc.IsEmpty())
+ return;
+
+ pp::ImageData gradient(instance, PP_IMAGEDATAFORMAT_BGRA_PREMUL,
+ gradient_rc.size(), false);
+
+ GradientFill(&gradient, pp::Rect(pp::Point(), gradient_rc.size()),
+ start_color, end_color, horizontal);
+
+ pp::Rect copy_rc(draw_rc);
+ copy_rc.Offset(-gradient_rc.x(), -gradient_rc.y());
+ AlphaBlend(gradient, copy_rc, image, draw_rc.point(), transparency);
+}
+
+void CopyImage(const pp::ImageData& src, const pp::Rect& src_rc,
+ pp::ImageData* dest, const pp::Rect& dest_rc,
+ bool stretch) {
+ if (src_rc.IsEmpty() || !ImageDataContainsRect(src, src_rc))
+ return;
+
+ pp::Rect stretched_rc(dest_rc.point(),
+ stretch ? dest_rc.size() : src_rc.size());
+ if (stretched_rc.IsEmpty() || !ImageDataContainsRect(*dest, stretched_rc))
+ return;
+
+ const uint32_t* src_origin_pixel = src.GetAddr32(src_rc.point());
+ uint32_t* dest_origin_pixel = dest->GetAddr32(dest_rc.point());
+ if (stretch) {
+ double x_ratio = static_cast<double>(src_rc.width()) / dest_rc.width();
+ double y_ratio = static_cast<double>(src_rc.height()) / dest_rc.height();
+ int32_t height = dest_rc.height();
+ int32_t width = dest_rc.width();
+ for (int32_t y = 0; y < height; ++y) {
+ uint32_t* dest_pixel = dest_origin_pixel;
+ for (int32_t x = 0; x < width; ++x) {
+ uint32_t src_x = static_cast<uint32_t>(x * x_ratio);
+ uint32_t src_y = static_cast<uint32_t>(y * y_ratio);
+ const uint32_t* src_pixel = src.GetAddr32(
+ pp::Point(src_rc.x() + src_x, src_rc.y() + src_y));
+ *dest_pixel = *src_pixel;
+ dest_pixel++;
+ }
+ dest_origin_pixel = reinterpret_cast<uint32_t*>(
+ reinterpret_cast<char*>(dest_origin_pixel) + dest->stride());
+ }
+ } else {
+ int32_t height = src_rc.height();
+ base::CheckedNumeric<int32_t> width_bytes = src_rc.width();
+ width_bytes *= 4;
+ for (int32_t y = 0; y < height; ++y) {
+ memcpy(dest_origin_pixel, src_origin_pixel, width_bytes.ValueOrDie());
+ src_origin_pixel = reinterpret_cast<const uint32_t*>(
+ reinterpret_cast<const char*>(src_origin_pixel) + src.stride());
+ dest_origin_pixel = reinterpret_cast<uint32_t*>(
+ reinterpret_cast<char*>(dest_origin_pixel) + dest->stride());
+ }
+ }
+}
+
+void FillRect(pp::ImageData* image, const pp::Rect& rc, uint32_t color) {
+ int height = rc.height();
+ if (height == 0)
+ return;
+
+ // Fill in first row.
+ uint32_t* top_line = image->GetAddr32(rc.point());
+ int width = rc.width();
+ for (int x = 0; x < width; x++)
+ top_line[x] = color;
+
+ // Fill in the rest of the rectangle.
+ int byte_width = width * 4;
+ uint32_t* cur_line = reinterpret_cast<uint32_t*>(
+ reinterpret_cast<char*>(top_line) + image->stride());
+ for (int y = 1; y < height; y++) {
+ memcpy(cur_line, top_line, byte_width);
+ cur_line = reinterpret_cast<uint32_t*>(
+ reinterpret_cast<char*>(cur_line) + image->stride());
+ }
+}
+
+ShadowMatrix::ShadowMatrix(uint32_t depth, double factor, uint32_t background)
+ : depth_(depth), factor_(factor), background_(background) {
+ DCHECK(depth_ > 0);
+ matrix_.resize(depth_ * depth_);
+
+ // pv - is a rounding power factor for smoothing corners.
+ // pv = 2.0 will make corners completely round.
+ const double pv = 4.0;
+ // pow_pv - cache to avoid recalculating pow(x, pv) every time.
+ std::vector<double> pow_pv(depth_, 0.0);
+
+ double r = static_cast<double>(depth_);
+ double coef = 256.0 / pow(r, factor);
+
+ for (uint32_t y = 0; y < depth_; y++) {
+ // Since matrix is symmetrical, we can reduce the number of calculations
+ // by mirroring results.
+ for (uint32_t x = 0; x <= y; x++) {
+ // Fill cache if needed.
+ if (pow_pv[x] == 0.0)
+ pow_pv[x] = pow(x, pv);
+ if (pow_pv[y] == 0.0)
+ pow_pv[y] = pow(y, pv);
+
+ // v - is a value for the smoothing function.
+ // If x == 0 simplify calculations.
+ double v = (x == 0) ? y : pow(pow_pv[x] + pow_pv[y], 1 / pv);
+
+ // Smoothing function.
+ // If factor == 1, smoothing will be linear from 0 to the end,
+ // if 0 < factor < 1, smoothing will drop faster near 0.
+ // if factor > 1, smoothing will drop faster near the end (depth).
+ double f = 256.0 - coef * pow(v, factor);
+
+ uint8_t alpha = 0;
+ if (f > kOpaqueAlpha)
+ alpha = kOpaqueAlpha;
+ else if (f < kTransparentAlpha)
+ alpha = kTransparentAlpha;
+ else
+ alpha = static_cast<uint8_t>(f);
+
+ uint8_t red = ProcessColor(0, GetRed(background), alpha);
+ uint8_t green = ProcessColor(0, GetGreen(background), alpha);
+ uint8_t blue = ProcessColor(0, GetBlue(background), alpha);
+ uint32_t pixel = MakePixel(red, green, blue, GetAlpha(background));
+
+ // Mirror matrix.
+ matrix_[y * depth_ + x] = pixel;
+ matrix_[x * depth_ + y] = pixel;
+ }
+ }
+}
+
+ShadowMatrix::~ShadowMatrix() {
+}
+
+void PaintShadow(pp::ImageData* image,
+ const pp::Rect& clip_rc,
+ const pp::Rect& shadow_rc,
+ const ShadowMatrix& matrix) {
+ pp::Rect draw_rc = shadow_rc.Intersect(clip_rc);
+ if (draw_rc.IsEmpty())
+ return;
+
+ int32_t depth = static_cast<int32_t>(matrix.depth());
+ for (int32_t y = draw_rc.y(); y < draw_rc.bottom(); y++) {
+ for (int32_t x = draw_rc.x(); x < draw_rc.right(); x++) {
+ int32_t matrix_x = std::max(depth + shadow_rc.x() - x - 1,
+ depth - shadow_rc.right() + x);
+ int32_t matrix_y = std::max(depth + shadow_rc.y() - y - 1,
+ depth - shadow_rc.bottom() + y);
+ uint32_t* pixel = image->GetAddr32(pp::Point(x, y));
+
+ if (matrix_x < 0)
+ matrix_x = 0;
+ else if (matrix_x >= static_cast<int32_t>(depth))
+ matrix_x = depth - 1;
+
+ if (matrix_y < 0)
+ matrix_y = 0;
+ else if (matrix_y >= static_cast<int32_t>(depth))
+ matrix_y = depth - 1;
+
+ *pixel = matrix.GetValue(matrix_x, matrix_y);
+ }
+ }
+}
+
+void DrawShadow(pp::ImageData* image,
+ const pp::Rect& shadow_rc,
+ const pp::Rect& object_rc,
+ const pp::Rect& clip_rc,
+ const ShadowMatrix& matrix) {
+ if (shadow_rc == object_rc)
+ return; // Nothing to paint.
+
+ // Fill top part.
+ pp::Rect rc(shadow_rc.point(),
+ pp::Size(shadow_rc.width(), object_rc.y() - shadow_rc.y()));
+ PaintShadow(image, rc.Intersect(clip_rc), shadow_rc, matrix);
+
+ // Fill bottom part.
+ rc = pp::Rect(shadow_rc.x(), object_rc.bottom(),
+ shadow_rc.width(), shadow_rc.bottom() - object_rc.bottom());
+ PaintShadow(image, rc.Intersect(clip_rc), shadow_rc, matrix);
+
+ // Fill left part.
+ rc = pp::Rect(shadow_rc.x(), object_rc.y(),
+ object_rc.x() - shadow_rc.x(), object_rc.height());
+ PaintShadow(image, rc.Intersect(clip_rc), shadow_rc, matrix);
+
+ // Fill right part.
+ rc = pp::Rect(object_rc.right(), object_rc.y(),
+ shadow_rc.right() - object_rc.right(), object_rc.height());
+ PaintShadow(image, rc.Intersect(clip_rc), shadow_rc, matrix);
+}
+
+} // namespace chrome_pdf
+
diff --git a/chromium/pdf/draw_utils.h b/chromium/pdf/draw_utils.h
new file mode 100644
index 00000000000..8f91046610f
--- /dev/null
+++ b/chromium/pdf/draw_utils.h
@@ -0,0 +1,99 @@
+// Copyright (c) 2011 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_DRAW_UTILS_H_
+#define PDF_DRAW_UTILS_H_
+
+#include <stdint.h>
+
+#include <vector>
+
+#include "ppapi/cpp/image_data.h"
+#include "ppapi/cpp/rect.h"
+
+namespace chrome_pdf {
+
+const uint8_t kOpaqueAlpha = 0xFF;
+const uint8_t kTransparentAlpha = 0x00;
+
+void AlphaBlend(const pp::ImageData& src,
+ const pp::Rect& src_rc,
+ pp::ImageData* dest,
+ const pp::Point& dest_origin,
+ uint8_t alpha_adjustment);
+
+// Fill rectangle with gradient horizontally or vertically. Start is a color of
+// top-left point of the rectangle, end color is a color of
+// top-right (horizontal==true) or bottom-left (horizontal==false) point.
+void GradientFill(pp::ImageData* image,
+ const pp::Rect& rc,
+ uint32_t start_color,
+ uint32_t end_color,
+ bool horizontal);
+
+// Fill dirty rectangle with gradient, where gradient color set for corners of
+// gradient rectangle. Parts of the dirty rect outside of gradient rect will
+// be unchanged.
+void GradientFill(pp::Instance* instance,
+ pp::ImageData* image,
+ const pp::Rect& dirty_rc,
+ const pp::Rect& gradient_rc,
+ uint32_t start_color,
+ uint32_t end_color,
+ bool horizontal,
+ uint8_t transparency);
+
+// Copy one image into another. If stretch is true, the result occupy the entire
+// dest_rc. If stretch is false, dest_rc.point will be used as an origin of the
+// result image. Copy will ignore all pixels with transparent alpha from the
+// source image.
+void CopyImage(const pp::ImageData& src, const pp::Rect& src_rc,
+ pp::ImageData* dest, const pp::Rect& dest_rc,
+ bool stretch);
+
+// Fill in rectangle with specified color.
+void FillRect(pp::ImageData* image, const pp::Rect& rc, uint32_t color);
+
+// Shadow Matrix contains matrix for shadow rendering. To reduce amount of
+// calculations user may choose to cache matrix and reuse it if nothing changed.
+class ShadowMatrix {
+ public:
+ // Matrix parameters.
+ // depth - how big matrix should be. Shadow will go smoothly across the
+ // entire matrix from black to background color.
+ // If factor == 1, smoothing will be linear from 0 to the end (depth),
+ // if 0 < factor < 1, smoothing will drop faster near 0.
+ // if factor > 1, smoothing will drop faster near the end (depth).
+ ShadowMatrix(uint32_t depth, double factor, uint32_t background);
+
+ ~ShadowMatrix();
+
+ uint32_t GetValue(int32_t x, int32_t y) const {
+ return matrix_[y * depth_ + x];
+ }
+
+ uint32_t depth() const { return depth_; }
+ double factor() const { return factor_; }
+ uint32_t background() const { return background_; }
+
+ private:
+ uint32_t depth_;
+ double factor_;
+ uint32_t background_;
+ std::vector<uint32_t> matrix_;
+};
+
+// Draw shadow on the image using provided ShadowMatrix.
+// shadow_rc - rectangle occupied by shadow
+// object_rc - rectangle that drops the shadow
+// clip_rc - clipping region
+void DrawShadow(pp::ImageData* image,
+ const pp::Rect& shadow_rc,
+ const pp::Rect& object_rc,
+ const pp::Rect& clip_rc,
+ const ShadowMatrix& matrix);
+
+} // namespace chrome_pdf
+
+#endif // PDF_DRAW_UTILS_H_
diff --git a/chromium/pdf/out_of_process_instance.cc b/chromium/pdf/out_of_process_instance.cc
new file mode 100644
index 00000000000..869fdf24958
--- /dev/null
+++ b/chromium/pdf/out_of_process_instance.cc
@@ -0,0 +1,1445 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "pdf/out_of_process_instance.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include <algorithm> // for min/max()
+#define _USE_MATH_DEFINES // for M_PI
+#include <cmath> // for log() and pow()
+#include <math.h>
+#include <list>
+
+#include "base/json/json_reader.h"
+#include "base/json/json_writer.h"
+#include "base/logging.h"
+#include "base/strings/string_number_conversions.h"
+#include "base/strings/string_split.h"
+#include "base/strings/string_util.h"
+#include "base/strings/utf_string_conversions.h"
+#include "base/values.h"
+#include "chrome/common/content_restriction.h"
+#include "net/base/escape.h"
+#include "pdf/pdf.h"
+#include "ppapi/c/dev/ppb_cursor_control_dev.h"
+#include "ppapi/c/pp_errors.h"
+#include "ppapi/c/pp_rect.h"
+#include "ppapi/c/private/ppb_instance_private.h"
+#include "ppapi/c/private/ppp_pdf.h"
+#include "ppapi/c/trusted/ppb_url_loader_trusted.h"
+#include "ppapi/cpp/core.h"
+#include "ppapi/cpp/dev/memory_dev.h"
+#include "ppapi/cpp/dev/text_input_dev.h"
+#include "ppapi/cpp/dev/url_util_dev.h"
+#include "ppapi/cpp/module.h"
+#include "ppapi/cpp/point.h"
+#include "ppapi/cpp/private/pdf.h"
+#include "ppapi/cpp/private/var_private.h"
+#include "ppapi/cpp/rect.h"
+#include "ppapi/cpp/resource.h"
+#include "ppapi/cpp/url_request_info.h"
+#include "ppapi/cpp/var_array.h"
+#include "ppapi/cpp/var_dictionary.h"
+#include "ui/events/keycodes/keyboard_codes.h"
+
+namespace chrome_pdf {
+
+const char kChromePrint[] = "chrome://print/";
+const char kChromeExtension[] =
+ "chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai";
+
+// Dictionary Value key names for the document accessibility info
+const char kAccessibleNumberOfPages[] = "numberOfPages";
+const char kAccessibleLoaded[] = "loaded";
+const char kAccessibleCopyable[] = "copyable";
+
+// Constants used in handling postMessage() messages.
+const char kType[] = "type";
+// Viewport message arguments. (Page -> Plugin).
+const char kJSViewportType[] = "viewport";
+const char kJSXOffset[] = "xOffset";
+const char kJSYOffset[] = "yOffset";
+const char kJSZoom[] = "zoom";
+// Stop scrolling message (Page -> Plugin)
+const char kJSStopScrollingType[] = "stopScrolling";
+// Document dimension arguments (Plugin -> Page).
+const char kJSDocumentDimensionsType[] = "documentDimensions";
+const char kJSDocumentWidth[] = "width";
+const char kJSDocumentHeight[] = "height";
+const char kJSPageDimensions[] = "pageDimensions";
+const char kJSPageX[] = "x";
+const char kJSPageY[] = "y";
+const char kJSPageWidth[] = "width";
+const char kJSPageHeight[] = "height";
+// Document load progress arguments (Plugin -> Page)
+const char kJSLoadProgressType[] = "loadProgress";
+const char kJSProgressPercentage[] = "progress";
+// Metadata
+const char kJSMetadataType[] = "metadata";
+const char kJSBookmarks[] = "bookmarks";
+const char kJSTitle[] = "title";
+// Get password arguments (Plugin -> Page)
+const char kJSGetPasswordType[] = "getPassword";
+// Get password complete arguments (Page -> Plugin)
+const char kJSGetPasswordCompleteType[] = "getPasswordComplete";
+const char kJSPassword[] = "password";
+// Print (Page -> Plugin)
+const char kJSPrintType[] = "print";
+// Save (Page -> Plugin)
+const char kJSSaveType[] = "save";
+// Go to page (Plugin -> Page)
+const char kJSGoToPageType[] = "goToPage";
+const char kJSPageNumber[] = "page";
+// Reset print preview mode (Page -> Plugin)
+const char kJSResetPrintPreviewModeType[] = "resetPrintPreviewMode";
+const char kJSPrintPreviewUrl[] = "url";
+const char kJSPrintPreviewGrayscale[] = "grayscale";
+const char kJSPrintPreviewPageCount[] = "pageCount";
+// Load preview page (Page -> Plugin)
+const char kJSLoadPreviewPageType[] = "loadPreviewPage";
+const char kJSPreviewPageUrl[] = "url";
+const char kJSPreviewPageIndex[] = "index";
+// Set scroll position (Plugin -> Page)
+const char kJSSetScrollPositionType[] = "setScrollPosition";
+const char kJSPositionX[] = "x";
+const char kJSPositionY[] = "y";
+// Request accessibility JSON data (Page -> Plugin)
+const char kJSGetAccessibilityJSONType[] = "getAccessibilityJSON";
+const char kJSAccessibilityPageNumber[] = "page";
+// Reply with accessibility JSON data (Plugin -> Page)
+const char kJSGetAccessibilityJSONReplyType[] = "getAccessibilityJSONReply";
+const char kJSAccessibilityJSON[] = "json";
+// Cancel the stream URL request (Plugin -> Page)
+const char kJSCancelStreamUrlType[] = "cancelStreamUrl";
+// Navigate to the given URL (Plugin -> Page)
+const char kJSNavigateType[] = "navigate";
+const char kJSNavigateUrl[] = "url";
+const char kJSNavigateNewTab[] = "newTab";
+// Open the email editor with the given parameters (Plugin -> Page)
+const char kJSEmailType[] = "email";
+const char kJSEmailTo[] = "to";
+const char kJSEmailCc[] = "cc";
+const char kJSEmailBcc[] = "bcc";
+const char kJSEmailSubject[] = "subject";
+const char kJSEmailBody[] = "body";
+// Rotation (Page -> Plugin)
+const char kJSRotateClockwiseType[] = "rotateClockwise";
+const char kJSRotateCounterclockwiseType[] = "rotateCounterclockwise";
+// Select all text in the document (Page -> Plugin)
+const char kJSSelectAllType[] = "selectAll";
+// Get the selected text in the document (Page -> Plugin)
+const char kJSGetSelectedTextType[] = "getSelectedText";
+// Reply with selected text (Plugin -> Page)
+const char kJSGetSelectedTextReplyType[] = "getSelectedTextReply";
+const char kJSSelectedText[] = "selectedText";
+
+// Get the named destination with the given name (Page -> Plugin)
+const char KJSGetNamedDestinationType[] = "getNamedDestination";
+const char KJSGetNamedDestination[] = "namedDestination";
+// Reply with the page number of the named destination (Plugin -> Page)
+const char kJSGetNamedDestinationReplyType[] = "getNamedDestinationReply";
+const char kJSNamedDestinationPageNumber[] = "pageNumber";
+
+// Selecting text in document (Plugin -> Page)
+const char kJSSetIsSelectingType[] = "setIsSelecting";
+const char kJSIsSelecting[] = "isSelecting";
+
+// Notify when a form field is focused (Plugin -> Page)
+const char kJSFieldFocusType[] = "formFocusChange";
+const char kJSFieldFocus[] = "focused";
+
+const int kFindResultCooldownMs = 100;
+
+const double kMinZoom = 0.01;
+
+namespace {
+
+static const char kPPPPdfInterface[] = PPP_PDF_INTERFACE_1;
+
+// Used for UMA. Do not delete entries, and keep in sync with histograms.xml.
+enum PDFFeatures {
+ LOADED_DOCUMENT = 0,
+ HAS_TITLE = 1,
+ HAS_BOOKMARKS = 2,
+ FEATURES_COUNT
+};
+
+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) {
+ OutOfProcessInstance* 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) {
+ OutOfProcessInstance* obj_instance =
+ static_cast<OutOfProcessInstance*>(object);
+ obj_instance->GetPrintPresetOptionsFromDocument(options);
+ }
+ return PP_TRUE;
+}
+
+const PPP_Pdf ppp_private = {
+ &GetLinkAtPosition,
+ &Transform,
+ &GetPrintPresetOptionsFromDocument
+};
+
+int ExtractPrintPreviewPageIndex(const std::string& src_url) {
+ // Sample |src_url| format: chrome://print/id/page_index/print.pdf
+ std::vector<std::string> url_substr = base::SplitString(
+ src_url.substr(strlen(kChromePrint)), "/",
+ base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
+ if (url_substr.size() != 3)
+ return -1;
+
+ if (url_substr[2] != "print.pdf")
+ return -1;
+
+ int page_index = 0;
+ if (!base::StringToInt(url_substr[1], &page_index))
+ return -1;
+ return page_index;
+}
+
+bool IsPrintPreviewUrl(const std::string& url) {
+ return url.substr(0, strlen(kChromePrint)) == kChromePrint;
+}
+
+void ScalePoint(float scale, pp::Point* point) {
+ point->set_x(static_cast<int>(point->x() * scale));
+ point->set_y(static_cast<int>(point->y() * scale));
+}
+
+void ScaleRect(float scale, pp::Rect* rect) {
+ int left = static_cast<int>(floorf(rect->x() * scale));
+ int top = static_cast<int>(floorf(rect->y() * scale));
+ int right = static_cast<int>(ceilf((rect->x() + rect->width()) * scale));
+ int bottom = static_cast<int>(ceilf((rect->y() + rect->height()) * scale));
+ rect->SetRect(left, top, right - left, bottom - top);
+}
+
+// TODO(raymes): Remove this dependency on VarPrivate/InstancePrivate. It's
+// needed right now to do a synchronous call to JavaScript, but we could easily
+// replace this with a custom PPB_PDF function.
+pp::Var ModalDialog(const pp::Instance* instance,
+ const std::string& type,
+ const std::string& message,
+ const std::string& default_answer) {
+ const PPB_Instance_Private* interface =
+ reinterpret_cast<const PPB_Instance_Private*>(
+ pp::Module::Get()->GetBrowserInterface(
+ PPB_INSTANCE_PRIVATE_INTERFACE));
+ pp::VarPrivate window(pp::PASS_REF,
+ interface->GetWindowObject(instance->pp_instance()));
+ if (default_answer.empty())
+ return window.Call(type, message);
+ else
+ return window.Call(type, message, default_answer);
+}
+
+} // namespace
+
+OutOfProcessInstance::OutOfProcessInstance(PP_Instance instance)
+ : pp::Instance(instance),
+ pp::Find_Private(this),
+ pp::Printing_Dev(this),
+ cursor_(PP_CURSORTYPE_POINTER),
+ zoom_(1.0),
+ device_scale_(1.0),
+ full_(false),
+ paint_manager_(this, this, true),
+ first_paint_(true),
+ document_load_state_(LOAD_STATE_LOADING),
+ preview_document_load_state_(LOAD_STATE_COMPLETE),
+ uma_(this),
+ told_browser_about_unsupported_feature_(false),
+ print_preview_page_count_(0),
+ last_progress_sent_(0),
+ recently_sent_find_update_(false),
+ received_viewport_message_(false),
+ did_call_start_loading_(false),
+ stop_scrolling_(false),
+ background_color_(0),
+ top_toolbar_height_(0) {
+ loader_factory_.Initialize(this);
+ timer_factory_.Initialize(this);
+ form_factory_.Initialize(this);
+ print_callback_factory_.Initialize(this);
+ engine_.reset(PDFEngine::Create(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 reset the PDFEngine during destruction as it may call back into
+ // this object.
+ engine_.reset();
+}
+
+bool OutOfProcessInstance::Init(uint32_t argc,
+ const char* argn[],
+ const char* argv[]) {
+ // Check if the PDF is being loaded in the PDF chrome extension. We only allow
+ // the plugin to be loaded in the extension and print preview to avoid
+ // exposing sensitive APIs directly to external websites.
+ pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this);
+ if (!document_url_var.is_string())
+ return false;
+ std::string document_url = document_url_var.AsString();
+ std::string extension_url = std::string(kChromeExtension);
+ std::string print_preview_url = std::string(kChromePrint);
+ if (!base::StringPiece(document_url).starts_with(kChromeExtension) &&
+ !base::StringPiece(document_url).starts_with(kChromePrint)) {
+ return false;
+ }
+
+ // Check if the plugin is full frame. This is passed in from JS.
+ for (uint32_t i = 0; i < argc; ++i) {
+ if (strcmp(argn[i], "full-frame") == 0) {
+ full_ = true;
+ break;
+ }
+ }
+
+ // Only allow the plugin to handle find requests if it is full frame.
+ if (full_)
+ SetPluginToHandleFindRequests();
+
+ text_input_.reset(new pp::TextInput_Dev(this));
+
+ const char* stream_url = nullptr;
+ const char* original_url = nullptr;
+ const char* headers = nullptr;
+ for (uint32_t i = 0; i < argc; ++i) {
+ bool success = true;
+ if (strcmp(argn[i], "src") == 0)
+ original_url = argv[i];
+ else if (strcmp(argn[i], "stream-url") == 0)
+ stream_url = argv[i];
+ else if (strcmp(argn[i], "headers") == 0)
+ headers = argv[i];
+ else if (strcmp(argn[i], "background-color") == 0)
+ success = base::HexStringToUInt(argv[i], &background_color_);
+ else if (strcmp(argn[i], "top-toolbar-height") == 0)
+ success = base::StringToInt(argv[i], &top_toolbar_height_);
+
+ if (!success)
+ return false;
+ }
+
+ if (!original_url)
+ return false;
+
+ if (!stream_url)
+ stream_url = original_url;
+
+ // If we're in print preview mode we don't need to load the document yet.
+ // A |kJSResetPrintPreviewModeType| message will be sent to the plugin letting
+ // it know the url to load. By not loading here we avoid loading the same
+ // document twice.
+ if (IsPrintPreviewUrl(original_url))
+ return true;
+
+ LoadUrl(stream_url);
+ url_ = original_url;
+ return engine_->New(original_url, headers);
+}
+
+void OutOfProcessInstance::HandleMessage(const pp::Var& message) {
+ pp::VarDictionary dict(message);
+ if (!dict.Get(kType).is_string()) {
+ NOTREACHED();
+ return;
+ }
+
+ std::string type = dict.Get(kType).AsString();
+
+ if (type == kJSViewportType &&
+ dict.Get(pp::Var(kJSXOffset)).is_number() &&
+ dict.Get(pp::Var(kJSYOffset)).is_number() &&
+ dict.Get(pp::Var(kJSZoom)).is_number()) {
+ received_viewport_message_ = true;
+ stop_scrolling_ = false;
+ double zoom = dict.Get(pp::Var(kJSZoom)).AsDouble();
+ pp::FloatPoint scroll_offset(dict.Get(pp::Var(kJSXOffset)).AsDouble(),
+ dict.Get(pp::Var(kJSYOffset)).AsDouble());
+
+ // Bound the input parameters.
+ zoom = std::max(kMinZoom, zoom);
+ SetZoom(zoom);
+ scroll_offset = BoundScrollOffsetToDocument(scroll_offset);
+ engine_->ScrolledToXPosition(scroll_offset.x() * device_scale_);
+ engine_->ScrolledToYPosition(scroll_offset.y() * device_scale_);
+ } else if (type == kJSGetPasswordCompleteType &&
+ dict.Get(pp::Var(kJSPassword)).is_string()) {
+ if (password_callback_) {
+ pp::CompletionCallbackWithOutput<pp::Var> callback = *password_callback_;
+ password_callback_.reset();
+ *callback.output() = dict.Get(pp::Var(kJSPassword)).pp_var();
+ callback.Run(PP_OK);
+ } else {
+ NOTREACHED();
+ }
+ } else if (type == kJSPrintType) {
+ Print();
+ } else if (type == kJSSaveType) {
+ pp::PDF::SaveAs(this);
+ } else if (type == kJSRotateClockwiseType) {
+ RotateClockwise();
+ } else if (type == kJSRotateCounterclockwiseType) {
+ RotateCounterclockwise();
+ } else if (type == kJSSelectAllType) {
+ engine_->SelectAll();
+ } else if (type == kJSResetPrintPreviewModeType &&
+ dict.Get(pp::Var(kJSPrintPreviewUrl)).is_string() &&
+ dict.Get(pp::Var(kJSPrintPreviewGrayscale)).is_bool() &&
+ dict.Get(pp::Var(kJSPrintPreviewPageCount)).is_int()) {
+ url_ = dict.Get(pp::Var(kJSPrintPreviewUrl)).AsString();
+ preview_pages_info_ = std::queue<PreviewPageInfo>();
+ preview_document_load_state_ = LOAD_STATE_COMPLETE;
+ document_load_state_ = LOAD_STATE_LOADING;
+ LoadUrl(url_);
+ preview_engine_.reset();
+ engine_.reset(PDFEngine::Create(this));
+ engine_->SetGrayscale(dict.Get(pp::Var(kJSPrintPreviewGrayscale)).AsBool());
+ engine_->New(url_.c_str(), nullptr /* empty header */);
+
+ print_preview_page_count_ =
+ std::max(dict.Get(pp::Var(kJSPrintPreviewPageCount)).AsInt(), 0);
+
+ paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
+ } else if (type == kJSLoadPreviewPageType &&
+ dict.Get(pp::Var(kJSPreviewPageUrl)).is_string() &&
+ dict.Get(pp::Var(kJSPreviewPageIndex)).is_int()) {
+ ProcessPreviewPageInfo(dict.Get(pp::Var(kJSPreviewPageUrl)).AsString(),
+ dict.Get(pp::Var(kJSPreviewPageIndex)).AsInt());
+ } else if (type == kJSGetAccessibilityJSONType) {
+ pp::VarDictionary reply;
+ reply.Set(pp::Var(kType), pp::Var(kJSGetAccessibilityJSONReplyType));
+ if (dict.Get(pp::Var(kJSAccessibilityPageNumber)).is_int()) {
+ int page = dict.Get(pp::Var(kJSAccessibilityPageNumber)).AsInt();
+ reply.Set(pp::Var(kJSAccessibilityJSON),
+ pp::Var(engine_->GetPageAsJSON(page)));
+ } else {
+ base::DictionaryValue node;
+ node.SetInteger(kAccessibleNumberOfPages, engine_->GetNumberOfPages());
+ node.SetBoolean(kAccessibleLoaded,
+ document_load_state_ != LOAD_STATE_LOADING);
+ bool has_permissions =
+ engine_->HasPermission(PDFEngine::PERMISSION_COPY) ||
+ engine_->HasPermission(PDFEngine::PERMISSION_COPY_ACCESSIBLE);
+ node.SetBoolean(kAccessibleCopyable, has_permissions);
+ std::string json;
+ base::JSONWriter::Write(node, &json);
+ reply.Set(pp::Var(kJSAccessibilityJSON), pp::Var(json));
+ }
+ PostMessage(reply);
+ } else if (type == kJSStopScrollingType) {
+ stop_scrolling_ = true;
+ } else if (type == kJSGetSelectedTextType) {
+ std::string selected_text = engine_->GetSelectedText();
+ // Always return unix newlines to JS.
+ base::ReplaceChars(selected_text, "\r", std::string(), &selected_text);
+ pp::VarDictionary reply;
+ reply.Set(pp::Var(kType), pp::Var(kJSGetSelectedTextReplyType));
+ reply.Set(pp::Var(kJSSelectedText), selected_text);
+ PostMessage(reply);
+ } else if (type == KJSGetNamedDestinationType &&
+ dict.Get(pp::Var(KJSGetNamedDestination)).is_string()) {
+ int page_number = engine_->GetNamedDestinationPage(
+ dict.Get(pp::Var(KJSGetNamedDestination)).AsString());
+ pp::VarDictionary reply;
+ reply.Set(pp::Var(kType), pp::Var(kJSGetNamedDestinationReplyType));
+ if (page_number >= 0)
+ reply.Set(pp::Var(kJSNamedDestinationPageNumber), page_number);
+ PostMessage(reply);
+ } else {
+ NOTREACHED();
+ }
+}
+
+bool OutOfProcessInstance::HandleInputEvent(
+ const pp::InputEvent& event) {
+ // To simplify things, convert the event into device coordinates if it is
+ // a mouse event.
+ pp::InputEvent event_device_res(event);
+ {
+ pp::MouseInputEvent mouse_event(event);
+ if (!mouse_event.is_null()) {
+ pp::Point point = mouse_event.GetPosition();
+ pp::Point movement = mouse_event.GetMovement();
+ ScalePoint(device_scale_, &point);
+ ScalePoint(device_scale_, &movement);
+ mouse_event = pp::MouseInputEvent(
+ this,
+ event.GetType(),
+ event.GetTimeStamp(),
+ event.GetModifiers(),
+ mouse_event.GetButton(),
+ point,
+ mouse_event.GetClickCount(),
+ movement);
+ event_device_res = mouse_event;
+ }
+ }
+
+ pp::InputEvent offset_event(event_device_res);
+ switch (offset_event.GetType()) {
+ case PP_INPUTEVENT_TYPE_MOUSEDOWN:
+ case PP_INPUTEVENT_TYPE_MOUSEUP:
+ case PP_INPUTEVENT_TYPE_MOUSEMOVE:
+ case PP_INPUTEVENT_TYPE_MOUSEENTER:
+ case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
+ pp::MouseInputEvent mouse_event(event_device_res);
+ pp::MouseInputEvent mouse_event_dip(event);
+ pp::Point point = mouse_event.GetPosition();
+ point.set_x(point.x() - available_area_.x());
+ offset_event = pp::MouseInputEvent(
+ this,
+ event.GetType(),
+ event.GetTimeStamp(),
+ event.GetModifiers(),
+ mouse_event.GetButton(),
+ point,
+ mouse_event.GetClickCount(),
+ mouse_event.GetMovement());
+ break;
+ }
+ default:
+ break;
+ }
+ if (engine_->HandleEvent(offset_event))
+ return true;
+
+ // Middle click is used for scrolling and is handled by the container page.
+ pp::MouseInputEvent mouse_event(event_device_res);
+ if (!mouse_event.is_null() &&
+ mouse_event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_MIDDLE) {
+ return false;
+ }
+
+ // Return true for unhandled clicks so the plugin takes focus.
+ return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
+}
+
+void OutOfProcessInstance::DidChangeView(const pp::View& view) {
+ pp::Rect view_rect(view.GetRect());
+ float old_device_scale = device_scale_;
+ float device_scale = view.GetDeviceScale();
+ pp::Size view_device_size(view_rect.width() * device_scale,
+ view_rect.height() * device_scale);
+
+ if (view_device_size != plugin_size_ || device_scale != device_scale_) {
+ device_scale_ = device_scale;
+ plugin_dip_size_ = view_rect.size();
+ plugin_size_ = view_device_size;
+
+ paint_manager_.SetSize(view_device_size, device_scale_);
+
+ pp::Size new_image_data_size = PaintManager::GetNewContextSize(
+ image_data_.size(),
+ plugin_size_);
+ if (new_image_data_size != image_data_.size()) {
+ image_data_ = pp::ImageData(this,
+ PP_IMAGEDATAFORMAT_BGRA_PREMUL,
+ new_image_data_size,
+ false);
+ first_paint_ = true;
+ }
+
+ if (image_data_.is_null()) {
+ DCHECK(plugin_size_.IsEmpty());
+ return;
+ }
+
+ OnGeometryChanged(zoom_, old_device_scale);
+ }
+
+ if (!stop_scrolling_) {
+ pp::Point scroll_offset(view.GetScrollOffset());
+ // Because view messages come from the DOM, the coordinates of the viewport
+ // are 0-based (i.e. they do not correspond to the viewport's coordinates in
+ // JS), so we need to subtract the toolbar height to convert them into
+ // viewport coordinates.
+ pp::FloatPoint scroll_offset_float(scroll_offset.x(),
+ scroll_offset.y() - top_toolbar_height_);
+ scroll_offset_float = BoundScrollOffsetToDocument(scroll_offset_float);
+ engine_->ScrolledToXPosition(scroll_offset_float.x() * device_scale_);
+ engine_->ScrolledToYPosition(scroll_offset_float.y() * device_scale_);
+ }
+}
+
+void OutOfProcessInstance::GetPrintPresetOptionsFromDocument(
+ PP_PdfPrintPresetOptions_Dev* options) {
+ options->is_scaling_disabled = PP_FromBool(IsPrintScalingDisabled());
+ options->duplex =
+ static_cast<PP_PrivateDuplexMode_Dev>(engine_->GetDuplexType());
+ options->copies = engine_->GetCopiesToPrint();
+ pp::Size uniform_page_size;
+ options->is_page_size_uniform =
+ PP_FromBool(engine_->GetPageSizeAndUniformity(&uniform_page_size));
+ options->uniform_page_size = uniform_page_size;
+}
+
+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(offset_point);
+}
+
+uint32_t OutOfProcessInstance::QuerySupportedPrintOutputFormats() {
+ return engine_->QuerySupportedPrintOutputFormats();
+}
+
+int32_t OutOfProcessInstance::PrintBegin(
+ const PP_PrintSettings_Dev& print_settings) {
+ // For us num_pages is always equal to the number of pages in the PDF
+ // document irrespective of the printable area.
+ int32_t ret = engine_->GetNumberOfPages();
+ if (!ret)
+ return 0;
+
+ uint32_t supported_formats = engine_->QuerySupportedPrintOutputFormats();
+ if ((print_settings.format & supported_formats) == 0)
+ return 0;
+
+ print_settings_.is_printing = true;
+ print_settings_.pepper_print_settings = print_settings;
+ engine_->PrintBegin();
+ return ret;
+}
+
+pp::Resource OutOfProcessInstance::PrintPages(
+ const PP_PrintPageNumberRange_Dev* page_ranges,
+ uint32_t page_range_count) {
+ if (!print_settings_.is_printing)
+ return pp::Resource();
+
+ print_settings_.print_pages_called_ = true;
+ return engine_->PrintPages(page_ranges, page_range_count,
+ print_settings_.pepper_print_settings);
+}
+
+void OutOfProcessInstance::PrintEnd() {
+ if (print_settings_.print_pages_called_)
+ UserMetricsRecordAction("PDF.PrintPage");
+ print_settings_.Clear();
+ engine_->PrintEnd();
+}
+
+bool OutOfProcessInstance::IsPrintScalingDisabled() {
+ return !engine_->GetPrintScaling();
+}
+
+bool OutOfProcessInstance::StartFind(const std::string& text,
+ bool case_sensitive) {
+ engine_->StartFind(text, case_sensitive);
+ return true;
+}
+
+void OutOfProcessInstance::SelectFindResult(bool forward) {
+ engine_->SelectFindResult(forward);
+}
+
+void OutOfProcessInstance::StopFind() {
+ engine_->StopFind();
+ tickmarks_.clear();
+ SetTickmarks(tickmarks_);
+}
+
+void OutOfProcessInstance::OnPaint(
+ const std::vector<pp::Rect>& paint_rects,
+ std::vector<PaintManager::ReadyRect>* ready,
+ std::vector<pp::Rect>* pending) {
+ if (image_data_.is_null()) {
+ DCHECK(plugin_size_.IsEmpty());
+ return;
+ }
+ if (first_paint_) {
+ first_paint_ = false;
+ pp::Rect rect = pp::Rect(pp::Point(), image_data_.size());
+ FillRect(rect, background_color_);
+ ready->push_back(PaintManager::ReadyRect(rect, image_data_, true));
+ }
+
+ if (!received_viewport_message_)
+ return;
+
+ engine_->PrePaint();
+
+ for (const auto& paint_rect : paint_rects) {
+ // Intersect with plugin area since there could be pending invalidates from
+ // when the plugin area was larger.
+ pp::Rect rect =
+ paint_rect.Intersect(pp::Rect(pp::Point(), plugin_size_));
+ if (rect.IsEmpty())
+ continue;
+
+ pp::Rect pdf_rect = available_area_.Intersect(rect);
+ if (!pdf_rect.IsEmpty()) {
+ pdf_rect.Offset(available_area_.x() * -1, 0);
+
+ std::vector<pp::Rect> pdf_ready;
+ std::vector<pp::Rect> pdf_pending;
+ engine_->Paint(pdf_rect, &image_data_, &pdf_ready, &pdf_pending);
+ for (auto& ready_rect : pdf_ready) {
+ ready_rect.Offset(available_area_.point());
+ ready->push_back(
+ PaintManager::ReadyRect(ready_rect, image_data_, false));
+ }
+ for (auto& pending_rect : pdf_pending) {
+ pending_rect.Offset(available_area_.point());
+ pending->push_back(pending_rect);
+ }
+ }
+
+ // Ensure the region above the first page (if any) is filled;
+ int32_t first_page_ypos = engine_->GetNumberOfPages() == 0 ?
+ 0 : engine_->GetPageScreenRect(0).y();
+ if (rect.y() < first_page_ypos) {
+ pp::Rect region = rect.Intersect(pp::Rect(
+ pp::Point(), pp::Size(plugin_size_.width(), first_page_ypos)));
+ ready->push_back(PaintManager::ReadyRect(region, image_data_, false));
+ FillRect(region, background_color_);
+ }
+
+ for (const auto& background_part : background_parts_) {
+ pp::Rect intersection = background_part.location.Intersect(rect);
+ if (!intersection.IsEmpty()) {
+ FillRect(intersection, background_part.color);
+ ready->push_back(
+ PaintManager::ReadyRect(intersection, image_data_, false));
+ }
+ }
+ }
+
+ engine_->PostPaint();
+}
+
+void OutOfProcessInstance::DidOpen(int32_t result) {
+ if (result == PP_OK) {
+ if (!engine_->HandleDocumentLoad(embed_loader_)) {
+ document_load_state_ = LOAD_STATE_LOADING;
+ DocumentLoadFailed();
+ }
+ } else if (result != PP_ERROR_ABORTED) { // Can happen in tests.
+ NOTREACHED();
+ DocumentLoadFailed();
+ }
+
+ // If it's a progressive load, cancel the stream URL request so that requests
+ // can be made on the original URL.
+ // TODO(raymes): Make this clearer once the in-process plugin is deleted.
+ if (engine_->IsProgressiveLoad()) {
+ pp::VarDictionary message;
+ message.Set(kType, kJSCancelStreamUrlType);
+ PostMessage(message);
+ }
+}
+
+void OutOfProcessInstance::DidOpenPreview(int32_t result) {
+ if (result == PP_OK) {
+ preview_client_.reset(new PreviewModeClient(this));
+ preview_engine_.reset(PDFEngine::Create(preview_client_.get()));
+ preview_engine_->HandleDocumentLoad(embed_preview_loader_);
+ } else {
+ NOTREACHED();
+ }
+}
+
+void OutOfProcessInstance::OnClientTimerFired(int32_t id) {
+ engine_->OnCallback(id);
+}
+
+void OutOfProcessInstance::CalculateBackgroundParts() {
+ background_parts_.clear();
+ int left_width = available_area_.x();
+ int right_start = available_area_.right();
+ int right_width = abs(plugin_size_.width() - available_area_.right());
+ int bottom = std::min(available_area_.bottom(), plugin_size_.height());
+
+ // Add the left, right, and bottom rectangles. Note: we assume only
+ // horizontal centering.
+ BackgroundPart part = {
+ pp::Rect(0, 0, left_width, bottom),
+ background_color_
+ };
+ if (!part.location.IsEmpty())
+ background_parts_.push_back(part);
+ part.location = pp::Rect(right_start, 0, right_width, bottom);
+ if (!part.location.IsEmpty())
+ background_parts_.push_back(part);
+ part.location = pp::Rect(
+ 0, bottom, plugin_size_.width(), plugin_size_.height() - bottom);
+ if (!part.location.IsEmpty())
+ background_parts_.push_back(part);
+}
+
+int OutOfProcessInstance::GetDocumentPixelWidth() const {
+ return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_));
+}
+
+int OutOfProcessInstance::GetDocumentPixelHeight() const {
+ return static_cast<int>(
+ ceil(document_size_.height() * zoom_ * device_scale_));
+}
+
+void OutOfProcessInstance::FillRect(const pp::Rect& rect, uint32_t color) {
+ DCHECK(!image_data_.is_null() || rect.IsEmpty());
+ uint32_t* buffer_start = static_cast<uint32_t*>(image_data_.data());
+ int stride = image_data_.stride();
+ uint32_t* ptr = buffer_start + rect.y() * stride / 4 + rect.x();
+ int height = rect.height();
+ int width = rect.width();
+ for (int y = 0; y < height; ++y) {
+ for (int x = 0; x < width; ++x)
+ *(ptr + x) = color;
+ ptr += stride /4;
+ }
+}
+
+void OutOfProcessInstance::DocumentSizeUpdated(const pp::Size& size) {
+ document_size_ = size;
+
+ pp::VarDictionary dimensions;
+ dimensions.Set(kType, kJSDocumentDimensionsType);
+ dimensions.Set(kJSDocumentWidth, pp::Var(document_size_.width()));
+ dimensions.Set(kJSDocumentHeight, pp::Var(document_size_.height()));
+ pp::VarArray page_dimensions_array;
+ int num_pages = engine_->GetNumberOfPages();
+ for (int i = 0; i < num_pages; ++i) {
+ pp::Rect page_rect = engine_->GetPageRect(i);
+ pp::VarDictionary page_dimensions;
+ page_dimensions.Set(kJSPageX, pp::Var(page_rect.x()));
+ page_dimensions.Set(kJSPageY, pp::Var(page_rect.y()));
+ page_dimensions.Set(kJSPageWidth, pp::Var(page_rect.width()));
+ page_dimensions.Set(kJSPageHeight, pp::Var(page_rect.height()));
+ page_dimensions_array.Set(i, page_dimensions);
+ }
+ dimensions.Set(kJSPageDimensions, page_dimensions_array);
+ PostMessage(dimensions);
+
+ OnGeometryChanged(zoom_, device_scale_);
+}
+
+void OutOfProcessInstance::Invalidate(const pp::Rect& rect) {
+ pp::Rect offset_rect(rect);
+ offset_rect.Offset(available_area_.point());
+ paint_manager_.InvalidateRect(offset_rect);
+}
+
+void OutOfProcessInstance::Scroll(const pp::Point& point) {
+ if (!image_data_.is_null())
+ paint_manager_.ScrollRect(available_area_, point);
+}
+
+void OutOfProcessInstance::ScrollToX(int x) {
+ pp::VarDictionary position;
+ position.Set(kType, kJSSetScrollPositionType);
+ position.Set(kJSPositionX, pp::Var(x / device_scale_));
+ PostMessage(position);
+}
+
+void OutOfProcessInstance::ScrollToY(int y) {
+ pp::VarDictionary position;
+ position.Set(kType, kJSSetScrollPositionType);
+ position.Set(kJSPositionY, pp::Var(y / device_scale_));
+ PostMessage(position);
+}
+
+void OutOfProcessInstance::ScrollToPage(int page) {
+ if (engine_->GetNumberOfPages() == 0)
+ return;
+
+ pp::VarDictionary message;
+ message.Set(kType, kJSGoToPageType);
+ message.Set(kJSPageNumber, pp::Var(page));
+ PostMessage(message);
+}
+
+void OutOfProcessInstance::NavigateTo(const std::string& url,
+ bool open_in_new_tab) {
+ pp::VarDictionary message;
+ message.Set(kType, kJSNavigateType);
+ message.Set(kJSNavigateUrl, url);
+ message.Set(kJSNavigateNewTab, open_in_new_tab);
+ PostMessage(message);
+}
+
+void OutOfProcessInstance::UpdateCursor(PP_CursorType_Dev cursor) {
+ if (cursor == cursor_)
+ return;
+ cursor_ = cursor;
+
+ const PPB_CursorControl_Dev* cursor_interface =
+ reinterpret_cast<const PPB_CursorControl_Dev*>(
+ pp::Module::Get()->GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
+ if (!cursor_interface) {
+ NOTREACHED();
+ return;
+ }
+
+ cursor_interface->SetCursor(
+ pp_instance(), cursor_, pp::ImageData().pp_resource(), nullptr);
+}
+
+void OutOfProcessInstance::UpdateTickMarks(
+ const std::vector<pp::Rect>& tickmarks) {
+ float inverse_scale = 1.0f / device_scale_;
+ std::vector<pp::Rect> scaled_tickmarks = tickmarks;
+ for (auto& tickmark : scaled_tickmarks)
+ ScaleRect(inverse_scale, &tickmark);
+ tickmarks_ = scaled_tickmarks;
+}
+
+void OutOfProcessInstance::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 (final_result) {
+ NumberOfFindResultsChanged(total, final_result);
+ SetTickmarks(tickmarks_);
+ return;
+ }
+
+ if (recently_sent_find_update_)
+ return;
+
+ NumberOfFindResultsChanged(total, final_result);
+ SetTickmarks(tickmarks_);
+ recently_sent_find_update_ = true;
+ pp::CompletionCallback callback =
+ timer_factory_.NewCallback(
+ &OutOfProcessInstance::ResetRecentlySentFindUpdate);
+ pp::Module::Get()->core()->CallOnMainThread(kFindResultCooldownMs,
+ callback, 0);
+}
+
+void OutOfProcessInstance::NotifySelectedFindResultChanged(
+ int current_find_index) {
+ DCHECK_GE(current_find_index, 0);
+ SelectedFindResultChanged(current_find_index);
+}
+
+void OutOfProcessInstance::GetDocumentPassword(
+ pp::CompletionCallbackWithOutput<pp::Var> callback) {
+ if (password_callback_) {
+ NOTREACHED();
+ return;
+ }
+
+ password_callback_.reset(
+ new pp::CompletionCallbackWithOutput<pp::Var>(callback));
+ pp::VarDictionary message;
+ message.Set(pp::Var(kType), pp::Var(kJSGetPasswordType));
+ PostMessage(message);
+}
+
+void OutOfProcessInstance::Alert(const std::string& message) {
+ ModalDialog(this, "alert", message, std::string());
+}
+
+bool OutOfProcessInstance::Confirm(const std::string& message) {
+ pp::Var result = ModalDialog(this, "confirm", message, std::string());
+ return result.is_bool() ? result.AsBool() : false;
+}
+
+std::string OutOfProcessInstance::Prompt(const std::string& question,
+ const std::string& default_answer) {
+ pp::Var result = ModalDialog(this, "prompt", question, default_answer);
+ return result.is_string() ? result.AsString() : std::string();
+}
+
+std::string OutOfProcessInstance::GetURL() {
+ return url_;
+}
+
+void OutOfProcessInstance::Email(const std::string& to,
+ const std::string& cc,
+ const std::string& bcc,
+ const std::string& subject,
+ const std::string& body) {
+ pp::VarDictionary message;
+ message.Set(pp::Var(kType), pp::Var(kJSEmailType));
+ message.Set(pp::Var(kJSEmailTo),
+ pp::Var(net::EscapeUrlEncodedData(to, false)));
+ message.Set(pp::Var(kJSEmailCc),
+ pp::Var(net::EscapeUrlEncodedData(cc, false)));
+ message.Set(pp::Var(kJSEmailBcc),
+ pp::Var(net::EscapeUrlEncodedData(bcc, false)));
+ message.Set(pp::Var(kJSEmailSubject),
+ pp::Var(net::EscapeUrlEncodedData(subject, false)));
+ message.Set(pp::Var(kJSEmailBody),
+ pp::Var(net::EscapeUrlEncodedData(body, false)));
+ PostMessage(message);
+}
+
+void OutOfProcessInstance::Print() {
+ if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
+ !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
+ return;
+ }
+
+ pp::CompletionCallback callback =
+ print_callback_factory_.NewCallback(&OutOfProcessInstance::OnPrint);
+ pp::Module::Get()->core()->CallOnMainThread(0, callback);
+}
+
+void OutOfProcessInstance::OnPrint(int32_t) {
+ pp::PDF::Print(this);
+}
+
+void OutOfProcessInstance::SubmitForm(const std::string& url,
+ const void* data,
+ int length) {
+ pp::URLRequestInfo request(this);
+ request.SetURL(url);
+ request.SetMethod("POST");
+ request.AppendDataToBody(reinterpret_cast<const char*>(data), length);
+
+ pp::CompletionCallback callback =
+ form_factory_.NewCallback(&OutOfProcessInstance::FormDidOpen);
+ form_loader_ = CreateURLLoaderInternal();
+ int rv = form_loader_.Open(request, callback);
+ if (rv != PP_OK_COMPLETIONPENDING)
+ callback.Run(rv);
+}
+
+void OutOfProcessInstance::FormDidOpen(int32_t result) {
+ // TODO: inform the user of success/failure.
+ if (result != PP_OK) {
+ NOTREACHED();
+ }
+}
+
+std::string OutOfProcessInstance::ShowFileSelectionDialog() {
+ // Seems like very low priority to implement, since the pdf has no way to get
+ // the file data anyways. Javascript doesn't let you do this synchronously.
+ NOTREACHED();
+ return std::string();
+}
+
+pp::URLLoader OutOfProcessInstance::CreateURLLoader() {
+ if (full_) {
+ if (!did_call_start_loading_) {
+ did_call_start_loading_ = true;
+ pp::PDF::DidStartLoading(this);
+ }
+
+ // Disable save and print until the document is fully loaded, since they
+ // would generate an incomplete document. Need to do this each time we
+ // call DidStartLoading since that resets the content restrictions.
+ pp::PDF::SetContentRestriction(this, CONTENT_RESTRICTION_SAVE |
+ CONTENT_RESTRICTION_PRINT);
+ }
+
+ return CreateURLLoaderInternal();
+}
+
+void OutOfProcessInstance::ScheduleCallback(int id, int delay_in_ms) {
+ pp::CompletionCallback callback =
+ timer_factory_.NewCallback(&OutOfProcessInstance::OnClientTimerFired);
+ pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id);
+}
+
+void OutOfProcessInstance::SearchString(const base::char16* string,
+ const base::char16* term,
+ bool case_sensitive,
+ std::vector<SearchStringResult>* results) {
+ PP_PrivateFindResult* pp_results;
+ int count = 0;
+ pp::PDF::SearchString(
+ this,
+ reinterpret_cast<const unsigned short*>(string),
+ reinterpret_cast<const unsigned short*>(term),
+ case_sensitive,
+ &pp_results,
+ &count);
+
+ results->resize(count);
+ for (int 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);
+}
+
+void OutOfProcessInstance::DocumentPaintOccurred() {
+}
+
+void OutOfProcessInstance::DocumentLoadComplete(int page_count) {
+ // Clear focus state for OSK.
+ FormTextFieldFocusChange(false);
+
+ DCHECK(document_load_state_ == LOAD_STATE_LOADING);
+ document_load_state_ = LOAD_STATE_COMPLETE;
+ UserMetricsRecordAction("PDF.LoadSuccess");
+ uma_.HistogramEnumeration("PDF.DocumentFeature", LOADED_DOCUMENT,
+ FEATURES_COUNT);
+
+ // Note: If we are in print preview mode the scroll location is retained
+ // across document loads so we don't want to scroll again and override it.
+ if (IsPrintPreview()) {
+ AppendBlankPrintPreviewPages();
+ OnGeometryChanged(0, 0);
+ }
+
+ pp::VarDictionary metadata_message;
+ metadata_message.Set(pp::Var(kType), pp::Var(kJSMetadataType));
+ std::string title = engine_->GetMetadata("Title");
+ if (!base::TrimWhitespace(base::UTF8ToUTF16(title), base::TRIM_ALL).empty()) {
+ metadata_message.Set(pp::Var(kJSTitle), pp::Var(title));
+ uma_.HistogramEnumeration("PDF.DocumentFeature", HAS_TITLE, FEATURES_COUNT);
+ }
+
+ pp::VarArray bookmarks = engine_->GetBookmarks();
+ metadata_message.Set(pp::Var(kJSBookmarks), bookmarks);
+ if (bookmarks.GetLength() > 0) {
+ uma_.HistogramEnumeration("PDF.DocumentFeature", HAS_BOOKMARKS,
+ FEATURES_COUNT);
+ }
+ PostMessage(metadata_message);
+
+ pp::VarDictionary progress_message;
+ progress_message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
+ progress_message.Set(pp::Var(kJSProgressPercentage), pp::Var(100));
+ PostMessage(progress_message);
+
+ if (!full_)
+ return;
+
+ if (did_call_start_loading_) {
+ pp::PDF::DidStopLoading(this);
+ did_call_start_loading_ = false;
+ }
+
+ int content_restrictions =
+ CONTENT_RESTRICTION_CUT | CONTENT_RESTRICTION_PASTE;
+ if (!engine_->HasPermission(PDFEngine::PERMISSION_COPY))
+ content_restrictions |= CONTENT_RESTRICTION_COPY;
+
+ if (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) &&
+ !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY)) {
+ content_restrictions |= CONTENT_RESTRICTION_PRINT;
+ }
+
+ pp::PDF::SetContentRestriction(this, content_restrictions);
+
+ uma_.HistogramCustomCounts("PDF.PageCount", page_count, 1, 1000000, 50);
+}
+
+void OutOfProcessInstance::RotateClockwise() {
+ engine_->RotateClockwise();
+}
+
+void OutOfProcessInstance::RotateCounterclockwise() {
+ engine_->RotateCounterclockwise();
+}
+
+void OutOfProcessInstance::PreviewDocumentLoadComplete() {
+ if (preview_document_load_state_ != LOAD_STATE_LOADING ||
+ preview_pages_info_.empty()) {
+ return;
+ }
+
+ preview_document_load_state_ = LOAD_STATE_COMPLETE;
+
+ int dest_page_index = preview_pages_info_.front().second;
+ int src_page_index =
+ ExtractPrintPreviewPageIndex(preview_pages_info_.front().first);
+ if (src_page_index > 0 && dest_page_index > -1 && preview_engine_.get())
+ engine_->AppendPage(preview_engine_.get(), dest_page_index);
+
+ preview_pages_info_.pop();
+ // |print_preview_page_count_| is not updated yet. Do not load any
+ // other preview pages till we get this information.
+ if (print_preview_page_count_ == 0)
+ return;
+
+ if (!preview_pages_info_.empty())
+ LoadAvailablePreviewPage();
+}
+
+void OutOfProcessInstance::DocumentLoadFailed() {
+ DCHECK(document_load_state_ == LOAD_STATE_LOADING);
+ UserMetricsRecordAction("PDF.LoadFailure");
+
+ if (did_call_start_loading_) {
+ pp::PDF::DidStopLoading(this);
+ did_call_start_loading_ = false;
+ }
+
+ document_load_state_ = LOAD_STATE_FAILED;
+ paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
+
+ // Send a progress value of -1 to indicate a failure.
+ pp::VarDictionary message;
+ message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
+ message.Set(pp::Var(kJSProgressPercentage), pp::Var(-1));
+ PostMessage(message);
+}
+
+void OutOfProcessInstance::PreviewDocumentLoadFailed() {
+ UserMetricsRecordAction("PDF.PreviewDocumentLoadFailure");
+ if (preview_document_load_state_ != LOAD_STATE_LOADING ||
+ preview_pages_info_.empty()) {
+ return;
+ }
+
+ preview_document_load_state_ = LOAD_STATE_FAILED;
+ preview_pages_info_.pop();
+
+ if (!preview_pages_info_.empty())
+ LoadAvailablePreviewPage();
+}
+
+pp::Instance* OutOfProcessInstance::GetPluginInstance() {
+ return this;
+}
+
+void OutOfProcessInstance::DocumentHasUnsupportedFeature(
+ const std::string& feature) {
+ std::string metric("PDF_Unsupported_");
+ metric += feature;
+ if (!unsupported_features_reported_.count(metric)) {
+ unsupported_features_reported_.insert(metric);
+ UserMetricsRecordAction(metric);
+ }
+
+ // Since we use an info bar, only do this for full frame plugins..
+ if (!full_)
+ return;
+
+ if (told_browser_about_unsupported_feature_)
+ return;
+ told_browser_about_unsupported_feature_ = true;
+
+ pp::PDF::HasUnsupportedFeature(this);
+}
+
+void OutOfProcessInstance::DocumentLoadProgress(uint32_t available,
+ uint32_t doc_size) {
+ double progress = 0.0;
+ if (doc_size == 0) {
+ // Document size is unknown. Use heuristics.
+ // We'll make progress logarithmic from 0 to 100M.
+ static const double kFactor = log(100000000.0) / 100.0;
+ if (available > 0) {
+ progress = log(static_cast<double>(available)) / kFactor;
+ if (progress > 100.0)
+ progress = 100.0;
+ }
+ } else {
+ progress = 100.0 * static_cast<double>(available) / doc_size;
+ }
+
+ // We send 100% load progress in DocumentLoadComplete.
+ if (progress >= 100)
+ return;
+
+ // Avoid sending too many progress messages over PostMessage.
+ if (progress > last_progress_sent_ + 1) {
+ last_progress_sent_ = progress;
+ pp::VarDictionary message;
+ message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType));
+ message.Set(pp::Var(kJSProgressPercentage), pp::Var(progress));
+ PostMessage(message);
+ }
+}
+
+void OutOfProcessInstance::FormTextFieldFocusChange(bool in_focus) {
+ if (!text_input_.get())
+ return;
+
+ pp::VarDictionary message;
+ message.Set(pp::Var(kType), pp::Var(kJSFieldFocusType));
+ message.Set(pp::Var(kJSFieldFocus), pp::Var(in_focus));
+ PostMessage(message);
+
+ if (in_focus)
+ text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT);
+ else
+ text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE);
+}
+
+void OutOfProcessInstance::ResetRecentlySentFindUpdate(int32_t /* unused */) {
+ recently_sent_find_update_ = false;
+}
+
+void OutOfProcessInstance::OnGeometryChanged(double old_zoom,
+ float old_device_scale) {
+ if (zoom_ != old_zoom || device_scale_ != old_device_scale)
+ engine_->ZoomUpdated(zoom_ * device_scale_);
+
+ available_area_ = pp::Rect(plugin_size_);
+ int doc_width = GetDocumentPixelWidth();
+ if (doc_width < available_area_.width()) {
+ available_area_.Offset((available_area_.width() - doc_width) / 2, 0);
+ available_area_.set_width(doc_width);
+ }
+ int bottom_of_document =
+ GetDocumentPixelHeight() + (top_toolbar_height_ * device_scale_);
+ if (bottom_of_document < available_area_.height())
+ available_area_.set_height(bottom_of_document);
+
+ CalculateBackgroundParts();
+ engine_->PageOffsetUpdated(available_area_.point());
+ engine_->PluginSizeUpdated(available_area_.size());
+
+ if (!document_size_.GetArea())
+ return;
+ paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_));
+}
+
+void OutOfProcessInstance::LoadUrl(const std::string& url) {
+ LoadUrlInternal(url, &embed_loader_, &OutOfProcessInstance::DidOpen);
+}
+
+void OutOfProcessInstance::LoadPreviewUrl(const std::string& url) {
+ LoadUrlInternal(url, &embed_preview_loader_,
+ &OutOfProcessInstance::DidOpenPreview);
+}
+
+void OutOfProcessInstance::LoadUrlInternal(
+ const std::string& url,
+ pp::URLLoader* loader,
+ void (OutOfProcessInstance::* method)(int32_t)) {
+ pp::URLRequestInfo request(this);
+ request.SetURL(url);
+ request.SetMethod("GET");
+
+ *loader = CreateURLLoaderInternal();
+ pp::CompletionCallback callback = loader_factory_.NewCallback(method);
+ int rv = loader->Open(request, callback);
+ if (rv != PP_OK_COMPLETIONPENDING)
+ callback.Run(rv);
+}
+
+pp::URLLoader OutOfProcessInstance::CreateURLLoaderInternal() {
+ pp::URLLoader loader(this);
+
+ const PPB_URLLoaderTrusted* trusted_interface =
+ reinterpret_cast<const PPB_URLLoaderTrusted*>(
+ pp::Module::Get()->GetBrowserInterface(
+ PPB_URLLOADERTRUSTED_INTERFACE));
+ if (trusted_interface)
+ trusted_interface->GrantUniversalAccess(loader.pp_resource());
+ return loader;
+}
+
+void OutOfProcessInstance::SetZoom(double scale) {
+ double old_zoom = zoom_;
+ zoom_ = scale;
+ OnGeometryChanged(old_zoom, device_scale_);
+}
+
+void OutOfProcessInstance::AppendBlankPrintPreviewPages() {
+ if (print_preview_page_count_ == 0)
+ return;
+ engine_->AppendBlankPages(print_preview_page_count_);
+ if (!preview_pages_info_.empty())
+ LoadAvailablePreviewPage();
+}
+
+bool OutOfProcessInstance::IsPrintPreview() {
+ return IsPrintPreviewUrl(url_);
+}
+
+uint32_t OutOfProcessInstance::GetBackgroundColor() {
+ return background_color_;
+}
+
+void OutOfProcessInstance::IsSelectingChanged(bool is_selecting) {
+ pp::VarDictionary message;
+ message.Set(kType, kJSSetIsSelectingType);
+ message.Set(kJSIsSelecting, pp::Var(is_selecting));
+ PostMessage(message);
+}
+
+void OutOfProcessInstance::ProcessPreviewPageInfo(const std::string& url,
+ int dst_page_index) {
+ if (!IsPrintPreview())
+ return;
+
+ int src_page_index = ExtractPrintPreviewPageIndex(url);
+ if (src_page_index < 1)
+ return;
+
+ preview_pages_info_.push(std::make_pair(url, dst_page_index));
+ LoadAvailablePreviewPage();
+}
+
+void OutOfProcessInstance::LoadAvailablePreviewPage() {
+ if (preview_pages_info_.empty() ||
+ document_load_state_ != LOAD_STATE_COMPLETE) {
+ return;
+ }
+
+ std::string url = preview_pages_info_.front().first;
+ int dst_page_index = preview_pages_info_.front().second;
+ int src_page_index = ExtractPrintPreviewPageIndex(url);
+ if (src_page_index < 1 ||
+ dst_page_index >= print_preview_page_count_ ||
+ preview_document_load_state_ == LOAD_STATE_LOADING) {
+ return;
+ }
+
+ preview_document_load_state_ = LOAD_STATE_LOADING;
+ LoadPreviewUrl(url);
+}
+
+void OutOfProcessInstance::UserMetricsRecordAction(
+ const std::string& action) {
+ // TODO(raymes): Move this function to PPB_UMA_Private.
+ pp::PDF::UserMetricsRecordAction(this, pp::Var(action));
+}
+
+pp::FloatPoint OutOfProcessInstance::BoundScrollOffsetToDocument(
+ const pp::FloatPoint& scroll_offset) {
+ float max_x = document_size_.width() * zoom_ - plugin_dip_size_.width();
+ float x = std::max(std::min(scroll_offset.x(), max_x), 0.0f);
+ float min_y = -top_toolbar_height_;
+ float max_y = document_size_.height() * zoom_ - plugin_dip_size_.height();
+ float y = std::max(std::min(scroll_offset.y(), max_y), min_y);
+ return pp::FloatPoint(x, y);
+}
+
+} // namespace chrome_pdf
diff --git a/chromium/pdf/out_of_process_instance.h b/chromium/pdf/out_of_process_instance.h
new file mode 100644
index 00000000000..bdd0e686015
--- /dev/null
+++ b/chromium/pdf/out_of_process_instance.h
@@ -0,0 +1,350 @@
+// 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 <queue>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "base/macros.h"
+#include "base/memory/scoped_ptr.h"
+#include "pdf/paint_manager.h"
+#include "pdf/pdf_engine.h"
+#include "pdf/preview_mode_client.h"
+
+#include "ppapi/c/private/ppb_pdf.h"
+#include "ppapi/c/private/ppp_pdf.h"
+#include "ppapi/cpp/dev/printing_dev.h"
+#include "ppapi/cpp/dev/scriptable_object_deprecated.h"
+#include "ppapi/cpp/graphics_2d.h"
+#include "ppapi/cpp/image_data.h"
+#include "ppapi/cpp/input_event.h"
+#include "ppapi/cpp/instance.h"
+#include "ppapi/cpp/private/find_private.h"
+#include "ppapi/cpp/private/uma_private.h"
+#include "ppapi/cpp/url_loader.h"
+#include "ppapi/utility/completion_callback_factory.h"
+
+namespace pp {
+class TextInput_Dev;
+}
+
+namespace chrome_pdf {
+
+class OutOfProcessInstance : public pp::Instance,
+ public pp::Find_Private,
+ public pp::Printing_Dev,
+ public PaintManager::Client,
+ public PDFEngine::Client,
+ public PreviewModeClient::Client {
+ public:
+ explicit OutOfProcessInstance(PP_Instance instance);
+ ~OutOfProcessInstance() override;
+
+ // pp::Instance implementation.
+ 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;
+
+ // pp::Find_Private implementation.
+ bool StartFind(const std::string& text, bool case_sensitive) override;
+ void SelectFindResult(bool forward) override;
+ void StopFind() override;
+
+ // pp::PaintManager::Client implementation.
+ void OnPaint(const std::vector<pp::Rect>& paint_rects,
+ std::vector<PaintManager::ReadyRect>* ready,
+ std::vector<pp::Rect>* pending) override;
+
+ // pp::Printing_Dev implementation.
+ 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 implementation.
+ pp::Var GetLinkAtPosition(const pp::Point& point);
+ void GetPrintPresetOptionsFromDocument(PP_PdfPrintPresetOptions_Dev* options);
+
+ void FlushCallback(int32_t result);
+ void DidOpen(int32_t result);
+ void DidOpenPreview(int32_t result);
+
+ // Called when the timer is fired.
+ void OnClientTimerFired(int32_t id);
+
+ // Called to print without re-entrancy issues.
+ void OnPrint(int32_t);
+
+ // PDFEngine::Client implementation.
+ void DocumentSizeUpdated(const pp::Size& size) override;
+ void Invalidate(const pp::Rect& rect) override;
+ void Scroll(const pp::Point& point) override;
+ void ScrollToX(int position) override;
+ void ScrollToY(int position) override;
+ void ScrollToPage(int page) override;
+ void NavigateTo(const std::string& url, bool open_in_new_tab) override;
+ void UpdateCursor(PP_CursorType_Dev cursor) override;
+ void UpdateTickMarks(const std::vector<pp::Rect>& tickmarks) override;
+ void NotifyNumberOfFindResultsChanged(int total, bool final_result) override;
+ void NotifySelectedFindResultChanged(int current_find_index) override;
+ void GetDocumentPassword(
+ pp::CompletionCallbackWithOutput<pp::Var> callback) 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::string GetURL() override;
+ void Email(const std::string& to,
+ const std::string& cc,
+ const std::string& bcc,
+ const std::string& subject,
+ const std::string& body) override;
+ void Print() override;
+ void SubmitForm(const std::string& url,
+ const void* data,
+ int length) override;
+ std::string ShowFileSelectionDialog() override;
+ pp::URLLoader CreateURLLoader() override;
+ void ScheduleCallback(int id, int delay_in_ms) override;
+ void SearchString(const base::char16* string,
+ const base::char16* term,
+ bool case_sensitive,
+ std::vector<SearchStringResult>* results) override;
+ void DocumentPaintOccurred() override;
+ void DocumentLoadComplete(int page_count) override;
+ void DocumentLoadFailed() override;
+ pp::Instance* GetPluginInstance() override;
+ void DocumentHasUnsupportedFeature(const std::string& feature) override;
+ void DocumentLoadProgress(uint32_t available, uint32_t doc_size) override;
+ void FormTextFieldFocusChange(bool in_focus) override;
+ bool IsPrintPreview() override;
+ uint32_t GetBackgroundColor() override;
+ void IsSelectingChanged(bool is_selecting) override;
+
+ // PreviewModeClient::Client implementation.
+ void PreviewDocumentLoadComplete() override;
+ void PreviewDocumentLoadFailed() override;
+
+ // Helper functions for implementing PPP_PDF.
+ void RotateClockwise();
+ void RotateCounterclockwise();
+
+ private:
+ void ResetRecentlySentFindUpdate(int32_t);
+
+ // Called whenever the plugin geometry changes to update the location of the
+ // background parts, and notifies the pdf engine.
+ void OnGeometryChanged(double old_zoom, float old_device_scale);
+
+ // Figures out the location of any background rectangles (i.e. those that
+ // aren't painted by the PDF engine).
+ void CalculateBackgroundParts();
+
+ // Computes document width/height in device pixels, based on current zoom and
+ // device scale
+ int GetDocumentPixelWidth() const;
+ int GetDocumentPixelHeight() const;
+
+ // Draws a rectangle with the specified dimensions and color in our buffer.
+ void FillRect(const pp::Rect& rect, uint32_t color);
+
+ void LoadUrl(const std::string& url);
+ void LoadPreviewUrl(const std::string& url);
+ void LoadUrlInternal(const std::string& url, pp::URLLoader* loader,
+ void (OutOfProcessInstance::* method)(int32_t));
+
+ // Creates a URL loader and allows it to access all urls, i.e. not just the
+ // frame's origin.
+ pp::URLLoader CreateURLLoaderInternal();
+
+ void FormDidOpen(int32_t result);
+
+ void UserMetricsRecordAction(const std::string& action);
+
+ enum DocumentLoadState {
+ LOAD_STATE_LOADING,
+ LOAD_STATE_COMPLETE,
+ LOAD_STATE_FAILED,
+ };
+
+ // Set new zoom scale.
+ void SetZoom(double scale);
+
+ // Reduces the document to 1 page and appends |print_preview_page_count_|
+ // blank pages to the document for print preview.
+ void AppendBlankPrintPreviewPages();
+
+ // Process the preview page data information. |src_url| specifies the preview
+ // page data location. The |src_url| is in the format:
+ // chrome://print/id/page_number/print.pdf
+ // |dst_page_index| specifies the blank page index that needs to be replaced
+ // with the new page data.
+ void ProcessPreviewPageInfo(const std::string& src_url, int dst_page_index);
+ // Load the next available preview page into the blank page.
+ void LoadAvailablePreviewPage();
+
+ // Bound the given scroll offset to the document.
+ pp::FloatPoint BoundScrollOffsetToDocument(
+ const pp::FloatPoint& scroll_offset);
+
+ pp::ImageData image_data_;
+ // Used when the plugin is embedded in a page and we have to create the loader
+ // ourself.
+ pp::CompletionCallbackFactory<OutOfProcessInstance> loader_factory_;
+ pp::URLLoader embed_loader_;
+ pp::URLLoader embed_preview_loader_;
+
+ PP_CursorType_Dev cursor_; // The current cursor.
+
+ pp::CompletionCallbackFactory<OutOfProcessInstance> timer_factory_;
+
+ // Size, in pixels, of plugin rectangle.
+ pp::Size plugin_size_;
+ // Size, in DIPs, of plugin rectangle.
+ pp::Size plugin_dip_size_;
+ // Remaining area, in pixels, to render the pdf in after accounting for
+ // horizontal centering.
+ pp::Rect available_area_;
+ // Size of entire document in pixels (i.e. if each page is 800 pixels high and
+ // there are 10 pages, the height will be 8000).
+ pp::Size document_size_;
+
+ double zoom_; // Current zoom factor.
+
+ float device_scale_; // Current device scale factor.
+ // True if the plugin is full-page.
+ bool full_;
+
+ PaintManager paint_manager_;
+
+ struct BackgroundPart {
+ pp::Rect location;
+ uint32_t color;
+ };
+ std::vector<BackgroundPart> background_parts_;
+
+ struct PrintSettings {
+ PrintSettings() {
+ Clear();
+ }
+ void Clear() {
+ is_printing = false;
+ print_pages_called_ = false;
+ memset(&pepper_print_settings, 0, sizeof(pepper_print_settings));
+ }
+ // This is set to true when PrintBegin is called and false when PrintEnd is
+ // called.
+ bool is_printing;
+ // To know whether this was an actual print operation, so we don't double
+ // count UMA logging.
+ bool print_pages_called_;
+ PP_PrintSettings_Dev pepper_print_settings;
+ };
+
+ PrintSettings print_settings_;
+
+ scoped_ptr<PDFEngine> engine_;
+
+ // The PreviewModeClient used for print preview. Will be passed to
+ // |preview_engine_|.
+ scoped_ptr<PreviewModeClient> preview_client_;
+
+ // This engine is used to render the individual preview page data. This is
+ // used only in print preview mode. This will use |PreviewModeClient|
+ // interface which has very limited access to the pp::Instance.
+ scoped_ptr<PDFEngine> preview_engine_;
+
+ std::string url_;
+
+ // Used for submitting forms.
+ pp::CompletionCallbackFactory<OutOfProcessInstance> form_factory_;
+ pp::URLLoader form_loader_;
+
+ // Used for printing without re-entrancy issues.
+ pp::CompletionCallbackFactory<OutOfProcessInstance> print_callback_factory_;
+
+ // The callback for receiving the password from the page.
+ scoped_ptr<pp::CompletionCallbackWithOutput<pp::Var> > password_callback_;
+
+ // True if we haven't painted the plugin viewport yet.
+ bool first_paint_;
+
+ DocumentLoadState document_load_state_;
+ DocumentLoadState preview_document_load_state_;
+
+ // A UMA resource for histogram reporting.
+ pp::UMAPrivate uma_;
+
+ // Used so that we only tell the browser once about an unsupported feature, to
+ // avoid the infobar going up more than once.
+ bool told_browser_about_unsupported_feature_;
+
+ // Keeps track of which unsupported features we reported, so we avoid spamming
+ // the stats if a feature shows up many times per document.
+ std::set<std::string> unsupported_features_reported_;
+
+ // Number of pages in print preview mode, 0 if not in print preview mode.
+ int print_preview_page_count_;
+ std::vector<int> print_preview_page_numbers_;
+
+ // Used to manage loaded print preview page information. A |PreviewPageInfo|
+ // consists of data source url string and the page index in the destination
+ // document.
+ typedef std::pair<std::string, int> PreviewPageInfo;
+ std::queue<PreviewPageInfo> preview_pages_info_;
+
+ // 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
+ scoped_ptr<pp::TextInput_Dev> text_input_;
+
+ // The last document load progress value sent to the web page.
+ double last_progress_sent_;
+
+ // Whether an update to the number of find results found was sent less than
+ // |kFindResultCooldownMs| milliseconds ago.
+ bool recently_sent_find_update_;
+
+ // The tickmarks.
+ std::vector<pp::Rect> tickmarks_;
+
+ // Whether the plugin has received a viewport changed message. Nothing should
+ // be painted until this is received.
+ bool received_viewport_message_;
+
+ // If true, this means we told the RenderView that we're starting a network
+ // request so that it can start the throbber. We will tell it again once the
+ // document finishes loading.
+ bool did_call_start_loading_;
+
+ // If this is true, then don't scroll the plugin in response to DidChangeView
+ // messages. 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_;
+
+ // The background color of the PDF viewer.
+ uint32_t background_color_;
+
+ // The blank space above the first page of the document reserved for the
+ // toolbar.
+ int top_toolbar_height_;
+
+ DISALLOW_COPY_AND_ASSIGN(OutOfProcessInstance);
+};
+
+} // namespace chrome_pdf
+
+#endif // PDF_OUT_OF_PROCESS_INSTANCE_H_
diff --git a/chromium/pdf/paint_aggregator.cc b/chromium/pdf/paint_aggregator.cc
new file mode 100644
index 00000000000..50d77fe47d3
--- /dev/null
+++ b/chromium/pdf/paint_aggregator.cc
@@ -0,0 +1,291 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "pdf/paint_aggregator.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include <algorithm>
+
+#include "base/logging.h"
+
+namespace {
+
+bool IsNegative(int32_t num) {
+ return num < 0;
+}
+
+} // namespace
+
+// ----------------------------------------------------------------------------
+// ALGORITHM NOTES
+//
+// We attempt to maintain a scroll rect in the presence of invalidations that
+// are contained within the scroll rect. If an invalidation crosses a scroll
+// rect, then we just treat the scroll rect as an invalidation rect.
+//
+// For invalidations performed prior to scrolling and contained within the
+// scroll rect, we offset the invalidation rects to account for the fact that
+// the consumer will perform scrolling before painting.
+//
+// We only support scrolling along one axis at a time. A diagonal scroll will
+// therefore be treated as an invalidation.
+// ----------------------------------------------------------------------------
+
+PaintAggregator::PaintUpdate::PaintUpdate() {
+}
+
+PaintAggregator::PaintUpdate::~PaintUpdate() {
+}
+
+PaintAggregator::InternalPaintUpdate::InternalPaintUpdate() :
+ synthesized_scroll_damage_rect_(false) {
+}
+
+PaintAggregator::InternalPaintUpdate::~InternalPaintUpdate() {
+}
+
+pp::Rect PaintAggregator::InternalPaintUpdate::GetScrollDamage() const {
+ // Should only be scrolling in one direction at a time.
+ DCHECK(!(scroll_delta.x() && scroll_delta.y()));
+
+ pp::Rect damaged_rect;
+
+ // Compute the region we will expose by scrolling, and paint that into a
+ // shared memory section.
+ if (scroll_delta.x()) {
+ int32_t dx = scroll_delta.x();
+ damaged_rect.set_y(scroll_rect.y());
+ damaged_rect.set_height(scroll_rect.height());
+ if (dx > 0) {
+ damaged_rect.set_x(scroll_rect.x());
+ damaged_rect.set_width(dx);
+ } else {
+ damaged_rect.set_x(scroll_rect.right() + dx);
+ damaged_rect.set_width(-dx);
+ }
+ } else {
+ int32_t dy = scroll_delta.y();
+ damaged_rect.set_x(scroll_rect.x());
+ damaged_rect.set_width(scroll_rect.width());
+ if (dy > 0) {
+ damaged_rect.set_y(scroll_rect.y());
+ damaged_rect.set_height(dy);
+ } else {
+ damaged_rect.set_y(scroll_rect.bottom() + dy);
+ damaged_rect.set_height(-dy);
+ }
+ }
+
+ // In case the scroll offset exceeds the width/height of the scroll rect
+ return scroll_rect.Intersect(damaged_rect);
+}
+
+PaintAggregator::PaintAggregator() {
+}
+
+bool PaintAggregator::HasPendingUpdate() const {
+ return !update_.scroll_rect.IsEmpty() || !update_.paint_rects.empty();
+}
+
+void PaintAggregator::ClearPendingUpdate() {
+ update_ = InternalPaintUpdate();
+}
+
+PaintAggregator::PaintUpdate PaintAggregator::GetPendingUpdate() {
+ // Convert the internal paint update to the external one, which includes a
+ // bit more precomputed info for the caller.
+ PaintUpdate ret;
+ ret.scroll_delta = update_.scroll_delta;
+ ret.scroll_rect = update_.scroll_rect;
+ ret.has_scroll = ret.scroll_delta.x() != 0 || ret.scroll_delta.y() != 0;
+
+ // Include the scroll damage (if any) in the paint rects.
+ // Code invalidates damaged rect here, it pick it up from the list of paint
+ // rects in the next block.
+ if (ret.has_scroll && !update_.synthesized_scroll_damage_rect_) {
+ update_.synthesized_scroll_damage_rect_ = true;
+ pp::Rect scroll_damage = update_.GetScrollDamage();
+ InvalidateRectInternal(scroll_damage, false);
+ }
+
+ ret.paint_rects.reserve(update_.paint_rects.size() + 1);
+ ret.paint_rects.insert(ret.paint_rects.end(), update_.paint_rects.begin(),
+ update_.paint_rects.end());
+
+ return ret;
+}
+
+void PaintAggregator::SetIntermediateResults(
+ const std::vector<ReadyRect>& ready,
+ const std::vector<pp::Rect>& pending) {
+ update_.ready_rects.insert(
+ update_.ready_rects.end(), ready.begin(), ready.end());
+ update_.paint_rects = pending;
+}
+
+std::vector<PaintAggregator::ReadyRect> PaintAggregator::GetReadyRects() const {
+ return update_.ready_rects;
+}
+
+void PaintAggregator::InvalidateRect(const pp::Rect& rect) {
+ InvalidateRectInternal(rect, true);
+}
+
+void PaintAggregator::ScrollRect(const pp::Rect& clip_rect,
+ const pp::Point& amount) {
+ // We only support scrolling along one axis at a time.
+ if (amount.x() != 0 && amount.y() != 0) {
+ InvalidateRect(clip_rect);
+ return;
+ }
+
+ // We can only scroll one rect at a time.
+ if (!update_.scroll_rect.IsEmpty() && update_.scroll_rect != clip_rect) {
+ InvalidateRect(clip_rect);
+ return;
+ }
+
+ // Again, we only support scrolling along one axis at a time. Make sure this
+ // update doesn't scroll on a different axis than any existing one.
+ if ((amount.x() && update_.scroll_delta.y()) ||
+ (amount.y() && update_.scroll_delta.x())) {
+ InvalidateRect(clip_rect);
+ return;
+ }
+
+ // If we scroll in a reverse direction to the direction we originally scrolled
+ // and there were invalidations that happened in-between we may end up
+ // incorrectly clipping the invalidated rects (see crbug.com/488390). This bug
+ // doesn't exist in the original implementation
+ // (ppapi/utility/graphics/paint_aggregator.cc) which uses a different method
+ // of handling invalidations that occur after a scroll. The problem is that
+ // when we scroll the invalidated region, we clip it to the scroll rect. This
+ // can cause us to lose information about what the invalidated region was if
+ // it gets scrolled back into view. We either need to not do this clipping or
+ // disallow combining scrolls that occur in different directions with
+ // invalidations that happen in-between. This code really needs some tests...
+ if (!update_.paint_rects.empty()) {
+ if (IsNegative(amount.x()) != IsNegative(update_.scroll_delta.x()) ||
+ IsNegative(amount.y()) != IsNegative(update_.scroll_delta.y())) {
+ InvalidateRect(clip_rect);
+ return;
+ }
+ }
+
+ // The scroll rect is new or isn't changing (though the scroll amount may
+ // be changing).
+ update_.scroll_rect = clip_rect;
+ update_.scroll_delta += amount;
+
+ // We might have just wiped out a pre-existing scroll.
+ if (update_.scroll_delta == pp::Point()) {
+ update_.scroll_rect = pp::Rect();
+ return;
+ }
+
+ // Adjust any paint rects that intersect the scroll. For the portion of the
+ // paint that is inside the scroll area, move it by the scroll amount and
+ // replace the existing paint with it. For the portion (if any) that is
+ // outside the scroll, just invalidate it.
+ std::vector<pp::Rect> leftover_rects;
+ for (size_t i = 0; i < update_.paint_rects.size(); ++i) {
+ if (!update_.scroll_rect.Intersects(update_.paint_rects[i]))
+ continue;
+
+ pp::Rect intersection =
+ update_.paint_rects[i].Intersect(update_.scroll_rect);
+ pp::Rect rect = update_.paint_rects[i];
+ while (!rect.IsEmpty()) {
+ pp::Rect leftover = rect.Subtract(intersection);
+ if (leftover.IsEmpty())
+ break;
+ // Don't want to call InvalidateRectInternal now since it'll modify
+ // update_.paint_rects, so keep track of this and do it below.
+ leftover_rects.push_back(leftover);
+ rect = rect.Subtract(leftover);
+ }
+
+ update_.paint_rects[i] = ScrollPaintRect(intersection, amount);
+
+ // The rect may have been scrolled out of view.
+ if (update_.paint_rects[i].IsEmpty()) {
+ update_.paint_rects.erase(update_.paint_rects.begin() + i);
+ i--;
+ }
+ }
+
+ for (const auto& leftover_rect : leftover_rects)
+ InvalidateRectInternal(leftover_rect, false);
+
+ for (auto& update_rect : update_.ready_rects) {
+ if (update_.scroll_rect.Contains(update_rect.rect))
+ update_rect.rect = ScrollPaintRect(update_rect.rect, amount);
+ }
+
+ if (update_.synthesized_scroll_damage_rect_) {
+ pp::Rect damage = update_.GetScrollDamage();
+ InvalidateRect(damage);
+ }
+}
+
+pp::Rect PaintAggregator::ScrollPaintRect(const pp::Rect& paint_rect,
+ const pp::Point& amount) const {
+ pp::Rect result = paint_rect;
+ result.Offset(amount);
+ result = update_.scroll_rect.Intersect(result);
+ return result;
+}
+
+void PaintAggregator::InvalidateScrollRect() {
+ pp::Rect scroll_rect = update_.scroll_rect;
+ update_.scroll_rect = pp::Rect();
+ update_.scroll_delta = pp::Point();
+ InvalidateRect(scroll_rect);
+}
+
+void PaintAggregator::InvalidateRectInternal(const pp::Rect& rect_old,
+ bool check_scroll) {
+ pp::Rect rect = rect_old;
+ // Check if any rects that are ready to be painted overlap.
+ for (size_t i = 0; i < update_.ready_rects.size(); ++i) {
+ const pp::Rect& existing_rect = update_.ready_rects[i].rect;
+ if (rect.Intersects(existing_rect)) {
+ // Re-invalidate in case the union intersects other paint rects.
+ rect = existing_rect.Union(rect);
+ update_.ready_rects.erase(update_.ready_rects.begin() + i);
+ break;
+ }
+ }
+
+ bool add_paint = true;
+
+ // Combine overlapping paints using smallest bounding box.
+ for (size_t i = 0; i < update_.paint_rects.size(); ++i) {
+ const pp::Rect& existing_rect = update_.paint_rects[i];
+ if (existing_rect.Contains(rect)) // Optimize out redundancy.
+ add_paint = false;
+ if (rect.Intersects(existing_rect) || rect.SharesEdgeWith(existing_rect)) {
+ // Re-invalidate in case the union intersects other paint rects.
+ pp::Rect combined_rect = existing_rect.Union(rect);
+ update_.paint_rects.erase(update_.paint_rects.begin() + i);
+ InvalidateRectInternal(combined_rect, check_scroll);
+ add_paint = false;
+ }
+ }
+
+ if (add_paint) {
+ // Add a non-overlapping paint.
+ update_.paint_rects.push_back(rect);
+ }
+
+ // If the new paint overlaps with a scroll, then also invalidate the rect in
+ // its new position.
+ if (check_scroll &&
+ !update_.scroll_rect.IsEmpty() &&
+ update_.scroll_rect.Intersects(rect)) {
+ InvalidateRectInternal(ScrollPaintRect(rect, update_.scroll_delta), false);
+ }
+}
diff --git a/chromium/pdf/paint_aggregator.h b/chromium/pdf/paint_aggregator.h
new file mode 100644
index 00000000000..96f61e08787
--- /dev/null
+++ b/chromium/pdf/paint_aggregator.h
@@ -0,0 +1,130 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef PDF_PAINT_AGGREGATOR_H_
+#define PDF_PAINT_AGGREGATOR_H_
+
+#include <vector>
+
+#include "ppapi/cpp/image_data.h"
+#include "ppapi/cpp/rect.h"
+#include "ppapi/cpp/rect.h"
+
+// This class is responsible for aggregating multiple invalidation and scroll
+// commands to produce a scroll and repaint sequence. You can use this manually
+// to track your updates, but most applications will use the PaintManager to
+// additionally handle the necessary callbacks on top of the PaintAggregator
+// functionality.
+//
+// See http://code.google.com/p/ppapi/wiki/2DPaintingModel
+class PaintAggregator {
+ public:
+ // Stores information about a rectangle that has finished painting. The
+ // PaintManager will paint it only when everything else on the screen is also
+ // ready.
+ struct ReadyRect {
+ pp::Point offset;
+ pp::Rect rect;
+ pp::ImageData image_data;
+ };
+
+ struct PaintUpdate {
+ PaintUpdate();
+ ~PaintUpdate();
+
+ // True if there is a scroll applied. This indicates that the scroll delta
+ // and scroll_rect are nonzero (just as a convenience).
+ bool has_scroll;
+
+ // The amount to scroll by. Either the X or Y may be nonzero to indicate a
+ // scroll in that direction, but there will never be a scroll in both
+ // directions at the same time (this will be converted to a paint of the
+ // region instead).
+ //
+ // If there is no scroll, this will be (0, 0).
+ pp::Point scroll_delta;
+
+ // The rectangle that should be scrolled by the scroll_delta. If there is no
+ // scroll, this will be (0, 0, 0, 0). We only track one scroll command at
+ // once. If there are multiple ones, they will be converted to invalidates.
+ pp::Rect scroll_rect;
+
+ // A list of all the individual dirty rectangles. This is an aggregated list
+ // of all invalidate calls. Different rectangles may be unified to produce a
+ // minimal list with no overlap that is more efficient to paint. This list
+ // also contains the region exposed by any scroll command.
+ std::vector<pp::Rect> paint_rects;
+ };
+
+ PaintAggregator();
+
+ // There is a PendingUpdate if InvalidateRect or ScrollRect were called and
+ // ClearPendingUpdate was not called.
+ bool HasPendingUpdate() const;
+ void ClearPendingUpdate();
+
+ PaintUpdate GetPendingUpdate();
+
+ // Sets the result of a call to the plugin to paint. This includes rects that
+ // are finished painting (ready), and ones that are still in-progress
+ // (pending).
+ void SetIntermediateResults(const std::vector<ReadyRect>& ready,
+ const std::vector<pp::Rect>& pending);
+
+ // Returns the rectangles that are ready to be painted.
+ std::vector<ReadyRect> GetReadyRects() const;
+
+ // The given rect should be repainted.
+ void InvalidateRect(const pp::Rect& rect);
+
+ // The given rect should be scrolled by the given amounts.
+ void ScrollRect(const pp::Rect& clip_rect, const pp::Point& amount);
+
+ private:
+ // This structure is an internal version of PaintUpdate. It's different in
+ // two respects:
+ //
+ // - The scroll damange (area exposed by the scroll operation, if any) is
+ // maintained separately from the dirty rects generated by calling
+ // InvalidateRect. We need to know this distinction for some operations.
+ //
+ // - The paint bounds union is computed on the fly so we don't have to keep
+ // a rectangle up-to-date as we do different operations.
+ class InternalPaintUpdate {
+ public:
+ InternalPaintUpdate();
+ ~InternalPaintUpdate();
+
+ // Computes the rect damaged by scrolling within |scroll_rect| by
+ // |scroll_delta|. This rect must be repainted. It is not included in
+ // paint_rects.
+ pp::Rect GetScrollDamage() const;
+
+ pp::Point scroll_delta;
+ pp::Rect scroll_rect;
+
+ // Does not include the scroll damage rect unless
+ // synthesized_scroll_damage_rect_ is set.
+ std::vector<pp::Rect> paint_rects;
+
+ // Rectangles that are finished painting.
+ std::vector<ReadyRect> ready_rects;
+
+ // Whether we have added the scroll damage rect to paint_rects yet or not.
+ bool synthesized_scroll_damage_rect_;
+ };
+
+ pp::Rect ScrollPaintRect(const pp::Rect& paint_rect,
+ const pp::Point& amount) const;
+ void InvalidateScrollRect();
+
+ // Internal method used by InvalidateRect. If |check_scroll| is true, then the
+ // method checks if there's a pending scroll and if so also invalidates |rect|
+ // in the new scroll position.
+ void InvalidateRectInternal(const pp::Rect& rect, bool check_scroll);
+
+ InternalPaintUpdate update_;
+};
+
+#endif // PDF_PAINT_AGGREGATOR_H_
diff --git a/chromium/pdf/paint_manager.cc b/chromium/pdf/paint_manager.cc
new file mode 100644
index 00000000000..226994c3b05
--- /dev/null
+++ b/chromium/pdf/paint_manager.cc
@@ -0,0 +1,304 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "pdf/paint_manager.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include <algorithm>
+
+#include "base/logging.h"
+#include "ppapi/c/pp_errors.h"
+#include "ppapi/cpp/instance.h"
+#include "ppapi/cpp/module.h"
+
+PaintManager::PaintManager(pp::Instance* instance,
+ Client* client,
+ bool is_always_opaque)
+ : instance_(instance),
+ client_(client),
+ is_always_opaque_(is_always_opaque),
+ callback_factory_(NULL),
+ manual_callback_pending_(false),
+ flush_pending_(false),
+ has_pending_resize_(false),
+ graphics_need_to_be_bound_(false),
+ pending_device_scale_(1.0),
+ device_scale_(1.0),
+ in_paint_(false),
+ first_paint_(true),
+ view_size_changed_waiting_for_paint_(false) {
+ // Set the callback object outside of the initializer list to avoid a
+ // compiler warning about using "this" in an initializer list.
+ callback_factory_.Initialize(this);
+
+ // You can not use a NULL client pointer.
+ DCHECK(client);
+}
+
+PaintManager::~PaintManager() {
+}
+
+// static
+pp::Size PaintManager::GetNewContextSize(const pp::Size& current_context_size,
+ const pp::Size& plugin_size) {
+ // The amount of additional space in pixels to allocate to the right/bottom of
+ // the context.
+ const int kBufferSize = 50;
+
+ // Default to returning the same size.
+ pp::Size result = current_context_size;
+
+ // The minimum size of the plugin before resizing the context to ensure we
+ // aren't wasting too much memory. We deduct twice the kBufferSize from the
+ // current context size which gives a threshhold that is kBufferSize below
+ // the plugin size when the context size was last computed.
+ pp::Size min_size(
+ std::max(current_context_size.width() - 2 * kBufferSize, 0),
+ std::max(current_context_size.height() - 2 * kBufferSize, 0));
+
+ // If the plugin size is bigger than the current context size, we need to
+ // resize the context. If the plugin size is smaller than the current
+ // context size by a given threshhold then resize the context so that we
+ // aren't wasting too much memory.
+ if (plugin_size.width() > current_context_size.width() ||
+ plugin_size.height() > current_context_size.height() ||
+ plugin_size.width() < min_size.width() ||
+ plugin_size.height() < min_size.height()) {
+ // Create a larger context than needed so that if we only resize by a
+ // small margin, we don't need a new context.
+ result = pp::Size(plugin_size.width() + kBufferSize,
+ plugin_size.height() + kBufferSize);
+ }
+
+ return result;
+}
+
+void PaintManager::Initialize(pp::Instance* instance,
+ Client* client,
+ bool is_always_opaque) {
+ DCHECK(!instance_ && !client_); // Can't initialize twice.
+ instance_ = instance;
+ client_ = client;
+ is_always_opaque_ = is_always_opaque;
+}
+
+void PaintManager::SetSize(const pp::Size& new_size, float device_scale) {
+ if (GetEffectiveSize() == new_size &&
+ GetEffectiveDeviceScale() == device_scale)
+ return;
+
+ has_pending_resize_ = true;
+ pending_size_ = new_size;
+ pending_device_scale_ = device_scale;
+
+ view_size_changed_waiting_for_paint_ = true;
+
+ Invalidate();
+}
+
+void PaintManager::Invalidate() {
+ if (graphics_.is_null() && !has_pending_resize_)
+ return;
+
+ EnsureCallbackPending();
+ aggregator_.InvalidateRect(pp::Rect(GetEffectiveSize()));
+}
+
+void PaintManager::InvalidateRect(const pp::Rect& rect) {
+ DCHECK(!in_paint_);
+
+ if (graphics_.is_null() && !has_pending_resize_)
+ return;
+
+ // Clip the rect to the device area.
+ pp::Rect clipped_rect = rect.Intersect(pp::Rect(GetEffectiveSize()));
+ if (clipped_rect.IsEmpty())
+ return; // Nothing to do.
+
+ EnsureCallbackPending();
+ aggregator_.InvalidateRect(clipped_rect);
+}
+
+void PaintManager::ScrollRect(const pp::Rect& clip_rect,
+ const pp::Point& amount) {
+ DCHECK(!in_paint_);
+
+ if (graphics_.is_null() && !has_pending_resize_)
+ return;
+
+ EnsureCallbackPending();
+
+ aggregator_.ScrollRect(clip_rect, amount);
+}
+
+pp::Size PaintManager::GetEffectiveSize() const {
+ return has_pending_resize_ ? pending_size_ : plugin_size_;
+}
+
+float PaintManager::GetEffectiveDeviceScale() const {
+ return has_pending_resize_ ? pending_device_scale_ : device_scale_;
+}
+
+void PaintManager::EnsureCallbackPending() {
+ // The best way for us to do the next update is to get a notification that
+ // a previous one has completed. So if we're already waiting for one, we
+ // don't have to do anything differently now.
+ if (flush_pending_)
+ return;
+
+ // If no flush is pending, we need to do a manual call to get back to the
+ // main thread. We may have one already pending, or we may need to schedule.
+ if (manual_callback_pending_)
+ return;
+
+ pp::Module::Get()->core()->CallOnMainThread(
+ 0,
+ callback_factory_.NewCallback(&PaintManager::OnManualCallbackComplete),
+ 0);
+ manual_callback_pending_ = true;
+}
+
+void PaintManager::DoPaint() {
+ in_paint_ = true;
+
+ std::vector<ReadyRect> ready;
+ std::vector<pp::Rect> pending;
+
+ DCHECK(aggregator_.HasPendingUpdate());
+
+ // Apply any pending resize. Setting the graphics to this class must happen
+ // before asking the plugin to paint in case it requests invalides or resizes.
+ // However, the bind must not happen until afterward since we don't want to
+ // have an unpainted device bound. The needs_binding flag tells us whether to
+ // do this later.
+ if (has_pending_resize_) {
+ plugin_size_ = pending_size_;
+ // Only create a new graphics context if the current context isn't big
+ // enough or if it is far too big. This avoids creating a new context if
+ // we only resize by a small amount.
+ pp::Size new_size = GetNewContextSize(graphics_.size(), pending_size_);
+ if (graphics_.size() != new_size) {
+ graphics_ = pp::Graphics2D(instance_, new_size, is_always_opaque_);
+ graphics_need_to_be_bound_ = true;
+
+ // Since we're binding a new one, all of the callbacks have been canceled.
+ manual_callback_pending_ = false;
+ flush_pending_ = false;
+ callback_factory_.CancelAll();
+ }
+
+ if (pending_device_scale_ != 1.0)
+ graphics_.SetScale(1.0 / pending_device_scale_);
+ device_scale_ = pending_device_scale_;
+
+ // This must be cleared before calling into the plugin since it may do
+ // additional invalidation or sizing operations.
+ has_pending_resize_ = false;
+ pending_size_ = pp::Size();
+ }
+
+ PaintAggregator::PaintUpdate update = aggregator_.GetPendingUpdate();
+ client_->OnPaint(update.paint_rects, &ready, &pending);
+
+ if (ready.empty() && pending.empty()) {
+ in_paint_ = false;
+ return; // Nothing was painted, don't schedule a flush.
+ }
+
+ std::vector<PaintAggregator::ReadyRect> ready_now;
+ if (pending.empty()) {
+ std::vector<PaintAggregator::ReadyRect> temp_ready;
+ temp_ready.insert(temp_ready.end(), ready.begin(), ready.end());
+ aggregator_.SetIntermediateResults(temp_ready, pending);
+ ready_now = aggregator_.GetReadyRects();
+ aggregator_.ClearPendingUpdate();
+
+ // Apply any scroll first.
+ if (update.has_scroll)
+ graphics_.Scroll(update.scroll_rect, update.scroll_delta);
+
+ view_size_changed_waiting_for_paint_ = false;
+ } else {
+ std::vector<PaintAggregator::ReadyRect> ready_later;
+ for (const auto& ready_rect : ready) {
+ // Don't flush any part (i.e. scrollbars) if we're resizing the browser,
+ // as that'll lead to flashes. Until we flush, the browser will use the
+ // previous image, but if we flush, it'll revert to using the blank image.
+ // We make an exception for the first paint since we want to show the
+ // default background color instead of the pepper default of black.
+ if (ready_rect.flush_now &&
+ (!view_size_changed_waiting_for_paint_ || first_paint_)) {
+ ready_now.push_back(ready_rect);
+ } else {
+ ready_later.push_back(ready_rect);
+ }
+ }
+ // Take the rectangles, except the ones that need to be flushed right away,
+ // and save them so that everything is flushed at once.
+ aggregator_.SetIntermediateResults(ready_later, pending);
+
+ if (ready_now.empty()) {
+ in_paint_ = false;
+ EnsureCallbackPending();
+ return;
+ }
+ }
+
+ for (const auto& ready_rect : ready_now) {
+ graphics_.PaintImageData(
+ ready_rect.image_data, ready_rect.offset, ready_rect.rect);
+ }
+
+ int32_t result = graphics_.Flush(
+ callback_factory_.NewCallback(&PaintManager::OnFlushComplete));
+
+ // If you trigger this assertion, then your plugin has called Flush()
+ // manually. When using the PaintManager, you should not call Flush, it will
+ // handle that for you because it needs to know when it can do the next paint
+ // by implementing the flush callback.
+ //
+ // Another possible cause of this assertion is re-using devices. If you
+ // use one device, swap it with another, then swap it back, we won't know
+ // that we've already scheduled a Flush on the first device. It's best to not
+ // re-use devices in this way.
+ DCHECK(result != PP_ERROR_INPROGRESS);
+
+ if (result == PP_OK_COMPLETIONPENDING) {
+ flush_pending_ = true;
+ } else {
+ DCHECK(result == PP_OK); // Catch all other errors in debug mode.
+ }
+
+ in_paint_ = false;
+ first_paint_ = false;
+
+ if (graphics_need_to_be_bound_) {
+ instance_->BindGraphics(graphics_);
+ graphics_need_to_be_bound_ = false;
+ }
+}
+
+void PaintManager::OnFlushComplete(int32_t) {
+ DCHECK(flush_pending_);
+ flush_pending_ = false;
+
+ // If more paints were enqueued while we were waiting for the flush to
+ // complete, execute them now.
+ if (aggregator_.HasPendingUpdate())
+ DoPaint();
+}
+
+void PaintManager::OnManualCallbackComplete(int32_t) {
+ DCHECK(manual_callback_pending_);
+ manual_callback_pending_ = false;
+
+ // Just because we have a manual callback doesn't mean there are actually any
+ // invalid regions. Even though we only schedule this callback when something
+ // is pending, a Flush callback could have come in before this callback was
+ // executed and that could have cleared the queue.
+ if (aggregator_.HasPendingUpdate())
+ DoPaint();
+}
diff --git a/chromium/pdf/paint_manager.h b/chromium/pdf/paint_manager.h
new file mode 100644
index 00000000000..d7f7e3f594b
--- /dev/null
+++ b/chromium/pdf/paint_manager.h
@@ -0,0 +1,207 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef PDF_PAINT_MANAGER_H_
+#define PDF_PAINT_MANAGER_H_
+
+#include <stdint.h>
+
+#include <vector>
+
+#include "pdf/paint_aggregator.h"
+#include "ppapi/cpp/graphics_2d.h"
+#include "ppapi/utility/completion_callback_factory.h"
+
+namespace pp {
+class Graphics2D;
+class Instance;
+class Point;
+class Rect;
+};
+
+// Custom PaintManager for the PDF plugin. This is branched from the Pepper
+// version. The difference is that this supports progressive rendering of dirty
+// rects, where multiple calls to the rendering engine are needed. It also
+// supports having higher-priority rects flushing right away, i.e. the
+// scrollbars.
+//
+// The client's OnPaint
+class PaintManager {
+ public:
+ // Like PaintAggregator's version, but allows the plugin to tell us whether
+ // it should be flushed to the screen immediately or when the rest of the
+ // plugin viewport is ready.
+ struct ReadyRect {
+ pp::Point offset;
+ pp::Rect rect;
+ pp::ImageData image_data;
+ bool flush_now;
+
+ ReadyRect(const pp::Rect& r, const pp::ImageData& i, bool f)
+ : rect(r), image_data(i), flush_now(f) {}
+
+ operator PaintAggregator::ReadyRect() const {
+ PaintAggregator::ReadyRect rv;
+ rv.offset = offset;
+ rv.rect = rect;
+ rv.image_data = image_data;
+ return rv;
+ }
+ };
+ class Client {
+ public:
+ // Paints the given invalid area of the plugin to the given graphics
+ // device. Returns true if anything was painted.
+ //
+ // You are given the list of rects to paint in |paint_rects|. You can
+ // combine painting into less rectangles if it's more efficient. When a
+ // rect is painted, information about that paint should be inserted into
+ // |ready|. Otherwise if a paint needs more work, add the rect to
+ // |pending|. If |pending| is not empty, your OnPaint function will get
+ // called again. Once OnPaint is called and it returns no pending rects,
+ // all the previously ready rects will be flushed on screen. The exception
+ // is for ready rects that have |flush_now| set to true. These will be
+ // flushed right away.
+ //
+ // Do not call Flush() on the graphics device, this will be done
+ // automatically if you return true from this function since the
+ // PaintManager needs to handle the callback.
+ //
+ // Calling Invalidate/Scroll is not allowed while inside an OnPaint
+ virtual void OnPaint(const std::vector<pp::Rect>& paint_rects,
+ std::vector<ReadyRect>* ready,
+ std::vector<pp::Rect>* pending) = 0;
+ protected:
+ // You shouldn't be doing deleting through this interface.
+ virtual ~Client() {}
+ };
+
+ // The instance is the plugin instance using this paint manager to do its
+ // painting. Painting will automatically go to this instance and you don't
+ // have to manually bind any device context (this is all handled by the
+ // paint manager).
+ //
+ // The Client is a non-owning pointer and must remain valid (normally the
+ // object implementing the Client interface will own the paint manager).
+ //
+ // The is_always_opaque flag will be passed to the device contexts that this
+ // class creates. Set this to true if your plugin always draws an opaque
+ // image to the device. This is used as a hint to the browser that it does
+ // not need to do alpha blending, which speeds up painting. If you generate
+ // non-opqaue pixels or aren't sure, set this to false for more general
+ // blending.
+ //
+ // If you set is_always_opaque, your alpha channel should always be set to
+ // 0xFF or there may be painting artifacts. Being opaque will allow the
+ // browser to do a memcpy rather than a blend to paint the plugin, and this
+ // means your alpha values will get set on the page backing store. If these
+ // values are incorrect, it could mess up future blending. If you aren't
+ // sure, it is always correct to specify that it it not opaque.
+ //
+ // You will need to call SetSize before this class will do anything. Normally
+ // you do this from the ViewChanged method of your plugin instance.
+ PaintManager(pp::Instance* instance, Client* client, bool is_always_opaque);
+
+ ~PaintManager();
+
+ // Returns the size of the graphics context to allocate for a given plugin
+ // size. We may allocated a slightly larger buffer than required so that we
+ // don't have to resize the context when scrollbars appear/dissapear due to
+ // zooming (which can result in flickering).
+ static pp::Size GetNewContextSize(const pp::Size& current_context_size,
+ const pp::Size& plugin_size);
+
+ // You must call this function before using if you use the 0-arg constructor.
+ // See the constructor for what these arguments mean.
+ void Initialize(pp::Instance* instance, Client* client,
+ bool is_always_opaque);
+
+ // Sets the size of the plugin. If the size is the same as the previous call,
+ // this will be a NOP. If the size has changed, a new device will be
+ // allocated to the given size and a paint to that device will be scheduled.
+ //
+ // This is intended to be called from ViewChanged with the size of the
+ // plugin. Since it tracks the old size and only allocates when the size
+ // changes, you can always call this function without worrying about whether
+ // the size changed or ViewChanged is called for another reason (like the
+ // position changed).
+ void SetSize(const pp::Size& new_size, float new_device_scale);
+
+ // Invalidate the entire plugin.
+ void Invalidate();
+
+ // Invalidate the given rect.
+ void InvalidateRect(const pp::Rect& rect);
+
+ // The given rect should be scrolled by the given amounts.
+ void ScrollRect(const pp::Rect& clip_rect, const pp::Point& amount);
+
+ // Returns the size of the graphics context for the next paint operation.
+ // This is the pending size if a resize is pending (the plugin has called
+ // SetSize but we haven't actually painted it yet), or the current size of
+ // no resize is pending.
+ pp::Size GetEffectiveSize() const;
+ float GetEffectiveDeviceScale() const;
+
+ private:
+ // Disallow copy and assign (these are unimplemented).
+ PaintManager(const PaintManager&);
+ PaintManager& operator=(const PaintManager&);
+
+ // Makes sure there is a callback that will trigger a paint at a later time.
+ // This will be either a Flush callback telling us we're allowed to generate
+ // more data, or, if there's no flush callback pending, a manual call back
+ // to the message loop via ExecuteOnMainThread.
+ void EnsureCallbackPending();
+
+ // Does the client paint and executes a Flush if necessary.
+ void DoPaint();
+
+ // Callback for asynchronous completion of Flush.
+ void OnFlushComplete(int32_t);
+
+ // Callback for manual scheduling of paints when there is no flush callback
+ // pending.
+ void OnManualCallbackComplete(int32_t);
+
+ pp::Instance* instance_;
+
+ // Non-owning pointer. See the constructor.
+ Client* client_;
+
+ bool is_always_opaque_;
+
+ pp::CompletionCallbackFactory<PaintManager> callback_factory_;
+
+ // This graphics device will be is_null() if no graphics has been manually
+ // set yet.
+ pp::Graphics2D graphics_;
+
+ PaintAggregator aggregator_;
+
+ // See comment for EnsureCallbackPending for more on how these work.
+ bool manual_callback_pending_;
+ bool flush_pending_;
+
+ // When we get a resize, we don't bind right away (see SetSize). The
+ // has_pending_resize_ tells us that we need to do a resize for the next
+ // paint operation. When true, the new size is in pending_size_.
+ bool has_pending_resize_;
+ bool graphics_need_to_be_bound_;
+ pp::Size pending_size_;
+ pp::Size plugin_size_;
+ float pending_device_scale_;
+ float device_scale_;
+
+ // True iff we're in the middle of a paint.
+ bool in_paint_;
+
+ // True if we haven't painted the plugin viewport yet.
+ bool first_paint_;
+
+ // True when the view size just changed and we're waiting for a paint.
+ bool view_size_changed_waiting_for_paint_;
+};
+
+#endif // PDF_PAINT_MANAGER_H_
diff --git a/chromium/pdf/pdf.cc b/chromium/pdf/pdf.cc
new file mode 100644
index 00000000000..fa43eaeb3c7
--- /dev/null
+++ b/chromium/pdf/pdf.cc
@@ -0,0 +1,182 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "pdf/pdf.h"
+
+#include <stdint.h>
+
+#if defined(OS_WIN)
+#include <windows.h>
+#endif
+
+#include "base/command_line.h"
+#include "base/logging.h"
+#include "pdf/out_of_process_instance.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 {
+
+bool g_sdk_initialized_via_pepper = false;
+
+} // namespace
+
+PDFModule::PDFModule() {
+}
+
+PDFModule::~PDFModule() {
+ if (g_sdk_initialized_via_pepper) {
+ chrome_pdf::ShutdownSDK();
+ g_sdk_initialized_via_pepper = false;
+ }
+}
+
+bool PDFModule::Init() {
+ return true;
+}
+
+pp::Instance* PDFModule::CreateInstance(PP_Instance instance) {
+ if (!g_sdk_initialized_via_pepper) {
+ v8::StartupData natives;
+ v8::StartupData snapshot;
+ pp::PDF::GetV8ExternalSnapshotData(pp::InstanceHandle(instance),
+ &natives.data, &natives.raw_size,
+ &snapshot.data, &snapshot.raw_size);
+ if (natives.data) {
+ v8::V8::SetNativesDataBlob(&natives);
+ v8::V8::SetSnapshotDataBlob(&snapshot);
+ }
+ if (!chrome_pdf::InitializeSDK())
+ return NULL;
+ g_sdk_initialized_via_pepper = true;
+ }
+
+ return new OutOfProcessInstance(instance);
+}
+
+
+// Implementation of Global PPP functions ---------------------------------
+int32_t PPP_InitializeModule(PP_Module module_id,
+ PPB_GetInterface get_browser_interface) {
+ PDFModule* module = new PDFModule();
+ if (!module->InternalInit(module_id, get_browser_interface)) {
+ delete module;
+ return PP_ERROR_FAILED;
+ }
+
+ pp::InternalSetModuleSingleton(module);
+ return PP_OK;
+}
+
+void PPP_ShutdownModule() {
+ delete pp::Module::Get();
+ pp::InternalSetModuleSingleton(NULL);
+}
+
+const void* PPP_GetInterface(const char* interface_name) {
+ if (!pp::Module::Get())
+ return NULL;
+ return pp::Module::Get()->GetPluginInterface(interface_name);
+}
+
+#if defined(OS_WIN)
+bool RenderPDFPageToDC(const void* pdf_buffer,
+ int buffer_size,
+ int page_number,
+ HDC dc,
+ int dpi,
+ int bounds_origin_x,
+ int bounds_origin_y,
+ int bounds_width,
+ int bounds_height,
+ bool fit_to_bounds,
+ bool stretch_to_bounds,
+ bool keep_aspect_ratio,
+ bool center_in_bounds,
+ bool autorotate) {
+ if (!g_sdk_initialized_via_pepper) {
+ if (!chrome_pdf::InitializeSDK()) {
+ return false;
+ }
+ }
+ chrome_pdf::PDFEngineExports* engine_exports =
+ chrome_pdf::PDFEngineExports::Get();
+ chrome_pdf::PDFEngineExports::RenderingSettings settings(
+ dpi, dpi, pp::Rect(bounds_origin_x, bounds_origin_y, bounds_width,
+ bounds_height),
+ fit_to_bounds, stretch_to_bounds, keep_aspect_ratio, center_in_bounds,
+ autorotate);
+ bool ret = engine_exports->RenderPDFPageToDC(pdf_buffer, buffer_size,
+ page_number, settings, dc);
+ if (!g_sdk_initialized_via_pepper) {
+ chrome_pdf::ShutdownSDK();
+ }
+ return ret;
+}
+
+#endif // OS_WIN
+
+bool GetPDFDocInfo(const void* pdf_buffer,
+ int buffer_size, int* page_count,
+ double* max_page_width) {
+ if (!g_sdk_initialized_via_pepper) {
+ if (!chrome_pdf::InitializeSDK())
+ return false;
+ }
+ chrome_pdf::PDFEngineExports* engine_exports =
+ chrome_pdf::PDFEngineExports::Get();
+ bool ret = engine_exports->GetPDFDocInfo(
+ pdf_buffer, buffer_size, page_count, max_page_width);
+ if (!g_sdk_initialized_via_pepper) {
+ chrome_pdf::ShutdownSDK();
+ }
+ return ret;
+}
+
+bool GetPDFPageSizeByIndex(const void* pdf_buffer,
+ int pdf_buffer_size, int page_number,
+ double* width, double* height) {
+ if (!g_sdk_initialized_via_pepper) {
+ if (!chrome_pdf::InitializeSDK())
+ return false;
+ }
+ chrome_pdf::PDFEngineExports* engine_exports =
+ chrome_pdf::PDFEngineExports::Get();
+ bool ret = engine_exports->GetPDFPageSizeByIndex(
+ pdf_buffer, pdf_buffer_size, page_number, width, height);
+ if (!g_sdk_initialized_via_pepper)
+ chrome_pdf::ShutdownSDK();
+ return ret;
+}
+
+bool RenderPDFPageToBitmap(const void* pdf_buffer,
+ int pdf_buffer_size,
+ int page_number,
+ void* bitmap_buffer,
+ int bitmap_width,
+ int bitmap_height,
+ int dpi,
+ bool autorotate) {
+ if (!g_sdk_initialized_via_pepper) {
+ if (!chrome_pdf::InitializeSDK())
+ return false;
+ }
+ chrome_pdf::PDFEngineExports* engine_exports =
+ chrome_pdf::PDFEngineExports::Get();
+ chrome_pdf::PDFEngineExports::RenderingSettings settings(
+ dpi, dpi, pp::Rect(bitmap_width, bitmap_height), true, false, true, true,
+ autorotate);
+ bool ret = engine_exports->RenderPDFPageToBitmap(
+ pdf_buffer, pdf_buffer_size, page_number, settings, bitmap_buffer);
+ if (!g_sdk_initialized_via_pepper) {
+ chrome_pdf::ShutdownSDK();
+ }
+ return ret;
+}
+
+} // namespace chrome_pdf
diff --git a/chromium/pdf/pdf.h b/chromium/pdf/pdf.h
new file mode 100644
index 00000000000..342757f2462
--- /dev/null
+++ b/chromium/pdf/pdf.h
@@ -0,0 +1,113 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef PDF_PDF_H_
+#define PDF_PDF_H_
+
+#include "ppapi/c/ppb.h"
+#include "ppapi/cpp/module.h"
+
+namespace chrome_pdf {
+
+class PDFModule : public pp::Module {
+ public:
+ PDFModule();
+ ~PDFModule() override;
+
+ // pp::Module implementation.
+ bool Init() override;
+ pp::Instance* CreateInstance(PP_Instance instance) override;
+};
+
+int PPP_InitializeModule(PP_Module module_id,
+ PPB_GetInterface get_browser_interface);
+void PPP_ShutdownModule();
+const void* PPP_GetInterface(const char* interface_name);
+
+#if defined(OS_WIN)
+// |pdf_buffer| is the buffer that contains the entire PDF document to be
+// rendered.
+// |buffer_size| is the size of |pdf_buffer| in bytes.
+// |page_number| is the 0-based index of the page to be rendered.
+// |dc| is the device context to render into.
+// |dpi| and |dpi_y| is the resolution. If the value is -1, the dpi from the DC
+// will be used.
+// |bounds_origin_x|, |bounds_origin_y|, |bounds_width| and |bounds_height|
+// specify a bounds rectangle within the DC in which to render the PDF
+// page.
+// |fit_to_bounds| specifies whether the output should be shrunk to fit the
+// supplied bounds if the page size is larger than the bounds in any
+// dimension. If this is false, parts of the PDF page that lie outside
+// the bounds will be clipped.
+// |stretch_to_bounds| specifies whether the output should be stretched to fit
+// the supplied bounds if the page size is smaller than the bounds in any
+// dimension.
+// If both |fit_to_bounds| and |stretch_to_bounds| are true, then
+// |fit_to_bounds| is honored first.
+// |keep_aspect_ratio| If any scaling is to be done is true, this flag
+// specifies whether the original aspect ratio of the page should be
+// preserved while scaling.
+// |center_in_bounds| specifies whether the final image (after any scaling is
+// done) should be centered within the given bounds.
+// |autorotate| specifies whether the final image should be rotated to match
+// the output bound.
+// Returns false if the document or the page number are not valid.
+bool RenderPDFPageToDC(const void* pdf_buffer,
+ int buffer_size,
+ int page_number,
+ HDC dc,
+ int dpi,
+ int bounds_origin_x,
+ int bounds_origin_y,
+ int bounds_width,
+ int bounds_height,
+ bool fit_to_bounds,
+ bool stretch_to_bounds,
+ bool keep_aspect_ratio,
+ bool center_in_bounds,
+ bool autorotate);
+#endif
+// |page_count| and |max_page_width| are optional and can be NULL.
+// Returns false if the document is not valid.
+bool GetPDFDocInfo(const void* pdf_buffer,
+ int buffer_size, int* page_count,
+ double* max_page_width);
+
+// Gets the dimensions of a specific page in a document.
+// |pdf_buffer| is the buffer that contains the entire PDF document to be
+// rendered.
+// |pdf_buffer_size| is the size of |pdf_buffer| in bytes.
+// |page_number| is the page number that the function will get the dimensions
+// of.
+// |width| is the output for the width of the page in points.
+// |height| is the output for the height of the page in points.
+// Returns false if the document or the page number are not valid.
+bool GetPDFPageSizeByIndex(const void* pdf_buffer,
+ int pdf_buffer_size, int page_number,
+ double* width, double* height);
+
+// Renders PDF page into 4-byte per pixel BGRA color bitmap.
+// |pdf_buffer| is the buffer that contains the entire PDF document to be
+// rendered.
+// |pdf_buffer_size| is the size of |pdf_buffer| in bytes.
+// |page_number| is the 0-based index of the page to be rendered.
+// |bitmap_buffer| is the output buffer for bitmap.
+// |bitmap_width| is the width of the output bitmap.
+// |bitmap_height| is the height of the output bitmap.
+// |dpi| is the resolutions.
+// |autorotate| specifies whether the final image should be rotated to match
+// the output bound.
+// Returns false if the document or the page number are not valid.
+bool RenderPDFPageToBitmap(const void* pdf_buffer,
+ int pdf_buffer_size,
+ int page_number,
+ void* bitmap_buffer,
+ int bitmap_width,
+ int bitmap_height,
+ int dpi,
+ bool autorotate);
+
+} // namespace chrome_pdf
+
+#endif // PDF_PDF_H_
diff --git a/chromium/pdf/pdf_engine.h b/chromium/pdf/pdf_engine.h
new file mode 100644
index 00000000000..c5d33c87066
--- /dev/null
+++ b/chromium/pdf/pdf_engine.h
@@ -0,0 +1,345 @@
+// 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_PDF_ENGINE_H_
+#define PDF_PDF_ENGINE_H_
+
+#include <stdint.h>
+
+#include "build/build_config.h"
+
+#if defined(OS_WIN)
+#include <windows.h>
+#endif
+
+#include <string>
+#include <vector>
+
+#include "base/strings/string16.h"
+
+#include "ppapi/c/dev/pp_cursor_type_dev.h"
+#include "ppapi/c/dev/ppp_printing_dev.h"
+#include "ppapi/c/ppb_input_event.h"
+#include "ppapi/cpp/completion_callback.h"
+#include "ppapi/cpp/image_data.h"
+#include "ppapi/cpp/rect.h"
+#include "ppapi/cpp/size.h"
+#include "ppapi/cpp/url_loader.h"
+#include "ppapi/cpp/var_array.h"
+
+namespace pp {
+class InputEvent;
+class VarDictionary;
+}
+
+namespace chrome_pdf {
+
+class Stream;
+
+#if defined(OS_MACOSX)
+const uint32_t kDefaultKeyModifier = PP_INPUTEVENT_MODIFIER_METAKEY;
+#else // !OS_MACOSX
+const uint32_t kDefaultKeyModifier = PP_INPUTEVENT_MODIFIER_CONTROLKEY;
+#endif // OS_MACOSX
+
+// Do one time initialization of the SDK.
+bool InitializeSDK();
+// Tells the SDK that we're shutting down.
+void ShutdownSDK();
+
+// This class encapsulates a PDF rendering engine.
+class PDFEngine {
+ public:
+ enum DocumentPermission {
+ PERMISSION_COPY,
+ PERMISSION_COPY_ACCESSIBLE,
+ PERMISSION_PRINT_LOW_QUALITY,
+ PERMISSION_PRINT_HIGH_QUALITY,
+ };
+
+ // The interface that's provided to the rendering engine.
+ class Client {
+ public:
+ virtual ~Client() {}
+
+ // Informs the client about the document's size in pixels.
+ virtual void DocumentSizeUpdated(const pp::Size& size) = 0;
+
+ // Informs the client that the given rect needs to be repainted.
+ virtual void Invalidate(const pp::Rect& rect) = 0;
+
+ // Informs the client to scroll the plugin area by the given offset.
+ virtual void Scroll(const pp::Point& point) = 0;
+
+ // Scroll the horizontal/vertical scrollbars to a given position.
+ virtual void ScrollToX(int position) = 0;
+ virtual void ScrollToY(int position) = 0;
+
+ // Scroll to the specified page.
+ virtual void ScrollToPage(int page) = 0;
+
+ // Navigate to the given url.
+ virtual void NavigateTo(const std::string& url, bool open_in_new_tab) = 0;
+
+ // Updates the cursor.
+ virtual void UpdateCursor(PP_CursorType_Dev cursor) = 0;
+
+ // Updates the tick marks in the vertical scrollbar.
+ virtual void UpdateTickMarks(const std::vector<pp::Rect>& tickmarks) = 0;
+
+ // Updates the number of find results for the current search term. If
+ // there are no matches 0 should be passed in. Only when the plugin has
+ // finished searching should it pass in the final count with final_result
+ // set to true.
+ virtual void NotifyNumberOfFindResultsChanged(int total,
+ bool final_result) = 0;
+
+ // Updates the index of the currently selected search item.
+ virtual void NotifySelectedFindResultChanged(int current_find_index) = 0;
+
+ // Prompts the user for a password to open this document. The callback is
+ // called when the password is retrieved.
+ virtual void GetDocumentPassword(
+ pp::CompletionCallbackWithOutput<pp::Var> callback) = 0;
+
+ // Puts up an alert with the given message.
+ virtual void Alert(const std::string& message) = 0;
+
+ // Puts up a confirm with the given message, and returns true if the user
+ // presses OK, or false if they press cancel.
+ virtual bool Confirm(const std::string& message) = 0;
+
+ // Puts up a prompt with the given message and default answer and returns
+ // the answer.
+ virtual std::string Prompt(const std::string& question,
+ const std::string& default_answer) = 0;
+
+ // Returns the url of the pdf.
+ virtual std::string GetURL() = 0;
+
+ // Send an email.
+ virtual void Email(const std::string& to,
+ const std::string& cc,
+ const std::string& bcc,
+ const std::string& subject,
+ const std::string& body) = 0;
+
+ // Put up the print dialog.
+ virtual void Print() = 0;
+
+ // Submit the data using HTTP POST.
+ virtual void SubmitForm(const std::string& url,
+ const void* data,
+ int length) = 0;
+
+ // Pops up a file selection dialog and returns the result.
+ virtual std::string ShowFileSelectionDialog() = 0;
+
+ // Creates and returns new URL loader for partial document requests.
+ virtual pp::URLLoader CreateURLLoader() = 0;
+
+ // Calls the client's OnCallback() function in delay_in_ms with the given
+ // id.
+ virtual void ScheduleCallback(int id, int delay_in_ms) = 0;
+
+ // Searches the given string for "term" and returns the results. Unicode-
+ // aware.
+ struct SearchStringResult {
+ int start_index;
+ int length;
+ };
+ virtual void SearchString(const base::char16* string,
+ const base::char16* term,
+ bool case_sensitive,
+ std::vector<SearchStringResult>* results) = 0;
+
+ // Notifies the client that the engine has painted a page from the document.
+ virtual void DocumentPaintOccurred() = 0;
+
+ // Notifies the client that the document has finished loading.
+ virtual void DocumentLoadComplete(int page_count) = 0;
+
+ // Notifies the client that the document has failed to load.
+ virtual void DocumentLoadFailed() = 0;
+
+ virtual pp::Instance* GetPluginInstance() = 0;
+
+ // Notifies that an unsupported feature in the PDF was encountered.
+ virtual void DocumentHasUnsupportedFeature(const std::string& feature) = 0;
+
+ // Notifies the client about document load progress.
+ virtual void DocumentLoadProgress(uint32_t available,
+ uint32_t doc_size) = 0;
+
+ // Notifies the client about focus changes for form text fields.
+ virtual void FormTextFieldFocusChange(bool in_focus) = 0;
+
+ // Returns true if the plugin has been opened within print preview.
+ virtual bool IsPrintPreview() = 0;
+
+ // Get the background color of the PDF.
+ virtual uint32_t GetBackgroundColor() = 0;
+
+ // Sets selection status.
+ virtual void IsSelectingChanged(bool is_selecting) {}
+ };
+
+ // Factory method to create an instance of the PDF Engine.
+ static PDFEngine* Create(Client* client);
+
+ virtual ~PDFEngine() {}
+
+ // Most of these functions are similar to the Pepper functions of the same
+ // name, so not repeating the description here unless it's different.
+ virtual bool New(const char* url, const char* headers) = 0;
+ virtual void PageOffsetUpdated(const pp::Point& page_offset) = 0;
+ virtual void PluginSizeUpdated(const pp::Size& size) = 0;
+ virtual void ScrolledToXPosition(int position) = 0;
+ virtual void ScrolledToYPosition(int position) = 0;
+ // Paint is called a series of times. Before these n calls are made, PrePaint
+ // is called once. After Paint is called n times, PostPaint is called once.
+ virtual void PrePaint() = 0;
+ virtual void Paint(const pp::Rect& rect,
+ pp::ImageData* image_data,
+ std::vector<pp::Rect>* ready,
+ std::vector<pp::Rect>* pending) = 0;
+ virtual void PostPaint() = 0;
+ virtual bool HandleDocumentLoad(const pp::URLLoader& loader) = 0;
+ virtual bool HandleEvent(const pp::InputEvent& event) = 0;
+ virtual uint32_t QuerySupportedPrintOutputFormats() = 0;
+ virtual void PrintBegin() = 0;
+ virtual pp::Resource PrintPages(
+ const PP_PrintPageNumberRange_Dev* page_ranges,
+ uint32_t page_range_count,
+ const PP_PrintSettings_Dev& print_settings) = 0;
+ virtual void PrintEnd() = 0;
+ virtual void StartFind(const std::string& text, bool case_sensitive) = 0;
+ virtual bool SelectFindResult(bool forward) = 0;
+ virtual void StopFind() = 0;
+ virtual void ZoomUpdated(double new_zoom_level) = 0;
+ virtual void RotateClockwise() = 0;
+ virtual void RotateCounterclockwise() = 0;
+ virtual std::string GetSelectedText() = 0;
+ virtual std::string GetLinkAtPosition(const pp::Point& point) = 0;
+ // Checks the permissions associated with this document.
+ virtual bool HasPermission(DocumentPermission permission) const = 0;
+ virtual void SelectAll() = 0;
+ // Gets the number of pages in the document.
+ virtual int GetNumberOfPages() = 0;
+ // Gets the 0-based page number of |destination|, or -1 if it does not exist.
+ virtual int GetNamedDestinationPage(const std::string& destination) = 0;
+ // Gets the index of the most visible page, or -1 if none are visible.
+ virtual int GetMostVisiblePage() = 0;
+ // Gets the rectangle of the page including shadow.
+ virtual pp::Rect GetPageRect(int index) = 0;
+ // Gets the rectangle of the page excluding any additional areas.
+ virtual pp::Rect GetPageContentsRect(int index) = 0;
+ // Returns a page's rect in screen coordinates, as well as its surrounding
+ // border areas and bottom separator.
+ virtual pp::Rect GetPageScreenRect(int page_index) const = 0;
+ // Gets the offset of the vertical scrollbar from the top in document
+ // coordinates.
+ virtual int GetVerticalScrollbarYPosition() = 0;
+ // Set color / grayscale rendering modes.
+ virtual void SetGrayscale(bool grayscale) = 0;
+ // Callback for timer that's set with ScheduleCallback().
+ virtual void OnCallback(int id) = 0;
+ // Gets the JSON representation of the PDF file
+ virtual std::string GetPageAsJSON(int index) = 0;
+ // Gets the PDF document's print scaling preference. True if the document can
+ // be scaled to fit.
+ virtual bool GetPrintScaling() = 0;
+ // Returns number of copies to be printed.
+ virtual int GetCopiesToPrint() = 0;
+ // Returns the duplex setting.
+ virtual int GetDuplexType() = 0;
+ // Returns true if all the pages are the same size.
+ virtual bool GetPageSizeAndUniformity(pp::Size* size) = 0;
+
+ // Returns a VarArray of Bookmarks, each a VarDictionary containing the
+ // following key/values:
+ // - "title" - a string Var.
+ // - "page" - an int Var.
+ // - "children" - a VarArray(), with each entry containing a VarDictionary of
+ // the same structure.
+ virtual pp::VarArray GetBookmarks() = 0;
+
+ // Append blank pages to make a 1-page document to a |num_pages| document.
+ // Always retain the first page data.
+ virtual void AppendBlankPages(int num_pages) = 0;
+ // Append the first page of the document loaded with the |engine| to this
+ // document at page |index|.
+ virtual void AppendPage(PDFEngine* engine, int index) = 0;
+
+ // Allow client to query and reset scroll positions in document coordinates.
+ // Note that this is meant for cases where the device scale factor changes,
+ // and not for general scrolling - the engine will not repaint due to this.
+ virtual pp::Point GetScrollPosition() = 0;
+ virtual void SetScrollPosition(const pp::Point& position) = 0;
+
+ virtual bool IsProgressiveLoad() = 0;
+
+ virtual std::string GetMetadata(const std::string& key) = 0;
+};
+
+// Interface for exports that wrap the PDF engine.
+class PDFEngineExports {
+ public:
+ struct RenderingSettings {
+ RenderingSettings(int dpi_x,
+ int dpi_y,
+ const pp::Rect& bounds,
+ bool fit_to_bounds,
+ bool stretch_to_bounds,
+ bool keep_aspect_ratio,
+ bool center_in_bounds,
+ bool autorotate)
+ : dpi_x(dpi_x), dpi_y(dpi_y), bounds(bounds),
+ fit_to_bounds(fit_to_bounds), stretch_to_bounds(stretch_to_bounds),
+ keep_aspect_ratio(keep_aspect_ratio),
+ center_in_bounds(center_in_bounds), autorotate(autorotate) {
+ }
+ int dpi_x;
+ int dpi_y;
+ pp::Rect bounds;
+ bool fit_to_bounds;
+ bool stretch_to_bounds;
+ bool keep_aspect_ratio;
+ bool center_in_bounds;
+ bool autorotate;
+ };
+
+ PDFEngineExports() {}
+ virtual ~PDFEngineExports() {}
+ static PDFEngineExports* Get();
+
+#if defined(OS_WIN)
+ // See the definition of RenderPDFPageToDC in pdf.cc for details.
+ virtual bool RenderPDFPageToDC(const void* pdf_buffer,
+ int buffer_size,
+ int page_number,
+ const RenderingSettings& settings,
+ HDC dc) = 0;
+#endif // OS_WIN
+ // See the definition of RenderPDFPageToBitmap in pdf.cc for details.
+ virtual bool RenderPDFPageToBitmap(const void* pdf_buffer,
+ int pdf_buffer_size,
+ int page_number,
+ const RenderingSettings& settings,
+ void* bitmap_buffer) = 0;
+
+ virtual bool GetPDFDocInfo(const void* pdf_buffer,
+ int buffer_size,
+ int* page_count,
+ double* max_page_width) = 0;
+
+ // See the definition of GetPDFPageSizeByIndex in pdf.cc for details.
+ virtual bool GetPDFPageSizeByIndex(const void* pdf_buffer,
+ int pdf_buffer_size, int page_number,
+ double* width, double* height) = 0;
+};
+
+} // namespace chrome_pdf
+
+#endif // PDF_PDF_ENGINE_H_
diff --git a/chromium/pdf/pdfium/pdfium_api_string_buffer_adapter.cc b/chromium/pdf/pdfium/pdfium_api_string_buffer_adapter.cc
new file mode 100644
index 00000000000..e4e953aed94
--- /dev/null
+++ b/chromium/pdf/pdfium/pdfium_api_string_buffer_adapter.cc
@@ -0,0 +1,88 @@
+// Copyright 2015 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "pdf/pdfium/pdfium_api_string_buffer_adapter.h"
+
+#include <stddef.h>
+
+#include <string>
+
+#include "base/logging.h"
+#include "base/strings/string16.h"
+#include "base/strings/string_util.h"
+
+namespace chrome_pdf {
+
+template <class StringType>
+PDFiumAPIStringBufferAdapter<StringType>::PDFiumAPIStringBufferAdapter(
+ StringType* str,
+ size_t expected_size,
+ bool check_expected_size)
+ : str_(str),
+ data_(base::WriteInto(str, expected_size + 1)),
+ expected_size_(expected_size),
+ check_expected_size_(check_expected_size),
+ is_closed_(false) {
+}
+
+template <class StringType>
+PDFiumAPIStringBufferAdapter<StringType>::~PDFiumAPIStringBufferAdapter() {
+ DCHECK(is_closed_);
+}
+
+template <class StringType>
+void* PDFiumAPIStringBufferAdapter<StringType>::GetData() {
+ DCHECK(!is_closed_);
+ return data_;
+}
+
+template <class StringType>
+void PDFiumAPIStringBufferAdapter<StringType>::Close(size_t actual_size) {
+ DCHECK(!is_closed_);
+ is_closed_ = true;
+
+ if (check_expected_size_)
+ DCHECK_EQ(expected_size_, actual_size);
+
+ if (actual_size > 0) {
+ DCHECK((*str_)[actual_size - 1] == 0);
+ str_->resize(actual_size - 1);
+ } else {
+ str_->clear();
+ }
+}
+
+template <class StringType>
+PDFiumAPIStringBufferSizeInBytesAdapter<StringType>::
+ PDFiumAPIStringBufferSizeInBytesAdapter(StringType* str,
+ size_t expected_size,
+ bool check_expected_size)
+ : adapter_(str,
+ expected_size / sizeof(typename StringType::value_type),
+ check_expected_size) {
+ DCHECK(expected_size % sizeof(typename StringType::value_type) == 0);
+}
+
+template <class StringType>
+PDFiumAPIStringBufferSizeInBytesAdapter<
+ StringType>::~PDFiumAPIStringBufferSizeInBytesAdapter() = default;
+
+template <class StringType>
+void* PDFiumAPIStringBufferSizeInBytesAdapter<StringType>::GetData() {
+ return adapter_.GetData();
+}
+
+template <class StringType>
+void PDFiumAPIStringBufferSizeInBytesAdapter<StringType>::Close(
+ size_t actual_size) {
+ DCHECK(actual_size % sizeof(typename StringType::value_type) == 0);
+ adapter_.Close(actual_size / sizeof(typename StringType::value_type));
+}
+
+// explicit instantiations
+template class PDFiumAPIStringBufferAdapter<std::string>;
+template class PDFiumAPIStringBufferAdapter<base::string16>;
+template class PDFiumAPIStringBufferSizeInBytesAdapter<base::string16>;
+
+} // namespace chrome_pdf
diff --git a/chromium/pdf/pdfium/pdfium_api_string_buffer_adapter.h b/chromium/pdf/pdfium/pdfium_api_string_buffer_adapter.h
new file mode 100644
index 00000000000..7b45cbe36a8
--- /dev/null
+++ b/chromium/pdf/pdfium/pdfium_api_string_buffer_adapter.h
@@ -0,0 +1,101 @@
+// Copyright 2015 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_PDFIUM_PDFIUM_API_STRING_BUFFER_ADAPTER_H_
+#define PDF_PDFIUM_PDFIUM_API_STRING_BUFFER_ADAPTER_H_
+
+#include <stddef.h>
+
+#include "base/macros.h"
+#include "base/numerics/safe_math.h"
+
+namespace chrome_pdf {
+
+// Helper to deal with the fact that many PDFium APIs write the null-terminator
+// into string buffers that are passed to them, but the PDF plugin likes to pass
+// in std::strings / base::string16s, where one should not count on the internal
+// string buffers to be null-terminated.
+
+template <class StringType>
+class PDFiumAPIStringBufferAdapter {
+ public:
+ // |str| is the string to write into.
+ // |expected_size| is the number of characters the PDFium API will write,
+ // including the null-terminator. It should be at least 1.
+ // |check_expected_size| whether to check the actual number of characters
+ // written into |str| against |expected_size| when calling Close().
+ PDFiumAPIStringBufferAdapter(StringType* str,
+ size_t expected_size,
+ bool check_expected_size);
+ ~PDFiumAPIStringBufferAdapter();
+
+ // Returns a pointer to |str_|'s buffer. The buffer's size is large enough to
+ // hold |expected_size_| + 1 characters, so the PDFium API that uses the
+ // pointer has space to write a null-terminator.
+ void* GetData();
+
+ // Resizes |str_| to |actual_size| - 1 characters, thereby removing the extra
+ // null-terminator. This must be called prior to the adapter's destruction.
+ // The pointer returned by GetData() should be considered invalid.
+ void Close(size_t actual_size);
+
+ template <typename IntType>
+ void Close(IntType actual_size) {
+ base::CheckedNumeric<size_t> unsigned_size = actual_size;
+ Close(unsigned_size.ValueOrDie());
+ }
+
+ private:
+ StringType* const str_;
+ void* const data_;
+ const size_t expected_size_;
+ const bool check_expected_size_;
+ bool is_closed_;
+
+ DISALLOW_COPY_AND_ASSIGN(PDFiumAPIStringBufferAdapter);
+};
+
+// Helper to deal with the fact that many PDFium APIs write the null-terminator
+// into string buffers that are passed to them, but the PDF plugin likes to pass
+// in std::strings / base::string16s, where one should not count on the internal
+// string buffers to be null-terminated. This version is suitable for APIs that
+// work in terms of number of bytes instead of the number of characters.
+template <class StringType>
+class PDFiumAPIStringBufferSizeInBytesAdapter {
+ public:
+ // |str| is the string to write into.
+ // |expected_size| is the number of bytes the PDFium API will write,
+ // including the null-terminator. It should be at least the size of a
+ // character in bytes.
+ // |check_expected_size| whether to check the actual number of bytes
+ // written into |str| against |expected_size| when calling Close().
+ PDFiumAPIStringBufferSizeInBytesAdapter(StringType* str,
+ size_t expected_size,
+ bool check_expected_size);
+ ~PDFiumAPIStringBufferSizeInBytesAdapter();
+
+ // Returns a pointer to |str_|'s buffer. The buffer's size is large enough to
+ // hold |expected_size_| + sizeof(StringType::value_type) bytes, so the PDFium
+ // API that uses the pointer has space to write a null-terminator.
+ void* GetData();
+
+ // Resizes |str_| to |actual_size| - sizeof(StringType::value_type) bytes,
+ // thereby removing the extra null-terminator. This must be called prior to
+ // the adapter's destruction. The pointer returned by GetData() should be
+ // considered invalid.
+ void Close(size_t actual_size);
+
+ template <typename IntType>
+ void Close(IntType actual_size) {
+ base::CheckedNumeric<size_t> unsigned_size = actual_size;
+ Close(unsigned_size.ValueOrDie());
+ }
+
+ private:
+ PDFiumAPIStringBufferAdapter<StringType> adapter_;
+};
+
+} // namespace chrome_pdf
+
+#endif // PDF_PDFIUM_PDFIUM_API_STRING_BUFFER_ADAPTER_H_
diff --git a/chromium/pdf/pdfium/pdfium_assert_matching_enums.cc b/chromium/pdf/pdfium/pdfium_assert_matching_enums.cc
new file mode 100644
index 00000000000..2dcba5418ef
--- /dev/null
+++ b/chromium/pdf/pdfium/pdfium_assert_matching_enums.cc
@@ -0,0 +1,213 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "ppapi/c/pp_input_event.h"
+#include "ppapi/c/private/ppb_pdf.h"
+#include "ppapi/c/private/ppp_pdf.h"
+#include "third_party/pdfium/public/fpdf_fwlevent.h"
+#include "third_party/pdfium/public/fpdf_sysfontinfo.h"
+#include "ui/events/keycodes/keyboard_codes.h"
+
+#define STATIC_ASSERT_MATCH(np_name, pdfium_name) \
+ static_assert(int(np_name) == int(pdfium_name), \
+ "mismatching enums: " #np_name)
+
+STATIC_ASSERT_MATCH(PP_INPUTEVENT_MODIFIER_SHIFTKEY, FWL_EVENTFLAG_ShiftKey);
+STATIC_ASSERT_MATCH(PP_INPUTEVENT_MODIFIER_CONTROLKEY,
+ FWL_EVENTFLAG_ControlKey);
+STATIC_ASSERT_MATCH(PP_INPUTEVENT_MODIFIER_ALTKEY, FWL_EVENTFLAG_AltKey);
+STATIC_ASSERT_MATCH(PP_INPUTEVENT_MODIFIER_METAKEY, FWL_EVENTFLAG_MetaKey);
+STATIC_ASSERT_MATCH(PP_INPUTEVENT_MODIFIER_ISKEYPAD, FWL_EVENTFLAG_KeyPad);
+STATIC_ASSERT_MATCH(PP_INPUTEVENT_MODIFIER_ISAUTOREPEAT,
+ FWL_EVENTFLAG_AutoRepeat);
+STATIC_ASSERT_MATCH(PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN,
+ FWL_EVENTFLAG_LeftButtonDown);
+STATIC_ASSERT_MATCH(PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN,
+ FWL_EVENTFLAG_MiddleButtonDown);
+STATIC_ASSERT_MATCH(PP_INPUTEVENT_MODIFIER_RIGHTBUTTONDOWN,
+ FWL_EVENTFLAG_RightButtonDown);
+
+STATIC_ASSERT_MATCH(ui::VKEY_BACK, FWL_VKEY_Back);
+STATIC_ASSERT_MATCH(ui::VKEY_TAB, FWL_VKEY_Tab);
+STATIC_ASSERT_MATCH(ui::VKEY_CLEAR, FWL_VKEY_Clear);
+STATIC_ASSERT_MATCH(ui::VKEY_RETURN, FWL_VKEY_Return);
+STATIC_ASSERT_MATCH(ui::VKEY_SHIFT, FWL_VKEY_Shift);
+STATIC_ASSERT_MATCH(ui::VKEY_CONTROL, FWL_VKEY_Control);
+STATIC_ASSERT_MATCH(ui::VKEY_MENU, FWL_VKEY_Menu);
+STATIC_ASSERT_MATCH(ui::VKEY_PAUSE, FWL_VKEY_Pause);
+STATIC_ASSERT_MATCH(ui::VKEY_CAPITAL, FWL_VKEY_Capital);
+STATIC_ASSERT_MATCH(ui::VKEY_KANA, FWL_VKEY_Kana);
+STATIC_ASSERT_MATCH(ui::VKEY_HANGUL, FWL_VKEY_Hangul);
+STATIC_ASSERT_MATCH(ui::VKEY_JUNJA, FWL_VKEY_Junja);
+STATIC_ASSERT_MATCH(ui::VKEY_FINAL, FWL_VKEY_Final);
+STATIC_ASSERT_MATCH(ui::VKEY_HANJA, FWL_VKEY_Hanja);
+STATIC_ASSERT_MATCH(ui::VKEY_KANJI, FWL_VKEY_Kanji);
+STATIC_ASSERT_MATCH(ui::VKEY_ESCAPE, FWL_VKEY_Escape);
+STATIC_ASSERT_MATCH(ui::VKEY_CONVERT, FWL_VKEY_Convert);
+STATIC_ASSERT_MATCH(ui::VKEY_NONCONVERT, FWL_VKEY_NonConvert);
+STATIC_ASSERT_MATCH(ui::VKEY_ACCEPT, FWL_VKEY_Accept);
+STATIC_ASSERT_MATCH(ui::VKEY_MODECHANGE, FWL_VKEY_ModeChange);
+STATIC_ASSERT_MATCH(ui::VKEY_SPACE, FWL_VKEY_Space);
+STATIC_ASSERT_MATCH(ui::VKEY_PRIOR, FWL_VKEY_Prior);
+STATIC_ASSERT_MATCH(ui::VKEY_NEXT, FWL_VKEY_Next);
+STATIC_ASSERT_MATCH(ui::VKEY_END, FWL_VKEY_End);
+STATIC_ASSERT_MATCH(ui::VKEY_HOME, FWL_VKEY_Home);
+STATIC_ASSERT_MATCH(ui::VKEY_LEFT, FWL_VKEY_Left);
+STATIC_ASSERT_MATCH(ui::VKEY_UP, FWL_VKEY_Up);
+STATIC_ASSERT_MATCH(ui::VKEY_RIGHT, FWL_VKEY_Right);
+STATIC_ASSERT_MATCH(ui::VKEY_DOWN, FWL_VKEY_Down);
+STATIC_ASSERT_MATCH(ui::VKEY_SELECT, FWL_VKEY_Select);
+STATIC_ASSERT_MATCH(ui::VKEY_PRINT, FWL_VKEY_Print);
+STATIC_ASSERT_MATCH(ui::VKEY_EXECUTE, FWL_VKEY_Execute);
+STATIC_ASSERT_MATCH(ui::VKEY_SNAPSHOT, FWL_VKEY_Snapshot);
+STATIC_ASSERT_MATCH(ui::VKEY_INSERT, FWL_VKEY_Insert);
+STATIC_ASSERT_MATCH(ui::VKEY_DELETE, FWL_VKEY_Delete);
+STATIC_ASSERT_MATCH(ui::VKEY_HELP, FWL_VKEY_Help);
+STATIC_ASSERT_MATCH(ui::VKEY_0, FWL_VKEY_0);
+STATIC_ASSERT_MATCH(ui::VKEY_1, FWL_VKEY_1);
+STATIC_ASSERT_MATCH(ui::VKEY_2, FWL_VKEY_2);
+STATIC_ASSERT_MATCH(ui::VKEY_3, FWL_VKEY_3);
+STATIC_ASSERT_MATCH(ui::VKEY_4, FWL_VKEY_4);
+STATIC_ASSERT_MATCH(ui::VKEY_5, FWL_VKEY_5);
+STATIC_ASSERT_MATCH(ui::VKEY_6, FWL_VKEY_6);
+STATIC_ASSERT_MATCH(ui::VKEY_7, FWL_VKEY_7);
+STATIC_ASSERT_MATCH(ui::VKEY_8, FWL_VKEY_8);
+STATIC_ASSERT_MATCH(ui::VKEY_9, FWL_VKEY_9);
+STATIC_ASSERT_MATCH(ui::VKEY_A, FWL_VKEY_A);
+STATIC_ASSERT_MATCH(ui::VKEY_B, FWL_VKEY_B);
+STATIC_ASSERT_MATCH(ui::VKEY_C, FWL_VKEY_C);
+STATIC_ASSERT_MATCH(ui::VKEY_D, FWL_VKEY_D);
+STATIC_ASSERT_MATCH(ui::VKEY_E, FWL_VKEY_E);
+STATIC_ASSERT_MATCH(ui::VKEY_F, FWL_VKEY_F);
+STATIC_ASSERT_MATCH(ui::VKEY_G, FWL_VKEY_G);
+STATIC_ASSERT_MATCH(ui::VKEY_H, FWL_VKEY_H);
+STATIC_ASSERT_MATCH(ui::VKEY_I, FWL_VKEY_I);
+STATIC_ASSERT_MATCH(ui::VKEY_J, FWL_VKEY_J);
+STATIC_ASSERT_MATCH(ui::VKEY_K, FWL_VKEY_K);
+STATIC_ASSERT_MATCH(ui::VKEY_L, FWL_VKEY_L);
+STATIC_ASSERT_MATCH(ui::VKEY_M, FWL_VKEY_M);
+STATIC_ASSERT_MATCH(ui::VKEY_N, FWL_VKEY_N);
+STATIC_ASSERT_MATCH(ui::VKEY_O, FWL_VKEY_O);
+STATIC_ASSERT_MATCH(ui::VKEY_P, FWL_VKEY_P);
+STATIC_ASSERT_MATCH(ui::VKEY_Q, FWL_VKEY_Q);
+STATIC_ASSERT_MATCH(ui::VKEY_R, FWL_VKEY_R);
+STATIC_ASSERT_MATCH(ui::VKEY_S, FWL_VKEY_S);
+STATIC_ASSERT_MATCH(ui::VKEY_T, FWL_VKEY_T);
+STATIC_ASSERT_MATCH(ui::VKEY_U, FWL_VKEY_U);
+STATIC_ASSERT_MATCH(ui::VKEY_V, FWL_VKEY_V);
+STATIC_ASSERT_MATCH(ui::VKEY_W, FWL_VKEY_W);
+STATIC_ASSERT_MATCH(ui::VKEY_X, FWL_VKEY_X);
+STATIC_ASSERT_MATCH(ui::VKEY_Y, FWL_VKEY_Y);
+STATIC_ASSERT_MATCH(ui::VKEY_Z, FWL_VKEY_Z);
+STATIC_ASSERT_MATCH(ui::VKEY_LWIN, FWL_VKEY_LWin);
+STATIC_ASSERT_MATCH(ui::VKEY_COMMAND, FWL_VKEY_Command);
+STATIC_ASSERT_MATCH(ui::VKEY_RWIN, FWL_VKEY_RWin);
+STATIC_ASSERT_MATCH(ui::VKEY_APPS, FWL_VKEY_Apps);
+STATIC_ASSERT_MATCH(ui::VKEY_SLEEP, FWL_VKEY_Sleep);
+STATIC_ASSERT_MATCH(ui::VKEY_NUMPAD0, FWL_VKEY_NumPad0);
+STATIC_ASSERT_MATCH(ui::VKEY_NUMPAD1, FWL_VKEY_NumPad1);
+STATIC_ASSERT_MATCH(ui::VKEY_NUMPAD2, FWL_VKEY_NumPad2);
+STATIC_ASSERT_MATCH(ui::VKEY_NUMPAD3, FWL_VKEY_NumPad3);
+STATIC_ASSERT_MATCH(ui::VKEY_NUMPAD4, FWL_VKEY_NumPad4);
+STATIC_ASSERT_MATCH(ui::VKEY_NUMPAD5, FWL_VKEY_NumPad5);
+STATIC_ASSERT_MATCH(ui::VKEY_NUMPAD6, FWL_VKEY_NumPad6);
+STATIC_ASSERT_MATCH(ui::VKEY_NUMPAD7, FWL_VKEY_NumPad7);
+STATIC_ASSERT_MATCH(ui::VKEY_NUMPAD8, FWL_VKEY_NumPad8);
+STATIC_ASSERT_MATCH(ui::VKEY_NUMPAD9, FWL_VKEY_NumPad9);
+STATIC_ASSERT_MATCH(ui::VKEY_MULTIPLY, FWL_VKEY_Multiply);
+STATIC_ASSERT_MATCH(ui::VKEY_ADD, FWL_VKEY_Add);
+STATIC_ASSERT_MATCH(ui::VKEY_SEPARATOR, FWL_VKEY_Separator);
+STATIC_ASSERT_MATCH(ui::VKEY_SUBTRACT, FWL_VKEY_Subtract);
+STATIC_ASSERT_MATCH(ui::VKEY_DECIMAL, FWL_VKEY_Decimal);
+STATIC_ASSERT_MATCH(ui::VKEY_DIVIDE, FWL_VKEY_Divide);
+STATIC_ASSERT_MATCH(ui::VKEY_F1, FWL_VKEY_F1);
+STATIC_ASSERT_MATCH(ui::VKEY_F2, FWL_VKEY_F2);
+STATIC_ASSERT_MATCH(ui::VKEY_F3, FWL_VKEY_F3);
+STATIC_ASSERT_MATCH(ui::VKEY_F4, FWL_VKEY_F4);
+STATIC_ASSERT_MATCH(ui::VKEY_F5, FWL_VKEY_F5);
+STATIC_ASSERT_MATCH(ui::VKEY_F6, FWL_VKEY_F6);
+STATIC_ASSERT_MATCH(ui::VKEY_F7, FWL_VKEY_F7);
+STATIC_ASSERT_MATCH(ui::VKEY_F8, FWL_VKEY_F8);
+STATIC_ASSERT_MATCH(ui::VKEY_F9, FWL_VKEY_F9);
+STATIC_ASSERT_MATCH(ui::VKEY_F10, FWL_VKEY_F10);
+STATIC_ASSERT_MATCH(ui::VKEY_F11, FWL_VKEY_F11);
+STATIC_ASSERT_MATCH(ui::VKEY_F12, FWL_VKEY_F12);
+STATIC_ASSERT_MATCH(ui::VKEY_F13, FWL_VKEY_F13);
+STATIC_ASSERT_MATCH(ui::VKEY_F14, FWL_VKEY_F14);
+STATIC_ASSERT_MATCH(ui::VKEY_F15, FWL_VKEY_F15);
+STATIC_ASSERT_MATCH(ui::VKEY_F16, FWL_VKEY_F16);
+STATIC_ASSERT_MATCH(ui::VKEY_F17, FWL_VKEY_F17);
+STATIC_ASSERT_MATCH(ui::VKEY_F18, FWL_VKEY_F18);
+STATIC_ASSERT_MATCH(ui::VKEY_F19, FWL_VKEY_F19);
+STATIC_ASSERT_MATCH(ui::VKEY_F20, FWL_VKEY_F20);
+STATIC_ASSERT_MATCH(ui::VKEY_F21, FWL_VKEY_F21);
+STATIC_ASSERT_MATCH(ui::VKEY_F22, FWL_VKEY_F22);
+STATIC_ASSERT_MATCH(ui::VKEY_F23, FWL_VKEY_F23);
+STATIC_ASSERT_MATCH(ui::VKEY_F24, FWL_VKEY_F24);
+STATIC_ASSERT_MATCH(ui::VKEY_NUMLOCK, FWL_VKEY_NunLock);
+STATIC_ASSERT_MATCH(ui::VKEY_SCROLL, FWL_VKEY_Scroll);
+STATIC_ASSERT_MATCH(ui::VKEY_LSHIFT, FWL_VKEY_LShift);
+STATIC_ASSERT_MATCH(ui::VKEY_RSHIFT, FWL_VKEY_RShift);
+STATIC_ASSERT_MATCH(ui::VKEY_LCONTROL, FWL_VKEY_LControl);
+STATIC_ASSERT_MATCH(ui::VKEY_RCONTROL, FWL_VKEY_RControl);
+STATIC_ASSERT_MATCH(ui::VKEY_LMENU, FWL_VKEY_LMenu);
+STATIC_ASSERT_MATCH(ui::VKEY_RMENU, FWL_VKEY_RMenu);
+STATIC_ASSERT_MATCH(ui::VKEY_BROWSER_BACK, FWL_VKEY_BROWSER_Back);
+STATIC_ASSERT_MATCH(ui::VKEY_BROWSER_FORWARD, FWL_VKEY_BROWSER_Forward);
+STATIC_ASSERT_MATCH(ui::VKEY_BROWSER_REFRESH, FWL_VKEY_BROWSER_Refresh);
+STATIC_ASSERT_MATCH(ui::VKEY_BROWSER_STOP, FWL_VKEY_BROWSER_Stop);
+STATIC_ASSERT_MATCH(ui::VKEY_BROWSER_SEARCH, FWL_VKEY_BROWSER_Search);
+STATIC_ASSERT_MATCH(ui::VKEY_BROWSER_FAVORITES, FWL_VKEY_BROWSER_Favorites);
+STATIC_ASSERT_MATCH(ui::VKEY_BROWSER_HOME, FWL_VKEY_BROWSER_Home);
+STATIC_ASSERT_MATCH(ui::VKEY_VOLUME_MUTE, FWL_VKEY_VOLUME_Mute);
+STATIC_ASSERT_MATCH(ui::VKEY_VOLUME_DOWN, FWL_VKEY_VOLUME_Down);
+STATIC_ASSERT_MATCH(ui::VKEY_VOLUME_UP, FWL_VKEY_VOLUME_Up);
+STATIC_ASSERT_MATCH(ui::VKEY_MEDIA_NEXT_TRACK, FWL_VKEY_MEDIA_NEXT_Track);
+STATIC_ASSERT_MATCH(ui::VKEY_MEDIA_PREV_TRACK, FWL_VKEY_MEDIA_PREV_Track);
+STATIC_ASSERT_MATCH(ui::VKEY_MEDIA_STOP, FWL_VKEY_MEDIA_Stop);
+STATIC_ASSERT_MATCH(ui::VKEY_MEDIA_PLAY_PAUSE, FWL_VKEY_MEDIA_PLAY_Pause);
+STATIC_ASSERT_MATCH(ui::VKEY_MEDIA_LAUNCH_MAIL, FWL_VKEY_MEDIA_LAUNCH_Mail);
+STATIC_ASSERT_MATCH(ui::VKEY_MEDIA_LAUNCH_MEDIA_SELECT,
+ FWL_VKEY_MEDIA_LAUNCH_MEDIA_Select);
+STATIC_ASSERT_MATCH(ui::VKEY_MEDIA_LAUNCH_APP1, FWL_VKEY_MEDIA_LAUNCH_APP1);
+STATIC_ASSERT_MATCH(ui::VKEY_MEDIA_LAUNCH_APP2, FWL_VKEY_MEDIA_LAUNCH_APP2);
+STATIC_ASSERT_MATCH(ui::VKEY_OEM_1, FWL_VKEY_OEM_1);
+STATIC_ASSERT_MATCH(ui::VKEY_OEM_PLUS, FWL_VKEY_OEM_Plus);
+STATIC_ASSERT_MATCH(ui::VKEY_OEM_COMMA, FWL_VKEY_OEM_Comma);
+STATIC_ASSERT_MATCH(ui::VKEY_OEM_MINUS, FWL_VKEY_OEM_Minus);
+STATIC_ASSERT_MATCH(ui::VKEY_OEM_PERIOD, FWL_VKEY_OEM_Period);
+STATIC_ASSERT_MATCH(ui::VKEY_OEM_2, FWL_VKEY_OEM_2);
+STATIC_ASSERT_MATCH(ui::VKEY_OEM_3, FWL_VKEY_OEM_3);
+STATIC_ASSERT_MATCH(ui::VKEY_OEM_4, FWL_VKEY_OEM_4);
+STATIC_ASSERT_MATCH(ui::VKEY_OEM_5, FWL_VKEY_OEM_5);
+STATIC_ASSERT_MATCH(ui::VKEY_OEM_6, FWL_VKEY_OEM_6);
+STATIC_ASSERT_MATCH(ui::VKEY_OEM_7, FWL_VKEY_OEM_7);
+STATIC_ASSERT_MATCH(ui::VKEY_OEM_8, FWL_VKEY_OEM_8);
+STATIC_ASSERT_MATCH(ui::VKEY_OEM_102, FWL_VKEY_OEM_102);
+STATIC_ASSERT_MATCH(ui::VKEY_PROCESSKEY, FWL_VKEY_ProcessKey);
+STATIC_ASSERT_MATCH(ui::VKEY_PACKET, FWL_VKEY_Packet);
+STATIC_ASSERT_MATCH(ui::VKEY_ATTN, FWL_VKEY_Attn);
+STATIC_ASSERT_MATCH(ui::VKEY_CRSEL, FWL_VKEY_Crsel);
+STATIC_ASSERT_MATCH(ui::VKEY_EXSEL, FWL_VKEY_Exsel);
+STATIC_ASSERT_MATCH(ui::VKEY_EREOF, FWL_VKEY_Ereof);
+STATIC_ASSERT_MATCH(ui::VKEY_PLAY, FWL_VKEY_Play);
+STATIC_ASSERT_MATCH(ui::VKEY_ZOOM, FWL_VKEY_Zoom);
+STATIC_ASSERT_MATCH(ui::VKEY_NONAME, FWL_VKEY_NoName);
+STATIC_ASSERT_MATCH(ui::VKEY_PA1, FWL_VKEY_PA1);
+STATIC_ASSERT_MATCH(ui::VKEY_OEM_CLEAR, FWL_VKEY_OEM_Clear);
+STATIC_ASSERT_MATCH(ui::VKEY_UNKNOWN, FWL_VKEY_Unknown);
+
+STATIC_ASSERT_MATCH(PP_PRIVATEFONTCHARSET_ANSI, FXFONT_ANSI_CHARSET);
+STATIC_ASSERT_MATCH(PP_PRIVATEFONTCHARSET_DEFAULT, FXFONT_DEFAULT_CHARSET);
+STATIC_ASSERT_MATCH(PP_PRIVATEFONTCHARSET_SYMBOL, FXFONT_SYMBOL_CHARSET);
+STATIC_ASSERT_MATCH(PP_PRIVATEFONTCHARSET_SHIFTJIS, FXFONT_SHIFTJIS_CHARSET);
+STATIC_ASSERT_MATCH(PP_PRIVATEFONTCHARSET_HANGUL, FXFONT_HANGEUL_CHARSET);
+STATIC_ASSERT_MATCH(PP_PRIVATEFONTCHARSET_GB2312, FXFONT_GB2312_CHARSET);
+STATIC_ASSERT_MATCH(PP_PRIVATEFONTCHARSET_CHINESEBIG5,
+ FXFONT_CHINESEBIG5_CHARSET);
+
+STATIC_ASSERT_MATCH(PP_PRIVATEDUPLEXMODE_NONE, DuplexUndefined);
+STATIC_ASSERT_MATCH(PP_PRIVATEDUPLEXMODE_SIMPLEX, Simplex);
+STATIC_ASSERT_MATCH(PP_PRIVATEDUPLEXMODE_SHORT_EDGE, DuplexFlipShortEdge);
+STATIC_ASSERT_MATCH(PP_PRIVATEDUPLEXMODE_LONG_EDGE, DuplexFlipLongEdge);
diff --git a/chromium/pdf/pdfium/pdfium_engine.cc b/chromium/pdf/pdfium/pdfium_engine.cc
new file mode 100644
index 00000000000..10f11d126ba
--- /dev/null
+++ b/chromium/pdf/pdfium/pdfium_engine.cc
@@ -0,0 +1,3953 @@
+// 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/pdfium/pdfium_engine.h"
+
+#include <math.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#include <set>
+
+#include "base/i18n/icu_encoding_detection.h"
+#include "base/i18n/icu_string_conversions.h"
+#include "base/json/json_writer.h"
+#include "base/lazy_instance.h"
+#include "base/logging.h"
+#include "base/macros.h"
+#include "base/memory/scoped_ptr.h"
+#include "base/numerics/safe_conversions.h"
+#include "base/stl_util.h"
+#include "base/strings/string_number_conversions.h"
+#include "base/strings/string_piece.h"
+#include "base/strings/string_util.h"
+#include "base/strings/utf_string_conversions.h"
+#include "base/values.h"
+#include "gin/array_buffer.h"
+#include "gin/public/gin_embedders.h"
+#include "gin/public/isolate_holder.h"
+#include "pdf/draw_utils.h"
+#include "pdf/pdfium/pdfium_api_string_buffer_adapter.h"
+#include "pdf/pdfium/pdfium_mem_buffer_file_read.h"
+#include "pdf/pdfium/pdfium_mem_buffer_file_write.h"
+#include "ppapi/c/pp_errors.h"
+#include "ppapi/c/pp_input_event.h"
+#include "ppapi/c/ppb_core.h"
+#include "ppapi/c/private/ppb_pdf.h"
+#include "ppapi/cpp/dev/memory_dev.h"
+#include "ppapi/cpp/input_event.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 "ppapi/cpp/url_response_info.h"
+#include "ppapi/cpp/var.h"
+#include "ppapi/cpp/var_dictionary.h"
+#include "printing/pdf_transform.h"
+#include "printing/units.h"
+#include "third_party/pdfium/public/fpdf_edit.h"
+#include "third_party/pdfium/public/fpdf_ext.h"
+#include "third_party/pdfium/public/fpdf_flatten.h"
+#include "third_party/pdfium/public/fpdf_ppo.h"
+#include "third_party/pdfium/public/fpdf_save.h"
+#include "third_party/pdfium/public/fpdf_searchex.h"
+#include "third_party/pdfium/public/fpdf_sysfontinfo.h"
+#include "third_party/pdfium/public/fpdf_transformpage.h"
+#include "ui/events/keycodes/keyboard_codes.h"
+#include "ui/gfx/geometry/rect.h"
+#include "v8/include/v8.h"
+
+using printing::ConvertUnit;
+using printing::ConvertUnitDouble;
+using printing::kPointsPerInch;
+using printing::kPixelsPerInch;
+
+namespace chrome_pdf {
+
+namespace {
+
+#define kPageShadowTop 3
+#define kPageShadowBottom 7
+#define kPageShadowLeft 5
+#define kPageShadowRight 5
+
+#define kPageSeparatorThickness 4
+#define kHighlightColorR 153
+#define kHighlightColorG 193
+#define kHighlightColorB 218
+
+const uint32_t kPendingPageColor = 0xFFEEEEEE;
+
+#define kFormHighlightColor 0xFFE4DD
+#define kFormHighlightAlpha 100
+
+#define kMaxPasswordTries 3
+
+// See Table 3.20 in
+// http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
+#define kPDFPermissionPrintLowQualityMask 1 << 2
+#define kPDFPermissionPrintHighQualityMask 1 << 11
+#define kPDFPermissionCopyMask 1 << 4
+#define kPDFPermissionCopyAccessibleMask 1 << 9
+
+#define kLoadingTextVerticalOffset 50
+
+// The maximum amount of time we'll spend doing a paint before we give back
+// control of the thread.
+#define kMaxProgressivePaintTimeMs 50
+
+// The maximum amount of time we'll spend doing the first paint. This is less
+// than the above to keep things smooth if the user is scrolling quickly. We
+// try painting a little because with accelerated compositing, we get flushes
+// only every 16 ms. If we were to wait until the next flush to paint the rest
+// of the pdf, we would never get to draw the pdf and would only draw the
+// scrollbars. This value is picked to give enough time for gpu related code to
+// do its thing and still fit within the timelimit for 60Hz. For the
+// non-composited case, this doesn't make things worse since we're still
+// painting the scrollbars > 60 Hz.
+#define kMaxInitialProgressivePaintTimeMs 10
+
+std::vector<uint32_t> GetPageNumbersFromPrintPageNumberRange(
+ const PP_PrintPageNumberRange_Dev* page_ranges,
+ uint32_t page_range_count) {
+ std::vector<uint32_t> page_numbers;
+ for (uint32_t index = 0; index < page_range_count; ++index) {
+ for (uint32_t page_number = page_ranges[index].first_page_number;
+ page_number <= page_ranges[index].last_page_number; ++page_number) {
+ page_numbers.push_back(page_number);
+ }
+ }
+ return page_numbers;
+}
+
+#if defined(OS_LINUX)
+
+PP_Instance g_last_instance_id;
+
+PP_BrowserFont_Trusted_Weight WeightToBrowserFontTrustedWeight(int weight) {
+ static_assert(PP_BROWSERFONT_TRUSTED_WEIGHT_100 == 0,
+ "PP_BrowserFont_Trusted_Weight min");
+ static_assert(PP_BROWSERFONT_TRUSTED_WEIGHT_900 == 8,
+ "PP_BrowserFont_Trusted_Weight max");
+ const int kMinimumWeight = 100;
+ const int kMaximumWeight = 900;
+ int normalized_weight =
+ std::min(std::max(weight, kMinimumWeight), kMaximumWeight);
+ normalized_weight = (normalized_weight / 100) - 1;
+ return static_cast<PP_BrowserFont_Trusted_Weight>(normalized_weight);
+}
+
+// This list is for CPWL_FontMap::GetDefaultFontByCharset().
+// We pretend to have these font natively and let the browser (or underlying
+// fontconfig) to pick the proper font on the system.
+void EnumFonts(struct _FPDF_SYSFONTINFO* sysfontinfo, void* mapper) {
+ FPDF_AddInstalledFont(mapper, "Arial", FXFONT_DEFAULT_CHARSET);
+
+ const FPDF_CharsetFontMap* font_map = FPDF_GetDefaultTTFMap();
+ for (; font_map->charset != -1; ++font_map) {
+ FPDF_AddInstalledFont(mapper, font_map->fontname, font_map->charset);
+ }
+}
+
+void* MapFont(struct _FPDF_SYSFONTINFO*, int weight, int italic,
+ int charset, int pitch_family, const char* face, int* exact) {
+ // Do not attempt to map fonts if pepper is not initialized (for privet local
+ // printing).
+ // TODO(noamsml): Real font substitution (http://crbug.com/391978)
+ if (!pp::Module::Get())
+ return NULL;
+
+ pp::BrowserFontDescription description;
+
+ // Pretend the system does not have the Symbol font to force a fallback to
+ // the built in Symbol font in CFX_FontMapper::FindSubstFont().
+ if (strcmp(face, "Symbol") == 0)
+ return NULL;
+
+ if (pitch_family & FXFONT_FF_FIXEDPITCH) {
+ description.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_MONOSPACE);
+ } else if (pitch_family & FXFONT_FF_ROMAN) {
+ description.set_family(PP_BROWSERFONT_TRUSTED_FAMILY_SERIF);
+ }
+
+ static const struct {
+ const char* pdf_name;
+ const char* face;
+ bool bold;
+ bool italic;
+ } kPdfFontSubstitutions[] = {
+ {"Courier", "Courier New", false, false},
+ {"Courier-Bold", "Courier New", true, false},
+ {"Courier-BoldOblique", "Courier New", true, true},
+ {"Courier-Oblique", "Courier New", false, true},
+ {"Helvetica", "Arial", false, false},
+ {"Helvetica-Bold", "Arial", true, false},
+ {"Helvetica-BoldOblique", "Arial", true, true},
+ {"Helvetica-Oblique", "Arial", false, true},
+ {"Times-Roman", "Times New Roman", false, false},
+ {"Times-Bold", "Times New Roman", true, false},
+ {"Times-BoldItalic", "Times New Roman", true, true},
+ {"Times-Italic", "Times New Roman", false, true},
+
+ // MS P?(Mincho|Gothic) are the most notable fonts in Japanese PDF files
+ // without embedding the glyphs. Sometimes the font names are encoded
+ // in Japanese Windows's locale (CP932/Shift_JIS) without space.
+ // Most Linux systems don't have the exact font, but for outsourcing
+ // fontconfig to find substitutable font in the system, we pass ASCII
+ // font names to it.
+ {"MS-PGothic", "MS PGothic", false, false},
+ {"MS-Gothic", "MS Gothic", false, false},
+ {"MS-PMincho", "MS PMincho", false, false},
+ {"MS-Mincho", "MS Mincho", false, false},
+ // MS PGothic in Shift_JIS encoding.
+ {"\x82\x6C\x82\x72\x82\x6F\x83\x53\x83\x56\x83\x62\x83\x4E",
+ "MS PGothic", false, false},
+ // MS Gothic in Shift_JIS encoding.
+ {"\x82\x6C\x82\x72\x83\x53\x83\x56\x83\x62\x83\x4E",
+ "MS Gothic", false, false},
+ // MS PMincho in Shift_JIS encoding.
+ {"\x82\x6C\x82\x72\x82\x6F\x96\xBE\x92\xA9",
+ "MS PMincho", false, false},
+ // MS Mincho in Shift_JIS encoding.
+ {"\x82\x6C\x82\x72\x96\xBE\x92\xA9",
+ "MS Mincho", false, false},
+ };
+
+ // Similar logic exists in PDFium's CFX_FolderFontInfo::FindFont().
+ if (charset == FXFONT_ANSI_CHARSET && (pitch_family & FXFONT_FF_FIXEDPITCH))
+ face = "Courier New";
+
+ // Map from the standard PDF fonts to TrueType font names.
+ size_t i;
+ for (i = 0; i < arraysize(kPdfFontSubstitutions); ++i) {
+ if (strcmp(face, kPdfFontSubstitutions[i].pdf_name) == 0) {
+ description.set_face(kPdfFontSubstitutions[i].face);
+ if (kPdfFontSubstitutions[i].bold)
+ description.set_weight(PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD);
+ if (kPdfFontSubstitutions[i].italic)
+ description.set_italic(true);
+ break;
+ }
+ }
+
+ if (i == arraysize(kPdfFontSubstitutions)) {
+ // Convert to UTF-8 before calling set_face().
+ std::string face_utf8;
+ if (base::IsStringUTF8(face)) {
+ face_utf8 = face;
+ } else {
+ std::string encoding;
+ if (base::DetectEncoding(face, &encoding)) {
+ // ConvertToUtf8AndNormalize() clears |face_utf8| on failure.
+ base::ConvertToUtf8AndNormalize(face, encoding, &face_utf8);
+ }
+ }
+
+ if (face_utf8.empty())
+ return nullptr;
+
+ description.set_face(face_utf8);
+ description.set_weight(WeightToBrowserFontTrustedWeight(weight));
+ description.set_italic(italic > 0);
+ }
+
+ if (!pp::PDF::IsAvailable()) {
+ NOTREACHED();
+ return NULL;
+ }
+
+ 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 GetFontData(struct _FPDF_SYSFONTINFO*, void* font_id,
+ unsigned int table, unsigned char* buffer,
+ unsigned long buf_size) {
+ if (!pp::PDF::IsAvailable()) {
+ NOTREACHED();
+ return 0;
+ }
+
+ 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 DeleteFont(struct _FPDF_SYSFONTINFO*, void* font_id) {
+ long res_id = reinterpret_cast<long>(font_id);
+ pp::Module::Get()->core()->ReleaseResource(res_id);
+}
+
+FPDF_SYSFONTINFO g_font_info = {
+ 1,
+ 0,
+ EnumFonts,
+ MapFont,
+ 0,
+ GetFontData,
+ 0,
+ 0,
+ DeleteFont
+};
+#endif // defined(OS_LINUX)
+
+PDFiumEngine* g_engine_for_unsupported;
+
+void Unsupported_Handler(UNSUPPORT_INFO*, int type) {
+ if (!g_engine_for_unsupported) {
+ NOTREACHED();
+ return;
+ }
+
+ g_engine_for_unsupported->UnsupportedFeature(type);
+}
+
+UNSUPPORT_INFO g_unsupported_info = {
+ 1,
+ Unsupported_Handler
+};
+
+// Set the destination page size and content area in points based on source
+// page rotation and orientation.
+//
+// |rotated| True if source page is rotated 90 degree or 270 degree.
+// |is_src_page_landscape| is true if the source page orientation is landscape.
+// |page_size| has the actual destination page size in points.
+// |content_rect| has the actual destination page printable area values in
+// points.
+void SetPageSizeAndContentRect(bool rotated,
+ bool is_src_page_landscape,
+ pp::Size* page_size,
+ pp::Rect* content_rect) {
+ bool is_dst_page_landscape = page_size->width() > page_size->height();
+ bool page_orientation_mismatched = is_src_page_landscape !=
+ is_dst_page_landscape;
+ bool rotate_dst_page = rotated ^ page_orientation_mismatched;
+ if (rotate_dst_page) {
+ page_size->SetSize(page_size->height(), page_size->width());
+ content_rect->SetRect(content_rect->y(), content_rect->x(),
+ content_rect->height(), content_rect->width());
+ }
+}
+
+// This formats a string with special 0xfffe end-of-line hyphens the same way
+// as Adobe Reader. When a hyphen is encountered, the next non-CR/LF whitespace
+// becomes CR+LF and the hyphen is erased. If there is no whitespace between
+// two hyphens, the latter hyphen is erased and ignored.
+void FormatStringWithHyphens(base::string16* text) {
+ // First pass marks all the hyphen positions.
+ struct HyphenPosition {
+ HyphenPosition() : position(0), next_whitespace_position(0) {}
+ size_t position;
+ size_t next_whitespace_position; // 0 for none
+ };
+ std::vector<HyphenPosition> hyphen_positions;
+ HyphenPosition current_hyphen_position;
+ bool current_hyphen_position_is_valid = false;
+ const base::char16 kPdfiumHyphenEOL = 0xfffe;
+
+ for (size_t i = 0; i < text->size(); ++i) {
+ const base::char16& current_char = (*text)[i];
+ if (current_char == kPdfiumHyphenEOL) {
+ if (current_hyphen_position_is_valid)
+ hyphen_positions.push_back(current_hyphen_position);
+ current_hyphen_position = HyphenPosition();
+ current_hyphen_position.position = i;
+ current_hyphen_position_is_valid = true;
+ } else if (base::IsUnicodeWhitespace(current_char)) {
+ if (current_hyphen_position_is_valid) {
+ if (current_char != L'\r' && current_char != L'\n')
+ current_hyphen_position.next_whitespace_position = i;
+ hyphen_positions.push_back(current_hyphen_position);
+ current_hyphen_position_is_valid = false;
+ }
+ }
+ }
+ if (current_hyphen_position_is_valid)
+ hyphen_positions.push_back(current_hyphen_position);
+
+ // With all the hyphen positions, do the search and replace.
+ while (!hyphen_positions.empty()) {
+ static const base::char16 kCr[] = {L'\r', L'\0'};
+ const HyphenPosition& position = hyphen_positions.back();
+ if (position.next_whitespace_position != 0) {
+ (*text)[position.next_whitespace_position] = L'\n';
+ text->insert(position.next_whitespace_position, kCr);
+ }
+ text->erase(position.position, 1);
+ hyphen_positions.pop_back();
+ }
+
+ // Adobe Reader also get rid of trailing spaces right before a CRLF.
+ static const base::char16 kSpaceCrCn[] = {L' ', L'\r', L'\n', L'\0'};
+ static const base::char16 kCrCn[] = {L'\r', L'\n', L'\0'};
+ base::ReplaceSubstringsAfterOffset(text, 0, kSpaceCrCn, kCrCn);
+}
+
+// Replace CR/LF with just LF on POSIX.
+void FormatStringForOS(base::string16* text) {
+#if defined(OS_POSIX)
+ static const base::char16 kCr[] = {L'\r', L'\0'};
+ static const base::char16 kBlank[] = {L'\0'};
+ base::ReplaceChars(*text, kCr, kBlank, text);
+#elif defined(OS_WIN)
+ // Do nothing
+#else
+ NOTIMPLEMENTED();
+#endif
+}
+
+// Returns a VarDictionary (representing a bookmark), which in turn contains
+// child VarDictionaries (representing the child bookmarks).
+// If NULL is passed in as the bookmark then we traverse from the "root".
+// Note that the "root" bookmark contains no useful information.
+pp::VarDictionary TraverseBookmarks(FPDF_DOCUMENT doc,
+ FPDF_BOOKMARK bookmark,
+ unsigned int depth) {
+ pp::VarDictionary dict;
+ base::string16 title;
+ unsigned long buffer_size = FPDFBookmark_GetTitle(bookmark, NULL, 0);
+ if (buffer_size > 0) {
+ PDFiumAPIStringBufferSizeInBytesAdapter<base::string16> api_string_adapter(
+ &title, buffer_size, true);
+ api_string_adapter.Close(FPDFBookmark_GetTitle(
+ bookmark, api_string_adapter.GetData(), buffer_size));
+ }
+ dict.Set(pp::Var("title"), pp::Var(base::UTF16ToUTF8(title)));
+
+ FPDF_DEST dest = FPDFBookmark_GetDest(doc, bookmark);
+ // Some bookmarks don't have a page to select.
+ if (dest) {
+ int page_index = FPDFDest_GetPageIndex(doc, dest);
+ dict.Set(pp::Var("page"), pp::Var(page_index));
+ }
+
+ pp::VarArray children;
+
+ // Don't trust PDFium to handle circular bookmarks.
+ const unsigned int kMaxDepth = 128;
+ if (depth < kMaxDepth) {
+ int child_index = 0;
+ std::set<FPDF_BOOKMARK> seen_bookmarks;
+ for (FPDF_BOOKMARK child_bookmark =
+ FPDFBookmark_GetFirstChild(doc, bookmark);
+ child_bookmark;
+ child_bookmark = FPDFBookmark_GetNextSibling(doc, child_bookmark)) {
+ if (ContainsKey(seen_bookmarks, child_bookmark))
+ break;
+
+ seen_bookmarks.insert(child_bookmark);
+ children.Set(child_index,
+ TraverseBookmarks(doc, child_bookmark, depth + 1));
+ child_index++;
+ }
+ }
+ dict.Set(pp::Var("children"), children);
+ return dict;
+}
+
+std::string GetDocumentMetadata(FPDF_DOCUMENT doc, const std::string& key) {
+ size_t size = FPDF_GetMetaText(doc, key.c_str(), nullptr, 0);
+ if (size == 0)
+ return std::string();
+
+ base::string16 value;
+ PDFiumAPIStringBufferSizeInBytesAdapter<base::string16> string_adapter(
+ &value, size, false);
+ string_adapter.Close(
+ FPDF_GetMetaText(doc, key.c_str(), string_adapter.GetData(), size));
+ return base::UTF16ToUTF8(value);
+}
+
+gin::IsolateHolder* g_isolate_holder = nullptr;
+
+void SetUpV8() {
+ gin::IsolateHolder::Initialize(gin::IsolateHolder::kNonStrictMode,
+ gin::IsolateHolder::kStableV8Extras,
+ gin::ArrayBufferAllocator::SharedInstance());
+ g_isolate_holder =
+ new gin::IsolateHolder(gin::IsolateHolder::kSingleThread);
+ g_isolate_holder->isolate()->Enter();
+}
+
+void TearDownV8() {
+ g_isolate_holder->isolate()->Exit();
+ delete g_isolate_holder;
+ g_isolate_holder = nullptr;
+}
+
+} // namespace
+
+bool InitializeSDK() {
+ SetUpV8();
+
+ FPDF_LIBRARY_CONFIG config;
+ config.version = 2;
+ config.m_pUserFontPaths = nullptr;
+ config.m_pIsolate = v8::Isolate::GetCurrent();
+ config.m_v8EmbedderSlot = gin::kEmbedderPDFium;
+ FPDF_InitLibraryWithConfig(&config);
+
+#if defined(OS_LINUX)
+ // Font loading doesn't work in the renderer sandbox in Linux.
+ FPDF_SetSystemFontInfo(&g_font_info);
+#endif
+
+ FSDK_SetUnSpObjProcessHandler(&g_unsupported_info);
+
+ return true;
+}
+
+void ShutdownSDK() {
+ TearDownV8();
+ FPDF_DestroyLibrary();
+}
+
+PDFEngine* PDFEngine::Create(PDFEngine::Client* client) {
+ return new PDFiumEngine(client);
+}
+
+PDFiumEngine::PDFiumEngine(PDFEngine::Client* client)
+ : client_(client),
+ current_zoom_(1.0),
+ current_rotation_(0),
+ doc_loader_(this),
+ password_tries_remaining_(0),
+ doc_(NULL),
+ form_(NULL),
+ defer_page_unload_(false),
+ selecting_(false),
+ mouse_down_state_(PDFiumPage::NONSELECTABLE_AREA,
+ PDFiumPage::LinkTarget()),
+ next_page_to_search_(-1),
+ last_page_to_search_(-1),
+ last_character_index_to_search_(-1),
+ permissions_(0),
+ permissions_handler_revision_(-1),
+ fpdf_availability_(NULL),
+ next_timer_id_(0),
+ last_page_mouse_down_(-1),
+ most_visible_page_(-1),
+ called_do_document_action_(false),
+ render_grayscale_(false),
+ progressive_paint_timeout_(0),
+ getting_password_(false) {
+ find_factory_.Initialize(this);
+ password_factory_.Initialize(this);
+
+ file_access_.m_FileLen = 0;
+ file_access_.m_GetBlock = &GetBlock;
+ file_access_.m_Param = &doc_loader_;
+
+ file_availability_.version = 1;
+ file_availability_.IsDataAvail = &IsDataAvail;
+ file_availability_.loader = &doc_loader_;
+
+ download_hints_.version = 1;
+ download_hints_.AddSegment = &AddSegment;
+ download_hints_.loader = &doc_loader_;
+
+ // Initialize FPDF_FORMFILLINFO member variables. Deriving from this struct
+ // allows the static callbacks to be able to cast the FPDF_FORMFILLINFO in
+ // callbacks to ourself instead of maintaining a map of them to
+ // PDFiumEngine.
+ FPDF_FORMFILLINFO::version = 1;
+ FPDF_FORMFILLINFO::m_pJsPlatform = this;
+ FPDF_FORMFILLINFO::Release = NULL;
+ FPDF_FORMFILLINFO::FFI_Invalidate = Form_Invalidate;
+ FPDF_FORMFILLINFO::FFI_OutputSelectedRect = Form_OutputSelectedRect;
+ FPDF_FORMFILLINFO::FFI_SetCursor = Form_SetCursor;
+ FPDF_FORMFILLINFO::FFI_SetTimer = Form_SetTimer;
+ FPDF_FORMFILLINFO::FFI_KillTimer = Form_KillTimer;
+ FPDF_FORMFILLINFO::FFI_GetLocalTime = Form_GetLocalTime;
+ FPDF_FORMFILLINFO::FFI_OnChange = Form_OnChange;
+ FPDF_FORMFILLINFO::FFI_GetPage = Form_GetPage;
+ FPDF_FORMFILLINFO::FFI_GetCurrentPage = Form_GetCurrentPage;
+ FPDF_FORMFILLINFO::FFI_GetRotation = Form_GetRotation;
+ FPDF_FORMFILLINFO::FFI_ExecuteNamedAction = Form_ExecuteNamedAction;
+ FPDF_FORMFILLINFO::FFI_SetTextFieldFocus = Form_SetTextFieldFocus;
+ FPDF_FORMFILLINFO::FFI_DoURIAction = Form_DoURIAction;
+ FPDF_FORMFILLINFO::FFI_DoGoToAction = Form_DoGoToAction;
+#ifdef PDF_USE_XFA
+ FPDF_FORMFILLINFO::version = 2;
+ FPDF_FORMFILLINFO::FFI_EmailTo = Form_EmailTo;
+ FPDF_FORMFILLINFO::FFI_DisplayCaret = Form_DisplayCaret;
+ FPDF_FORMFILLINFO::FFI_SetCurrentPage = Form_SetCurrentPage;
+ FPDF_FORMFILLINFO::FFI_GetCurrentPageIndex = Form_GetCurrentPageIndex;
+ FPDF_FORMFILLINFO::FFI_GetPageViewRect = Form_GetPageViewRect;
+ FPDF_FORMFILLINFO::FFI_GetPlatform = Form_GetPlatform;
+ FPDF_FORMFILLINFO::FFI_PopupMenu = Form_PopupMenu;
+ FPDF_FORMFILLINFO::FFI_PostRequestURL = Form_PostRequestURL;
+ FPDF_FORMFILLINFO::FFI_PutRequestURL = Form_PutRequestURL;
+ FPDF_FORMFILLINFO::FFI_UploadTo = Form_UploadTo;
+ FPDF_FORMFILLINFO::FFI_DownloadFromURL = Form_DownloadFromURL;
+ FPDF_FORMFILLINFO::FFI_OpenFile = Form_OpenFile;
+ FPDF_FORMFILLINFO::FFI_GotoURL = Form_GotoURL;
+ FPDF_FORMFILLINFO::FFI_GetLanguage = Form_GetLanguage;
+#endif // PDF_USE_XFA
+ IPDF_JSPLATFORM::version = 3;
+ IPDF_JSPLATFORM::app_alert = Form_Alert;
+ IPDF_JSPLATFORM::app_beep = Form_Beep;
+ IPDF_JSPLATFORM::app_response = Form_Response;
+ IPDF_JSPLATFORM::Doc_getFilePath = Form_GetFilePath;
+ IPDF_JSPLATFORM::Doc_mail = Form_Mail;
+ IPDF_JSPLATFORM::Doc_print = Form_Print;
+ IPDF_JSPLATFORM::Doc_submitForm = Form_SubmitForm;
+ IPDF_JSPLATFORM::Doc_gotoPage = Form_GotoPage;
+ IPDF_JSPLATFORM::Field_browse = Form_Browse;
+
+ IFSDK_PAUSE::version = 1;
+ IFSDK_PAUSE::user = NULL;
+ IFSDK_PAUSE::NeedToPauseNow = Pause_NeedToPauseNow;
+}
+
+PDFiumEngine::~PDFiumEngine() {
+ for (auto& page : pages_)
+ page->Unload();
+
+ if (doc_) {
+ FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_WC);
+
+#ifdef PDF_USE_XFA
+ // XFA may require |form_| to outlive |doc_|, so shut down in that order.
+ FPDF_CloseDocument(doc_);
+ FPDFDOC_ExitFormFillEnvironment(form_);
+#else
+ // Normally |doc_| should outlive |form_|.
+ FPDFDOC_ExitFormFillEnvironment(form_);
+ FPDF_CloseDocument(doc_);
+#endif
+ }
+ FPDFAvail_Destroy(fpdf_availability_);
+
+ STLDeleteElements(&pages_);
+}
+
+#ifdef PDF_USE_XFA
+
+// This is just for testing, needs to be removed later
+#if defined(WIN32)
+#define XFA_TESTFILE(filename) "E:/"#filename
+#else
+#define XFA_TESTFILE(filename) "/home/"#filename
+#endif
+
+struct FPDF_FILE {
+ FPDF_FILEHANDLER file_handler;
+ FILE* file;
+};
+
+void Sample_Release(FPDF_LPVOID client_data) {
+ if (!client_data)
+ return;
+ FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
+ fclose(file_wrapper->file);
+ delete file_wrapper;
+}
+
+FPDF_DWORD Sample_GetSize(FPDF_LPVOID client_data) {
+ if (!client_data)
+ return 0;
+ FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
+ long cur_pos = ftell(file_wrapper->file);
+ if (cur_pos == -1)
+ return 0;
+ if (fseek(file_wrapper->file, 0, SEEK_END))
+ return 0;
+ long size = ftell(file_wrapper->file);
+ fseek(file_wrapper->file, cur_pos, SEEK_SET);
+ return (FPDF_DWORD)size;
+}
+
+FPDF_RESULT Sample_ReadBlock(FPDF_LPVOID client_data,
+ FPDF_DWORD offset,
+ FPDF_LPVOID buffer,
+ FPDF_DWORD size) {
+ if (!client_data)
+ return -1;
+ FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
+ if (fseek(file_wrapper->file, (long)offset, SEEK_SET))
+ return -1;
+ size_t read_size = fread(buffer, 1, size, file_wrapper->file);
+ return read_size == size ? 0 : -1;
+}
+
+FPDF_RESULT Sample_WriteBlock(FPDF_LPVOID client_data,
+ FPDF_DWORD offset,
+ FPDF_LPCVOID buffer,
+ FPDF_DWORD size) {
+ if (!client_data)
+ return -1;
+ FPDF_FILE* file_wrapper = (FPDF_FILE*)client_data;
+ if (fseek(file_wrapper->file, (long)offset, SEEK_SET))
+ return -1;
+ // Write data
+ size_t write_size = fwrite(buffer, 1, size, file_wrapper->file);
+ return write_size == size ? 0 : -1;
+}
+
+FPDF_RESULT Sample_Flush(FPDF_LPVOID client_data) {
+ if (!client_data)
+ return -1;
+ // Flush file
+ fflush(((FPDF_FILE*)client_data)->file);
+ return 0;
+}
+
+FPDF_RESULT Sample_Truncate(FPDF_LPVOID client_data, FPDF_DWORD size) {
+ return 0;
+}
+
+void PDFiumEngine::Form_EmailTo(FPDF_FORMFILLINFO* param,
+ FPDF_FILEHANDLER* file_handler,
+ FPDF_WIDESTRING to,
+ FPDF_WIDESTRING subject,
+ FPDF_WIDESTRING cc,
+ FPDF_WIDESTRING bcc,
+ FPDF_WIDESTRING message) {
+ std::string to_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(to));
+ std::string subject_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(subject));
+ std::string cc_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(cc));
+ std::string bcc_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(bcc));
+ std::string message_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
+
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ engine->client_->Email(to_str, cc_str, bcc_str, subject_str, message_str);
+}
+
+void PDFiumEngine::Form_DisplayCaret(FPDF_FORMFILLINFO* param,
+ FPDF_PAGE page,
+ FPDF_BOOL visible,
+ double left,
+ double top,
+ double right,
+ double bottom) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ engine->client_->UpdateCursor(PP_CURSORTYPE_IBEAM);
+ std::vector<pp::Rect> tickmarks;
+ pp::Rect rect(left, top, right, bottom);
+ tickmarks.push_back(rect);
+ engine->client_->UpdateTickMarks(tickmarks);
+}
+
+void PDFiumEngine::Form_SetCurrentPage(FPDF_FORMFILLINFO* param,
+ FPDF_DOCUMENT document,
+ int page) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ pp::Rect page_view_rect = engine->GetPageContentsRect(page);
+ engine->ScrolledToYPosition(page_view_rect.height());
+ pp::Point pos(1, page_view_rect.height());
+ engine->SetScrollPosition(pos);
+}
+
+int PDFiumEngine::Form_GetCurrentPageIndex(FPDF_FORMFILLINFO* param,
+ FPDF_DOCUMENT document) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ return engine->GetMostVisiblePage();
+}
+
+void PDFiumEngine::Form_GetPageViewRect(FPDF_FORMFILLINFO* param,
+ FPDF_PAGE page,
+ double* left,
+ double* top,
+ double* right,
+ double* bottom) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ int page_index = engine->GetMostVisiblePage();
+ pp::Rect page_view_rect = engine->GetPageContentsRect(page_index);
+
+ *left = page_view_rect.x();
+ *right = page_view_rect.right();
+ *top = page_view_rect.y();
+ *bottom = page_view_rect.bottom();
+}
+
+int PDFiumEngine::Form_GetPlatform(FPDF_FORMFILLINFO* param,
+ void* platform,
+ int length) {
+ int platform_flag = -1;
+
+#if defined(WIN32)
+ platform_flag = 0;
+#elif defined(__linux__)
+ platform_flag = 1;
+#else
+ platform_flag = 2;
+#endif
+
+ std::string javascript = "alert(\"Platform:"
+ + base::DoubleToString(platform_flag)
+ + "\")";
+
+ return platform_flag;
+}
+
+FPDF_BOOL PDFiumEngine::Form_PopupMenu(FPDF_FORMFILLINFO* param,
+ FPDF_PAGE page,
+ FPDF_WIDGET widget,
+ int menu_flag,
+ float x,
+ float y) {
+ return false;
+}
+
+FPDF_BOOL PDFiumEngine::Form_PostRequestURL(FPDF_FORMFILLINFO* param,
+ FPDF_WIDESTRING url,
+ FPDF_WIDESTRING data,
+ FPDF_WIDESTRING content_type,
+ FPDF_WIDESTRING encode,
+ FPDF_WIDESTRING header,
+ FPDF_BSTR* response) {
+ std::string url_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
+ std::string data_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(data));
+ std::string content_type_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(content_type));
+ std::string encode_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(encode));
+ std::string header_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(header));
+
+ std::string javascript = "alert(\"Post:"
+ + url_str + "," + data_str + "," + content_type_str + ","
+ + encode_str + "," + header_str
+ + "\")";
+ return true;
+}
+
+FPDF_BOOL PDFiumEngine::Form_PutRequestURL(FPDF_FORMFILLINFO* param,
+ FPDF_WIDESTRING url,
+ FPDF_WIDESTRING data,
+ FPDF_WIDESTRING encode) {
+ std::string url_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
+ std::string data_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(data));
+ std::string encode_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(encode));
+
+ std::string javascript = "alert(\"Put:"
+ + url_str + "," + data_str + "," + encode_str
+ + "\")";
+
+ return true;
+}
+
+void PDFiumEngine::Form_UploadTo(FPDF_FORMFILLINFO* param,
+ FPDF_FILEHANDLER* file_handle,
+ int file_flag,
+ FPDF_WIDESTRING to) {
+ std::string to_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(to));
+ // TODO: needs the full implementation of form uploading
+}
+
+FPDF_LPFILEHANDLER PDFiumEngine::Form_DownloadFromURL(FPDF_FORMFILLINFO* param,
+ FPDF_WIDESTRING url) {
+ std::string url_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
+
+ // Now should get data from url.
+ // For testing purpose, use data read from file
+ // TODO: needs the full implementation here
+ FILE* file = fopen(XFA_TESTFILE("downloadtest.tem"), "w");
+
+ FPDF_FILE* file_wrapper = new FPDF_FILE;
+ file_wrapper->file = file;
+ file_wrapper->file_handler.clientData = file_wrapper;
+ file_wrapper->file_handler.Flush = Sample_Flush;
+ file_wrapper->file_handler.GetSize = Sample_GetSize;
+ file_wrapper->file_handler.ReadBlock = Sample_ReadBlock;
+ file_wrapper->file_handler.Release = Sample_Release;
+ file_wrapper->file_handler.Truncate = Sample_Truncate;
+ file_wrapper->file_handler.WriteBlock = Sample_WriteBlock;
+
+ return &file_wrapper->file_handler;
+}
+
+FPDF_FILEHANDLER* PDFiumEngine::Form_OpenFile(FPDF_FORMFILLINFO* param,
+ int file_flag,
+ FPDF_WIDESTRING url,
+ const char* mode) {
+ std::string url_str = url ?
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url)) : "NULL";
+
+ // TODO: need to implement open file from the url
+ // Use a file path for the ease of testing
+ FILE* file = fopen(XFA_TESTFILE("tem.txt"), mode);
+ FPDF_FILE* file_wrapper = new FPDF_FILE;
+ file_wrapper->file = file;
+ file_wrapper->file_handler.clientData = file_wrapper;
+ file_wrapper->file_handler.Flush = Sample_Flush;
+ file_wrapper->file_handler.GetSize = Sample_GetSize;
+ file_wrapper->file_handler.ReadBlock = Sample_ReadBlock;
+ file_wrapper->file_handler.Release = Sample_Release;
+ file_wrapper->file_handler.Truncate = Sample_Truncate;
+ file_wrapper->file_handler.WriteBlock = Sample_WriteBlock;
+ return &file_wrapper->file_handler;
+}
+
+void PDFiumEngine::Form_GotoURL(FPDF_FORMFILLINFO* param,
+ FPDF_DOCUMENT document,
+ FPDF_WIDESTRING url) {
+ std::string url_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
+ // TODO: needs to implement GOTO URL action
+}
+
+int PDFiumEngine::Form_GetLanguage(FPDF_FORMFILLINFO* param,
+ void* language,
+ int length) {
+ return 0;
+}
+
+#endif // PDF_USE_XFA
+
+int PDFiumEngine::GetBlock(void* param, unsigned long position,
+ unsigned char* buffer, unsigned long size) {
+ DocumentLoader* loader = static_cast<DocumentLoader*>(param);
+ return loader->GetBlock(position, size, buffer);
+}
+
+FPDF_BOOL PDFiumEngine::IsDataAvail(FX_FILEAVAIL* param,
+ size_t offset, size_t size) {
+ PDFiumEngine::FileAvail* file_avail =
+ static_cast<PDFiumEngine::FileAvail*>(param);
+ return file_avail->loader->IsDataAvailable(offset, size);
+}
+
+void PDFiumEngine::AddSegment(FX_DOWNLOADHINTS* param,
+ size_t offset, size_t size) {
+ PDFiumEngine::DownloadHints* download_hints =
+ static_cast<PDFiumEngine::DownloadHints*>(param);
+ return download_hints->loader->RequestData(offset, size);
+}
+
+bool PDFiumEngine::New(const char* url,
+ const char* headers) {
+ url_ = url;
+ if (!headers)
+ headers_.clear();
+ else
+ headers_ = headers;
+ return true;
+}
+
+void PDFiumEngine::PageOffsetUpdated(const pp::Point& page_offset) {
+ page_offset_ = page_offset;
+}
+
+void PDFiumEngine::PluginSizeUpdated(const pp::Size& size) {
+ CancelPaints();
+
+ plugin_size_ = size;
+ CalculateVisiblePages();
+}
+
+void PDFiumEngine::ScrolledToXPosition(int position) {
+ CancelPaints();
+
+ int old_x = position_.x();
+ position_.set_x(position);
+ CalculateVisiblePages();
+ client_->Scroll(pp::Point(old_x - position, 0));
+}
+
+void PDFiumEngine::ScrolledToYPosition(int position) {
+ CancelPaints();
+
+ int old_y = position_.y();
+ position_.set_y(position);
+ CalculateVisiblePages();
+ client_->Scroll(pp::Point(0, old_y - position));
+}
+
+void PDFiumEngine::PrePaint() {
+ for (auto& paint : progressive_paints_)
+ paint.painted_ = false;
+}
+
+void PDFiumEngine::Paint(const pp::Rect& rect,
+ pp::ImageData* image_data,
+ std::vector<pp::Rect>* ready,
+ std::vector<pp::Rect>* pending) {
+ DCHECK(image_data);
+ DCHECK(ready);
+ DCHECK(pending);
+
+ pp::Rect leftover = rect;
+ for (size_t i = 0; i < visible_pages_.size(); ++i) {
+ int index = visible_pages_[i];
+ pp::Rect page_rect = pages_[index]->rect();
+ // Convert the current page's rectangle to screen rectangle. We do this
+ // instead of the reverse (converting the dirty rectangle from screen to
+ // page coordinates) because then we'd have to convert back to screen
+ // coordinates, and the rounding errors sometime leave pixels dirty or even
+ // move the text up or down a pixel when zoomed.
+ pp::Rect page_rect_in_screen = GetPageScreenRect(index);
+ pp::Rect dirty_in_screen = page_rect_in_screen.Intersect(leftover);
+ if (dirty_in_screen.IsEmpty())
+ continue;
+
+ // Compute the leftover dirty region. The first page may have blank space
+ // above it, in which case we also need to subtract that space from the
+ // dirty region.
+ if (i == 0) {
+ pp::Rect blank_space_in_screen = dirty_in_screen;
+ blank_space_in_screen.set_y(0);
+ blank_space_in_screen.set_height(dirty_in_screen.y());
+ leftover = leftover.Subtract(blank_space_in_screen);
+ }
+ leftover = leftover.Subtract(dirty_in_screen);
+
+ if (pages_[index]->available()) {
+ int progressive = GetProgressiveIndex(index);
+ if (progressive != -1) {
+ DCHECK_GE(progressive, 0);
+ DCHECK_LT(static_cast<size_t>(progressive), progressive_paints_.size());
+ if (progressive_paints_[progressive].rect != dirty_in_screen) {
+ // The PDFium code can only handle one progressive paint at a time, so
+ // queue this up. Previously we used to merge the rects when this
+ // happened, but it made scrolling up on complex PDFs very slow since
+ // there would be a damaged rect at the top (from scroll) and at the
+ // bottom (from toolbar).
+ pending->push_back(dirty_in_screen);
+ continue;
+ }
+ }
+
+ if (progressive == -1) {
+ progressive = StartPaint(index, dirty_in_screen);
+ progressive_paint_timeout_ = kMaxInitialProgressivePaintTimeMs;
+ } else {
+ progressive_paint_timeout_ = kMaxProgressivePaintTimeMs;
+ }
+
+ progressive_paints_[progressive].painted_ = true;
+ if (ContinuePaint(progressive, image_data)) {
+ FinishPaint(progressive, image_data);
+ ready->push_back(dirty_in_screen);
+ } else {
+ pending->push_back(dirty_in_screen);
+ }
+ } else {
+ PaintUnavailablePage(index, dirty_in_screen, image_data);
+ ready->push_back(dirty_in_screen);
+ }
+ }
+}
+
+void PDFiumEngine::PostPaint() {
+ for (size_t i = 0; i < progressive_paints_.size(); ++i) {
+ if (progressive_paints_[i].painted_)
+ continue;
+
+ // This rectangle must have been merged with another one, that's why we
+ // weren't asked to paint it. Remove it or otherwise we'll never finish
+ // painting.
+ FPDF_RenderPage_Close(
+ pages_[progressive_paints_[i].page_index]->GetPage());
+ FPDFBitmap_Destroy(progressive_paints_[i].bitmap);
+ progressive_paints_.erase(progressive_paints_.begin() + i);
+ --i;
+ }
+}
+
+bool PDFiumEngine::HandleDocumentLoad(const pp::URLLoader& loader) {
+ password_tries_remaining_ = kMaxPasswordTries;
+ return doc_loader_.Init(loader, url_, headers_);
+}
+
+pp::Instance* PDFiumEngine::GetPluginInstance() {
+ return client_->GetPluginInstance();
+}
+
+pp::URLLoader PDFiumEngine::CreateURLLoader() {
+ return client_->CreateURLLoader();
+}
+
+void PDFiumEngine::AppendPage(PDFEngine* engine, int index) {
+ // Unload and delete the blank page before appending.
+ pages_[index]->Unload();
+ pages_[index]->set_calculated_links(false);
+ pp::Size curr_page_size = GetPageSize(index);
+ FPDFPage_Delete(doc_, index);
+ FPDF_ImportPages(doc_,
+ static_cast<PDFiumEngine*>(engine)->doc(),
+ "1",
+ index);
+ pp::Size new_page_size = GetPageSize(index);
+ if (curr_page_size != new_page_size)
+ LoadPageInfo(true);
+ client_->Invalidate(GetPageScreenRect(index));
+}
+
+pp::Point PDFiumEngine::GetScrollPosition() {
+ return position_;
+}
+
+void PDFiumEngine::SetScrollPosition(const pp::Point& position) {
+ position_ = position;
+}
+
+bool PDFiumEngine::IsProgressiveLoad() {
+ return doc_loader_.is_partial_document();
+}
+
+std::string PDFiumEngine::GetMetadata(const std::string& key) {
+ return GetDocumentMetadata(doc(), key);
+}
+
+void PDFiumEngine::OnPartialDocumentLoaded() {
+ file_access_.m_FileLen = doc_loader_.document_size();
+ fpdf_availability_ = FPDFAvail_Create(&file_availability_, &file_access_);
+ DCHECK(fpdf_availability_);
+
+ // Currently engine does not deal efficiently with some non-linearized files.
+ // See http://code.google.com/p/chromium/issues/detail?id=59400
+ // To improve user experience we download entire file for non-linearized PDF.
+ if (!FPDFAvail_IsLinearized(fpdf_availability_)) {
+ doc_loader_.RequestData(0, doc_loader_.document_size());
+ return;
+ }
+
+ LoadDocument();
+}
+
+void PDFiumEngine::OnPendingRequestComplete() {
+ if (!doc_ || !form_) {
+ LoadDocument();
+ return;
+ }
+
+ // LoadDocument() will result in |pending_pages_| being reset so there's no
+ // need to run the code below in that case.
+ bool update_pages = false;
+ std::vector<int> still_pending;
+ for (int pending_page : pending_pages_) {
+ if (CheckPageAvailable(pending_page, &still_pending)) {
+ update_pages = true;
+ if (IsPageVisible(pending_page))
+ client_->Invalidate(GetPageScreenRect(pending_page));
+ }
+ }
+ pending_pages_.swap(still_pending);
+ if (update_pages)
+ LoadPageInfo(true);
+}
+
+void PDFiumEngine::OnNewDataAvailable() {
+ client_->DocumentLoadProgress(doc_loader_.GetAvailableData(),
+ doc_loader_.document_size());
+}
+
+void PDFiumEngine::OnDocumentComplete() {
+ if (!doc_ || !form_) {
+ file_access_.m_FileLen = doc_loader_.document_size();
+ LoadDocument();
+ return;
+ }
+
+ FinishLoadingDocument();
+}
+
+void PDFiumEngine::FinishLoadingDocument() {
+ DCHECK(doc_loader_.IsDocumentComplete() && doc_);
+
+ bool need_update = false;
+ for (size_t i = 0; i < pages_.size(); ++i) {
+ if (pages_[i]->available())
+ continue;
+
+ pages_[i]->set_available(true);
+ // We still need to call IsPageAvail() even if the whole document is
+ // already downloaded.
+ FPDFAvail_IsPageAvail(fpdf_availability_, i, &download_hints_);
+ need_update = true;
+ if (IsPageVisible(i))
+ client_->Invalidate(GetPageScreenRect(i));
+ }
+ if (need_update)
+ LoadPageInfo(true);
+
+ if (called_do_document_action_)
+ return;
+ called_do_document_action_ = true;
+
+ // These can only be called now, as the JS might end up needing a page.
+ FORM_DoDocumentJSAction(form_);
+ FORM_DoDocumentOpenAction(form_);
+ if (most_visible_page_ != -1) {
+ FPDF_PAGE new_page = pages_[most_visible_page_]->GetPage();
+ FORM_DoPageAAction(new_page, form_, FPDFPAGE_AACTION_OPEN);
+ }
+
+ if (doc_) // This can only happen if loading |doc_| fails.
+ client_->DocumentLoadComplete(pages_.size());
+}
+
+void PDFiumEngine::UnsupportedFeature(int type) {
+ std::string feature;
+ switch (type) {
+#ifndef PDF_USE_XFA
+ case FPDF_UNSP_DOC_XFAFORM:
+ feature = "XFA";
+ break;
+#endif
+ case FPDF_UNSP_DOC_PORTABLECOLLECTION:
+ feature = "Portfolios_Packages";
+ break;
+ case FPDF_UNSP_DOC_ATTACHMENT:
+ case FPDF_UNSP_ANNOT_ATTACHMENT:
+ feature = "Attachment";
+ break;
+ case FPDF_UNSP_DOC_SECURITY:
+ feature = "Rights_Management";
+ break;
+ case FPDF_UNSP_DOC_SHAREDREVIEW:
+ feature = "Shared_Review";
+ break;
+ case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT:
+ case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM:
+ case FPDF_UNSP_DOC_SHAREDFORM_EMAIL:
+ feature = "Shared_Form";
+ break;
+ case FPDF_UNSP_ANNOT_3DANNOT:
+ feature = "3D";
+ break;
+ case FPDF_UNSP_ANNOT_MOVIE:
+ feature = "Movie";
+ break;
+ case FPDF_UNSP_ANNOT_SOUND:
+ feature = "Sound";
+ break;
+ case FPDF_UNSP_ANNOT_SCREEN_MEDIA:
+ case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA:
+ feature = "Screen";
+ break;
+ case FPDF_UNSP_ANNOT_SIG:
+ feature = "Digital_Signature";
+ break;
+ }
+ client_->DocumentHasUnsupportedFeature(feature);
+}
+
+void PDFiumEngine::ContinueFind(int32_t result) {
+ StartFind(current_find_text_, result != 0);
+}
+
+bool PDFiumEngine::HandleEvent(const pp::InputEvent& event) {
+ DCHECK(!defer_page_unload_);
+ defer_page_unload_ = true;
+ bool rv = false;
+ switch (event.GetType()) {
+ case PP_INPUTEVENT_TYPE_MOUSEDOWN:
+ rv = OnMouseDown(pp::MouseInputEvent(event));
+ break;
+ case PP_INPUTEVENT_TYPE_MOUSEUP:
+ rv = OnMouseUp(pp::MouseInputEvent(event));
+ break;
+ case PP_INPUTEVENT_TYPE_MOUSEMOVE:
+ rv = OnMouseMove(pp::MouseInputEvent(event));
+ break;
+ case PP_INPUTEVENT_TYPE_KEYDOWN:
+ rv = OnKeyDown(pp::KeyboardInputEvent(event));
+ break;
+ case PP_INPUTEVENT_TYPE_KEYUP:
+ rv = OnKeyUp(pp::KeyboardInputEvent(event));
+ break;
+ case PP_INPUTEVENT_TYPE_CHAR:
+ rv = OnChar(pp::KeyboardInputEvent(event));
+ break;
+ default:
+ break;
+ }
+
+ DCHECK(defer_page_unload_);
+ defer_page_unload_ = false;
+ for (int page_index : deferred_page_unloads_)
+ pages_[page_index]->Unload();
+ deferred_page_unloads_.clear();
+ return rv;
+}
+
+uint32_t PDFiumEngine::QuerySupportedPrintOutputFormats() {
+ if (!HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY))
+ return 0;
+ return PP_PRINTOUTPUTFORMAT_PDF;
+}
+
+void PDFiumEngine::PrintBegin() {
+ FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_WP);
+}
+
+pp::Resource PDFiumEngine::PrintPages(
+ const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
+ const PP_PrintSettings_Dev& print_settings) {
+ if (HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY))
+ return PrintPagesAsPDF(page_ranges, page_range_count, print_settings);
+ else if (HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY))
+ return PrintPagesAsRasterPDF(page_ranges, page_range_count, print_settings);
+ return pp::Resource();
+}
+
+FPDF_DOCUMENT PDFiumEngine::CreateSinglePageRasterPdf(
+ double source_page_width,
+ double source_page_height,
+ const PP_PrintSettings_Dev& print_settings,
+ PDFiumPage* page_to_print) {
+ FPDF_DOCUMENT temp_doc = FPDF_CreateNewDocument();
+ if (!temp_doc)
+ return temp_doc;
+
+ const pp::Size& bitmap_size(page_to_print->rect().size());
+
+ FPDF_PAGE temp_page =
+ FPDFPage_New(temp_doc, 0, source_page_width, source_page_height);
+
+ pp::ImageData image = pp::ImageData(client_->GetPluginInstance(),
+ PP_IMAGEDATAFORMAT_BGRA_PREMUL,
+ bitmap_size,
+ false);
+
+ FPDF_BITMAP bitmap = FPDFBitmap_CreateEx(bitmap_size.width(),
+ bitmap_size.height(),
+ FPDFBitmap_BGRx,
+ image.data(),
+ image.stride());
+
+ // Clear the bitmap
+ FPDFBitmap_FillRect(
+ bitmap, 0, 0, bitmap_size.width(), bitmap_size.height(), 0xFFFFFFFF);
+
+ pp::Rect page_rect = page_to_print->rect();
+ FPDF_RenderPageBitmap(bitmap,
+ page_to_print->GetPrintPage(),
+ page_rect.x(),
+ page_rect.y(),
+ page_rect.width(),
+ page_rect.height(),
+ print_settings.orientation,
+ FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
+
+ double ratio_x = ConvertUnitDouble(bitmap_size.width(),
+ print_settings.dpi,
+ kPointsPerInch);
+ double ratio_y = ConvertUnitDouble(bitmap_size.height(),
+ print_settings.dpi,
+ kPointsPerInch);
+
+ // Add the bitmap to an image object and add the image object to the output
+ // page.
+ FPDF_PAGEOBJECT temp_img = FPDFPageObj_NewImgeObj(temp_doc);
+ FPDFImageObj_SetBitmap(&temp_page, 1, temp_img, bitmap);
+ FPDFImageObj_SetMatrix(temp_img, ratio_x, 0, 0, ratio_y, 0, 0);
+ FPDFPage_InsertObject(temp_page, temp_img);
+ FPDFPage_GenerateContent(temp_page);
+ FPDF_ClosePage(temp_page);
+
+ page_to_print->ClosePrintPage();
+ FPDFBitmap_Destroy(bitmap);
+
+ return temp_doc;
+}
+
+pp::Buffer_Dev PDFiumEngine::PrintPagesAsRasterPDF(
+ const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
+ const PP_PrintSettings_Dev& print_settings) {
+ if (!page_range_count)
+ return pp::Buffer_Dev();
+
+ // If document is not downloaded yet, disable printing.
+ if (doc_ && !doc_loader_.IsDocumentComplete())
+ return pp::Buffer_Dev();
+
+ FPDF_DOCUMENT output_doc = FPDF_CreateNewDocument();
+ if (!output_doc)
+ return pp::Buffer_Dev();
+
+ SaveSelectedFormForPrint();
+
+ std::vector<PDFiumPage> pages_to_print;
+ // width and height of source PDF pages.
+ std::vector<std::pair<double, double> > source_page_sizes;
+ // Collect pages to print and sizes of source pages.
+ std::vector<uint32_t> page_numbers =
+ GetPageNumbersFromPrintPageNumberRange(page_ranges, page_range_count);
+ for (uint32_t page_number : page_numbers) {
+ FPDF_PAGE pdf_page = FPDF_LoadPage(doc_, page_number);
+ double source_page_width = FPDF_GetPageWidth(pdf_page);
+ double source_page_height = FPDF_GetPageHeight(pdf_page);
+ source_page_sizes.push_back(std::make_pair(source_page_width,
+ source_page_height));
+
+ int width_in_pixels = ConvertUnit(source_page_width,
+ kPointsPerInch,
+ print_settings.dpi);
+ int height_in_pixels = ConvertUnit(source_page_height,
+ kPointsPerInch,
+ print_settings.dpi);
+
+ pp::Rect rect(width_in_pixels, height_in_pixels);
+ pages_to_print.push_back(PDFiumPage(this, page_number, rect, true));
+ FPDF_ClosePage(pdf_page);
+ }
+
+#if defined(OS_LINUX)
+ g_last_instance_id = client_->GetPluginInstance()->pp_instance();
+#endif
+
+ size_t i = 0;
+ for (; i < pages_to_print.size(); ++i) {
+ double source_page_width = source_page_sizes[i].first;
+ double source_page_height = source_page_sizes[i].second;
+
+ // Use temp_doc to compress image by saving PDF to buffer.
+ FPDF_DOCUMENT temp_doc = CreateSinglePageRasterPdf(source_page_width,
+ source_page_height,
+ print_settings,
+ &pages_to_print[i]);
+
+ if (!temp_doc)
+ break;
+
+ pp::Buffer_Dev buffer = GetFlattenedPrintData(temp_doc);
+ FPDF_CloseDocument(temp_doc);
+
+ PDFiumMemBufferFileRead file_read(buffer.data(), buffer.size());
+ temp_doc = FPDF_LoadCustomDocument(&file_read, NULL);
+
+ FPDF_BOOL imported = FPDF_ImportPages(output_doc, temp_doc, "1", i);
+ FPDF_CloseDocument(temp_doc);
+ if (!imported)
+ break;
+ }
+
+ pp::Buffer_Dev buffer;
+ if (i == pages_to_print.size()) {
+ FPDF_CopyViewerPreferences(output_doc, doc_);
+ FitContentsToPrintableAreaIfRequired(output_doc, print_settings);
+ // Now flatten all the output pages.
+ buffer = GetFlattenedPrintData(output_doc);
+ }
+ FPDF_CloseDocument(output_doc);
+ return buffer;
+}
+
+pp::Buffer_Dev PDFiumEngine::GetFlattenedPrintData(const FPDF_DOCUMENT& doc) {
+ pp::Buffer_Dev buffer;
+ int page_count = FPDF_GetPageCount(doc);
+ for (int i = 0; i < page_count; ++i) {
+ FPDF_PAGE page = FPDF_LoadPage(doc, i);
+ DCHECK(page);
+ int flatten_ret = FPDFPage_Flatten(page, FLAT_PRINT);
+ FPDF_ClosePage(page);
+ if (flatten_ret == FLATTEN_FAIL)
+ return buffer;
+ }
+
+ PDFiumMemBufferFileWrite output_file_write;
+ if (FPDF_SaveAsCopy(doc, &output_file_write, 0)) {
+ buffer = pp::Buffer_Dev(
+ client_->GetPluginInstance(), output_file_write.size());
+ if (!buffer.is_null()) {
+ memcpy(buffer.data(), output_file_write.buffer().c_str(),
+ output_file_write.size());
+ }
+ }
+ return buffer;
+}
+
+pp::Buffer_Dev PDFiumEngine::PrintPagesAsPDF(
+ const PP_PrintPageNumberRange_Dev* page_ranges, uint32_t page_range_count,
+ const PP_PrintSettings_Dev& print_settings) {
+ if (!page_range_count)
+ return pp::Buffer_Dev();
+
+ DCHECK(doc_);
+ FPDF_DOCUMENT output_doc = FPDF_CreateNewDocument();
+ if (!output_doc)
+ return pp::Buffer_Dev();
+
+ SaveSelectedFormForPrint();
+
+ std::string page_number_str;
+ for (uint32_t index = 0; index < page_range_count; ++index) {
+ if (!page_number_str.empty())
+ page_number_str.append(",");
+ page_number_str.append(
+ base::UintToString(page_ranges[index].first_page_number + 1));
+ if (page_ranges[index].first_page_number !=
+ page_ranges[index].last_page_number) {
+ page_number_str.append("-");
+ page_number_str.append(
+ base::UintToString(page_ranges[index].last_page_number + 1));
+ }
+ }
+
+ std::vector<uint32_t> page_numbers =
+ GetPageNumbersFromPrintPageNumberRange(page_ranges, page_range_count);
+ for (uint32_t page_number : page_numbers) {
+ pages_[page_number]->GetPage();
+ if (!IsPageVisible(page_number))
+ pages_[page_number]->Unload();
+ }
+
+ FPDF_CopyViewerPreferences(output_doc, doc_);
+ if (!FPDF_ImportPages(output_doc, doc_, page_number_str.c_str(), 0)) {
+ FPDF_CloseDocument(output_doc);
+ return pp::Buffer_Dev();
+ }
+
+ FitContentsToPrintableAreaIfRequired(output_doc, print_settings);
+
+ // Now flatten all the output pages.
+ pp::Buffer_Dev buffer = GetFlattenedPrintData(output_doc);
+ FPDF_CloseDocument(output_doc);
+ return buffer;
+}
+
+void PDFiumEngine::FitContentsToPrintableAreaIfRequired(
+ const FPDF_DOCUMENT& doc, const PP_PrintSettings_Dev& print_settings) {
+ // Check to see if we need to fit pdf contents to printer paper size.
+ if (print_settings.print_scaling_option !=
+ PP_PRINTSCALINGOPTION_SOURCE_SIZE) {
+ int num_pages = FPDF_GetPageCount(doc);
+ // In-place transformation is more efficient than creating a new
+ // transformed document from the source document. Therefore, transform
+ // every page to fit the contents in the selected printer paper.
+ for (int i = 0; i < num_pages; ++i) {
+ FPDF_PAGE page = FPDF_LoadPage(doc, i);
+ TransformPDFPageForPrinting(page, print_settings);
+ FPDF_ClosePage(page);
+ }
+ }
+}
+
+void PDFiumEngine::SaveSelectedFormForPrint() {
+ FORM_ForceToKillFocus(form_);
+ client_->FormTextFieldFocusChange(false);
+}
+
+void PDFiumEngine::PrintEnd() {
+ FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_DP);
+}
+
+PDFiumPage::Area PDFiumEngine::GetCharIndex(const pp::MouseInputEvent& event,
+ int* page_index,
+ int* char_index,
+ int* form_type,
+ PDFiumPage::LinkTarget* target) {
+ // First figure out which page this is in.
+ pp::Point mouse_point = event.GetPosition();
+ return GetCharIndex(mouse_point, page_index, char_index, form_type, target);
+}
+
+PDFiumPage::Area PDFiumEngine::GetCharIndex(const pp::Point& point,
+ int* page_index,
+ int* char_index,
+ int* form_type,
+ PDFiumPage::LinkTarget* target) {
+ int page = -1;
+ pp::Point point_in_page(
+ static_cast<int>((point.x() + position_.x()) / current_zoom_),
+ static_cast<int>((point.y() + position_.y()) / current_zoom_));
+ for (int visible_page : visible_pages_) {
+ if (pages_[visible_page]->rect().Contains(point_in_page)) {
+ page = visible_page;
+ break;
+ }
+ }
+ if (page == -1)
+ return PDFiumPage::NONSELECTABLE_AREA;
+
+ // If the page hasn't finished rendering, calling into the page sometimes
+ // leads to hangs.
+ for (const auto& paint : progressive_paints_) {
+ if (paint.page_index == page)
+ return PDFiumPage::NONSELECTABLE_AREA;
+ }
+
+ *page_index = page;
+ return pages_[page]->GetCharIndex(
+ point_in_page, current_rotation_, char_index, form_type, target);
+}
+
+bool PDFiumEngine::OnMouseDown(const pp::MouseInputEvent& event) {
+ if (event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_RIGHT) {
+ if (selection_.empty())
+ return false;
+ std::vector<pp::Rect> selection_rect_vector;
+ GetAllScreenRectsUnion(&selection_, GetVisibleRect().point(),
+ &selection_rect_vector);
+ pp::Point point = event.GetPosition();
+ for (const auto& rect : selection_rect_vector) {
+ if (rect.Contains(point.x(), point.y()))
+ return false;
+ }
+ SelectionChangeInvalidator selection_invalidator(this);
+ selection_.clear();
+ return true;
+ }
+ if (event.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT)
+ return false;
+
+ SelectionChangeInvalidator selection_invalidator(this);
+ selection_.clear();
+
+ int page_index = -1;
+ int char_index = -1;
+ int form_type = FPDF_FORMFIELD_UNKNOWN;
+ PDFiumPage::LinkTarget target;
+ PDFiumPage::Area area =
+ GetCharIndex(event, &page_index, &char_index, &form_type, &target);
+ mouse_down_state_.Set(area, target);
+
+ // Decide whether to open link or not based on user action in mouse up and
+ // mouse move events.
+ if (area == PDFiumPage::WEBLINK_AREA)
+ return true;
+
+ if (area == PDFiumPage::DOCLINK_AREA) {
+ client_->ScrollToPage(target.page);
+ client_->FormTextFieldFocusChange(false);
+ return true;
+ }
+
+ if (page_index != -1) {
+ last_page_mouse_down_ = page_index;
+ double page_x, page_y;
+ pp::Point point = event.GetPosition();
+ DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
+
+ FORM_OnLButtonDown(form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
+ if (form_type > FPDF_FORMFIELD_UNKNOWN) { // returns -1 sometimes...
+ mouse_down_state_.Set(PDFiumPage::NONSELECTABLE_AREA, target);
+ bool is_valid_control = (form_type == FPDF_FORMFIELD_TEXTFIELD ||
+ form_type == FPDF_FORMFIELD_COMBOBOX);
+#ifdef PDF_USE_XFA
+ is_valid_control |= (form_type == FPDF_FORMFIELD_XFA);
+#endif
+ client_->FormTextFieldFocusChange(is_valid_control);
+ return true; // Return now before we get into the selection code.
+ }
+ }
+
+ client_->FormTextFieldFocusChange(false);
+
+ if (area != PDFiumPage::TEXT_AREA)
+ return true; // Return true so WebKit doesn't do its own highlighting.
+
+ if (event.GetClickCount() == 1) {
+ OnSingleClick(page_index, char_index);
+ } else if (event.GetClickCount() == 2 ||
+ event.GetClickCount() == 3) {
+ OnMultipleClick(event.GetClickCount(), page_index, char_index);
+ }
+
+ return true;
+}
+
+void PDFiumEngine::OnSingleClick(int page_index, int char_index) {
+ SetSelecting(true);
+ selection_.push_back(PDFiumRange(pages_[page_index], char_index, 0));
+}
+
+void PDFiumEngine::OnMultipleClick(int click_count,
+ int page_index,
+ int char_index) {
+ // It would be more efficient if the SDK could support finding a space, but
+ // now it doesn't.
+ int start_index = char_index;
+ do {
+ base::char16 cur = pages_[page_index]->GetCharAtIndex(start_index);
+ // For double click, we want to select one word so we look for whitespace
+ // boundaries. For triple click, we want the whole line.
+ if (cur == '\n' || (click_count == 2 && (cur == ' ' || cur == '\t')))
+ break;
+ } while (--start_index >= 0);
+ if (start_index)
+ start_index++;
+
+ int end_index = char_index;
+ int total = pages_[page_index]->GetCharCount();
+ while (end_index++ <= total) {
+ base::char16 cur = pages_[page_index]->GetCharAtIndex(end_index);
+ if (cur == '\n' || (click_count == 2 && (cur == ' ' || cur == '\t')))
+ break;
+ }
+
+ selection_.push_back(PDFiumRange(
+ pages_[page_index], start_index, end_index - start_index));
+}
+
+bool PDFiumEngine::OnMouseUp(const pp::MouseInputEvent& event) {
+ if (event.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT)
+ return false;
+
+ int page_index = -1;
+ int char_index = -1;
+ int form_type = FPDF_FORMFIELD_UNKNOWN;
+ PDFiumPage::LinkTarget target;
+ PDFiumPage::Area area =
+ GetCharIndex(event, &page_index, &char_index, &form_type, &target);
+
+ // Open link on mouse up for same link for which mouse down happened earlier.
+ if (mouse_down_state_.Matches(area, target)) {
+ if (area == PDFiumPage::WEBLINK_AREA) {
+ bool open_in_new_tab = !!(event.GetModifiers() & kDefaultKeyModifier);
+ client_->NavigateTo(target.url, open_in_new_tab);
+ client_->FormTextFieldFocusChange(false);
+ return true;
+ }
+ }
+
+ if (page_index != -1) {
+ double page_x, page_y;
+ pp::Point point = event.GetPosition();
+ DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
+ FORM_OnLButtonUp(
+ form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
+ }
+
+ if (!selecting_)
+ return false;
+
+ SetSelecting(false);
+ return true;
+}
+
+bool PDFiumEngine::OnMouseMove(const pp::MouseInputEvent& event) {
+ int page_index = -1;
+ int char_index = -1;
+ int form_type = FPDF_FORMFIELD_UNKNOWN;
+ PDFiumPage::LinkTarget target;
+ PDFiumPage::Area area =
+ GetCharIndex(event, &page_index, &char_index, &form_type, &target);
+
+ // Clear |mouse_down_state_| if mouse moves away from where the mouse down
+ // happened.
+ if (!mouse_down_state_.Matches(area, target))
+ mouse_down_state_.Reset();
+
+ if (!selecting_) {
+ PP_CursorType_Dev cursor;
+ switch (area) {
+ case PDFiumPage::TEXT_AREA:
+ cursor = PP_CURSORTYPE_IBEAM;
+ break;
+ case PDFiumPage::WEBLINK_AREA:
+ case PDFiumPage::DOCLINK_AREA:
+ cursor = PP_CURSORTYPE_HAND;
+ break;
+ case PDFiumPage::NONSELECTABLE_AREA:
+ default:
+ switch (form_type) {
+ case FPDF_FORMFIELD_PUSHBUTTON:
+ case FPDF_FORMFIELD_CHECKBOX:
+ case FPDF_FORMFIELD_RADIOBUTTON:
+ case FPDF_FORMFIELD_COMBOBOX:
+ case FPDF_FORMFIELD_LISTBOX:
+ cursor = PP_CURSORTYPE_HAND;
+ break;
+ case FPDF_FORMFIELD_TEXTFIELD:
+ cursor = PP_CURSORTYPE_IBEAM;
+ break;
+ default:
+ cursor = PP_CURSORTYPE_POINTER;
+ break;
+ }
+ break;
+ }
+
+ if (page_index != -1) {
+ double page_x, page_y;
+ pp::Point point = event.GetPosition();
+ DeviceToPage(page_index, point.x(), point.y(), &page_x, &page_y);
+ FORM_OnMouseMove(form_, pages_[page_index]->GetPage(), 0, page_x, page_y);
+ }
+
+ client_->UpdateCursor(cursor);
+ pp::Point point = event.GetPosition();
+ std::string url = GetLinkAtPosition(event.GetPosition());
+ if (url != link_under_cursor_) {
+ link_under_cursor_ = url;
+ pp::PDF::SetLinkUnderCursor(GetPluginInstance(), url.c_str());
+ }
+ // No need to swallow the event, since this might interfere with the
+ // scrollbars if the user is dragging them.
+ return false;
+ }
+
+ // We're selecting but right now we're not over text, so don't change the
+ // current selection.
+ if (area != PDFiumPage::TEXT_AREA && area != PDFiumPage::WEBLINK_AREA &&
+ area != PDFiumPage::DOCLINK_AREA) {
+ return false;
+ }
+
+ SelectionChangeInvalidator selection_invalidator(this);
+
+ // Check if the user has descreased their selection area and we need to remove
+ // pages from selection_.
+ for (size_t i = 0; i < selection_.size(); ++i) {
+ if (selection_[i].page_index() == page_index) {
+ // There should be no other pages after this.
+ selection_.erase(selection_.begin() + i + 1, selection_.end());
+ break;
+ }
+ }
+
+ if (selection_.empty())
+ return false;
+
+ int last = selection_.size() - 1;
+ if (selection_[last].page_index() == page_index) {
+ // Selecting within a page.
+ int count;
+ if (char_index >= selection_[last].char_index()) {
+ // Selecting forward.
+ count = char_index - selection_[last].char_index() + 1;
+ } else {
+ count = char_index - selection_[last].char_index() - 1;
+ }
+ selection_[last].SetCharCount(count);
+ } else if (selection_[last].page_index() < page_index) {
+ // Selecting into the next page.
+
+ // First make sure that there are no gaps in selection, i.e. if mousedown on
+ // page one but we only get mousemove over page three, we want page two.
+ for (int i = selection_[last].page_index() + 1; i < page_index; ++i) {
+ selection_.push_back(PDFiumRange(pages_[i], 0,
+ pages_[i]->GetCharCount()));
+ }
+
+ int count = pages_[selection_[last].page_index()]->GetCharCount();
+ selection_[last].SetCharCount(count - selection_[last].char_index());
+ selection_.push_back(PDFiumRange(pages_[page_index], 0, char_index));
+ } else {
+ // Selecting into the previous page.
+ // The selection's char_index is 0-based, so the character count is one
+ // more than the index. The character count needs to be negative to
+ // indicate a backwards selection.
+ selection_[last].SetCharCount(-(selection_[last].char_index() + 1));
+
+ // First make sure that there are no gaps in selection, i.e. if mousedown on
+ // page three but we only get mousemove over page one, we want page two.
+ for (int i = selection_[last].page_index() - 1; i > page_index; --i) {
+ selection_.push_back(PDFiumRange(pages_[i], 0,
+ pages_[i]->GetCharCount()));
+ }
+
+ int count = pages_[page_index]->GetCharCount();
+ selection_.push_back(
+ PDFiumRange(pages_[page_index], count, count - char_index));
+ }
+
+ return true;
+}
+
+bool PDFiumEngine::OnKeyDown(const pp::KeyboardInputEvent& event) {
+ if (last_page_mouse_down_ == -1)
+ return false;
+
+ bool rv = !!FORM_OnKeyDown(
+ form_, pages_[last_page_mouse_down_]->GetPage(),
+ event.GetKeyCode(), event.GetModifiers());
+
+ if (event.GetKeyCode() == ui::VKEY_BACK ||
+ event.GetKeyCode() == ui::VKEY_ESCAPE) {
+ // Chrome doesn't send char events for backspace or escape keys, see
+ // PlatformKeyboardEventBuilder::isCharacterKey() and
+ // http://chrome-corpsvn.mtv.corp.google.com/viewvc?view=rev&root=chrome&revision=31805
+ // for more information. So just fake one since PDFium uses it.
+ std::string str;
+ str.push_back(event.GetKeyCode());
+ pp::KeyboardInputEvent synthesized(pp::KeyboardInputEvent(
+ client_->GetPluginInstance(),
+ PP_INPUTEVENT_TYPE_CHAR,
+ event.GetTimeStamp(),
+ event.GetModifiers(),
+ event.GetKeyCode(),
+ str));
+ OnChar(synthesized);
+ }
+
+ return rv;
+}
+
+bool PDFiumEngine::OnKeyUp(const pp::KeyboardInputEvent& event) {
+ if (last_page_mouse_down_ == -1)
+ return false;
+
+ return !!FORM_OnKeyUp(
+ form_, pages_[last_page_mouse_down_]->GetPage(),
+ event.GetKeyCode(), event.GetModifiers());
+}
+
+bool PDFiumEngine::OnChar(const pp::KeyboardInputEvent& event) {
+ if (last_page_mouse_down_ == -1)
+ return false;
+
+ base::string16 str = base::UTF8ToUTF16(event.GetCharacterText().AsString());
+ return !!FORM_OnChar(
+ form_, pages_[last_page_mouse_down_]->GetPage(),
+ str[0],
+ event.GetModifiers());
+}
+
+void PDFiumEngine::StartFind(const std::string& text, bool case_sensitive) {
+ // If the caller asks StartFind() to search for no text, then this is an
+ // error on the part of the caller. The PPAPI Find_Private interface
+ // guarantees it is not empty, so this should never happen.
+ DCHECK(!text.empty());
+
+ // If StartFind() gets called before we have any page information (i.e.
+ // before the first call to LoadDocument has happened). Handle this case.
+ if (pages_.empty())
+ return;
+
+ bool first_search = (current_find_text_ != text);
+ int character_to_start_searching_from = 0;
+ if (first_search) {
+ std::vector<PDFiumRange> old_selection = selection_;
+ StopFind();
+ current_find_text_ = text;
+
+ if (old_selection.empty()) {
+ // Start searching from the beginning of the document.
+ next_page_to_search_ = 0;
+ last_page_to_search_ = pages_.size() - 1;
+ last_character_index_to_search_ = -1;
+ } else {
+ // There's a current selection, so start from it.
+ next_page_to_search_ = old_selection[0].page_index();
+ last_character_index_to_search_ = old_selection[0].char_index();
+ character_to_start_searching_from = old_selection[0].char_index();
+ last_page_to_search_ = next_page_to_search_;
+ }
+ }
+
+ int current_page = next_page_to_search_;
+
+ if (pages_[current_page]->available()) {
+ base::string16 str = base::UTF8ToUTF16(text);
+ // Don't use PDFium to search for now, since it doesn't support unicode
+ // text. Leave the code for now to avoid bit-rot, in case it's fixed later.
+ if (0) {
+ SearchUsingPDFium(
+ str, case_sensitive, first_search, character_to_start_searching_from,
+ current_page);
+ } else {
+ SearchUsingICU(
+ str, case_sensitive, first_search, character_to_start_searching_from,
+ current_page);
+ }
+
+ if (!IsPageVisible(current_page))
+ pages_[current_page]->Unload();
+ }
+
+ if (next_page_to_search_ != last_page_to_search_ ||
+ (first_search && last_character_index_to_search_ != -1)) {
+ ++next_page_to_search_;
+ }
+
+ if (next_page_to_search_ == static_cast<int>(pages_.size()))
+ next_page_to_search_ = 0;
+ // If there's only one page in the document and we start searching midway,
+ // then we'll want to search the page one more time.
+ bool end_of_search =
+ next_page_to_search_ == last_page_to_search_ &&
+ // Only one page but didn't start midway.
+ ((pages_.size() == 1 && last_character_index_to_search_ == -1) ||
+ // Started midway, but only 1 page and we already looped around.
+ (pages_.size() == 1 && !first_search) ||
+ // Started midway, and we've just looped around.
+ (pages_.size() > 1 && current_page == next_page_to_search_));
+
+ if (end_of_search) {
+ // Send the final notification.
+ client_->NotifyNumberOfFindResultsChanged(find_results_.size(), true);
+
+ // When searching is complete, resume finding at a particular index.
+ // Assuming the user has not clicked the find button in the meanwhile.
+ if (resume_find_index_.valid() && !current_find_index_.valid()) {
+ size_t resume_index = resume_find_index_.GetIndex();
+ if (resume_index >= find_results_.size()) {
+ // This might happen if the PDF has some dynamically generated text?
+ resume_index = 0;
+ }
+ current_find_index_.SetIndex(resume_index);
+ client_->NotifySelectedFindResultChanged(resume_index);
+ }
+ resume_find_index_.Invalidate();
+ } else {
+ pp::CompletionCallback callback =
+ find_factory_.NewCallback(&PDFiumEngine::ContinueFind);
+ pp::Module::Get()->core()->CallOnMainThread(
+ 0, callback, case_sensitive ? 1 : 0);
+ }
+}
+
+void PDFiumEngine::SearchUsingPDFium(const base::string16& term,
+ bool case_sensitive,
+ bool first_search,
+ int character_to_start_searching_from,
+ int current_page) {
+ // Find all the matches in the current page.
+ unsigned long flags = case_sensitive ? FPDF_MATCHCASE : 0;
+ FPDF_SCHHANDLE find = FPDFText_FindStart(
+ pages_[current_page]->GetTextPage(),
+ reinterpret_cast<const unsigned short*>(term.c_str()),
+ flags, character_to_start_searching_from);
+
+ // Note: since we search one page at a time, we don't find matches across
+ // page boundaries. We could do this manually ourself, but it seems low
+ // priority since Reader itself doesn't do it.
+ while (FPDFText_FindNext(find)) {
+ PDFiumRange result(pages_[current_page],
+ FPDFText_GetSchResultIndex(find),
+ FPDFText_GetSchCount(find));
+
+ if (!first_search &&
+ last_character_index_to_search_ != -1 &&
+ result.page_index() == last_page_to_search_ &&
+ result.char_index() >= last_character_index_to_search_) {
+ break;
+ }
+
+ AddFindResult(result);
+ }
+
+ FPDFText_FindClose(find);
+}
+
+void PDFiumEngine::SearchUsingICU(const base::string16& term,
+ bool case_sensitive,
+ bool first_search,
+ int character_to_start_searching_from,
+ int current_page) {
+ base::string16 page_text;
+ int text_length = pages_[current_page]->GetCharCount();
+ if (character_to_start_searching_from) {
+ text_length -= character_to_start_searching_from;
+ } else if (!first_search &&
+ last_character_index_to_search_ != -1 &&
+ current_page == last_page_to_search_) {
+ text_length = last_character_index_to_search_;
+ }
+ if (text_length <= 0)
+ return;
+
+ PDFiumAPIStringBufferAdapter<base::string16> api_string_adapter(&page_text,
+ text_length,
+ false);
+ unsigned short* data =
+ reinterpret_cast<unsigned short*>(api_string_adapter.GetData());
+ int written = FPDFText_GetText(pages_[current_page]->GetTextPage(),
+ character_to_start_searching_from,
+ text_length,
+ data);
+ api_string_adapter.Close(written);
+
+ std::vector<PDFEngine::Client::SearchStringResult> results;
+ client_->SearchString(
+ page_text.c_str(), term.c_str(), case_sensitive, &results);
+ for (const auto& result : results) {
+ // Need to map the indexes from the page text, which may have generated
+ // characters like space etc, to character indices from the page.
+ int temp_start = result.start_index + character_to_start_searching_from;
+ int start = FPDFText_GetCharIndexFromTextIndex(
+ pages_[current_page]->GetTextPage(), temp_start);
+ int end = FPDFText_GetCharIndexFromTextIndex(
+ pages_[current_page]->GetTextPage(),
+ temp_start + result.length);
+ AddFindResult(PDFiumRange(pages_[current_page], start, end - start));
+ }
+}
+
+void PDFiumEngine::AddFindResult(const PDFiumRange& result) {
+ // Figure out where to insert the new location, since we could have
+ // started searching midway and now we wrapped.
+ size_t result_index;
+ int page_index = result.page_index();
+ int char_index = result.char_index();
+ for (result_index = 0; result_index < find_results_.size(); ++result_index) {
+ if (find_results_[result_index].page_index() > page_index ||
+ (find_results_[result_index].page_index() == page_index &&
+ find_results_[result_index].char_index() > char_index)) {
+ break;
+ }
+ }
+ find_results_.insert(find_results_.begin() + result_index, result);
+ UpdateTickMarks();
+
+ if (current_find_index_.valid()) {
+ if (result_index <= current_find_index_.GetIndex()) {
+ // Update the current match index
+ size_t find_index = current_find_index_.IncrementIndex();
+ DCHECK_LT(find_index, find_results_.size());
+ client_->NotifySelectedFindResultChanged(current_find_index_.GetIndex());
+ }
+ } else if (!resume_find_index_.valid()) {
+ // Both indices are invalid. Select the first match.
+ SelectFindResult(true);
+ }
+ client_->NotifyNumberOfFindResultsChanged(find_results_.size(), false);
+}
+
+bool PDFiumEngine::SelectFindResult(bool forward) {
+ if (find_results_.empty()) {
+ NOTREACHED();
+ return false;
+ }
+
+ SelectionChangeInvalidator selection_invalidator(this);
+
+ // Move back/forward through the search locations we previously found.
+ size_t new_index;
+ const size_t last_index = find_results_.size() - 1;
+ if (current_find_index_.valid()) {
+ size_t current_index = current_find_index_.GetIndex();
+ if (forward) {
+ new_index = (current_index >= last_index) ? 0 : current_index + 1;
+ } else {
+ new_index = (current_find_index_.GetIndex() == 0) ?
+ last_index : current_index - 1;
+ }
+ } else {
+ new_index = forward ? 0 : last_index;
+ }
+ current_find_index_.SetIndex(new_index);
+
+ // Update the selection before telling the client to scroll, since it could
+ // paint then.
+ selection_.clear();
+ selection_.push_back(find_results_[current_find_index_.GetIndex()]);
+
+ // If the result is not in view, scroll to it.
+ pp::Rect bounding_rect;
+ pp::Rect visible_rect = GetVisibleRect();
+ // Use zoom of 1.0 since visible_rect is without zoom.
+ std::vector<pp::Rect> rects;
+ rects = find_results_[current_find_index_.GetIndex()].GetScreenRects(
+ pp::Point(), 1.0, current_rotation_);
+ for (const auto& rect : rects)
+ bounding_rect = bounding_rect.Union(rect);
+ if (!visible_rect.Contains(bounding_rect)) {
+ pp::Point center = bounding_rect.CenterPoint();
+ // Make the page centered.
+ int new_y = static_cast<int>(center.y() * current_zoom_) -
+ static_cast<int>(visible_rect.height() * current_zoom_ / 2);
+ if (new_y < 0)
+ new_y = 0;
+ client_->ScrollToY(new_y);
+
+ // Only move horizontally if it's not visible.
+ if (center.x() < visible_rect.x() || center.x() > visible_rect.right()) {
+ int new_x = static_cast<int>(center.x() * current_zoom_) -
+ static_cast<int>(visible_rect.width() * current_zoom_ / 2);
+ if (new_x < 0)
+ new_x = 0;
+ client_->ScrollToX(new_x);
+ }
+ }
+
+ client_->NotifySelectedFindResultChanged(current_find_index_.GetIndex());
+ return true;
+}
+
+void PDFiumEngine::StopFind() {
+ SelectionChangeInvalidator selection_invalidator(this);
+
+ selection_.clear();
+ selecting_ = false;
+ find_results_.clear();
+ next_page_to_search_ = -1;
+ last_page_to_search_ = -1;
+ last_character_index_to_search_ = -1;
+ current_find_index_.Invalidate();
+ current_find_text_.clear();
+ UpdateTickMarks();
+ find_factory_.CancelAll();
+}
+
+void PDFiumEngine::GetAllScreenRectsUnion(std::vector<PDFiumRange>* rect_range,
+ const pp::Point& offset_point,
+ std::vector<pp::Rect>* rect_vector) {
+ for (auto& range : *rect_range) {
+ pp::Rect result_rect;
+ std::vector<pp::Rect> rects =
+ range.GetScreenRects(offset_point, current_zoom_, current_rotation_);
+ for (const auto& rect : rects)
+ result_rect = result_rect.Union(rect);
+ rect_vector->push_back(result_rect);
+ }
+}
+
+void PDFiumEngine::UpdateTickMarks() {
+ std::vector<pp::Rect> tickmarks;
+ GetAllScreenRectsUnion(&find_results_, pp::Point(0, 0), &tickmarks);
+ client_->UpdateTickMarks(tickmarks);
+}
+
+void PDFiumEngine::ZoomUpdated(double new_zoom_level) {
+ CancelPaints();
+
+ current_zoom_ = new_zoom_level;
+
+ CalculateVisiblePages();
+ UpdateTickMarks();
+}
+
+void PDFiumEngine::RotateClockwise() {
+ current_rotation_ = (current_rotation_ + 1) % 4;
+ RotateInternal();
+}
+
+void PDFiumEngine::RotateCounterclockwise() {
+ current_rotation_ = (current_rotation_ - 1) % 4;
+ RotateInternal();
+}
+
+void PDFiumEngine::InvalidateAllPages() {
+ CancelPaints();
+ StopFind();
+ LoadPageInfo(true);
+ client_->Invalidate(pp::Rect(plugin_size_));
+}
+
+std::string PDFiumEngine::GetSelectedText() {
+ if (!HasPermission(PDFEngine::PERMISSION_COPY))
+ return std::string();
+
+ base::string16 result;
+ base::string16 new_line_char = base::UTF8ToUTF16("\n");
+ for (size_t i = 0; i < selection_.size(); ++i) {
+ if (i > 0 &&
+ selection_[i - 1].page_index() > selection_[i].page_index()) {
+ result = selection_[i].GetText() + new_line_char + result;
+ } else {
+ if (i > 0)
+ result.append(new_line_char);
+ result.append(selection_[i].GetText());
+ }
+ }
+
+ FormatStringWithHyphens(&result);
+ FormatStringForOS(&result);
+ return base::UTF16ToUTF8(result);
+}
+
+std::string PDFiumEngine::GetLinkAtPosition(const pp::Point& point) {
+ std::string url;
+ int temp;
+ int page_index = -1;
+ int form_type = FPDF_FORMFIELD_UNKNOWN;
+ PDFiumPage::LinkTarget target;
+ PDFiumPage::Area area =
+ GetCharIndex(point, &page_index, &temp, &form_type, &target);
+ if (area == PDFiumPage::WEBLINK_AREA)
+ url = target.url;
+ return url;
+}
+
+bool PDFiumEngine::HasPermission(DocumentPermission permission) const {
+ // PDF 1.7 spec, section 3.5.2 says: "If the revision number is 2 or greater,
+ // the operations to which user access can be controlled are as follows: ..."
+ //
+ // Thus for revision numbers less than 2, permissions are ignored and this
+ // always returns true.
+ if (permissions_handler_revision_ < 2)
+ return true;
+
+ // Handle high quality printing permission separately for security handler
+ // revision 3+. See table 3.20 in the PDF 1.7 spec.
+ if (permission == PERMISSION_PRINT_HIGH_QUALITY &&
+ permissions_handler_revision_ >= 3) {
+ return (permissions_ & kPDFPermissionPrintLowQualityMask) != 0 &&
+ (permissions_ & kPDFPermissionPrintHighQualityMask) != 0;
+ }
+
+ switch (permission) {
+ case PERMISSION_COPY:
+ return (permissions_ & kPDFPermissionCopyMask) != 0;
+ case PERMISSION_COPY_ACCESSIBLE:
+ return (permissions_ & kPDFPermissionCopyAccessibleMask) != 0;
+ case PERMISSION_PRINT_LOW_QUALITY:
+ case PERMISSION_PRINT_HIGH_QUALITY:
+ // With security handler revision 2 rules, check the same bit for high
+ // and low quality. See table 3.20 in the PDF 1.7 spec.
+ return (permissions_ & kPDFPermissionPrintLowQualityMask) != 0;
+ default:
+ return true;
+ }
+}
+
+void PDFiumEngine::SelectAll() {
+ SelectionChangeInvalidator selection_invalidator(this);
+
+ selection_.clear();
+ for (const auto& page : pages_) {
+ if (page->available())
+ selection_.push_back(PDFiumRange(page, 0, page->GetCharCount()));
+ }
+}
+
+int PDFiumEngine::GetNumberOfPages() {
+ return pages_.size();
+}
+
+pp::VarArray PDFiumEngine::GetBookmarks() {
+ pp::VarDictionary dict = TraverseBookmarks(doc_, NULL, 0);
+ // The root bookmark contains no useful information.
+ return pp::VarArray(dict.Get(pp::Var("children")));
+}
+
+int PDFiumEngine::GetNamedDestinationPage(const std::string& destination) {
+ // Look for the destination.
+ FPDF_DEST dest = FPDF_GetNamedDestByName(doc_, destination.c_str());
+ if (!dest) {
+ // Look for a bookmark with the same name.
+ base::string16 destination_wide = base::UTF8ToUTF16(destination);
+ FPDF_WIDESTRING destination_pdf_wide =
+ reinterpret_cast<FPDF_WIDESTRING>(destination_wide.c_str());
+ FPDF_BOOKMARK bookmark = FPDFBookmark_Find(doc_, destination_pdf_wide);
+ if (!bookmark)
+ return -1;
+ dest = FPDFBookmark_GetDest(doc_, bookmark);
+ }
+ return dest ? FPDFDest_GetPageIndex(doc_, dest) : -1;
+}
+
+int PDFiumEngine::GetMostVisiblePage() {
+ CalculateVisiblePages();
+ return most_visible_page_;
+}
+
+pp::Rect PDFiumEngine::GetPageRect(int index) {
+ pp::Rect rc(pages_[index]->rect());
+ rc.Inset(-kPageShadowLeft, -kPageShadowTop,
+ -kPageShadowRight, -kPageShadowBottom);
+ return rc;
+}
+
+pp::Rect PDFiumEngine::GetPageContentsRect(int index) {
+ return GetScreenRect(pages_[index]->rect());
+}
+
+void PDFiumEngine::SetGrayscale(bool grayscale) {
+ render_grayscale_ = grayscale;
+}
+
+void PDFiumEngine::OnCallback(int id) {
+ if (!timers_.count(id))
+ return;
+
+ timers_[id].second(id);
+ if (timers_.count(id)) // The callback might delete the timer.
+ client_->ScheduleCallback(id, timers_[id].first);
+}
+
+std::string PDFiumEngine::GetPageAsJSON(int index) {
+ if (!(HasPermission(PERMISSION_COPY) ||
+ HasPermission(PERMISSION_COPY_ACCESSIBLE))) {
+ return "{}";
+ }
+
+ if (index < 0 || static_cast<size_t>(index) > pages_.size() - 1)
+ return "{}";
+
+ scoped_ptr<base::Value> node(
+ pages_[index]->GetAccessibleContentAsValue(current_rotation_));
+ std::string page_json;
+ base::JSONWriter::Write(*node, &page_json);
+ return page_json;
+}
+
+bool PDFiumEngine::GetPrintScaling() {
+ return !!FPDF_VIEWERREF_GetPrintScaling(doc_);
+}
+
+int PDFiumEngine::GetCopiesToPrint() {
+ return FPDF_VIEWERREF_GetNumCopies(doc_);
+}
+
+int PDFiumEngine::GetDuplexType() {
+ return static_cast<int>(FPDF_VIEWERREF_GetDuplex(doc_));
+}
+
+bool PDFiumEngine::GetPageSizeAndUniformity(pp::Size* size) {
+ if (pages_.empty())
+ return false;
+
+ pp::Size page_size = GetPageSize(0);
+ for (size_t i = 1; i < pages_.size(); ++i) {
+ if (page_size != GetPageSize(i))
+ return false;
+ }
+
+ // Convert |page_size| back to points.
+ size->set_width(
+ ConvertUnit(page_size.width(), kPixelsPerInch, kPointsPerInch));
+ size->set_height(
+ ConvertUnit(page_size.height(), kPixelsPerInch, kPointsPerInch));
+ return true;
+}
+
+void PDFiumEngine::AppendBlankPages(int num_pages) {
+ DCHECK_NE(num_pages, 0);
+
+ if (!doc_)
+ return;
+
+ selection_.clear();
+ pending_pages_.clear();
+
+ // Delete all pages except the first one.
+ while (pages_.size() > 1) {
+ delete pages_.back();
+ pages_.pop_back();
+ FPDFPage_Delete(doc_, pages_.size());
+ }
+
+ // Calculate document size and all page sizes.
+ std::vector<pp::Rect> page_rects;
+ pp::Size page_size = GetPageSize(0);
+ page_size.Enlarge(kPageShadowLeft + kPageShadowRight,
+ kPageShadowTop + kPageShadowBottom);
+ pp::Size old_document_size = document_size_;
+ document_size_ = pp::Size(page_size.width(), 0);
+ for (int i = 0; i < num_pages; ++i) {
+ if (i != 0) {
+ // Add space for horizontal separator.
+ document_size_.Enlarge(0, kPageSeparatorThickness);
+ }
+
+ pp::Rect rect(pp::Point(0, document_size_.height()), page_size);
+ page_rects.push_back(rect);
+
+ document_size_.Enlarge(0, page_size.height());
+ }
+
+ // Create blank pages.
+ for (int i = 1; i < num_pages; ++i) {
+ pp::Rect page_rect(page_rects[i]);
+ page_rect.Inset(kPageShadowLeft, kPageShadowTop,
+ kPageShadowRight, kPageShadowBottom);
+ double width_in_points = ConvertUnitDouble(page_rect.width(),
+ kPixelsPerInch,
+ kPointsPerInch);
+ double height_in_points = ConvertUnitDouble(page_rect.height(),
+ kPixelsPerInch,
+ kPointsPerInch);
+ FPDFPage_New(doc_, i, width_in_points, height_in_points);
+ pages_.push_back(new PDFiumPage(this, i, page_rect, true));
+ }
+
+ CalculateVisiblePages();
+ if (document_size_ != old_document_size)
+ client_->DocumentSizeUpdated(document_size_);
+}
+
+void PDFiumEngine::LoadDocument() {
+ // Check if the document is ready for loading. If it isn't just bail for now,
+ // we will call LoadDocument() again later.
+ if (!doc_ && !doc_loader_.IsDocumentComplete() &&
+ !FPDFAvail_IsDocAvail(fpdf_availability_, &download_hints_)) {
+ return;
+ }
+
+ // If we're in the middle of getting a password, just return. We will retry
+ // loading the document after we get the password anyway.
+ if (getting_password_)
+ return;
+
+ ScopedUnsupportedFeature scoped_unsupported_feature(this);
+ bool needs_password = false;
+ if (TryLoadingDoc(false, std::string(), &needs_password)) {
+ ContinueLoadingDocument(false, std::string());
+ return;
+ }
+ if (needs_password)
+ GetPasswordAndLoad();
+ else
+ client_->DocumentLoadFailed();
+}
+
+bool PDFiumEngine::TryLoadingDoc(bool with_password,
+ const std::string& password,
+ bool* needs_password) {
+ *needs_password = false;
+ if (doc_)
+ return true;
+
+ const char* password_cstr = nullptr;
+ if (with_password) {
+ password_cstr = password.c_str();
+ password_tries_remaining_--;
+ }
+ if (doc_loader_.IsDocumentComplete())
+ doc_ = FPDF_LoadCustomDocument(&file_access_, password_cstr);
+ else
+ doc_ = FPDFAvail_GetDocument(fpdf_availability_, password_cstr);
+
+ if (!doc_ && FPDF_GetLastError() == FPDF_ERR_PASSWORD)
+ *needs_password = true;
+
+ return !!doc_;
+}
+
+void PDFiumEngine::GetPasswordAndLoad() {
+ getting_password_ = true;
+ DCHECK(!doc_ && FPDF_GetLastError() == FPDF_ERR_PASSWORD);
+ client_->GetDocumentPassword(password_factory_.NewCallbackWithOutput(
+ &PDFiumEngine::OnGetPasswordComplete));
+}
+
+void PDFiumEngine::OnGetPasswordComplete(int32_t result,
+ const pp::Var& password) {
+ getting_password_ = false;
+
+ bool password_given = false;
+ std::string password_text;
+ if (result == PP_OK && password.is_string()) {
+ password_text = password.AsString();
+ if (!password_text.empty())
+ password_given = true;
+ }
+ ContinueLoadingDocument(password_given, password_text);
+}
+
+void PDFiumEngine::ContinueLoadingDocument(
+ bool has_password,
+ const std::string& password) {
+ ScopedUnsupportedFeature scoped_unsupported_feature(this);
+
+ bool needs_password = false;
+ bool loaded = TryLoadingDoc(has_password, password, &needs_password);
+ bool password_incorrect = !loaded && has_password && needs_password;
+ if (password_incorrect && password_tries_remaining_ > 0) {
+ GetPasswordAndLoad();
+ return;
+ }
+
+ if (!doc_) {
+ client_->DocumentLoadFailed();
+ return;
+ }
+
+ if (FPDFDoc_GetPageMode(doc_) == PAGEMODE_USEOUTLINES)
+ client_->DocumentHasUnsupportedFeature("Bookmarks");
+
+ permissions_ = FPDF_GetDocPermissions(doc_);
+ permissions_handler_revision_ = FPDF_GetSecurityHandlerRevision(doc_);
+
+ if (!form_) {
+ int form_status =
+ FPDFAvail_IsFormAvail(fpdf_availability_, &download_hints_);
+ bool doc_complete = doc_loader_.IsDocumentComplete();
+ // Try again if the data is not available and the document hasn't finished
+ // downloading.
+ if (form_status == PDF_FORM_NOTAVAIL && !doc_complete)
+ return;
+
+ form_ = FPDFDOC_InitFormFillEnvironment(
+ doc_, static_cast<FPDF_FORMFILLINFO*>(this));
+#ifdef PDF_USE_XFA
+ FPDF_LoadXFA(doc_);
+#endif
+
+ FPDF_SetFormFieldHighlightColor(form_, 0, kFormHighlightColor);
+ FPDF_SetFormFieldHighlightAlpha(form_, kFormHighlightAlpha);
+ }
+
+ if (!doc_loader_.IsDocumentComplete()) {
+ // Check if the first page is available. In a linearized PDF, that is not
+ // always page 0. Doing this gives us the default page size, since when the
+ // document is available, the first page is available as well.
+ CheckPageAvailable(FPDFAvail_GetFirstPageNum(doc_), &pending_pages_);
+ }
+
+ LoadPageInfo(false);
+
+ if (doc_loader_.IsDocumentComplete())
+ FinishLoadingDocument();
+}
+
+void PDFiumEngine::LoadPageInfo(bool reload) {
+ pending_pages_.clear();
+ pp::Size old_document_size = document_size_;
+ document_size_ = pp::Size();
+ std::vector<pp::Rect> page_rects;
+ int page_count = FPDF_GetPageCount(doc_);
+ bool doc_complete = doc_loader_.IsDocumentComplete();
+ for (int i = 0; i < page_count; ++i) {
+ if (i != 0) {
+ // Add space for horizontal separator.
+ document_size_.Enlarge(0, kPageSeparatorThickness);
+ }
+
+ // Get page availability. If reload==false, and document is not loaded yet
+ // (we are using async loading) - mark all pages as unavailable.
+ // If reload==true (we have document constructed already), get page
+ // availability flag from already existing PDFiumPage class.
+ bool page_available = reload ? pages_[i]->available() : doc_complete;
+
+ pp::Size size = page_available ? GetPageSize(i) : default_page_size_;
+ size.Enlarge(kPageShadowLeft + kPageShadowRight,
+ kPageShadowTop + kPageShadowBottom);
+ pp::Rect rect(pp::Point(0, document_size_.height()), size);
+ page_rects.push_back(rect);
+
+ if (size.width() > document_size_.width())
+ document_size_.set_width(size.width());
+
+ document_size_.Enlarge(0, size.height());
+ }
+
+ for (int i = 0; i < page_count; ++i) {
+ // Center pages relative to the entire document.
+ page_rects[i].set_x((document_size_.width() - page_rects[i].width()) / 2);
+ pp::Rect page_rect(page_rects[i]);
+ page_rect.Inset(kPageShadowLeft, kPageShadowTop,
+ kPageShadowRight, kPageShadowBottom);
+ if (reload) {
+ pages_[i]->set_rect(page_rect);
+ } else {
+ // The page is marked as not being available even if |doc_complete| is
+ // true because FPDFAvail_IsPageAvail() still has to be called for this
+ // page, which will be done in FinishLoadingDocument().
+ pages_.push_back(new PDFiumPage(this, i, page_rect, false));
+ }
+ }
+
+ CalculateVisiblePages();
+ if (document_size_ != old_document_size)
+ client_->DocumentSizeUpdated(document_size_);
+}
+
+void PDFiumEngine::CalculateVisiblePages() {
+ // Clear pending requests queue, since it may contain requests to the pages
+ // that are already invisible (after scrolling for example).
+ pending_pages_.clear();
+ doc_loader_.ClearPendingRequests();
+
+ visible_pages_.clear();
+ pp::Rect visible_rect(plugin_size_);
+ for (size_t i = 0; i < pages_.size(); ++i) {
+ // Check an entire PageScreenRect, since we might need to repaint side
+ // borders and shadows even if the page itself is not visible.
+ // For example, when user use pdf with different page sizes and zoomed in
+ // outside page area.
+ if (visible_rect.Intersects(GetPageScreenRect(i))) {
+ visible_pages_.push_back(i);
+ CheckPageAvailable(i, &pending_pages_);
+ } else {
+ // Need to unload pages when we're not using them, since some PDFs use a
+ // lot of memory. See http://crbug.com/48791
+ if (defer_page_unload_) {
+ deferred_page_unloads_.push_back(i);
+ } else {
+ pages_[i]->Unload();
+ }
+
+ // If the last mouse down was on a page that's no longer visible, reset
+ // that variable so that we don't send keyboard events to it (the focus
+ // will be lost when the page is first closed anyways).
+ if (static_cast<int>(i) == last_page_mouse_down_)
+ last_page_mouse_down_ = -1;
+ }
+ }
+
+ // Any pending highlighting of form fields will be invalid since these are in
+ // screen coordinates.
+ form_highlights_.clear();
+
+ int most_visible_page = visible_pages_.empty() ? -1 : visible_pages_.front();
+ // Check if the next page is more visible than the first one.
+ if (most_visible_page != -1 && !pages_.empty() &&
+ most_visible_page < static_cast<int>(pages_.size()) - 1) {
+ pp::Rect rc_first =
+ visible_rect.Intersect(GetPageScreenRect(most_visible_page));
+ pp::Rect rc_next =
+ visible_rect.Intersect(GetPageScreenRect(most_visible_page + 1));
+ if (rc_next.height() > rc_first.height())
+ most_visible_page++;
+ }
+
+ SetCurrentPage(most_visible_page);
+}
+
+bool PDFiumEngine::IsPageVisible(int index) const {
+ return ContainsValue(visible_pages_, index);
+}
+
+bool PDFiumEngine::CheckPageAvailable(int index, std::vector<int>* pending) {
+ if (!doc_ || !form_)
+ return false;
+
+ if (static_cast<int>(pages_.size()) > index && pages_[index]->available())
+ return true;
+
+ if (!FPDFAvail_IsPageAvail(fpdf_availability_, index, &download_hints_)) {
+ size_t j;
+ for (j = 0; j < pending->size(); ++j) {
+ if ((*pending)[j] == index)
+ break;
+ }
+
+ if (j == pending->size())
+ pending->push_back(index);
+ return false;
+ }
+
+ if (static_cast<int>(pages_.size()) > index)
+ pages_[index]->set_available(true);
+ if (!default_page_size_.GetArea())
+ default_page_size_ = GetPageSize(index);
+ return true;
+}
+
+pp::Size PDFiumEngine::GetPageSize(int index) {
+ pp::Size size;
+ double width_in_points = 0;
+ double height_in_points = 0;
+ int rv = FPDF_GetPageSizeByIndex(
+ doc_, index, &width_in_points, &height_in_points);
+
+ if (rv) {
+ int width_in_pixels = static_cast<int>(
+ ConvertUnitDouble(width_in_points, kPointsPerInch, kPixelsPerInch));
+ int height_in_pixels = static_cast<int>(
+ ConvertUnitDouble(height_in_points, kPointsPerInch, kPixelsPerInch));
+ if (current_rotation_ % 2 == 1)
+ std::swap(width_in_pixels, height_in_pixels);
+ size = pp::Size(width_in_pixels, height_in_pixels);
+ }
+ return size;
+}
+
+int PDFiumEngine::StartPaint(int page_index, const pp::Rect& dirty) {
+ // For the first time we hit paint, do nothing and just record the paint for
+ // the next callback. This keeps the UI responsive in case the user is doing
+ // a lot of scrolling.
+ ProgressivePaint progressive;
+ progressive.rect = dirty;
+ progressive.page_index = page_index;
+ progressive.bitmap = NULL;
+ progressive.painted_ = false;
+ progressive_paints_.push_back(progressive);
+ return progressive_paints_.size() - 1;
+}
+
+bool PDFiumEngine::ContinuePaint(int progressive_index,
+ pp::ImageData* image_data) {
+ DCHECK_GE(progressive_index, 0);
+ DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
+ DCHECK(image_data);
+
+#if defined(OS_LINUX)
+ g_last_instance_id = client_->GetPluginInstance()->pp_instance();
+#endif
+
+ int rv;
+ FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
+ int page_index = progressive_paints_[progressive_index].page_index;
+ DCHECK_GE(page_index, 0);
+ DCHECK_LT(static_cast<size_t>(page_index), pages_.size());
+ FPDF_PAGE page = pages_[page_index]->GetPage();
+
+ last_progressive_start_time_ = base::Time::Now();
+ if (bitmap) {
+ rv = FPDF_RenderPage_Continue(page, static_cast<IFSDK_PAUSE*>(this));
+ } else {
+ pp::Rect dirty = progressive_paints_[progressive_index].rect;
+ bitmap = CreateBitmap(dirty, image_data);
+ int start_x, start_y, size_x, size_y;
+ GetPDFiumRect(page_index, dirty, &start_x, &start_y, &size_x, &size_y);
+ FPDFBitmap_FillRect(bitmap, start_x, start_y, size_x, size_y, 0xFFFFFFFF);
+ rv = FPDF_RenderPageBitmap_Start(
+ bitmap, page, start_x, start_y, size_x, size_y,
+ current_rotation_,
+ GetRenderingFlags(), static_cast<IFSDK_PAUSE*>(this));
+ progressive_paints_[progressive_index].bitmap = bitmap;
+ }
+ return rv != FPDF_RENDER_TOBECOUNTINUED;
+}
+
+void PDFiumEngine::FinishPaint(int progressive_index,
+ pp::ImageData* image_data) {
+ DCHECK_GE(progressive_index, 0);
+ DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
+ DCHECK(image_data);
+
+ int page_index = progressive_paints_[progressive_index].page_index;
+ pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
+ FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
+ int start_x, start_y, size_x, size_y;
+ GetPDFiumRect(
+ page_index, dirty_in_screen, &start_x, &start_y, &size_x, &size_y);
+
+ // Draw the forms.
+ FPDF_FFLDraw(
+ form_, bitmap, pages_[page_index]->GetPage(), start_x, start_y, size_x,
+ size_y, current_rotation_, GetRenderingFlags());
+
+ FillPageSides(progressive_index);
+
+ // Paint the page shadows.
+ PaintPageShadow(progressive_index, image_data);
+
+ DrawSelections(progressive_index, image_data);
+
+ FPDF_RenderPage_Close(pages_[page_index]->GetPage());
+ FPDFBitmap_Destroy(bitmap);
+ progressive_paints_.erase(progressive_paints_.begin() + progressive_index);
+
+ client_->DocumentPaintOccurred();
+}
+
+void PDFiumEngine::CancelPaints() {
+ for (const auto& paint : progressive_paints_) {
+ FPDF_RenderPage_Close(pages_[paint.page_index]->GetPage());
+ FPDFBitmap_Destroy(paint.bitmap);
+ }
+ progressive_paints_.clear();
+}
+
+void PDFiumEngine::FillPageSides(int progressive_index) {
+ DCHECK_GE(progressive_index, 0);
+ DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
+
+ int page_index = progressive_paints_[progressive_index].page_index;
+ pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
+ FPDF_BITMAP bitmap = progressive_paints_[progressive_index].bitmap;
+
+ pp::Rect page_rect = pages_[page_index]->rect();
+ if (page_rect.x() > 0) {
+ pp::Rect left(0,
+ page_rect.y() - kPageShadowTop,
+ page_rect.x() - kPageShadowLeft,
+ page_rect.height() + kPageShadowTop +
+ kPageShadowBottom + kPageSeparatorThickness);
+ left = GetScreenRect(left).Intersect(dirty_in_screen);
+
+ FPDFBitmap_FillRect(bitmap, left.x() - dirty_in_screen.x(),
+ left.y() - dirty_in_screen.y(), left.width(),
+ left.height(), client_->GetBackgroundColor());
+ }
+
+ if (page_rect.right() < document_size_.width()) {
+ pp::Rect right(page_rect.right() + kPageShadowRight,
+ page_rect.y() - kPageShadowTop,
+ document_size_.width() - page_rect.right() -
+ kPageShadowRight,
+ page_rect.height() + kPageShadowTop +
+ kPageShadowBottom + kPageSeparatorThickness);
+ right = GetScreenRect(right).Intersect(dirty_in_screen);
+
+ FPDFBitmap_FillRect(bitmap, right.x() - dirty_in_screen.x(),
+ right.y() - dirty_in_screen.y(), right.width(),
+ right.height(), client_->GetBackgroundColor());
+ }
+
+ // Paint separator.
+ pp::Rect bottom(page_rect.x() - kPageShadowLeft,
+ page_rect.bottom() + kPageShadowBottom,
+ page_rect.width() + kPageShadowLeft + kPageShadowRight,
+ kPageSeparatorThickness);
+ bottom = GetScreenRect(bottom).Intersect(dirty_in_screen);
+
+ FPDFBitmap_FillRect(bitmap, bottom.x() - dirty_in_screen.x(),
+ bottom.y() - dirty_in_screen.y(), bottom.width(),
+ bottom.height(), client_->GetBackgroundColor());
+}
+
+void PDFiumEngine::PaintPageShadow(int progressive_index,
+ pp::ImageData* image_data) {
+ DCHECK_GE(progressive_index, 0);
+ DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
+ DCHECK(image_data);
+
+ int page_index = progressive_paints_[progressive_index].page_index;
+ pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
+ pp::Rect page_rect = pages_[page_index]->rect();
+ pp::Rect shadow_rect(page_rect);
+ shadow_rect.Inset(-kPageShadowLeft, -kPageShadowTop,
+ -kPageShadowRight, -kPageShadowBottom);
+
+ // Due to the rounding errors of the GetScreenRect it is possible to get
+ // different size shadows on the left and right sides even they are defined
+ // the same. To fix this issue let's calculate shadow rect and then shrink
+ // it by the size of the shadows.
+ shadow_rect = GetScreenRect(shadow_rect);
+ page_rect = shadow_rect;
+
+ page_rect.Inset(static_cast<int>(ceil(kPageShadowLeft * current_zoom_)),
+ static_cast<int>(ceil(kPageShadowTop * current_zoom_)),
+ static_cast<int>(ceil(kPageShadowRight * current_zoom_)),
+ static_cast<int>(ceil(kPageShadowBottom * current_zoom_)));
+
+ DrawPageShadow(page_rect, shadow_rect, dirty_in_screen, image_data);
+}
+
+void PDFiumEngine::DrawSelections(int progressive_index,
+ pp::ImageData* image_data) {
+ DCHECK_GE(progressive_index, 0);
+ DCHECK_LT(static_cast<size_t>(progressive_index), progressive_paints_.size());
+ DCHECK(image_data);
+
+ int page_index = progressive_paints_[progressive_index].page_index;
+ pp::Rect dirty_in_screen = progressive_paints_[progressive_index].rect;
+
+ void* region = NULL;
+ int stride;
+ GetRegion(dirty_in_screen.point(), image_data, &region, &stride);
+
+ std::vector<pp::Rect> highlighted_rects;
+ pp::Rect visible_rect = GetVisibleRect();
+ for (auto& range : selection_) {
+ if (range.page_index() != page_index)
+ continue;
+
+ std::vector<pp::Rect> rects = range.GetScreenRects(
+ visible_rect.point(), current_zoom_, current_rotation_);
+ for (const auto& rect : rects) {
+ pp::Rect visible_selection = rect.Intersect(dirty_in_screen);
+ if (visible_selection.IsEmpty())
+ continue;
+
+ visible_selection.Offset(
+ -dirty_in_screen.point().x(), -dirty_in_screen.point().y());
+ Highlight(region, stride, visible_selection, &highlighted_rects);
+ }
+ }
+
+ for (const auto& highlight : form_highlights_) {
+ pp::Rect visible_selection = highlight.Intersect(dirty_in_screen);
+ if (visible_selection.IsEmpty())
+ continue;
+
+ visible_selection.Offset(
+ -dirty_in_screen.point().x(), -dirty_in_screen.point().y());
+ Highlight(region, stride, visible_selection, &highlighted_rects);
+ }
+ form_highlights_.clear();
+}
+
+void PDFiumEngine::PaintUnavailablePage(int page_index,
+ const pp::Rect& dirty,
+ pp::ImageData* image_data) {
+ int start_x, start_y, size_x, size_y;
+ GetPDFiumRect(page_index, dirty, &start_x, &start_y, &size_x, &size_y);
+ FPDF_BITMAP bitmap = CreateBitmap(dirty, image_data);
+ FPDFBitmap_FillRect(bitmap, start_x, start_y, size_x, size_y,
+ kPendingPageColor);
+
+ pp::Rect loading_text_in_screen(
+ pages_[page_index]->rect().width() / 2,
+ pages_[page_index]->rect().y() + kLoadingTextVerticalOffset, 0, 0);
+ loading_text_in_screen = GetScreenRect(loading_text_in_screen);
+ FPDFBitmap_Destroy(bitmap);
+}
+
+int PDFiumEngine::GetProgressiveIndex(int page_index) const {
+ for (size_t i = 0; i < progressive_paints_.size(); ++i) {
+ if (progressive_paints_[i].page_index == page_index)
+ return i;
+ }
+ return -1;
+}
+
+FPDF_BITMAP PDFiumEngine::CreateBitmap(const pp::Rect& rect,
+ pp::ImageData* image_data) const {
+ void* region;
+ int stride;
+ GetRegion(rect.point(), image_data, &region, &stride);
+ if (!region)
+ return NULL;
+ return FPDFBitmap_CreateEx(
+ rect.width(), rect.height(), FPDFBitmap_BGRx, region, stride);
+}
+
+void PDFiumEngine::GetPDFiumRect(
+ int page_index, const pp::Rect& rect, int* start_x, int* start_y,
+ int* size_x, int* size_y) const {
+ pp::Rect page_rect = GetScreenRect(pages_[page_index]->rect());
+ page_rect.Offset(-rect.x(), -rect.y());
+
+ *start_x = page_rect.x();
+ *start_y = page_rect.y();
+ *size_x = page_rect.width();
+ *size_y = page_rect.height();
+}
+
+int PDFiumEngine::GetRenderingFlags() const {
+ int flags = FPDF_LCD_TEXT | FPDF_NO_CATCH;
+ if (render_grayscale_)
+ flags |= FPDF_GRAYSCALE;
+ if (client_->IsPrintPreview())
+ flags |= FPDF_PRINTING;
+ return flags;
+}
+
+pp::Rect PDFiumEngine::GetVisibleRect() const {
+ pp::Rect rv;
+ rv.set_x(static_cast<int>(position_.x() / current_zoom_));
+ rv.set_y(static_cast<int>(position_.y() / current_zoom_));
+ rv.set_width(static_cast<int>(ceil(plugin_size_.width() / current_zoom_)));
+ rv.set_height(static_cast<int>(ceil(plugin_size_.height() / current_zoom_)));
+ return rv;
+}
+
+pp::Rect PDFiumEngine::GetPageScreenRect(int page_index) const {
+ // Since we use this rect for creating the PDFium bitmap, also include other
+ // areas around the page that we might need to update such as the page
+ // separator and the sides if the page is narrower than the document.
+ return GetScreenRect(pp::Rect(
+ 0,
+ pages_[page_index]->rect().y() - kPageShadowTop,
+ document_size_.width(),
+ pages_[page_index]->rect().height() + kPageShadowTop +
+ kPageShadowBottom + kPageSeparatorThickness));
+}
+
+pp::Rect PDFiumEngine::GetScreenRect(const pp::Rect& rect) const {
+ pp::Rect rv;
+ int right =
+ static_cast<int>(ceil(rect.right() * current_zoom_ - position_.x()));
+ int bottom =
+ static_cast<int>(ceil(rect.bottom() * current_zoom_ - position_.y()));
+
+ rv.set_x(static_cast<int>(rect.x() * current_zoom_ - position_.x()));
+ rv.set_y(static_cast<int>(rect.y() * current_zoom_ - position_.y()));
+ rv.set_width(right - rv.x());
+ rv.set_height(bottom - rv.y());
+ return rv;
+}
+
+void PDFiumEngine::Highlight(void* buffer,
+ int stride,
+ const pp::Rect& rect,
+ std::vector<pp::Rect>* highlighted_rects) {
+ if (!buffer)
+ return;
+
+ pp::Rect new_rect = rect;
+ for (const auto& highlighted : *highlighted_rects)
+ new_rect = new_rect.Subtract(highlighted);
+
+ highlighted_rects->push_back(new_rect);
+ int l = new_rect.x();
+ int t = new_rect.y();
+ int w = new_rect.width();
+ int h = new_rect.height();
+
+ for (int y = t; y < t + h; ++y) {
+ for (int x = l; x < l + w; ++x) {
+ uint8_t* pixel = static_cast<uint8_t*>(buffer) + y * stride + x * 4;
+ // This is our highlight color.
+ pixel[0] = static_cast<uint8_t>(pixel[0] * (kHighlightColorB / 255.0));
+ pixel[1] = static_cast<uint8_t>(pixel[1] * (kHighlightColorG / 255.0));
+ pixel[2] = static_cast<uint8_t>(pixel[2] * (kHighlightColorR / 255.0));
+ }
+ }
+}
+
+PDFiumEngine::SelectionChangeInvalidator::SelectionChangeInvalidator(
+ PDFiumEngine* engine) : engine_(engine) {
+ previous_origin_ = engine_->GetVisibleRect().point();
+ GetVisibleSelectionsScreenRects(&old_selections_);
+}
+
+PDFiumEngine::SelectionChangeInvalidator::~SelectionChangeInvalidator() {
+ // Offset the old selections if the document scrolled since we recorded them.
+ pp::Point offset = previous_origin_ - engine_->GetVisibleRect().point();
+ for (auto& old_selection : old_selections_)
+ old_selection.Offset(offset);
+
+ std::vector<pp::Rect> new_selections;
+ GetVisibleSelectionsScreenRects(&new_selections);
+ for (auto& new_selection : new_selections) {
+ for (auto& old_selection : old_selections_) {
+ if (!old_selection.IsEmpty() && new_selection == old_selection) {
+ // Rectangle was selected before and after, so no need to invalidate it.
+ // Mark the rectangles by setting them to empty.
+ new_selection = old_selection = pp::Rect();
+ break;
+ }
+ }
+ }
+
+ for (const auto& old_selection : old_selections_) {
+ if (!old_selection.IsEmpty())
+ engine_->client_->Invalidate(old_selection);
+ }
+ for (const auto& new_selection : new_selections) {
+ if (!new_selection.IsEmpty())
+ engine_->client_->Invalidate(new_selection);
+ }
+ engine_->OnSelectionChanged();
+}
+
+void PDFiumEngine::SelectionChangeInvalidator::GetVisibleSelectionsScreenRects(
+ std::vector<pp::Rect>* rects) {
+ pp::Rect visible_rect = engine_->GetVisibleRect();
+ for (auto& range : engine_->selection_) {
+ int page_index = range.page_index();
+ if (!engine_->IsPageVisible(page_index))
+ continue; // This selection is on a page that's not currently visible.
+
+ std::vector<pp::Rect> selection_rects =
+ range.GetScreenRects(
+ visible_rect.point(),
+ engine_->current_zoom_,
+ engine_->current_rotation_);
+ rects->insert(rects->end(), selection_rects.begin(), selection_rects.end());
+ }
+}
+
+PDFiumEngine::MouseDownState::MouseDownState(
+ const PDFiumPage::Area& area,
+ const PDFiumPage::LinkTarget& target)
+ : area_(area), target_(target) {
+}
+
+PDFiumEngine::MouseDownState::~MouseDownState() {
+}
+
+void PDFiumEngine::MouseDownState::Set(const PDFiumPage::Area& area,
+ const PDFiumPage::LinkTarget& target) {
+ area_ = area;
+ target_ = target;
+}
+
+void PDFiumEngine::MouseDownState::Reset() {
+ area_ = PDFiumPage::NONSELECTABLE_AREA;
+ target_ = PDFiumPage::LinkTarget();
+}
+
+bool PDFiumEngine::MouseDownState::Matches(
+ const PDFiumPage::Area& area,
+ const PDFiumPage::LinkTarget& target) const {
+ if (area_ != area)
+ return false;
+
+ if (area == PDFiumPage::WEBLINK_AREA)
+ return target_.url == target.url;
+
+ if (area == PDFiumPage::DOCLINK_AREA)
+ return target_.page == target.page;
+
+ return true;
+}
+
+PDFiumEngine::FindTextIndex::FindTextIndex()
+ : valid_(false), index_(0) {
+}
+
+PDFiumEngine::FindTextIndex::~FindTextIndex() {
+}
+
+void PDFiumEngine::FindTextIndex::Invalidate() {
+ valid_ = false;
+}
+
+size_t PDFiumEngine::FindTextIndex::GetIndex() const {
+ DCHECK(valid_);
+ return index_;
+}
+
+void PDFiumEngine::FindTextIndex::SetIndex(size_t index) {
+ valid_ = true;
+ index_ = index;
+}
+
+size_t PDFiumEngine::FindTextIndex::IncrementIndex() {
+ DCHECK(valid_);
+ return ++index_;
+}
+
+void PDFiumEngine::DeviceToPage(int page_index,
+ float device_x,
+ float device_y,
+ double* page_x,
+ double* page_y) {
+ *page_x = *page_y = 0;
+ int temp_x = static_cast<int>((device_x + position_.x())/ current_zoom_ -
+ pages_[page_index]->rect().x());
+ int temp_y = static_cast<int>((device_y + position_.y())/ current_zoom_ -
+ pages_[page_index]->rect().y());
+ FPDF_DeviceToPage(
+ pages_[page_index]->GetPage(), 0, 0,
+ pages_[page_index]->rect().width(), pages_[page_index]->rect().height(),
+ current_rotation_, temp_x, temp_y, page_x, page_y);
+}
+
+int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page) {
+ for (int page_index : visible_pages_) {
+ if (pages_[page_index]->GetPage() == page)
+ return page_index;
+ }
+ return -1;
+}
+
+void PDFiumEngine::SetCurrentPage(int index) {
+ if (index == most_visible_page_ || !form_)
+ return;
+ if (most_visible_page_ != -1 && called_do_document_action_) {
+ FPDF_PAGE old_page = pages_[most_visible_page_]->GetPage();
+ FORM_DoPageAAction(old_page, form_, FPDFPAGE_AACTION_CLOSE);
+ }
+ most_visible_page_ = index;
+#if defined(OS_LINUX)
+ g_last_instance_id = client_->GetPluginInstance()->pp_instance();
+#endif
+ 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);
+ }
+}
+
+void PDFiumEngine::TransformPDFPageForPrinting(
+ FPDF_PAGE page,
+ const PP_PrintSettings_Dev& print_settings) {
+ // Get the source page width and height in points.
+ const double src_page_width = FPDF_GetPageWidth(page);
+ const double src_page_height = FPDF_GetPageHeight(page);
+
+ const int src_page_rotation = FPDFPage_GetRotation(page);
+ const bool fit_to_page = print_settings.print_scaling_option ==
+ PP_PRINTSCALINGOPTION_FIT_TO_PRINTABLE_AREA;
+
+ pp::Size page_size(print_settings.paper_size);
+ pp::Rect content_rect(print_settings.printable_area);
+ const bool rotated = (src_page_rotation % 2 == 1);
+ SetPageSizeAndContentRect(rotated,
+ src_page_width > src_page_height,
+ &page_size,
+ &content_rect);
+
+ // Compute the screen page width and height in points.
+ const int actual_page_width =
+ rotated ? page_size.height() : page_size.width();
+ const int actual_page_height =
+ rotated ? page_size.width() : page_size.height();
+
+ const gfx::Rect gfx_content_rect(content_rect.x(),
+ content_rect.y(),
+ content_rect.width(),
+ content_rect.height());
+ const double scale_factor = fit_to_page ?
+ printing::CalculateScaleFactor(
+ gfx_content_rect, src_page_width, src_page_height, rotated) : 1.0;
+
+ // Calculate positions for the clip box.
+ printing::ClipBox media_box;
+ printing::ClipBox crop_box;
+ bool has_media_box = !!FPDFPage_GetMediaBox(page,
+ &media_box.left,
+ &media_box.bottom,
+ &media_box.right,
+ &media_box.top);
+ bool has_crop_box = !!FPDFPage_GetCropBox(page,
+ &crop_box.left,
+ &crop_box.bottom,
+ &crop_box.right,
+ &crop_box.top);
+ printing::CalculateMediaBoxAndCropBox(
+ rotated, has_media_box, has_crop_box, &media_box, &crop_box);
+ printing::ClipBox source_clip_box =
+ printing::CalculateClipBoxBoundary(media_box, crop_box);
+ printing::ScaleClipBox(scale_factor, &source_clip_box);
+
+ // Calculate the translation offset values.
+ double offset_x = 0;
+ double offset_y = 0;
+ if (fit_to_page) {
+ printing::CalculateScaledClipBoxOffset(
+ gfx_content_rect, source_clip_box, &offset_x, &offset_y);
+ } else {
+ printing::CalculateNonScaledClipBoxOffset(
+ gfx_content_rect, src_page_rotation,
+ actual_page_width, actual_page_height,
+ source_clip_box, &offset_x, &offset_y);
+ }
+
+ // Reset the media box and crop box. When the page has crop box and media box,
+ // the plugin will display the crop box contents and not the entire media box.
+ // If the pages have different crop box values, the plugin will display a
+ // document of multiple page sizes. To give better user experience, we
+ // decided to have same crop box and media box values. Hence, the user will
+ // see a list of uniform pages.
+ FPDFPage_SetMediaBox(page, 0, 0, page_size.width(), page_size.height());
+ FPDFPage_SetCropBox(page, 0, 0, page_size.width(), page_size.height());
+
+ // Transformation is not required, return. Do this check only after updating
+ // the media box and crop box. For more detailed information, please refer to
+ // the comment block right before FPDF_SetMediaBox and FPDF_GetMediaBox calls.
+ if (scale_factor == 1.0 && offset_x == 0 && offset_y == 0)
+ return;
+
+
+ // All the positions have been calculated, now manipulate the PDF.
+ FS_MATRIX matrix = {static_cast<float>(scale_factor),
+ 0,
+ 0,
+ static_cast<float>(scale_factor),
+ static_cast<float>(offset_x),
+ static_cast<float>(offset_y)};
+ FS_RECTF cliprect = {static_cast<float>(source_clip_box.left+offset_x),
+ static_cast<float>(source_clip_box.top+offset_y),
+ static_cast<float>(source_clip_box.right+offset_x),
+ static_cast<float>(source_clip_box.bottom+offset_y)};
+ FPDFPage_TransFormWithClip(page, &matrix, &cliprect);
+ FPDFPage_TransformAnnots(page, scale_factor, 0, 0, scale_factor,
+ offset_x, offset_y);
+}
+
+void PDFiumEngine::DrawPageShadow(const pp::Rect& page_rc,
+ const pp::Rect& shadow_rc,
+ const pp::Rect& clip_rc,
+ pp::ImageData* image_data) {
+ pp::Rect page_rect(page_rc);
+ page_rect.Offset(page_offset_);
+
+ pp::Rect shadow_rect(shadow_rc);
+ shadow_rect.Offset(page_offset_);
+
+ pp::Rect clip_rect(clip_rc);
+ clip_rect.Offset(page_offset_);
+
+ // Page drop shadow parameters.
+ const double factor = 0.5;
+ uint32_t depth =
+ std::max(std::max(page_rect.x() - shadow_rect.x(),
+ page_rect.y() - shadow_rect.y()),
+ std::max(shadow_rect.right() - page_rect.right(),
+ shadow_rect.bottom() - page_rect.bottom()));
+ depth = static_cast<uint32_t>(depth * 1.5) + 1;
+
+ // We need to check depth only to verify our copy of shadow matrix is correct.
+ if (!page_shadow_.get() || page_shadow_->depth() != depth)
+ page_shadow_.reset(new ShadowMatrix(depth, factor,
+ client_->GetBackgroundColor()));
+
+ DCHECK(!image_data->is_null());
+ DrawShadow(image_data, shadow_rect, page_rect, clip_rect, *page_shadow_);
+}
+
+void PDFiumEngine::GetRegion(const pp::Point& location,
+ pp::ImageData* image_data,
+ void** region,
+ int* stride) const {
+ if (image_data->is_null()) {
+ DCHECK(plugin_size_.IsEmpty());
+ *stride = 0;
+ *region = NULL;
+ return;
+ }
+ char* buffer = static_cast<char*>(image_data->data());
+ *stride = image_data->stride();
+
+ pp::Point offset_location = location + page_offset_;
+ // TODO: update this when we support BIDI and scrollbars can be on the left.
+ if (!buffer ||
+ !pp::Rect(page_offset_, plugin_size_).Contains(offset_location)) {
+ *region = NULL;
+ return;
+ }
+
+ buffer += location.y() * (*stride);
+ buffer += (location.x() + page_offset_.x()) * 4;
+ *region = buffer;
+}
+
+void PDFiumEngine::OnSelectionChanged() {
+ pp::PDF::SetSelectedText(GetPluginInstance(), GetSelectedText().c_str());
+}
+
+void PDFiumEngine::RotateInternal() {
+ // Store the current find index so that we can resume finding at that
+ // particular index after we have recomputed the find results.
+ std::string current_find_text = current_find_text_;
+ if (current_find_index_.valid())
+ resume_find_index_.SetIndex(current_find_index_.GetIndex());
+ else
+ resume_find_index_.Invalidate();
+
+ InvalidateAllPages();
+
+ if (!current_find_text.empty()) {
+ // Clear the UI.
+ client_->NotifyNumberOfFindResultsChanged(0, false);
+ StartFind(current_find_text, false);
+ }
+}
+
+void PDFiumEngine::SetSelecting(bool selecting) {
+ bool was_selecting = selecting_;
+ selecting_ = selecting;
+ if (selecting_ != was_selecting)
+ client_->IsSelectingChanged(selecting);
+}
+
+void PDFiumEngine::Form_Invalidate(FPDF_FORMFILLINFO* param,
+ FPDF_PAGE page,
+ double left,
+ double top,
+ double right,
+ double bottom) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ int page_index = engine->GetVisiblePageIndex(page);
+ if (page_index == -1) {
+ // This can sometime happen when the page is closed because it went off
+ // screen, and PDFium invalidates the control as it's being deleted.
+ return;
+ }
+
+ pp::Rect rect = engine->pages_[page_index]->PageToScreen(
+ engine->GetVisibleRect().point(), engine->current_zoom_, left, top, right,
+ bottom, engine->current_rotation_);
+ engine->client_->Invalidate(rect);
+}
+
+void PDFiumEngine::Form_OutputSelectedRect(FPDF_FORMFILLINFO* param,
+ FPDF_PAGE page,
+ double left,
+ double top,
+ double right,
+ double bottom) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ int page_index = engine->GetVisiblePageIndex(page);
+ if (page_index == -1) {
+ NOTREACHED();
+ return;
+ }
+ pp::Rect rect = engine->pages_[page_index]->PageToScreen(
+ engine->GetVisibleRect().point(), engine->current_zoom_, left, top, right,
+ bottom, engine->current_rotation_);
+ engine->form_highlights_.push_back(rect);
+}
+
+void PDFiumEngine::Form_SetCursor(FPDF_FORMFILLINFO* param, int cursor_type) {
+ // We don't need this since it's not enough to change the cursor in all
+ // scenarios. Instead, we check which form field we're under in OnMouseMove.
+}
+
+int PDFiumEngine::Form_SetTimer(FPDF_FORMFILLINFO* param,
+ int elapse,
+ TimerCallback timer_func) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ engine->timers_[++engine->next_timer_id_] =
+ std::pair<int, TimerCallback>(elapse, timer_func);
+ engine->client_->ScheduleCallback(engine->next_timer_id_, elapse);
+ return engine->next_timer_id_;
+}
+
+void PDFiumEngine::Form_KillTimer(FPDF_FORMFILLINFO* param, int timer_id) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ engine->timers_.erase(timer_id);
+}
+
+FPDF_SYSTEMTIME PDFiumEngine::Form_GetLocalTime(FPDF_FORMFILLINFO* param) {
+ base::Time time = base::Time::Now();
+ base::Time::Exploded exploded;
+ time.LocalExplode(&exploded);
+
+ FPDF_SYSTEMTIME rv;
+ rv.wYear = exploded.year;
+ rv.wMonth = exploded.month;
+ rv.wDayOfWeek = exploded.day_of_week;
+ rv.wDay = exploded.day_of_month;
+ rv.wHour = exploded.hour;
+ rv.wMinute = exploded.minute;
+ rv.wSecond = exploded.second;
+ rv.wMilliseconds = exploded.millisecond;
+ return rv;
+}
+
+void PDFiumEngine::Form_OnChange(FPDF_FORMFILLINFO* param) {
+ // Don't care about.
+}
+
+FPDF_PAGE PDFiumEngine::Form_GetPage(FPDF_FORMFILLINFO* param,
+ FPDF_DOCUMENT document,
+ int page_index) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ if (page_index < 0 || page_index >= static_cast<int>(engine->pages_.size()))
+ return NULL;
+ return engine->pages_[page_index]->GetPage();
+}
+
+FPDF_PAGE PDFiumEngine::Form_GetCurrentPage(FPDF_FORMFILLINFO* param,
+ FPDF_DOCUMENT document) {
+ // TODO(jam): find out what this is used for.
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ int index = engine->last_page_mouse_down_;
+ if (index == -1) {
+ index = engine->GetMostVisiblePage();
+ if (index == -1) {
+ NOTREACHED();
+ return NULL;
+ }
+ }
+
+ return engine->pages_[index]->GetPage();
+}
+
+int PDFiumEngine::Form_GetRotation(FPDF_FORMFILLINFO* param, FPDF_PAGE page) {
+ return 0;
+}
+
+void PDFiumEngine::Form_ExecuteNamedAction(FPDF_FORMFILLINFO* param,
+ FPDF_BYTESTRING named_action) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ std::string action(named_action);
+ if (action == "Print") {
+ engine->client_->Print();
+ return;
+ }
+
+ int index = engine->last_page_mouse_down_;
+ /* Don't try to calculate the most visible page if we don't have a left click
+ before this event (this code originally copied Form_GetCurrentPage which of
+ course needs to do that and which doesn't have recursion). This can end up
+ causing infinite recursion. See http://crbug.com/240413 for more
+ information. Either way, it's not necessary for the spec'd list of named
+ actions.
+ if (index == -1)
+ index = engine->GetMostVisiblePage();
+ */
+ if (index == -1)
+ return;
+
+ // This is the only list of named actions per the spec (see 12.6.4.11). Adobe
+ // Reader supports more, like FitWidth, but since they're not part of the spec
+ // and we haven't got bugs about them, no need to now.
+ if (action == "NextPage") {
+ engine->client_->ScrollToPage(index + 1);
+ } else if (action == "PrevPage") {
+ engine->client_->ScrollToPage(index - 1);
+ } else if (action == "FirstPage") {
+ engine->client_->ScrollToPage(0);
+ } else if (action == "LastPage") {
+ engine->client_->ScrollToPage(engine->pages_.size() - 1);
+ }
+}
+
+void PDFiumEngine::Form_SetTextFieldFocus(FPDF_FORMFILLINFO* param,
+ FPDF_WIDESTRING value,
+ FPDF_DWORD valueLen,
+ FPDF_BOOL is_focus) {
+ // Do nothing for now.
+ // TODO(gene): use this signal to trigger OSK.
+}
+
+void PDFiumEngine::Form_DoURIAction(FPDF_FORMFILLINFO* param,
+ FPDF_BYTESTRING uri) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ engine->client_->NavigateTo(std::string(uri), false);
+}
+
+void PDFiumEngine::Form_DoGoToAction(FPDF_FORMFILLINFO* param,
+ int page_index,
+ int zoom_mode,
+ float* position_array,
+ int size_of_array) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ engine->client_->ScrollToPage(page_index);
+}
+
+int PDFiumEngine::Form_Alert(IPDF_JSPLATFORM* param,
+ FPDF_WIDESTRING message,
+ FPDF_WIDESTRING title,
+ int type,
+ int icon) {
+ // See fpdfformfill.h for these values.
+ enum AlertType {
+ ALERT_TYPE_OK = 0,
+ ALERT_TYPE_OK_CANCEL,
+ ALERT_TYPE_YES_ON,
+ ALERT_TYPE_YES_NO_CANCEL
+ };
+
+ enum AlertResult {
+ ALERT_RESULT_OK = 1,
+ ALERT_RESULT_CANCEL,
+ ALERT_RESULT_NO,
+ ALERT_RESULT_YES
+ };
+
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ std::string message_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
+ if (type == ALERT_TYPE_OK) {
+ engine->client_->Alert(message_str);
+ return ALERT_RESULT_OK;
+ }
+
+ bool rv = engine->client_->Confirm(message_str);
+ if (type == ALERT_TYPE_OK_CANCEL)
+ return rv ? ALERT_RESULT_OK : ALERT_RESULT_CANCEL;
+ return rv ? ALERT_RESULT_YES : ALERT_RESULT_NO;
+}
+
+void PDFiumEngine::Form_Beep(IPDF_JSPLATFORM* param, int type) {
+ // Beeps are annoying, and not possible using javascript, so ignore for now.
+}
+
+int PDFiumEngine::Form_Response(IPDF_JSPLATFORM* param,
+ FPDF_WIDESTRING question,
+ FPDF_WIDESTRING title,
+ FPDF_WIDESTRING default_response,
+ FPDF_WIDESTRING label,
+ FPDF_BOOL password,
+ void* response,
+ int length) {
+ std::string question_str = base::UTF16ToUTF8(
+ reinterpret_cast<const base::char16*>(question));
+ std::string default_str = base::UTF16ToUTF8(
+ reinterpret_cast<const base::char16*>(default_response));
+
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ std::string rv = engine->client_->Prompt(question_str, default_str);
+ base::string16 rv_16 = base::UTF8ToUTF16(rv);
+ int rv_bytes = rv_16.size() * sizeof(base::char16);
+ if (response) {
+ int bytes_to_copy = rv_bytes < length ? rv_bytes : length;
+ memcpy(response, rv_16.c_str(), bytes_to_copy);
+ }
+ return rv_bytes;
+}
+
+int PDFiumEngine::Form_GetFilePath(IPDF_JSPLATFORM* param,
+ void* file_path,
+ int length) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ std::string rv = engine->client_->GetURL();
+ if (file_path && rv.size() <= static_cast<size_t>(length))
+ memcpy(file_path, rv.c_str(), rv.size());
+ return rv.size();
+}
+
+void PDFiumEngine::Form_Mail(IPDF_JSPLATFORM* param,
+ void* mail_data,
+ int length,
+ FPDF_BOOL ui,
+ FPDF_WIDESTRING to,
+ FPDF_WIDESTRING subject,
+ FPDF_WIDESTRING cc,
+ FPDF_WIDESTRING bcc,
+ FPDF_WIDESTRING message) {
+ // Note: |mail_data| and |length| are ignored. We don't handle attachments;
+ // there is no way with mailto.
+ std::string to_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(to));
+ std::string cc_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(cc));
+ std::string bcc_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(bcc));
+ std::string subject_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(subject));
+ std::string message_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(message));
+
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ engine->client_->Email(to_str, cc_str, bcc_str, subject_str, message_str);
+}
+
+void PDFiumEngine::Form_Print(IPDF_JSPLATFORM* param,
+ FPDF_BOOL ui,
+ int start,
+ int end,
+ FPDF_BOOL silent,
+ FPDF_BOOL shrink_to_fit,
+ FPDF_BOOL print_as_image,
+ FPDF_BOOL reverse,
+ FPDF_BOOL annotations) {
+ // No way to pass the extra information to the print dialog using JavaScript.
+ // Just opening it is fine for now.
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ engine->client_->Print();
+}
+
+void PDFiumEngine::Form_SubmitForm(IPDF_JSPLATFORM* param,
+ void* form_data,
+ int length,
+ FPDF_WIDESTRING url) {
+ std::string url_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(url));
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ engine->client_->SubmitForm(url_str, form_data, length);
+}
+
+void PDFiumEngine::Form_GotoPage(IPDF_JSPLATFORM* param,
+ int page_number) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ engine->client_->ScrollToPage(page_number);
+}
+
+int PDFiumEngine::Form_Browse(IPDF_JSPLATFORM* param,
+ void* file_path,
+ int length) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ std::string path = engine->client_->ShowFileSelectionDialog();
+ if (path.size() + 1 <= static_cast<size_t>(length))
+ memcpy(file_path, &path[0], path.size() + 1);
+ return path.size() + 1;
+}
+
+FPDF_BOOL PDFiumEngine::Pause_NeedToPauseNow(IFSDK_PAUSE* param) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(param);
+ return (base::Time::Now() - engine->last_progressive_start_time_).
+ InMilliseconds() > engine->progressive_paint_timeout_;
+}
+
+ScopedUnsupportedFeature::ScopedUnsupportedFeature(PDFiumEngine* engine)
+ : engine_(engine), old_engine_(g_engine_for_unsupported) {
+ g_engine_for_unsupported = engine_;
+}
+
+ScopedUnsupportedFeature::~ScopedUnsupportedFeature() {
+ g_engine_for_unsupported = old_engine_;
+}
+
+namespace {
+
+base::LazyInstance<PDFiumEngineExports>::Leaky g_pdf_engine_exports =
+ LAZY_INSTANCE_INITIALIZER;
+
+int CalculatePosition(FPDF_PAGE page,
+ const PDFiumEngineExports::RenderingSettings& settings,
+ pp::Rect* dest) {
+ int page_width = static_cast<int>(ConvertUnitDouble(FPDF_GetPageWidth(page),
+ kPointsPerInch,
+ settings.dpi_x));
+ int page_height = static_cast<int>(ConvertUnitDouble(FPDF_GetPageHeight(page),
+ kPointsPerInch,
+ settings.dpi_y));
+
+ // Start by assuming that we will draw exactly to the bounds rect
+ // specified.
+ *dest = settings.bounds;
+
+ int rotate = 0; // normal orientation.
+
+ // Auto-rotate landscape pages to print correctly.
+ if (settings.autorotate &&
+ (dest->width() > dest->height()) != (page_width > page_height)) {
+ rotate = 3; // 90 degrees counter-clockwise.
+ std::swap(page_width, page_height);
+ }
+
+ // See if we need to scale the output
+ bool scale_to_bounds = false;
+ if (settings.fit_to_bounds &&
+ ((page_width > dest->width()) || (page_height > dest->height()))) {
+ scale_to_bounds = true;
+ } else if (settings.stretch_to_bounds &&
+ ((page_width < dest->width()) || (page_height < dest->height()))) {
+ scale_to_bounds = true;
+ }
+
+ if (scale_to_bounds) {
+ // If we need to maintain aspect ratio, calculate the actual width and
+ // height.
+ if (settings.keep_aspect_ratio) {
+ double scale_factor_x = page_width;
+ scale_factor_x /= dest->width();
+ double scale_factor_y = page_height;
+ scale_factor_y /= dest->height();
+ if (scale_factor_x > scale_factor_y) {
+ dest->set_height(page_height / scale_factor_x);
+ } else {
+ dest->set_width(page_width / scale_factor_y);
+ }
+ }
+ } else {
+ // We are not scaling to bounds. Draw in the actual page size. If the
+ // actual page size is larger than the bounds, the output will be
+ // clipped.
+ dest->set_width(page_width);
+ dest->set_height(page_height);
+ }
+
+ if (settings.center_in_bounds) {
+ pp::Point offset((settings.bounds.width() - dest->width()) / 2,
+ (settings.bounds.height() - dest->height()) / 2);
+ dest->Offset(offset);
+ }
+ return rotate;
+}
+
+} // namespace
+
+PDFEngineExports* PDFEngineExports::Get() {
+ return g_pdf_engine_exports.Pointer();
+}
+
+#if defined(OS_WIN)
+bool PDFiumEngineExports::RenderPDFPageToDC(const void* pdf_buffer,
+ int buffer_size,
+ int page_number,
+ const RenderingSettings& settings,
+ HDC dc) {
+ FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, buffer_size, NULL);
+ if (!doc)
+ return false;
+ FPDF_PAGE page = FPDF_LoadPage(doc, page_number);
+ if (!page) {
+ FPDF_CloseDocument(doc);
+ return false;
+ }
+ RenderingSettings new_settings = settings;
+ // calculate the page size
+ if (new_settings.dpi_x == -1)
+ new_settings.dpi_x = GetDeviceCaps(dc, LOGPIXELSX);
+ if (new_settings.dpi_y == -1)
+ new_settings.dpi_y = GetDeviceCaps(dc, LOGPIXELSY);
+
+ pp::Rect dest;
+ int rotate = CalculatePosition(page, new_settings, &dest);
+
+ int save_state = SaveDC(dc);
+ // The caller wanted all drawing to happen within the bounds specified.
+ // Based on scale calculations, our destination rect might be larger
+ // than the bounds. Set the clip rect to the bounds.
+ IntersectClipRect(dc, settings.bounds.x(), settings.bounds.y(),
+ settings.bounds.x() + settings.bounds.width(),
+ settings.bounds.y() + settings.bounds.height());
+
+ // A "temporary" hack. Some PDFs seems to render very slowly if
+ // FPDF_RenderPage() is directly used on a printer DC. I suspect it is
+ // because of the code to talk Postscript directly to the printer if
+ // the printer supports this. Need to discuss this with PDFium. For now,
+ // render to a bitmap and then blit the bitmap to the DC if we have been
+ // supplied a printer DC.
+ int device_type = GetDeviceCaps(dc, TECHNOLOGY);
+ if (device_type == DT_RASPRINTER || device_type == DT_PLOTTER) {
+ FPDF_BITMAP bitmap = FPDFBitmap_Create(dest.width(), dest.height(),
+ FPDFBitmap_BGRx);
+ // Clear the bitmap
+ FPDFBitmap_FillRect(bitmap, 0, 0, dest.width(), dest.height(), 0xFFFFFFFF);
+ FPDF_RenderPageBitmap(
+ bitmap, page, 0, 0, dest.width(), dest.height(), rotate,
+ FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
+ int stride = FPDFBitmap_GetStride(bitmap);
+ BITMAPINFO bmi;
+ memset(&bmi, 0, sizeof(bmi));
+ bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
+ bmi.bmiHeader.biWidth = dest.width();
+ bmi.bmiHeader.biHeight = -dest.height(); // top-down image
+ bmi.bmiHeader.biPlanes = 1;
+ bmi.bmiHeader.biBitCount = 32;
+ bmi.bmiHeader.biCompression = BI_RGB;
+ bmi.bmiHeader.biSizeImage = stride * dest.height();
+ StretchDIBits(dc, dest.x(), dest.y(), dest.width(), dest.height(),
+ 0, 0, dest.width(), dest.height(),
+ FPDFBitmap_GetBuffer(bitmap), &bmi, DIB_RGB_COLORS, SRCCOPY);
+ FPDFBitmap_Destroy(bitmap);
+ } else {
+ FPDF_RenderPage(dc, page, dest.x(), dest.y(), dest.width(), dest.height(),
+ rotate, FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
+ }
+ RestoreDC(dc, save_state);
+ FPDF_ClosePage(page);
+ FPDF_CloseDocument(doc);
+ return true;
+}
+#endif // defined(OS_WIN)
+
+bool PDFiumEngineExports::RenderPDFPageToBitmap(
+ const void* pdf_buffer,
+ int pdf_buffer_size,
+ int page_number,
+ const RenderingSettings& settings,
+ void* bitmap_buffer) {
+ FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, pdf_buffer_size, NULL);
+ if (!doc)
+ return false;
+ FPDF_PAGE page = FPDF_LoadPage(doc, page_number);
+ if (!page) {
+ FPDF_CloseDocument(doc);
+ return false;
+ }
+
+ pp::Rect dest;
+ int rotate = CalculatePosition(page, settings, &dest);
+
+ FPDF_BITMAP bitmap =
+ FPDFBitmap_CreateEx(settings.bounds.width(), settings.bounds.height(),
+ FPDFBitmap_BGRA, bitmap_buffer,
+ settings.bounds.width() * 4);
+ // Clear the bitmap
+ FPDFBitmap_FillRect(bitmap, 0, 0, settings.bounds.width(),
+ settings.bounds.height(), 0xFFFFFFFF);
+ // Shift top-left corner of bounds to (0, 0) if it's not there.
+ dest.set_point(dest.point() - settings.bounds.point());
+ FPDF_RenderPageBitmap(
+ bitmap, page, dest.x(), dest.y(), dest.width(), dest.height(), rotate,
+ FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
+ FPDFBitmap_Destroy(bitmap);
+ FPDF_ClosePage(page);
+ FPDF_CloseDocument(doc);
+ return true;
+}
+
+bool PDFiumEngineExports::GetPDFDocInfo(const void* pdf_buffer,
+ int buffer_size,
+ int* page_count,
+ double* max_page_width) {
+ FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, buffer_size, NULL);
+ if (!doc)
+ return false;
+ int page_count_local = FPDF_GetPageCount(doc);
+ if (page_count) {
+ *page_count = page_count_local;
+ }
+ if (max_page_width) {
+ *max_page_width = 0;
+ for (int page_number = 0; page_number < page_count_local; page_number++) {
+ double page_width = 0;
+ double page_height = 0;
+ FPDF_GetPageSizeByIndex(doc, page_number, &page_width, &page_height);
+ if (page_width > *max_page_width) {
+ *max_page_width = page_width;
+ }
+ }
+ }
+ FPDF_CloseDocument(doc);
+ return true;
+}
+
+bool PDFiumEngineExports::GetPDFPageSizeByIndex(
+ const void* pdf_buffer,
+ int pdf_buffer_size,
+ int page_number,
+ double* width,
+ double* height) {
+ FPDF_DOCUMENT doc = FPDF_LoadMemDocument(pdf_buffer, pdf_buffer_size, NULL);
+ if (!doc)
+ return false;
+ bool success = FPDF_GetPageSizeByIndex(doc, page_number, width, height) != 0;
+ FPDF_CloseDocument(doc);
+ return success;
+}
+
+} // namespace chrome_pdf
diff --git a/chromium/pdf/pdfium/pdfium_engine.h b/chromium/pdf/pdfium/pdfium_engine.h
new file mode 100644
index 00000000000..e0b8af5bb8a
--- /dev/null
+++ b/chromium/pdf/pdfium/pdfium_engine.h
@@ -0,0 +1,757 @@
+// 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_PDFIUM_PDFIUM_ENGINE_H_
+#define PDF_PDFIUM_PDFIUM_ENGINE_H_
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include <map>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "base/macros.h"
+#include "base/memory/scoped_ptr.h"
+#include "base/time/time.h"
+#include "pdf/document_loader.h"
+#include "pdf/pdf_engine.h"
+#include "pdf/pdfium/pdfium_page.h"
+#include "pdf/pdfium/pdfium_range.h"
+#include "ppapi/cpp/completion_callback.h"
+#include "ppapi/cpp/dev/buffer_dev.h"
+#include "ppapi/cpp/image_data.h"
+#include "ppapi/cpp/point.h"
+#include "ppapi/cpp/var_array.h"
+#include "third_party/pdfium/public/fpdf_dataavail.h"
+#include "third_party/pdfium/public/fpdf_formfill.h"
+#include "third_party/pdfium/public/fpdf_progressive.h"
+#include "third_party/pdfium/public/fpdfview.h"
+
+namespace pp {
+class KeyboardInputEvent;
+class MouseInputEvent;
+class VarDictionary;
+}
+
+namespace chrome_pdf {
+
+class ShadowMatrix;
+
+class PDFiumEngine : public PDFEngine,
+ public DocumentLoader::Client,
+ public FPDF_FORMFILLINFO,
+ public IPDF_JSPLATFORM,
+ public IFSDK_PAUSE {
+ public:
+ explicit PDFiumEngine(PDFEngine::Client* client);
+ ~PDFiumEngine() override;
+
+ // PDFEngine implementation.
+ bool New(const char* url, const char* headers) override;
+ void PageOffsetUpdated(const pp::Point& page_offset) override;
+ void PluginSizeUpdated(const pp::Size& size) override;
+ void ScrolledToXPosition(int position) override;
+ void ScrolledToYPosition(int position) override;
+ void PrePaint() override;
+ void Paint(const pp::Rect& rect,
+ pp::ImageData* image_data,
+ std::vector<pp::Rect>* ready,
+ std::vector<pp::Rect>* pending) override;
+ void PostPaint() override;
+ bool HandleDocumentLoad(const pp::URLLoader& loader) override;
+ bool HandleEvent(const pp::InputEvent& event) override;
+ uint32_t QuerySupportedPrintOutputFormats() override;
+ void PrintBegin() override;
+ pp::Resource PrintPages(const PP_PrintPageNumberRange_Dev* page_ranges,
+ uint32_t page_range_count,
+ const PP_PrintSettings_Dev& print_settings) override;
+ void PrintEnd() override;
+ void StartFind(const std::string& text, bool case_sensitive) override;
+ bool SelectFindResult(bool forward) override;
+ void StopFind() override;
+ void ZoomUpdated(double new_zoom_level) override;
+ void RotateClockwise() override;
+ void RotateCounterclockwise() override;
+ std::string GetSelectedText() override;
+ std::string GetLinkAtPosition(const pp::Point& point) override;
+ bool HasPermission(DocumentPermission permission) const override;
+ void SelectAll() override;
+ int GetNumberOfPages() override;
+ pp::VarArray GetBookmarks() override;
+ int GetNamedDestinationPage(const std::string& destination) override;
+ int GetMostVisiblePage() override;
+ pp::Rect GetPageRect(int index) override;
+ pp::Rect GetPageContentsRect(int index) override;
+ pp::Rect GetPageScreenRect(int page_index) const override;
+ int GetVerticalScrollbarYPosition() override { return position_.y(); }
+ void SetGrayscale(bool grayscale) override;
+ void OnCallback(int id) override;
+ std::string GetPageAsJSON(int index) override;
+ bool GetPrintScaling() override;
+ int GetCopiesToPrint() override;
+ int GetDuplexType() override;
+ bool GetPageSizeAndUniformity(pp::Size* size) override;
+ void AppendBlankPages(int num_pages) override;
+ void AppendPage(PDFEngine* engine, int index) override;
+ pp::Point GetScrollPosition() override;
+ void SetScrollPosition(const pp::Point& position) override;
+ bool IsProgressiveLoad() override;
+ std::string GetMetadata(const std::string& key) override;
+
+ // DocumentLoader::Client implementation.
+ pp::Instance* GetPluginInstance() override;
+ pp::URLLoader CreateURLLoader() override;
+ void OnPartialDocumentLoaded() override;
+ void OnPendingRequestComplete() override;
+ void OnNewDataAvailable() override;
+ void OnDocumentComplete() override;
+
+ void UnsupportedFeature(int type);
+
+ std::string current_find_text() const { return current_find_text_; }
+
+ FPDF_DOCUMENT doc() { return doc_; }
+ FPDF_FORMHANDLE form() { return form_; }
+
+ private:
+ // This helper class is used to detect the difference in selection between
+ // construction and destruction. At destruction, it invalidates all the
+ // parts that are newly selected, along with all the parts that used to be
+ // selected but are not anymore.
+ class SelectionChangeInvalidator {
+ public:
+ explicit SelectionChangeInvalidator(PDFiumEngine* engine);
+ ~SelectionChangeInvalidator();
+ private:
+ // Sets the given container to the all the currently visible selection
+ // rectangles, in screen coordinates.
+ void GetVisibleSelectionsScreenRects(std::vector<pp::Rect>* rects);
+
+ PDFiumEngine* engine_;
+ // Screen rectangles that were selected on construction.
+ std::vector<pp::Rect> old_selections_;
+ // The origin at the time this object was constructed.
+ pp::Point previous_origin_;
+ };
+
+ // Used to store mouse down state to handle it in other mouse event handlers.
+ class MouseDownState {
+ public:
+ MouseDownState(const PDFiumPage::Area& area,
+ const PDFiumPage::LinkTarget& target);
+ ~MouseDownState();
+
+ void Set(const PDFiumPage::Area& area,
+ const PDFiumPage::LinkTarget& target);
+ void Reset();
+ bool Matches(const PDFiumPage::Area& area,
+ const PDFiumPage::LinkTarget& target) const;
+
+ private:
+ PDFiumPage::Area area_;
+ PDFiumPage::LinkTarget target_;
+
+ DISALLOW_COPY_AND_ASSIGN(MouseDownState);
+ };
+
+ // Used to store the state of a text search.
+ class FindTextIndex {
+ public:
+ FindTextIndex();
+ ~FindTextIndex();
+
+ bool valid() const { return valid_; }
+ void Invalidate();
+
+ size_t GetIndex() const;
+ void SetIndex(size_t index);
+ size_t IncrementIndex();
+
+ private:
+ bool valid_; // Whether |index_| is valid or not.
+ size_t index_; // The current search result, 0-based.
+
+ DISALLOW_COPY_AND_ASSIGN(FindTextIndex);
+ };
+
+ friend class SelectionChangeInvalidator;
+
+ struct FileAvail : public FX_FILEAVAIL {
+ DocumentLoader* loader;
+ };
+
+ struct DownloadHints : public FX_DOWNLOADHINTS {
+ DocumentLoader* loader;
+ };
+
+ // PDFium interface to get block of data.
+ static int GetBlock(void* param, unsigned long position,
+ unsigned char* buffer, unsigned long size);
+
+ // PDFium interface to check is block of data is available.
+ static FPDF_BOOL IsDataAvail(FX_FILEAVAIL* param,
+ size_t offset, size_t size);
+
+ // PDFium interface to request download of the block of data.
+ static void AddSegment(FX_DOWNLOADHINTS* param,
+ size_t offset, size_t size);
+
+ // We finished getting the pdf file, so load it. This will complete
+ // asynchronously (due to password fetching) and may be run multiple times.
+ void LoadDocument();
+
+ // Try loading the document. Returns true if the document is successfully
+ // loaded or is already loaded otherwise it will return false. If
+ // |with_password| is set to true, the document will be loaded with
+ // |password|. If the document could not be loaded and needs a password,
+ // |needs_password| will be set to true.
+ bool TryLoadingDoc(bool with_password,
+ const std::string& password,
+ bool* needs_password);
+
+ // Ask the user for the document password and then continue loading the
+ // document.
+ void GetPasswordAndLoad();
+
+ // Called when the password has been retrieved.
+ void OnGetPasswordComplete(int32_t result,
+ const pp::Var& password);
+
+ // Continues loading the document when the password has been retrieved, or if
+ // there is no password.
+ void ContinueLoadingDocument(bool has_password,
+ const std::string& password);
+
+ // Finish loading the document and notify the client that the document has
+ // been loaded. This should only be run after |doc_| has been loaded and the
+ // document is fully downloaded. If this has been run once, it will result in
+ // a no-op.
+ void FinishLoadingDocument();
+
+ // Loads information about the pages in the document and calculate the
+ // document size.
+ void LoadPageInfo(bool reload);
+
+ // Calculate which pages should be displayed right now.
+ void CalculateVisiblePages();
+
+ // Returns true iff the given page index is visible. CalculateVisiblePages
+ // must have been called first.
+ bool IsPageVisible(int index) const;
+
+ // Checks if a page is now available, and if so marks it as such and returns
+ // true. Otherwise, it will return false and will add the index to the given
+ // array if it's not already there.
+ bool CheckPageAvailable(int index, std::vector<int>* pending);
+
+ // Helper function to get a given page's size in pixels. This is not part of
+ // PDFiumPage because we might not have that structure when we need this.
+ pp::Size GetPageSize(int index);
+
+ void GetAllScreenRectsUnion(std::vector<PDFiumRange>* rect_range,
+ const pp::Point& offset_point,
+ std::vector<pp::Rect>* rect_vector);
+
+ void UpdateTickMarks();
+
+ // Called to continue searching so we don't block the main thread.
+ void ContinueFind(int32_t result);
+
+ // Inserts a find result into find_results_, which is sorted.
+ void AddFindResult(const PDFiumRange& result);
+
+ // Search a page using PDFium's methods. Doesn't work with unicode. This
+ // function is just kept arount in case PDFium code is fixed.
+ void SearchUsingPDFium(const base::string16& term,
+ bool case_sensitive,
+ bool first_search,
+ int character_to_start_searching_from,
+ int current_page);
+
+ // Search a page ourself using ICU.
+ void SearchUsingICU(const base::string16& term,
+ bool case_sensitive,
+ bool first_search,
+ int character_to_start_searching_from,
+ int current_page);
+
+ // Input event handlers.
+ bool OnMouseDown(const pp::MouseInputEvent& event);
+ bool OnMouseUp(const pp::MouseInputEvent& event);
+ bool OnMouseMove(const pp::MouseInputEvent& event);
+ bool OnKeyDown(const pp::KeyboardInputEvent& event);
+ bool OnKeyUp(const pp::KeyboardInputEvent& event);
+ bool OnChar(const pp::KeyboardInputEvent& event);
+
+ FPDF_DOCUMENT CreateSinglePageRasterPdf(
+ double source_page_width,
+ double source_page_height,
+ const PP_PrintSettings_Dev& print_settings,
+ PDFiumPage* page_to_print);
+
+ pp::Buffer_Dev PrintPagesAsRasterPDF(
+ const PP_PrintPageNumberRange_Dev* page_ranges,
+ uint32_t page_range_count,
+ const PP_PrintSettings_Dev& print_settings);
+
+ pp::Buffer_Dev PrintPagesAsPDF(const PP_PrintPageNumberRange_Dev* page_ranges,
+ uint32_t page_range_count,
+ const PP_PrintSettings_Dev& print_settings);
+
+ pp::Buffer_Dev GetFlattenedPrintData(const FPDF_DOCUMENT& doc);
+ void FitContentsToPrintableAreaIfRequired(
+ const FPDF_DOCUMENT& doc,
+ const PP_PrintSettings_Dev& print_settings);
+ void SaveSelectedFormForPrint();
+
+ // Given a mouse event, returns which page and character location it's closest
+ // to.
+ PDFiumPage::Area GetCharIndex(const pp::MouseInputEvent& event,
+ int* page_index,
+ int* char_index,
+ int* form_type,
+ PDFiumPage::LinkTarget* target);
+ PDFiumPage::Area GetCharIndex(const pp::Point& point,
+ int* page_index,
+ int* char_index,
+ int* form_type,
+ PDFiumPage::LinkTarget* target);
+
+ void OnSingleClick(int page_index, int char_index);
+ void OnMultipleClick(int click_count, int page_index, int char_index);
+
+ // Starts a progressive paint operation given a rectangle in screen
+ // coordinates. Returns the index in progressive_rects_.
+ int StartPaint(int page_index, const pp::Rect& dirty);
+
+ // Continues a paint operation that was started earlier. Returns true if the
+ // paint is done, or false if it needs to be continued.
+ bool ContinuePaint(int progressive_index, pp::ImageData* image_data);
+
+ // Called once PDFium is finished rendering a page so that we draw our
+ // borders, highlighting etc.
+ void FinishPaint(int progressive_index, pp::ImageData* image_data);
+
+ // Stops any paints that are in progress.
+ void CancelPaints();
+
+ // Invalidates all pages. Use this when some global parameter, such as page
+ // orientation, has changed.
+ void InvalidateAllPages();
+
+ // If the page is narrower than the document size, paint the extra space
+ // with the page background.
+ void FillPageSides(int progressive_index);
+
+ void PaintPageShadow(int progressive_index, pp::ImageData* image_data);
+
+ // Highlight visible find results and selections.
+ void DrawSelections(int progressive_index, pp::ImageData* image_data);
+
+ // Paints an page that hasn't finished downloading.
+ void PaintUnavailablePage(int page_index,
+ const pp::Rect& dirty,
+ pp::ImageData* image_data);
+
+ // Given a page index, returns the corresponding index in progressive_rects_,
+ // or -1 if it doesn't exist.
+ int GetProgressiveIndex(int page_index) const;
+
+ // Creates a FPDF_BITMAP from a rectangle in screen coordinates.
+ FPDF_BITMAP CreateBitmap(const pp::Rect& rect,
+ pp::ImageData* image_data) const;
+
+ // Given a rectangle in screen coordinates, returns the coordinates in the
+ // units that PDFium rendering functions expect.
+ void GetPDFiumRect(int page_index, const pp::Rect& rect, int* start_x,
+ int* start_y, int* size_x, int* size_y) const;
+
+ // Returns the rendering flags to pass to PDFium.
+ int GetRenderingFlags() const;
+
+ // Returns the currently visible rectangle in document coordinates.
+ pp::Rect GetVisibleRect() const;
+
+ // Given a rectangle in document coordinates, returns the rectange into screen
+ // coordinates (i.e. 0,0 is top left corner of plugin area). If it's not
+ // visible, an empty rectangle is returned.
+ pp::Rect GetScreenRect(const pp::Rect& rect) const;
+
+ // Highlights the given rectangle.
+ void Highlight(void* buffer,
+ int stride,
+ const pp::Rect& rect,
+ std::vector<pp::Rect>* highlighted_rects);
+
+ // Helper function to convert a device to page coordinates. If the page is
+ // not yet loaded, page_x and page_y will be set to 0.
+ void DeviceToPage(int page_index,
+ float device_x,
+ float device_y,
+ double* page_x,
+ double* page_y);
+
+ // Helper function to get the index of a given FPDF_PAGE. Returns -1 if not
+ // found.
+ int GetVisiblePageIndex(FPDF_PAGE page);
+
+ // Helper function to change the current page, running page open/close
+ // triggers as necessary.
+ void SetCurrentPage(int index);
+
+ // Transform |page| contents to fit in the selected printer paper size.
+ void TransformPDFPageForPrinting(FPDF_PAGE page,
+ const PP_PrintSettings_Dev& print_settings);
+
+ void DrawPageShadow(const pp::Rect& page_rect,
+ const pp::Rect& shadow_rect,
+ const pp::Rect& clip_rect,
+ pp::ImageData* image_data);
+
+ void GetRegion(const pp::Point& location,
+ pp::ImageData* image_data,
+ void** region,
+ int* stride) const;
+
+ // Called when the selection changes.
+ void OnSelectionChanged();
+
+ // Common code shared by RotateClockwise() and RotateCounterclockwise().
+ void RotateInternal();
+
+ // Setting selection status of document.
+ void SetSelecting(bool selecting);
+
+ // FPDF_FORMFILLINFO callbacks.
+ static void Form_Invalidate(FPDF_FORMFILLINFO* param,
+ FPDF_PAGE page,
+ double left,
+ double top,
+ double right,
+ double bottom);
+ static void Form_OutputSelectedRect(FPDF_FORMFILLINFO* param,
+ FPDF_PAGE page,
+ double left,
+ double top,
+ double right,
+ double bottom);
+ static void Form_SetCursor(FPDF_FORMFILLINFO* param, int cursor_type);
+ static int Form_SetTimer(FPDF_FORMFILLINFO* param,
+ int elapse,
+ TimerCallback timer_func);
+ static void Form_KillTimer(FPDF_FORMFILLINFO* param, int timer_id);
+ static FPDF_SYSTEMTIME Form_GetLocalTime(FPDF_FORMFILLINFO* param);
+ static void Form_OnChange(FPDF_FORMFILLINFO* param);
+ static FPDF_PAGE Form_GetPage(FPDF_FORMFILLINFO* param,
+ FPDF_DOCUMENT document,
+ int page_index);
+ static FPDF_PAGE Form_GetCurrentPage(FPDF_FORMFILLINFO* param,
+ FPDF_DOCUMENT document);
+ static int Form_GetRotation(FPDF_FORMFILLINFO* param, FPDF_PAGE page);
+ static void Form_ExecuteNamedAction(FPDF_FORMFILLINFO* param,
+ FPDF_BYTESTRING named_action);
+ static void Form_SetTextFieldFocus(FPDF_FORMFILLINFO* param,
+ FPDF_WIDESTRING value,
+ FPDF_DWORD valueLen,
+ FPDF_BOOL is_focus);
+ static void Form_DoURIAction(FPDF_FORMFILLINFO* param, FPDF_BYTESTRING uri);
+ static void Form_DoGoToAction(FPDF_FORMFILLINFO* param,
+ int page_index,
+ int zoom_mode,
+ float* position_array,
+ int size_of_array);
+
+ // IPDF_JSPLATFORM callbacks.
+ static int Form_Alert(IPDF_JSPLATFORM* param,
+ FPDF_WIDESTRING message,
+ FPDF_WIDESTRING title,
+ int type,
+ int icon);
+ static void Form_Beep(IPDF_JSPLATFORM* param, int type);
+ static int Form_Response(IPDF_JSPLATFORM* param,
+ FPDF_WIDESTRING question,
+ FPDF_WIDESTRING title,
+ FPDF_WIDESTRING default_response,
+ FPDF_WIDESTRING label,
+ FPDF_BOOL password,
+ void* response,
+ int length);
+ static int Form_GetFilePath(IPDF_JSPLATFORM* param,
+ void* file_path,
+ int length);
+ static void Form_Mail(IPDF_JSPLATFORM* param,
+ void* mail_data,
+ int length,
+ FPDF_BOOL ui,
+ FPDF_WIDESTRING to,
+ FPDF_WIDESTRING subject,
+ FPDF_WIDESTRING cc,
+ FPDF_WIDESTRING bcc,
+ FPDF_WIDESTRING message);
+ static void Form_Print(IPDF_JSPLATFORM* param,
+ FPDF_BOOL ui,
+ int start,
+ int end,
+ FPDF_BOOL silent,
+ FPDF_BOOL shrink_to_fit,
+ FPDF_BOOL print_as_image,
+ FPDF_BOOL reverse,
+ FPDF_BOOL annotations);
+ static void Form_SubmitForm(IPDF_JSPLATFORM* param,
+ void* form_data,
+ int length,
+ FPDF_WIDESTRING url);
+ static void Form_GotoPage(IPDF_JSPLATFORM* param, int page_number);
+ static int Form_Browse(IPDF_JSPLATFORM* param, void* file_path, int length);
+
+#ifdef PDF_USE_XFA
+ static void Form_EmailTo(FPDF_FORMFILLINFO* param,
+ FPDF_FILEHANDLER* file_handler,
+ FPDF_WIDESTRING to,
+ FPDF_WIDESTRING subject,
+ FPDF_WIDESTRING cc,
+ FPDF_WIDESTRING bcc,
+ FPDF_WIDESTRING message);
+ static void Form_DisplayCaret(FPDF_FORMFILLINFO* param,
+ FPDF_PAGE page,
+ FPDF_BOOL visible,
+ double left,
+ double top,
+ double right,
+ double bottom);
+ static void Form_SetCurrentPage(FPDF_FORMFILLINFO* param,
+ FPDF_DOCUMENT document,
+ int page);
+ static int Form_GetCurrentPageIndex(FPDF_FORMFILLINFO* param,
+ FPDF_DOCUMENT document);
+ static void Form_GetPageViewRect(FPDF_FORMFILLINFO* param,
+ FPDF_PAGE page,
+ double* left,
+ double* top,
+ double* right,
+ double* bottom);
+ static int Form_GetPlatform(FPDF_FORMFILLINFO* param,
+ void* platform,
+ int length);
+ static FPDF_BOOL Form_PopupMenu(FPDF_FORMFILLINFO* param,
+ FPDF_PAGE page,
+ FPDF_WIDGET widget,
+ int menu_flag,
+ float x,
+ float y);
+ static FPDF_BOOL Form_PostRequestURL(FPDF_FORMFILLINFO* param,
+ FPDF_WIDESTRING url,
+ FPDF_WIDESTRING data,
+ FPDF_WIDESTRING content_type,
+ FPDF_WIDESTRING encode,
+ FPDF_WIDESTRING header,
+ FPDF_BSTR* response);
+ static FPDF_BOOL Form_PutRequestURL(FPDF_FORMFILLINFO* param,
+ FPDF_WIDESTRING url,
+ FPDF_WIDESTRING data,
+ FPDF_WIDESTRING encode);
+ static void Form_UploadTo(FPDF_FORMFILLINFO* param,
+ FPDF_FILEHANDLER* file_handler,
+ int file_flag,
+ FPDF_WIDESTRING dest);
+ static FPDF_LPFILEHANDLER Form_DownloadFromURL(FPDF_FORMFILLINFO* param,
+ FPDF_WIDESTRING url);
+ static FPDF_FILEHANDLER* Form_OpenFile(FPDF_FORMFILLINFO* param,
+ int file_flag,
+ FPDF_WIDESTRING url,
+ const char* mode);
+ static void Form_GotoURL(FPDF_FORMFILLINFO* param,
+ FPDF_DOCUMENT document,
+ FPDF_WIDESTRING url);
+ static int Form_GetLanguage(FPDF_FORMFILLINFO* param,
+ void* language,
+ int length);
+#endif // PDF_USE_XFA
+
+ // IFSDK_PAUSE callbacks
+ static FPDF_BOOL Pause_NeedToPauseNow(IFSDK_PAUSE* param);
+
+ PDFEngine::Client* const client_;
+ pp::Size document_size_; // Size of document in pixels.
+
+ // The scroll position in screen coordinates.
+ pp::Point position_;
+ // The offset of the page into the viewport.
+ pp::Point page_offset_;
+ // The plugin size in screen coordinates.
+ pp::Size plugin_size_;
+ double current_zoom_;
+ unsigned int current_rotation_;
+
+ DocumentLoader doc_loader_; // Main document's loader.
+ std::string url_;
+ std::string headers_;
+ pp::CompletionCallbackFactory<PDFiumEngine> find_factory_;
+
+ pp::CompletionCallbackFactory<PDFiumEngine> password_factory_;
+ int32_t password_tries_remaining_;
+
+ // The current text used for searching.
+ std::string current_find_text_;
+
+ // The PDFium wrapper object for the document.
+ FPDF_DOCUMENT doc_;
+
+ // The PDFium wrapper for form data. Used even if there are no form controls
+ // on the page.
+ FPDF_FORMHANDLE form_;
+
+ // The page(s) of the document. Store a vector of pointers so that when the
+ // vector is resized we don't close the pages that are used in pending
+ // paints.
+ std::vector<PDFiumPage*> pages_;
+
+ // The indexes of the pages currently visible.
+ std::vector<int> visible_pages_;
+
+ // The indexes of the pages pending download.
+ std::vector<int> pending_pages_;
+
+ // During handling of input events we don't want to unload any pages in
+ // callbacks to us from PDFium, since the current page can change while PDFium
+ // code still has a pointer to it.
+ bool defer_page_unload_;
+ std::vector<int> deferred_page_unloads_;
+
+ // Used for selection. There could be more than one range if selection spans
+ // more than one page.
+ std::vector<PDFiumRange> selection_;
+ // True if we're in the middle of selection.
+ bool selecting_;
+
+ MouseDownState mouse_down_state_;
+
+ // Used for searching.
+ typedef std::vector<PDFiumRange> FindResults;
+ FindResults find_results_;
+ // Which page to search next.
+ int next_page_to_search_;
+ // Where to stop searching.
+ int last_page_to_search_;
+ int last_character_index_to_search_; // -1 if search until end of page.
+ // Which result the user has currently selected.
+ FindTextIndex current_find_index_;
+ // Where to resume searching.
+ FindTextIndex resume_find_index_;
+
+ // Permissions bitfield.
+ unsigned long permissions_;
+
+ // Permissions security handler revision number. -1 for unknown.
+ int permissions_handler_revision_;
+
+ // Interface structure to provide access to document stream.
+ FPDF_FILEACCESS file_access_;
+ // Interface structure to check data availability in the document stream.
+ FileAvail file_availability_;
+ // Interface structure to request data chunks from the document stream.
+ DownloadHints download_hints_;
+ // Pointer to the document availability interface.
+ FPDF_AVAIL fpdf_availability_;
+
+ pp::Size default_page_size_;
+
+ // Used to manage timers that form fill API needs. The pair holds the timer
+ // period, in ms, and the callback function.
+ std::map<int, std::pair<int, TimerCallback> > timers_;
+ int next_timer_id_;
+
+ // Holds the page index of the last page that the mouse clicked on.
+ int last_page_mouse_down_;
+
+ // Holds the page index of the most visible page; refreshed by calling
+ // CalculateVisiblePages()
+ int most_visible_page_;
+
+ // Set to true after FORM_DoDocumentJSAction/FORM_DoDocumentOpenAction have
+ // been called. Only after that can we call FORM_DoPageAAction.
+ bool called_do_document_action_;
+
+ // Records parts of form fields that need to be highlighted at next paint, in
+ // screen coordinates.
+ std::vector<pp::Rect> form_highlights_;
+
+ // Whether to render in grayscale or in color.
+ bool render_grayscale_;
+
+ // The link currently under the cursor.
+ std::string link_under_cursor_;
+
+ // Pending progressive paints.
+ struct ProgressivePaint {
+ pp::Rect rect; // In screen coordinates.
+ FPDF_BITMAP bitmap;
+ int page_index;
+ // Temporary used to figure out if in a series of Paint() calls whether this
+ // pending paint was updated or not.
+ bool painted_;
+ };
+ std::vector<ProgressivePaint> progressive_paints_;
+
+ // Keeps track of when we started the last progressive paint, so that in our
+ // callback we can determine if we need to pause.
+ base::Time last_progressive_start_time_;
+
+ // The timeout to use for the current progressive paint.
+ int progressive_paint_timeout_;
+
+ // Shadow matrix for generating the page shadow bitmap.
+ scoped_ptr<ShadowMatrix> page_shadow_;
+
+ // Set to true if the user is being prompted for their password. Will be set
+ // to false after the user finishes getting their password.
+ bool getting_password_;
+
+ DISALLOW_COPY_AND_ASSIGN(PDFiumEngine);
+};
+
+// Create a local variable of this when calling PDFium functions which can call
+// our global callback when an unsupported feature is reached.
+class ScopedUnsupportedFeature {
+ public:
+ explicit ScopedUnsupportedFeature(PDFiumEngine* engine);
+ ~ScopedUnsupportedFeature();
+ private:
+ PDFiumEngine* engine_;
+ PDFiumEngine* old_engine_;
+};
+
+class PDFiumEngineExports : public PDFEngineExports {
+ public:
+ PDFiumEngineExports() {}
+
+// PDFEngineExports:
+#if defined(OS_WIN)
+ bool RenderPDFPageToDC(const void* pdf_buffer,
+ int buffer_size,
+ int page_number,
+ const RenderingSettings& settings,
+ HDC dc) override;
+#endif // defined(OS_WIN)
+ bool RenderPDFPageToBitmap(const void* pdf_buffer,
+ int pdf_buffer_size,
+ int page_number,
+ const RenderingSettings& settings,
+ void* bitmap_buffer) override;
+ bool GetPDFDocInfo(const void* pdf_buffer,
+ int buffer_size,
+ int* page_count,
+ double* max_page_width) override;
+ bool GetPDFPageSizeByIndex(const void* pdf_buffer,
+ int pdf_buffer_size,
+ int page_number,
+ double* width,
+ double* height) override;
+};
+
+} // namespace chrome_pdf
+
+#endif // PDF_PDFIUM_PDFIUM_ENGINE_H_
diff --git a/chromium/pdf/pdfium/pdfium_mem_buffer_file_read.cc b/chromium/pdf/pdfium/pdfium_mem_buffer_file_read.cc
new file mode 100644
index 00000000000..56d766217f3
--- /dev/null
+++ b/chromium/pdf/pdfium/pdfium_mem_buffer_file_read.cc
@@ -0,0 +1,35 @@
+// 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/pdfium/pdfium_mem_buffer_file_read.h"
+
+#include <stddef.h>
+#include <string.h>
+
+namespace chrome_pdf {
+
+PDFiumMemBufferFileRead::PDFiumMemBufferFileRead(const void* data,
+ size_t size) {
+ m_FileLen = size;
+ m_Param = this;
+ m_GetBlock = &GetBlock;
+ data_ = reinterpret_cast<const unsigned char*>(data);
+}
+
+PDFiumMemBufferFileRead::~PDFiumMemBufferFileRead() {
+}
+
+int PDFiumMemBufferFileRead::GetBlock(void* param,
+ unsigned long position,
+ unsigned char* buf,
+ unsigned long size) {
+ const PDFiumMemBufferFileRead* data =
+ reinterpret_cast<const PDFiumMemBufferFileRead*>(param);
+ if (!data || position + size > data->m_FileLen)
+ return 0;
+ memcpy(buf, data->data_ + position, size);
+ return 1;
+}
+
+} // namespace chrome_pdf
diff --git a/chromium/pdf/pdfium/pdfium_mem_buffer_file_read.h b/chromium/pdf/pdfium/pdfium_mem_buffer_file_read.h
new file mode 100644
index 00000000000..1c4b77974d2
--- /dev/null
+++ b/chromium/pdf/pdfium/pdfium_mem_buffer_file_read.h
@@ -0,0 +1,31 @@
+// 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_PDFIUM_PDFIUM_MEM_BUFFER_FILE_READ_H_
+#define PDF_PDFIUM_PDFIUM_MEM_BUFFER_FILE_READ_H_
+
+#include <stddef.h>
+#include <stdlib.h>
+
+#include "third_party/pdfium/public/fpdfview.h"
+
+namespace chrome_pdf {
+
+// Implementation of FPDF_FILEACCESS from a memory buffer.
+class PDFiumMemBufferFileRead : public FPDF_FILEACCESS {
+ public:
+ PDFiumMemBufferFileRead(const void* data, size_t size);
+ ~PDFiumMemBufferFileRead();
+
+ private:
+ static int GetBlock(void* param,
+ unsigned long position,
+ unsigned char* buf,
+ unsigned long size);
+ const unsigned char* data_;
+};
+
+} // namespace chrome_pdf
+
+#endif // PDF_PDFIUM_PDFIUM_MEM_BUFFER_FILE_READ_H_
diff --git a/chromium/pdf/pdfium/pdfium_mem_buffer_file_write.cc b/chromium/pdf/pdfium/pdfium_mem_buffer_file_write.cc
new file mode 100644
index 00000000000..45e564b67ba
--- /dev/null
+++ b/chromium/pdf/pdfium/pdfium_mem_buffer_file_write.cc
@@ -0,0 +1,33 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "pdf/pdfium/pdfium_mem_buffer_file_write.h"
+
+namespace chrome_pdf {
+
+PDFiumMemBufferFileWrite::PDFiumMemBufferFileWrite() {
+ version = 1;
+ WriteBlock = &WriteBlockImpl;
+}
+
+PDFiumMemBufferFileWrite::~PDFiumMemBufferFileWrite() {
+}
+
+int PDFiumMemBufferFileWrite::WriteBlockImpl(FPDF_FILEWRITE* this_file_write,
+ const void* data,
+ unsigned long size) {
+ PDFiumMemBufferFileWrite* mem_buffer_file_write =
+ static_cast<PDFiumMemBufferFileWrite*>(this_file_write);
+ return mem_buffer_file_write->DoWriteBlock(data, size);
+}
+
+int PDFiumMemBufferFileWrite::DoWriteBlock(const void* data,
+ unsigned long size) {
+ buffer_.append(static_cast<const unsigned char*>(data), size);
+ return 1;
+}
+
+
+} // namespace chrome_pdf
+
diff --git a/chromium/pdf/pdfium/pdfium_mem_buffer_file_write.h b/chromium/pdf/pdfium/pdfium_mem_buffer_file_write.h
new file mode 100644
index 00000000000..ed940f8cd6a
--- /dev/null
+++ b/chromium/pdf/pdfium/pdfium_mem_buffer_file_write.h
@@ -0,0 +1,36 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef PDF_PDFIUM_PDFIUM_MEM_BUFFER_FILE_WRITE_
+#define PDF_PDFIUM_PDFIUM_MEM_BUFFER_FILE_WRITE_
+
+#include <stddef.h>
+
+#include <string>
+
+#include "third_party/pdfium/public/fpdf_save.h"
+
+namespace chrome_pdf {
+
+// Implementation of FPDF_FILEWRITE into a memory buffer.
+class PDFiumMemBufferFileWrite : public FPDF_FILEWRITE {
+ public:
+ PDFiumMemBufferFileWrite();
+ ~PDFiumMemBufferFileWrite();
+
+ const std::basic_string<unsigned char>& buffer() { return buffer_; }
+ size_t size() { return buffer_.size(); }
+
+ private:
+ int DoWriteBlock(const void* data, unsigned long size);
+ static int WriteBlockImpl(FPDF_FILEWRITE* this_file_write, const void* data,
+ unsigned long size);
+
+ std::basic_string<unsigned char> buffer_;
+};
+
+} // namespace chrome_pdf
+
+#endif // PDF_PDFIUM_PDFIUM_MEM_BUFFER_FILE_WRITE_
+
diff --git a/chromium/pdf/pdfium/pdfium_page.cc b/chromium/pdf/pdfium/pdfium_page.cc
new file mode 100644
index 00000000000..95a8fba3d71
--- /dev/null
+++ b/chromium/pdf/pdfium/pdfium_page.cc
@@ -0,0 +1,534 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "pdf/pdfium/pdfium_page.h"
+
+#include <math.h>
+#include <stddef.h>
+
+#include "base/logging.h"
+#include "base/strings/string_number_conversions.h"
+#include "base/strings/string_util.h"
+#include "base/strings/utf_string_conversions.h"
+#include "base/values.h"
+#include "pdf/pdfium/pdfium_api_string_buffer_adapter.h"
+#include "pdf/pdfium/pdfium_engine.h"
+
+// Used when doing hit detection.
+#define kTolerance 20.0
+
+namespace {
+
+// Dictionary Value key names for returning the accessible page content as JSON.
+const char kPageWidth[] = "width";
+const char kPageHeight[] = "height";
+const char kPageTextBox[] = "textBox";
+const char kTextBoxLeft[] = "left";
+const char kTextBoxTop[] = "top";
+const char kTextBoxWidth[] = "width";
+const char kTextBoxHeight[] = "height";
+const char kTextBoxFontSize[] = "fontSize";
+const char kTextBoxNodes[] = "textNodes";
+const char kTextNodeType[] = "type";
+const char kTextNodeText[] = "text";
+const char kTextNodeURL[] = "url";
+const char kTextNodeTypeText[] = "text";
+const char kTextNodeTypeURL[] = "url";
+const char kDocLinkURLPrefix[] = "#page";
+
+} // namespace
+
+namespace chrome_pdf {
+
+PDFiumPage::PDFiumPage(PDFiumEngine* engine,
+ int i,
+ const pp::Rect& r,
+ bool available)
+ : engine_(engine),
+ page_(NULL),
+ text_page_(NULL),
+ index_(i),
+ loading_count_(0),
+ rect_(r),
+ calculated_links_(false),
+ available_(available) {
+}
+
+PDFiumPage::~PDFiumPage() {
+ DCHECK_EQ(0, loading_count_);
+}
+
+void PDFiumPage::Unload() {
+ // Do not unload while in the middle of a load.
+ if (loading_count_)
+ return;
+
+ if (text_page_) {
+ FPDFText_ClosePage(text_page_);
+ text_page_ = NULL;
+ }
+
+ if (page_) {
+ if (engine_->form()) {
+ FORM_OnBeforeClosePage(page_, engine_->form());
+ }
+ FPDF_ClosePage(page_);
+ page_ = NULL;
+ }
+}
+
+FPDF_PAGE PDFiumPage::GetPage() {
+ ScopedUnsupportedFeature scoped_unsupported_feature(engine_);
+ if (!available_)
+ return NULL;
+ if (!page_) {
+ ScopedLoadCounter scoped_load(this);
+ page_ = FPDF_LoadPage(engine_->doc(), index_);
+ if (page_ && engine_->form()) {
+ FORM_OnAfterLoadPage(page_, engine_->form());
+ }
+ }
+ return page_;
+}
+
+FPDF_PAGE PDFiumPage::GetPrintPage() {
+ ScopedUnsupportedFeature scoped_unsupported_feature(engine_);
+ if (!available_)
+ return NULL;
+ if (!page_) {
+ ScopedLoadCounter scoped_load(this);
+ page_ = FPDF_LoadPage(engine_->doc(), index_);
+ }
+ return page_;
+}
+
+void PDFiumPage::ClosePrintPage() {
+ // Do not close |page_| while in the middle of a load.
+ if (loading_count_)
+ return;
+
+ if (page_) {
+ FPDF_ClosePage(page_);
+ page_ = NULL;
+ }
+}
+
+FPDF_TEXTPAGE PDFiumPage::GetTextPage() {
+ if (!available_)
+ return NULL;
+ if (!text_page_) {
+ ScopedLoadCounter scoped_load(this);
+ text_page_ = FPDFText_LoadPage(GetPage());
+ }
+ return text_page_;
+}
+
+base::Value* PDFiumPage::GetAccessibleContentAsValue(int rotation) {
+ base::DictionaryValue* node = new base::DictionaryValue();
+
+ if (!available_)
+ return node;
+
+ double width = FPDF_GetPageWidth(GetPage());
+ double height = FPDF_GetPageHeight(GetPage());
+
+ base::ListValue* text = new base::ListValue();
+ int box_count = FPDFText_CountRects(GetTextPage(), 0, GetCharCount());
+ for (int i = 0; i < box_count; i++) {
+ double left, top, right, bottom;
+ FPDFText_GetRect(GetTextPage(), i, &left, &top, &right, &bottom);
+ text->Append(
+ GetTextBoxAsValue(height, left, top, right, bottom, rotation));
+ }
+
+ node->SetDouble(kPageWidth, width);
+ node->SetDouble(kPageHeight, height);
+ node->Set(kPageTextBox, text); // Takes ownership of |text|
+
+ return node;
+}
+
+base::Value* PDFiumPage::GetTextBoxAsValue(double page_height,
+ double left, double top,
+ double right, double bottom,
+ int rotation) {
+ base::string16 text_utf16;
+ int char_count =
+ FPDFText_GetBoundedText(GetTextPage(), left, top, right, bottom, NULL, 0);
+ if (char_count > 0) {
+ unsigned short* data = reinterpret_cast<unsigned short*>(
+ base::WriteInto(&text_utf16, char_count + 1));
+ FPDFText_GetBoundedText(GetTextPage(),
+ left, top, right, bottom,
+ data, char_count);
+ }
+ std::string text_utf8 = base::UTF16ToUTF8(text_utf16);
+
+ FPDF_LINK link = FPDFLink_GetLinkAtPoint(GetPage(), left, top);
+ Area area;
+ std::vector<LinkTarget> targets;
+ if (link) {
+ targets.push_back(LinkTarget());
+ area = GetLinkTarget(link, &targets[0]);
+ } else {
+ pp::Rect rect(
+ PageToScreen(pp::Point(), 1.0, left, top, right, bottom, rotation));
+ GetLinks(rect, &targets);
+ area = targets.empty() ? TEXT_AREA : WEBLINK_AREA;
+ }
+
+ int char_index = FPDFText_GetCharIndexAtPos(GetTextPage(), left, top,
+ kTolerance, kTolerance);
+ double font_size = FPDFText_GetFontSize(GetTextPage(), char_index);
+
+ base::DictionaryValue* node = new base::DictionaryValue();
+ node->SetDouble(kTextBoxLeft, left);
+ node->SetDouble(kTextBoxTop, page_height - top);
+ node->SetDouble(kTextBoxWidth, right - left);
+ node->SetDouble(kTextBoxHeight, top - bottom);
+ node->SetDouble(kTextBoxFontSize, font_size);
+
+ base::ListValue* text_nodes = new base::ListValue();
+
+ if (area == DOCLINK_AREA) {
+ std::string url = kDocLinkURLPrefix + base::IntToString(targets[0].page);
+ text_nodes->Append(CreateURLNode(text_utf8, url));
+ } else if (area == WEBLINK_AREA && link) {
+ text_nodes->Append(CreateURLNode(text_utf8, targets[0].url));
+ } else if (area == WEBLINK_AREA && !link) {
+ size_t start = 0;
+ for (const auto& target : targets) {
+ // If there is an extra NULL character at end, find() will not return any
+ // matches. There should not be any though.
+ if (!target.url.empty())
+ DCHECK_NE(target.url.back(), '\0');
+
+ // PDFium may change the case of generated links.
+ std::string lowerCaseURL = base::ToLowerASCII(target.url);
+ std::string lowerCaseText = base::ToLowerASCII(text_utf8);
+ size_t pos = lowerCaseText.find(lowerCaseURL, start);
+ size_t length = target.url.size();
+ if (pos == std::string::npos) {
+ // Check if the link is a "mailto:" URL
+ if (lowerCaseURL.compare(0, 7, "mailto:") == 0) {
+ pos = lowerCaseText.find(lowerCaseURL.substr(7), start);
+ length -= 7;
+ }
+
+ if (pos == std::string::npos) {
+ // No match has been found. This should never happen.
+ continue;
+ }
+ }
+
+ std::string before_text = text_utf8.substr(start, pos - start);
+ if (!before_text.empty())
+ text_nodes->Append(CreateTextNode(before_text));
+ std::string link_text = text_utf8.substr(pos, length);
+ text_nodes->Append(CreateURLNode(link_text, target.url));
+
+ start = pos + length;
+ }
+ std::string before_text = text_utf8.substr(start);
+ if (!before_text.empty())
+ text_nodes->Append(CreateTextNode(before_text));
+ } else {
+ text_nodes->Append(CreateTextNode(text_utf8));
+ }
+
+ node->Set(kTextBoxNodes, text_nodes); // Takes ownership of |text_nodes|.
+ return node;
+}
+
+base::Value* PDFiumPage::CreateTextNode(const std::string& text) {
+ base::DictionaryValue* node = new base::DictionaryValue();
+ node->SetString(kTextNodeType, kTextNodeTypeText);
+ node->SetString(kTextNodeText, text);
+ return node;
+}
+
+base::Value* PDFiumPage::CreateURLNode(const std::string& text,
+ const std::string& url) {
+ base::DictionaryValue* node = new base::DictionaryValue();
+ node->SetString(kTextNodeType, kTextNodeTypeURL);
+ node->SetString(kTextNodeText, text);
+ node->SetString(kTextNodeURL, url);
+ return node;
+}
+
+PDFiumPage::Area PDFiumPage::GetCharIndex(const pp::Point& point,
+ int rotation,
+ int* char_index,
+ int* form_type,
+ LinkTarget* target) {
+ if (!available_)
+ return NONSELECTABLE_AREA;
+ pp::Point point2 = point - rect_.point();
+ double new_x;
+ double new_y;
+ FPDF_DeviceToPage(GetPage(), 0, 0, rect_.width(), rect_.height(),
+ rotation, point2.x(), point2.y(), &new_x, &new_y);
+
+ int rv = FPDFText_GetCharIndexAtPos(
+ GetTextPage(), new_x, new_y, kTolerance, kTolerance);
+ *char_index = rv;
+
+ FPDF_LINK link = FPDFLink_GetLinkAtPoint(GetPage(), new_x, new_y);
+ int control =
+ FPDPage_HasFormFieldAtPoint(engine_->form(), GetPage(), new_x, new_y);
+
+ // If there is a control and link at the same point, figure out their z-order
+ // to determine which is on top.
+ if (link && control > FPDF_FORMFIELD_UNKNOWN) {
+ int control_z_order = FPDFPage_FormFieldZOrderAtPoint(
+ engine_->form(), GetPage(), new_x, new_y);
+ int link_z_order = FPDFLink_GetLinkZOrderAtPoint(GetPage(), new_x, new_y);
+ DCHECK_NE(control_z_order, link_z_order);
+ if (control_z_order > link_z_order) {
+ *form_type = control;
+ return PDFiumPage::NONSELECTABLE_AREA;
+ }
+
+ // We don't handle all possible link types of the PDF. For example,
+ // launch actions, cross-document links, etc.
+ // In that case, GetLinkTarget() will return NONSELECTABLE_AREA
+ // and we should proceed with area detection.
+ PDFiumPage::Area area = GetLinkTarget(link, target);
+ if (area != PDFiumPage::NONSELECTABLE_AREA)
+ return area;
+ } else if (link) {
+ // We don't handle all possible link types of the PDF. For example,
+ // launch actions, cross-document links, etc.
+ // See identical block above.
+ PDFiumPage::Area area = GetLinkTarget(link, target);
+ if (area != PDFiumPage::NONSELECTABLE_AREA)
+ return area;
+ } else if (control > FPDF_FORMFIELD_UNKNOWN) {
+ *form_type = control;
+ return PDFiumPage::NONSELECTABLE_AREA;
+ }
+
+ if (rv < 0)
+ return NONSELECTABLE_AREA;
+
+ return GetLink(*char_index, target) != -1 ? WEBLINK_AREA : TEXT_AREA;
+}
+
+base::char16 PDFiumPage::GetCharAtIndex(int index) {
+ if (!available_)
+ return L'\0';
+ return static_cast<base::char16>(FPDFText_GetUnicode(GetTextPage(), index));
+}
+
+int PDFiumPage::GetCharCount() {
+ if (!available_)
+ return 0;
+ return FPDFText_CountChars(GetTextPage());
+}
+
+PDFiumPage::Area PDFiumPage::GetLinkTarget(
+ FPDF_LINK link, PDFiumPage::LinkTarget* target) const {
+ FPDF_DEST dest = FPDFLink_GetDest(engine_->doc(), link);
+ if (dest)
+ return GetDestinationTarget(dest, target);
+
+ FPDF_ACTION action = FPDFLink_GetAction(link);
+ if (action) {
+ switch (FPDFAction_GetType(action)) {
+ case PDFACTION_GOTO: {
+ FPDF_DEST dest = FPDFAction_GetDest(engine_->doc(), action);
+ if (dest)
+ return GetDestinationTarget(dest, target);
+ // TODO(gene): We don't fully support all types of the in-document
+ // links. Need to implement that. There is a bug to track that:
+ // http://code.google.com/p/chromium/issues/detail?id=55776
+ } break;
+ case PDFACTION_URI: {
+ if (target) {
+ size_t buffer_size =
+ FPDFAction_GetURIPath(engine_->doc(), action, NULL, 0);
+ if (buffer_size > 0) {
+ PDFiumAPIStringBufferAdapter<std::string> api_string_adapter(
+ &target->url, buffer_size, true);
+ void* data = api_string_adapter.GetData();
+ size_t bytes_written = FPDFAction_GetURIPath(
+ engine_->doc(), action, data, buffer_size);
+ api_string_adapter.Close(bytes_written);
+ }
+ }
+ return WEBLINK_AREA;
+ } break;
+ // TODO(gene): We don't support PDFACTION_REMOTEGOTO and PDFACTION_LAUNCH
+ // at the moment.
+ }
+ }
+
+ return NONSELECTABLE_AREA;
+}
+
+PDFiumPage::Area PDFiumPage::GetDestinationTarget(
+ FPDF_DEST destination, PDFiumPage::LinkTarget* target) const {
+ if (target)
+ target->page = FPDFDest_GetPageIndex(engine_->doc(), destination);
+ return DOCLINK_AREA;
+}
+
+int PDFiumPage::GetLink(int char_index, PDFiumPage::LinkTarget* target) {
+ if (!available_)
+ return -1;
+
+ CalculateLinks();
+
+ // Get the bounding box of the rect again, since it might have moved because
+ // of the tolerance above.
+ double left, right, bottom, top;
+ FPDFText_GetCharBox(GetTextPage(), char_index, &left, &right, &bottom, &top);
+
+ pp::Point origin(
+ PageToScreen(pp::Point(), 1.0, left, top, right, bottom, 0).point());
+ for (size_t i = 0; i < links_.size(); ++i) {
+ for (const auto& rect : links_[i].rects) {
+ if (rect.Contains(origin)) {
+ if (target)
+ target->url = links_[i].url;
+ return i;
+ }
+ }
+ }
+ return -1;
+}
+
+std::vector<int> PDFiumPage::GetLinks(pp::Rect text_area,
+ std::vector<LinkTarget>* targets) {
+ std::vector<int> links;
+ if (!available_)
+ return links;
+
+ CalculateLinks();
+
+ for (size_t i = 0; i < links_.size(); ++i) {
+ for (const auto& rect : links_[i].rects) {
+ if (rect.Intersects(text_area)) {
+ if (targets) {
+ LinkTarget target;
+ target.url = links_[i].url;
+ targets->push_back(target);
+ }
+ links.push_back(i);
+ }
+ }
+ }
+ return links;
+}
+
+void PDFiumPage::CalculateLinks() {
+ if (calculated_links_)
+ return;
+
+ calculated_links_ = true;
+ FPDF_PAGELINK links = FPDFLink_LoadWebLinks(GetTextPage());
+ int count = FPDFLink_CountWebLinks(links);
+ for (int i = 0; i < count; ++i) {
+ base::string16 url;
+ int url_length = FPDFLink_GetURL(links, i, NULL, 0);
+ if (url_length > 0) {
+ PDFiumAPIStringBufferAdapter<base::string16> api_string_adapter(
+ &url, url_length, true);
+ unsigned short* data =
+ reinterpret_cast<unsigned short*>(api_string_adapter.GetData());
+ int actual_length = FPDFLink_GetURL(links, i, data, url_length);
+ api_string_adapter.Close(actual_length);
+ }
+ Link link;
+ link.url = base::UTF16ToUTF8(url);
+
+ // If the link cannot be converted to a pp::Var, then it is not possible to
+ // pass it to JS. In this case, ignore the link like other PDF viewers.
+ // See http://crbug.com/312882 for an example.
+ pp::Var link_var(link.url);
+ if (!link_var.is_string())
+ continue;
+
+ // Make sure all the characters in the URL are valid per RFC 1738.
+ // http://crbug.com/340326 has a sample bad PDF.
+ // GURL does not work correctly, e.g. it just strips \t \r \n.
+ bool is_invalid_url = false;
+ for (size_t j = 0; j < link.url.length(); ++j) {
+ // Control characters are not allowed.
+ // 0x7F is also a control character.
+ // 0x80 and above are not in US-ASCII.
+ if (link.url[j] < ' ' || link.url[j] >= '\x7F') {
+ is_invalid_url = true;
+ break;
+ }
+ }
+ if (is_invalid_url)
+ continue;
+
+ int rect_count = FPDFLink_CountRects(links, i);
+ for (int j = 0; j < rect_count; ++j) {
+ double left, top, right, bottom;
+ FPDFLink_GetRect(links, i, j, &left, &top, &right, &bottom);
+ link.rects.push_back(
+ PageToScreen(pp::Point(), 1.0, left, top, right, bottom, 0));
+ }
+ links_.push_back(link);
+ }
+ FPDFLink_CloseWebLinks(links);
+}
+
+pp::Rect PDFiumPage::PageToScreen(const pp::Point& offset,
+ double zoom,
+ double left,
+ double top,
+ double right,
+ double bottom,
+ int rotation) const {
+ if (!available_)
+ return pp::Rect();
+
+ int new_left, new_top, new_right, new_bottom;
+ FPDF_PageToDevice(
+ page_,
+ static_cast<int>((rect_.x() - offset.x()) * zoom),
+ static_cast<int>((rect_.y() - offset.y()) * zoom),
+ static_cast<int>(ceil(rect_.width() * zoom)),
+ static_cast<int>(ceil(rect_.height() * zoom)),
+ rotation, left, top, &new_left, &new_top);
+ FPDF_PageToDevice(
+ page_,
+ static_cast<int>((rect_.x() - offset.x()) * zoom),
+ static_cast<int>((rect_.y() - offset.y()) * zoom),
+ static_cast<int>(ceil(rect_.width() * zoom)),
+ static_cast<int>(ceil(rect_.height() * zoom)),
+ rotation, right, bottom, &new_right, &new_bottom);
+
+ // If the PDF is rotated, the horizontal/vertical coordinates could be
+ // flipped. See
+ // http://www.netl.doe.gov/publications/proceedings/03/ubc/presentations/Goeckner-pres.pdf
+ if (new_right < new_left)
+ std::swap(new_right, new_left);
+ if (new_bottom < new_top)
+ std::swap(new_bottom, new_top);
+
+ return pp::Rect(
+ new_left, new_top, new_right - new_left + 1, new_bottom - new_top + 1);
+}
+
+PDFiumPage::ScopedLoadCounter::ScopedLoadCounter(PDFiumPage* page)
+ : page_(page) {
+ page_->loading_count_++;
+}
+
+PDFiumPage::ScopedLoadCounter::~ScopedLoadCounter() {
+ page_->loading_count_--;
+}
+
+PDFiumPage::Link::Link() {
+}
+
+PDFiumPage::Link::~Link() {
+}
+
+} // namespace chrome_pdf
diff --git a/chromium/pdf/pdfium/pdfium_page.h b/chromium/pdf/pdfium/pdfium_page.h
new file mode 100644
index 00000000000..da30504b153
--- /dev/null
+++ b/chromium/pdf/pdfium/pdfium_page.h
@@ -0,0 +1,147 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef PDF_PDFIUM_PDFIUM_PAGE_H_
+#define PDF_PDFIUM_PDFIUM_PAGE_H_
+
+#include <string>
+#include <vector>
+
+#include "base/strings/string16.h"
+#include "ppapi/cpp/rect.h"
+#include "third_party/pdfium/public/fpdf_doc.h"
+#include "third_party/pdfium/public/fpdf_formfill.h"
+#include "third_party/pdfium/public/fpdf_text.h"
+
+namespace base {
+class Value;
+}
+
+namespace chrome_pdf {
+
+class PDFiumEngine;
+
+// Wrapper around a page from the document.
+class PDFiumPage {
+ public:
+ PDFiumPage(PDFiumEngine* engine,
+ int i,
+ const pp::Rect& r,
+ bool available);
+ ~PDFiumPage();
+
+ // Unloads the PDFium data for this page from memory.
+ void Unload();
+ // Gets the FPDF_PAGE for this page, loading and parsing it if necessary.
+ FPDF_PAGE GetPage();
+ // Get the FPDF_PAGE for printing.
+ FPDF_PAGE GetPrintPage();
+ // Close the printing page.
+ void ClosePrintPage();
+
+ // Returns FPDF_TEXTPAGE for the page, loading and parsing it if necessary.
+ FPDF_TEXTPAGE GetTextPage();
+
+ // Returns a DictionaryValue version of the page.
+ base::Value* GetAccessibleContentAsValue(int rotation);
+
+ enum Area {
+ NONSELECTABLE_AREA,
+ TEXT_AREA,
+ WEBLINK_AREA, // Area is a hyperlink.
+ DOCLINK_AREA, // Area is a link to a different part of the same document.
+ };
+
+ struct LinkTarget {
+ // We are using std::string here which have a copy contructor.
+ // That prevents us from using union here.
+ std::string url; // Valid for WEBLINK_AREA only.
+ int page; // Valid for DOCLINK_AREA only.
+ };
+
+ // Given a point in the document that's in this page, returns its character
+ // index if it's near a character, and also the type of text.
+ // Target is optional. It will be filled in for WEBLINK_AREA or
+ // DOCLINK_AREA only.
+ Area GetCharIndex(const pp::Point& point, int rotation, int* char_index,
+ int* form_type, LinkTarget* target);
+
+ // Gets the character at the given index.
+ base::char16 GetCharAtIndex(int index);
+
+ // Gets the number of characters in the page.
+ int GetCharCount();
+
+ // Converts from page coordinates to screen coordinates.
+ pp::Rect PageToScreen(const pp::Point& offset,
+ double zoom,
+ double left,
+ double top,
+ double right,
+ double bottom,
+ int rotation) const;
+
+ int index() const { return index_; }
+ pp::Rect rect() const { return rect_; }
+ void set_rect(const pp::Rect& r) { rect_ = r; }
+ bool available() const { return available_; }
+ void set_available(bool available) { available_ = available; }
+ void set_calculated_links(bool calculated_links) {
+ calculated_links_ = calculated_links;
+ }
+
+ private:
+ // Returns a link index if the given character index is over a link, or -1
+ // otherwise.
+ int GetLink(int char_index, LinkTarget* target);
+ // Returns the link indices if the given rect intersects a link rect, or an
+ // empty vector otherwise.
+ std::vector<int> GetLinks(pp::Rect text_area,
+ std::vector<LinkTarget>* targets);
+ // Calculate the locations of any links on the page.
+ void CalculateLinks();
+ // Returns link type and target associated with a link. Returns
+ // NONSELECTABLE_AREA if link detection failed.
+ Area GetLinkTarget(FPDF_LINK link, LinkTarget* target) const;
+ // Returns target associated with a destination.
+ Area GetDestinationTarget(FPDF_DEST destination, LinkTarget* target) const;
+ // Returns the text in the supplied box as a Value Node
+ base::Value* GetTextBoxAsValue(double page_height, double left, double top,
+ double right, double bottom, int rotation);
+ // Helper functions for JSON generation
+ base::Value* CreateTextNode(const std::string& text);
+ base::Value* CreateURLNode(const std::string& text, const std::string& url);
+
+ class ScopedLoadCounter {
+ public:
+ explicit ScopedLoadCounter(PDFiumPage* page);
+ ~ScopedLoadCounter();
+
+ private:
+ PDFiumPage* const page_;
+ };
+
+ struct Link {
+ Link();
+ ~Link();
+
+ std::string url;
+ // Bounding rectangles of characters.
+ std::vector<pp::Rect> rects;
+ };
+
+ PDFiumEngine* engine_;
+ FPDF_PAGE page_;
+ FPDF_TEXTPAGE text_page_;
+ int index_;
+ int loading_count_;
+ pp::Rect rect_;
+ bool calculated_links_;
+ std::vector<Link> links_;
+ bool available_;
+};
+
+} // namespace chrome_pdf
+
+#endif // PDF_PDFIUM_PDFIUM_PAGE_H_
diff --git a/chromium/pdf/pdfium/pdfium_range.cc b/chromium/pdf/pdfium/pdfium_range.cc
new file mode 100644
index 00000000000..3b8371f7f6c
--- /dev/null
+++ b/chromium/pdf/pdfium/pdfium_range.cc
@@ -0,0 +1,82 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "pdf/pdfium/pdfium_range.h"
+
+#include "base/logging.h"
+#include "base/strings/string_util.h"
+#include "pdf/pdfium/pdfium_api_string_buffer_adapter.h"
+
+namespace chrome_pdf {
+
+PDFiumRange::PDFiumRange(PDFiumPage* page, int char_index, int char_count)
+ : page_(page),
+ char_index_(char_index),
+ char_count_(char_count),
+ cached_screen_rects_zoom_(0) {
+}
+
+PDFiumRange::~PDFiumRange() {
+}
+
+void PDFiumRange::SetCharCount(int char_count) {
+ char_count_ = char_count;
+
+ cached_screen_rects_offset_ = pp::Point();
+ cached_screen_rects_zoom_ = 0;
+}
+
+std::vector<pp::Rect> PDFiumRange::GetScreenRects(const pp::Point& offset,
+ double zoom,
+ int rotation) {
+ if (offset == cached_screen_rects_offset_ &&
+ zoom == cached_screen_rects_zoom_) {
+ return cached_screen_rects_;
+ }
+
+ cached_screen_rects_.clear();
+ cached_screen_rects_offset_ = offset;
+ cached_screen_rects_zoom_ = zoom;
+
+ int char_index = char_index_;
+ int char_count = char_count_;
+ if (char_count < 0) {
+ char_count *= -1;
+ char_index -= char_count - 1;
+ }
+
+ int count = FPDFText_CountRects(page_->GetTextPage(), char_index, char_count);
+ for (int i = 0; i < count; ++i) {
+ double left, top, right, bottom;
+ FPDFText_GetRect(page_->GetTextPage(), i, &left, &top, &right, &bottom);
+ cached_screen_rects_.push_back(
+ page_->PageToScreen(offset, zoom, left, top, right, bottom, rotation));
+ }
+
+ return cached_screen_rects_;
+}
+
+base::string16 PDFiumRange::GetText() const {
+ int index = char_index_;
+ int count = char_count_;
+ base::string16 rv;
+ if (count < 0) {
+ count *= -1;
+ index -= count - 1;
+ }
+
+ if (count > 0) {
+ PDFiumAPIStringBufferAdapter<base::string16> api_string_adapter(&rv,
+ count,
+ false);
+ unsigned short* data =
+ reinterpret_cast<unsigned short*>(api_string_adapter.GetData());
+ int written = FPDFText_GetText(page_->GetTextPage(), index, count, data);
+ api_string_adapter.Close(written);
+ }
+
+ return rv;
+}
+
+} // namespace chrome_pdf
diff --git a/chromium/pdf/pdfium/pdfium_range.h b/chromium/pdf/pdfium/pdfium_range.h
new file mode 100644
index 00000000000..a0f9ea13db8
--- /dev/null
+++ b/chromium/pdf/pdfium/pdfium_range.h
@@ -0,0 +1,54 @@
+// Copyright (c) 2010 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef PDF_PDFIUM_PDFIUM_RANGE_H_
+#define PDF_PDFIUM_PDFIUM_RANGE_H_
+
+#include <string>
+#include <vector>
+
+#include "base/strings/string16.h"
+#include "pdf/pdfium/pdfium_page.h"
+#include "ppapi/cpp/rect.h"
+
+namespace chrome_pdf {
+
+// Describes location of a string of characters.
+class PDFiumRange {
+ public:
+ PDFiumRange(PDFiumPage* page, int char_index, int char_count);
+ ~PDFiumRange();
+
+ // Update how many characters are in the selection. Could be negative if
+ // backwards.
+ void SetCharCount(int char_count);
+
+ int page_index() const { return page_->index(); }
+ int char_index() const { return char_index_; }
+ int char_count() const { return char_count_; }
+
+ // Gets bounding rectangles of range in screen coordinates.
+ std::vector<pp::Rect> GetScreenRects(const pp::Point& offset,
+ double zoom,
+ int rotation);
+
+ // Gets the string of characters in this range.
+ base::string16 GetText() const;
+
+ private:
+ PDFiumPage* page_;
+ // Index of first character.
+ int char_index_;
+ // How many characters are part of this range (negative if backwards).
+ int char_count_;
+
+ // Cache of ScreenRect, and the associated variables used when caching it.
+ std::vector<pp::Rect> cached_screen_rects_;
+ pp::Point cached_screen_rects_offset_;
+ double cached_screen_rects_zoom_;
+};
+
+} // namespace chrome_pdf
+
+#endif // PDF_PDFIUM_PDFIUM_RANGE_H_
diff --git a/chromium/pdf/preview_mode_client.cc b/chromium/pdf/preview_mode_client.cc
new file mode 100644
index 00000000000..7c74dabb9cd
--- /dev/null
+++ b/chromium/pdf/preview_mode_client.cc
@@ -0,0 +1,167 @@
+// Copyright (c) 2011 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/preview_mode_client.h"
+
+#include <stdint.h>
+
+#include "base/logging.h"
+
+namespace chrome_pdf {
+
+PreviewModeClient::PreviewModeClient(Client* client)
+ : client_(client) {
+}
+
+void PreviewModeClient::DocumentSizeUpdated(const pp::Size& size) {
+}
+
+void PreviewModeClient::Invalidate(const pp::Rect& rect) {
+ NOTREACHED();
+}
+
+void PreviewModeClient::Scroll(const pp::Point& point) {
+ NOTREACHED();
+}
+
+void PreviewModeClient::ScrollToX(int position) {
+ NOTREACHED();
+}
+
+void PreviewModeClient::ScrollToY(int position) {
+ NOTREACHED();
+}
+
+void PreviewModeClient::ScrollToPage(int page) {
+ NOTREACHED();
+}
+
+void PreviewModeClient::NavigateTo(const std::string& url,
+ bool open_in_new_tab) {
+ NOTREACHED();
+}
+
+void PreviewModeClient::UpdateCursor(PP_CursorType_Dev cursor) {
+ NOTREACHED();
+}
+
+void PreviewModeClient::UpdateTickMarks(
+ const std::vector<pp::Rect>& tickmarks) {
+ NOTREACHED();
+}
+
+void PreviewModeClient::NotifyNumberOfFindResultsChanged(int total,
+ bool final_result) {
+ NOTREACHED();
+}
+
+void PreviewModeClient::NotifySelectedFindResultChanged(
+ int current_find_index) {
+ NOTREACHED();
+}
+
+void PreviewModeClient::GetDocumentPassword(
+ pp::CompletionCallbackWithOutput<pp::Var> callback) {
+ callback.Run(PP_ERROR_FAILED);
+}
+
+void PreviewModeClient::Alert(const std::string& message) {
+ NOTREACHED();
+}
+
+bool PreviewModeClient::Confirm(const std::string& message) {
+ NOTREACHED();
+ return false;
+}
+
+std::string PreviewModeClient::Prompt(const std::string& question,
+ const std::string& default_answer) {
+ NOTREACHED();
+ return std::string();
+}
+
+std::string PreviewModeClient::GetURL() {
+ NOTREACHED();
+ return std::string();
+}
+
+void PreviewModeClient::Email(const std::string& to,
+ const std::string& cc,
+ const std::string& bcc,
+ const std::string& subject,
+ const std::string& body) {
+ NOTREACHED();
+}
+
+void PreviewModeClient::Print() {
+ NOTREACHED();
+}
+
+void PreviewModeClient::SubmitForm(const std::string& url,
+ const void* data,
+ int length) {
+ NOTREACHED();
+}
+
+std::string PreviewModeClient::ShowFileSelectionDialog() {
+ NOTREACHED();
+ return std::string();
+}
+
+pp::URLLoader PreviewModeClient::CreateURLLoader() {
+ NOTREACHED();
+ return pp::URLLoader();
+}
+
+void PreviewModeClient::ScheduleCallback(int id, int delay_in_ms) {
+ NOTREACHED();
+}
+
+void PreviewModeClient::SearchString(const base::char16* string,
+ const base::char16* term,
+ bool case_sensitive,
+ std::vector<SearchStringResult>* results) {
+ NOTREACHED();
+}
+
+void PreviewModeClient::DocumentPaintOccurred() {
+ NOTREACHED();
+}
+
+void PreviewModeClient::DocumentLoadComplete(int page_count) {
+ client_->PreviewDocumentLoadComplete();
+}
+
+void PreviewModeClient::DocumentLoadFailed() {
+ client_->PreviewDocumentLoadFailed();
+}
+
+pp::Instance* PreviewModeClient::GetPluginInstance() {
+ NOTREACHED();
+ return NULL;
+}
+
+void PreviewModeClient::DocumentHasUnsupportedFeature(
+ const std::string& feature) {
+ NOTREACHED();
+}
+
+void PreviewModeClient::DocumentLoadProgress(uint32_t available,
+ uint32_t doc_size) {}
+
+void PreviewModeClient::FormTextFieldFocusChange(bool in_focus) {
+ NOTREACHED();
+}
+
+bool PreviewModeClient::IsPrintPreview() {
+ NOTREACHED();
+ return false;
+}
+
+uint32_t PreviewModeClient::GetBackgroundColor() {
+ NOTREACHED();
+ return 0;
+}
+
+} // namespace chrome_pdf
diff --git a/chromium/pdf/preview_mode_client.h b/chromium/pdf/preview_mode_client.h
new file mode 100644
index 00000000000..0127db9a3a5
--- /dev/null
+++ b/chromium/pdf/preview_mode_client.h
@@ -0,0 +1,80 @@
+// Copyright (c) 2011 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_PREVIEW_MODE_CLIENT_H_
+#define PDF_PREVIEW_MODE_CLIENT_H_
+
+#include <stdint.h>
+
+#include <string>
+#include <vector>
+
+#include "pdf/pdf_engine.h"
+
+namespace chrome_pdf {
+
+// The interface that's provided to the print preview rendering engine.
+class PreviewModeClient : public PDFEngine::Client {
+ public:
+ class Client {
+ public:
+ virtual void PreviewDocumentLoadFailed() = 0;
+ virtual void PreviewDocumentLoadComplete() = 0;
+ };
+
+ explicit PreviewModeClient(Client* client);
+ ~PreviewModeClient() override {}
+
+ // PDFEngine::Client implementation.
+ void DocumentSizeUpdated(const pp::Size& size) override;
+ void Invalidate(const pp::Rect& rect) override;
+ void Scroll(const pp::Point& point) override;
+ void ScrollToX(int position) override;
+ void ScrollToY(int position) override;
+ void ScrollToPage(int page) override;
+ void NavigateTo(const std::string& url, bool open_in_new_tab) override;
+ void UpdateCursor(PP_CursorType_Dev cursor) override;
+ void UpdateTickMarks(const std::vector<pp::Rect>& tickmarks) override;
+ void NotifyNumberOfFindResultsChanged(int total, bool final_result) override;
+ void NotifySelectedFindResultChanged(int current_find_index) override;
+ void GetDocumentPassword(
+ pp::CompletionCallbackWithOutput<pp::Var> callback) 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::string GetURL() override;
+ void Email(const std::string& to,
+ const std::string& cc,
+ const std::string& bcc,
+ const std::string& subject,
+ const std::string& body) override;
+ void Print() override;
+ void SubmitForm(const std::string& url,
+ const void* data,
+ int length) override;
+ std::string ShowFileSelectionDialog() override;
+ pp::URLLoader CreateURLLoader() override;
+ void ScheduleCallback(int id, int delay_in_ms) override;
+ void SearchString(const base::char16* string,
+ const base::char16* term,
+ bool case_sensitive,
+ std::vector<SearchStringResult>* results) override;
+ void DocumentPaintOccurred() override;
+ void DocumentLoadComplete(int page_count) override;
+ void DocumentLoadFailed() override;
+ pp::Instance* GetPluginInstance() override;
+ void DocumentHasUnsupportedFeature(const std::string& feature) override;
+ void DocumentLoadProgress(uint32_t available, uint32_t doc_size) override;
+ void FormTextFieldFocusChange(bool in_focus) override;
+ bool IsPrintPreview() override;
+ uint32_t GetBackgroundColor() override;
+
+ private:
+ Client* const client_;
+};
+
+} // namespace chrome_pdf
+
+#endif // PDF_PREVIEW_MODE_CLIENT_H_