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