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

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