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

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