source: trunk/FACT++/src/InterpreterV8.cc@ 18424

Last change on this file since 18424 was 18383, checked in by Daniela Dorner, 9 years ago
fixed bug in interrupt that made dimserver crash
File size: 92.3 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
13#ifdef HAVE_NOVA
14#include "externals/nova.h"
15#endif
16
17#ifdef HAVE_SQL
18#include "Database.h"
19#endif
20
21#include <v8.h>
22
23#include "dim.h"
24#include "tools.h"
25#include "Readline.h"
26#include "externals/izstream.h"
27
28#include "WindowLog.h"
29
30using namespace std;
31using namespace v8;
32
33v8::Handle<v8::FunctionTemplate> InterpreterV8::fTemplateLocal;
34v8::Handle<v8::FunctionTemplate> InterpreterV8::fTemplateSky;
35v8::Handle<v8::FunctionTemplate> InterpreterV8::fTemplateEvent;
36v8::Handle<v8::FunctionTemplate> InterpreterV8::fTemplateDescription;
37//v8::Handle<v8::FunctionTemplate> InterpreterV8::fTemplateDatabase;
38
39
40// ==========================================================================
41// Some documentation
42// ==========================================================================
43//
44// Threads:
45// --------
46// In most cases Js* and other calls to native C++ code could be wrapped
47// with an Unlocker to allow possible other JavaScipt 'threads' to run
48// during that time. However, all of these calls should take much less than
49// the preemption time of 10ms, so it would just be a waste of tim.
50//
51// Termination:
52// ------------
53// Each thread running V8 code needs to be signalled individually for
54// termination. Therefor a list of V8 thread ids is created.
55//
56// If termination has already be signalled, no thread should start running
57// anymore (thy could, e.g., wait for their locking). So after locking
58// it has to be checked if the thread was terminated already. Note
59// that all calls to Terminate() must be locked to ensure that fThreadId
60// is correct when it is checked.
61//
62// The current thread id must be added to fThreadIds _before_ any
63// function is called after Locking and before execution is given
64// back to JavaScript, e.g. in script->Run(). So until the thread
65// is added to the list Terminate will not be executed. If Terminate
66// is then executed, it is ensured that the current thread is
67// already in the list. If terminate has been called before
68// the Locking, the check for the validiy of fThreadId ensures that
69// nothing is executed.
70//
71// Empty handles:
72// --------------
73// If exceution is terminated, V8 calls might return with empty handles,
74// e.g. Date::New(). Therefore, the returned handles of these calls have to
75// be checked in all placed to avoid that V8 will core dump.
76//
77// HandleScope:
78// ------------
79// A handle scope is a garbage collector and collects all handles created
80// until it goes out of scope. Handles which are not needed anymore are
81// then deleted. To return a handle from a HandleScope you need to use
82// Close(). E.g., String::AsciiValue does not create a new handle and
83// hence does not need a HandleScope. Any ::New will need a handle scope.
84// Forgetting the HandleScope could in principle fill your memory,
85// but everything is properly deleted by the global HandleScope at
86// script termination.
87//
88// Here is another good reference for v8, also containing some
89// good explanations for the meaning of handles, persistent handles
90// and weak handles: http://create.tpsitulsa.com/wiki/V8_Cookbook
91//
92// ==========================================================================
93// Simple interface
94// ==========================================================================
95
96Handle<Value> InterpreterV8::FuncExit(const Arguments &)
97{
98 V8::TerminateExecution(fThreadId);
99
100 // we have to throw an excption to make sure that the
101 // calling thread does not go on executing until it
102 // has realized that it should terminate
103 return ThrowException(Null());
104}
105
106Handle<Value> InterpreterV8::FuncSleep(const Arguments& args)
107{
108 if (args.Length()==0)
109 {
110 // Theoretically, the CPU usage can be reduced by maybe a factor
111 // of four using a larger value, but this also means that the
112 // JavaScript is locked for a longer time.
113 const Unlocker unlock;
114 usleep(1000);
115 return Undefined();
116 }
117
118 if (args.Length()!=1)
119 return ThrowException(String::New("Number of arguments must be exactly 1."));
120
121 if (!args[0]->IsUint32())
122 return ThrowException(String::New("Argument 1 must be an uint32."));
123
124 // Using a Javascript function has the advantage that it is fully
125 // interruptable without the need of C++ code
126 const string code =
127 "(function(){"
128 "var t=new Date();"
129 "while ((new Date()-t)<"+to_string(args[0]->Int32Value())+") v8.sleep();"
130 "})();";
131
132 return ExecuteInternal(code);
133}
134
135Handle<Value> InterpreterV8::FuncTimeout(const Arguments &args)
136{
137 if (args.Length()<2)
138 return ThrowException(String::New("Number of arguments must be at least two."));
139
140 if (!args[0]->IsNull() && !args[0]->IsInt32())
141 return ThrowException(String::New("Argument 0 not null and not an int32."));
142
143 if (!args[1]->IsFunction())
144 return ThrowException(String::New("Argument 1 not a function."));
145
146 if (args.Length()>2 && !args[2]->IsObject())
147 return ThrowException(String::New("Argument 2 not an object."));
148
149 const int32_t timeout = args[0]->IsNull() ? 0 : args[0]->Int32Value();
150 const bool null = args[0]->IsNull();
151
152 HandleScope handle_scope;
153
154 Handle<Function> func = Handle<Function>::Cast(args[1]);
155
156 const int nn = args.Length()==2 ? 0 : args.Length()-3;
157
158 Handle<Value> argv[nn];
159 for (int i=0; i<nn; i++)
160 argv[i] = args[i+3];
161
162 Time t;
163 while (1)
164 {
165 const Handle<Value> rc = args.Length()<3 ? func->Call(func, nn, argv) : func->Call(args[2]->ToObject(), nn, argv);
166 if (rc.IsEmpty())
167 return Undefined();
168
169 if (!rc->IsUndefined())
170 return handle_scope.Close(rc);
171
172 if (!null && Time()-t>=boost::posix_time::milliseconds(abs(timeout)))
173 break;
174
175 // Theoretically, the CPU usage can be reduced by maybe a factor
176 // of four using a larger value, but this also means that the
177 // JavaScript is locked for a longer time.
178 const Unlocker unlock;
179 usleep(1000);
180 }
181
182 if (timeout<0)
183 return Undefined();
184
185 const string str = "Waiting for func to return a defined value timed out.";
186 return ThrowException(String::New(str.c_str()));
187}
188
189void InterpreterV8::Thread(int &id, Persistent<Object> _this, Persistent<Function> func, uint32_t ms)
190{
191 const Locker lock;
192
193 if (fThreadId<0)
194 {
195 id = -1;
196 return;
197 }
198
199 // Warning: As soon as id is set, the parent of this thread might terminate
200 // and hance the reference to id does not exist anymore. So, id
201 // is just a kind of return value and must not be used at all
202 // otherwise.
203
204 const int id_local = V8::GetCurrentThreadId();
205 id = id_local;
206 fThreadIds.insert(id_local);
207
208 const HandleScope handle_scope;
209
210 func->CreationContext()->Enter();
211
212 TryCatch exception;
213
214 const bool rc = ms==0 || !ExecuteInternal("v8.sleep("+to_string(ms)+");").IsEmpty();
215 if (rc)
216 {
217 if (_this.IsEmpty())
218 func->Call(func, 0, NULL);
219 else
220 func->Call(_this, 0, NULL);
221 }
222
223 func.Dispose();
224 _this.Dispose();
225
226 fThreadIds.erase(id_local);
227
228 if (!HandleException(exception, "thread"))
229 V8::TerminateExecution(fThreadId);
230
231 func->CreationContext()->Exit();
232}
233
234Handle<Value> InterpreterV8::FuncThread(const Arguments& args)
235{
236 if (!args.IsConstructCall())
237 return ThrowException(String::New("Thread must be called as constructor."));
238
239 if (args.Length()!=2 && args.Length()!=3)
240 return ThrowException(String::New("Number of arguments must be two or three."));
241
242 if (!args[0]->IsUint32())
243 return ThrowException(String::New("Argument 0 not an uint32."));
244
245 if (!args[1]->IsFunction())
246 return ThrowException(String::New("Argument 1 not a function."));
247
248 if (args.Length()==3 && !args[2]->IsObject())
249 return ThrowException(String::New("Argument 2 not an object."));
250
251 //if (!args.IsConstructCall())
252 // return Constructor(args);
253
254 const HandleScope handle_scope;
255
256 Handle<Function> handle = Handle<Function>::Cast(args[1]);
257
258 Persistent<Function> func = Persistent<Function>::New(handle);
259 Persistent<Object> _this;
260 if (args.Length()==3)
261 _this = Persistent<Object>::New(args[2]->ToObject());
262
263 const uint32_t ms = args[0]->Uint32Value();
264
265 int id=-2;
266 fThreads.push_back(thread(bind(&InterpreterV8::Thread, this, ref(id), _this, func, ms)));
267 {
268 // Allow the thread to lock, so we can get the thread id.
269 const Unlocker unlock;
270 while (id==-2)
271 usleep(1);
272 }
273
274 Handle<Object> self = args.This();
275
276 self->Set(String::New("id"), Integer::NewFromUnsigned(id), ReadOnly);
277 self->Set(String::New("kill"), FunctionTemplate::New(WrapKill)->GetFunction(), ReadOnly);
278
279 return Undefined();
280}
281
282Handle<Value> InterpreterV8::FuncKill(const Arguments& args)
283{
284 const uint32_t id = args.This()->Get(String::New("id"))->Uint32Value();
285
286 V8::TerminateExecution(id);
287
288 return Boolean::New(fThreadIds.erase(id));
289}
290
291Handle<Value> InterpreterV8::FuncSend(const Arguments& args)
292{
293 if (args.Length()==0)
294 return ThrowException(String::New("Number of arguments must be at least 1."));
295
296 if (!args[0]->IsString())
297 return ThrowException(String::New("Argument 1 must be a string."));
298
299 const String::AsciiValue str(args[0]);
300
301 string command = *str;
302
303 if (command.length()==0)
304 return ThrowException(String::New("Server name empty."));
305
306 if (args.Length()==0)
307 {
308 if (command.find_first_of('/')==string::npos)
309 command += "/";
310 }
311
312 // Escape all string arguments. All others can be kept as they are.
313 for (int i=1; i<args.Length(); i++)
314 {
315 string arg = *String::AsciiValue(args[i]);
316
317 // Escape string
318 if (args[i]->IsString())
319 {
320 boost::replace_all(arg, "\\", "\\\\");
321 boost::replace_all(arg, "'", "\\'");
322 boost::replace_all(arg, "\"", "\\\"");
323 }
324
325 command += " "+arg;
326 }
327
328 try
329 {
330 return Boolean::New(JsSend(command));
331 }
332 catch (const runtime_error &e)
333 {
334 return ThrowException(String::New(e.what()));
335 }
336}
337
338// ==========================================================================
339// State control
340// ==========================================================================
341
342Handle<Value> InterpreterV8::FuncWait(const Arguments& args)
343{
344 if (args.Length()!=2 && args.Length()!=3)
345 return ThrowException(String::New("Number of arguments must be 2 or 3."));
346
347 if (!args[0]->IsString())
348 return ThrowException(String::New("Argument 1 not a string."));
349
350 if (!args[1]->IsInt32() && !args[1]->IsString())
351 return ThrowException(String::New("Argument 2 not an int32 and not a string."));
352
353 if (args.Length()==3 && !args[2]->IsInt32() && !args[2]->IsUndefined())
354 return ThrowException(String::New("Argument 3 not an int32 and not undefined."));
355
356 // Using a Javascript function has the advantage that it is fully
357 // interruptable without the need of C++ code
358
359 const string index = args[1]->IsInt32() ? "s.index" : "s.name";
360 const bool timeout = args.Length()==3 && !args[2]->IsUndefined();
361 const string arg0 = *String::AsciiValue(args[0]);
362 const string state = args[1]->IsString() ? *String::AsciiValue(args[1]) : "";
363 const string arg1 = args[1]->IsString() ? ("\""+state+"\"") : to_string(args[1]->Int32Value());
364 const bool isNot = arg0[0]=='!';
365 const string name = isNot ? arg0.substr(1) : arg0;
366
367 if (arg0.find_first_of("\"'")!=string::npos)
368 return ThrowException(String::New("Server name must not contain quotation marks."));
369
370 if (args[1]->IsString())
371 if (state.find_first_of("\"'")!=string::npos)
372 return ThrowException(String::New("State name must not contain quotation marks."));
373
374 string code = "(function(name,state,ms)"
375 "{";
376 if (timeout)
377 code += "var t = new Date();";
378 code += "while (1)"
379 "{"
380 "var s = dim.state(name);"
381 "if(!s)throw new Error('Waiting for state "+arg1+" of server "+arg0+" failed.');";
382 if (isNot)
383 code +=
384 "if(state!="+index+")return true;";
385 else
386 code +=
387 "if(state=="+index+")return true;";
388 if (timeout)
389 code += "if((new Date()-t)>Math.abs(ms))break;";
390
391 code += "v8.sleep();"
392 "}";
393 if (timeout)
394 code += "if(ms>0)throw new Error('Waiting for state "+arg1+" of server "+arg0+" timed out.');";
395 code += "return false;"
396 "})('"+name+"',"+arg1;
397 if (timeout)
398 code += "," + (args[2]->IsUndefined()?"undefined":to_string(args[2]->Int32Value()));
399 code += ");";
400
401 return ExecuteInternal(code);
402}
403
404Handle<Value> InterpreterV8::FuncState(const Arguments& args)
405{
406 if (args.Length()!=1)
407 return ThrowException(String::New("Number of arguments must be exactly 1."));
408
409 if (!args[0]->IsString())
410 return ThrowException(String::New("Argument 1 must be a string."));
411
412 // Return state.name/state.index
413
414 const String::AsciiValue str(args[0]);
415
416 const State rc = JsState(*str);
417 if (rc.index<=-256)
418 return Undefined();
419
420 HandleScope handle_scope;
421
422 Handle<Object> obj = Object::New();
423
424 obj->Set(String::New("server"), String::New(*str), ReadOnly);
425 obj->Set(String::New("index"), Integer::New(rc.index), ReadOnly);
426 obj->Set(String::New("name"), String::New(rc.name.c_str()), ReadOnly);
427
428 const Local<Value> date = Date::New(rc.time.JavaDate());
429 if (rc.index>-256 && !date.IsEmpty())
430 obj->Set(String::New("time"), date);
431
432 return handle_scope.Close(obj);
433}
434
435Handle<Value> InterpreterV8::FuncNewState(const Arguments& args)
436{
437 if (args.Length()<1 || args.Length()>3)
438 return ThrowException(String::New("Number of arguments must be 1, 2 or 3."));
439
440 if (!args[0]->IsUint32())
441 return ThrowException(String::New("Argument 1 must be an uint32."));
442 if (args.Length()>1 && !args[1]->IsString())
443 return ThrowException(String::New("Argument 2 must be a string."));
444 if (args.Length()>2 && !args[2]->IsString())
445 return ThrowException(String::New("Argument 3 must be a string."));
446
447 const uint32_t index = args[0]->Int32Value();
448 const string name = *String::AsciiValue(args[1]);
449 const string comment = *String::AsciiValue(args[2]);
450
451 if (index<10 || index>255)
452 return ThrowException(String::New("State must be in the range [10, 255]."));
453
454 if (name.empty())
455 return ThrowException(String::New("State name must not be empty."));
456
457 if (name.find_first_of(':')!=string::npos || name.find_first_of('=')!=string::npos)
458 return ThrowException(String::New("State name must not contain : or =."));
459
460 struct Find : State
461 {
462 Find(int idx, const string &n) : State(idx, n) { }
463 bool operator()(const pair<int, string> &p) { return index==p.first || name==p.second; }
464 };
465
466 if (find_if(fStates.begin(), fStates.end(), Find(index, name))!=fStates.end())
467 {
468 const string what =
469 "State index ["+to_string(index)+"] or name ["+name+"] already defined.";
470
471 return ThrowException(String::New(what.c_str()));
472 }
473
474 return Boolean::New(JsNewState(index, name, comment));
475}
476
477Handle<Value> InterpreterV8::FuncSetState(const Arguments& args)
478{
479 if (args.Length()!=1)
480 return ThrowException(String::New("Number of arguments must be exactly 1."));
481
482 if (!args[0]->IsUint32() && !args[0]->IsString())
483 return ThrowException(String::New("Argument must be an unint32 or a string."));
484
485 int index = -2;
486 if (args[0]->IsUint32())
487 {
488 index = args[0]->Int32Value();
489 }
490 else
491 {
492 const string name = *String::AsciiValue(args[0]);
493 index = JsGetState(name);
494 if (index==-2)
495 return ThrowException(String::New(("State '"+name+"' not found.").c_str()));
496 }
497
498 if (index<10 || index>255)
499 return ThrowException(String::New("State must be in the range [10, 255]."));
500
501 return Boolean::New(JsSetState(index));
502}
503
504Handle<Value> InterpreterV8::FuncGetState(const Arguments& args)
505{
506 if (args.Length()>0)
507 return ThrowException(String::New("getState must not take arguments."));
508
509 const State state = JsGetCurrentState();
510
511 HandleScope handle_scope;
512
513 Handle<Object> rc = Object::New();
514 if (rc.IsEmpty())
515 return Undefined();
516
517 rc->Set(String::New("index"), Integer::New(state.index), ReadOnly);
518 rc->Set(String::New("name"), String::New(state.name.c_str()), ReadOnly);
519 rc->Set(String::New("description"), String::New(state.comment.c_str()), ReadOnly);
520
521 return handle_scope.Close(rc);
522}
523
524Handle<Value> InterpreterV8::FuncGetStates(const Arguments& args)
525{
526 if (args.Length()>1)
527 return ThrowException(String::New("getStates must not take more than one arguments."));
528
529 if (args.Length()==1 && !args[0]->IsString())
530 return ThrowException(String::New("Argument must be a string."));
531
532 const string server = args.Length()==1 ? *String::AsciiValue(args[0]) : "DIM_CONTROL";
533
534 const vector<State> states = JsGetStates(server);
535
536 HandleScope handle_scope;
537
538 Handle<Object> list = Object::New();
539 if (list.IsEmpty())
540 return Undefined();
541
542 for (auto it=states.begin(); it!=states.end(); it++)
543 {
544 Handle<Value> entry = StringObject::New(String::New(it->name.c_str()));
545 if (entry.IsEmpty())
546 return Undefined();
547
548 StringObject::Cast(*entry)->Set(String::New("description"), String::New(it->comment.c_str()), ReadOnly);
549 list->Set(Integer::New(it->index), entry, ReadOnly);
550 }
551
552 return handle_scope.Close(list);
553}
554
555Handle<Value> InterpreterV8::FuncGetDescription(const Arguments& args)
556{
557 if (args.Length()!=1)
558 return ThrowException(String::New("getDescription must take exactly one argument."));
559
560 if (args.Length()==1 && !args[0]->IsString())
561 return ThrowException(String::New("Argument must be a string."));
562
563 const string service = *String::AsciiValue(args[0]);
564
565 const vector<Description> descriptions = JsGetDescription(service);
566 const set<Service> services = JsGetServices();
567
568 auto is=services.begin();
569 for (; is!=services.end(); is++)
570 if (is->name==service)
571 break;
572
573 if (is==services.end())
574 return Undefined();
575
576 HandleScope handle_scope;
577
578 Handle<Object> arr = fTemplateDescription->GetFunction()->NewInstance();//Object::New();
579 if (arr.IsEmpty())
580 return Undefined();
581
582 auto it=descriptions.begin();
583 arr->Set(String::New("name"), String::New(it->name.c_str()), ReadOnly);
584 if (!it->comment.empty())
585 arr->Set(String::New("description"), String::New(it->comment.c_str()), ReadOnly);
586 if (is!=services.end())
587 {
588 arr->Set(String::New("server"), String::New(is->server.c_str()), ReadOnly);
589 arr->Set(String::New("service"), String::New(is->service.c_str()), ReadOnly);
590 arr->Set(String::New("isCommand"), Boolean::New(is->iscmd), ReadOnly);
591 if (!is->format.empty())
592 arr->Set(String::New("format"), String::New(is->format.c_str()), ReadOnly);
593 }
594
595 uint32_t i=0;
596 for (it++; it!=descriptions.end(); it++)
597 {
598 Handle<Object> obj = Object::New();
599 if (obj.IsEmpty())
600 return Undefined();
601
602 if (!it->name.empty())
603 obj->Set(String::New("name"), String::New(it->name.c_str()), ReadOnly);
604 if (!it->comment.empty())
605 obj->Set(String::New("description"), String::New(it->comment.c_str()), ReadOnly);
606 if (!it->unit.empty())
607 obj->Set(String::New("unit"), String::New(it->unit.c_str()), ReadOnly);
608
609 arr->Set(i++, obj);
610 }
611
612 return handle_scope.Close(arr);
613}
614
615Handle<Value> InterpreterV8::FuncGetServices(const Arguments& args)
616{
617 if (args.Length()>2)
618 return ThrowException(String::New("getServices must not take more than two argument."));
619
620 if (args.Length()>=1 && !args[0]->IsString())
621 return ThrowException(String::New("First argument must be a string."));
622
623 if (args.Length()==2 && !args[1]->IsBoolean())
624 return ThrowException(String::New("Second argument must be a boolean."));
625
626 string arg0 = args.Length() ? *String::AsciiValue(args[0]) : "";
627 if (arg0=="*")
628 arg0=="";
629
630 const set<Service> services = JsGetServices();
631
632 HandleScope handle_scope;
633
634 Handle<Array> arr = Array::New();
635 if (arr.IsEmpty())
636 return Undefined();
637
638 uint32_t i=0;
639 for (auto is=services.begin(); is!=services.end(); is++)
640 {
641 if (!arg0.empty() && is->name.find(arg0)!=0)
642 continue;
643
644 if (args.Length()==2 && args[1]->BooleanValue()!=is->iscmd)
645 continue;
646
647 Handle<Object> obj = Object::New();
648 if (obj.IsEmpty())
649 return Undefined();
650
651 obj->Set(String::New("name"), String::New(is->name.c_str()), ReadOnly);
652 obj->Set(String::New("server"), String::New(is->server.c_str()), ReadOnly);
653 obj->Set(String::New("service"), String::New(is->service.c_str()), ReadOnly);
654 obj->Set(String::New("isCommand"), Boolean::New(is->iscmd), ReadOnly);
655 if (!is->format.empty())
656 obj->Set(String::New("format"), String::New(is->format.c_str()), ReadOnly);
657
658 arr->Set(i++, obj);
659 }
660
661 return handle_scope.Close(arr);
662}
663
664// ==========================================================================
665// Internal functions
666// ==========================================================================
667
668
669// The callback that is invoked by v8 whenever the JavaScript 'print'
670// function is called. Prints its arguments on stdout separated by
671// spaces and ending with a newline.
672Handle<Value> InterpreterV8::FuncLog(const Arguments& args)
673{
674 for (int i=0; i<args.Length(); i++)
675 {
676 const String::AsciiValue str(args[i]);
677 if (*str)
678 JsPrint(*str);
679 }
680
681 if (args.Length()==0)
682 JsPrint();
683
684 return Undefined();
685}
686
687Handle<Value> InterpreterV8::FuncAlarm(const Arguments& args)
688{
689 for (int i=0; i<args.Length(); i++)
690 {
691 const String::AsciiValue str(args[i]);
692 if (*str)
693 JsAlarm(*str);
694 }
695
696 if (args.Length()==0)
697 JsAlarm();
698
699 return Undefined();
700}
701
702Handle<Value> InterpreterV8::FuncOut(const Arguments& args)
703{
704 for (int i=0; i<args.Length(); i++)
705 {
706 const String::AsciiValue str(args[i]);
707 if (*str)
708 JsOut(*str);
709 }
710 return Undefined();
711}
712
713Handle<Value> InterpreterV8::FuncWarn(const Arguments& args)
714{
715 for (int i=0; i<args.Length(); i++)
716 {
717 const String::AsciiValue str(args[i]);
718 if (*str)
719 JsWarn(*str);
720 }
721 return Undefined();
722}
723
724// The callback that is invoked by v8 whenever the JavaScript 'load'
725// function is called. Loads, compiles and executes its argument
726// JavaScript file.
727Handle<Value> InterpreterV8::FuncInclude(const Arguments& args)
728{
729 if (args.Length()!=1)
730 return ThrowException(String::New("Number of arguments must be one."));
731
732 if (!args[0]->IsString())
733 return ThrowException(String::New("Argument must be a string."));
734
735 const String::AsciiValue file(args[0]);
736 if (*file == NULL)
737 return ThrowException(String::New("File name missing."));
738
739 if (strlen(*file)==0)
740 return ThrowException(String::New("File name empty."));
741
742 izstream fin(*file);
743 if (!fin)
744 return ThrowException(String::New(errno!=0?strerror(errno):"Insufficient memory for decompression"));
745
746 string buffer;
747 getline(fin, buffer, '\0');
748
749 if ((fin.fail() && !fin.eof()) || fin.bad())
750 return ThrowException(String::New(strerror(errno)));
751
752 if (buffer.length()>1 && buffer[0]=='#' && buffer[1]=='!')
753 buffer.insert(0, "//");
754
755 return ExecuteCode(buffer, *file);
756}
757
758Handle<Value> InterpreterV8::FuncFile(const Arguments& args)
759{
760 if (args.Length()!=1 && args.Length()!=2)
761 return ThrowException(String::New("Number of arguments must be one or two."));
762
763 const String::AsciiValue file(args[0]);
764 if (*file == NULL)
765 return ThrowException(String::New("File name missing"));
766
767 if (args.Length()==2 && !args[1]->IsString())
768 return ThrowException(String::New("Second argument must be a string."));
769
770 const string delim = args.Length()==2 ? *String::AsciiValue(args[1]) : "";
771
772 if (args.Length()==2 && delim.size()!=1)
773 return ThrowException(String::New("Second argument must be a string of length 1."));
774
775 HandleScope handle_scope;
776
777 izstream fin(*file);
778 if (!fin)
779 return ThrowException(String::New(errno!=0?strerror(errno):"Insufficient memory for decompression"));
780
781 if (args.Length()==1)
782 {
783 string buffer;
784 getline(fin, buffer, '\0');
785 if ((fin.fail() && !fin.eof()) || fin.bad())
786 return ThrowException(String::New(strerror(errno)));
787
788 Handle<Value> str = StringObject::New(String::New(buffer.c_str()));
789 StringObject::Cast(*str)->Set(String::New("name"), String::New(*file));
790 return handle_scope.Close(str);
791 }
792
793 Handle<Array> arr = Array::New();
794 if (arr.IsEmpty())
795 return Undefined();
796
797 int i=0;
798 string buffer;
799 while (getline(fin, buffer, delim[0]))
800 arr->Set(i++, String::New(buffer.c_str()));
801
802 if ((fin.fail() && !fin.eof()) || fin.bad())
803 return ThrowException(String::New(strerror(errno)));
804
805 arr->Set(String::New("name"), String::New(*file));
806 arr->Set(String::New("delim"), String::New(delim.c_str(), 1));
807
808 return handle_scope.Close(arr);
809}
810
811// ==========================================================================
812// Mail
813// ==========================================================================
814
815Handle<Value> InterpreterV8::ConstructorMail(const Arguments &args)
816{
817 if (!args.IsConstructCall())
818 return ThrowException(String::New("Mail must be called as constructor"));
819
820 if (args.Length()!=1 || !args[0]->IsString())
821 return ThrowException(String::New("Constructor must be called with a single string as argument"));
822
823 HandleScope handle_scope;
824
825 Handle<Array> rec = Array::New();
826 Handle<Array> att = Array::New();
827 Handle<Array> bcc = Array::New();
828 Handle<Array> cc = Array::New();
829 Handle<Array> txt = Array::New();
830 if (rec.IsEmpty() || att.IsEmpty() || bcc.IsEmpty() || cc.IsEmpty() || txt.IsEmpty())
831 return Undefined();
832
833 Handle<Object> self = args.This();
834
835 self->Set(String::New("subject"), args[0]->ToString(), ReadOnly);
836 self->Set(String::New("recipients"), rec, ReadOnly);
837 self->Set(String::New("attachments"), att, ReadOnly);
838 self->Set(String::New("bcc"), bcc, ReadOnly);
839 self->Set(String::New("cc"), cc, ReadOnly);
840 self->Set(String::New("text"), txt, ReadOnly);
841
842 self->Set(String::New("send"), FunctionTemplate::New(WrapSendMail)->GetFunction(), ReadOnly);
843
844 return handle_scope.Close(self);
845}
846
847vector<string> InterpreterV8::ValueToArray(const Handle<Value> &val, bool only)
848{
849 vector<string> rc;
850
851 Handle<Array> arr = Handle<Array>::Cast(val);
852 for (uint32_t i=0; i<arr->Length(); i++)
853 {
854 Handle<Value> obj = arr->Get(i);
855 if (obj.IsEmpty())
856 continue;
857
858 if (obj->IsNull() || obj->IsUndefined())
859 continue;
860
861 if (only && !obj->IsString())
862 continue;
863
864 rc.push_back(*String::AsciiValue(obj->ToString()));
865 }
866
867 return rc;
868}
869
870Handle<Value> InterpreterV8::FuncSendMail(const Arguments& args)
871{
872 HandleScope handle_scope;
873
874 if (args.Length()>1)
875 return ThrowException(String::New("Only one argument allowed."));
876
877 if (args.Length()==1 && !args[0]->IsBoolean())
878 return ThrowException(String::New("Argument must be a boolean."));
879
880 const bool block = args.Length()==0 || args[0]->BooleanValue();
881
882 const Handle<Value> sub = args.This()->Get(String::New("subject"));
883 const Handle<Value> rec = args.This()->Get(String::New("recipients"));
884 const Handle<Value> txt = args.This()->Get(String::New("text"));
885 const Handle<Value> att = args.This()->Get(String::New("attachments"));
886 const Handle<Value> bcc = args.This()->Get(String::New("bcc"));
887 const Handle<Value> cc = args.This()->Get(String::New("cc"));
888
889 const vector<string> vrec = ValueToArray(rec);
890 const vector<string> vtxt = ValueToArray(txt, false);
891 const vector<string> vatt = ValueToArray(att);
892 const vector<string> vbcc = ValueToArray(bcc);
893 const vector<string> vcc = ValueToArray(cc);
894
895 if (vrec.size()==0)
896 return ThrowException(String::New("At least one valid string is required in 'recipients'."));
897 if (vtxt.size()==0)
898 return ThrowException(String::New("At least one valid string is required in 'text'."));
899
900 const string subject = *String::AsciiValue(sub->ToString());
901
902 FILE *pipe = popen(("from=no-reply@fact-project.org mailx -~ "+vrec[0]).c_str(), "w");
903 if (!pipe)
904 return ThrowException(String::New(strerror(errno)));
905
906 fprintf(pipe, "%s", ("~s"+subject+"\n").c_str());
907 for (auto it=vrec.begin()+1; it<vrec.end(); it++)
908 fprintf(pipe, "%s", ("~t"+*it+"\n").c_str());
909 for (auto it=vbcc.begin(); it<vbcc.end(); it++)
910 fprintf(pipe, "%s", ("~b"+*it+"\n").c_str());
911 for (auto it=vcc.begin(); it<vcc.end(); it++)
912 fprintf(pipe, "%s", ("~c"+*it+"\n").c_str());
913 for (auto it=vatt.begin(); it<vatt.end(); it++)
914 fprintf(pipe, "%s", ("~@"+*it+"\n").c_str()); // Must not contain white spaces
915
916 for (auto it=vtxt.begin(); it<vtxt.end(); it++)
917 fwrite((*it+"\n").c_str(), it->length()+1, 1, pipe);
918
919 fprintf(pipe, "\n---\nsent by dimctrl");
920
921 if (!block)
922 return Undefined();
923
924 const int rc = pclose(pipe);
925
926 const Locker lock;
927 return handle_scope.Close(Integer::New(WEXITSTATUS(rc)));
928}
929
930// ==========================================================================
931// Database
932// ==========================================================================
933
934Handle<Value> InterpreterV8::FuncDbClose(const Arguments &args)
935{
936 void *ptr = External::Unwrap(args.This()->GetInternalField(0));
937 if (!ptr)
938 return Boolean::New(false);
939
940#ifdef HAVE_SQL
941 Database *db = reinterpret_cast<Database*>(ptr);
942 auto it = find(fDatabases.begin(), fDatabases.end(), db);
943 fDatabases.erase(it);
944 delete db;
945#endif
946
947 HandleScope handle_scope;
948
949 args.This()->SetInternalField(0, External::New(0));
950
951 return handle_scope.Close(Boolean::New(true));
952}
953
954Handle<Value> InterpreterV8::FuncDbQuery(const Arguments &args)
955{
956 if (args.Length()==0)
957 return ThrowException(String::New("Arguments expected."));
958
959 void *ptr = External::Unwrap(args.This()->GetInternalField(0));
960 if (!ptr)
961 return Undefined();
962
963 string query;
964 for (int i=0; i<args.Length(); i++)
965 query += string(" ") + *String::AsciiValue(args[i]);
966 query.erase(0, 1);
967
968#ifdef HAVE_SQL
969 try
970 {
971 HandleScope handle_scope;
972
973 Database *db = reinterpret_cast<Database*>(ptr);
974
975 const mysqlpp::StoreQueryResult res = db->query(query).store();
976
977 Handle<Array> ret = Array::New();
978 if (ret.IsEmpty())
979 return Undefined();
980
981 ret->Set(String::New("table"), String::New(res.table()), ReadOnly);
982 ret->Set(String::New("query"), String::New(query.c_str()), ReadOnly);
983
984 Handle<Array> cols = Array::New();
985 if (cols.IsEmpty())
986 return Undefined();
987
988 int irow=0;
989 for (vector<mysqlpp::Row>::const_iterator it=res.begin(); it<res.end(); it++)
990 {
991 Handle<Object> row = Object::New();
992 if (row.IsEmpty())
993 return Undefined();
994
995 const mysqlpp::FieldNames *list = it->field_list().list;
996
997 for (size_t i=0; i<it->size(); i++)
998 {
999 const Handle<Value> name = String::New((*list)[i].c_str());
1000 if (irow==0)
1001 cols->Set(i, name);
1002
1003 if ((*it)[i].is_null())
1004 {
1005 row->Set(name, Undefined(), ReadOnly);
1006 continue;
1007 }
1008
1009 const string sql_type = (*it)[i].type().sql_name();
1010
1011 const bool uns = sql_type.find("UNSIGNED")==string::npos;
1012
1013 if (sql_type.find("BIGINT")!=string::npos)
1014 {
1015 if (uns)
1016 {
1017 const uint64_t val = (uint64_t)(*it)[i];
1018 if (val>UINT32_MAX)
1019 row->Set(name, Number::New(val), ReadOnly);
1020 else
1021 row->Set(name, Integer::NewFromUnsigned(val), ReadOnly);
1022 }
1023 else
1024 {
1025 const int64_t val = (int64_t)(*it)[i];
1026 if (val<INT32_MIN || val>INT32_MAX)
1027 row->Set(name, Number::New(val), ReadOnly);
1028 else
1029 row->Set(name, Integer::NewFromUnsigned(val), ReadOnly);
1030 }
1031 continue;
1032 }
1033
1034 // 32 bit
1035 if (sql_type.find("INT")!=string::npos)
1036 {
1037 if (uns)
1038 row->Set(name, Integer::NewFromUnsigned((uint32_t)(*it)[i]), ReadOnly);
1039 else
1040 row->Set(name, Integer::New((int32_t)(*it)[i]), ReadOnly);
1041 continue;
1042 }
1043
1044 if (sql_type.find("BOOL")!=string::npos )
1045 {
1046 row->Set(name, Boolean::New((bool)(*it)[i]), ReadOnly);
1047 continue;
1048 }
1049
1050 if (sql_type.find("FLOAT")!=string::npos)
1051 {
1052 ostringstream val;
1053 val << setprecision(7) << (float)(*it)[i];
1054 row->Set(name, Number::New(stod(val.str())), ReadOnly);
1055 continue;
1056
1057 }
1058 if (sql_type.find("DOUBLE")!=string::npos)
1059 {
1060 row->Set(name, Number::New((double)(*it)[i]), ReadOnly);
1061 continue;
1062 }
1063
1064 if (sql_type.find("CHAR")!=string::npos ||
1065 sql_type.find("TEXT")!=string::npos)
1066 {
1067 row->Set(name, String::New((const char*)(*it)[i]), ReadOnly);
1068 continue;
1069 }
1070
1071 time_t date = 0;
1072 if (sql_type.find("TIMESTAMP")!=string::npos)
1073 date = mysqlpp::Time((*it)[i]);
1074
1075 if (sql_type.find("DATETIME")!=string::npos)
1076 date = mysqlpp::DateTime((*it)[i]);
1077
1078 if (sql_type.find(" DATE ")!=string::npos)
1079 date = mysqlpp::Date((*it)[i]);
1080
1081 if (date>0)
1082 {
1083 // It is important to catch the exception thrown
1084 // by Date::New in case of thread termination!
1085 const Local<Value> val = Date::New(date*1000);
1086 if (val.IsEmpty())
1087 return Undefined();
1088
1089 row->Set(name, val, ReadOnly);
1090 }
1091 }
1092
1093 ret->Set(irow++, row);
1094 }
1095
1096 if (irow>0)
1097 ret->Set(String::New("cols"), cols, ReadOnly);
1098
1099 return handle_scope.Close(ret);
1100 }
1101 catch (const exception &e)
1102 {
1103 return ThrowException(String::New(e.what()));
1104 }
1105#endif
1106}
1107
1108Handle<Value> InterpreterV8::FuncDatabase(const Arguments &args)
1109{
1110 if (!args.IsConstructCall())
1111 return ThrowException(String::New("Database must be called as constructor."));
1112
1113 if (args.Length()!=1)
1114 return ThrowException(String::New("Number of arguments must be 1."));
1115
1116 if (!args[0]->IsString())
1117 return ThrowException(String::New("Argument 1 not a string."));
1118
1119#ifdef HAVE_SQL
1120 try
1121 {
1122 HandleScope handle_scope;
1123
1124 //if (!args.IsConstructCall())
1125 // return Constructor(fTemplateDatabase, args);
1126
1127 Database *db = new Database(*String::AsciiValue(args[0]));
1128 fDatabases.push_back(db);
1129
1130 Handle<Object> self = args.This();
1131 self->Set(String::New("user"), String::New(db->user.c_str()), ReadOnly);
1132 self->Set(String::New("server"), String::New(db->server.c_str()), ReadOnly);
1133 self->Set(String::New("database"), String::New(db->db.c_str()), ReadOnly);
1134 self->Set(String::New("port"), db->port==0?Undefined():Integer::NewFromUnsigned(db->port), ReadOnly);
1135 self->Set(String::New("query"), FunctionTemplate::New(WrapDbQuery)->GetFunction(), ReadOnly);
1136 self->Set(String::New("close"), FunctionTemplate::New(WrapDbClose)->GetFunction(), ReadOnly);
1137 self->SetInternalField(0, External::New(db));
1138
1139 return handle_scope.Close(self);
1140 }
1141 catch (const exception &e)
1142 {
1143 return ThrowException(String::New(e.what()));
1144 }
1145#endif
1146}
1147
1148// ==========================================================================
1149// Services
1150// ==========================================================================
1151
1152Handle<Value> InterpreterV8::Convert(char type, const char* &ptr)
1153{
1154 // Dim values are always unsigned per (FACT++) definition
1155 switch (type)
1156 {
1157 case 'F':
1158 {
1159 // Remove the "imprecision" effect coming from casting a float to
1160 // a double and then showing it with double precision
1161 ostringstream val;
1162 val << setprecision(7) << *reinterpret_cast<const float*>(ptr);
1163 ptr += 4;
1164 return Number::New(stod(val.str()));
1165 }
1166 case 'D': { Handle<Value> v=Number::New(*reinterpret_cast<const double*>(ptr)); ptr+=8; return v; }
1167 case 'I':
1168 case 'L': { Handle<Value> v=Integer::NewFromUnsigned(*reinterpret_cast<const uint32_t*>(ptr)); ptr += 4; return v; }
1169 case 'X':
1170 {
1171 const int64_t val = *reinterpret_cast<const int64_t*>(ptr);
1172 ptr += 8;
1173 if (val>=0 && val<=UINT32_MAX)
1174 return Integer::NewFromUnsigned(val);
1175 if (val>=INT32_MIN && val<0)
1176 return Integer::New(val);
1177 return Number::New(val);
1178 }
1179 case 'S': { Handle<Value> v=Integer::NewFromUnsigned(*reinterpret_cast<const uint16_t*>(ptr)); ptr += 2; return v; }
1180 case 'C': { Handle<Value> v=Integer::NewFromUnsigned((uint16_t)*reinterpret_cast<const uint8_t*>(ptr)); ptr += 1; return v; }
1181 }
1182 return Undefined();
1183}
1184
1185Handle<Value> InterpreterV8::FuncClose(const Arguments &args)
1186{
1187 HandleScope handle_scope;
1188
1189 //const void *ptr = Local<External>::Cast(args.Holder()->GetInternalField(0))->Value();
1190
1191 const String::AsciiValue str(args.This()->Get(String::New("name")));
1192
1193 const auto it = fReverseMap.find(*str);
1194 if (it!=fReverseMap.end())
1195 {
1196 it->second.Dispose();
1197 fReverseMap.erase(it);
1198 }
1199
1200 args.This()->Set(String::New("isOpen"), Boolean::New(false), ReadOnly);
1201
1202 return handle_scope.Close(Boolean::New(JsUnsubscribe(*str)));
1203}
1204
1205Handle<Value> InterpreterV8::ConvertEvent(const EventImp *evt, uint64_t counter, const char *str)
1206{
1207 const vector<Description> vec = JsDescription(str);
1208
1209 Handle<Object> ret = fTemplateEvent->GetFunction()->NewInstance();//Object::New();
1210 if (ret.IsEmpty())
1211 return Undefined();
1212
1213 const Local<Value> date = Date::New(evt->GetJavaDate());
1214 if (date.IsEmpty())
1215 return Undefined();
1216
1217 ret->Set(String::New("name"), String::New(str), ReadOnly);
1218 ret->Set(String::New("format"), String::New(evt->GetFormat().c_str()), ReadOnly);
1219 ret->Set(String::New("qos"), Integer::New(evt->GetQoS()), ReadOnly);
1220 ret->Set(String::New("size"), Integer::New(evt->GetSize()), ReadOnly);
1221 ret->Set(String::New("counter"), Integer::New(counter), ReadOnly);
1222 if (evt->GetJavaDate()>0)
1223 ret->Set(String::New("time"), date, ReadOnly);
1224
1225 // If names are available data will also be provided as an
1226 // object. If an empty event was received, but names are available,
1227 // the object will be empty. Otherwise 'obj' will be undefined.
1228 // obj===undefined: no data received
1229 // obj!==undefined, length==0: names for event available
1230 // obj!==undefined, obj.length>0: names available, data received
1231 Handle<Object> named = Object::New();
1232 if (vec.size()>0)
1233 ret->Set(String::New("obj"), named, ReadOnly);
1234
1235 // If no event was received (usually a disconnection event in
1236 // the context of FACT++), no data is returned
1237 if (evt->IsEmpty())
1238 return ret;
1239
1240 // If valid data was received, but the size was zero, then
1241 // null is returned as data
1242 // data===undefined: no data received
1243 // data===null: event received, but no data
1244 // data.length>0: event received, contains data
1245 if (evt->GetSize()==0 || evt->GetFormat().empty())
1246 {
1247 ret->Set(String::New("data"), Null(), ReadOnly);
1248 return ret;
1249 }
1250
1251 typedef boost::char_separator<char> separator;
1252 const boost::tokenizer<separator> tokenizer(evt->GetFormat(), separator(";:"));
1253
1254 const vector<string> tok(tokenizer.begin(), tokenizer.end());
1255
1256 Handle<Object> arr = tok.size()>1 ? Array::New() : ret;
1257 if (arr.IsEmpty())
1258 return Undefined();
1259
1260 const char *ptr = evt->GetText();
1261 const char *end = evt->GetText()+evt->GetSize();
1262
1263 try
1264 {
1265 size_t pos = 1;
1266 for (auto it=tok.begin(); it<tok.end() && ptr<end; it++, pos++)
1267 {
1268 char type = (*it)[0];
1269 it++;
1270
1271 string name = pos<vec.size() ? vec[pos].name : "";
1272 if (tok.size()==1)
1273 name = "data";
1274
1275 // Get element size
1276 uint32_t sz = 1;
1277 switch (type)
1278 {
1279 case 'X':
1280 case 'D': sz = 8; break;
1281 case 'F':
1282 case 'I':
1283 case 'L': sz = 4; break;
1284 case 'S': sz = 2; break;
1285 case 'C': sz = 1; break;
1286 }
1287
1288 // Check if no number is attached if the size of the
1289 // received data is consistent with the format string
1290 if (it==tok.end() && (end-ptr)%sz>0)
1291 return Exception::Error(String::New(("Number of received bytes ["+to_string(evt->GetSize())+"] does not match format ["+evt->GetFormat()+"]").c_str()));
1292
1293 // Check if format has a number attached.
1294 // If no number is attached calculate number of elements
1295 const uint32_t cnt = it==tok.end() ? (end-ptr)/sz : stoi(it->c_str());
1296
1297 // is_str: Array of type C but unknown size (String)
1298 // is_one: Array of known size, but size is 1 (I:1)
1299 const bool is_str = type=='C' && it==tok.end();
1300 const bool is_one = cnt==1 && it!=tok.end();
1301
1302 Handle<Value> v;
1303
1304 if (is_str)
1305 v = String::New(ptr);
1306 if (is_one)
1307 v = Convert(type, ptr);
1308
1309 // Array of known (I:5) or unknown size (I), but no string
1310 if (!is_str && !is_one)
1311 {
1312 Handle<Object> a = Array::New(cnt);
1313 if (a.IsEmpty())
1314 return Undefined();
1315
1316 for (uint32_t i=0; i<cnt; i++)
1317 a->Set(i, Convert(type, ptr));
1318
1319 v = a;
1320 }
1321
1322 if (tok.size()>1)
1323 arr->Set(pos-1, v);
1324 else
1325 ret->Set(String::New("data"), v, ReadOnly);
1326
1327 if (!name.empty())
1328 {
1329 const Handle<String> n = String::New(name.c_str());
1330 named->Set(n, v);
1331 }
1332 }
1333
1334 if (tok.size()>1)
1335 ret->Set(String::New("data"), arr, ReadOnly);
1336
1337 return ret;
1338 }
1339 catch (...)
1340 {
1341 return Exception::Error(String::New(("Format string conversion '"+evt->GetFormat()+"' failed.").c_str()));
1342 }
1343}
1344/*
1345Handle<Value> InterpreterV8::FuncGetData(const Arguments &args)
1346{
1347 HandleScope handle_scope;
1348
1349 const String::AsciiValue str(args.Holder()->Get(String::New("name")));
1350
1351 const pair<uint64_t, EventImp *> p = JsGetEvent(*str);
1352
1353 const EventImp *evt = p.second;
1354 if (!evt)
1355 return Undefined();
1356
1357 //if (counter==cnt)
1358 // return info.Holder();//Holder()->Get(String::New("data"));
1359
1360 Handle<Value> ret = ConvertEvent(evt, p.first, *str);
1361 return ret->IsNativeError() ? ThrowException(ret) : handle_scope.Close(ret);
1362}
1363*/
1364Handle<Value> InterpreterV8::FuncGetData(const Arguments &args)
1365{
1366 if (args.Length()>2)
1367 return ThrowException(String::New("Number of arguments must not be greater than 2."));
1368
1369 if (args.Length()>=1 && !args[0]->IsInt32() && !args[0]->IsNull())
1370 return ThrowException(String::New("Argument 1 not an uint32."));
1371
1372 if (args.Length()==2 && !args[1]->IsBoolean())
1373 return ThrowException(String::New("Argument 2 not a boolean."));
1374
1375 // Using a Javascript function has the advantage that it is fully
1376 // interruptable without the need of C++ code
1377 const bool null = args.Length()>=1 && args[0]->IsNull();
1378 const int32_t timeout = args.Length()>=1 ? args[0]->Int32Value() : 0;
1379 const bool named = args.Length()<2 || args[1]->BooleanValue();
1380
1381 HandleScope handle_scope;
1382
1383 const Handle<String> data = String::New("data");
1384 const Handle<String> object = String::New("obj");
1385
1386 const String::AsciiValue name(args.Holder()->Get(String::New("name")));
1387
1388 TryCatch exception;
1389
1390 Time t;
1391 while (!exception.HasCaught())
1392 {
1393 const pair<uint64_t, EventImp *> p = JsGetEvent(*name);
1394
1395 const EventImp *evt = p.second;
1396 if (evt)
1397 {
1398 const Handle<Value> val = ConvertEvent(evt, p.first, *name);
1399 if (val->IsNativeError())
1400 return ThrowException(val);
1401
1402 // Protect against the return of an exception
1403 if (val->IsObject())
1404 {
1405 const Handle<Object> event = val->ToObject();
1406 const Handle<Value> obj = event->Get(named?object:data);
1407 if (!obj.IsEmpty())
1408 {
1409 if (!named)
1410 {
1411 // No names (no 'obj'), but 'data'
1412 if (!obj->IsUndefined())
1413 return handle_scope.Close(val);
1414 }
1415 else
1416 {
1417 // Has names and data was received?
1418 if (obj->IsObject() && obj->ToObject()->GetOwnPropertyNames()->Length()>0)
1419 return handle_scope.Close(val);
1420 }
1421 }
1422 }
1423 }
1424
1425 if (args.Length()==0)
1426 break;
1427
1428 if (!null && Time()-t>=boost::posix_time::milliseconds(abs(timeout)))
1429 break;
1430
1431 // Theoretically, the CPU usage can be reduced by maybe a factor
1432 // of four using a larger value, but this also means that the
1433 // JavaScript is locked for a longer time.
1434 const Unlocker unlock;
1435 usleep(1000);
1436 }
1437
1438 // This hides the location of the exception, which is wanted.
1439 if (exception.HasCaught())
1440 return exception.ReThrow();
1441
1442 if (timeout<0)
1443 return Undefined();
1444
1445 const string str = "Waiting for a valid event of "+string(*name)+" timed out.";
1446 return ThrowException(String::New(str.c_str()));
1447}
1448
1449
1450// This is a callback from the RemoteControl piping event handling
1451// to the java script ---> in test phase!
1452void InterpreterV8::JsHandleEvent(const EventImp &evt, uint64_t cnt, const string &service)
1453{
1454 // FIXME: This blocks service updates, we have to run this
1455 // in a dedicated thread.
1456 const Locker locker;
1457
1458 if (fThreadId<0)
1459 return;
1460
1461 const auto it = fReverseMap.find(service);
1462 if (it==fReverseMap.end())
1463 return;
1464
1465 const HandleScope handle_scope;
1466
1467 Handle<Object> obj = it->second;
1468
1469 const Handle<String> onchange = String::New("onchange");
1470 if (!obj->Has(onchange))
1471 return;
1472
1473 const Handle<Value> val = obj->Get(onchange);
1474 if (!val->IsFunction())
1475 return;
1476
1477 obj->CreationContext()->Enter();
1478
1479 // -------------------------------------------------------------------
1480
1481 TryCatch exception;
1482
1483 const int id = V8::GetCurrentThreadId();
1484 fThreadIds.insert(id);
1485
1486 Handle<Value> ret = ConvertEvent(&evt, cnt, service.c_str());
1487 if (ret->IsObject())
1488 Handle<Function>::Cast(val)->Call(obj, 1, &ret);
1489
1490 fThreadIds.erase(id);
1491
1492 if (!HandleException(exception, "Service.onchange"))
1493 V8::TerminateExecution(fThreadId);
1494
1495 if (ret->IsNativeError())
1496 {
1497 JsException(service+".onchange callback - "+*String::AsciiValue(ret));
1498 V8::TerminateExecution(fThreadId);
1499 }
1500
1501 obj->CreationContext()->Exit();
1502}
1503
1504Handle<Value> InterpreterV8::OnChangeSet(Local<String> prop, Local<Value> value, const AccessorInfo &)
1505{
1506 // Returns the value if the setter intercepts the request. Otherwise, returns an empty handle.
1507 const string server = *String::AsciiValue(prop);
1508 auto it = fStateCallbacks.find(server);
1509
1510 if (it!=fStateCallbacks.end())
1511 {
1512 it->second.Dispose();
1513 fStateCallbacks.erase(it);
1514 }
1515
1516 if (value->IsFunction())
1517 fStateCallbacks[server] = Persistent<Object>::New(value->ToObject());
1518
1519 return Handle<Value>();
1520}
1521
1522void InterpreterV8::JsHandleState(const std::string &server, const State &state)
1523{
1524 // FIXME: This blocks service updates, we have to run this
1525 // in a dedicated thread.
1526 const Locker locker;
1527
1528 if (fThreadId<0)
1529 return;
1530
1531 auto it = fStateCallbacks.find(server);
1532 if (it==fStateCallbacks.end())
1533 {
1534 it = fStateCallbacks.find("*");
1535 if (it==fStateCallbacks.end())
1536 return;
1537 }
1538
1539 const HandleScope handle_scope;
1540
1541 it->second->CreationContext()->Enter();
1542
1543 // -------------------------------------------------------------------
1544
1545 Handle<ObjectTemplate> obj = ObjectTemplate::New();
1546 obj->Set(String::New("server"), String::New(server.c_str()), ReadOnly);
1547
1548 if (state.index>-256)
1549 {
1550 obj->Set(String::New("index"), Integer::New(state.index), ReadOnly);
1551 obj->Set(String::New("name"), String::New(state.name.c_str()), ReadOnly);
1552 obj->Set(String::New("comment"), String::New(state.comment.c_str()), ReadOnly);
1553 const Local<Value> date = Date::New(state.time.JavaDate());
1554 if (!date.IsEmpty())
1555 obj->Set(String::New("time"), date);
1556 }
1557
1558 // -------------------------------------------------------------------
1559
1560 TryCatch exception;
1561
1562 const int id = V8::GetCurrentThreadId();
1563 fThreadIds.insert(id);
1564
1565 Handle<Value> args[] = { obj->NewInstance() };
1566 Handle<Function> fun = Handle<Function>(Function::Cast(*it->second));
1567 fun->Call(fun, 1, args);
1568
1569 fThreadIds.erase(id);
1570
1571 if (!HandleException(exception, "dim.onchange"))
1572 V8::TerminateExecution(fThreadId);
1573
1574 it->second->CreationContext()->Exit();
1575}
1576
1577// ==========================================================================
1578// Interrupt handling
1579// ==========================================================================
1580
1581Handle<Value> InterpreterV8::FuncSetInterrupt(const Arguments &args)
1582{
1583 if (args.Length()!=1)
1584 return ThrowException(String::New("Number of arguments must be 1."));
1585
1586 if (!args[0]->IsNull() && !args[0]->IsUndefined() && !args[0]->IsFunction())
1587 return ThrowException(String::New("Argument not a function, null or undefined."));
1588
1589 if (args[0]->IsNull() || args[0]->IsUndefined())
1590 {
1591 fInterruptCallback.Dispose();
1592 fInterruptCallback.Clear();
1593 return Undefined();
1594 }
1595
1596 // Returns the value if the setter intercepts the request. Otherwise, returns an empty handle.
1597 fInterruptCallback = Persistent<Object>::New(args[0]->ToObject());
1598 return Undefined();
1599}
1600
1601Handle<Value> InterpreterV8::HandleInterruptImp(string str, uint64_t time)
1602{
1603 if (fInterruptCallback.IsEmpty())
1604 return Handle<Value>();
1605
1606 const size_t p = str.find_last_of('\n');
1607
1608 const string usr = p==string::npos?"":str.substr(p+1);
1609
1610 string irq = p==string::npos?str:str.substr(0, p);
1611 const map<string,string> data = Tools::Split(irq, true);
1612
1613 Local<Value> irq_str = String::New(irq.c_str());
1614 Local<Value> usr_str = String::New(usr.c_str());
1615 Local<Value> date = Date::New(time);
1616 Handle<Object> arr = Array::New(data.size());
1617
1618 if (date.IsEmpty() || arr.IsEmpty())
1619 return Handle<Value>();
1620
1621 for (auto it=data.begin(); it!=data.end(); it++)
1622 arr->Set(String::New(it->first.c_str()), String::New(it->second.c_str()));
1623
1624 Handle<Value> args[] = { irq_str, arr, date, usr_str };
1625 Handle<Function> fun = Handle<Function>(Function::Cast(*fInterruptCallback));
1626
1627 return fun->Call(fun, 4, args);
1628}
1629
1630int InterpreterV8::JsHandleInterrupt(const EventImp &evt)
1631{
1632 // FIXME: This blocks service updates, we have to run this
1633 // in a dedicated thread.
1634 const Locker locker;
1635
1636 if (fThreadId<0 || fInterruptCallback.IsEmpty())
1637 return -42;
1638
1639 const HandleScope handle_scope;
1640
1641 fInterruptCallback->CreationContext()->Enter();
1642
1643 // -------------------------------------------------------------------
1644
1645 TryCatch exception;
1646
1647 const int id = V8::GetCurrentThreadId();
1648 fThreadIds.insert(id);
1649
1650 const Handle<Value> val = HandleInterruptImp(evt.GetString(), evt.GetJavaDate());
1651
1652 fThreadIds.erase(id);
1653
1654 const int rc = !val.IsEmpty() && val->IsInt32() ? val->Int32Value() : 0;
1655
1656 if (!HandleException(exception, "interrupt"))
1657 V8::TerminateExecution(fThreadId);
1658
1659 fInterruptCallback->CreationContext()->Exit();
1660
1661 return rc<10 || rc>255 ? -42 : rc;
1662}
1663
1664Handle<Value> InterpreterV8::FuncTriggerInterrupt(const Arguments &args)
1665{
1666 string data;
1667 for (int i=0; i<args.Length(); i++)
1668 {
1669 const String::AsciiValue str(args[i]);
1670
1671 if (string(*str).find_first_of('\n')!=string::npos)
1672 return ThrowException(String::New("No argument must contain line breaks."));
1673
1674 if (!*str)
1675 continue;
1676
1677 data += *str;
1678 data += ' ';
1679 }
1680
1681 HandleScope handle_scope;
1682
1683 const Handle<Value> rc = HandleInterruptImp(Tools::Trim(data), Time().JavaDate());
1684 return handle_scope.Close(rc);
1685}
1686
1687// ==========================================================================
1688// Class 'Subscription'
1689// ==========================================================================
1690
1691Handle<Value> InterpreterV8::FuncSubscription(const Arguments &args)
1692{
1693 if (args.Length()!=1 && args.Length()!=2)
1694 return ThrowException(String::New("Number of arguments must be one or two."));
1695
1696 if (!args[0]->IsString())
1697 return ThrowException(String::New("Argument 1 must be a string."));
1698
1699 if (args.Length()==2 && !args[1]->IsFunction())
1700 return ThrowException(String::New("Argument 2 must be a function."));
1701
1702 const String::AsciiValue str(args[0]);
1703
1704 if (!args.IsConstructCall())
1705 {
1706 const auto it = fReverseMap.find(*str);
1707 if (it!=fReverseMap.end())
1708 return it->second;
1709
1710 return Undefined();
1711 }
1712
1713 const HandleScope handle_scope;
1714
1715 Handle<Object> self = args.This();
1716 self->Set(String::New("get"), FunctionTemplate::New(WrapGetData)->GetFunction(), ReadOnly);
1717 self->Set(String::New("close"), FunctionTemplate::New(WrapClose)->GetFunction(), ReadOnly);
1718 self->Set(String::New("name"), String::New(*str), ReadOnly);
1719 self->Set(String::New("isOpen"), Boolean::New(true));
1720
1721 if (args.Length()==2)
1722 self->Set(String::New("onchange"), args[1]);
1723
1724 fReverseMap[*str] = Persistent<Object>::New(self);
1725
1726 void *ptr = JsSubscribe(*str);
1727 if (ptr==0)
1728 return ThrowException(String::New(("Subscription to '"+string(*str)+"' already exists.").c_str()));
1729
1730 self->SetInternalField(0, External::New(ptr));
1731
1732 return Undefined();
1733
1734 // Persistent<Object> p = Persistent<Object>::New(obj->NewInstance());
1735 // obj.MakeWeak((void*)1, Cleanup);
1736 // return obj;
1737}
1738
1739// ==========================================================================
1740// Astrometry
1741// ==========================================================================
1742#ifdef HAVE_NOVA
1743
1744double InterpreterV8::GetDataMember(const Arguments &args, const char *name)
1745{
1746 return args.This()->Get(String::New(name))->NumberValue();
1747}
1748
1749Handle<Value> InterpreterV8::CalcDist(const Arguments &args, const bool local)
1750{
1751 if (args.Length()!=2)
1752 return ThrowException(String::New("dist must not be called with two arguments."));
1753
1754 if (!args[0]->IsObject() || !args[1]->IsObject())
1755 return ThrowException(String::New("at least one argument not an object."));
1756
1757 HandleScope handle_scope;
1758
1759 Handle<Object> obj[2] =
1760 {
1761 Handle<Object>::Cast(args[0]),
1762 Handle<Object>::Cast(args[1])
1763 };
1764
1765 const Handle<String> s_theta = String::New(local?"zd":"dec"); // was: zd
1766 const Handle<String> s_phi = String::New(local?"az":"ra"); // was: az
1767
1768 const double conv_t = M_PI/180;
1769 const double conv_p = local ? -M_PI/180 : M_PI/12;
1770 const double offset = local ? 0 : M_PI;
1771
1772 const double theta0 = offset - obj[0]->Get(s_theta)->NumberValue() * conv_t;
1773 const double phi0 = obj[0]->Get(s_phi )->NumberValue() * conv_p;
1774 const double theta1 = offset - obj[1]->Get(s_theta)->NumberValue() * conv_t;
1775 const double phi1 = obj[1]->Get(s_phi )->NumberValue() * conv_p;
1776
1777 if (!finite(theta0) || !finite(theta1) || !finite(phi0) || !finite(phi1))
1778 return ThrowException(String::New("some values not valid or not finite."));
1779
1780 /*
1781 const double x0 = sin(zd0) * cos(az0); // az0 -= az0
1782 const double y0 = sin(zd0) * sin(az0); // az0 -= az0
1783 const double z0 = cos(zd0);
1784
1785 const double x1 = sin(zd1) * cos(az1); // az1 -= az0
1786 const double y1 = sin(zd1) * sin(az1); // az1 -= az0
1787 const double z1 = cos(zd1);
1788
1789 const double res = acos(x0*x1 + y0*y1 + z0*z1) * 180/M_PI;
1790 */
1791
1792 // cos(az1-az0) = cos(az1)*cos(az0) + sin(az1)*sin(az0)
1793
1794 const double x = sin(theta0) * sin(theta1) * cos(phi1-phi0);
1795 const double y = cos(theta0) * cos(theta1);
1796
1797 const double res = acos(x + y) * 180/M_PI;
1798
1799 return handle_scope.Close(Number::New(res));
1800}
1801
1802Handle<Value> InterpreterV8::LocalDist(const Arguments &args)
1803{
1804 return CalcDist(args, true);
1805}
1806
1807Handle<Value> InterpreterV8::SkyDist(const Arguments &args)
1808{
1809 return CalcDist(args, false);
1810}
1811
1812Handle<Value> InterpreterV8::MoonDisk(const Arguments &args)
1813{
1814 if (args.Length()>1)
1815 return ThrowException(String::New("disk must not be called with more than one argument."));
1816
1817 const uint64_t v = uint64_t(args[0]->NumberValue());
1818 const Time utc = args.Length()==0 ? Time() : Time(v/1000, v%1000);
1819
1820 return Number::New(Nova::GetLunarDisk(utc.JD()));
1821}
1822
1823Handle<Value> InterpreterV8::LocalToSky(const Arguments &args)
1824{
1825 if (args.Length()>1)
1826 return ThrowException(String::New("toSky must not be called with more than one argument."));
1827
1828 if (args.Length()==1 && !args[0]->IsDate())
1829 return ThrowException(String::New("Argument must be a Date"));
1830
1831 Nova::ZdAzPosn hrz;
1832 hrz.zd = GetDataMember(args, "zd");
1833 hrz.az = GetDataMember(args, "az");
1834
1835 if (!finite(hrz.zd) || !finite(hrz.az))
1836 return ThrowException(String::New("zd and az must be finite."));
1837
1838 HandleScope handle_scope;
1839
1840 const Local<Value> date =
1841 args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
1842 if (date.IsEmpty())
1843 return Undefined();
1844
1845 const uint64_t v = uint64_t(date->NumberValue());
1846 const Time utc(v/1000, v%1000);
1847
1848 const Nova::EquPosn equ = Nova::GetEquFromHrz(hrz, utc.JD());
1849
1850 // -----------------------------
1851
1852 Handle<Value> arg[] = { Number::New(equ.ra/15), Number::New(equ.dec), date };
1853 return handle_scope.Close(fTemplateSky->GetFunction()->NewInstance(3, arg));
1854}
1855
1856Handle<Value> InterpreterV8::SkyToLocal(const Arguments &args)
1857{
1858 if (args.Length()>1)
1859 return ThrowException(String::New("toLocal must not be called with more than one argument."));
1860
1861 if (args.Length()==1 && !args[0]->IsDate())
1862 return ThrowException(String::New("Argument must be a Date"));
1863
1864 Nova::EquPosn equ;
1865 equ.ra = GetDataMember(args, "ra")*15;
1866 equ.dec = GetDataMember(args, "dec");
1867
1868 if (!finite(equ.ra) || !finite(equ.dec))
1869 return ThrowException(String::New("Ra and dec must be finite."));
1870
1871 HandleScope handle_scope;
1872
1873 const Local<Value> date =
1874 args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
1875 if (date.IsEmpty())
1876 return Undefined();
1877
1878 const uint64_t v = uint64_t(date->NumberValue());
1879 const Time utc(v/1000, v%1000);
1880
1881 const Nova::ZdAzPosn hrz = Nova::GetHrzFromEqu(equ, utc.JD());
1882
1883 Handle<Value> arg[] = { Number::New(hrz.zd), Number::New(hrz.az), date };
1884 return handle_scope.Close(fTemplateLocal->GetFunction()->NewInstance(3, arg));
1885}
1886
1887Handle<Value> InterpreterV8::MoonToLocal(const Arguments &args)
1888{
1889 if (args.Length()>0)
1890 return ThrowException(String::New("toLocal must not be called with arguments."));
1891
1892 Nova::EquPosn equ;
1893 equ.ra = GetDataMember(args, "ra")*15;
1894 equ.dec = GetDataMember(args, "dec");
1895
1896 if (!finite(equ.ra) || !finite(equ.dec))
1897 return ThrowException(String::New("ra and dec must be finite."));
1898
1899 HandleScope handle_scope;
1900
1901 const Local<Value> date = args.This()->Get(String::New("time"));
1902 if (date.IsEmpty() || date->IsUndefined() )
1903 return Undefined();
1904
1905 const uint64_t v = uint64_t(date->NumberValue());
1906 const Time utc(v/1000, v%1000);
1907
1908 const Nova::ZdAzPosn hrz = Nova::GetHrzFromEqu(equ, utc.JD());
1909
1910 Handle<Value> arg[] = { Number::New(hrz.zd), Number::New(hrz.az), date };
1911 return handle_scope.Close(fTemplateLocal->GetFunction()->NewInstance(3, arg));
1912}
1913
1914Handle<Value> InterpreterV8::ConstructorMoon(const Arguments &args)
1915{
1916 if (args.Length()>1)
1917 return ThrowException(String::New("Moon constructor must not be called with more than one argument."));
1918
1919 if (args.Length()==1 && !args[0]->IsDate())
1920 return ThrowException(String::New("Argument must be a Date"));
1921
1922 HandleScope handle_scope;
1923
1924 const Local<Value> date =
1925 args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
1926 if (date.IsEmpty())
1927 return Undefined();
1928
1929 const uint64_t v = uint64_t(date->NumberValue());
1930 const Time utc(v/1000, v%1000);
1931
1932 const Nova::EquPosn equ = Nova::GetLunarEquCoords(utc.JD(), 0.01);
1933
1934 // ----------------------------
1935
1936 if (!args.IsConstructCall())
1937 return handle_scope.Close(Constructor(args));
1938
1939 Handle<Function> function =
1940 FunctionTemplate::New(MoonToLocal)->GetFunction();
1941 if (function.IsEmpty())
1942 return Undefined();
1943
1944 Handle<Object> self = args.This();
1945 self->Set(String::New("ra"), Number::New(equ.ra/15), ReadOnly);
1946 self->Set(String::New("dec"), Number::New(equ.dec), ReadOnly);
1947 self->Set(String::New("toLocal"), function, ReadOnly);
1948 self->Set(String::New("time"), date, ReadOnly);
1949
1950 return handle_scope.Close(self);
1951}
1952
1953Handle<Value> InterpreterV8::ConstructorSky(const Arguments &args)
1954{
1955 if (args.Length()<2 || args.Length()>3)
1956 return ThrowException(String::New("Sky constructor takes two or three arguments."));
1957
1958 if (args.Length()==3 && !args[2]->IsDate())
1959 return ThrowException(String::New("Third argument must be a Date."));
1960
1961 const double ra = args[0]->NumberValue();
1962 const double dec = args[1]->NumberValue();
1963
1964 if (!finite(ra) || !finite(dec))
1965 return ThrowException(String::New("Both arguments to Sky must be valid numbers."));
1966
1967 // ----------------------------
1968
1969 HandleScope handle_scope;
1970
1971 if (!args.IsConstructCall())
1972 return handle_scope.Close(Constructor(args));
1973
1974 Handle<Function> function =
1975 FunctionTemplate::New(SkyToLocal)->GetFunction();
1976 if (function.IsEmpty())
1977 return Undefined();
1978
1979 Handle<Object> self = args.This();
1980 self->Set(String::New("ra"), Number::New(ra), ReadOnly);
1981 self->Set(String::New("dec"), Number::New(dec), ReadOnly);
1982 self->Set(String::New("toLocal"), function, ReadOnly);
1983 if (args.Length()==3)
1984 self->Set(String::New("time"), args[2], ReadOnly);
1985
1986 return handle_scope.Close(self);
1987}
1988
1989Handle<Value> InterpreterV8::ConstructorLocal(const Arguments &args)
1990{
1991 if (args.Length()<2 || args.Length()>3)
1992 return ThrowException(String::New("Local constructor takes two or three arguments."));
1993
1994 if (args.Length()==3 && !args[2]->IsDate())
1995 return ThrowException(String::New("Third argument must be a Date."));
1996
1997 const double zd = args[0]->NumberValue();
1998 const double az = args[1]->NumberValue();
1999
2000 if (!finite(zd) || !finite(az))
2001 return ThrowException(String::New("Both arguments to Local must be valid numbers."));
2002
2003 // --------------------
2004
2005 HandleScope handle_scope;
2006
2007 if (!args.IsConstructCall())
2008 return handle_scope.Close(Constructor(args));
2009
2010 Handle<Function> function =
2011 FunctionTemplate::New(LocalToSky)->GetFunction();
2012 if (function.IsEmpty())
2013 return Undefined();
2014
2015 Handle<Object> self = args.This();
2016 self->Set(String::New("zd"), Number::New(zd), ReadOnly);
2017 self->Set(String::New("az"), Number::New(az), ReadOnly);
2018 self->Set(String::New("toSky"), function, ReadOnly);
2019 if (args.Length()==3)
2020 self->Set(String::New("time"), args[2], ReadOnly);
2021
2022 return handle_scope.Close(self);
2023}
2024
2025Handle<Object> InterpreterV8::ConstructRiseSet(const Handle<Value> time, const Nova::RstTime &rst, const bool &rc)
2026{
2027 Handle<Object> obj = Object::New();
2028 obj->Set(String::New("time"), time, ReadOnly);
2029
2030 const uint64_t v = uint64_t(time->NumberValue());
2031 const double jd = Time(v/1000, v%1000).JD();
2032
2033 const bool isUp = rc>0 ||
2034 (rst.rise<rst.set && (jd>rst.rise && jd<rst.set)) ||
2035 (rst.rise>rst.set && (jd<rst.set || jd>rst.rise));
2036
2037 obj->Set(String::New("isUp"), Boolean::New(rc>=0 && isUp), ReadOnly);
2038
2039 if (rc!=0)
2040 return obj;
2041
2042 Handle<Value> rise = Date::New(Time(rst.rise).JavaDate());
2043 Handle<Value> set = Date::New(Time(rst.set).JavaDate());
2044 Handle<Value> trans = Date::New(Time(rst.transit).JavaDate());
2045 if (rise.IsEmpty() || set.IsEmpty() || trans.IsEmpty())
2046 return Handle<Object>();
2047
2048 obj->Set(String::New("rise"), rise, ReadOnly);
2049 obj->Set(String::New("set"), set, ReadOnly);
2050 obj->Set(String::New("transit"), trans, ReadOnly);
2051
2052 return obj;
2053}
2054
2055Handle<Value> InterpreterV8::SunHorizon(const Arguments &args)
2056{
2057 if (args.Length()>2)
2058 return ThrowException(String::New("Sun.horizon must not be called with one or two arguments."));
2059
2060 if (args.Length()==2 && !args[1]->IsDate())
2061 return ThrowException(String::New("Second argument must be a Date"));
2062
2063 HandleScope handle_scope;
2064
2065 double hrz = NAN;
2066 if (args.Length()==0 || args[0]->IsNull())
2067 hrz = LN_SOLAR_STANDART_HORIZON;
2068 if (args.Length()>0 && args[0]->IsNumber())
2069 hrz = args[0]->NumberValue();
2070 if (args.Length()>0 && args[0]->IsString())
2071 {
2072 string arg(Tools::Trim(*String::AsciiValue(args[0])));
2073 transform(arg.begin(), arg.end(), arg.begin(), ::tolower);
2074
2075 if (arg==string("horizon").substr(0, arg.length()))
2076 hrz = LN_SOLAR_STANDART_HORIZON;
2077 if (arg==string("civil").substr(0, arg.length()))
2078 hrz = LN_SOLAR_CIVIL_HORIZON;
2079 if (arg==string("nautical").substr(0, arg.length()))
2080 hrz = LN_SOLAR_NAUTIC_HORIZON;
2081 if (arg==string("fact").substr(0, arg.length()))
2082 hrz = -13;
2083 if (arg==string("astronomical").substr(0, arg.length()))
2084 hrz = LN_SOLAR_ASTRONOMICAL_HORIZON;
2085 }
2086
2087 if (!finite(hrz))
2088 return ThrowException(String::New("Second argument did not yield a valid number."));
2089
2090 const Local<Value> date =
2091 args.Length()<2 ? Date::New(Time().JavaDate()) : args[1];
2092 if (date.IsEmpty())
2093 return Undefined();
2094
2095 const uint64_t v = uint64_t(date->NumberValue());
2096 const Time utc(v/1000, v%1000);
2097
2098 Nova::LnLatPosn obs = Nova::ORM();
2099
2100 ln_rst_time sun;
2101 const int rc = ln_get_solar_rst_horizon(utc.JD()-0.5, &obs, hrz, &sun);
2102 Handle<Object> rst = ConstructRiseSet(date, sun, rc);
2103 rst->Set(String::New("horizon"), Number::New(hrz));
2104 return handle_scope.Close(rst);
2105};
2106
2107Handle<Value> InterpreterV8::MoonHorizon(const Arguments &args)
2108{
2109 if (args.Length()>1)
2110 return ThrowException(String::New("Moon.horizon must not be called with one argument."));
2111
2112 if (args.Length()==1 && !args[0]->IsDate())
2113 return ThrowException(String::New("Argument must be a Date"));
2114
2115 HandleScope handle_scope;
2116
2117 const Local<Value> date =
2118 args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
2119 if (date.IsEmpty())
2120 return Undefined();
2121
2122 const uint64_t v = uint64_t(date->NumberValue());
2123 const Time utc(v/1000, v%1000);
2124
2125 Nova::LnLatPosn obs = Nova::ORM();
2126
2127 ln_rst_time moon;
2128 const int rc = ln_get_lunar_rst(utc.JD()-0.5, &obs, &moon);
2129 Handle<Object> rst = ConstructRiseSet(date, moon, rc);
2130 return handle_scope.Close(rst);
2131};
2132#endif
2133
2134// ==========================================================================
2135// Process control
2136// ==========================================================================
2137
2138bool InterpreterV8::HandleException(TryCatch& try_catch, const char *where)
2139{
2140 if (!try_catch.HasCaught() || !try_catch.CanContinue())
2141 return true;
2142
2143 const HandleScope handle_scope;
2144
2145 Handle<Value> except = try_catch.Exception();
2146 if (except.IsEmpty() || except->IsNull())
2147 return true;
2148
2149 const String::AsciiValue exception(except);
2150
2151 const Handle<Message> message = try_catch.Message();
2152 if (message.IsEmpty())
2153 return false;
2154
2155 ostringstream out;
2156
2157 if (!message->GetScriptResourceName()->IsUndefined())
2158 {
2159 // Print (filename):(line number): (message).
2160 const String::AsciiValue filename(message->GetScriptResourceName());
2161 if (filename.length()>0)
2162 {
2163 out << *filename;
2164 if (message->GetLineNumber()>0)
2165 out << ": l." << message->GetLineNumber();
2166 if (*exception)
2167 out << ": ";
2168 }
2169 }
2170
2171 if (*exception)
2172 out << *exception;
2173
2174 out << " [" << where << "]";
2175
2176 JsException(out.str());
2177
2178 // Print line of source code.
2179 const String::AsciiValue sourceline(message->GetSourceLine());
2180 if (*sourceline)
2181 JsException(*sourceline);
2182
2183 // Print wavy underline (GetUnderline is deprecated).
2184 const int start = message->GetStartColumn();
2185 const int end = message->GetEndColumn();
2186
2187 out.str("");
2188 if (start>0)
2189 out << setfill(' ') << setw(start) << ' ';
2190 out << setfill('^') << setw(end-start) << '^';
2191
2192 JsException(out.str());
2193
2194 const String::AsciiValue stack_trace(try_catch.StackTrace());
2195 if (stack_trace.length()<=0)
2196 return false;
2197
2198 if (!*stack_trace)
2199 return false;
2200
2201 const string trace(*stack_trace);
2202
2203 typedef boost::char_separator<char> separator;
2204 const boost::tokenizer<separator> tokenizer(trace, separator("\n"));
2205
2206 // maybe skip: " at internal:"
2207 // maybe skip: " at unknown source:"
2208
2209 auto it = tokenizer.begin();
2210 JsException("");
2211 while (it!=tokenizer.end())
2212 JsException(*it++);
2213
2214 return false;
2215}
2216
2217Handle<Value> InterpreterV8::ExecuteInternal(const string &code)
2218{
2219 // Try/catch and re-throw hides our internal code from
2220 // the displayed exception showing the origin and shows
2221 // the user function instead.
2222 TryCatch exception;
2223
2224 const Handle<Value> result = ExecuteCode(code);
2225
2226 // This hides the location of the exception in the internal code,
2227 // which is wanted.
2228 if (exception.HasCaught())
2229 exception.ReThrow();
2230
2231 return result;
2232}
2233
2234Handle<Value> InterpreterV8::ExecuteCode(const string &code, const string &file)
2235{
2236 HandleScope handle_scope;
2237
2238 const Handle<String> source = String::New(code.c_str(), code.size());
2239 const Handle<String> origin = String::New(file.c_str());
2240 if (source.IsEmpty())
2241 return Undefined();
2242
2243 const Handle<Script> script = Script::Compile(source, origin);
2244 if (script.IsEmpty())
2245 return Undefined();
2246
2247 const Handle<String> __date__ = String::New("__DATE__");
2248 const Handle<String> __file__ = String::New("__FILE__");
2249
2250 Handle<Value> save_date;
2251 Handle<Value> save_file;
2252
2253 Handle<Object> global = Context::GetCurrent()->Global();
2254 if (!global.IsEmpty())
2255 {
2256 struct stat attrib;
2257 if (stat(file.c_str(), &attrib)==0)
2258 {
2259 save_date = global->Get(__date__);
2260 save_file = global->Get(__file__);
2261
2262 global->Set(__file__, String::New(file.c_str()));
2263
2264 const Local<Value> date = Date::New(attrib.st_mtime*1000);
2265 if (!date.IsEmpty())
2266 global->Set(__date__, date);
2267 }
2268 }
2269
2270 const Handle<Value> rc = script->Run();
2271 if (rc.IsEmpty())
2272 return Undefined();
2273
2274 if (!global.IsEmpty() && !save_date.IsEmpty())
2275 {
2276 global->ForceSet(__date__, save_date);
2277 global->ForceSet(__file__, save_file);
2278 }
2279
2280 return handle_scope.Close(rc);
2281}
2282
2283void InterpreterV8::ExecuteConsole()
2284{
2285 JsSetState(3);
2286
2287 WindowLog lout;
2288 lout << "\n " << kUnderline << " JavaScript interpreter " << kReset << " (enter '.q' to quit)\n" << endl;
2289
2290 Readline::StaticPushHistory("java.his");
2291
2292 string command;
2293 while (1)
2294 {
2295 // Create a local handle scope so that left-overs from single
2296 // console inputs will not fill up the memory
2297 const HandleScope handle_scope;
2298
2299 // Unlocking is necessary for the preemption to work
2300 const Unlocker global_unlock;
2301
2302 const string buffer = Tools::Trim(Readline::StaticPrompt(command.empty() ? "JS> " : " \\> "));
2303 if (buffer==".q")
2304 break;
2305
2306 // buffer empty, do nothing
2307 if (buffer.empty())
2308 continue;
2309
2310 // Compose command
2311 if (!command.empty())
2312 command += ' ';
2313 command += buffer;
2314
2315 // If line ends with a backslash, allow addition of next line
2316 auto back = command.rbegin();
2317 if (*back=='\\')
2318 {
2319 *back = ' ';
2320 command = Tools::Trim(command);
2321 continue;
2322 }
2323
2324 // Locking is necessary to be able to execute java script code
2325 const Locker lock;
2326
2327 // Catch exceptions during code compilation
2328 TryCatch exception;
2329
2330 // Execute code which was entered
2331 const Handle<Value> rc = ExecuteCode(command, "console");
2332
2333 // If all went well and the result wasn't undefined then print
2334 // the returned value.
2335 if (!rc->IsUndefined() && !rc->IsFunction())
2336 JsResult(*String::AsciiValue(rc));
2337
2338 if (!HandleException(exception, "console"))
2339 lout << endl;
2340
2341 // Stop all other threads
2342 for (auto it=fThreadIds.begin(); it!=fThreadIds.end(); it++)
2343 V8::TerminateExecution(*it);
2344
2345 // Allow the java scripts (threads) to run and hence to terminate
2346 const Unlocker unlock;
2347
2348 // Wait until all threads are terminated
2349 while (!fThreadIds.empty())
2350 usleep(1000);
2351
2352 // command has been executed, collect new command
2353 command = "";
2354 }
2355
2356 lout << endl;
2357
2358 Readline::StaticPopHistory("java.his");
2359}
2360
2361// ==========================================================================
2362// CORE
2363// ==========================================================================
2364
2365InterpreterV8::InterpreterV8() : fThreadId(-1)
2366{
2367 const string ver(V8::GetVersion());
2368
2369 typedef boost::char_separator<char> separator;
2370 const boost::tokenizer<separator> tokenizer(ver, separator("."));
2371
2372 const vector<string> tok(tokenizer.begin(), tokenizer.end());
2373
2374 const int major = tok.size()>0 ? stol(tok[0]) : -1;
2375 const int minor = tok.size()>1 ? stol(tok[1]) : -1;
2376 const int build = tok.size()>2 ? stol(tok[2]) : -1;
2377
2378 if (major>3 || (major==3 && minor>9) || (major==3 && minor==9 && build>10))
2379 {
2380 const string argv = "--use_strict";
2381 V8::SetFlagsFromString(argv.c_str(), argv.size());
2382 }
2383
2384 /*
2385 const string argv1 = "--prof";
2386 const string argv2 = "--noprof-lazy";
2387
2388 V8::SetFlagsFromString(argv1.c_str(), argv1.size());
2389 V8::SetFlagsFromString(argv2.c_str(), argv2.size());
2390 */
2391
2392 This = this;
2393}
2394
2395Handle<Value> InterpreterV8::Constructor(/*Handle<FunctionTemplate> T,*/ const Arguments &args)
2396{
2397 Handle<Value> argv[args.Length()];
2398
2399 for (int i=0; i<args.Length(); i++)
2400 argv[i] = args[i];
2401
2402 return args.Callee()->NewInstance(args.Length(), argv);
2403}
2404
2405
2406void InterpreterV8::AddFormatToGlobal()// const
2407{
2408 const string code =
2409 "String.form = function(str, arr)"
2410 "{"
2411 "var i = -1;"
2412 "function callback(exp, p0, p1, p2, p3, p4/*, pos, str*/)"
2413 "{"
2414 "if (exp=='%%')"
2415 "return '%';"
2416 ""
2417 "if (arr[++i]===undefined)"
2418 "return undefined;"
2419 ""
2420 "var exp = p2 ? parseInt(p2.substr(1)) : undefined;"
2421 "var base = p3 ? parseInt(p3.substr(1)) : undefined;"
2422 ""
2423 "var val;"
2424 "switch (p4)"
2425 "{"
2426 "case 's': val = arr[i]; break;"
2427 "case 'c': val = arr[i][0]; break;"
2428 "case 'f': val = parseFloat(arr[i]).toFixed(exp); break;"
2429 "case 'p': val = parseFloat(arr[i]).toPrecision(exp); break;"
2430 "case 'e': val = parseFloat(arr[i]).toExponential(exp); break;"
2431 "case 'x': val = parseInt(arr[i]).toString(base?base:16); break;"
2432 "case 'd': val = parseFloat(parseInt(arr[i], base?base:10).toPrecision(exp)).toFixed(0); break;"
2433 //"default:\n"
2434 //" throw new SyntaxError('Conversion specifier '+p4+' unknown.');\n"
2435 "}"
2436 ""
2437 "val = typeof(val)=='object' ? JSON.stringify(val) : val.toString(base);"
2438 ""
2439 "var sz = parseInt(p1); /* padding size */"
2440 "var ch = p1 && p1[0]=='0' ? '0' : ' '; /* isnull? */"
2441 "while (val.length<sz)"
2442 "val = p0 !== undefined ? val+ch : ch+val; /* isminus? */"
2443 ""
2444 "return val;"
2445 "}"
2446 ""
2447 "var regex = /%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd])/g;"
2448 "return str.replace(regex, callback);"
2449 "}"
2450 "\n"
2451 "String.prototype.$ = function()"
2452 "{"
2453 "return String.form(this, Array.prototype.slice.call(arguments));"
2454 "}"
2455 "\n"
2456 "String.prototype.count = function(c,i)"
2457 "{"
2458 "return (this.match(new RegExp(c,i?'gi':'g'))||[]).length;"
2459 "}"/*
2460 "\n"
2461 "var format = function()"
2462 "{"
2463 "return dim.format(arguments[0], Array.prototype.slice.call(arguments,1));"
2464 "}"*/;
2465
2466 // ExcuteInternal does not work properly here...
2467 // If suring compilation an exception is thrown, it will not work
2468 Handle<Script> script = Script::New(String::New(code.c_str()), String::New("internal"));
2469 if (!script.IsEmpty())
2470 script->Run();
2471}
2472
2473void InterpreterV8::JsLoad(const std::string &)
2474{
2475 Readline::SetScriptDepth(1);
2476}
2477
2478void InterpreterV8::JsEnd(const std::string &)
2479{
2480 Readline::SetScriptDepth(0);
2481}
2482
2483bool InterpreterV8::JsRun(const string &filename, const map<string, string> &map)
2484{
2485 const Locker locker;
2486 fThreadId = V8::GetCurrentThreadId();
2487
2488 JsPrint(string("JavaScript Engine V8 ")+V8::GetVersion());
2489
2490 JsLoad(filename);
2491
2492 const HandleScope handle_scope;
2493
2494 // Create a template for the global object.
2495 Handle<ObjectTemplate> dim = ObjectTemplate::New();
2496 dim->Set(String::New("log"), FunctionTemplate::New(WrapLog), ReadOnly);
2497 dim->Set(String::New("alarm"), FunctionTemplate::New(WrapAlarm), ReadOnly);
2498 dim->Set(String::New("wait"), FunctionTemplate::New(WrapWait), ReadOnly);
2499 dim->Set(String::New("send"), FunctionTemplate::New(WrapSend), ReadOnly);
2500 dim->Set(String::New("state"), FunctionTemplate::New(WrapState), ReadOnly);
2501 dim->Set(String::New("version"), Integer::New(DIM_VERSION_NUMBER), ReadOnly);
2502 dim->Set(String::New("getStates"), FunctionTemplate::New(WrapGetStates), ReadOnly);
2503 dim->Set(String::New("getDescription"), FunctionTemplate::New(WrapGetDescription), ReadOnly);
2504 dim->Set(String::New("getServices"), FunctionTemplate::New(WrapGetServices), ReadOnly);
2505
2506 Handle<ObjectTemplate> dimctrl = ObjectTemplate::New();
2507 dimctrl->Set(String::New("defineState"), FunctionTemplate::New(WrapNewState), ReadOnly);
2508 dimctrl->Set(String::New("setState"), FunctionTemplate::New(WrapSetState), ReadOnly);
2509 dimctrl->Set(String::New("getState"), FunctionTemplate::New(WrapGetState), ReadOnly);
2510 dimctrl->Set(String::New("setInterruptHandler"), FunctionTemplate::New(WrapSetInterrupt), ReadOnly);
2511 dimctrl->Set(String::New("triggerInterrupt"), FunctionTemplate::New(WrapTriggerInterrupt), ReadOnly);
2512
2513 Handle<ObjectTemplate> v8 = ObjectTemplate::New();
2514 v8->Set(String::New("sleep"), FunctionTemplate::New(WrapSleep), ReadOnly);
2515 v8->Set(String::New("timeout"), FunctionTemplate::New(WrapTimeout), ReadOnly);
2516 v8->Set(String::New("version"), String::New(V8::GetVersion()), ReadOnly);
2517
2518 Handle<ObjectTemplate> console = ObjectTemplate::New();
2519 console->Set(String::New("out"), FunctionTemplate::New(WrapOut), ReadOnly);
2520 console->Set(String::New("warn"), FunctionTemplate::New(WrapWarn), ReadOnly);
2521
2522 Handle<ObjectTemplate> onchange = ObjectTemplate::New();
2523 onchange->SetNamedPropertyHandler(OnChangeGet, WrapOnChangeSet);
2524 dim->Set(String::New("onchange"), onchange);
2525
2526 Handle<ObjectTemplate> global = ObjectTemplate::New();
2527 global->Set(String::New("v8"), v8, ReadOnly);
2528 global->Set(String::New("dim"), dim, ReadOnly);
2529 global->Set(String::New("dimctrl"), dimctrl, ReadOnly);
2530 global->Set(String::New("console"), console, ReadOnly);
2531 global->Set(String::New("include"), FunctionTemplate::New(WrapInclude), ReadOnly);
2532 global->Set(String::New("exit"), FunctionTemplate::New(WrapExit), ReadOnly);
2533
2534 Handle<FunctionTemplate> sub = FunctionTemplate::New(WrapSubscription);
2535 sub->SetClassName(String::New("Subscription"));
2536 sub->InstanceTemplate()->SetInternalFieldCount(1);
2537 global->Set(String::New("Subscription"), sub, ReadOnly);
2538
2539#ifdef HAVE_SQL
2540 Handle<FunctionTemplate> db = FunctionTemplate::New(WrapDatabase);
2541 db->SetClassName(String::New("Database"));
2542 db->InstanceTemplate()->SetInternalFieldCount(1);
2543 global->Set(String::New("Database"), db, ReadOnly);
2544#endif
2545
2546 Handle<FunctionTemplate> thread = FunctionTemplate::New(WrapThread);
2547 thread->SetClassName(String::New("Thread"));
2548 global->Set(String::New("Thread"), thread, ReadOnly);
2549
2550 Handle<FunctionTemplate> file = FunctionTemplate::New(WrapFile);
2551 file->SetClassName(String::New("File"));
2552 global->Set(String::New("File"), file, ReadOnly);
2553
2554 Handle<FunctionTemplate> evt = FunctionTemplate::New();
2555 evt->SetClassName(String::New("Event"));
2556 global->Set(String::New("Event"), evt, ReadOnly);
2557
2558 Handle<FunctionTemplate> desc = FunctionTemplate::New();
2559 desc->SetClassName(String::New("Description"));
2560 global->Set(String::New("Description"), desc, ReadOnly);
2561
2562 fTemplateEvent = evt;
2563 fTemplateDescription = desc;
2564
2565#ifdef HAVE_MAILX
2566 Handle<FunctionTemplate> mail = FunctionTemplate::New(ConstructorMail);
2567 mail->SetClassName(String::New("Mail"));
2568 global->Set(String::New("Mail"), mail, ReadOnly);
2569#endif
2570
2571#ifdef HAVE_NOVA
2572 Handle<FunctionTemplate> sky = FunctionTemplate::New(ConstructorSky);
2573 sky->SetClassName(String::New("Sky"));
2574 sky->Set(String::New("dist"), FunctionTemplate::New(SkyDist), ReadOnly);
2575 global->Set(String::New("Sky"), sky, ReadOnly);
2576
2577 Handle<FunctionTemplate> loc = FunctionTemplate::New(ConstructorLocal);
2578 loc->SetClassName(String::New("Local"));
2579 loc->Set(String::New("dist"), FunctionTemplate::New(LocalDist), ReadOnly);
2580 global->Set(String::New("Local"), loc, ReadOnly);
2581
2582 Handle<FunctionTemplate> moon = FunctionTemplate::New(ConstructorMoon);
2583 moon->SetClassName(String::New("Moon"));
2584 moon->Set(String::New("disk"), FunctionTemplate::New(MoonDisk), ReadOnly);
2585 moon->Set(String::New("horizon"), FunctionTemplate::New(MoonHorizon), ReadOnly);
2586 global->Set(String::New("Moon"), moon, ReadOnly);
2587
2588 Handle<FunctionTemplate> sun = FunctionTemplate::New();
2589 sun->SetClassName(String::New("Sun"));
2590 sun->Set(String::New("horizon"), FunctionTemplate::New(SunHorizon), ReadOnly);
2591 global->Set(String::New("Sun"), sun, ReadOnly);
2592
2593 fTemplateLocal = loc;
2594 fTemplateSky = sky;
2595#endif
2596
2597 // Persistent
2598 Persistent<Context> context = Context::New(NULL, global);
2599 if (context.IsEmpty())
2600 {
2601 JsException("Creation of global context failed...");
2602 JsEnd(filename);
2603 return false;
2604 }
2605
2606 // Switch off eval(). It is not possible to track it's exceptions.
2607 context->AllowCodeGenerationFromStrings(false);
2608
2609 Context::Scope scope(context);
2610
2611 Handle<Array> args = Array::New(map.size());
2612 for (auto it=map.begin(); it!=map.end(); it++)
2613 args->Set(String::New(it->first.c_str()), String::New(it->second.c_str()));
2614 context->Global()->Set(String::New("$"), args, ReadOnly);
2615 context->Global()->Set(String::New("arg"), args, ReadOnly);
2616
2617 const Local<Value> starttime = Date::New(Time().JavaDate());
2618 if (!starttime.IsEmpty())
2619 context->Global()->Set(String::New("__START__"), starttime, ReadOnly);
2620
2621 //V8::ResumeProfiler();
2622
2623 TryCatch exception;
2624
2625 AddFormatToGlobal();
2626
2627 if (!exception.HasCaught())
2628 {
2629 JsStart(filename);
2630
2631 Locker::StartPreemption(10);
2632
2633 if (filename.empty())
2634 ExecuteConsole();
2635 else
2636 {
2637 // We call script->Run because it is the only way to
2638 // catch exceptions.
2639 const Handle<String> source = String::New(("include('"+filename+"');").c_str());
2640 const Handle<String> origin = String::New("main");
2641 const Handle<Script> script = Script::Compile(source, origin);
2642 if (!script.IsEmpty())
2643 {
2644 JsSetState(3);
2645 script->Run();
2646 }
2647 }
2648
2649 Locker::StopPreemption();
2650
2651 // Stop all other threads
2652 for (auto it=fThreadIds.begin(); it!=fThreadIds.end(); it++)
2653 V8::TerminateExecution(*it);
2654 fThreadIds.clear();
2655 }
2656
2657 // Handle an exception
2658 /*const bool rc =*/ HandleException(exception, "main");
2659
2660 // IsProfilerPaused()
2661 // V8::PauseProfiler();
2662
2663 // -----
2664 // This is how an exit handler could look like, but there is no way to interrupt it
2665 // -----
2666 // Handle<Object> obj = Handle<Object>::Cast(context->Global()->Get(String::New("dim")));
2667 // if (!obj.IsEmpty())
2668 // {
2669 // Handle<Value> onexit = obj->Get(String::New("onexit"));
2670 // if (!onexit->IsUndefined())
2671 // Handle<Function>::Cast(onexit)->NewInstance(0, NULL); // argc, argv
2672 // // Handle<Object> result = Handle<Function>::Cast(onexit)->NewInstance(0, NULL); // argc, argv
2673 // }
2674
2675 //context->Exit();
2676
2677 // The threads are started already and wait to get the lock
2678 // So we have to unlock (manual preemtion) so that they get
2679 // the signal to terminate.
2680 {
2681 const Unlocker unlock;
2682
2683 for (auto it=fThreads.begin(); it!=fThreads.end(); it++)
2684 it->join();
2685 fThreads.clear();
2686 }
2687
2688 // Now we can dispose all persistent handles from state callbacks
2689 for (auto it=fStateCallbacks.begin(); it!=fStateCallbacks.end(); it++)
2690 it->second.Dispose();
2691 fStateCallbacks.clear();
2692
2693 // Now we can dispose the persistent interrupt handler
2694 fInterruptCallback.Dispose();
2695 fInterruptCallback.Clear();
2696
2697 // Now we can dispose all persistent handles from reverse maps
2698 for (auto it=fReverseMap.begin(); it!=fReverseMap.end(); it++)
2699 it->second.Dispose();
2700 fReverseMap.clear();
2701
2702#ifdef HAVE_SQL
2703 // ...and close all database handles
2704 for (auto it=fDatabases.begin(); it!=fDatabases.end(); it++)
2705 delete *it;
2706 fDatabases.clear();
2707#endif
2708
2709 fStates.clear();
2710
2711 context.Dispose();
2712
2713 JsEnd(filename);
2714
2715 return true;
2716}
2717
2718void InterpreterV8::JsStop()
2719{
2720 Locker locker;
2721 V8::TerminateExecution(This->fThreadId);
2722}
2723
2724vector<string> InterpreterV8::JsGetCommandList(const char *, int) const
2725{
2726 vector<string> rc;
2727
2728 rc.emplace_back("for (");
2729 rc.emplace_back("while (");
2730 rc.emplace_back("if (");
2731 rc.emplace_back("switch (");
2732 rc.emplace_back("case ");
2733 rc.emplace_back("var ");
2734 rc.emplace_back("function ");
2735 rc.emplace_back("Date(");
2736 rc.emplace_back("new Date(");
2737 rc.emplace_back("'use strict';");
2738 rc.emplace_back("undefined");
2739 rc.emplace_back("null");
2740 rc.emplace_back("delete ");
2741
2742 rc.emplace_back("dim.log(");
2743 rc.emplace_back("dim.alarm(");
2744 rc.emplace_back("dim.wait(");
2745 rc.emplace_back("dim.send(");
2746 rc.emplace_back("dim.state(");
2747 rc.emplace_back("dim.version");
2748 rc.emplace_back("dim.getStates(");
2749 rc.emplace_back("dim.getDescription(");
2750 rc.emplace_back("dim.getServices(");
2751
2752 rc.emplace_back("dimctrl.defineState(");
2753 rc.emplace_back("dimctrl.setState(");
2754 rc.emplace_back("dimctrl.getState(");
2755 rc.emplace_back("dimctrl.setInterruptHandler(");
2756 rc.emplace_back("dimctrl.triggerInterrupt(");
2757
2758 rc.emplace_back("v8.sleep(");
2759 rc.emplace_back("v8.timeout(");
2760 rc.emplace_back("v8.version()");
2761
2762 rc.emplace_back("console.out(");
2763 rc.emplace_back("console.warn(");
2764
2765 rc.emplace_back("include(");
2766 rc.emplace_back("exit()");
2767
2768#ifdef HAVE_SQL
2769 rc.emplace_back("Database(");
2770 rc.emplace_back("new Database(");
2771
2772 rc.emplace_back(".table");
2773 rc.emplace_back(".user");
2774 rc.emplace_back(".database");
2775 rc.emplace_back(".port");
2776 rc.emplace_back(".query");
2777#endif
2778
2779 rc.emplace_back("Subscription(");
2780 rc.emplace_back("new Subscription(");
2781
2782 rc.emplace_back("Thread(");
2783 rc.emplace_back("new Thread(");
2784
2785 rc.emplace_back("File(");
2786 rc.emplace_back("new File(");
2787
2788 rc.emplace_back("Event(");
2789 rc.emplace_back("new Event(");
2790
2791 rc.emplace_back("Description(");
2792 rc.emplace_back("new Description(");
2793
2794#ifdef HAVE_MAILX
2795 rc.emplace_back("Mail(");
2796 rc.emplace_back("new Mail(");
2797
2798 rc.emplace_back(".subject");
2799 rc.emplace_back(".receipients");
2800 rc.emplace_back(".attachments");
2801 rc.emplace_back(".bcc");
2802 rc.emplace_back(".cc");
2803 rc.emplace_back(".text");
2804 rc.emplace_back(".send(");
2805#endif
2806
2807#ifdef HAVE_NOVA
2808 rc.emplace_back("Sky(");
2809 rc.emplace_back("new Sky(");
2810
2811 rc.emplace_back("Sky.dist");
2812 rc.emplace_back("Local(");
2813
2814 rc.emplace_back("new Local(");
2815 rc.emplace_back("Local.dist");
2816
2817 rc.emplace_back("Moon(");
2818 rc.emplace_back("new Moon(");
2819 rc.emplace_back("Moon.disk(");
2820 rc.emplace_back("Moon.horizon(");
2821
2822 rc.emplace_back("Sun.horizon(");
2823
2824 rc.emplace_back(".zd");
2825 rc.emplace_back(".az");
2826 rc.emplace_back(".ra");
2827 rc.emplace_back(".dec");
2828
2829 rc.emplace_back(".toLocal(");
2830 rc.emplace_back(".toSky(");
2831 rc.emplace_back(".rise");
2832 rc.emplace_back(".set");
2833 rc.emplace_back(".transit");
2834 rc.emplace_back(".isUp");
2835
2836 rc.emplace_back("horizon");
2837 rc.emplace_back("civil");
2838 rc.emplace_back("nautical");
2839 rc.emplace_back("astronomical");
2840#endif
2841
2842 rc.emplace_back(".server");
2843 rc.emplace_back(".service");
2844 rc.emplace_back(".name");
2845 rc.emplace_back(".isCommand");
2846 rc.emplace_back(".format");
2847 rc.emplace_back(".description");
2848 rc.emplace_back(".unit");
2849 rc.emplace_back(".delim");
2850 rc.emplace_back(".isOpen");
2851
2852 rc.emplace_back(".qos");
2853 rc.emplace_back(".size");
2854 rc.emplace_back(".counter");
2855 rc.emplace_back(".type");
2856 rc.emplace_back(".obj");
2857 rc.emplace_back(".data");
2858 rc.emplace_back(".comment");
2859 rc.emplace_back(".index");
2860 rc.emplace_back(".time");
2861 rc.emplace_back(".close()");
2862 rc.emplace_back(".onchange");
2863 rc.emplace_back(".get(");
2864
2865
2866 rc.emplace_back("__DATE__");
2867 rc.emplace_back("__FILE__");
2868
2869 return rc;
2870}
2871
2872#endif
2873
2874InterpreterV8 *InterpreterV8::This = 0;
Note: See TracBrowser for help on using the repository browser.