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

Last change on this file since 18290 was 17655, checked in by tbretz, 11 years ago
To check for not equal one should use != not == and to add a text to a string, the text alone is not enough.
File size: 92.0 KB
Line 
1#include "InterpreterV8.h"
2
3#ifdef HAVE_V8
4
5#include <fstream>
6#include <sstream>
7#include <iomanip>
8
9#include <sys/stat.h>
10
11#include <boost/tokenizer.hpp>
12
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 const Locker locker;
1455
1456 if (fThreadId<0)
1457 return;
1458
1459 const auto it = fReverseMap.find(service);
1460 if (it==fReverseMap.end())
1461 return;
1462
1463 const HandleScope handle_scope;
1464
1465 Handle<Object> obj = it->second;
1466
1467 const Handle<String> onchange = String::New("onchange");
1468 if (!obj->Has(onchange))
1469 return;
1470
1471 const Handle<Value> val = obj->Get(onchange);
1472 if (!val->IsFunction())
1473 return;
1474
1475 obj->CreationContext()->Enter();
1476
1477 // -------------------------------------------------------------------
1478
1479 TryCatch exception;
1480
1481 const int id = V8::GetCurrentThreadId();
1482 fThreadIds.insert(id);
1483
1484 Handle<Value> ret = ConvertEvent(&evt, cnt, service.c_str());
1485 if (ret->IsObject())
1486 Handle<Function>::Cast(val)->Call(obj, 1, &ret);
1487
1488 fThreadIds.erase(id);
1489
1490 if (!HandleException(exception, "Service.onchange"))
1491 V8::TerminateExecution(fThreadId);
1492
1493 if (ret->IsNativeError())
1494 {
1495 JsException(service+".onchange callback - "+*String::AsciiValue(ret));
1496 V8::TerminateExecution(fThreadId);
1497 }
1498
1499 obj->CreationContext()->Exit();
1500}
1501
1502Handle<Value> InterpreterV8::OnChangeSet(Local<String> prop, Local<Value> value, const AccessorInfo &)
1503{
1504 // Returns the value if the setter intercepts the request. Otherwise, returns an empty handle.
1505 const string server = *String::AsciiValue(prop);
1506 auto it = fStateCallbacks.find(server);
1507
1508 if (it!=fStateCallbacks.end())
1509 {
1510 it->second.Dispose();
1511 fStateCallbacks.erase(it);
1512 }
1513
1514 if (value->IsFunction())
1515 fStateCallbacks[server] = Persistent<Object>::New(value->ToObject());
1516
1517 return Handle<Value>();
1518}
1519
1520void InterpreterV8::JsHandleState(const std::string &server, const State &state)
1521{
1522 const Locker locker;
1523
1524 if (fThreadId<0)
1525 return;
1526
1527 auto it = fStateCallbacks.find(server);
1528 if (it==fStateCallbacks.end())
1529 {
1530 it = fStateCallbacks.find("*");
1531 if (it==fStateCallbacks.end())
1532 return;
1533 }
1534
1535 const HandleScope handle_scope;
1536
1537 it->second->CreationContext()->Enter();
1538
1539 // -------------------------------------------------------------------
1540
1541 Handle<ObjectTemplate> obj = ObjectTemplate::New();
1542 obj->Set(String::New("server"), String::New(server.c_str()), ReadOnly);
1543
1544 if (state.index>-256)
1545 {
1546 obj->Set(String::New("index"), Integer::New(state.index), ReadOnly);
1547 obj->Set(String::New("name"), String::New(state.name.c_str()), ReadOnly);
1548 obj->Set(String::New("comment"), String::New(state.comment.c_str()), ReadOnly);
1549 const Local<Value> date = Date::New(state.time.JavaDate());
1550 if (!date.IsEmpty())
1551 obj->Set(String::New("time"), date);
1552 }
1553
1554 // -------------------------------------------------------------------
1555
1556 TryCatch exception;
1557
1558 const int id = V8::GetCurrentThreadId();
1559 fThreadIds.insert(id);
1560
1561 Handle<Value> args[] = { obj->NewInstance() };
1562 Handle<Function> fun = Handle<Function>(Function::Cast(*it->second));
1563 fun->Call(fun, 1, args);
1564
1565 fThreadIds.erase(id);
1566
1567 if (!HandleException(exception, "dim.onchange"))
1568 V8::TerminateExecution(fThreadId);
1569
1570 it->second->CreationContext()->Exit();
1571}
1572
1573// ==========================================================================
1574// Interrupt handling
1575// ==========================================================================
1576
1577Handle<Value> InterpreterV8::FuncSetInterrupt(const Arguments &args)
1578{
1579 if (args.Length()!=1)
1580 return ThrowException(String::New("Number of arguments must be 1."));
1581
1582 if (!args[0]->IsNull() && !args[0]->IsUndefined() && !args[0]->IsFunction())
1583 return ThrowException(String::New("Argument not a function, null or undefined."));
1584
1585 if (args[0]->IsNull() || args[0]->IsUndefined())
1586 {
1587 fInterruptCallback.Dispose();
1588 fInterruptCallback.Clear();
1589 return Undefined();
1590 }
1591
1592 // Returns the value if the setter intercepts the request. Otherwise, returns an empty handle.
1593 fInterruptCallback = Persistent<Object>::New(args[0]->ToObject());
1594 return Undefined();
1595}
1596
1597Handle<Value> InterpreterV8::HandleInterruptImp(string str, uint64_t time)
1598{
1599 if (fInterruptCallback.IsEmpty())
1600 return Handle<Value>();
1601
1602 const size_t p = str.find_last_of('\n');
1603
1604 const string usr = p==string::npos?"":str.substr(p+1);
1605
1606 string irq = p==string::npos?str:str.substr(0, p);
1607 const map<string,string> data = Tools::Split(irq, true);
1608
1609 Local<Value> irq_str = String::New(irq.c_str());
1610 Local<Value> usr_str = String::New(usr.c_str());
1611 Local<Value> date = Date::New(time);
1612 Handle<Object> arr = Array::New(data.size());
1613
1614 if (date.IsEmpty() || arr.IsEmpty())
1615 return Handle<Value>();
1616
1617 for (auto it=data.begin(); it!=data.end(); it++)
1618 arr->Set(String::New(it->first.c_str()), String::New(it->second.c_str()));
1619
1620 Handle<Value> args[] = { irq_str, arr, date, usr_str };
1621 Handle<Function> fun = Handle<Function>(Function::Cast(*fInterruptCallback));
1622
1623 return fun->Call(fun, 4, args);
1624}
1625
1626int InterpreterV8::JsHandleInterrupt(const EventImp &evt)
1627{
1628 const Locker locker;
1629
1630 if (fThreadId<0)
1631 return -42;
1632
1633 const HandleScope handle_scope;
1634
1635 fInterruptCallback->CreationContext()->Enter();
1636
1637 // -------------------------------------------------------------------
1638
1639 TryCatch exception;
1640
1641 const int id = V8::GetCurrentThreadId();
1642 fThreadIds.insert(id);
1643
1644 const Handle<Value> val = HandleInterruptImp(evt.GetString(), evt.GetJavaDate());
1645
1646 fThreadIds.erase(id);
1647
1648 const int rc = !val.IsEmpty() && val->IsInt32() ? val->Int32Value() : 0;
1649
1650 if (!HandleException(exception, "interrupt"))
1651 V8::TerminateExecution(fThreadId);
1652
1653 fInterruptCallback->CreationContext()->Exit();
1654
1655 return rc<10 || rc>255 ? -42 : rc;
1656}
1657
1658Handle<Value> InterpreterV8::FuncTriggerInterrupt(const Arguments &args)
1659{
1660 string data;
1661 for (int i=0; i<args.Length(); i++)
1662 {
1663 const String::AsciiValue str(args[i]);
1664
1665 if (string(*str).find_first_of('\n')!=string::npos)
1666 return ThrowException(String::New("No argument must contain line breaks."));
1667
1668 if (!*str)
1669 continue;
1670
1671 data += *str;
1672 data += ' ';
1673 }
1674
1675 HandleScope handle_scope;
1676
1677 const Handle<Value> rc = HandleInterruptImp(Tools::Trim(data), Time().JavaDate());
1678 return handle_scope.Close(rc);
1679}
1680
1681// ==========================================================================
1682// Class 'Subscription'
1683// ==========================================================================
1684
1685Handle<Value> InterpreterV8::FuncSubscription(const Arguments &args)
1686{
1687 if (args.Length()!=1 && args.Length()!=2)
1688 return ThrowException(String::New("Number of arguments must be one or two."));
1689
1690 if (!args[0]->IsString())
1691 return ThrowException(String::New("Argument 1 must be a string."));
1692
1693 if (args.Length()==2 && !args[1]->IsFunction())
1694 return ThrowException(String::New("Argument 2 must be a function."));
1695
1696 const String::AsciiValue str(args[0]);
1697
1698 if (!args.IsConstructCall())
1699 {
1700 const auto it = fReverseMap.find(*str);
1701 if (it!=fReverseMap.end())
1702 return it->second;
1703
1704 return Undefined();
1705 }
1706
1707 const HandleScope handle_scope;
1708
1709 Handle<Object> self = args.This();
1710 self->Set(String::New("get"), FunctionTemplate::New(WrapGetData)->GetFunction(), ReadOnly);
1711 self->Set(String::New("close"), FunctionTemplate::New(WrapClose)->GetFunction(), ReadOnly);
1712 self->Set(String::New("name"), String::New(*str), ReadOnly);
1713 self->Set(String::New("isOpen"), Boolean::New(true));
1714
1715 if (args.Length()==2)
1716 self->Set(String::New("onchange"), args[1]);
1717
1718 fReverseMap[*str] = Persistent<Object>::New(self);
1719
1720 void *ptr = JsSubscribe(*str);
1721 if (ptr==0)
1722 return ThrowException(String::New(("Subscription to '"+string(*str)+"' already exists.").c_str()));
1723
1724 self->SetInternalField(0, External::New(ptr));
1725
1726 return Undefined();
1727
1728 // Persistent<Object> p = Persistent<Object>::New(obj->NewInstance());
1729 // obj.MakeWeak((void*)1, Cleanup);
1730 // return obj;
1731}
1732
1733// ==========================================================================
1734// Astrometry
1735// ==========================================================================
1736#ifdef HAVE_NOVA
1737
1738double InterpreterV8::GetDataMember(const Arguments &args, const char *name)
1739{
1740 return args.This()->Get(String::New(name))->NumberValue();
1741}
1742
1743Handle<Value> InterpreterV8::CalcDist(const Arguments &args, const bool local)
1744{
1745 if (args.Length()!=2)
1746 return ThrowException(String::New("dist must not be called with two arguments."));
1747
1748 if (!args[0]->IsObject() || !args[1]->IsObject())
1749 return ThrowException(String::New("at least one argument not an object."));
1750
1751 HandleScope handle_scope;
1752
1753 Handle<Object> obj[2] =
1754 {
1755 Handle<Object>::Cast(args[0]),
1756 Handle<Object>::Cast(args[1])
1757 };
1758
1759 const Handle<String> s_theta = String::New(local?"zd":"dec"); // was: zd
1760 const Handle<String> s_phi = String::New(local?"az":"ra"); // was: az
1761
1762 const double conv_t = M_PI/180;
1763 const double conv_p = local ? -M_PI/180 : M_PI/12;
1764 const double offset = local ? 0 : M_PI;
1765
1766 const double theta0 = offset - obj[0]->Get(s_theta)->NumberValue() * conv_t;
1767 const double phi0 = obj[0]->Get(s_phi )->NumberValue() * conv_p;
1768 const double theta1 = offset - obj[1]->Get(s_theta)->NumberValue() * conv_t;
1769 const double phi1 = obj[1]->Get(s_phi )->NumberValue() * conv_p;
1770
1771 if (!finite(theta0) || !finite(theta1) || !finite(phi0) || !finite(phi1))
1772 return ThrowException(String::New("some values not valid or not finite."));
1773
1774 /*
1775 const double x0 = sin(zd0) * cos(az0); // az0 -= az0
1776 const double y0 = sin(zd0) * sin(az0); // az0 -= az0
1777 const double z0 = cos(zd0);
1778
1779 const double x1 = sin(zd1) * cos(az1); // az1 -= az0
1780 const double y1 = sin(zd1) * sin(az1); // az1 -= az0
1781 const double z1 = cos(zd1);
1782
1783 const double res = acos(x0*x1 + y0*y1 + z0*z1) * 180/M_PI;
1784 */
1785
1786 // cos(az1-az0) = cos(az1)*cos(az0) + sin(az1)*sin(az0)
1787
1788 const double x = sin(theta0) * sin(theta1) * cos(phi1-phi0);
1789 const double y = cos(theta0) * cos(theta1);
1790
1791 const double res = acos(x + y) * 180/M_PI;
1792
1793 return handle_scope.Close(Number::New(res));
1794}
1795
1796Handle<Value> InterpreterV8::LocalDist(const Arguments &args)
1797{
1798 return CalcDist(args, true);
1799}
1800
1801Handle<Value> InterpreterV8::SkyDist(const Arguments &args)
1802{
1803 return CalcDist(args, false);
1804}
1805
1806Handle<Value> InterpreterV8::MoonDisk(const Arguments &args)
1807{
1808 if (args.Length()>1)
1809 return ThrowException(String::New("disk must not be called with more than one argument."));
1810
1811 const uint64_t v = uint64_t(args[0]->NumberValue());
1812 const Time utc = args.Length()==0 ? Time() : Time(v/1000, v%1000);
1813
1814 return Number::New(Nova::GetLunarDisk(utc.JD()));
1815}
1816
1817Handle<Value> InterpreterV8::LocalToSky(const Arguments &args)
1818{
1819 if (args.Length()>1)
1820 return ThrowException(String::New("toSky must not be called with more than one argument."));
1821
1822 if (args.Length()==1 && !args[0]->IsDate())
1823 return ThrowException(String::New("Argument must be a Date"));
1824
1825 Nova::ZdAzPosn hrz;
1826 hrz.zd = GetDataMember(args, "zd");
1827 hrz.az = GetDataMember(args, "az");
1828
1829 if (!finite(hrz.zd) || !finite(hrz.az))
1830 return ThrowException(String::New("zd and az must be finite."));
1831
1832 HandleScope handle_scope;
1833
1834 const Local<Value> date =
1835 args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
1836 if (date.IsEmpty())
1837 return Undefined();
1838
1839 const uint64_t v = uint64_t(date->NumberValue());
1840 const Time utc(v/1000, v%1000);
1841
1842 const Nova::EquPosn equ = Nova::GetEquFromHrz(hrz, utc.JD());
1843
1844 // -----------------------------
1845
1846 Handle<Value> arg[] = { Number::New(equ.ra/15), Number::New(equ.dec), date };
1847 return handle_scope.Close(fTemplateSky->GetFunction()->NewInstance(3, arg));
1848}
1849
1850Handle<Value> InterpreterV8::SkyToLocal(const Arguments &args)
1851{
1852 if (args.Length()>1)
1853 return ThrowException(String::New("toLocal must not be called with more than one argument."));
1854
1855 if (args.Length()==1 && !args[0]->IsDate())
1856 return ThrowException(String::New("Argument must be a Date"));
1857
1858 Nova::EquPosn equ;
1859 equ.ra = GetDataMember(args, "ra")*15;
1860 equ.dec = GetDataMember(args, "dec");
1861
1862 if (!finite(equ.ra) || !finite(equ.dec))
1863 return ThrowException(String::New("Ra and dec must be finite."));
1864
1865 HandleScope handle_scope;
1866
1867 const Local<Value> date =
1868 args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
1869 if (date.IsEmpty())
1870 return Undefined();
1871
1872 const uint64_t v = uint64_t(date->NumberValue());
1873 const Time utc(v/1000, v%1000);
1874
1875 const Nova::ZdAzPosn hrz = Nova::GetHrzFromEqu(equ, utc.JD());
1876
1877 Handle<Value> arg[] = { Number::New(hrz.zd), Number::New(hrz.az), date };
1878 return handle_scope.Close(fTemplateLocal->GetFunction()->NewInstance(3, arg));
1879}
1880
1881Handle<Value> InterpreterV8::MoonToLocal(const Arguments &args)
1882{
1883 if (args.Length()>0)
1884 return ThrowException(String::New("toLocal must not be called with arguments."));
1885
1886 Nova::EquPosn equ;
1887 equ.ra = GetDataMember(args, "ra")*15;
1888 equ.dec = GetDataMember(args, "dec");
1889
1890 if (!finite(equ.ra) || !finite(equ.dec))
1891 return ThrowException(String::New("ra and dec must be finite."));
1892
1893 HandleScope handle_scope;
1894
1895 const Local<Value> date = args.This()->Get(String::New("time"));
1896 if (date.IsEmpty() || date->IsUndefined() )
1897 return Undefined();
1898
1899 const uint64_t v = uint64_t(date->NumberValue());
1900 const Time utc(v/1000, v%1000);
1901
1902 const Nova::ZdAzPosn hrz = Nova::GetHrzFromEqu(equ, utc.JD());
1903
1904 Handle<Value> arg[] = { Number::New(hrz.zd), Number::New(hrz.az), date };
1905 return handle_scope.Close(fTemplateLocal->GetFunction()->NewInstance(3, arg));
1906}
1907
1908Handle<Value> InterpreterV8::ConstructorMoon(const Arguments &args)
1909{
1910 if (args.Length()>1)
1911 return ThrowException(String::New("Moon constructor must not be called with more than one argument."));
1912
1913 if (args.Length()==1 && !args[0]->IsDate())
1914 return ThrowException(String::New("Argument must be a Date"));
1915
1916 HandleScope handle_scope;
1917
1918 const Local<Value> date =
1919 args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
1920 if (date.IsEmpty())
1921 return Undefined();
1922
1923 const uint64_t v = uint64_t(date->NumberValue());
1924 const Time utc(v/1000, v%1000);
1925
1926 const Nova::EquPosn equ = Nova::GetLunarEquCoords(utc.JD(), 0.01);
1927
1928 // ----------------------------
1929
1930 if (!args.IsConstructCall())
1931 return handle_scope.Close(Constructor(args));
1932
1933 Handle<Function> function =
1934 FunctionTemplate::New(MoonToLocal)->GetFunction();
1935 if (function.IsEmpty())
1936 return Undefined();
1937
1938 Handle<Object> self = args.This();
1939 self->Set(String::New("ra"), Number::New(equ.ra/15), ReadOnly);
1940 self->Set(String::New("dec"), Number::New(equ.dec), ReadOnly);
1941 self->Set(String::New("toLocal"), function, ReadOnly);
1942 self->Set(String::New("time"), date, ReadOnly);
1943
1944 return handle_scope.Close(self);
1945}
1946
1947Handle<Value> InterpreterV8::ConstructorSky(const Arguments &args)
1948{
1949 if (args.Length()<2 || args.Length()>3)
1950 return ThrowException(String::New("Sky constructor takes two or three arguments."));
1951
1952 if (args.Length()==3 && !args[2]->IsDate())
1953 return ThrowException(String::New("Third argument must be a Date."));
1954
1955 const double ra = args[0]->NumberValue();
1956 const double dec = args[1]->NumberValue();
1957
1958 if (!finite(ra) || !finite(dec))
1959 return ThrowException(String::New("Both arguments to Sky must be valid numbers."));
1960
1961 // ----------------------------
1962
1963 HandleScope handle_scope;
1964
1965 if (!args.IsConstructCall())
1966 return handle_scope.Close(Constructor(args));
1967
1968 Handle<Function> function =
1969 FunctionTemplate::New(SkyToLocal)->GetFunction();
1970 if (function.IsEmpty())
1971 return Undefined();
1972
1973 Handle<Object> self = args.This();
1974 self->Set(String::New("ra"), Number::New(ra), ReadOnly);
1975 self->Set(String::New("dec"), Number::New(dec), ReadOnly);
1976 self->Set(String::New("toLocal"), function, ReadOnly);
1977 if (args.Length()==3)
1978 self->Set(String::New("time"), args[2], ReadOnly);
1979
1980 return handle_scope.Close(self);
1981}
1982
1983Handle<Value> InterpreterV8::ConstructorLocal(const Arguments &args)
1984{
1985 if (args.Length()<2 || args.Length()>3)
1986 return ThrowException(String::New("Local constructor takes two or three arguments."));
1987
1988 if (args.Length()==3 && !args[2]->IsDate())
1989 return ThrowException(String::New("Third argument must be a Date."));
1990
1991 const double zd = args[0]->NumberValue();
1992 const double az = args[1]->NumberValue();
1993
1994 if (!finite(zd) || !finite(az))
1995 return ThrowException(String::New("Both arguments to Local must be valid numbers."));
1996
1997 // --------------------
1998
1999 HandleScope handle_scope;
2000
2001 if (!args.IsConstructCall())
2002 return handle_scope.Close(Constructor(args));
2003
2004 Handle<Function> function =
2005 FunctionTemplate::New(LocalToSky)->GetFunction();
2006 if (function.IsEmpty())
2007 return Undefined();
2008
2009 Handle<Object> self = args.This();
2010 self->Set(String::New("zd"), Number::New(zd), ReadOnly);
2011 self->Set(String::New("az"), Number::New(az), ReadOnly);
2012 self->Set(String::New("toSky"), function, ReadOnly);
2013 if (args.Length()==3)
2014 self->Set(String::New("time"), args[2], ReadOnly);
2015
2016 return handle_scope.Close(self);
2017}
2018
2019Handle<Object> InterpreterV8::ConstructRiseSet(const Handle<Value> time, const Nova::RstTime &rst, const bool &rc)
2020{
2021 Handle<Object> obj = Object::New();
2022 obj->Set(String::New("time"), time, ReadOnly);
2023
2024 const uint64_t v = uint64_t(time->NumberValue());
2025 const double jd = Time(v/1000, v%1000).JD();
2026
2027 const bool isUp = rc>0 ||
2028 (rst.rise<rst.set && (jd>rst.rise && jd<rst.set)) ||
2029 (rst.rise>rst.set && (jd<rst.set || jd>rst.rise));
2030
2031 obj->Set(String::New("isUp"), Boolean::New(rc>=0 && isUp), ReadOnly);
2032
2033 if (rc!=0)
2034 return obj;
2035
2036 Handle<Value> rise = Date::New(Time(rst.rise).JavaDate());
2037 Handle<Value> set = Date::New(Time(rst.set).JavaDate());
2038 Handle<Value> trans = Date::New(Time(rst.transit).JavaDate());
2039 if (rise.IsEmpty() || set.IsEmpty() || trans.IsEmpty())
2040 return Handle<Object>();
2041
2042 obj->Set(String::New("rise"), rise, ReadOnly);
2043 obj->Set(String::New("set"), set, ReadOnly);
2044 obj->Set(String::New("transit"), trans, ReadOnly);
2045
2046 return obj;
2047}
2048
2049Handle<Value> InterpreterV8::SunHorizon(const Arguments &args)
2050{
2051 if (args.Length()>2)
2052 return ThrowException(String::New("Sun.horizon must not be called with one or two arguments."));
2053
2054 if (args.Length()==2 && !args[1]->IsDate())
2055 return ThrowException(String::New("Second argument must be a Date"));
2056
2057 HandleScope handle_scope;
2058
2059 double hrz = NAN;
2060 if (args.Length()==0 || args[0]->IsNull())
2061 hrz = LN_SOLAR_STANDART_HORIZON;
2062 if (args.Length()>0 && args[0]->IsNumber())
2063 hrz = args[0]->NumberValue();
2064 if (args.Length()>0 && args[0]->IsString())
2065 {
2066 string arg(Tools::Trim(*String::AsciiValue(args[0])));
2067 transform(arg.begin(), arg.end(), arg.begin(), ::tolower);
2068
2069 if (arg==string("horizon").substr(0, arg.length()))
2070 hrz = LN_SOLAR_STANDART_HORIZON;
2071 if (arg==string("civil").substr(0, arg.length()))
2072 hrz = LN_SOLAR_CIVIL_HORIZON;
2073 if (arg==string("nautical").substr(0, arg.length()))
2074 hrz = LN_SOLAR_NAUTIC_HORIZON;
2075 if (arg==string("fact").substr(0, arg.length()))
2076 hrz = -13;
2077 if (arg==string("astronomical").substr(0, arg.length()))
2078 hrz = LN_SOLAR_ASTRONOMICAL_HORIZON;
2079 }
2080
2081 if (!finite(hrz))
2082 return ThrowException(String::New("Second argument did not yield a valid number."));
2083
2084 const Local<Value> date =
2085 args.Length()<2 ? Date::New(Time().JavaDate()) : args[1];
2086 if (date.IsEmpty())
2087 return Undefined();
2088
2089 const uint64_t v = uint64_t(date->NumberValue());
2090 const Time utc(v/1000, v%1000);
2091
2092 Nova::LnLatPosn obs = Nova::ORM();
2093
2094 ln_rst_time sun;
2095 const int rc = ln_get_solar_rst_horizon(utc.JD()-0.5, &obs, hrz, &sun);
2096 Handle<Object> rst = ConstructRiseSet(date, sun, rc);
2097 rst->Set(String::New("horizon"), Number::New(hrz));
2098 return handle_scope.Close(rst);
2099};
2100
2101Handle<Value> InterpreterV8::MoonHorizon(const Arguments &args)
2102{
2103 if (args.Length()>1)
2104 return ThrowException(String::New("Moon.horizon must not be called with one argument."));
2105
2106 if (args.Length()==1 && !args[0]->IsDate())
2107 return ThrowException(String::New("Argument must be a Date"));
2108
2109 HandleScope handle_scope;
2110
2111 const Local<Value> date =
2112 args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
2113 if (date.IsEmpty())
2114 return Undefined();
2115
2116 const uint64_t v = uint64_t(date->NumberValue());
2117 const Time utc(v/1000, v%1000);
2118
2119 Nova::LnLatPosn obs = Nova::ORM();
2120
2121 ln_rst_time moon;
2122 const int rc = ln_get_lunar_rst(utc.JD()-0.5, &obs, &moon);
2123 Handle<Object> rst = ConstructRiseSet(date, moon, rc);
2124 return handle_scope.Close(rst);
2125};
2126#endif
2127
2128// ==========================================================================
2129// Process control
2130// ==========================================================================
2131
2132bool InterpreterV8::HandleException(TryCatch& try_catch, const char *where)
2133{
2134 if (!try_catch.HasCaught() || !try_catch.CanContinue())
2135 return true;
2136
2137 const HandleScope handle_scope;
2138
2139 Handle<Value> except = try_catch.Exception();
2140 if (except.IsEmpty() || except->IsNull())
2141 return true;
2142
2143 const String::AsciiValue exception(except);
2144
2145 const Handle<Message> message = try_catch.Message();
2146 if (message.IsEmpty())
2147 return false;
2148
2149 ostringstream out;
2150
2151 if (!message->GetScriptResourceName()->IsUndefined())
2152 {
2153 // Print (filename):(line number): (message).
2154 const String::AsciiValue filename(message->GetScriptResourceName());
2155 if (filename.length()>0)
2156 {
2157 out << *filename;
2158 if (message->GetLineNumber()>0)
2159 out << ": l." << message->GetLineNumber();
2160 if (*exception)
2161 out << ": ";
2162 }
2163 }
2164
2165 if (*exception)
2166 out << *exception;
2167
2168 out << " [" << where << "]";
2169
2170 JsException(out.str());
2171
2172 // Print line of source code.
2173 const String::AsciiValue sourceline(message->GetSourceLine());
2174 if (*sourceline)
2175 JsException(*sourceline);
2176
2177 // Print wavy underline (GetUnderline is deprecated).
2178 const int start = message->GetStartColumn();
2179 const int end = message->GetEndColumn();
2180
2181 out.str("");
2182 if (start>0)
2183 out << setfill(' ') << setw(start) << ' ';
2184 out << setfill('^') << setw(end-start) << '^';
2185
2186 JsException(out.str());
2187
2188 const String::AsciiValue stack_trace(try_catch.StackTrace());
2189 if (stack_trace.length()<=0)
2190 return false;
2191
2192 if (!*stack_trace)
2193 return false;
2194
2195 const string trace(*stack_trace);
2196
2197 typedef boost::char_separator<char> separator;
2198 const boost::tokenizer<separator> tokenizer(trace, separator("\n"));
2199
2200 // maybe skip: " at internal:"
2201 // maybe skip: " at unknown source:"
2202
2203 auto it = tokenizer.begin();
2204 JsException("");
2205 while (it!=tokenizer.end())
2206 JsException(*it++);
2207
2208 return false;
2209}
2210
2211Handle<Value> InterpreterV8::ExecuteInternal(const string &code)
2212{
2213 // Try/catch and re-throw hides our internal code from
2214 // the displayed exception showing the origin and shows
2215 // the user function instead.
2216 TryCatch exception;
2217
2218 const Handle<Value> result = ExecuteCode(code);
2219
2220 // This hides the location of the exception in the internal code,
2221 // which is wanted.
2222 if (exception.HasCaught())
2223 exception.ReThrow();
2224
2225 return result;
2226}
2227
2228Handle<Value> InterpreterV8::ExecuteCode(const string &code, const string &file)
2229{
2230 HandleScope handle_scope;
2231
2232 const Handle<String> source = String::New(code.c_str(), code.size());
2233 const Handle<String> origin = String::New(file.c_str());
2234 if (source.IsEmpty())
2235 return Undefined();
2236
2237 const Handle<Script> script = Script::Compile(source, origin);
2238 if (script.IsEmpty())
2239 return Undefined();
2240
2241 const Handle<String> __date__ = String::New("__DATE__");
2242 const Handle<String> __file__ = String::New("__FILE__");
2243
2244 Handle<Value> save_date;
2245 Handle<Value> save_file;
2246
2247 Handle<Object> global = Context::GetCurrent()->Global();
2248 if (!global.IsEmpty())
2249 {
2250 struct stat attrib;
2251 if (stat(file.c_str(), &attrib)==0)
2252 {
2253 save_date = global->Get(__date__);
2254 save_file = global->Get(__file__);
2255
2256 global->Set(__file__, String::New(file.c_str()));
2257
2258 const Local<Value> date = Date::New(attrib.st_mtime*1000);
2259 if (!date.IsEmpty())
2260 global->Set(__date__, date);
2261 }
2262 }
2263
2264 const Handle<Value> rc = script->Run();
2265 if (rc.IsEmpty())
2266 return Undefined();
2267
2268 if (!global.IsEmpty() && !save_date.IsEmpty())
2269 {
2270 global->ForceSet(__date__, save_date);
2271 global->ForceSet(__file__, save_file);
2272 }
2273
2274 return handle_scope.Close(rc);
2275}
2276
2277void InterpreterV8::ExecuteConsole()
2278{
2279 JsSetState(3);
2280
2281 WindowLog lout;
2282 lout << "\n " << kUnderline << " JavaScript interpreter " << kReset << " (enter '.q' to quit)\n" << endl;
2283
2284 Readline::StaticPushHistory("java.his");
2285
2286 string command;
2287 while (1)
2288 {
2289 // Create a local handle scope so that left-overs from single
2290 // console inputs will not fill up the memory
2291 const HandleScope handle_scope;
2292
2293 // Unlocking is necessary for the preemption to work
2294 const Unlocker global_unlock;
2295
2296 const string buffer = Tools::Trim(Readline::StaticPrompt(command.empty() ? "JS> " : " \\> "));
2297 if (buffer==".q")
2298 break;
2299
2300 // buffer empty, do nothing
2301 if (buffer.empty())
2302 continue;
2303
2304 // Compose command
2305 if (!command.empty())
2306 command += ' ';
2307 command += buffer;
2308
2309 // If line ends with a backslash, allow addition of next line
2310 auto back = command.rbegin();
2311 if (*back=='\\')
2312 {
2313 *back = ' ';
2314 command = Tools::Trim(command);
2315 continue;
2316 }
2317
2318 // Locking is necessary to be able to execute java script code
2319 const Locker lock;
2320
2321 // Catch exceptions during code compilation
2322 TryCatch exception;
2323
2324 // Execute code which was entered
2325 const Handle<Value> rc = ExecuteCode(command, "console");
2326
2327 // If all went well and the result wasn't undefined then print
2328 // the returned value.
2329 if (!rc->IsUndefined() && !rc->IsFunction())
2330 JsResult(*String::AsciiValue(rc));
2331
2332 if (!HandleException(exception, "console"))
2333 lout << endl;
2334
2335 // Stop all other threads
2336 for (auto it=fThreadIds.begin(); it!=fThreadIds.end(); it++)
2337 V8::TerminateExecution(*it);
2338
2339 // Allow the java scripts (threads) to run and hence to terminate
2340 const Unlocker unlock;
2341
2342 // Wait until all threads are terminated
2343 while (!fThreadIds.empty())
2344 usleep(1000);
2345
2346 // command has been executed, collect new command
2347 command = "";
2348 }
2349
2350 lout << endl;
2351
2352 Readline::StaticPopHistory("java.his");
2353}
2354
2355// ==========================================================================
2356// CORE
2357// ==========================================================================
2358
2359InterpreterV8::InterpreterV8() : fThreadId(-1)
2360{
2361 const string ver(V8::GetVersion());
2362
2363 typedef boost::char_separator<char> separator;
2364 const boost::tokenizer<separator> tokenizer(ver, separator("."));
2365
2366 const vector<string> tok(tokenizer.begin(), tokenizer.end());
2367
2368 const int major = tok.size()>0 ? stol(tok[0]) : -1;
2369 const int minor = tok.size()>1 ? stol(tok[1]) : -1;
2370 const int build = tok.size()>2 ? stol(tok[2]) : -1;
2371
2372 if (major>3 || (major==3 && minor>9) || (major==3 && minor==9 && build>10))
2373 {
2374 const string argv = "--use_strict";
2375 V8::SetFlagsFromString(argv.c_str(), argv.size());
2376 }
2377
2378 /*
2379 const string argv1 = "--prof";
2380 const string argv2 = "--noprof-lazy";
2381
2382 V8::SetFlagsFromString(argv1.c_str(), argv1.size());
2383 V8::SetFlagsFromString(argv2.c_str(), argv2.size());
2384 */
2385
2386 This = this;
2387}
2388
2389Handle<Value> InterpreterV8::Constructor(/*Handle<FunctionTemplate> T,*/ const Arguments &args)
2390{
2391 Handle<Value> argv[args.Length()];
2392
2393 for (int i=0; i<args.Length(); i++)
2394 argv[i] = args[i];
2395
2396 return args.Callee()->NewInstance(args.Length(), argv);
2397}
2398
2399
2400void InterpreterV8::AddFormatToGlobal()// const
2401{
2402 const string code =
2403 "String.form = function(str, arr)"
2404 "{"
2405 "var i = -1;"
2406 "function callback(exp, p0, p1, p2, p3, p4/*, pos, str*/)"
2407 "{"
2408 "if (exp=='%%')"
2409 "return '%';"
2410 ""
2411 "if (arr[++i]===undefined)"
2412 "return undefined;"
2413 ""
2414 "var exp = p2 ? parseInt(p2.substr(1)) : undefined;"
2415 "var base = p3 ? parseInt(p3.substr(1)) : undefined;"
2416 ""
2417 "var val;"
2418 "switch (p4)"
2419 "{"
2420 "case 's': val = arr[i]; break;"
2421 "case 'c': val = arr[i][0]; break;"
2422 "case 'f': val = parseFloat(arr[i]).toFixed(exp); break;"
2423 "case 'p': val = parseFloat(arr[i]).toPrecision(exp); break;"
2424 "case 'e': val = parseFloat(arr[i]).toExponential(exp); break;"
2425 "case 'x': val = parseInt(arr[i]).toString(base?base:16); break;"
2426 "case 'd': val = parseFloat(parseInt(arr[i], base?base:10).toPrecision(exp)).toFixed(0); break;"
2427 //"default:\n"
2428 //" throw new SyntaxError('Conversion specifier '+p4+' unknown.');\n"
2429 "}"
2430 ""
2431 "val = typeof(val)=='object' ? JSON.stringify(val) : val.toString(base);"
2432 ""
2433 "var sz = parseInt(p1); /* padding size */"
2434 "var ch = p1 && p1[0]=='0' ? '0' : ' '; /* isnull? */"
2435 "while (val.length<sz)"
2436 "val = p0 !== undefined ? val+ch : ch+val; /* isminus? */"
2437 ""
2438 "return val;"
2439 "}"
2440 ""
2441 "var regex = /%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd])/g;"
2442 "return str.replace(regex, callback);"
2443 "}"
2444 "\n"
2445 "String.prototype.$ = function()"
2446 "{"
2447 "return String.form(this, Array.prototype.slice.call(arguments));"
2448 "}"
2449 "\n"
2450 "String.prototype.count = function(c,i)"
2451 "{"
2452 "return (this.match(new RegExp(c,i?'gi':'g'))||[]).length;"
2453 "}"/*
2454 "\n"
2455 "var format = function()"
2456 "{"
2457 "return dim.format(arguments[0], Array.prototype.slice.call(arguments,1));"
2458 "}"*/;
2459
2460 // ExcuteInternal does not work properly here...
2461 // If suring compilation an exception is thrown, it will not work
2462 Handle<Script> script = Script::New(String::New(code.c_str()), String::New("internal"));
2463 if (!script.IsEmpty())
2464 script->Run();
2465}
2466
2467void InterpreterV8::JsLoad(const std::string &)
2468{
2469 Readline::SetScriptDepth(1);
2470}
2471
2472void InterpreterV8::JsEnd(const std::string &)
2473{
2474 Readline::SetScriptDepth(0);
2475}
2476
2477bool InterpreterV8::JsRun(const string &filename, const map<string, string> &map)
2478{
2479 const Locker locker;
2480 fThreadId = V8::GetCurrentThreadId();
2481
2482 JsPrint(string("JavaScript Engine V8 ")+V8::GetVersion());
2483
2484 JsLoad(filename);
2485
2486 const HandleScope handle_scope;
2487
2488 // Create a template for the global object.
2489 Handle<ObjectTemplate> dim = ObjectTemplate::New();
2490 dim->Set(String::New("log"), FunctionTemplate::New(WrapLog), ReadOnly);
2491 dim->Set(String::New("alarm"), FunctionTemplate::New(WrapAlarm), ReadOnly);
2492 dim->Set(String::New("wait"), FunctionTemplate::New(WrapWait), ReadOnly);
2493 dim->Set(String::New("send"), FunctionTemplate::New(WrapSend), ReadOnly);
2494 dim->Set(String::New("state"), FunctionTemplate::New(WrapState), ReadOnly);
2495 dim->Set(String::New("version"), Integer::New(DIM_VERSION_NUMBER), ReadOnly);
2496 dim->Set(String::New("getStates"), FunctionTemplate::New(WrapGetStates), ReadOnly);
2497 dim->Set(String::New("getDescription"), FunctionTemplate::New(WrapGetDescription), ReadOnly);
2498 dim->Set(String::New("getServices"), FunctionTemplate::New(WrapGetServices), ReadOnly);
2499
2500 Handle<ObjectTemplate> dimctrl = ObjectTemplate::New();
2501 dimctrl->Set(String::New("defineState"), FunctionTemplate::New(WrapNewState), ReadOnly);
2502 dimctrl->Set(String::New("setState"), FunctionTemplate::New(WrapSetState), ReadOnly);
2503 dimctrl->Set(String::New("getState"), FunctionTemplate::New(WrapGetState), ReadOnly);
2504 dimctrl->Set(String::New("setInterruptHandler"), FunctionTemplate::New(WrapSetInterrupt), ReadOnly);
2505 dimctrl->Set(String::New("triggerInterrupt"), FunctionTemplate::New(WrapTriggerInterrupt), ReadOnly);
2506
2507 Handle<ObjectTemplate> v8 = ObjectTemplate::New();
2508 v8->Set(String::New("sleep"), FunctionTemplate::New(WrapSleep), ReadOnly);
2509 v8->Set(String::New("timeout"), FunctionTemplate::New(WrapTimeout), ReadOnly);
2510 v8->Set(String::New("version"), String::New(V8::GetVersion()), ReadOnly);
2511
2512 Handle<ObjectTemplate> console = ObjectTemplate::New();
2513 console->Set(String::New("out"), FunctionTemplate::New(WrapOut), ReadOnly);
2514 console->Set(String::New("warn"), FunctionTemplate::New(WrapWarn), ReadOnly);
2515
2516 Handle<ObjectTemplate> onchange = ObjectTemplate::New();
2517 onchange->SetNamedPropertyHandler(OnChangeGet, WrapOnChangeSet);
2518 dim->Set(String::New("onchange"), onchange);
2519
2520 Handle<ObjectTemplate> global = ObjectTemplate::New();
2521 global->Set(String::New("v8"), v8, ReadOnly);
2522 global->Set(String::New("dim"), dim, ReadOnly);
2523 global->Set(String::New("dimctrl"), dimctrl, ReadOnly);
2524 global->Set(String::New("console"), console, ReadOnly);
2525 global->Set(String::New("include"), FunctionTemplate::New(WrapInclude), ReadOnly);
2526 global->Set(String::New("exit"), FunctionTemplate::New(WrapExit), ReadOnly);
2527
2528 Handle<FunctionTemplate> sub = FunctionTemplate::New(WrapSubscription);
2529 sub->SetClassName(String::New("Subscription"));
2530 sub->InstanceTemplate()->SetInternalFieldCount(1);
2531 global->Set(String::New("Subscription"), sub, ReadOnly);
2532
2533#ifdef HAVE_SQL
2534 Handle<FunctionTemplate> db = FunctionTemplate::New(WrapDatabase);
2535 db->SetClassName(String::New("Database"));
2536 db->InstanceTemplate()->SetInternalFieldCount(1);
2537 global->Set(String::New("Database"), db, ReadOnly);
2538#endif
2539
2540 Handle<FunctionTemplate> thread = FunctionTemplate::New(WrapThread);
2541 thread->SetClassName(String::New("Thread"));
2542 global->Set(String::New("Thread"), thread, ReadOnly);
2543
2544 Handle<FunctionTemplate> file = FunctionTemplate::New(WrapFile);
2545 file->SetClassName(String::New("File"));
2546 global->Set(String::New("File"), file, ReadOnly);
2547
2548 Handle<FunctionTemplate> evt = FunctionTemplate::New();
2549 evt->SetClassName(String::New("Event"));
2550 global->Set(String::New("Event"), evt, ReadOnly);
2551
2552 Handle<FunctionTemplate> desc = FunctionTemplate::New();
2553 desc->SetClassName(String::New("Description"));
2554 global->Set(String::New("Description"), desc, ReadOnly);
2555
2556 fTemplateEvent = evt;
2557 fTemplateDescription = desc;
2558
2559#ifdef HAVE_MAILX
2560 Handle<FunctionTemplate> mail = FunctionTemplate::New(ConstructorMail);
2561 mail->SetClassName(String::New("Mail"));
2562 global->Set(String::New("Mail"), mail, ReadOnly);
2563#endif
2564
2565#ifdef HAVE_NOVA
2566 Handle<FunctionTemplate> sky = FunctionTemplate::New(ConstructorSky);
2567 sky->SetClassName(String::New("Sky"));
2568 sky->Set(String::New("dist"), FunctionTemplate::New(SkyDist), ReadOnly);
2569 global->Set(String::New("Sky"), sky, ReadOnly);
2570
2571 Handle<FunctionTemplate> loc = FunctionTemplate::New(ConstructorLocal);
2572 loc->SetClassName(String::New("Local"));
2573 loc->Set(String::New("dist"), FunctionTemplate::New(LocalDist), ReadOnly);
2574 global->Set(String::New("Local"), loc, ReadOnly);
2575
2576 Handle<FunctionTemplate> moon = FunctionTemplate::New(ConstructorMoon);
2577 moon->SetClassName(String::New("Moon"));
2578 moon->Set(String::New("disk"), FunctionTemplate::New(MoonDisk), ReadOnly);
2579 moon->Set(String::New("horizon"), FunctionTemplate::New(MoonHorizon), ReadOnly);
2580 global->Set(String::New("Moon"), moon, ReadOnly);
2581
2582 Handle<FunctionTemplate> sun = FunctionTemplate::New();
2583 sun->SetClassName(String::New("Sun"));
2584 sun->Set(String::New("horizon"), FunctionTemplate::New(SunHorizon), ReadOnly);
2585 global->Set(String::New("Sun"), sun, ReadOnly);
2586
2587 fTemplateLocal = loc;
2588 fTemplateSky = sky;
2589#endif
2590
2591 // Persistent
2592 Persistent<Context> context = Context::New(NULL, global);
2593 if (context.IsEmpty())
2594 {
2595 JsException("Creation of global context failed...");
2596 JsEnd(filename);
2597 return false;
2598 }
2599
2600 // Switch off eval(). It is not possible to track it's exceptions.
2601 context->AllowCodeGenerationFromStrings(false);
2602
2603 Context::Scope scope(context);
2604
2605 Handle<Array> args = Array::New(map.size());
2606 for (auto it=map.begin(); it!=map.end(); it++)
2607 args->Set(String::New(it->first.c_str()), String::New(it->second.c_str()));
2608 context->Global()->Set(String::New("$"), args, ReadOnly);
2609 context->Global()->Set(String::New("arg"), args, ReadOnly);
2610
2611 const Local<Value> starttime = Date::New(Time().JavaDate());
2612 if (!starttime.IsEmpty())
2613 context->Global()->Set(String::New("__START__"), starttime, ReadOnly);
2614
2615 //V8::ResumeProfiler();
2616
2617 TryCatch exception;
2618
2619 AddFormatToGlobal();
2620
2621 if (!exception.HasCaught())
2622 {
2623 JsStart(filename);
2624
2625 Locker::StartPreemption(10);
2626
2627 if (filename.empty())
2628 ExecuteConsole();
2629 else
2630 {
2631 // We call script->Run because it is the only way to
2632 // catch exceptions.
2633 const Handle<String> source = String::New(("include('"+filename+"');").c_str());
2634 const Handle<String> origin = String::New("main");
2635 const Handle<Script> script = Script::Compile(source, origin);
2636 if (!script.IsEmpty())
2637 {
2638 JsSetState(3);
2639 script->Run();
2640 }
2641 }
2642
2643 Locker::StopPreemption();
2644
2645 // Stop all other threads
2646 for (auto it=fThreadIds.begin(); it!=fThreadIds.end(); it++)
2647 V8::TerminateExecution(*it);
2648 fThreadIds.clear();
2649 }
2650
2651 // Handle an exception
2652 /*const bool rc =*/ HandleException(exception, "main");
2653
2654 // IsProfilerPaused()
2655 // V8::PauseProfiler();
2656
2657 // -----
2658 // This is how an exit handler could look like, but there is no way to interrupt it
2659 // -----
2660 // Handle<Object> obj = Handle<Object>::Cast(context->Global()->Get(String::New("dim")));
2661 // if (!obj.IsEmpty())
2662 // {
2663 // Handle<Value> onexit = obj->Get(String::New("onexit"));
2664 // if (!onexit->IsUndefined())
2665 // Handle<Function>::Cast(onexit)->NewInstance(0, NULL); // argc, argv
2666 // // Handle<Object> result = Handle<Function>::Cast(onexit)->NewInstance(0, NULL); // argc, argv
2667 // }
2668
2669 //context->Exit();
2670
2671 // The threads are started already and wait to get the lock
2672 // So we have to unlock (manual preemtion) so that they get
2673 // the signal to terminate.
2674 {
2675 const Unlocker unlock;
2676
2677 for (auto it=fThreads.begin(); it!=fThreads.end(); it++)
2678 it->join();
2679 fThreads.clear();
2680 }
2681
2682 // Now we can dispose all persistent handles from state callbacks
2683 for (auto it=fStateCallbacks.begin(); it!=fStateCallbacks.end(); it++)
2684 it->second.Dispose();
2685 fStateCallbacks.clear();
2686
2687 // Now we can dispose the persistent interrupt handler
2688 fInterruptCallback.Dispose();
2689 fInterruptCallback.Clear();
2690
2691 // Now we can dispose all persistent handles from reverse maps
2692 for (auto it=fReverseMap.begin(); it!=fReverseMap.end(); it++)
2693 it->second.Dispose();
2694 fReverseMap.clear();
2695
2696#ifdef HAVE_SQL
2697 // ...and close all database handles
2698 for (auto it=fDatabases.begin(); it!=fDatabases.end(); it++)
2699 delete *it;
2700 fDatabases.clear();
2701#endif
2702
2703 fStates.clear();
2704
2705 context.Dispose();
2706
2707 JsEnd(filename);
2708
2709 return true;
2710}
2711
2712void InterpreterV8::JsStop()
2713{
2714 Locker locker;
2715 V8::TerminateExecution(This->fThreadId);
2716}
2717
2718vector<string> InterpreterV8::JsGetCommandList(const char *, int) const
2719{
2720 vector<string> rc;
2721
2722 rc.emplace_back("for (");
2723 rc.emplace_back("while (");
2724 rc.emplace_back("if (");
2725 rc.emplace_back("switch (");
2726 rc.emplace_back("case ");
2727 rc.emplace_back("var ");
2728 rc.emplace_back("function ");
2729 rc.emplace_back("Date(");
2730 rc.emplace_back("new Date(");
2731 rc.emplace_back("'use strict';");
2732 rc.emplace_back("undefined");
2733 rc.emplace_back("null");
2734 rc.emplace_back("delete ");
2735
2736 rc.emplace_back("dim.log(");
2737 rc.emplace_back("dim.alarm(");
2738 rc.emplace_back("dim.wait(");
2739 rc.emplace_back("dim.send(");
2740 rc.emplace_back("dim.state(");
2741 rc.emplace_back("dim.version");
2742 rc.emplace_back("dim.getStates(");
2743 rc.emplace_back("dim.getDescription(");
2744 rc.emplace_back("dim.getServices(");
2745
2746 rc.emplace_back("dimctrl.defineState(");
2747 rc.emplace_back("dimctrl.setState(");
2748 rc.emplace_back("dimctrl.getState(");
2749 rc.emplace_back("dimctrl.setInterruptHandler(");
2750 rc.emplace_back("dimctrl.triggerInterrupt(");
2751
2752 rc.emplace_back("v8.sleep(");
2753 rc.emplace_back("v8.timeout(");
2754 rc.emplace_back("v8.version()");
2755
2756 rc.emplace_back("console.out(");
2757 rc.emplace_back("console.warn(");
2758
2759 rc.emplace_back("include(");
2760 rc.emplace_back("exit()");
2761
2762#ifdef HAVE_SQL
2763 rc.emplace_back("Database(");
2764 rc.emplace_back("new Database(");
2765
2766 rc.emplace_back(".table");
2767 rc.emplace_back(".user");
2768 rc.emplace_back(".database");
2769 rc.emplace_back(".port");
2770 rc.emplace_back(".query");
2771#endif
2772
2773 rc.emplace_back("Subscription(");
2774 rc.emplace_back("new Subscription(");
2775
2776 rc.emplace_back("Thread(");
2777 rc.emplace_back("new Thread(");
2778
2779 rc.emplace_back("File(");
2780 rc.emplace_back("new File(");
2781
2782 rc.emplace_back("Event(");
2783 rc.emplace_back("new Event(");
2784
2785 rc.emplace_back("Description(");
2786 rc.emplace_back("new Description(");
2787
2788#ifdef HAVE_MAILX
2789 rc.emplace_back("Mail(");
2790 rc.emplace_back("new Mail(");
2791
2792 rc.emplace_back(".subject");
2793 rc.emplace_back(".receipients");
2794 rc.emplace_back(".attachments");
2795 rc.emplace_back(".bcc");
2796 rc.emplace_back(".cc");
2797 rc.emplace_back(".text");
2798 rc.emplace_back(".send(");
2799#endif
2800
2801#ifdef HAVE_NOVA
2802 rc.emplace_back("Sky(");
2803 rc.emplace_back("new Sky(");
2804
2805 rc.emplace_back("Sky.dist");
2806 rc.emplace_back("Local(");
2807
2808 rc.emplace_back("new Local(");
2809 rc.emplace_back("Local.dist");
2810
2811 rc.emplace_back("Moon(");
2812 rc.emplace_back("new Moon(");
2813 rc.emplace_back("Moon.disk(");
2814 rc.emplace_back("Moon.horizon(");
2815
2816 rc.emplace_back("Sun.horizon(");
2817
2818 rc.emplace_back(".zd");
2819 rc.emplace_back(".az");
2820 rc.emplace_back(".ra");
2821 rc.emplace_back(".dec");
2822
2823 rc.emplace_back(".toLocal(");
2824 rc.emplace_back(".toSky(");
2825 rc.emplace_back(".rise");
2826 rc.emplace_back(".set");
2827 rc.emplace_back(".transit");
2828 rc.emplace_back(".isUp");
2829
2830 rc.emplace_back("horizon");
2831 rc.emplace_back("civil");
2832 rc.emplace_back("nautical");
2833 rc.emplace_back("astronomical");
2834#endif
2835
2836 rc.emplace_back(".server");
2837 rc.emplace_back(".service");
2838 rc.emplace_back(".name");
2839 rc.emplace_back(".isCommand");
2840 rc.emplace_back(".format");
2841 rc.emplace_back(".description");
2842 rc.emplace_back(".unit");
2843 rc.emplace_back(".delim");
2844 rc.emplace_back(".isOpen");
2845
2846 rc.emplace_back(".qos");
2847 rc.emplace_back(".size");
2848 rc.emplace_back(".counter");
2849 rc.emplace_back(".type");
2850 rc.emplace_back(".obj");
2851 rc.emplace_back(".data");
2852 rc.emplace_back(".comment");
2853 rc.emplace_back(".index");
2854 rc.emplace_back(".time");
2855 rc.emplace_back(".close()");
2856 rc.emplace_back(".onchange");
2857 rc.emplace_back(".get(");
2858
2859
2860 rc.emplace_back("__DATE__");
2861 rc.emplace_back("__FILE__");
2862
2863 return rc;
2864}
2865
2866#endif
2867
2868InterpreterV8 *InterpreterV8::This = 0;
Note: See TracBrowser for help on using the repository browser.