diff options
Diffstat (limited to 'xfa_test/pdf')
55 files changed, 16252 insertions, 0 deletions
diff --git a/xfa_test/pdf/BUILD.gn b/xfa_test/pdf/BUILD.gn new file mode 100644 index 0000000000..5e1f165b1c --- /dev/null +++ b/xfa_test/pdf/BUILD.gn @@ -0,0 +1,99 @@ +# 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. + +pdf_engine = 0 # 0 PDFium + +# TODO(GYP) need support for loadable modules +shared_library("pdf") { + sources = [ + "button.h", + "button.cc", + "chunk_stream.h", + "chunk_stream.cc", + "control.h", + "control.cc", + "document_loader.h", + "document_loader.cc", + "draw_utils.cc", + "draw_utils.h", + "fading_control.cc", + "fading_control.h", + "fading_controls.cc", + "fading_controls.h", + "instance.cc", + "instance.h", + "number_image_generator.cc", + "number_image_generator.h", + "out_of_process_instance.cc", + "out_of_process_instance.h", + "page_indicator.cc", + "page_indicator.h", + "paint_aggregator.cc", + "paint_aggregator.h", + "paint_manager.cc", + "paint_manager.h", + "pdf.cc", + "pdf.h", + "pdf.rc", + "progress_control.cc", + "progress_control.h", + "pdf_engine.h", + "preview_mode_client.cc", + "preview_mode_client.h", + "resource.h", + "resource_consts.h", + "thumbnail_control.cc", + "thumbnail_control.h", + "../chrome/browser/chrome_page_zoom_constants.cc", + "../content/common/page_zoom.cc", + ] + + if (pdf_engine == 0) { + sources += [ + "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 (is_win) { + defines = [ "COMPILE_CONTENT_STATICALLY" ] + cflags = [ "/wd4267" ] # TODO(jschuh) size_t to int truncations. + } + + if (is_mac) { + # TODO(GYP) + #'mac_bundle': 1, + #'product_name': 'PDF', + #'product_extension': 'plugin', + ## Strip the shipping binary of symbols so "Foxit" doesn't appear in + ## the binary. Symbols are stored in a separate .dSYM. + #'variables': { + # 'mac_real_dsym': 1, + #}, + #'sources+': [ + # 'Info.plist' + #] + #'xcode_settings': { + # 'INFOPLIST_FILE': 'Info.plist', + #}, + } + + deps = [ + "//base", + "//net", + "//ppapi:ppapi_cpp", + "//third_party/pdfium", + ] +} + +# TODO(GYP) pdf_linux_symbols target. diff --git a/xfa_test/pdf/DEPS b/xfa_test/pdf/DEPS new file mode 100644 index 0000000000..73f2f8f44d --- /dev/null +++ b/xfa_test/pdf/DEPS @@ -0,0 +1,9 @@ +include_rules = [ + "!chrome/browser/chrome_page_zoom_constants.h", + "!chrome/common/content_restriction.h", + "!content/public/common/page_zoom.h", + "+net", + "+ppapi", + "+third_party/pdfium/fpdfsdk/include", + "+ui/events/keycodes/keyboard_codes.h", +] diff --git a/xfa_test/pdf/Info.plist b/xfa_test/pdf/Info.plist new file mode 100644 index 0000000000..9f3dfdf834 --- /dev/null +++ b/xfa_test/pdf/Info.plist @@ -0,0 +1,44 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>CFBundleDevelopmentRegion</key> + <string>English</string> + <key>CFBundleExecutable</key> + <string>${EXECUTABLE_NAME}</string> + <key>CFBundleIdentifier</key> + <string>org.chromium.pdf_plugin</string> + <key>CFBundleInfoDictionaryVersion</key> + <string>6.0</string> + <key>CFBundleName</key> + <string>${PRODUCT_NAME}</string> + <key>CFBundlePackageType</key> + <string>BRPL</string> + <key>CFBundleShortVersionString</key> + <string>1.0</string> + <key>CFBundleSignature</key> + <string>????</string> + <key>CFBundleVersion</key> + <string>1.0</string> + <key>CFPlugInDynamicRegisterFunction</key> + <string></string> + <key>CFPlugInDynamicRegistration</key> + <string>NO</string> + <key>WebPluginDescription</key> + <string>Chrome PDF Viewer</string> + <key>WebPluginMIMETypes</key> + <dict> + <key>application/pdf</key> + <dict> + <key>WebPluginExtensions</key> + <array> + <string>pdf</string> + </array> + <key>WebPluginTypeDescription</key> + <string>Acrobat Portable Document Format</string> + </dict> + </dict> + <key>WebPluginName</key> + <string>Chrome PDF Viewer</string> +</dict> +</plist> diff --git a/xfa_test/pdf/OWNERS b/xfa_test/pdf/OWNERS new file mode 100644 index 0000000000..4b408bc7c9 --- /dev/null +++ b/xfa_test/pdf/OWNERS @@ -0,0 +1,4 @@ +gene@chromium.org +jam@chromium.org +raymes@chromium.org +thestig@chromium.org
\ No newline at end of file diff --git a/xfa_test/pdf/button.cc b/xfa_test/pdf/button.cc new file mode 100644 index 0000000000..3a30164c14 --- /dev/null +++ b/xfa_test/pdf/button.cc @@ -0,0 +1,179 @@ +// 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/button.h" + +#include "base/logging.h" +#include "pdf/draw_utils.h" +#include "ppapi/cpp/input_event.h" + +namespace chrome_pdf { + +Button::Button() + : style_(BUTTON_CLICKABLE), state_(BUTTON_NORMAL), is_pressed_(false) { +} + +Button::~Button() { +} + +bool Button::CreateButton(uint32 id, + const pp::Point& origin, + bool visible, + Control::Owner* owner, + ButtonStyle style, + const pp::ImageData& face_normal, + const pp::ImageData& face_highlighted, + const pp::ImageData& face_pressed) { + DCHECK(face_normal.size().GetArea()); + DCHECK(face_normal.size() == face_highlighted.size()); + DCHECK(face_normal.size() == face_pressed.size()); + + pp::Rect rc(origin, face_normal.size()); + if (!Control::Create(id, rc, visible, owner)) + return false; + + style_ = style; + + normal_ = face_normal; + highlighted_ = face_highlighted; + pressed_ = face_pressed; + + return true; +} + + +void Button::Paint(pp::ImageData* image_data, const pp::Rect& rc) { + if (!visible()) + return; + + pp::Rect draw_rc = rc.Intersect(rect()); + if (draw_rc.IsEmpty()) + return; + + pp::Point origin = draw_rc.point(); + draw_rc.Offset(-rect().x(), -rect().y()); + + AlphaBlend(GetCurrentImage(), draw_rc, image_data, origin, transparency()); +} + +bool Button::HandleEvent(const pp::InputEvent& event) { + if (!visible()) + return false; + + // Button handles mouse events only. + pp::MouseInputEvent mouse_event(event); + if (mouse_event.is_null()) + return false; + + pp::Point pt = mouse_event.GetPosition(); + if (!rect().Contains(pt) || + event.GetType() == PP_INPUTEVENT_TYPE_MOUSELEAVE) { + ChangeState(BUTTON_NORMAL, false); + owner()->SetEventCapture(id(), false); + return false; + } + + owner()->SetCursor(id(), PP_CURSORTYPE_POINTER); + owner()->SetEventCapture(id(), true); + + bool handled = true; + switch (event.GetType()) { + case PP_INPUTEVENT_TYPE_MOUSEMOVE: + if (state_ == BUTTON_NORMAL) + ChangeState(BUTTON_HIGHLIGHTED, false); + break; + case PP_INPUTEVENT_TYPE_MOUSEDOWN: + if (mouse_event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_LEFT) { + ChangeState(BUTTON_PRESSED, false); + is_pressed_ = true; + } + break; + case PP_INPUTEVENT_TYPE_MOUSEUP: + if (mouse_event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_LEFT && + is_pressed_) { + OnButtonClicked(); + is_pressed_ = false; + } else { + // Since button has not been pressed, return false to allow other + // controls (scrollbar) to process mouse button up. + return false; + } + break; + default: + handled = false; + break; + } + + return handled; +} + +void Button::OnEventCaptureReleased() { + ChangeState(BUTTON_NORMAL, false); +} + +void Button::Show(bool visible, bool invalidate) { + // If button become invisible, remove pressed flag. + if (!visible) + is_pressed_ = false; + Control::Show(visible, invalidate); +} + +void Button::AdjustTransparency(uint8 transparency, bool invalidate) { + // If button become invisible, remove pressed flag. + if (transparency == kTransparentAlpha) + is_pressed_ = false; + Control::AdjustTransparency(transparency, invalidate); +} + +void Button::SetPressedState(bool pressed) { + if (style_ == BUTTON_STATE) { + if (IsPressed() != pressed) + ChangeState(pressed ? BUTTON_PRESSED_STICKY : BUTTON_NORMAL, true); + } +} + +const pp::ImageData& Button::GetCurrentImage() { + switch (state_) { + case BUTTON_NORMAL: return normal_; + case BUTTON_HIGHLIGHTED: return highlighted_; + case BUTTON_PRESSED: + case BUTTON_PRESSED_STICKY: return pressed_; + } + NOTREACHED(); + return normal_; +} + +void Button::ChangeState(ButtonState new_state, bool force) { + if (style_ == BUTTON_STATE && !force) { + // If button is a state button and pressed state is sticky, + // user have to click on this button again to unpress it. + if ((state_ == BUTTON_PRESSED_STICKY && new_state != BUTTON_PRESSED_STICKY) + || + (state_ != BUTTON_PRESSED_STICKY && new_state == BUTTON_PRESSED_STICKY)) + return; + } + + if (state_ != new_state) { + state_ = new_state; + owner()->Invalidate(id(), rect()); + } +} + +void Button::OnButtonClicked() { + switch (style_) { + case BUTTON_CLICKABLE: + ChangeState(BUTTON_HIGHLIGHTED, true); + owner()->OnEvent(id(), EVENT_ID_BUTTON_CLICKED, NULL); + break; + case BUTTON_STATE: + SetPressedState(!IsPressed()); + owner()->OnEvent(id(), EVENT_ID_BUTTON_STATE_CHANGED, NULL); + break; + default: + NOTREACHED(); + } +} + +} // namespace chrome_pdf + diff --git a/xfa_test/pdf/button.h b/xfa_test/pdf/button.h new file mode 100644 index 0000000000..fa2517d62b --- /dev/null +++ b/xfa_test/pdf/button.h @@ -0,0 +1,71 @@ +// 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_BUTTON_H_ +#define PDF_BUTTON_H_ + +#include "pdf/control.h" +#include "ppapi/cpp/image_data.h" +#include "ppapi/cpp/rect.h" + +namespace chrome_pdf { + +class Button : public Control { + public: + enum ButtonEventIds { + EVENT_ID_BUTTON_CLICKED, + EVENT_ID_BUTTON_STATE_CHANGED, + }; + + enum ButtonStyle { + BUTTON_CLICKABLE, + BUTTON_STATE + }; + + enum ButtonState { + BUTTON_NORMAL, + BUTTON_HIGHLIGHTED, + BUTTON_PRESSED, + BUTTON_PRESSED_STICKY, + }; + + Button(); + virtual ~Button(); + virtual bool CreateButton(uint32 id, + const pp::Point& origin, + bool visible, + Control::Owner* delegate, + ButtonStyle style, + const pp::ImageData& face_normal, + const pp::ImageData& face_highlighted, + const pp::ImageData& face_pressed); + + virtual void Paint(pp::ImageData* image_data, const pp::Rect& rc); + virtual bool HandleEvent(const pp::InputEvent& event); + virtual void OnEventCaptureReleased(); + virtual void Show(bool visible, bool invalidate); + virtual void AdjustTransparency(uint8 transparency, bool invalidate); + + ButtonState state() const { return state_; } + bool IsPressed() const { return state() == BUTTON_PRESSED_STICKY; } + void SetPressedState(bool pressed); + + private: + void OnButtonClicked(); + + const pp::ImageData& GetCurrentImage(); + void ChangeState(ButtonState new_state, bool force); + + ButtonStyle style_; + ButtonState state_; + bool is_pressed_; + + pp::ImageData normal_; + pp::ImageData highlighted_; + pp::ImageData pressed_; +}; + +} // namespace chrome_pdf + +#endif // PDF_BUTTON_H_ diff --git a/xfa_test/pdf/chunk_stream.cc b/xfa_test/pdf/chunk_stream.cc new file mode 100644 index 0000000000..7ac8f974a5 --- /dev/null +++ b/xfa_test/pdf/chunk_stream.cc @@ -0,0 +1,172 @@ +// 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" + +#define __STDC_LIMIT_MACROS +#ifdef _WIN32 +#include <limits.h> +#else +#include <stdint.h> +#endif + +#include <algorithm> + +#include "base/basictypes.h" + +namespace chrome_pdf { + +ChunkStream::ChunkStream() { +} + +ChunkStream::~ChunkStream() { +} + +void ChunkStream::Clear() { + chunks_.clear(); + data_.clear(); +} + +void ChunkStream::Preallocate(size_t stream_size) { + data_.reserve(stream_size); +} + +size_t ChunkStream::GetSize() { + 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::GetLastByteBefore(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::GetFirstByteAfter(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_.end()) + return data_.size(); + return it->first; +} + +} // namespace chrome_pdf diff --git a/xfa_test/pdf/chunk_stream.h b/xfa_test/pdf/chunk_stream.h new file mode 100644 index 0000000000..fac1ec644d --- /dev/null +++ b/xfa_test/pdf/chunk_stream.h @@ -0,0 +1,48 @@ +// 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 <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(); + + 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; + + size_t GetLastByteBefore(size_t offset) const; + size_t GetFirstByteAfter(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_; +}; + +}; // namespace chrome_pdf + +#endif diff --git a/xfa_test/pdf/control.cc b/xfa_test/pdf/control.cc new file mode 100644 index 0000000000..ed911b6b95 --- /dev/null +++ b/xfa_test/pdf/control.cc @@ -0,0 +1,117 @@ +// 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/control.h" + +#include "base/logging.h" +#include "pdf/draw_utils.h" + +namespace chrome_pdf { + +Control::Control() + : id_(kInvalidControlId), + visible_(false), + owner_(NULL), + transparency_(kOpaqueAlpha) { +} + +Control::~Control() { +} + +bool Control::Create(uint32 id, const pp::Rect& rc, + bool visible, Owner* owner) { + DCHECK(owner); + if (owner_ || id == kInvalidControlId) + return false; // Already created or id is invalid. + id_ = id; + rc_ = rc; + visible_ = visible; + owner_ = owner; + return true; +} + +bool Control::HandleEvent(const pp::InputEvent& event) { + return false; +} + +void Control::PaintMultipleRects(pp::ImageData* image_data, + const std::list<pp::Rect>& rects) { + DCHECK(rects.size() > 0); + if (rects.size() == 1) { + Paint(image_data, rects.front()); + return; + } + + // Some rects in the input list may overlap. To prevent double + // painting (causes problems with semi-transparent controls) we'll + // paint control into buffer image data only once and copy requested + // rectangles. + pp::ImageData buffer(owner()->GetInstance(), image_data->format(), + rect().size(), false); + if (buffer.is_null()) + return; + + pp::Rect draw_rc = pp::Rect(image_data->size()).Intersect(rect()); + pp::Rect ctrl_rc = pp::Rect(draw_rc.point() - rect().point(), draw_rc.size()); + CopyImage(*image_data, draw_rc, &buffer, ctrl_rc, false); + + // Temporary move control to origin (0,0) and draw it into temp buffer. + // Move to the original position afterward. Since this is going on temp + // buffer, we don't need to invalidate here. + pp::Rect temp = rect(); + MoveTo(pp::Point(0, 0), false); + Paint(&buffer, ctrl_rc); + MoveTo(temp.point(), false); + + std::list<pp::Rect>::const_iterator iter; + for (iter = rects.begin(); iter != rects.end(); ++iter) { + pp::Rect draw_rc = rect().Intersect(*iter); + if (!draw_rc.IsEmpty()) { + // Copy requested rect from the buffer image. + pp::Rect src_rc = draw_rc; + src_rc.Offset(-rect().x(), -rect().y()); + CopyImage(buffer, src_rc, image_data, draw_rc, false); + } + } +} + +void Control::Show(bool visible, bool invalidate) { + if (visible_ != visible) { + visible_ = visible; + if (invalidate) + owner_->Invalidate(id_, rc_); + } +} + +void Control::AdjustTransparency(uint8 transparency, bool invalidate) { + if (transparency_ != transparency) { + transparency_ = transparency; + if (invalidate && visible_) + owner_->Invalidate(id_, rc_); + } +} + +void Control::MoveBy(const pp::Point& offset, bool invalidate) { + pp::Rect old_rc = rc_; + rc_.Offset(offset); + if (invalidate && visible_) { + owner()->Invalidate(id(), old_rc); + owner()->Invalidate(id(), rect()); + } +} + +void Control::SetRect(const pp::Rect& rc, bool invalidate) { + pp::Rect old_rc = rc_; + rc_ = rc; + if (invalidate && visible_) { + owner()->Invalidate(id(), old_rc); + owner()->Invalidate(id(), rect()); + } +} + +void Control::MoveTo(const pp::Point& origin, bool invalidate) { + MoveBy(origin - rc_.point(), invalidate); +} + +} // namespace chrome_pdf diff --git a/xfa_test/pdf/control.h b/xfa_test/pdf/control.h new file mode 100644 index 0000000000..babb37a2c0 --- /dev/null +++ b/xfa_test/pdf/control.h @@ -0,0 +1,77 @@ +// 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_CONTROL_H_ +#define PDF_CONTROL_H_ + +#include <list> + +#include "base/basictypes.h" +#include "ppapi/c/dev/pp_cursor_type_dev.h" +#include "ppapi/cpp/rect.h" + +namespace pp { +class ImageData; +class InputEvent; +class Instance; +} + +namespace chrome_pdf { + +const uint32 kInvalidControlId = 0; + +class Control { + public: + class Owner { + public: + virtual ~Owner() {} + virtual void OnEvent(uint32 control_id, uint32 event_id, void* data) = 0; + virtual void Invalidate(uint32 control_id, const pp::Rect& rc) = 0; + virtual uint32 ScheduleTimer(uint32 control_id, uint32 timeout_ms) = 0; + virtual void SetEventCapture(uint32 control_id, bool set_capture) = 0; + virtual void SetCursor(uint32 control_id, + PP_CursorType_Dev cursor_type) = 0; + virtual pp::Instance* GetInstance() = 0; + }; + + Control(); + virtual ~Control(); + virtual bool Create(uint32 id, const pp::Rect& rc, + bool visible, Owner* owner); + + virtual void Paint(pp::ImageData* image_data, const pp::Rect& rc) {} + virtual bool HandleEvent(const pp::InputEvent& event); + virtual void OnTimerFired(uint32 timer_id) {} + virtual void EventCaptureReleased() {} + + // Paint control into multiple destination rects. + virtual void PaintMultipleRects(pp::ImageData* image_data, + const std::list<pp::Rect>& rects); + + virtual void Show(bool visible, bool invalidate); + virtual void AdjustTransparency(uint8 transparency, bool invalidate); + virtual void MoveBy(const pp::Point& offset, bool invalidate); + virtual void SetRect(const pp::Rect& rc, bool invalidate); + + void MoveTo(const pp::Point& origin, bool invalidate); + + uint32 id() const { return id_; } + const pp::Rect& rect() const { return rc_; } + bool visible() const { return visible_; } + Owner* owner() { return owner_; } + uint8 transparency() const { return transparency_; } + + private: + uint32 id_; + pp::Rect rc_; + bool visible_; + Owner* owner_; + uint8 transparency_; +}; + +typedef Control::Owner ControlOwner; + +} // namespace chrome_pdf + +#endif // PDF_CONTROL_H_ diff --git a/xfa_test/pdf/document_loader.cc b/xfa_test/pdf/document_loader.cc new file mode 100644 index 0000000000..b2628a6271 --- /dev/null +++ b/xfa_test/pdf/document_loader.cc @@ -0,0 +1,513 @@ +// 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 "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 { + +// Document below size will be downloaded in one chunk. +const uint32 kMinFileSize = 64*1024; + +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 content_length = 0; + std::string type; + std::string disposition; + if (!response_headers.empty()) { + net::HttpUtil::HeadersIterator it(response_headers.begin(), + response_headers.end(), "\n"); + while (it.GetNext()) { + if (LowerCaseEqualsASCII(it.name(), "content-length")) { + content_length = atoi(it.values().c_str()); + } else if (LowerCaseEqualsASCII(it.name(), "accept-ranges")) { + accept_ranges_bytes = LowerCaseEqualsASCII(it.values(), "bytes"); + } else if (LowerCaseEqualsASCII(it.name(), "content-encoding")) { + content_encoded = true; + } else if (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); + } + TrimWhitespace(type, base::TRIM_ALL, &type); + } else if (LowerCaseEqualsASCII(it.name(), "content-disposition")) { + disposition = it.values(); + } + } + } + if (!type.empty() && + !EndsWith(type, "/pdf", false) && + !EndsWith(type, ".pdf", false) && + !EndsWith(type, "/x-pdf", false) && + !EndsWith(type, "/*", false) && + !EndsWith(type, "/acrobat", false) && + !EndsWith(type, "/unknown", false)) { + return false; + } + if (StartsWithASCII(disposition, "attachment", false)) { + 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() { + partial_document_ = true; + // Force the main request to be cancelled, since if we're a full-frame plugin + // there could be other references to the loader. + loader_.Close(); + loader_ = pp::URLLoader(); + // Download file header. + header_request_ = true; + RequestData(0, std::min(GetRequestSize(), document_size_)); +} + +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 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 available = document_size_; + std::vector<std::pair<size_t, size_t> >::iterator it; + for (it = ranges.begin(); it != ranges.end(); ++it) { + available -= it->second; + } + return available; +} + +void DocumentLoader::ClearPendingRequests() { + // The first item in the queue is pending (need to keep it in the queue). + if (pending_requests_.size() > 1) { + // Remove all elements except the first one. + pending_requests_.erase(++pending_requests_.begin(), + pending_requests_.end()); + } +} + +bool DocumentLoader::GetBlock(uint32 position, uint32 size, void* buf) const { + return chunk_stream_.ReadData(position, size, buf); +} + +bool DocumentLoader::IsDataAvailable(uint32 position, uint32 size) const { + return chunk_stream_.IsRangeAvailable(position, size); +} + +void DocumentLoader::RequestData(uint32 position, uint32 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::DownloadPendingRequests() { + if (request_pending_ || pending_requests_.empty()) + return; + + // Remove already completed requests. + // By design DownloadPendingRequests() should have at least 1 request in the + // queue. ReadComplete() will remove the last pending comment from the queue. + while (pending_requests_.size() > 1) { + if (IsDataAvailable(pending_requests_.front().first, + pending_requests_.front().second)) { + pending_requests_.pop_front(); + } else { + break; + } + } + + uint32 pos = pending_requests_.front().first; + uint32 size = pending_requests_.front().second; + if (IsDataAvailable(pos, size)) { + ReadComplete(); + return; + } + + // If current request has been partially downloaded already, split it into + // a few smaller requests. + std::vector<std::pair<size_t, size_t> > ranges; + chunk_stream_.GetMissedRanges(pos, size, &ranges); + if (ranges.size() > 0) { + pending_requests_.pop_front(); + pending_requests_.insert(pending_requests_.begin(), + ranges.begin(), ranges.end()); + pos = pending_requests_.front().first; + size = pending_requests_.front().second; + } + + uint32 cur_request_size = GetRequestSize(); + // If size is less than default request, try to expand download range for + // more optimal download. + if (size < cur_request_size && partial_document_) { + // First, try to expand block towards the end of the file. + uint32 new_pos = pos; + uint32 new_size = cur_request_size; + if (pos + new_size > document_size_) + new_size = document_size_ - pos; + + std::vector<std::pair<size_t, size_t> > ranges; + if (chunk_stream_.GetMissedRanges(new_pos, new_size, &ranges)) { + new_pos = ranges[0].first; + new_size = ranges[0].second; + } + + // Second, try to expand block towards the beginning of the file. + if (new_size < cur_request_size) { + uint32 block_end = new_pos + new_size; + if (block_end > cur_request_size) { + new_pos = block_end - cur_request_size; + } else { + new_pos = 0; + } + new_size = block_end - new_pos; + + if (chunk_stream_.GetMissedRanges(new_pos, new_size, &ranges)) { + new_pos = ranges.back().first; + new_size = ranges.back().second; + } + } + pos = new_pos; + size = new_size; + } + + size_t last_byte_before = chunk_stream_.GetLastByteBefore(pos); + size_t first_byte_after = chunk_stream_.GetFirstByteAfter(pos + size - 1); + if (pos - last_byte_before < cur_request_size) { + size = pos + size - last_byte_before; + pos = last_byte_before; + } + + if ((pos + size < first_byte_after) && + (pos + size + cur_request_size >= first_byte_after)) + size = first_byte_after - pos; + + 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, size); + requests_count_++; + int rv = loader_.Open(request, callback); + if (rv != PP_OK_COMPLETIONPENDING) + callback.Run(rv); +} + +pp::URLRequestInfo DocumentLoader::GetRequest(uint32 position, + uint32 size) const { + pp::URLRequestInfo request(client_->GetPluginInstance()); + request.SetURL(url_.c_str()); + request.SetMethod("GET"); + request.SetFollowRedirects(true); + + 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.size()) { + // 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 bye-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 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; + } + } + + ReadMore(); +} + +bool DocumentLoader::GetByteRange(const std::string& headers, uint32* start, + uint32* end) { + net::HttpUtil::HeadersIterator it(headers.begin(), headers.end(), "\n"); + while (it.GetNext()) { + if (LowerCaseEqualsASCII(it.name(), "content-range")) { + std::string range = it.values().c_str(); + if (StartsWithASCII(range, "bytes", false)) { + 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); + TrimWhitespaceASCII(range, base::TRIM_LEADING, &range); + TrimWhitespaceASCII(range_end, base::TRIM_LEADING, &range_end); + *start = atoi(range.c_str()); + *end = atoi(range_end.c_str()); + return true; + } + } + } + return false; +} + +std::string DocumentLoader::GetMultiPartBoundary(const std::string& headers) { + net::HttpUtil::HeadersIterator it(headers.begin(), headers.end(), "\n"); + while (it.GetNext()) { + if (LowerCaseEqualsASCII(it.name(), "content-type")) { + std::string type = base::StringToLowerASCII(it.values()); + if (StartsWithASCII(type, "multipart/", true)) { + const char* boundary = strstr(type.c_str(), "boundary="); + if (!boundary) { + NOTREACHED(); + break; + } + + return std::string(boundary + 9); + } + } + } + return std::string(); +} + +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 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. + chunk_buffer_.push_back(std::vector<unsigned char>()); + chunk_buffer_.back().resize(length); + memcpy(&(chunk_buffer_.back()[0]), start, length); + } + current_pos_ += length; + current_chunk_read_ += length; + client_->OnNewDataAvailable(); + } + ReadMore(); + } else if (result == PP_OK) { + ReadComplete(); + } else { + NOTREACHED(); + } +} + +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 pos = 0; + std::list<std::vector<unsigned char> >::iterator it; + for (it = chunk_buffer_.begin(); it != chunk_buffer_.end(); ++it) { + chunk_stream_.WriteData(pos, &((*it)[0]), it->size()); + pos += it->size(); + } + chunk_buffer_.clear(); + } + document_size_ = current_pos_; + client_->OnDocumentComplete(); + return; + } + + request_pending_ = false; + pending_requests_.pop_front(); + + // If there are more pending request - continue downloading. + if (!pending_requests_.empty()) { + DownloadPendingRequests(); + return; + } + + if (IsDocumentComplete()) { + client_->OnDocumentComplete(); + return; + } + + if (header_request_) + client_->OnPartialDocumentLoaded(); + else + client_->OnPendingRequestComplete(); + header_request_ = false; + + // The OnPendingRequestComplete could have added more requests. + if (!pending_requests_.empty()) { + DownloadPendingRequests(); + } else { + // Document is not complete and we have no outstanding requests. + // Let's keep downloading PDF file in small chunks. + uint32 pos = chunk_stream_.GetFirstMissingByte(); + std::vector<std::pair<size_t, size_t> > ranges; + chunk_stream_.GetMissedRanges(pos, GetRequestSize(), &ranges); + DCHECK(ranges.size() > 0); + RequestData(ranges[0].first, ranges[0].second); + } +} + +uint32 DocumentLoader::GetRequestSize() const { + // Document loading strategy: + // For first 10 requests, we use 32k chunk sizes, for the next 10 requests we + // double the size (64k), and so on, until we cap max request size at 2M for + // 71 or more requests. + uint32 limited_count = std::min(std::max(requests_count_, 10u), 70u); + return 32*1024 * (1 << ((limited_count - 1) / 10u)); +} + +} // namespace chrome_pdf diff --git a/xfa_test/pdf/document_loader.h b/xfa_test/pdf/document_loader.h new file mode 100644 index 0000000000..c09dba2ddd --- /dev/null +++ b/xfa_test/pdf/document_loader.h @@ -0,0 +1,124 @@ +// 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 <list> +#include <string> +#include <vector> + +#include "base/basictypes.h" +#include "pdf/chunk_stream.h" +#include "ppapi/cpp/url_loader.h" +#include "ppapi/utility/completion_callback_factory.h" + +#define kDefaultRequestSize 32768u + +namespace chrome_pdf { + +class DocumentLoader { + public: + class Client { + public: + // 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); + virtual ~DocumentLoader(); + + bool Init(const pp::URLLoader& loader, + const std::string& url, + const std::string& headers); + + // Data access interface. Return true is sucessful. + bool GetBlock(uint32 position, uint32 size, void* buf) const; + + // Data availability interface. Return true data avaialble. + bool IsDataAvailable(uint32 position, uint32 size) const; + + // Data availability interface. Return true data avaialble. + void RequestData(uint32 position, uint32 size); + + bool IsDocumentComplete() const; + uint32 document_size() const { return document_size_; } + + // Return number of bytes available. + uint32 GetAvailableData() const; + + // Clear pending requests from the queue. + void ClearPendingRequests(); + + bool is_partial_document() { 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); + + // 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. + static bool GetByteRange(const std::string& headers, uint32* start, + uint32* end); + + // If the headers have a multi-part response, returns the boundary name. + // Otherwise returns an empty string. + static std::string GetMultiPartBoundary(const std::string& headers); + + // 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(); + // 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 position, uint32 size) const; + // Returns current request size in bytes. + uint32 GetRequestSize() const; + + Client* 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_; + char buffer_[kDefaultRequestSize]; + uint32 current_pos_; + uint32 current_chunk_size_; + uint32 current_chunk_read_; + uint32 document_size_; + bool header_request_; + bool is_multipart_; + std::string multipart_boundary_; + uint32 requests_count_; + std::list<std::vector<unsigned char> > chunk_buffer_; +}; + +} // namespace chrome_pdf + +#endif // PDF_DOCUMENT_LOADER_H_ diff --git a/xfa_test/pdf/draw_utils.cc b/xfa_test/pdf/draw_utils.cc new file mode 100644 index 0000000000..d38be52aef --- /dev/null +++ b/xfa_test/pdf/draw_utils.cc @@ -0,0 +1,343 @@ +// 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 <algorithm> +#include <math.h> +#include <vector> + +#include "base/logging.h" +#include "base/numerics/safe_math.h" + +namespace chrome_pdf { + +inline uint8 GetBlue(const uint32& pixel) { + return static_cast<uint8>(pixel & 0xFF); +} + +inline uint8 GetGreen(const uint32& pixel) { + return static_cast<uint8>((pixel >> 8) & 0xFF); +} + +inline uint8 GetRed(const uint32& pixel) { + return static_cast<uint8>((pixel >> 16) & 0xFF); +} + +inline uint8 GetAlpha(const uint32& pixel) { + return static_cast<uint8>((pixel >> 24) & 0xFF); +} + +inline uint32_t MakePixel(uint8 red, uint8 green, uint8 blue, uint8 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 GradientChannel(uint8 start, uint8 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>(new_channel + 0.5); +} + +inline uint8 ProcessColor(uint8 src_color, uint8 dest_color, uint8 alpha) { + uint32 processed = static_cast<uint32>(src_color) * alpha + + static_cast<uint32>(dest_color) * (0xFF - alpha); + return static_cast<uint8>((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 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 alpha = static_cast<uint8>(static_cast<uint32_t>(alpha_adjustment) * + GetAlpha(*src_pixel) / 0xFF); + uint8 red = ProcessColor(GetRed(*src_pixel), GetRed(*dest_pixel), alpha); + uint8 green = ProcessColor(GetGreen(*src_pixel), + GetGreen(*dest_pixel), alpha); + uint8 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 start_color, uint32 end_color, bool horizontal) { + std::vector<uint32> 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 start_color, + uint32 end_color, + bool horizontal, + uint8 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 src_x = static_cast<uint32>(x * x_ratio); + uint32 src_y = static_cast<uint32>(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 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 depth, double factor, uint32 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 y = 0; y < depth_; y++) { + // Since matrix is symmetrical, we can reduce the number of calculations + // by mirroring results. + for (uint32 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 alpha = 0; + if (f > kOpaqueAlpha) + alpha = kOpaqueAlpha; + else if (f < kTransparentAlpha) + alpha = kTransparentAlpha; + else + alpha = static_cast<uint8>(f); + + uint8 red = ProcessColor(0, GetRed(background), alpha); + uint8 green = ProcessColor(0, GetGreen(background), alpha); + uint8 blue = ProcessColor(0, GetBlue(background), alpha); + uint32 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 depth = static_cast<int32>(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>(depth)) + matrix_x = depth - 1; + + if (matrix_y < 0) + matrix_y = 0; + else if (matrix_y >= static_cast<int32>(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/xfa_test/pdf/draw_utils.h b/xfa_test/pdf/draw_utils.h new file mode 100644 index 0000000000..eedf24f27d --- /dev/null +++ b/xfa_test/pdf/draw_utils.h @@ -0,0 +1,94 @@ +// 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 <vector> + +#include "base/basictypes.h" +#include "ppapi/cpp/image_data.h" +#include "ppapi/cpp/rect.h" + +namespace chrome_pdf { + +const uint8 kOpaqueAlpha = 0xFF; +const uint8 kTransparentAlpha = 0x00; + +void AlphaBlend(const pp::ImageData& src, const pp::Rect& src_rc, + pp::ImageData* dest, const pp::Point& dest_origin, + uint8 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 start_color, + uint32 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 start_color, + uint32 end_color, + bool horizontal, + uint8 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 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 depth, double factor, uint32 background); + + ~ShadowMatrix(); + + uint32 GetValue(int32 x, int32 y) const { return matrix_[y * depth_ + x]; } + + uint32 depth() const { return depth_; } + double factor() const { return factor_; } + uint32 background() const { return background_; } + + private: + uint32 depth_; + double factor_; + uint32 background_; + std::vector<uint32> 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/xfa_test/pdf/fading_control.cc b/xfa_test/pdf/fading_control.cc new file mode 100644 index 0000000000..7e4d8ef63e --- /dev/null +++ b/xfa_test/pdf/fading_control.cc @@ -0,0 +1,75 @@ +// 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/fading_control.h" + +#include <math.h> + +#include "base/logging.h" +#include "pdf/draw_utils.h" +#include "pdf/resource_consts.h" + +namespace chrome_pdf { + +FadingControl::FadingControl() + : alpha_shift_(0), timer_id_(0) { +} + +FadingControl::~FadingControl() { +} + +void FadingControl::OnTimerFired(uint32 timer_id) { + if (timer_id == timer_id_) { + int32 new_alpha = transparency() + alpha_shift_; + if (new_alpha <= kTransparentAlpha) { + Show(false, true); + OnFadeOutComplete(); + return; + } + if (new_alpha >= kOpaqueAlpha) { + AdjustTransparency(kOpaqueAlpha, true); + OnFadeInComplete(); + return; + } + + AdjustTransparency(static_cast<uint8>(new_alpha), true); + timer_id_ = owner()->ScheduleTimer(id(), kFadingTimeoutMs); + } +} + +// Fade In/Out control depending on visible flag over the time of time_ms. +void FadingControl::Fade(bool show, uint32 time_ms) { + DCHECK(time_ms != 0); + // Check if we already in the same state. + if (!visible() && !show) + return; + if (!visible() && show) { + Show(show, false); + AdjustTransparency(kTransparentAlpha, false); + OnFadeOutComplete(); + } + if (transparency() == kOpaqueAlpha && show) { + OnFadeInComplete(); + return; + } + + int delta = show ? kOpaqueAlpha - transparency() : transparency(); + double shift = + static_cast<double>(delta) * kFadingTimeoutMs / time_ms; + if (shift > delta) + alpha_shift_ = delta; + else + alpha_shift_ = static_cast<int>(ceil(shift)); + + if (alpha_shift_ == 0) + alpha_shift_ = 1; + + // If disabling, make alpha shift negative. + if (!show) + alpha_shift_ = -alpha_shift_; + + timer_id_ = owner()->ScheduleTimer(id(), kFadingTimeoutMs); +} + +} // namespace chrome_pdf diff --git a/xfa_test/pdf/fading_control.h b/xfa_test/pdf/fading_control.h new file mode 100644 index 0000000000..03ac134698 --- /dev/null +++ b/xfa_test/pdf/fading_control.h @@ -0,0 +1,32 @@ +// 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_FADING_CONTROL_H_ +#define PDF_FADING_CONTROL_H_ + +#include "pdf/control.h" + +namespace chrome_pdf { + +class FadingControl : public Control { + public: + FadingControl(); + virtual ~FadingControl(); + + virtual void OnTimerFired(uint32 timer_id); + + // Fade In/Out control depending on visible flag over the time of time_ms. + virtual void Fade(bool visible, uint32 time_ms); + + virtual void OnFadeInComplete() {} + virtual void OnFadeOutComplete() {} + + private: + int alpha_shift_; + uint32 timer_id_; +}; + +} // namespace chrome_pdf + +#endif // PDF_FADING_CONTROL_H_ diff --git a/xfa_test/pdf/fading_controls.cc b/xfa_test/pdf/fading_controls.cc new file mode 100644 index 0000000000..8a9fd89510 --- /dev/null +++ b/xfa_test/pdf/fading_controls.cc @@ -0,0 +1,316 @@ +// 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/fading_controls.h" + +#include "base/logging.h" +#include "base/stl_util.h" +#include "pdf/draw_utils.h" +#include "pdf/resource_consts.h" +#include "ppapi/cpp/input_event.h" + +namespace chrome_pdf { + +const uint32 kFadingAlphaShift = 64; +const uint32 kSplashFadingAlphaShift = 16; + +FadingControls::FadingControls() + : state_(NONE), current_transparency_(kOpaqueAlpha), fading_timer_id_(0), + current_capture_control_(kInvalidControlId), + fading_timeout_(kFadingTimeoutMs), alpha_shift_(kFadingAlphaShift), + splash_(false), splash_timeout_(0) { +} + +FadingControls::~FadingControls() { + STLDeleteElements(&controls_); +} + +bool FadingControls::CreateFadingControls( + uint32 id, const pp::Rect& rc, bool visible, + Control::Owner* owner, uint8 transparency) { + current_transparency_ = transparency; + return Control::Create(id, rc, visible, owner); +} + +void FadingControls::Paint(pp::ImageData* image_data, const pp::Rect& rc) { + // When this control is set to invisible the individual controls are not. + // So we need to check for visible() here. + if (!visible()) + return; + + std::list<Control*>::iterator iter; + for (iter = controls_.begin(); iter != controls_.end(); ++iter) { + (*iter)->Paint(image_data, rc); + } +} + +bool FadingControls::HandleEvent(const pp::InputEvent& event) { + if (!visible()) + return false; + + pp::MouseInputEvent mouse_event(event); + if (mouse_event.is_null()) + return NotifyControls(event); + + pp::Point pt = mouse_event.GetPosition(); + + bool is_mouse_click = + mouse_event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN || + mouse_event.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP; + + if (rect().Contains(pt)) { + CancelSplashMode(); + FadeIn(); + + // Eat mouse click if are invisible or just fading in. + // That prevents accidental clicks on the controls for touch devices. + bool eat_mouse_click = + (state_ == FADING_IN || current_transparency_ == kTransparentAlpha); + if (eat_mouse_click && is_mouse_click && + mouse_event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_LEFT) + return true; // Eat this event here. + } + + if ((!rect().Contains(pt)) || + event.GetType() == PP_INPUTEVENT_TYPE_MOUSELEAVE) { + if (!splash_) + FadeOut(); + pp::MouseInputEvent event_leave(pp::MouseInputEvent( + owner()->GetInstance(), + PP_INPUTEVENT_TYPE_MOUSELEAVE, + event.GetTimeStamp(), + event.GetModifiers(), + mouse_event.GetButton(), + mouse_event.GetPosition(), + mouse_event.GetClickCount(), + mouse_event.GetMovement())); + return NotifyControls(event_leave); + } + + return NotifyControls(event); +} + +void FadingControls::OnTimerFired(uint32 timer_id) { + if (timer_id == fading_timer_id_) { + int32 current_alpha = static_cast<int32>(current_transparency_); + if (state_ == FADING_IN) + current_alpha += alpha_shift_; + else if (state_ == FADING_OUT) + current_alpha -= alpha_shift_; + + if (current_alpha >= kOpaqueAlpha) { + state_ = NONE; + current_alpha = kOpaqueAlpha; + } else if (current_alpha <= kTransparentAlpha) { + state_ = NONE; + current_alpha = kTransparentAlpha; + } + current_transparency_ = static_cast<uint8>(current_alpha); + + // Invalidate controls with new alpha transparency. + std::list<Control*>::iterator iter; + for (iter = controls_.begin(); iter != controls_.end(); ++iter) { + // We are going to invalidate the whole FadingControls area, to + // allow simultaneous drawing. + (*iter)->AdjustTransparency(current_transparency_, false); + } + owner()->Invalidate(id(), GetControlsRect()); + + if (state_ != NONE) // Fading still in progress. + fading_timer_id_ = owner()->ScheduleTimer(id(), fading_timeout_); + else + OnFadingComplete(); + } else { + // Dispatch timer to controls. + std::list<Control*>::iterator iter; + for (iter = controls_.begin(); iter != controls_.end(); ++iter) { + (*iter)->OnTimerFired(timer_id); + } + } +} + +void FadingControls::EventCaptureReleased() { + if (current_capture_control_ != kInvalidControlId) { + // Remove previous catpure. + Control* ctrl = GetControl(current_capture_control_); + if (ctrl) + ctrl->EventCaptureReleased(); + } +} + +void FadingControls::MoveBy(const pp::Point& offset, bool invalidate) { + std::list<Control*>::iterator iter; + for (iter = controls_.begin(); iter != controls_.end(); ++iter) { + // We invalidate entire FadingControl later if needed. + (*iter)->MoveBy(offset, false); + } + Control::MoveBy(offset, invalidate); +} + +void FadingControls::OnEvent(uint32 control_id, uint32 event_id, void* data) { + owner()->OnEvent(control_id, event_id, data); +} + +void FadingControls::Invalidate(uint32 control_id, const pp::Rect& rc) { + owner()->Invalidate(control_id, rc); +} + +uint32 FadingControls::ScheduleTimer(uint32 control_id, uint32 timeout_ms) { + // TODO(gene): implement timer routine properly. + NOTIMPLEMENTED(); + //owner()->ScheduleTimer(control_id); + return 0; +} + +void FadingControls::SetEventCapture(uint32 control_id, bool set_capture) { + if (control_id == current_capture_control_) { + if (!set_capture) // Remove event capture. + current_capture_control_ = kInvalidControlId; + } else { + EventCaptureReleased(); + current_capture_control_ = control_id; + } +} + +void FadingControls::SetCursor(uint32 control_id, + PP_CursorType_Dev cursor_type) { + owner()->SetCursor(control_id, cursor_type); +} + +pp::Instance* FadingControls::GetInstance() { + return owner()->GetInstance(); +} + +bool FadingControls::AddControl(Control* control) { + DCHECK(control); + if (control->owner() != this) + return false; + if (!rect().Contains(control->rect())) + return false; + + control->AdjustTransparency(current_transparency_, false); + controls_.push_back(control); + return true; +} + +void FadingControls::RemoveControl(uint32 control_id) { + if (current_capture_control_ == control_id) { + current_capture_control_ = kInvalidControlId; + } + std::list<Control*>::iterator iter; + for (iter = controls_.begin(); iter != controls_.end(); ++iter) { + if ((*iter)->id() == control_id) { + delete (*iter); + controls_.erase(iter); + break; + } + } +} + +Control* FadingControls::GetControl(uint32 id) { + std::list<Control*>::iterator iter; + for (iter = controls_.begin(); iter != controls_.end(); ++iter) { + if ((*iter)->id() == id) + return *iter; + } + return NULL; +} + +pp::Rect FadingControls::GetControlsRect() { + pp::Rect rc; + std::list<Control*>::iterator iter; + for (iter = controls_.begin(); iter != controls_.end(); ++iter) { + rc = rc.Union((*iter)->rect()); + } + return rc; +} + +bool FadingControls::ExpandLeft(int offset) { + pp::Rect rc = rect(); + rc.set_width(rc.width() + offset); + rc.set_x(rc.x() - offset); + if (!rc.Contains(GetControlsRect())) + return false; + // No need to invalidate since we are expanding triggering area only. + SetRect(rc, false); + return true; +} + +void FadingControls::Splash(uint32 time_ms) { + splash_ = true; + splash_timeout_ = time_ms; + alpha_shift_ = kSplashFadingAlphaShift; + FadeIn(); +} + +bool FadingControls::NotifyControls(const pp::InputEvent& event) { + // First pass event to a control that current capture is set to. + Control* ctrl = GetControl(current_capture_control_); + if (ctrl) { + if (ctrl->HandleEvent(event)) + return true; + } + + std::list<Control*>::iterator iter; + for (iter = controls_.begin(); iter != controls_.end(); ++iter) { + // Now pass event to all control except control with capture, + // since we already passed to it above. + if ((*iter) != ctrl && (*iter)->HandleEvent(event)) + return true; + } + return false; +} + +void FadingControls::FadeIn() { + bool already_visible = + (state_ == NONE && current_transparency_ == kOpaqueAlpha); + if (state_ != FADING_IN && !already_visible) { + state_ = FADING_IN; + fading_timer_id_ = owner()->ScheduleTimer(id(), fading_timeout_); + } + if (already_visible) + OnFadingComplete(); +} + +void FadingControls::FadeOut() { + bool already_invisible = + (state_ == NONE && current_transparency_ == kTransparentAlpha); + if (state_ != FADING_OUT && !already_invisible) { + state_ = FADING_OUT; + fading_timer_id_ = owner()->ScheduleTimer(id(), fading_timeout_); + } + if (already_invisible) + OnFadingComplete(); +} + +void FadingControls::OnFadingComplete() { + DCHECK(current_transparency_ == kOpaqueAlpha || + current_transparency_ == kTransparentAlpha); + // In the splash mode following states are possible: + // Fade-in complete: splash_==true, splash_timeout_ != 0 + // We need to schedule timer for splash_timeout_. + // Splash timeout complete: splash_==true, splash_timeout_ == 0 + // We need to fade out still using splash settings. + // Fade-out complete: current_transparency_ == kTransparentAlpha + // We need to cancel splash mode and go back to normal settings. + if (splash_) { + if (current_transparency_ == kOpaqueAlpha) { + if (splash_timeout_) { + fading_timer_id_ = owner()->ScheduleTimer(id(), splash_timeout_); + splash_timeout_ = 0; + } else { + FadeOut(); + } + } else { + CancelSplashMode(); + } + } +} + +void FadingControls::CancelSplashMode() { + splash_ = false; + alpha_shift_ = kFadingAlphaShift; +} + +} // namespace chrome_pdf diff --git a/xfa_test/pdf/fading_controls.h b/xfa_test/pdf/fading_controls.h new file mode 100644 index 0000000000..532464b473 --- /dev/null +++ b/xfa_test/pdf/fading_controls.h @@ -0,0 +1,84 @@ +// 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_FADING_CONTROLS_H_ +#define PDF_FADING_CONTROLS_H_ + +#include <list> + +#include "pdf/control.h" + +namespace chrome_pdf { + +class FadingControls : public Control, + public ControlOwner { + public: + enum FadingState { + NONE, + FADING_IN, + FADING_OUT + }; + + FadingControls(); + virtual ~FadingControls(); + virtual bool CreateFadingControls( + uint32 id, const pp::Rect& rc, bool visible, + Control::Owner* delegate, uint8 transparency); + + // Control interface. + virtual void Paint(pp::ImageData* image_data, const pp::Rect& rc); + virtual bool HandleEvent(const pp::InputEvent& event); + virtual void OnTimerFired(uint32 timer_id); + virtual void EventCaptureReleased(); + virtual void MoveBy(const pp::Point& offset, bool invalidate); + + // ControlOwner interface. + virtual void OnEvent(uint32 control_id, uint32 event_id, void* data); + virtual void Invalidate(uint32 control_id, const pp::Rect& rc); + virtual uint32 ScheduleTimer(uint32 control_id, uint32 timeout_ms); + virtual void SetEventCapture(uint32 control_id, bool set_capture); + virtual void SetCursor(uint32 control_id, PP_CursorType_Dev cursor_type); + virtual pp::Instance* GetInstance(); + + // FadingControls interface + // This function takes ownership of the control, and will destoy it + // when control is destroyed. + // Input control MUST be located inside FadingControls boundaries, and has + // this instance of FadingControls as a delegate. + virtual bool AddControl(Control* control); + virtual void RemoveControl(uint32 control_id); + virtual Control* GetControl(uint32 id); + virtual pp::Rect GetControlsRect(); + + // Expand/Shrink area which triggers inner control appearance to the left. + virtual bool ExpandLeft(int offset); + + // Fade-in, then show controls for time_ms, and then fade-out. Any mouse + // event in this control area will interrupt splash mode. + virtual void Splash(uint32 time_ms); + + uint8 current_transparency() const { return current_transparency_; } + + private: + bool NotifyControls(const pp::InputEvent& event); + void FadeIn(); + void FadeOut(); + void OnFadingComplete(); + void CancelSplashMode(); + + std::list<Control*> controls_; + FadingState state_; + uint8 current_transparency_; + uint32 fading_timer_id_; + uint32 current_capture_control_; + uint32 fading_timeout_; + uint32 alpha_shift_; + bool splash_; + uint32 splash_timeout_; +}; + +} // namespace chrome_pdf + +#endif // PDF_FADING_CONTROLS_H_ + diff --git a/xfa_test/pdf/instance.cc b/xfa_test/pdf/instance.cc new file mode 100644 index 0000000000..4bd2f787df --- /dev/null +++ b/xfa_test/pdf/instance.cc @@ -0,0 +1,2778 @@ +// 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/instance.h" + +#include <algorithm> // for min() +#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/values.h" +#include "chrome/browser/chrome_page_zoom_constants.h" +#include "chrome/common/content_restriction.h" +#include "content/public/common/page_zoom.h" +#include "net/base/escape.h" +#include "pdf/draw_utils.h" +#include "pdf/number_image_generator.h" +#include "pdf/pdf.h" +#include "pdf/resource_consts.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/ppp_pdf.h" +#include "ppapi/c/trusted/ppb_url_loader_trusted.h" +#include "ppapi/cpp/core.h" +#include "ppapi/cpp/dev/font_dev.h" +#include "ppapi/cpp/dev/memory_dev.h" +#include "ppapi/cpp/dev/text_input_dev.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/point.h" +#include "ppapi/cpp/private/pdf.h" +#include "ppapi/cpp/rect.h" +#include "ppapi/cpp/resource.h" +#include "ppapi/cpp/url_request_info.h" +#include "ui/events/keycodes/keyboard_codes.h" + +#if defined(OS_MACOSX) +#include "base/mac/mac_util.h" +#endif + +namespace chrome_pdf { + +struct ToolbarButtonInfo { + uint32 id; + Button::ButtonStyle style; + PP_ResourceImage normal; + PP_ResourceImage highlighted; + PP_ResourceImage pressed; +}; + +namespace { + +// Uncomment following #define to enable thumbnails. +// #define ENABLE_THUMBNAILS + +const uint32 kToolbarSplashTimeoutMs = 6000; +const uint32 kMessageTextColor = 0xFF575757; +const uint32 kMessageTextSize = 22; +const uint32 kProgressFadeTimeoutMs = 250; +const uint32 kProgressDelayTimeoutMs = 1000; +const uint32 kAutoScrollTimeoutMs = 50; +const double kAutoScrollFactor = 0.2; + +// Javascript methods. +const char kJSAccessibility[] = "accessibility"; +const char kJSDocumentLoadComplete[] = "documentLoadComplete"; +const char kJSGetHeight[] = "getHeight"; +const char kJSGetHorizontalScrollbarThickness[] = + "getHorizontalScrollbarThickness"; +const char kJSGetPageLocationNormalized[] = "getPageLocationNormalized"; +const char kJSGetSelectedText[] = "getSelectedText"; +const char kJSGetVerticalScrollbarThickness[] = "getVerticalScrollbarThickness"; +const char kJSGetWidth[] = "getWidth"; +const char kJSGetZoomLevel[] = "getZoomLevel"; +const char kJSGoToPage[] = "goToPage"; +const char kJSGrayscale[] = "grayscale"; +const char kJSLoadPreviewPage[] = "loadPreviewPage"; +const char kJSOnLoad[] = "onload"; +const char kJSOnPluginSizeChanged[] = "onPluginSizeChanged"; +const char kJSOnScroll[] = "onScroll"; +const char kJSPageXOffset[] = "pageXOffset"; +const char kJSPageYOffset[] = "pageYOffset"; +const char kJSPrintPreviewPageCount[] = "printPreviewPageCount"; +const char kJSReload[] = "reload"; +const char kJSRemovePrintButton[] = "removePrintButton"; +const char kJSResetPrintPreviewUrl[] = "resetPrintPreviewUrl"; +const char kJSSendKeyEvent[] = "sendKeyEvent"; +const char kJSSetPageNumbers[] = "setPageNumbers"; +const char kJSSetPageXOffset[] = "setPageXOffset"; +const char kJSSetPageYOffset[] = "setPageYOffset"; +const char kJSSetZoomLevel[] = "setZoomLevel"; +const char kJSZoomFitToHeight[] = "fitToHeight"; +const char kJSZoomFitToWidth[] = "fitToWidth"; +const char kJSZoomIn[] = "zoomIn"; +const char kJSZoomOut[] = "zoomOut"; + +// URL reference parameters. +// For more possible parameters, see RFC 3778 and the "PDF Open Parameters" +// document from Adobe. +const char kDelimiters[] = "#&"; +const char kNamedDest[] = "nameddest"; +const char kPage[] = "page"; + +const char kChromePrint[] = "chrome://print/"; + +// Dictionary Value key names for the document accessibility info +const char kAccessibleNumberOfPages[] = "numberOfPages"; +const char kAccessibleLoaded[] = "loaded"; +const char kAccessibleCopyable[] = "copyable"; + +const ToolbarButtonInfo kPDFToolbarButtons[] = { + { kFitToPageButtonId, Button::BUTTON_STATE, + PP_RESOURCEIMAGE_PDF_BUTTON_FTP, + PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER, + PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED }, + { kFitToWidthButtonId, Button::BUTTON_STATE, + PP_RESOURCEIMAGE_PDF_BUTTON_FTW, + PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER, + PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED }, + { kZoomOutButtonId, Button::BUTTON_CLICKABLE, + PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT, + PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER, + PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED }, + { kZoomInButtonId, Button::BUTTON_CLICKABLE, + PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN, + PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER, + PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED }, + { kSaveButtonId, Button::BUTTON_CLICKABLE, + PP_RESOURCEIMAGE_PDF_BUTTON_SAVE, + PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_HOVER, + PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_PRESSED }, + { kPrintButtonId, Button::BUTTON_CLICKABLE, + PP_RESOURCEIMAGE_PDF_BUTTON_PRINT, + PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_HOVER, + PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_PRESSED }, +}; + +const ToolbarButtonInfo kPDFNoPrintToolbarButtons[] = { + { kFitToPageButtonId, Button::BUTTON_STATE, + PP_RESOURCEIMAGE_PDF_BUTTON_FTP, + PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER, + PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED }, + { kFitToWidthButtonId, Button::BUTTON_STATE, + PP_RESOURCEIMAGE_PDF_BUTTON_FTW, + PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER, + PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED }, + { kZoomOutButtonId, Button::BUTTON_CLICKABLE, + PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT, + PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER, + PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED }, + { kZoomInButtonId, Button::BUTTON_CLICKABLE, + PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN, + PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER, + PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED }, + { kSaveButtonId, Button::BUTTON_CLICKABLE, + PP_RESOURCEIMAGE_PDF_BUTTON_SAVE, + PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_HOVER, + PP_RESOURCEIMAGE_PDF_BUTTON_SAVE_PRESSED }, + { kPrintButtonId, Button::BUTTON_CLICKABLE, + PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED, + PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED, + PP_RESOURCEIMAGE_PDF_BUTTON_PRINT_DISABLED } +}; + +const ToolbarButtonInfo kPrintPreviewToolbarButtons[] = { + { kFitToPageButtonId, Button::BUTTON_STATE, + PP_RESOURCEIMAGE_PDF_BUTTON_FTP, + PP_RESOURCEIMAGE_PDF_BUTTON_FTP_HOVER, + PP_RESOURCEIMAGE_PDF_BUTTON_FTP_PRESSED }, + { kFitToWidthButtonId, Button::BUTTON_STATE, + PP_RESOURCEIMAGE_PDF_BUTTON_FTW, + PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER, + PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED }, + { kZoomOutButtonId, Button::BUTTON_CLICKABLE, + PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT, + PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER, + PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED }, + { kZoomInButtonId, Button::BUTTON_CLICKABLE, + PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END, + PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END_HOVER, + PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_END_PRESSED }, +}; + +static const char kPPPPdfInterface[] = PPP_PDF_INTERFACE_1; + +PP_Var GetLinkAtPosition(PP_Instance instance, PP_Point point) { + pp::Var var; + void* object = + pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface); + if (object) + var = static_cast<Instance*>(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) { + Instance* obj_instance = static_cast<Instance*>(object); + switch (type) { + case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CW: + obj_instance->RotateClockwise(); + break; + case PP_PRIVATEPAGETRANSFORMTYPE_ROTATE_90_CCW: + obj_instance->RotateCounterclockwise(); + break; + } + } +} + +const PPP_Pdf ppp_private = { + &GetLinkAtPosition, + &Transform +}; + +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)), '/', &url_substr); + 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); +} + +template<class T> +T ClipToRange(T value, T lower_boundary, T upper_boundary) { + DCHECK(lower_boundary <= upper_boundary); + return std::max<T>(lower_boundary, std::min<T>(value, upper_boundary)); +} + +} // namespace + +Instance::Instance(PP_Instance instance) + : pp::InstancePrivate(instance), + pp::Find_Private(this), + pp::Printing_Dev(this), + pp::Selection_Dev(this), + pp::WidgetClient_Dev(this), + pp::Zoom_Dev(this), + cursor_(PP_CURSORTYPE_POINTER), + timer_pending_(false), + current_timer_id_(0), + zoom_(1.0), + device_scale_(1.0), + printing_enabled_(true), + hidpi_enabled_(false), + full_(IsFullFrame()), + zoom_mode_(full_ ? ZOOM_AUTO : ZOOM_SCALE), + did_call_start_loading_(false), + is_autoscroll_(false), + scrollbar_thickness_(-1), + scrollbar_reserved_thickness_(-1), + current_tb_info_(NULL), + current_tb_info_size_(0), + paint_manager_(this, this, true), + delayed_progress_timer_id_(0), + first_paint_(true), + painted_first_page_(false), + show_page_indicator_(false), + document_load_state_(LOAD_STATE_LOADING), + preview_document_load_state_(LOAD_STATE_COMPLETE), + told_browser_about_unsupported_feature_(false), + print_preview_page_count_(0) { + loader_factory_.Initialize(this); + timer_factory_.Initialize(this); + form_factory_.Initialize(this); + 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_WHEEL); + RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_KEYBOARD); + RequestFilteringInputEvents(PP_INPUTEVENT_CLASS_TOUCH); +} + +Instance::~Instance() { + if (timer_pending_) { + timer_factory_.CancelAll(); + timer_pending_ = false; + } + // The engine may try to access this instance during its destruction. + // Make sure this happens early while the instance is still intact. + engine_.reset(); + RemovePerInstanceObject(kPPPPdfInterface, this); +} + +bool Instance::Init(uint32_t argc, const char* argn[], const char* argv[]) { + // For now, we hide HiDPI support behind a flag. + if (pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_HIDPI)) + hidpi_enabled_ = true; + + printing_enabled_ = pp::PDF::IsFeatureEnabled(this, PP_PDFFEATURE_PRINTING); + if (printing_enabled_) { + CreateToolbar(kPDFToolbarButtons, arraysize(kPDFToolbarButtons)); + } else { + CreateToolbar(kPDFNoPrintToolbarButtons, + arraysize(kPDFNoPrintToolbarButtons)); + } + + CreateProgressBar(); + + // Load autoscroll anchor image. + autoscroll_anchor_ = + CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON); + +#ifdef ENABLE_THUMBNAILS + CreateThumbnails(); +#endif + const char* url = NULL; + for (uint32_t i = 0; i < argc; ++i) { + if (strcmp(argn[i], "src") == 0) { + url = argv[i]; + break; + } + } + + if (!url) + return false; + + CreatePageIndicator(IsPrintPreviewUrl(url)); + + if (!full_) { + // For PDFs embedded in a frame, we don't get the data automatically like we + // do for full-frame loads. Start loading the data manually. + LoadUrl(url); + } else { + DCHECK(!did_call_start_loading_); + pp::PDF::DidStartLoading(this); + did_call_start_loading_ = true; + } + + ZoomLimitsChanged(kMinZoom, kMaxZoom); + + text_input_.reset(new pp::TextInput_Dev(this)); + + url_ = url; + return engine_->New(url); +} + +bool Instance::HandleDocumentLoad(const pp::URLLoader& loader) { + delayed_progress_timer_id_ = ScheduleTimer(kProgressBarId, + kProgressDelayTimeoutMs); + return engine_->HandleDocumentLoad(loader); +} + +bool Instance::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; + } + } + + // Check if we need to go to autoscroll mode. + if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE && + (event.GetModifiers() & PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN)) { + pp::MouseInputEvent mouse_event(event_device_res); + pp::Point pos = mouse_event.GetPosition(); + EnableAutoscroll(pos); + UpdateCursor(CalculateAutoscroll(pos)); + return true; + } else { + // Quit autoscrolling on any other event. + DisableAutoscroll(); + } + +#ifdef ENABLE_THUMBNAILS + if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSELEAVE) + thumbnails_.SlideOut(); + + if (thumbnails_.HandleEvent(event_device_res)) + return true; +#endif + + if (toolbar_->HandleEvent(event_device_res)) + return true; + +#ifdef ENABLE_THUMBNAILS + if (v_scrollbar_.get() && event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE) { + pp::MouseInputEvent mouse_event(event); + pp::Point pt = mouse_event.GetPosition(); + pp::Rect v_scrollbar_rc; + v_scrollbar_->GetLocation(&v_scrollbar_rc); + // There is a bug (https://bugs.webkit.org/show_bug.cgi?id=45208) + // in the webkit that makes event.u.mouse.button + // equal to PP_INPUTEVENT_MOUSEBUTTON_LEFT, even when no button is pressed. + // To work around this issue we use modifier for now, and will switch + // to button once the bug is fixed and webkit got merged back to our tree. + if (v_scrollbar_rc.Contains(pt) && + (event.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN)) { + thumbnails_.SlideIn(); + } + + // When scrollbar is in the scrolling mode we should display thumbnails + // even the mouse is outside the thumbnail and scrollbar areas. + // If mouse is outside plugin area, we are still getting mouse move events + // while scrolling. See bug description for details: + // http://code.google.com/p/chromium/issues/detail?id=56444 + if (!v_scrollbar_rc.Contains(pt) && thumbnails_.visible() && + !(event.GetModifiers() & PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN) && + !thumbnails_.rect().Contains(pt)) { + thumbnails_.SlideOut(); + } + } +#endif + + // Need to pass the event to the engine first, since if we're over an edit + // control we want it to get keyboard events (like space) instead of the + // scrollbar. + // TODO: will have to offset the mouse coordinates once we support bidi and + // there could be scrollbars on the left. + pp::InputEvent offset_event(event_device_res); + bool try_engine_first = true; + 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()); + if (!engine_->IsSelecting()) { + if (!IsOverlayScrollbar() && + !available_area_.Contains(mouse_event.GetPosition())) { + try_engine_first = false; + } else if (IsOverlayScrollbar()) { + pp::Rect temp; + if ((v_scrollbar_.get() && v_scrollbar_->GetLocation(&temp) && + temp.Contains(mouse_event_dip.GetPosition())) || + (h_scrollbar_.get() && h_scrollbar_->GetLocation(&temp) && + temp.Contains(mouse_event_dip.GetPosition()))) { + try_engine_first = false; + } + } + } + break; + } + default: + break; + } + if (try_engine_first && engine_->HandleEvent(offset_event)) + return true; + + // Left/Right arrows should scroll to the beginning of the Prev/Next page if + // there is no horizontal scroll bar. + // If fit-to-height, PgDown/PgUp should scroll to the beginning of the + // Prev/Next page. Spacebar / shift+spacebar should do the same. + if (v_scrollbar_.get() && event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN) { + pp::KeyboardInputEvent keyboard_event(event); + bool no_h_scrollbar = !h_scrollbar_.get(); + uint32_t key_code = keyboard_event.GetKeyCode(); + bool page_down = no_h_scrollbar && key_code == ui::VKEY_RIGHT; + bool page_up = no_h_scrollbar && key_code == ui::VKEY_LEFT; + if (zoom_mode_ == ZOOM_FIT_TO_PAGE) { + bool has_shift = + keyboard_event.GetModifiers() & PP_INPUTEVENT_MODIFIER_SHIFTKEY; + bool key_is_space = key_code == ui::VKEY_SPACE; + page_down |= key_is_space || key_code == ui::VKEY_NEXT; + page_up |= (key_is_space && has_shift) || (key_code == ui::VKEY_PRIOR); + } + if (page_down) { + int page = engine_->GetFirstVisiblePage(); + if (page == -1) + return true; + // Engine calculates visible page including delimiter to the page size. + // We need to check here if the page itself is completely out of view and + // scroll to the next one in that case. + if (engine_->GetPageRect(page).bottom() * zoom_ <= + v_scrollbar_->GetValue()) + page++; + ScrollToPage(page + 1); + UpdateCursor(PP_CURSORTYPE_POINTER); + return true; + } else if (page_up) { + int page = engine_->GetFirstVisiblePage(); + if (page == -1) + return true; + if (engine_->GetPageRect(page).y() * zoom_ >= v_scrollbar_->GetValue()) + page--; + ScrollToPage(page); + UpdateCursor(PP_CURSORTYPE_POINTER); + return true; + } + } + + if (v_scrollbar_.get() && v_scrollbar_->HandleEvent(event)) { + UpdateCursor(PP_CURSORTYPE_POINTER); + return true; + } + + if (h_scrollbar_.get() && h_scrollbar_->HandleEvent(event)) { + UpdateCursor(PP_CURSORTYPE_POINTER); + return true; + } + + if (timer_pending_ && + (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP || + event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE)) { + timer_factory_.CancelAll(); + timer_pending_ = false; + } else if (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEMOVE && + engine_->IsSelecting()) { + bool set_timer = false; + pp::MouseInputEvent mouse_event(event); + if (v_scrollbar_.get() && + (mouse_event.GetPosition().y() <= 0 || + mouse_event.GetPosition().y() >= (plugin_dip_size_.height() - 1))) { + v_scrollbar_->ScrollBy( + PP_SCROLLBY_LINE, mouse_event.GetPosition().y() >= 0 ? 1: -1); + set_timer = true; + } + if (h_scrollbar_.get() && + (mouse_event.GetPosition().x() <= 0 || + mouse_event.GetPosition().x() >= (plugin_dip_size_.width() - 1))) { + h_scrollbar_->ScrollBy(PP_SCROLLBY_LINE, + mouse_event.GetPosition().x() >= 0 ? 1: -1); + set_timer = true; + } + + if (set_timer) { + last_mouse_event_ = pp::MouseInputEvent(event); + + pp::CompletionCallback callback = + timer_factory_.NewCallback(&Instance::OnTimerFired); + pp::Module::Get()->core()->CallOnMainThread(kDragTimerMs, callback); + timer_pending_ = true; + } + } + + if (event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN) { + pp::KeyboardInputEvent keyboard_event(event); + const uint32 modifier = event.GetModifiers(); + if (modifier & kDefaultKeyModifier) { + switch (keyboard_event.GetKeyCode()) { + case 'A': + engine_->SelectAll(); + return true; + } + } else if (modifier & PP_INPUTEVENT_MODIFIER_CONTROLKEY) { + switch (keyboard_event.GetKeyCode()) { + case ui::VKEY_OEM_4: + // Left bracket. + engine_->RotateCounterclockwise(); + return true; + case ui::VKEY_OEM_6: + // Right bracket. + engine_->RotateClockwise(); + return true; + } + } + } + + // Return true for unhandled clicks so the plugin takes focus. + return (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN); +} + +void Instance::DidChangeView(const pp::View& view) { + pp::Rect view_rect(view.GetRect()); + float device_scale = 1.0f; + float old_device_scale = device_scale_; + if (hidpi_enabled_) + 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_) + return; // We don't care about the position, only the size. + + image_data_ = pp::ImageData(); + device_scale_ = device_scale; + plugin_dip_size_ = view_rect.size(); + plugin_size_ = view_device_size; + + paint_manager_.SetSize(view_device_size, device_scale_); + + image_data_ = pp::ImageData(this, + PP_IMAGEDATAFORMAT_BGRA_PREMUL, + plugin_size_, + false); + if (image_data_.is_null()) { + DCHECK(plugin_size_.IsEmpty()); + return; + } + + // View dimensions changed, disable autoscroll (if it was enabled). + DisableAutoscroll(); + + OnGeometryChanged(zoom_, old_device_scale); +} + +pp::Var Instance::GetInstanceObject() { + if (instance_object_.is_undefined()) { + PDFScriptableObject* object = new PDFScriptableObject(this); + // The pp::Var takes ownership of object here. + instance_object_ = pp::VarPrivate(this, object); + } + + return instance_object_; +} + +pp::Var Instance::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); +} + +pp::Var Instance::GetSelectedText(bool html) { + if (html || !engine_->HasPermission(PDFEngine::PERMISSION_COPY)) + return pp::Var(); + return engine_->GetSelectedText(); +} + +void Instance::InvalidateWidget(pp::Widget_Dev widget, + const pp::Rect& dirty_rect) { + if (v_scrollbar_.get() && *v_scrollbar_ == widget) { + if (!image_data_.is_null()) + v_scrollbar_->Paint(dirty_rect.pp_rect(), &image_data_); + } else if (h_scrollbar_.get() && *h_scrollbar_ == widget) { + if (!image_data_.is_null()) + h_scrollbar_->Paint(dirty_rect.pp_rect(), &image_data_); + } else { + // Possible to hit this condition since sometimes the scrollbar codes posts + // a task to do something later, and we could have deleted our reference in + // the meantime. + return; + } + + pp::Rect dirty_rect_scaled = dirty_rect; + ScaleRect(device_scale_, &dirty_rect_scaled); + paint_manager_.InvalidateRect(dirty_rect_scaled); +} + +void Instance::ScrollbarValueChanged(pp::Scrollbar_Dev scrollbar, + uint32_t value) { + value = GetScaled(value); + if (v_scrollbar_.get() && *v_scrollbar_ == scrollbar) { + engine_->ScrolledToYPosition(value); + pp::Rect rc; + v_scrollbar_->GetLocation(&rc); + int32 doc_height = GetDocumentPixelHeight(); + doc_height -= GetScaled(rc.height()); +#ifdef ENABLE_THUMBNAILS + if (thumbnails_.visible()) { + thumbnails_.SetPosition(value, doc_height, true); + } +#endif + pp::Point origin( + plugin_size_.width() - page_indicator_.rect().width() - + GetScaled(GetScrollbarReservedThickness()), + page_indicator_.GetYPosition(value, doc_height, plugin_size_.height())); + page_indicator_.MoveTo(origin, page_indicator_.visible()); + } else if (h_scrollbar_.get() && *h_scrollbar_ == scrollbar) { + engine_->ScrolledToXPosition(value); + } +} + +void Instance::ScrollbarOverlayChanged(pp::Scrollbar_Dev scrollbar, + bool overlay) { + scrollbar_reserved_thickness_ = overlay ? 0 : scrollbar_thickness_; + OnGeometryChanged(zoom_, device_scale_); +} + +uint32_t Instance::QuerySupportedPrintOutputFormats() { + return engine_->QuerySupportedPrintOutputFormats(); +} + +int32_t Instance::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 Instance::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 Instance::PrintEnd() { + if (print_settings_.print_pages_called_) + UserMetricsRecordAction("PDF.PrintPage"); + print_settings_.Clear(); + engine_->PrintEnd(); +} + +bool Instance::IsPrintScalingDisabled() { + return !engine_->GetPrintScaling(); +} + +bool Instance::StartFind(const std::string& text, bool case_sensitive) { + engine_->StartFind(text.c_str(), case_sensitive); + return true; +} + +void Instance::SelectFindResult(bool forward) { + engine_->SelectFindResult(forward); +} + +void Instance::StopFind() { + engine_->StopFind(); +} + +void Instance::Zoom(double scale, bool text_only) { + UserMetricsRecordAction("PDF.ZoomFromBrowser"); + + // If the zoom level doesn't change it means that this zoom change might have + // been initiated by the plugin. In that case, we don't want to change the + // zoom mode to ZOOM_SCALE as it may have been intentionally set to + // ZOOM_FIT_TO_PAGE or some other value when the zoom was last changed. + if (scale == zoom_) + return; + + SetZoom(ZOOM_SCALE, scale); +} + +void Instance::ZoomChanged(double factor) { + if (full_) + Zoom_Dev::ZoomChanged(factor); +} + +void Instance::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(), plugin_size_); + FillRect(rect, kBackgroundColor); + ready->push_back(PaintManager::ReadyRect(rect, image_data_, true)); + *pending = paint_rects; + return; + } + + engine_->PrePaint(); + + for (size_t i = 0; i < paint_rects.size(); i++) { + // Intersect with plugin area since there could be pending invalidates from + // when the plugin area was larger. + pp::Rect rect = + paint_rects[i].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 (size_t j = 0; j < pdf_ready.size(); ++j) { + pdf_ready[j].Offset(available_area_.point()); + ready->push_back( + PaintManager::ReadyRect(pdf_ready[j], image_data_, false)); + } + for (size_t j = 0; j < pdf_pending.size(); ++j) { + pdf_pending[j].Offset(available_area_.point()); + pending->push_back(pdf_pending[j]); + } + } + + for (size_t j = 0; j < background_parts_.size(); ++j) { + pp::Rect intersection = background_parts_[j].location.Intersect(rect); + if (!intersection.IsEmpty()) { + FillRect(intersection, background_parts_[j].color); + ready->push_back( + PaintManager::ReadyRect(intersection, image_data_, false)); + } + } + + if (document_load_state_ == LOAD_STATE_FAILED) { + pp::Point top_center; + top_center.set_x(plugin_size_.width() / 2); + top_center.set_y(plugin_size_.height() / 2); + DrawText(top_center, PP_RESOURCESTRING_PDFLOAD_FAILED); + } + +#ifdef ENABLE_THUMBNAILS + thumbnails_.Paint(&image_data_, rect); +#endif + } + + engine_->PostPaint(); + + // Must paint scrollbars after the background parts, in case we have an + // overlay scrollbar that's over the background. We also do this in a separate + // loop because the scrollbar painting logic uses the signal of whether there + // are pending paints or not to figure out if it should draw right away or + // not. + for (size_t i = 0; i < paint_rects.size(); i++) { + PaintIfWidgetIntersects(h_scrollbar_.get(), paint_rects[i], ready, pending); + PaintIfWidgetIntersects(v_scrollbar_.get(), paint_rects[i], ready, pending); + } + + if (progress_bar_.visible()) + PaintOverlayControl(&progress_bar_, &image_data_, ready); + + if (page_indicator_.visible()) + PaintOverlayControl(&page_indicator_, &image_data_, ready); + + if (toolbar_->current_transparency() != kTransparentAlpha) + PaintOverlayControl(toolbar_.get(), &image_data_, ready); + + // Paint autoscroll anchor if needed. + if (is_autoscroll_) { + size_t limit = ready->size(); + for (size_t i = 0; i < limit; i++) { + pp::Rect anchor_rect = autoscroll_rect_.Intersect((*ready)[i].rect); + if (!anchor_rect.IsEmpty()) { + pp::Rect draw_rc = pp::Rect( + pp::Point(anchor_rect.x() - autoscroll_rect_.x(), + anchor_rect.y() - autoscroll_rect_.y()), + anchor_rect.size()); + // Paint autoscroll anchor. + AlphaBlend(autoscroll_anchor_, draw_rc, + &image_data_, anchor_rect.point(), kOpaqueAlpha); + } + } + } +} + +void Instance::PaintOverlayControl( + Control* ctrl, + pp::ImageData* image_data, + std::vector<PaintManager::ReadyRect>* ready) { + // Make sure that we only paint overlay controls over an area that's ready, + // i.e. not pending. Otherwise we'll mark the control rect as ready and + // it'll overwrite the pdf region. + std::list<pp::Rect> ctrl_rects; + for (size_t i = 0; i < ready->size(); i++) { + pp::Rect rc = ctrl->rect().Intersect((*ready)[i].rect); + if (!rc.IsEmpty()) + ctrl_rects.push_back(rc); + } + + if (!ctrl_rects.empty()) { + ctrl->PaintMultipleRects(image_data, ctrl_rects); + + std::list<pp::Rect>::iterator iter; + for (iter = ctrl_rects.begin(); iter != ctrl_rects.end(); ++iter) { + ready->push_back(PaintManager::ReadyRect(*iter, *image_data, false)); + } + } +} + +void Instance::DidOpen(int32_t result) { + if (result == PP_OK) { + engine_->HandleDocumentLoad(embed_loader_); + } else if (result != PP_ERROR_ABORTED) { // Can happen in tests. + NOTREACHED(); + } +} + +void Instance::DidOpenPreview(int32_t result) { + if (result == PP_OK) { + preview_engine_.reset(PDFEngine::Create(new PreviewModeClient(this))); + preview_engine_->HandleDocumentLoad(embed_preview_loader_); + } else { + NOTREACHED(); + } +} + +void Instance::PaintIfWidgetIntersects( + pp::Widget_Dev* widget, + const pp::Rect& rect, + std::vector<PaintManager::ReadyRect>* ready, + std::vector<pp::Rect>* pending) { + if (!widget) + return; + + pp::Rect location; + if (!widget->GetLocation(&location)) + return; + + ScaleRect(device_scale_, &location); + location = location.Intersect(rect); + if (location.IsEmpty()) + return; + + if (IsOverlayScrollbar()) { + // If we're using overlay scrollbars, and there are pending paints under the + // scrollbar, don't update the scrollbar instantly. While it would be nice, + // we would need to double buffer the plugin area in order to make this + // work. This is because we'd need to always have a copy of what the pdf + // under the scrollbar looks like, and additionally we couldn't paint the + // pdf under the scrollbar if it's ready until we got the preceding flush. + // So in practice, it would make painting slower and introduce extra buffer + // copies for the general case. + for (size_t i = 0; i < pending->size(); ++i) { + if ((*pending)[i].Intersects(location)) + return; + } + + // Even if none of the pending paints are under the scrollbar, we never want + // to paint it if it's over the pdf if there are other pending paints. + // Otherwise different parts of the pdf plugin would display at different + // scroll offsets. + if (!pending->empty() && available_area_.Intersects(rect)) { + pending->push_back(location); + return; + } + } + + pp::Rect location_dip = location; + ScaleRect(1.0f / device_scale_, &location_dip); + + DCHECK(!image_data_.is_null()); + widget->Paint(location_dip, &image_data_); + + ready->push_back(PaintManager::ReadyRect(location, image_data_, true)); +} + +void Instance::OnTimerFired(int32_t) { + HandleInputEvent(last_mouse_event_); +} + +void Instance::OnClientTimerFired(int32_t id) { + engine_->OnCallback(id); +} + +void Instance::OnControlTimerFired(int32_t, + const uint32& control_id, + const uint32& timer_id) { + if (control_id == toolbar_->id()) { + toolbar_->OnTimerFired(timer_id); + } else if (control_id == progress_bar_.id()) { + if (timer_id == delayed_progress_timer_id_) { + if (document_load_state_ == LOAD_STATE_LOADING && + !progress_bar_.visible()) { + progress_bar_.Fade(true, kProgressFadeTimeoutMs); + } + delayed_progress_timer_id_ = 0; + } else { + progress_bar_.OnTimerFired(timer_id); + } + } else if (control_id == kAutoScrollId) { + if (is_autoscroll_) { + if (autoscroll_x_ != 0 && h_scrollbar_.get()) { + h_scrollbar_->ScrollBy(PP_SCROLLBY_PIXEL, autoscroll_x_); + } + if (autoscroll_y_ != 0 && v_scrollbar_.get()) { + v_scrollbar_->ScrollBy(PP_SCROLLBY_PIXEL, autoscroll_y_); + } + + // Reschedule timer. + ScheduleTimer(kAutoScrollId, kAutoScrollTimeoutMs); + } + } else if (control_id == kPageIndicatorId) { + page_indicator_.OnTimerFired(timer_id); + } +#ifdef ENABLE_THUMBNAILS + else if (control_id == thumbnails_.id()) { + thumbnails_.OnTimerFired(timer_id); + } +#endif +} + +void Instance::CalculateBackgroundParts() { + background_parts_.clear(); + int v_scrollbar_thickness = + GetScaled(v_scrollbar_.get() ? GetScrollbarReservedThickness() : 0); + int h_scrollbar_thickness = + GetScaled(h_scrollbar_.get() ? GetScrollbarReservedThickness() : 0); + int width_without_scrollbar = std::max( + plugin_size_.width() - v_scrollbar_thickness, 0); + int height_without_scrollbar = std::max( + plugin_size_.height() - h_scrollbar_thickness, 0); + int left_width = available_area_.x(); + int right_start = available_area_.right(); + int right_width = abs(width_without_scrollbar - available_area_.right()); + int bottom = std::min(available_area_.bottom(), height_without_scrollbar); + + // Add the left, right, and bottom rectangles. Note: we assume only + // horizontal centering. + BackgroundPart part = { + pp::Rect(0, 0, left_width, bottom), + kBackgroundColor + }; + 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, width_without_scrollbar, height_without_scrollbar - bottom); + if (!part.location.IsEmpty()) + background_parts_.push_back(part); + + if (h_scrollbar_thickness +#if defined(OS_MACOSX) + || +#else + && +#endif + v_scrollbar_thickness) { + part.color = 0xFFFFFFFF; + part.location = pp::Rect(plugin_size_.width() - v_scrollbar_thickness, + plugin_size_.height() - h_scrollbar_thickness, + h_scrollbar_thickness, + v_scrollbar_thickness); + background_parts_.push_back(part); + } +} + +int Instance::GetDocumentPixelWidth() const { + return static_cast<int>(ceil(document_size_.width() * zoom_ * device_scale_)); +} + +int Instance::GetDocumentPixelHeight() const { + return static_cast<int>(ceil(document_size_.height() * + zoom_ * + device_scale_)); +} + +void Instance::FillRect(const pp::Rect& rect, uint32 color) { + DCHECK(!image_data_.is_null() || rect.IsEmpty()); + uint32* buffer_start = static_cast<uint32*>(image_data_.data()); + int stride = image_data_.stride(); + uint32* 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 Instance::DocumentSizeUpdated(const pp::Size& size) { + document_size_ = size; + + OnGeometryChanged(zoom_, device_scale_); +} + +void Instance::Invalidate(const pp::Rect& rect) { + pp::Rect offset_rect(rect); + offset_rect.Offset(available_area_.point()); + paint_manager_.InvalidateRect(offset_rect); +} + +void Instance::Scroll(const pp::Point& point) { + pp::Rect scroll_area = available_area_; + if (IsOverlayScrollbar()) { + pp::Rect rc; + if (h_scrollbar_.get()) { + h_scrollbar_->GetLocation(&rc); + ScaleRect(device_scale_, &rc); + if (scroll_area.bottom() > rc.y()) { + scroll_area.set_height(rc.y() - scroll_area.y()); + paint_manager_.InvalidateRect(rc); + } + } + if (v_scrollbar_.get()) { + v_scrollbar_->GetLocation(&rc); + ScaleRect(device_scale_, &rc); + if (scroll_area.right() > rc.x()) { + scroll_area.set_width(rc.x() - scroll_area.x()); + paint_manager_.InvalidateRect(rc); + } + } + } + paint_manager_.ScrollRect(scroll_area, point); + + if (toolbar_->current_transparency() != kTransparentAlpha) + paint_manager_.InvalidateRect(toolbar_->GetControlsRect()); + + if (progress_bar_.visible()) + paint_manager_.InvalidateRect(progress_bar_.rect()); + + if (is_autoscroll_) + paint_manager_.InvalidateRect(autoscroll_rect_); + + if (show_page_indicator_) { + page_indicator_.set_current_page(GetPageNumberToDisplay()); + page_indicator_.Splash(); + } + + if (page_indicator_.visible()) + paint_manager_.InvalidateRect(page_indicator_.rect()); + + // Run the scroll callback asynchronously. This function can be invoked by a + // layout change which should not re-enter into JS synchronously. + pp::CompletionCallback callback = + callback_factory_.NewCallback(&Instance::RunCallback, + on_scroll_callback_); + pp::Module::Get()->core()->CallOnMainThread(0, callback); +} + +void Instance::ScrollToX(int position) { + if (!h_scrollbar_.get()) { + NOTREACHED(); + return; + } + int position_dip = static_cast<int>(position / device_scale_); + h_scrollbar_->SetValue(position_dip); +} + +void Instance::ScrollToY(int position) { + if (!v_scrollbar_.get()) { + NOTREACHED(); + return; + } + int position_dip = static_cast<int>(position / device_scale_); + v_scrollbar_->SetValue(ClipToRange(position_dip, 0, valid_v_range_)); +} + +void Instance::ScrollToPage(int page) { + if (!v_scrollbar_.get()) + return; + + if (engine_->GetNumberOfPages() == 0) + return; + + int index = ClipToRange(page, 0, engine_->GetNumberOfPages() - 1); + pp::Rect rect = engine_->GetPageRect(index); + // If we are trying to scroll pass the last page, + // scroll to the end of the last page. + int position = index < page ? rect.bottom() : rect.y(); + ScrollToY(position * zoom_ * device_scale_); +} + +void Instance::NavigateTo(const std::string& url, bool open_in_new_tab) { + std::string url_copy(url); + + // Empty |url_copy| is ok, and will effectively be a reload. + // Skip the code below so an empty URL does not turn into "http://", which + // will cause GURL to fail a DCHECK. + if (!url_copy.empty()) { + // If |url_copy| starts with '#', then it's for the same URL with a + // different URL fragment. + if (url_copy[0] == '#') { + url_copy = url_ + url_copy; + // Changing the href does not actually do anything when navigating in the + // same tab, so do the actual page scroll here. Then fall through so the + // href gets updated. + if (!open_in_new_tab) { + int page_number = GetInitialPage(url_copy); + if (page_number >= 0) + ScrollToPage(page_number); + } + } + // If there's no scheme, add http. + if (url_copy.find("://") == std::string::npos && + url_copy.find("mailto:") == std::string::npos) { + url_copy = "http://" + url_copy; + } + // Make sure |url_copy| starts with a valid scheme. + if (url_copy.find("http://") != 0 && + url_copy.find("https://") != 0 && + url_copy.find("ftp://") != 0 && + url_copy.find("file://") != 0 && + url_copy.find("mailto:") != 0) { + return; + } + // Make sure |url_copy| is not only a scheme. + if (url_copy == "http://" || + url_copy == "https://" || + url_copy == "ftp://" || + url_copy == "file://" || + url_copy == "mailto:") { + return; + } + } + if (open_in_new_tab) { + GetWindowObject().Call("open", url_copy); + } else { + GetWindowObject().GetProperty("top").GetProperty("location"). + SetProperty("href", url_copy); + } +} + +void Instance::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(), NULL); +} + +void Instance::UpdateTickMarks(const std::vector<pp::Rect>& tickmarks) { + if (!v_scrollbar_.get()) + return; + + float inverse_scale = 1.0f / device_scale_; + std::vector<pp::Rect> scaled_tickmarks = tickmarks; + for (size_t i = 0; i < scaled_tickmarks.size(); i++) { + ScaleRect(inverse_scale, &scaled_tickmarks[i]); + } + + v_scrollbar_->SetTickMarks( + scaled_tickmarks.empty() ? NULL : &scaled_tickmarks[0], tickmarks.size()); +} + +void Instance::NotifyNumberOfFindResultsChanged(int total, bool final_result) { + NumberOfFindResultsChanged(total, final_result); +} + +void Instance::NotifySelectedFindResultChanged(int current_find_index) { + SelectedFindResultChanged(current_find_index); +} + +void Instance::OnEvent(uint32 control_id, uint32 event_id, void* data) { + if (event_id == Button::EVENT_ID_BUTTON_CLICKED || + event_id == Button::EVENT_ID_BUTTON_STATE_CHANGED) { + switch (control_id) { + case kFitToPageButtonId: + UserMetricsRecordAction("PDF.FitToPageButton"); + SetZoom(ZOOM_FIT_TO_PAGE, 0); + ZoomChanged(zoom_); + break; + case kFitToWidthButtonId: + UserMetricsRecordAction("PDF.FitToWidthButton"); + SetZoom(ZOOM_FIT_TO_WIDTH, 0); + ZoomChanged(zoom_); + break; + case kZoomOutButtonId: + case kZoomInButtonId: + UserMetricsRecordAction(control_id == kZoomOutButtonId ? + "PDF.ZoomOutButton" : "PDF.ZoomInButton"); + SetZoom(ZOOM_SCALE, CalculateZoom(control_id)); + ZoomChanged(zoom_); + break; + case kSaveButtonId: + UserMetricsRecordAction("PDF.SaveButton"); + SaveAs(); + break; + case kPrintButtonId: + UserMetricsRecordAction("PDF.PrintButton"); + Print(); + break; + } + } + if (control_id == kThumbnailsId && + event_id == ThumbnailControl::EVENT_ID_THUMBNAIL_SELECTED) { + int page = *static_cast<int*>(data); + pp::Rect page_rc(engine_->GetPageRect(page)); + ScrollToY(static_cast<int>(page_rc.y() * zoom_ * device_scale_)); + } +} + +void Instance::Invalidate(uint32 control_id, const pp::Rect& rc) { + paint_manager_.InvalidateRect(rc); +} + +uint32 Instance::ScheduleTimer(uint32 control_id, uint32 timeout_ms) { + current_timer_id_++; + pp::CompletionCallback callback = + timer_factory_.NewCallback(&Instance::OnControlTimerFired, + control_id, + current_timer_id_); + pp::Module::Get()->core()->CallOnMainThread(timeout_ms, callback); + return current_timer_id_; +} + +void Instance::SetEventCapture(uint32 control_id, bool set_capture) { + // TODO(gene): set event capture here. +} + +void Instance::SetCursor(uint32 control_id, PP_CursorType_Dev cursor_type) { + UpdateCursor(cursor_type); +} + +pp::Instance* Instance::GetInstance() { + return this; +} + +void Instance::GetDocumentPassword( + pp::CompletionCallbackWithOutput<pp::Var> callback) { + std::string message(GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD)); + pp::Var result = pp::PDF::ModalPromptForPassword(this, message); + *callback.output() = result.pp_var(); + callback.Run(PP_OK); +} + +void Instance::Alert(const std::string& message) { + GetWindowObject().Call("alert", message); +} + +bool Instance::Confirm(const std::string& message) { + pp::Var result = GetWindowObject().Call("confirm", message); + return result.is_bool() ? result.AsBool() : false; +} + +std::string Instance::Prompt(const std::string& question, + const std::string& default_answer) { + pp::Var result = GetWindowObject().Call("prompt", question, default_answer); + return result.is_string() ? result.AsString() : std::string(); +} + +std::string Instance::GetURL() { + return url_; +} + +void Instance::Email(const std::string& to, + const std::string& cc, + const std::string& bcc, + const std::string& subject, + const std::string& body) { + std::string javascript = + "var href = 'mailto:" + net::EscapeUrlEncodedData(to, false) + + "?cc=" + net::EscapeUrlEncodedData(cc, false) + + "&bcc=" + net::EscapeUrlEncodedData(bcc, false) + + "&subject=" + net::EscapeUrlEncodedData(subject, false) + + "&body=" + net::EscapeUrlEncodedData(body, false) + + "';var temp = window.open(href, '_blank', " + + "'width=1,height=1');if(temp) temp.close();"; + ExecuteScript(javascript); +} + +void Instance::Print() { + if (!printing_enabled_ || + (!engine_->HasPermission(PDFEngine::PERMISSION_PRINT_LOW_QUALITY) && + !engine_->HasPermission(PDFEngine::PERMISSION_PRINT_HIGH_QUALITY))) { + return; + } + + pp::CompletionCallback callback = + callback_factory_.NewCallback(&Instance::OnPrint); + pp::Module::Get()->core()->CallOnMainThread(0, callback); +} + +void Instance::OnPrint(int32_t) { + pp::PDF::Print(this); +} + +void Instance::SaveAs() { + pp::PDF::SaveAs(this); +} + +void Instance::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(&Instance::FormDidOpen); + form_loader_ = CreateURLLoaderInternal(); + int rv = form_loader_.Open(request, callback); + if (rv != PP_OK_COMPLETIONPENDING) + callback.Run(rv); +} + +void Instance::FormDidOpen(int32_t result) { + // TODO: inform the user of success/failure. + if (result != PP_OK) { + NOTREACHED(); + } +} + +std::string Instance::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 Instance::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 Instance::ScheduleCallback(int id, int delay_in_ms) { + pp::CompletionCallback callback = + timer_factory_.NewCallback(&Instance::OnClientTimerFired); + pp::Module::Get()->core()->CallOnMainThread(delay_in_ms, callback, id); +} + +void Instance::SearchString(const base::char16* string, + const base::char16* term, + bool case_sensitive, + std::vector<SearchStringResult>* results) { + if (!pp::PDF::IsAvailable()) { + NOTREACHED(); + return; + } + + 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 Instance::DocumentPaintOccurred() { + if (painted_first_page_) + return; + + painted_first_page_ = true; + UpdateToolbarPosition(false); + toolbar_->Splash(kToolbarSplashTimeoutMs); + + if (engine_->GetNumberOfPages() > 1) + show_page_indicator_ = true; + else + show_page_indicator_ = false; + + if (v_scrollbar_.get() && show_page_indicator_) { + page_indicator_.set_current_page(GetPageNumberToDisplay()); + page_indicator_.Splash(kToolbarSplashTimeoutMs, + kPageIndicatorInitialFadeTimeoutMs); + } +} + +void Instance::DocumentLoadComplete(int page_count) { + // Clear focus state for OSK. + FormTextFieldFocusChange(false); + + // Update progress control. + if (progress_bar_.visible()) + progress_bar_.Fade(false, kProgressFadeTimeoutMs); + + DCHECK(document_load_state_ == LOAD_STATE_LOADING); + document_load_state_ = LOAD_STATE_COMPLETE; + UserMetricsRecordAction("PDF.LoadSuccess"); + + if (did_call_start_loading_) { + pp::PDF::DidStopLoading(this); + did_call_start_loading_ = false; + } + + if (on_load_callback_.is_string()) + ExecuteScript(on_load_callback_); + // Note: If we are in print preview mode on_load_callback_ might call + // ScrollTo{X|Y}() and we don't want to scroll again and override it. + // #page=N is not supported in Print Preview. + if (!IsPrintPreview()) { + int initial_page = GetInitialPage(url_); + if (initial_page >= 0) + ScrollToPage(initial_page); + } + + if (!full_) + return; + if (!pp::PDF::IsAvailable()) + return; + + 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)) { + printing_enabled_ = false; + if (current_tb_info_ == kPDFToolbarButtons) { + // Remove Print button. + CreateToolbar(kPDFNoPrintToolbarButtons, + arraysize(kPDFNoPrintToolbarButtons)); + UpdateToolbarPosition(false); + Invalidate(pp::Rect(plugin_size_)); + } + } + + pp::PDF::SetContentRestriction(this, content_restrictions); + + pp::PDF::HistogramPDFPageCount(this, page_count); +} + +void Instance::RotateClockwise() { + engine_->RotateClockwise(); +} + +void Instance::RotateCounterclockwise() { + engine_->RotateCounterclockwise(); +} + +void Instance::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_.size()) + LoadAvailablePreviewPage(); +} + +void Instance::DocumentLoadFailed() { + DCHECK(document_load_state_ == LOAD_STATE_LOADING); + UserMetricsRecordAction("PDF.LoadFailure"); + + // Hide progress control. + progress_bar_.Fade(false, kProgressFadeTimeoutMs); + + 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_)); +} + +void Instance::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_.size()) + LoadAvailablePreviewPage(); +} + +pp::Instance* Instance::GetPluginInstance() { + return GetInstance(); +} + +void Instance::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 Instance::DocumentLoadProgress(uint32 available, uint32 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; + } + progress_bar_.SetProgress(progress); +} + +void Instance::FormTextFieldFocusChange(bool in_focus) { + if (!text_input_.get()) + return; + if (in_focus) + text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_TEXT); + else + text_input_->SetTextInputType(PP_TEXTINPUT_TYPE_DEV_NONE); +} + +// Called by PDFScriptableObject. +bool Instance::HasScriptableMethod(const pp::Var& method, pp::Var* exception) { + std::string method_str = method.AsString(); + return (method_str == kJSAccessibility || + method_str == kJSDocumentLoadComplete || + method_str == kJSGetHeight || + method_str == kJSGetHorizontalScrollbarThickness || + method_str == kJSGetPageLocationNormalized || + method_str == kJSGetSelectedText || + method_str == kJSGetVerticalScrollbarThickness || + method_str == kJSGetWidth || + method_str == kJSGetZoomLevel || + method_str == kJSGoToPage || + method_str == kJSGrayscale || + method_str == kJSLoadPreviewPage || + method_str == kJSOnLoad || + method_str == kJSOnPluginSizeChanged || + method_str == kJSOnScroll || + method_str == kJSPageXOffset || + method_str == kJSPageYOffset || + method_str == kJSPrintPreviewPageCount || + method_str == kJSReload || + method_str == kJSRemovePrintButton || + method_str == kJSResetPrintPreviewUrl || + method_str == kJSSendKeyEvent || + method_str == kJSSetPageNumbers || + method_str == kJSSetPageXOffset || + method_str == kJSSetPageYOffset || + method_str == kJSSetZoomLevel || + method_str == kJSZoomFitToHeight || + method_str == kJSZoomFitToWidth || + method_str == kJSZoomIn || + method_str == kJSZoomOut); +} + +pp::Var Instance::CallScriptableMethod(const pp::Var& method, + const std::vector<pp::Var>& args, + pp::Var* exception) { + std::string method_str = method.AsString(); + if (method_str == kJSGrayscale) { + if (args.size() == 1 && args[0].is_bool()) { + engine_->SetGrayscale(args[0].AsBool()); + // Redraw + paint_manager_.InvalidateRect(pp::Rect(pp::Point(), plugin_size_)); +#ifdef ENABLE_THUMBNAILS + if (thumbnails_.visible()) + thumbnails_.Show(true, true); +#endif + return pp::Var(true); + } + return pp::Var(false); + } + if (method_str == kJSOnLoad) { + if (args.size() == 1 && args[0].is_string()) { + on_load_callback_ = args[0]; + return pp::Var(true); + } + return pp::Var(false); + } + if (method_str == kJSOnScroll) { + if (args.size() == 1 && args[0].is_string()) { + on_scroll_callback_ = args[0]; + return pp::Var(true); + } + return pp::Var(false); + } + if (method_str == kJSOnPluginSizeChanged) { + if (args.size() == 1 && args[0].is_string()) { + on_plugin_size_changed_callback_ = args[0]; + return pp::Var(true); + } + return pp::Var(false); + } + if (method_str == kJSReload) { + document_load_state_ = LOAD_STATE_LOADING; + if (!full_) + LoadUrl(url_); + preview_engine_.reset(); + print_preview_page_count_ = 0; + engine_.reset(PDFEngine::Create(this)); + engine_->New(url_.c_str()); +#ifdef ENABLE_THUMBNAILS + thumbnails_.ResetEngine(engine_.get()); +#endif + return pp::Var(); + } + if (method_str == kJSResetPrintPreviewUrl) { + if (args.size() == 1 && args[0].is_string()) { + url_ = args[0].AsString(); + preview_pages_info_ = std::queue<PreviewPageInfo>(); + preview_document_load_state_ = LOAD_STATE_COMPLETE; + } + return pp::Var(); + } + if (method_str == kJSZoomFitToHeight) { + SetZoom(ZOOM_FIT_TO_PAGE, 0); + return pp::Var(); + } + if (method_str == kJSZoomFitToWidth) { + SetZoom(ZOOM_FIT_TO_WIDTH, 0); + return pp::Var(); + } + if (method_str == kJSZoomIn) { + SetZoom(ZOOM_SCALE, CalculateZoom(kZoomInButtonId)); + return pp::Var(); + } + if (method_str == kJSZoomOut) { + SetZoom(ZOOM_SCALE, CalculateZoom(kZoomOutButtonId)); + return pp::Var(); + } + if (method_str == kJSSetZoomLevel) { + if (args.size() == 1 && args[0].is_number()) + SetZoom(ZOOM_SCALE, args[0].AsDouble()); + return pp::Var(); + } + if (method_str == kJSGetZoomLevel) { + return pp::Var(zoom_); + } + if (method_str == kJSGetHeight) { + return pp::Var(plugin_size_.height()); + } + if (method_str == kJSGetWidth) { + return pp::Var(plugin_size_.width()); + } + if (method_str == kJSGetHorizontalScrollbarThickness) { + return pp::Var( + h_scrollbar_.get() ? GetScrollbarReservedThickness() : 0); + } + if (method_str == kJSGetVerticalScrollbarThickness) { + return pp::Var( + v_scrollbar_.get() ? GetScrollbarReservedThickness() : 0); + } + if (method_str == kJSGetSelectedText) { + return GetSelectedText(false); + } + if (method_str == kJSDocumentLoadComplete) { + return pp::Var((document_load_state_ != LOAD_STATE_LOADING)); + } + if (method_str == kJSPageYOffset) { + return pp::Var(static_cast<int32_t>( + v_scrollbar_.get() ? v_scrollbar_->GetValue() : 0)); + } + if (method_str == kJSSetPageYOffset) { + if (args.size() == 1 && args[0].is_number() && v_scrollbar_.get()) + ScrollToY(GetScaled(args[0].AsInt())); + return pp::Var(); + } + if (method_str == kJSPageXOffset) { + return pp::Var(static_cast<int32_t>( + h_scrollbar_.get() ? h_scrollbar_->GetValue() : 0)); + } + if (method_str == kJSSetPageXOffset) { + if (args.size() == 1 && args[0].is_number() && h_scrollbar_.get()) + ScrollToX(GetScaled(args[0].AsInt())); + return pp::Var(); + } + if (method_str == kJSRemovePrintButton) { + CreateToolbar(kPrintPreviewToolbarButtons, + arraysize(kPrintPreviewToolbarButtons)); + UpdateToolbarPosition(false); + Invalidate(pp::Rect(plugin_size_)); + return pp::Var(); + } + if (method_str == kJSGoToPage) { + if (args.size() == 1 && args[0].is_string()) { + ScrollToPage(atoi(args[0].AsString().c_str())); + } + return pp::Var(); + } + if (method_str == kJSAccessibility) { + if (args.size() == 0) { + 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); + return pp::Var(json); + } else if (args[0].is_number()) { + return pp::Var(engine_->GetPageAsJSON(args[0].AsInt())); + } + } + if (method_str == kJSPrintPreviewPageCount) { + if (args.size() == 1 && args[0].is_number()) + SetPrintPreviewMode(args[0].AsInt()); + return pp::Var(); + } + if (method_str == kJSLoadPreviewPage) { + if (args.size() == 2 && args[0].is_string() && args[1].is_number()) + ProcessPreviewPageInfo(args[0].AsString(), args[1].AsInt()); + return pp::Var(); + } + if (method_str == kJSGetPageLocationNormalized) { + const size_t kMaxLength = 30; + char location_info[kMaxLength]; + int page_idx = engine_->GetMostVisiblePage(); + if (page_idx < 0) + return pp::Var(std::string()); + pp::Rect rect = engine_->GetPageContentsRect(page_idx); + int v_scrollbar_reserved_thickness = + v_scrollbar_.get() ? GetScaled(GetScrollbarReservedThickness()) : 0; + + rect.set_x(rect.x() + ((plugin_size_.width() - + v_scrollbar_reserved_thickness - available_area_.width()) / 2)); + base::snprintf(location_info, + kMaxLength, + "%0.4f;%0.4f;%0.4f;%0.4f;", + rect.x() / static_cast<float>(plugin_size_.width()), + rect.y() / static_cast<float>(plugin_size_.height()), + rect.width() / static_cast<float>(plugin_size_.width()), + rect.height()/ static_cast<float>(plugin_size_.height())); + return pp::Var(std::string(location_info)); + } + if (method_str == kJSSetPageNumbers) { + if (args.size() != 1 || !args[0].is_string()) + return pp::Var(); + const int num_pages_signed = engine_->GetNumberOfPages(); + if (num_pages_signed <= 0) + return pp::Var(); + scoped_ptr<base::ListValue> page_ranges(static_cast<base::ListValue*>( + base::JSONReader::Read(args[0].AsString(), false))); + const size_t num_pages = static_cast<size_t>(num_pages_signed); + if (!page_ranges.get() || page_ranges->GetSize() != num_pages) + return pp::Var(); + + std::vector<int> print_preview_page_numbers; + for (size_t index = 0; index < num_pages; ++index) { + int page_number = 0; // |page_number| is 1-based. + if (!page_ranges->GetInteger(index, &page_number) || page_number < 1) + return pp::Var(); + print_preview_page_numbers.push_back(page_number); + } + print_preview_page_numbers_ = print_preview_page_numbers; + page_indicator_.set_current_page(GetPageNumberToDisplay()); + return pp::Var(); + } + // This is here to work around https://bugs.webkit.org/show_bug.cgi?id=16735. + // In JS, creating a synthetic keyboard event and dispatching it always + // result in a keycode of 0. + if (method_str == kJSSendKeyEvent) { + if (args.size() == 1 && args[0].is_number()) { + pp::KeyboardInputEvent event( + this, // instance + PP_INPUTEVENT_TYPE_KEYDOWN, // HandleInputEvent only care about this. + 0, // timestamp, not used for kbd events. + 0, // no modifiers. + args[0].AsInt(), // keycode. + pp::Var()); // no char text needed. + HandleInputEvent(event); + } + } + return pp::Var(); +} + +void Instance::OnGeometryChanged(double old_zoom, float old_device_scale) { + bool force_no_horizontal_scrollbar = false; + int scrollbar_thickness = GetScrollbarThickness(); + + if (old_device_scale != device_scale_) { + // Change in device scale forces us to recreate resources + ConfigureNumberImageGenerator(); + + CreateToolbar(current_tb_info_, current_tb_info_size_); + // Load autoscroll anchor image. + autoscroll_anchor_ = + CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAN_SCROLL_ICON); + + ConfigurePageIndicator(); + ConfigureProgressBar(); + + pp::Point scroll_position = engine_->GetScrollPosition(); + ScalePoint(device_scale_ / old_device_scale, &scroll_position); + engine_->SetScrollPosition(scroll_position); + } + + UpdateZoomScale(); + if (zoom_ != old_zoom || device_scale_ != old_device_scale) + engine_->ZoomUpdated(zoom_ * device_scale_); + if (zoom_ != old_zoom) + ZoomChanged(zoom_); + + available_area_ = pp::Rect(plugin_size_); + if (GetDocumentPixelHeight() > plugin_size_.height()) { + CreateVerticalScrollbar(); + } else { + DestroyVerticalScrollbar(); + } + + int v_scrollbar_reserved_thickness = + v_scrollbar_.get() ? GetScaled(GetScrollbarReservedThickness()) : 0; + + if (!force_no_horizontal_scrollbar && + GetDocumentPixelWidth() > + (plugin_size_.width() - v_scrollbar_reserved_thickness)) { + CreateHorizontalScrollbar(); + + // Adding the horizontal scrollbar now might cause us to need vertical + // scrollbars. + if (GetDocumentPixelHeight() > + plugin_size_.height() - GetScaled(GetScrollbarReservedThickness())) { + CreateVerticalScrollbar(); + } + + } else { + DestroyHorizontalScrollbar(); + } + +#ifdef ENABLE_THUMBNAILS + int thumbnails_pos = 0, thumbnails_total = 0; +#endif + if (v_scrollbar_.get()) { + v_scrollbar_->SetScale(device_scale_); + available_area_.set_width( + std::max(0, plugin_size_.width() - v_scrollbar_reserved_thickness)); + +#ifdef ENABLE_THUMBNAILS + int height = plugin_size_.height(); +#endif + int height_dip = plugin_dip_size_.height(); + +#if defined(OS_MACOSX) + // Before Lion, Mac always had the resize at the bottom. After that, it + // never did. + if ((base::mac::IsOSSnowLeopard() && full_) || + (base::mac::IsOSLionOrLater() && h_scrollbar_.get())) { +#else + if (h_scrollbar_.get()) { +#endif // defined(OS_MACOSX) +#ifdef ENABLE_THUMBNAILS + height -= GetScaled(GetScrollbarThickness()); +#endif + height_dip -= GetScrollbarThickness(); + } +#ifdef ENABLE_THUMBNAILS + int32 doc_height = GetDocumentPixelHeight(); +#endif + int32 doc_height_dip = + static_cast<int32>(GetDocumentPixelHeight() / device_scale_); +#if defined(OS_MACOSX) + // On the Mac we always allow room for the resize button (whose width is + // the same as that of the scrollbar) in full mode. However, if there is no + // no horizontal scrollbar, the end of the scrollbar will scroll past the + // end of the document. This is because the scrollbar assumes that its own + // height (in the case of a vscroll bar) is the same as the height of the + // viewport. Since the viewport is actually larger, we compensate by + // adjusting the document height. Similar logic applies below for the + // horizontal scrollbar. + // For example, if the document size is 1000, and the viewport size is 200, + // then the scrollbar position at the end will be 800. In this case the + // viewport is actally 215 (assuming 15 as the scrollbar width) but the + // scrollbar thinks it is 200. We want the scrollbar position at the end to + // be 785. Making the document size 985 achieves this. + if (full_ && !h_scrollbar_.get()) { +#ifdef ENABLE_THUMBNAILS + doc_height -= GetScaled(GetScrollbarThickness()); +#endif + doc_height_dip -= GetScrollbarThickness(); + } +#endif // defined(OS_MACOSX) + + int32 position; + position = v_scrollbar_->GetValue(); + position = static_cast<int>(position * zoom_ / old_zoom); + valid_v_range_ = doc_height_dip - height_dip; + if (position > valid_v_range_) + position = valid_v_range_; + + v_scrollbar_->SetValue(position); + + PP_Rect loc; + loc.point.x = static_cast<int>(available_area_.right() / device_scale_); + if (IsOverlayScrollbar()) + loc.point.x -= scrollbar_thickness; + loc.point.y = 0; + loc.size.width = scrollbar_thickness; + loc.size.height = height_dip; + v_scrollbar_->SetLocation(loc); + v_scrollbar_->SetDocumentSize(doc_height_dip); + +#ifdef ENABLE_THUMBNAILS + thumbnails_pos = position; + thumbnails_total = doc_height - height; +#endif + } + + if (h_scrollbar_.get()) { + h_scrollbar_->SetScale(device_scale_); + available_area_.set_height( + std::max(0, plugin_size_.height() - + GetScaled(GetScrollbarReservedThickness()))); + + int width_dip = plugin_dip_size_.width(); + + // See note above. +#if defined(OS_MACOSX) + if ((base::mac::IsOSSnowLeopard() && full_) || + (base::mac::IsOSLionOrLater() && v_scrollbar_.get())) { +#else + if (v_scrollbar_.get()) { +#endif + width_dip -= GetScrollbarThickness(); + } + int32 doc_width_dip = + static_cast<int32>(GetDocumentPixelWidth() / device_scale_); +#if defined(OS_MACOSX) + // See comment in the above if (v_scrollbar_.get()) block. + if (full_ && !v_scrollbar_.get()) + doc_width_dip -= GetScrollbarThickness(); +#endif // defined(OS_MACOSX) + + int32 position; + position = h_scrollbar_->GetValue(); + position = static_cast<int>(position * zoom_ / old_zoom); + position = std::min(position, doc_width_dip - width_dip); + + h_scrollbar_->SetValue(position); + + PP_Rect loc; + loc.point.x = 0; + loc.point.y = static_cast<int>(available_area_.bottom() / device_scale_); + if (IsOverlayScrollbar()) + loc.point.y -= scrollbar_thickness; + loc.size.width = width_dip; + loc.size.height = scrollbar_thickness; + h_scrollbar_->SetLocation(loc); + h_scrollbar_->SetDocumentSize(doc_width_dip); + } + + 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 doc_height = GetDocumentPixelHeight(); + if (doc_height < available_area_.height()) { + available_area_.set_height(doc_height); + } + + // We'll invalidate the entire plugin anyways. + UpdateToolbarPosition(false); + UpdateProgressBarPosition(false); + UpdatePageIndicatorPosition(false); + +#ifdef ENABLE_THUMBNAILS + // Update thumbnail control position. + thumbnails_.SetPosition(thumbnails_pos, thumbnails_total, false); + pp::Rect thumbnails_rc(plugin_size_.width() - GetScaled(kThumbnailsWidth), 0, + GetScaled(kThumbnailsWidth), plugin_size_.height()); + if (v_scrollbar_.get()) + thumbnails_rc.Offset(-v_scrollbar_reserved_thickness, 0); + if (h_scrollbar_.get()) + thumbnails_rc.Inset(0, 0, 0, v_scrollbar_reserved_thickness); + thumbnails_.SetRect(thumbnails_rc, false); +#endif + + 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_)); + + // Run the plugin size change callback asynchronously. This function can be + // invoked by a layout change which should not re-enter into JS synchronously. + pp::CompletionCallback callback = + callback_factory_.NewCallback(&Instance::RunCallback, + on_plugin_size_changed_callback_); + pp::Module::Get()->core()->CallOnMainThread(0, callback); +} + +void Instance::RunCallback(int32_t, pp::Var callback) { + if (callback.is_string()) + ExecuteScript(callback); +} + +void Instance::CreateHorizontalScrollbar() { + if (h_scrollbar_.get()) + return; + + h_scrollbar_.reset(new pp::Scrollbar_Dev(this, false)); +} + +void Instance::CreateVerticalScrollbar() { + if (v_scrollbar_.get()) + return; + + v_scrollbar_.reset(new pp::Scrollbar_Dev(this, true)); +} + +void Instance::DestroyHorizontalScrollbar() { + if (!h_scrollbar_.get()) + return; + if (h_scrollbar_->GetValue()) + engine_->ScrolledToXPosition(0); + h_scrollbar_.reset(); +} + +void Instance::DestroyVerticalScrollbar() { + if (!v_scrollbar_.get()) + return; + if (v_scrollbar_->GetValue()) + engine_->ScrolledToYPosition(0); + v_scrollbar_.reset(); + page_indicator_.Show(false, true); +} + +int Instance::GetScrollbarThickness() { + if (scrollbar_thickness_ == -1) { + pp::Scrollbar_Dev temp_scrollbar(this, false); + scrollbar_thickness_ = temp_scrollbar.GetThickness(); + scrollbar_reserved_thickness_ = + temp_scrollbar.IsOverlay() ? 0 : scrollbar_thickness_; + } + + return scrollbar_thickness_; +} + +int Instance::GetScrollbarReservedThickness() { + GetScrollbarThickness(); + return scrollbar_reserved_thickness_; +} + +bool Instance::IsOverlayScrollbar() { + return GetScrollbarReservedThickness() == 0; +} + +void Instance::CreateToolbar(const ToolbarButtonInfo* tb_info, size_t size) { + toolbar_.reset(new FadingControls()); + + DCHECK(tb_info); + DCHECK(size >= 0); + + // Remember the current toolbar information in case we need to recreate the + // images later. + current_tb_info_ = tb_info; + current_tb_info_size_ = size; + + int max_height = 0; + pp::Point origin(kToolbarFadingOffsetLeft, kToolbarFadingOffsetTop); + ScalePoint(device_scale_, &origin); + + std::list<Button*> buttons; + for (size_t i = 0; i < size; i++) { + Button* btn = new Button; + pp::ImageData normal_face = + CreateResourceImage(tb_info[i].normal); + btn->CreateButton(tb_info[i].id, + origin, + true, + toolbar_.get(), + tb_info[i].style, + normal_face, + CreateResourceImage(tb_info[i].highlighted), + CreateResourceImage(tb_info[i].pressed)); + buttons.push_back(btn); + + origin += pp::Point(normal_face.size().width(), 0); + max_height = std::max(max_height, normal_face.size().height()); + } + + pp::Rect rc_toolbar(0, 0, + origin.x() + GetToolbarRightOffset(), + origin.y() + max_height + GetToolbarBottomOffset()); + toolbar_->CreateFadingControls( + kToolbarId, rc_toolbar, false, this, kTransparentAlpha); + + std::list<Button*>::iterator iter; + for (iter = buttons.begin(); iter != buttons.end(); ++iter) { + toolbar_->AddControl(*iter); + } +} + +int Instance::GetToolbarRightOffset() { + int scrollbar_thickness = GetScrollbarThickness(); + return GetScaled(kToolbarFadingOffsetRight) + 2 * scrollbar_thickness; +} + +int Instance::GetToolbarBottomOffset() { + int scrollbar_thickness = GetScrollbarThickness(); + return GetScaled(kToolbarFadingOffsetBottom) + scrollbar_thickness; +} + +std::vector<pp::ImageData> Instance::GetThumbnailResources() { + std::vector<pp::ImageData> num_images(10); + num_images[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0); + num_images[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1); + num_images[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2); + num_images[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3); + num_images[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4); + num_images[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5); + num_images[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6); + num_images[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7); + num_images[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8); + num_images[9] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9); + return num_images; +} + +std::vector<pp::ImageData> Instance::GetProgressBarResources( + pp::ImageData* background) { + std::vector<pp::ImageData> result(9); + result[0] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_0); + result[1] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_1); + result[2] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_2); + result[3] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_3); + result[4] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_4); + result[5] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_5); + result[6] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_6); + result[7] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_7); + result[8] = CreateResourceImage(PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_8); + *background = CreateResourceImage( + PP_RESOURCEIMAGE_PDF_PROGRESS_BAR_BACKGROUND); + return result; +} + +void Instance::CreatePageIndicator(bool always_visible) { + page_indicator_.CreatePageIndicator(kPageIndicatorId, false, this, + number_image_generator(), always_visible); + ConfigurePageIndicator(); +} + +void Instance::ConfigurePageIndicator() { + pp::ImageData background = + CreateResourceImage(PP_RESOURCEIMAGE_PDF_PAGE_INDICATOR_BACKGROUND); + page_indicator_.Configure(pp::Point(), background); +} + +void Instance::CreateProgressBar() { + pp::ImageData background; + std::vector<pp::ImageData> images = GetProgressBarResources(&background); + std::string text = GetLocalizedString(PP_RESOURCESTRING_PDFPROGRESSLOADING); + progress_bar_.CreateProgressControl(kProgressBarId, false, this, 0.0, + device_scale_, images, background, text); +} + +void Instance::ConfigureProgressBar() { + pp::ImageData background; + std::vector<pp::ImageData> images = GetProgressBarResources(&background); + progress_bar_.Reconfigure(background, images, device_scale_); +} + +void Instance::CreateThumbnails() { + thumbnails_.CreateThumbnailControl( + kThumbnailsId, pp::Rect(), false, this, engine_.get(), + number_image_generator()); +} + +void Instance::LoadUrl(const std::string& url) { + LoadUrlInternal(url, &embed_loader_, &Instance::DidOpen); +} + +void Instance::LoadPreviewUrl(const std::string& url) { + LoadUrlInternal(url, &embed_preview_loader_, &Instance::DidOpenPreview); +} + +void Instance::LoadUrlInternal(const std::string& url, pp::URLLoader* loader, + void (Instance::* 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 Instance::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; +} + +int Instance::GetInitialPage(const std::string& url) { + size_t found_idx = url.find('#'); + if (found_idx == std::string::npos) + return -1; + + const std::string& ref = url.substr(found_idx + 1); + std::vector<std::string> fragments; + Tokenize(ref, kDelimiters, &fragments); + + // Page number to return, zero-based. + int page = -1; + + // Handle the case of http://foo.com/bar#NAMEDDEST. This is not explicitly + // mentioned except by example in the Adobe "PDF Open Parameters" document. + if ((fragments.size() == 1) && (fragments[0].find('=') == std::string::npos)) + return engine_->GetNamedDestinationPage(fragments[0]); + + for (size_t i = 0; i < fragments.size(); ++i) { + std::vector<std::string> key_value; + base::SplitString(fragments[i], '=', &key_value); + if (key_value.size() != 2) + continue; + const std::string& key = key_value[0]; + const std::string& value = key_value[1]; + + if (base::strcasecmp(kPage, key.c_str()) == 0) { + // |page_value| is 1-based. + int page_value = -1; + if (base::StringToInt(value, &page_value) && page_value > 0) + page = page_value - 1; + continue; + } + if (base::strcasecmp(kNamedDest, key.c_str()) == 0) { + // |page_value| is 0-based. + int page_value = engine_->GetNamedDestinationPage(value); + if (page_value >= 0) + page = page_value; + continue; + } + } + return page; +} + +void Instance::UpdateToolbarPosition(bool invalidate) { + pp::Rect ctrl_rc = toolbar_->GetControlsRect(); + int min_toolbar_width = ctrl_rc.width() + GetToolbarRightOffset() + + GetScaled(kToolbarFadingOffsetLeft); + int min_toolbar_height = ctrl_rc.width() + GetToolbarBottomOffset() + + GetScaled(kToolbarFadingOffsetBottom); + + // Update toolbar position + if (plugin_size_.width() < min_toolbar_width || + plugin_size_.height() < min_toolbar_height) { + // Disable toolbar if it does not fit on the screen. + toolbar_->Show(false, invalidate); + } else { + pp::Point offset( + plugin_size_.width() - GetToolbarRightOffset() - ctrl_rc.right(), + plugin_size_.height() - GetToolbarBottomOffset() - ctrl_rc.bottom()); + toolbar_->MoveBy(offset, invalidate); + + int toolbar_width = std::max(plugin_size_.width() / 2, min_toolbar_width); + toolbar_->ExpandLeft(toolbar_width - toolbar_->rect().width()); + toolbar_->Show(painted_first_page_, invalidate); + } +} + +void Instance::UpdateProgressBarPosition(bool invalidate) { + // TODO(gene): verify we don't overlap with toolbar. + int scrollbar_thickness = GetScrollbarThickness(); + pp::Point progress_origin( + scrollbar_thickness + GetScaled(kProgressOffsetLeft), + plugin_size_.height() - progress_bar_.rect().height() - + scrollbar_thickness - GetScaled(kProgressOffsetBottom)); + progress_bar_.MoveTo(progress_origin, invalidate); +} + +void Instance::UpdatePageIndicatorPosition(bool invalidate) { + int32 doc_height = static_cast<int>(document_size_.height() * zoom_); + pp::Point origin( + plugin_size_.width() - page_indicator_.rect().width() - + GetScaled(GetScrollbarReservedThickness()), + page_indicator_.GetYPosition(engine_->GetVerticalScrollbarYPosition(), + doc_height, plugin_size_.height())); + page_indicator_.MoveTo(origin, invalidate); +} + +void Instance::SetZoom(ZoomMode zoom_mode, double scale) { + double old_zoom = zoom_; + + zoom_mode_ = zoom_mode; + if (zoom_mode_ == ZOOM_SCALE) + zoom_ = scale; + UpdateZoomScale(); + + engine_->ZoomUpdated(zoom_ * device_scale_); + OnGeometryChanged(old_zoom, device_scale_); + + // If fit-to-height, snap to the beginning of the most visible page. + if (zoom_mode_ == ZOOM_FIT_TO_PAGE) { + ScrollToPage(engine_->GetMostVisiblePage()); + } + + // Update sticky buttons to the current zoom style. + Button* ftp_btn = static_cast<Button*>( + toolbar_->GetControl(kFitToPageButtonId)); + Button* ftw_btn = static_cast<Button*>( + toolbar_->GetControl(kFitToWidthButtonId)); + switch (zoom_mode_) { + case ZOOM_FIT_TO_PAGE: + ftp_btn->SetPressedState(true); + ftw_btn->SetPressedState(false); + break; + case ZOOM_FIT_TO_WIDTH: + ftw_btn->SetPressedState(true); + ftp_btn->SetPressedState(false); + break; + default: + ftw_btn->SetPressedState(false); + ftp_btn->SetPressedState(false); + } +} + +void Instance::UpdateZoomScale() { + switch (zoom_mode_) { + case ZOOM_SCALE: + break; // Keep current scale. + case ZOOM_FIT_TO_PAGE: { + int page_num = engine_->GetFirstVisiblePage(); + if (page_num == -1) + break; + pp::Rect rc = engine_->GetPageRect(page_num); + if (!rc.height()) + break; + // Calculate fit to width zoom level. + double ftw_zoom = static_cast<double>(plugin_dip_size_.width() - + GetScrollbarReservedThickness()) / document_size_.width(); + // Calculate fit to height zoom level. If document will not fit + // horizontally, adjust zoom level to allow space for horizontal + // scrollbar. + double fth_zoom = + static_cast<double>(plugin_dip_size_.height()) / rc.height(); + if (fth_zoom * document_size_.width() > + plugin_dip_size_.width() - GetScrollbarReservedThickness()) + fth_zoom = static_cast<double>(plugin_dip_size_.height() + - GetScrollbarReservedThickness()) / rc.height(); + zoom_ = std::min(ftw_zoom, fth_zoom); + } break; + case ZOOM_FIT_TO_WIDTH: + case ZOOM_AUTO: + if (!document_size_.width()) + break; + zoom_ = static_cast<double>(plugin_dip_size_.width() - + GetScrollbarReservedThickness()) / document_size_.width(); + if (zoom_mode_ == ZOOM_AUTO && zoom_ > 1.0) + zoom_ = 1.0; + break; + } + zoom_ = ClipToRange(zoom_, kMinZoom, kMaxZoom); +} + +double Instance::CalculateZoom(uint32 control_id) const { + if (control_id == kZoomInButtonId) { + for (size_t i = 0; i < chrome_page_zoom::kPresetZoomFactorsSize; ++i) { + double current_zoom = chrome_page_zoom::kPresetZoomFactors[i]; + if (current_zoom - content::kEpsilon > zoom_) + return current_zoom; + } + } else { + for (size_t i = chrome_page_zoom::kPresetZoomFactorsSize; i > 0; --i) { + double current_zoom = chrome_page_zoom::kPresetZoomFactors[i - 1]; + if (current_zoom + content::kEpsilon < zoom_) + return current_zoom; + } + } + return zoom_; +} + +pp::ImageData Instance::CreateResourceImage(PP_ResourceImage image_id) { + pp::ImageData resource_data; + if (hidpi_enabled_) { + resource_data = + pp::PDF::GetResourceImageForScale(this, image_id, device_scale_); + } + + return resource_data.data() ? resource_data + : pp::PDF::GetResourceImage(this, image_id); +} + +std::string Instance::GetLocalizedString(PP_ResourceString id) { + pp::Var rv(pp::PDF::GetLocalizedString(this, id)); + if (!rv.is_string()) + return std::string(); + + return rv.AsString(); +} + +void Instance::DrawText(const pp::Point& top_center, PP_ResourceString id) { + std::string str(GetLocalizedString(id)); + + pp::FontDescription_Dev description; + description.set_family(PP_FONTFAMILY_SANSSERIF); + description.set_size(kMessageTextSize * device_scale_); + pp::Font_Dev font(this, description); + int length = font.MeasureSimpleText(str); + pp::Point point(top_center); + point.set_x(point.x() - length / 2); + DCHECK(!image_data_.is_null()); + font.DrawSimpleText(&image_data_, str, point, kMessageTextColor); +} + +void Instance::SetPrintPreviewMode(int page_count) { + if (!IsPrintPreview() || page_count <= 0) { + print_preview_page_count_ = 0; + return; + } + + print_preview_page_count_ = page_count; + ScrollToPage(0); + engine_->AppendBlankPages(print_preview_page_count_); + if (preview_pages_info_.size() > 0) + LoadAvailablePreviewPage(); +} + +bool Instance::IsPrintPreview() { + return IsPrintPreviewUrl(url_); +} + +int Instance::GetPageNumberToDisplay() { + int page = engine_->GetMostVisiblePage(); + if (IsPrintPreview() && !print_preview_page_numbers_.empty()) { + page = ClipToRange<int>(page, 0, print_preview_page_numbers_.size() - 1); + return print_preview_page_numbers_[page]; + } + return page + 1; +} + +void Instance::ProcessPreviewPageInfo(const std::string& url, + int dst_page_index) { + if (!IsPrintPreview() || print_preview_page_count_ < 0) + 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 Instance::LoadAvailablePreviewPage() { + if (preview_pages_info_.size() <= 0) + 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 Instance::EnableAutoscroll(const pp::Point& origin) { + if (is_autoscroll_) + return; + + pp::Size client_size = plugin_size_; + if (v_scrollbar_.get()) + client_size.Enlarge(-GetScrollbarThickness(), 0); + if (h_scrollbar_.get()) + client_size.Enlarge(0, -GetScrollbarThickness()); + + // Do not allow autoscroll if client area is too small. + if (autoscroll_anchor_.size().width() > client_size.width() || + autoscroll_anchor_.size().height() > client_size.height()) + return; + + autoscroll_rect_ = pp::Rect( + pp::Point(origin.x() - autoscroll_anchor_.size().width() / 2, + origin.y() - autoscroll_anchor_.size().height() / 2), + autoscroll_anchor_.size()); + + // Make sure autoscroll anchor is in the client area. + if (autoscroll_rect_.right() > client_size.width()) { + autoscroll_rect_.set_x( + client_size.width() - autoscroll_anchor_.size().width()); + } + if (autoscroll_rect_.bottom() > client_size.height()) { + autoscroll_rect_.set_y( + client_size.height() - autoscroll_anchor_.size().height()); + } + + if (autoscroll_rect_.x() < 0) + autoscroll_rect_.set_x(0); + if (autoscroll_rect_.y() < 0) + autoscroll_rect_.set_y(0); + + is_autoscroll_ = true; + Invalidate(kAutoScrollId, autoscroll_rect_); + + ScheduleTimer(kAutoScrollId, kAutoScrollTimeoutMs); +} + +void Instance::DisableAutoscroll() { + if (is_autoscroll_) { + is_autoscroll_ = false; + Invalidate(kAutoScrollId, autoscroll_rect_); + } +} + +PP_CursorType_Dev Instance::CalculateAutoscroll(const pp::Point& mouse_pos) { + // Scroll only if mouse pointer is outside of the anchor area. + if (autoscroll_rect_.Contains(mouse_pos)) { + autoscroll_x_ = 0; + autoscroll_y_ = 0; + return PP_CURSORTYPE_MIDDLEPANNING; + } + + // Relative position to the center of anchor area. + pp::Point rel_pos = mouse_pos - autoscroll_rect_.CenterPoint(); + + // Calculate angle from the X axis. Angle is in range from -pi to pi. + double angle = atan2(static_cast<double>(rel_pos.y()), + static_cast<double>(rel_pos.x())); + + autoscroll_x_ = rel_pos.x() * kAutoScrollFactor; + autoscroll_y_ = rel_pos.y() * kAutoScrollFactor; + + // Angle is from -pi to pi. Screen Y is increasing toward bottom, + // so negative angle represent north direction. + if (angle < - (M_PI * 7.0 / 8.0)) { + // going west + return PP_CURSORTYPE_WESTPANNING; + } else if (angle < - (M_PI * 5.0 / 8.0)) { + // going north-west + return PP_CURSORTYPE_NORTHWESTPANNING; + } else if (angle < - (M_PI * 3.0 / 8.0)) { + // going north. + return PP_CURSORTYPE_NORTHPANNING; + } else if (angle < - (M_PI * 1.0 / 8.0)) { + // going north-east + return PP_CURSORTYPE_NORTHEASTPANNING; + } else if (angle < M_PI * 1.0 / 8.0) { + // going east. + return PP_CURSORTYPE_EASTPANNING; + } else if (angle < M_PI * 3.0 / 8.0) { + // going south-east + return PP_CURSORTYPE_SOUTHEASTPANNING; + } else if (angle < M_PI * 5.0 / 8.0) { + // going south. + return PP_CURSORTYPE_SOUTHPANNING; + } else if (angle < M_PI * 7.0 / 8.0) { + // going south-west + return PP_CURSORTYPE_SOUTHWESTPANNING; + } + + // went around the circle, going west again + return PP_CURSORTYPE_WESTPANNING; +} + +void Instance::ConfigureNumberImageGenerator() { + std::vector<pp::ImageData> num_images = GetThumbnailResources(); + pp::ImageData number_background = CreateResourceImage( + PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND); + number_image_generator_->Configure(number_background, + num_images, + device_scale_); +} + +NumberImageGenerator* Instance::number_image_generator() { + if (!number_image_generator_.get()) { + number_image_generator_.reset(new NumberImageGenerator(this)); + ConfigureNumberImageGenerator(); + } + return number_image_generator_.get(); +} + +int Instance::GetScaled(int x) const { + return static_cast<int>(x * device_scale_); +} + +void Instance::UserMetricsRecordAction(const std::string& action) { + pp::PDF::UserMetricsRecordAction(this, pp::Var(action)); +} + +PDFScriptableObject::PDFScriptableObject(Instance* instance) + : instance_(instance) { +} + +PDFScriptableObject::~PDFScriptableObject() { +} + +bool PDFScriptableObject::HasMethod(const pp::Var& name, pp::Var* exception) { + return instance_->HasScriptableMethod(name, exception); +} + +pp::Var PDFScriptableObject::Call(const pp::Var& method, + const std::vector<pp::Var>& args, + pp::Var* exception) { + return instance_->CallScriptableMethod(method, args, exception); +} + +} // namespace chrome_pdf diff --git a/xfa_test/pdf/instance.h b/xfa_test/pdf/instance.h new file mode 100644 index 0000000000..d39ba407c9 --- /dev/null +++ b/xfa_test/pdf/instance.h @@ -0,0 +1,531 @@ +// 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_INSTANCE_H_ +#define PDF_INSTANCE_H_ + +#include <queue> +#include <set> +#include <string> +#include <utility> +#include <vector> + +#include "base/memory/scoped_ptr.h" +#include "pdf/button.h" +#include "pdf/fading_controls.h" +#include "pdf/page_indicator.h" +#include "pdf/paint_manager.h" +#include "pdf/pdf_engine.h" +#include "pdf/preview_mode_client.h" +#include "pdf/progress_control.h" +#include "pdf/thumbnail_control.h" + +#include "ppapi/c/private/ppb_pdf.h" +#include "ppapi/cpp/dev/printing_dev.h" +#include "ppapi/cpp/dev/scriptable_object_deprecated.h" +#include "ppapi/cpp/dev/scrollbar_dev.h" +#include "ppapi/cpp/dev/selection_dev.h" +#include "ppapi/cpp/dev/widget_client_dev.h" +#include "ppapi/cpp/dev/zoom_dev.h" +#include "ppapi/cpp/graphics_2d.h" +#include "ppapi/cpp/image_data.h" +#include "ppapi/cpp/input_event.h" +#include "ppapi/cpp/private/find_private.h" +#include "ppapi/cpp/private/instance_private.h" +#include "ppapi/cpp/private/var_private.h" +#include "ppapi/cpp/url_loader.h" +#include "ppapi/utility/completion_callback_factory.h" + +namespace pp { +class TextInput_Dev; +} + +namespace chrome_pdf { + +struct ToolbarButtonInfo; + +class Instance : public pp::InstancePrivate, + public pp::Find_Private, + public pp::Printing_Dev, + public pp::Selection_Dev, + public pp::WidgetClient_Dev, + public pp::Zoom_Dev, + public PaintManager::Client, + public PDFEngine::Client, + public PreviewModeClient::Client, + public ControlOwner { + public: + explicit Instance(PP_Instance instance); + virtual ~Instance(); + + // pp::Instance implementation. + virtual bool Init(uint32_t argc, + const char* argn[], + const char* argv[]) override; + virtual bool HandleDocumentLoad(const pp::URLLoader& loader) override; + virtual bool HandleInputEvent(const pp::InputEvent& event) override; + virtual void DidChangeView(const pp::View& view) override; + virtual pp::Var GetInstanceObject() override; + + // pp::Find_Private implementation. + virtual bool StartFind(const std::string& text, bool case_sensitive) override; + virtual void SelectFindResult(bool forward) override; + virtual void StopFind() override; + + // pp::PaintManager::Client implementation. + virtual void OnPaint(const std::vector<pp::Rect>& paint_rects, + std::vector<PaintManager::ReadyRect>* ready, + std::vector<pp::Rect>* pending) override; + + // pp::Printing_Dev implementation. + virtual uint32_t QuerySupportedPrintOutputFormats() override; + virtual int32_t PrintBegin( + const PP_PrintSettings_Dev& print_settings) override; + virtual pp::Resource PrintPages( + const PP_PrintPageNumberRange_Dev* page_ranges, + uint32_t page_range_count) override; + virtual void PrintEnd() override; + virtual bool IsPrintScalingDisabled() override; + + // pp::Private implementation. + virtual pp::Var GetLinkAtPosition(const pp::Point& point); + + // PPP_Selection_Dev implementation. + virtual pp::Var GetSelectedText(bool html) override; + + // WidgetClient_Dev implementation. + virtual void InvalidateWidget(pp::Widget_Dev widget, + const pp::Rect& dirty_rect) override; + virtual void ScrollbarValueChanged(pp::Scrollbar_Dev scrollbar, + uint32_t value) override; + virtual void ScrollbarOverlayChanged(pp::Scrollbar_Dev scrollbar, + bool overlay) override; + + // pp::Zoom_Dev implementation. + virtual void Zoom(double scale, bool text_only) override; + void ZoomChanged(double factor); // Override. + + void FlushCallback(int32_t result); + void DidOpen(int32_t result); + void DidOpenPreview(int32_t result); + // If the given widget intersects the rectangle, paints it and adds the + // rect to ready. + void PaintIfWidgetIntersects(pp::Widget_Dev* widget, + const pp::Rect& rect, + std::vector<PaintManager::ReadyRect>* ready, + std::vector<pp::Rect>* pending); + + // Called when the timer is fired. + void OnTimerFired(int32_t); + void OnClientTimerFired(int32_t id); + + // Called when the control timer is fired. + void OnControlTimerFired(int32_t, + const uint32& control_id, + const uint32& timer_id); + + // Called to print without re-entrancy issues. + void OnPrint(int32_t); + + // PDFEngine::Client implementation. + virtual void DocumentSizeUpdated(const pp::Size& size); + virtual void Invalidate(const pp::Rect& rect); + virtual void Scroll(const pp::Point& point); + virtual void ScrollToX(int position); + virtual void ScrollToY(int position); + virtual void ScrollToPage(int page); + virtual void NavigateTo(const std::string& url, bool open_in_new_tab); + virtual void UpdateCursor(PP_CursorType_Dev cursor); + virtual void UpdateTickMarks(const std::vector<pp::Rect>& tickmarks); + virtual void NotifyNumberOfFindResultsChanged(int total, bool final_result); + virtual void NotifySelectedFindResultChanged(int current_find_index); + virtual void GetDocumentPassword( + pp::CompletionCallbackWithOutput<pp::Var> callback); + virtual void Alert(const std::string& message); + virtual bool Confirm(const std::string& message); + virtual std::string Prompt(const std::string& question, + const std::string& default_answer); + virtual std::string GetURL(); + virtual void Email(const std::string& to, + const std::string& cc, + const std::string& bcc, + const std::string& subject, + const std::string& body); + virtual void Print(); + virtual void SubmitForm(const std::string& url, + const void* data, + int length); + virtual std::string ShowFileSelectionDialog(); + virtual pp::URLLoader CreateURLLoader(); + virtual void ScheduleCallback(int id, int delay_in_ms); + virtual void SearchString(const base::char16* string, + const base::char16* term, + bool case_sensitive, + std::vector<SearchStringResult>* results); + virtual void DocumentPaintOccurred(); + virtual void DocumentLoadComplete(int page_count); + virtual void DocumentLoadFailed(); + virtual pp::Instance* GetPluginInstance(); + virtual void DocumentHasUnsupportedFeature(const std::string& feature); + virtual void DocumentLoadProgress(uint32 available, uint32 doc_size); + virtual void FormTextFieldFocusChange(bool in_focus); + virtual bool IsPrintPreview(); + + // ControlOwner implementation. + virtual void OnEvent(uint32 control_id, uint32 event_id, void* data); + virtual void Invalidate(uint32 control_id, const pp::Rect& rc); + virtual uint32 ScheduleTimer(uint32 control_id, uint32 timeout_ms); + virtual void SetEventCapture(uint32 control_id, bool set_capture); + virtual void SetCursor(uint32 control_id, PP_CursorType_Dev cursor_type); + virtual pp::Instance* GetInstance(); + + bool dont_paint() const { return dont_paint_; } + void set_dont_paint(bool dont_paint) { dont_paint_ = dont_paint; } + + // Called by PDFScriptableObject. + bool HasScriptableMethod(const pp::Var& method, pp::Var* exception); + pp::Var CallScriptableMethod(const pp::Var& method, + const std::vector<pp::Var>& args, + pp::Var* exception); + + // PreviewModeClient::Client implementation. + virtual void PreviewDocumentLoadComplete() override; + virtual void PreviewDocumentLoadFailed() override; + + // Helper functions for implementing PPP_PDF. + void RotateClockwise(); + void RotateCounterclockwise(); + + private: + // Called whenever the plugin geometry changes to update the location of the + // scrollbars, background parts, and notifies the pdf engine. + void OnGeometryChanged(double old_zoom, float old_device_scale); + + // Runs the given JS callback given in |callback|. + void RunCallback(int32_t, pp::Var callback); + + void CreateHorizontalScrollbar(); + void CreateVerticalScrollbar(); + void DestroyHorizontalScrollbar(); + void DestroyVerticalScrollbar(); + + // Returns the thickness of a scrollbar. This returns the thickness when it's + // shown, so for overlay scrollbars it'll still be non-zero. + int GetScrollbarThickness(); + + // Returns the space we need to reserve for the scrollbar in the plugin area. + // If overlay scrollbars are used, this will be 0. + int GetScrollbarReservedThickness(); + + // Returns true if overlay scrollbars are in use. + bool IsOverlayScrollbar(); + + // 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 color); + + std::vector<pp::ImageData> GetThumbnailResources(); + std::vector<pp::ImageData> GetProgressBarResources(pp::ImageData* background); + + void CreateToolbar(const ToolbarButtonInfo* tb_info, size_t size); + int GetToolbarRightOffset(); + int GetToolbarBottomOffset(); + void CreateProgressBar(); + void ConfigureProgressBar(); + void CreateThumbnails(); + void CreatePageIndicator(bool always_visible); + void ConfigurePageIndicator(); + + void PaintOverlayControl(Control* ctrl, + pp::ImageData* image_data, + std::vector<PaintManager::ReadyRect>* ready); + + void LoadUrl(const std::string& url); + void LoadPreviewUrl(const std::string& url); + void LoadUrlInternal(const std::string& url, pp::URLLoader* loader, + void (Instance::* 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(); + + // Figure out the initial page to display based on #page=N and #nameddest=foo + // in the |url_|. + // Returns -1 if there is no valid fragment. The returned value is 0-based, + // whereas page=N is 1-based. + int GetInitialPage(const std::string& url); + + void UpdateToolbarPosition(bool invalidate); + void UpdateProgressBarPosition(bool invalidate); + void UpdatePageIndicatorPosition(bool invalidate); + + void FormDidOpen(int32_t result); + + std::string GetLocalizedString(PP_ResourceString id); + + void UserMetricsRecordAction(const std::string& action); + + void SaveAs(); + + enum ZoomMode { + ZOOM_SCALE, // Standard zooming mode, resize will not affect it. + ZOOM_FIT_TO_WIDTH, // Maintain fit to width on resize. + ZOOM_FIT_TO_PAGE, // Maintain fit to page on resize. + ZOOM_AUTO // Maintain the default auto fitting mode on resize. + }; + + enum DocumentLoadState { + LOAD_STATE_LOADING, + LOAD_STATE_COMPLETE, + LOAD_STATE_FAILED, + }; + + // Set new zoom mode and scale. Scale will be ignored if mode != ZOOM_SCALE. + void SetZoom(ZoomMode zoom_mode, double scale); + + // Updates internal zoom scale based on the plugin/document geometry and + // current mode. + void UpdateZoomScale(); + + // Simulates how Chrome "snaps" zooming up/down to the next nearest zoom level + // when the previous zoom level wasn't an integer. We do this so that + // pressing the zoom buttons has the same effect as the menu buttons, even if + // we start from a non-standard zoom level because of fit-width or fit-height. + double CalculateZoom(uint32 control_id) const; + + pp::ImageData CreateResourceImage(PP_ResourceImage image_id); + + void DrawText(const pp::Point& top_center, PP_ResourceString id); + + // Set print preview mode, where the current PDF document is reduced to + // only one page, and then extended to |page_count| pages with + // |page_count| - 1 blank pages. + void SetPrintPreviewMode(int page_count); + + // Returns the page number to be displayed in the page indicator. If the + // plugin is running within print preview, the displayed number might be + // different from the index of the displayed page. + int GetPageNumberToDisplay(); + + // 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(); + + // Enables autoscroll using origin as a neutral (center) point. + void EnableAutoscroll(const pp::Point& origin); + // Disables autoscroll and returns to normal functionality. + void DisableAutoscroll(); + // Calculate autoscroll info and return proper mouse pointer and scroll + // andjustments. + PP_CursorType_Dev CalculateAutoscroll(const pp::Point& mouse_pos); + + void ConfigureNumberImageGenerator(); + + NumberImageGenerator* number_image_generator(); + + int GetScaled(int x) const; + + pp::ImageData image_data_; + // Used when the plugin is embedded in a page and we have to create the loader + // ourself. + pp::CompletionCallbackFactory<Instance> loader_factory_; + pp::URLLoader embed_loader_; + pp::URLLoader embed_preview_loader_; + + scoped_ptr<pp::Scrollbar_Dev> h_scrollbar_; + scoped_ptr<pp::Scrollbar_Dev> v_scrollbar_; + int32 valid_v_range_; + + PP_CursorType_Dev cursor_; // The current cursor. + + // Used when selecting and dragging beyond the visible portion, in which case + // we want to scroll the document. + bool timer_pending_; + pp::MouseInputEvent last_mouse_event_; + pp::CompletionCallbackFactory<Instance> timer_factory_; + uint32 current_timer_id_; + + // 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 + // scrollbars/toolbars and 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. + bool printing_enabled_; + bool hidpi_enabled_; + // True if the plugin is full-page. + bool full_; + // Zooming mode (none, fit to width, fit to height) + ZoomMode zoom_mode_; + + // 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_; + + // Hold off on painting invalidated requests while this flag is true. + bool dont_paint_; + + // Indicates if plugin is in autoscroll mode. + bool is_autoscroll_; + // Rect for autoscroll anchor. + pp::Rect autoscroll_rect_; + // Image of the autoscroll anchor and its background. + pp::ImageData autoscroll_anchor_; + // Autoscrolling deltas in pixels. + int autoscroll_x_; + int autoscroll_y_; + + // Thickness of a scrollbar. + int scrollbar_thickness_; + + // Reserved thickness of a scrollbar. This is how much space the scrollbar + // takes from the available area. 0 for overlay. + int scrollbar_reserved_thickness_; + + // Used to remember which toolbar is in use + const ToolbarButtonInfo* current_tb_info_; + size_t current_tb_info_size_; + + PaintManager paint_manager_; + + struct BackgroundPart { + pp::Rect location; + uint32 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_; + + // 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_; + + scoped_ptr<FadingControls> toolbar_; + ThumbnailControl thumbnails_; + ProgressControl progress_bar_; + uint32 delayed_progress_timer_id_; + PageIndicator page_indicator_; + + // Used for creating images from numbers. + scoped_ptr<NumberImageGenerator> number_image_generator_; + + // Used for submitting forms. + pp::CompletionCallbackFactory<Instance> form_factory_; + pp::URLLoader form_loader_; + + // Used for generating callbacks. + // TODO(raymes): We don't really need other callback factories we can just + // fold them into this one. + pp::CompletionCallbackFactory<Instance> callback_factory_; + + // True if we haven't painted the plugin viewport yet. + bool first_paint_; + + // True when we've painted at least one page from the document. + bool painted_first_page_; + + // True if we should display page indicator, false otherwise + bool show_page_indicator_; + + // Callback when the document load completes. + pp::Var on_load_callback_; + pp::Var on_scroll_callback_; + pp::Var on_plugin_size_changed_callback_; + + DocumentLoadState document_load_state_; + DocumentLoadState preview_document_load_state_; + + // JavaScript interface to control this instance. + // This wraps a PDFScriptableObject in a pp::Var. + pp::VarPrivate instance_object_; + + // 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_; +}; + +// This implements the JavaScript class entrypoint for the plugin instance. +// This class is just a thin wrapper. It delegates relevant methods to Instance. +class PDFScriptableObject : public pp::deprecated::ScriptableObject { + public: + explicit PDFScriptableObject(Instance* instance); + virtual ~PDFScriptableObject(); + + // pp::deprecated::ScriptableObject implementation. + virtual bool HasMethod(const pp::Var& method, pp::Var* exception); + virtual pp::Var Call(const pp::Var& method, + const std::vector<pp::Var>& args, + pp::Var* exception); + + private: + Instance* instance_; +}; + +} // namespace chrome_pdf + +#endif // PDF_INSTANCE_H_ diff --git a/xfa_test/pdf/number_image_generator.cc b/xfa_test/pdf/number_image_generator.cc new file mode 100644 index 0000000000..289691513c --- /dev/null +++ b/xfa_test/pdf/number_image_generator.cc @@ -0,0 +1,81 @@ +// 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/number_image_generator.h" + +#include "base/logging.h" +#include "base/strings/string_util.h" +#include "pdf/draw_utils.h" +#include "pdf/instance.h" + +namespace chrome_pdf { + +const int kPageNumberSeparator = 0; +const int kPageNumberOriginX = 8; +const int kPageNumberOriginY = 4; + +NumberImageGenerator::NumberImageGenerator(Instance* instance) + : instance_(instance), + device_scale_(1.0f) { +} + +NumberImageGenerator::~NumberImageGenerator() { +} + +void NumberImageGenerator::Configure(const pp::ImageData& number_background, + const std::vector<pp::ImageData>& number_images, float device_scale) { + number_background_ = number_background; + number_images_ = number_images; + device_scale_ = device_scale; +} + +void NumberImageGenerator::GenerateImage( + int page_number, pp::ImageData* image) { + char buffer[12]; + base::snprintf(buffer, sizeof(buffer), "%u", page_number); + int extra_width = 0; + DCHECK(number_images_.size() >= 10); + DCHECK(!number_background_.is_null()); + for (size_t i = 1; i < strlen(buffer); ++i) { + int index = buffer[i] - '0'; + extra_width += number_images_[index].size().width(); + extra_width += static_cast<int>(kPageNumberSeparator * device_scale_); + } + + *image = pp::ImageData( + instance_, + PP_IMAGEDATAFORMAT_BGRA_PREMUL, + pp::Size(number_background_.size().width() + extra_width, + number_background_.size().height()), + false); + + int stretch_point = number_background_.size().width() / 2; + + pp::Rect src_rc(0, 0, stretch_point, number_background_.size().height()); + pp::Rect dest_rc(src_rc); + CopyImage(number_background_, src_rc, image, dest_rc, false); + src_rc.Offset(number_background_.size().width() - stretch_point, 0); + dest_rc.Offset(image->size().width() - stretch_point, 0); + CopyImage(number_background_, src_rc, image, dest_rc, false); + src_rc = pp::Rect(stretch_point, 0, 1, number_background_.size().height()); + dest_rc = src_rc; + dest_rc.set_width(extra_width + 1); + CopyImage(number_background_, src_rc, image, dest_rc, true); + + pp::Point origin(static_cast<int>(kPageNumberOriginX * device_scale_), + static_cast<int>(kPageNumberOriginY * device_scale_)); + for (size_t i = 0; i < strlen(buffer); ++i) { + int index = buffer[i] - '0'; + CopyImage( + number_images_[index], + pp::Rect(pp::Point(), number_images_[index].size()), + image, pp::Rect(origin, number_images_[index].size()), false); + origin += pp::Point( + number_images_[index].size().width() + + static_cast<int>(kPageNumberSeparator * device_scale_), 0); + } +} + +} // namespace chrome_pdf + diff --git a/xfa_test/pdf/number_image_generator.h b/xfa_test/pdf/number_image_generator.h new file mode 100644 index 0000000000..51ffd3ec3d --- /dev/null +++ b/xfa_test/pdf/number_image_generator.h @@ -0,0 +1,37 @@ +// 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_NUMBER_IMAGE_GENERATOR_H +#define PDF_NUMBER_IMAGE_GENERATOR_H + +#include <vector> + +#include "ppapi/cpp/image_data.h" + +namespace chrome_pdf { + +class Instance; + +class NumberImageGenerator { + public: + explicit NumberImageGenerator(Instance* instance); + virtual ~NumberImageGenerator(); + + void Configure(const pp::ImageData& number_background, + const std::vector<pp::ImageData>& number_images, + float device_scale); + + void GenerateImage(int page_number, pp::ImageData* image); + + private: + Instance* instance_; + pp::ImageData number_background_; + std::vector<pp::ImageData> number_images_; + float device_scale_; +}; + +} // namespace chrome_pdf + +#endif // PDF_NUMBER_IMAGE_GENERATOR_H + diff --git a/xfa_test/pdf/out_of_process_instance.cc b/xfa_test/pdf/out_of_process_instance.cc new file mode 100644 index 0000000000..d627dc2d79 --- /dev/null +++ b/xfa_test/pdf/out_of_process_instance.cc @@ -0,0 +1,1369 @@ +// 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 <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/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" + +#if defined(OS_MACOSX) +#include "base/mac/mac_util.h" +#endif + +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"; +// 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"; +// 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"; +// Set translated strings (Plugin -> Page) +const char kJSSetTranslatedStringsType[] = "setTranslatedStrings"; +const char kJSGetPasswordString[] = "getPasswordString"; +const char kJSLoadingString[] = "loadingString"; +const char kJSLoadFailedString[] = "loadFailedString"; +// 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"; + +const int kFindResultCooldownMs = 100; + +const double kMinZoom = 0.01; + +namespace { + +static const char kPPPPdfInterface[] = PPP_PDF_INTERFACE_1; + +PP_Var GetLinkAtPosition(PP_Instance instance, PP_Point point) { + pp::Var var; + void* object = pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface); + if (object) { + var = static_cast<OutOfProcessInstance*>(object)->GetLinkAtPosition( + pp::Point(point)); + } + return var.Detach(); +} + +void Transform(PP_Instance instance, PP_PrivatePageTransformType type) { + void* object = + pp::Instance::GetPerInstanceObject(instance, kPPPPdfInterface); + if (object) { + 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; + } + } +} + +const PPP_Pdf ppp_private = { + &GetLinkAtPosition, + &Transform +}; + +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)), '/', &url_substr); + 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), + pp::Selection_Dev(this), + cursor_(PP_CURSORTYPE_POINTER), + zoom_(1.0), + device_scale_(1.0), + printing_enabled_(true), + 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) { + 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); +} + +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 put into "full frame" mode when it is being loaded in the + // extension because this enables some features that we don't want pages + // abusing outside of the extension. + pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this); + std::string document_url = document_url_var.is_string() ? + document_url_var.AsString() : std::string(); + std::string extension_url = std::string(kChromeExtension); + bool in_extension = + !document_url.compare(0, extension_url.size(), extension_url); + + if (in_extension) { + // 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(); + + // Send translated strings to the extension where they will be displayed. + // TODO(raymes): It would be better to get these in the extension directly + // through an API but no such API currently exists. + pp::VarDictionary translated_strings; + translated_strings.Set(kType, kJSSetTranslatedStringsType); + translated_strings.Set(kJSGetPasswordString, + GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD)); + translated_strings.Set(kJSLoadingString, + GetLocalizedString(PP_RESOURCESTRING_PDFLOADING)); + translated_strings.Set(kJSLoadFailedString, + GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED)); + PostMessage(translated_strings); + + text_input_.reset(new pp::TextInput_Dev(this)); + + const char* stream_url = NULL; + const char* original_url = NULL; + const char* headers = NULL; + for (uint32_t i = 0; i < argc; ++i) { + 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]; + } + + // TODO(raymes): This is a hack to ensure that if no headers are passed in + // then we get the right MIME type. When the in process plugin is removed we + // can fix the document loader properly and remove this hack. + if (!headers || strcmp(headers, "") == 0) + headers = "content-type: application/pdf"; + + 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_int() && + dict.Get(pp::Var(kJSYOffset)).is_int() && + dict.Get(pp::Var(kJSZoom)).is_number()) { + received_viewport_message_ = true; + stop_scrolling_ = false; + double zoom = dict.Get(pp::Var(kJSZoom)).AsDouble(); + pp::Point scroll_offset(dict.Get(pp::Var(kJSXOffset)).AsInt(), + dict.Get(pp::Var(kJSYOffset)).AsInt()); + + // 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 == 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()); + + 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 { + 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; + + // TODO(raymes): Implement this scroll behavior in JS: + // When click+dragging, scroll the document correctly. + + // 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( + BoundScrollOffsetToDocument(view.GetScrollOffset())); + engine_->ScrolledToXPosition(scroll_offset.x() * device_scale_); + engine_->ScrolledToYPosition(scroll_offset.y() * device_scale_); + } +} + +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); +} + +pp::Var OutOfProcessInstance::GetSelectedText(bool html) { + if (html || !engine_->HasPermission(PDFEngine::PERMISSION_COPY)) + return pp::Var(); + return engine_->GetSelectedText(); +} + +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.c_str(), 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, kBackgroundColor); + ready->push_back(PaintManager::ReadyRect(rect, image_data_, true)); + } + + if (!received_viewport_message_) + return; + + engine_->PrePaint(); + + for (size_t i = 0; i < paint_rects.size(); i++) { + // Intersect with plugin area since there could be pending invalidates from + // when the plugin area was larger. + pp::Rect rect = + paint_rects[i].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 (size_t j = 0; j < pdf_ready.size(); ++j) { + pdf_ready[j].Offset(available_area_.point()); + ready->push_back( + PaintManager::ReadyRect(pdf_ready[j], image_data_, false)); + } + for (size_t j = 0; j < pdf_pending.size(); ++j) { + pdf_pending[j].Offset(available_area_.point()); + pending->push_back(pdf_pending[j]); + } + } + + for (size_t j = 0; j < background_parts_.size(); ++j) { + pp::Rect intersection = background_parts_[j].location.Intersect(rect); + if (!intersection.IsEmpty()) { + FillRect(intersection, background_parts_[j].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_engine_.reset(PDFEngine::Create(new PreviewModeClient(this))); + 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), + kBackgroundColor + }; + 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 color) { + DCHECK(!image_data_.is_null() || rect.IsEmpty()); + uint32* buffer_start = static_cast<uint32*>(image_data_.data()); + int stride = image_data_.stride(); + uint32* 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) { + std::string url_copy(url); + + // Empty |url_copy| is ok, and will effectively be a reload. + // Skip the code below so an empty URL does not turn into "http://", which + // will cause GURL to fail a DCHECK. + if (!url_copy.empty()) { + // If |url_copy| starts with '#', then it's for the same URL with a + // different URL fragment. + if (url_copy[0] == '#') { + url_copy = url_ + url_copy; + } + // If there's no scheme, add http. + if (url_copy.find("://") == std::string::npos && + url_copy.find("mailto:") == std::string::npos) { + url_copy = std::string("http://") + url_copy; + } + // Make sure |url_copy| starts with a valid scheme. + if (url_copy.find("http://") != 0 && + url_copy.find("https://") != 0 && + url_copy.find("ftp://") != 0 && + url_copy.find("file://") != 0 && + url_copy.find("mailto:") != 0) { + return; + } + // Make sure |url_copy| is not only a scheme. + if (url_copy == "http://" || + url_copy == "https://" || + url_copy == "ftp://" || + url_copy == "file://" || + url_copy == "mailto:") { + return; + } + } + pp::VarDictionary message; + message.Set(kType, kJSNavigateType); + message.Set(kJSNavigateUrl, url_copy); + 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(), NULL); +} + +void OutOfProcessInstance::UpdateTickMarks( + const std::vector<pp::Rect>& tickmarks) { + float inverse_scale = 1.0f / device_scale_; + std::vector<pp::Rect> scaled_tickmarks = tickmarks; + for (size_t i = 0; i < scaled_tickmarks.size(); i++) + ScaleRect(inverse_scale, &scaled_tickmarks[i]); + 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) { + 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 (!printing_enabled_ || + (!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"); + + // 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 message; + message.Set(pp::Var(kType), pp::Var(kJSLoadProgressType)); + message.Set(pp::Var(kJSProgressPercentage), pp::Var(100)) ; + PostMessage(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)) { + printing_enabled_ = false; + } + + 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_.size()) + 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_.size()) + 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 available, + uint32 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; + 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 doc_height = GetDocumentPixelHeight(); + if (doc_height < available_area_.height()) { + available_area_.set_height(doc_height); + } + + 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_); +} + +std::string OutOfProcessInstance::GetLocalizedString(PP_ResourceString id) { + pp::Var rv(pp::PDF::GetLocalizedString(this, id)); + if (!rv.is_string()) + return std::string(); + + return rv.AsString(); +} + +void OutOfProcessInstance::AppendBlankPrintPreviewPages() { + if (print_preview_page_count_ == 0) + return; + engine_->AppendBlankPages(print_preview_page_count_); + if (preview_pages_info_.size() > 0) + LoadAvailablePreviewPage(); +} + +bool OutOfProcessInstance::IsPrintPreview() { + return IsPrintPreviewUrl(url_); +} + +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_.size() <= 0 || + 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::Point OutOfProcessInstance::BoundScrollOffsetToDocument( + const pp::Point& scroll_offset) { + int max_x = document_size_.width() * zoom_ - plugin_dip_size_.width(); + int x = std::max(std::min(scroll_offset.x(), max_x), 0); + int max_y = document_size_.height() * zoom_ - plugin_dip_size_.height(); + int y = std::max(std::min(scroll_offset.y(), max_y), 0); + return pp::Point(x, y); +} + +} // namespace chrome_pdf diff --git a/xfa_test/pdf/out_of_process_instance.h b/xfa_test/pdf/out_of_process_instance.h new file mode 100644 index 0000000000..355f050dc3 --- /dev/null +++ b/xfa_test/pdf/out_of_process_instance.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_OUT_OF_PROCESS_INSTANCE_H_ +#define PDF_OUT_OF_PROCESS_INSTANCE_H_ + +#include <queue> +#include <set> +#include <string> +#include <utility> +#include <vector> + +#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/cpp/dev/printing_dev.h" +#include "ppapi/cpp/dev/scriptable_object_deprecated.h" +#include "ppapi/cpp/dev/selection_dev.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 pp::Selection_Dev, + public PaintManager::Client, + public PDFEngine::Client, + public PreviewModeClient::Client { + public: + explicit OutOfProcessInstance(PP_Instance instance); + virtual ~OutOfProcessInstance(); + + // pp::Instance implementation. + virtual bool Init(uint32_t argc, + const char* argn[], + const char* argv[]) override; + virtual void HandleMessage(const pp::Var& message) override; + virtual bool HandleInputEvent(const pp::InputEvent& event) override; + virtual void DidChangeView(const pp::View& view) override; + + // pp::Find_Private implementation. + virtual bool StartFind(const std::string& text, bool case_sensitive) override; + virtual void SelectFindResult(bool forward) override; + virtual void StopFind() override; + + // pp::PaintManager::Client implementation. + virtual void OnPaint(const std::vector<pp::Rect>& paint_rects, + std::vector<PaintManager::ReadyRect>* ready, + std::vector<pp::Rect>* pending) override; + + // pp::Printing_Dev implementation. + virtual uint32_t QuerySupportedPrintOutputFormats() override; + virtual int32_t PrintBegin( + const PP_PrintSettings_Dev& print_settings) override; + virtual pp::Resource PrintPages( + const PP_PrintPageNumberRange_Dev* page_ranges, + uint32_t page_range_count) override; + virtual void PrintEnd() override; + virtual bool IsPrintScalingDisabled() override; + + // pp::Private implementation. + virtual pp::Var GetLinkAtPosition(const pp::Point& point); + + // PPP_Selection_Dev implementation. + virtual pp::Var GetSelectedText(bool html) override; + + 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. + virtual void DocumentSizeUpdated(const pp::Size& size); + virtual void Invalidate(const pp::Rect& rect); + virtual void Scroll(const pp::Point& point); + virtual void ScrollToX(int position); + virtual void ScrollToY(int position); + virtual void ScrollToPage(int page); + virtual void NavigateTo(const std::string& url, bool open_in_new_tab); + virtual void UpdateCursor(PP_CursorType_Dev cursor); + virtual void UpdateTickMarks(const std::vector<pp::Rect>& tickmarks); + virtual void NotifyNumberOfFindResultsChanged(int total, bool final_result); + virtual void NotifySelectedFindResultChanged(int current_find_index); + virtual void GetDocumentPassword( + pp::CompletionCallbackWithOutput<pp::Var> callback); + virtual void Alert(const std::string& message); + virtual bool Confirm(const std::string& message); + virtual std::string Prompt(const std::string& question, + const std::string& default_answer); + virtual std::string GetURL(); + virtual void Email(const std::string& to, + const std::string& cc, + const std::string& bcc, + const std::string& subject, + const std::string& body); + virtual void Print(); + virtual void SubmitForm(const std::string& url, + const void* data, + int length); + virtual std::string ShowFileSelectionDialog(); + virtual pp::URLLoader CreateURLLoader(); + virtual void ScheduleCallback(int id, int delay_in_ms); + virtual void SearchString(const base::char16* string, + const base::char16* term, + bool case_sensitive, + std::vector<SearchStringResult>* results); + virtual void DocumentPaintOccurred(); + virtual void DocumentLoadComplete(int page_count); + virtual void DocumentLoadFailed(); + virtual pp::Instance* GetPluginInstance(); + virtual void DocumentHasUnsupportedFeature(const std::string& feature); + virtual void DocumentLoadProgress(uint32 available, uint32 doc_size); + virtual void FormTextFieldFocusChange(bool in_focus); + virtual bool IsPrintPreview(); + + // PreviewModeClient::Client implementation. + virtual void PreviewDocumentLoadComplete() override; + virtual 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 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(); + + // Figure out the initial page to display based on #page=N and #nameddest=foo + // in the |url_|. + // Returns -1 if there is no valid fragment. The returned value is 0-based, + // whereas page=N is 1-based. + int GetInitialPage(const std::string& url); + + void FormDidOpen(int32_t result); + + std::string GetLocalizedString(PP_ResourceString id); + + 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::Point BoundScrollOffsetToDocument(const pp::Point& 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. + bool printing_enabled_; + // True if the plugin is full-page. + bool full_; + + PaintManager paint_manager_; + + struct BackgroundPart { + pp::Rect location; + uint32 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_; + + // 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_; + + // 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 callback for receiving the password from the page. + scoped_ptr<pp::CompletionCallbackWithOutput<pp::Var> > password_callback_; +}; + +} // namespace chrome_pdf + +#endif // PDF_OUT_OF_PROCESS_INSTANCE_H_ diff --git a/xfa_test/pdf/page_indicator.cc b/xfa_test/pdf/page_indicator.cc new file mode 100644 index 0000000000..c4af1e07b7 --- /dev/null +++ b/xfa_test/pdf/page_indicator.cc @@ -0,0 +1,127 @@ +// 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/page_indicator.h" + +#include "base/logging.h" +#include "base/strings/string_util.h" +#include "pdf/draw_utils.h" +#include "pdf/number_image_generator.h" +#include "pdf/resource_consts.h" + +namespace chrome_pdf { + + +PageIndicator::PageIndicator() + : current_page_(0), + fade_out_timer_id_(0), + splash_timeout_(kPageIndicatorSplashTimeoutMs), + fade_timeout_(kPageIndicatorScrollFadeTimeoutMs), + always_visible_(false) { +} + +PageIndicator::~PageIndicator() { +} + +bool PageIndicator::CreatePageIndicator( + uint32 id, + bool visible, + Control::Owner* delegate, + NumberImageGenerator* number_image_generator, + bool always_visible) { + number_image_generator_ = number_image_generator; + always_visible_ = always_visible; + + pp::Rect rc; + bool res = Control::Create(id, rc, visible, delegate); + return res; +} + +void PageIndicator::Configure(const pp::Point& origin, + const pp::ImageData& background) { + background_ = background; + pp::Rect rc(origin, background_.size()); + Control::SetRect(rc, false); +} + +void PageIndicator::set_current_page(int current_page) { + if (current_page_ < 0) + return; + + current_page_ = current_page; +} + +void PageIndicator::Paint(pp::ImageData* image_data, const pp::Rect& rc) { + if (!visible()) + return; + + pp::Rect draw_rc = rc.Intersect(rect()); + if (draw_rc.IsEmpty()) + return; + + // Copying the background image to a temporary buffer. + pp::ImageData buffer(owner()->GetInstance(), background_.format(), + background_.size(), false); + CopyImage(background_, pp::Rect(background_.size()), + &buffer, pp::Rect(background_.size()), false); + + // Creating the page number image. + pp::ImageData page_number_image; + number_image_generator_->GenerateImage(current_page_, &page_number_image); + + pp::Point origin2( + (buffer.size().width() - page_number_image.size().width()) / 2.5, + (buffer.size().height() - page_number_image.size().height()) / 2); + + // Drawing page number image on the buffer. + if (origin2.x() > 0 && origin2.y() > 0) { + CopyImage(page_number_image, + pp::Rect(pp::Point(), page_number_image.size()), + &buffer, + pp::Rect(origin2, page_number_image.size()), + false); + } + + // Drawing the buffer. + pp::Point origin = draw_rc.point(); + draw_rc.Offset(-rect().x(), -rect().y()); + AlphaBlend(buffer, draw_rc, image_data, origin, transparency()); +} + +void PageIndicator::OnTimerFired(uint32 timer_id) { + FadingControl::OnTimerFired(timer_id); + if (timer_id == fade_out_timer_id_) { + Fade(false, fade_timeout_); + } +} + +void PageIndicator::ResetFadeOutTimer() { + fade_out_timer_id_ = + owner()->ScheduleTimer(id(), splash_timeout_); +} + +void PageIndicator::OnFadeInComplete() { + if (!always_visible_) + ResetFadeOutTimer(); +} + +void PageIndicator::Splash() { + Splash(kPageIndicatorSplashTimeoutMs, kPageIndicatorScrollFadeTimeoutMs); +} + +void PageIndicator::Splash(uint32 splash_timeout, uint32 fade_timeout) { + splash_timeout_ = splash_timeout; + fade_timeout_ = fade_timeout; + if (!always_visible_) + fade_out_timer_id_ = 0; + Fade(true, fade_timeout_); +} + +int PageIndicator::GetYPosition( + int vertical_scrollbar_y, int document_height, int plugin_height) { + double percent = static_cast<double>(vertical_scrollbar_y) / document_height; + return (plugin_height - rect().height()) * percent; +} + +} // namespace chrome_pdf diff --git a/xfa_test/pdf/page_indicator.h b/xfa_test/pdf/page_indicator.h new file mode 100644 index 0000000000..0d06ee1a0b --- /dev/null +++ b/xfa_test/pdf/page_indicator.h @@ -0,0 +1,72 @@ +// 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_PAGE_INDICATOR_H_ +#define PDF_PAGE_INDICATOR_H_ + +#include <string> +#include <vector> + +#include "pdf/control.h" +#include "pdf/fading_control.h" +#include "ppapi/cpp/image_data.h" +#include "ppapi/cpp/point.h" +#include "ppapi/cpp/rect.h" + +namespace chrome_pdf { + +class NumberImageGenerator; + +const uint32 kPageIndicatorScrollFadeTimeoutMs = 240; +const uint32 kPageIndicatorInitialFadeTimeoutMs = 960; +const uint32 kPageIndicatorSplashTimeoutMs = 2000; + +class PageIndicator : public FadingControl { + public: + PageIndicator(); + virtual ~PageIndicator(); + virtual bool CreatePageIndicator( + uint32 id, + bool visible, + Control::Owner* delegate, + NumberImageGenerator* number_image_generator, + bool always_visible); + + void Configure(const pp::Point& origin, const pp::ImageData& background); + + int current_page() const { return current_page_; } + void set_current_page(int current_page); + + virtual void Splash(); + void Splash(uint32 splash_timeout, uint32 page_timeout); + + // Returns the y position where the page indicator should be drawn given the + // position of the scrollbar and the total document height and the plugin + // height. + int GetYPosition( + int vertical_scrollbar_y, int document_height, int plugin_height); + + // Control interface. + virtual void Paint(pp::ImageData* image_data, const pp::Rect& rc); + virtual void OnTimerFired(uint32 timer_id); + + // FadingControl interface. + virtual void OnFadeInComplete(); + + private: + void ResetFadeOutTimer(); + + int current_page_; + pp::ImageData background_; + NumberImageGenerator* number_image_generator_; + uint32 fade_out_timer_id_; + uint32 splash_timeout_; + uint32 fade_timeout_; + + bool always_visible_; +}; + +} // namespace chrome_pdf + +#endif // PDF_PAGE_INDICATOR_H_ diff --git a/xfa_test/pdf/paint_aggregator.cc b/xfa_test/pdf/paint_aggregator.cc new file mode 100644 index 0000000000..549cab6d09 --- /dev/null +++ b/xfa_test/pdf/paint_aggregator.cc @@ -0,0 +1,263 @@ +// 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 <algorithm> + +#include "base/logging.h" + +// ---------------------------------------------------------------------------- +// 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); + for (size_t i = 0; i < update_.paint_rects.size(); i++) + ret.paint_rects.push_back(update_.paint_rects[i]); + + 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; + } + + // 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 (size_t i = 0; i < leftover_rects.size(); ++i) + InvalidateRectInternal(leftover_rects[i], false); + + for (size_t i = 0; i < update_.ready_rects.size(); ++i) { + if (update_.scroll_rect.Contains(update_.ready_rects[i].rect)) { + update_.ready_rects[i].rect = + ScrollPaintRect(update_.ready_rects[i].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/xfa_test/pdf/paint_aggregator.h b/xfa_test/pdf/paint_aggregator.h new file mode 100644 index 0000000000..96f61e0878 --- /dev/null +++ b/xfa_test/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/xfa_test/pdf/paint_manager.cc b/xfa_test/pdf/paint_manager.cc new file mode 100644 index 0000000000..f452b37186 --- /dev/null +++ b/xfa_test/pdf/paint_manager.cc @@ -0,0 +1,302 @@ +// 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 <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() { + // You must call SetSize before using. + DCHECK(!graphics_.is_null() || has_pending_resize_); + + EnsureCallbackPending(); + aggregator_.InvalidateRect(pp::Rect(GetEffectiveSize())); +} + +void PaintManager::InvalidateRect(const pp::Rect& rect) { + DCHECK(!in_paint_); + + // You must call SetSize before using. + DCHECK(!graphics_.is_null() || has_pending_resize_); + + // 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_); + + // You must call SetSize before using. + DCHECK(!graphics_.is_null() || has_pending_resize_); + + 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; + for (size_t i = 0; i < ready.size(); ++i) + temp_ready.push_back(ready[i]); + 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 (size_t i = 0; i < ready.size(); ++i) { + // 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[i].flush_now && + (!view_size_changed_waiting_for_paint_ || first_paint_)) { + ready_now.push_back(ready[i]); + } else { + ready_later.push_back(ready[i]); + } + } + // 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 (size_t i = 0; i < ready_now.size(); ++i) { + graphics_.PaintImageData( + ready_now[i].image_data, ready_now[i].offset, ready_now[i].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/xfa_test/pdf/paint_manager.h b/xfa_test/pdf/paint_manager.h new file mode 100644 index 0000000000..7755eb6829 --- /dev/null +++ b/xfa_test/pdf/paint_manager.h @@ -0,0 +1,205 @@ +// 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 <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/xfa_test/pdf/pdf.cc b/xfa_test/pdf/pdf.cc new file mode 100644 index 0000000000..6a4507f4fc --- /dev/null +++ b/xfa_test/pdf/pdf.cc @@ -0,0 +1,275 @@ +// 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" + +#if defined(OS_WIN) +#include <windows.h> +#endif + +#include "base/command_line.h" +#include "base/logging.h" +#include "pdf/instance.h" +#include "pdf/out_of_process_instance.h" +#include "ppapi/c/ppp.h" +#include "ppapi/cpp/private/pdf.h" + +bool g_sdk_initialized_via_pepper = false; + +// The Mac release builds discard CreateModule and the entire PDFModule +// definition because they are not referenced here. This causes the Pepper +// exports (PPP_GetInterface etc) to not be exported. So we force the linker +// to include this code by using __attribute__((used)). +#if __GNUC__ >= 4 +#define PDF_USED __attribute__((used)) +#else +#define PDF_USED +#endif + +#if defined(OS_WIN) +HMODULE g_hmodule; + +void HandleInvalidParameter(const wchar_t* expression, + const wchar_t* function, + const wchar_t* file, + unsigned int line, + uintptr_t reserved) { + // Do the same as Chrome's CHECK(false) which is undefined. + ::base::debug::BreakDebugger(); + return; +} + +void HandlePureVirtualCall() { + // Do the same as Chrome's CHECK(false) which is undefined. + ::base::debug::BreakDebugger(); + return; +} + + +BOOL APIENTRY DllMain(HMODULE module, DWORD reason_for_call, LPVOID reserved) { + g_hmodule = module; + if (reason_for_call == DLL_PROCESS_ATTACH) { + // On windows following handlers work only inside module. So breakpad in + // chrome.dll does not catch that. To avoid linking related code or + // duplication breakpad_win.cc::InitCrashReporter() just catch errors here + // and crash in a way interceptable by breakpad of parent module. + _set_invalid_parameter_handler(HandleInvalidParameter); + _set_purecall_handler(HandlePureVirtualCall); + } + return TRUE; +} + +#endif + +namespace pp { + +PDF_USED Module* CreateModule() { + return new chrome_pdf::PDFModule(); +} + +} // namespace pp + +namespace chrome_pdf { + +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) { + void* data = NULL; +#if defined(OS_WIN) + data = g_hmodule; +#endif + if (!chrome_pdf::InitializeSDK(data)) + return NULL; + g_sdk_initialized_via_pepper = true; + } + + if (pp::PDF::IsOutOfProcess(pp::InstanceHandle(instance))) + return new OutOfProcessInstance(instance); + return new Instance(instance); +} + +} // namespace chrome_pdf + +extern "C" { + +// TODO(sanjeevr): It might make sense to provide more stateful wrappers over +// the internal PDF SDK (such as LoadDocument, LoadPage etc). Determine if we +// need to provide this. +// Wrapper exports over the PDF engine that can be used by an external module +// such as Chrome (since Chrome cannot directly pull in PDFium sources). +#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_x| and |dpi_y| are the x and y resolutions respectively. If either +// 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. +PP_EXPORT bool RenderPDFPageToDC(const void* pdf_buffer, + int buffer_size, + int page_number, + HDC dc, + int dpi_x, + int dpi_y, + 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(g_hmodule)) { + return false; + } + } + scoped_ptr<chrome_pdf::PDFEngineExports> engine_exports( + chrome_pdf::PDFEngineExports::Create()); + chrome_pdf::PDFEngineExports::RenderingSettings settings( + dpi_x, dpi_y, 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 + +// |page_count| and |max_page_width| are optional and can be NULL. +// Returns false if the document is not valid. +PDF_USED PP_EXPORT +bool GetPDFDocInfo(const void* pdf_buffer, + int buffer_size, int* page_count, + double* max_page_width) { + if (!g_sdk_initialized_via_pepper) { + void* data = NULL; +#if defined(OS_WIN) + data = g_hmodule; +#endif + if (!chrome_pdf::InitializeSDK(data)) + return false; + } + scoped_ptr<chrome_pdf::PDFEngineExports> engine_exports( + chrome_pdf::PDFEngineExports::Create()); + 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; +} + +// 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. +PDF_USED PP_EXPORT +bool GetPDFPageSizeByIndex(const void* pdf_buffer, + int pdf_buffer_size, int page_number, + double* width, double* height) { + if (!g_sdk_initialized_via_pepper) { + void* data = NULL; +#if defined(OS_WIN) + data = g_hmodule; +#endif + if (!chrome_pdf::InitializeSDK(data)) + return false; + } + scoped_ptr<chrome_pdf::PDFEngineExports> engine_exports( + chrome_pdf::PDFEngineExports::Create()); + 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; +} + +// 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. +PDF_USED PP_EXPORT +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) { + void* data = NULL; +#if defined(OS_WIN) + data = g_hmodule; +#endif + if (!chrome_pdf::InitializeSDK(data)) + return false; + } + scoped_ptr<chrome_pdf::PDFEngineExports> engine_exports( + chrome_pdf::PDFEngineExports::Create()); + 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; +} + +} // extern "C" diff --git a/xfa_test/pdf/pdf.def b/xfa_test/pdf/pdf.def new file mode 100644 index 0000000000..b36918bb27 --- /dev/null +++ b/xfa_test/pdf/pdf.def @@ -0,0 +1,7 @@ +LIBRARY pdf + +EXPORTS + NP_GetEntryPoints @1 + NP_Initialize @2 + NP_Shutdown @3 + diff --git a/xfa_test/pdf/pdf.gyp b/xfa_test/pdf/pdf.gyp new file mode 100644 index 0000000000..f1e8e3e658 --- /dev/null +++ b/xfa_test/pdf/pdf.gyp @@ -0,0 +1,200 @@ +{ + 'variables': { + 'chromium_code': 1, + 'pdf_engine%': 0, # 0 PDFium + }, + 'target_defaults': { + 'cflags': [ + '-fPIC', + ], + }, + 'targets': [ + { + 'target_name': 'pdf', + 'type': 'loadable_module', + 'msvs_guid': '647863C0-C7A3-469A-B1ED-AD7283C34BED', + 'dependencies': [ + '../base/base.gyp:base', + '../net/net.gyp:net', + '../ppapi/ppapi.gyp:ppapi_cpp', + '../third_party/pdfium/pdfium.gyp:pdfium', + ], + 'xcode_settings': { + 'INFOPLIST_FILE': 'Info.plist', + }, + 'mac_framework_dirs': [ + '$(SDKROOT)/System/Library/Frameworks/ApplicationServices.framework/Frameworks', + ], + 'ldflags': [ '-L<(PRODUCT_DIR)',], + 'sources': [ + 'button.h', + 'button.cc', + 'chunk_stream.h', + 'chunk_stream.cc', + 'control.h', + 'control.cc', + 'document_loader.h', + 'document_loader.cc', + 'draw_utils.cc', + 'draw_utils.h', + 'fading_control.cc', + 'fading_control.h', + 'fading_controls.cc', + 'fading_controls.h', + 'instance.cc', + 'instance.h', + 'number_image_generator.cc', + 'number_image_generator.h', + 'out_of_process_instance.cc', + 'out_of_process_instance.h', + 'page_indicator.cc', + 'page_indicator.h', + 'paint_aggregator.cc', + 'paint_aggregator.h', + 'paint_manager.cc', + 'paint_manager.h', + 'pdf.cc', + 'pdf.h', + 'pdf.rc', + 'progress_control.cc', + 'progress_control.h', + 'pdf_engine.h', + 'preview_mode_client.cc', + 'preview_mode_client.h', + 'resource.h', + 'resource_consts.h', + 'thumbnail_control.cc', + 'thumbnail_control.h', + '../chrome/browser/chrome_page_zoom_constants.cc', + '../content/common/page_zoom.cc', + ], + 'conditions': [ + ['pdf_engine==0', { + 'sources': [ + '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', + ], + }], + ['OS!="win"', { + 'sources!': [ + 'pdf.rc', + ], + }], + ['OS=="mac"', { + 'mac_bundle': 1, + 'product_name': 'PDF', + 'product_extension': 'plugin', + # Strip the shipping binary of symbols so "Foxit" doesn't appear in + # the binary. Symbols are stored in a separate .dSYM. + 'variables': { + 'mac_real_dsym': 1, + }, + 'sources+': [ + 'Info.plist' + ], + }], + ['OS=="win"', { + 'defines': [ + 'COMPILE_CONTENT_STATICALLY', + ], + # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. + 'msvs_disabled_warnings': [ 4267, ], + }], + ['OS=="linux"', { + 'configurations': { + 'Release_Base': { + #'cflags': [ '-fno-weak',], # get rid of symbols that strip doesn't remove. + # Don't do this for now since official builder will take care of it. That + # way symbols can still be uploaded to the crash server. + #'ldflags': [ '-s',], # strip local symbols from binary. + }, + }, + }], + ], + }, + ], + 'conditions': [ + # CrOS has a separate step to do this. + ['OS=="linux" and chromeos==0', + { 'targets': [ + { + 'target_name': 'pdf_linux_symbols', + 'type': 'none', + 'conditions': [ + ['linux_dump_symbols==1', { + 'actions': [ + { + 'action_name': 'dump_symbols', + 'inputs': [ + '<(DEPTH)/build/linux/dump_app_syms', + '<(PRODUCT_DIR)/dump_syms', + '<(PRODUCT_DIR)/libpdf.so', + ], + 'outputs': [ + '<(PRODUCT_DIR)/libpdf.so.breakpad.<(target_arch)', + ], + 'action': ['<(DEPTH)/build/linux/dump_app_syms', + '<(PRODUCT_DIR)/dump_syms', + '<(linux_strip_binary)', + '<(PRODUCT_DIR)/libpdf.so', + '<@(_outputs)'], + 'message': 'Dumping breakpad symbols to <(_outputs)', + 'process_outputs_as_sources': 1, + }, + ], + 'dependencies': [ + 'pdf', + '../breakpad/breakpad.gyp:dump_syms', + ], + }], + ], + }, + ], + },], # OS=="linux" and chromeos==0 + ['OS=="win" and fastbuild==0 and target_arch=="ia32" and syzyasan==1', { + 'variables': { + 'dest_dir': '<(PRODUCT_DIR)/syzygy', + }, + 'targets': [ + { + 'target_name': 'pdf_syzyasan', + 'type': 'none', + 'sources' : [], + 'dependencies': [ + 'pdf', + ], + # Instrument PDFium with SyzyAsan. + 'actions': [ + { + 'action_name': 'Instrument PDFium with SyzyAsan', + 'inputs': [ + '<(PRODUCT_DIR)/pdf.dll', + ], + 'outputs': [ + '<(dest_dir)/pdf.dll', + '<(dest_dir)/pdf.dll.pdb', + ], + 'action': [ + 'python', + '<(DEPTH)/chrome/tools/build/win/syzygy_instrument.py', + '--mode', 'asan', + '--input_executable', '<(PRODUCT_DIR)/pdf.dll', + '--input_symbol', '<(PRODUCT_DIR)/pdf.dll.pdb', + '--destination_dir', '<(dest_dir)', + ], + }, + ], + }, + ], + }], # OS=="win" and fastbuild==0 and target_arch=="ia32" and syzyasan==1 + ], +} diff --git a/xfa_test/pdf/pdf.h b/xfa_test/pdf/pdf.h new file mode 100644 index 0000000000..d797bbbaf5 --- /dev/null +++ b/xfa_test/pdf/pdf.h @@ -0,0 +1,24 @@ +// 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/cpp/module.h" + +namespace chrome_pdf { + +class PDFModule : public pp::Module { + public: + PDFModule(); + virtual ~PDFModule(); + + // pp::Module implementation. + virtual bool Init(); + virtual pp::Instance* CreateInstance(PP_Instance instance); +}; + +} // namespace chrome_pdf + +#endif // PDF_PDF_H_ diff --git a/xfa_test/pdf/pdf.rc b/xfa_test/pdf/pdf.rc new file mode 100644 index 0000000000..cbc98e1e4b --- /dev/null +++ b/xfa_test/pdf/pdf.rc @@ -0,0 +1,104 @@ +// Microsoft Visual C++ generated resource script.
+//
+#include "resource.h"
+
+#define APSTUDIO_READONLY_SYMBOLS
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 2 resource.
+//
+#include "afxres.h"
+
+/////////////////////////////////////////////////////////////////////////////
+#undef APSTUDIO_READONLY_SYMBOLS
+
+/////////////////////////////////////////////////////////////////////////////
+// English (U.S.) resources
+
+#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
+#ifdef _WIN32
+LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
+#pragma code_page(1252)
+#endif //_WIN32
+
+#ifdef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// TEXTINCLUDE
+//
+
+1 TEXTINCLUDE
+BEGIN
+ "resource.h\0"
+END
+
+2 TEXTINCLUDE
+BEGIN
+ "#include ""afxres.h""\r\n"
+ "\0"
+END
+
+3 TEXTINCLUDE
+BEGIN
+ "\r\n"
+ "\0"
+END
+
+#endif // APSTUDIO_INVOKED
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Version
+//
+
+VS_VERSION_INFO VERSIONINFO
+ FILEVERSION 1,0,0,1
+ PRODUCTVERSION 1,0,0,1
+ FILEFLAGSMASK 0x17L
+#ifdef _DEBUG
+ FILEFLAGS 0x1L
+#else
+ FILEFLAGS 0x0L
+#endif
+ FILEOS 0x4L
+ FILETYPE 0x2L
+ FILESUBTYPE 0x0L
+BEGIN
+ BLOCK "StringFileInfo"
+ BEGIN
+ BLOCK "040904e4"
+ BEGIN
+ VALUE "FileDescription", "Chrome PDF Viewer"
+ VALUE "FileVersion", "1, 0, 0, 1"
+ VALUE "InternalName", "pdf"
+ VALUE "LegalCopyright", "Copyright (C) 2010"
+ VALUE "MIMEType", "application/pdf"
+ VALUE "FileExtents", "pdf"
+ VALUE "FileOpenName", "Acrobat Portable Document Format"
+ VALUE "OriginalFilename", "pdf.dll"
+ VALUE "ProductName", "Chrome PDF Viewer"
+ VALUE "ProductVersion", "1, 0, 0, 1"
+ END
+ END
+ BLOCK "VarFileInfo"
+ BEGIN
+ VALUE "Translation", 0x409, 1252
+ END
+END
+
+#endif // English (U.S.) resources
+/////////////////////////////////////////////////////////////////////////////
+
+
+
+#ifndef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 3 resource.
+//
+
+
+/////////////////////////////////////////////////////////////////////////////
+#endif // not APSTUDIO_INVOKED
+
diff --git a/xfa_test/pdf/pdf_engine.h b/xfa_test/pdf/pdf_engine.h new file mode 100644 index 0000000000..cc25a299d8 --- /dev/null +++ b/xfa_test/pdf/pdf_engine.h @@ -0,0 +1,321 @@ +// 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 "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" + +namespace pp { +class InputEvent; +} + +const uint32 kBackgroundColor = 0xFFCCCCCC; + +namespace chrome_pdf { + +class Stream; + +#if defined(OS_MACOSX) +const uint32 kDefaultKeyModifier = PP_INPUTEVENT_MODIFIER_METAKEY; +#else // !OS_MACOSX +const uint32 kDefaultKeyModifier = PP_INPUTEVENT_MODIFIER_CONTROLKEY; +#endif // OS_MACOSX + +// Do one time initialization of the SDK. data is platform specific, on Windows +// it's the instance of the DLL and it's unused on other platforms. +bool InitializeSDK(void* data); +// 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: + // 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 available, uint32 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; + }; + + // 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) = 0; + 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 char* 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; + virtual bool IsSelecting() = 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 first visible page, or -1 if none are visible. + virtual int GetFirstVisiblePage() = 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; + // Gets the offset of the vertical scrollbar from the top in document + // coordinates. + virtual int GetVerticalScrollbarYPosition() = 0; + // Paints page thumbnail to the ImageData. + virtual void PaintThumbnail(pp::ImageData* image_data, int index) = 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; + + // 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; +}; + +// 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* Create(); +#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/xfa_test/pdf/pdfium/pdfium_assert_matching_enums.cc b/xfa_test/pdf/pdfium/pdfium_assert_matching_enums.cc new file mode 100644 index 0000000000..ef140cf7c9 --- /dev/null +++ b/xfa_test/pdf/pdfium/pdfium_assert_matching_enums.cc @@ -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. + +#include "base/basictypes.h" +#include "ppapi/c/pp_input_event.h" +#include "ppapi/c/private/ppb_pdf.h" +#include "third_party/pdfium/fpdfsdk/include/fpdf_fwlevent.h" +#include "third_party/pdfium/fpdfsdk/include/fpdf_sysfontinfo.h" +#include "ui/events/keycodes/keyboard_codes.h" + +#define COMPILE_ASSERT_MATCH(np_name, pdfium_name) \ + COMPILE_ASSERT(int(np_name) == int(pdfium_name), mismatching_enums) + +COMPILE_ASSERT_MATCH(PP_INPUTEVENT_MODIFIER_SHIFTKEY, FWL_EVENTFLAG_ShiftKey); +COMPILE_ASSERT_MATCH(PP_INPUTEVENT_MODIFIER_CONTROLKEY, + FWL_EVENTFLAG_ControlKey); +COMPILE_ASSERT_MATCH(PP_INPUTEVENT_MODIFIER_ALTKEY, FWL_EVENTFLAG_AltKey); +COMPILE_ASSERT_MATCH(PP_INPUTEVENT_MODIFIER_METAKEY, FWL_EVENTFLAG_MetaKey); +COMPILE_ASSERT_MATCH(PP_INPUTEVENT_MODIFIER_ISKEYPAD, FWL_EVENTFLAG_KeyPad); +COMPILE_ASSERT_MATCH(PP_INPUTEVENT_MODIFIER_ISAUTOREPEAT, + FWL_EVENTFLAG_AutoRepeat); +COMPILE_ASSERT_MATCH(PP_INPUTEVENT_MODIFIER_LEFTBUTTONDOWN, + FWL_EVENTFLAG_LeftButtonDown); +COMPILE_ASSERT_MATCH(PP_INPUTEVENT_MODIFIER_MIDDLEBUTTONDOWN, + FWL_EVENTFLAG_MiddleButtonDown); +COMPILE_ASSERT_MATCH(PP_INPUTEVENT_MODIFIER_RIGHTBUTTONDOWN, + FWL_EVENTFLAG_RightButtonDown); + +COMPILE_ASSERT_MATCH(ui::VKEY_BACK, FWL_VKEY_Back); +COMPILE_ASSERT_MATCH(ui::VKEY_TAB, FWL_VKEY_Tab); +COMPILE_ASSERT_MATCH(ui::VKEY_CLEAR, FWL_VKEY_Clear); +COMPILE_ASSERT_MATCH(ui::VKEY_RETURN, FWL_VKEY_Return); +COMPILE_ASSERT_MATCH(ui::VKEY_SHIFT, FWL_VKEY_Shift); +COMPILE_ASSERT_MATCH(ui::VKEY_CONTROL, FWL_VKEY_Control); +COMPILE_ASSERT_MATCH(ui::VKEY_MENU, FWL_VKEY_Menu); +COMPILE_ASSERT_MATCH(ui::VKEY_PAUSE, FWL_VKEY_Pause); +COMPILE_ASSERT_MATCH(ui::VKEY_CAPITAL, FWL_VKEY_Capital); +COMPILE_ASSERT_MATCH(ui::VKEY_KANA, FWL_VKEY_Kana); +COMPILE_ASSERT_MATCH(ui::VKEY_HANGUL, FWL_VKEY_Hangul); +COMPILE_ASSERT_MATCH(ui::VKEY_JUNJA, FWL_VKEY_Junja); +COMPILE_ASSERT_MATCH(ui::VKEY_FINAL, FWL_VKEY_Final); +COMPILE_ASSERT_MATCH(ui::VKEY_HANJA, FWL_VKEY_Hanja); +COMPILE_ASSERT_MATCH(ui::VKEY_KANJI, FWL_VKEY_Kanji); +COMPILE_ASSERT_MATCH(ui::VKEY_ESCAPE, FWL_VKEY_Escape); +COMPILE_ASSERT_MATCH(ui::VKEY_CONVERT, FWL_VKEY_Convert); +COMPILE_ASSERT_MATCH(ui::VKEY_NONCONVERT, FWL_VKEY_NonConvert); +COMPILE_ASSERT_MATCH(ui::VKEY_ACCEPT, FWL_VKEY_Accept); +COMPILE_ASSERT_MATCH(ui::VKEY_MODECHANGE, FWL_VKEY_ModeChange); +COMPILE_ASSERT_MATCH(ui::VKEY_SPACE, FWL_VKEY_Space); +COMPILE_ASSERT_MATCH(ui::VKEY_PRIOR, FWL_VKEY_Prior); +COMPILE_ASSERT_MATCH(ui::VKEY_NEXT, FWL_VKEY_Next); +COMPILE_ASSERT_MATCH(ui::VKEY_END, FWL_VKEY_End); +COMPILE_ASSERT_MATCH(ui::VKEY_HOME, FWL_VKEY_Home); +COMPILE_ASSERT_MATCH(ui::VKEY_LEFT, FWL_VKEY_Left); +COMPILE_ASSERT_MATCH(ui::VKEY_UP, FWL_VKEY_Up); +COMPILE_ASSERT_MATCH(ui::VKEY_RIGHT, FWL_VKEY_Right); +COMPILE_ASSERT_MATCH(ui::VKEY_DOWN, FWL_VKEY_Down); +COMPILE_ASSERT_MATCH(ui::VKEY_SELECT, FWL_VKEY_Select); +COMPILE_ASSERT_MATCH(ui::VKEY_PRINT, FWL_VKEY_Print); +COMPILE_ASSERT_MATCH(ui::VKEY_EXECUTE, FWL_VKEY_Execute); +COMPILE_ASSERT_MATCH(ui::VKEY_SNAPSHOT, FWL_VKEY_Snapshot); +COMPILE_ASSERT_MATCH(ui::VKEY_INSERT, FWL_VKEY_Insert); +COMPILE_ASSERT_MATCH(ui::VKEY_DELETE, FWL_VKEY_Delete); +COMPILE_ASSERT_MATCH(ui::VKEY_HELP, FWL_VKEY_Help); +COMPILE_ASSERT_MATCH(ui::VKEY_0, FWL_VKEY_0); +COMPILE_ASSERT_MATCH(ui::VKEY_1, FWL_VKEY_1); +COMPILE_ASSERT_MATCH(ui::VKEY_2, FWL_VKEY_2); +COMPILE_ASSERT_MATCH(ui::VKEY_3, FWL_VKEY_3); +COMPILE_ASSERT_MATCH(ui::VKEY_4, FWL_VKEY_4); +COMPILE_ASSERT_MATCH(ui::VKEY_5, FWL_VKEY_5); +COMPILE_ASSERT_MATCH(ui::VKEY_6, FWL_VKEY_6); +COMPILE_ASSERT_MATCH(ui::VKEY_7, FWL_VKEY_7); +COMPILE_ASSERT_MATCH(ui::VKEY_8, FWL_VKEY_8); +COMPILE_ASSERT_MATCH(ui::VKEY_9, FWL_VKEY_9); +COMPILE_ASSERT_MATCH(ui::VKEY_A, FWL_VKEY_A); +COMPILE_ASSERT_MATCH(ui::VKEY_B, FWL_VKEY_B); +COMPILE_ASSERT_MATCH(ui::VKEY_C, FWL_VKEY_C); +COMPILE_ASSERT_MATCH(ui::VKEY_D, FWL_VKEY_D); +COMPILE_ASSERT_MATCH(ui::VKEY_E, FWL_VKEY_E); +COMPILE_ASSERT_MATCH(ui::VKEY_F, FWL_VKEY_F); +COMPILE_ASSERT_MATCH(ui::VKEY_G, FWL_VKEY_G); +COMPILE_ASSERT_MATCH(ui::VKEY_H, FWL_VKEY_H); +COMPILE_ASSERT_MATCH(ui::VKEY_I, FWL_VKEY_I); +COMPILE_ASSERT_MATCH(ui::VKEY_J, FWL_VKEY_J); +COMPILE_ASSERT_MATCH(ui::VKEY_K, FWL_VKEY_K); +COMPILE_ASSERT_MATCH(ui::VKEY_L, FWL_VKEY_L); +COMPILE_ASSERT_MATCH(ui::VKEY_M, FWL_VKEY_M); +COMPILE_ASSERT_MATCH(ui::VKEY_N, FWL_VKEY_N); +COMPILE_ASSERT_MATCH(ui::VKEY_O, FWL_VKEY_O); +COMPILE_ASSERT_MATCH(ui::VKEY_P, FWL_VKEY_P); +COMPILE_ASSERT_MATCH(ui::VKEY_Q, FWL_VKEY_Q); +COMPILE_ASSERT_MATCH(ui::VKEY_R, FWL_VKEY_R); +COMPILE_ASSERT_MATCH(ui::VKEY_S, FWL_VKEY_S); +COMPILE_ASSERT_MATCH(ui::VKEY_T, FWL_VKEY_T); +COMPILE_ASSERT_MATCH(ui::VKEY_U, FWL_VKEY_U); +COMPILE_ASSERT_MATCH(ui::VKEY_V, FWL_VKEY_V); +COMPILE_ASSERT_MATCH(ui::VKEY_W, FWL_VKEY_W); +COMPILE_ASSERT_MATCH(ui::VKEY_X, FWL_VKEY_X); +COMPILE_ASSERT_MATCH(ui::VKEY_Y, FWL_VKEY_Y); +COMPILE_ASSERT_MATCH(ui::VKEY_Z, FWL_VKEY_Z); +COMPILE_ASSERT_MATCH(ui::VKEY_LWIN, FWL_VKEY_LWin); +COMPILE_ASSERT_MATCH(ui::VKEY_COMMAND, FWL_VKEY_Command); +COMPILE_ASSERT_MATCH(ui::VKEY_RWIN, FWL_VKEY_RWin); +COMPILE_ASSERT_MATCH(ui::VKEY_APPS, FWL_VKEY_Apps); +COMPILE_ASSERT_MATCH(ui::VKEY_SLEEP, FWL_VKEY_Sleep); +COMPILE_ASSERT_MATCH(ui::VKEY_NUMPAD0, FWL_VKEY_NumPad0); +COMPILE_ASSERT_MATCH(ui::VKEY_NUMPAD1, FWL_VKEY_NumPad1); +COMPILE_ASSERT_MATCH(ui::VKEY_NUMPAD2, FWL_VKEY_NumPad2); +COMPILE_ASSERT_MATCH(ui::VKEY_NUMPAD3, FWL_VKEY_NumPad3); +COMPILE_ASSERT_MATCH(ui::VKEY_NUMPAD4, FWL_VKEY_NumPad4); +COMPILE_ASSERT_MATCH(ui::VKEY_NUMPAD5, FWL_VKEY_NumPad5); +COMPILE_ASSERT_MATCH(ui::VKEY_NUMPAD6, FWL_VKEY_NumPad6); +COMPILE_ASSERT_MATCH(ui::VKEY_NUMPAD7, FWL_VKEY_NumPad7); +COMPILE_ASSERT_MATCH(ui::VKEY_NUMPAD8, FWL_VKEY_NumPad8); +COMPILE_ASSERT_MATCH(ui::VKEY_NUMPAD9, FWL_VKEY_NumPad9); +COMPILE_ASSERT_MATCH(ui::VKEY_MULTIPLY, FWL_VKEY_Multiply); +COMPILE_ASSERT_MATCH(ui::VKEY_ADD, FWL_VKEY_Add); +COMPILE_ASSERT_MATCH(ui::VKEY_SEPARATOR, FWL_VKEY_Separator); +COMPILE_ASSERT_MATCH(ui::VKEY_SUBTRACT, FWL_VKEY_Subtract); +COMPILE_ASSERT_MATCH(ui::VKEY_DECIMAL, FWL_VKEY_Decimal); +COMPILE_ASSERT_MATCH(ui::VKEY_DIVIDE, FWL_VKEY_Divide); +COMPILE_ASSERT_MATCH(ui::VKEY_F1, FWL_VKEY_F1); +COMPILE_ASSERT_MATCH(ui::VKEY_F2, FWL_VKEY_F2); +COMPILE_ASSERT_MATCH(ui::VKEY_F3, FWL_VKEY_F3); +COMPILE_ASSERT_MATCH(ui::VKEY_F4, FWL_VKEY_F4); +COMPILE_ASSERT_MATCH(ui::VKEY_F5, FWL_VKEY_F5); +COMPILE_ASSERT_MATCH(ui::VKEY_F6, FWL_VKEY_F6); +COMPILE_ASSERT_MATCH(ui::VKEY_F7, FWL_VKEY_F7); +COMPILE_ASSERT_MATCH(ui::VKEY_F8, FWL_VKEY_F8); +COMPILE_ASSERT_MATCH(ui::VKEY_F9, FWL_VKEY_F9); +COMPILE_ASSERT_MATCH(ui::VKEY_F10, FWL_VKEY_F10); +COMPILE_ASSERT_MATCH(ui::VKEY_F11, FWL_VKEY_F11); +COMPILE_ASSERT_MATCH(ui::VKEY_F12, FWL_VKEY_F12); +COMPILE_ASSERT_MATCH(ui::VKEY_F13, FWL_VKEY_F13); +COMPILE_ASSERT_MATCH(ui::VKEY_F14, FWL_VKEY_F14); +COMPILE_ASSERT_MATCH(ui::VKEY_F15, FWL_VKEY_F15); +COMPILE_ASSERT_MATCH(ui::VKEY_F16, FWL_VKEY_F16); +COMPILE_ASSERT_MATCH(ui::VKEY_F17, FWL_VKEY_F17); +COMPILE_ASSERT_MATCH(ui::VKEY_F18, FWL_VKEY_F18); +COMPILE_ASSERT_MATCH(ui::VKEY_F19, FWL_VKEY_F19); +COMPILE_ASSERT_MATCH(ui::VKEY_F20, FWL_VKEY_F20); +COMPILE_ASSERT_MATCH(ui::VKEY_F21, FWL_VKEY_F21); +COMPILE_ASSERT_MATCH(ui::VKEY_F22, FWL_VKEY_F22); +COMPILE_ASSERT_MATCH(ui::VKEY_F23, FWL_VKEY_F23); +COMPILE_ASSERT_MATCH(ui::VKEY_F24, FWL_VKEY_F24); +COMPILE_ASSERT_MATCH(ui::VKEY_NUMLOCK, FWL_VKEY_NunLock); +COMPILE_ASSERT_MATCH(ui::VKEY_SCROLL, FWL_VKEY_Scroll); +COMPILE_ASSERT_MATCH(ui::VKEY_LSHIFT, FWL_VKEY_LShift); +COMPILE_ASSERT_MATCH(ui::VKEY_RSHIFT, FWL_VKEY_RShift); +COMPILE_ASSERT_MATCH(ui::VKEY_LCONTROL, FWL_VKEY_LControl); +COMPILE_ASSERT_MATCH(ui::VKEY_RCONTROL, FWL_VKEY_RControl); +COMPILE_ASSERT_MATCH(ui::VKEY_LMENU, FWL_VKEY_LMenu); +COMPILE_ASSERT_MATCH(ui::VKEY_RMENU, FWL_VKEY_RMenu); +COMPILE_ASSERT_MATCH(ui::VKEY_BROWSER_BACK, FWL_VKEY_BROWSER_Back); +COMPILE_ASSERT_MATCH(ui::VKEY_BROWSER_FORWARD, FWL_VKEY_BROWSER_Forward); +COMPILE_ASSERT_MATCH(ui::VKEY_BROWSER_REFRESH, FWL_VKEY_BROWSER_Refresh); +COMPILE_ASSERT_MATCH(ui::VKEY_BROWSER_STOP, FWL_VKEY_BROWSER_Stop); +COMPILE_ASSERT_MATCH(ui::VKEY_BROWSER_SEARCH, FWL_VKEY_BROWSER_Search); +COMPILE_ASSERT_MATCH(ui::VKEY_BROWSER_FAVORITES, FWL_VKEY_BROWSER_Favorites); +COMPILE_ASSERT_MATCH(ui::VKEY_BROWSER_HOME, FWL_VKEY_BROWSER_Home); +COMPILE_ASSERT_MATCH(ui::VKEY_VOLUME_MUTE, FWL_VKEY_VOLUME_Mute); +COMPILE_ASSERT_MATCH(ui::VKEY_VOLUME_DOWN, FWL_VKEY_VOLUME_Down); +COMPILE_ASSERT_MATCH(ui::VKEY_VOLUME_UP, FWL_VKEY_VOLUME_Up); +COMPILE_ASSERT_MATCH(ui::VKEY_MEDIA_NEXT_TRACK, FWL_VKEY_MEDIA_NEXT_Track); +COMPILE_ASSERT_MATCH(ui::VKEY_MEDIA_PREV_TRACK, FWL_VKEY_MEDIA_PREV_Track); +COMPILE_ASSERT_MATCH(ui::VKEY_MEDIA_STOP, FWL_VKEY_MEDIA_Stop); +COMPILE_ASSERT_MATCH(ui::VKEY_MEDIA_PLAY_PAUSE, FWL_VKEY_MEDIA_PLAY_Pause); +COMPILE_ASSERT_MATCH(ui::VKEY_MEDIA_LAUNCH_MAIL, FWL_VKEY_MEDIA_LAUNCH_Mail); +COMPILE_ASSERT_MATCH(ui::VKEY_MEDIA_LAUNCH_MEDIA_SELECT, + FWL_VKEY_MEDIA_LAUNCH_MEDIA_Select); +COMPILE_ASSERT_MATCH(ui::VKEY_MEDIA_LAUNCH_APP1, FWL_VKEY_MEDIA_LAUNCH_APP1); +COMPILE_ASSERT_MATCH(ui::VKEY_MEDIA_LAUNCH_APP2, FWL_VKEY_MEDIA_LAUNCH_APP2); +COMPILE_ASSERT_MATCH(ui::VKEY_OEM_1, FWL_VKEY_OEM_1); +COMPILE_ASSERT_MATCH(ui::VKEY_OEM_PLUS, FWL_VKEY_OEM_Plus); +COMPILE_ASSERT_MATCH(ui::VKEY_OEM_COMMA, FWL_VKEY_OEM_Comma); +COMPILE_ASSERT_MATCH(ui::VKEY_OEM_MINUS, FWL_VKEY_OEM_Minus); +COMPILE_ASSERT_MATCH(ui::VKEY_OEM_PERIOD, FWL_VKEY_OEM_Period); +COMPILE_ASSERT_MATCH(ui::VKEY_OEM_2, FWL_VKEY_OEM_2); +COMPILE_ASSERT_MATCH(ui::VKEY_OEM_3, FWL_VKEY_OEM_3); +COMPILE_ASSERT_MATCH(ui::VKEY_OEM_4, FWL_VKEY_OEM_4); +COMPILE_ASSERT_MATCH(ui::VKEY_OEM_5, FWL_VKEY_OEM_5); +COMPILE_ASSERT_MATCH(ui::VKEY_OEM_6, FWL_VKEY_OEM_6); +COMPILE_ASSERT_MATCH(ui::VKEY_OEM_7, FWL_VKEY_OEM_7); +COMPILE_ASSERT_MATCH(ui::VKEY_OEM_8, FWL_VKEY_OEM_8); +COMPILE_ASSERT_MATCH(ui::VKEY_OEM_102, FWL_VKEY_OEM_102); +COMPILE_ASSERT_MATCH(ui::VKEY_PROCESSKEY, FWL_VKEY_ProcessKey); +COMPILE_ASSERT_MATCH(ui::VKEY_PACKET, FWL_VKEY_Packet); +COMPILE_ASSERT_MATCH(ui::VKEY_ATTN, FWL_VKEY_Attn); +COMPILE_ASSERT_MATCH(ui::VKEY_CRSEL, FWL_VKEY_Crsel); +COMPILE_ASSERT_MATCH(ui::VKEY_EXSEL, FWL_VKEY_Exsel); +COMPILE_ASSERT_MATCH(ui::VKEY_EREOF, FWL_VKEY_Ereof); +COMPILE_ASSERT_MATCH(ui::VKEY_PLAY, FWL_VKEY_Play); +COMPILE_ASSERT_MATCH(ui::VKEY_ZOOM, FWL_VKEY_Zoom); +COMPILE_ASSERT_MATCH(ui::VKEY_NONAME, FWL_VKEY_NoName); +COMPILE_ASSERT_MATCH(ui::VKEY_PA1, FWL_VKEY_PA1); +COMPILE_ASSERT_MATCH(ui::VKEY_OEM_CLEAR, FWL_VKEY_OEM_Clear); +COMPILE_ASSERT_MATCH(ui::VKEY_UNKNOWN, FWL_VKEY_Unknown); + +COMPILE_ASSERT_MATCH(PP_PRIVATEFONTCHARSET_ANSI, FXFONT_ANSI_CHARSET); +COMPILE_ASSERT_MATCH(PP_PRIVATEFONTCHARSET_DEFAULT, FXFONT_DEFAULT_CHARSET); +COMPILE_ASSERT_MATCH(PP_PRIVATEFONTCHARSET_SYMBOL, FXFONT_SYMBOL_CHARSET); +COMPILE_ASSERT_MATCH(PP_PRIVATEFONTCHARSET_SHIFTJIS, FXFONT_SHIFTJIS_CHARSET); +COMPILE_ASSERT_MATCH(PP_PRIVATEFONTCHARSET_HANGUL, FXFONT_HANGEUL_CHARSET); +COMPILE_ASSERT_MATCH(PP_PRIVATEFONTCHARSET_GB2312, FXFONT_GB2312_CHARSET); +COMPILE_ASSERT_MATCH(PP_PRIVATEFONTCHARSET_CHINESEBIG5, + FXFONT_CHINESEBIG5_CHARSET); diff --git a/xfa_test/pdf/pdfium/pdfium_engine.cc b/xfa_test/pdf/pdfium/pdfium_engine.cc new file mode 100644 index 0000000000..44e7052bf3 --- /dev/null +++ b/xfa_test/pdf/pdfium/pdfium_engine.cc @@ -0,0 +1,3884 @@ +// 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 "base/json/json_writer.h"
+#include "base/logging.h"
+#include "base/memory/scoped_ptr.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 "pdf/draw_utils.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 "third_party/pdfium/fpdfsdk/include/fpdf_ext.h"
+#include "third_party/pdfium/fpdfsdk/include/fpdf_flatten.h"
+#include "third_party/pdfium/fpdfsdk/include/fpdf_searchex.h"
+#include "third_party/pdfium/fpdfsdk/include/fpdf_sysfontinfo.h"
+#include "third_party/pdfium/fpdfsdk/include/fpdf_transformpage.h"
+#include "third_party/pdfium/fpdfsdk/include/fpdfedit.h"
+#include "third_party/pdfium/fpdfsdk/include/fpdfoom.h"
+#include "third_party/pdfium/fpdfsdk/include/fpdfppo.h"
+#include "third_party/pdfium/fpdfsdk/include/fpdfsave.h"
+#include "third_party/pdfium/fpdfsdk/include/pdfwindow/PDFWindow.h"
+#include "third_party/pdfium/fpdfsdk/include/pdfwindow/PWL_FontMap.h"
+#include "ui/events/keycodes/keyboard_codes.h"
+
+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 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
+
+// Copied from printing/units.cc because we don't want to depend on printing
+// since it brings in libpng which causes duplicate symbols with PDFium.
+const int kPointsPerInch = 72;
+const int kPixelsPerInch = 96;
+
+struct ClipBox {
+ float left;
+ float right;
+ float top;
+ float bottom;
+};
+
+int ConvertUnit(int value, int old_unit, int new_unit) {
+ // With integer arithmetic, to divide a value with correct rounding, you need
+ // to add half of the divisor value to the dividend value. You need to do the
+ // reverse with negative number.
+ if (value >= 0) {
+ return ((value * new_unit) + (old_unit / 2)) / old_unit;
+ } else {
+ return ((value * new_unit) - (old_unit / 2)) / old_unit;
+ }
+}
+
+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;
+
+struct PDFFontSubstitution {
+ const char* pdf_name;
+ const char* face;
+ bool bold;
+ bool italic;
+};
+
+PP_BrowserFont_Trusted_Weight WeightToBrowserFontTrustedWeight(int weight) {
+ COMPILE_ASSERT(PP_BROWSERFONT_TRUSTED_WEIGHT_100 == 0,
+ PP_BrowserFont_Trusted_Weight_Min);
+ COMPILE_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);
+
+ int i = 0;
+ while (CPWL_FontMap::defaultTTFMap[i].charset != -1) {
+ FPDF_AddInstalledFont(mapper,
+ CPWL_FontMap::defaultTTFMap[i].fontname,
+ CPWL_FontMap::defaultTTFMap[i].charset);
+ ++i;
+ }
+}
+
+const PDFFontSubstitution PDFFontSubstitutions[] = {
+ {"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},
+};
+
+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);
+ }
+
+ // Map from the standard PDF fonts to TrueType font names.
+ size_t i;
+ for (i = 0; i < arraysize(PDFFontSubstitutions); ++i) {
+ if (strcmp(face, PDFFontSubstitutions[i].pdf_name) == 0) {
+ description.set_face(PDFFontSubstitutions[i].face);
+ if (PDFFontSubstitutions[i].bold)
+ description.set_weight(PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD);
+ if (PDFFontSubstitutions[i].italic)
+ description.set_italic(true);
+ break;
+ }
+ }
+
+ if (i == arraysize(PDFFontSubstitutions)) {
+ // TODO(kochi): Pass the face in UTF-8. If face is not encoded in UTF-8,
+ // convert to UTF-8 before passing.
+ description.set_face(face);
+
+ 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)
+
+void OOM_Handler(_OOM_INFO*) {
+ // Kill the process. This is important for security, since the code doesn't
+ // NULL-check many memory allocations. If a malloc fails, returns NULL, and
+ // the buffer is then used, it provides a handy mapping of memory starting at
+ // address 0 for an attacker to utilize.
+ abort();
+}
+
+OOM_INFO g_oom_info = {
+ 1,
+ OOM_Handler
+};
+
+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_unsuppored_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());
+ }
+}
+
+// Calculate the scale factor between |content_rect| and a page of size
+// |src_width| x |src_height|.
+//
+// |scale_to_fit| is true, if we need to calculate the scale factor.
+// |content_rect| specifies the printable area of the destination page, with
+// origin at left-bottom. Values are in points.
+// |src_width| specifies the source page width in points.
+// |src_height| specifies the source page height in points.
+// |rotated| True if source page is rotated 90 degree or 270 degree.
+double CalculateScaleFactor(bool scale_to_fit,
+ const pp::Rect& content_rect,
+ double src_width, double src_height, bool rotated) {
+ if (!scale_to_fit || src_width == 0 || src_height == 0)
+ return 1.0;
+
+ double actual_source_page_width = rotated ? src_height : src_width;
+ double actual_source_page_height = rotated ? src_width : src_height;
+ double ratio_x = static_cast<double>(content_rect.width()) /
+ actual_source_page_width;
+ double ratio_y = static_cast<double>(content_rect.height()) /
+ actual_source_page_height;
+ return std::min(ratio_x, ratio_y);
+}
+
+// Compute source clip box boundaries based on the crop box / media box of
+// source page and scale factor.
+//
+// |page| Handle to the source page. Returned by FPDF_LoadPage function.
+// |scale_factor| specifies the scale factor that should be applied to source
+// clip box boundaries.
+// |rotated| True if source page is rotated 90 degree or 270 degree.
+// |clip_box| out param to hold the computed source clip box values.
+void CalculateClipBoxBoundary(FPDF_PAGE page, double scale_factor, bool rotated,
+ ClipBox* clip_box) {
+ if (!FPDFPage_GetCropBox(page, &clip_box->left, &clip_box->bottom,
+ &clip_box->right, &clip_box->top)) {
+ if (!FPDFPage_GetMediaBox(page, &clip_box->left, &clip_box->bottom,
+ &clip_box->right, &clip_box->top)) {
+ // Make the default size to be letter size (8.5" X 11"). We are just
+ // following the PDFium way of handling these corner cases. PDFium always
+ // consider US-Letter as the default page size.
+ float paper_width = 612;
+ float paper_height = 792;
+ clip_box->left = 0;
+ clip_box->bottom = 0;
+ clip_box->right = rotated ? paper_height : paper_width;
+ clip_box->top = rotated ? paper_width : paper_height;
+ }
+ }
+ clip_box->left *= scale_factor;
+ clip_box->right *= scale_factor;
+ clip_box->bottom *= scale_factor;
+ clip_box->top *= scale_factor;
+}
+
+// Calculate the clip box translation offset for a page that does need to be
+// scaled. All parameters are in points.
+//
+// |content_rect| specifies the printable area of the destination page, with
+// origin at left-bottom.
+// |source_clip_box| specifies the source clip box positions, relative to
+// origin at left-bottom.
+// |offset_x| and |offset_y| will contain the final translation offsets for the
+// source clip box, relative to origin at left-bottom.
+void CalculateScaledClipBoxOffset(const pp::Rect& content_rect,
+ const ClipBox& source_clip_box,
+ double* offset_x, double* offset_y) {
+ const float clip_box_width = source_clip_box.right - source_clip_box.left;
+ const float clip_box_height = source_clip_box.top - source_clip_box.bottom;
+
+ // Center the intended clip region to real clip region.
+ *offset_x = (content_rect.width() - clip_box_width) / 2 + content_rect.x() -
+ source_clip_box.left;
+ *offset_y = (content_rect.height() - clip_box_height) / 2 + content_rect.y() -
+ source_clip_box.bottom;
+}
+
+// Calculate the clip box offset for a page that does not need to be scaled.
+// All parameters are in points.
+//
+// |content_rect| specifies the printable area of the destination page, with
+// origin at left-bottom.
+// |rotation| specifies the source page rotation values which are N / 90
+// degrees.
+// |page_width| specifies the screen destination page width.
+// |page_height| specifies the screen destination page height.
+// |source_clip_box| specifies the source clip box positions, relative to origin
+// at left-bottom.
+// |offset_x| and |offset_y| will contain the final translation offsets for the
+// source clip box, relative to origin at left-bottom.
+void CalculateNonScaledClipBoxOffset(const pp::Rect& content_rect, int rotation,
+ int page_width, int page_height,
+ const ClipBox& source_clip_box,
+ double* offset_x, double* offset_y) {
+ // Align the intended clip region to left-top corner of real clip region.
+ switch (rotation) {
+ case 0:
+ *offset_x = -1 * source_clip_box.left;
+ *offset_y = page_height - source_clip_box.top;
+ break;
+ case 1:
+ *offset_x = 0;
+ *offset_y = -1 * source_clip_box.bottom;
+ break;
+ case 2:
+ *offset_x = page_width - source_clip_box.right;
+ *offset_y = 0;
+ break;
+ case 3:
+ *offset_x = page_height - source_clip_box.right;
+ *offset_y = page_width - source_clip_box.top;
+ break;
+ default:
+ NOTREACHED();
+ break;
+ }
+}
+
+// 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 (IsWhitespace(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'};
+ 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
+}
+
+} // namespace
+
+bool InitializeSDK(void* data) {
+ FPDF_InitLibrary(data);
+
+#if defined(OS_LINUX)
+ // Font loading doesn't work in the renderer sandbox in Linux.
+ FPDF_SetSystemFontInfo(&g_font_info);
+#endif
+
+ FSDK_SetOOMHandler(&g_oom_info);
+ FSDK_SetUnSpObjProcessHandler(&g_unsuppored_info);
+
+ return true;
+}
+
+void ShutdownSDK() {
+ 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),
+ current_find_index_(-1),
+ resume_find_index_(-1),
+ permissions_(0),
+ fpdf_availability_(NULL),
+ next_timer_id_(0),
+ last_page_mouse_down_(-1),
+ first_visible_page_(-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 _TEST_XFA
+ FPDF_FORMFILLINFO::FFI_EmailTo = Form_EmailTo;
+ FPDF_FORMFILLINFO::FFI_DisplayCaret = Form_DisplayCaret;
+ //FPDF_FORMFILLINFO::FFI_GetCurDocumentIndex = Form_GetCurDocumentIndex;
+ //FPDF_FORMFILLINFO::FFI_GetDocumentCount = Form_GetDocumentCount;
+ 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_ShowFileDialog = Form_ShowFileDialog;
+ FPDF_FORMFILLINFO::FFI_UploadTo = Form_UploadTo;
+ FPDF_FORMFILLINFO::FFI_DownloadFromURL = Form_DownloadFromURL;
+ // FPDF_FORMFILLINFO::FFI_GetFilePath = MyForm_GetFilePath;
+ FPDF_FORMFILLINFO::FFI_OpenFile = Form_OpenFile;
+ FPDF_FORMFILLINFO::FFI_GotoURL = Form_GotoURL;
+ FPDF_FORMFILLINFO::FFI_GetLanguage = Form_GetLanguage;
+#endif // _TEST_XFA
+ IPDF_JSPLATFORM::version = 1;
+ 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 (size_t i = 0; i < pages_.size(); ++i)
+ pages_[i]->Unload();
+
+ if (doc_) {
+ if (form_) {
+ FORM_DoDocumentAAction(form_, FPDFDOC_AACTION_WC);
+ }
+ FPDF_CloseDocument(doc_);
+ if (form_) {
+ FPDFDOC_ExitFormFillEnviroument(form_);
+ }
+ }
+
+ if (fpdf_availability_)
+ FPDFAvail_Destroy(fpdf_availability_);
+
+ STLDeleteElements(&pages_);
+}
+
+#ifdef _TEST_XFA
+
+typedef struct _FPDF_FILE {
+ FPDF_FILEHANDLER fileHandler;
+ FILE* file;
+}FPDF_FILE;
+
+
+void Sample_Release(FPDF_LPVOID clientData) {
+ if (!clientData) return;
+
+ fclose(((FPDF_FILE*)clientData)->file);
+ delete ((FPDF_FILE*)clientData);
+}
+
+FPDF_DWORD Sample_GetSize(FPDF_LPVOID clientData) {
+ if (!clientData) return 0;
+
+ long curPos = ftell(((FPDF_FILE*)clientData)->file);
+ fseek(((FPDF_FILE*)clientData)->file, 0, SEEK_END);
+ long size = ftell(((FPDF_FILE*)clientData)->file);
+ fseek(((FPDF_FILE*)clientData)->file, curPos, SEEK_SET);
+
+ return (FPDF_DWORD)size;
+}
+
+FPDF_RESULT Sample_ReadBlock(FPDF_LPVOID clientData, FPDF_DWORD offset, FPDF_LPVOID buffer, FPDF_DWORD size) {
+ if (!clientData) return -1;
+
+ fseek(((FPDF_FILE*)clientData)->file, (long)offset, SEEK_SET);
+ size_t readSize = fread(buffer, 1, size, ((FPDF_FILE*)clientData)->file);
+ return readSize == size ? 0 : -1;
+}
+
+FPDF_RESULT Sample_WriteBlock(FPDF_LPVOID clientData, FPDF_DWORD offset, FPDF_LPCVOID buffer, FPDF_DWORD size) {
+ if (!clientData) return -1;
+
+ fseek(((FPDF_FILE*)clientData)->file, (long)offset, SEEK_SET);
+ //Write data
+ size_t writeSize = fwrite(buffer, 1, size, ((FPDF_FILE*)clientData)->file);
+ return writeSize == size ? 0 : -1;
+}
+
+FPDF_RESULT Sample_Flush(FPDF_LPVOID clientData) {
+ if (!clientData) return -1;
+
+ //Flush file
+ fflush(((FPDF_FILE*)clientData)->file);
+
+ return 0;
+}
+
+FPDF_RESULT Sample_Truncate(FPDF_LPVOID clientData, FPDF_DWORD size) {
+ return 0;
+}
+
+
+void PDFiumEngine::Form_EmailTo(FPDF_FORMFILLINFO* pThis,
+ FPDF_FILEHANDLER* fileHandler,
+ 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*>(pThis);
+ engine->client_->Email(to_str, cc_str, bcc_str, subject_str, message_str);
+}
+
+void PDFiumEngine::Form_DisplayCaret(FPDF_FORMFILLINFO* pThis,
+ FPDF_PAGE page, FPDF_BOOL bVisible,
+ double left, double top, double right, double bottom) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(pThis);
+ 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);
+}
+
+//int PDFiumEngine::Form_GetCurDocumentIndex(FPDF_FORMFILLINFO* pThis) {
+// PDFiumEngine* engine = static_cast<PDFiumEngine*>(pThis);
+// engine->client_->RunJSCmd("alert(\"GetCurDocumentIndex\")");
+// return 0;
+//}
+//
+//int PDFiumEngine::Form_GetDocumentCount(FPDF_FORMFILLINFO* pThis) {
+// PDFiumEngine* engine = static_cast<PDFiumEngine*>(pThis);
+// engine->client_->RunJSCmd("alert(\"GetCurDocumentCount\")");
+// return 0;
+//}
+
+void PDFiumEngine::Form_SetCurrentPage(FPDF_FORMFILLINFO* pThis, FPDF_DOCUMENT document, int iCurPage) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(pThis);
+ pp::Rect pageViewRect = engine->GetPageContentsRect(iCurPage);
+ engine->ScrolledToYPosition(pageViewRect.height());
+ pp::Point pos(1, pageViewRect.height());
+ engine->SetScrollPosition(pos);
+}
+
+int PDFiumEngine::Form_GetCurrentPageIndex(FPDF_FORMFILLINFO* pThis, FPDF_DOCUMENT document) {
+ //int pageCount = FPDF_GetPageCount(document);
+ int pageIndex = -1;
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(pThis);
+ pageIndex = engine->GetMostVisiblePage();
+ return pageIndex;
+}
+
+void PDFiumEngine::Form_GetPageViewRect(FPDF_FORMFILLINFO* pThis,
+ FPDF_PAGE page,
+ double* left, double* top, double* right, double* bottom) {
+ PDFiumEngine* engine = static_cast<PDFiumEngine*>(pThis);
+ int page_index = engine->GetMostVisiblePage();
+ pp::Rect pageViewRect = engine->GetPageContentsRect(page_index);
+
+ *left = pageViewRect.x();
+ *right = pageViewRect.width() + pageViewRect.x();
+ *top = pageViewRect.y();
+ *bottom = pageViewRect.height();
+
+ std::string javascript = "alert(\"PageViewRect:"
+ + base::DoubleToString(*left) + ","
+ + base::DoubleToString(*right) + ","
+ + base::DoubleToString(*top) + ","
+ + base::DoubleToString(*bottom) + ","
+ + "\")";
+
+}
+
+int PDFiumEngine::Form_GetPlatform(FPDF_FORMFILLINFO* pThis,
+ 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)
+ + "\")";
+ //platform = new char[3];
+ //char tem[10] = "WIN";
+ //strncpy((char*)platform, tem, 3);
+
+ return 3;
+}
+
+FPDF_BOOL PDFiumEngine::Form_PopupMenu(FPDF_FORMFILLINFO* pThis,
+ FPDF_PAGE page,
+ FPDF_WIDGET hWidget,
+ int menuFlag, float x, float y) {
+ return false;
+}
+
+FPDF_BOOL PDFiumEngine::Form_PostRequestURL(FPDF_FORMFILLINFO* pThis, FPDF_WIDESTRING wsURL,
+ FPDF_WIDESTRING wsData, FPDF_WIDESTRING wsContentType,
+ FPDF_WIDESTRING wsEncode, FPDF_WIDESTRING wsHeader, FPDF_BSTR* respone) {
+ std::string url_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(wsURL));
+ std::string data_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(wsData));
+ std::string content_type_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(wsContentType));
+ std::string encode_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(wsEncode));
+ std::string header_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(wsHeader));
+
+ 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* pThis,
+ FPDF_WIDESTRING wsURL, FPDF_WIDESTRING wsData, FPDF_WIDESTRING wsEncode) {
+ std::string url_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(wsURL));
+ std::string data_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(wsData));
+ std::string encode_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(wsEncode));
+
+ std::string javascript = "alert(\"Put:"
+ + url_str + "," + data_str + "," + encode_str
+ + "\")";
+
+ return true;
+}
+
+//FPDF_BOOL PDFiumEngine::Form_ShowFileDialog(FPDF_FORMFILLINFO* pThis, FPDF_WIDESTRING wsTitle, FPDF_WIDESTRING wsFilter, FPDF_BOOL isOpen, FPDF_STRINGHANDLE pathArr) {
+// int tem = 1;
+// tem++;
+// return false;
+//}
+
+void PDFiumEngine::Form_UploadTo(FPDF_FORMFILLINFO* pThis, FPDF_FILEHANDLER* fileHandler, int fileFlag, FPDF_WIDESTRING uploadTo) {
+ std::string to_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(uploadTo));
+
+}
+
+FPDF_LPFILEHANDLER PDFiumEngine::Form_DownloadFromURL(FPDF_FORMFILLINFO* pThis, FPDF_WIDESTRING URL) {
+ std::string url_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(URL));
+
+
+ // Get URL data...
+ FILE* file = fopen(FXQA_TESTFILE("downloadtest.tem"), "w");
+ FPDF_FILE* pFileHander = new FPDF_FILE;
+ pFileHander->file = file;
+ pFileHander->fileHandler.clientData = pFileHander;
+ pFileHander->fileHandler.Flush = Sample_Flush;
+ pFileHander->fileHandler.GetSize = Sample_GetSize;
+ pFileHander->fileHandler.ReadBlock = Sample_ReadBlock;
+ pFileHander->fileHandler.Release = Sample_Release;
+ pFileHander->fileHandler.Truncate = Sample_Truncate;
+ pFileHander->fileHandler.WriteBlock = Sample_WriteBlock;
+
+ return &pFileHander->fileHandler;
+}
+
+//FPDF_BOOL PDFiumEngine::MyForm_GetFilePath(FPDF_FORMFILLINFO* pThis, FPDF_FILEHANDLER* pFileHandler, void* filePath, int length) {
+// //std::string filePath = engine->client_->FileOpen(fileFlag);
+// if (filePath == NULL) {
+// std::string javascript = "alert(\"GetFilePath:NULL\")";
+// PDFiumEngine* engine = static_cast<PDFiumEngine*>(pThis);
+// engine->client_->RunJSCmd(javascript);
+// return false;
+// }
+// std::string filePath_str = (char*)filePath;
+//
+// std::string javascript = "alert(\"GetFilePath:" + filePath_str + "\")";
+// PDFiumEngine* engine = static_cast<PDFiumEngine*>(pThis);
+// engine->client_->RunJSCmd(javascript);
+//
+// FILE* file = fopen(FXQA_TESTFILE("tem.xdp"), "w");
+// FPDF_FILE* pFileHander = new FPDF_FILE;
+// pFileHander->file = file;
+// pFileHander->fileHandler.clientData = pFileHander;
+// pFileHander->fileHandler.Flush = Sample_Flush;
+// pFileHander->fileHandler.GetSize = Sample_GetSize;
+// pFileHander->fileHandler.ReadBlock = Sample_ReadBlock;
+// pFileHander->fileHandler.Release = Sample_Release;
+// pFileHander->fileHandler.Truncate = Sample_Truncate;
+// pFileHander->fileHandler.WriteBlock = Sample_WriteBlock;
+//
+// pFileHandler = &pFileHander->fileHandler;
+//
+// return true;
+//}
+
+FPDF_FILEHANDLER* PDFiumEngine::Form_OpenFile(FPDF_FORMFILLINFO* pThis, int fileFlag, FPDF_WIDESTRING wsURL, const char* mode) {
+ std::string url_str = "NULL";
+ if (wsURL == NULL) {
+ url_str = "NULL";
+ }
+ else {
+ url_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(wsURL));
+ }
+ if (strncmp(mode, "wb", 2) == 0) {
+
+ FILE* file = fopen(FXQA_TESTFILE("tem.txt"), mode);
+ FPDF_FILE* pFileHander = new FPDF_FILE;
+ pFileHander->file = file;
+ pFileHander->fileHandler.clientData = pFileHander;
+ pFileHander->fileHandler.Flush = Sample_Flush;
+ pFileHander->fileHandler.GetSize = Sample_GetSize;
+ pFileHander->fileHandler.ReadBlock = Sample_ReadBlock;
+ pFileHander->fileHandler.Release = Sample_Release;
+ pFileHander->fileHandler.Truncate = Sample_Truncate;
+ pFileHander->fileHandler.WriteBlock = Sample_WriteBlock;
+ return &pFileHander->fileHandler;
+ }
+ else {
+ url_str = base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(wsURL));
+ }
+ return NULL;
+}
+
+
+void PDFiumEngine::Form_GotoURL(FPDF_FORMFILLINFO* pThis, FPDF_DOCUMENT document, FPDF_WIDESTRING wsURL) {
+ std::string url_str =
+ base::UTF16ToUTF8(reinterpret_cast<const base::char16*>(wsURL));
+ int pageCount = FPDF_GetPageCount(document);
+}
+
+int PDFiumEngine::Form_GetLanguage(FPDF_FORMFILLINFO* pThis, void* language, int length) {
+ return 0;
+}
+
+#endif // _TEST_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);
+}
+
+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) {
+ url_ = url;
+ headers_ = std::string();
+ return true;
+}
+
+bool PDFiumEngine::New(const char* url,
+ const char* headers) {
+ url_ = url;
+ if (!headers)
+ headers_ = std::string();
+ 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 (size_t i = 0; i < progressive_paints_.size(); ++i)
+ progressive_paints_[i].painted_ = false;
+}
+
+void PDFiumEngine::Paint(const pp::Rect& rect,
+ pp::ImageData* image_data,
+ std::vector<pp::Rect>* ready,
+ std::vector<pp::Rect>* 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;
+
+ leftover = leftover.Subtract(dirty_in_screen);
+
+ if (pages_[index]->available()) {
+ int progressive = GetProgressiveIndex(index);
+ if (progressive != -1 &&
+ 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();
+}
+
+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 (size_t i = 0; i < pending_pages_.size(); ++i) {
+ if (CheckPageAvailable(pending_pages_[i], &still_pending)) {
+ update_pages = true;
+ if (IsPageVisible(pending_pages_[i]))
+ client_->Invalidate(GetPageScreenRect(pending_pages_[i]));
+ }
+ }
+ 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;
+ }
+
+ 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);
+
+ FinishLoadingDocument();
+}
+
+void PDFiumEngine::FinishLoadingDocument() {
+ DCHECK(doc_loader_.IsDocumentComplete() && doc_);
+ 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) {
+ case FPDF_UNSP_DOC_XFAFORM:
+ //feature = "XFA";
+ break;
+ 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_.c_str(), !!result);
+}
+
+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 (size_t i = 0; i < deferred_page_unloads_.size(); ++i)
+ pages_[deferred_page_unloads_[i]]->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 = (static_cast<double>(bitmap_size.width()) * kPointsPerInch) /
+ print_settings.dpi;
+ double ratio_y =
+ (static_cast<double>(bitmap_size.height()) * kPointsPerInch) /
+ print_settings.dpi;
+
+ // 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 (size_t i = 0; i < page_numbers.size(); ++i) {
+ uint32_t page_number = page_numbers[i];
+ 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,
+ static_cast<int>(kPointsPerInch),
+ print_settings.dpi);
+ int height_in_pixels = ConvertUnit(source_page_height,
+ static_cast<int>(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) {
+ int page_count = FPDF_GetPageCount(doc);
+ bool flatten_succeeded = true;
+ for (int i = 0; i < page_count; ++i) {
+ FPDF_PAGE page = FPDF_LoadPage(doc, i);
+ DCHECK(page);
+ if (page) {
+ int flatten_ret = FPDFPage_Flatten(page, FLAT_PRINT);
+ FPDF_ClosePage(page);
+ if (flatten_ret == FLATTEN_FAIL) {
+ flatten_succeeded = false;
+ break;
+ }
+ } else {
+ flatten_succeeded = false;
+ break;
+ }
+ }
+ if (!flatten_succeeded) {
+ FPDF_CloseDocument(doc);
+ return pp::Buffer_Dev();
+ }
+
+ pp::Buffer_Dev 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::IntToString(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::IntToString(page_ranges[index].last_page_number + 1));
+ }
+ }
+
+ std::vector<uint32_t> page_numbers =
+ GetPageNumbersFromPrintPageNumberRange(page_ranges, page_range_count);
+ for (size_t i = 0; i < page_numbers.size(); ++i) {
+ uint32_t page_number = page_numbers[i];
+ pages_[page_number]->GetPage();
+ if (!IsPageVisible(page_numbers[i]))
+ 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, PDFiumPage::LinkTarget* target) {
+ // First figure out which page this is in.
+ pp::Point mouse_point = event.GetPosition();
+ pp::Point point(
+ static_cast<int>((mouse_point.x() + position_.x()) / current_zoom_),
+ static_cast<int>((mouse_point.y() + position_.y()) / current_zoom_));
+ return GetCharIndex(point, page_index, char_index, target);
+}
+
+PDFiumPage::Area PDFiumEngine::GetCharIndex(
+ const pp::Point& point,
+ int* page_index,
+ int* char_index,
+ PDFiumPage::LinkTarget* target) {
+ int page = -1;
+ for (size_t i = 0; i < visible_pages_.size(); ++i) {
+ if (pages_[visible_pages_[i]]->rect().Contains(point)) {
+ page = visible_pages_[i];
+ break;
+ }
+ }
+ if (page == -1)
+ return PDFiumPage::NONSELECTABLE_AREA;
+
+ // If the page hasn't finished rendering, calling into the page sometimes
+ // leads to hangs.
+ for (size_t i = 0; i < progressive_paints_.size(); ++i) {
+ if (progressive_paints_[i].page_index == page)
+ return PDFiumPage::NONSELECTABLE_AREA;
+ }
+
+ *page_index = page;
+ return pages_[page]->GetCharIndex(point, current_rotation_, char_index,
+ target);
+}
+
+bool PDFiumEngine::OnMouseDown(const pp::MouseInputEvent& event) {
+ if (event.GetButton() != PP_INPUTEVENT_MOUSEBUTTON_LEFT)
+ return false;
+
+ SelectionChangeInvalidator selection_invalidator(this);
+ selection_.clear();
+
+ int page_index = -1;
+ int char_index = -1;
+ PDFiumPage::LinkTarget target;
+ PDFiumPage::Area area = GetCharIndex(event, &page_index,
+ &char_index, &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);
+ int control = FPDPage_HasFormFieldAtPoint(
+ form_, pages_[page_index]->GetPage(), page_x, page_y);
+ if (control > FPDF_FORMFIELD_UNKNOWN) { // returns -1 sometimes...
+#ifdef _TEST_XFA
+ client_->FormTextFieldFocusChange(control == FPDF_FORMFIELD_TEXTFIELD ||
+ control == FPDF_FORMFIELD_COMBOBOX ||
+ control == FPDF_FORMFIELD_XFA);
+#else
+ client_->FormTextFieldFocusChange(control == FPDF_FORMFIELD_TEXTFIELD ||
+ control == FPDF_FORMFIELD_COMBOBOX);
+#endif
+ 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) {
+ selecting_ = 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;
+ PDFiumPage::LinkTarget target;
+ PDFiumPage::Area area =
+ GetCharIndex(event, &page_index, &char_index, &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;
+
+ selecting_ = false;
+ return true;
+}
+
+bool PDFiumEngine::OnMouseMove(const pp::MouseInputEvent& event) {
+ int page_index = -1;
+ int char_index = -1;
+ PDFiumPage::LinkTarget target;
+ PDFiumPage::Area area =
+ GetCharIndex(event, &page_index, &char_index, &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:
+ cursor = PP_CURSORTYPE_POINTER;
+ 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);
+ int control = FPDPage_HasFormFieldAtPoint(
+ form_, pages_[page_index]->GetPage(), page_x, page_y);
+ switch (control) {
+ 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:
+ break;
+ }
+ }
+
+ 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_.size() == 0)
+ 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.
+ selection_[last].SetCharCount(-selection_[last].char_index());
+
+ // 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 char* text, bool case_sensitive) {
+ // We can get a call to StartFind 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 = false;
+ int character_to_start_searching_from = 0;
+ if (current_find_text_ != text) { // First time we search for this text.
+ first_search = true;
+ 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.
+ if (resume_find_index_ != -1) {
+ current_find_index_ = resume_find_index_;
+ resume_find_index_ = -1;
+ }
+ } 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;
+ unsigned short* data =
+ reinterpret_cast<unsigned short*>(WriteInto(&page_text, text_length + 1));
+ FPDFText_GetText(pages_[current_page]->GetTextPage(),
+ character_to_start_searching_from,
+ text_length,
+ data);
+ std::vector<PDFEngine::Client::SearchStringResult> results;
+ client_->SearchString(
+ page_text.c_str(), term.c_str(), case_sensitive, &results);
+ for (size_t i = 0; i < results.size(); ++i) {
+ // 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 = results[i].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 + results[i].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 i;
+ int page_index = result.page_index();
+ int char_index = result.char_index();
+ for (i = 0; i < find_results_.size(); ++i) {
+ if (find_results_[i].page_index() > page_index ||
+ (find_results_[i].page_index() == page_index &&
+ find_results_[i].char_index() > char_index)) {
+ break;
+ }
+ }
+ find_results_.insert(find_results_.begin() + i, result);
+ UpdateTickMarks();
+
+ if (current_find_index_ == -1 && resume_find_index_ == -1) {
+ // Select the first match.
+ SelectFindResult(true);
+ } else if (static_cast<int>(i) <= current_find_index_) {
+ // Update the current match index
+ current_find_index_++;
+ client_->NotifySelectedFindResultChanged(current_find_index_);
+ }
+ 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.
+ if (forward) {
+ if (++current_find_index_ == static_cast<int>(find_results_.size()))
+ current_find_index_ = 0;
+ } else {
+ if (--current_find_index_ < 0) {
+ current_find_index_ = find_results_.size() - 1;
+ }
+ }
+
+ // Update the selection before telling the client to scroll, since it could
+ // paint then.
+ selection_.clear();
+ selection_.push_back(find_results_[current_find_index_]);
+
+ // If the result is not in view, scroll to it.
+ size_t i;
+ 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 = find_results_[current_find_index_].
+ GetScreenRects(pp::Point(), 1.0, current_rotation_);
+ for (i = 0; i < rects.size(); ++i)
+ bounding_rect = bounding_rect.Union(rects[i]);
+ 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_);
+
+ 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_ = -1;
+ current_find_text_.clear();
+ UpdateTickMarks();
+ find_factory_.CancelAll();
+}
+
+void PDFiumEngine::UpdateTickMarks() {
+ std::vector<pp::Rect> tickmarks;
+ for (size_t i = 0; i < find_results_.size(); ++i) {
+ pp::Rect rect;
+ // Always use an origin of 0,0 since scroll positions don't affect tickmark.
+ std::vector<pp::Rect> rects = find_results_[i].GetScreenRects(
+ pp::Point(0, 0), current_zoom_, current_rotation_);
+ for (size_t j = 0; j < rects.size(); ++j)
+ rect = rect.Union(rects[j]);
+ tickmarks.push_back(rect);
+ }
+
+ 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;
+
+ // 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_;
+ resume_find_index_ = current_find_index_;
+
+ InvalidateAllPages();
+
+ if (!current_find_text.empty())
+ StartFind(current_find_text.c_str(), false);
+}
+
+void PDFiumEngine::RotateCounterclockwise() {
+ current_rotation_ = (current_rotation_ - 1) % 4;
+
+ // 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_;
+ resume_find_index_ = current_find_index_;
+
+ InvalidateAllPages();
+
+ if (!current_find_text.empty())
+ StartFind(current_find_text.c_str(), false);
+}
+
+void PDFiumEngine::InvalidateAllPages() {
+ CancelPaints();
+ StopFind();
+ LoadPageInfo(true);
+ client_->Invalidate(pp::Rect(plugin_size_));
+}
+
+std::string PDFiumEngine::GetSelectedText() {
+ base::string16 result;
+ 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() + result;
+ } else {
+ result.append(selection_[i].GetText());
+ }
+ }
+
+ FormatStringWithHyphens(&result);
+ FormatStringForOS(&result);
+ return base::UTF16ToUTF8(result);
+}
+
+std::string PDFiumEngine::GetLinkAtPosition(const pp::Point& point) {
+ int temp;
+ PDFiumPage::LinkTarget target;
+ pp::Point point_in_page(
+ static_cast<int>((point.x() + position_.x()) / current_zoom_),
+ static_cast<int>((point.y() + position_.y()) / current_zoom_));
+ PDFiumPage::Area area = GetCharIndex(point_in_page, &temp, &temp, &target);
+ if (area == PDFiumPage::WEBLINK_AREA)
+ return target.url;
+ return std::string();
+}
+
+bool PDFiumEngine::IsSelecting() {
+ return selecting_;
+}
+
+bool PDFiumEngine::HasPermission(DocumentPermission permission) const {
+ switch (permission) {
+ case PERMISSION_COPY:
+ return (permissions_ & kPDFPermissionCopyMask) != 0;
+ case PERMISSION_COPY_ACCESSIBLE:
+ return (permissions_ & kPDFPermissionCopyAccessibleMask) != 0;
+ case PERMISSION_PRINT_LOW_QUALITY:
+ return (permissions_ & kPDFPermissionPrintLowQualityMask) != 0;
+ case PERMISSION_PRINT_HIGH_QUALITY:
+ return (permissions_ & kPDFPermissionPrintLowQualityMask) != 0 &&
+ (permissions_ & kPDFPermissionPrintHighQualityMask) != 0;
+ default:
+ return true;
+ };
+}
+
+void PDFiumEngine::SelectAll() {
+ SelectionChangeInvalidator selection_invalidator(this);
+
+ selection_.clear();
+ for (size_t i = 0; i < pages_.size(); ++i)
+ if (pages_[i]->available()) {
+ selection_.push_back(PDFiumRange(pages_[i], 0,
+ pages_[i]->GetCharCount()));
+ }
+}
+
+int PDFiumEngine::GetNumberOfPages() {
+ return pages_.size();
+}
+
+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::GetFirstVisiblePage() {
+ CalculateVisiblePages();
+ return first_visible_page_;
+}
+
+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::PaintThumbnail(pp::ImageData* image_data, int index) {
+ FPDF_BITMAP bitmap = FPDFBitmap_CreateEx(
+ image_data->size().width(), image_data->size().height(),
+ FPDFBitmap_BGRx, image_data->data(), image_data->stride());
+
+ if (pages_[index]->available()) {
+ FPDFBitmap_FillRect(bitmap, 0, 0, image_data->size().width(),
+ image_data->size().height(), 0xFFFFFFFF);
+
+ FPDF_RenderPageBitmap(
+ bitmap, pages_[index]->GetPage(), 0, 0, image_data->size().width(),
+ image_data->size().height(), 0, GetRenderingFlags());
+ } else {
+ FPDFBitmap_FillRect(bitmap, 0, 0, image_data->size().width(),
+ image_data->size().height(), kPendingPageColor);
+ }
+
+ FPDFBitmap_Destroy(bitmap);
+}
+
+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.get(), &page_json);
+ return page_json;
+}
+
+bool PDFiumEngine::GetPrintScaling() {
+ return !!FPDF_VIEWERREF_GetPrintScaling(doc_);
+}
+
+void PDFiumEngine::AppendBlankPages(int num_pages) {
+ DCHECK(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 =
+ page_rect.width() * kPointsPerInch / kPixelsPerInch;
+ double height_in_points =
+ page_rect.height() * kPointsPerInch / kPixelsPerInch;
+ 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 = NULL;
+ 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_ != NULL;
+}
+
+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_);
+
+ if (!form_) {
+ // Only returns 0 when data isn't available. If form data is downloaded, or
+ // if this isn't a form, returns positive values.
+ if (!doc_loader_.IsDocumentComplete() &&
+ !FPDFAvail_IsFormAvail(fpdf_availability_, &download_hints_)) {
+ return;
+ }
+
+ form_ = FPDFDOC_InitFormFillEnviroument(
+ doc_, static_cast<FPDF_FORMFILLINFO*>(this));
+#ifdef _TEST_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 {
+ pages_.push_back(new PDFiumPage(this, i, page_rect, doc_complete));
+ }
+ }
+
+ 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();
+
+ if (visible_pages_.size() == 0)
+ first_visible_page_ = -1;
+ else
+ first_visible_page_ = visible_pages_.front();
+
+ int most_visible_page = first_visible_page_;
+ // Check if the next page is more visible than the first one.
+ if (most_visible_page != -1 &&
+ pages_.size() > 0 &&
+ 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 {
+ for (size_t i = 0; i < visible_pages_.size(); ++i) {
+ if (visible_pages_[i] == index)
+ return true;
+ }
+
+ return false;
+}
+
+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>(
+ width_in_points * kPixelsPerInch / kPointsPerInch);
+ int height_in_pixels = static_cast<int>(
+ height_in_points * kPixelsPerInch / kPointsPerInch);
+ 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) {
+#if defined(OS_LINUX)
+ g_last_instance_id = client_->GetPluginInstance()->pp_instance();
+#endif
+
+ int rv;
+ int page_index = progressive_paints_[progressive_index].page_index;
+ last_progressive_start_time_ = base::Time::Now();
+ if (progressive_paints_[progressive_index].bitmap) {
+ rv = FPDF_RenderPage_Continue(
+ pages_[page_index]->GetPage(), static_cast<IFSDK_PAUSE*>(this));
+ } else {
+ pp::Rect dirty = progressive_paints_[progressive_index].rect;
+ progressive_paints_[progressive_index].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(progressive_paints_[progressive_index].bitmap, start_x,
+ start_y, size_x, size_y, 0xFFFFFFFF);
+ rv = FPDF_RenderPageBitmap_Start(
+ progressive_paints_[progressive_index].bitmap,
+ pages_[page_index]->GetPage(), start_x, start_y, size_x, size_y,
+ current_rotation_,
+ GetRenderingFlags(), static_cast<IFSDK_PAUSE*>(this));
+ }
+ return rv != FPDF_RENDER_TOBECOUNTINUED;
+}
+
+void PDFiumEngine::FinishPaint(int progressive_index,
+ pp::ImageData* 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 (size_t i = 0; i < progressive_paints_.size(); ++i) {
+ FPDF_RenderPage_Close(pages_[progressive_paints_[i].page_index]->GetPage());
+ FPDFBitmap_Destroy(progressive_paints_[i].bitmap);
+ }
+ progressive_paints_.clear();
+}
+
+void PDFiumEngine::FillPageSides(int progressive_index) {
+ 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(), kBackgroundColor);
+ }
+
+ 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(), kBackgroundColor);
+ }
+
+ // 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(), kBackgroundColor);
+}
+
+void PDFiumEngine::PaintPageShadow(int progressive_index,
+ pp::ImageData* 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) {
+ 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, ®ion, &stride);
+
+ std::vector<pp::Rect> highlighted_rects;
+ pp::Rect visible_rect = GetVisibleRect();
+ for (size_t k = 0; k < selection_.size(); ++k) {
+ if (selection_[k].page_index() != page_index)
+ continue;
+ std::vector<pp::Rect> rects = selection_[k].GetScreenRects(
+ visible_rect.point(), current_zoom_, current_rotation_);
+ for (size_t j = 0; j < rects.size(); ++j) {
+ pp::Rect visible_selection = rects[j].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 (size_t k = 0; k < form_highlights_.size(); ++k) {
+ pp::Rect visible_selection = form_highlights_[k].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, ®ion, &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 (size_t i = 0; i < highlighted_rects->size(); ++i)
+ new_rect = new_rect.Subtract((*highlighted_rects)[i]);
+
+ 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* pixel = static_cast<uint8*>(buffer) + y * stride + x * 4;
+ // This is our highlight color.
+ pixel[0] = static_cast<uint8>(
+ pixel[0] * (kHighlightColorB / 255.0));
+ pixel[1] = static_cast<uint8>(
+ pixel[1] * (kHighlightColorG / 255.0));
+ pixel[2] = static_cast<uint8>(
+ 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 (size_t i = 0; i < old_selections_.size(); ++i)
+ old_selections_[i].Offset(offset);
+
+ std::vector<pp::Rect> new_selections;
+ GetVisibleSelectionsScreenRects(&new_selections);
+ for (size_t i = 0; i < new_selections.size(); ++i) {
+ for (size_t j = 0; j < old_selections_.size(); ++j) {
+ if (!old_selections_[j].IsEmpty() &&
+ new_selections[i] == old_selections_[j]) {
+ // Rectangle was selected before and after, so no need to invalidate it.
+ // Mark the rectangles by setting them to empty.
+ new_selections[i] = old_selections_[j] = pp::Rect();
+ break;
+ }
+ }
+ }
+
+ for (size_t i = 0; i < old_selections_.size(); ++i) {
+ if (!old_selections_[i].IsEmpty())
+ engine_->client_->Invalidate(old_selections_[i]);
+ }
+ for (size_t i = 0; i < new_selections.size(); ++i) {
+ if (!new_selections[i].IsEmpty())
+ engine_->client_->Invalidate(new_selections[i]);
+ }
+ engine_->OnSelectionChanged();
+}
+
+void
+PDFiumEngine::SelectionChangeInvalidator::GetVisibleSelectionsScreenRects(
+ std::vector<pp::Rect>* rects) {
+ pp::Rect visible_rect = engine_->GetVisibleRect();
+ for (size_t i = 0; i < engine_->selection_.size(); ++i) {
+ int page_index = engine_->selection_[i].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 =
+ engine_->selection_[i].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) {
+ if (area == PDFiumPage::WEBLINK_AREA)
+ return target_.url == target.url;
+ if (area == PDFiumPage::DOCLINK_AREA)
+ return target_.page == target.page;
+ return true;
+ }
+ return false;
+}
+
+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 (size_t i = 0; i < visible_pages_.size(); ++i) {
+ if (pages_[visible_pages_[i]]->GetPage() == page)
+ return visible_pages_[i];
+ }
+ 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 double scale_factor = CalculateScaleFactor(fit_to_page, content_rect,
+ src_page_width,
+ src_page_height, rotated);
+
+ // Calculate positions for the clip box.
+ ClipBox source_clip_box;
+ CalculateClipBoxBoundary(page, scale_factor, rotated, &source_clip_box);
+
+ // Calculate the translation offset values.
+ double offset_x = 0;
+ double offset_y = 0;
+ if (fit_to_page) {
+ CalculateScaledClipBoxOffset(content_rect, source_clip_box, &offset_x,
+ &offset_y);
+ } else {
+ CalculateNonScaledClipBoxOffset(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 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>(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, kBackgroundColor));
+
+ 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() {
+ if (HasPermission(PDFEngine::PERMISSION_COPY))
+ pp::PDF::SetSelectedText(GetPluginInstance(), GetSelectedText().c_str());
+}
+
+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) {
+ DCHECK(length == 0); // Don't handle attachments; 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_;
+}
+
+PDFEngineExports* PDFEngineExports::Create() {
+ return new PDFiumEngineExports;
+}
+
+namespace {
+
+int CalculatePosition(FPDF_PAGE page,
+ const PDFiumEngineExports::RenderingSettings& settings,
+ pp::Rect* dest) {
+ int page_width = static_cast<int>(
+ FPDF_GetPageWidth(page) * settings.dpi_x / kPointsPerInch);
+ int page_height = static_cast<int>(
+ FPDF_GetPageHeight(page) * settings.dpi_y / kPointsPerInch);
+
+ // 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
+
+#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. PDFs generated by Cairo (used by Chrome OS to generate
+ // a PDF output from a webpage) result in very large metafiles and the
+ // rendering using FPDF_RenderPage is incorrect. In this case, render as a
+ // bitmap. Note that this code does not kick in for PDFs printed from Chrome
+ // because in that case we create a temp PDF first before printing and this
+ // temp PDF does not have a creator string that starts with "cairo".
+ base::string16 creator;
+ size_t buffer_bytes = FPDF_GetMetaText(doc, "Creator", NULL, 0);
+ if (buffer_bytes > 1) {
+ FPDF_GetMetaText(
+ doc, "Creator", WriteInto(&creator, buffer_bytes + 1), buffer_bytes);
+ }
+ bool use_bitmap = false;
+ if (StartsWith(creator, L"cairo", false))
+ use_bitmap = true;
+
+ // Another 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 (use_bitmap ||
+ (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 // 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/xfa_test/pdf/pdfium/pdfium_engine.h b/xfa_test/pdf/pdfium/pdfium_engine.h new file mode 100644 index 0000000000..242c33df27 --- /dev/null +++ b/xfa_test/pdf/pdfium/pdfium_engine.h @@ -0,0 +1,687 @@ +// 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 <map> +#include <string> +#include <utility> +#include <vector> + +#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 "third_party/pdfium/fpdfsdk/include/fpdf_dataavail.h" +#include "third_party/pdfium/fpdfsdk/include/fpdf_progressive.h" +#include "third_party/pdfium/fpdfsdk/include/fpdfformfill.h" +#include "third_party/pdfium/fpdfsdk/include/fpdfview.h" + +#define _TEST_XFA +#ifdef _TEST_XFA +# if defined(WIN32) +# define FXQA_TESTFILE(filename) "E:/"#filename +# else +# define FXQA_TESTFILE(filename) "/home/"#filename +# endif +#endif + +namespace pp { +class KeyboardInputEvent; +class MouseInputEvent; +} + +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); + virtual ~PDFiumEngine(); + + // PDFEngine implementation. + virtual bool New(const char* url); + virtual bool New(const char* url, + const char* headers); + virtual void PageOffsetUpdated(const pp::Point& page_offset); + virtual void PluginSizeUpdated(const pp::Size& size); + virtual void ScrolledToXPosition(int position); + virtual void ScrolledToYPosition(int position); + virtual void PrePaint(); + virtual void Paint(const pp::Rect& rect, + pp::ImageData* image_data, + std::vector<pp::Rect>* ready, + std::vector<pp::Rect>* pending); + virtual void PostPaint(); + virtual bool HandleDocumentLoad(const pp::URLLoader& loader); + virtual bool HandleEvent(const pp::InputEvent& event); + virtual uint32_t QuerySupportedPrintOutputFormats(); + virtual void PrintBegin(); + virtual pp::Resource PrintPages( + const PP_PrintPageNumberRange_Dev* page_ranges, + uint32_t page_range_count, + const PP_PrintSettings_Dev& print_settings); + virtual void PrintEnd(); + virtual void StartFind(const char* text, bool case_sensitive); + virtual bool SelectFindResult(bool forward); + virtual void StopFind(); + virtual void ZoomUpdated(double new_zoom_level); + virtual void RotateClockwise(); + virtual void RotateCounterclockwise(); + virtual std::string GetSelectedText(); + virtual std::string GetLinkAtPosition(const pp::Point& point); + virtual bool IsSelecting(); + virtual bool HasPermission(DocumentPermission permission) const; + virtual void SelectAll(); + virtual int GetNumberOfPages(); + virtual int GetNamedDestinationPage(const std::string& destination); + virtual int GetFirstVisiblePage(); + virtual int GetMostVisiblePage(); + virtual pp::Rect GetPageRect(int index); + virtual pp::Rect GetPageContentsRect(int index); + virtual int GetVerticalScrollbarYPosition() { return position_.y(); } + virtual void PaintThumbnail(pp::ImageData* image_data, int index); + virtual void SetGrayscale(bool grayscale); + virtual void OnCallback(int id); + virtual std::string GetPageAsJSON(int index); + virtual bool GetPrintScaling(); + virtual void AppendBlankPages(int num_pages); + virtual void AppendPage(PDFEngine* engine, int index); + virtual pp::Point GetScrollPosition(); + virtual void SetScrollPosition(const pp::Point& position); + virtual bool IsProgressiveLoad(); + + // DocumentLoader::Client implementation. + virtual pp::Instance* GetPluginInstance(); + virtual pp::URLLoader CreateURLLoader(); + virtual void OnPartialDocumentLoaded(); + virtual void OnPendingRequestComplete(); + virtual void OnNewDataAvailable(); + virtual void OnDocumentComplete(); + + 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); + }; + + 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 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 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, + PDFiumPage::LinkTarget* target); + PDFiumPage::Area GetCharIndex(const pp::Point& point, + int* page_index, + int* char_index, + 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; + + // Returns a page's rect in screen coordinates, as well as its surrounding + // border areas and bottom separator. + pp::Rect GetPageScreenRect(int page_index) 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(); + + // 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 _TEST_XFA + static void Form_EmailTo(FPDF_FORMFILLINFO* pThis, FPDF_FILEHANDLER* fileHandler, + FPDF_WIDESTRING to, FPDF_WIDESTRING subject, FPDF_WIDESTRING cc, FPDF_WIDESTRING bcc, FPDF_WIDESTRING message); + static void Form_DisplayCaret(FPDF_FORMFILLINFO* pThis, FPDF_PAGE page, FPDF_BOOL bVisible, double left, double top, double right, double bottom); + //static int Form_GetCurDocumentIndex(FPDF_FORMFILLINFO* pThis); + //static int Form_GetDocumentCount(FPDF_FORMFILLINFO* pThis); + static void Form_SetCurrentPage(FPDF_FORMFILLINFO* pThis, FPDF_DOCUMENT document, int iCurPage); + static int Form_GetCurrentPageIndex(FPDF_FORMFILLINFO* pThis, FPDF_DOCUMENT document); + static void Form_GetPageViewRect(FPDF_FORMFILLINFO* pThis, FPDF_PAGE page, double* left, double* top, double* right, double* bottom); + static int Form_GetPlatform(FPDF_FORMFILLINFO* pThis, void* platform, int length); + static FPDF_BOOL Form_PopupMenu(FPDF_FORMFILLINFO* pThis, FPDF_PAGE page, FPDF_WIDGET hWidget, int menuFlag, float x, float y); + static FPDF_BOOL Form_PostRequestURL(FPDF_FORMFILLINFO* pThis, FPDF_WIDESTRING wsURL, FPDF_WIDESTRING wsData, FPDF_WIDESTRING wsContentType, FPDF_WIDESTRING wsEncode, FPDF_WIDESTRING wsHeader, FPDF_BSTR* respone); + static FPDF_BOOL Form_PutRequestURL(FPDF_FORMFILLINFO* pThis, FPDF_WIDESTRING wsURL, FPDF_WIDESTRING wsData, FPDF_WIDESTRING wsEncode); + //static FPDF_BOOL Form_ShowFileDialog(FPDF_FORMFILLINFO* pThis, FPDF_WIDESTRING wsTitle, FPDF_WIDESTRING wsFilter, FPDF_BOOL isOpen, FPDF_STRINGHANDLE pathArr); + static void Form_UploadTo(FPDF_FORMFILLINFO* pThis, FPDF_FILEHANDLER* fileHandler, int fileFlag, FPDF_WIDESTRING uploadTo); + static FPDF_LPFILEHANDLER Form_DownloadFromURL(FPDF_FORMFILLINFO* pThis, FPDF_WIDESTRING URL); + //static FPDF_BOOL MyForm_GetFilePath(FPDF_FORMFILLINFO* pThis, FPDF_FILEHANDLER* pFileHandler, void* filePath, int length); + static FPDF_FILEHANDLER* Form_OpenFile(FPDF_FORMFILLINFO* pThis, int fileFlag, FPDF_WIDESTRING wsURL, const char* mode); + static void Form_GotoURL(FPDF_FORMFILLINFO* pThis, FPDF_DOCUMENT document, FPDF_WIDESTRING wsURL); + static int Form_GetLanguage(FPDF_FORMFILLINFO* pThis, void* language, int length); +#endif // _TEST_XFA + // IFSDK_PAUSE callbacks + static FPDF_BOOL Pause_NeedToPauseNow(IFSDK_PAUSE* param); + + PDFEngine::Client* 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. + int current_find_index_; + // Where to resume searching. + int resume_find_index_; + + // Permissions bitfield. + unsigned long permissions_; + + // 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 first visible page; refreshed by calling + // CalculateVisiblePages() + int first_visible_page_; + + // 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. + int 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_; +}; + +// 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() {} +#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); +#endif // OS_WIN + virtual bool RenderPDFPageToBitmap(const void* pdf_buffer, + int pdf_buffer_size, + int page_number, + const RenderingSettings& settings, + void* bitmap_buffer); + + virtual bool GetPDFDocInfo(const void* pdf_buffer, + int buffer_size, + int* page_count, + double* max_page_width); + + // 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); +}; + +} // namespace chrome_pdf + +#endif // PDF_PDFIUM_PDFIUM_ENGINE_H_ diff --git a/xfa_test/pdf/pdfium/pdfium_mem_buffer_file_read.cc b/xfa_test/pdf/pdfium/pdfium_mem_buffer_file_read.cc new file mode 100644 index 0000000000..b2371b42ff --- /dev/null +++ b/xfa_test/pdf/pdfium/pdfium_mem_buffer_file_read.cc @@ -0,0 +1,34 @@ +// 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 <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/xfa_test/pdf/pdfium/pdfium_mem_buffer_file_read.h b/xfa_test/pdf/pdfium/pdfium_mem_buffer_file_read.h new file mode 100644 index 0000000000..88ec410a6c --- /dev/null +++ b/xfa_test/pdf/pdfium/pdfium_mem_buffer_file_read.h @@ -0,0 +1,30 @@ +// 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 <stdlib.h> + +#include "third_party/pdfium/fpdfsdk/include/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/xfa_test/pdf/pdfium/pdfium_mem_buffer_file_write.cc b/xfa_test/pdf/pdfium/pdfium_mem_buffer_file_write.cc new file mode 100644 index 0000000000..45e564b67b --- /dev/null +++ b/xfa_test/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/xfa_test/pdf/pdfium/pdfium_mem_buffer_file_write.h b/xfa_test/pdf/pdfium/pdfium_mem_buffer_file_write.h new file mode 100644 index 0000000000..1795c83e89 --- /dev/null +++ b/xfa_test/pdf/pdfium/pdfium_mem_buffer_file_write.h @@ -0,0 +1,34 @@ +// 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 <string> + +#include "third_party/pdfium/fpdfsdk/include/fpdfsave.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/xfa_test/pdf/pdfium/pdfium_page.cc b/xfa_test/pdf/pdfium/pdfium_page.cc new file mode 100644 index 0000000000..d8a5dce5a2 --- /dev/null +++ b/xfa_test/pdf/pdfium/pdfium_page.cc @@ -0,0 +1,477 @@ +// 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 "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_engine.h" + +// Used when doing hit detection. +#define kTolerance 20.0 + +// 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 chrome_pdf { + +PDFiumPage::PDFiumPage(PDFiumEngine* engine, + int i, + const pp::Rect& r, + bool available) + : engine_(engine), + page_(NULL), + text_page_(NULL), + index_(i), + rect_(r), + calculated_links_(false), + available_(available) { +} + +PDFiumPage::~PDFiumPage() { +} + +void PDFiumPage::Unload() { + 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_) { + 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_) + page_ = FPDF_LoadPage(engine_->doc(), index_); + return page_; +} + +void PDFiumPage::ClosePrintPage() { + if (page_) { + FPDF_ClosePage(page_); + page_ = NULL; + } +} + +FPDF_TEXTPAGE PDFiumPage::GetTextPage() { + if (!available_) + return NULL; + if (!text_page_) + 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*>( + 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.size() == 0 ? 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 (size_t i = 0; i < targets.size(); ++i) { + // Remove the extra NULL character at end. + // Otherwise, find() will not return any matches. + if (targets[i].url.size() > 0 && + targets[i].url[targets[i].url.size() - 1] == '\0') { + targets[i].url.resize(targets[i].url.size() - 1); + } + // There should only ever be one NULL character + DCHECK(targets[i].url[targets[i].url.size() - 1] != '\0'); + + // PDFium may change the case of generated links. + std::string lowerCaseURL = base::StringToLowerASCII(targets[i].url); + std::string lowerCaseText = base::StringToLowerASCII(text_utf8); + size_t pos = lowerCaseText.find(lowerCaseURL, start); + size_t length = targets[i].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.size() > 0) + text_nodes->Append(CreateTextNode(before_text)); + std::string link_text = text_utf8.substr(pos, length); + text_nodes->Append(CreateURLNode(link_text, targets[i].url)); + + start = pos + length; + } + std::string before_text = text_utf8.substr(start); + if (before_text.size() > 0) + 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(std::string text) { + base::DictionaryValue* node = new base::DictionaryValue(); + node->SetString(kTextNodeType, kTextNodeTypeText); + node->SetString(kTextNodeText, text); + return node; +} + +base::Value* PDFiumPage::CreateURLNode(std::string text, 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, + LinkTarget* target) { + if (!available_) + return NONSELECTABLE_AREA; + pp::Point point2 = point - rect_.point(); + double new_x, 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); + if (link) { + // 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; + } + + 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) { + FPDF_DEST dest = FPDFLink_GetDest(engine_->doc(), link); + if (dest != NULL) + 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 > 1) { + void* data = WriteInto(&target->url, buffer_size + 1); + FPDFAction_GetURIPath(engine_->doc(), action, data, buffer_size); + } + } + 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) { + int page_index = FPDFDest_GetPageIndex(engine_->doc(), destination); + if (target) { + target->page = page_index; + } + 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 (size_t j = 0; j < links_[i].rects.size(); ++j) { + if (links_[i].rects[j].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) { + if (!available_) + return std::vector<int>(); + + CalculateLinks(); + + std::vector<int> links; + + for (size_t i = 0; i < links_.size(); ++i) { + for (size_t j = 0; j < links_[i].rects.size(); ++j) { + if (links_[i].rects[j].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 > 1) { // WriteInto needs at least 2 characters. + unsigned short* data = + reinterpret_cast<unsigned short*>(WriteInto(&url, url_length + 1)); + FPDFLink_GetURL(links, i, data, url_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) { + 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::Link::Link() { +} + +PDFiumPage::Link::~Link() { +} + +} // namespace chrome_pdf diff --git a/xfa_test/pdf/pdfium/pdfium_page.h b/xfa_test/pdf/pdfium/pdfium_page.h new file mode 100644 index 0000000000..22ea142988 --- /dev/null +++ b/xfa_test/pdf/pdfium/pdfium_page.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_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/fpdfsdk/include/fpdfdoc.h" +#include "third_party/pdfium/fpdfsdk/include/fpdfformfill.h" +#include "third_party/pdfium/fpdfsdk/include/fpdftext.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, + 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); + + 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); + // Returns target associated with a destination. + Area GetDestinationTarget(FPDF_DEST destination, LinkTarget* target); + // 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(std::string text); + base::Value* CreateURLNode(std::string text, std::string url); + + 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_; + pp::Rect rect_; + bool calculated_links_; + std::vector<Link> links_; + bool available_; +}; + +} // namespace chrome_pdf + +#endif // PDF_PDFIUM_PDFIUM_PAGE_H_ diff --git a/xfa_test/pdf/pdfium/pdfium_range.cc b/xfa_test/pdf/pdfium/pdfium_range.cc new file mode 100644 index 0000000000..c77d5906dd --- /dev/null +++ b/xfa_test/pdf/pdfium/pdfium_range.cc @@ -0,0 +1,79 @@ +// 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" + +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() { + int index = char_index_; + int count = char_count_; + if (!count) + return base::string16(); + if (count < 0) { + count *= -1; + index -= count - 1; + } + + base::string16 rv; + unsigned short* data = + reinterpret_cast<unsigned short*>(WriteInto(&rv, count + 1)); + if (data) { + int written = FPDFText_GetText(page_->GetTextPage(), index, count, data); + rv.reserve(written); + } + return rv; +} + +} // namespace chrome_pdf diff --git a/xfa_test/pdf/pdfium/pdfium_range.h b/xfa_test/pdf/pdfium/pdfium_range.h new file mode 100644 index 0000000000..ed8daf65bb --- /dev/null +++ b/xfa_test/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(); + + 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/xfa_test/pdf/preview_mode_client.cc b/xfa_test/pdf/preview_mode_client.cc new file mode 100644 index 0000000000..8b9919b46e --- /dev/null +++ b/xfa_test/pdf/preview_mode_client.cc @@ -0,0 +1,162 @@ +// 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 "base/logging.h" +#include "pdf/instance.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 available, + uint32 doc_size) { +} + +void PreviewModeClient::FormTextFieldFocusChange(bool in_focus) { + NOTREACHED(); +} + +bool PreviewModeClient::IsPrintPreview() { + NOTREACHED(); + return false; +} + +} // namespace chrome_pdf diff --git a/xfa_test/pdf/preview_mode_client.h b/xfa_test/pdf/preview_mode_client.h new file mode 100644 index 0000000000..0e766f949f --- /dev/null +++ b/xfa_test/pdf/preview_mode_client.h @@ -0,0 +1,77 @@ +// 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 <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); + virtual ~PreviewModeClient() {} + + // PDFEngine::Client implementation. + virtual void DocumentSizeUpdated(const pp::Size& size); + virtual void Invalidate(const pp::Rect& rect); + virtual void Scroll(const pp::Point& point); + virtual void ScrollToX(int position); + virtual void ScrollToY(int position); + virtual void ScrollToPage(int page); + virtual void NavigateTo(const std::string& url, bool open_in_new_tab); + virtual void UpdateCursor(PP_CursorType_Dev cursor); + virtual void UpdateTickMarks(const std::vector<pp::Rect>& tickmarks); + virtual void NotifyNumberOfFindResultsChanged(int total, + bool final_result); + virtual void NotifySelectedFindResultChanged(int current_find_index); + virtual void GetDocumentPassword( + pp::CompletionCallbackWithOutput<pp::Var> callback); + virtual void Alert(const std::string& message); + virtual bool Confirm(const std::string& message); + virtual std::string Prompt(const std::string& question, + const std::string& default_answer); + virtual std::string GetURL(); + virtual void Email(const std::string& to, + const std::string& cc, + const std::string& bcc, + const std::string& subject, + const std::string& body); + virtual void Print(); + virtual void SubmitForm(const std::string& url, + const void* data, + int length); + virtual std::string ShowFileSelectionDialog(); + virtual pp::URLLoader CreateURLLoader(); + virtual void ScheduleCallback(int id, int delay_in_ms); + virtual void SearchString(const base::char16* string, + const base::char16* term, + bool case_sensitive, + std::vector<SearchStringResult>* results); + virtual void DocumentPaintOccurred(); + virtual void DocumentLoadComplete(int page_count); + virtual void DocumentLoadFailed(); + virtual pp::Instance* GetPluginInstance(); + virtual void DocumentHasUnsupportedFeature(const std::string& feature); + virtual void DocumentLoadProgress(uint32 available, uint32 doc_size); + virtual void FormTextFieldFocusChange(bool in_focus); + virtual bool IsPrintPreview(); + + private: + Client* client_; +}; + +} // namespace chrome_pdf + +#endif // PDF_PREVIEW_MODE_CLIENT_H_ diff --git a/xfa_test/pdf/progress_control.cc b/xfa_test/pdf/progress_control.cc new file mode 100644 index 0000000000..2c2bca4e42 --- /dev/null +++ b/xfa_test/pdf/progress_control.cc @@ -0,0 +1,283 @@ +// 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/progress_control.h" + +#include <algorithm> + +#include "base/logging.h" +#include "pdf/draw_utils.h" +#include "pdf/resource_consts.h" +#include "ppapi/cpp/dev/font_dev.h" + +namespace chrome_pdf { + +const double ProgressControl::kCompleted = 100.0; + +// There is a bug outputting text with alpha 0xFF (opaque) to an intermediate +// image. It outputs alpha channgel of the text pixels to 0xFF (transparent). +// And it breaks next alpha blending. +// For now, let's use alpha 0xFE to work around this bug. +// TODO(gene): investigate this bug. +const uint32 kProgressTextColor = 0xFEDDE6FC; +const uint32 kProgressTextSize = 16; +const uint32 kImageTextSpacing = 8; +const uint32 kTopPadding = 8; +const uint32 kBottomPadding = 12; +const uint32 kLeftPadding = 10; +const uint32 kRightPadding = 10; + +int ScaleInt(int val, float scale) { + return static_cast<int>(val * scale); +} + +ProgressControl::ProgressControl() + : progress_(0.0), + device_scale_(1.0) { +} + +ProgressControl::~ProgressControl() { +} + +bool ProgressControl::CreateProgressControl( + uint32 id, + bool visible, + Control::Owner* delegate, + double progress, + float device_scale, + const std::vector<pp::ImageData>& images, + const pp::ImageData& background, + const std::string& text) { + progress_ = progress; + text_ = text; + bool res = Control::Create(id, pp::Rect(), visible, delegate); + if (res) + Reconfigure(background, images, device_scale); + return res; +} + +void ProgressControl::Reconfigure(const pp::ImageData& background, + const std::vector<pp::ImageData>& images, + float device_scale) { + DCHECK(images.size() != 0); + images_ = images; + background_ = background; + device_scale_ = device_scale; + pp::Size ctrl_size; + CalculateLayout(owner()->GetInstance(), images_, background_, text_, + device_scale_, &ctrl_size, &image_rc_, &text_rc_); + pp::Rect rc(pp::Point(), ctrl_size); + Control::SetRect(rc, false); + PrepareBackground(); +} + +// static +void ProgressControl::CalculateLayout(pp::Instance* instance, + const std::vector<pp::ImageData>& images, + const pp::ImageData& background, + const std::string& text, + float device_scale, + pp::Size* ctrl_size, + pp::Rect* image_rc, + pp::Rect* text_rc) { + DCHECK(images.size() != 0); + int image_width = 0; + int image_height = 0; + for (size_t i = 0; i < images.size(); i++) { + image_width = std::max(image_width, images[i].size().width()); + image_height = std::max(image_height, images[i].size().height()); + } + + pp::FontDescription_Dev description; + description.set_family(PP_FONTFAMILY_SANSSERIF); + description.set_size(ScaleInt(kProgressTextSize, device_scale)); + description.set_weight(PP_FONTWEIGHT_BOLD); + pp::Font_Dev font(instance, description); + int text_length = font.MeasureSimpleText(text); + + pp::FontDescription_Dev desc; + PP_FontMetrics_Dev metrics; + font.Describe(&desc, &metrics); + int text_height = metrics.height; + + *ctrl_size = pp::Size( + image_width + text_length + + ScaleInt(kImageTextSpacing + kLeftPadding + kRightPadding, device_scale), + std::max(image_height, text_height) + + ScaleInt(kTopPadding + kBottomPadding, device_scale)); + + int offset_x = 0; + int offset_y = 0; + if (ctrl_size->width() < background.size().width()) { + offset_x += (background.size().width() - ctrl_size->width()) / 2; + ctrl_size->set_width(background.size().width()); + } + if (ctrl_size->height() < background.size().height()) { + offset_y += (background.size().height() - ctrl_size->height()) / 2; + ctrl_size->set_height(background.size().height()); + } + + *image_rc = pp::Rect(ScaleInt(kLeftPadding, device_scale) + offset_x, + ScaleInt(kTopPadding, device_scale) + offset_y, + image_width, + image_height); + + *text_rc = pp::Rect( + ctrl_size->width() - text_length - + ScaleInt(kRightPadding, device_scale) - offset_x, + (ctrl_size->height() - text_height) / 2, + text_length, + text_height); +} + +size_t ProgressControl::GetImageIngex() const { + return static_cast<size_t>((progress_ / 100.0) * images_.size()); +} + +void ProgressControl::Paint(pp::ImageData* image_data, const pp::Rect& rc) { + if (!visible()) + return; + + pp::Rect draw_rc = rect().Intersect(rc); + if (draw_rc.IsEmpty()) + return; + + pp::ImageData buffer(owner()->GetInstance(), ctrl_background_.format(), + ctrl_background_.size(), false); + CopyImage(ctrl_background_, pp::Rect(ctrl_background_.size()), + &buffer, pp::Rect(ctrl_background_.size()), false); + + size_t index = GetImageIngex(); + if (index >= images_.size()) + index = images_.size() - 1; + + AlphaBlend(images_[index], + pp::Rect(images_[index].size()), + &buffer, + image_rc_.point(), + kOpaqueAlpha); + + pp::Rect image_draw_rc(draw_rc); + image_draw_rc.Offset(-rect().x(), -rect().y()); + AlphaBlend(buffer, + image_draw_rc, + image_data, + draw_rc.point(), + transparency()); +} + +void ProgressControl::SetProgress(double progress) { + size_t old_index = GetImageIngex(); + progress_ = progress; + size_t new_index = GetImageIngex(); + if (progress_ >= kCompleted) { + progress_ = kCompleted; + owner()->OnEvent(id(), EVENT_ID_PROGRESS_COMPLETED, NULL); + } + if (visible() && old_index != new_index) + owner()->Invalidate(id(), rect()); +} + +void ProgressControl::PrepareBackground() { + AdjustBackground(); + + pp::FontDescription_Dev description; + description.set_family(PP_FONTFAMILY_SANSSERIF); + description.set_size(ScaleInt(kProgressTextSize, device_scale_)); + description.set_weight(PP_FONTWEIGHT_BOLD); + pp::Font_Dev font(owner()->GetInstance(), description); + + pp::FontDescription_Dev desc; + PP_FontMetrics_Dev metrics; + font.Describe(&desc, &metrics); + + pp::Point text_origin = pp::Point(text_rc_.x(), + (text_rc_.y() + text_rc_.bottom() + metrics.x_height) / 2); + font.DrawTextAt(&ctrl_background_, pp::TextRun_Dev(text_), text_origin, + kProgressTextColor, pp::Rect(ctrl_background_.size()), false); +} + +void ProgressControl::AdjustBackground() { + ctrl_background_ = pp::ImageData(owner()->GetInstance(), + PP_IMAGEDATAFORMAT_BGRA_PREMUL, + rect().size(), + false); + + if (rect().size() == background_.size()) { + CopyImage(background_, pp::Rect(background_.size()), + &ctrl_background_, pp::Rect(ctrl_background_.size()), false); + return; + } + + // We need to stretch background to new dimentions. To do so, we split + // background into 9 different parts. We copy corner rects (1,3,7,9) as is, + // stretch rectangles between corners (2,4,6,8) in 1 dimention, and + // stretch center rect (5) in 2 dimentions. + // |---|---|---| + // | 1 | 2 | 3 | + // |---|---|---| + // | 4 | 5 | 6 | + // |---|---|---| + // | 7 | 8 | 9 | + // |---|---|---| + int slice_x = background_.size().width() / 3; + int slice_y = background_.size().height() / 3; + + // Copy rect 1 + pp::Rect src_rc(0, 0, slice_x, slice_y); + pp::Rect dest_rc(0, 0, slice_x, slice_y); + CopyImage(background_, src_rc, &ctrl_background_, dest_rc, false); + + // Copy rect 3 + src_rc.set_x(background_.size().width() - slice_x); + dest_rc.set_x(ctrl_background_.size().width() - slice_x); + CopyImage(background_, src_rc, &ctrl_background_, dest_rc, false); + + // Copy rect 9 + src_rc.set_y(background_.size().height() - slice_y); + dest_rc.set_y(ctrl_background_.size().height() - slice_y); + CopyImage(background_, src_rc, &ctrl_background_, dest_rc, false); + + // Copy rect 7 + src_rc.set_x(0); + dest_rc.set_x(0); + CopyImage(background_, src_rc, &ctrl_background_, dest_rc, false); + + // Stretch rect 2 + src_rc = pp::Rect( + slice_x, 0, background_.size().width() - 2 * slice_x, slice_y); + dest_rc = pp::Rect( + slice_x, 0, ctrl_background_.size().width() - 2 * slice_x, slice_y); + CopyImage(background_, src_rc, &ctrl_background_, dest_rc, true); + + // Copy rect 8 + src_rc.set_y(background_.size().height() - slice_y); + dest_rc.set_y(ctrl_background_.size().height() - slice_y); + CopyImage(background_, src_rc, &ctrl_background_, dest_rc, true); + + // Stretch rect 4 + src_rc = pp::Rect( + 0, slice_y, slice_x, background_.size().height() - 2 * slice_y); + dest_rc = pp::Rect( + 0, slice_y, slice_x, ctrl_background_.size().height() - 2 * slice_y); + CopyImage(background_, src_rc, &ctrl_background_, dest_rc, true); + + // Copy rect 6 + src_rc.set_x(background_.size().width() - slice_x); + dest_rc.set_x(ctrl_background_.size().width() - slice_x); + CopyImage(background_, src_rc, &ctrl_background_, dest_rc, true); + + // Stretch rect 5 + src_rc = pp::Rect(slice_x, + slice_y, + background_.size().width() - 2 * slice_x, + background_.size().height() - 2 * slice_y); + dest_rc = pp::Rect(slice_x, + slice_y, + ctrl_background_.size().width() - 2 * slice_x, + ctrl_background_.size().height() - 2 * slice_y); + CopyImage(background_, src_rc, &ctrl_background_, dest_rc, true); +} + +} // namespace chrome_pdf diff --git a/xfa_test/pdf/progress_control.h b/xfa_test/pdf/progress_control.h new file mode 100644 index 0000000000..96d5da1ce9 --- /dev/null +++ b/xfa_test/pdf/progress_control.h @@ -0,0 +1,72 @@ +// 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_PROGRESS_CONTROL_H_ +#define PDF_PROGRESS_CONTROL_H_ + +#include <string> +#include <vector> + +#include "pdf/control.h" +#include "pdf/fading_control.h" +#include "ppapi/cpp/image_data.h" + +namespace chrome_pdf { + +class ProgressControl : public FadingControl { + public: + static const double kCompleted; + + enum ProgressEventIds { + EVENT_ID_PROGRESS_COMPLETED, + }; + + ProgressControl(); + virtual ~ProgressControl(); + virtual bool CreateProgressControl(uint32 id, + bool visible, + Control::Owner* delegate, + double progress, + float device_scale, + const std::vector<pp::ImageData>& images, + const pp::ImageData& background, + const std::string& text); + void Reconfigure(const pp::ImageData& background, + const std::vector<pp::ImageData>& images, + float device_scale); + + static void CalculateLayout(pp::Instance* instance, + const std::vector<pp::ImageData>& images, + const pp::ImageData& background, + const std::string& text, + float device_scale, + pp::Size* ctrl_size, + pp::Rect* image_rc, + pp::Rect* text_rc); + + // Control interface. + virtual void Paint(pp::ImageData* image_data, const pp::Rect& rc); + + // ProgressControl interface + // Set progress indicator in percents from 0% to 100%. + virtual void SetProgress(double progress); + + private: + void PrepareBackground(); + void AdjustBackground(); + size_t GetImageIngex() const; + + double progress_; + float device_scale_; + std::vector<pp::ImageData> images_; + pp::ImageData background_; + pp::ImageData ctrl_background_; + std::string text_; + pp::Rect image_rc_; + pp::Rect text_rc_; +}; + +} // namespace chrome_pdf + +#endif // PDF_PROGRESS_CONTROL_H_ diff --git a/xfa_test/pdf/resource.h b/xfa_test/pdf/resource.h new file mode 100644 index 0000000000..9fdbea758b --- /dev/null +++ b/xfa_test/pdf/resource.h @@ -0,0 +1,14 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by pdf.rc + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/xfa_test/pdf/resource_consts.h b/xfa_test/pdf/resource_consts.h new file mode 100644 index 0000000000..f12efd61be --- /dev/null +++ b/xfa_test/pdf/resource_consts.h @@ -0,0 +1,49 @@ +// 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_RESOURCE_RESOURCE_CONSTS_H_ +#define PDF_RESOURCE_RESOURCE_CONSTS_H_ + +#include "base/basictypes.h" + +namespace chrome_pdf { + +const int kDragTimerMs = 50; +const double kMinZoom = 0.1; +const double kMaxZoom = 10.0; +const double kZoomStep = 1.2; + +const uint32 kFadingTimeoutMs = 50; + +const uint32 kToolbarId = 10; +const uint32 kThumbnailsId = 11; +const uint32 kProgressBarId = 12; +const uint32 kPageIndicatorId = 13; +const uint32 kFitToPageButtonId = 100; +const uint32 kFitToWidthButtonId = 101; +const uint32 kZoomOutButtonId = 102; +const uint32 kZoomInButtonId = 103; +const uint32 kSaveButtonId = 104; +const uint32 kPrintButtonId = 105; + +const uint32 kAutoScrollId = 200; + +// fading_rect.left = button_rect.left - kToolbarFadingOffsetLeft +const int32 kToolbarFadingOffsetLeft = 40; +// fading_rect.top = button_rect.top - kToolbarFadingOffsetTop +const int32 kToolbarFadingOffsetTop = 40; +// fading_rect.right = button_rect.right + kToolbarFadingOffsetRight +const int32 kToolbarFadingOffsetRight = 10; +// fading_rect.bottom = button_rect.bottom + kToolbarFadingOffsetBottom +const int32 kToolbarFadingOffsetBottom = 8; + +const int32 kProgressOffsetLeft = 8; +const int32 kProgressOffsetBottom = 8; + +// Width of the thumbnails control. +const int32 kThumbnailsWidth = 196; + +} // namespace chrome_pdf + +#endif // PDF_RESOURCE_RESOURCE_CONSTS_H_ diff --git a/xfa_test/pdf/thumbnail_control.cc b/xfa_test/pdf/thumbnail_control.cc new file mode 100644 index 0000000000..9a779b2912 --- /dev/null +++ b/xfa_test/pdf/thumbnail_control.cc @@ -0,0 +1,301 @@ +// 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/thumbnail_control.h" + +#include <algorithm> + +#include "base/logging.h" +#include "base/strings/string_util.h" +#include "pdf/draw_utils.h" +#include "pdf/number_image_generator.h" + +namespace chrome_pdf { + +const int kLeftBorderSize = 52; +const int kBorderSize = 12; +const int kHighlightBorderSize = 2; + +const uint32 kLeftColor = 0x003F537B; +const uint32 kRightColor = 0x990D1626; + +const uint32 kTopHighlightColor = 0xFF426DC9; +const uint32 kBottomHighlightColor = 0xFF6391DE; +const uint32 kThumbnailBackgroundColor = 0xFF000000; + +const uint32 kSlidingTimeoutMs = 50; +const int32 kSlidingShift = 50; + +const double kNonSelectedThumbnailAlpha = 0.91; + +ThumbnailControl::ThumbnailControl() + : engine_(NULL), sliding_width_(0), sliding_shift_(kSlidingShift), + sliding_timeout_(kSlidingTimeoutMs), sliding_timer_id_(0) { +} + +ThumbnailControl::~ThumbnailControl() { + ClearCache(); +} + +bool ThumbnailControl::CreateThumbnailControl( + uint32 id, const pp::Rect& rc, + bool visible, Owner* owner, PDFEngine* engine, + NumberImageGenerator* number_image_generator) { + engine_ = engine; + number_image_generator_ = number_image_generator; + sliding_width_ = rc.width(); + + return Control::Create(id, rc, visible, owner); +} + +void ThumbnailControl::SetPosition(int position, int total, bool invalidate) { + visible_rect_ = pp::Rect(); + visible_pages_.clear(); + + if (rect().width() < kLeftBorderSize + kBorderSize) { + return; // control is too narrow to show thumbnails. + } + + int num_pages = engine_->GetNumberOfPages(); + + int max_doc_width = 0, total_doc_height = 0; + std::vector<pp::Rect> page_sizes(num_pages); + for (int i = 0; i < num_pages; ++i) { + page_sizes[i] = engine_->GetPageRect(i); + max_doc_width = std::max(max_doc_width, page_sizes[i].width()); + total_doc_height += page_sizes[i].height(); + } + + if (!max_doc_width) + return; + + int max_thumbnail_width = rect().width() - kLeftBorderSize - kBorderSize; + double thumbnail_ratio = + max_thumbnail_width / static_cast<double>(max_doc_width); + + int total_thumbnail_height = 0; + for (int i = 0; i < num_pages; ++i) { + total_thumbnail_height += kBorderSize; + int thumbnail_width = + static_cast<int>(page_sizes[i].width() * thumbnail_ratio); + int thumbnail_height = + static_cast<int>(page_sizes[i].height() * thumbnail_ratio); + int x = (max_thumbnail_width - thumbnail_width) / 2; + page_sizes[i] = + pp::Rect(x, total_thumbnail_height, thumbnail_width, thumbnail_height); + total_thumbnail_height += thumbnail_height; + } + total_thumbnail_height += kBorderSize; + + int visible_y = 0; + if (total > 0) { + double range = total_thumbnail_height - rect().height(); + if (range < 0) + range = 0; + visible_y = static_cast<int>(range * position / total); + } + visible_rect_ = pp::Rect(0, visible_y, max_thumbnail_width, rect().height()); + + for (int i = 0; i < num_pages; ++i) { + if (page_sizes[i].Intersects(visible_rect_)) { + PageInfo page_info; + page_info.index = i; + page_info.rect = page_sizes[i]; + page_info.rect.Offset(kLeftBorderSize, -visible_rect_.y()); + visible_pages_.push_back(page_info); + } + } + + if (invalidate) + owner()->Invalidate(id(), rect()); +} + +void ThumbnailControl::Show(bool visible, bool invalidate) { + if (!visible || invalidate) + ClearCache(); + sliding_width_ = rect().width(); + Control::Show(visible, invalidate); +} + +void ThumbnailControl::SlideIn() { + if (visible()) + return; + + Show(true, false); + sliding_width_ = 0; + sliding_shift_ = kSlidingShift; + + sliding_timer_id_ = owner()->ScheduleTimer(id(), sliding_timeout_); + owner()->Invalidate(id(), rect()); +} + +void ThumbnailControl::SlideOut() { + if (!visible()) + return; + sliding_shift_ = -kSlidingShift; + sliding_timer_id_ = owner()->ScheduleTimer(id(), sliding_timeout_); +} + +void ThumbnailControl::Paint(pp::ImageData* image_data, const pp::Rect& rc) { + if (!visible()) + return; + + pp::Rect control_rc(rect()); + control_rc.Offset(control_rc.width() - sliding_width_, 0); + control_rc.set_width(sliding_width_); + + pp::Rect draw_rc = rc.Intersect(control_rc); + if (draw_rc.IsEmpty()) + return; + + pp::Rect gradient_rc(control_rc.x(), draw_rc.y(), + control_rc.width(), draw_rc.height()); + GradientFill(owner()->GetInstance(), + image_data, + draw_rc, + gradient_rc, + kLeftColor, + kRightColor, + true, + transparency()); + + int selected_page = engine_->GetMostVisiblePage(); + for (size_t i = 0; i < visible_pages_.size(); ++i) { + pp::Rect page_rc = visible_pages_[i].rect; + page_rc.Offset(control_rc.point()); + + if (visible_pages_[i].index == selected_page) { + pp::Rect highlight_rc = page_rc; + highlight_rc.Inset(-kHighlightBorderSize, -kHighlightBorderSize); + GradientFill(owner()->GetInstance(), + image_data, + draw_rc, + highlight_rc, + kTopHighlightColor, + kBottomHighlightColor, + false, + transparency()); + } + + pp::Rect draw_page_rc = page_rc.Intersect(draw_rc); + if (draw_page_rc.IsEmpty()) + continue; + + // First search page image in the cache. + pp::ImageData* thumbnail = NULL; + std::map<int, pp::ImageData*>::iterator it = + image_cache_.find(visible_pages_[i].index); + if (it != image_cache_.end()) { + if (it->second->size() == page_rc.size()) + thumbnail = image_cache_[visible_pages_[i].index]; + else + image_cache_.erase(it); + } + + // If page is not found in the cache, create new one. + if (thumbnail == NULL) { + thumbnail = new pp::ImageData(owner()->GetInstance(), + PP_IMAGEDATAFORMAT_BGRA_PREMUL, + page_rc.size(), + false); + engine_->PaintThumbnail(thumbnail, visible_pages_[i].index); + + pp::ImageData page_number; + number_image_generator_->GenerateImage( + visible_pages_[i].index + 1, &page_number); + pp::Point origin( + (thumbnail->size().width() - page_number.size().width()) / 2, + (thumbnail->size().height() - page_number.size().height()) / 2); + + if (origin.x() > 0 && origin.y() > 0) { + AlphaBlend(page_number, pp::Rect(pp::Point(), page_number.size()), + thumbnail, origin, kOpaqueAlpha); + } + + image_cache_[visible_pages_[i].index] = thumbnail; + } + + uint8 alpha = transparency(); + if (visible_pages_[i].index != selected_page) + alpha = static_cast<uint8>(alpha * kNonSelectedThumbnailAlpha); + FillRect(image_data, draw_page_rc, kThumbnailBackgroundColor); + draw_page_rc.Offset(-page_rc.x(), -page_rc.y()); + AlphaBlend(*thumbnail, draw_page_rc, image_data, + draw_page_rc.point() + page_rc.point(), alpha); + } +} + +bool ThumbnailControl::HandleEvent(const pp::InputEvent& event) { + if (!visible()) + return false; + + pp::MouseInputEvent mouse_event(event); + if (mouse_event.is_null()) + return false; + pp::Point pt = mouse_event.GetPosition(); + if (!rect().Contains(pt)) + return false; + + int over_page = -1; + for (size_t i = 0; i < visible_pages_.size(); ++i) { + pp::Rect page_rc = visible_pages_[i].rect; + page_rc.Offset(rect().point()); + if (page_rc.Contains(pt)) { + over_page = i; + break; + } + } + + bool handled = false; + switch (event.GetType()) { + case PP_INPUTEVENT_TYPE_MOUSEMOVE: + owner()->SetCursor(id(), + over_page == -1 ? PP_CURSORTYPE_POINTER : PP_CURSORTYPE_HAND); + break; + case PP_INPUTEVENT_TYPE_MOUSEDOWN: + if (over_page != -1) { + owner()->Invalidate(id(), rect()); + owner()->OnEvent(id(), EVENT_ID_THUMBNAIL_SELECTED, + &visible_pages_[over_page].index); + } + handled = true; + break; + default: + break; + } + + return handled; +} + +void ThumbnailControl::OnTimerFired(uint32 timer_id) { + if (timer_id == sliding_timer_id_) { + sliding_width_ += sliding_shift_; + if (sliding_width_ <= 0) { + // We completely slided out. Make control invisible now. + Show(false, false); + } else if (sliding_width_ >= rect().width()) { + // We completely slided in. Make sliding width to full control width. + sliding_width_ = rect().width(); + } else { + // We have not completed sliding yet. Keep sliding. + sliding_timer_id_ = owner()->ScheduleTimer(id(), sliding_timeout_); + } + owner()->Invalidate(id(), rect()); + } +} + +void ThumbnailControl::ResetEngine(PDFEngine* engine) { + engine_ = engine; + ClearCache(); +} + +void ThumbnailControl::ClearCache() { + std::map<int, pp::ImageData*>::iterator it; + for (it = image_cache_.begin(); it != image_cache_.end(); ++it) { + delete it->second; + } + image_cache_.clear(); +} + +} // namespace chrome_pdf diff --git a/xfa_test/pdf/thumbnail_control.h b/xfa_test/pdf/thumbnail_control.h new file mode 100644 index 0000000000..d10a32896d --- /dev/null +++ b/xfa_test/pdf/thumbnail_control.h @@ -0,0 +1,67 @@ +// 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_THUMBNAIL_CONTROL_H_ +#define PDF_THUMBNAIL_CONTROL_H_ + +#include <map> +#include <vector> + +#include "pdf/control.h" +#include "pdf/pdf_engine.h" +#include "ppapi/cpp/input_event.h" + +namespace chrome_pdf { + +class NumberImageGenerator; + +class ThumbnailControl : public Control { + public: + enum ThumbnailEventIds { + EVENT_ID_THUMBNAIL_SELECTED = 100, + }; + + explicit ThumbnailControl(); + virtual ~ThumbnailControl(); + + // Sets current position of the thumnail control. + void SetPosition(int position, int total, bool invalidate); + void SlideIn(); + void SlideOut(); + + virtual bool CreateThumbnailControl( + uint32 id, const pp::Rect& rc, + bool visible, Owner* owner, PDFEngine* engine, + NumberImageGenerator* number_image_generator); + + // Control interface. + virtual void Show(bool visible, bool invalidate); + virtual void Paint(pp::ImageData* image_data, const pp::Rect& rc); + virtual bool HandleEvent(const pp::InputEvent& event); + virtual void OnTimerFired(uint32 timer_id); + + virtual void ResetEngine(PDFEngine* engine); + + private: + void ClearCache(); + + struct PageInfo { + int index; + pp::Rect rect; + }; + + PDFEngine* engine_; + pp::Rect visible_rect_; + std::vector<PageInfo> visible_pages_; + std::map<int, pp::ImageData*> image_cache_; + int sliding_width_; + int sliding_shift_; + int sliding_timeout_; + uint32 sliding_timer_id_; + NumberImageGenerator* number_image_generator_; +}; + +} // namespace chrome_pdf + +#endif // PDF_THUMBNAIL_CONTROL_H_ |