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