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

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