Merge to XFA: Kill remaining sprintfs
[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)
307 {
308         if (!document)
309                 return FALSE;
310
311         CPDF_Document *pdfDoc = (static_cast<CPDFXFA_Document *>(document))->GetPDFDoc();
312         if (!pdfDoc)
313                 return FALSE;
314
315         CPDF_Dictionary* pRoot = pdfDoc->GetRoot();
316         if (!pRoot)
317                 return FALSE;
318
319         CPDF_Dictionary* pAcroForm = pRoot->GetDict("AcroForm");
320         if (!pAcroForm)
321                 return FALSE;
322
323         CPDF_Object* pXFA = pAcroForm->GetElement("XFA");
324         if (!pXFA)
325                 return FALSE;
326
327         FX_BOOL bDynamicXFA = pRoot->GetBoolean("NeedsRendering", FALSE);
328
329         if (bDynamicXFA)
330                 docType = DOCTYPE_DYNIMIC_XFA;
331         else
332                 docType = DOCTYPE_STATIC_XFA;
333
334         return TRUE;
335 }
336
337 DLLEXPORT  FPDF_BOOL STDCALL FPDF_LoadXFA(FPDF_DOCUMENT document)
338 {
339         return document && (static_cast<CPDFXFA_Document *>(document))->LoadXFADoc();
340 }
341
342
343 extern void CheckUnSupportError(CPDF_Document * pDoc, FX_DWORD err_code);
344
345 class CMemFile FX_FINAL: public IFX_FileRead, public CFX_Object
346 {
347 public:
348         CMemFile(FX_BYTE* pBuf, FX_FILESIZE size):m_pBuf(pBuf),m_size(size) {}
349
350         virtual void                    Release() {delete this;}
351         virtual FX_FILESIZE             GetSize() {return m_size;}
352         virtual FX_BOOL                 ReadBlock(void* buffer, FX_FILESIZE offset, size_t size) 
353         {
354             if (offset < 0) {
355                 return FALSE;
356             }
357             FX_SAFE_FILESIZE newPos = pdfium::base::checked_cast<FX_FILESIZE, size_t>(size);
358             newPos += offset;
359             if (!newPos.IsValid() || newPos.ValueOrDie() > (FX_DWORD)m_size) {
360                 return FALSE;
361             }
362             FXSYS_memcpy(buffer, m_pBuf+offset, size);
363             return TRUE;
364         }
365 private:
366         FX_BYTE* m_pBuf;
367         FX_FILESIZE m_size;
368 };
369 DLLEXPORT FPDF_DOCUMENT STDCALL FPDF_LoadMemDocument(const void* data_buf, int size, FPDF_BYTESTRING password)
370 {
371         CPDF_Parser* pParser = FX_NEW CPDF_Parser;
372         pParser->SetPassword(password);
373         CMemFile* pMemFile = FX_NEW CMemFile((FX_BYTE*)data_buf, size);
374         FX_DWORD err_code = pParser->StartParse(pMemFile);
375         if (err_code) {
376                 delete pParser;
377                 ProcessParseError(err_code);
378                 return NULL;
379         }
380         CPDF_Document * pDoc = NULL;
381         pDoc = pParser?pParser->GetDocument():NULL;
382         CheckUnSupportError(pDoc, err_code);
383         CPDF_Document* pPDFDoc = pParser->GetDocument();
384         if (!pPDFDoc)
385                 return NULL;
386
387         CPDFXFA_App* pProvider = FPDFXFA_GetApp();
388         CPDFXFA_Document* pDocument = FX_NEW CPDFXFA_Document(pPDFDoc, pProvider);
389         //pDocument->LoadXFADoc();
390
391         return pDocument;
392 }
393
394 DLLEXPORT FPDF_DOCUMENT STDCALL FPDF_LoadCustomDocument(FPDF_FILEACCESS* pFileAccess, FPDF_BYTESTRING password)
395 {
396         CPDF_Parser* pParser = FX_NEW CPDF_Parser;
397         pParser->SetPassword(password);
398         CPDF_CustomAccess* pFile = FX_NEW CPDF_CustomAccess(pFileAccess);
399         FX_DWORD err_code = pParser->StartParse(pFile);
400         if (err_code) {
401                 delete pParser;
402                 ProcessParseError(err_code);
403                 return NULL;
404         }
405         CPDF_Document * pDoc = NULL;
406         pDoc = pParser?pParser->GetDocument():NULL;
407         CheckUnSupportError(pDoc, err_code);
408         CPDF_Document* pPDFDoc = pParser->GetDocument();
409         if (!pPDFDoc)
410                 return NULL;
411
412         CPDFXFA_App* pProvider = FPDFXFA_GetApp();
413         CPDFXFA_Document* pDocument = FX_NEW CPDFXFA_Document(pPDFDoc, pProvider);
414         //pDocument->LoadXFADoc();
415
416         return pDocument;
417 }
418
419 DLLEXPORT FPDF_BOOL STDCALL FPDF_GetFileVersion(FPDF_DOCUMENT doc, int* fileVersion)
420 {
421         if(!doc||!fileVersion) return FALSE;
422         *fileVersion = 0;
423         CPDFXFA_Document* pDoc = (CPDFXFA_Document*)doc;
424         CPDF_Document* pPDFDoc = pDoc->GetPDFDoc();
425         if (!pPDFDoc) return (FX_DWORD)-1;
426         CPDF_Parser* pParser =  (CPDF_Parser*)pPDFDoc->GetParser();
427
428         if(!pParser)
429                 return FALSE;
430         *fileVersion = pParser->GetFileVersion();
431         return TRUE;
432 }
433
434 // jabdelmalek: changed return type from FX_DWORD to build on Linux (and match header).
435 DLLEXPORT unsigned long STDCALL FPDF_GetDocPermissions(FPDF_DOCUMENT document)
436 {
437         if (document == NULL) return 0;
438         CPDFXFA_Document*pDoc = (CPDFXFA_Document*)document;
439         CPDF_Document* pPDFDoc = pDoc->GetPDFDoc();
440         if (!pPDFDoc) return (FX_DWORD)-1;
441         CPDF_Parser* pParser =  (CPDF_Parser*)pPDFDoc->GetParser();
442         CPDF_Dictionary* pDict = pParser->GetEncryptDict();
443         if (pDict == NULL) return (FX_DWORD)-1;
444
445         return pDict->GetInteger("P");
446 }
447
448 DLLEXPORT int STDCALL FPDF_GetSecurityHandlerRevision(FPDF_DOCUMENT document)
449 {
450     if (document == NULL) return -1;
451         CPDF_Document*pDoc = ((CPDFXFA_Document*)document)->GetPDFDoc();
452     CPDF_Parser* pParser = (CPDF_Parser*)pDoc->GetParser();
453     CPDF_Dictionary* pDict = pParser->GetEncryptDict();
454     if (pDict == NULL) return -1;
455
456     return pDict->GetInteger("R");
457 }
458
459 DLLEXPORT int STDCALL FPDF_GetPageCount(FPDF_DOCUMENT document)
460 {
461         if (document == NULL) return 0;
462         CPDFXFA_Document* pDoc = (CPDFXFA_Document*)document;
463         return pDoc->GetPageCount();
464 //      return ((CPDF_Document*)document)->GetPageCount();
465 }
466
467 DLLEXPORT FPDF_PAGE STDCALL FPDF_LoadPage(FPDF_DOCUMENT document, int page_index)
468 {
469         if (document == NULL) return NULL;
470         CPDFXFA_Document* pDoc = (CPDFXFA_Document*)document;
471         if (page_index < 0 || page_index >= pDoc->GetPageCount()) return NULL;
472 //      CPDF_Parser* pParser = (CPDF_Parser*)document;
473         return pDoc->GetPage(page_index);
474 }
475
476 DLLEXPORT double STDCALL FPDF_GetPageWidth(FPDF_PAGE page)
477 {
478         if (!page)
479                 return 0.0;
480         return ((CPDFXFA_Page*)page)->GetPageWidth();
481 //      return ((CPDF_Page*)page)->GetPageWidth();
482 }
483
484 DLLEXPORT double STDCALL FPDF_GetPageHeight(FPDF_PAGE page)
485 {
486         if (!page) return 0.0;
487 //      return ((CPDF_Page*)page)->GetPageHeight();
488         return ((CPDFXFA_Page*)page)->GetPageHeight();
489 }
490
491 void DropContext(void* data)
492 {
493         delete (CRenderContext*)data;
494 }
495
496 void FPDF_RenderPage_Retail(CRenderContext* pContext, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
497                                                 int rotate, int flags,FX_BOOL bNeedToRestore, IFSDK_PAUSE_Adapter * pause  );
498 void (*Func_RenderPage)(CRenderContext*, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
499                                                 int rotate, int flags,FX_BOOL bNeedToRestore, IFSDK_PAUSE_Adapter * pause  ) = FPDF_RenderPage_Retail;
500
501 #if defined(_DEBUG) || defined(DEBUG)
502 #define DEBUG_TRACE
503 #endif
504
505 #if defined(_WIN32)
506 DLLEXPORT void STDCALL FPDF_RenderPage(HDC dc, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
507                                                 int rotate, int flags)
508 {
509         if (page==NULL) return;
510         CPDF_Page* pPage = ((CPDFXFA_Page*)page)->GetPDFPage();
511         if (!pPage) return;
512
513         CRenderContext* pContext = FX_NEW CRenderContext;
514         pPage->SetPrivateData((void*)1, pContext, DropContext);
515
516 #ifndef _WIN32_WCE
517         CFX_DIBitmap* pBitmap = NULL;
518         FX_BOOL bBackgroundAlphaNeeded=FALSE;
519         bBackgroundAlphaNeeded = pPage->BackgroundAlphaNeeded();
520         if (bBackgroundAlphaNeeded)
521         {
522                 
523                 pBitmap = FX_NEW CFX_DIBitmap;
524                 pBitmap->Create(size_x, size_y, FXDIB_Argb);
525                 pBitmap->Clear(0x00ffffff);
526 #ifdef _SKIA_SUPPORT_
527                 pContext->m_pDevice = FX_NEW CFX_SkiaDevice;
528                 ((CFX_SkiaDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)pBitmap);
529 #else
530                 pContext->m_pDevice = FX_NEW CFX_FxgeDevice;
531                 ((CFX_FxgeDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)pBitmap);
532 #endif
533         }
534         else
535             pContext->m_pDevice = FX_NEW CFX_WindowsDevice(dc);
536
537         Func_RenderPage(pContext, page, start_x, start_y, size_x, size_y, rotate, flags,TRUE,NULL);
538
539         if (bBackgroundAlphaNeeded) 
540         {
541                 if (pBitmap)
542                 {
543                         CFX_WindowsDevice WinDC(dc);
544                         
545                         if (WinDC.GetDeviceCaps(FXDC_DEVICE_CLASS) == FXDC_PRINTER)
546                         {
547                                 CFX_DIBitmap* pDst = FX_NEW CFX_DIBitmap;
548                                 int pitch = pBitmap->GetPitch();
549                                 pDst->Create(size_x, size_y, FXDIB_Rgb32);
550                                 FXSYS_memset(pDst->GetBuffer(), -1, pitch*size_y);
551                                 pDst->CompositeBitmap(0, 0, size_x, size_y, pBitmap, 0, 0, FXDIB_BLEND_NORMAL, NULL, FALSE, NULL);
552                                 WinDC.StretchDIBits(pDst,0,0,size_x,size_y);
553                                 delete pDst;
554                         }
555                         else
556                                 WinDC.SetDIBits(pBitmap,0,0);
557
558                 }
559         }
560 #else
561         // get clip region
562         RECT rect, cliprect;
563         rect.left = start_x;
564         rect.top = start_y;
565         rect.right = start_x + size_x;
566         rect.bottom = start_y + size_y;
567         GetClipBox(dc, &cliprect);
568         IntersectRect(&rect, &rect, &cliprect);
569         int width = rect.right - rect.left;
570         int height = rect.bottom - rect.top;
571
572 #ifdef DEBUG_TRACE
573         {
574                 char str[128];
575                 memset(str, 0, sizeof(str));
576                 FXSYS_snprintf(str, sizeof(str) - 1, "Rendering DIB %d x %d", width, height);
577                 CPDF_ModuleMgr::Get()->ReportError(999, str);
578         }
579 #endif
580
581         // Create a DIB section
582         LPVOID pBuffer;
583         BITMAPINFOHEADER bmih;
584         FXSYS_memset(&bmih, 0, sizeof bmih);
585         bmih.biSize = sizeof bmih;
586         bmih.biBitCount = 24;
587         bmih.biHeight = -height;
588         bmih.biPlanes = 1;
589         bmih.biWidth = width;
590         pContext->m_hBitmap = CreateDIBSection(dc, (BITMAPINFO*)&bmih, DIB_RGB_COLORS, &pBuffer, NULL, 0);
591         if (pContext->m_hBitmap == NULL) {
592 #if defined(DEBUG) || defined(_DEBUG)
593                 char str[128];
594                 memset(str, 0, sizeof(str));
595                 FXSYS_snprintf(str, sizeof(str) - 1, "Error CreateDIBSection: %d x %d, error code = %d", width, height, GetLastError());
596                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, str);
597 #else
598                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, NULL);
599 #endif
600         }
601         FXSYS_memset(pBuffer, 0xff, height*((width*3+3)/4*4));
602
603 #ifdef DEBUG_TRACE
604         {
605                 CPDF_ModuleMgr::Get()->ReportError(999, "DIBSection created");
606         }
607 #endif
608
609         // Create a device with this external buffer
610         pContext->m_pBitmap = FX_NEW CFX_DIBitmap;
611         pContext->m_pBitmap->Create(width, height, FXDIB_Rgb, (FX_LPBYTE)pBuffer);
612         pContext->m_pDevice = FX_NEW CPDF_FxgeDevice;
613         ((CPDF_FxgeDevice*)pContext->m_pDevice)->Attach(pContext->m_pBitmap);
614         
615 #ifdef DEBUG_TRACE
616         CPDF_ModuleMgr::Get()->ReportError(999, "Ready for PDF rendering");
617 #endif
618
619         // output to bitmap device
620         Func_RenderPage(pContext, page, start_x - rect.left, start_y - rect.top, size_x, size_y, rotate, flags);
621
622 #ifdef DEBUG_TRACE
623         CPDF_ModuleMgr::Get()->ReportError(999, "Finished PDF rendering");
624 #endif
625
626         // Now output to real device
627         HDC hMemDC = CreateCompatibleDC(dc);
628         if (hMemDC == NULL) {
629 #if defined(DEBUG) || defined(_DEBUG)
630                 char str[128];
631                 memset(str, 0, sizeof(str));
632                 FXSYS_snprintf(str, sizeof(str) - 1, "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 }