Add namespace and-re-arrange PDFium's local copy of chromium /base.
[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 = FX_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, public CFX_Object
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 = FX_NEW CPDF_Parser;
228         pParser->SetPassword(password);
229         CMemFile* pMemFile = FX_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 = FX_NEW CPDF_Parser;
245         pParser->SetPassword(password);
246         CPDF_CustomAccess* pFile = FX_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 //      CPDF_Parser* pParser = (CPDF_Parser*)document;
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 = FX_NEW CPDF_Page;
310         pPage->Load(pDoc, pDict);
311         pPage->ParseContent();
312         
313 //      CheckUnSupportError(pDoc, 0);
314
315         return pPage;
316 }
317
318 DLLEXPORT double STDCALL FPDF_GetPageWidth(FPDF_PAGE page)
319 {
320         if (!page)
321                 return 0.0;
322         return ((CPDF_Page*)page)->GetPageWidth();
323 }
324
325 DLLEXPORT double STDCALL FPDF_GetPageHeight(FPDF_PAGE page)
326 {
327         if (!page) return 0.0;
328         return ((CPDF_Page*)page)->GetPageHeight();
329 }
330
331 void DropContext(void* data)
332 {
333         delete (CRenderContext*)data;
334 }
335
336 void FPDF_RenderPage_Retail(CRenderContext* pContext, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
337                                                 int rotate, int flags,FX_BOOL bNeedToRestore, IFSDK_PAUSE_Adapter * pause  );
338 void (*Func_RenderPage)(CRenderContext*, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
339                                                 int rotate, int flags,FX_BOOL bNeedToRestore, IFSDK_PAUSE_Adapter * pause  ) = FPDF_RenderPage_Retail;
340
341 #if defined(_DEBUG) || defined(DEBUG)
342 #define DEBUG_TRACE
343 #endif
344
345 #if defined(_WIN32)
346 DLLEXPORT void STDCALL FPDF_RenderPage(HDC dc, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
347                                                 int rotate, int flags)
348 {
349         if (page==NULL) return;
350         CPDF_Page* pPage = (CPDF_Page*)page;
351
352         CRenderContext* pContext = FX_NEW CRenderContext;
353         pPage->SetPrivateData((void*)1, pContext, DropContext);
354
355 #ifndef _WIN32_WCE
356         CFX_DIBitmap* pBitmap = NULL;
357         FX_BOOL bBackgroundAlphaNeeded=FALSE;
358         bBackgroundAlphaNeeded = pPage->BackgroundAlphaNeeded();
359         if (bBackgroundAlphaNeeded)
360         {
361                 
362                 pBitmap = FX_NEW CFX_DIBitmap;
363                 pBitmap->Create(size_x, size_y, FXDIB_Argb);
364                 pBitmap->Clear(0x00ffffff);
365 #ifdef _SKIA_SUPPORT_
366                 pContext->m_pDevice = FX_NEW CFX_SkiaDevice;
367                 ((CFX_SkiaDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)pBitmap);
368 #else
369                 pContext->m_pDevice = FX_NEW CFX_FxgeDevice;
370                 ((CFX_FxgeDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)pBitmap);
371 #endif
372         }
373         else
374             pContext->m_pDevice = FX_NEW CFX_WindowsDevice(dc);
375
376         Func_RenderPage(pContext, page, start_x, start_y, size_x, size_y, rotate, flags,TRUE,NULL);
377
378         if (bBackgroundAlphaNeeded) 
379         {
380                 if (pBitmap)
381                 {
382                         CFX_WindowsDevice WinDC(dc);
383                         
384                         if (WinDC.GetDeviceCaps(FXDC_DEVICE_CLASS) == FXDC_PRINTER)
385                         {
386                                 CFX_DIBitmap* pDst = FX_NEW CFX_DIBitmap;
387                                 int pitch = pBitmap->GetPitch();
388                                 pDst->Create(size_x, size_y, FXDIB_Rgb32);
389                                 FXSYS_memset(pDst->GetBuffer(), -1, pitch*size_y);
390                                 pDst->CompositeBitmap(0, 0, size_x, size_y, pBitmap, 0, 0, FXDIB_BLEND_NORMAL, NULL, FALSE, NULL);
391                                 WinDC.StretchDIBits(pDst,0,0,size_x,size_y);
392                                 delete pDst;
393                         }
394                         else
395                                 WinDC.SetDIBits(pBitmap,0,0);
396
397                 }
398         }
399 #else
400         // get clip region
401         RECT rect, cliprect;
402         rect.left = start_x;
403         rect.top = start_y;
404         rect.right = start_x + size_x;
405         rect.bottom = start_y + size_y;
406         GetClipBox(dc, &cliprect);
407         IntersectRect(&rect, &rect, &cliprect);
408         int width = rect.right - rect.left;
409         int height = rect.bottom - rect.top;
410
411 #ifdef DEBUG_TRACE
412         {
413                 char str[128];
414                 sprintf(str, "Rendering DIB %d x %d", width, height);
415                 CPDF_ModuleMgr::Get()->ReportError(999, str);
416         }
417 #endif
418
419         // Create a DIB section
420         LPVOID pBuffer;
421         BITMAPINFOHEADER bmih;
422         FXSYS_memset(&bmih, 0, sizeof bmih);
423         bmih.biSize = sizeof bmih;
424         bmih.biBitCount = 24;
425         bmih.biHeight = -height;
426         bmih.biPlanes = 1;
427         bmih.biWidth = width;
428         pContext->m_hBitmap = CreateDIBSection(dc, (BITMAPINFO*)&bmih, DIB_RGB_COLORS, &pBuffer, NULL, 0);
429         if (pContext->m_hBitmap == NULL) {
430 #if defined(DEBUG) || defined(_DEBUG)
431                 char str[128];
432                 sprintf(str, "Error CreateDIBSection: %d x %d, error code = %d", width, height, GetLastError());
433                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, str);
434 #else
435                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, NULL);
436 #endif
437         }
438         FXSYS_memset(pBuffer, 0xff, height*((width*3+3)/4*4));
439
440 #ifdef DEBUG_TRACE
441         {
442                 CPDF_ModuleMgr::Get()->ReportError(999, "DIBSection created");
443         }
444 #endif
445
446         // Create a device with this external buffer
447         pContext->m_pBitmap = FX_NEW CFX_DIBitmap;
448         pContext->m_pBitmap->Create(width, height, FXDIB_Rgb, (FX_LPBYTE)pBuffer);
449         pContext->m_pDevice = FX_NEW CPDF_FxgeDevice;
450         ((CPDF_FxgeDevice*)pContext->m_pDevice)->Attach(pContext->m_pBitmap);
451         
452 #ifdef DEBUG_TRACE
453         CPDF_ModuleMgr::Get()->ReportError(999, "Ready for PDF rendering");
454 #endif
455
456         // output to bitmap device
457         Func_RenderPage(pContext, page, start_x - rect.left, start_y - rect.top, size_x, size_y, rotate, flags);
458
459 #ifdef DEBUG_TRACE
460         CPDF_ModuleMgr::Get()->ReportError(999, "Finished PDF rendering");
461 #endif
462
463         // Now output to real device
464         HDC hMemDC = CreateCompatibleDC(dc);
465         if (hMemDC == NULL) {
466 #if defined(DEBUG) || defined(_DEBUG)
467                 char str[128];
468                 sprintf(str, "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 = FX_NEW CRenderContext;
509         pPage->SetPrivateData((void*)1, pContext, DropContext);
510 #ifdef _SKIA_SUPPORT_
511         pContext->m_pDevice = FX_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 = FX_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 = FX_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 = FX_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         //Grayscale output
693         if (flags & FPDF_GRAYSCALE)
694         {
695                 pContext->m_pOptions->m_ColorMode = RENDER_COLOR_GRAY;
696                 pContext->m_pOptions->m_ForeColor = 0;
697                 pContext->m_pOptions->m_BackColor = 0xffffff;
698         }
699         const CPDF_OCContext::UsageType usage = (flags & FPDF_PRINTING) ? CPDF_OCContext::Print : CPDF_OCContext::View;
700
701         pContext->m_pOptions->m_AddFlags = flags >> 8;
702
703         pContext->m_pOptions->m_pOCContext = new CPDF_OCContext(pPage->m_pDocument, usage);
704
705
706         CFX_AffineMatrix matrix;
707         pPage->GetDisplayMatrix(matrix, start_x, start_y, size_x, size_y, rotate); 
708
709         FX_RECT clip;
710         clip.left = start_x;
711         clip.right = start_x + size_x;
712         clip.top = start_y;
713         clip.bottom = start_y + size_y;
714         pContext->m_pDevice->SaveState();
715         pContext->m_pDevice->SetClip_Rect(&clip);
716
717         pContext->m_pContext = FX_NEW CPDF_RenderContext;
718         pContext->m_pContext->Create(pPage);
719         pContext->m_pContext->AppendObjectList(pPage, &matrix);
720
721         if (flags & FPDF_ANNOT) {
722                 pContext->m_pAnnots = FX_NEW CPDF_AnnotList(pPage);
723                 FX_BOOL bPrinting = pContext->m_pDevice->GetDeviceClass() != FXDC_DISPLAY;
724                 pContext->m_pAnnots->DisplayAnnots(pPage, pContext->m_pContext, bPrinting, &matrix, TRUE, NULL);
725         }
726
727         pContext->m_pRenderer = FX_NEW CPDF_ProgressiveRenderer;
728         pContext->m_pRenderer->Start(pContext->m_pContext, pContext->m_pDevice, pContext->m_pOptions, pause);
729         if (bNeedToRestore)
730         {
731           pContext->m_pDevice->RestoreState();
732         }
733         
734 //#endif
735 }
736
737 DLLEXPORT int STDCALL FPDF_GetPageSizeByIndex(FPDF_DOCUMENT document, int page_index, double* width, double* height)
738 {
739         CPDF_Document* pDoc = (CPDF_Document*)document;
740         if(pDoc == NULL)
741                 return FALSE;
742
743         CPDF_Dictionary* pDict = pDoc->GetPage(page_index);
744         if (pDict == NULL) return FALSE;
745
746         CPDF_Page page;
747         page.Load(pDoc, pDict);
748         *width = page.GetPageWidth();
749         *height = page.GetPageHeight();
750
751         return TRUE;
752 }
753
754 DLLEXPORT FPDF_BOOL STDCALL FPDF_VIEWERREF_GetPrintScaling(FPDF_DOCUMENT document)
755 {
756         CPDF_Document* pDoc = (CPDF_Document*)document;
757         if (!pDoc) return TRUE;
758         CPDF_ViewerPreferences viewRef(pDoc);
759         return viewRef.PrintScaling();
760 }
761
762 DLLEXPORT int STDCALL FPDF_VIEWERREF_GetNumCopies(FPDF_DOCUMENT document)
763 {
764     CPDF_Document* pDoc = (CPDF_Document*)document;
765     if (!pDoc) return 1;
766     CPDF_ViewerPreferences viewRef(pDoc);
767     return viewRef.NumCopies();
768 }
769
770 DLLEXPORT FPDF_PAGERANGE STDCALL FPDF_VIEWERREF_GetPrintPageRange(FPDF_DOCUMENT document)
771 {
772     CPDF_Document* pDoc = (CPDF_Document*)document;
773     if (!pDoc) return NULL;
774     CPDF_ViewerPreferences viewRef(pDoc);
775     return viewRef.PrintPageRange();
776 }
777
778 DLLEXPORT FPDF_DUPLEXTYPE STDCALL FPDF_VIEWERREF_GetDuplex(FPDF_DOCUMENT document)
779 {
780     CPDF_Document* pDoc = (CPDF_Document*)document;
781     if (!pDoc) return DuplexUndefined;
782     CPDF_ViewerPreferences viewRef(pDoc);
783     CFX_ByteString duplex = viewRef.Duplex();
784     if (FX_BSTRC("Simplex") == duplex)
785         return Simplex;
786     if (FX_BSTRC("DuplexFlipShortEdge") == duplex)
787         return DuplexFlipShortEdge;
788     if (FX_BSTRC("DuplexFlipLongEdge") == duplex)
789         return DuplexFlipLongEdge;
790     return DuplexUndefined;
791 }
792
793 DLLEXPORT FPDF_DWORD STDCALL FPDF_CountNamedDests(FPDF_DOCUMENT document)
794 {
795     if (!document) return 0;
796     CPDF_Document* pDoc = (CPDF_Document*)document;
797
798     CPDF_Dictionary* pRoot = pDoc->GetRoot();
799     if (!pRoot) return 0;
800
801     CPDF_NameTree nameTree(pDoc, FX_BSTRC("Dests"));
802     int count = nameTree.GetCount();
803     CPDF_Dictionary* pDest = pRoot->GetDict(FX_BSTRC("Dests"));
804     if (pDest)
805         count += pDest->GetCount();
806     return count;
807 }
808
809 DLLEXPORT FPDF_DEST STDCALL FPDF_GetNamedDestByName(FPDF_DOCUMENT document,FPDF_BYTESTRING name)
810 {
811         if (!document)
812                 return NULL;
813         if (!name || name[0] == 0) 
814                 return NULL;
815
816         CPDF_Document* pDoc = (CPDF_Document*)document;
817         CPDF_NameTree name_tree(pDoc, FX_BSTRC("Dests"));
818         return name_tree.LookupNamedDest(pDoc, name);
819 }
820
821 DLLEXPORT FPDF_DEST STDCALL FPDF_GetNamedDest(FPDF_DOCUMENT document, int index, void* buffer, long& buflen)
822 {
823     if (!buffer)
824         buflen = 0;
825     if (!document || index < 0) return NULL;
826     CPDF_Document* pDoc = (CPDF_Document*)document;
827
828     CPDF_Dictionary* pRoot = pDoc->GetRoot();
829     if (!pRoot) return NULL;
830
831     CPDF_Object* pDestObj = NULL;
832     CFX_ByteString bsName;
833     CPDF_NameTree nameTree(pDoc, FX_BSTRC("Dests"));
834     int count = nameTree.GetCount();
835     if (index >= count) {
836         CPDF_Dictionary* pDest = pRoot->GetDict(FX_BSTRC("Dests"));
837         if (!pDest) return NULL;
838         if (index >= count + pDest->GetCount()) return NULL;
839         index -= count;
840         FX_POSITION pos = pDest->GetStartPos();
841         int i = 0;
842         while (pos) {
843             pDestObj = pDest->GetNextElement(pos, bsName);
844             if (!pDestObj) continue;
845             if (i == index) break;
846             i++;
847         }
848     } else {
849         pDestObj = nameTree.LookupValue(index, bsName);
850     }
851     if (!pDestObj) return NULL;
852     if (pDestObj->GetType() == PDFOBJ_DICTIONARY) {
853         pDestObj = ((CPDF_Dictionary*)pDestObj)->GetArray(FX_BSTRC("D"));
854         if (!pDestObj) return NULL;
855     }
856     if (pDestObj->GetType() != PDFOBJ_ARRAY) return NULL;
857     CFX_WideString wsName = PDF_DecodeText(bsName);
858     CFX_ByteString utf16Name = wsName.UTF16LE_Encode();
859     unsigned int len = utf16Name.GetLength();
860     if (!buffer) {
861         buflen = len;
862     } else if (buflen >= len) {
863         memcpy(buffer, utf16Name.c_str(), len);
864         buflen = len;
865     } else {
866         buflen = -1;
867     }
868     return (FPDF_DEST)pDestObj;
869 }