Extern in .cpp files is a code smell.
[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(VALUE_NAME_STRING, wcslen(VALUE_NAME_STRING)));
64   ASSERT(JSCONST_nNumberHash ==
65          JS_CalcHash(VALUE_NAME_NUMBER, wcslen(VALUE_NAME_NUMBER)));
66   ASSERT(JSCONST_nBoolHash ==
67          JS_CalcHash(VALUE_NAME_BOOLEAN, wcslen(VALUE_NAME_BOOLEAN)));
68   ASSERT(JSCONST_nDateHash ==
69          JS_CalcHash(VALUE_NAME_DATE, wcslen(VALUE_NAME_DATE)));
70   ASSERT(JSCONST_nObjectHash ==
71          JS_CalcHash(VALUE_NAME_OBJECT, wcslen(VALUE_NAME_OBJECT)));
72   ASSERT(JSCONST_nFXobjHash ==
73          JS_CalcHash(VALUE_NAME_FXOBJ, wcslen(VALUE_NAME_FXOBJ)));
74   ASSERT(JSCONST_nNullHash ==
75          JS_CalcHash(VALUE_NAME_NULL, wcslen(VALUE_NAME_NULL)));
76   ASSERT(JSCONST_nUndefHash ==
77          JS_CalcHash(VALUE_NAME_UNDEFINED, wcslen(VALUE_NAME_UNDEFINED)));
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_pApp->GetRuntimeFactory()->ReleaseGlobalData();
112 }
113
114 void JSGlobalAlternate::Initial(CPDFDoc_Environment* pApp) {
115   m_pApp = pApp;
116   m_pGlobalData = pApp->GetRuntimeFactory()->NewGlobalData(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         JSObject 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, (JSFXObject)(*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, (JSFXObject)(*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, (JSFXObject)(*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         IJS_Runtime* pRuntime = JS_GetRuntime((JSFXObject)(*m_pJSObject));
271         v8::Local<v8::Object> pObj = JS_NewFxDynamicObj(pRuntime, NULL, -1);
272
273         PutObjectProperty(pObj, &pData->data);
274
275         SetGlobalVariables(pData->data.sKey, JS_GLOBALDATA_TYPE_OBJECT, 0,
276                            false, "", (JSObject)pObj, pData->bPersistent == 1);
277         JS_PutObjectObject(NULL, (JSFXObject)(*m_pJSObject),
278                            pData->data.sKey.UTF8Decode().c_str(),
279                            (JSObject)pObj);
280       } break;
281       case JS_GLOBALDATA_TYPE_NULL:
282         SetGlobalVariables(pData->data.sKey, JS_GLOBALDATA_TYPE_NULL, 0, false,
283                            "", v8::Local<v8::Object>(),
284                            pData->bPersistent == 1);
285         JS_PutObjectNull(NULL, (JSFXObject)(*m_pJSObject),
286                          pData->data.sKey.UTF8Decode().c_str());
287         break;
288     }
289   }
290 }
291
292 void JSGlobalAlternate::CommitGlobalPersisitentVariables() {
293   ASSERT(m_pGlobalData);
294   for (auto it = m_mapGlobal.begin(); it != m_mapGlobal.end(); ++it) {
295     CFX_ByteString name = it->first;
296     JSGlobalData* pData = it->second;
297     if (pData->bDeleted) {
298       m_pGlobalData->DeleteGlobalVariable(name);
299     } else {
300       switch (pData->nType) {
301         case JS_GLOBALDATA_TYPE_NUMBER:
302           m_pGlobalData->SetGlobalVariableNumber(name, pData->dData);
303           m_pGlobalData->SetGlobalVariablePersistent(name, pData->bPersistent);
304           break;
305         case JS_GLOBALDATA_TYPE_BOOLEAN:
306           m_pGlobalData->SetGlobalVariableBoolean(name, pData->bData);
307           m_pGlobalData->SetGlobalVariablePersistent(name, pData->bPersistent);
308           break;
309         case JS_GLOBALDATA_TYPE_STRING:
310           m_pGlobalData->SetGlobalVariableString(name, pData->sData);
311           m_pGlobalData->SetGlobalVariablePersistent(name, pData->bPersistent);
312           break;
313         case JS_GLOBALDATA_TYPE_OBJECT:
314           // if (pData->pData)
315           {
316             CJS_GlobalVariableArray array;
317             v8::Local<v8::Object> obj = v8::Local<v8::Object>::New(
318                 GetJSObject()->GetIsolate(), pData->pData);
319             ObjectToArray(obj, array);
320             m_pGlobalData->SetGlobalVariableObject(name, array);
321             m_pGlobalData->SetGlobalVariablePersistent(name,
322                                                        pData->bPersistent);
323           }
324           break;
325         case JS_GLOBALDATA_TYPE_NULL:
326           m_pGlobalData->SetGlobalVariableNull(name);
327           m_pGlobalData->SetGlobalVariablePersistent(name, pData->bPersistent);
328           break;
329       }
330     }
331   }
332 }
333
334 void JSGlobalAlternate::ObjectToArray(v8::Local<v8::Object> pObj,
335                                       CJS_GlobalVariableArray& array) {
336   v8::Local<v8::Context> context = pObj->CreationContext();
337   v8::Isolate* isolate = context->GetIsolate();
338   v8::Local<v8::Array> pKeyList = JS_GetObjectElementNames(isolate, pObj);
339   int nObjElements = pKeyList->Length();
340
341   for (int i = 0; i < nObjElements; i++) {
342     CFX_WideString ws =
343         JS_ToString(isolate, JS_GetArrayElement(isolate, pKeyList, i));
344     CFX_ByteString sKey = ws.UTF8Encode();
345
346     v8::Local<v8::Value> v = JS_GetObjectElement(isolate, pObj, ws.c_str());
347     FXJSVALUETYPE vt = GET_VALUE_TYPE(v);
348     switch (vt) {
349       case VT_number: {
350         CJS_KeyValue* pObjElement = new CJS_KeyValue;
351         pObjElement->nType = JS_GLOBALDATA_TYPE_NUMBER;
352         pObjElement->sKey = sKey;
353         pObjElement->dData = JS_ToNumber(isolate, v);
354         array.Add(pObjElement);
355       } break;
356       case VT_boolean: {
357         CJS_KeyValue* pObjElement = new CJS_KeyValue;
358         pObjElement->nType = JS_GLOBALDATA_TYPE_BOOLEAN;
359         pObjElement->sKey = sKey;
360         pObjElement->dData = JS_ToBoolean(isolate, v);
361         array.Add(pObjElement);
362       } break;
363       case VT_string: {
364         CFX_ByteString sValue =
365             CJS_Value(isolate, v, VT_string).ToCFXByteString();
366         CJS_KeyValue* pObjElement = new CJS_KeyValue;
367         pObjElement->nType = JS_GLOBALDATA_TYPE_STRING;
368         pObjElement->sKey = sKey;
369         pObjElement->sData = sValue;
370         array.Add(pObjElement);
371       } break;
372       case VT_object: {
373         CJS_KeyValue* pObjElement = new CJS_KeyValue;
374         pObjElement->nType = JS_GLOBALDATA_TYPE_OBJECT;
375         pObjElement->sKey = sKey;
376         ObjectToArray(JS_ToObject(isolate, v), pObjElement->objData);
377         array.Add(pObjElement);
378       } break;
379       case VT_null: {
380         CJS_KeyValue* pObjElement = new CJS_KeyValue;
381         pObjElement->nType = JS_GLOBALDATA_TYPE_NULL;
382         pObjElement->sKey = sKey;
383         array.Add(pObjElement);
384       } break;
385       default:
386         break;
387     }
388   }
389 }
390
391 void JSGlobalAlternate::PutObjectProperty(v8::Local<v8::Object> pObj,
392                                           CJS_KeyValue* pData) {
393   ASSERT(pData != NULL);
394
395   for (int i = 0, sz = pData->objData.Count(); i < sz; i++) {
396     CJS_KeyValue* pObjData = pData->objData.GetAt(i);
397     ASSERT(pObjData != NULL);
398
399     switch (pObjData->nType) {
400       case JS_GLOBALDATA_TYPE_NUMBER:
401         JS_PutObjectNumber(NULL, (JSObject)pObj,
402                            pObjData->sKey.UTF8Decode().c_str(),
403                            pObjData->dData);
404         break;
405       case JS_GLOBALDATA_TYPE_BOOLEAN:
406         JS_PutObjectBoolean(NULL, (JSObject)pObj,
407                             pObjData->sKey.UTF8Decode().c_str(),
408                             (bool)(pObjData->bData == 1));
409         break;
410       case JS_GLOBALDATA_TYPE_STRING:
411         JS_PutObjectString(NULL, (JSObject)pObj,
412                            pObjData->sKey.UTF8Decode().c_str(),
413                            pObjData->sData.UTF8Decode().c_str());
414         break;
415       case JS_GLOBALDATA_TYPE_OBJECT: {
416         IJS_Runtime* pRuntime = JS_GetRuntime((JSFXObject)(*m_pJSObject));
417         v8::Local<v8::Object> pNewObj = JS_NewFxDynamicObj(pRuntime, NULL, -1);
418         PutObjectProperty(pNewObj, pObjData);
419         JS_PutObjectObject(NULL, (JSObject)pObj,
420                            pObjData->sKey.UTF8Decode().c_str(),
421                            (JSObject)pNewObj);
422       } break;
423       case JS_GLOBALDATA_TYPE_NULL:
424         JS_PutObjectNull(NULL, (JSObject)pObj,
425                          pObjData->sKey.UTF8Decode().c_str());
426         break;
427     }
428   }
429 }
430
431 void JSGlobalAlternate::DestroyGlobalPersisitentVariables() {
432   for (const auto& pair : m_mapGlobal) {
433     delete pair.second;
434   }
435   m_mapGlobal.clear();
436 }
437
438 FX_BOOL JSGlobalAlternate::SetGlobalVariables(const FX_CHAR* propname,
439                                               int nType,
440                                               double dData,
441                                               bool bData,
442                                               const CFX_ByteString& sData,
443                                               JSObject pData,
444                                               bool bDefaultPersistent) {
445   if (!propname)
446     return FALSE;
447
448   auto it = m_mapGlobal.find(propname);
449   if (it != m_mapGlobal.end()) {
450     JSGlobalData* pTemp = it->second;
451     if (pTemp->bDeleted || pTemp->nType != nType) {
452       pTemp->dData = 0;
453       pTemp->bData = 0;
454       pTemp->sData = "";
455       pTemp->nType = nType;
456     }
457
458     pTemp->bDeleted = FALSE;
459     switch (nType) {
460       case JS_GLOBALDATA_TYPE_NUMBER: {
461         pTemp->dData = dData;
462       } break;
463       case JS_GLOBALDATA_TYPE_BOOLEAN: {
464         pTemp->bData = bData;
465       } break;
466       case JS_GLOBALDATA_TYPE_STRING: {
467         pTemp->sData = sData;
468       } break;
469       case JS_GLOBALDATA_TYPE_OBJECT: {
470         pTemp->pData.Reset(JS_GetRuntime(pData), pData);
471       } break;
472       case JS_GLOBALDATA_TYPE_NULL:
473         break;
474       default:
475         return FALSE;
476     }
477     return TRUE;
478   }
479
480   JSGlobalData* pNewData = NULL;
481
482   switch (nType) {
483     case JS_GLOBALDATA_TYPE_NUMBER: {
484       pNewData = new JSGlobalData;
485       pNewData->nType = JS_GLOBALDATA_TYPE_NUMBER;
486       pNewData->dData = dData;
487       pNewData->bPersistent = bDefaultPersistent;
488     } break;
489     case JS_GLOBALDATA_TYPE_BOOLEAN: {
490       pNewData = new JSGlobalData;
491       pNewData->nType = JS_GLOBALDATA_TYPE_BOOLEAN;
492       pNewData->bData = bData;
493       pNewData->bPersistent = bDefaultPersistent;
494     } break;
495     case JS_GLOBALDATA_TYPE_STRING: {
496       pNewData = new JSGlobalData;
497       pNewData->nType = JS_GLOBALDATA_TYPE_STRING;
498       pNewData->sData = sData;
499       pNewData->bPersistent = bDefaultPersistent;
500     } break;
501     case JS_GLOBALDATA_TYPE_OBJECT: {
502       pNewData = new JSGlobalData;
503       pNewData->nType = JS_GLOBALDATA_TYPE_OBJECT;
504       pNewData->pData.Reset(JS_GetRuntime(pData), pData);
505       pNewData->bPersistent = bDefaultPersistent;
506     } break;
507     case JS_GLOBALDATA_TYPE_NULL: {
508       pNewData = new JSGlobalData;
509       pNewData->nType = JS_GLOBALDATA_TYPE_NULL;
510       pNewData->bPersistent = bDefaultPersistent;
511     } break;
512     default:
513       return FALSE;
514   }
515
516   m_mapGlobal[propname] = pNewData;
517   return TRUE;
518 }
519
520 FXJSVALUETYPE GET_VALUE_TYPE(v8::Local<v8::Value> p) {
521   const unsigned int nHash = JS_CalcHash(JS_GetTypeof(p));
522
523   if (nHash == JSCONST_nUndefHash)
524     return VT_undefined;
525   if (nHash == JSCONST_nNullHash)
526     return VT_null;
527   if (nHash == JSCONST_nStringHash)
528     return VT_string;
529   if (nHash == JSCONST_nNumberHash)
530     return VT_number;
531   if (nHash == JSCONST_nBoolHash)
532     return VT_boolean;
533   if (nHash == JSCONST_nDateHash)
534     return VT_date;
535   if (nHash == JSCONST_nObjectHash)
536     return VT_object;
537   if (nHash == JSCONST_nFXobjHash)
538     return VT_fxobject;
539
540   return VT_unknown;
541 }