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