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

Last change on this file since 15084 was 15078, checked in by tbretz, 12 years ago
Emit an empty string if no arguments are given in dim.log
File size: 78.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/solar.h>
13#include <libnova/lunar.h>
14#include <libnova/transform.h>
15#endif
16
17#ifdef HAVE_SQL
18#include "Database.h"
19#endif
20
21#include <v8.h>
22
23#include "dim.h"
24#include "tools.h"
25#include "Readline.h"
26#include "externals/izstream.h"
27
28#include "WindowLog.h"
29
30using namespace std;
31using namespace v8;
32
33v8::Handle<v8::FunctionTemplate> InterpreterV8::fTemplateLocal;
34v8::Handle<v8::FunctionTemplate> InterpreterV8::fTemplateSky;
35v8::Handle<v8::FunctionTemplate> InterpreterV8::fTemplateEvent;
36v8::Handle<v8::FunctionTemplate> InterpreterV8::fTemplateDescription;
37//v8::Handle<v8::FunctionTemplate> InterpreterV8::fTemplateDatabase;
38
39
40// ==========================================================================
41// Some documentation
42// ==========================================================================
43//
44// Threads:
45// --------
46// In most cases Js* and other calls to native C++ code could be wrapped
47// with an Unlocker to allow possible other JavaScipt 'threads' to run
48// during that time. However, all of these calls should take much less than
49// the preemption time of 10ms, so it would just be a waste of tim.
50//
51// Termination:
52// ------------
53// Each thread running V8 code needs to be signalled individually for
54// termination. Therefor a list of V8 thread ids is created.
55//
56// If termination has already be signalled, no thread should start running
57// anymore (thy could, e.g., wait for their locking). So after locking
58// it has to be checked if the thread was terminated already. Note
59// that all calls to Terminate() must be locked to ensure that fThreadId
60// is correct when it is checked.
61//
62// The current thread id must be added to fThreadIds _before_ any
63// function is called after Locking and before execution is given
64// back to JavaScript, e.g. in script->Run(). So until the thread
65// is added to the list Terminate will not be executed. If Terminate
66// is then executed, it is ensured that the current thread is
67// already in the list. If terminate has been called before
68// the Locking, the check for the validiy of fThreadId ensures that
69// nothing is executed.
70//
71// Empty handles:
72// --------------
73// If exceution is terminated, V8 calls might return with empty handles,
74// e.g. Date::New(). Therefore, the returned handles of these calls have to
75// be checked in all placed to avoid that V8 will core dump.
76//
77// HandleScope:
78// ------------
79// A handle scope is a garbage collector and collects all handles created
80// until it goes out of scope. Handles which are not needed anymore are
81// then deleted. To return a handle from a HandleScope you need to use
82// Close(). E.g., String::AsciiValue does not create a new handle and
83// hence does not need a HandleScope. Any ::New will need a handle scope.
84// Forgetting the HandleScope could in principle fill your memory,
85// but everything is properly deleted by the global HandleScope at
86// script termination.
87//
88
89// ==========================================================================
90// Simple interface
91// ==========================================================================
92
93Handle<Value> InterpreterV8::FuncExit(const Arguments &)
94{
95 V8::TerminateExecution(fThreadId);
96
97 // we have to throw an excption to make sure that the
98 // calling thread does not go on executing until it
99 // has realized that it should terminate
100 return ThrowException(Null());
101}
102
103Handle<Value> InterpreterV8::FuncSleep(const Arguments& args)
104{
105 if (args.Length()==0)
106 {
107 // Theoretically, the CPU usage can be reduced by maybe a factor
108 // of four using a larger value, but this also means that the
109 // JavaScript is locked for a longer time.
110 const Unlocker unlock;
111 usleep(1000);
112 return Undefined();
113 }
114
115 if (args.Length()!=1)
116 return ThrowException(String::New("Number of arguments must be exactly 1."));
117
118 if (!args[0]->IsUint32())
119 return ThrowException(String::New("Argument 1 must be an uint32."));
120
121 // Using a Javascript function has the advantage that it is fully
122 // interruptable without the need of C++ code
123 const string code =
124 "(function(){"
125 "var t=new Date();"
126 "while ((new Date()-t)<"+to_string(args[0]->Int32Value())+") v8.sleep();"
127 "})();";
128
129 return ExecuteInternal(code);
130}
131
132Handle<Value> InterpreterV8::FuncTimeout(const Arguments &args)
133{
134 if (args.Length()<2)
135 return ThrowException(String::New("Number of arguments must be at least two."));
136
137 if (!args[0]->IsNull() && !args[0]->IsInt32())
138 return ThrowException(String::New("Argument 0 not null and not an int32."));
139
140 if (!args[1]->IsFunction())
141 return ThrowException(String::New("Argument 1 not a function."));
142
143 const int32_t timeout = args[0]->IsNull() ? 0 : args[0]->Int32Value();
144 const bool null = args[0]->IsNull();
145
146 HandleScope handle_scope;
147
148 TryCatch exception;
149
150 const Handle<Script> sleep = Script::Compile(String::New("v8.sleep();"), String::New("internal"));
151 if (sleep.IsEmpty())
152 return Undefined();
153
154 Handle<Function> func = Handle<Function>::Cast(args[1]);
155
156 Handle<Value> argv[args.Length()-2];
157 for (int i=0; i<args.Length()-2; i++)
158 argv[i] = args[i+2];
159
160 Time t;
161 while (!exception.HasCaught())
162 {
163 const Handle<Value> rc = func->Call(func, args.Length()-2, argv);
164 if (!rc->IsUndefined())
165 return rc;
166
167 if (!null && Time()-t>=boost::posix_time::milliseconds(abs(timeout)))
168 break;
169
170 // We cannot sleep directly because we have to give control back to
171 // JavaScript ever now and then. This also allows us to catch
172 // exceptions, either from the preemption or ConvertEvent
173 sleep->Run();
174 }
175
176 if (exception.HasCaught())
177 return exception.ReThrow();
178
179 if (timeout<0)
180 return Undefined();
181
182 const string str = "Waiting for func to return a defined value timed out.";
183 return ThrowException(String::New(str.c_str()));
184}
185
186void InterpreterV8::Thread(int &id, Persistent<Function> func, uint32_t ms)
187{
188 const Locker lock;
189
190 if (fThreadId<0)
191 {
192 id = -1;
193 return;
194 }
195
196 // Warning: As soon as id is set, the parent of this thread might terminate
197 // and hance the reference to id does not exist anymore. So, id
198 // is just a kind of return value and must not be used at all
199 // otherwise.
200
201 const int id_local = V8::GetCurrentThreadId();
202 id = id_local;
203 fThreadIds.insert(id_local);
204
205 const HandleScope handle_scope;
206
207 func->CreationContext()->Enter();
208
209 TryCatch exception;
210
211 const bool rc = ms==0 || !ExecuteInternal("v8.sleep("+to_string(ms)+");").IsEmpty();
212 if (rc)
213 func->Call(func, 0, NULL);
214
215 func.Dispose();
216 fThreadIds.erase(id_local);
217
218 if (!HandleException(exception, "thread"))
219 V8::TerminateExecution(fThreadId);
220}
221
222Handle<Value> InterpreterV8::FuncThread(const Arguments& args)
223{
224 if (!args.IsConstructCall())
225 return ThrowException(String::New("Thread must be called as constructor."));
226
227 if (args.Length()!=2)
228 return ThrowException(String::New("Number of arguments must be two."));
229
230 if (!args[0]->IsUint32())
231 return ThrowException(String::New("Argument 0 not an uint32."));
232
233 if (!args[1]->IsFunction())
234 return ThrowException(String::New("Argument 1 not a function."));
235
236 //if (!args.IsConstructCall())
237 // return Constructor(args);
238
239 const HandleScope handle_scope;
240
241 Handle<Function> handle = Handle<Function>::Cast(args[1]);
242
243 Persistent<Function> func = Persistent<Function>::New(handle);
244
245 const uint32_t ms = args[0]->Uint32Value();
246
247 int id=-2;
248 fThreads.push_back(thread(bind(&InterpreterV8::Thread, this, ref(id), func, ms)));
249 {
250 // Allow the thread to lock, so we can get the thread id.
251 const Unlocker unlock;
252 while (id==-2)
253 usleep(1);
254 }
255
256 Handle<Object> self = args.This();
257
258 self->Set(String::New("id"), Integer::NewFromUnsigned(id), ReadOnly);
259 self->Set(String::New("kill"), FunctionTemplate::New(WrapKill)->GetFunction(), ReadOnly);
260
261 return Undefined();
262}
263
264Handle<Value> InterpreterV8::FuncKill(const Arguments& args)
265{
266 const uint32_t id = args.This()->Get(String::New("id"))->Uint32Value();
267
268 V8::TerminateExecution(id);
269
270 return Boolean::New(fThreadIds.erase(id));
271}
272
273Handle<Value> InterpreterV8::FuncSend(const Arguments& args)
274{
275 if (args.Length()==0)
276 return ThrowException(String::New("Number of arguments must be at least 1."));
277
278 if (!args[0]->IsString())
279 return ThrowException(String::New("Argument 1 must be a string."));
280
281 const String::AsciiValue str(args[0]);
282
283 string command = *str;
284
285 if (command.length()==0)
286 return ThrowException(String::New("Server name empty."));
287
288 if (args.Length()==0)
289 {
290 if (command.find_first_of('/')==string::npos)
291 command += "/";
292 }
293
294 // Escape all string arguments. All others can be kept as they are.
295 for (int i=1; i<args.Length(); i++)
296 {
297 string arg = *String::AsciiValue(args[i]);
298
299 // Escape string
300 if (args[i]->IsString())
301 {
302 boost::replace_all(arg, "\\", "\\\\");
303 boost::replace_all(arg, "'", "\\'");
304 boost::replace_all(arg, "\"", "\\\"");
305 }
306
307 command += " "+arg;
308 }
309
310 try
311 {
312 return Boolean::New(JsSend(command));
313 }
314 catch (const runtime_error &e)
315 {
316 return ThrowException(String::New(e.what()));
317 }
318}
319
320// ==========================================================================
321// State control
322// ==========================================================================
323
324Handle<Value> InterpreterV8::FuncWait(const Arguments& args)
325{
326 if (args.Length()!=2 && args.Length()!=3)
327 return ThrowException(String::New("Number of arguments must be 2 or 3."));
328
329 if (!args[0]->IsString())
330 return ThrowException(String::New("Argument 1 not a string."));
331
332 if (!args[1]->IsInt32() && !args[1]->IsString())
333 return ThrowException(String::New("Argument 2 not an int32 and not a string."));
334
335 if (args.Length()==3 && !args[2]->IsInt32())
336 return ThrowException(String::New("Argument 3 not an int32."));
337
338 // Using a Javascript function has the advantage that it is fully
339 // interruptable without the need of C++ code
340
341 const string index = args[1]->IsInt32() ? "s.index" : "s.name";
342 const bool timeout = args.Length()==3;
343 const string arg0 = *String::AsciiValue(args[0]);
344 const string state = args[1]->IsString() ? *String::AsciiValue(args[1]) : "";
345 const string arg1 = args[1]->IsString() ? ("\""+state+"\"") : to_string(args[1]->Int32Value());
346
347 if (arg0.find_first_of("\"'")!=string::npos)
348 return ThrowException(String::New("Server name must not contain quotation marks."));
349
350 if (args[1]->IsString())
351 if (state.find_first_of("\"'")!=string::npos)
352 return ThrowException(String::New("State name must not contain quotation marks."));
353
354 string code = "(function(name,state,ms)"
355 "{";
356 if (timeout)
357 code += "var t = new Date();";
358 code += "while (1)"
359 "{"
360 "var s = dim.state(name);"
361 "if(!s)throw new Error('Waitig for state "+arg1+" of server "+arg0+" failed.');"
362 "if(state=="+index+")return true;";
363 if (timeout)
364 code += "if((new Date()-t)>Math.abs(ms))break;";
365
366 code += "v8.sleep();"
367 "}";
368 if (timeout)
369 code += "if(ms>0)throw new Error('Waiting for state "+arg1+" of server "+arg0+" timed out.');";
370 code += "return false;"
371 "})('"+arg0+"',"+arg1;
372 if (timeout)
373 code += "," + to_string(args[2]->Int32Value());
374 code += ");";
375
376 return ExecuteInternal(code);
377}
378
379Handle<Value> InterpreterV8::FuncState(const Arguments& args)
380{
381 if (args.Length()!=1)
382 return ThrowException(String::New("Number of arguments must be exactly 1."));
383
384 if (!args[0]->IsString())
385 return ThrowException(String::New("Argument 1 must be a string."));
386
387 // Return state.name/state.index
388
389 const String::AsciiValue str(args[0]);
390
391 const State rc = JsState(*str);
392 if (rc.index<=-256)
393 return Undefined();
394
395 HandleScope handle_scope;
396
397 Handle<Object> obj = Object::New();
398
399 obj->Set(String::New("server"), String::New(*str), ReadOnly);
400 obj->Set(String::New("index"), Integer::New(rc.index), ReadOnly);
401 obj->Set(String::New("name"), String::New(rc.name.c_str()), ReadOnly);
402
403 const Local<Value> date = Date::New(rc.time.JavaDate());
404 if (rc.index>-256 && !date.IsEmpty())
405 obj->Set(String::New("time"), date);
406
407 return handle_scope.Close(obj);
408}
409
410Handle<Value> InterpreterV8::FuncNewState(const Arguments& args)
411{
412 if (args.Length()<1 || args.Length()>3)
413 return ThrowException(String::New("Number of arguments must be 1, 2 or 3."));
414
415 if (!args[0]->IsUint32())
416 return ThrowException(String::New("Argument 1 must be an uint32."));
417 if (args.Length()>1 && !args[1]->IsString())
418 return ThrowException(String::New("Argument 2 must be a string."));
419 if (args.Length()>2 && !args[2]->IsString())
420 return ThrowException(String::New("Argument 3 must be a string."));
421
422 const uint32_t index = args[0]->Int32Value();
423 const string name = *String::AsciiValue(args[1]);
424 const string comment = *String::AsciiValue(args[2]);
425
426 if (index<10 || index>255)
427 return ThrowException(String::New("State must be in the range [10, 255]."));
428
429 if (name.empty())
430 return ThrowException(String::New("State name must not be empty."));
431
432 if (name.find_first_of(':')!=string::npos || name.find_first_of('=')!=string::npos)
433 return ThrowException(String::New("State name must not contain : or =."));
434
435 struct Find : State
436 {
437 Find(int idx, const string &n) : State(idx, n) { }
438 bool operator()(const pair<int, string> &p) { return index==p.first || name==p.second; }
439 };
440
441 if (find_if(fStates.begin(), fStates.end(), Find(index, name))!=fStates.end())
442 {
443 const string what =
444 "State index ["+to_string(index)+"] or name ["+name+"] already defined.";
445
446 return ThrowException(String::New(what.c_str()));
447 }
448
449 return Boolean::New(JsNewState(index, name, comment));
450}
451
452Handle<Value> InterpreterV8::FuncSetState(const Arguments& args)
453{
454 if (args.Length()!=1)
455 return ThrowException(String::New("Number of arguments must be exactly 1."));
456
457 if (!args[0]->IsUint32() && !args[0]->IsString())
458 return ThrowException(String::New("Argument must be an unint32 or a string."));
459
460 int index = -2;
461 if (args[0]->IsUint32())
462 {
463 index = args[0]->Int32Value();
464 }
465 else
466 {
467 const string name = *String::AsciiValue(args[0]);
468 index = JsGetState(name);
469 if (index==-2)
470 return ThrowException(String::New(("State '"+name+"' not found.").c_str()));
471 }
472
473 if (index<10 || index>255)
474 return ThrowException(String::New("State must be in the range [10, 255]."));
475
476 return Boolean::New(JsSetState(index));
477}
478
479Handle<Value> InterpreterV8::FuncGetState(const Arguments& args)
480{
481 if (args.Length()>0)
482 return ThrowException(String::New("getState must not take arguments."));
483
484 const State state = JsGetCurrentState();
485
486 HandleScope handle_scope;
487
488 Handle<Object> rc = Object::New();
489 if (rc.IsEmpty())
490 return Undefined();
491
492 rc->Set(String::New("index"), Integer::New(state.index), ReadOnly);
493 rc->Set(String::New("name"), String::New(state.name.c_str()), ReadOnly);
494 rc->Set(String::New("description"), String::New(state.comment.c_str()), ReadOnly);
495
496 return handle_scope.Close(rc);
497}
498
499Handle<Value> InterpreterV8::FuncGetStates(const Arguments& args)
500{
501 if (args.Length()>1)
502 return ThrowException(String::New("getStates must not take more than one arguments."));
503
504 if (args.Length()==1 && !args[0]->IsString())
505 return ThrowException(String::New("Argument must be a string."));
506
507 const string server = args.Length()==1 ? *String::AsciiValue(args[0]) : "DIM_CONTROL";
508
509 const vector<State> states = JsGetStates(server);
510
511 HandleScope handle_scope;
512
513 Handle<Object> list = Object::New();
514 if (list.IsEmpty())
515 return Undefined();
516
517 for (auto it=states.begin(); it!=states.end(); it++)
518 {
519 Handle<Value> entry = StringObject::New(String::New(it->name.c_str()));
520 if (entry.IsEmpty())
521 return Undefined();
522
523 StringObject::Cast(*entry)->Set(String::New("description"), String::New(it->comment.c_str()), ReadOnly);
524 list->Set(Integer::New(it->index), entry, ReadOnly);
525 }
526
527 return handle_scope.Close(list);
528}
529
530Handle<Value> InterpreterV8::FuncGetDescription(const Arguments& args)
531{
532 if (args.Length()!=1)
533 return ThrowException(String::New("getDescription must take exactly one argument."));
534
535 if (args.Length()==1 && !args[0]->IsString())
536 return ThrowException(String::New("Argument must be a string."));
537
538 const string service = *String::AsciiValue(args[0]);
539
540 const vector<Description> descriptions = JsGetDescription(service);
541 const set<Service> services = JsGetServices();
542
543 auto is=services.begin();
544 for (; is!=services.end(); is++)
545 if (is->name==service)
546 break;
547
548 if (is==services.end())
549 return Undefined();
550
551 HandleScope handle_scope;
552
553 Handle<Object> arr = fTemplateDescription->GetFunction()->NewInstance();//Object::New();
554 if (arr.IsEmpty())
555 return Undefined();
556
557 auto it=descriptions.begin();
558 arr->Set(String::New("name"), String::New(it->name.c_str()), ReadOnly);
559 if (!it->comment.empty())
560 arr->Set(String::New("description"), String::New(it->comment.c_str()), ReadOnly);
561 if (is!=services.end())
562 {
563 arr->Set(String::New("server"), String::New(is->server.c_str()), ReadOnly);
564 arr->Set(String::New("service"), String::New(is->service.c_str()), ReadOnly);
565 arr->Set(String::New("isCommand"), Boolean::New(is->iscmd), ReadOnly);
566 if (!is->format.empty())
567 arr->Set(String::New("format"), String::New(is->format.c_str()), ReadOnly);
568 }
569
570 uint32_t i=0;
571 for (it++; it!=descriptions.end(); it++)
572 {
573 Handle<Object> obj = Object::New();
574 if (obj.IsEmpty())
575 return Undefined();
576
577 if (!it->name.empty())
578 obj->Set(String::New("name"), String::New(it->name.c_str()), ReadOnly);
579 if (!it->comment.empty())
580 obj->Set(String::New("description"), String::New(it->comment.c_str()), ReadOnly);
581 if (!it->unit.empty())
582 obj->Set(String::New("unit"), String::New(it->unit.c_str()), ReadOnly);
583
584 arr->Set(i++, obj);
585 }
586
587 return handle_scope.Close(arr);
588}
589
590Handle<Value> InterpreterV8::FuncGetServices(const Arguments& args)
591{
592 if (args.Length()>2)
593 return ThrowException(String::New("getServices must not take more than two argument."));
594
595 if (args.Length()>=1 && !args[0]->IsString())
596 return ThrowException(String::New("First argument must be a string."));
597
598 if (args.Length()==2 && !args[1]->IsBoolean())
599 return ThrowException(String::New("Second argument must be a boolean."));
600
601 string arg0 = args.Length() ? *String::AsciiValue(args[0]) : "";
602 if (arg0=="*")
603 arg0=="";
604
605 const set<Service> services = JsGetServices();
606
607 HandleScope handle_scope;
608
609 Handle<Array> arr = Array::New();
610 if (arr.IsEmpty())
611 return Undefined();
612
613 uint32_t i=0;
614 for (auto is=services.begin(); is!=services.end(); is++)
615 {
616 if (!arg0.empty() && is->name.find(arg0)!=0)
617 continue;
618
619 if (args.Length()==2 && args[1]->BooleanValue()!=is->iscmd)
620 continue;
621
622 Handle<Object> obj = Object::New();
623 if (obj.IsEmpty())
624 return Undefined();
625
626 obj->Set(String::New("name"), String::New(is->name.c_str()), ReadOnly);
627 obj->Set(String::New("server"), String::New(is->server.c_str()), ReadOnly);
628 obj->Set(String::New("service"), String::New(is->service.c_str()), ReadOnly);
629 obj->Set(String::New("isCommand"), Boolean::New(is->iscmd), ReadOnly);
630 if (!is->format.empty())
631 obj->Set(String::New("format"), String::New(is->format.c_str()), ReadOnly);
632
633 arr->Set(i++, obj);
634 }
635
636 return handle_scope.Close(arr);
637}
638
639// ==========================================================================
640// Internal functions
641// ==========================================================================
642
643
644// The callback that is invoked by v8 whenever the JavaScript 'print'
645// function is called. Prints its arguments on stdout separated by
646// spaces and ending with a newline.
647Handle<Value> InterpreterV8::FuncLog(const Arguments& args)
648{
649 for (int i=0; i<args.Length(); i++)
650 {
651 const String::AsciiValue str(args[i]);
652 if (*str)
653 JsPrint(*str);
654 }
655
656 if (args.Length()==0)
657 JsPrint();
658
659 return Undefined();
660}
661
662Handle<Value> InterpreterV8::FuncAlarm(const Arguments& args)
663{
664 for (int i=0; i<args.Length(); i++)
665 {
666 const String::AsciiValue str(args[i]);
667 if (*str)
668 JsAlarm(*str);
669 }
670
671 if (args.Length()==0)
672 JsAlarm();
673
674 return Undefined();
675}
676
677Handle<Value> InterpreterV8::FuncOut(const Arguments& args)
678{
679 for (int i=0; i<args.Length(); i++)
680 {
681 const String::AsciiValue str(args[i]);
682 if (*str)
683 JsOut(*str);
684 }
685 return Undefined();
686}
687
688// The callback that is invoked by v8 whenever the JavaScript 'load'
689// function is called. Loads, compiles and executes its argument
690// JavaScript file.
691Handle<Value> InterpreterV8::FuncInclude(const Arguments& args)
692{
693 for (int i=0; i<args.Length(); i++)
694 {
695 const String::AsciiValue file(args[i]);
696 if (*file == NULL)
697 return ThrowException(String::New("File name missing"));
698
699 TryCatch exception;
700 const bool rc = ExecuteFile(*file);
701 if (exception.HasCaught())
702 HandleException(exception, "include");
703 if (!rc)
704 {
705 V8::TerminateExecution(fThreadId);
706 return ThrowException(Null());
707 }
708 }
709
710 return Boolean::New(true);
711}
712
713Handle<Value> InterpreterV8::FuncFile(const Arguments& args)
714{
715 if (args.Length()!=1 && args.Length()!=2)
716 return ThrowException(String::New("Number of arguments must be one or two."));
717
718 const String::AsciiValue file(args[0]);
719 if (*file == NULL)
720 return ThrowException(String::New("File name missing"));
721
722 if (args.Length()==2 && !args[1]->IsString())
723 return ThrowException(String::New("Second argument must be a string."));
724
725 const string delim = args.Length()==2 ? *String::AsciiValue(args[1]) : "";
726
727 if (args.Length()==2 && delim.size()!=1)
728 return ThrowException(String::New("Second argument must be a string of length 1."));
729
730 HandleScope handle_scope;
731
732 izstream fin(*file);
733 if (!fin)
734 return ThrowException(String::New(errno!=0?strerror(errno):"Insufficient memory for decompression"));
735
736 if (args.Length()==1)
737 {
738 string buffer;
739 if (!getline(fin, buffer, '\0'))
740 return ThrowException(String::New(strerror(errno)));
741
742 Handle<Value> str = StringObject::New(String::New(buffer.c_str()));
743 StringObject::Cast(*str)->Set(String::New("name"), String::New(*file));
744 return handle_scope.Close(str);
745 }
746
747 Handle<Array> arr = Array::New();
748 if (arr.IsEmpty())
749 return Undefined();
750
751 int i=0;
752 string buffer;
753 while (getline(fin, buffer, delim[0]))
754 arr->Set(i++, String::New(buffer.c_str()));
755
756 if ((fin.fail() && !fin.eof()) || fin.bad())
757 return ThrowException(String::New(strerror(errno)));
758
759 arr->Set(String::New("name"), String::New(*file));
760 arr->Set(String::New("delim"), String::New(delim.c_str(), 1));
761
762 return handle_scope.Close(arr);
763}
764
765// ==========================================================================
766// Database
767// ==========================================================================
768
769Handle<Value> InterpreterV8::FuncDbClose(const Arguments &args)
770{
771 void *ptr = External::Unwrap(args.This()->GetInternalField(0));
772 if (!ptr)
773 return Boolean::New(false);
774
775#ifdef HAVE_SQL
776 Database *db = reinterpret_cast<Database*>(ptr);
777 auto it = find(fDatabases.begin(), fDatabases.end(), db);
778 fDatabases.erase(it);
779 delete db;
780#endif
781
782 HandleScope handle_scope;
783
784 args.This()->SetInternalField(0, External::New(0));
785
786 return handle_scope.Close(Boolean::New(true));
787}
788
789Handle<Value> InterpreterV8::FuncDbQuery(const Arguments &args)
790{
791 if (args.Length()==0)
792 return ThrowException(String::New("Arguments expected."));
793
794 void *ptr = External::Unwrap(args.This()->GetInternalField(0));
795 if (!ptr)
796 return Undefined();
797
798 string query;
799 for (int i=0; i<args.Length(); i++)
800 query += string(" ") + *String::AsciiValue(args[i]);
801 query.erase(0, 1);
802
803#ifdef HAVE_SQL
804 try
805 {
806 HandleScope handle_scope;
807
808 Database *db = reinterpret_cast<Database*>(ptr);
809
810 const mysqlpp::StoreQueryResult res = db->query(query).store();
811
812 Handle<Array> ret = Array::New();
813 if (ret.IsEmpty())
814 return Undefined();
815
816 ret->Set(String::New("table"), String::New(res.table()), ReadOnly);
817 ret->Set(String::New("query"), String::New(query.c_str()), ReadOnly);
818
819 Handle<Array> cols = Array::New();
820 if (cols.IsEmpty())
821 return Undefined();
822
823 int irow=0;
824 for (vector<mysqlpp::Row>::const_iterator it=res.begin(); it<res.end(); it++)
825 {
826 Handle<Object> row = Object::New();
827 if (row.IsEmpty())
828 return Undefined();
829
830 const mysqlpp::FieldNames *list = it->field_list().list;
831
832 for (size_t i=0; i<it->size(); i++)
833 {
834 const Handle<Value> name = String::New((*list)[i].c_str());
835 if (irow==0)
836 cols->Set(i, name);
837
838 if ((*it)[i].is_null())
839 {
840 row->Set(name, Undefined(), ReadOnly);
841 continue;
842 }
843
844 const string sql_type = (*it)[i].type().sql_name();
845
846 const bool uns = sql_type.find("UNSIGNED")==string::npos;
847
848 if (sql_type.find("BIGINT")!=string::npos)
849 {
850 if (uns)
851 {
852 const uint64_t val = (uint64_t)(*it)[i];
853 if (val>UINT32_MAX)
854 row->Set(name, Number::New(val), ReadOnly);
855 else
856 row->Set(name, Integer::NewFromUnsigned(val), ReadOnly);
857 }
858 else
859 {
860 const int64_t val = (int64_t)(*it)[i];
861 if (val<INT32_MIN || val>INT32_MAX)
862 row->Set(name, Number::New(val), ReadOnly);
863 else
864 row->Set(name, Integer::NewFromUnsigned(val), ReadOnly);
865 }
866 continue;
867 }
868
869 // 32 bit
870 if (sql_type.find("INT")!=string::npos)
871 {
872 if (uns)
873 row->Set(name, Integer::NewFromUnsigned((uint32_t)(*it)[i]), ReadOnly);
874 else
875 row->Set(name, Integer::New((int32_t)(*it)[i]), ReadOnly);
876 continue;
877 }
878
879 if (sql_type.find("BOOL")!=string::npos )
880 {
881 row->Set(name, Boolean::New((bool)(*it)[i]), ReadOnly);
882 continue;
883 }
884
885 if (sql_type.find("FLOAT")!=string::npos)
886 {
887 ostringstream val;
888 val << setprecision(7) << (float)(*it)[i];
889 row->Set(name, Number::New(stod(val.str())), ReadOnly);
890 continue;
891
892 }
893 if (sql_type.find("DOUBLE")!=string::npos)
894 {
895 row->Set(name, Number::New((double)(*it)[i]), ReadOnly);
896 continue;
897 }
898
899 if (sql_type.find("CHAR")!=string::npos ||
900 sql_type.find("TEXT")!=string::npos)
901 {
902 row->Set(name, String::New((const char*)(*it)[i]), ReadOnly);
903 continue;
904 }
905
906 time_t date = 0;
907 if (sql_type.find("TIMESTAMP")!=string::npos)
908 date = mysqlpp::Time((*it)[i]);
909
910 if (sql_type.find("DATETIME")!=string::npos)
911 date = mysqlpp::DateTime((*it)[i]);
912
913 if (sql_type.find(" DATE ")!=string::npos)
914 date = mysqlpp::Date((*it)[i]);
915
916 if (date>0)
917 {
918 // It is important to catch the exception thrown
919 // by Date::New in case of thread termination!
920 const Local<Value> val = Date::New(date*1000);
921 if (val.IsEmpty())
922 return Undefined();
923
924 row->Set(name, val, ReadOnly);
925 }
926 }
927
928 ret->Set(irow++, row);
929 }
930
931 if (irow>0)
932 ret->Set(String::New("cols"), cols, ReadOnly);
933
934 return handle_scope.Close(ret);
935 }
936 catch (const exception &e)
937 {
938 return ThrowException(String::New(e.what()));
939 }
940#endif
941}
942
943Handle<Value> InterpreterV8::FuncDatabase(const Arguments &args)
944{
945 if (!args.IsConstructCall())
946 return ThrowException(String::New("Database must be called as constructor."));
947
948 if (args.Length()!=1)
949 return ThrowException(String::New("Number of arguments must be 1."));
950
951 if (!args[0]->IsString())
952 return ThrowException(String::New("Argument 1 not a string."));
953
954#ifdef HAVE_SQL
955 try
956 {
957 HandleScope handle_scope;
958
959 //if (!args.IsConstructCall())
960 // return Constructor(fTemplateDatabase, args);
961
962 Database *db = new Database(*String::AsciiValue(args[0]));
963 fDatabases.push_back(db);
964
965 Handle<Object> self = args.This();
966 self->Set(String::New("user"), String::New(db->user.c_str()), ReadOnly);
967 self->Set(String::New("server"), String::New(db->server.c_str()), ReadOnly);
968 self->Set(String::New("database"), String::New(db->db.c_str()), ReadOnly);
969 self->Set(String::New("port"), db->port==0?Undefined():Integer::NewFromUnsigned(db->port), ReadOnly);
970 self->Set(String::New("query"), FunctionTemplate::New(WrapDbQuery)->GetFunction(), ReadOnly);
971 self->Set(String::New("close"), FunctionTemplate::New(WrapDbClose)->GetFunction(), ReadOnly);
972 self->SetInternalField(0, External::New(db));
973
974 return handle_scope.Close(self);
975 }
976 catch (const exception &e)
977 {
978 return ThrowException(String::New(e.what()));
979 }
980#endif
981}
982
983// ==========================================================================
984// Services
985// ==========================================================================
986
987Handle<Value> InterpreterV8::Convert(char type, const char* &ptr)
988{
989 // Dim values are always unsigned per (FACT++) definition
990 switch (type)
991 {
992 case 'F':
993 {
994 // Remove the "imprecision" effect coming from casting a float to
995 // a double and then showing it with double precision
996 ostringstream val;
997 val << setprecision(7) << *reinterpret_cast<const float*>(ptr);
998 ptr += 4;
999 return Number::New(stod(val.str()));
1000 }
1001 case 'D': { Handle<Value> v=Number::New(*reinterpret_cast<const double*>(ptr)); ptr+=8; return v; }
1002 case 'I':
1003 case 'L': { Handle<Value> v=Integer::NewFromUnsigned(*reinterpret_cast<const uint32_t*>(ptr)); ptr += 4; return v; }
1004 case 'X':
1005 {
1006 const uint64_t val = *reinterpret_cast<const uint64_t*>(ptr);
1007 ptr += 8;
1008 if (val>UINT32_MAX)
1009 return Number::New(val);
1010 return Integer::NewFromUnsigned(val);
1011 }
1012 case 'S': { Handle<Value> v=Integer::NewFromUnsigned(*reinterpret_cast<const uint16_t*>(ptr)); ptr += 2; return v; }
1013 case 'C': { Handle<Value> v=Integer::NewFromUnsigned((uint16_t)*reinterpret_cast<const uint8_t*>(ptr)); ptr += 1; return v; }
1014 }
1015 return Undefined();
1016}
1017
1018Handle<Value> InterpreterV8::FuncClose(const Arguments &args)
1019{
1020 HandleScope handle_scope;
1021
1022 //const void *ptr = Local<External>::Cast(args.Holder()->GetInternalField(0))->Value();
1023
1024 const String::AsciiValue str(args.This()->Get(String::New("name")));
1025
1026 const auto it = fReverseMap.find(*str);
1027 if (it!=fReverseMap.end())
1028 {
1029 it->second.Dispose();
1030 fReverseMap.erase(it);
1031 }
1032
1033 args.This()->Set(String::New("isOpen"), Boolean::New(false), ReadOnly);
1034
1035 return handle_scope.Close(Boolean::New(JsUnsubscribe(*str)));
1036}
1037
1038Handle<Value> InterpreterV8::ConvertEvent(const EventImp *evt, uint64_t counter, const char *str)
1039{
1040 const vector<Description> vec = JsDescription(str);
1041
1042 Handle<Object> ret = fTemplateEvent->GetFunction()->NewInstance();//Object::New();
1043 if (ret.IsEmpty())
1044 return Undefined();
1045
1046 const Local<Value> date = Date::New(evt->GetJavaDate());
1047 if (date.IsEmpty())
1048 return Undefined();
1049
1050 ret->Set(String::New("name"), String::New(str), ReadOnly);
1051 ret->Set(String::New("format"), String::New(evt->GetFormat().c_str()), ReadOnly);
1052 ret->Set(String::New("qos"), Integer::New(evt->GetQoS()), ReadOnly);
1053 ret->Set(String::New("size"), Integer::New(evt->GetSize()), ReadOnly);
1054 ret->Set(String::New("counter"), Integer::New(counter), ReadOnly);
1055 if (evt->GetJavaDate()>0)
1056 ret->Set(String::New("time"), date, ReadOnly);
1057
1058 // If names are available data will also be provided as an
1059 // object. If an empty event was received, but names are available,
1060 // the object will be empty. Otherwise 'obj' will be undefined.
1061 // obj===undefined: no data received
1062 // obj!==undefined, length==0: names for event available
1063 // obj!==undefined, obj.length>0: names available, data received
1064 Handle<Object> named = Object::New();
1065 if (vec.size()>0)
1066 ret->Set(String::New("obj"), named, ReadOnly);
1067
1068 // If no event was received (usually a disconnection event in
1069 // the context of FACT++), no data is returned
1070 if (evt->IsEmpty())
1071 return ret;
1072
1073 // If valid data was received, but the size was zero, then
1074 // null is returned as data
1075 // data===undefined: no data received
1076 // data===null: event received, but no data
1077 // data.length>0: event received, contains data
1078 if (evt->GetSize()==0 || evt->GetFormat().empty())
1079 {
1080 ret->Set(String::New("data"), Null(), ReadOnly);
1081 return ret;
1082 }
1083
1084 typedef boost::char_separator<char> separator;
1085 const boost::tokenizer<separator> tokenizer(evt->GetFormat(), separator(";:"));
1086
1087 const vector<string> tok(tokenizer.begin(), tokenizer.end());
1088
1089 Handle<Object> arr = tok.size()>1 ? Array::New() : ret;
1090 if (arr.IsEmpty())
1091 return Undefined();
1092
1093 const char *ptr = evt->GetText();
1094 const char *end = evt->GetText()+evt->GetSize();
1095
1096 try
1097 {
1098 size_t pos = 1;
1099 for (auto it=tok.begin(); it<tok.end() && ptr<end; it++, pos++)
1100 {
1101 char type = (*it)[0];
1102 it++;
1103
1104 string name = pos<vec.size() ? vec[pos].name : "";
1105 if (tok.size()==1)
1106 name = "data";
1107
1108 // Get element size
1109 uint32_t sz = 1;
1110 switch (type)
1111 {
1112 case 'X':
1113 case 'D': sz = 8; break;
1114 case 'F':
1115 case 'I':
1116 case 'L': sz = 4; break;
1117 case 'S': sz = 2; break;
1118 case 'C': sz = 1; break;
1119 }
1120
1121 // Check if no number is attached if the size of the
1122 // received data is consistent with the format string
1123 if (it==tok.end() && (end-ptr)%sz>0)
1124 return Exception::Error(String::New(("Number of received bytes ["+to_string(evt->GetSize())+"] does not match format ["+evt->GetFormat()+"]").c_str()));
1125
1126 // Check if format has a number attached.
1127 // If no number is attached calculate number of elements
1128 const uint32_t cnt = it==tok.end() ? (end-ptr)/sz : stoi(it->c_str());
1129
1130 // is_str: Array of type C but unknown size (String)
1131 // is_one: Array of known size, but size is 1 (I:1)
1132 const bool is_str = type=='C' && it==tok.end();
1133 const bool is_one = cnt==1 && it!=tok.end();
1134
1135 Handle<Value> v;
1136
1137 if (is_str)
1138 v = String::New(ptr);
1139 if (is_one)
1140 v = Convert(type, ptr);
1141
1142 // Array of known (I:5) or unknown size (I), but no string
1143 if (!is_str && !is_one)
1144 {
1145 Handle<Object> a = Array::New(cnt);
1146 if (a.IsEmpty())
1147 return Undefined();
1148
1149 for (uint32_t i=0; i<cnt; i++)
1150 a->Set(i, Convert(type, ptr));
1151
1152 v = a;
1153 }
1154
1155 if (tok.size()>1)
1156 arr->Set(pos-1, v);
1157 else
1158 ret->Set(String::New("data"), v, ReadOnly);
1159
1160 if (!name.empty())
1161 {
1162 const Handle<String> n = String::New(name.c_str());
1163 named->Set(n, v);
1164 }
1165 }
1166
1167 if (tok.size()>1)
1168 ret->Set(String::New("data"), arr, ReadOnly);
1169
1170 return ret;
1171 }
1172 catch (...)
1173 {
1174 return Exception::Error(String::New(("Format string conversion '"+evt->GetFormat()+"' failed.").c_str()));
1175 }
1176}
1177/*
1178Handle<Value> InterpreterV8::FuncGetData(const Arguments &args)
1179{
1180 HandleScope handle_scope;
1181
1182 const String::AsciiValue str(args.Holder()->Get(String::New("name")));
1183
1184 const pair<uint64_t, EventImp *> p = JsGetEvent(*str);
1185
1186 const EventImp *evt = p.second;
1187 if (!evt)
1188 return Undefined();
1189
1190 //if (counter==cnt)
1191 // return info.Holder();//Holder()->Get(String::New("data"));
1192
1193 Handle<Value> ret = ConvertEvent(evt, p.first, *str);
1194 return ret->IsNativeError() ? ThrowException(ret) : handle_scope.Close(ret);
1195}
1196*/
1197Handle<Value> InterpreterV8::FuncGetData(const Arguments &args)
1198{
1199 if (args.Length()>2)
1200 return ThrowException(String::New("Number of arguments must not be greater than 2."));
1201
1202 if (args.Length()>=1 && !args[0]->IsInt32() && !args[0]->IsNull())
1203 return ThrowException(String::New("Argument 1 not an uint32."));
1204
1205 if (args.Length()==2 && !args[1]->IsBoolean())
1206 return ThrowException(String::New("Argument 2 not a boolean."));
1207
1208 // Using a Javascript function has the advantage that it is fully
1209 // interruptable without the need of C++ code
1210 const bool null = args.Length()>=1 && args[0]->IsNull();
1211 const int32_t timeout = args.Length()>=1 ? args[0]->Int32Value() : 0;
1212 const bool named = args.Length()<2 || args[1]->BooleanValue();
1213
1214 HandleScope handle_scope;
1215
1216 const Handle<Script> sleep = Script::Compile(String::New("v8.sleep();"), String::New("internal"));
1217 if (sleep.IsEmpty())
1218 return Undefined();
1219
1220 const Handle<String> data = String::New("data");
1221 const Handle<String> object = String::New("obj");
1222
1223 const String::AsciiValue name(args.Holder()->Get(String::New("name")));
1224
1225 TryCatch exception;
1226
1227 Time t;
1228 while (!exception.HasCaught())
1229 {
1230 const pair<uint64_t, EventImp *> p = JsGetEvent(*name);
1231
1232 const EventImp *evt = p.second;
1233 if (evt)
1234 {
1235 const Handle<Value> val = ConvertEvent(evt, p.first, *name);
1236 if (val->IsNativeError())
1237 return ThrowException(val);
1238
1239 // Protect against the return of an exception
1240 if (!val.IsEmpty() && val->IsObject())
1241 {
1242 if (!named)
1243 {
1244 const Handle<Object> event = val->ToObject();
1245 const Handle<Value> obj = event->Get(data);
1246
1247 // No names (no 'obj'), but 'data'
1248 if (!obj.IsEmpty() && !obj->IsUndefined())
1249 return handle_scope.Close(val);
1250 }
1251 else
1252 {
1253 const Handle<Object> event = val->ToObject();
1254 const Handle<Value> obj = event->Get(object);
1255
1256 if (!obj.IsEmpty() && obj->IsObject())
1257 {
1258 // Has names and data was received?
1259 if (obj->ToObject()->GetOwnPropertyNames()->Length()>0)
1260 return handle_scope.Close(val);
1261 }
1262 }
1263 }
1264 }
1265
1266 if (args.Length()==0)
1267 break;
1268
1269 if (!null && Time()-t>=boost::posix_time::milliseconds(abs(timeout)))
1270 break;
1271
1272 // We cannot sleep directly because we have to give control back to
1273 // JavaScript ever now and then. This also allows us to catch
1274 // exceptions, either from the preemption or ConvertEvent
1275 sleep->Run();
1276 }
1277
1278 if (exception.HasCaught())
1279 return exception.ReThrow();
1280
1281 if (timeout<0)
1282 return Undefined();
1283
1284 const string str = "Waiting for a valid event of "+string(*name)+" timed out.";
1285 return ThrowException(String::New(str.c_str()));
1286}
1287
1288
1289// This is a callback from the RemoteControl piping event handling
1290// to the java script ---> in test phase!
1291void InterpreterV8::JsHandleEvent(const EventImp &evt, uint64_t cnt, const string &service)
1292{
1293 const Locker locker;
1294
1295 if (fThreadId<0)
1296 return;
1297
1298 const auto it = fReverseMap.find(service);
1299 if (it==fReverseMap.end())
1300 return;
1301
1302 const HandleScope handle_scope;
1303
1304 Handle<Object> obj = it->second;
1305
1306 obj->CreationContext()->Enter();
1307
1308 const Handle<String> onchange = String::New("onchange");
1309 if (!obj->Has(onchange))
1310 return;
1311
1312 const Handle<Value> val = obj->Get(onchange);
1313 if (!val->IsFunction())
1314 return;
1315
1316 // -------------------------------------------------------------------
1317
1318 TryCatch exception;
1319
1320 const int id = V8::GetCurrentThreadId();
1321 fThreadIds.insert(id);
1322
1323 Handle<Value> ret = ConvertEvent(&evt, cnt, service.c_str());
1324 if (ret->IsObject())
1325 Handle<Function>::Cast(val)->Call(obj, 1, &ret);
1326
1327 fThreadIds.erase(id);
1328
1329 if (!HandleException(exception, "Service.onchange"))
1330 V8::TerminateExecution(fThreadId);
1331
1332 if (ret->IsNativeError())
1333 {
1334 JsException(service+".onchange callback - "+*String::AsciiValue(ret));
1335 V8::TerminateExecution(fThreadId);
1336 }
1337}
1338
1339Handle<Value> InterpreterV8::OnChangeSet(Local<String> prop, Local<Value> value, const AccessorInfo &)
1340{
1341 // Returns the value if the setter intercepts the request. Otherwise, returns an empty handle.
1342 const string server = *String::AsciiValue(prop);
1343 auto it = fStateCallbacks.find(server);
1344
1345 if (it!=fStateCallbacks.end())
1346 {
1347 it->second.Dispose();
1348 fStateCallbacks.erase(it);
1349 }
1350
1351 if (value->IsFunction())
1352 fStateCallbacks[server] = Persistent<Object>::New(value->ToObject());
1353
1354 return Handle<Value>();
1355}
1356
1357
1358void InterpreterV8::JsHandleState(const std::string &server, const State &state)
1359{
1360 const Locker locker;
1361
1362 if (fThreadId<0)
1363 return;
1364
1365 auto it = fStateCallbacks.find(server);
1366 if (it==fStateCallbacks.end())
1367 {
1368 it = fStateCallbacks.find("*");
1369 if (it==fStateCallbacks.end())
1370 return;
1371 }
1372
1373 const HandleScope handle_scope;
1374
1375 it->second->CreationContext()->Enter();
1376
1377 // -------------------------------------------------------------------
1378
1379 Handle<ObjectTemplate> obj = ObjectTemplate::New();
1380 obj->Set(String::New("server"), String::New(server.c_str()), ReadOnly);
1381
1382 if (state.index>-256)
1383 {
1384 obj->Set(String::New("index"), Integer::New(state.index), ReadOnly);
1385 obj->Set(String::New("name"), String::New(state.name.c_str()), ReadOnly);
1386 obj->Set(String::New("comment"), String::New(state.comment.c_str()), ReadOnly);
1387 const Local<Value> date = Date::New(state.time.JavaDate());
1388 if (!date.IsEmpty())
1389 obj->Set(String::New("time"), date);
1390 }
1391
1392 // -------------------------------------------------------------------
1393
1394 TryCatch exception;
1395
1396 const int id = V8::GetCurrentThreadId();
1397 fThreadIds.insert(id);
1398
1399 Handle<Value> args[] = { obj->NewInstance() };
1400 Handle<Function> fun = Handle<Function>(Function::Cast(*it->second));
1401 fun->Call(fun, 1, args);
1402
1403 fThreadIds.erase(id);
1404
1405 if (!HandleException(exception, "dim.onchange"))
1406 V8::TerminateExecution(fThreadId);
1407}
1408
1409/*
1410void Cleanup( Persistent<Value> object, void *parameter )
1411{
1412 cout << "======================> RemoveMyObj()" << endl;
1413}*/
1414
1415Handle<Value> InterpreterV8::FuncSubscription(const Arguments &args)
1416{
1417 if (args.Length()!=1 && args.Length()!=2)
1418 return ThrowException(String::New("Number of arguments must be one or two."));
1419
1420 if (!args[0]->IsString())
1421 return ThrowException(String::New("Argument 1 must be a string."));
1422
1423 if (args.Length()==2 && !args[1]->IsFunction())
1424 return ThrowException(String::New("Argument 2 must be a function."));
1425
1426 const String::AsciiValue str(args[0]);
1427
1428 if (!args.IsConstructCall())
1429 {
1430 const auto it = fReverseMap.find(*str);
1431 if (it!=fReverseMap.end())
1432 return it->second;
1433
1434 return Undefined();
1435 }
1436
1437 const HandleScope handle_scope;
1438
1439 Handle<Object> self = args.This();
1440 self->Set(String::New("get"), FunctionTemplate::New(WrapGetData)->GetFunction(), ReadOnly);
1441 self->Set(String::New("close"), FunctionTemplate::New(WrapClose)->GetFunction(), ReadOnly);
1442 self->Set(String::New("name"), String::New(*str), ReadOnly);
1443 self->Set(String::New("isOpen"), Boolean::New(true));
1444
1445 if (args.Length()==2)
1446 self->Set(String::New("onchange"), args[1]);
1447
1448 fReverseMap[*str] = Persistent<Object>::New(self);
1449
1450 void *ptr = JsSubscribe(*str);
1451 if (ptr==0)
1452 return ThrowException(String::New(("Subscription to '"+string(*str)+"' already exists.").c_str()));
1453
1454 self->SetInternalField(0, External::New(ptr));
1455
1456 return Undefined();
1457
1458 // Persistent<Object> p = Persistent<Object>::New(obj->NewInstance());
1459 // obj.MakeWeak((void*)1, Cleanup);
1460 // return obj;
1461}
1462
1463// ==========================================================================
1464// Astrometry
1465// ==========================================================================
1466#ifdef HAVE_NOVA
1467
1468double InterpreterV8::GetDataMember(const Arguments &args, const char *name)
1469{
1470 return args.This()->Get(String::New(name))->NumberValue();
1471}
1472
1473Handle<Value> InterpreterV8::CalcDist(const Arguments &args, const bool local)
1474{
1475 if (args.Length()!=2)
1476 return ThrowException(String::New("dist must not be called with two arguments."));
1477
1478 if (!args[0]->IsObject() || !args[1]->IsObject())
1479 return ThrowException(String::New("at least one argument not an object."));
1480
1481 HandleScope handle_scope;
1482
1483 Handle<Object> obj[2] =
1484 {
1485 Handle<Object>::Cast(args[0]),
1486 Handle<Object>::Cast(args[1])
1487 };
1488
1489 const Handle<String> s_theta = String::New(local?"zd":"dec"); // was: zd
1490 const Handle<String> s_phi = String::New(local?"az":"ra"); // was: az
1491
1492 const double conv_t = M_PI/180;
1493 const double conv_p = local ? -M_PI/180 : M_PI/12;
1494 const double offset = local ? 0 : M_PI;
1495
1496 const double theta0 = offset - obj[0]->Get(s_theta)->NumberValue() * conv_t;
1497 const double phi0 = obj[0]->Get(s_phi )->NumberValue() * conv_p;
1498 const double theta1 = offset - obj[1]->Get(s_theta)->NumberValue() * conv_t;
1499 const double phi1 = obj[1]->Get(s_phi )->NumberValue() * conv_p;
1500
1501 if (!finite(theta0) || !finite(theta1) || !finite(phi0) || !finite(phi1))
1502 return ThrowException(String::New("some values not valid or not finite."));
1503
1504 /*
1505 const double x0 = sin(zd0) * cos(az0); // az0 -= az0
1506 const double y0 = sin(zd0) * sin(az0); // az0 -= az0
1507 const double z0 = cos(zd0);
1508
1509 const double x1 = sin(zd1) * cos(az1); // az1 -= az0
1510 const double y1 = sin(zd1) * sin(az1); // az1 -= az0
1511 const double z1 = cos(zd1);
1512
1513 const double res = acos(x0*x1 + y0*y1 + z0*z1) * 180/M_PI;
1514 */
1515
1516 // cos(az1-az0) = cos(az1)*cos(az0) + sin(az1)*sin(az0)
1517
1518 const double x = sin(theta0) * sin(theta1) * cos(phi1-phi0);
1519 const double y = cos(theta0) * cos(theta1);
1520
1521 const double res = acos(x + y) * 180/M_PI;
1522
1523 return handle_scope.Close(Number::New(res));
1524}
1525
1526Handle<Value> InterpreterV8::LocalDist(const Arguments &args)
1527{
1528 return CalcDist(args, true);
1529}
1530
1531Handle<Value> InterpreterV8::SkyDist(const Arguments &args)
1532{
1533 return CalcDist(args, false);
1534}
1535
1536Handle<Value> InterpreterV8::MoonDisk(const Arguments &args)
1537{
1538 if (args.Length()>1)
1539 return ThrowException(String::New("disk must not be called with more than one argument."));
1540
1541 const uint64_t v = uint64_t(args[0]->NumberValue());
1542 const Time utc = args.Length()==0 ? Time() : Time(v/1000, v%1000);
1543
1544 return Number::New(ln_get_lunar_disk(utc.JD()));
1545}
1546
1547Handle<Value> InterpreterV8::LocalToSky(const Arguments &args)
1548{
1549 if (args.Length()>1)
1550 return ThrowException(String::New("toSky must not be called with more than one argument."));
1551
1552 if (args.Length()==1 && !args[0]->IsDate())
1553 return ThrowException(String::New("Argument must be a Date"));
1554
1555 ln_hrz_posn hrz;
1556 hrz.alt = 90-GetDataMember(args, "zd");
1557 hrz.az = GetDataMember(args, "az");
1558
1559 if (!finite(hrz.alt) || !finite(hrz.az))
1560 return ThrowException(String::New("zd and az must be finite."));
1561
1562 HandleScope handle_scope;
1563
1564 const Local<Value> date =
1565 args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
1566 if (date.IsEmpty())
1567 return Undefined();
1568
1569 const uint64_t v = uint64_t(date->NumberValue());
1570 const Time utc(v/1000, v%1000);
1571
1572 ln_lnlat_posn obs;
1573 obs.lng = -(17.+53./60+26.525/3600);
1574 obs.lat = 28.+45./60+42.462/3600;
1575
1576 ln_equ_posn equ;
1577 ln_get_equ_from_hrz(&hrz, &obs, utc.JD(), &equ);
1578
1579 // -----------------------------
1580
1581 Handle<Value> arg[] = { Number::New(equ.ra/15), Number::New(equ.dec), date };
1582 return handle_scope.Close(fTemplateSky->GetFunction()->NewInstance(3, arg));
1583}
1584
1585Handle<Value> InterpreterV8::SkyToLocal(const Arguments &args)
1586{
1587 if (args.Length()>1)
1588 return ThrowException(String::New("toLocal must not be called with more than one argument."));
1589
1590 if (args.Length()==1 && !args[0]->IsDate())
1591 return ThrowException(String::New("Argument must be a Date"));
1592
1593 ln_equ_posn equ;
1594 equ.ra = GetDataMember(args, "ra")*15;
1595 equ.dec = GetDataMember(args, "dec");
1596
1597 if (!finite(equ.ra) || !finite(equ.dec))
1598 return ThrowException(String::New("Ra and dec must be finite."));
1599
1600 HandleScope handle_scope;
1601
1602 const Local<Value> date =
1603 args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
1604 if (date.IsEmpty())
1605 return Undefined();
1606
1607 const uint64_t v = uint64_t(date->NumberValue());
1608 const Time utc(v/1000, v%1000);
1609
1610 ln_lnlat_posn obs;
1611 obs.lng = -(17.+53./60+26.525/3600);
1612 obs.lat = 28.+45./60+42.462/3600;
1613
1614 ln_hrz_posn hrz;
1615 ln_get_hrz_from_equ(&equ, &obs, utc.JD(), &hrz);
1616
1617 Handle<Value> arg[] = { Number::New(90-hrz.alt), Number::New(hrz.az), date };
1618 return handle_scope.Close(fTemplateLocal->GetFunction()->NewInstance(3, arg));
1619}
1620
1621Handle<Value> InterpreterV8::MoonToLocal(const Arguments &args)
1622{
1623 if (args.Length()>0)
1624 return ThrowException(String::New("toLocal must not be called with arguments."));
1625
1626 ln_equ_posn equ;
1627 equ.ra = GetDataMember(args, "ra")*15;
1628 equ.dec = GetDataMember(args, "dec");
1629
1630 if (!finite(equ.ra) || !finite(equ.dec))
1631 return ThrowException(String::New("ra and dec must be finite."));
1632
1633 HandleScope handle_scope;
1634
1635 const Local<Value> date = args.This()->Get(String::New("time"));
1636 if (date.IsEmpty() || date->IsUndefined() )
1637 return Undefined();
1638
1639 const uint64_t v = uint64_t(date->NumberValue());
1640 const Time utc(v/1000, v%1000);
1641
1642 ln_lnlat_posn obs;
1643 obs.lng = -(17.+53./60+26.525/3600);
1644 obs.lat = 28.+45./60+42.462/3600;
1645
1646 ln_hrz_posn hrz;
1647 ln_get_hrz_from_equ(&equ, &obs, utc.JD(), &hrz);
1648
1649 Handle<Value> arg[] = { Number::New(90-hrz.alt), Number::New(hrz.az), date };
1650 return handle_scope.Close(fTemplateLocal->GetFunction()->NewInstance(3, arg));
1651}
1652
1653Handle<Value> InterpreterV8::ConstructorMoon(const Arguments &args)
1654{
1655 if (args.Length()>1)
1656 return ThrowException(String::New("Moon constructor must not be called with more than one argument."));
1657
1658 if (args.Length()==1 && !args[0]->IsDate())
1659 return ThrowException(String::New("Argument must be a Date"));
1660
1661 HandleScope handle_scope;
1662
1663 const Local<Value> date =
1664 args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
1665 if (date.IsEmpty())
1666 return Undefined();
1667
1668 const uint64_t v = uint64_t(date->NumberValue());
1669 const Time utc(v/1000, v%1000);
1670
1671 ln_equ_posn equ;
1672 ln_get_lunar_equ_coords_prec(utc.JD(), &equ, 0.01);
1673
1674 // ----------------------------
1675
1676 if (!args.IsConstructCall())
1677 return Constructor(args);
1678
1679 Handle<Function> function =
1680 FunctionTemplate::New(MoonToLocal)->GetFunction();
1681 if (function.IsEmpty())
1682 return Undefined();
1683
1684 Handle<Object> self = args.This();
1685 self->Set(String::New("ra"), Number::New(equ.ra/15), ReadOnly);
1686 self->Set(String::New("dec"), Number::New(equ.dec), ReadOnly);
1687 self->Set(String::New("toLocal"), function, ReadOnly);
1688 self->Set(String::New("time"), date, ReadOnly);
1689
1690 return handle_scope.Close(self);
1691}
1692
1693Handle<Value> InterpreterV8::ConstructorSky(const Arguments &args)
1694{
1695 if (args.Length()<2 || args.Length()>3)
1696 return ThrowException(String::New("Sky constructor takes two or three arguments."));
1697
1698 if (args.Length()==3 && !args[2]->IsDate())
1699 return ThrowException(String::New("Third argument must be a Date."));
1700
1701 const double ra = args[0]->NumberValue();
1702 const double dec = args[1]->NumberValue();
1703
1704 if (!finite(ra) || !finite(dec))
1705 return ThrowException(String::New("Both arguments to Sky must be valid numbers."));
1706
1707 // ----------------------------
1708
1709 HandleScope handle_scope;
1710
1711 if (!args.IsConstructCall())
1712 return Constructor(args);
1713
1714 Handle<Function> function =
1715 FunctionTemplate::New(SkyToLocal)->GetFunction();
1716 if (function.IsEmpty())
1717 return Undefined();
1718
1719 Handle<Object> self = args.This();
1720 self->Set(String::New("ra"), Number::New(ra), ReadOnly);
1721 self->Set(String::New("dec"), Number::New(dec), ReadOnly);
1722 self->Set(String::New("toLocal"), function, ReadOnly);
1723 if (args.Length()==3)
1724 self->Set(String::New("time"), args[2], ReadOnly);
1725
1726 return handle_scope.Close(self);
1727}
1728
1729Handle<Value> InterpreterV8::ConstructorLocal(const Arguments &args)
1730{
1731 if (args.Length()<2 || args.Length()>3)
1732 return ThrowException(String::New("Local constructor takes two or three arguments."));
1733
1734 if (args.Length()==3 && !args[2]->IsDate())
1735 return ThrowException(String::New("Third argument must be a Date."));
1736
1737 const double zd = args[0]->NumberValue();
1738 const double az = args[1]->NumberValue();
1739
1740 if (!finite(zd) || !finite(az))
1741 return ThrowException(String::New("Both arguments to Local must be valid numbers."));
1742
1743 // --------------------
1744
1745 HandleScope handle_scope;
1746
1747 if (!args.IsConstructCall())
1748 return Constructor(args);
1749
1750 Handle<Function> function =
1751 FunctionTemplate::New(LocalToSky)->GetFunction();
1752 if (function.IsEmpty())
1753 return Undefined();
1754
1755 Handle<Object> self = args.This();
1756 self->Set(String::New("zd"), Number::New(zd), ReadOnly);
1757 self->Set(String::New("az"), Number::New(az), ReadOnly);
1758 self->Set(String::New("toSky"), function, ReadOnly);
1759 if (args.Length()==3)
1760 self->Set(String::New("time"), args[2], ReadOnly);
1761
1762 return handle_scope.Close(self);
1763}
1764
1765Handle<Object> InterpreterV8::ConstructRiseSet(const Handle<Value> time, const ln_rst_time &rst, const bool &rc)
1766{
1767 Handle<Object> obj = Object::New();
1768 obj->Set(String::New("time"), time, ReadOnly);
1769
1770 const uint64_t v = uint64_t(time->NumberValue());
1771 const double jd = Time(v/1000, v%1000).JD();
1772
1773 const bool isUp = rc>0 ||
1774 (rst.rise<rst.set && (jd>rst.rise && jd<rst.set)) ||
1775 (rst.rise>rst.set && (jd<rst.set || jd>rst.rise));
1776
1777 obj->Set(String::New("isUp"), Boolean::New(rc>=0 && isUp), ReadOnly);
1778
1779 if (rc!=0)
1780 return obj;
1781
1782 Handle<Value> rise = Date::New(Time(rst.rise).JavaDate());
1783 Handle<Value> set = Date::New(Time(rst.set).JavaDate());
1784 Handle<Value> trans = Date::New(Time(rst.transit).JavaDate());
1785 if (rise.IsEmpty() || set.IsEmpty() || trans.IsEmpty())
1786 return Handle<Object>();
1787
1788 obj->Set(String::New("rise"), rise, ReadOnly);
1789 obj->Set(String::New("set"), set, ReadOnly);
1790 obj->Set(String::New("transit"), trans, ReadOnly);
1791
1792 return obj;
1793}
1794
1795Handle<Value> InterpreterV8::SunHorizon(const Arguments &args)
1796{
1797 if (args.Length()>2)
1798 return ThrowException(String::New("Sun.horizon must not be called with one or two arguments."));
1799
1800 if (args.Length()==2 && !args[1]->IsDate())
1801 return ThrowException(String::New("Second argument must be a Date"));
1802
1803 HandleScope handle_scope;
1804
1805 double hrz = NAN;
1806 if (args.Length()==0 || args[0]->IsNull())
1807 hrz = LN_SOLAR_STANDART_HORIZON;
1808 if (args.Length()>0 && args[0]->IsNumber())
1809 hrz = args[0]->NumberValue();
1810 if (args.Length()>0 && args[0]->IsString())
1811 {
1812 string arg(Tools::Trim(*String::AsciiValue(args[0])));
1813 transform(arg.begin(), arg.end(), arg.begin(), ::tolower);
1814
1815 if (arg==string("horizon").substr(0, arg.length()))
1816 hrz = LN_SOLAR_STANDART_HORIZON;
1817 if (arg==string("civil").substr(0, arg.length()))
1818 hrz = LN_SOLAR_CIVIL_HORIZON;
1819 if (arg==string("nautical").substr(0, arg.length()))
1820 hrz = LN_SOLAR_NAUTIC_HORIZON;
1821 if (arg==string("fact").substr(0, arg.length()))
1822 hrz = -15;
1823 if (arg==string("astronomical").substr(0, arg.length()))
1824 hrz = LN_SOLAR_ASTRONOMICAL_HORIZON;
1825 }
1826
1827 if (!finite(hrz))
1828 return ThrowException(String::New("Second argument did not yield a valid number."));
1829
1830 const Local<Value> date =
1831 args.Length()<2 ? Date::New(Time().JavaDate()) : args[1];
1832 if (date.IsEmpty())
1833 return Undefined();
1834
1835 const uint64_t v = uint64_t(date->NumberValue());
1836 const Time utc(v/1000, v%1000);
1837
1838 ln_lnlat_posn obs;
1839 obs.lng = -(17.+53./60+26.525/3600);
1840 obs.lat = 28.+45./60+42.462/3600;
1841
1842 // get Julian day from local time
1843 const double JD = utc.JD();
1844
1845 ln_rst_time sun;
1846 const int rc = ln_get_solar_rst_horizon(JD-0.5, &obs, hrz, &sun);
1847 Handle<Object> rst = ConstructRiseSet(date, sun, rc);
1848 rst->Set(String::New("horizon"), Number::New(hrz));
1849 return handle_scope.Close(rst);
1850};
1851
1852Handle<Value> InterpreterV8::MoonHorizon(const Arguments &args)
1853{
1854 if (args.Length()>1)
1855 return ThrowException(String::New("Moon.horizon must not be called with one argument."));
1856
1857 if (args.Length()==1 && !args[0]->IsDate())
1858 return ThrowException(String::New("Argument must be a Date"));
1859
1860 HandleScope handle_scope;
1861
1862 const Local<Value> date =
1863 args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
1864 if (date.IsEmpty())
1865 return Undefined();
1866
1867 const uint64_t v = uint64_t(date->NumberValue());
1868 const Time utc(v/1000, v%1000);
1869
1870 ln_lnlat_posn obs;
1871 obs.lng = -(17.+53./60+26.525/3600);
1872 obs.lat = 28.+45./60+42.462/3600;
1873
1874 // get Julian day from local time
1875 const double JD = utc.JD();
1876
1877 ln_rst_time moon;
1878 const int rc = ln_get_lunar_rst(JD-0.5, &obs, &moon);
1879 Handle<Object> rst = ConstructRiseSet(date, moon, rc);
1880 return handle_scope.Close(rst);
1881};
1882#endif
1883
1884// ==========================================================================
1885// Process control
1886// ==========================================================================
1887
1888bool InterpreterV8::HandleException(TryCatch& try_catch, const char *where)
1889{
1890 if (!try_catch.HasCaught() || !try_catch.CanContinue())
1891 return true;
1892
1893 const HandleScope handle_scope;
1894
1895 Handle<Value> except = try_catch.Exception();
1896 if (except.IsEmpty() || except->IsNull())
1897 return true;
1898
1899 const String::AsciiValue exception(except);
1900
1901 const Handle<Message> message = try_catch.Message();
1902 if (message.IsEmpty())
1903 return false;
1904
1905 ostringstream out;
1906
1907 if (!message->GetScriptResourceName()->IsUndefined())
1908 {
1909 // Print (filename):(line number): (message).
1910 const String::AsciiValue filename(message->GetScriptResourceName());
1911 if (filename.length()>0)
1912 {
1913 out << *filename;
1914 if (message->GetLineNumber()>0)
1915 out << ": l." << message->GetLineNumber();
1916 if (*exception)
1917 out << ": ";
1918 }
1919 }
1920
1921 if (*exception)
1922 out << *exception;
1923
1924 out << " [" << where << "]";
1925
1926 JsException(out.str());
1927
1928 // Print line of source code.
1929 const String::AsciiValue sourceline(message->GetSourceLine());
1930 if (*sourceline)
1931 JsException(*sourceline);
1932
1933 // Print wavy underline (GetUnderline is deprecated).
1934 const int start = message->GetStartColumn();
1935 const int end = message->GetEndColumn();
1936
1937 out.str("");
1938 if (start>0)
1939 out << setfill(' ') << setw(start) << ' ';
1940 out << setfill('^') << setw(end-start) << '^';
1941
1942 JsException(out.str());
1943
1944 const String::AsciiValue stack_trace(try_catch.StackTrace());
1945 if (stack_trace.length()<=0)
1946 return false;
1947
1948 if (!*stack_trace)
1949 return false;
1950
1951 const string trace(*stack_trace);
1952
1953 typedef boost::char_separator<char> separator;
1954 const boost::tokenizer<separator> tokenizer(trace, separator("\n"));
1955
1956 // maybe skip: " at internal:"
1957 // maybe skip: " at unknown source:"
1958
1959 auto it = tokenizer.begin();
1960 JsException("");
1961 while (it!=tokenizer.end())
1962 JsException(*it++);
1963
1964 return false;
1965}
1966
1967Handle<Value> InterpreterV8::ExecuteInternal(const string &code)
1968{
1969 // Try/catch and re-throw hides our internal code from
1970 // the displayed exception showing the origin and shows
1971 // the user function instead.
1972 TryCatch exception;
1973
1974 const Handle<Value> result = ExecuteCode(code);
1975 if (exception.HasCaught())
1976 exception.ReThrow();
1977
1978 return result;
1979}
1980
1981Handle<Value> InterpreterV8::ExecuteCode(const string &code, const string &file, bool main)
1982{
1983 HandleScope handle_scope;
1984
1985 const Handle<String> source = String::New(code.c_str(), code.size());
1986 const Handle<String> origin = String::New(file.c_str());
1987 if (source.IsEmpty())
1988 return Handle<Value>();
1989
1990 const Handle<Script> script = Script::Compile(source, origin);
1991 if (script.IsEmpty())
1992 return Handle<Value>();
1993
1994 if (main)
1995 JsSetState(3);
1996
1997 TryCatch exception;
1998
1999 const Handle<Value> result = script->Run();
2000 if (exception.HasCaught())
2001 {
2002 if (file=="internal")
2003 return exception.ReThrow();
2004
2005 HandleException(exception, "code");
2006 return Handle<Value>();
2007 }
2008
2009 // If all went well and the result wasn't undefined then print
2010 // the returned value.
2011 if (!result.IsEmpty() && !result->IsUndefined() && file!="internal")
2012 JsResult(*String::AsciiValue(result));
2013
2014 return handle_scope.Close(result);
2015}
2016
2017bool InterpreterV8::ExecuteFile(const string &name, bool main)
2018{
2019 ifstream fin(name.c_str());
2020 if (!fin)
2021 {
2022 JsException("Error - Could not open file '"+name+"'");
2023 return false;
2024 }
2025
2026 string buffer;
2027 if (!getline(fin, buffer, '\0'))
2028 return true;
2029
2030 if (fin.fail())
2031 {
2032 JsException("Error - reading file.");
2033 return false;
2034 }
2035
2036 return !ExecuteCode(buffer, name, main).IsEmpty();
2037}
2038
2039bool InterpreterV8::ExecuteConsole()
2040{
2041 // Just necessray for the Handle<Script>
2042 const HandleScope handle_scope;
2043
2044 // A void script doing nothing than making sure that some JavaScript is executed
2045 const Handle<Script> catcher = Script::Compile(String::New(";"), String::New(""));
2046
2047 // Unlocking is necessary for the preemption to work
2048 const Unlocker global_unlock;
2049
2050 JsSetState(3);
2051
2052 WindowLog lout;
2053 lout << "\n " << kUnderline << " JavaScript interpreter " << kReset << " (enter '.q' to quit)\n" << endl;
2054
2055 Readline::StaticPushHistory("java.his");
2056
2057 string command;
2058 while (1)
2059 {
2060 const string buffer = Tools::Trim(Readline::StaticPrompt(command.empty() ? "JS> " : " \\> "));
2061 if (buffer==".q")
2062 break;
2063
2064 // buffer empty, do nothing
2065 if (buffer.empty())
2066 continue;
2067
2068 // Compose command
2069 if (!command.empty())
2070 command += ' ';
2071 command += buffer;
2072
2073 // If line ends with a backslash, allow addition of next line
2074 auto back = command.rbegin();
2075 if (*back=='\\')
2076 {
2077 *back = ' ';
2078 command = Tools::Trim(command);
2079 continue;
2080 }
2081
2082 // Locking is necessary to be able to execute java script code
2083 const Locker lock;
2084
2085 // Dump all pending exceptions. This is mainly to catch the 'null' exception
2086 // thrown if a running JavaScript should be terminated from somewhere.
2087 while (1)
2088 {
2089 TryCatch exception;
2090 catcher->Run();
2091 if (!exception.HasCaught())
2092 break;
2093 }
2094
2095 // Catch exceptions during code compilation
2096 TryCatch exception;
2097
2098 // Execute code which was entered
2099 bool rc = ExecuteCode(command, "console", false).IsEmpty();
2100 if (exception.HasCaught())
2101 {
2102 HandleException(exception, "compile");
2103 rc = true;
2104 }
2105
2106 // Stop all other threads
2107 for (auto it=fThreadIds.begin(); it!=fThreadIds.end(); it++)
2108 V8::TerminateExecution(*it);
2109
2110 // Allow the java scripts (threads) to run and hence to terminate
2111 const Unlocker unlock;
2112
2113 // Wait until all threads are terminated
2114 while (fThreadIds.size()>0)
2115 usleep(1000);
2116
2117 // In case of an exception add an empty line to the output
2118 if (rc)
2119 lout << endl;
2120
2121 // command has been executed, collect new command
2122 command = "";
2123 }
2124
2125 lout << endl;
2126
2127 Readline::StaticPopHistory("java.his");
2128
2129 return true;
2130}
2131
2132// ==========================================================================
2133// CORE
2134// ==========================================================================
2135
2136InterpreterV8::InterpreterV8() : fThreadId(-1)
2137{
2138 const string ver(V8::GetVersion());
2139
2140 typedef boost::char_separator<char> separator;
2141 const boost::tokenizer<separator> tokenizer(ver, separator("."));
2142
2143 const vector<string> tok(tokenizer.begin(), tokenizer.end());
2144
2145 const int major = tok.size()>0 ? stol(tok[0]) : -1;
2146 const int minor = tok.size()>1 ? stol(tok[1]) : -1;
2147 const int build = tok.size()>2 ? stol(tok[2]) : -1;
2148
2149 if (major>3 || (major==3 && minor>9) || (major==3 && minor==9 && build>10))
2150 {
2151 const string argv = "--use_strict";
2152 V8::SetFlagsFromString(argv.c_str(), argv.size());
2153 }
2154
2155 This = this;
2156}
2157
2158Handle<Value> InterpreterV8::Constructor(/*Handle<FunctionTemplate> T,*/ const Arguments &args)
2159{
2160 Handle<Value> argv[args.Length()];
2161
2162 for (int i=0; i<args.Length(); i++)
2163 argv[i] = args[i];
2164
2165 return args.Callee()->NewInstance(args.Length(), argv);
2166}
2167
2168
2169void InterpreterV8::AddFormatToGlobal()// const
2170{
2171 const string code =
2172 "String.form = function(str, arr)"
2173 "{"
2174 "var i = -1;"
2175 "function callback(exp, p0, p1, p2, p3, p4/*, pos, str*/)"
2176 "{"
2177 "if (exp=='%%')"
2178 "return '%';"
2179 ""
2180 "if (arr[++i]===undefined)"
2181 "return undefined;"
2182 ""
2183 "var exp = p2 ? parseInt(p2.substr(1)) : undefined;"
2184 "var base = p3 ? parseInt(p3.substr(1)) : undefined;"
2185 ""
2186 "var val;"
2187 "switch (p4)"
2188 "{"
2189 "case 's': val = arr[i]; break;"
2190 "case 'c': val = arr[i][0]; break;"
2191 "case 'f': val = parseFloat(arr[i]).toFixed(exp); break;"
2192 "case 'p': val = parseFloat(arr[i]).toPrecision(exp); break;"
2193 "case 'e': val = parseFloat(arr[i]).toExponential(exp); break;"
2194 "case 'x': val = parseInt(arr[i]).toString(base?base:16); break;"
2195 "case 'd': val = parseFloat(parseInt(arr[i], base?base:10).toPrecision(exp)).toFixed(0); break;"
2196 //"default:\n"
2197 //" throw new SyntaxError('Conversion specifier '+p4+' unknown.');\n"
2198 "}"
2199 ""
2200 "val = typeof(val)=='object' ? JSON.stringify(val) : val.toString(base);"
2201 ""
2202 "var sz = parseInt(p1); /* padding size */"
2203 "var ch = p1 && p1[0]=='0' ? '0' : ' '; /* isnull? */"
2204 "while (val.length<sz)"
2205 "val = p0 !== undefined ? val+ch : ch+val; /* isminus? */"
2206 ""
2207 "return val;"
2208 "}"
2209 ""
2210 "var regex = /%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd])/g;"
2211 "return str.replace(regex, callback);"
2212 "}"
2213 "\n"
2214 "String.prototype.$ = function()"
2215 "{"
2216 "return String.form(this, Array.prototype.slice.call(arguments));"
2217 "}"/*
2218 "\n"
2219 "var format = function()"
2220 "{"
2221 "return dim.format(arguments[0], Array.prototype.slice.call(arguments,1));"
2222 "}"*/;
2223
2224 // ExcuteInternal does not work properly here...
2225 // If suring compilation an exception is thrown, it will not work
2226 Handle<Script> script = Script::New(String::New(code.c_str()), String::New("internal"));
2227 if (!script.IsEmpty())
2228 script->Run();
2229}
2230
2231bool InterpreterV8::JsRun(const string &filename, const map<string, string> &map)
2232{
2233 const Locker locker;
2234 fThreadId = V8::GetCurrentThreadId();
2235
2236 JsPrint(string("JavaScript Engine V8 ")+V8::GetVersion());
2237
2238 JsLoad(filename);
2239
2240 const HandleScope handle_scope;
2241
2242 // Create a template for the global object.
2243 Handle<ObjectTemplate> dim = ObjectTemplate::New();
2244 dim->Set(String::New("log"), FunctionTemplate::New(WrapLog), ReadOnly);
2245 dim->Set(String::New("alarm"), FunctionTemplate::New(WrapAlarm), ReadOnly);
2246 dim->Set(String::New("wait"), FunctionTemplate::New(WrapWait), ReadOnly);
2247 dim->Set(String::New("send"), FunctionTemplate::New(WrapSend), ReadOnly);
2248 dim->Set(String::New("state"), FunctionTemplate::New(WrapState), ReadOnly);
2249 dim->Set(String::New("version"), Integer::New(DIM_VERSION_NUMBER), ReadOnly);
2250 dim->Set(String::New("getStates"), FunctionTemplate::New(WrapGetStates), ReadOnly);
2251 dim->Set(String::New("getDescription"), FunctionTemplate::New(WrapGetDescription), ReadOnly);
2252 dim->Set(String::New("getServices"), FunctionTemplate::New(WrapGetServices), ReadOnly);
2253
2254 Handle<ObjectTemplate> dimctrl = ObjectTemplate::New();
2255 dimctrl->Set(String::New("defineState"), FunctionTemplate::New(WrapNewState), ReadOnly);
2256 dimctrl->Set(String::New("setState"), FunctionTemplate::New(WrapSetState), ReadOnly);
2257 dimctrl->Set(String::New("getState"), FunctionTemplate::New(WrapGetState), ReadOnly);
2258
2259 Handle<ObjectTemplate> v8 = ObjectTemplate::New();
2260 v8->Set(String::New("sleep"), FunctionTemplate::New(WrapSleep), ReadOnly);
2261 v8->Set(String::New("timeout"), FunctionTemplate::New(WrapTimeout), ReadOnly);
2262 v8->Set(String::New("version"), String::New(V8::GetVersion()), ReadOnly);
2263
2264 Handle<ObjectTemplate> console = ObjectTemplate::New();
2265 console->Set(String::New("out"), FunctionTemplate::New(WrapOut), ReadOnly);
2266
2267 Handle<ObjectTemplate> onchange = ObjectTemplate::New();
2268 onchange->SetNamedPropertyHandler(OnChangeGet, WrapOnChangeSet);
2269 dim->Set(String::New("onchange"), onchange);
2270
2271 Handle<ObjectTemplate> global = ObjectTemplate::New();
2272 global->Set(String::New("v8"), v8, ReadOnly);
2273 global->Set(String::New("dim"), dim, ReadOnly);
2274 global->Set(String::New("dimctrl"), dimctrl, ReadOnly);
2275 global->Set(String::New("console"), console, ReadOnly);
2276 global->Set(String::New("include"), FunctionTemplate::New(WrapInclude), ReadOnly);
2277 global->Set(String::New("exit"), FunctionTemplate::New(WrapExit), ReadOnly);
2278
2279 Handle<FunctionTemplate> sub = FunctionTemplate::New(WrapSubscription);
2280 sub->SetClassName(String::New("Subscription"));
2281 sub->InstanceTemplate()->SetInternalFieldCount(1);
2282 global->Set(String::New("Subscription"), sub, ReadOnly);
2283
2284 Handle<FunctionTemplate> db = FunctionTemplate::New(WrapDatabase);
2285 db->SetClassName(String::New("Database"));
2286 db->InstanceTemplate()->SetInternalFieldCount(1);
2287 global->Set(String::New("Database"), db, ReadOnly);
2288
2289 Handle<FunctionTemplate> thread = FunctionTemplate::New(WrapThread);
2290 thread->SetClassName(String::New("Thread"));
2291 global->Set(String::New("Thread"), thread, ReadOnly);
2292
2293 Handle<FunctionTemplate> file = FunctionTemplate::New(WrapFile);
2294 file->SetClassName(String::New("File"));
2295 global->Set(String::New("File"), file, ReadOnly);
2296
2297 Handle<FunctionTemplate> evt = FunctionTemplate::New();
2298 evt->SetClassName(String::New("Event"));
2299 global->Set(String::New("Event"), evt, ReadOnly);
2300
2301 Handle<FunctionTemplate> desc = FunctionTemplate::New();
2302 desc->SetClassName(String::New("Description"));
2303 global->Set(String::New("Description"), desc, ReadOnly);
2304
2305 fTemplateEvent = evt;
2306 fTemplateDescription = desc;
2307
2308#ifdef HAVE_NOVA
2309 Handle<FunctionTemplate> sky = FunctionTemplate::New(ConstructorSky);
2310 sky->SetClassName(String::New("Sky"));
2311 sky->Set(String::New("dist"), FunctionTemplate::New(SkyDist), ReadOnly);
2312 global->Set(String::New("Sky"), sky, ReadOnly);
2313
2314 Handle<FunctionTemplate> loc = FunctionTemplate::New(ConstructorLocal);
2315 loc->SetClassName(String::New("Local"));
2316 loc->Set(String::New("dist"), FunctionTemplate::New(LocalDist), ReadOnly);
2317 global->Set(String::New("Local"), loc, ReadOnly);
2318
2319 Handle<FunctionTemplate> moon = FunctionTemplate::New(ConstructorMoon);
2320 moon->SetClassName(String::New("Moon"));
2321 moon->Set(String::New("disk"), FunctionTemplate::New(MoonDisk), ReadOnly);
2322 moon->Set(String::New("horizon"), FunctionTemplate::New(MoonHorizon), ReadOnly);
2323 global->Set(String::New("Moon"), moon, ReadOnly);
2324
2325 Handle<FunctionTemplate> sun = FunctionTemplate::New();
2326 sun->SetClassName(String::New("Sun"));
2327 sun->Set(String::New("horizon"), FunctionTemplate::New(SunHorizon), ReadOnly);
2328 global->Set(String::New("Sun"), sun, ReadOnly);
2329
2330 fTemplateLocal = loc;
2331 fTemplateSky = sky;
2332#endif
2333
2334 // Persistent
2335 Persistent<Context> context = Context::New(NULL, global);
2336 if (context.IsEmpty())
2337 {
2338 JsException("Creation of global context failed...");
2339 JsEnd(filename);
2340 return false;
2341 }
2342
2343 // Switch off eval(). It is not possible to track it's exceptions.
2344 context->AllowCodeGenerationFromStrings(false);
2345
2346 Context::Scope scope(context);
2347
2348 Handle<Array> args = Array::New(map.size());
2349 for (auto it=map.begin(); it!=map.end(); it++)
2350 args->Set(String::New(it->first.c_str()), String::New(it->second.c_str()));
2351 context->Global()->Set(String::New("$"), args, ReadOnly);
2352 context->Global()->Set(String::New("arg"), args, ReadOnly);
2353
2354 //V8::ResumeProfiler();
2355
2356 TryCatch exception;
2357
2358 AddFormatToGlobal();
2359
2360 bool rc = true;
2361 if (!exception.HasCaught())
2362 {
2363 JsStart(filename);
2364
2365 Locker::StartPreemption(10);
2366
2367 rc &= filename.empty() ? ExecuteConsole() : ExecuteFile(filename, true);
2368
2369 Locker::StopPreemption();
2370
2371 // Stop all other threads
2372 for (auto it=fThreadIds.begin(); it!=fThreadIds.end(); it++)
2373 V8::TerminateExecution(*it);
2374 fThreadIds.clear();
2375 }
2376
2377 // Handle an exception
2378 rc &= HandleException(exception, "main");
2379
2380 // IsProfilerPaused()
2381 // V8::PauseProfiler();
2382
2383 // -----
2384 // This is how an exit handler could look like, but there is no way to interrupt it
2385 // -----
2386 // Handle<Object> obj = Handle<Object>::Cast(context->Global()->Get(String::New("dim")));
2387 // if (!obj.IsEmpty())
2388 // {
2389 // Handle<Value> onexit = obj->Get(String::New("onexit"));
2390 // if (!onexit->IsUndefined())
2391 // Handle<Function>::Cast(onexit)->NewInstance(0, NULL); // argc, argv
2392 // // Handle<Object> result = Handle<Function>::Cast(onexit)->NewInstance(0, NULL); // argc, argv
2393 // }
2394
2395 //context->Exit();
2396
2397 // The threads are started already and wait to get the lock
2398 // So we have to unlock (manual preemtion) so that they get
2399 // the signal to terminate.
2400 {
2401 const Unlocker unlock;
2402
2403 for (auto it=fThreads.begin(); it!=fThreads.end(); it++)
2404 it->join();
2405 fThreads.clear();
2406 }
2407
2408 // Now we can dispose all persistent handles from state callbacks
2409 for (auto it=fStateCallbacks.begin(); it!=fStateCallbacks.end(); it++)
2410 it->second.Dispose();
2411 fStateCallbacks.clear();
2412
2413 // Now we can dispose all persistent handles from reverse maps
2414 for (auto it=fReverseMap.begin(); it!=fReverseMap.end(); it++)
2415 it->second.Dispose();
2416 fReverseMap.clear();
2417
2418#ifdef HAVE_SQL
2419 // ...and close all database handles
2420 for (auto it=fDatabases.begin(); it!=fDatabases.end(); it++)
2421 delete *it;
2422 fDatabases.clear();
2423#endif
2424
2425 fStates.clear();
2426
2427 context.Dispose();
2428
2429 JsEnd(filename);
2430
2431 return true;
2432}
2433
2434void InterpreterV8::JsStop()
2435{
2436 Locker locker;
2437 V8::TerminateExecution(This->fThreadId);
2438}
2439
2440#endif
2441
2442InterpreterV8 *InterpreterV8::This = 0;
Note: See TracBrowser for help on using the repository browser.