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

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