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