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

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