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. 4 5 #ifndef PDF_PDFIUM_PDFIUM_ENGINE_H_ 6 #define PDF_PDFIUM_PDFIUM_ENGINE_H_ 7 8 #include <map> 9 #include <string> 10 #include <utility> 11 #include <vector> 12 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" 27 28 namespace pp { 29 class KeyboardInputEvent; 30 class MouseInputEvent; 31 } 32 33 namespace chrome_pdf { 34 35 class ShadowMatrix; 36 37 class PDFiumEngine : public PDFEngine, 38 public DocumentLoader::Client, 39 public FPDF_FORMFILLINFO, 40 public IPDF_JSPLATFORM, 41 public IFSDK_PAUSE { 42 public: 43 explicit PDFiumEngine(PDFEngine::Client* client); 44 virtual ~PDFiumEngine(); 45 46 // PDFEngine implementation. 47 virtual bool New(const char* url); 48 virtual bool New(const char* url, 49 const char* headers); 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(); 97 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(); 105 106 void UnsupportedFeature(int type); 107 108 std::string current_find_text() const { return current_find_text_; } 109 110 FPDF_DOCUMENT doc() { return doc_; } 111 FPDF_FORMHANDLE form() { return form_; } 112 113 private: 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 { 119 public: 120 explicit SelectionChangeInvalidator(PDFiumEngine* engine); 121 ~SelectionChangeInvalidator(); 122 private: 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); 126 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_; 132 }; 133 134 friend class SelectionChangeInvalidator; 135 136 struct FileAvail : public FX_FILEAVAIL { 137 DocumentLoader* loader; 138 }; 139 140 struct DownloadHints : public FX_DOWNLOADHINTS { 141 DocumentLoader* loader; 142 }; 143 144 // PDFium interface to get block of data. 145 static int GetBlock(void* param, unsigned long position, 146 unsigned char* buffer, unsigned long size); 147 148 // PDFium interface to check is block of data is available. 149 static bool IsDataAvail(FX_FILEAVAIL* param, 150 size_t offset, size_t size); 151 152 // PDFium interface to request download of the block of data. 153 static void AddSegment(FX_DOWNLOADHINTS* param, 154 size_t offset, size_t size); 155 156 // We finished getting the pdf file, so load it. This will complete 157 // asynchronously (due to password fetching) and may be run multiple times. 158 void LoadDocument(); 159 160 // Try loading the document. Returns true if the document is successfully 161 // loaded or is already loaded otherwise it will return false. If 162 // |with_password| is set to true, the document will be loaded with 163 // |password|. If the document could not be loaded and needs a password, 164 // |needs_password| will be set to true. 165 bool TryLoadingDoc(bool with_password, 166 const std::string& password, 167 bool* needs_password); 168 169 // Ask the user for the document password and then continue loading the 170 // document. 171 void GetPasswordAndLoad(); 172 173 // Called when the password has been retrieved. 174 void OnGetPasswordComplete(int32_t result, 175 const pp::Var& password); 176 177 // Continues loading the document when the password has been retrieved, or if 178 // there is no password. 179 void ContinueLoadingDocument(bool has_password, 180 const std::string& password); 181 182 // Finish loading the document and notify the client that the document has 183 // been loaded. This should only be run after |doc_| has been loaded and the 184 // document is fully downloaded. If this has been run once, it will result in 185 // a no-op. 186 void FinishLoadingDocument(); 187 188 // Loads information about the pages in the document and calculate the 189 // document size. 190 void LoadPageInfo(bool reload); 191 192 // Calculate which pages should be displayed right now. 193 void CalculateVisiblePages(); 194 195 // Returns true iff the given page index is visible. CalculateVisiblePages 196 // must have been called first. 197 bool IsPageVisible(int index) const; 198 199 // Checks if a page is now available, and if so marks it as such and returns 200 // true. Otherwise, it will return false and will add the index to the given 201 // array if it's not already there. 202 bool CheckPageAvailable(int index, std::vector<int>* pending); 203 204 // Helper function to get a given page's size in pixels. This is not part of 205 // PDFiumPage because we might not have that structure when we need this. 206 pp::Size GetPageSize(int index); 207 208 void UpdateTickMarks(); 209 210 // Called to continue searching so we don't block the main thread. 211 void ContinueFind(int32_t result); 212 213 // Inserts a find result into find_results_, which is sorted. 214 void AddFindResult(const PDFiumRange& result); 215 216 // Search a page using PDFium's methods. Doesn't work with unicode. This 217 // function is just kept arount in case PDFium code is fixed. 218 void SearchUsingPDFium(const base::string16& term, 219 bool case_sensitive, 220 bool first_search, 221 int character_to_start_searching_from, 222 int current_page); 223 224 // Search a page ourself using ICU. 225 void SearchUsingICU(const base::string16& term, 226 bool case_sensitive, 227 bool first_search, 228 int character_to_start_searching_from, 229 int current_page); 230 231 // Input event handlers. 232 bool OnMouseDown(const pp::MouseInputEvent& event); 233 bool OnMouseUp(const pp::MouseInputEvent& event); 234 bool OnMouseMove(const pp::MouseInputEvent& event); 235 bool OnKeyDown(const pp::KeyboardInputEvent& event); 236 bool OnKeyUp(const pp::KeyboardInputEvent& event); 237 bool OnChar(const pp::KeyboardInputEvent& event); 238 239 pp::Buffer_Dev PrintPagesAsRasterPDF( 240 const PP_PrintPageNumberRange_Dev* page_ranges, 241 uint32_t page_range_count, 242 const PP_PrintSettings_Dev& print_settings); 243 pp::Buffer_Dev PrintPagesAsPDF(const PP_PrintPageNumberRange_Dev* page_ranges, 244 uint32_t page_range_count, 245 const PP_PrintSettings_Dev& print_settings); 246 pp::Buffer_Dev GetFlattenedPrintData(const FPDF_DOCUMENT& doc); 247 void FitContentsToPrintableAreaIfRequired( 248 const FPDF_DOCUMENT& doc, 249 const PP_PrintSettings_Dev& print_settings); 250 void SaveSelectedFormForPrint(); 251 252 // Given a mouse event, returns which page and character location it's closest 253 // to. 254 PDFiumPage::Area GetCharIndex(const pp::MouseInputEvent& event, 255 int* page_index, 256 int* char_index, 257 PDFiumPage::LinkTarget* target); 258 PDFiumPage::Area GetCharIndex(const pp::Point& point, 259 int* page_index, 260 int* char_index, 261 PDFiumPage::LinkTarget* target); 262 263 void OnSingleClick(int page_index, int char_index); 264 void OnMultipleClick(int click_count, int page_index, int char_index); 265 266 // Starts a progressive paint operation given a rectangle in screen 267 // coordinates. Returns the index in progressive_rects_. 268 int StartPaint(int page_index, const pp::Rect& dirty); 269 270 // Continues a paint operation that was started earlier. Returns true if the 271 // paint is done, or false if it needs to be continued. 272 bool ContinuePaint(int progressive_index, pp::ImageData* image_data); 273 274 // Called once PDFium is finished rendering a page so that we draw our 275 // borders, highlighting etc. 276 void FinishPaint(int progressive_index, pp::ImageData* image_data); 277 278 // Stops any paints that are in progress. 279 void CancelPaints(); 280 281 // Invalidates all pages. Use this when some global parameter, such as page 282 // orientation, has changed. 283 void InvalidateAllPages(); 284 285 // If the page is narrower than the document size, paint the extra space 286 // with the page background. 287 void FillPageSides(int progressive_index); 288 289 void PaintPageShadow(int progressive_index, pp::ImageData* image_data); 290 291 // Highlight visible find results and selections. 292 void DrawSelections(int progressive_index, pp::ImageData* image_data); 293 294 // Paints an page that hasn't finished downloading. 295 void PaintUnavailablePage(int page_index, 296 const pp::Rect& dirty, 297 pp::ImageData* image_data); 298 299 // Given a page index, returns the corresponding index in progressive_rects_, 300 // or -1 if it doesn't exist. 301 int GetProgressiveIndex(int page_index) const; 302 303 // Creates a FPDF_BITMAP from a rectangle in screen coordinates. 304 FPDF_BITMAP CreateBitmap(const pp::Rect& rect, 305 pp::ImageData* image_data) const; 306 307 // Given a rectangle in screen coordinates, returns the coordinates in the 308 // units that PDFium rendering functions expect. 309 void GetPDFiumRect(int page_index, const pp::Rect& rect, int* start_x, 310 int* start_y, int* size_x, int* size_y) const; 311 312 // Returns the rendering flags to pass to PDFium. 313 int GetRenderingFlags() const; 314 315 // Returns the currently visible rectangle in document coordinates. 316 pp::Rect GetVisibleRect() const; 317 318 // Returns a page's rect in screen coordinates, as well as its surrounding 319 // border areas and bottom separator. 320 pp::Rect GetPageScreenRect(int page_index) const; 321 322 // Given a rectangle in document coordinates, returns the rectange into screen 323 // coordinates (i.e. 0,0 is top left corner of plugin area). If it's not 324 // visible, an empty rectangle is returned. 325 pp::Rect GetScreenRect(const pp::Rect& rect) const; 326 327 // Highlights the given rectangle. 328 void Highlight(void* buffer, 329 int stride, 330 const pp::Rect& rect, 331 std::vector<pp::Rect>* highlighted_rects); 332 333 // Helper function to convert a device to page coordinates. If the page is 334 // not yet loaded, page_x and page_y will be set to 0. 335 void DeviceToPage(int page_index, 336 float device_x, 337 float device_y, 338 double* page_x, 339 double* page_y); 340 341 // Helper function to get the index of a given FPDF_PAGE. Returns -1 if not 342 // found. 343 int GetVisiblePageIndex(FPDF_PAGE page); 344 345 // Helper function to change the current page, running page open/close 346 // triggers as necessary. 347 void SetCurrentPage(int index); 348 349 // Transform |page| contents to fit in the selected printer paper size. 350 void TransformPDFPageForPrinting(FPDF_PAGE page, 351 const PP_PrintSettings_Dev& print_settings); 352 353 void DrawPageShadow(const pp::Rect& page_rect, 354 const pp::Rect& shadow_rect, 355 const pp::Rect& clip_rect, 356 pp::ImageData* image_data); 357 358 void GetRegion(const pp::Point& location, 359 pp::ImageData* image_data, 360 void** region, 361 int* stride) const; 362 363 // Called when the selection changes. 364 void OnSelectionChanged(); 365 366 // FPDF_FORMFILLINFO callbacks. 367 static void Form_Invalidate(FPDF_FORMFILLINFO* param, 368 FPDF_PAGE page, 369 double left, 370 double top, 371 double right, 372 double bottom); 373 static void Form_OutputSelectedRect(FPDF_FORMFILLINFO* param, 374 FPDF_PAGE page, 375 double left, 376 double top, 377 double right, 378 double bottom); 379 static void Form_SetCursor(FPDF_FORMFILLINFO* param, int cursor_type); 380 static int Form_SetTimer(FPDF_FORMFILLINFO* param, 381 int elapse, 382 TimerCallback timer_func); 383 static void Form_KillTimer(FPDF_FORMFILLINFO* param, int timer_id); 384 static FPDF_SYSTEMTIME Form_GetLocalTime(FPDF_FORMFILLINFO* param); 385 static void Form_OnChange(FPDF_FORMFILLINFO* param); 386 static FPDF_PAGE Form_GetPage(FPDF_FORMFILLINFO* param, 387 FPDF_DOCUMENT document, 388 int page_index); 389 static FPDF_PAGE Form_GetCurrentPage(FPDF_FORMFILLINFO* param, 390 FPDF_DOCUMENT document); 391 static int Form_GetRotation(FPDF_FORMFILLINFO* param, FPDF_PAGE page); 392 static void Form_ExecuteNamedAction(FPDF_FORMFILLINFO* param, 393 FPDF_BYTESTRING named_action); 394 static void Form_SetTextFieldFocus(FPDF_FORMFILLINFO* param, 395 FPDF_WIDESTRING value, 396 FPDF_DWORD valueLen, 397 FPDF_BOOL is_focus); 398 static void Form_DoURIAction(FPDF_FORMFILLINFO* param, FPDF_BYTESTRING uri); 399 static void Form_DoGoToAction(FPDF_FORMFILLINFO* param, 400 int page_index, 401 int zoom_mode, 402 float* position_array, 403 int size_of_array); 404 405 // IPDF_JSPLATFORM callbacks. 406 static int Form_Alert(IPDF_JSPLATFORM* param, 407 FPDF_WIDESTRING message, 408 FPDF_WIDESTRING title, 409 int type, 410 int icon); 411 static void Form_Beep(IPDF_JSPLATFORM* param, int type); 412 static int Form_Response(IPDF_JSPLATFORM* param, 413 FPDF_WIDESTRING question, 414 FPDF_WIDESTRING title, 415 FPDF_WIDESTRING default_response, 416 FPDF_WIDESTRING label, 417 FPDF_BOOL password, 418 void* response, 419 int length); 420 static int Form_GetFilePath(IPDF_JSPLATFORM* param, 421 void* file_path, 422 int length); 423 static void Form_Mail(IPDF_JSPLATFORM* param, 424 void* mail_data, 425 int length, 426 FPDF_BOOL ui, 427 FPDF_WIDESTRING to, 428 FPDF_WIDESTRING subject, 429 FPDF_WIDESTRING cc, 430 FPDF_WIDESTRING bcc, 431 FPDF_WIDESTRING message); 432 static void Form_Print(IPDF_JSPLATFORM* param, 433 FPDF_BOOL ui, 434 int start, 435 int end, 436 FPDF_BOOL silent, 437 FPDF_BOOL shrink_to_fit, 438 FPDF_BOOL print_as_image, 439 FPDF_BOOL reverse, 440 FPDF_BOOL annotations); 441 static void Form_SubmitForm(IPDF_JSPLATFORM* param, 442 void* form_data, 443 int length, 444 FPDF_WIDESTRING url); 445 static void Form_GotoPage(IPDF_JSPLATFORM* param, int page_number); 446 static int Form_Browse(IPDF_JSPLATFORM* param, void* file_path, int length); 447 448 // IFSDK_PAUSE callbacks 449 static FPDF_BOOL Pause_NeedToPauseNow(IFSDK_PAUSE* param); 450 451 PDFEngine::Client* client_; 452 pp::Size document_size_; // Size of document in pixels. 453 454 // The scroll position in screen coordinates. 455 pp::Point position_; 456 // The offset of the page into the viewport. 457 pp::Point page_offset_; 458 // The plugin size in screen coordinates. 459 pp::Size plugin_size_; 460 double current_zoom_; 461 unsigned int current_rotation_; 462 463 DocumentLoader doc_loader_; // Main document's loader. 464 std::string url_; 465 std::string headers_; 466 pp::CompletionCallbackFactory<PDFiumEngine> find_factory_; 467 468 pp::CompletionCallbackFactory<PDFiumEngine> password_factory_; 469 int32_t password_tries_remaining_; 470 471 // The current text used for searching. 472 std::string current_find_text_; 473 474 // The PDFium wrapper object for the document. 475 FPDF_DOCUMENT doc_; 476 477 // The PDFium wrapper for form data. Used even if there are no form controls 478 // on the page. 479 FPDF_FORMHANDLE form_; 480 481 // The page(s) of the document. Store a vector of pointers so that when the 482 // vector is resized we don't close the pages that are used in pending 483 // paints. 484 std::vector<PDFiumPage*> pages_; 485 486 // The indexes of the pages currently visible. 487 std::vector<int> visible_pages_; 488 489 // The indexes of the pages pending download. 490 std::vector<int> pending_pages_; 491 492 // During handling of input events we don't want to unload any pages in 493 // callbacks to us from PDFium, since the current page can change while PDFium 494 // code still has a pointer to it. 495 bool defer_page_unload_; 496 std::vector<int> deferred_page_unloads_; 497 498 // Used for selection. There could be more than one range if selection spans 499 // more than one page. 500 std::vector<PDFiumRange> selection_; 501 // True if we're in the middle of selection. 502 bool selecting_; 503 504 // Used for searching. 505 typedef std::vector<PDFiumRange> FindResults; 506 FindResults find_results_; 507 // Which page to search next. 508 int next_page_to_search_; 509 // Where to stop searching. 510 int last_page_to_search_; 511 int last_character_index_to_search_; // -1 if search until end of page. 512 // Which result the user has currently selected. 513 int current_find_index_; 514 515 // Permissions bitfield. 516 unsigned long permissions_; 517 518 // Interface structure to provide access to document stream. 519 FPDF_FILEACCESS file_access_; 520 // Interface structure to check data availability in the document stream. 521 FileAvail file_availability_; 522 // Interface structure to request data chunks from the document stream. 523 DownloadHints download_hints_; 524 // Pointer to the document availability interface. 525 FPDF_AVAIL fpdf_availability_; 526 527 pp::Size default_page_size_; 528 529 // Used to manage timers that form fill API needs. The pair holds the timer 530 // period, in ms, and the callback function. 531 std::map<int, std::pair<int, TimerCallback> > timers_; 532 int next_timer_id_; 533 534 // Holds the page index of the last page that the mouse clicked on. 535 int last_page_mouse_down_; 536 537 // Holds the page index of the first visible page; refreshed by calling 538 // CalculateVisiblePages() 539 int first_visible_page_; 540 541 // Holds the page index of the most visible page; refreshed by calling 542 // CalculateVisiblePages() 543 int most_visible_page_; 544 545 // Set to true after FORM_DoDocumentJSAction/FORM_DoDocumentOpenAction have 546 // been called. Only after that can we call FORM_DoPageAAction. 547 bool called_do_document_action_; 548 549 // Records parts of form fields that need to be highlighted at next paint, in 550 // screen coordinates. 551 std::vector<pp::Rect> form_highlights_; 552 553 // Whether to render in grayscale or in color. 554 bool render_grayscale_; 555 556 // The link currently under the cursor. 557 std::string link_under_cursor_; 558 559 // Pending progressive paints. 560 struct ProgressivePaint { 561 pp::Rect rect; // In screen coordinates. 562 FPDF_BITMAP bitmap; 563 int page_index; 564 // Temporary used to figure out if in a series of Paint() calls whether this 565 // pending paint was updated or not. 566 int painted_; 567 }; 568 std::vector<ProgressivePaint> progressive_paints_; 569 570 // Keeps track of when we started the last progressive paint, so that in our 571 // callback we can determine if we need to pause. 572 base::Time last_progressive_start_time_; 573 574 // The timeout to use for the current progressive paint. 575 int progressive_paint_timeout_; 576 577 // Shadow matrix for generating the page shadow bitmap. 578 scoped_ptr<ShadowMatrix> page_shadow_; 579 580 // Set to true if the user is being prompted for their password. Will be set 581 // to false after the user finishes getting their password. 582 bool getting_password_; 583 }; 584 585 // Create a local variable of this when calling PDFium functions which can call 586 // our global callback when an unsupported feature is reached. 587 class ScopedUnsupportedFeature { 588 public: 589 explicit ScopedUnsupportedFeature(PDFiumEngine* engine); 590 ~ScopedUnsupportedFeature(); 591 private: 592 PDFiumEngine* engine_; 593 PDFiumEngine* old_engine_; 594 }; 595 596 class PDFiumEngineExports : public PDFEngineExports { 597 public: 598 PDFiumEngineExports() {} 599 #if defined(OS_WIN) 600 // See the definition of RenderPDFPageToDC in pdf.cc for details. 601 virtual bool RenderPDFPageToDC(const void* pdf_buffer, 602 int buffer_size, 603 int page_number, 604 const RenderingSettings& settings, 605 HDC dc); 606 #endif // OS_WIN 607 virtual bool RenderPDFPageToBitmap(const void* pdf_buffer, 608 int pdf_buffer_size, 609 int page_number, 610 const RenderingSettings& settings, 611 void* bitmap_buffer); 612 613 virtual bool GetPDFDocInfo(const void* pdf_buffer, 614 int buffer_size, 615 int* page_count, 616 double* max_page_width); 617 }; 618 619 } // namespace chrome_pdf 620 621 #endif // PDF_PDFIUM_PDFIUM_ENGINE_H_ 622