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

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