Clean up CPDF_AnnotList.
[pdfium.git] / fpdfsdk / src / javascript / global.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 "global.h"
8
9 #include "../../../core/include/fxcrt/fx_ext.h"
10 #include "../../include/javascript/IJavaScript.h"
11 #include "JS_Context.h"
12 #include "JS_Define.h"
13 #include "JS_EventHandler.h"
14 #include "JS_GlobalData.h"
15 #include "JS_Object.h"
16 #include "JS_Value.h"
17 #include "resource.h"
18
19 /* ---------------------------- global ---------------------------- */
20
21 // Helper class for compile-time calculation of hash values in order to
22 // avoid having global object initializers.
23 template <unsigned ACC, wchar_t... Ns>
24 struct CHash;
25
26 // Only needed to hash single-character strings.
27 template <wchar_t N>
28 struct CHash<N> {
29   static const unsigned value = N;
30 };
31
32 template <unsigned ACC, wchar_t N>
33 struct CHash<ACC, N> {
34   static const unsigned value = (ACC * 1313LLU + N) & 0xFFFFFFFF;
35 };
36
37 template <unsigned ACC, wchar_t N, wchar_t... Ns>
38 struct CHash<ACC, N, Ns...> {
39   static const unsigned value = CHash<CHash<ACC, N>::value, Ns...>::value;
40 };
41
42 const unsigned int JSCONST_nStringHash =
43     CHash<'s', 't', 'r', 'i', 'n', 'g'>::value;
44 const unsigned int JSCONST_nNumberHash =
45     CHash<'n', 'u', 'm', 'b', 'e', 'r'>::value;
46 const unsigned int JSCONST_nBoolHash =
47     CHash<'b', 'o', 'o', 'l', 'e', 'a', 'n'>::value;
48 const unsigned int JSCONST_nDateHash = CHash<'d', 'a', 't', 'e'>::value;
49 const unsigned int JSCONST_nObjectHash =
50     CHash<'o', 'b', 'j', 'e', 'c', 't'>::value;
51 const unsigned int JSCONST_nFXobjHash = CHash<'f', 'x', 'o', 'b', 'j'>::value;
52 const unsigned int JSCONST_nNullHash = CHash<'n', 'u', 'l', 'l'>::value;
53 const unsigned int JSCONST_nUndefHash =
54     CHash<'u', 'n', 'd', 'e', 'f', 'i', 'n', 'e', 'd'>::value;
55
56 static unsigned JS_CalcHash(const wchar_t* main) {
57   return (unsigned)FX_HashCode_String_GetW(main, FXSYS_wcslen(main));
58 }
59
60 #ifdef _DEBUG
61 class HashVerify {
62  public:
63   HashVerify();
64 } g_hashVerify;
65
66 HashVerify::HashVerify() {
67   ASSERT(JSCONST_nStringHash == JS_CalcHash(kFXJSValueNameString));
68   ASSERT(JSCONST_nNumberHash == JS_CalcHash(kFXJSValueNameNumber));
69   ASSERT(JSCONST_nBoolHash == JS_CalcHash(kFXJSValueNameBoolean));
70   ASSERT(JSCONST_nDateHash == JS_CalcHash(kFXJSValueNameDate));
71   ASSERT(JSCONST_nObjectHash == JS_CalcHash(kFXJSValueNameObject));
72   ASSERT(JSCONST_nFXobjHash == JS_CalcHash(kFXJSValueNameFxobj));
73   ASSERT(JSCONST_nNullHash == JS_CalcHash(kFXJSValueNameNull));
74   ASSERT(JSCONST_nUndefHash == JS_CalcHash(kFXJSValueNameUndefined));
75 }
76 #endif
77
78 BEGIN_JS_STATIC_CONST(CJS_Global)
79 END_JS_STATIC_CONST()
80
81 BEGIN_JS_STATIC_PROP(CJS_Global)
82 END_JS_STATIC_PROP()
83
84 BEGIN_JS_STATIC_METHOD(CJS_Global)
85 JS_STATIC_METHOD_ENTRY(setPersistent)
86 END_JS_STATIC_METHOD()
87
88 IMPLEMENT_SPECIAL_JS_CLASS(CJS_Global, JSGlobalAlternate, global);
89
90 void CJS_Global::InitInstance(IJS_Runtime* pIRuntime) {
91   CJS_Runtime* pRuntime = static_cast<CJS_Runtime*>(pIRuntime);
92   JSGlobalAlternate* pGlobal =
93       static_cast<JSGlobalAlternate*>(GetEmbedObject());
94   pGlobal->Initial(pRuntime->GetReaderApp());
95 }
96
97 JSGlobalAlternate::JSGlobalAlternate(CJS_Object* pJSObject)
98     : CJS_EmbedObj(pJSObject), m_pApp(NULL) {
99 }
100
101 JSGlobalAlternate::~JSGlobalAlternate() {
102   DestroyGlobalPersisitentVariables();
103   m_pGlobalData->Release();
104 }
105
106 void JSGlobalAlternate::Initial(CPDFDoc_Environment* pApp) {
107   m_pApp = pApp;
108   m_pGlobalData = CJS_GlobalData::GetRetainedInstance(pApp);
109   UpdateGlobalPersistentVariables();
110 }
111
112 FX_BOOL JSGlobalAlternate::QueryProperty(const FX_WCHAR* propname) {
113   return CFX_WideString(propname) != L"setPersistent";
114 }
115
116 FX_BOOL JSGlobalAlternate::DelProperty(IJS_Context* cc,
117                                        const FX_WCHAR* propname,
118                                        CFX_WideString& sError) {
119   auto it = m_mapGlobal.find(CFX_ByteString::FromUnicode(propname));
120   if (it == m_mapGlobal.end())
121     return FALSE;
122
123   it->second->bDeleted = TRUE;
124   return TRUE;
125 }
126
127 FX_BOOL JSGlobalAlternate::DoProperty(IJS_Context* cc,
128                                       const FX_WCHAR* propname,
129                                       CJS_PropValue& vp,
130                                       CFX_WideString& sError) {
131   if (vp.IsSetting()) {
132     CFX_ByteString sPropName = CFX_ByteString::FromUnicode(propname);
133     switch (vp.GetType()) {
134       case CJS_Value::VT_number: {
135         double dData;
136         vp >> dData;
137         return SetGlobalVariables(sPropName, JS_GLOBALDATA_TYPE_NUMBER, dData,
138                                   false, "", v8::Local<v8::Object>(), FALSE);
139       }
140       case CJS_Value::VT_boolean: {
141         bool bData;
142         vp >> bData;
143         return SetGlobalVariables(sPropName, JS_GLOBALDATA_TYPE_BOOLEAN, 0,
144                                   bData, "", v8::Local<v8::Object>(), FALSE);
145       }
146       case CJS_Value::VT_string: {
147         CFX_ByteString sData;
148         vp >> sData;
149         return SetGlobalVariables(sPropName, JS_GLOBALDATA_TYPE_STRING, 0,
150                                   false, sData, v8::Local<v8::Object>(), FALSE);
151       }
152       case CJS_Value::VT_object: {
153         v8::Local<v8::Object> pData;
154         vp >> pData;
155         return SetGlobalVariables(sPropName, JS_GLOBALDATA_TYPE_OBJECT, 0,
156                                   false, "", pData, FALSE);
157       }
158       case CJS_Value::VT_null: {
159         return SetGlobalVariables(sPropName, JS_GLOBALDATA_TYPE_NULL, 0, false,
160                                   "", v8::Local<v8::Object>(), FALSE);
161       }
162       case CJS_Value::VT_undefined: {
163         DelProperty(cc, propname, sError);
164         return TRUE;
165       }
166       default:
167         break;
168     }
169   } else {
170     auto it = m_mapGlobal.find(CFX_ByteString::FromUnicode(propname));
171     if (it == m_mapGlobal.end()) {
172       vp.SetNull();
173       return TRUE;
174     }
175     JSGlobalData* pData = it->second;
176     if (pData->bDeleted) {
177       vp.SetNull();
178       return TRUE;
179     }
180     switch (pData->nType) {
181       case JS_GLOBALDATA_TYPE_NUMBER:
182         vp << pData->dData;
183         return TRUE;
184       case JS_GLOBALDATA_TYPE_BOOLEAN:
185         vp << pData->bData;
186         return TRUE;
187       case JS_GLOBALDATA_TYPE_STRING:
188         vp << pData->sData;
189         return TRUE;
190       case JS_GLOBALDATA_TYPE_OBJECT: {
191         v8::Local<v8::Object> obj = v8::Local<v8::Object>::New(
192             vp.GetJSRuntime()->GetIsolate(), pData->pData);
193         vp << obj;
194         return TRUE;
195       }
196       case JS_GLOBALDATA_TYPE_NULL:
197         vp.SetNull();
198         return TRUE;
199       default:
200         break;
201     }
202   }
203   return FALSE;
204 }
205
206 FX_BOOL JSGlobalAlternate::setPersistent(IJS_Context* cc,
207                                          const CJS_Parameters& params,
208                                          CJS_Value& vRet,
209                                          CFX_WideString& sError) {
210   CJS_Context* pContext = static_cast<CJS_Context*>(cc);
211   if (params.size() != 2) {
212     sError = JSGetStringFromID(pContext, IDS_STRING_JSPARAMERROR);
213     return FALSE;
214   }
215
216   auto it = m_mapGlobal.find(params[0].ToCFXByteString());
217   if (it != m_mapGlobal.end()) {
218     JSGlobalData* pData = it->second;
219     if (!pData->bDeleted) {
220       pData->bPersistent = params[1].ToBool();
221       return TRUE;
222     }
223   }
224
225   sError = JSGetStringFromID(pContext, IDS_STRING_JSNOGLOBAL);
226   return FALSE;
227 }
228
229 void JSGlobalAlternate::UpdateGlobalPersistentVariables() {
230   ASSERT(m_pGlobalData != NULL);
231
232   for (int i = 0, sz = m_pGlobalData->GetSize(); i < sz; i++) {
233     CJS_GlobalData_Element* pData = m_pGlobalData->GetAt(i);
234     ASSERT(pData != NULL);
235
236     switch (pData->data.nType) {
237       case JS_GLOBALDATA_TYPE_NUMBER:
238         SetGlobalVariables(pData->data.sKey, JS_GLOBALDATA_TYPE_NUMBER,
239                            pData->data.dData, false, "",
240                            v8::Local<v8::Object>(), pData->bPersistent == 1);
241         FXJS_PutObjectNumber(NULL, m_pJSObject->ToV8Object(),
242                              pData->data.sKey.UTF8Decode().c_str(),
243                              pData->data.dData);
244         break;
245       case JS_GLOBALDATA_TYPE_BOOLEAN:
246         SetGlobalVariables(pData->data.sKey, JS_GLOBALDATA_TYPE_BOOLEAN, 0,
247                            (bool)(pData->data.bData == 1), "",
248                            v8::Local<v8::Object>(), pData->bPersistent == 1);
249         FXJS_PutObjectBoolean(NULL, m_pJSObject->ToV8Object(),
250                               pData->data.sKey.UTF8Decode().c_str(),
251                               (bool)(pData->data.bData == 1));
252         break;
253       case JS_GLOBALDATA_TYPE_STRING:
254         SetGlobalVariables(pData->data.sKey, JS_GLOBALDATA_TYPE_STRING, 0,
255                            false, pData->data.sData, v8::Local<v8::Object>(),
256                            pData->bPersistent == 1);
257         FXJS_PutObjectString(NULL, m_pJSObject->ToV8Object(),
258                              pData->data.sKey.UTF8Decode().c_str(),
259                              pData->data.sData.UTF8Decode().c_str());
260         break;
261       case JS_GLOBALDATA_TYPE_OBJECT: {
262         v8::Isolate* pRuntime = FXJS_GetRuntime(m_pJSObject->ToV8Object());
263         v8::Local<v8::Object> pObj = FXJS_NewFxDynamicObj(pRuntime, NULL, -1);
264
265         PutObjectProperty(pObj, &pData->data);
266
267         SetGlobalVariables(pData->data.sKey, JS_GLOBALDATA_TYPE_OBJECT, 0,
268                            false, "", pObj, pData->bPersistent == 1);
269         FXJS_PutObjectObject(NULL, m_pJSObject->ToV8Object(),
270                              pData->data.sKey.UTF8Decode().c_str(), pObj);
271
272       } break;
273       case JS_GLOBALDATA_TYPE_NULL:
274         SetGlobalVariables(pData->data.sKey, JS_GLOBALDATA_TYPE_NULL, 0, false,
275                            "", v8::Local<v8::Object>(),
276                            pData->bPersistent == 1);
277         FXJS_PutObjectNull(NULL, m_pJSObject->ToV8Object(),
278                            pData->data.sKey.UTF8Decode().c_str());
279         break;
280     }
281   }
282 }
283
284 void JSGlobalAlternate::CommitGlobalPersisitentVariables(IJS_Context* cc) {
285   for (auto it = m_mapGlobal.begin(); it != m_mapGlobal.end(); ++it) {
286     CFX_ByteString name = it->first;
287     JSGlobalData* pData = it->second;
288     if (pData->bDeleted) {
289       m_pGlobalData->DeleteGlobalVariable(name);
290     } else {
291       switch (pData->nType) {
292         case JS_GLOBALDATA_TYPE_NUMBER:
293           m_pGlobalData->SetGlobalVariableNumber(name, pData->dData);
294           m_pGlobalData->SetGlobalVariablePersistent(name, pData->bPersistent);
295           break;
296         case JS_GLOBALDATA_TYPE_BOOLEAN:
297           m_pGlobalData->SetGlobalVariableBoolean(name, pData->bData);
298           m_pGlobalData->SetGlobalVariablePersistent(name, pData->bPersistent);
299           break;
300         case JS_GLOBALDATA_TYPE_STRING:
301           m_pGlobalData->SetGlobalVariableString(name, pData->sData);
302           m_pGlobalData->SetGlobalVariablePersistent(name, pData->bPersistent);
303           break;
304         case JS_GLOBALDATA_TYPE_OBJECT:
305           {
306             CJS_GlobalVariableArray array;
307             v8::Local<v8::Object> obj = v8::Local<v8::Object>::New(
308                 GetJSObject()->GetIsolate(), pData->pData);
309             ObjectToArray(cc, obj, array);
310             m_pGlobalData->SetGlobalVariableObject(name, array);
311             m_pGlobalData->SetGlobalVariablePersistent(name,
312                                                        pData->bPersistent);
313           }
314           break;
315         case JS_GLOBALDATA_TYPE_NULL:
316           m_pGlobalData->SetGlobalVariableNull(name);
317           m_pGlobalData->SetGlobalVariablePersistent(name, pData->bPersistent);
318           break;
319       }
320     }
321   }
322 }
323
324 void JSGlobalAlternate::ObjectToArray(IJS_Context* cc,
325                                       v8::Local<v8::Object> pObj,
326                                       CJS_GlobalVariableArray& array) {
327   v8::Local<v8::Context> context = pObj->CreationContext();
328   v8::Isolate* isolate = context->GetIsolate();
329   CJS_Runtime* pRuntime = CJS_Runtime::FromContext(cc);
330
331   v8::Local<v8::Array> pKeyList = FXJS_GetObjectElementNames(isolate, pObj);
332   int nObjElements = pKeyList->Length();
333   for (int i = 0; i < nObjElements; i++) {
334     CFX_WideString ws =
335         FXJS_ToString(isolate, FXJS_GetArrayElement(isolate, pKeyList, i));
336     CFX_ByteString sKey = ws.UTF8Encode();
337
338     v8::Local<v8::Value> v = FXJS_GetObjectElement(isolate, pObj, ws.c_str());
339     switch (GET_VALUE_TYPE(v)) {
340       case CJS_Value::VT_number: {
341         CJS_KeyValue* pObjElement = new CJS_KeyValue;
342         pObjElement->nType = JS_GLOBALDATA_TYPE_NUMBER;
343         pObjElement->sKey = sKey;
344         pObjElement->dData = FXJS_ToNumber(isolate, v);
345         array.Add(pObjElement);
346       } break;
347       case CJS_Value::VT_boolean: {
348         CJS_KeyValue* pObjElement = new CJS_KeyValue;
349         pObjElement->nType = JS_GLOBALDATA_TYPE_BOOLEAN;
350         pObjElement->sKey = sKey;
351         pObjElement->dData = FXJS_ToBoolean(isolate, v);
352         array.Add(pObjElement);
353       } break;
354       case CJS_Value::VT_string: {
355         CFX_ByteString sValue =
356             CJS_Value(pRuntime, v, CJS_Value::VT_string).ToCFXByteString();
357         CJS_KeyValue* pObjElement = new CJS_KeyValue;
358         pObjElement->nType = JS_GLOBALDATA_TYPE_STRING;
359         pObjElement->sKey = sKey;
360         pObjElement->sData = sValue;
361         array.Add(pObjElement);
362       } break;
363       case CJS_Value::VT_object: {
364         CJS_KeyValue* pObjElement = new CJS_KeyValue;
365         pObjElement->nType = JS_GLOBALDATA_TYPE_OBJECT;
366         pObjElement->sKey = sKey;
367         ObjectToArray(cc, FXJS_ToObject(isolate, v), pObjElement->objData);
368         array.Add(pObjElement);
369       } break;
370       case CJS_Value::VT_null: {
371         CJS_KeyValue* pObjElement = new CJS_KeyValue;
372         pObjElement->nType = JS_GLOBALDATA_TYPE_NULL;
373         pObjElement->sKey = sKey;
374         array.Add(pObjElement);
375       } break;
376       default:
377         break;
378     }
379   }
380 }
381
382 void JSGlobalAlternate::PutObjectProperty(v8::Local<v8::Object> pObj,
383                                           CJS_KeyValue* pData) {
384   ASSERT(pData != NULL);
385
386   for (int i = 0, sz = pData->objData.Count(); i < sz; i++) {
387     CJS_KeyValue* pObjData = pData->objData.GetAt(i);
388     ASSERT(pObjData != NULL);
389
390     switch (pObjData->nType) {
391       case JS_GLOBALDATA_TYPE_NUMBER:
392         FXJS_PutObjectNumber(NULL, pObj, pObjData->sKey.UTF8Decode().c_str(),
393                              pObjData->dData);
394         break;
395       case JS_GLOBALDATA_TYPE_BOOLEAN:
396         FXJS_PutObjectBoolean(NULL, pObj, pObjData->sKey.UTF8Decode().c_str(),
397                               pObjData->bData == 1);
398         break;
399       case JS_GLOBALDATA_TYPE_STRING:
400         FXJS_PutObjectString(NULL, pObj, pObjData->sKey.UTF8Decode().c_str(),
401                              pObjData->sData.UTF8Decode().c_str());
402         break;
403       case JS_GLOBALDATA_TYPE_OBJECT: {
404         v8::Isolate* pRuntime = FXJS_GetRuntime(m_pJSObject->ToV8Object());
405         v8::Local<v8::Object> pNewObj =
406             FXJS_NewFxDynamicObj(pRuntime, NULL, -1);
407         PutObjectProperty(pNewObj, pObjData);
408         FXJS_PutObjectObject(NULL, pObj, pObjData->sKey.UTF8Decode().c_str(),
409                              pNewObj);
410       } break;
411       case JS_GLOBALDATA_TYPE_NULL:
412         FXJS_PutObjectNull(NULL, pObj, pObjData->sKey.UTF8Decode().c_str());
413         break;
414     }
415   }
416 }
417
418 void JSGlobalAlternate::DestroyGlobalPersisitentVariables() {
419   for (const auto& pair : m_mapGlobal) {
420     delete pair.second;
421   }
422   m_mapGlobal.clear();
423 }
424
425 FX_BOOL JSGlobalAlternate::SetGlobalVariables(const FX_CHAR* propname,
426                                               int nType,
427                                               double dData,
428                                               bool bData,
429                                               const CFX_ByteString& sData,
430                                               v8::Local<v8::Object> pData,
431                                               bool bDefaultPersistent) {
432   if (!propname)
433     return FALSE;
434
435   auto it = m_mapGlobal.find(propname);
436   if (it != m_mapGlobal.end()) {
437     JSGlobalData* pTemp = it->second;
438     if (pTemp->bDeleted || pTemp->nType != nType) {
439       pTemp->dData = 0;
440       pTemp->bData = 0;
441       pTemp->sData = "";
442       pTemp->nType = nType;
443     }
444
445     pTemp->bDeleted = FALSE;
446     switch (nType) {
447       case JS_GLOBALDATA_TYPE_NUMBER: {
448         pTemp->dData = dData;
449       } break;
450       case JS_GLOBALDATA_TYPE_BOOLEAN: {
451         pTemp->bData = bData;
452       } break;
453       case JS_GLOBALDATA_TYPE_STRING: {
454         pTemp->sData = sData;
455       } break;
456       case JS_GLOBALDATA_TYPE_OBJECT: {
457         pTemp->pData.Reset(FXJS_GetRuntime(pData), pData);
458       } break;
459       case JS_GLOBALDATA_TYPE_NULL:
460         break;
461       default:
462         return FALSE;
463     }
464     return TRUE;
465   }
466
467   JSGlobalData* pNewData = NULL;
468
469   switch (nType) {
470     case JS_GLOBALDATA_TYPE_NUMBER: {
471       pNewData = new JSGlobalData;
472       pNewData->nType = JS_GLOBALDATA_TYPE_NUMBER;
473       pNewData->dData = dData;
474       pNewData->bPersistent = bDefaultPersistent;
475     } break;
476     case JS_GLOBALDATA_TYPE_BOOLEAN: {
477       pNewData = new JSGlobalData;
478       pNewData->nType = JS_GLOBALDATA_TYPE_BOOLEAN;
479       pNewData->bData = bData;
480       pNewData->bPersistent = bDefaultPersistent;
481     } break;
482     case JS_GLOBALDATA_TYPE_STRING: {
483       pNewData = new JSGlobalData;
484       pNewData->nType = JS_GLOBALDATA_TYPE_STRING;
485       pNewData->sData = sData;
486       pNewData->bPersistent = bDefaultPersistent;
487     } break;
488     case JS_GLOBALDATA_TYPE_OBJECT: {
489       pNewData = new JSGlobalData;
490       pNewData->nType = JS_GLOBALDATA_TYPE_OBJECT;
491       pNewData->pData.Reset(FXJS_GetRuntime(pData), pData);
492       pNewData->bPersistent = bDefaultPersistent;
493     } break;
494     case JS_GLOBALDATA_TYPE_NULL: {
495       pNewData = new JSGlobalData;
496       pNewData->nType = JS_GLOBALDATA_TYPE_NULL;
497       pNewData->bPersistent = bDefaultPersistent;
498     } break;
499     default:
500       return FALSE;
501   }
502
503   m_mapGlobal[propname] = pNewData;
504   return TRUE;
505 }
506
507 CJS_Value::Type GET_VALUE_TYPE(v8::Local<v8::Value> p) {
508   const unsigned int nHash = JS_CalcHash(FXJS_GetTypeof(p));
509
510   if (nHash == JSCONST_nUndefHash)
511     return CJS_Value::VT_undefined;
512   if (nHash == JSCONST_nNullHash)
513     return CJS_Value::VT_null;
514   if (nHash == JSCONST_nStringHash)
515     return CJS_Value::VT_string;
516   if (nHash == JSCONST_nNumberHash)
517     return CJS_Value::VT_number;
518   if (nHash == JSCONST_nBoolHash)
519     return CJS_Value::VT_boolean;
520   if (nHash == JSCONST_nDateHash)
521     return CJS_Value::VT_date;
522   if (nHash == JSCONST_nObjectHash)
523     return CJS_Value::VT_object;
524   if (nHash == JSCONST_nFXobjHash)
525     return CJS_Value::VT_fxobject;
526
527   return CJS_Value::VT_unknown;
528 }