1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef PDF_PDFIUM_PDFIUM_ENGINE_H_
6 #define PDF_PDFIUM_PDFIUM_ENGINE_H_
13 #include "base/memory/scoped_ptr.h"
14 #include "base/time/time.h"
15 #include "pdf/document_loader.h"
16 #include "pdf/pdf_engine.h"
17 #include "pdf/pdfium/pdfium_page.h"
18 #include "pdf/pdfium/pdfium_range.h"
19 #include "ppapi/cpp/completion_callback.h"
20 #include "ppapi/cpp/dev/buffer_dev.h"
21 #include "ppapi/cpp/image_data.h"
22 #include "ppapi/cpp/point.h"
23 #include "third_party/pdfium/fpdfsdk/include/fpdf_dataavail.h"
24 #include "third_party/pdfium/fpdfsdk/include/fpdf_progressive.h"
25 #include "third_party/pdfium/fpdfsdk/include/fpdfformfill.h"
26 #include "third_party/pdfium/fpdfsdk/include/fpdfview.h"
29 class KeyboardInputEvent;
30 class MouseInputEvent;
33 namespace chrome_pdf {
37 class PDFiumEngine : public PDFEngine,
38 public DocumentLoader::Client,
39 public FPDF_FORMFILLINFO,
40 public IPDF_JSPLATFORM,
43 explicit PDFiumEngine(PDFEngine::Client* client);
44 virtual ~PDFiumEngine();
46 // PDFEngine implementation.
47 virtual bool New(const char* url);
48 virtual bool New(const char* url,
50 virtual void PageOffsetUpdated(const pp::Point& page_offset);
51 virtual void PluginSizeUpdated(const pp::Size& size);
52 virtual void ScrolledToXPosition(int position);
53 virtual void ScrolledToYPosition(int position);
54 virtual void PrePaint();
55 virtual void Paint(const pp::Rect& rect,
56 pp::ImageData* image_data,
57 std::vector<pp::Rect>* ready,
58 std::vector<pp::Rect>* pending);
59 virtual void PostPaint();
60 virtual bool HandleDocumentLoad(const pp::URLLoader& loader);
61 virtual bool HandleEvent(const pp::InputEvent& event);
62 virtual uint32_t QuerySupportedPrintOutputFormats();
63 virtual void PrintBegin();
64 virtual pp::Resource PrintPages(
65 const PP_PrintPageNumberRange_Dev* page_ranges,
66 uint32_t page_range_count,
67 const PP_PrintSettings_Dev& print_settings);
68 virtual void PrintEnd();
69 virtual void StartFind(const char* text, bool case_sensitive);
70 virtual bool SelectFindResult(bool forward);
71 virtual void StopFind();
72 virtual void ZoomUpdated(double new_zoom_level);
73 virtual void RotateClockwise();
74 virtual void RotateCounterclockwise();
75 virtual std::string GetSelectedText();
76 virtual std::string GetLinkAtPosition(const pp::Point& point);
77 virtual bool IsSelecting();
78 virtual bool HasPermission(DocumentPermission permission) const;
79 virtual void SelectAll();
80 virtual int GetNumberOfPages();
81 virtual int GetNamedDestinationPage(const std::string& destination);
82 virtual int GetFirstVisiblePage();
83 virtual int GetMostVisiblePage();
84 virtual pp::Rect GetPageRect(int index);
85 virtual pp::Rect GetPageContentsRect(int index);
86 virtual int GetVerticalScrollbarYPosition() { return position_.y(); }
87 virtual void PaintThumbnail(pp::ImageData* image_data, int index);
88 virtual void SetGrayscale(bool grayscale);
89 virtual void OnCallback(int id);
90 virtual std::string GetPageAsJSON(int index);
91 virtual bool GetPrintScaling();
92 virtual void AppendBlankPages(int num_pages);
93 virtual void AppendPage(PDFEngine* engine, int index);
94 virtual pp::Point GetScrollPosition();
95 virtual void SetScrollPosition(const pp::Point& position);
96 virtual bool IsProgressiveLoad();
98 // DocumentLoader::Client implementation.
99 virtual pp::Instance* GetPluginInstance();
100 virtual pp::URLLoader CreateURLLoader();
101 virtual void OnPartialDocumentLoaded();
102 virtual void OnPendingRequestComplete();
103 virtual void OnNewDataAvailable();
104 virtual void OnDocumentComplete();
106 void UnsupportedFeature(int type);
108 std::string current_find_text() const { return current_find_text_; }
110 FPDF_DOCUMENT doc() { return doc_; }
111 FPDF_FORMHANDLE form() { return form_; }
114 // This helper class is used to detect the difference in selection between
115 // construction and destruction. At destruction, it invalidates all the
116 // parts that are newly selected, along with all the parts that used to be
117 // selected but are not anymore.
118 class SelectionChangeInvalidator {
120 explicit SelectionChangeInvalidator(PDFiumEngine* engine);
121 ~SelectionChangeInvalidator();
123 // Sets the given container to the all the currently visible selection
124 // rectangles, in screen coordinates.
125 void GetVisibleSelectionsScreenRects(std::vector<pp::Rect>* rects);
127 PDFiumEngine* engine_;
128 // Screen rectangles that were selected on construction.
129 std::vector<pp::Rect> old_selections_;
130 // The origin at the time this object was constructed.
131 pp::Point previous_origin_;
134 // Used to store mouse down state to handle it in other mouse event handlers.
135 class MouseDownState {
137 MouseDownState(const PDFiumPage::Area& area,
138 const PDFiumPage::LinkTarget& target);
141 void Set(const PDFiumPage::Area& area,
142 const PDFiumPage::LinkTarget& target);
144 bool Matches(const PDFiumPage::Area& area,
145 const PDFiumPage::LinkTarget& target) const;
148 PDFiumPage::Area area_;
149 PDFiumPage::LinkTarget target_;
151 DISALLOW_COPY_AND_ASSIGN(MouseDownState);
154 // Used to store the state of a text search.
155 class FindTextIndex {
160 bool valid() const { return valid_; }
163 size_t GetIndex() const;
164 void SetIndex(size_t index);
165 size_t IncrementIndex();
168 bool valid_; // Whether |index_| is valid or not.
169 size_t index_; // The current search result, 0-based.
171 DISALLOW_COPY_AND_ASSIGN(FindTextIndex);
174 friend class SelectionChangeInvalidator;
176 struct FileAvail : public FX_FILEAVAIL {
177 DocumentLoader* loader;
180 struct DownloadHints : public FX_DOWNLOADHINTS {
181 DocumentLoader* loader;
184 // PDFium interface to get block of data.
185 static int GetBlock(void* param, unsigned long position,
186 unsigned char* buffer, unsigned long size);
188 // PDFium interface to check is block of data is available.
189 static bool IsDataAvail(FX_FILEAVAIL* param,
190 size_t offset, size_t size);
192 // PDFium interface to request download of the block of data.
193 static void AddSegment(FX_DOWNLOADHINTS* param,
194 size_t offset, size_t size);
196 // We finished getting the pdf file, so load it. This will complete
197 // asynchronously (due to password fetching) and may be run multiple times.
200 // Try loading the document. Returns true if the document is successfully
201 // loaded or is already loaded otherwise it will return false. If
202 // |with_password| is set to true, the document will be loaded with
203 // |password|. If the document could not be loaded and needs a password,
204 // |needs_password| will be set to true.
205 bool TryLoadingDoc(bool with_password,
206 const std::string& password,
207 bool* needs_password);
209 // Ask the user for the document password and then continue loading the
211 void GetPasswordAndLoad();
213 // Called when the password has been retrieved.
214 void OnGetPasswordComplete(int32_t result,
215 const pp::Var& password);
217 // Continues loading the document when the password has been retrieved, or if
218 // there is no password.
219 void ContinueLoadingDocument(bool has_password,
220 const std::string& password);
222 // Finish loading the document and notify the client that the document has
223 // been loaded. This should only be run after |doc_| has been loaded and the
224 // document is fully downloaded. If this has been run once, it will result in
226 void FinishLoadingDocument();
228 // Loads information about the pages in the document and calculate the
230 void LoadPageInfo(bool reload);
232 // Calculate which pages should be displayed right now.
233 void CalculateVisiblePages();
235 // Returns true iff the given page index is visible. CalculateVisiblePages
236 // must have been called first.
237 bool IsPageVisible(int index) const;
239 // Checks if a page is now available, and if so marks it as such and returns
240 // true. Otherwise, it will return false and will add the index to the given
241 // array if it's not already there.
242 bool CheckPageAvailable(int index, std::vector<int>* pending);
244 // Helper function to get a given page's size in pixels. This is not part of
245 // PDFiumPage because we might not have that structure when we need this.
246 pp::Size GetPageSize(int index);
248 void UpdateTickMarks();
250 // Called to continue searching so we don't block the main thread.
251 void ContinueFind(int32_t result);
253 // Inserts a find result into find_results_, which is sorted.
254 void AddFindResult(const PDFiumRange& result);
256 // Search a page using PDFium's methods. Doesn't work with unicode. This
257 // function is just kept arount in case PDFium code is fixed.
258 void SearchUsingPDFium(const base::string16& term,
261 int character_to_start_searching_from,
264 // Search a page ourself using ICU.
265 void SearchUsingICU(const base::string16& term,
268 int character_to_start_searching_from,
271 // Input event handlers.
272 bool OnMouseDown(const pp::MouseInputEvent& event);
273 bool OnMouseUp(const pp::MouseInputEvent& event);
274 bool OnMouseMove(const pp::MouseInputEvent& event);
275 bool OnKeyDown(const pp::KeyboardInputEvent& event);
276 bool OnKeyUp(const pp::KeyboardInputEvent& event);
277 bool OnChar(const pp::KeyboardInputEvent& event);
279 FPDF_DOCUMENT CreateSinglePageRasterPdf(
280 double source_page_width,
281 double source_page_height,
282 const PP_PrintSettings_Dev& print_settings,
283 PDFiumPage* page_to_print);
285 pp::Buffer_Dev PrintPagesAsRasterPDF(
286 const PP_PrintPageNumberRange_Dev* page_ranges,
287 uint32_t page_range_count,
288 const PP_PrintSettings_Dev& print_settings);
290 pp::Buffer_Dev PrintPagesAsPDF(const PP_PrintPageNumberRange_Dev* page_ranges,
291 uint32_t page_range_count,
292 const PP_PrintSettings_Dev& print_settings);
294 pp::Buffer_Dev GetFlattenedPrintData(const FPDF_DOCUMENT& doc);
295 void FitContentsToPrintableAreaIfRequired(
296 const FPDF_DOCUMENT& doc,
297 const PP_PrintSettings_Dev& print_settings);
298 void SaveSelectedFormForPrint();
300 // Given a mouse event, returns which page and character location it's closest
302 PDFiumPage::Area GetCharIndex(const pp::MouseInputEvent& event,
305 PDFiumPage::LinkTarget* target);
306 PDFiumPage::Area GetCharIndex(const pp::Point& point,
309 PDFiumPage::LinkTarget* target);
311 void OnSingleClick(int page_index, int char_index);
312 void OnMultipleClick(int click_count, int page_index, int char_index);
314 // Starts a progressive paint operation given a rectangle in screen
315 // coordinates. Returns the index in progressive_rects_.
316 int StartPaint(int page_index, const pp::Rect& dirty);
318 // Continues a paint operation that was started earlier. Returns true if the
319 // paint is done, or false if it needs to be continued.
320 bool ContinuePaint(int progressive_index, pp::ImageData* image_data);
322 // Called once PDFium is finished rendering a page so that we draw our
323 // borders, highlighting etc.
324 void FinishPaint(int progressive_index, pp::ImageData* image_data);
326 // Stops any paints that are in progress.
329 // Invalidates all pages. Use this when some global parameter, such as page
330 // orientation, has changed.
331 void InvalidateAllPages();
333 // If the page is narrower than the document size, paint the extra space
334 // with the page background.
335 void FillPageSides(int progressive_index);
337 void PaintPageShadow(int progressive_index, pp::ImageData* image_data);
339 // Highlight visible find results and selections.
340 void DrawSelections(int progressive_index, pp::ImageData* image_data);
342 // Paints an page that hasn't finished downloading.
343 void PaintUnavailablePage(int page_index,
344 const pp::Rect& dirty,
345 pp::ImageData* image_data);
347 // Given a page index, returns the corresponding index in progressive_rects_,
348 // or -1 if it doesn't exist.
349 int GetProgressiveIndex(int page_index) const;
351 // Creates a FPDF_BITMAP from a rectangle in screen coordinates.
352 FPDF_BITMAP CreateBitmap(const pp::Rect& rect,
353 pp::ImageData* image_data) const;
355 // Given a rectangle in screen coordinates, returns the coordinates in the
356 // units that PDFium rendering functions expect.
357 void GetPDFiumRect(int page_index, const pp::Rect& rect, int* start_x,
358 int* start_y, int* size_x, int* size_y) const;
360 // Returns the rendering flags to pass to PDFium.
361 int GetRenderingFlags() const;
363 // Returns the currently visible rectangle in document coordinates.
364 pp::Rect GetVisibleRect() const;
366 // Returns a page's rect in screen coordinates, as well as its surrounding
367 // border areas and bottom separator.
368 pp::Rect GetPageScreenRect(int page_index) const;
370 // Given a rectangle in document coordinates, returns the rectange into screen
371 // coordinates (i.e. 0,0 is top left corner of plugin area). If it's not
372 // visible, an empty rectangle is returned.
373 pp::Rect GetScreenRect(const pp::Rect& rect) const;
375 // Highlights the given rectangle.
376 void Highlight(void* buffer,
378 const pp::Rect& rect,
379 std::vector<pp::Rect>* highlighted_rects);
381 // Helper function to convert a device to page coordinates. If the page is
382 // not yet loaded, page_x and page_y will be set to 0.
383 void DeviceToPage(int page_index,
389 // Helper function to get the index of a given FPDF_PAGE. Returns -1 if not
391 int GetVisiblePageIndex(FPDF_PAGE page);
393 // Helper function to change the current page, running page open/close
394 // triggers as necessary.
395 void SetCurrentPage(int index);
397 // Transform |page| contents to fit in the selected printer paper size.
398 void TransformPDFPageForPrinting(FPDF_PAGE page,
399 const PP_PrintSettings_Dev& print_settings);
401 void DrawPageShadow(const pp::Rect& page_rect,
402 const pp::Rect& shadow_rect,
403 const pp::Rect& clip_rect,
404 pp::ImageData* image_data);
406 void GetRegion(const pp::Point& location,
407 pp::ImageData* image_data,
411 // Called when the selection changes.
412 void OnSelectionChanged();
414 // Common code shared by RotateClockwise() and RotateCounterclockwise().
415 void RotateInternal();
417 // FPDF_FORMFILLINFO callbacks.
418 static void Form_Invalidate(FPDF_FORMFILLINFO* param,
424 static void Form_OutputSelectedRect(FPDF_FORMFILLINFO* param,
430 static void Form_SetCursor(FPDF_FORMFILLINFO* param, int cursor_type);
431 static int Form_SetTimer(FPDF_FORMFILLINFO* param,
433 TimerCallback timer_func);
434 static void Form_KillTimer(FPDF_FORMFILLINFO* param, int timer_id);
435 static FPDF_SYSTEMTIME Form_GetLocalTime(FPDF_FORMFILLINFO* param);
436 static void Form_OnChange(FPDF_FORMFILLINFO* param);
437 static FPDF_PAGE Form_GetPage(FPDF_FORMFILLINFO* param,
438 FPDF_DOCUMENT document,
440 static FPDF_PAGE Form_GetCurrentPage(FPDF_FORMFILLINFO* param,
441 FPDF_DOCUMENT document);
442 static int Form_GetRotation(FPDF_FORMFILLINFO* param, FPDF_PAGE page);
443 static void Form_ExecuteNamedAction(FPDF_FORMFILLINFO* param,
444 FPDF_BYTESTRING named_action);
445 static void Form_SetTextFieldFocus(FPDF_FORMFILLINFO* param,
446 FPDF_WIDESTRING value,
449 static void Form_DoURIAction(FPDF_FORMFILLINFO* param, FPDF_BYTESTRING uri);
450 static void Form_DoGoToAction(FPDF_FORMFILLINFO* param,
453 float* position_array,
456 // IPDF_JSPLATFORM callbacks.
457 static int Form_Alert(IPDF_JSPLATFORM* param,
458 FPDF_WIDESTRING message,
459 FPDF_WIDESTRING title,
462 static void Form_Beep(IPDF_JSPLATFORM* param, int type);
463 static int Form_Response(IPDF_JSPLATFORM* param,
464 FPDF_WIDESTRING question,
465 FPDF_WIDESTRING title,
466 FPDF_WIDESTRING default_response,
467 FPDF_WIDESTRING label,
471 static int Form_GetFilePath(IPDF_JSPLATFORM* param,
474 static void Form_Mail(IPDF_JSPLATFORM* param,
479 FPDF_WIDESTRING subject,
482 FPDF_WIDESTRING message);
483 static void Form_Print(IPDF_JSPLATFORM* param,
488 FPDF_BOOL shrink_to_fit,
489 FPDF_BOOL print_as_image,
491 FPDF_BOOL annotations);
492 static void Form_SubmitForm(IPDF_JSPLATFORM* param,
495 FPDF_WIDESTRING url);
496 static void Form_GotoPage(IPDF_JSPLATFORM* param, int page_number);
497 static int Form_Browse(IPDF_JSPLATFORM* param, void* file_path, int length);
499 // IFSDK_PAUSE callbacks
500 static FPDF_BOOL Pause_NeedToPauseNow(IFSDK_PAUSE* param);
502 PDFEngine::Client* client_;
503 pp::Size document_size_; // Size of document in pixels.
505 // The scroll position in screen coordinates.
507 // The offset of the page into the viewport.
508 pp::Point page_offset_;
509 // The plugin size in screen coordinates.
510 pp::Size plugin_size_;
511 double current_zoom_;
512 unsigned int current_rotation_;
514 DocumentLoader doc_loader_; // Main document's loader.
516 std::string headers_;
517 pp::CompletionCallbackFactory<PDFiumEngine> find_factory_;
519 pp::CompletionCallbackFactory<PDFiumEngine> password_factory_;
520 int32_t password_tries_remaining_;
522 // The current text used for searching.
523 std::string current_find_text_;
525 // The PDFium wrapper object for the document.
528 // The PDFium wrapper for form data. Used even if there are no form controls
530 FPDF_FORMHANDLE form_;
532 // The page(s) of the document. Store a vector of pointers so that when the
533 // vector is resized we don't close the pages that are used in pending
535 std::vector<PDFiumPage*> pages_;
537 // The indexes of the pages currently visible.
538 std::vector<int> visible_pages_;
540 // The indexes of the pages pending download.
541 std::vector<int> pending_pages_;
543 // During handling of input events we don't want to unload any pages in
544 // callbacks to us from PDFium, since the current page can change while PDFium
545 // code still has a pointer to it.
546 bool defer_page_unload_;
547 std::vector<int> deferred_page_unloads_;
549 // Used for selection. There could be more than one range if selection spans
550 // more than one page.
551 std::vector<PDFiumRange> selection_;
552 // True if we're in the middle of selection.
555 MouseDownState mouse_down_state_;
557 // Used for searching.
558 typedef std::vector<PDFiumRange> FindResults;
559 FindResults find_results_;
560 // Which page to search next.
561 int next_page_to_search_;
562 // Where to stop searching.
563 int last_page_to_search_;
564 int last_character_index_to_search_; // -1 if search until end of page.
565 // Which result the user has currently selected.
566 FindTextIndex current_find_index_;
567 // Where to resume searching.
568 FindTextIndex resume_find_index_;
570 // Permissions bitfield.
571 unsigned long permissions_;
573 // Interface structure to provide access to document stream.
574 FPDF_FILEACCESS file_access_;
575 // Interface structure to check data availability in the document stream.
576 FileAvail file_availability_;
577 // Interface structure to request data chunks from the document stream.
578 DownloadHints download_hints_;
579 // Pointer to the document availability interface.
580 FPDF_AVAIL fpdf_availability_;
582 pp::Size default_page_size_;
584 // Used to manage timers that form fill API needs. The pair holds the timer
585 // period, in ms, and the callback function.
586 std::map<int, std::pair<int, TimerCallback> > timers_;
589 // Holds the page index of the last page that the mouse clicked on.
590 int last_page_mouse_down_;
592 // Holds the page index of the first visible page; refreshed by calling
593 // CalculateVisiblePages()
594 int first_visible_page_;
596 // Holds the page index of the most visible page; refreshed by calling
597 // CalculateVisiblePages()
598 int most_visible_page_;
600 // Set to true after FORM_DoDocumentJSAction/FORM_DoDocumentOpenAction have
601 // been called. Only after that can we call FORM_DoPageAAction.
602 bool called_do_document_action_;
604 // Records parts of form fields that need to be highlighted at next paint, in
605 // screen coordinates.
606 std::vector<pp::Rect> form_highlights_;
608 // Whether to render in grayscale or in color.
609 bool render_grayscale_;
611 // The link currently under the cursor.
612 std::string link_under_cursor_;
614 // Pending progressive paints.
615 struct ProgressivePaint {
616 pp::Rect rect; // In screen coordinates.
619 // Temporary used to figure out if in a series of Paint() calls whether this
620 // pending paint was updated or not.
623 std::vector<ProgressivePaint> progressive_paints_;
625 // Keeps track of when we started the last progressive paint, so that in our
626 // callback we can determine if we need to pause.
627 base::Time last_progressive_start_time_;
629 // The timeout to use for the current progressive paint.
630 int progressive_paint_timeout_;
632 // Shadow matrix for generating the page shadow bitmap.
633 scoped_ptr<ShadowMatrix> page_shadow_;
635 // Set to true if the user is being prompted for their password. Will be set
636 // to false after the user finishes getting their password.
637 bool getting_password_;
640 // Create a local variable of this when calling PDFium functions which can call
641 // our global callback when an unsupported feature is reached.
642 class ScopedUnsupportedFeature {
644 explicit ScopedUnsupportedFeature(PDFiumEngine* engine);
645 ~ScopedUnsupportedFeature();
647 PDFiumEngine* engine_;
648 PDFiumEngine* old_engine_;
651 class PDFiumEngineExports : public PDFEngineExports {
653 PDFiumEngineExports() {}
655 // See the definition of RenderPDFPageToDC in pdf.cc for details.
656 virtual bool RenderPDFPageToDC(const void* pdf_buffer,
659 const RenderingSettings& settings,
662 virtual bool RenderPDFPageToBitmap(const void* pdf_buffer,
665 const RenderingSettings& settings,
666 void* bitmap_buffer);
668 virtual bool GetPDFDocInfo(const void* pdf_buffer,
671 double* max_page_width);
673 // See the definition of GetPDFPageSizeByIndex in pdf.cc for details.
674 virtual bool GetPDFPageSizeByIndex(const void* pdf_buffer,
675 int pdf_buffer_size, int page_number,
676 double* width, double* height);
679 } // namespace chrome_pdf
681 #endif // PDF_PDFIUM_PDFIUM_ENGINE_H_