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

Last change on this file since 14633 was 14633, checked in by tbretz, 12 years ago
Removed fGlobalcontext, using the one bound in which th function/object was created instead; removed obsolte handles to FunctionTemplates, using the callee object instead.
File size: 58.3 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 Handle<FunctionTemplate> sky = FunctionTemplate::New(ConstructorSky);
1259 sky->SetClassName(String::New("Sky"));
1260 Handle<Value> arg[] = { Number::New(equ.ra/15), Number::New(equ.dec), date };
1261 return handle_scope.Close(sky->GetFunction()->NewInstance(3, arg));
1262
1263 //Handle<Value> arg[] = { Number::New(equ.ra/15), Number::New(equ.dec), date };
1264 //return handle_scope.Close(fTemplateSky->GetFunction()->NewInstance(3, arg));
1265}
1266
1267Handle<Value> InterpreterV8::SkyToLocal(const Arguments &args)
1268{
1269 if (args.Length()>1)
1270 return ThrowException(String::New("toLocal must not be called with more than one argument."));
1271
1272 ln_equ_posn equ;
1273 equ.ra = GetDataMember(args, "ra")*15;
1274 equ.dec = GetDataMember(args, "dec");
1275
1276 if (!finite(equ.ra) || !finite(equ.dec))
1277 return ThrowException(String::New("Ra and dec must be finite."));
1278
1279 HandleScope handle_scope;
1280
1281 const Local<Value> date =
1282 args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
1283 if (date.IsEmpty())
1284 return Undefined();
1285
1286 const uint64_t v = uint64_t(date->NumberValue());
1287 const Time utc(v/1000, v%1000);
1288
1289 ln_lnlat_posn obs;
1290 obs.lng = -(17.+53./60+26.525/3600);
1291 obs.lat = 28.+45./60+42.462/3600;
1292
1293 ln_hrz_posn hrz;
1294 ln_get_hrz_from_equ(&equ, &obs, utc.JD(), &hrz);
1295
1296 Handle<Value> arg[] = { Number::New(90-hrz.alt), Number::New(hrz.az), date };
1297 return handle_scope.Close(fTemplateLocal->GetFunction()->NewInstance(3, arg));
1298}
1299
1300Handle<Value> InterpreterV8::MoonToLocal(const Arguments &args)
1301{
1302 if (args.Length()>0)
1303 return ThrowException(String::New("toLocal must not be called with arguments."));
1304
1305 ln_equ_posn equ;
1306 equ.ra = GetDataMember(args, "ra")*15;
1307 equ.dec = GetDataMember(args, "dec");
1308
1309 if (!finite(equ.ra) || !finite(equ.dec))
1310 return ThrowException(String::New("ra and dec must be finite."));
1311
1312 HandleScope handle_scope;
1313
1314 const Local<Value> date = args.This()->Get(String::New("time"));
1315 if (date.IsEmpty() || date->IsUndefined() )
1316 return Undefined();
1317
1318 const uint64_t v = uint64_t(date->NumberValue());
1319 const Time utc(v/1000, v%1000);
1320
1321 ln_lnlat_posn obs;
1322 obs.lng = -(17.+53./60+26.525/3600);
1323 obs.lat = 28.+45./60+42.462/3600;
1324
1325 ln_hrz_posn hrz;
1326 ln_get_hrz_from_equ(&equ, &obs, utc.JD(), &hrz);
1327
1328 Handle<Value> arg[] = { Number::New(90-hrz.alt), Number::New(hrz.az), date };
1329 return handle_scope.Close(fTemplateLocal->GetFunction()->NewInstance(3, arg));
1330}
1331
1332Handle<Value> InterpreterV8::ConstructorMoon(const Arguments &args)
1333{
1334 if (args.Length()>1)
1335 return ThrowException(String::New("Moon constructor must not be called with more than one argument."));
1336
1337 HandleScope handle_scope;
1338
1339 const Local<Value> date =
1340 args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
1341 if (date.IsEmpty())
1342 return Undefined();
1343
1344 const uint64_t v = uint64_t(date->NumberValue());
1345 const Time utc(v/1000, v%1000);
1346
1347 ln_equ_posn equ;
1348 ln_get_lunar_equ_coords_prec(utc.JD(), &equ, 0.01);
1349
1350 // ----------------------------
1351
1352 if (!args.IsConstructCall())
1353 return Constructor(args);
1354
1355 Handle<Function> function =
1356 FunctionTemplate::New(MoonToLocal)->GetFunction();
1357 if (function.IsEmpty())
1358 return Undefined();
1359
1360 Handle<Object> This = args.This();
1361 This->Set(String::New("ra"), Number::New(equ.ra/15), ReadOnly);
1362 This->Set(String::New("dec"), Number::New(equ.dec), ReadOnly);
1363 This->Set(String::New("toLocal"), function, ReadOnly);
1364 This->Set(String::New("time"), date, ReadOnly);
1365
1366 return handle_scope.Close(This);
1367}
1368
1369Handle<Value> InterpreterV8::ConstructorSky(const Arguments &args)
1370{
1371 if (args.Length()<2 || args.Length()>3)
1372 return ThrowException(String::New("Sky constructor takes two or three arguments."));
1373
1374 if (args.Length()==3 && !args[2]->IsDate())
1375 return ThrowException(String::New("Third argument must be a Date."));
1376
1377 const double ra = args[0]->NumberValue();
1378 const double dec = args[1]->NumberValue();
1379
1380 if (!finite(ra) || !finite(dec))
1381 return ThrowException(String::New("Both arguments to Sky must be valid numbers."));
1382
1383 // ----------------------------
1384
1385 HandleScope handle_scope;
1386
1387 if (!args.IsConstructCall())
1388 return Constructor(args);
1389
1390 Handle<Function> function =
1391 FunctionTemplate::New(SkyToLocal)->GetFunction();
1392 if (function.IsEmpty())
1393 return Undefined();
1394
1395 Handle<Object> This = args.This();
1396 This->Set(String::New("ra"), Number::New(ra), ReadOnly);
1397 This->Set(String::New("dec"), Number::New(dec), ReadOnly);
1398 This->Set(String::New("toLocal"), function, ReadOnly);
1399 if (args.Length()==3)
1400 This->Set(String::New("time"), args[2], ReadOnly);
1401
1402 return handle_scope.Close(This);
1403}
1404
1405Handle<Value> InterpreterV8::ConstructorLocal(const Arguments &args)
1406{
1407 if (args.Length()<2 || args.Length()>3)
1408 return ThrowException(String::New("Local constructor takes two or three arguments."));
1409
1410 if (args.Length()==3 && !args[2]->IsDate())
1411 return ThrowException(String::New("Third argument must be a Date."));
1412
1413 const double zd = args[0]->NumberValue();
1414 const double az = args[1]->NumberValue();
1415
1416 if (!finite(zd) || !finite(az))
1417 return ThrowException(String::New("Both arguments to Local must be valid numbers."));
1418
1419 // --------------------
1420
1421 HandleScope handle_scope;
1422
1423 if (!args.IsConstructCall())
1424 return Constructor(args);
1425
1426 Handle<Function> function =
1427 FunctionTemplate::New(LocalToSky)->GetFunction();
1428 if (function.IsEmpty())
1429 return Undefined();
1430
1431 Handle<Object> This = args.This();
1432 This->Set(String::New("zd"), Number::New(zd), ReadOnly);
1433 This->Set(String::New("az"), Number::New(az), ReadOnly);
1434 This->Set(String::New("toSky"), function, ReadOnly);
1435 if (args.Length()==3)
1436 This->Set(String::New("time"), args[2], ReadOnly);
1437
1438 return handle_scope.Close(This);
1439}
1440#endif
1441
1442// ==========================================================================
1443// Process control
1444// ==========================================================================
1445
1446bool InterpreterV8::ReportException(TryCatch* try_catch)
1447{
1448 if (!try_catch->CanContinue())
1449 return false;
1450
1451 const HandleScope handle_scope;
1452
1453 const String::Utf8Value exception(try_catch->Exception());
1454
1455 if (*exception && string(*exception)=="exit")
1456 return true;
1457 if (*exception && string(*exception)=="null")
1458 return false;
1459
1460 const Handle<Message> message = try_catch->Message();
1461 if (message.IsEmpty())
1462 return false;
1463
1464 ostringstream out;
1465
1466 if (!message->GetScriptResourceName()->IsUndefined())
1467 {
1468 // Print (filename):(line number): (message).
1469 const String::Utf8Value filename(message->GetScriptResourceName());
1470
1471 if (*filename)
1472 out << *filename << ": ";
1473 out << "l." << message->GetLineNumber();
1474 if (*exception)
1475 out << ": ";
1476 }
1477
1478 // -------------- SKIP if 'internal' and 'Error' ---------------
1479 if (*exception)
1480 out << *exception;
1481
1482 JsException(out.str());
1483
1484 // Print line of source code.
1485 const String::Utf8Value sourceline(message->GetSourceLine());
1486 if (*sourceline)
1487 JsException(*sourceline);
1488 // -------------- SKIP if 'internal' and 'Error: ' ---------------
1489
1490 // Print wavy underline (GetUnderline is deprecated).
1491 const int start = message->GetStartColumn();
1492 const int end = message->GetEndColumn();
1493
1494 out.str("");
1495 if (start>0)
1496 out << setfill(' ') << setw(start) << ' ';
1497 out << setfill('^') << setw(end-start) << '^';
1498
1499 JsException(out.str());
1500
1501 const String::Utf8Value stack_trace(try_catch->StackTrace());
1502 if (stack_trace.length()<=0)
1503 return false;
1504
1505 if (!*stack_trace)
1506 return false;
1507
1508 const string trace(*stack_trace);
1509
1510 typedef boost::char_separator<char> separator;
1511 const boost::tokenizer<separator> tokenizer(trace, separator("\n"));
1512
1513 // maybe skip: " at internal:"
1514
1515 auto it = tokenizer.begin();
1516 JsException("");
1517 while (it!=tokenizer.end())
1518 JsException(*it++);
1519
1520 return false;
1521}
1522
1523Handle<Value> InterpreterV8::ExecuteInternal(const string &code)
1524{
1525 // Try/catch and re-throw hides our internal code from
1526 // the displayed exception showing the origin and shows
1527 // the user function instead.
1528 TryCatch exception;
1529
1530 const Handle<Value> result = ExecuteCode(code);
1531 if (exception.HasCaught())
1532 exception.ReThrow();
1533
1534 return result;
1535}
1536
1537Handle<Value> InterpreterV8::ExecuteCode(const string &code, const string &file, bool main)
1538{
1539 HandleScope handle_scope;
1540
1541 const Handle<String> source = String::New(code.c_str(), code.size());
1542 const Handle<String> origin = String::New(file.c_str());
1543 if (source.IsEmpty())
1544 return Handle<Value>();
1545
1546 const Handle<Script> script = Script::Compile(source, origin);
1547 if (script.IsEmpty())
1548 return Handle<Value>();
1549
1550 if (main)
1551 JsSetState(3);
1552
1553 const Handle<Value> result = script->Run();
1554 if (result.IsEmpty())
1555 return Handle<Value>();
1556
1557 // If all went well and the result wasn't undefined then print
1558 // the returned value.
1559 if (!result->IsUndefined())
1560 JsResult(*String::Utf8Value(result));
1561
1562 return handle_scope.Close(result);
1563}
1564
1565bool InterpreterV8::ExecuteFile(const string &name, bool main)
1566{
1567 ifstream fin(name.c_str());
1568 if (!fin)
1569 {
1570 JsException("Error - Could not open file '"+name+"'");
1571 return false;
1572 }
1573
1574 string buffer;
1575 if (!getline(fin, buffer, '\0'))
1576 return true;
1577
1578 if (fin.fail())
1579 {
1580 JsException("Error - reading file.");
1581 return false;
1582 }
1583
1584 return !ExecuteCode(buffer, name, main).IsEmpty();
1585}
1586
1587// ==========================================================================
1588// CORE
1589// ==========================================================================
1590
1591Handle<Value> InterpreterV8::Constructor(/*Handle<FunctionTemplate> T,*/ const Arguments &args)
1592{
1593 Handle<Value> argv[args.Length()];
1594
1595 for (int i=0; i<args.Length(); i++)
1596 argv[i] = args[i];
1597
1598 return args.Callee()->NewInstance(args.Length(), argv);
1599}
1600
1601
1602void InterpreterV8::AddFormatToGlobal() const
1603{
1604 const string code =
1605 "dim.format = function(str, arr)"
1606 "{"
1607 "var i = -1;"
1608 "function callback(exp, p0, p1, p2, p3, p4/*, pos, str*/)"
1609 "{"
1610 "if (exp=='%%')"
1611 "return '%';"
1612 ""
1613 "if (arr[++i]===undefined)"
1614 "return undefined;"
1615 ""
1616 "var exp = p2 ? parseInt(p2.substr(1)) : undefined;"
1617 "var base = p3 ? parseInt(p3.substr(1)) : undefined;"
1618 ""
1619 "var val;"
1620 "switch (p4)"
1621 "{"
1622 "case 's': val = arr[i]; break;"
1623 "case 'c': val = arr[i][0]; break;"
1624 "case 'f': val = parseFloat(arr[i]).toFixed(exp); break;"
1625 "case 'p': val = parseFloat(arr[i]).toPrecision(exp); break;"
1626 "case 'e': val = parseFloat(arr[i]).toExponential(exp); break;"
1627 "case 'x': val = parseInt(arr[i]).toString(base?base:16); break;"
1628 "case 'd': val = parseFloat(parseInt(arr[i], base?base:10).toPrecision(exp)).toFixed(0); break;"
1629 //"default:\n"
1630 //" throw new SyntaxError('Conversion specifier '+p4+' unknown.');\n"
1631 "}"
1632 ""
1633 "val = typeof(val)=='object' ? JSON.stringify(val) : val.toString(base);"
1634 ""
1635 "var sz = parseInt(p1); /* padding size */"
1636 "var ch = p1 && p1[0]=='0' ? '0' : ' '; /* isnull? */"
1637 "while (val.length<sz)"
1638 "val = p0 !== undefined ? val+ch : ch+val; /* isminus? */"
1639 ""
1640 "return val;"
1641 "}"
1642 ""
1643 "var regex = /%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd])/g;"
1644 "return str.replace(regex, callback);"
1645 "}"
1646 "\n"
1647 "String.prototype.$ = function()"
1648 "{"
1649 "return dim.format(this, Array.prototype.slice.call(arguments));"
1650 "}"/*
1651 "\n"
1652 "var format = function()"
1653 "{"
1654 "return dim.format(arguments[0], Array.prototype.slice.call(arguments,1));"
1655 "}"*/;
1656
1657 Handle<Script> script = Script::New(String::New(code.c_str()), String::New("internal"));
1658 if (!script.IsEmpty())
1659 script->Run();
1660}
1661
1662bool InterpreterV8::JsRun(const string &filename, const map<string, string> &map)
1663{
1664 //const string argv = "--prof";
1665 //V8::SetFlagsFromString(argv.c_str(), argv.size());
1666
1667 const Locker locker;
1668 fThreadId = V8::GetCurrentThreadId();
1669
1670 JsPrint(string("JavaScript Engine V8 ")+V8::GetVersion());
1671
1672 JsLoad(filename);
1673
1674 const HandleScope handle_scope;
1675
1676 // Create a template for the global object.
1677 Handle<ObjectTemplate> dim = ObjectTemplate::New();
1678 dim->Set(String::New("print"), FunctionTemplate::New(WrapPrint), ReadOnly);
1679 dim->Set(String::New("alarm"), FunctionTemplate::New(WrapAlarm), ReadOnly);
1680 dim->Set(String::New("out"), FunctionTemplate::New(WrapOut), ReadOnly);
1681 dim->Set(String::New("wait"), FunctionTemplate::New(WrapWait), ReadOnly);
1682 dim->Set(String::New("send"), FunctionTemplate::New(WrapSend), ReadOnly);
1683 dim->Set(String::New("state"), FunctionTemplate::New(WrapState), ReadOnly);
1684 dim->Set(String::New("newState"), FunctionTemplate::New(WrapNewState), ReadOnly);
1685 dim->Set(String::New("setState"), FunctionTemplate::New(WrapSetState), ReadOnly);
1686 dim->Set(String::New("getState"), FunctionTemplate::New(WrapGetState), ReadOnly);
1687 dim->Set(String::New("sleep"), FunctionTemplate::New(WrapSleep), ReadOnly);
1688 dim->Set(String::New("timeout"), FunctionTemplate::New(WrapTimeout), ReadOnly);
1689 dim->Set(String::New("subscribe"), FunctionTemplate::New(WrapSubscribe), ReadOnly);
1690 dim->Set(String::New("file"), FunctionTemplate::New(WrapFile), ReadOnly);
1691
1692 // timeout -> Thread - class?
1693 // subscribe -> Service - class?
1694 // file -> File - class?
1695 // new class State ?
1696 // newState -> return State?
1697 // setState -> return State?
1698 // getState -> return State?
1699
1700 Handle<ObjectTemplate> onchange = ObjectTemplate::New();
1701 onchange->SetNamedPropertyHandler(OnChangeGet, WrapOnChangeSet);
1702 dim->Set(v8::String::New("onchange"), onchange);
1703
1704 Handle<ObjectTemplate> global = ObjectTemplate::New();
1705 global->Set(String::New("dim"), dim, ReadOnly);
1706 global->Set(String::New("include"), FunctionTemplate::New(WrapInclude), ReadOnly);
1707 global->Set(String::New("exit"), FunctionTemplate::New(WrapExit), ReadOnly);
1708 global->Set(String::New("version"), FunctionTemplate::New(InterpreterV8::FuncVersion), ReadOnly);
1709
1710 Handle<FunctionTemplate> db = FunctionTemplate::New(WrapDatabase);
1711 db->SetClassName(String::New("Database"));
1712 db->InstanceTemplate()->SetInternalFieldCount(1);
1713 global->Set(String::New("Database"), db, ReadOnly);
1714
1715#ifdef HAVE_NOVA
1716 Handle<FunctionTemplate> sky = FunctionTemplate::New(ConstructorSky);
1717 sky->SetClassName(String::New("Sky"));
1718 global->Set(String::New("Sky"), sky, ReadOnly);
1719
1720 Handle<FunctionTemplate> loc = FunctionTemplate::New(ConstructorLocal);
1721 loc->SetClassName(String::New("Local"));
1722 loc->Set(String::New("dist"), FunctionTemplate::New(LocalDist), ReadOnly);
1723 global->Set(String::New("Local"), loc, ReadOnly);
1724
1725 Handle<FunctionTemplate> moon = FunctionTemplate::New(ConstructorMoon);
1726 moon->SetClassName(String::New("Moon"));
1727 moon->Set(String::New("disk"), FunctionTemplate::New(MoonDisk), ReadOnly);
1728 global->Set(String::New("Moon"), moon, ReadOnly);
1729
1730 fTemplateLocal = loc;
1731 fTemplateSky = sky;
1732#endif
1733
1734 // Persistent
1735 Persistent<Context> context = Context::New(NULL, global);
1736 if (context.IsEmpty())
1737 {
1738 //printf("Error creating context\n");
1739 return false;
1740 }
1741
1742 Context::Scope scope(context);
1743
1744 Handle<Array> args = Array::New(map.size());
1745 for (auto it=map.begin(); it!=map.end(); it++)
1746 args->Set(String::New(it->first.c_str()), String::New(it->second.c_str()));
1747 context->Global()->Set(String::New("$"), args, ReadOnly);
1748 context->Global()->Set(String::New("arg"), args, ReadOnly);
1749
1750 //V8::ResumeProfiler();
1751
1752 AddFormatToGlobal();
1753
1754 JsStart(filename);
1755
1756 //context->Enter();
1757
1758 TryCatch exception;
1759
1760 Locker::StartPreemption(10);
1761 bool rc = ExecuteFile(filename, true);
1762
1763 Locker::StopPreemption();
1764
1765 Terminate();
1766
1767 if (exception.HasCaught())
1768 rc = ReportException(&exception);
1769
1770 // IsProfilerPaused()
1771 // V8::PauseProfiler();
1772
1773 // -----
1774 // This is how an exit handler could look like, but there is no way to interrupt it
1775 // -----
1776 // Handle<Object> obj = Handle<Object>::Cast(context->Global()->Get(String::New("dim")));
1777 // if (!obj.IsEmpty())
1778 // {
1779 // Handle<Value> onexit = obj->Get(String::New("onexit"));
1780 // if (!onexit->IsUndefined())
1781 // Handle<Function>::Cast(onexit)->NewInstance(0, NULL); // argc, argv
1782 // // Handle<Object> result = Handle<Function>::Cast(onexit)->NewInstance(0, NULL); // argc, argv
1783 // }
1784
1785 //context->Exit();
1786
1787 // Thre threads are started already and wait to get the lock
1788 // So we have to unlock (manual preemtion) so they they get
1789 // the signal to terminate. After they are all successfully
1790 // terminated, just to be sure... we lock again
1791 {
1792 const Unlocker unlock;
1793
1794 for (auto it=fTimeout.begin(); it!=fTimeout.end(); it++)
1795 it->join();
1796 fTimeout.clear();
1797 }
1798
1799 // Now we can dispose all persistent handles from state callbacks
1800 for (auto it=fStateCallbacks.begin(); it!=fStateCallbacks.end(); it++)
1801 it->second.Dispose();
1802 fStateCallbacks.clear();
1803
1804 // Now we can dispose all persistent handles from reverse maps
1805 for (auto it=fReverseMap.begin(); it!=fReverseMap.end(); it++)
1806 it->second.Dispose();
1807 fReverseMap.clear();
1808
1809#ifdef HAVE_SQL
1810 // ...and close all database handles
1811 for (auto it=fDatabases.begin(); it!=fDatabases.end(); it++)
1812 delete *it;
1813 fDatabases.clear();
1814#endif
1815
1816 fStates.clear();
1817
1818 context.Dispose();
1819
1820 JsEnd(filename);
1821
1822 return rc;
1823}
1824
1825void InterpreterV8::JsStop()
1826{
1827 Locker locker;
1828 This->Terminate();
1829}
1830
1831#endif
1832
1833InterpreterV8 *InterpreterV8::This = 0;
Note: See TracBrowser for help on using the repository browser.