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