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