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

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