Keep the declaration of FPDF_HasXFAField consistent with other XFA APIs
[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 #include "../include/fpdfformfill.h"
16 #include "../include/fpdfxfa/fpdfxfa_doc.h"
17 #include "../include/fpdfxfa/fpdfxfa_app.h"
18 #include "../include/fpdfxfa/fpdfxfa_page.h"
19 #include "../include/fpdfxfa/fpdfxfa_util.h"
20
21 CFPDF_FileStream::CFPDF_FileStream(FPDF_FILEHANDLER* pFS)
22 {
23         m_pFS                   =       pFS;
24         m_nCurPos               =       0;
25 }
26
27 IFX_FileStream* CFPDF_FileStream::Retain()
28 {
29         return this;
30 }
31
32 void CFPDF_FileStream::Release()
33 {
34         if (m_pFS && m_pFS->Release)
35                 m_pFS->Release(m_pFS->clientData);
36         delete this;
37 }
38
39 FX_FILESIZE CFPDF_FileStream::GetSize()
40 {
41         if (m_pFS && m_pFS->GetSize)
42                 return (FX_FILESIZE)m_pFS->GetSize(m_pFS->clientData);
43         return 0;
44 }
45
46 FX_BOOL CFPDF_FileStream::IsEOF()
47 {
48         return m_nCurPos >= GetSize();
49 }
50
51 FX_BOOL CFPDF_FileStream::ReadBlock(void* buffer, FX_FILESIZE offset, size_t size)
52 {
53         if (!buffer || !size || !m_pFS->ReadBlock) return FALSE;
54
55         if (m_pFS->ReadBlock(m_pFS->clientData, (FPDF_DWORD)offset, buffer, (FPDF_DWORD)size) == 0)
56         {
57                 m_nCurPos = offset + size;
58                 return TRUE;
59         }
60         return FALSE;
61 }
62
63 size_t CFPDF_FileStream::ReadBlock(void* buffer, size_t size)
64 {
65         if (!buffer || !size || !m_pFS->ReadBlock) return 0;
66         
67         FX_FILESIZE nSize = GetSize();
68         if (m_nCurPos >= nSize) return 0;
69         FX_FILESIZE dwAvail = nSize - m_nCurPos;
70         if (dwAvail < (FX_FILESIZE)size) size = (size_t)dwAvail;
71         if (m_pFS->ReadBlock(m_pFS->clientData, (FPDF_DWORD)m_nCurPos, buffer, (FPDF_DWORD)size) == 0)
72         {
73                 m_nCurPos += size;
74                 return size;
75         }
76
77         return 0;
78 }
79
80 FX_BOOL CFPDF_FileStream::WriteBlock(const void* buffer, FX_FILESIZE offset, size_t size)
81 {
82         if (!m_pFS || !m_pFS->WriteBlock) return FALSE;
83
84         if(m_pFS->WriteBlock(m_pFS->clientData, (FPDF_DWORD)offset, buffer, (FPDF_DWORD)size) == 0)
85         {
86                 m_nCurPos = offset + size;
87                 return TRUE;
88         }
89         return FALSE;
90 }
91
92 FX_BOOL CFPDF_FileStream::Flush()
93 {
94         if (!m_pFS || !m_pFS->Flush) return TRUE;
95
96         return m_pFS->Flush(m_pFS->clientData) == 0;
97 }
98
99 CPDF_CustomAccess::CPDF_CustomAccess(FPDF_FILEACCESS* pFileAccess)
100 {
101         m_FileAccess = *pFileAccess;
102         m_BufferOffset = (FX_DWORD)-1;
103 }
104
105 FX_BOOL CPDF_CustomAccess::GetByte(FX_DWORD pos, FX_BYTE& ch)
106 {
107         if (pos >= m_FileAccess.m_FileLen) return FALSE;
108         if (m_BufferOffset == (FX_DWORD)-1 || pos < m_BufferOffset || pos >= m_BufferOffset + 512) {
109                 // Need to read from file access
110                 m_BufferOffset = pos;
111                 int size = 512;
112                 if (pos + 512 > m_FileAccess.m_FileLen)
113                         size = m_FileAccess.m_FileLen - pos;
114                 if (!m_FileAccess.m_GetBlock(m_FileAccess.m_Param, m_BufferOffset, m_Buffer, size))
115                         return FALSE;
116         }
117         ch = m_Buffer[pos - m_BufferOffset];
118         return TRUE;
119 }
120
121 FX_BOOL CPDF_CustomAccess::GetBlock(FX_DWORD pos, FX_LPBYTE pBuf, FX_DWORD size)
122 {
123         if (pos + size > m_FileAccess.m_FileLen) return FALSE;
124         return m_FileAccess.m_GetBlock(m_FileAccess.m_Param, pos, pBuf, size);
125 }
126
127 FX_BOOL CPDF_CustomAccess::ReadBlock(void* buffer, FX_FILESIZE offset, size_t size)
128 {
129     if (offset < 0) {
130         return FALSE;
131     }
132     FX_SAFE_FILESIZE newPos = pdfium::base::checked_cast<FX_FILESIZE, size_t>(size);
133     newPos += offset;
134     if (!newPos.IsValid() || newPos.ValueOrDie() > m_FileAccess.m_FileLen) {
135         return FALSE;
136     }
137     return m_FileAccess.m_GetBlock(m_FileAccess.m_Param, offset,(FX_LPBYTE) buffer, size);
138 }
139
140 //0 bit: FPDF_POLICY_MACHINETIME_ACCESS
141 static FX_DWORD foxit_sandbox_policy = 0xFFFFFFFF;
142
143 void FSDK_SetSandBoxPolicy(FPDF_DWORD policy, FPDF_BOOL enable)
144 {
145         switch(policy)
146         {
147         case FPDF_POLICY_MACHINETIME_ACCESS:
148                 {
149                         if(enable)
150                                 foxit_sandbox_policy |= 0x01;
151                         else
152                                 foxit_sandbox_policy &= 0xFFFFFFFE;
153                 }
154                 break;
155         default:
156                 break;
157         }
158 }
159
160 FPDF_BOOL FSDK_IsSandBoxPolicyEnabled(FPDF_DWORD policy)
161 {
162         switch(policy)
163         {
164         case FPDF_POLICY_MACHINETIME_ACCESS:
165                 {
166                         if(foxit_sandbox_policy&0x01)
167                                 return TRUE;
168                         else
169                                 return FALSE;
170                 }
171                 break;
172         default:
173                 break;
174         }
175         return FALSE;
176 }
177
178
179 #ifndef _T
180 #define _T(x) x
181 #endif
182
183 #ifdef API5
184         CPDF_ModuleMgr* g_pModuleMgr = NULL;
185 #else
186         CCodec_ModuleMgr*       g_pCodecModule = NULL;
187 #endif
188
189 //extern CPDFSDK_FormFillApp* g_pFormFillApp;
190
191 #if _FX_OS_ == _FX_LINUX_EMBEDDED_
192 class CFontMapper : public IPDF_FontMapper
193 {
194 public:
195         CFontMapper();
196         virtual ~CFontMapper();
197
198         virtual FT_Face FindSubstFont(
199                                                         CPDF_Document* pDoc,                            // [IN] The PDF document
200                                                         const CFX_ByteString& face_name,        // [IN] Original name
201                                                         FX_BOOL bTrueType,                                      // [IN] TrueType or Type1
202                                                         FX_DWORD flags,                                         // [IN] PDF font flags (see PDF Reference section 5.7.1)
203                                                         int font_weight,                                        // [IN] original font weight. 0 for not specified
204                                                         int CharsetCP,                                          // [IN] code page for charset (see Win32 GetACP())
205                                                         FX_BOOL bVertical,
206                                                         CPDF_SubstFont* pSubstFont                      // [OUT] Subst font data
207                                                 );
208
209         FT_Face m_SysFace;
210 };
211
212 CFontMapper* g_pFontMapper = NULL;
213 #endif          // #if _FX_OS_ == _FX_LINUX_EMBEDDED_
214
215 DLLEXPORT void STDCALL FPDF_InitLibrary()
216 {
217         g_pCodecModule = CCodec_ModuleMgr::Create();
218         
219         CFX_GEModule::Create();
220         CFX_GEModule::Get()->SetCodecModule(g_pCodecModule);
221         
222         CPDF_ModuleMgr::Create();
223         CPDF_ModuleMgr::Get()->SetCodecModule(g_pCodecModule);
224         CPDF_ModuleMgr::Get()->InitPageModule();
225         CPDF_ModuleMgr::Get()->InitRenderModule();
226
227         CPDFXFA_App* pAppProvider = FPDFXFA_GetApp();
228         pAppProvider->Initialize();
229 }
230
231
232 DLLEXPORT void STDCALL FPDF_DestroyLibrary()
233 {
234         FPDFXFA_ReleaseApp();
235
236 #if _FX_OS_ == _FX_LINUX_EMBEDDED_
237         if (g_pFontMapper) delete g_pFontMapper;
238 #endif
239 #ifdef API5
240         g_pModuleMgr->Destroy();
241 #else
242         CPDF_ModuleMgr::Destroy();
243         CFX_GEModule::Destroy();
244         g_pCodecModule->Destroy();
245 #endif
246 }
247
248 #ifndef _WIN32
249 int g_LastError;
250 void SetLastError(int err)
251 {
252         g_LastError = err;
253 }
254
255 int GetLastError()
256 {
257         return g_LastError;
258 }
259 #endif
260
261 void ProcessParseError(FX_DWORD err_code)
262 {
263         // Translate FPDFAPI error code to FPDFVIEW error code
264         switch (err_code) {
265                 case PDFPARSE_ERROR_FILE:
266                         err_code = FPDF_ERR_FILE;
267                         break;
268                 case PDFPARSE_ERROR_FORMAT:
269                         err_code = FPDF_ERR_FORMAT;
270                         break;
271                 case PDFPARSE_ERROR_PASSWORD:
272                         err_code = FPDF_ERR_PASSWORD;
273                         break;
274                 case PDFPARSE_ERROR_HANDLER:
275                         err_code = FPDF_ERR_SECURITY;
276                         break;
277         }
278         SetLastError(err_code);
279 }
280
281 DLLEXPORT void  STDCALL FPDF_SetSandBoxPolicy(FPDF_DWORD policy, FPDF_BOOL enable)
282 {
283         return FSDK_SetSandBoxPolicy(policy, enable);
284 }
285
286 DLLEXPORT FPDF_DOCUMENT STDCALL FPDF_LoadDocument(FPDF_STRING file_path, FPDF_BYTESTRING password)
287 {
288         CPDF_Parser* pParser = FX_NEW CPDF_Parser;
289         pParser->SetPassword(password);
290
291         FX_DWORD err_code = pParser->StartParse((FX_LPCSTR)file_path);
292         if (err_code) {
293                 delete pParser;
294                 ProcessParseError(err_code);
295                 return NULL;
296         }
297         CPDF_Document* pPDFDoc = pParser->GetDocument();
298         if (!pPDFDoc)
299                 return NULL;
300
301         CPDFXFA_App* pProvider = FPDFXFA_GetApp();
302         CPDFXFA_Document* pDocument = FX_NEW CPDFXFA_Document(pPDFDoc, pProvider);
303         return pDocument;
304 }
305
306 DLLEXPORT FX_BOOL STDCALL FPDF_HasXFAField(FPDF_DOCUMENT document, int& docType)\r
307 {\r
308         if (!document)\r
309                 return FALSE;\r
310 \r
311         CPDF_Dictionary* pRoot = ((CPDF_Document*)document)->GetRoot();\r
312         if (!pRoot)\r
313                 return FALSE;\r
314 \r
315         CPDF_Dictionary* pAcroForm = pRoot->GetDict("AcroForm");\r
316         if (!pAcroForm)\r
317                 return FALSE;\r
318 \r
319         CPDF_Object* pXFA = pAcroForm->GetElement("XFA");\r
320         if (!pXFA)\r
321                 return FALSE;\r
322 \r
323         FX_BOOL bDynamicXFA = pRoot->GetBoolean("NeedsRendering", FALSE);\r
324 \r
325         if (bDynamicXFA)\r
326                 docType = DOCTYPE_DYNIMIC_XFA;\r
327         else\r
328                 docType = DOCTYPE_STATIC_XFA;\r
329 \r
330         return TRUE;\r
331 }
332
333 DLLEXPORT  FPDF_BOOL STDCALL FPDF_LoadXFA(FPDF_DOCUMENT document)
334 {
335         if (!document) 
336                 return FALSE;
337
338         int iDocType = DOCTYPE_PDF;
339         FX_BOOL hasXFAField = FPDF_HasXFAField(document, iDocType);
340         if (!hasXFAField)
341                 return FALSE;
342         return ((CPDFXFA_Document*)document)->LoadXFADoc();
343 }
344
345
346 extern void CheckUnSupportError(CPDF_Document * pDoc, FX_DWORD err_code);
347
348 class CMemFile FX_FINAL: public IFX_FileRead, public CFX_Object
349 {
350 public:
351         CMemFile(FX_BYTE* pBuf, FX_FILESIZE size):m_pBuf(pBuf),m_size(size) {}
352
353         virtual void                    Release() {delete this;}
354         virtual FX_FILESIZE             GetSize() {return m_size;}
355         virtual FX_BOOL                 ReadBlock(void* buffer, FX_FILESIZE offset, size_t size) 
356         {
357             if (offset < 0) {
358                 return FALSE;
359             }
360             FX_SAFE_FILESIZE newPos = pdfium::base::checked_cast<FX_FILESIZE, size_t>(size);
361             newPos += offset;
362             if (!newPos.IsValid() || newPos.ValueOrDie() > (FX_DWORD)m_size) {
363                 return FALSE;
364             }
365             FXSYS_memcpy(buffer, m_pBuf+offset, size);
366             return TRUE;
367         }
368 private:
369         FX_BYTE* m_pBuf;
370         FX_FILESIZE m_size;
371 };
372 DLLEXPORT FPDF_DOCUMENT STDCALL FPDF_LoadMemDocument(const void* data_buf, int size, FPDF_BYTESTRING password)
373 {
374         CPDF_Parser* pParser = FX_NEW CPDF_Parser;
375         pParser->SetPassword(password);
376         CMemFile* pMemFile = FX_NEW CMemFile((FX_BYTE*)data_buf, size);
377         FX_DWORD err_code = pParser->StartParse(pMemFile);
378         if (err_code) {
379                 delete pParser;
380                 ProcessParseError(err_code);
381                 return NULL;
382         }
383         CPDF_Document * pDoc = NULL;
384         pDoc = pParser?pParser->GetDocument():NULL;
385         CheckUnSupportError(pDoc, err_code);
386         CPDF_Document* pPDFDoc = pParser->GetDocument();
387         if (!pPDFDoc)
388                 return NULL;
389
390         CPDFXFA_App* pProvider = FPDFXFA_GetApp();
391         CPDFXFA_Document* pDocument = FX_NEW CPDFXFA_Document(pPDFDoc, pProvider);
392         //pDocument->LoadXFADoc();
393
394         return pDocument;
395 }
396
397 DLLEXPORT FPDF_DOCUMENT STDCALL FPDF_LoadCustomDocument(FPDF_FILEACCESS* pFileAccess, FPDF_BYTESTRING password)
398 {
399         CPDF_Parser* pParser = FX_NEW CPDF_Parser;
400         pParser->SetPassword(password);
401         CPDF_CustomAccess* pFile = FX_NEW CPDF_CustomAccess(pFileAccess);
402         FX_DWORD err_code = pParser->StartParse(pFile);
403         if (err_code) {
404                 delete pParser;
405                 ProcessParseError(err_code);
406                 return NULL;
407         }
408         CPDF_Document * pDoc = NULL;
409         pDoc = pParser?pParser->GetDocument():NULL;
410         CheckUnSupportError(pDoc, err_code);
411         CPDF_Document* pPDFDoc = pParser->GetDocument();
412         if (!pPDFDoc)
413                 return NULL;
414
415         CPDFXFA_App* pProvider = FPDFXFA_GetApp();
416         CPDFXFA_Document* pDocument = FX_NEW CPDFXFA_Document(pPDFDoc, pProvider);
417         //pDocument->LoadXFADoc();
418
419         return pDocument;
420 }
421
422 DLLEXPORT FPDF_BOOL STDCALL FPDF_GetFileVersion(FPDF_DOCUMENT doc, int* fileVersion)
423 {
424         if(!doc||!fileVersion) return FALSE;
425         *fileVersion = 0;
426         CPDFXFA_Document* pDoc = (CPDFXFA_Document*)doc;
427         CPDF_Document* pPDFDoc = pDoc->GetPDFDoc();
428         if (!pPDFDoc) return (FX_DWORD)-1;
429         CPDF_Parser* pParser =  (CPDF_Parser*)pPDFDoc->GetParser();
430
431         if(!pParser)
432                 return FALSE;
433         *fileVersion = pParser->GetFileVersion();
434         return TRUE;
435 }
436
437 // jabdelmalek: changed return type from FX_DWORD to build on Linux (and match header).
438 DLLEXPORT unsigned long STDCALL FPDF_GetDocPermissions(FPDF_DOCUMENT document)
439 {
440         if (document == NULL) return 0;
441         CPDFXFA_Document*pDoc = (CPDFXFA_Document*)document;
442         CPDF_Document* pPDFDoc = pDoc->GetPDFDoc();
443         if (!pPDFDoc) return (FX_DWORD)-1;
444         CPDF_Parser* pParser =  (CPDF_Parser*)pPDFDoc->GetParser();
445         CPDF_Dictionary* pDict = pParser->GetEncryptDict();
446         if (pDict == NULL) return (FX_DWORD)-1;
447
448         return pDict->GetInteger("P");
449 }
450
451 DLLEXPORT int STDCALL FPDF_GetSecurityHandlerRevision(FPDF_DOCUMENT document)
452 {
453     if (document == NULL) return -1;
454         CPDF_Document*pDoc = ((CPDFXFA_Document*)document)->GetPDFDoc();
455     CPDF_Parser* pParser = (CPDF_Parser*)pDoc->GetParser();
456     CPDF_Dictionary* pDict = pParser->GetEncryptDict();
457     if (pDict == NULL) return -1;
458
459     return pDict->GetInteger("R");
460 }
461
462 DLLEXPORT int STDCALL FPDF_GetPageCount(FPDF_DOCUMENT document)
463 {
464         if (document == NULL) return 0;
465         CPDFXFA_Document* pDoc = (CPDFXFA_Document*)document;
466         return pDoc->GetPageCount();
467 //      return ((CPDF_Document*)document)->GetPageCount();
468 }
469
470 DLLEXPORT FPDF_PAGE STDCALL FPDF_LoadPage(FPDF_DOCUMENT document, int page_index)
471 {
472         if (document == NULL) return NULL;
473         CPDFXFA_Document* pDoc = (CPDFXFA_Document*)document;
474         if (page_index < 0 || page_index >= pDoc->GetPageCount()) return NULL;
475 //      CPDF_Parser* pParser = (CPDF_Parser*)document;
476         return pDoc->GetPage(page_index);
477 }
478
479 DLLEXPORT double STDCALL FPDF_GetPageWidth(FPDF_PAGE page)
480 {
481         if (!page)
482                 return 0.0;
483         return ((CPDFXFA_Page*)page)->GetPageWidth();
484 //      return ((CPDF_Page*)page)->GetPageWidth();
485 }
486
487 DLLEXPORT double STDCALL FPDF_GetPageHeight(FPDF_PAGE page)
488 {
489         if (!page) return 0.0;
490 //      return ((CPDF_Page*)page)->GetPageHeight();
491         return ((CPDFXFA_Page*)page)->GetPageHeight();
492 }
493
494 void DropContext(void* data)
495 {
496         delete (CRenderContext*)data;
497 }
498
499 void FPDF_RenderPage_Retail(CRenderContext* pContext, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
500                                                 int rotate, int flags,FX_BOOL bNeedToRestore, IFSDK_PAUSE_Adapter * pause  );
501 void (*Func_RenderPage)(CRenderContext*, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
502                                                 int rotate, int flags,FX_BOOL bNeedToRestore, IFSDK_PAUSE_Adapter * pause  ) = FPDF_RenderPage_Retail;
503
504 #if defined(_DEBUG) || defined(DEBUG)
505 #define DEBUG_TRACE
506 #endif
507
508 #if defined(_WIN32)
509 DLLEXPORT void STDCALL FPDF_RenderPage(HDC dc, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
510                                                 int rotate, int flags)
511 {
512         if (page==NULL) return;
513         CPDF_Page* pPage = ((CPDFXFA_Page*)page)->GetPDFPage();
514         if (!pPage) return;
515
516         CRenderContext* pContext = FX_NEW CRenderContext;
517         pPage->SetPrivateData((void*)1, pContext, DropContext);
518
519 #ifndef _WIN32_WCE
520         CFX_DIBitmap* pBitmap = NULL;
521         FX_BOOL bBackgroundAlphaNeeded=FALSE;
522         bBackgroundAlphaNeeded = pPage->BackgroundAlphaNeeded();
523         if (bBackgroundAlphaNeeded)
524         {
525                 
526                 pBitmap = FX_NEW CFX_DIBitmap;
527                 pBitmap->Create(size_x, size_y, FXDIB_Argb);
528                 pBitmap->Clear(0x00ffffff);
529 #ifdef _SKIA_SUPPORT_
530                 pContext->m_pDevice = FX_NEW CFX_SkiaDevice;
531                 ((CFX_SkiaDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)pBitmap);
532 #else
533                 pContext->m_pDevice = FX_NEW CFX_FxgeDevice;
534                 ((CFX_FxgeDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)pBitmap);
535 #endif
536         }
537         else
538             pContext->m_pDevice = FX_NEW CFX_WindowsDevice(dc);
539
540         Func_RenderPage(pContext, page, start_x, start_y, size_x, size_y, rotate, flags,TRUE,NULL);
541
542         if (bBackgroundAlphaNeeded) 
543         {
544                 if (pBitmap)
545                 {
546                         CFX_WindowsDevice WinDC(dc);
547                         
548                         if (WinDC.GetDeviceCaps(FXDC_DEVICE_CLASS) == FXDC_PRINTER)
549                         {
550                                 CFX_DIBitmap* pDst = FX_NEW CFX_DIBitmap;
551                                 int pitch = pBitmap->GetPitch();
552                                 pDst->Create(size_x, size_y, FXDIB_Rgb32);
553                                 FXSYS_memset(pDst->GetBuffer(), -1, pitch*size_y);
554                                 pDst->CompositeBitmap(0, 0, size_x, size_y, pBitmap, 0, 0, FXDIB_BLEND_NORMAL, NULL, FALSE, NULL);
555                                 WinDC.StretchDIBits(pDst,0,0,size_x,size_y);
556                                 delete pDst;
557                         }
558                         else
559                                 WinDC.SetDIBits(pBitmap,0,0);
560
561                 }
562         }
563 #else
564         // get clip region
565         RECT rect, cliprect;
566         rect.left = start_x;
567         rect.top = start_y;
568         rect.right = start_x + size_x;
569         rect.bottom = start_y + size_y;
570         GetClipBox(dc, &cliprect);
571         IntersectRect(&rect, &rect, &cliprect);
572         int width = rect.right - rect.left;
573         int height = rect.bottom - rect.top;
574
575 #ifdef DEBUG_TRACE
576         {
577                 char str[128];
578                 sprintf(str, "Rendering DIB %d x %d", width, height);
579                 CPDF_ModuleMgr::Get()->ReportError(999, str);
580         }
581 #endif
582
583         // Create a DIB section
584         LPVOID pBuffer;
585         BITMAPINFOHEADER bmih;
586         FXSYS_memset(&bmih, 0, sizeof bmih);
587         bmih.biSize = sizeof bmih;
588         bmih.biBitCount = 24;
589         bmih.biHeight = -height;
590         bmih.biPlanes = 1;
591         bmih.biWidth = width;
592         pContext->m_hBitmap = CreateDIBSection(dc, (BITMAPINFO*)&bmih, DIB_RGB_COLORS, &pBuffer, NULL, 0);
593         if (pContext->m_hBitmap == NULL) {
594 #if defined(DEBUG) || defined(_DEBUG)
595                 char str[128];
596                 sprintf(str, "Error CreateDIBSection: %d x %d, error code = %d", width, height, GetLastError());
597                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, str);
598 #else
599                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, NULL);
600 #endif
601         }
602         FXSYS_memset(pBuffer, 0xff, height*((width*3+3)/4*4));
603
604 #ifdef DEBUG_TRACE
605         {
606                 CPDF_ModuleMgr::Get()->ReportError(999, "DIBSection created");
607         }
608 #endif
609
610         // Create a device with this external buffer
611         pContext->m_pBitmap = FX_NEW CFX_DIBitmap;
612         pContext->m_pBitmap->Create(width, height, FXDIB_Rgb, (FX_LPBYTE)pBuffer);
613         pContext->m_pDevice = FX_NEW CPDF_FxgeDevice;
614         ((CPDF_FxgeDevice*)pContext->m_pDevice)->Attach(pContext->m_pBitmap);
615         
616 #ifdef DEBUG_TRACE
617         CPDF_ModuleMgr::Get()->ReportError(999, "Ready for PDF rendering");
618 #endif
619
620         // output to bitmap device
621         Func_RenderPage(pContext, page, start_x - rect.left, start_y - rect.top, size_x, size_y, rotate, flags);
622
623 #ifdef DEBUG_TRACE
624         CPDF_ModuleMgr::Get()->ReportError(999, "Finished PDF rendering");
625 #endif
626
627         // Now output to real device
628         HDC hMemDC = CreateCompatibleDC(dc);
629         if (hMemDC == NULL) {
630 #if defined(DEBUG) || defined(_DEBUG)
631                 char str[128];
632                 sprintf(str, "Error CreateCompatibleDC. Error code = %d", GetLastError());
633                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, str);
634 #else
635                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, NULL);
636 #endif
637         }
638
639         HGDIOBJ hOldBitmap = SelectObject(hMemDC, pContext->m_hBitmap);
640
641 #ifdef DEBUG_TRACE
642         CPDF_ModuleMgr::Get()->ReportError(999, "Ready for screen rendering");
643 #endif
644
645         BitBlt(dc, rect.left, rect.top, width, height, hMemDC, 0, 0, SRCCOPY);
646         SelectObject(hMemDC, hOldBitmap);
647         DeleteDC(hMemDC);
648
649 #ifdef DEBUG_TRACE
650         CPDF_ModuleMgr::Get()->ReportError(999, "Finished screen rendering");
651 #endif
652
653 #endif
654         if (bBackgroundAlphaNeeded)
655         {
656                 if (pBitmap)
657                         delete pBitmap;
658                 pBitmap = NULL;
659         }
660         delete pContext;
661         pPage->RemovePrivateData((void*)1);
662 }
663 #endif
664
665 DLLEXPORT void STDCALL FPDF_RenderPageBitmap(FPDF_BITMAP bitmap, FPDF_PAGE page, int start_x, int start_y, 
666                                                 int size_x, int size_y, int rotate, int flags)
667 {
668         if (bitmap == NULL || page == NULL) return;
669         CPDF_Page* pPage = ((CPDFXFA_Page*)page)->GetPDFPage();
670         if (!pPage) return;
671
672         CRenderContext* pContext = FX_NEW CRenderContext;
673         pPage->SetPrivateData((void*)1, pContext, DropContext);
674 #ifdef _SKIA_SUPPORT_
675         pContext->m_pDevice = FX_NEW CFX_SkiaDevice;
676
677         if (flags & FPDF_REVERSE_BYTE_ORDER)
678                 ((CFX_SkiaDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap,0,TRUE);
679         else
680                 ((CFX_SkiaDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap);
681 #else
682         pContext->m_pDevice = FX_NEW CFX_FxgeDevice;
683
684         if (flags & FPDF_REVERSE_BYTE_ORDER)
685                 ((CFX_FxgeDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap,0,TRUE);
686         else
687                 ((CFX_FxgeDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap);
688 #endif
689
690         Func_RenderPage(pContext, page, start_x, start_y, size_x, size_y, rotate, flags,TRUE,NULL);
691
692         delete pContext;
693         pPage->RemovePrivateData((void*)1);
694 }
695
696 DLLEXPORT void STDCALL FPDF_ClosePage(FPDF_PAGE page)
697 {
698         if (!page) return;
699         CPDFXFA_Page* pPage = (CPDFXFA_Page*)page;
700         
701         pPage->Release();
702 //      CPDFXFA_Document* pDoc = pPage->GetDocument();
703 //      if (pDoc) {
704 //              pDoc->RemovePage(pPage);
705 //      }
706 //      delete (CPDFXFA_Page*)page;
707
708 }
709
710 DLLEXPORT void STDCALL FPDF_CloseDocument(FPDF_DOCUMENT document)
711 {
712         if (!document)
713                 return;
714         CPDFXFA_Document* pDoc = (CPDFXFA_Document*)document;   
715         delete pDoc;
716
717 //      CPDF_Parser* pParser = (CPDF_Parser*)pDoc->GetParser();
718 //      if (pParser == NULL) 
719 //      {
720 //              delete pDoc;
721 //              return;
722 //      }
723 //      delete pParser;
724 //      delete pDoc;
725 }
726
727 DLLEXPORT unsigned long STDCALL FPDF_GetLastError()
728 {
729         return GetLastError();
730 }
731
732 DLLEXPORT void STDCALL FPDF_DeviceToPage(FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
733                                                 int rotate, int device_x, int device_y, double* page_x, double* page_y)
734 {
735         if (page == NULL || page_x == NULL || page_y == NULL) return;
736         CPDFXFA_Page* pPage = (CPDFXFA_Page*)page;
737
738         pPage->DeviceToPage(start_x, start_y, size_x, size_y, rotate, device_x, device_y, page_x, page_y);
739 }
740
741 DLLEXPORT void STDCALL FPDF_PageToDevice(FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
742                                                 int rotate, double page_x, double page_y, int* device_x, int* device_y)
743 {
744         if (page == NULL || device_x == NULL || device_y == NULL) return;
745         CPDFXFA_Page* pPage = (CPDFXFA_Page*)page;
746         pPage->PageToDevice(start_x, start_y, size_x, size_y, rotate, page_x, page_y, device_x, device_y);
747 }
748
749 DLLEXPORT FPDF_BITMAP STDCALL FPDFBitmap_Create(int width, int height, int alpha)
750 {
751         CFX_DIBitmap* pBitmap = FX_NEW CFX_DIBitmap;
752         pBitmap->Create(width, height, alpha ? FXDIB_Argb : FXDIB_Rgb32);
753         return pBitmap;
754 }
755
756 DLLEXPORT FPDF_BITMAP STDCALL FPDFBitmap_CreateEx(int width, int height, int format, void* first_scan, int stride)
757 {
758         FXDIB_Format fx_format;
759         switch (format) {
760                 case FPDFBitmap_Gray:
761                         fx_format = FXDIB_8bppRgb;
762                         break;
763                 case FPDFBitmap_BGR:
764                         fx_format = FXDIB_Rgb;
765                         break;
766                 case FPDFBitmap_BGRx:
767                         fx_format = FXDIB_Rgb32;
768                         break;
769                 case FPDFBitmap_BGRA:
770                         fx_format = FXDIB_Argb;
771                         break;
772                 default:
773                         return NULL;
774         }
775         CFX_DIBitmap* pBitmap = FX_NEW CFX_DIBitmap;
776         pBitmap->Create(width, height, fx_format, (FX_LPBYTE)first_scan, stride);
777         return pBitmap;
778 }
779
780 DLLEXPORT void STDCALL FPDFBitmap_FillRect(FPDF_BITMAP bitmap, int left, int top, int width, int height, FPDF_DWORD color)
781 {
782         if (bitmap == NULL) return;
783 #ifdef _SKIA_SUPPORT_
784         CFX_SkiaDevice device;
785 #else
786         CFX_FxgeDevice device;
787 #endif
788         device.Attach((CFX_DIBitmap*)bitmap);
789         if (!((CFX_DIBitmap*)bitmap)->HasAlpha()) color |= 0xFF000000;
790         FX_RECT rect(left, top, left+width, top+height);
791         device.FillRect(&rect, color);
792 }
793
794 DLLEXPORT void* STDCALL FPDFBitmap_GetBuffer(FPDF_BITMAP bitmap)
795 {
796         if (bitmap == NULL) return NULL;
797         return ((CFX_DIBitmap*)bitmap)->GetBuffer();
798 }
799
800 DLLEXPORT int STDCALL FPDFBitmap_GetWidth(FPDF_BITMAP bitmap)
801 {
802         if (bitmap == NULL) return 0;
803         return ((CFX_DIBitmap*)bitmap)->GetWidth();
804 }
805
806 DLLEXPORT int STDCALL FPDFBitmap_GetHeight(FPDF_BITMAP bitmap)
807 {
808         if (bitmap == NULL) return 0;
809         return ((CFX_DIBitmap*)bitmap)->GetHeight();
810 }
811
812 DLLEXPORT int STDCALL FPDFBitmap_GetStride(FPDF_BITMAP bitmap)
813 {
814         if (bitmap == NULL) return 0;
815         return ((CFX_DIBitmap*)bitmap)->GetPitch();
816 }
817
818 DLLEXPORT void STDCALL FPDFBitmap_Destroy(FPDF_BITMAP bitmap)
819 {
820         if (bitmap == NULL) return;
821         delete (CFX_DIBitmap*)bitmap;
822 }
823
824 void FPDF_RenderPage_Retail(CRenderContext* pContext, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
825                                                 int rotate, int flags,FX_BOOL bNeedToRestore, IFSDK_PAUSE_Adapter * pause )
826 {
827         CPDF_Page* pPage = ((CPDFXFA_Page*)page)->GetPDFPage();
828         if (pPage == NULL) return;
829
830         if (!pContext->m_pOptions)
831                 pContext->m_pOptions = new CPDF_RenderOptions;
832 //      CPDF_RenderOptions options;
833         if (flags & FPDF_LCD_TEXT)
834                 pContext->m_pOptions->m_Flags |= RENDER_CLEARTYPE;
835         else
836                 pContext->m_pOptions->m_Flags &= ~RENDER_CLEARTYPE;
837         if (flags & FPDF_NO_NATIVETEXT)
838                 pContext->m_pOptions->m_Flags |= RENDER_NO_NATIVETEXT;
839         if (flags & FPDF_RENDER_LIMITEDIMAGECACHE)
840                 pContext->m_pOptions->m_Flags |= RENDER_LIMITEDIMAGECACHE;
841         if (flags & FPDF_RENDER_FORCEHALFTONE)
842                 pContext->m_pOptions->m_Flags |= RENDER_FORCE_HALFTONE;
843         //Grayscale output
844         if (flags & FPDF_GRAYSCALE)
845         {
846                 pContext->m_pOptions->m_ColorMode = RENDER_COLOR_GRAY;
847                 pContext->m_pOptions->m_ForeColor = 0;
848                 pContext->m_pOptions->m_BackColor = 0xffffff;
849         }
850         const CPDF_OCContext::UsageType usage = (flags & FPDF_PRINTING) ? CPDF_OCContext::Print : CPDF_OCContext::View;
851
852         pContext->m_pOptions->m_AddFlags = flags >> 8;
853
854         pContext->m_pOptions->m_pOCContext = new CPDF_OCContext(pPage->m_pDocument, usage);
855
856
857         CFX_AffineMatrix matrix;
858         pPage->GetDisplayMatrix(matrix, start_x, start_y, size_x, size_y, rotate); 
859
860         FX_RECT clip;
861         clip.left = start_x;
862         clip.right = start_x + size_x;
863         clip.top = start_y;
864         clip.bottom = start_y + size_y;
865         pContext->m_pDevice->SaveState();
866         pContext->m_pDevice->SetClip_Rect(&clip);
867
868         pContext->m_pContext = FX_NEW CPDF_RenderContext;
869         pContext->m_pContext->Create(pPage);
870         pContext->m_pContext->AppendObjectList(pPage, &matrix);
871
872         if (flags & FPDF_ANNOT) {
873                 pContext->m_pAnnots = FX_NEW CPDF_AnnotList(pPage);
874                 FX_BOOL bPrinting = pContext->m_pDevice->GetDeviceClass() != FXDC_DISPLAY;
875                 pContext->m_pAnnots->DisplayAnnots(pPage, pContext->m_pContext, bPrinting, &matrix, TRUE, NULL);
876         }
877
878         pContext->m_pRenderer = FX_NEW CPDF_ProgressiveRenderer;
879         pContext->m_pRenderer->Start(pContext->m_pContext, pContext->m_pDevice, pContext->m_pOptions, pause);
880         if (bNeedToRestore)
881         {
882           pContext->m_pDevice->RestoreState();
883         }
884         
885 //#endif
886 }
887
888 DLLEXPORT int STDCALL FPDF_GetPageSizeByIndex(FPDF_DOCUMENT document, int page_index, double* width, double* height)
889 {
890 //      CPDF_Document* pDoc = (CPDF_Document*)document;
891 //      if(pDoc == NULL)
892 //              return FALSE;
893 // 
894 //      CPDF_Dictionary* pDict = pDoc->GetPage(page_index);
895 //      if (pDict == NULL) return FALSE;
896 // 
897 //      CPDF_Page page;
898 //      page.Load(pDoc, pDict);
899 //      *width = page.GetPageWidth();
900 //      *height = page.GetPageHeight();
901
902         CPDFXFA_Document* pDoc = (CPDFXFA_Document*)document;
903         if (pDoc == NULL)
904                 return FALSE;
905
906         int count = pDoc->GetPageCount();
907         if (page_index < 0 || page_index >= count)
908                 return FALSE;
909
910         CPDFXFA_Page* pPage = pDoc->GetPage(page_index);
911         if (!pPage)
912                 return FALSE;
913
914         *width = pPage->GetPageWidth();
915         *height = pPage->GetPageHeight();
916
917         return TRUE;
918 }
919
920 DLLEXPORT FPDF_BOOL STDCALL FPDF_VIEWERREF_GetPrintScaling(FPDF_DOCUMENT document)
921 {
922         CPDFXFA_Document* pDoc = (CPDFXFA_Document*)document;
923         if (!pDoc) return TRUE;
924         CPDF_Document* pPDFDoc = pDoc->GetPDFDoc();
925         if (!pPDFDoc) return TRUE;
926         CPDF_ViewerPreferences viewRef(pPDFDoc);
927         return viewRef.PrintScaling();
928 }
929
930 DLLEXPORT int STDCALL FPDF_VIEWERREF_GetNumCopies(FPDF_DOCUMENT document)
931 {
932         CPDF_Document* pDoc = ((CPDFXFA_Document*)document)->GetPDFDoc();
933     if (!pDoc) return 1;
934     CPDF_ViewerPreferences viewRef(pDoc);
935     return viewRef.NumCopies();
936 }
937
938 DLLEXPORT FPDF_PAGERANGE STDCALL FPDF_VIEWERREF_GetPrintPageRange(FPDF_DOCUMENT document)
939 {
940         CPDF_Document* pDoc = ((CPDFXFA_Document*)document)->GetPDFDoc();
941     if (!pDoc) return NULL;
942     CPDF_ViewerPreferences viewRef(pDoc);
943     return viewRef.PrintPageRange();
944 }
945
946 DLLEXPORT FPDF_DUPLEXTYPE STDCALL FPDF_VIEWERREF_GetDuplex(FPDF_DOCUMENT document)
947 {
948         CPDF_Document* pDoc = ((CPDFXFA_Document*)document)->GetPDFDoc();
949     if (!pDoc) return DuplexUndefined;
950     CPDF_ViewerPreferences viewRef(pDoc);
951     CFX_ByteString duplex = viewRef.Duplex();
952     if (FX_BSTRC("Simplex") == duplex)
953         return Simplex;
954     if (FX_BSTRC("DuplexFlipShortEdge") == duplex)
955         return DuplexFlipShortEdge;
956     if (FX_BSTRC("DuplexFlipLongEdge") == duplex)
957         return DuplexFlipLongEdge;
958     return DuplexUndefined;
959 }
960
961 DLLEXPORT FPDF_DWORD STDCALL FPDF_CountNamedDests(FPDF_DOCUMENT document)
962 {
963     if (!document) return 0;
964         CPDF_Document* pDoc = ((CPDFXFA_Document*)document)->GetPDFDoc();
965
966     CPDF_Dictionary* pRoot = pDoc->GetRoot();
967     if (!pRoot) return 0;
968
969     CPDF_NameTree nameTree(pDoc, FX_BSTRC("Dests"));
970     int count = nameTree.GetCount();
971     CPDF_Dictionary* pDest = pRoot->GetDict(FX_BSTRC("Dests"));
972     if (pDest)
973         count += pDest->GetCount();
974     return count;
975 }
976
977 DLLEXPORT FPDF_DEST STDCALL FPDF_GetNamedDestByName(FPDF_DOCUMENT document,FPDF_BYTESTRING name)
978 {
979         if (!document)
980                 return NULL;
981         if (!name || name[0] == 0) 
982                 return NULL;
983
984         CPDFXFA_Document* pDoc = (CPDFXFA_Document*)document;
985         CPDF_Document* pPDFDoc = pDoc->GetPDFDoc();
986         if (!pPDFDoc) 
987                 return NULL;
988         CPDF_NameTree name_tree(pPDFDoc, FX_BSTRC("Dests"));
989         return name_tree.LookupNamedDest(pPDFDoc, name);
990 }
991
992 FPDF_RESULT     FPDF_BStr_Init(FPDF_BSTR* str)
993 {
994         if (!str)
995                 return -1;
996
997         FXSYS_memset32(str, 0, sizeof(FPDF_BSTR));
998         return 0;
999 }
1000
1001 FPDF_RESULT FPDF_BStr_Set(FPDF_BSTR* str, FPDF_LPCSTR bstr, int length)
1002 {
1003         if (!str) return -1;
1004         if (!bstr || !length)
1005                 return -1;
1006         if (length == -1)
1007                 length = FXSYS_strlen(bstr);
1008
1009         if (length == 0)
1010         {
1011                 if (str->str)
1012                 {
1013                         FX_Free(str->str);
1014                         str->str = NULL;
1015                 }
1016                 str->len = 0;
1017                 return 0;
1018         }
1019
1020         if (str->str && str->len < length)
1021                 str->str = FX_Realloc(char, str->str, length+1);
1022         else if (!str->str)
1023                 str->str = FX_Alloc(char, length+1);
1024
1025         str->str[length] = 0;
1026         if (str->str == NULL)
1027                 return -1;
1028
1029         FXSYS_memcpy(str->str, bstr, length);
1030         str->len = length;
1031
1032         return 0;
1033 }
1034
1035 FPDF_RESULT     FPDF_BStr_Clear(FPDF_BSTR* str)
1036 {
1037         if(!str)
1038                 return -1;
1039
1040         if (str->str)
1041         {
1042                 FX_Free(str->str);
1043                 str->str = NULL;
1044         }
1045         str->len = 0;
1046         return 0;
1047 }
1048
1049 DLLEXPORT FPDF_DEST STDCALL FPDF_GetNamedDest(FPDF_DOCUMENT document, int index, void* buffer, long& buflen)
1050 {
1051     if (!buffer)
1052         buflen = 0;
1053     if (!document || index < 0) return NULL;
1054         CPDF_Document* pDoc = ((CPDFXFA_Document*)document)->GetPDFDoc();
1055
1056     CPDF_Dictionary* pRoot = pDoc->GetRoot();
1057     if (!pRoot) return NULL;
1058
1059     CPDF_Object* pDestObj = NULL;
1060     CFX_ByteString bsName;
1061     CPDF_NameTree nameTree(pDoc, FX_BSTRC("Dests"));
1062     int count = nameTree.GetCount();
1063     if (index >= count) {
1064         CPDF_Dictionary* pDest = pRoot->GetDict(FX_BSTRC("Dests"));
1065         if (!pDest) return NULL;
1066         if (index >= count + pDest->GetCount()) return NULL;
1067         index -= count;
1068         FX_POSITION pos = pDest->GetStartPos();
1069         int i = 0;
1070         while (pos) {
1071             pDestObj = pDest->GetNextElement(pos, bsName);
1072             if (!pDestObj) continue;
1073             if (i == index) break;
1074             i++;
1075         }
1076     } else {
1077         pDestObj = nameTree.LookupValue(index, bsName);
1078     }
1079     if (!pDestObj) return NULL;
1080     if (pDestObj->GetType() == PDFOBJ_DICTIONARY) {
1081         pDestObj = ((CPDF_Dictionary*)pDestObj)->GetArray(FX_BSTRC("D"));
1082         if (!pDestObj) return NULL;
1083     }
1084     if (pDestObj->GetType() != PDFOBJ_ARRAY) return NULL;
1085     CFX_WideString wsName = PDF_DecodeText(bsName);
1086     CFX_ByteString utf16Name = wsName.UTF16LE_Encode();
1087     unsigned int len = utf16Name.GetLength();
1088     if (!buffer) {
1089         buflen = len;
1090     } else if (buflen >= len) {
1091         memcpy(buffer, utf16Name.c_str(), len);
1092         buflen = len;
1093     } else {
1094         buflen = -1;
1095     }
1096     return (FPDF_DEST)pDestObj;
1097 }