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

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