3207ebe336000ca0afd373fb31af1e5b83e0c872
[pdfium.git] / fpdfsdk / src / fpdfview.cpp
1 // Copyright 2014 PDFium 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 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
6
7 #include "../include/fsdk_define.h"
8 #include "../include/fsdk_mgr.h"
9 #include "../include/fpdfview.h"
10 #include "../include/fsdk_rendercontext.h"
11 #include "../include/fpdf_progressive.h"
12 #include "../include/fpdf_ext.h"
13 #include "../../../core/src/fxcrt/fx_safe_types.h"
14 #include "../../third_party/base/numerics/safe_conversions_impl.h"
15
16 CPDF_CustomAccess::CPDF_CustomAccess(FPDF_FILEACCESS* pFileAccess)
17 {
18         if (pFileAccess)
19                 m_FileAccess = *pFileAccess;
20 }
21
22 FX_BOOL CPDF_CustomAccess::ReadBlock(void* buffer, FX_FILESIZE offset, size_t size)
23 {
24     if (offset < 0) {
25         return FALSE;
26     }
27     FX_SAFE_FILESIZE newPos = pdfium::base::checked_cast<FX_FILESIZE, size_t>(size);
28     newPos += offset;
29     if (!newPos.IsValid() || newPos.ValueOrDie() > m_FileAccess.m_FileLen) {
30         return FALSE;
31     }
32     return m_FileAccess.m_GetBlock(m_FileAccess.m_Param, offset,(FX_LPBYTE) buffer, size);
33 }
34
35 //0 bit: FPDF_POLICY_MACHINETIME_ACCESS
36 static FX_DWORD foxit_sandbox_policy = 0xFFFFFFFF;
37
38 void FSDK_SetSandBoxPolicy(FPDF_DWORD policy, FPDF_BOOL enable)
39 {
40         switch(policy)
41         {
42         case FPDF_POLICY_MACHINETIME_ACCESS:
43                 {
44                         if(enable)
45                                 foxit_sandbox_policy |= 0x01;
46                         else
47                                 foxit_sandbox_policy &= 0xFFFFFFFE;
48                 }
49                 break;
50         default:
51                 break;
52         }
53 }
54
55 FPDF_BOOL FSDK_IsSandBoxPolicyEnabled(FPDF_DWORD policy)
56 {
57         switch(policy)
58         {
59         case FPDF_POLICY_MACHINETIME_ACCESS:
60                 {
61                         if(foxit_sandbox_policy&0x01)
62                                 return TRUE;
63                         else
64                                 return FALSE;
65                 }
66                 break;
67         default:
68                 break;
69         }
70         return FALSE;
71 }
72
73
74 #ifndef _T
75 #define _T(x) x
76 #endif
77
78 #ifdef API5
79         CPDF_ModuleMgr* g_pModuleMgr = NULL;
80 #else
81         CCodec_ModuleMgr*       g_pCodecModule = NULL;
82 #endif
83
84 //extern CPDFSDK_FormFillApp* g_pFormFillApp;
85
86 #if _FX_OS_ == _FX_LINUX_EMBEDDED_
87 class CFontMapper : public IPDF_FontMapper
88 {
89 public:
90         CFontMapper();
91         virtual ~CFontMapper();
92
93         virtual FT_Face FindSubstFont(
94                                                         CPDF_Document* pDoc,                            // [IN] The PDF document
95                                                         const CFX_ByteString& face_name,        // [IN] Original name
96                                                         FX_BOOL bTrueType,                                      // [IN] TrueType or Type1
97                                                         FX_DWORD flags,                                         // [IN] PDF font flags (see PDF Reference section 5.7.1)
98                                                         int font_weight,                                        // [IN] original font weight. 0 for not specified
99                                                         int CharsetCP,                                          // [IN] code page for charset (see Win32 GetACP())
100                                                         FX_BOOL bVertical,
101                                                         CPDF_SubstFont* pSubstFont                      // [OUT] Subst font data
102                                                 );
103
104         FT_Face m_SysFace;
105 };
106
107 CFontMapper* g_pFontMapper = NULL;
108 #endif          // #if _FX_OS_ == _FX_LINUX_EMBEDDED_
109
110 DLLEXPORT void STDCALL FPDF_InitLibrary()
111 {
112         g_pCodecModule = CCodec_ModuleMgr::Create();
113         
114         CFX_GEModule::Create();
115         CFX_GEModule::Get()->SetCodecModule(g_pCodecModule);
116         
117         CPDF_ModuleMgr::Create();
118         CPDF_ModuleMgr::Get()->SetCodecModule(g_pCodecModule);
119         CPDF_ModuleMgr::Get()->InitPageModule();
120         CPDF_ModuleMgr::Get()->InitRenderModule();
121         CPDF_ModuleMgr * pModuleMgr = CPDF_ModuleMgr::Get();
122         if ( pModuleMgr )
123         {
124                 pModuleMgr->LoadEmbeddedGB1CMaps();
125                 pModuleMgr->LoadEmbeddedJapan1CMaps();
126                 pModuleMgr->LoadEmbeddedCNS1CMaps();
127                 pModuleMgr->LoadEmbeddedKorea1CMaps();
128         }
129 }
130
131
132 DLLEXPORT void STDCALL FPDF_DestroyLibrary()
133 {
134
135 #if _FX_OS_ == _FX_LINUX_EMBEDDED_
136         if (g_pFontMapper) delete g_pFontMapper;
137 #endif
138 #ifdef API5
139         g_pModuleMgr->Destroy();
140 #else
141         CPDF_ModuleMgr::Destroy();
142         CFX_GEModule::Destroy();
143         g_pCodecModule->Destroy();
144 #endif
145 }
146
147 #ifndef _WIN32
148 int g_LastError;
149 void SetLastError(int err)
150 {
151         g_LastError = err;
152 }
153
154 int GetLastError()
155 {
156         return g_LastError;
157 }
158 #endif
159
160 void ProcessParseError(FX_DWORD err_code)
161 {
162         // Translate FPDFAPI error code to FPDFVIEW error code
163         switch (err_code) {
164                 case PDFPARSE_ERROR_FILE:
165                         err_code = FPDF_ERR_FILE;
166                         break;
167                 case PDFPARSE_ERROR_FORMAT:
168                         err_code = FPDF_ERR_FORMAT;
169                         break;
170                 case PDFPARSE_ERROR_PASSWORD:
171                         err_code = FPDF_ERR_PASSWORD;
172                         break;
173                 case PDFPARSE_ERROR_HANDLER:
174                         err_code = FPDF_ERR_SECURITY;
175                         break;
176         }
177         SetLastError(err_code);
178 }
179
180 DLLEXPORT void  STDCALL FPDF_SetSandBoxPolicy(FPDF_DWORD policy, FPDF_BOOL enable)
181 {
182         return FSDK_SetSandBoxPolicy(policy, enable);
183 }
184
185 DLLEXPORT FPDF_DOCUMENT STDCALL FPDF_LoadDocument(FPDF_STRING file_path, FPDF_BYTESTRING password)
186 {
187         CPDF_Parser* pParser = new CPDF_Parser;
188         pParser->SetPassword(password);
189
190         FX_DWORD err_code = pParser->StartParse((FX_LPCSTR)file_path);
191         if (err_code) {
192                 delete pParser;
193                 ProcessParseError(err_code);
194                 return NULL;
195         }
196         return pParser->GetDocument();
197 }
198
199 extern void CheckUnSupportError(CPDF_Document * pDoc, FX_DWORD err_code);
200
201 class CMemFile FX_FINAL: public IFX_FileRead
202 {
203 public:
204         CMemFile(FX_BYTE* pBuf, FX_FILESIZE size):m_pBuf(pBuf),m_size(size) {}
205
206         virtual void                    Release() {delete this;}
207         virtual FX_FILESIZE             GetSize() {return m_size;}
208         virtual FX_BOOL                 ReadBlock(void* buffer, FX_FILESIZE offset, size_t size) 
209         {
210             if (offset < 0) {
211                 return FALSE;
212             }
213             FX_SAFE_FILESIZE newPos = pdfium::base::checked_cast<FX_FILESIZE, size_t>(size);
214             newPos += offset;
215             if (!newPos.IsValid() || newPos.ValueOrDie() > (FX_DWORD)m_size) {
216                 return FALSE;
217             }
218             FXSYS_memcpy(buffer, m_pBuf+offset, size);
219             return TRUE;
220         }
221 private:
222         FX_BYTE* m_pBuf;
223         FX_FILESIZE m_size;
224 };
225 DLLEXPORT FPDF_DOCUMENT STDCALL FPDF_LoadMemDocument(const void* data_buf, int size, FPDF_BYTESTRING password)
226 {
227         CPDF_Parser* pParser = new CPDF_Parser;
228         pParser->SetPassword(password);
229         CMemFile* pMemFile = new CMemFile((FX_BYTE*)data_buf, size);
230         FX_DWORD err_code = pParser->StartParse(pMemFile);
231         if (err_code) {
232                 delete pParser;
233                 ProcessParseError(err_code);
234                 return NULL;
235         }
236         CPDF_Document * pDoc = NULL;
237         pDoc = pParser?pParser->GetDocument():NULL;
238         CheckUnSupportError(pDoc, err_code);
239         return pParser->GetDocument();
240 }
241
242 DLLEXPORT FPDF_DOCUMENT STDCALL FPDF_LoadCustomDocument(FPDF_FILEACCESS* pFileAccess, FPDF_BYTESTRING password)
243 {
244         CPDF_Parser* pParser = new CPDF_Parser;
245         pParser->SetPassword(password);
246         CPDF_CustomAccess* pFile = new CPDF_CustomAccess(pFileAccess);
247         FX_DWORD err_code = pParser->StartParse(pFile);
248         if (err_code) {
249                 delete pParser;
250                 ProcessParseError(err_code);
251                 return NULL;
252         }
253         CPDF_Document * pDoc = NULL;
254         pDoc = pParser?pParser->GetDocument():NULL;
255         CheckUnSupportError(pDoc, err_code);
256         return pParser->GetDocument();
257 }
258
259 DLLEXPORT FPDF_BOOL STDCALL FPDF_GetFileVersion(FPDF_DOCUMENT doc, int* fileVersion)
260 {
261         if(!doc||!fileVersion) return FALSE;
262         *fileVersion = 0;
263         CPDF_Document* pDoc = (CPDF_Document*)doc;
264         CPDF_Parser* pParser = (CPDF_Parser*)pDoc->GetParser();
265         if(!pParser)
266                 return FALSE;
267         *fileVersion = pParser->GetFileVersion();
268         return TRUE;
269 }
270
271 // jabdelmalek: changed return type from FX_DWORD to build on Linux (and match header).
272 DLLEXPORT unsigned long STDCALL FPDF_GetDocPermissions(FPDF_DOCUMENT document)
273 {
274         if (document == NULL) return 0;
275         CPDF_Document*pDoc = (CPDF_Document*)document;
276         CPDF_Parser* pParser =  (CPDF_Parser*)pDoc->GetParser();
277         CPDF_Dictionary* pDict = pParser->GetEncryptDict();
278         if (pDict == NULL) return (FX_DWORD)-1;
279
280         return pDict->GetInteger("P");
281 }
282
283 DLLEXPORT int STDCALL FPDF_GetSecurityHandlerRevision(FPDF_DOCUMENT document)
284 {
285     if (document == NULL) return -1;
286     CPDF_Document*pDoc = (CPDF_Document*)document;
287     CPDF_Parser* pParser = (CPDF_Parser*)pDoc->GetParser();
288     CPDF_Dictionary* pDict = pParser->GetEncryptDict();
289     if (pDict == NULL) return -1;
290
291     return pDict->GetInteger("R");
292 }
293
294 DLLEXPORT int STDCALL FPDF_GetPageCount(FPDF_DOCUMENT document)
295 {
296         if (document == NULL) return 0;
297         return ((CPDF_Document*)document)->GetPageCount();
298 }
299
300 DLLEXPORT FPDF_PAGE STDCALL FPDF_LoadPage(FPDF_DOCUMENT document, int page_index)
301 {
302         if (document == NULL) return NULL;
303         if (page_index < 0 || page_index >= FPDF_GetPageCount(document)) return NULL;
304
305         CPDF_Document* pDoc = (CPDF_Document*)document;
306         if (pDoc == NULL) return NULL;
307         CPDF_Dictionary* pDict = pDoc->GetPage(page_index);
308         if (pDict == NULL) return NULL;
309         CPDF_Page* pPage = new CPDF_Page;
310         pPage->Load(pDoc, pDict);
311         pPage->ParseContent();
312         return pPage;
313 }
314
315 DLLEXPORT double STDCALL FPDF_GetPageWidth(FPDF_PAGE page)
316 {
317         if (!page)
318                 return 0.0;
319         return ((CPDF_Page*)page)->GetPageWidth();
320 }
321
322 DLLEXPORT double STDCALL FPDF_GetPageHeight(FPDF_PAGE page)
323 {
324         if (!page) return 0.0;
325         return ((CPDF_Page*)page)->GetPageHeight();
326 }
327
328 void DropContext(void* data)
329 {
330         delete (CRenderContext*)data;
331 }
332
333 void FPDF_RenderPage_Retail(CRenderContext* pContext, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
334                                                 int rotate, int flags,FX_BOOL bNeedToRestore, IFSDK_PAUSE_Adapter * pause  );
335 void (*Func_RenderPage)(CRenderContext*, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
336                                                 int rotate, int flags,FX_BOOL bNeedToRestore, IFSDK_PAUSE_Adapter * pause  ) = FPDF_RenderPage_Retail;
337
338 #if defined(_DEBUG) || defined(DEBUG)
339 #define DEBUG_TRACE
340 #endif
341
342 #if defined(_WIN32)
343 DLLEXPORT void STDCALL FPDF_RenderPage(HDC dc, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
344                                                 int rotate, int flags)
345 {
346         if (page==NULL) return;
347         CPDF_Page* pPage = (CPDF_Page*)page;
348
349         CRenderContext* pContext = new CRenderContext;
350         pPage->SetPrivateData((void*)1, pContext, DropContext);
351
352 #ifndef _WIN32_WCE
353         CFX_DIBitmap* pBitmap = NULL;
354         FX_BOOL bBackgroundAlphaNeeded=FALSE;
355         bBackgroundAlphaNeeded = pPage->BackgroundAlphaNeeded();
356         if (bBackgroundAlphaNeeded)
357         {
358                 
359                 pBitmap = new CFX_DIBitmap;
360                 pBitmap->Create(size_x, size_y, FXDIB_Argb);
361                 pBitmap->Clear(0x00ffffff);
362 #ifdef _SKIA_SUPPORT_
363                 pContext->m_pDevice = new CFX_SkiaDevice;
364                 ((CFX_SkiaDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)pBitmap);
365 #else
366                 pContext->m_pDevice = new CFX_FxgeDevice;
367                 ((CFX_FxgeDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)pBitmap);
368 #endif
369         }
370         else
371             pContext->m_pDevice = new CFX_WindowsDevice(dc);
372
373         Func_RenderPage(pContext, page, start_x, start_y, size_x, size_y, rotate, flags,TRUE,NULL);
374
375         if (bBackgroundAlphaNeeded) 
376         {
377                 if (pBitmap)
378                 {
379                         CFX_WindowsDevice WinDC(dc);
380                         
381                         if (WinDC.GetDeviceCaps(FXDC_DEVICE_CLASS) == FXDC_PRINTER)
382                         {
383                                 CFX_DIBitmap* pDst = new CFX_DIBitmap;
384                                 int pitch = pBitmap->GetPitch();
385                                 pDst->Create(size_x, size_y, FXDIB_Rgb32);
386                                 FXSYS_memset(pDst->GetBuffer(), -1, pitch*size_y);
387                                 pDst->CompositeBitmap(0, 0, size_x, size_y, pBitmap, 0, 0, FXDIB_BLEND_NORMAL, NULL, FALSE, NULL);
388                                 WinDC.StretchDIBits(pDst,0,0,size_x,size_y);
389                                 delete pDst;
390                         }
391                         else
392                                 WinDC.SetDIBits(pBitmap,0,0);
393
394                 }
395         }
396 #else
397         // get clip region
398         RECT rect, cliprect;
399         rect.left = start_x;
400         rect.top = start_y;
401         rect.right = start_x + size_x;
402         rect.bottom = start_y + size_y;
403         GetClipBox(dc, &cliprect);
404         IntersectRect(&rect, &rect, &cliprect);
405         int width = rect.right - rect.left;
406         int height = rect.bottom - rect.top;
407
408 #ifdef DEBUG_TRACE
409         {
410                 char str[128];
411                 memset(str, 0, sizeof(str));
412                 FXSYS_snprintf(str, sizeof(str) - 1, "Rendering DIB %d x %d", width, height);
413                 CPDF_ModuleMgr::Get()->ReportError(999, str);
414         }
415 #endif
416
417         // Create a DIB section
418         LPVOID pBuffer;
419         BITMAPINFOHEADER bmih;
420         FXSYS_memset(&bmih, 0, sizeof bmih);
421         bmih.biSize = sizeof bmih;
422         bmih.biBitCount = 24;
423         bmih.biHeight = -height;
424         bmih.biPlanes = 1;
425         bmih.biWidth = width;
426         pContext->m_hBitmap = CreateDIBSection(dc, (BITMAPINFO*)&bmih, DIB_RGB_COLORS, &pBuffer, NULL, 0);
427         if (pContext->m_hBitmap == NULL) {
428 #if defined(DEBUG) || defined(_DEBUG)
429                 char str[128];
430                 memset(str, 0, sizeof(str));
431                 FXSYS_snprintf(str, sizeof(str) - 1, "Error CreateDIBSection: %d x %d, error code = %d", width, height, GetLastError());
432                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, str);
433 #else
434                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, NULL);
435 #endif
436         }
437         FXSYS_memset(pBuffer, 0xff, height*((width*3+3)/4*4));
438
439 #ifdef DEBUG_TRACE
440         {
441                 CPDF_ModuleMgr::Get()->ReportError(999, "DIBSection created");
442         }
443 #endif
444
445         // Create a device with this external buffer
446         pContext->m_pBitmap = new CFX_DIBitmap;
447         pContext->m_pBitmap->Create(width, height, FXDIB_Rgb, (FX_LPBYTE)pBuffer);
448         pContext->m_pDevice = new CPDF_FxgeDevice;
449         ((CPDF_FxgeDevice*)pContext->m_pDevice)->Attach(pContext->m_pBitmap);
450
451 #ifdef DEBUG_TRACE
452         CPDF_ModuleMgr::Get()->ReportError(999, "Ready for PDF rendering");
453 #endif
454
455         // output to bitmap device
456         Func_RenderPage(pContext, page, start_x - rect.left, start_y - rect.top, size_x, size_y, rotate, flags);
457
458 #ifdef DEBUG_TRACE
459         CPDF_ModuleMgr::Get()->ReportError(999, "Finished PDF rendering");
460 #endif
461
462         // Now output to real device
463         HDC hMemDC = CreateCompatibleDC(dc);
464         if (hMemDC == NULL) {
465 #if defined(DEBUG) || defined(_DEBUG)
466                 char str[128];
467                 memset(str, 0, sizeof(str));
468                 FXSYS_snprintf(str, sizeof(str) - 1, "Error CreateCompatibleDC. Error code = %d", GetLastError());
469                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, str);
470 #else
471                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, NULL);
472 #endif
473         }
474
475         HGDIOBJ hOldBitmap = SelectObject(hMemDC, pContext->m_hBitmap);
476
477 #ifdef DEBUG_TRACE
478         CPDF_ModuleMgr::Get()->ReportError(999, "Ready for screen rendering");
479 #endif
480
481         BitBlt(dc, rect.left, rect.top, width, height, hMemDC, 0, 0, SRCCOPY);
482         SelectObject(hMemDC, hOldBitmap);
483         DeleteDC(hMemDC);
484
485 #ifdef DEBUG_TRACE
486         CPDF_ModuleMgr::Get()->ReportError(999, "Finished screen rendering");
487 #endif
488
489 #endif
490         if (bBackgroundAlphaNeeded)
491         {
492                 if (pBitmap)
493                         delete pBitmap;
494                 pBitmap = NULL;
495         }
496         delete pContext;
497         pPage->RemovePrivateData((void*)1);
498 }
499 #endif
500
501 DLLEXPORT void STDCALL FPDF_RenderPageBitmap(FPDF_BITMAP bitmap, FPDF_PAGE page, int start_x, int start_y, 
502                                                 int size_x, int size_y, int rotate, int flags)
503 {
504         if (bitmap == NULL || page == NULL) return;
505         CPDF_Page* pPage = (CPDF_Page*)page;
506
507
508         CRenderContext* pContext = new CRenderContext;
509         pPage->SetPrivateData((void*)1, pContext, DropContext);
510 #ifdef _SKIA_SUPPORT_
511         pContext->m_pDevice = new CFX_SkiaDevice;
512
513         if (flags & FPDF_REVERSE_BYTE_ORDER)
514                 ((CFX_SkiaDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap,0,TRUE);
515         else
516                 ((CFX_SkiaDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap);
517 #else
518         pContext->m_pDevice = new CFX_FxgeDevice;
519
520         if (flags & FPDF_REVERSE_BYTE_ORDER)
521                 ((CFX_FxgeDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap,0,TRUE);
522         else
523                 ((CFX_FxgeDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap);
524 #endif
525
526         Func_RenderPage(pContext, page, start_x, start_y, size_x, size_y, rotate, flags,TRUE,NULL);
527
528         delete pContext;
529         pPage->RemovePrivateData((void*)1);
530 }
531
532 DLLEXPORT void STDCALL FPDF_ClosePage(FPDF_PAGE page)
533 {
534         if (!page) return;
535         CPDFSDK_PageView* pPageView = (CPDFSDK_PageView*)(((CPDF_Page*)page))->GetPrivateData((FX_LPVOID)page);
536         if (pPageView && pPageView->IsLocked()) {
537             pPageView->TakeOverPage();
538             return;
539         }
540         delete (CPDF_Page*)page;
541
542 }
543
544 DLLEXPORT void STDCALL FPDF_CloseDocument(FPDF_DOCUMENT document)
545 {
546         if (!document)
547                 return;
548         CPDF_Document* pDoc = (CPDF_Document*)document; 
549         CPDF_Parser* pParser = (CPDF_Parser*)pDoc->GetParser();
550         if (pParser == NULL) 
551         {
552                 delete pDoc;
553                 return;
554         }
555         delete pParser;
556 //      delete pDoc;
557 }
558
559 DLLEXPORT unsigned long STDCALL FPDF_GetLastError()
560 {
561         return GetLastError();
562 }
563
564 DLLEXPORT void STDCALL FPDF_DeviceToPage(FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
565                                                 int rotate, int device_x, int device_y, double* page_x, double* page_y)
566 {
567         if (page == NULL || page_x == NULL || page_y == NULL) return;
568         CPDF_Page* pPage = (CPDF_Page*)page;
569
570         CPDF_Matrix page2device;
571         pPage->GetDisplayMatrix(page2device, start_x, start_y, size_x, size_y, rotate);
572         CPDF_Matrix device2page;
573         device2page.SetReverse(page2device);
574
575         FX_FLOAT page_x_f, page_y_f;
576         device2page.Transform((FX_FLOAT)(device_x), (FX_FLOAT)(device_y), page_x_f, page_y_f);
577
578         *page_x = (page_x_f);
579         *page_y = (page_y_f);
580 }
581
582 DLLEXPORT void STDCALL FPDF_PageToDevice(FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
583                                                 int rotate, double page_x, double page_y, int* device_x, int* device_y)
584 {
585         if (page == NULL || device_x == NULL || device_y == NULL) return;
586         CPDF_Page* pPage = (CPDF_Page*)page;
587
588         CPDF_Matrix page2device;
589         pPage->GetDisplayMatrix(page2device, start_x, start_y, size_x, size_y, rotate);
590
591         FX_FLOAT device_x_f, device_y_f;
592         page2device.Transform(((FX_FLOAT)page_x), ((FX_FLOAT)page_y), device_x_f, device_y_f);
593
594         *device_x = FXSYS_round(device_x_f);
595         *device_y = FXSYS_round(device_y_f);
596 }
597
598 DLLEXPORT FPDF_BITMAP STDCALL FPDFBitmap_Create(int width, int height, int alpha)
599 {
600         CFX_DIBitmap* pBitmap = new CFX_DIBitmap;
601         pBitmap->Create(width, height, alpha ? FXDIB_Argb : FXDIB_Rgb32);
602         return pBitmap;
603 }
604
605 DLLEXPORT FPDF_BITMAP STDCALL FPDFBitmap_CreateEx(int width, int height, int format, void* first_scan, int stride)
606 {
607         FXDIB_Format fx_format;
608         switch (format) {
609                 case FPDFBitmap_Gray:
610                         fx_format = FXDIB_8bppRgb;
611                         break;
612                 case FPDFBitmap_BGR:
613                         fx_format = FXDIB_Rgb;
614                         break;
615                 case FPDFBitmap_BGRx:
616                         fx_format = FXDIB_Rgb32;
617                         break;
618                 case FPDFBitmap_BGRA:
619                         fx_format = FXDIB_Argb;
620                         break;
621                 default:
622                         return NULL;
623         }
624         CFX_DIBitmap* pBitmap = new CFX_DIBitmap;
625         pBitmap->Create(width, height, fx_format, (FX_LPBYTE)first_scan, stride);
626         return pBitmap;
627 }
628
629 DLLEXPORT void STDCALL FPDFBitmap_FillRect(FPDF_BITMAP bitmap, int left, int top, int width, int height, FPDF_DWORD color)
630 {
631         if (bitmap == NULL) return;
632 #ifdef _SKIA_SUPPORT_
633         CFX_SkiaDevice device;
634 #else
635         CFX_FxgeDevice device;
636 #endif
637         device.Attach((CFX_DIBitmap*)bitmap);
638         if (!((CFX_DIBitmap*)bitmap)->HasAlpha()) color |= 0xFF000000;
639         FX_RECT rect(left, top, left+width, top+height);
640         device.FillRect(&rect, color);
641 }
642
643 DLLEXPORT void* STDCALL FPDFBitmap_GetBuffer(FPDF_BITMAP bitmap)
644 {
645         if (bitmap == NULL) return NULL;
646         return ((CFX_DIBitmap*)bitmap)->GetBuffer();
647 }
648
649 DLLEXPORT int STDCALL FPDFBitmap_GetWidth(FPDF_BITMAP bitmap)
650 {
651         if (bitmap == NULL) return 0;
652         return ((CFX_DIBitmap*)bitmap)->GetWidth();
653 }
654
655 DLLEXPORT int STDCALL FPDFBitmap_GetHeight(FPDF_BITMAP bitmap)
656 {
657         if (bitmap == NULL) return 0;
658         return ((CFX_DIBitmap*)bitmap)->GetHeight();
659 }
660
661 DLLEXPORT int STDCALL FPDFBitmap_GetStride(FPDF_BITMAP bitmap)
662 {
663         if (bitmap == NULL) return 0;
664         return ((CFX_DIBitmap*)bitmap)->GetPitch();
665 }
666
667 DLLEXPORT void STDCALL FPDFBitmap_Destroy(FPDF_BITMAP bitmap)
668 {
669         if (bitmap == NULL) return;
670         delete (CFX_DIBitmap*)bitmap;
671 }
672
673 void FPDF_RenderPage_Retail(CRenderContext* pContext, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
674                                                 int rotate, int flags,FX_BOOL bNeedToRestore, IFSDK_PAUSE_Adapter * pause )
675 {
676         CPDF_Page* pPage = (CPDF_Page*)page;
677         if (pPage == NULL) return;
678
679         if (!pContext->m_pOptions)
680                 pContext->m_pOptions = new CPDF_RenderOptions;
681 //      CPDF_RenderOptions options;
682         if (flags & FPDF_LCD_TEXT)
683                 pContext->m_pOptions->m_Flags |= RENDER_CLEARTYPE;
684         else
685                 pContext->m_pOptions->m_Flags &= ~RENDER_CLEARTYPE;
686         if (flags & FPDF_NO_NATIVETEXT)
687                 pContext->m_pOptions->m_Flags |= RENDER_NO_NATIVETEXT;
688         if (flags & FPDF_RENDER_LIMITEDIMAGECACHE)
689                 pContext->m_pOptions->m_Flags |= RENDER_LIMITEDIMAGECACHE;
690         if (flags & FPDF_RENDER_FORCEHALFTONE)
691                 pContext->m_pOptions->m_Flags |= RENDER_FORCE_HALFTONE;
692         if (flags & FPDF_RENDER_NO_SMOOTHTEXT)
693                 pContext->m_pOptions->m_Flags |= RENDER_NOTEXTSMOOTH;
694         if (flags & FPDF_RENDER_NO_SMOOTHIMAGE)
695                 pContext->m_pOptions->m_Flags |= RENDER_NOIMAGESMOOTH;
696         if (flags & FPDF_RENDER_NO_SMOOTHPATH)
697                 pContext->m_pOptions->m_Flags |= RENDER_NOPATHSMOOTH;
698         //Grayscale output
699         if (flags & FPDF_GRAYSCALE)
700         {
701                 pContext->m_pOptions->m_ColorMode = RENDER_COLOR_GRAY;
702                 pContext->m_pOptions->m_ForeColor = 0;
703                 pContext->m_pOptions->m_BackColor = 0xffffff;
704         }
705         const CPDF_OCContext::UsageType usage = (flags & FPDF_PRINTING) ? CPDF_OCContext::Print : CPDF_OCContext::View;
706
707         pContext->m_pOptions->m_AddFlags = flags >> 8;
708
709         pContext->m_pOptions->m_pOCContext = new CPDF_OCContext(pPage->m_pDocument, usage);
710
711
712         CFX_AffineMatrix matrix;
713         pPage->GetDisplayMatrix(matrix, start_x, start_y, size_x, size_y, rotate); 
714
715         FX_RECT clip;
716         clip.left = start_x;
717         clip.right = start_x + size_x;
718         clip.top = start_y;
719         clip.bottom = start_y + size_y;
720         pContext->m_pDevice->SaveState();
721         pContext->m_pDevice->SetClip_Rect(&clip);
722
723         pContext->m_pContext = new CPDF_RenderContext;
724         pContext->m_pContext->Create(pPage);
725         pContext->m_pContext->AppendObjectList(pPage, &matrix);
726
727         if (flags & FPDF_ANNOT) {
728                 pContext->m_pAnnots = new CPDF_AnnotList(pPage);
729                 FX_BOOL bPrinting = pContext->m_pDevice->GetDeviceClass() != FXDC_DISPLAY;
730                 pContext->m_pAnnots->DisplayAnnots(pPage, pContext->m_pContext, bPrinting, &matrix, TRUE, NULL);
731         }
732
733         pContext->m_pRenderer = new CPDF_ProgressiveRenderer;
734         pContext->m_pRenderer->Start(pContext->m_pContext, pContext->m_pDevice, pContext->m_pOptions, pause);
735         if (bNeedToRestore)
736         {
737           pContext->m_pDevice->RestoreState();
738         }
739 }
740
741 DLLEXPORT int STDCALL FPDF_GetPageSizeByIndex(FPDF_DOCUMENT document, int page_index, double* width, double* height)
742 {
743         CPDF_Document* pDoc = (CPDF_Document*)document;
744         if(pDoc == NULL)
745                 return FALSE;
746
747         CPDF_Dictionary* pDict = pDoc->GetPage(page_index);
748         if (pDict == NULL) return FALSE;
749
750         CPDF_Page page;
751         page.Load(pDoc, pDict);
752         *width = page.GetPageWidth();
753         *height = page.GetPageHeight();
754
755         return TRUE;
756 }
757
758 DLLEXPORT FPDF_BOOL STDCALL FPDF_VIEWERREF_GetPrintScaling(FPDF_DOCUMENT document)
759 {
760         CPDF_Document* pDoc = (CPDF_Document*)document;
761         if (!pDoc) return TRUE;
762         CPDF_ViewerPreferences viewRef(pDoc);
763         return viewRef.PrintScaling();
764 }
765
766 DLLEXPORT int STDCALL FPDF_VIEWERREF_GetNumCopies(FPDF_DOCUMENT document)
767 {
768     CPDF_Document* pDoc = (CPDF_Document*)document;
769     if (!pDoc) return 1;
770     CPDF_ViewerPreferences viewRef(pDoc);
771     return viewRef.NumCopies();
772 }
773
774 DLLEXPORT FPDF_PAGERANGE STDCALL FPDF_VIEWERREF_GetPrintPageRange(FPDF_DOCUMENT document)
775 {
776     CPDF_Document* pDoc = (CPDF_Document*)document;
777     if (!pDoc) return NULL;
778     CPDF_ViewerPreferences viewRef(pDoc);
779     return viewRef.PrintPageRange();
780 }
781
782 DLLEXPORT FPDF_DUPLEXTYPE STDCALL FPDF_VIEWERREF_GetDuplex(FPDF_DOCUMENT document)
783 {
784     CPDF_Document* pDoc = (CPDF_Document*)document;
785     if (!pDoc) return DuplexUndefined;
786     CPDF_ViewerPreferences viewRef(pDoc);
787     CFX_ByteString duplex = viewRef.Duplex();
788     if (FX_BSTRC("Simplex") == duplex)
789         return Simplex;
790     if (FX_BSTRC("DuplexFlipShortEdge") == duplex)
791         return DuplexFlipShortEdge;
792     if (FX_BSTRC("DuplexFlipLongEdge") == duplex)
793         return DuplexFlipLongEdge;
794     return DuplexUndefined;
795 }
796
797 DLLEXPORT FPDF_DWORD STDCALL FPDF_CountNamedDests(FPDF_DOCUMENT document)
798 {
799     if (!document) return 0;
800     CPDF_Document* pDoc = (CPDF_Document*)document;
801
802     CPDF_Dictionary* pRoot = pDoc->GetRoot();
803     if (!pRoot) return 0;
804
805     CPDF_NameTree nameTree(pDoc, FX_BSTRC("Dests"));
806     int count = nameTree.GetCount();
807     CPDF_Dictionary* pDest = pRoot->GetDict(FX_BSTRC("Dests"));
808     if (pDest)
809         count += pDest->GetCount();
810     return count;
811 }
812
813 DLLEXPORT FPDF_DEST STDCALL FPDF_GetNamedDestByName(FPDF_DOCUMENT document,FPDF_BYTESTRING name)
814 {
815         if (!document)
816                 return NULL;
817         if (!name || name[0] == 0) 
818                 return NULL;
819
820         CPDF_Document* pDoc = (CPDF_Document*)document;
821         CPDF_NameTree name_tree(pDoc, FX_BSTRC("Dests"));
822         return name_tree.LookupNamedDest(pDoc, name);
823 }
824
825 DLLEXPORT FPDF_DEST STDCALL FPDF_GetNamedDest(FPDF_DOCUMENT document, int index, void* buffer, long& buflen)
826 {
827     if (!buffer)
828         buflen = 0;
829     if (!document || index < 0) return NULL;
830     CPDF_Document* pDoc = (CPDF_Document*)document;
831
832     CPDF_Dictionary* pRoot = pDoc->GetRoot();
833     if (!pRoot) return NULL;
834
835     CPDF_Object* pDestObj = NULL;
836     CFX_ByteString bsName;
837     CPDF_NameTree nameTree(pDoc, FX_BSTRC("Dests"));
838     int count = nameTree.GetCount();
839     if (index >= count) {
840         CPDF_Dictionary* pDest = pRoot->GetDict(FX_BSTRC("Dests"));
841         if (!pDest) return NULL;
842         if (index >= count + pDest->GetCount()) return NULL;
843         index -= count;
844         FX_POSITION pos = pDest->GetStartPos();
845         int i = 0;
846         while (pos) {
847             pDestObj = pDest->GetNextElement(pos, bsName);
848             if (!pDestObj) continue;
849             if (i == index) break;
850             i++;
851         }
852     } else {
853         pDestObj = nameTree.LookupValue(index, bsName);
854     }
855     if (!pDestObj) return NULL;
856     if (pDestObj->GetType() == PDFOBJ_DICTIONARY) {
857         pDestObj = ((CPDF_Dictionary*)pDestObj)->GetArray(FX_BSTRC("D"));
858         if (!pDestObj) return NULL;
859     }
860     if (pDestObj->GetType() != PDFOBJ_ARRAY) return NULL;
861     CFX_WideString wsName = PDF_DecodeText(bsName);
862     CFX_ByteString utf16Name = wsName.UTF16LE_Encode();
863     unsigned int len = utf16Name.GetLength();
864     if (!buffer) {
865         buflen = len;
866     } else if (buflen >= len) {
867         memcpy(buffer, utf16Name.c_str(), len);
868         buflen = len;
869     } else {
870         buflen = -1;
871     }
872     return (FPDF_DEST)pDestObj;
873 }