db191245f37bc4a12f745e3d8c922d806363f4c8
[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                 sprintf(str, "Rendering DIB %d x %d", width, height);
576                 CPDF_ModuleMgr::Get()->ReportError(999, str);
577         }
578 #endif
579
580         // Create a DIB section
581         LPVOID pBuffer;
582         BITMAPINFOHEADER bmih;
583         FXSYS_memset(&bmih, 0, sizeof bmih);
584         bmih.biSize = sizeof bmih;
585         bmih.biBitCount = 24;
586         bmih.biHeight = -height;
587         bmih.biPlanes = 1;
588         bmih.biWidth = width;
589         pContext->m_hBitmap = CreateDIBSection(dc, (BITMAPINFO*)&bmih, DIB_RGB_COLORS, &pBuffer, NULL, 0);
590         if (pContext->m_hBitmap == NULL) {
591 #if defined(DEBUG) || defined(_DEBUG)
592                 char str[128];
593                 sprintf(str, "Error CreateDIBSection: %d x %d, error code = %d", width, height, GetLastError());
594                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, str);
595 #else
596                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, NULL);
597 #endif
598         }
599         FXSYS_memset(pBuffer, 0xff, height*((width*3+3)/4*4));
600
601 #ifdef DEBUG_TRACE
602         {
603                 CPDF_ModuleMgr::Get()->ReportError(999, "DIBSection created");
604         }
605 #endif
606
607         // Create a device with this external buffer
608         pContext->m_pBitmap = FX_NEW CFX_DIBitmap;
609         pContext->m_pBitmap->Create(width, height, FXDIB_Rgb, (FX_LPBYTE)pBuffer);
610         pContext->m_pDevice = FX_NEW CPDF_FxgeDevice;
611         ((CPDF_FxgeDevice*)pContext->m_pDevice)->Attach(pContext->m_pBitmap);
612         
613 #ifdef DEBUG_TRACE
614         CPDF_ModuleMgr::Get()->ReportError(999, "Ready for PDF rendering");
615 #endif
616
617         // output to bitmap device
618         Func_RenderPage(pContext, page, start_x - rect.left, start_y - rect.top, size_x, size_y, rotate, flags);
619
620 #ifdef DEBUG_TRACE
621         CPDF_ModuleMgr::Get()->ReportError(999, "Finished PDF rendering");
622 #endif
623
624         // Now output to real device
625         HDC hMemDC = CreateCompatibleDC(dc);
626         if (hMemDC == NULL) {
627 #if defined(DEBUG) || defined(_DEBUG)
628                 char str[128];
629                 sprintf(str, "Error CreateCompatibleDC. Error code = %d", GetLastError());
630                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, str);
631 #else
632                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, NULL);
633 #endif
634         }
635
636         HGDIOBJ hOldBitmap = SelectObject(hMemDC, pContext->m_hBitmap);
637
638 #ifdef DEBUG_TRACE
639         CPDF_ModuleMgr::Get()->ReportError(999, "Ready for screen rendering");
640 #endif
641
642         BitBlt(dc, rect.left, rect.top, width, height, hMemDC, 0, 0, SRCCOPY);
643         SelectObject(hMemDC, hOldBitmap);
644         DeleteDC(hMemDC);
645
646 #ifdef DEBUG_TRACE
647         CPDF_ModuleMgr::Get()->ReportError(999, "Finished screen rendering");
648 #endif
649
650 #endif
651         if (bBackgroundAlphaNeeded)
652         {
653                 if (pBitmap)
654                         delete pBitmap;
655                 pBitmap = NULL;
656         }
657         delete pContext;
658         pPage->RemovePrivateData((void*)1);
659 }
660 #endif
661
662 DLLEXPORT void STDCALL FPDF_RenderPageBitmap(FPDF_BITMAP bitmap, FPDF_PAGE page, int start_x, int start_y, 
663                                                 int size_x, int size_y, int rotate, int flags)
664 {
665         if (bitmap == NULL || page == NULL) return;
666         CPDF_Page* pPage = ((CPDFXFA_Page*)page)->GetPDFPage();
667         if (!pPage) return;
668
669         CRenderContext* pContext = FX_NEW CRenderContext;
670         pPage->SetPrivateData((void*)1, pContext, DropContext);
671 #ifdef _SKIA_SUPPORT_
672         pContext->m_pDevice = FX_NEW CFX_SkiaDevice;
673
674         if (flags & FPDF_REVERSE_BYTE_ORDER)
675                 ((CFX_SkiaDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap,0,TRUE);
676         else
677                 ((CFX_SkiaDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap);
678 #else
679         pContext->m_pDevice = FX_NEW CFX_FxgeDevice;
680
681         if (flags & FPDF_REVERSE_BYTE_ORDER)
682                 ((CFX_FxgeDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap,0,TRUE);
683         else
684                 ((CFX_FxgeDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap);
685 #endif
686
687         Func_RenderPage(pContext, page, start_x, start_y, size_x, size_y, rotate, flags,TRUE,NULL);
688
689         delete pContext;
690         pPage->RemovePrivateData((void*)1);
691 }
692
693 DLLEXPORT void STDCALL FPDF_ClosePage(FPDF_PAGE page)
694 {
695         if (!page) return;
696         CPDFXFA_Page* pPage = (CPDFXFA_Page*)page;
697         
698         pPage->Release();
699 //      CPDFXFA_Document* pDoc = pPage->GetDocument();
700 //      if (pDoc) {
701 //              pDoc->RemovePage(pPage);
702 //      }
703 //      delete (CPDFXFA_Page*)page;
704
705 }
706
707 DLLEXPORT void STDCALL FPDF_CloseDocument(FPDF_DOCUMENT document)
708 {
709         if (!document)
710                 return;
711         CPDFXFA_Document* pDoc = (CPDFXFA_Document*)document;   
712         delete pDoc;
713
714 //      CPDF_Parser* pParser = (CPDF_Parser*)pDoc->GetParser();
715 //      if (pParser == NULL) 
716 //      {
717 //              delete pDoc;
718 //              return;
719 //      }
720 //      delete pParser;
721 //      delete pDoc;
722 }
723
724 DLLEXPORT unsigned long STDCALL FPDF_GetLastError()
725 {
726         return GetLastError();
727 }
728
729 DLLEXPORT void STDCALL FPDF_DeviceToPage(FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
730                                                 int rotate, int device_x, int device_y, double* page_x, double* page_y)
731 {
732         if (page == NULL || page_x == NULL || page_y == NULL) return;
733         CPDFXFA_Page* pPage = (CPDFXFA_Page*)page;
734
735         pPage->DeviceToPage(start_x, start_y, size_x, size_y, rotate, device_x, device_y, page_x, page_y);
736 }
737
738 DLLEXPORT void STDCALL FPDF_PageToDevice(FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
739                                                 int rotate, double page_x, double page_y, int* device_x, int* device_y)
740 {
741         if (page == NULL || device_x == NULL || device_y == NULL) return;
742         CPDFXFA_Page* pPage = (CPDFXFA_Page*)page;
743         pPage->PageToDevice(start_x, start_y, size_x, size_y, rotate, page_x, page_y, device_x, device_y);
744 }
745
746 DLLEXPORT FPDF_BITMAP STDCALL FPDFBitmap_Create(int width, int height, int alpha)
747 {
748         CFX_DIBitmap* pBitmap = FX_NEW CFX_DIBitmap;
749         pBitmap->Create(width, height, alpha ? FXDIB_Argb : FXDIB_Rgb32);
750         return pBitmap;
751 }
752
753 DLLEXPORT FPDF_BITMAP STDCALL FPDFBitmap_CreateEx(int width, int height, int format, void* first_scan, int stride)
754 {
755         FXDIB_Format fx_format;
756         switch (format) {
757                 case FPDFBitmap_Gray:
758                         fx_format = FXDIB_8bppRgb;
759                         break;
760                 case FPDFBitmap_BGR:
761                         fx_format = FXDIB_Rgb;
762                         break;
763                 case FPDFBitmap_BGRx:
764                         fx_format = FXDIB_Rgb32;
765                         break;
766                 case FPDFBitmap_BGRA:
767                         fx_format = FXDIB_Argb;
768                         break;
769                 default:
770                         return NULL;
771         }
772         CFX_DIBitmap* pBitmap = FX_NEW CFX_DIBitmap;
773         pBitmap->Create(width, height, fx_format, (FX_LPBYTE)first_scan, stride);
774         return pBitmap;
775 }
776
777 DLLEXPORT void STDCALL FPDFBitmap_FillRect(FPDF_BITMAP bitmap, int left, int top, int width, int height, FPDF_DWORD color)
778 {
779         if (bitmap == NULL) return;
780 #ifdef _SKIA_SUPPORT_
781         CFX_SkiaDevice device;
782 #else
783         CFX_FxgeDevice device;
784 #endif
785         device.Attach((CFX_DIBitmap*)bitmap);
786         if (!((CFX_DIBitmap*)bitmap)->HasAlpha()) color |= 0xFF000000;
787         FX_RECT rect(left, top, left+width, top+height);
788         device.FillRect(&rect, color);
789 }
790
791 DLLEXPORT void* STDCALL FPDFBitmap_GetBuffer(FPDF_BITMAP bitmap)
792 {
793         if (bitmap == NULL) return NULL;
794         return ((CFX_DIBitmap*)bitmap)->GetBuffer();
795 }
796
797 DLLEXPORT int STDCALL FPDFBitmap_GetWidth(FPDF_BITMAP bitmap)
798 {
799         if (bitmap == NULL) return 0;
800         return ((CFX_DIBitmap*)bitmap)->GetWidth();
801 }
802
803 DLLEXPORT int STDCALL FPDFBitmap_GetHeight(FPDF_BITMAP bitmap)
804 {
805         if (bitmap == NULL) return 0;
806         return ((CFX_DIBitmap*)bitmap)->GetHeight();
807 }
808
809 DLLEXPORT int STDCALL FPDFBitmap_GetStride(FPDF_BITMAP bitmap)
810 {
811         if (bitmap == NULL) return 0;
812         return ((CFX_DIBitmap*)bitmap)->GetPitch();
813 }
814
815 DLLEXPORT void STDCALL FPDFBitmap_Destroy(FPDF_BITMAP bitmap)
816 {
817         if (bitmap == NULL) return;
818         delete (CFX_DIBitmap*)bitmap;
819 }
820
821 void FPDF_RenderPage_Retail(CRenderContext* pContext, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
822                                                 int rotate, int flags,FX_BOOL bNeedToRestore, IFSDK_PAUSE_Adapter * pause )
823 {
824         CPDF_Page* pPage = ((CPDFXFA_Page*)page)->GetPDFPage();
825         if (pPage == NULL) return;
826
827         if (!pContext->m_pOptions)
828                 pContext->m_pOptions = new CPDF_RenderOptions;
829 //      CPDF_RenderOptions options;
830         if (flags & FPDF_LCD_TEXT)
831                 pContext->m_pOptions->m_Flags |= RENDER_CLEARTYPE;
832         else
833                 pContext->m_pOptions->m_Flags &= ~RENDER_CLEARTYPE;
834         if (flags & FPDF_NO_NATIVETEXT)
835                 pContext->m_pOptions->m_Flags |= RENDER_NO_NATIVETEXT;
836         if (flags & FPDF_RENDER_LIMITEDIMAGECACHE)
837                 pContext->m_pOptions->m_Flags |= RENDER_LIMITEDIMAGECACHE;
838         if (flags & FPDF_RENDER_FORCEHALFTONE)
839                 pContext->m_pOptions->m_Flags |= RENDER_FORCE_HALFTONE;
840         //Grayscale output
841         if (flags & FPDF_GRAYSCALE)
842         {
843                 pContext->m_pOptions->m_ColorMode = RENDER_COLOR_GRAY;
844                 pContext->m_pOptions->m_ForeColor = 0;
845                 pContext->m_pOptions->m_BackColor = 0xffffff;
846         }
847         const CPDF_OCContext::UsageType usage = (flags & FPDF_PRINTING) ? CPDF_OCContext::Print : CPDF_OCContext::View;
848
849         pContext->m_pOptions->m_AddFlags = flags >> 8;
850
851         pContext->m_pOptions->m_pOCContext = new CPDF_OCContext(pPage->m_pDocument, usage);
852
853
854         CFX_AffineMatrix matrix;
855         pPage->GetDisplayMatrix(matrix, start_x, start_y, size_x, size_y, rotate); 
856
857         FX_RECT clip;
858         clip.left = start_x;
859         clip.right = start_x + size_x;
860         clip.top = start_y;
861         clip.bottom = start_y + size_y;
862         pContext->m_pDevice->SaveState();
863         pContext->m_pDevice->SetClip_Rect(&clip);
864
865         pContext->m_pContext = FX_NEW CPDF_RenderContext;
866         pContext->m_pContext->Create(pPage);
867         pContext->m_pContext->AppendObjectList(pPage, &matrix);
868
869         if (flags & FPDF_ANNOT) {
870                 pContext->m_pAnnots = FX_NEW CPDF_AnnotList(pPage);
871                 FX_BOOL bPrinting = pContext->m_pDevice->GetDeviceClass() != FXDC_DISPLAY;
872                 pContext->m_pAnnots->DisplayAnnots(pPage, pContext->m_pContext, bPrinting, &matrix, TRUE, NULL);
873         }
874
875         pContext->m_pRenderer = FX_NEW CPDF_ProgressiveRenderer;
876         pContext->m_pRenderer->Start(pContext->m_pContext, pContext->m_pDevice, pContext->m_pOptions, pause);
877         if (bNeedToRestore)
878         {
879           pContext->m_pDevice->RestoreState();
880         }
881         
882 //#endif
883 }
884
885 DLLEXPORT int STDCALL FPDF_GetPageSizeByIndex(FPDF_DOCUMENT document, int page_index, double* width, double* height)
886 {
887 //      CPDF_Document* pDoc = (CPDF_Document*)document;
888 //      if(pDoc == NULL)
889 //              return FALSE;
890 // 
891 //      CPDF_Dictionary* pDict = pDoc->GetPage(page_index);
892 //      if (pDict == NULL) return FALSE;
893 // 
894 //      CPDF_Page page;
895 //      page.Load(pDoc, pDict);
896 //      *width = page.GetPageWidth();
897 //      *height = page.GetPageHeight();
898
899         CPDFXFA_Document* pDoc = (CPDFXFA_Document*)document;
900         if (pDoc == NULL)
901                 return FALSE;
902
903         int count = pDoc->GetPageCount();
904         if (page_index < 0 || page_index >= count)
905                 return FALSE;
906
907         CPDFXFA_Page* pPage = pDoc->GetPage(page_index);
908         if (!pPage)
909                 return FALSE;
910
911         *width = pPage->GetPageWidth();
912         *height = pPage->GetPageHeight();
913
914         return TRUE;
915 }
916
917 DLLEXPORT FPDF_BOOL STDCALL FPDF_VIEWERREF_GetPrintScaling(FPDF_DOCUMENT document)
918 {
919         CPDFXFA_Document* pDoc = (CPDFXFA_Document*)document;
920         if (!pDoc) return TRUE;
921         CPDF_Document* pPDFDoc = pDoc->GetPDFDoc();
922         if (!pPDFDoc) return TRUE;
923         CPDF_ViewerPreferences viewRef(pPDFDoc);
924         return viewRef.PrintScaling();
925 }
926
927 DLLEXPORT int STDCALL FPDF_VIEWERREF_GetNumCopies(FPDF_DOCUMENT document)
928 {
929         CPDF_Document* pDoc = ((CPDFXFA_Document*)document)->GetPDFDoc();
930     if (!pDoc) return 1;
931     CPDF_ViewerPreferences viewRef(pDoc);
932     return viewRef.NumCopies();
933 }
934
935 DLLEXPORT FPDF_PAGERANGE STDCALL FPDF_VIEWERREF_GetPrintPageRange(FPDF_DOCUMENT document)
936 {
937         CPDF_Document* pDoc = ((CPDFXFA_Document*)document)->GetPDFDoc();
938     if (!pDoc) return NULL;
939     CPDF_ViewerPreferences viewRef(pDoc);
940     return viewRef.PrintPageRange();
941 }
942
943 DLLEXPORT FPDF_DUPLEXTYPE STDCALL FPDF_VIEWERREF_GetDuplex(FPDF_DOCUMENT document)
944 {
945         CPDF_Document* pDoc = ((CPDFXFA_Document*)document)->GetPDFDoc();
946     if (!pDoc) return DuplexUndefined;
947     CPDF_ViewerPreferences viewRef(pDoc);
948     CFX_ByteString duplex = viewRef.Duplex();
949     if (FX_BSTRC("Simplex") == duplex)
950         return Simplex;
951     if (FX_BSTRC("DuplexFlipShortEdge") == duplex)
952         return DuplexFlipShortEdge;
953     if (FX_BSTRC("DuplexFlipLongEdge") == duplex)
954         return DuplexFlipLongEdge;
955     return DuplexUndefined;
956 }
957
958 DLLEXPORT FPDF_DWORD STDCALL FPDF_CountNamedDests(FPDF_DOCUMENT document)
959 {
960     if (!document) return 0;
961         CPDF_Document* pDoc = ((CPDFXFA_Document*)document)->GetPDFDoc();
962
963     CPDF_Dictionary* pRoot = pDoc->GetRoot();
964     if (!pRoot) return 0;
965
966     CPDF_NameTree nameTree(pDoc, FX_BSTRC("Dests"));
967     int count = nameTree.GetCount();
968     CPDF_Dictionary* pDest = pRoot->GetDict(FX_BSTRC("Dests"));
969     if (pDest)
970         count += pDest->GetCount();
971     return count;
972 }
973
974 DLLEXPORT FPDF_DEST STDCALL FPDF_GetNamedDestByName(FPDF_DOCUMENT document,FPDF_BYTESTRING name)
975 {
976         if (!document)
977                 return NULL;
978         if (!name || name[0] == 0) 
979                 return NULL;
980
981         CPDFXFA_Document* pDoc = (CPDFXFA_Document*)document;
982         CPDF_Document* pPDFDoc = pDoc->GetPDFDoc();
983         if (!pPDFDoc) 
984                 return NULL;
985         CPDF_NameTree name_tree(pPDFDoc, FX_BSTRC("Dests"));
986         return name_tree.LookupNamedDest(pPDFDoc, name);
987 }
988
989 FPDF_RESULT     FPDF_BStr_Init(FPDF_BSTR* str)
990 {
991         if (!str)
992                 return -1;
993
994         FXSYS_memset32(str, 0, sizeof(FPDF_BSTR));
995         return 0;
996 }
997
998 FPDF_RESULT FPDF_BStr_Set(FPDF_BSTR* str, FPDF_LPCSTR bstr, int length)
999 {
1000         if (!str) return -1;
1001         if (!bstr || !length)
1002                 return -1;
1003         if (length == -1)
1004                 length = FXSYS_strlen(bstr);
1005
1006         if (length == 0)
1007         {
1008                 if (str->str)
1009                 {
1010                         FX_Free(str->str);
1011                         str->str = NULL;
1012                 }
1013                 str->len = 0;
1014                 return 0;
1015         }
1016
1017         if (str->str && str->len < length)
1018                 str->str = FX_Realloc(char, str->str, length+1);
1019         else if (!str->str)
1020                 str->str = FX_Alloc(char, length+1);
1021
1022         str->str[length] = 0;
1023         if (str->str == NULL)
1024                 return -1;
1025
1026         FXSYS_memcpy(str->str, bstr, length);
1027         str->len = length;
1028
1029         return 0;
1030 }
1031
1032 FPDF_RESULT     FPDF_BStr_Clear(FPDF_BSTR* str)
1033 {
1034         if(!str)
1035                 return -1;
1036
1037         if (str->str)
1038         {
1039                 FX_Free(str->str);
1040                 str->str = NULL;
1041         }
1042         str->len = 0;
1043         return 0;
1044 }
1045
1046 DLLEXPORT FPDF_DEST STDCALL FPDF_GetNamedDest(FPDF_DOCUMENT document, int index, void* buffer, long& buflen)
1047 {
1048     if (!buffer)
1049         buflen = 0;
1050     if (!document || index < 0) return NULL;
1051         CPDF_Document* pDoc = ((CPDFXFA_Document*)document)->GetPDFDoc();
1052
1053     CPDF_Dictionary* pRoot = pDoc->GetRoot();
1054     if (!pRoot) return NULL;
1055
1056     CPDF_Object* pDestObj = NULL;
1057     CFX_ByteString bsName;
1058     CPDF_NameTree nameTree(pDoc, FX_BSTRC("Dests"));
1059     int count = nameTree.GetCount();
1060     if (index >= count) {
1061         CPDF_Dictionary* pDest = pRoot->GetDict(FX_BSTRC("Dests"));
1062         if (!pDest) return NULL;
1063         if (index >= count + pDest->GetCount()) return NULL;
1064         index -= count;
1065         FX_POSITION pos = pDest->GetStartPos();
1066         int i = 0;
1067         while (pos) {
1068             pDestObj = pDest->GetNextElement(pos, bsName);
1069             if (!pDestObj) continue;
1070             if (i == index) break;
1071             i++;
1072         }
1073     } else {
1074         pDestObj = nameTree.LookupValue(index, bsName);
1075     }
1076     if (!pDestObj) return NULL;
1077     if (pDestObj->GetType() == PDFOBJ_DICTIONARY) {
1078         pDestObj = ((CPDF_Dictionary*)pDestObj)->GetArray(FX_BSTRC("D"));
1079         if (!pDestObj) return NULL;
1080     }
1081     if (pDestObj->GetType() != PDFOBJ_ARRAY) return NULL;
1082     CFX_WideString wsName = PDF_DecodeText(bsName);
1083     CFX_ByteString utf16Name = wsName.UTF16LE_Encode();
1084     unsigned int len = utf16Name.GetLength();
1085     if (!buffer) {
1086         buflen = len;
1087     } else if (buflen >= len) {
1088         memcpy(buffer, utf16Name.c_str(), len);
1089         buflen = len;
1090     } else {
1091         buflen = -1;
1092     }
1093     return (FPDF_DEST)pDestObj;
1094 }