Include windows.h instead of the MFC header afxres.h
[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                 memset(str, 0, sizeof(str));
415                 FXSYS_snprintf(str, sizeof(str) - 1, "Rendering DIB %d x %d", width, height);
416                 CPDF_ModuleMgr::Get()->ReportError(999, str);
417         }
418 #endif
419
420         // Create a DIB section
421         LPVOID pBuffer;
422         BITMAPINFOHEADER bmih;
423         FXSYS_memset(&bmih, 0, sizeof bmih);
424         bmih.biSize = sizeof bmih;
425         bmih.biBitCount = 24;
426         bmih.biHeight = -height;
427         bmih.biPlanes = 1;
428         bmih.biWidth = width;
429         pContext->m_hBitmap = CreateDIBSection(dc, (BITMAPINFO*)&bmih, DIB_RGB_COLORS, &pBuffer, NULL, 0);
430         if (pContext->m_hBitmap == NULL) {
431 #if defined(DEBUG) || defined(_DEBUG)
432                 char str[128];
433                 memset(str, 0, sizeof(str));
434                 FXSYS_snprintf(str, sizeof(str) - 1, "Error CreateDIBSection: %d x %d, error code = %d", width, height, GetLastError());
435                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, str);
436 #else
437                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, NULL);
438 #endif
439         }
440         FXSYS_memset(pBuffer, 0xff, height*((width*3+3)/4*4));
441
442 #ifdef DEBUG_TRACE
443         {
444                 CPDF_ModuleMgr::Get()->ReportError(999, "DIBSection created");
445         }
446 #endif
447
448         // Create a device with this external buffer
449         pContext->m_pBitmap = FX_NEW CFX_DIBitmap;
450         pContext->m_pBitmap->Create(width, height, FXDIB_Rgb, (FX_LPBYTE)pBuffer);
451         pContext->m_pDevice = FX_NEW CPDF_FxgeDevice;
452         ((CPDF_FxgeDevice*)pContext->m_pDevice)->Attach(pContext->m_pBitmap);
453         
454 #ifdef DEBUG_TRACE
455         CPDF_ModuleMgr::Get()->ReportError(999, "Ready for PDF rendering");
456 #endif
457
458         // output to bitmap device
459         Func_RenderPage(pContext, page, start_x - rect.left, start_y - rect.top, size_x, size_y, rotate, flags);
460
461 #ifdef DEBUG_TRACE
462         CPDF_ModuleMgr::Get()->ReportError(999, "Finished PDF rendering");
463 #endif
464
465         // Now output to real device
466         HDC hMemDC = CreateCompatibleDC(dc);
467         if (hMemDC == NULL) {
468 #if defined(DEBUG) || defined(_DEBUG)
469                 char str[128];
470                 memset(str, 0, sizeof(str));
471                 FXSYS_snprintf(str, sizeof(str) - 1, "Error CreateCompatibleDC. Error code = %d", GetLastError());
472                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, str);
473 #else
474                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, NULL);
475 #endif
476         }
477
478         HGDIOBJ hOldBitmap = SelectObject(hMemDC, pContext->m_hBitmap);
479
480 #ifdef DEBUG_TRACE
481         CPDF_ModuleMgr::Get()->ReportError(999, "Ready for screen rendering");
482 #endif
483
484         BitBlt(dc, rect.left, rect.top, width, height, hMemDC, 0, 0, SRCCOPY);
485         SelectObject(hMemDC, hOldBitmap);
486         DeleteDC(hMemDC);
487
488 #ifdef DEBUG_TRACE
489         CPDF_ModuleMgr::Get()->ReportError(999, "Finished screen rendering");
490 #endif
491
492 #endif
493         if (bBackgroundAlphaNeeded)
494         {
495                 if (pBitmap)
496                         delete pBitmap;
497                 pBitmap = NULL;
498         }
499         delete pContext;
500         pPage->RemovePrivateData((void*)1);
501 }
502 #endif
503
504 DLLEXPORT void STDCALL FPDF_RenderPageBitmap(FPDF_BITMAP bitmap, FPDF_PAGE page, int start_x, int start_y, 
505                                                 int size_x, int size_y, int rotate, int flags)
506 {
507         if (bitmap == NULL || page == NULL) return;
508         CPDF_Page* pPage = (CPDF_Page*)page;
509
510
511         CRenderContext* pContext = FX_NEW CRenderContext;
512         pPage->SetPrivateData((void*)1, pContext, DropContext);
513 #ifdef _SKIA_SUPPORT_
514         pContext->m_pDevice = FX_NEW CFX_SkiaDevice;
515
516         if (flags & FPDF_REVERSE_BYTE_ORDER)
517                 ((CFX_SkiaDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap,0,TRUE);
518         else
519                 ((CFX_SkiaDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap);
520 #else
521         pContext->m_pDevice = FX_NEW CFX_FxgeDevice;
522
523         if (flags & FPDF_REVERSE_BYTE_ORDER)
524                 ((CFX_FxgeDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap,0,TRUE);
525         else
526                 ((CFX_FxgeDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap);
527 #endif
528
529         Func_RenderPage(pContext, page, start_x, start_y, size_x, size_y, rotate, flags,TRUE,NULL);
530
531         delete pContext;
532         pPage->RemovePrivateData((void*)1);
533 }
534
535 DLLEXPORT void STDCALL FPDF_ClosePage(FPDF_PAGE page)
536 {
537         if (!page) return;
538         CPDFSDK_PageView* pPageView = (CPDFSDK_PageView*)(((CPDF_Page*)page))->GetPrivateData((FX_LPVOID)page);
539         if (pPageView && pPageView->IsLocked()) {
540             pPageView->TakeOverPage();
541             return;
542         }
543         delete (CPDF_Page*)page;
544
545 }
546
547 DLLEXPORT void STDCALL FPDF_CloseDocument(FPDF_DOCUMENT document)
548 {
549         if (!document)
550                 return;
551         CPDF_Document* pDoc = (CPDF_Document*)document; 
552         CPDF_Parser* pParser = (CPDF_Parser*)pDoc->GetParser();
553         if (pParser == NULL) 
554         {
555                 delete pDoc;
556                 return;
557         }
558         delete pParser;
559 //      delete pDoc;
560 }
561
562 DLLEXPORT unsigned long STDCALL FPDF_GetLastError()
563 {
564         return GetLastError();
565 }
566
567 DLLEXPORT void STDCALL FPDF_DeviceToPage(FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
568                                                 int rotate, int device_x, int device_y, double* page_x, double* page_y)
569 {
570         if (page == NULL || page_x == NULL || page_y == NULL) return;
571         CPDF_Page* pPage = (CPDF_Page*)page;
572
573         CPDF_Matrix page2device;
574         pPage->GetDisplayMatrix(page2device, start_x, start_y, size_x, size_y, rotate);
575         CPDF_Matrix device2page;
576         device2page.SetReverse(page2device);
577
578         FX_FLOAT page_x_f, page_y_f;
579         device2page.Transform((FX_FLOAT)(device_x), (FX_FLOAT)(device_y), page_x_f, page_y_f);
580
581         *page_x = (page_x_f);
582         *page_y = (page_y_f);
583 }
584
585 DLLEXPORT void STDCALL FPDF_PageToDevice(FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
586                                                 int rotate, double page_x, double page_y, int* device_x, int* device_y)
587 {
588         if (page == NULL || device_x == NULL || device_y == NULL) return;
589         CPDF_Page* pPage = (CPDF_Page*)page;
590
591         CPDF_Matrix page2device;
592         pPage->GetDisplayMatrix(page2device, start_x, start_y, size_x, size_y, rotate);
593
594         FX_FLOAT device_x_f, device_y_f;
595         page2device.Transform(((FX_FLOAT)page_x), ((FX_FLOAT)page_y), device_x_f, device_y_f);
596
597         *device_x = FXSYS_round(device_x_f);
598         *device_y = FXSYS_round(device_y_f);
599 }
600
601 DLLEXPORT FPDF_BITMAP STDCALL FPDFBitmap_Create(int width, int height, int alpha)
602 {
603         CFX_DIBitmap* pBitmap = FX_NEW CFX_DIBitmap;
604         pBitmap->Create(width, height, alpha ? FXDIB_Argb : FXDIB_Rgb32);
605         return pBitmap;
606 }
607
608 DLLEXPORT FPDF_BITMAP STDCALL FPDFBitmap_CreateEx(int width, int height, int format, void* first_scan, int stride)
609 {
610         FXDIB_Format fx_format;
611         switch (format) {
612                 case FPDFBitmap_Gray:
613                         fx_format = FXDIB_8bppRgb;
614                         break;
615                 case FPDFBitmap_BGR:
616                         fx_format = FXDIB_Rgb;
617                         break;
618                 case FPDFBitmap_BGRx:
619                         fx_format = FXDIB_Rgb32;
620                         break;
621                 case FPDFBitmap_BGRA:
622                         fx_format = FXDIB_Argb;
623                         break;
624                 default:
625                         return NULL;
626         }
627         CFX_DIBitmap* pBitmap = FX_NEW CFX_DIBitmap;
628         pBitmap->Create(width, height, fx_format, (FX_LPBYTE)first_scan, stride);
629         return pBitmap;
630 }
631
632 DLLEXPORT void STDCALL FPDFBitmap_FillRect(FPDF_BITMAP bitmap, int left, int top, int width, int height, FPDF_DWORD color)
633 {
634         if (bitmap == NULL) return;
635 #ifdef _SKIA_SUPPORT_
636         CFX_SkiaDevice device;
637 #else
638         CFX_FxgeDevice device;
639 #endif
640         device.Attach((CFX_DIBitmap*)bitmap);
641         if (!((CFX_DIBitmap*)bitmap)->HasAlpha()) color |= 0xFF000000;
642         FX_RECT rect(left, top, left+width, top+height);
643         device.FillRect(&rect, color);
644 }
645
646 DLLEXPORT void* STDCALL FPDFBitmap_GetBuffer(FPDF_BITMAP bitmap)
647 {
648         if (bitmap == NULL) return NULL;
649         return ((CFX_DIBitmap*)bitmap)->GetBuffer();
650 }
651
652 DLLEXPORT int STDCALL FPDFBitmap_GetWidth(FPDF_BITMAP bitmap)
653 {
654         if (bitmap == NULL) return 0;
655         return ((CFX_DIBitmap*)bitmap)->GetWidth();
656 }
657
658 DLLEXPORT int STDCALL FPDFBitmap_GetHeight(FPDF_BITMAP bitmap)
659 {
660         if (bitmap == NULL) return 0;
661         return ((CFX_DIBitmap*)bitmap)->GetHeight();
662 }
663
664 DLLEXPORT int STDCALL FPDFBitmap_GetStride(FPDF_BITMAP bitmap)
665 {
666         if (bitmap == NULL) return 0;
667         return ((CFX_DIBitmap*)bitmap)->GetPitch();
668 }
669
670 DLLEXPORT void STDCALL FPDFBitmap_Destroy(FPDF_BITMAP bitmap)
671 {
672         if (bitmap == NULL) return;
673         delete (CFX_DIBitmap*)bitmap;
674 }
675
676 void FPDF_RenderPage_Retail(CRenderContext* pContext, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
677                                                 int rotate, int flags,FX_BOOL bNeedToRestore, IFSDK_PAUSE_Adapter * pause )
678 {
679         CPDF_Page* pPage = (CPDF_Page*)page;
680         if (pPage == NULL) return;
681
682         if (!pContext->m_pOptions)
683                 pContext->m_pOptions = new CPDF_RenderOptions;
684 //      CPDF_RenderOptions options;
685         if (flags & FPDF_LCD_TEXT)
686                 pContext->m_pOptions->m_Flags |= RENDER_CLEARTYPE;
687         else
688                 pContext->m_pOptions->m_Flags &= ~RENDER_CLEARTYPE;
689         if (flags & FPDF_NO_NATIVETEXT)
690                 pContext->m_pOptions->m_Flags |= RENDER_NO_NATIVETEXT;
691         if (flags & FPDF_RENDER_LIMITEDIMAGECACHE)
692                 pContext->m_pOptions->m_Flags |= RENDER_LIMITEDIMAGECACHE;
693         if (flags & FPDF_RENDER_FORCEHALFTONE)
694                 pContext->m_pOptions->m_Flags |= RENDER_FORCE_HALFTONE;
695         //Grayscale output
696         if (flags & FPDF_GRAYSCALE)
697         {
698                 pContext->m_pOptions->m_ColorMode = RENDER_COLOR_GRAY;
699                 pContext->m_pOptions->m_ForeColor = 0;
700                 pContext->m_pOptions->m_BackColor = 0xffffff;
701         }
702         const CPDF_OCContext::UsageType usage = (flags & FPDF_PRINTING) ? CPDF_OCContext::Print : CPDF_OCContext::View;
703
704         pContext->m_pOptions->m_AddFlags = flags >> 8;
705
706         pContext->m_pOptions->m_pOCContext = new CPDF_OCContext(pPage->m_pDocument, usage);
707
708
709         CFX_AffineMatrix matrix;
710         pPage->GetDisplayMatrix(matrix, start_x, start_y, size_x, size_y, rotate); 
711
712         FX_RECT clip;
713         clip.left = start_x;
714         clip.right = start_x + size_x;
715         clip.top = start_y;
716         clip.bottom = start_y + size_y;
717         pContext->m_pDevice->SaveState();
718         pContext->m_pDevice->SetClip_Rect(&clip);
719
720         pContext->m_pContext = FX_NEW CPDF_RenderContext;
721         pContext->m_pContext->Create(pPage);
722         pContext->m_pContext->AppendObjectList(pPage, &matrix);
723
724         if (flags & FPDF_ANNOT) {
725                 pContext->m_pAnnots = FX_NEW CPDF_AnnotList(pPage);
726                 FX_BOOL bPrinting = pContext->m_pDevice->GetDeviceClass() != FXDC_DISPLAY;
727                 pContext->m_pAnnots->DisplayAnnots(pPage, pContext->m_pContext, bPrinting, &matrix, TRUE, NULL);
728         }
729
730         pContext->m_pRenderer = FX_NEW CPDF_ProgressiveRenderer;
731         pContext->m_pRenderer->Start(pContext->m_pContext, pContext->m_pDevice, pContext->m_pOptions, pause);
732         if (bNeedToRestore)
733         {
734           pContext->m_pDevice->RestoreState();
735         }
736         
737 //#endif
738 }
739
740 DLLEXPORT int STDCALL FPDF_GetPageSizeByIndex(FPDF_DOCUMENT document, int page_index, double* width, double* height)
741 {
742         CPDF_Document* pDoc = (CPDF_Document*)document;
743         if(pDoc == NULL)
744                 return FALSE;
745
746         CPDF_Dictionary* pDict = pDoc->GetPage(page_index);
747         if (pDict == NULL) return FALSE;
748
749         CPDF_Page page;
750         page.Load(pDoc, pDict);
751         *width = page.GetPageWidth();
752         *height = page.GetPageHeight();
753
754         return TRUE;
755 }
756
757 DLLEXPORT FPDF_BOOL STDCALL FPDF_VIEWERREF_GetPrintScaling(FPDF_DOCUMENT document)
758 {
759         CPDF_Document* pDoc = (CPDF_Document*)document;
760         if (!pDoc) return TRUE;
761         CPDF_ViewerPreferences viewRef(pDoc);
762         return viewRef.PrintScaling();
763 }
764
765 DLLEXPORT int STDCALL FPDF_VIEWERREF_GetNumCopies(FPDF_DOCUMENT document)
766 {
767     CPDF_Document* pDoc = (CPDF_Document*)document;
768     if (!pDoc) return 1;
769     CPDF_ViewerPreferences viewRef(pDoc);
770     return viewRef.NumCopies();
771 }
772
773 DLLEXPORT FPDF_PAGERANGE STDCALL FPDF_VIEWERREF_GetPrintPageRange(FPDF_DOCUMENT document)
774 {
775     CPDF_Document* pDoc = (CPDF_Document*)document;
776     if (!pDoc) return NULL;
777     CPDF_ViewerPreferences viewRef(pDoc);
778     return viewRef.PrintPageRange();
779 }
780
781 DLLEXPORT FPDF_DUPLEXTYPE STDCALL FPDF_VIEWERREF_GetDuplex(FPDF_DOCUMENT document)
782 {
783     CPDF_Document* pDoc = (CPDF_Document*)document;
784     if (!pDoc) return DuplexUndefined;
785     CPDF_ViewerPreferences viewRef(pDoc);
786     CFX_ByteString duplex = viewRef.Duplex();
787     if (FX_BSTRC("Simplex") == duplex)
788         return Simplex;
789     if (FX_BSTRC("DuplexFlipShortEdge") == duplex)
790         return DuplexFlipShortEdge;
791     if (FX_BSTRC("DuplexFlipLongEdge") == duplex)
792         return DuplexFlipLongEdge;
793     return DuplexUndefined;
794 }
795
796 DLLEXPORT FPDF_DWORD STDCALL FPDF_CountNamedDests(FPDF_DOCUMENT document)
797 {
798     if (!document) return 0;
799     CPDF_Document* pDoc = (CPDF_Document*)document;
800
801     CPDF_Dictionary* pRoot = pDoc->GetRoot();
802     if (!pRoot) return 0;
803
804     CPDF_NameTree nameTree(pDoc, FX_BSTRC("Dests"));
805     int count = nameTree.GetCount();
806     CPDF_Dictionary* pDest = pRoot->GetDict(FX_BSTRC("Dests"));
807     if (pDest)
808         count += pDest->GetCount();
809     return count;
810 }
811
812 DLLEXPORT FPDF_DEST STDCALL FPDF_GetNamedDestByName(FPDF_DOCUMENT document,FPDF_BYTESTRING name)
813 {
814         if (!document)
815                 return NULL;
816         if (!name || name[0] == 0) 
817                 return NULL;
818
819         CPDF_Document* pDoc = (CPDF_Document*)document;
820         CPDF_NameTree name_tree(pDoc, FX_BSTRC("Dests"));
821         return name_tree.LookupNamedDest(pDoc, name);
822 }
823
824 DLLEXPORT FPDF_DEST STDCALL FPDF_GetNamedDest(FPDF_DOCUMENT document, int index, void* buffer, long& buflen)
825 {
826     if (!buffer)
827         buflen = 0;
828     if (!document || index < 0) return NULL;
829     CPDF_Document* pDoc = (CPDF_Document*)document;
830
831     CPDF_Dictionary* pRoot = pDoc->GetRoot();
832     if (!pRoot) return NULL;
833
834     CPDF_Object* pDestObj = NULL;
835     CFX_ByteString bsName;
836     CPDF_NameTree nameTree(pDoc, FX_BSTRC("Dests"));
837     int count = nameTree.GetCount();
838     if (index >= count) {
839         CPDF_Dictionary* pDest = pRoot->GetDict(FX_BSTRC("Dests"));
840         if (!pDest) return NULL;
841         if (index >= count + pDest->GetCount()) return NULL;
842         index -= count;
843         FX_POSITION pos = pDest->GetStartPos();
844         int i = 0;
845         while (pos) {
846             pDestObj = pDest->GetNextElement(pos, bsName);
847             if (!pDestObj) continue;
848             if (i == index) break;
849             i++;
850         }
851     } else {
852         pDestObj = nameTree.LookupValue(index, bsName);
853     }
854     if (!pDestObj) return NULL;
855     if (pDestObj->GetType() == PDFOBJ_DICTIONARY) {
856         pDestObj = ((CPDF_Dictionary*)pDestObj)->GetArray(FX_BSTRC("D"));
857         if (!pDestObj) return NULL;
858     }
859     if (pDestObj->GetType() != PDFOBJ_ARRAY) return NULL;
860     CFX_WideString wsName = PDF_DecodeText(bsName);
861     CFX_ByteString utf16Name = wsName.UTF16LE_Encode();
862     unsigned int len = utf16Name.GetLength();
863     if (!buffer) {
864         buflen = len;
865     } else if (buflen >= len) {
866         memcpy(buffer, utf16Name.c_str(), len);
867         buflen = len;
868     } else {
869         buflen = -1;
870     }
871     return (FPDF_DEST)pDestObj;
872 }