source: trunk/FACT++/src/InterpreterV8-4.cc@ 20115

Last change on this file since 20115 was 20090, checked in by tbretz, 4 years ago
ObjectTemplates can not hold non primitive values anymore, therefore implemented a workaround.
File size: 116.8 KB
Line 
1#include "InterpreterV8.h"
2
3#ifdef HAVE_V8
4
5#include <fstream>
6#include <sstream>
7#include <iomanip>
8
9#include <sys/stat.h>
10
11#include <boost/tokenizer.hpp>
12#include <boost/filesystem.hpp>
13#include <boost/algorithm/string/join.hpp>
14
15#ifdef HAVE_NOVA
16#include "nova.h"
17#endif
18
19#ifdef HAVE_SQL
20#include "Database.h"
21#endif
22
23#include <v8.h>
24#include <libplatform/libplatform.h>
25
26#include "dim.h"
27#include "tools.h"
28#include "Readline.h"
29#include "izstream.h"
30
31#include "WindowLog.h"
32
33using namespace std;
34using namespace v8;
35
36v8::Handle<v8::FunctionTemplate> InterpreterV8::fTemplateLocal;
37v8::Handle<v8::FunctionTemplate> InterpreterV8::fTemplateSky;
38v8::Handle<v8::FunctionTemplate> InterpreterV8::fTemplateEvent;
39v8::Handle<v8::FunctionTemplate> InterpreterV8::fTemplateDescription;
40//v8::Handle<v8::FunctionTemplate> InterpreterV8::fTemplateDatabase;
41
42
43// ==========================================================================
44// Some documentation
45// ==========================================================================
46//
47// Threads:
48// --------
49// In most cases Js* and other calls to native C++ code could be wrapped
50// with an Unlocker to allow possible other JavaScipt 'threads' to run
51// during that time. However, all of these calls should take much less than
52// the preemption time of 10ms, so it would just be a waste of tim.
53//
54// Termination:
55// ------------
56// Each thread running V8 code needs to be signalled individually for
57// termination. Therefor a list of V8 thread ids is created.
58//
59// If termination has already be signalled, no thread should start running
60// anymore (thy could, e.g., wait for their locking). So after locking
61// it has to be checked if the thread was terminated already. Note
62// that all calls to Terminate() must be locked to ensure that fThreadId
63// is correct when it is checked.
64//
65// The current thread id must be added to fThreadIds _before_ any
66// function is called after Locking and before execution is given
67// back to JavaScript, e.g. in script->Run(). So until the thread
68// is added to the list Terminate will not be executed. If Terminate
69// is then executed, it is ensured that the current thread is
70// already in the list. If terminate has been called before
71// the Locking, the check for the validiy of fThreadId ensures that
72// nothing is executed.
73//
74// Empty handles:
75// --------------
76// If exceution is terminated, V8 calls might return with empty handles,
77// e.g. Date::New(isolate). Therefore, the returned handles of these calls have to
78// be checked in all placed to avoid that V8 will core dump.
79//
80// HandleScope:
81// ------------
82// A handle scope is a garbage collector and collects all handles created
83// until it goes out of scope. Handles which are not needed anymore are
84// then deleted. To return a handle from a HandleScope you need to use
85// Close(). E.g., String::Utf8Value does not create a new handle and
86// hence does not need a HandleScope. Any ::New will need a handle scope.
87// Forgetting the HandleScope could in principle fill your memory,
88// but everything is properly deleted by the global HandleScope at
89// script termination.
90//
91// Here is another good reference for v8, also containing some
92// good explanations for the meaning of handles, persistent handles
93// and weak handles: http://create.tpsitulsa.com/wiki/V8_Cookbook
94//
95// ==========================================================================
96// Simple interface
97// ==========================================================================
98
99typedef FunctionCallbackInfo<Value> Arguments;
100
101void InterpreterV8::FuncExit(const Arguments &)
102{
103 fMainThread->TerminateExecution();
104
105 // we have to throw an excption to make sure that the
106 // calling thread does not go on executing until it
107 // has realized that it should terminate
108
109 //*NEw* FIXME: Which Thread???
110 Isolate* isolate = Isolate::GetCurrent();
111 isolate->ThrowException(Null(isolate));
112}
113
114void InterpreterV8::FuncSleep(const Arguments& args)
115{
116 Isolate* isolate = Isolate::GetCurrent();
117
118 if (args.Length()==0)
119 {
120 // Theoretically, the CPU usage can be reduced by maybe a factor
121 // of four using a larger value, but this also means that the
122 // JavaScript is locked for a longer time.
123 const Unlocker unlock(isolate);
124 usleep(1000);
125 return;
126 }
127
128 if (args.Length()!=1)
129 {
130 isolate->ThrowException(String::NewFromUtf8(isolate, "Number of arguments must be exactly 1."));
131 return;
132 }
133
134 if (!args[0]->IsUint32())
135 {
136 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 1 must be an uint32."));
137 return;
138 }
139
140 // Using a Javascript function has the advantage that it is fully
141 // interruptable without the need of C++ code
142 const string code =
143 "(function(){"
144 "var t=new Date();"
145 "while ((new Date()-t)<"+to_string(args[0]->Int32Value())+") v8.sleep();"
146 "})();";
147
148 args.GetReturnValue().Set(ExecuteInternal(code));
149}
150
151void InterpreterV8::FuncTimeout(const Arguments &args)
152{
153 Isolate* isolate = Isolate::GetCurrent();
154
155 if (args.Length()<2)
156 {
157 isolate->ThrowException(String::NewFromUtf8(isolate, "Number of arguments must be at least two."));
158 return;
159 }
160
161 if (!args[0]->IsNull() && !args[0]->IsInt32())
162 {
163 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 0 not null and not an int32."));
164 return;
165 }
166
167 if (!args[1]->IsFunction())
168 {
169 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 1 not a function."));
170 return;
171 }
172
173 if (args.Length()>2 && !args[2]->IsObject())
174 {
175 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 2 not an object."));
176 return;
177 }
178
179 const int32_t timeout = args[0]->IsNull() ? 0 : args[0]->Int32Value();
180 const bool null = args[0]->IsNull();
181
182 HandleScope handle_scope(isolate);
183
184 Handle<Function> func = Handle<Function>::Cast(args[1]);
185
186 const int nn = args.Length()==2 ? 0 : args.Length()-3;
187
188 vector<Handle<Value>> argv(nn);
189 for (int i=0; i<nn; i++)
190 argv[i] = args[i+3];
191
192 Time t;
193 while (1)
194 {
195 const Handle<Value> rc = args.Length()<3 ?
196 func->Call(func, nn, argv.data()) :
197 func->Call(args[2]->ToObject(), nn, argv.data());
198
199 if (rc.IsEmpty())
200 return;
201
202 if (!rc->IsUndefined())
203 {
204 args.GetReturnValue().Set(rc);
205 return;
206 }
207
208 if (!null && Time()-t>=boost::posix_time::milliseconds(abs(timeout)))
209 break;
210
211 // Theoretically, the CPU usage can be reduced by maybe a factor
212 // of four using a larger value, but this also means that the
213 // JavaScript is locked for a longer time.
214 const Unlocker unlock(isolate);
215 usleep(1000);
216 }
217
218 if (timeout<0)
219 return;
220
221 isolate->ThrowException(String::NewFromUtf8(isolate, "Waiting for func to return a defined value timed out."));
222}
223
224void InterpreterV8::Thread(v8::UniquePersistent<Object> &_this, v8::UniquePersistent<v8::Object> &func, uint32_t ms)
225{
226 Isolate *isolate = fMainThread;
227 if (!isolate)
228 return;
229
230 // We want to run as an interrupt in the main thread
231 const Locker locker(isolate);
232 if (!fMainThread)
233 return;
234
235 const Isolate::Scope isolate_scope(isolate);
236 const HandleScope handle_scope(isolate);
237
238 Handle<Object> fun = func.Get(isolate);
239 const Context::Scope scope(fun->CreationContext());
240
241 TryCatch exception(isolate);
242
243 fun->CreationContext()->Enter();
244
245 const bool rc = ms==0 || !ExecuteInternal("v8.sleep("+to_string(ms)+");").IsEmpty();
246 if (rc)
247 {
248 if (_this.IsEmpty())
249 Handle<Function>::Cast(fun)->Call(fun->CreationContext(), fun, 0, NULL).IsEmpty();
250 else
251 Handle<Function>::Cast(fun)->Call(fun->CreationContext(), _this.Get(isolate), 0, NULL).IsEmpty();
252 }
253
254 if (!HandleException(exception, "Thread"))
255 isolate->AddBeforeCallEnteredCallback(TerminateExecution);
256
257 fun->CreationContext()->Exit();
258}
259
260void InterpreterV8::FuncThread(const Arguments& args)
261{
262 Isolate *isolate = Isolate::GetCurrent();
263
264 if (!args.IsConstructCall())
265 {
266 isolate->ThrowException(String::NewFromUtf8(isolate, "Thread must be called as constructor."));
267 return;
268 }
269
270 if (args.Length()!=2 && args.Length()!=3)
271 {
272 isolate->ThrowException(String::NewFromUtf8(isolate, "Number of arguments must be two or three."));
273 return;
274 }
275
276
277 if (!args[0]->IsUint32())
278 {
279 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 0 not an uint32."));
280 return;
281 }
282
283
284 if (!args[1]->IsFunction())
285 {
286 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 1 not a function."));
287 return;
288 }
289
290 if (args.Length()==3 && !args[2]->IsObject())
291 {
292 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 2 not an object."));
293 return;
294 }
295
296 const HandleScope handle_scope(isolate);
297
298 UniquePersistent<Object> func = UniquePersistent<Object>(isolate, args[1]->ToObject());
299
300 UniquePersistent<Object> _this;
301 if (args.Length()==3)
302 _this = UniquePersistent<Object>(isolate, args[2]->ToObject());
303
304 const uint32_t ms = args[0]->Uint32Value();
305
306 //int id=__id;
307 fThreads.push_back(thread(bind(&InterpreterV8::Thread, this, /*ref(id),*/ std::move(_this), std::move(func), ms)));
308 /*
309 {
310 // Allow the thread to lock, so we can get the thread id.
311 const Unlocker unlock(isolate);
312 while (id==-2)
313 usleep(1);
314 }
315
316 Handle<Object> self = args.This();
317 self->Set(String::NewFromUtf8(isolate, "id"), Integer::NewFromUnsigned(isolate, id));
318 self->Set(String::NewFromUtf8(isolate, "kill"), FunctionTemplate::New(isolate, WrapKill)->GetFunction());
319 args.GetReturnValue().Set(self);
320 */
321}
322
323void InterpreterV8::FuncKill(const Arguments& args)
324{
325 /*
326 Isolate *isolate = Isolate::GetCurrent();
327
328 const uint32_t id = args.This()->Get(String::NewFromUtf8(isolate, "id"))->Uint32Value();
329
330 V8::TerminateExecution(id);
331
332 // DISPOSE?
333
334 return Boolean::New(fThreadIds.erase(id));
335 */
336}
337
338void InterpreterV8::FuncSend(const Arguments& args)
339{
340 Isolate *isolate = Isolate::GetCurrent();
341
342 if (args.Length()==0)
343 {
344 isolate->ThrowException(String::NewFromUtf8(isolate, "Number of arguments must be at least 1."));
345 return;
346 }
347
348 if (!args[0]->IsString())
349 {
350 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 1 must be a string."));
351 return;
352 }
353
354 string command = *String::Utf8Value(args[0]);
355
356 if (command.length()==0)
357 {
358 isolate->ThrowException(String::NewFromUtf8(isolate, "Server name empty."));
359 return;
360 }
361
362 if (args.Length()==0)
363 {
364 if (command.find_first_of('/')==string::npos)
365 command += "/";
366 }
367
368 // Escape all string arguments. All others can be kept as they are.
369 for (int i=1; i<args.Length(); i++)
370 {
371 string arg = *String::Utf8Value(args[i]);
372
373 // Escape string
374 if (args[i]->IsString())
375 {
376 boost::replace_all(arg, "\\", "\\\\");
377 boost::replace_all(arg, "'", "\\'");
378 boost::replace_all(arg, "\"", "\\\"");
379 }
380
381 command += " "+arg;
382 }
383
384 try
385 {
386 args.GetReturnValue().Set(JsSend(command));
387 }
388 catch (const runtime_error &e)
389 {
390 isolate->ThrowException(String::NewFromUtf8(isolate, e.what()));
391 }
392}
393
394// ==========================================================================
395// State control
396// ==========================================================================
397
398void InterpreterV8::FuncWait(const Arguments& args)
399{
400 Isolate *isolate = Isolate::GetCurrent();
401
402 if (args.Length()!=2 && args.Length()!=3)
403 {
404 isolate->ThrowException(String::NewFromUtf8(isolate, "Number of arguments must be 2 or 3."));
405 return;
406 }
407
408 if (!args[0]->IsString())
409 {
410 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 1 not a string."));
411 return;
412 }
413
414 if (!args[1]->IsInt32() && !args[1]->IsString())
415 {
416 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 2 not an int32 and not a string."));
417 return;
418 }
419
420 if (args.Length()==3 && !args[2]->IsInt32() && !args[2]->IsUndefined())
421 {
422 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 3 not an int32 and not undefined."));
423 return;
424 }
425
426 // Using a Javascript function has the advantage that it is fully
427 // interruptable without the need of C++ code
428
429 const string index = args[1]->IsInt32() ? "s.index" : "s.name";
430 const bool timeout = args.Length()==3 && !args[2]->IsUndefined();
431 const string arg0 = *String::Utf8Value(args[0]);
432 const string state = args[1]->IsString() ? *String::Utf8Value(args[1]) : "";
433 const string arg1 = args[1]->IsString() ? ("\""+state+"\"") : to_string(args[1]->Int32Value());
434 const bool isNot = arg0[0]=='!';
435 const string name = isNot ? arg0.substr(1) : arg0;
436
437 if (arg0.find_first_of("\"'")!=string::npos)
438 {
439 isolate->ThrowException(String::NewFromUtf8(isolate, "Server name must not contain quotation marks."));
440 return;
441 }
442
443 if (args[1]->IsString())
444 if (state.find_first_of("\"'")!=string::npos)
445 {
446 isolate->ThrowException(String::NewFromUtf8(isolate, "State name must not contain quotation marks."));
447 return;
448 }
449
450 string code = "(function(name,state,ms)"
451 "{";
452 if (timeout)
453 code += "var t = new Date();";
454 code += "var s;"
455 "while (1)"
456 "{"
457 "s = dim.state(name);"
458 "if(!s)throw new Error('Waiting for state "+arg1+" of server "+arg0+" failed.');";
459 if (isNot)
460 code +=
461 "if(state!="+index+")return true;";
462 else
463 code +=
464 "if(state=="+index+")return true;";
465 if (timeout)
466 code += "if((new Date()-t)>Math.abs(ms))break;";
467
468 code += "v8.sleep();"
469 "}";
470 if (timeout)
471 code += "if(ms>0)throw new Error('Waiting for state "+arg1+" of server "+arg0+" ['+"+index+"+'] timed out.');";
472 code += "return false;"
473 "})('"+name+"',"+arg1;
474 if (timeout)
475 code += "," + (args[2]->IsUndefined()?"undefined":to_string(args[2]->Int32Value()));
476 code += ");";
477
478 args.GetReturnValue().Set(ExecuteInternal(code));
479}
480
481void InterpreterV8::GetterCallback(Local< Name > name, const PropertyCallbackInfo< Value > &info)
482{
483 //const string server = *String::Utf8Value(name);
484 info.GetReturnValue().Set(info.Data());
485}
486
487
488void InterpreterV8::SetProperty(Handle<ObjectTemplate> &obj, const char *name, const Local<Value> &val)
489{
490 // My answer on: https://bugs.chromium.org/p/v8/issues/detail?id=4997
491 obj->SetNativeDataProperty(String::NewFromUtf8(Isolate::GetCurrent(), name),
492 GetterCallback,
493 nullptr,
494 val,
495 ReadOnly,
496 Local<AccessorSignature>(),
497 ALL_CAN_READ);
498}
499
500
501void InterpreterV8::FuncState(const Arguments& args)
502{
503 Isolate *isolate = Isolate::GetCurrent();
504
505 if (args.Length()!=1)
506 {
507 isolate->ThrowException(String::NewFromUtf8(isolate, "Number of arguments must be exactly 1."));
508 return;
509 }
510
511 if (!args[0]->IsString())
512 {
513 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 1 must be a string."));
514 return;
515 }
516
517 // Return state.name/state.index
518
519 const String::Utf8Value str(args[0]);
520
521 const State rc = JsState(*str);
522 if (rc.index<=-256)
523 return;
524
525 const HandleScope handle_scope(isolate);
526
527 Handle<ObjectTemplate> obj = ObjectTemplate::New(isolate);
528 if (obj.IsEmpty())
529 return;
530
531 obj->Set(String::NewFromUtf8(isolate, "server"), String::NewFromUtf8(isolate, *str), ReadOnly);
532 obj->Set(String::NewFromUtf8(isolate, "index"), Integer::New(isolate, rc.index), ReadOnly);
533 obj->Set(String::NewFromUtf8(isolate, "name"), String::NewFromUtf8(isolate, rc.name.c_str()), ReadOnly);
534
535 MaybeLocal<Value> date = Date::New(isolate->GetCurrentContext(), rc.time.JavaDate());
536 if (rc.index>-256 && !date.IsEmpty())
537 SetProperty(obj, "time", date.ToLocalChecked());
538
539 args.GetReturnValue().Set(obj->NewInstance());
540}
541
542void InterpreterV8::FuncNewState(const Arguments& args)
543{
544 Isolate *isolate = Isolate::GetCurrent();
545
546 if (args.Length()<1 || args.Length()>3)
547 {
548 isolate->ThrowException(String::NewFromUtf8(isolate, "Number of arguments must be 1, 2 or 3."));
549 return;
550 }
551
552 if (!args[0]->IsUint32())
553 {
554 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 1 must be an uint32."));
555 return;
556 }
557 if (args.Length()>1 && !args[1]->IsString())
558 {
559 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 2 must be a string."));
560 return;
561 }
562 if (args.Length()>2 && !args[2]->IsString())
563 {
564 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 3 must be a string."));
565 return;
566 }
567
568 const uint32_t index = args[0]->Int32Value();
569 const string name = *String::Utf8Value(args[1]);
570 const string comment = *String::Utf8Value(args[2]);
571
572 if (index<10 || index>255)
573 {
574 isolate->ThrowException(String::NewFromUtf8(isolate, "State must be in the range [10, 255]."));
575 return;
576 }
577
578 if (name.empty())
579 {
580 isolate->ThrowException(String::NewFromUtf8(isolate, "State name must not be empty."));
581 return;
582 }
583
584 if (name.find_first_of(':')!=string::npos || name.find_first_of('=')!=string::npos)
585 {
586 isolate->ThrowException(String::NewFromUtf8(isolate, "State name must not contain : or =."));
587 return;
588 }
589
590 struct Find : State
591 {
592 Find(int idx, const string &n) : State(idx, n) { }
593 bool operator()(const pair<int, string> &p) { return index==p.first || name==p.second; }
594 };
595
596 if (find_if(fStates.begin(), fStates.end(), Find(index, name))!=fStates.end())
597 {
598 const string what =
599 "State index ["+to_string(index)+"] or name ["+name+"] already defined.";
600
601 isolate->ThrowException(String::NewFromUtf8(isolate, what.c_str()));
602 return;
603 }
604
605 args.GetReturnValue().Set(JsNewState(index, name, comment));
606}
607
608void InterpreterV8::FuncSetState(const Arguments& args)
609{
610 Isolate *isolate = Isolate::GetCurrent();
611
612 if (args.Length()!=1)
613 {
614 isolate->ThrowException(String::NewFromUtf8(isolate, "Number of arguments must be exactly 1."));
615 return;
616 }
617
618 if (!args[0]->IsUint32() && !args[0]->IsString())
619 {
620 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument must be an uint32 or a string."));
621 return;
622 }
623
624 int index = -2;
625 if (args[0]->IsUint32())
626 {
627 index = args[0]->Int32Value();
628 }
629 else
630 {
631 const string name = *String::Utf8Value(args[0]);
632 index = JsGetState(name);
633 if (index==-2)
634 {
635 isolate->ThrowException(String::NewFromUtf8(isolate, ("State '"+name+"' not found.").c_str()));
636 return;
637 }
638 }
639
640 if (index<10 || index>255)
641 {
642 isolate->ThrowException(String::NewFromUtf8(isolate, "State must be in the range [10, 255]."));
643 return;
644 }
645
646 args.GetReturnValue().Set(JsSetState(index));
647}
648
649void InterpreterV8::FuncGetState(const Arguments& args)
650{
651 Isolate *isolate = Isolate::GetCurrent();
652
653 if (args.Length()>0)
654 {
655 isolate->ThrowException(String::NewFromUtf8(isolate, "getState must not take arguments."));
656 return;
657 }
658
659 const State state = JsGetCurrentState();
660
661 const HandleScope handle_scope(isolate);
662
663 Handle<ObjectTemplate> obj = ObjectTemplate::New(isolate);
664 if (obj.IsEmpty())
665 return;
666
667 obj->Set(String::NewFromUtf8(isolate, "index"), Integer::New(isolate, state.index), ReadOnly);
668 obj->Set(String::NewFromUtf8(isolate, "name"), String::NewFromUtf8(isolate, state.name.c_str()), ReadOnly);
669 obj->Set(String::NewFromUtf8(isolate, "description"), String::NewFromUtf8(isolate, state.comment.c_str()), ReadOnly);
670
671 args.GetReturnValue().Set(obj->NewInstance());
672}
673
674void InterpreterV8::FuncGetStates(const Arguments& args)
675{
676 Isolate *isolate = Isolate::GetCurrent();
677
678 if (args.Length()>1)
679 {
680 isolate->ThrowException(String::NewFromUtf8(isolate, "getStates must not take more than one arguments."));
681 return;
682 }
683
684 if (args.Length()==1 && !args[0]->IsString())
685 {
686 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument must be a string."));
687 return;
688 }
689
690 const string server = args.Length()==1 ? *String::Utf8Value(args[0]) : "DIM_CONTROL";
691
692 const vector<State> states = JsGetStates(server);
693
694 const HandleScope handle_scope(isolate);
695
696 Handle<Object> obj = Object::New(isolate);
697 if (obj.IsEmpty())
698 return;
699
700 for (auto it=states.begin(); it!=states.end(); it++)
701 {
702 Handle<Value> entry = StringObject::New(String::NewFromUtf8(isolate, it->name.c_str()));
703 if (entry.IsEmpty())
704 return;
705
706 StringObject::Cast(*entry)->Set(String::NewFromUtf8(isolate, "description"), String::NewFromUtf8(isolate, it->comment.c_str())/*, ReadOnly*/);
707 obj->Set(Integer::New(isolate, it->index), entry/*, ReadOnly*/);
708 }
709
710 args.GetReturnValue().Set(obj);
711}
712
713void InterpreterV8::FuncGetDescription(const Arguments& args)
714{
715 Isolate *isolate = Isolate::GetCurrent();
716
717 if (args.Length()!=1)
718 {
719 isolate->ThrowException(String::NewFromUtf8(isolate, "getDescription must take exactly one argument."));
720 return;
721 }
722
723 if (args.Length()==1 && !args[0]->IsString())
724 {
725 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument must be a string."));
726 return;
727 }
728
729 const string service = *String::Utf8Value(args[0]);
730
731 const vector<Description> descriptions = JsGetDescription(service);
732 const set<Service> services = JsGetServices();
733
734 auto is=services.begin();
735 for (; is!=services.end(); is++)
736 if (is->name==service)
737 break;
738
739 if (is==services.end())
740 return;
741
742 const HandleScope handle_scope(isolate);
743
744 Local<Context> context = isolate->GetCurrentContext();
745 MaybeLocal<Object> marr = fTemplateDescription->GetFunction()->NewInstance(context);
746 if (marr.IsEmpty())
747 return;
748
749 Local<Object> arr = marr.ToLocalChecked();
750
751 auto it=descriptions.begin();
752 arr->Set(String::NewFromUtf8(isolate, "name"), String::NewFromUtf8(isolate, it->name.c_str())/*, ReadOnly*/);
753 if (!it->comment.empty())
754 arr->Set(String::NewFromUtf8(isolate, "description"), String::NewFromUtf8(isolate, it->comment.c_str())/*, ReadOnly*/);
755 if (is!=services.end())
756 {
757 arr->Set(String::NewFromUtf8(isolate, "server"), String::NewFromUtf8(isolate, is->server.c_str())/*, ReadOnly*/);
758 arr->Set(String::NewFromUtf8(isolate, "service"), String::NewFromUtf8(isolate, is->service.c_str())/*, ReadOnly*/);
759 arr->Set(String::NewFromUtf8(isolate, "isCommand"), Boolean::New(isolate, is->iscmd)/*, ReadOnly*/);
760 if (!is->format.empty())
761 arr->Set(String::NewFromUtf8(isolate, "format"), String::NewFromUtf8(isolate, is->format.c_str())/*, ReadOnly*/);
762 }
763
764 uint32_t i=0;
765 for (it++; it!=descriptions.end(); it++)
766 {
767 Handle<Object> obj = Object::New(isolate);
768 if (obj.IsEmpty())
769 return;
770
771 if (!it->name.empty())
772 obj->Set(String::NewFromUtf8(isolate, "name"), String::NewFromUtf8(isolate, it->name.c_str())/*, ReadOnly*/);
773 if (!it->comment.empty())
774 obj->Set(String::NewFromUtf8(isolate, "description"), String::NewFromUtf8(isolate, it->comment.c_str())/*, ReadOnly*/);
775 if (!it->unit.empty())
776 obj->Set(String::NewFromUtf8(isolate, "unit"), String::NewFromUtf8(isolate, it->unit.c_str())/*, ReadOnly*/);
777
778 arr->Set(i++, obj);
779 }
780
781 args.GetReturnValue().Set(arr);
782}
783
784void InterpreterV8::FuncGetServices(const Arguments& args)
785{
786 Isolate *isolate = Isolate::GetCurrent();
787
788 if (args.Length()>2)
789 {
790 isolate->ThrowException(String::NewFromUtf8(isolate, "getServices must not take more than two argument."));
791 return;
792 }
793
794 if (args.Length()>=1 && !args[0]->IsString())
795 {
796 isolate->ThrowException(String::NewFromUtf8(isolate, "First argument must be a string."));
797 return;
798 }
799
800 if (args.Length()==2 && !args[1]->IsBoolean())
801 {
802 isolate->ThrowException(String::NewFromUtf8(isolate, "Second argument must be a boolean."));
803 return;
804 }
805
806 string arg0 = args.Length() ? *String::Utf8Value(args[0]) : "";
807 if (arg0=="*")
808 arg0="";
809
810 const set<Service> services = JsGetServices();
811
812 const HandleScope handle_scope(isolate);
813
814 Handle<Array> arr = Array::New(isolate);
815 if (arr.IsEmpty())
816 return;
817
818 uint32_t i=0;
819 for (auto is=services.begin(); is!=services.end(); is++)
820 {
821 if (!arg0.empty() && is->name.find(arg0)!=0)
822 continue;
823
824 if (args.Length()==2 && args[1]->BooleanValue()!=is->iscmd)
825 continue;
826
827 Handle<Object> obj = Object::New(isolate);
828 if (obj.IsEmpty())
829 return;
830
831 obj->Set(String::NewFromUtf8(isolate, "name"), String::NewFromUtf8(isolate, is->name.c_str())/*, ReadOnly*/);
832 obj->Set(String::NewFromUtf8(isolate, "server"), String::NewFromUtf8(isolate, is->server.c_str())/*, ReadOnly*/);
833 obj->Set(String::NewFromUtf8(isolate, "service"), String::NewFromUtf8(isolate, is->service.c_str())/*, ReadOnly*/);
834 obj->Set(String::NewFromUtf8(isolate, "isCommand"), Boolean::New(isolate, is->iscmd)/*, ReadOnly*/);
835 if (!is->format.empty())
836 obj->Set(String::NewFromUtf8(isolate, "format"), String::NewFromUtf8(isolate, is->format.c_str())/*, ReadOnly*/);
837
838 arr->Set(i++, obj);
839 }
840
841 args.GetReturnValue().Set(arr);
842}
843
844// ==========================================================================
845// Internal functions
846// ==========================================================================
847
848
849// The callback that is invoked by v8 whenever the JavaScript 'print'
850// function is called. Prints its arguments on stdout separated by
851// spaces and ending with a newline.
852void InterpreterV8::FuncLog(const Arguments& args)
853{
854 for (int i=0; i<args.Length(); i++)
855 {
856 const String::Utf8Value str(args[i]);
857 if (*str)
858 JsPrint(*str);
859 }
860
861 if (args.Length()==0)
862 JsPrint();
863}
864
865void InterpreterV8::FuncAlarm(const Arguments& args)
866{
867 for (int i=0; i<args.Length(); i++)
868 {
869 const String::Utf8Value str(args[i]);
870 if (*str)
871 JsAlarm(*str);
872 }
873
874 if (args.Length()==0)
875 JsAlarm();
876}
877
878void InterpreterV8::FuncOut(const Arguments& args)
879{
880 for (int i=0; i<args.Length(); i++)
881 {
882 const String::Utf8Value str(args[i]);
883 if (*str)
884 JsOut(*str);
885 }
886}
887
888void InterpreterV8::FuncWarn(const Arguments& args)
889{
890 for (int i=0; i<args.Length(); i++)
891 {
892 const String::Utf8Value str(args[i]);
893 if (*str)
894 JsWarn(*str);
895 }
896}
897
898// The callback that is invoked by v8 whenever the JavaScript 'load'
899// function is called. Loads, compiles and executes its argument
900// JavaScript file.
901void InterpreterV8::FuncInclude(const Arguments& args)
902{
903 Isolate *isolate = Isolate::GetCurrent();
904
905 if (args.Length()!=1)
906 {
907 isolate->ThrowException(String::NewFromUtf8(isolate, "Number of arguments must be one."));
908 return;
909 }
910 if (!args[0]->IsString())
911 {
912 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument must be a string."));
913 return;
914 }
915
916 const String::Utf8Value file(args[0]);
917 if (*file == NULL)
918 {
919 isolate->ThrowException(String::NewFromUtf8(isolate, "File name missing."));
920 return;
921 }
922
923 if (strlen(*file)==0)
924 {
925 isolate->ThrowException(String::NewFromUtf8(isolate, "File name empty."));
926 return;
927 }
928
929 const auto path = boost::filesystem::path(*file);
930
931 const auto f = path.is_absolute() ? path : boost::filesystem::path(fIncludePath)/path;
932
933 izstream fin(*file);//f.string().c_str());
934 if (!fin)
935 {
936 isolate->ThrowException(String::NewFromUtf8(isolate, errno!=0?strerror(errno):"Insufficient memory for decompression"));
937 return;
938 }
939
940 string buffer;
941 getline(fin, buffer, '\0');
942
943 if ((fin.fail() && !fin.eof()) || fin.bad())
944 {
945 isolate->ThrowException(String::NewFromUtf8(isolate, strerror(errno)));
946 return;
947 }
948
949 if (buffer.length()>1 && buffer[0]=='#' && buffer[1]=='!')
950 buffer.insert(0, "//");
951
952 args.GetReturnValue().Set(ExecuteCode(buffer, *file));
953}
954
955void InterpreterV8::FuncFile(const Arguments& args)
956{
957 Isolate *isolate = Isolate::GetCurrent();
958
959 if (args.Length()!=1 && args.Length()!=2)
960 {
961 isolate->ThrowException(String::NewFromUtf8(isolate, "Number of arguments must be one or two."));
962 return;
963 }
964
965 const String::Utf8Value file(args[0]);
966 if (*file == NULL)
967 {
968 isolate->ThrowException(String::NewFromUtf8(isolate, "File name missing"));
969 return;
970 }
971
972 if (args.Length()==2 && !args[1]->IsString())
973 {
974 isolate->ThrowException(String::NewFromUtf8(isolate, "Second argument must be a string."));
975 return;
976 }
977
978 const string delim = args.Length()==2 ? *String::Utf8Value(args[1]) : "";
979
980 if (args.Length()==2 && delim.size()!=1)
981 {
982 isolate->ThrowException(String::NewFromUtf8(isolate, "Second argument must be a string of length 1."));
983 return;
984 }
985
986 const HandleScope handle_scope(isolate);
987
988 const auto path = boost::filesystem::path(*file);
989
990 const auto f = path.is_absolute() ? path : boost::filesystem::path(fIncludePath)/path;
991
992 izstream fin(*file);//f.string().c_str());
993 if (!fin)
994 {
995 isolate->ThrowException(String::NewFromUtf8(isolate, errno!=0?strerror(errno):"Insufficient memory for decompression"));
996 return;
997 }
998
999 if (args.Length()==1)
1000 {
1001 string buffer;
1002 getline(fin, buffer, '\0');
1003 if ((fin.fail() && !fin.eof()) || fin.bad())
1004 {
1005 isolate->ThrowException(String::NewFromUtf8(isolate, strerror(errno)));
1006 return;
1007 }
1008
1009 Handle<Value> str = StringObject::New(String::NewFromUtf8(isolate, buffer.c_str()));
1010 StringObject::Cast(*str)->Set(String::NewFromUtf8(isolate, "name"), String::NewFromUtf8(isolate, *file));
1011 args.GetReturnValue().Set(str);
1012 return;
1013 }
1014
1015 Handle<Array> arr = Array::New(isolate);
1016 if (arr.IsEmpty())
1017 return;
1018
1019 int i=0;
1020 string buffer;
1021 while (getline(fin, buffer, delim[0]))
1022 arr->Set(i++, String::NewFromUtf8(isolate, buffer.c_str()));
1023
1024 if ((fin.fail() && !fin.eof()) || fin.bad())
1025 {
1026 isolate->ThrowException(String::NewFromUtf8(isolate, strerror(errno)));
1027 return;
1028 }
1029
1030 arr->Set(String::NewFromUtf8(isolate, "name"), String::NewFromUtf8(isolate, *file));
1031 arr->Set(String::NewFromUtf8(isolate, "delim"), String::NewFromUtf8(isolate, delim.c_str(), NewStringType::kNormal, 1).ToLocalChecked());
1032
1033 args.GetReturnValue().Set(arr);
1034}
1035
1036// ==========================================================================
1037// Mail
1038// ==========================================================================
1039
1040void InterpreterV8::ConstructorMail(const Arguments &args)
1041{
1042 Isolate *isolate = Isolate::GetCurrent();
1043
1044 if (!args.IsConstructCall())
1045 {
1046 isolate->ThrowException(String::NewFromUtf8(isolate, "Mail must be called as constructor"));
1047 return;
1048 }
1049
1050 if (args.Length()!=1 || !args[0]->IsString())
1051 {
1052 isolate->ThrowException(String::NewFromUtf8(isolate, "Constructor must be called with a single string as argument"));
1053 return;
1054 }
1055
1056 const HandleScope handle_scope(isolate);
1057
1058 Handle<Array> rec = Array::New(isolate);
1059 Handle<Array> att = Array::New(isolate);
1060 Handle<Array> bcc = Array::New(isolate);
1061 Handle<Array> cc = Array::New(isolate);
1062 Handle<Array> txt = Array::New(isolate);
1063 if (rec.IsEmpty() || att.IsEmpty() || bcc.IsEmpty() || cc.IsEmpty() || txt.IsEmpty())
1064 return;
1065
1066 Handle<Object> self = args.This();
1067
1068 self->Set(String::NewFromUtf8(isolate, "subject"), args[0]->ToString()/*, ReadOnly*/);
1069 self->Set(String::NewFromUtf8(isolate, "recipients"), rec/*, ReadOnly*/);
1070 self->Set(String::NewFromUtf8(isolate, "attachments"), att/*, ReadOnly*/);
1071 self->Set(String::NewFromUtf8(isolate, "bcc"), bcc/*, ReadOnly*/);
1072 self->Set(String::NewFromUtf8(isolate, "cc"), cc/*, ReadOnly*/);
1073 self->Set(String::NewFromUtf8(isolate, "text"), txt/*, ReadOnly*/);
1074
1075 self->Set(String::NewFromUtf8(isolate, "send"), FunctionTemplate::New(isolate, WrapSendMail)->GetFunction()/*, ReadOnly*/);
1076
1077 args.GetReturnValue().Set(self);
1078}
1079
1080vector<string> InterpreterV8::ValueToArray(const Handle<Value> &val, bool only)
1081{
1082 vector<string> rc;
1083
1084 Handle<Array> arr = Handle<Array>::Cast(val);
1085 for (uint32_t i=0; i<arr->Length(); i++)
1086 {
1087 Handle<Value> obj = arr->Get(i);
1088 if (obj.IsEmpty())
1089 continue;
1090
1091 if (obj->IsNull() || obj->IsUndefined())
1092 continue;
1093
1094 if (only && !obj->IsString())
1095 continue;
1096
1097 rc.push_back(*String::Utf8Value(obj->ToString()));
1098 }
1099
1100 return rc;
1101}
1102
1103void InterpreterV8::FuncSendMail(const Arguments& args)
1104{
1105 Isolate *isolate = Isolate::GetCurrent();
1106
1107 const HandleScope handle_scope(isolate);
1108
1109 if (args.Length()>1)
1110 {
1111 isolate->ThrowException(String::NewFromUtf8(isolate, "Only one argument allowed."));
1112 return;
1113 }
1114
1115 if (args.Length()==1 && !args[0]->IsBoolean())
1116 {
1117 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument must be a boolean."));
1118 return;
1119 }
1120
1121 const bool block = args.Length()==0 || args[0]->BooleanValue();
1122
1123 const Handle<Value> sub = args.This()->Get(String::NewFromUtf8(isolate, "subject"));
1124 const Handle<Value> rec = args.This()->Get(String::NewFromUtf8(isolate, "recipients"));
1125 const Handle<Value> txt = args.This()->Get(String::NewFromUtf8(isolate, "text"));
1126 const Handle<Value> att = args.This()->Get(String::NewFromUtf8(isolate, "attachments"));
1127 const Handle<Value> bcc = args.This()->Get(String::NewFromUtf8(isolate, "bcc"));
1128 const Handle<Value> cc = args.This()->Get(String::NewFromUtf8(isolate, "cc"));
1129
1130 const vector<string> vrec = ValueToArray(rec);
1131 const vector<string> vtxt = ValueToArray(txt, false);
1132 const vector<string> vatt = ValueToArray(att);
1133 const vector<string> vbcc = ValueToArray(bcc);
1134 const vector<string> vcc = ValueToArray(cc);
1135
1136 if (vrec.size()==0)
1137 {
1138 isolate->ThrowException(String::NewFromUtf8(isolate, "At least one valid string is required in 'recipients'."));
1139 return;
1140 }
1141 if (vtxt.size()==0)
1142 {
1143 isolate->ThrowException(String::NewFromUtf8(isolate, "At least one valid string is required in 'text'."));
1144 return;
1145 }
1146
1147 const string subject = *String::Utf8Value(sub->ToString());
1148
1149 FILE *pipe = popen(("from=no-reply@fact-project.org mailx -~ "+vrec[0]).c_str(), "w");
1150 if (!pipe)
1151 {
1152 isolate->ThrowException(String::NewFromUtf8(isolate, strerror(errno)));
1153 return;
1154 }
1155
1156
1157 fprintf(pipe, "%s", ("~s"+subject+"\n").c_str());
1158 for (auto it=vrec.begin()+1; it<vrec.end(); it++)
1159 fprintf(pipe, "%s", ("~t"+*it+"\n").c_str());
1160 for (auto it=vbcc.begin(); it<vbcc.end(); it++)
1161 fprintf(pipe, "%s", ("~b"+*it+"\n").c_str());
1162 for (auto it=vcc.begin(); it<vcc.end(); it++)
1163 fprintf(pipe, "%s", ("~c"+*it+"\n").c_str());
1164 for (auto it=vatt.begin(); it<vatt.end(); it++)
1165 fprintf(pipe, "%s", ("~@"+*it+"\n").c_str()); // Must not contain white spaces
1166
1167 for (auto it=vtxt.begin(); it<vtxt.end(); it++)
1168 fwrite((*it+"\n").c_str(), it->length()+1, 1, pipe);
1169
1170 fprintf(pipe, "\n---\nsent by dimctrl");
1171
1172 if (!block)
1173 return;
1174
1175 const int rc = pclose(pipe);
1176
1177 const Locker lock(isolate);
1178 args.GetReturnValue().Set(WEXITSTATUS(rc));
1179}
1180
1181// =========================================================================
1182// Curl
1183// ==========================================================================
1184
1185void InterpreterV8::ConstructorCurl(const Arguments &args)
1186{
1187 Isolate *isolate = Isolate::GetCurrent();
1188
1189 if (!args.IsConstructCall())
1190 {
1191 isolate->ThrowException(String::NewFromUtf8(isolate, "Curl must be called as constructor"));
1192 return;
1193 }
1194
1195 if (args.Length()!=1 || !args[0]->IsString())
1196 {
1197 isolate->ThrowException(String::NewFromUtf8(isolate, "Constructor must be called with a single string as argument"));
1198 return;
1199 }
1200
1201 const HandleScope handle_scope(isolate);
1202
1203 Handle<Array> data = Array::New(isolate);
1204 if (data.IsEmpty())
1205 return;
1206
1207 Handle<Object> self = args.This();
1208
1209 self->Set(String::NewFromUtf8(isolate, "url"), args[0]->ToString()/*, ReadOnly*/);
1210 self->Set(String::NewFromUtf8(isolate, "data"), data/*, ReadOnly*/);
1211
1212 self->Set(String::NewFromUtf8(isolate, "send"), FunctionTemplate::New(isolate, WrapSendCurl)->GetFunction()/*, ReadOnly*/);
1213
1214 args.GetReturnValue().Set(self);
1215}
1216
1217void InterpreterV8::FuncSendCurl(const Arguments& args)
1218{
1219 Isolate *isolate = Isolate::GetCurrent();
1220
1221 if (args.Length()>1)
1222 {
1223 isolate->ThrowException(String::NewFromUtf8(isolate, "Only one argument allowed."));
1224 return;
1225 }
1226
1227 if (args.Length()==1 && !args[0]->IsBoolean())
1228 {
1229 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument must be a boolean."));
1230 return;
1231 }
1232
1233 const HandleScope handle_scope(isolate);
1234
1235 const bool block = args.Length()==0 || args[0]->BooleanValue();
1236
1237 const Handle<Value> url = args.This()->Get(String::NewFromUtf8(isolate, "url"));
1238 const Handle<Value> data = args.This()->Get(String::NewFromUtf8(isolate, "data"));
1239
1240 const vector<string> vdata = ValueToArray(data);
1241 const string sdata = boost::algorithm::join(vdata, "&");
1242
1243 const string surl = *String::Utf8Value(url->ToString());
1244
1245 string cmd = "curl -sSf ";
1246 if (!sdata.empty())
1247 cmd += "--data '"+sdata+"' ";
1248 cmd += "'http://"+surl+"' 2>&1 ";
1249
1250 FILE *pipe = popen(cmd.c_str(), "r");
1251 if (!pipe)
1252 {
1253 isolate->ThrowException(String::NewFromUtf8(isolate, strerror(errno)));
1254 return;
1255 }
1256
1257 if (!block)
1258 return;
1259
1260 string txt;
1261
1262 while (!feof(pipe))
1263 {
1264 char buf[1025];
1265 if (fgets(buf, 1024, pipe)==NULL)
1266 break;
1267 txt += buf;
1268 }
1269
1270 const int rc = pclose(pipe);
1271
1272 Handle<Object> obj = Object::New(isolate);
1273
1274 obj->Set(String::NewFromUtf8(isolate, "cmd"), String::NewFromUtf8(isolate, cmd.c_str()));
1275 obj->Set(String::NewFromUtf8(isolate, "data"), String::NewFromUtf8(isolate, txt.c_str()));
1276 obj->Set(String::NewFromUtf8(isolate, "rc"), Integer::NewFromUnsigned(isolate, WEXITSTATUS(rc)));
1277
1278 const Locker lock(isolate);
1279 args.GetReturnValue().Set(obj);
1280}
1281
1282// ==========================================================================
1283// Database
1284// ==========================================================================
1285
1286void InterpreterV8::FuncDbClose(const Arguments &args)
1287{
1288 Isolate* isolate = Isolate::GetCurrent();
1289
1290 void *ptr = args.This()->GetInternalField(0).As<v8::External>()->Value();
1291 if (!ptr)
1292 {
1293 args.GetReturnValue().Set(false);
1294 return;
1295 }
1296
1297#ifdef HAVE_SQL
1298 Database *db = reinterpret_cast<Database*>(ptr);
1299 auto it = find(fDatabases.begin(), fDatabases.end(), db);
1300 fDatabases.erase(it);
1301 delete db;
1302#endif
1303
1304 const HandleScope handle_scope(isolate);
1305
1306 args.This()->SetInternalField(0, External::New(isolate, 0));
1307
1308 args.GetReturnValue().Set(true);
1309}
1310
1311void InterpreterV8::FuncDbQuery(const Arguments &args)
1312{
1313 Isolate* isolate = Isolate::GetCurrent();
1314
1315 if (args.Length()==0)
1316 {
1317 isolate->ThrowException(String::NewFromUtf8(isolate, "Arguments expected."));
1318 return;
1319 }
1320
1321 void *ptr = args.This()->GetInternalField(0).As<v8::External>()->Value();
1322 if (!ptr)
1323 return;
1324
1325 string query;
1326 for (int i=0; i<args.Length(); i++)
1327 query += string(" ") + *String::Utf8Value(args[i]);
1328 query.erase(0, 1);
1329
1330#ifdef HAVE_SQL
1331 try
1332 {
1333 const HandleScope handle_scope(isolate);
1334
1335 Database *db = reinterpret_cast<Database*>(ptr);
1336
1337 const mysqlpp::StoreQueryResult res = db->query(query).store();
1338
1339 Handle<Array> ret = Array::New(isolate);
1340 if (ret.IsEmpty())
1341 return;
1342
1343 ret->Set(String::NewFromUtf8(isolate, "table"), String::NewFromUtf8(isolate, res.table())/*, ReadOnly*/);
1344 ret->Set(String::NewFromUtf8(isolate, "query"), String::NewFromUtf8(isolate, query.c_str())/*, ReadOnly*/);
1345
1346 Handle<Array> cols = Array::New(isolate);
1347 if (cols.IsEmpty())
1348 return;
1349
1350 int irow=0;
1351 for (vector<mysqlpp::Row>::const_iterator it=res.begin(); it<res.end(); it++)
1352 {
1353 Handle<Object> row = Object::New(isolate);
1354 if (row.IsEmpty())
1355 return;
1356
1357 const mysqlpp::FieldNames *list = it->field_list().list;
1358
1359 for (size_t i=0; i<it->size(); i++)
1360 {
1361 const Handle<Value> name = String::NewFromUtf8(isolate, (*list)[i].c_str());
1362 if (irow==0)
1363 cols->Set(i, name);
1364
1365 if ((*it)[i].is_null())
1366 {
1367 row->Set(name, Undefined(isolate)/*, ReadOnly*/);
1368 continue;
1369 }
1370
1371 const string sql_type = (*it)[i].type().sql_name();
1372
1373 const bool uns = sql_type.find("UNSIGNED")==string::npos;
1374
1375 if (sql_type.find("BIGINT")!=string::npos)
1376 {
1377 if (uns)
1378 {
1379 const uint64_t val = (uint64_t)(*it)[i];
1380 if (val>UINT32_MAX)
1381 row->Set(name, Number::New(isolate, val)/*, ReadOnly*/);
1382 else
1383 row->Set(name, Integer::NewFromUnsigned(isolate, val)/*, ReadOnly*/);
1384 }
1385 else
1386 {
1387 const int64_t val = (int64_t)(*it)[i];
1388 if (val<INT32_MIN || val>INT32_MAX)
1389 row->Set(name, Number::New(isolate, val)/*, ReadOnly*/);
1390 else
1391 row->Set(name, Integer::NewFromUnsigned(isolate, val)/*, ReadOnly*/);
1392 }
1393 continue;
1394 }
1395
1396 // 32 bit
1397 if (sql_type.find("INT")!=string::npos)
1398 {
1399 if (uns)
1400 row->Set(name, Integer::NewFromUnsigned(isolate, (uint32_t)(*it)[i])/*, ReadOnly*/);
1401 else
1402 row->Set(name, Integer::New(isolate, (int32_t)(*it)[i])/*, ReadOnly*/);
1403 continue;
1404 }
1405
1406 if (sql_type.find("BOOL")!=string::npos )
1407 {
1408 row->Set(name, Boolean::New(isolate, (bool)(*it)[i])/*, ReadOnly*/);
1409 continue;
1410 }
1411
1412 if (sql_type.find("FLOAT")!=string::npos)
1413 {
1414 ostringstream val;
1415 val << setprecision(7) << (float)(*it)[i];
1416 row->Set(name, Number::New(isolate, stod(val.str()))/*, ReadOnly*/);
1417 continue;
1418
1419 }
1420 if (sql_type.find("DOUBLE")!=string::npos)
1421 {
1422 row->Set(name, Number::New(isolate, (double)(*it)[i])/*, ReadOnly*/);
1423 continue;
1424 }
1425
1426 if (sql_type.find("CHAR")!=string::npos ||
1427 sql_type.find("TEXT")!=string::npos)
1428 {
1429 row->Set(name, String::NewFromUtf8(isolate, (const char*)(*it)[i])/*, ReadOnly*/);
1430 continue;
1431 }
1432
1433 time_t date = 0;
1434 if (sql_type.find("TIMESTAMP")!=string::npos)
1435 date = mysqlpp::Time((*it)[i]);
1436
1437 if (sql_type.find("DATETIME")!=string::npos)
1438 date = mysqlpp::DateTime((*it)[i]);
1439
1440 if (sql_type.find(" DATE ")!=string::npos)
1441 date = mysqlpp::Date((*it)[i]);
1442
1443 if (date>0)
1444 {
1445 // It is important to catch the exception thrown
1446 // by Date::New in case of thread termination!
1447 const Local<Value> val = Date::New(isolate, date*1000);
1448 if (val.IsEmpty())
1449 return;
1450
1451 row->Set(name, val/*, ReadOnly*/);
1452 }
1453 }
1454
1455 ret->Set(irow++, row);
1456 }
1457
1458 if (irow>0)
1459 ret->Set(String::NewFromUtf8(isolate, "cols"), cols/*, ReadOnly*/);
1460
1461 args.GetReturnValue().Set(ret);
1462 }
1463 catch (const exception &e)
1464 {
1465 isolate->ThrowException(String::NewFromUtf8(isolate, e.what()));
1466 }
1467#endif
1468}
1469
1470void InterpreterV8::FuncDatabase(const Arguments &args)
1471{
1472 Isolate *isolate = Isolate::GetCurrent();
1473
1474 if (!args.IsConstructCall())
1475 {
1476 isolate->ThrowException(String::NewFromUtf8(isolate, "Database must be called as constructor."));
1477 return;
1478 }
1479
1480 if (args.Length()!=1)
1481 {
1482 isolate->ThrowException(String::NewFromUtf8(isolate, "Number of arguments must be 1."));
1483 return;
1484 }
1485
1486 if (!args[0]->IsString())
1487 {
1488 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 1 not a string."));
1489 return;
1490 }
1491
1492#ifdef HAVE_SQL
1493 try
1494 {
1495 const HandleScope handle_scope(isolate);
1496
1497 // if (!args.IsConstructCall())
1498 // return Constructor(fTemplateDatabase, args);
1499
1500 Database *db = new Database(*String::Utf8Value(args[0]));
1501 fDatabases.push_back(db);
1502
1503 Handle<Object> self = args.This();
1504 self->Set(String::NewFromUtf8(isolate, "user"), String::NewFromUtf8(isolate, db->user.c_str())/*, ReadOnly*/);
1505 self->Set(String::NewFromUtf8(isolate, "server"), String::NewFromUtf8(isolate, db->server.c_str())/*, ReadOnly*/);
1506 self->Set(String::NewFromUtf8(isolate, "database"), String::NewFromUtf8(isolate, db->db.c_str())/*, ReadOnly*/);
1507 if (db->port)
1508 self->Set(String::NewFromUtf8(isolate, "port"), Integer::NewFromUnsigned(isolate, db->port));
1509 self->Set(String::NewFromUtf8(isolate, "query"), FunctionTemplate::New(isolate, WrapDbQuery)->GetFunction()/*, ReadOnly*/);
1510 self->Set(String::NewFromUtf8(isolate, "close"), FunctionTemplate::New(isolate, WrapDbClose)->GetFunction()/*, ReadOnly*/);
1511 self->SetInternalField(0, External::New(isolate, db));
1512
1513 args.GetReturnValue().Set(self);
1514 }
1515 catch (const exception &e)
1516 {
1517 isolate->ThrowException(String::NewFromUtf8(isolate, e.what()));
1518 }
1519#endif
1520}
1521
1522// ==========================================================================
1523// Services
1524// ==========================================================================
1525
1526Handle<Value> InterpreterV8::Convert(char type, const char* &ptr)
1527{
1528 Isolate *isolate = Isolate::GetCurrent();
1529
1530 // Dim values are always unsigned per (FACT++) definition
1531 switch (type)
1532 {
1533 case 'F':
1534 {
1535 // Remove the "imprecision" effect coming from casting a float to
1536 // a double and then showing it with double precision
1537 ostringstream val;
1538 val << setprecision(7) << *reinterpret_cast<const float*>(ptr);
1539 ptr += 4;
1540 return Number::New(isolate, stod(val.str()));
1541 }
1542 case 'D': { Handle<Value> v=Number::New(isolate, *reinterpret_cast<const double*>(ptr)); ptr+=8; return v; }
1543 case 'I':
1544 case 'L': { Handle<Value> v=Integer::NewFromUnsigned(isolate, *reinterpret_cast<const uint32_t*>(ptr)); ptr += 4; return v; }
1545 case 'X':
1546 {
1547 const int64_t val = *reinterpret_cast<const int64_t*>(ptr);
1548 ptr += 8;
1549 if (val>=0 && val<=UINT32_MAX)
1550 return Integer::NewFromUnsigned(isolate, val);
1551 if (val>=INT32_MIN && val<0)
1552 return Integer::New(isolate, val);
1553 return Number::New(isolate, val);
1554 }
1555 case 'S': { Handle<Value> v=Integer::NewFromUnsigned(isolate, *reinterpret_cast<const uint16_t*>(ptr)); ptr += 2; return v; }
1556 case 'C': { Handle<Value> v=Integer::NewFromUnsigned(isolate, (uint16_t)*reinterpret_cast<const uint8_t*>(ptr)); ptr += 1; return v; }
1557 }
1558 return Undefined(isolate);
1559}
1560
1561void InterpreterV8::FuncClose(const Arguments &args)
1562{
1563 Isolate *isolate = Isolate::GetCurrent();
1564
1565 const HandleScope handle_scope(isolate);
1566
1567 //const void *ptr = Local<External>::Cast(args.Holder()->GetInternalField(0))->Value();
1568
1569 const String::Utf8Value str(args.This()->Get(String::NewFromUtf8(isolate, "name")));
1570
1571 const auto it = fReverseMap.find(*str);
1572 if (it!=fReverseMap.end())
1573 fReverseMap.erase(it);
1574
1575 args.This()->Set(String::NewFromUtf8(isolate, "isOpen"), Boolean::New(isolate, false)/*, ReadOnly*/);
1576
1577 args.GetReturnValue().Set(JsUnsubscribe(*str));
1578}
1579
1580Handle<Value> InterpreterV8::ConvertEvent(const EventImp *evt, uint64_t counter, const char *str)
1581{
1582 Isolate *isolate = Isolate::GetCurrent();
1583
1584 const vector<Description> vec = JsDescription(str);
1585
1586 Local<Context> context = isolate->GetCurrentContext();
1587 MaybeLocal<Object> mret = fTemplateEvent->GetFunction()->NewInstance(context);
1588 if (mret.IsEmpty())
1589 return Undefined(isolate);
1590
1591 const Local<Value> date = Date::New(isolate, evt->GetJavaDate());
1592 if (date.IsEmpty())
1593 return Undefined(isolate);
1594
1595 Local<Object> ret = mret.ToLocalChecked();
1596
1597 ret->Set(String::NewFromUtf8(isolate, "name"), String::NewFromUtf8(isolate, str)/*, ReadOnly*/);
1598 ret->Set(String::NewFromUtf8(isolate, "format"), String::NewFromUtf8(isolate, evt->GetFormat().c_str())/*, ReadOnly*/);
1599 ret->Set(String::NewFromUtf8(isolate, "qos"), Integer::New(isolate, evt->GetQoS())/*, ReadOnly*/);
1600 ret->Set(String::NewFromUtf8(isolate, "size"), Integer::New(isolate, evt->GetSize())/*, ReadOnly*/);
1601 ret->Set(String::NewFromUtf8(isolate, "counter"), Integer::New(isolate, counter)/*, ReadOnly*/);
1602 if (evt->GetJavaDate()>0)
1603 ret->Set(String::NewFromUtf8(isolate, "time"), date/*, ReadOnly*/);
1604
1605 // If names are available data will also be provided as an
1606 // object. If an empty event was received, but names are available,
1607 // the object will be empty. Otherwise 'obj' will be undefined.
1608 // obj===undefined: no data received
1609 // obj!==undefined, length==0: names for event available
1610 // obj!==undefined, obj.length>0: names available, data received
1611 Handle<Object> named = Object::New(isolate);
1612 if (vec.size()>0)
1613 ret->Set(String::NewFromUtf8(isolate, "obj"), named/*, ReadOnly*/);
1614
1615 // If no event was received (usually a disconnection event in
1616 // the context of FACT++), no data is returned
1617 if (evt->IsEmpty())
1618 return ret;
1619
1620 // If valid data was received, but the size was zero, then
1621 // null is returned as data
1622 // data===undefined: no data received
1623 // data===null: event received, but no data
1624 // data.length>0: event received, contains data
1625 if (evt->GetSize()==0 || evt->GetFormat().empty())
1626 {
1627 ret->Set(String::NewFromUtf8(isolate, "data"), Null(isolate)/*, ReadOnly*/);
1628 return ret;
1629 }
1630
1631 // It seems a copy is required either in the boost which comes with
1632 // Ubuntu 16.04 or in gcc5 ?!
1633 const string fmt = evt->GetFormat();
1634
1635 typedef boost::char_separator<char> separator;
1636 const boost::tokenizer<separator> tokenizer(fmt, separator(";:"));
1637
1638 const vector<string> tok(tokenizer.begin(), tokenizer.end());
1639
1640 //Handle<Object> arr = tok.size()>1 ? Array::New(isolate) : ret;
1641
1642 Handle<Object> arr;
1643 if (tok.size()>1)
1644 arr = Array::New(isolate);
1645 else
1646 arr = ret;
1647
1648 if (arr.IsEmpty())
1649 return Undefined(isolate);
1650
1651 const char *ptr = evt->GetText();
1652 const char *end = evt->GetText()+evt->GetSize();
1653
1654 try
1655 {
1656 size_t pos = 1;
1657 for (auto it=tok.begin(); it<tok.end() && ptr<end; it++, pos++)
1658 {
1659 char type = (*it)[0];
1660 it++;
1661
1662 string name = pos<vec.size() ? vec[pos].name : "";
1663 if (tok.size()==1)
1664 name = "data";
1665
1666 // Get element size
1667 uint32_t sz = 1;
1668 switch (type)
1669 {
1670 case 'X':
1671 case 'D': sz = 8; break;
1672 case 'F':
1673 case 'I':
1674 case 'L': sz = 4; break;
1675 case 'S': sz = 2; break;
1676 case 'C': sz = 1; break;
1677 }
1678
1679 // Check if no number is attached if the size of the
1680 // received data is consistent with the format string
1681 if (it==tok.end() && (end-ptr)%sz>0)
1682 return Exception::Error(String::NewFromUtf8(isolate, ("Number of received bytes ["+to_string(evt->GetSize())+"] does not match format ["+evt->GetFormat()+"]").c_str()));
1683
1684 // Check if format has a number attached.
1685 // If no number is attached calculate number of elements
1686 const uint32_t cnt = it==tok.end() ? (end-ptr)/sz : stoi(it->c_str());
1687
1688 // is_str: Array of type C but unknown size (String)
1689 // is_one: Array of known size, but size is 1 (I:1)
1690 const bool is_str = type=='C' && it==tok.end();
1691 const bool is_one = cnt==1 && it!=tok.end();
1692
1693 Handle<Value> v;
1694
1695 if (is_str)
1696 v = String::NewFromUtf8(isolate, ptr);
1697 if (is_one)
1698 v = Convert(type, ptr);
1699
1700 // Array of known (I:5) or unknown size (I), but no string
1701 if (!is_str && !is_one)
1702 {
1703 Handle<Object> a = Array::New(isolate, cnt);
1704 if (a.IsEmpty())
1705 return Undefined(isolate);
1706
1707 for (uint32_t i=0; i<cnt; i++)
1708 a->Set(i, Convert(type, ptr));
1709
1710 v = a;
1711 }
1712
1713 if (tok.size()>1)
1714 arr->Set(pos-1, v);
1715 else
1716 ret->Set(String::NewFromUtf8(isolate, "data"), v/*, ReadOnly*/);
1717
1718 if (!name.empty())
1719 {
1720 const Handle<String> n = String::NewFromUtf8(isolate, name.c_str());
1721 named->Set(n, v);
1722 }
1723 }
1724
1725 if (tok.size()>1)
1726 ret->Set(String::NewFromUtf8(isolate, "data"), arr/*, ReadOnly*/);
1727
1728 return ret;
1729 }
1730 catch (...)
1731 {
1732 return Exception::Error(String::NewFromUtf8(isolate, ("Format string conversion '"+evt->GetFormat()+"' failed.").c_str()));
1733 }
1734}
1735/*
1736Handle<Value> InterpreterV8::FuncGetData(const Arguments &args)
1737{
1738 HandleScope handle_scope;
1739
1740 const String::Utf8Value str(args.Holder()->Get(String::NewFromUtf8(isolate, "name")));
1741
1742 const pair<uint64_t, EventImp *> p = JsGetEvent(*str);
1743
1744 const EventImp *evt = p.second;
1745 if (!evt)
1746 return Undefined(isolate);
1747
1748 //if (counter==cnt)
1749 // return info.Holder();//Holder()->Get(String::NewFromUtf8(isolate, "data"));
1750
1751 Handle<Value> ret = ConvertEvent(evt, p.first, *str);
1752 return ret->IsNativeError() ? isolate->ThrowException(ret) : handle_scope.Escape(ret);
1753}
1754*/
1755void InterpreterV8::FuncGetData(const Arguments &args)
1756{
1757 Isolate *isolate = Isolate::GetCurrent();
1758
1759 if (args.Length()>2)
1760 {
1761 isolate->ThrowException(String::NewFromUtf8(isolate, "Number of arguments must not be greater than 2."));
1762 return;
1763 }
1764
1765 if (args.Length()>=1 && !args[0]->IsInt32() && !args[0]->IsNull())
1766 {
1767 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 1 not an uint32."));
1768 return;
1769 }
1770
1771 if (args.Length()==2 && !args[1]->IsBoolean())
1772 {
1773 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 2 not a boolean."));
1774 return;
1775 }
1776
1777 // Using a Javascript function has the advantage that it is fully
1778 // interruptable without the need of C++ code
1779 const bool null = args.Length()>=1 && args[0]->IsNull();
1780 const int32_t timeout = args.Length()>=1 ? args[0]->Int32Value() : 0;
1781 const bool named = args.Length()<2 || args[1]->BooleanValue();
1782
1783 const HandleScope handle_scope(isolate);
1784
1785 const Handle<String> data = String::NewFromUtf8(isolate, "data");
1786 const Handle<String> object = String::NewFromUtf8(isolate, "obj");
1787
1788 const String::Utf8Value name(args.Holder()->Get(String::NewFromUtf8(isolate, "name")));
1789
1790 TryCatch exception(isolate);
1791
1792 Time t;
1793 while (!exception.HasCaught())
1794 {
1795 const pair<uint64_t, EventImp *> p = JsGetEvent(*name);
1796
1797 const EventImp *evt = p.second;
1798 if (evt)
1799 {
1800 const Handle<Value> val = ConvertEvent(evt, p.first, *name);
1801 if (val->IsNativeError())
1802 {
1803 isolate->ThrowException(val);
1804 return;
1805 }
1806
1807
1808 // Protect against the return of an exception
1809 if (val->IsObject())
1810 {
1811 const Handle<Object> event = val->ToObject();
1812 const Handle<Value> obj = event->Get(named?object:data);
1813 if (!obj.IsEmpty())
1814 {
1815 if (!named)
1816 {
1817 // No names (no 'obj'), but 'data'
1818 if (!obj->IsUndefined())
1819 {
1820 args.GetReturnValue().Set(val);
1821 return;
1822 }
1823 }
1824 else
1825 {
1826 // Has names and data was received?
1827 if (obj->IsObject() && obj->ToObject()->GetOwnPropertyNames()->Length()>0)
1828 {
1829 args.GetReturnValue().Set(val);
1830 return;
1831 }
1832 }
1833 }
1834 }
1835 }
1836
1837 if (args.Length()==0)
1838 break;
1839
1840 if (!null && Time()-t>=boost::posix_time::milliseconds(abs(timeout)))
1841 break;
1842
1843 // Theoretically, the CPU usage can be reduced by maybe a factor
1844 // of four using a larger value, but this also means that the
1845 // JavaScript is locked for a longer time.
1846 const Unlocker unlock(isolate);
1847 usleep(1000);
1848 }
1849
1850 // This hides the location of the exception, which is wanted.
1851 if (exception.HasCaught())
1852 {
1853 exception.ReThrow();
1854 return;
1855 }
1856
1857 if (timeout<0)
1858 return;
1859
1860 const string str = "Waiting for a valid event of "+string(*name)+" timed out.";
1861 isolate->ThrowException(String::NewFromUtf8(isolate, str.c_str()));
1862}
1863
1864void InterpreterV8::TerminateExecution(Isolate* isolate)
1865{
1866 // This makes all threads/contexts sooner or later terminate
1867 isolate->TerminateExecution();
1868}
1869
1870// This is a callback from the RemoteControl piping event handling
1871// to the java script ---> in test phase!
1872void InterpreterV8::JsHandleEvent(const EventImp &evt, uint64_t cnt, const string &service)
1873{
1874 // FIXME: This is not thread safe!
1875 // This is copied as fMainThread=0 is used to signal
1876 // that no execution should take place anymore
1877 Isolate *isolate = fMainThread;
1878 if (!isolate)
1879 return;
1880
1881 //{
1882
1883 // We want to run as an interrupt in the main thread
1884 const Locker locker(isolate);
1885 if (!fMainThread)
1886 return;
1887
1888 const Isolate::Scope isolate_scope(isolate);
1889 const HandleScope handle_scope(isolate);
1890
1891 const auto it = fReverseMap.find(service);
1892 if (it==fReverseMap.end())
1893 return;
1894
1895 Handle<Object> fun = it->second.Get(isolate);
1896 const Context::Scope scope(fun->CreationContext());
1897
1898 const Handle<String> onchange = String::NewFromUtf8(isolate, "onchange");
1899 if (!fun->Has(onchange))
1900 return;
1901
1902 const Handle<Value> val = fun->Get(onchange);
1903 if (!val->IsFunction())
1904 return;
1905
1906 TryCatch exception(isolate);
1907
1908 Handle<Value> ret = ConvertEvent(&evt, cnt, service.c_str());
1909 if (ret->IsObject())
1910 Handle<Function>::Cast(val)->Call(fun->CreationContext(), fun, 1, &ret).IsEmpty();
1911
1912 if (!HandleException(exception, "Service.onchange"))
1913 isolate->AddBeforeCallEnteredCallback(TerminateExecution);
1914
1915 if (ret->IsNativeError())
1916 {
1917 JsException(service+".onchange callback - "+*String::Utf8Value(ret));
1918 isolate->AddBeforeCallEnteredCallback(TerminateExecution);
1919 }
1920
1921 // isolate->DiscardThreadSpecificMetadata();
1922
1923/*
1924 // The Isolation context isolates (keeps local) interrupts and termination requests!
1925 // Terminating execution doesn't work while the JS is still runnning in this script
1926 if (term)
1927 {
1928 // There is no point in calling TerminateExecution before (after releasing
1929 // the lock) the scheduler has entered the main thread again, as the
1930 // TerminateExecution would just be lost.
1931 const Unlocker unlock(isolate);
1932 for (int i=0; i<10 && !fMainThread->InContext(); i++)
1933 usleep(50);
1934 isolate->TerminateExecution();
1935 }
1936*/
1937}
1938
1939void InterpreterV8::OnChangeSet(Local<Name> name, Local<Value> value, const PropertyCallbackInfo<Value> &)
1940{
1941 Isolate *isolate = Isolate::GetCurrent();
1942
1943 // Returns the value if the setter intercepts the request.
1944 // Otherwise, returns an empty handle.
1945 const string server = *String::Utf8Value(name);
1946 auto it = fStateCallbacks.find(server);
1947
1948 if (it!=fStateCallbacks.end())
1949 fStateCallbacks.erase(it);
1950
1951 if (value->IsFunction())
1952 fStateCallbacks[server] = UniquePersistent<Object>(isolate, value->ToObject());
1953}
1954
1955void InterpreterV8::JsHandleState(const std::string &server, const State &state)
1956{
1957 // FIXME: This is not thread safe!
1958 // This is copied as fMainThread=0 is used to signal
1959 // that no execution should take place anymore
1960 Isolate *isolate = fMainThread;
1961 if (!isolate)
1962 return;
1963
1964 //{
1965
1966 // We want to run as an interrupt in the main thread
1967 const Locker locker(isolate);
1968 if (!fMainThread)
1969 return;
1970
1971 const Isolate::Scope isolate_scope(isolate);
1972 const HandleScope handle_scope(isolate);
1973
1974
1975 auto it = fStateCallbacks.find(server);
1976 if (it==fStateCallbacks.end())
1977 {
1978 it = fStateCallbacks.find("*");
1979 if (it==fStateCallbacks.end())
1980 return;
1981 }
1982
1983 Handle<Object> fun = it->second.Get(isolate);
1984 const Context::Scope scope(fun->CreationContext());
1985
1986 // -------------------------------------------------------------------
1987
1988 Handle<ObjectTemplate> obj = ObjectTemplate::New(isolate);
1989 obj->Set(String::NewFromUtf8(isolate, "server"), String::NewFromUtf8(isolate, server.c_str()), ReadOnly);
1990
1991 if (state.index>-256)
1992 {
1993 obj->Set(String::NewFromUtf8(isolate, "index"), Integer::New(isolate, state.index), ReadOnly);
1994 obj->Set(String::NewFromUtf8(isolate, "name"), String::NewFromUtf8(isolate, state.name.c_str()), ReadOnly);
1995 obj->Set(String::NewFromUtf8(isolate, "comment"), String::NewFromUtf8(isolate, state.comment.c_str()), ReadOnly);
1996
1997 MaybeLocal<Value> date = Date::New(isolate->GetCurrentContext(), state.time.JavaDate());
1998 if (!date.IsEmpty())
1999 SetProperty(obj, "time", date.ToLocalChecked());
2000 /*
2001 {
2002 obj->Set(String::NewFromUtf8(isolate, "time"), date.ToLocalChecked()->ToString(), ReadOnly);
2003
2004 // This crahshes when called a secont time. I don't know why.
2005 // obj->Set(String::NewFromUtf8(isolate, "time"), date.ToLocalChecked(), ReadOnly);
2006 }*/
2007 }
2008
2009 // -------------------------------------------------------------------
2010
2011 TryCatch exception(isolate);
2012
2013 Handle<Value> args[] = { obj->NewInstance() };
2014 Handle<Function>::Cast(fun)->Call(fun->CreationContext(), fun, 1, args).IsEmpty();
2015
2016 if (!HandleException(exception, "dim.onchange"))
2017 isolate->AddBeforeCallEnteredCallback(TerminateExecution);
2018
2019 // isolate->DiscardThreadSpecificMetadata();
2020}
2021
2022// ==========================================================================
2023// Interrupt handling
2024// ==========================================================================
2025
2026void InterpreterV8::FuncSetInterrupt(const Arguments &args)
2027{
2028 Isolate *isolate = Isolate::GetCurrent();
2029
2030 if (args.Length()!=1)
2031 {
2032 isolate->ThrowException(String::NewFromUtf8(isolate, "Number of arguments must be 1."));
2033 return;
2034 }
2035
2036 if (!args[0]->IsNull() && !args[0]->IsUndefined() && !args[0]->IsFunction())
2037 {
2038 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument not a function, null or undefined."));
2039 return;
2040 }
2041
2042 if (args[0]->IsNull() || args[0]->IsUndefined())
2043 {
2044 fInterruptCallback.Reset();
2045 return;
2046 }
2047
2048 // Returns the value if the setter intercepts the request. Otherwise, returns an empty handle.
2049 fInterruptCallback = UniquePersistent<Object>(isolate, args[0]->ToObject());
2050}
2051
2052Handle<Value> InterpreterV8::HandleInterruptImp(string str, uint64_t time)
2053{
2054 Isolate *isolate = Isolate::GetCurrent();
2055
2056 if (fInterruptCallback.IsEmpty())
2057 return Handle<Value>();
2058
2059 const size_t p = str.find_last_of('\n');
2060
2061 const string usr = p==string::npos?"":str.substr(p+1);
2062
2063 string irq = p==string::npos?str:str.substr(0, p);
2064
2065 map<string,string> data;
2066 try
2067 {
2068 data = Tools::Split(irq, true);
2069 }
2070 catch (const exception &e)
2071 {
2072 irq = "ERROR";
2073 data["0"] = e.what();
2074 JsWarn("Couldn't parse interrupt: "+irq+" ["+string(e.what())+"]");
2075 }
2076
2077 Local<Value> irq_str = String::NewFromUtf8(isolate, irq.c_str());
2078 Local<Value> usr_str = String::NewFromUtf8(isolate, usr.c_str());
2079 Local<Value> date = Date::New(isolate, time);
2080 Handle<Object> arr = Array::New(isolate, data.size());
2081
2082 if (date.IsEmpty() || arr.IsEmpty())
2083 return Handle<Value>();
2084
2085 for (auto it=data.begin(); it!=data.end(); it++)
2086 arr->Set(String::NewFromUtf8(isolate, it->first.c_str()), String::NewFromUtf8(isolate, it->second.c_str()));
2087
2088 Handle<Value> args[] = { irq_str, arr, date, usr_str };
2089
2090 Handle<Object> fun = fInterruptCallback.Get(isolate);
2091 //const Context::Scope scope(obj->CreationContext());
2092
2093 MaybeLocal<Value> ret = Handle<Function>::Cast(fun)->Call(fun->CreationContext(), fun, 4, args);
2094 return ret.IsEmpty() ? Handle<Value>() : ret.ToLocalChecked();
2095}
2096
2097int InterpreterV8::JsHandleInterrupt(const EventImp &evt)
2098{
2099 // FIXME: This is not thread safe!
2100 // This is copied as fMainThread=0 is used to signal
2101 // that no execution should take place anymore
2102 Isolate *isolate = fMainThread;
2103 if (!isolate)
2104 return -42;
2105
2106 //{
2107
2108 // We want to run as an interrupt in the main thread
2109 const Locker locker(isolate);
2110 if (!fMainThread)
2111 return -42;
2112
2113 const Isolate::Scope isolate_scope(isolate);
2114 const HandleScope handle_scope(isolate);
2115
2116 if (fInterruptCallback.IsEmpty())
2117 return -42;
2118
2119 Handle<Object> fun = fInterruptCallback.Get(isolate);
2120 const Context::Scope scope(fun->CreationContext());
2121
2122 // -------------------------------------------------------------------
2123
2124 TryCatch exception(isolate);
2125
2126 const Handle<Value> val = HandleInterruptImp(evt.GetString(), evt.GetJavaDate());
2127
2128 const int rc = !val.IsEmpty() && val->IsInt32() ? val->Int32Value() : 0;
2129
2130 if (!HandleException(exception, "interrupt"))
2131 isolate->AddBeforeCallEnteredCallback(TerminateExecution);
2132
2133 return rc<10 || rc>255 ? -42 : rc;
2134}
2135
2136void InterpreterV8::FuncTriggerInterrupt(const Arguments &args)
2137{
2138 Isolate *isolate = Isolate::GetCurrent();
2139
2140 string data;
2141 for (int i=0; i<args.Length(); i++)
2142 {
2143 const String::Utf8Value str(args[i]);
2144
2145 if (string(*str).find_first_of('\n')!=string::npos)
2146 {
2147 isolate->ThrowException(String::NewFromUtf8(isolate, "No argument must contain line breaks."));
2148 return;
2149 }
2150
2151 if (!*str)
2152 continue;
2153
2154 data += *str;
2155 data += ' ';
2156 }
2157
2158 const HandleScope handle_scope(isolate);
2159
2160 const Handle<Value> rc = HandleInterruptImp(Tools::Trim(data), Time().JavaDate());
2161 args.GetReturnValue().Set(rc);
2162}
2163
2164// ==========================================================================
2165// Class 'Subscription'
2166// ==========================================================================
2167
2168void InterpreterV8::FuncSubscription(const Arguments &args)
2169{
2170 Isolate *isolate = Isolate::GetCurrent();
2171
2172 if (args.Length()!=1 && args.Length()!=2)
2173 {
2174 isolate->ThrowException(String::NewFromUtf8(isolate, "Number of arguments must be one or two."));
2175 return;
2176 }
2177
2178 if (!args[0]->IsString())
2179 {
2180 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 1 must be a string."));
2181 return;
2182 }
2183
2184 if (args.Length()==2 && !args[1]->IsFunction())
2185 {
2186 isolate->ThrowException(String::NewFromUtf8(isolate, "Argument 2 must be a function."));
2187 return;
2188 }
2189
2190 const String::Utf8Value str(args[0]);
2191
2192 if (!args.IsConstructCall())
2193 {
2194 const auto it = fReverseMap.find(*str);
2195 if (it!=fReverseMap.end())
2196 args.GetReturnValue().Set(it->second.Get(isolate)/*Local<Object>::New(isolate, it->second)*/);
2197
2198 return;
2199 }
2200
2201 const HandleScope handle_scope(isolate);
2202
2203 Handle<Object> self = args.This();
2204 self->Set(String::NewFromUtf8(isolate, "get"), FunctionTemplate::New(isolate, WrapGetData)->GetFunction()/*, ReadOnly*/);
2205 self->Set(String::NewFromUtf8(isolate, "close"), FunctionTemplate::New(isolate, WrapClose)->GetFunction()/*, ReadOnly*/);
2206 self->Set(String::NewFromUtf8(isolate, "name"), String::NewFromUtf8(isolate, *str)/*, ReadOnly*/);
2207 self->Set(String::NewFromUtf8(isolate, "isOpen"), Boolean::New(isolate, true));
2208
2209 if (args.Length()==2)
2210 self->Set(String::NewFromUtf8(isolate, "onchange"), args[1]);
2211
2212 fReverseMap[*str] = UniquePersistent<Object>(isolate, self);
2213
2214 void *ptr = JsSubscribe(*str);
2215 if (ptr==0)
2216 {
2217 isolate->ThrowException(String::NewFromUtf8(isolate, ("Subscription to '"+string(*str)+"' already exists.").c_str()));
2218 return;
2219 }
2220
2221 self->SetInternalField(0, External::New(isolate, ptr));
2222
2223 // Persistent<Object> p = Persistent<Object>::New(obj->NewInstance());
2224 // obj.MakeWeak((void*)1, Cleanup);
2225 // return obj;
2226}
2227
2228// ==========================================================================
2229// Astrometry
2230// ==========================================================================
2231#ifdef HAVE_NOVA
2232
2233double InterpreterV8::GetDataMember(const Arguments &args, const char *name)
2234{
2235 Isolate *isolate = Isolate::GetCurrent();
2236 return args.This()->Get(String::NewFromUtf8(isolate, name))->NumberValue();
2237}
2238
2239void InterpreterV8::CalcDist(const Arguments &args, const bool local)
2240{
2241 Isolate *isolate = Isolate::GetCurrent();
2242
2243 if (args.Length()!=2)
2244 {
2245 isolate->ThrowException(String::NewFromUtf8(isolate, "dist must be called with exactly two arguments."));
2246 return;
2247 }
2248
2249 if (!args[0]->IsObject() || !args[1]->IsObject())
2250 {
2251 isolate->ThrowException(String::NewFromUtf8(isolate, "At least one argument not an object."));
2252 return;
2253 }
2254
2255 // FiXME: Add a check for the argument type
2256
2257 const HandleScope handle_scope(isolate);
2258
2259 Handle<Object> obj[2] =
2260 {
2261 Handle<Object>::Cast(args[0]),
2262 Handle<Object>::Cast(args[1])
2263 };
2264
2265 const Handle<String> s_theta = String::NewFromUtf8(isolate, local?"zd":"dec"); // was: zd
2266 const Handle<String> s_phi = String::NewFromUtf8(isolate, local?"az":"ra"); // was: az
2267
2268 const double conv_t = M_PI/180;
2269 const double conv_p = local ? -M_PI/180 : M_PI/12;
2270 const double offset = local ? 0 : M_PI;
2271
2272 const double theta0 = offset - obj[0]->Get(s_theta)->NumberValue() * conv_t;
2273 const double phi0 = obj[0]->Get(s_phi )->NumberValue() * conv_p;
2274 const double theta1 = offset - obj[1]->Get(s_theta)->NumberValue() * conv_t;
2275 const double phi1 = obj[1]->Get(s_phi )->NumberValue() * conv_p;
2276
2277 if (!finite(theta0) || !finite(theta1) || !finite(phi0) || !finite(phi1))
2278 {
2279 isolate->ThrowException(String::NewFromUtf8(isolate, "some values not valid or not finite."));
2280 return;
2281 }
2282
2283 /*
2284 const double x0 = sin(zd0) * cos(az0); // az0 -= az0
2285 const double y0 = sin(zd0) * sin(az0); // az0 -= az0
2286 const double z0 = cos(zd0);
2287
2288 const double x1 = sin(zd1) * cos(az1); // az1 -= az0
2289 const double y1 = sin(zd1) * sin(az1); // az1 -= az0
2290 const double z1 = cos(zd1);
2291
2292 const double res = acos(x0*x1 + y0*y1 + z0*z1) * 180/M_PI;
2293 */
2294
2295 // cos(az1-az0) = cos(az1)*cos(az0) + sin(az1)*sin(az0)
2296
2297 const double x = sin(theta0) * sin(theta1) * cos(phi1-phi0);
2298 const double y = cos(theta0) * cos(theta1);
2299
2300 const double res = acos(x + y) * 180/M_PI;
2301
2302 args.GetReturnValue().Set(res);
2303}
2304
2305void InterpreterV8::LocalDist(const Arguments &args)
2306{
2307 CalcDist(args, true);
2308}
2309
2310void InterpreterV8::SkyDist(const Arguments &args)
2311{
2312 CalcDist(args, false);
2313}
2314
2315void InterpreterV8::MoonDisk(const Arguments &args)
2316{
2317 Isolate *isolate = Isolate::GetCurrent();
2318
2319 if (args.Length()>1)
2320 {
2321 isolate->ThrowException(String::NewFromUtf8(isolate, "disk must not be called with more than one argument."));
2322 return;
2323 }
2324
2325 const uint64_t v = uint64_t(args[0]->NumberValue());
2326 const Time utc = args.Length()==0 ? Time() : Time(v/1000, v%1000);
2327
2328 args.GetReturnValue().Set(Nova::GetLunarDisk(utc.JD()));
2329}
2330
2331struct AstroArgs
2332{
2333 string obs;
2334 Nova::LnLatPosn posn;
2335 double jd;
2336 uint64_t jsdate;
2337
2338 AstroArgs() : jsdate(0) { }
2339};
2340
2341AstroArgs EvalAstroArgs(int offset, const Arguments &args, int8_t type=2)
2342{
2343 const uint8_t max = abs(type);
2344
2345 if (args.Length()>offset+max)
2346 throw runtime_error("Number of arguments must not exceed "+to_string(offset+max)+".");
2347
2348 if (type==1 && args.Length()==offset+1 && !args[offset]->IsString())
2349 throw runtime_error("Argument "+to_string(offset+1)+" must be a string.");
2350 if (type==-1 && args.Length()==offset+1 && !args[offset]->IsDate())
2351 throw runtime_error("Argument "+to_string(offset+1)+" must be a date.");
2352
2353 if (args.Length()==offset+1 && !(args[offset]->IsDate() || args[offset]->IsString()))
2354 throw runtime_error("Argument "+to_string(offset+1)+" must be a string or Date.");
2355
2356 if (args.Length()==offset+2 &&
2357 !(args[offset+0]->IsDate() && args[offset+1]->IsString()) &&
2358 !(args[offset+1]->IsDate() && args[offset+0]->IsString()))
2359 throw runtime_error("Arguments "+to_string(offset+1)+" and "+to_string(offset+2)+" must be a string/Date or Date/string.");
2360
2361 Isolate *isolate = Isolate::GetCurrent();
2362
2363 const HandleScope handle_scope(isolate);
2364
2365 Local<Value> obs = args.This()->Get(String::NewFromUtf8(isolate, "observatory"));
2366 if (args.Length()>offset && args[offset]->IsString())
2367 obs = args[offset];
2368 if (args.Length()>offset+1 && args[offset+1]->IsString())
2369 obs = args[offset+1];
2370
2371 AstroArgs rc;
2372
2373 // For constructors, observatory can stay empty if not explicitly given
2374 if (offset<2)
2375 rc.obs = Nova::LnLatPosn::preset();
2376
2377 if (!obs.IsEmpty() && !obs->IsUndefined())
2378 rc.obs = *String::Utf8Value(obs);
2379
2380 rc.posn = rc.obs;
2381
2382 if ((!rc.obs.empty() || offset==0) && !rc.posn.isValid())
2383 throw runtime_error("Observatory "+rc.obs+" unknown.");
2384
2385 Local<Value> date = args.This()->Get(String::NewFromUtf8(isolate, "time"));
2386 if (args.Length()>offset && args[offset]->IsDate())
2387 date = args[offset];
2388 if (args.Length()>offset+1 && args[offset+1]->IsDate())
2389 date = args[offset+1];
2390
2391 // For constructors, time can stay empty if not explicitly given
2392 if (offset<2)
2393 rc.jsdate = Time().JavaDate();
2394
2395 if (!date.IsEmpty() && !date->IsUndefined())
2396 rc.jsdate = uint64_t(date->NumberValue());
2397
2398 rc.jd = Time(rc.jsdate/1000, rc.jsdate%1000).JD();
2399
2400 return rc;
2401}
2402
2403void InterpreterV8::LocalToSky(const Arguments &args)
2404{
2405 Isolate *isolate = Isolate::GetCurrent();
2406
2407 AstroArgs local;
2408 try
2409 {
2410 local = EvalAstroArgs(0, args, 2);
2411 }
2412 catch (const exception &e)
2413 {
2414 isolate->ThrowException(String::NewFromUtf8(isolate, e.what()));
2415 return;
2416 }
2417
2418 Nova::ZdAzPosn hrz;
2419 hrz.zd = GetDataMember(args, "zd");
2420 hrz.az = GetDataMember(args, "az");
2421
2422 if (!finite(hrz.zd) || !finite(hrz.az))
2423 {
2424 isolate->ThrowException(String::NewFromUtf8(isolate, "Zd and az must be finite."));
2425 return;
2426 }
2427
2428 const Nova::EquPosn equ = Nova::GetEquFromHrz(hrz, local.posn, local.jd);
2429
2430 const HandleScope handle_scope(isolate);
2431
2432 Local<Context> context = isolate->GetCurrentContext();
2433
2434 Handle<Value> arg_loc[] = { Number::New(isolate, hrz.zd), Number::New(isolate, hrz.az), String::NewFromUtf8(isolate, local.obs.c_str()), Date::New(isolate, local.jsdate) };
2435 MaybeLocal<Object> loc = fTemplateLocal->GetFunction()->NewInstance(context, 4, arg_loc);
2436
2437 Handle<Value> arg_sky[] = { Number::New(isolate, equ.ra/15), Number::New(isolate, equ.dec), loc.ToLocalChecked() };
2438 args.GetReturnValue().Set(fTemplateSky->GetFunction()->NewInstance(context, 3, arg_sky).ToLocalChecked());
2439}
2440
2441void InterpreterV8::SkyToLocal(const Arguments &args)
2442{
2443 Isolate *isolate = Isolate::GetCurrent();
2444
2445 AstroArgs local;
2446 try
2447 {
2448 local = EvalAstroArgs(0, args, 2);
2449 }
2450 catch (const exception &e)
2451 {
2452 isolate->ThrowException(String::NewFromUtf8(isolate, e.what()));
2453 return;
2454 }
2455
2456 Nova::EquPosn equ;
2457 equ.ra = GetDataMember(args, "ra")*15;
2458 equ.dec = GetDataMember(args, "dec");
2459
2460 if (!finite(equ.ra) || !finite(equ.dec))
2461 {
2462 isolate->ThrowException(String::NewFromUtf8(isolate, "Ra and dec must be finite."));
2463 return;
2464 }
2465
2466 const HandleScope handle_scope(isolate);
2467
2468 Local<Context> context = isolate->GetCurrentContext();
2469
2470 const Nova::ZdAzPosn hrz = Nova::GetHrzFromEqu(equ, local.posn, local.jd);
2471
2472 Handle<Value> arg[] = { Number::New(isolate, hrz.zd), Number::New(isolate, hrz.az), String::NewFromUtf8(isolate, local.obs.c_str()), Date::New(isolate, local.jsdate) };
2473 args.GetReturnValue().Set(fTemplateLocal->GetFunction()->NewInstance(context, 4, arg).ToLocalChecked());
2474}
2475
2476void InterpreterV8::MoonToLocal(const Arguments &args)
2477{
2478 Isolate *isolate = Isolate::GetCurrent();
2479
2480 AstroArgs local;
2481 try
2482 {
2483 local = EvalAstroArgs(0, args, 1);
2484 }
2485 catch (const exception &e)
2486 {
2487 isolate->ThrowException(String::NewFromUtf8(isolate, e.what()));
2488 return;
2489 }
2490
2491 Nova::EquPosn equ;
2492 equ.ra = GetDataMember(args, "ra")*15;
2493 equ.dec = GetDataMember(args, "dec");
2494
2495 if (!finite(equ.ra) || !finite(equ.dec))
2496 {
2497 isolate->ThrowException(String::NewFromUtf8(isolate, "Ra and dec must be finite."));
2498 return;
2499 }
2500
2501 const HandleScope handle_scope(isolate);
2502
2503 Local<Context> context = isolate->GetCurrentContext();
2504
2505 const Nova::ZdAzPosn hrz = Nova::GetHrzFromEqu(equ, local.posn, local.jd);
2506
2507 Handle<Value> arg[] = { Number::New(isolate, hrz.zd), Number::New(isolate, hrz.az), String::NewFromUtf8(isolate, local.obs.c_str()), Date::New(isolate, local.jsdate) };
2508 args.GetReturnValue().Set(fTemplateLocal->GetFunction()->NewInstance(context, 4, arg).ToLocalChecked());
2509}
2510
2511void InterpreterV8::ConstructorMoon(const Arguments &args)
2512{
2513 Isolate *isolate = Isolate::GetCurrent();
2514
2515 AstroArgs local;
2516 try
2517 {
2518 local = EvalAstroArgs(0, args, -1);
2519 }
2520 catch (const exception &e)
2521 {
2522 isolate->ThrowException(String::NewFromUtf8(isolate, e.what()));
2523 return;
2524 }
2525
2526 const Nova::EquPosn equ = Nova::GetLunarEquCoords(local.jd, 0.01);
2527
2528 const HandleScope handle_scope(isolate);
2529
2530 // ----------------------------
2531
2532 if (!args.IsConstructCall())
2533 {
2534 args.GetReturnValue().Set(Constructor(args));
2535 return;
2536 }
2537
2538 Handle<Function> function =
2539 FunctionTemplate::New(isolate, MoonToLocal)->GetFunction();
2540 if (function.IsEmpty())
2541 return;
2542
2543 Handle<Object> self = args.This();
2544 self->Set(String::NewFromUtf8(isolate, "ra"), Number::New(isolate, equ.ra/15)/*, ReadOnly*/);
2545 self->Set(String::NewFromUtf8(isolate, "dec"), Number::New(isolate, equ.dec)/*, ReadOnly*/);
2546 self->Set(String::NewFromUtf8(isolate, "toLocal"), function/*, ReadOnly*/);
2547 self->Set(String::NewFromUtf8(isolate, "time"), Date::New(isolate, local.jsdate)/*, ReadOnly*/);
2548
2549 args.GetReturnValue().Set(self);
2550}
2551
2552void InterpreterV8::ConstructorSky(const Arguments &args)
2553{
2554 Isolate *isolate = Isolate::GetCurrent();
2555
2556 if (args.Length()<2 || args.Length()>3)
2557 {
2558 isolate->ThrowException(String::NewFromUtf8(isolate, "Sky constructor takes two or three arguments."));
2559 return;
2560 }
2561
2562 if (args.Length()>2 && !args[2]->IsObject())
2563 {
2564 const string n = *String::Utf8Value(args[2]->ToObject()->GetConstructorName());
2565 if (n!="Local")
2566 {
2567 isolate->ThrowException(String::NewFromUtf8(isolate, "Third argument must be of type Local."));
2568 return;
2569 }
2570 }
2571
2572 const double ra = args[0]->NumberValue();
2573 const double dec = args[1]->NumberValue();
2574
2575 if (!finite(ra) || !finite(dec))
2576 {
2577 isolate->ThrowException(String::NewFromUtf8(isolate, "The first two arguments to Sky must be valid numbers."));
2578 return;
2579 }
2580
2581
2582 // ----------------------------
2583
2584 const HandleScope handle_scope(isolate);
2585
2586 if (!args.IsConstructCall())
2587 {
2588 args.GetReturnValue().Set(Constructor(args));
2589 return;
2590 }
2591
2592 Handle<Function> function =
2593 FunctionTemplate::New(isolate, SkyToLocal)->GetFunction();
2594 if (function.IsEmpty())
2595 return;
2596
2597 Handle<Object> self = args.This();
2598 self->Set(String::NewFromUtf8(isolate, "ra"), Number::New(isolate, ra)/*, ReadOnly*/);
2599 self->Set(String::NewFromUtf8(isolate, "dec"), Number::New(isolate, dec)/*, ReadOnly*/);
2600 self->Set(String::NewFromUtf8(isolate, "toLocal"), function/*, ReadOnly*/);
2601 if (args.Length()==3)
2602 self->Set(String::NewFromUtf8(isolate, "local"), args[2]/*, ReadOnly*/);
2603
2604 args.GetReturnValue().Set(self);
2605}
2606
2607void InterpreterV8::ConstructorLocal(const Arguments &args)
2608{
2609 Isolate *isolate = Isolate::GetCurrent();
2610
2611 AstroArgs local;
2612 try
2613 {
2614 local = EvalAstroArgs(2, args, 2);
2615 }
2616 catch (const exception &e)
2617 {
2618 isolate->ThrowException(String::NewFromUtf8(isolate, e.what()));
2619 return;
2620 }
2621
2622 const double zd = args[0]->NumberValue();
2623 const double az = args[1]->NumberValue();
2624
2625 if (!finite(zd) || !finite(az))
2626 {
2627 isolate->ThrowException(String::NewFromUtf8(isolate, "The first two arguments to Local must be valid numbers."));
2628 return;
2629 }
2630
2631 // --------------------
2632
2633 const HandleScope handle_scope(isolate);
2634
2635 if (!args.IsConstructCall())
2636 {
2637 args.GetReturnValue().Set(Constructor(args));
2638 return;
2639 }
2640
2641 Handle<Function> function = FunctionTemplate::New(isolate, LocalToSky)->GetFunction();
2642 if (function.IsEmpty())
2643 return;
2644
2645 Handle<Object> self = args.This();
2646 self->Set(String::NewFromUtf8(isolate, "zd"), Number::New(isolate, zd)/*, ReadOnly*/);
2647 self->Set(String::NewFromUtf8(isolate, "az"), Number::New(isolate, az)/*, ReadOnly*/);
2648 self->Set(String::NewFromUtf8(isolate, "toSky"), function/*, ReadOnly*/);
2649 if (!local.obs.empty())
2650 self->Set(String::NewFromUtf8(isolate, "observatory"), String::NewFromUtf8(isolate, local.obs.c_str())/*, ReadOnly*/);
2651 if (local.jsdate>0)
2652 self->Set(String::NewFromUtf8(isolate, "time"), Date::New(isolate, local.jsdate)/*, ReadOnly*/);
2653
2654 args.GetReturnValue().Set(self);
2655}
2656
2657Handle<Object> ConstructRiseSet(const AstroArgs &args, const Nova::RstTime &rst, const bool &rc)
2658{
2659 Isolate *isolate = Isolate::GetCurrent();
2660
2661 Handle<Object> obj = Object::New(isolate);
2662 obj->Set(String::NewFromUtf8(isolate, "time"), Date::New(isolate, args.jsdate)/*, ReadOnly*/);
2663 obj->Set(String::NewFromUtf8(isolate, "observatory"), String::NewFromUtf8(isolate, args.obs.c_str())/*, ReadOnly*/);
2664
2665 const bool isUp =
2666 (rst.rise<rst.set && (args.jd>rst.rise && args.jd<rst.set)) ||
2667 (rst.rise>rst.set && (args.jd<rst.set || args.jd>rst.rise));
2668
2669 obj->Set(String::NewFromUtf8(isolate, "isUp"), Boolean::New(isolate, isUp)/*, ReadOnly*/);
2670
2671 if (!rc) // circumpolar
2672 return obj;
2673
2674 Handle<Value> rise = Date::New(isolate, Time(rst.rise).JavaDate());
2675 Handle<Value> set = Date::New(isolate, Time(rst.set).JavaDate());
2676 Handle<Value> trans = Date::New(isolate, Time(rst.transit).JavaDate());
2677 if (rise.IsEmpty() || set.IsEmpty() || trans.IsEmpty())
2678 return Handle<Object>();
2679
2680 obj->Set(String::NewFromUtf8(isolate, "rise"), rise/*, ReadOnly*/);
2681 obj->Set(String::NewFromUtf8(isolate, "set"), set/*, ReadOnly*/);
2682 obj->Set(String::NewFromUtf8(isolate, "transit"), trans/*, ReadOnly*/);
2683
2684 return obj;
2685}
2686
2687void InterpreterV8::SunHorizon(const Arguments &args)
2688{
2689 Isolate *isolate = Isolate::GetCurrent();
2690
2691 AstroArgs local;
2692 try
2693 {
2694 local = EvalAstroArgs(1, args, 2);
2695 }
2696 catch (const exception &e)
2697 {
2698 isolate->ThrowException(String::NewFromUtf8(isolate, e.what()));
2699 return;
2700 }
2701
2702 const HandleScope handle_scope(isolate);
2703
2704 double hrz = NAN;
2705 if (args.Length()==0 || args[0]->IsNull())
2706 hrz = LN_SOLAR_STANDART_HORIZON;
2707 if (args.Length()>0 && args[0]->IsNumber())
2708 hrz = args[0]->NumberValue();
2709 if (args.Length()>0 && args[0]->IsString())
2710 {
2711 string arg(Tools::Trim(*String::Utf8Value(args[0])));
2712 transform(arg.begin(), arg.end(), arg.begin(), ::tolower);
2713
2714 if (arg==string("horizon").substr(0, arg.length()))
2715 hrz = LN_SOLAR_STANDART_HORIZON;
2716 if (arg==string("civil").substr(0, arg.length()))
2717 hrz = LN_SOLAR_CIVIL_HORIZON;
2718 if (arg==string("nautical").substr(0, arg.length()))
2719 hrz = LN_SOLAR_NAUTIC_HORIZON;
2720 if (arg==string("fact").substr(0, arg.length()))
2721 hrz = -13;
2722 if (arg==string("astronomical").substr(0, arg.length()))
2723 hrz = LN_SOLAR_ASTRONOMICAL_HORIZON;
2724 }
2725
2726 if (!finite(hrz))
2727 {
2728 isolate->ThrowException(String::NewFromUtf8(isolate, "First argument did not yield a valid number."));
2729 return;
2730 }
2731
2732 ln_rst_time sun;
2733 const bool rc = ln_get_solar_rst_horizon(local.jd-0.5, &local.posn, hrz, &sun)==0;
2734 Handle<Object> rst = ConstructRiseSet(local, sun, rc);
2735 rst->Set(String::NewFromUtf8(isolate, "horizon"), Number::New(isolate, hrz));
2736 args.GetReturnValue().Set(rst);
2737};
2738
2739void InterpreterV8::MoonHorizon(const Arguments &args)
2740{
2741 Isolate *isolate = Isolate::GetCurrent();
2742
2743 AstroArgs local;
2744 try
2745 {
2746 local = EvalAstroArgs(0, args, 2);
2747 }
2748 catch (const exception &e)
2749 {
2750 isolate->ThrowException(String::NewFromUtf8(isolate, e.what()));
2751 return;
2752 }
2753
2754 const HandleScope handle_scope(isolate);
2755
2756 ln_rst_time moon;
2757 const bool rc = ln_get_lunar_rst(local.jd-0.5, &local.posn, &moon)==0;
2758 Handle<Object> rst = ConstructRiseSet(local, moon, rc);
2759 args.GetReturnValue().Set(rst);
2760};
2761#endif
2762
2763// ==========================================================================
2764// Process control
2765// ==========================================================================
2766
2767bool InterpreterV8::HandleException(TryCatch& try_catch, const char *where)
2768{
2769 if (!try_catch.HasCaught() || !try_catch.CanContinue())
2770 return true;
2771
2772 Isolate *isolate = Isolate::GetCurrent();
2773
2774 const HandleScope handle_scope(isolate);
2775
2776 Handle<Value> except = try_catch.Exception();
2777 if (except.IsEmpty() || except->IsNull())
2778 return true;
2779
2780 const String::Utf8Value exception(except);
2781
2782 const Handle<Message> message = try_catch.Message();
2783 if (message.IsEmpty())
2784 return false;
2785
2786 ostringstream out;
2787
2788 if (!message->GetScriptResourceName()->IsUndefined())
2789 {
2790 // Print (filename):(line number): (message).
2791 const String::Utf8Value filename(message->GetScriptResourceName());
2792 if (filename.length()>0)
2793 {
2794 out << *filename;
2795 if (message->GetLineNumber()>0)
2796 out << ": l." << message->GetLineNumber();
2797 if (*exception)
2798 out << ": ";
2799 }
2800 }
2801
2802 if (*exception)
2803 out << *exception;
2804
2805 out << " [" << where << "]";
2806
2807 JsException(out.str());
2808
2809 // Print line of source code.
2810 const String::Utf8Value sourceline(message->GetSourceLine());
2811 if (*sourceline)
2812 JsException(*sourceline);
2813
2814 // Print wavy underline (GetUnderline is deprecated).
2815 const int start = message->GetStartColumn();
2816 const int end = message->GetEndColumn();
2817
2818 out.str("");
2819 if (start>0)
2820 out << setfill(' ') << setw(start) << ' ';
2821 out << setfill('^') << setw(end-start) << '^';
2822
2823 JsException(out.str());
2824
2825 const String::Utf8Value stack_trace(try_catch.StackTrace());
2826 if (stack_trace.length()<=0)
2827 return false;
2828
2829 if (!*stack_trace)
2830 return false;
2831
2832 const string trace(*stack_trace);
2833
2834 typedef boost::char_separator<char> separator;
2835 const boost::tokenizer<separator> tokenizer(trace, separator("\n"));
2836
2837 // maybe skip: " at internal:"
2838 // maybe skip: " at unknown source:"
2839
2840 auto it = tokenizer.begin();
2841 JsException("");
2842 while (it!=tokenizer.end())
2843 JsException(*it++);
2844
2845 return false;
2846}
2847
2848Handle<Value> InterpreterV8::ExecuteInternal(const string &code)
2849{
2850 Isolate *isolate = Isolate::GetCurrent();
2851
2852 // Try/catch and re-throw hides our internal code from
2853 // the displayed exception showing the origin and shows
2854 // the user function instead.
2855 TryCatch exception(isolate);
2856
2857 const Handle<Value> result = ExecuteCode(code);
2858
2859 // This hides the location of the exception in the internal code,
2860 // which is wanted.
2861 if (exception.HasCaught())
2862 exception.ReThrow();
2863
2864 return result;
2865}
2866
2867Handle<Value> InterpreterV8::ExecuteCode(const string &code, const string &file)
2868{
2869 Isolate *isolate = Isolate::GetCurrent();
2870
2871 EscapableHandleScope handle_scope(isolate);
2872
2873 MaybeLocal<String> source = String::NewFromUtf8(isolate, code.c_str(), NewStringType::kNormal, code.size());
2874 const Handle<String> origin = String::NewFromUtf8(isolate, file.c_str());
2875 if (source.IsEmpty())
2876 return Undefined(isolate);
2877
2878 ScriptOrigin sorigin(origin);
2879
2880 Local<Context> context = isolate->GetCurrentContext();
2881 MaybeLocal<Script> script = Script::Compile(context, source.ToLocalChecked(), &sorigin);
2882 if (script.IsEmpty())
2883 return Undefined(isolate);
2884
2885 const Handle<String> __date__ = String::NewFromUtf8(isolate, "__DATE__");
2886 const Handle<String> __file__ = String::NewFromUtf8(isolate, "__FILE__");
2887
2888 Handle<Value> save_date;
2889 Handle<Value> save_file;
2890
2891 //*NEW* FIMXE: context->Global() or isolate->GetCurrentContext()
2892 Handle<Object> global = /*Context::GetCurrent()*/context->Global();
2893 if (!global.IsEmpty())
2894 {
2895 struct stat attrib;
2896 if (stat(file.c_str(), &attrib)==0)
2897 {
2898 save_date = global->Get(__date__);
2899 save_file = global->Get(__file__);
2900
2901 global->Set(__file__, String::NewFromUtf8(isolate, file.c_str()));
2902
2903 const Local<Value> date = Date::New(isolate, attrib.st_mtime*1000);
2904 if (!date.IsEmpty())
2905 global->Set(__date__, date);
2906 }
2907 }
2908
2909 MaybeLocal<Value> rc = script.ToLocalChecked()->Run(context);
2910 if (rc.IsEmpty())
2911 return Undefined(isolate);
2912
2913 if (!global.IsEmpty() && !save_date.IsEmpty())
2914 {
2915 global->/*Force*/Set(__date__, save_date);
2916 global->/*Force*/Set(__file__, save_file);
2917 }
2918
2919 return handle_scope.Escape(rc.ToLocalChecked());
2920}
2921
2922void InterpreterV8::ExecuteConsole()
2923{
2924 WindowLog lout;
2925 lout << "\n " << kUnderline << " JavaScript interpreter " << kReset << " (enter '.q' to quit)\n" << endl;
2926
2927 Readline::StaticPushHistory("java.his");
2928
2929 string command;
2930 while (1)
2931 {
2932 Isolate *isolate = Isolate::GetCurrent();
2933
2934 // Create a local handle scope so that left-overs from single
2935 // console inputs will not fill up the memory
2936 const HandleScope handle_scope(isolate);
2937
2938 // Unlocking is necessary for the preemption to work
2939 const Unlocker global_unlock(isolate);
2940 const string buffer = Tools::Trim(Readline::StaticPrompt(command.empty() ? "JS> " : " \\> "));
2941 if (buffer==".q")
2942 break;
2943
2944 // buffer empty, do nothing
2945 if (buffer.empty())
2946 continue;
2947
2948 // Compose command
2949 if (!command.empty())
2950 command += ' ';
2951 command += buffer;
2952
2953 // If line ends with a backslash, allow addition of next line
2954 auto back = command.rbegin();
2955 if (*back=='\\')
2956 {
2957 *back = ' ';
2958 command = Tools::Trim(command);
2959 continue;
2960 }
2961
2962 // Locking is necessary to be able to execute java script code
2963 const Locker lock(isolate);
2964
2965 // Catch exceptions during code compilation
2966 TryCatch exception(isolate);
2967
2968 // Execute code which was entered
2969 const Handle<Value> rc = ExecuteCode(command, "console");
2970
2971 // If all went well and the result wasn't undefined then print
2972 // the returned value.
2973 if (!rc->IsUndefined() && !rc->IsFunction())
2974 JsResult(*String::Utf8Value(rc));
2975
2976 if (!HandleException(exception, "console"))
2977 lout << endl;
2978
2979 // command has been executed, collect new command
2980 command = "";
2981 }
2982
2983 lout << endl;
2984
2985 Readline::StaticPopHistory("java.his");
2986}
2987
2988// ==========================================================================
2989// CORE
2990// ==========================================================================
2991
2992InterpreterV8::InterpreterV8() : fMainThread(nullptr)
2993{
2994 const string ver(V8::GetVersion());
2995
2996 typedef boost::char_separator<char> separator;
2997 const boost::tokenizer<separator> tokenizer(ver, separator("."));
2998
2999 const vector<string> tok(tokenizer.begin(), tokenizer.end());
3000
3001 const int major = tok.size()>0 ? stol(tok[0]) : -1;
3002 const int minor = tok.size()>1 ? stol(tok[1]) : -1;
3003 const int build = tok.size()>2 ? stol(tok[2]) : -1;
3004
3005 if (major>3 || (major==3 && minor>9) || (major==3 && minor==9 && build>10))
3006 {
3007 const string argv = "--use_strict";
3008 V8::SetFlagsFromString(argv.c_str(), argv.size());
3009 }
3010
3011 /*
3012 const string argv1 = "--prof";
3013 const string argv2 = "--noprof-lazy";
3014
3015 V8::SetFlagsFromString(argv1.c_str(), argv1.size());
3016 V8::SetFlagsFromString(argv2.c_str(), argv2.size());
3017 */
3018
3019 if (!fPlatform)
3020 {
3021 // Initialize V8.
3022 V8::InitializeICU();
3023 //v8::V8::InitializeExternalStartupData(argv[0]);
3024 fPlatform = platform::NewDefaultPlatform();
3025 V8::InitializePlatform(fPlatform.get());
3026 V8::Initialize();
3027
3028 // Releases any resources used by v8 and stops any utility threads
3029 // that may be running. Note that disposing v8 is permanent,
3030 // it cannot be reinitialized.
3031 // It should generally not be necessary to dispose v8 before exiting
3032 // a process, this should happen automatically. It is only necessary
3033 // to use if the process needs the resources taken up by v8.
3034 //
3035 // v8::V8::Dispose();
3036 // v8::V8::ShutdownPlatform();
3037 }
3038
3039 This = this;
3040}
3041
3042Handle<Value> InterpreterV8::Constructor(const Arguments &args)
3043{
3044 vector<Handle<Value>> argv(args.Length());
3045
3046 for (int i=0; i<args.Length(); i++)
3047 argv[i] = args[i];
3048
3049 Local<Context> context = Isolate::GetCurrent()->GetCurrentContext();
3050 MaybeLocal<Value> obj = args.This()->CallAsConstructor(context, args.Length(), argv.data());
3051 if (obj.IsEmpty())
3052 return Undefined(Isolate::GetCurrent());
3053
3054 return obj.ToLocalChecked();
3055}
3056
3057
3058void InterpreterV8::AddFormatToGlobal()// const
3059{
3060 const string code =
3061 "String.form = function(str, arr)"
3062 "{"
3063 "var i = -1;"
3064 "function callback(exp, p0, p1, p2, p3, p4/*, pos, str*/)"
3065 "{"
3066 "if (exp=='%%')"
3067 "return '%';"
3068 ""
3069 "if (arr[++i]===undefined)"
3070 "return undefined;"
3071 ""
3072 "var exp = p2 ? parseInt(p2.substr(1)) : undefined;"
3073 "var base = p3 ? parseInt(p3.substr(1)) : undefined;"
3074 ""
3075 "var val;"
3076 "switch (p4)"
3077 "{"
3078 "case 's': val = arr[i]; break;"
3079 "case 'c': val = arr[i][0]; break;"
3080 "case 'f': val = parseFloat(arr[i]).toFixed(exp); break;"
3081 "case 'p': val = parseFloat(arr[i]).toPrecision(exp); break;"
3082 "case 'e': val = parseFloat(arr[i]).toExponential(exp); break;"
3083 "case 'x': val = parseInt(arr[i]).toString(base?base:16); break;"
3084 "case 'd': val = parseFloat(parseInt(arr[i], base?base:10).toPrecision(exp)).toFixed(0); break;"
3085 //"default:\n"
3086 //" throw new SyntaxError('Conversion specifier '+p4+' unknown.');\n"
3087 "}"
3088 ""
3089 "val = val==undefined || typeof(val)=='object' ? JSON.stringify(val) : val.toString(base);"
3090 ""
3091 "var sz = parseInt(p1); /* padding size */"
3092 "var ch = p1 && p1[0]=='0' ? '0' : ' '; /* isnull? */"
3093 "while (val.length<sz)"
3094 "val = p0 !== undefined ? val+ch : ch+val; /* isminus? */"
3095 ""
3096 "return val;"
3097 "}"
3098 ""
3099 "var regex = /%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd])/g;"
3100 "return str.replace(regex, callback);"
3101 "}"
3102 "\n"
3103 "String.prototype.$ = function()"
3104 "{"
3105 "return String.form(this, Array.prototype.slice.call(arguments));"
3106 "}"
3107 "\n"
3108 "String.prototype.count = function(c,i)"
3109 "{"
3110 "return (this.match(new RegExp(c,i?'gi':'g'))||[]).length;"
3111 "}"/*
3112 "\n"
3113 "var format = function()"
3114 "{"
3115 "return dim.format(arguments[0], Array.prototype.slice.call(arguments,1));"
3116 "}"*/;
3117
3118 Isolate *isolate = Isolate::GetCurrent();
3119
3120 // Create a string containing the JavaScript source code.
3121 const Local<String> source = String::NewFromUtf8(isolate, code.c_str(), v8::NewStringType::kNormal).ToLocalChecked();;
3122
3123 // Compile the source code.
3124 const Local<Script> script = Script::Compile(isolate->GetCurrentContext(), source).ToLocalChecked();
3125
3126 // Run the script to get the result.
3127 if (!script.IsEmpty())
3128 script->Run(isolate->GetCurrentContext()).IsEmpty(); // Is empty to avoid warning on usused return value
3129}
3130
3131void InterpreterV8::JsLoad(const std::string &)
3132{
3133 Readline::SetScriptDepth(1);
3134}
3135
3136void InterpreterV8::JsEnd(const std::string &)
3137{
3138 Readline::SetScriptDepth(0);
3139}
3140
3141// For debugging purposes only
3142// void BeforeCallEnteredCallbackF(Isolate*isolate) { cout << ">> " << isolate << endl; }
3143// void CallCompletedCallbackF(Isolate*isolate) { cout << "<< " << isolate << endl; }
3144
3145bool InterpreterV8::JsRun(const string &filename, const map<string, string> &map)
3146{
3147 JsPrint(string("JavaScript Engine V8 ")+V8::GetVersion());
3148 JsLoad(filename);
3149
3150 // Create a new Isolate and make it the current one.
3151 Isolate::CreateParams create_params;
3152 create_params.array_buffer_allocator = ArrayBuffer::Allocator::NewDefaultAllocator();
3153
3154 Isolate* isolate = Isolate::New(create_params);
3155
3156 // For debugging purposes only
3157 // isolate->AddBeforeCallEnteredCallback ( BeforeCallEnteredCallbackF);
3158 // isolate->AddCallCompletedCallback ( CallCompletedCallbackF);
3159
3160 {
3161 // #
3162 // # Fatal error in HandleScope::HandleScope
3163 // # Entering the V8 API without proper locking in place
3164 // #
3165 const Locker lock(isolate);
3166
3167 const Isolate::Scope isolate_scope(isolate);
3168
3169 // Create a stack-allocated handle scope.
3170 const HandleScope handle_scope(isolate);
3171
3172 // ===================================================================================
3173
3174 // Create a template for the global object.
3175 Handle<ObjectTemplate> dim = ObjectTemplate::New(isolate);
3176 dim->Set(String::NewFromUtf8(isolate, "log"), FunctionTemplate::New(isolate, WrapLog), ReadOnly);
3177 dim->Set(String::NewFromUtf8(isolate, "alarm"), FunctionTemplate::New(isolate, WrapAlarm), ReadOnly);
3178 dim->Set(String::NewFromUtf8(isolate, "wait"), FunctionTemplate::New(isolate, WrapWait), ReadOnly);
3179 dim->Set(String::NewFromUtf8(isolate, "send"), FunctionTemplate::New(isolate, WrapSend), ReadOnly);
3180 dim->Set(String::NewFromUtf8(isolate, "state"), FunctionTemplate::New(isolate, WrapState), ReadOnly);
3181 dim->Set(String::NewFromUtf8(isolate, "version"), Integer::New(isolate, DIM_VERSION_NUMBER), ReadOnly);
3182 dim->Set(String::NewFromUtf8(isolate, "getStates"), FunctionTemplate::New(isolate, WrapGetStates), ReadOnly);
3183 dim->Set(String::NewFromUtf8(isolate, "getDescription"), FunctionTemplate::New(isolate, WrapGetDescription), ReadOnly);
3184 dim->Set(String::NewFromUtf8(isolate, "getServices"), FunctionTemplate::New(isolate, WrapGetServices), ReadOnly);
3185
3186 Handle<ObjectTemplate> dimctrl = ObjectTemplate::New(isolate);
3187 dimctrl->Set(String::NewFromUtf8(isolate, "defineState"), FunctionTemplate::New(isolate, WrapNewState), ReadOnly);
3188 dimctrl->Set(String::NewFromUtf8(isolate, "setState"), FunctionTemplate::New(isolate, WrapSetState), ReadOnly);
3189 dimctrl->Set(String::NewFromUtf8(isolate, "getState"), FunctionTemplate::New(isolate, WrapGetState), ReadOnly);
3190 dimctrl->Set(String::NewFromUtf8(isolate, "setInterruptHandler"), FunctionTemplate::New(isolate, WrapSetInterrupt), ReadOnly);
3191 dimctrl->Set(String::NewFromUtf8(isolate, "triggerInterrupt"), FunctionTemplate::New(isolate, WrapTriggerInterrupt), ReadOnly);
3192
3193 Handle<ObjectTemplate> v8 = ObjectTemplate::New(isolate);
3194 v8->Set(String::NewFromUtf8(isolate, "sleep"), FunctionTemplate::New(isolate, WrapSleep), ReadOnly);
3195 v8->Set(String::NewFromUtf8(isolate, "timeout"), FunctionTemplate::New(isolate, WrapTimeout), ReadOnly);
3196 v8->Set(String::NewFromUtf8(isolate, "version"), String::NewFromUtf8(isolate, V8::GetVersion()), ReadOnly);
3197
3198 Handle<ObjectTemplate> console = ObjectTemplate::New(isolate);
3199 console->Set(String::NewFromUtf8(isolate, "out"), FunctionTemplate::New(isolate, WrapOut), ReadOnly);
3200 console->Set(String::NewFromUtf8(isolate, "warn"), FunctionTemplate::New(isolate, WrapWarn), ReadOnly);
3201
3202 Handle<ObjectTemplate> onchange = ObjectTemplate::New(isolate);
3203 //onchange->SetNamedPropertyHandler(OnChangeGet, WrapOnChangeSet);
3204 onchange->SetHandler(v8::NamedPropertyHandlerConfiguration(OnChangeGet, WrapOnChangeSet));
3205 dim->Set(String::NewFromUtf8(isolate, "onchange"), onchange);
3206
3207 Handle<ObjectTemplate> global = ObjectTemplate::New(isolate);
3208 global->Set(String::NewFromUtf8(isolate, "v8"), v8, ReadOnly);
3209 global->Set(String::NewFromUtf8(isolate, "dim"), dim, ReadOnly);
3210 global->Set(String::NewFromUtf8(isolate, "dimctrl"), dimctrl, ReadOnly);
3211 global->Set(String::NewFromUtf8(isolate, "console"), console, ReadOnly);
3212 global->Set(String::NewFromUtf8(isolate, "include"), FunctionTemplate::New(isolate, WrapInclude), ReadOnly);
3213 global->Set(String::NewFromUtf8(isolate, "exit"), FunctionTemplate::New(isolate, WrapExit), ReadOnly);
3214
3215 Handle<FunctionTemplate> sub = FunctionTemplate::New(isolate, WrapSubscription);
3216 sub->SetClassName(String::NewFromUtf8(isolate, "Subscription"));
3217 sub->InstanceTemplate()->SetInternalFieldCount(1);
3218 global->Set(String::NewFromUtf8(isolate, "Subscription"), sub, ReadOnly);
3219
3220#ifdef HAVE_SQL
3221 Handle<FunctionTemplate> db = FunctionTemplate::New(isolate, WrapDatabase);
3222 db->SetClassName(String::NewFromUtf8(isolate, "Database"));
3223 db->InstanceTemplate()->SetInternalFieldCount(1);
3224 global->Set(String::NewFromUtf8(isolate, "Database"), db, ReadOnly);
3225#endif
3226
3227 Handle<FunctionTemplate> thread = FunctionTemplate::New(isolate, WrapThread);
3228 thread->SetClassName(String::NewFromUtf8(isolate, "Thread"));
3229 global->Set(String::NewFromUtf8(isolate, "Thread"), thread, ReadOnly);
3230
3231 Handle<FunctionTemplate> file = FunctionTemplate::New(isolate, WrapFile);
3232 file->SetClassName(String::NewFromUtf8(isolate, "File"));
3233 global->Set(String::NewFromUtf8(isolate, "File"), file, ReadOnly);
3234
3235 Handle<FunctionTemplate> evt = FunctionTemplate::New(isolate);
3236 evt->SetClassName(String::NewFromUtf8(isolate, "Event"));
3237 global->Set(String::NewFromUtf8(isolate, "Event"), evt, ReadOnly);
3238
3239 Handle<FunctionTemplate> desc = FunctionTemplate::New(isolate);
3240 desc->SetClassName(String::NewFromUtf8(isolate, "Description"));
3241 global->Set(String::NewFromUtf8(isolate, "Description"), desc, ReadOnly);
3242
3243 fTemplateEvent = evt;
3244 fTemplateDescription = desc;
3245
3246#ifdef HAVE_MAILX
3247 Handle<FunctionTemplate> mail = FunctionTemplate::New(isolate, ConstructorMail);
3248 mail->SetClassName(String::NewFromUtf8(isolate, "Mail"));
3249 global->Set(String::NewFromUtf8(isolate, "Mail"), mail, ReadOnly);
3250#endif
3251
3252#ifdef HAVE_CURL
3253 Handle<FunctionTemplate> curl = FunctionTemplate::New(isolate, ConstructorCurl);
3254 curl->SetClassName(String::NewFromUtf8(isolate, "Curl"));
3255 global->Set(String::NewFromUtf8(isolate, "Curl"), curl, ReadOnly);
3256#endif
3257
3258#ifdef HAVE_NOVA
3259 Handle<FunctionTemplate> sky = FunctionTemplate::New(isolate, ConstructorSky);
3260 sky->SetClassName(String::NewFromUtf8(isolate, "Sky"));
3261 sky->Set(String::NewFromUtf8(isolate, "dist"), FunctionTemplate::New(isolate, SkyDist), ReadOnly);
3262 global->Set(String::NewFromUtf8(isolate, "Sky"), sky, ReadOnly);
3263
3264 Handle<FunctionTemplate> loc = FunctionTemplate::New(isolate, ConstructorLocal);
3265 loc->SetClassName(String::NewFromUtf8(isolate, "Local"));
3266 loc->Set(String::NewFromUtf8(isolate, "dist"), FunctionTemplate::New(isolate, LocalDist), ReadOnly);
3267 global->Set(String::NewFromUtf8(isolate, "Local"), loc, ReadOnly);
3268
3269 Handle<FunctionTemplate> moon = FunctionTemplate::New(isolate, ConstructorMoon);
3270 moon->SetClassName(String::NewFromUtf8(isolate, "Moon"));
3271 moon->Set(String::NewFromUtf8(isolate, "disk"), FunctionTemplate::New(isolate, MoonDisk), ReadOnly);
3272 moon->Set(String::NewFromUtf8(isolate, "horizon"), FunctionTemplate::New(isolate, MoonHorizon), ReadOnly);
3273 global->Set(String::NewFromUtf8(isolate, "Moon"), moon, ReadOnly);
3274
3275 Handle<FunctionTemplate> sun = FunctionTemplate::New(isolate);
3276 sun->SetClassName(String::NewFromUtf8(isolate, "Sun"));
3277 sun->Set(String::NewFromUtf8(isolate, "horizon"), FunctionTemplate::New(isolate, SunHorizon), ReadOnly);
3278 global->Set(String::NewFromUtf8(isolate, "Sun"), sun, ReadOnly);
3279
3280 fTemplateLocal = loc;
3281 fTemplateSky = sky;
3282#endif
3283
3284 // ===================================================================================
3285
3286 // Create a new context with "global" as contents
3287 Local<Context> context = Context::New(isolate, nullptr, global);
3288 if (context.IsEmpty())
3289 {
3290 JsException("Creation of global context failed...");
3291 JsEnd(filename);
3292 return false;
3293 }
3294
3295 // Switch off eval(). It is not possible to track it's exceptions.
3296 context->AllowCodeGenerationFromStrings(false);
3297
3298 // Enter the context for compiling and running the hello world script.
3299 const Context::Scope scope(context);
3300
3301 // ===================================================================================
3302
3303 Handle<Array> args = Array::New(isolate, map.size());
3304 for (auto it=map.begin(); it!=map.end(); it++)
3305 args->Set(String::NewFromUtf8(isolate, it->first.c_str()), String::NewFromUtf8(isolate, it->second.c_str()));
3306
3307 context->Global()->Set(String::NewFromUtf8(isolate, "$"), args/*, ReadOnly*/);
3308 context->Global()->Set(String::NewFromUtf8(isolate, "arg"), args/*, ReadOnly*/);
3309
3310 const Local<Value> starttime = Date::New(isolate, Time().JavaDate());
3311 if (!starttime.IsEmpty())
3312 context->Global()->Set(String::NewFromUtf8(isolate, "__START__"), starttime/*, ReadOnly*/);
3313
3314 //V8::ResumeProfiler();
3315
3316 TryCatch exception(isolate);
3317
3318 AddFormatToGlobal();
3319
3320 // ===================================================================================
3321
3322 if (!exception.HasCaught())
3323 {
3324#if 0
3325 // Create a string containing the JavaScript source code.
3326 v8::Local<v8::String> source =
3327 v8::String::NewFromUtf8(isolate, "var x=5; 'Hello' + ', World!'+x", v8::NewStringType::kNormal).ToLocalChecked();
3328
3329 // Compile the source code.
3330 v8::Local<v8::Script> script =
3331 v8::Script::Compile(context, source).ToLocalChecked();
3332
3333 // Run the script to get the result.
3334 v8::Local<v8::Value> result =
3335 script->Run(context).ToLocalChecked();
3336
3337 // Convert the result to an UTF8 string and print it.
3338 v8::String::Utf8Value utf8(isolate, result);
3339 printf("%s\n", *utf8);
3340#endif
3341
3342 JsStart(filename);
3343
3344// Locker::StartPreemption(10);
3345
3346 // We are ready to go an can allow other threads to run...
3347 fMainThread = isolate;
3348
3349 if (filename.empty())
3350 {
3351 JsSetState(3);
3352 ExecuteConsole();
3353 }
3354 else
3355 {
3356 // We call script->Run because it is the only way to
3357 // catch exceptions.
3358 const Handle<String> source = String::NewFromUtf8(isolate, ("include('"+filename+"');").c_str());
3359 const Handle<String> origin = String::NewFromUtf8(isolate, "main");
3360 const Handle<Script> script = Script::Compile(source, origin);
3361 if (!script.IsEmpty())
3362 {
3363 JsSetState(3);
3364 script->Run();
3365 }
3366 }
3367
3368 // Before releasing the Lock, signal all other threads not to run again
3369 fMainThread = 0;
3370
3371 // Locker::StopPreemption();
3372 }
3373
3374 // Handle an exception
3375 HandleException(exception, "main");
3376 }
3377
3378 // Just to be on the safe side:
3379 // Terminate all other threads once they try to run
3380 isolate->AddBeforeCallEnteredCallback(TerminateExecution);
3381
3382 // Wait until all threads have finished so that we can safely(?) proceed
3383 while (isolate->IsInUse())
3384 usleep(50);
3385
3386 // The threads are started already and wait to get the lock
3387 // So we have to unlock (manual preemtion) so that they get
3388 // the signal to terminate.
3389 //{
3390 // const Unlocker unlock(isolate);
3391 for (auto it=fThreads.begin(); it!=fThreads.end(); it++)
3392 it->join();
3393 fThreads.clear();
3394 //}
3395
3396 // Now we can dispose the persistent interrupt handlers
3397 fInterruptCallback.Reset();
3398
3399 // Now we can dispose all persistent handles from state callbacks
3400 fStateCallbacks.clear();
3401
3402 // ... and from the onchange callbacks
3403 fReverseMap.clear();
3404
3405#ifdef HAVE_SQL
3406 // ...and close all database handles
3407 for (auto it=fDatabases.begin(); it!=fDatabases.end(); it++)
3408 delete *it;
3409 fDatabases.clear();
3410#endif
3411
3412 //fStates.clear();
3413
3414 isolate->Dispose();
3415
3416 delete create_params.array_buffer_allocator;
3417 create_params.array_buffer_allocator = 0;
3418
3419 JsEnd(filename);
3420
3421 return 0;
3422}
3423
3424void InterpreterV8::JsStop()
3425{
3426 Isolate *isolate = This ? This->fMainThread : nullptr;
3427 if (!isolate)
3428 return;
3429
3430 // Terminate the main thread immediately
3431 isolate->TerminateExecution();
3432 // Terminate all other threads once they try to run
3433 isolate->AddBeforeCallEnteredCallback(TerminateExecution);
3434}
3435
3436vector<string> InterpreterV8::JsGetCommandList(const char *, int) const
3437{
3438 vector<string> rc;
3439
3440 rc.emplace_back("for (");
3441 rc.emplace_back("while (");
3442 rc.emplace_back("if (");
3443 rc.emplace_back("switch (");
3444 rc.emplace_back("case ");
3445 rc.emplace_back("var ");
3446 rc.emplace_back("function ");
3447 rc.emplace_back("Date(");
3448 rc.emplace_back("new Date(");
3449 rc.emplace_back("'use strict';");
3450 rc.emplace_back("undefined");
3451 rc.emplace_back("null");
3452 rc.emplace_back("delete ");
3453 rc.emplace_back("JSON.stringify(");
3454 rc.emplace_back("JSON.parse(");
3455
3456 rc.emplace_back("dim.log(");
3457 rc.emplace_back("dim.alarm(");
3458 rc.emplace_back("dim.wait(");
3459 rc.emplace_back("dim.send(");
3460 rc.emplace_back("dim.state(");
3461 rc.emplace_back("dim.version");
3462 rc.emplace_back("dim.getStates(");
3463 rc.emplace_back("dim.getDescription(");
3464 rc.emplace_back("dim.getServices(");
3465
3466 rc.emplace_back("dimctrl.defineState(");
3467 rc.emplace_back("dimctrl.setState(");
3468 rc.emplace_back("dimctrl.getState(");
3469 rc.emplace_back("dimctrl.setInterruptHandler(");
3470 rc.emplace_back("dimctrl.triggerInterrupt(");
3471
3472 rc.emplace_back("v8.sleep(");
3473 rc.emplace_back("v8.timeout(");
3474 rc.emplace_back("v8.version");
3475
3476 rc.emplace_back("console.out(");
3477 rc.emplace_back("console.warn(");
3478
3479 rc.emplace_back("include(");
3480 rc.emplace_back("exit()");
3481
3482#ifdef HAVE_SQL
3483 rc.emplace_back("Database(");
3484 rc.emplace_back("new Database(");
3485
3486 rc.emplace_back(".table");
3487 rc.emplace_back(".user");
3488 rc.emplace_back(".database");
3489 rc.emplace_back(".port");
3490 rc.emplace_back(".query");
3491#endif
3492
3493 rc.emplace_back("Subscription(");
3494 rc.emplace_back("new Subscription(");
3495
3496 rc.emplace_back("Thread(");
3497 rc.emplace_back("new Thread(");
3498
3499 rc.emplace_back("File(");
3500 rc.emplace_back("new File(");
3501
3502 rc.emplace_back("Event(");
3503 rc.emplace_back("new Event(");
3504
3505 rc.emplace_back("Description(");
3506 rc.emplace_back("new Description(");
3507
3508#ifdef HAVE_MAILX
3509 rc.emplace_back("Mail(");
3510 rc.emplace_back("new Mail(");
3511
3512 rc.emplace_back(".subject");
3513 rc.emplace_back(".receipients");
3514 rc.emplace_back(".attachments");
3515 rc.emplace_back(".bcc");
3516 rc.emplace_back(".cc");
3517 rc.emplace_back(".text");
3518 rc.emplace_back(".send(");
3519#endif
3520
3521#ifdef HAVE_CURL
3522 rc.emplace_back("Curl(");
3523 rc.emplace_back("new Curl(");
3524
3525 rc.emplace_back(".url");
3526 rc.emplace_back(".user");
3527 rc.emplace_back(".data");
3528// rc.emplace_back(".send("); -> MAILX
3529#endif
3530
3531#ifdef HAVE_NOVA
3532 rc.emplace_back("Sky(");
3533 rc.emplace_back("new Sky(");
3534
3535 rc.emplace_back("Sky.dist");
3536 rc.emplace_back("Local(");
3537
3538 rc.emplace_back("new Local(");
3539 rc.emplace_back("Local.dist");
3540
3541 rc.emplace_back("Moon(");
3542 rc.emplace_back("new Moon(");
3543 rc.emplace_back("Moon.disk(");
3544 rc.emplace_back("Moon.horizon(");
3545
3546 rc.emplace_back("Sun.horizon(");
3547
3548 rc.emplace_back(".zd");
3549 rc.emplace_back(".az");
3550 rc.emplace_back(".ra");
3551 rc.emplace_back(".dec");
3552
3553 rc.emplace_back(".toLocal(");
3554 rc.emplace_back(".toSky(");
3555 rc.emplace_back(".rise");
3556 rc.emplace_back(".set");
3557 rc.emplace_back(".transit");
3558 rc.emplace_back(".isUp");
3559
3560 rc.emplace_back("horizon");
3561 rc.emplace_back("civil");
3562 rc.emplace_back("nautical");
3563 rc.emplace_back("astronomical");
3564#endif
3565
3566 rc.emplace_back(".server");
3567 rc.emplace_back(".service");
3568 rc.emplace_back(".name");
3569 rc.emplace_back(".isCommand");
3570 rc.emplace_back(".format");
3571 rc.emplace_back(".description");
3572 rc.emplace_back(".unit");
3573 rc.emplace_back(".delim");
3574 rc.emplace_back(".isOpen");
3575
3576 rc.emplace_back(".qos");
3577 rc.emplace_back(".size");
3578 rc.emplace_back(".counter");
3579 rc.emplace_back(".type");
3580 rc.emplace_back(".obj");
3581 rc.emplace_back(".data");
3582 rc.emplace_back(".comment");
3583 rc.emplace_back(".index");
3584 rc.emplace_back(".time");
3585 rc.emplace_back(".close()");
3586 rc.emplace_back(".onchange");
3587 rc.emplace_back(".get(");
3588
3589
3590 rc.emplace_back("__DATE__");
3591 rc.emplace_back("__FILE__");
3592
3593 return rc;
3594}
3595
3596#endif
3597
3598InterpreterV8 *InterpreterV8::This = 0;
3599unique_ptr<v8::Platform> InterpreterV8::fPlatform;
Note: See TracBrowser for help on using the repository browser.