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