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

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