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

Last change on this file since 14556 was 14556, checked in by tbretz, 12 years ago
Added 'comment' to state info.
File size: 32.8 KB
Line 
1#include "InterpreterV8.h"
2
3#ifdef HAVE_SQL
4#include "Database.h"
5#endif
6
7#include <boost/tokenizer.hpp>
8
9InterpreterV8 *InterpreterV8::This = 0;
10
11#ifdef HAVE_V8
12
13#include <v8.h>
14#include <fstream>
15#include <sstream>
16#include <iomanip>
17
18using namespace std;
19using namespace v8;
20
21bool InterpreterV8::ReportException(TryCatch* try_catch)
22{
23 if (!try_catch->CanContinue())
24 return false;
25
26 const HandleScope handle_scope;
27
28 const String::Utf8Value exception(try_catch->Exception());
29
30 if (*exception && string(*exception)=="exit")
31 return true;
32 if (*exception && string(*exception)=="null")
33 return false;
34
35 const Handle<Message> message = try_catch->Message();
36 if (message.IsEmpty())
37 return false;
38
39 // Print (filename):(line number): (message).
40 const String::Utf8Value filename(message->GetScriptResourceName());
41
42 ostringstream out;
43
44 if (*filename)
45 out << *filename << ": ";
46 out << "l." << message->GetLineNumber();
47 if (*exception)
48 out << ": " << *exception;
49
50 JsException(out.str());
51
52 // Print line of source code.
53 const String::Utf8Value sourceline(message->GetSourceLine());
54 if (*sourceline)
55 JsException(*sourceline);
56
57 // Print wavy underline (GetUnderline is deprecated).
58 const int start = message->GetStartColumn();
59 const int end = message->GetEndColumn();
60
61 out.str("");
62 if (start>0)
63 out << setfill(' ') << setw(start) << ' ';
64 out << setfill('^') << setw(end-start) << '^';
65
66 JsException(out.str());
67
68 String::Utf8Value stack_trace(try_catch->StackTrace());
69 if (stack_trace.length()<=0)
70 return false;
71
72 //if (*stack_trace)
73 // JsException(string("\n")+*stack_trace);
74
75 return false;
76}
77
78// Executes a string within the current v8 context.
79bool InterpreterV8::ExecuteStringNT(const Handle<String> &code, const Handle<Value> &file)
80{
81 if (code.IsEmpty())
82 return true;
83
84 const HandleScope handle_scope;
85
86 const Handle<Script> script = Script::Compile(code, file);
87 if (script.IsEmpty())
88 return false;
89
90 const Handle<Value> result = script->Run();
91 if (result.IsEmpty())
92 return false;
93
94 // If all went well and the result wasn't undefined then print
95 // the returned value.
96 if (!result->IsUndefined())
97 JsResult(*String::Utf8Value(result));
98
99 return true;
100}
101
102bool InterpreterV8::ExecuteCode(const Handle<String> &code, const Handle<Value> &file)
103{
104 TryCatch exception;
105
106 const bool rc = ExecuteStringNT(code, file);
107
108 // Check if this is a termination exception
109 //if (!exception.CanContinue())
110 // return false;
111
112 if (exception.HasCaught())
113 return ReportException(&exception);
114
115 return rc;
116}
117
118bool InterpreterV8::ExecuteCode(const string &code, const string &file)
119{
120 return ExecuteCode(String::New(code.c_str(), code.size()),
121 String::New(file.c_str()));
122}
123
124bool InterpreterV8::ExecuteFile(const string &name)
125{
126 ifstream fin(name.c_str());
127 if (!fin)
128 {
129 JsException("Error - Could not open file '"+name+"'");
130 return false;
131 }
132
133 string buffer;
134 if (!getline(fin, buffer, '\0'))
135 return true;
136
137 if (fin.fail())
138 {
139 JsException("Error - reading file.");
140 return false;
141 }
142
143 return ExecuteCode(buffer, name);
144}
145
146Handle<Value> InterpreterV8::FuncWait(const Arguments& args)
147{
148 if (args.Length()!=2 && args.Length()!=3)
149 return ThrowException(String::New("Number of arguments must be 2 or 3."));
150
151 if (!args[0]->IsString())
152 return ThrowException(String::New("Argument 1 not a string."));
153
154 if (!args[1]->IsInt32() && !args[1]->IsString())
155 return ThrowException(String::New("Argument 2 not an int32 and not a string."));
156
157 if (args.Length()==3 && !args[2]->IsUint32())
158 return ThrowException(String::New("Argument 3 not an uint32."));
159
160 // Using a Javascript function has the advantage that it is fully
161 // interruptable without the need of C++ code
162
163 const string index = args[1]->IsInt32() ? "s.index" : "s.name";
164 const bool timeout = args.Length()==3;
165 const string arg0 = *String::Utf8Value(args[0]);
166 const string state = args[1]->IsString() ? *String::Utf8Value(args[1]) : "";
167 const string arg1 = args[1]->IsString() ? ("\""+state+"\"") : to_string(args[1]->Int32Value());
168
169 if (arg0.find_first_of("\"'")!=string::npos)
170 return ThrowException(String::New("Server name must not contain quotation marks."));
171
172 if (args[1]->IsString())
173 if (state.find_first_of("\"'")!=string::npos)
174 return ThrowException(String::New("State name must not contain quotation marks."));
175
176 string code = "(function(name,state,ms)"
177 "{";
178 if (timeout)
179 code += "var t = new Date();";
180 code += "while (1)"
181 "{"
182 "var s = dim.state(name);"
183 "if(!"+index+")throw 'Waitig for state "+arg1+" of server "+arg0+" failed.';"
184 "if(state=="+index+")return true;";
185 if (timeout)
186 code += "if((new Date()-t)>ms)return false;";
187
188 code += "dim.sleep();"
189 "}"
190 "})('"+arg0+"',"+arg1;
191 if (timeout)
192 code += "," + to_string(args[2]->Int32Value());
193 code += ");";
194
195 const HandleScope handle_scope;
196
197 // It is not strictly necessary to catch the exception, instead
198 // script->Run() could just be returned, but catching the
199 // exception allow to print the position in the file in
200 // the exception handler instead of just the posiiton in the script.
201 TryCatch exception;
202
203 const Handle<Script> script = Script::Compile(String::New(code.c_str()));
204 const Handle<Value> result = script->Run();
205
206 return exception.HasCaught() ? exception.ReThrow() : result;
207
208 /*
209 const string server = *String::Utf8Value(args[0]);
210 const int32_t state = args[1]->Int32Value();
211 const uint32_t millisec = args.Length()==3 ? args[2]->Int32Value() : 0;
212
213 const int rc = JsWait(server, state, millisec);
214
215 if (rc==0 || rc==1)
216 return Boolean::New(rc);
217
218 return ThrowException(String::New(("Waitig for state "+to_string(state)+" of server '"+server+"' failed.").c_str()));
219 */
220}
221
222Handle<Value> InterpreterV8::FuncSend(const Arguments& args)
223{
224 if (args.Length()==0)
225 return ThrowException(String::New("Number of arguments must be at least 1."));
226
227 if (!args[0]->IsString())
228 return ThrowException(String::New("Argument 1 must be a string."));
229
230 const HandleScope handle_scope;
231
232 const String::Utf8Value str(args[0]);
233
234 string command = *str;
235
236 // Escape all string arguments. All others can be kept as they are.
237 for (int i=1; i<args.Length(); i++)
238 {
239 const String::Utf8Value arg(args[i]);
240 if (args[i]->IsString())
241 command += " \""+string(*arg)+"\"";
242 else
243 command += " "+string(*arg);
244 }
245
246 return Boolean::New(JsSend(command));
247}
248
249Handle<Value> InterpreterV8::FuncSleep(const Arguments& args)
250{
251 if (args.Length()==0)
252 {
253 // Theoretically, the CPU usage can be reduced by maybe a factor
254 // of four using a larger value, but this also means that the
255 // JavaScript is locked for a longer time.
256 usleep(1000);
257 return Undefined();
258 }
259
260 if (args.Length()!=1)
261 return ThrowException(String::New("Number of arguments must be exactly 1."));
262
263 if (!args[0]->IsUint32())
264 return ThrowException(String::New("Argument 1 must be an uint32."));
265
266 // Using a Javascript function has the advantage that it is fully
267 // interruptable without the need of C++ code
268
269 const string code =
270 "(function(){"
271 "var t=new Date();"
272 "while ((new Date()-t)<"+to_string(args[0]->Int32Value())+") dim.sleep();"
273 "})();";
274
275 const HandleScope handle_scope;
276
277 const Handle<Script> script = Script::Compile(String::New(code.c_str()));
278 return script->Run();
279
280 //JsSleep(args[0]->Int32Value());
281 //return Undefined();
282}
283
284Handle<Value> InterpreterV8::FuncState(const Arguments& args)
285{
286 if (args.Length()!=1)
287 return ThrowException(String::New("Number of arguments must be exactly 1."));
288
289 if (!args[0]->IsString())
290 return ThrowException(String::New("Argument 1 must be a string."));
291
292 // Return state.name/state.index
293
294 const String::Utf8Value str(args[0]);
295
296 const State rc = JsState(*str);
297
298 //if (rc.first<=-256)
299 // return Undefined();
300
301 HandleScope handle_scope;
302
303 // It is important to catch the exception thrown
304 // by Date::New in case of thread termination!
305 Local<Value> date;
306 {
307 TryCatch exception;
308 date = Date::New(rc.time.JavaDate());
309 if (exception.HasCaught())
310 return exception.ReThrow();
311 }
312
313 Handle<ObjectTemplate> obj = ObjectTemplate::New();
314 obj->Set(String::New("index"), rc.index<=-256?Undefined():Integer::New(rc.index), ReadOnly);
315 obj->Set(String::New("name"), rc.index<=-256?Undefined():String::New(rc.name.c_str()), ReadOnly);
316 if (rc.index>-256)
317 obj->Set(String::New("time"), date);
318 //obj->Set(String::New("toString"), String::New(("[Object state "+string(*str)+":"+to_string(rc.index)+"]").c_str()));
319
320 return handle_scope.Close(obj->NewInstance());
321}
322
323Handle<Value> InterpreterV8::FuncExit(const Arguments &)
324{
325 V8::TerminateExecution(fThreadId);
326 return ThrowException(String::New("exit"));
327/*
328 if (args.Length()!=1)
329 return ThrowException(String::New("Number of arguments must be exactly 1."));
330
331 if (!args[0]->IsUint32())
332 return ThrowException(String::New("Argument 1 must be an uint32."));
333
334 const HandleScope handle_scope;
335
336 JsSleep(args[0]->Int32Value());
337*/
338 return Undefined();
339}
340
341// The callback that is invoked by v8 whenever the JavaScript 'print'
342// function is called. Prints its arguments on stdout separated by
343// spaces and ending with a newline.
344Handle<Value> InterpreterV8::FuncPrint(const Arguments& args)
345{
346 for (int i=0; i<args.Length(); i++)
347 {
348 const HandleScope handle_scope;
349
350 const String::Utf8Value str(args[i]);
351 if (*str)
352 JsPrint(*str);
353 }
354 return Undefined();
355}
356
357Handle<Value> InterpreterV8::FuncAlarm(const Arguments& args)
358{
359 for (int i=0; i<args.Length(); i++)
360 {
361 const HandleScope handle_scope;
362
363 const String::Utf8Value str(args[i]);
364 if (*str)
365 JsAlarm(*str);
366 }
367
368 if (args.Length()==0)
369 JsAlarm();
370
371 return Undefined();
372}
373
374Handle<Value> InterpreterV8::FuncOut(const Arguments& args)
375{
376 for (int i=0; i<args.Length(); i++)
377 {
378 const HandleScope handle_scope;
379
380 const String::Utf8Value str(args[i]);
381 if (*str)
382 JsOut(*str);
383 }
384 return Undefined();
385}
386
387// The callback that is invoked by v8 whenever the JavaScript 'load'
388// function is called. Loads, compiles and executes its argument
389// JavaScript file.
390Handle<Value> InterpreterV8::FuncInclude(const Arguments& args)
391{
392 for (int i=0; i<args.Length(); i++)
393 {
394 const HandleScope handle_scope;
395
396 const String::Utf8Value file(args[i]);
397 if (*file == NULL)
398 return ThrowException(String::New(("Error loading file '"+string(*file)+"'").c_str()));
399
400 if (!ExecuteFile(*file))
401 return ThrowException(String::New(("Execution of '"+string(*file)+"' failed").c_str()));
402 }
403 return Undefined();
404}
405
406Handle<Value> InterpreterV8::FuncVersion(const Arguments&)
407{
408 return String::New(V8::GetVersion());
409}
410
411Handle<Value> InterpreterV8::FuncDbClose(const Arguments &args)
412{
413 HandleScope handle_scope;
414
415 void *ptr = Handle<External>::Cast(args.This()->GetInternalField(0))->Value();
416 if (!ptr)
417 return Boolean::New(false);
418
419#ifdef HAVE_SQL
420 Database *db = reinterpret_cast<Database*>(ptr);
421 auto it = find(fDatabases.begin(), fDatabases.end(), db);
422 fDatabases.erase(it);
423 delete db;
424#endif
425
426 args.This()->SetInternalField(0, External::New(0));
427
428 return Boolean::New(true);
429}
430Handle<Value> InterpreterV8::FuncDbQuery(const Arguments &args)
431{
432 if (args.Length()!=1)
433 return ThrowException(String::New("Number of arguments must be exactly 1."));
434
435 if (!args[0]->IsString())
436 return ThrowException(String::New("Both arguments must be a string."));
437
438 HandleScope handle_scope;
439
440 void *ptr = Handle<External>::Cast(args.This()->GetInternalField(0))->Value();
441 if (!ptr)
442 return Undefined();
443
444 const String::Utf8Value query(args[0]);
445
446#ifdef HAVE_SQL
447 try
448 {
449 Database *db = reinterpret_cast<Database*>(ptr);
450
451 const mysqlpp::StoreQueryResult res = db->query(*query).store();
452
453 Handle<Array> ret = Array::New();
454 ret->Set(String::New("table"), String::New(res.table()), ReadOnly);
455
456 Handle<Array> cols = Array::New();
457
458 int irow=0;
459 for (vector<mysqlpp::Row>::const_iterator it=res.begin(); it<res.end(); it++)
460 {
461 Handle<Array> row = Array::New();
462
463 const mysqlpp::FieldNames *list = it->field_list().list;
464
465 for (size_t i=0; i<it->size(); i++)
466 {
467 const Handle<Value> name = String::New((*list)[i].c_str());
468 if (irow==0)
469 cols->Set(Integer::NewFromUnsigned(i), name, ReadOnly);
470
471 if ((*it)[i].is_null())
472 {
473 row->Set(name, Undefined(), ReadOnly);
474 continue;
475 }
476
477 const string sql_type = (*it)[i].type().sql_name();
478
479 const bool uns = sql_type.find("UNSIGNED")==string::npos;
480
481 if (sql_type.find("BIGINT")!=string::npos)
482 {
483 if (uns)
484 {
485 const uint64_t val = (uint64_t)(*it)[i];
486 if (val>UINT32_MAX)
487 row->Set(name, Number::New(val), ReadOnly);
488 else
489 row->Set(name, Integer::NewFromUnsigned(val), ReadOnly);
490 }
491 else
492 {
493 const int64_t val = (int64_t)(*it)[i];
494 if (val<INT32_MIN || val>INT32_MAX)
495 row->Set(name, Number::New(val), ReadOnly);
496 else
497 row->Set(name, Integer::NewFromUnsigned(val), ReadOnly);
498 }
499 continue;
500 }
501
502 // 32 bit
503 if (sql_type.find("INT")!=string::npos)
504 {
505 if (uns)
506 row->Set(name, Integer::NewFromUnsigned((uint32_t)(*it)[i]), ReadOnly);
507 else
508 row->Set(name, Integer::New((int32_t)(*it)[i]), ReadOnly);
509 }
510
511 if (sql_type.find("BOOL")!=string::npos )
512 {
513 row->Set(name, Boolean::New((bool)(*it)[i]), ReadOnly);
514 continue;
515 }
516
517 if (sql_type.find("FLOAT")!=string::npos)
518 {
519 ostringstream val;
520 val << setprecision(7) << (float)(*it)[i];
521 row->Set(name, Number::New(stod(val.str())), ReadOnly);
522 continue;
523
524 }
525 if (sql_type.find("DOUBLE")!=string::npos)
526 {
527 row->Set(name, Number::New((double)(*it)[i]), ReadOnly);
528 continue;
529 }
530
531 if (sql_type.find("CHAR")!=string::npos ||
532 sql_type.find("TEXT")!=string::npos)
533 {
534 row->Set(name, String::New((const char*)(*it)[i]), ReadOnly);
535 continue;
536 }
537
538 time_t date = 0;
539 if (sql_type.find("TIMESTAMP")!=string::npos)
540 date = mysqlpp::Time((*it)[i]);
541
542 if (sql_type.find("DATETIME")!=string::npos)
543 date = mysqlpp::DateTime((*it)[i]);
544
545 if (sql_type.find(" DATE ")!=string::npos)
546 date = mysqlpp::Date((*it)[i]);
547
548 if (date>0)
549 {
550 // It is important to catch the exception thrown
551 // by Date::New in case of thread termination!
552 TryCatch exception;
553 Local<Value> val = Date::New(date*1000);
554 if (exception.HasCaught())
555 return exception.ReThrow();
556 //if (V8::IsExecutionTerminating())
557 // return Undefined();
558
559 row->Set(name, val, ReadOnly);
560 }
561 }
562
563 ret->Set(Integer::NewFromUnsigned(irow++), row, ReadOnly);
564 }
565
566 if (irow>0)
567 ret->Set(String::New("cols"), cols, ReadOnly);
568
569 return handle_scope.Close(ret);
570 }
571 catch (const exception &e)
572 {
573 return ThrowException(String::New(e.what()));
574 }
575#endif
576}
577
578Handle<Value> InterpreterV8::FuncDatabase(const Arguments &args)
579{
580 if (args.Length()!=1)
581 return ThrowException(String::New("Number of arguments must be exactly 1."));
582
583 if (!args[0]->IsString())
584 return ThrowException(String::New("Argument 1 must be a string."));
585
586 HandleScope handle_scope;
587
588 const String::Utf8Value database(args[0]);
589 const String::Utf8Value query (args[1]);
590
591#ifdef HAVE_SQL
592 try
593 {
594 Database *db = new Database(*database);
595 fDatabases.push_back(db);
596
597 Handle<ObjectTemplate> tem = ObjectTemplate::New();
598 tem->Set(String::New("user"), String::New(db->user.c_str()), ReadOnly);
599 tem->Set(String::New("server"), String::New(db->server.c_str()), ReadOnly);
600 tem->Set(String::New("database"), String::New(db->db.c_str()), ReadOnly);
601 tem->Set(String::New("port"), db->port==0?Undefined():Integer::NewFromUnsigned(db->port), ReadOnly);
602 tem->Set(String::New("query"), FunctionTemplate::New(WrapDbQuery), ReadOnly);
603 tem->Set(String::New("close"), FunctionTemplate::New(WrapDbClose), ReadOnly);
604 tem->SetInternalFieldCount(1);
605
606 Handle<Object> obj = tem->NewInstance();
607 obj->SetInternalField(0, External::New(db));
608
609 return handle_scope.Close(obj);
610 }
611 catch (const exception &e)
612 {
613 return ThrowException(String::New(e.what()));
614 }
615#endif
616}
617
618Handle<Value> InterpreterV8::Convert(char type, const char* &ptr)
619{
620 // Dim values are always unsigned per (FACT++) definition
621 switch (type)
622 {
623 case 'F':
624 {
625 // Remove the "imprecision" effect coming from casting a float to
626 // a double and then showing it with double precision
627 ostringstream val;
628 val << setprecision(7) << *reinterpret_cast<const float*>(ptr);
629 Handle<Value> v=Number::New(stod(val.str()));
630 ptr+=4;
631 return v;
632 }
633 case 'D': { Handle<Value> v=Number::New(*reinterpret_cast<const double*>(ptr)); ptr+=8; return v; }
634 case 'I':
635 case 'L': { Handle<Value> v=Integer::NewFromUnsigned(*reinterpret_cast<const uint32_t*>(ptr)); ptr += 4; return v; }
636 case 'X':
637 {
638 const uint64_t val = *reinterpret_cast<const uint64_t*>(ptr);
639 ptr += 8;
640 if (val>UINT32_MAX)
641 return Number::New(val);
642 return Integer::NewFromUnsigned(val);
643 }
644 case 'S': { Handle<Value> v=Integer::NewFromUnsigned(*reinterpret_cast<const uint16_t*>(ptr)); ptr += 2; return v; }
645 case 'C': { Handle<Value> v=Integer::NewFromUnsigned((uint16_t)*reinterpret_cast<const uint8_t*>(ptr)); ptr += 1; return v; }
646 case ':': { Handle<Value> v=String::New(ptr); return v; }
647 }
648 return Undefined();
649}
650
651Handle<Value> InterpreterV8::FuncClose(const Arguments &args)
652{
653 const HandleScope handle_scope;
654
655 //const void *ptr = Local<External>::Cast(args.Holder()->GetInternalField(0))->Value();
656
657 const String::Utf8Value str(args.Holder()->Get(String::New("name")));
658
659 const auto it = fReverseMap.find(*str);
660 if (it!=fReverseMap.end())
661 {
662 it->second.Dispose();
663 fReverseMap.erase(it);
664 }
665
666 args.Holder()->Set(String::New("isOpen"), Boolean::New(false), ReadOnly);
667
668 return Boolean::New(JsUnsubscribe(*str));
669}
670
671Handle<Value> InterpreterV8::ConvertEvent(const EventImp *evt, uint64_t counter, const char *str)
672{
673 Local<Value> date;
674
675 // It is important to catch the exception thrown
676 // by Date::New in case of thread termination!
677 {
678 TryCatch exception;
679 date = Date::New(evt->GetJavaDate());
680 if (exception.HasCaught())
681 return exception.ReThrow();
682 }
683
684 const vector<Description> vec = JsDescription(str);
685
686 Handle<Array> ret = Array::New();
687 ret->Set(String::New("name"), String::New(str), ReadOnly);
688 ret->Set(String::New("format"), String::New(evt->GetFormat().c_str()), ReadOnly);
689 ret->Set(String::New("named"), Boolean::New(vec.size()>0), ReadOnly);
690 ret->Set(String::New("qos"), Integer::New(evt->GetQoS()), ReadOnly);
691 ret->Set(String::New("size"), Integer::New(evt->GetSize()), ReadOnly);
692 ret->Set(String::New("counter"), Integer::New(counter), ReadOnly);
693 ret->Set(String::New("time"), date, ReadOnly);
694
695 typedef boost::char_separator<char> separator;
696 const boost::tokenizer<separator> tokenizer(evt->GetFormat(), separator(";:"));
697
698 const vector<string> tok(tokenizer.begin(), tokenizer.end());
699
700 Handle<Array> obj = tok.size()==1 ? ret : Array::New();
701
702 const char *ptr = evt->GetText();
703 try
704 {
705 size_t pos = 1;
706 for (auto it=tok.begin(); it!=tok.end(); it++, pos++)
707 {
708 if (ptr>=evt->GetText())
709 return ret;
710
711 char type = (*it)[0];
712 it++;
713
714 if (it==tok.end() && type=='C')
715 type = ':';
716
717 if (it==tok.end() && type!=':')
718 return Exception::Error(String::New(("Format string invalid '"+evt->GetFormat()+"'").c_str()));
719
720 string name = pos<vec.size() ? vec[pos].name : "";
721 if (tok.size()==1)
722 name = "data";
723
724 const uint32_t cnt = it==tok.end() ? 1 : stoi(it->c_str());
725
726 if (cnt==1)
727 {
728 const Handle<Value> v = Convert(type, ptr);
729 if (tok.size()>1)
730 obj->Set(pos-1, v);
731 if (!name.empty())
732 obj->Set(String::New(name.c_str()), v);
733 }
734 else
735 {
736 Handle<Array> a = Array::New(cnt);
737 for (uint32_t i=0; i<cnt; i++)
738 a->Set(i, Convert(type, ptr));
739 if (tok.size()>1)
740 obj->Set(pos-1, a);
741 if (!name.empty())
742 obj->Set(String::New(name.c_str()), a);
743 }
744
745 if (it==tok.end())
746 break;
747 }
748
749 if (tok.size()>1)
750 ret->Set(String::New("data"), obj, ReadOnly);
751
752 return ret;
753 }
754 catch (...)
755 {
756 return Exception::Error(String::New(("Format string conversion '"+evt->GetFormat()+"' failed.").c_str()));
757 }
758}
759
760Handle<Value> InterpreterV8::FuncGetData(const Arguments &args)
761{
762 HandleScope handle_scope;
763
764 const String::Utf8Value str(args.Holder()->Get(String::New("name")));
765
766 const pair<uint64_t, EventImp *> p = JsGetEvent(*str);
767
768 const EventImp *evt = p.second;
769 if (!evt)
770 return Undefined();
771
772 //if (counter==cnt)
773 // return info.Holder();//Holder()->Get(String::New("data"));
774
775 Handle<Value> ret = ConvertEvent(evt, p.first, *str);
776 return ret->IsNativeError() ? ThrowException(ret) : handle_scope.Close(ret);
777}
778
779// This is a callback from the RemoteControl piping event handling
780// to the java script ---> in test phase!
781void InterpreterV8::JsHandleEvent(const EventImp &evt, uint64_t cnt, const string &service)
782{
783 if (fThreadId<0)
784 return;
785
786 Locker locker;
787
788 const auto it = fReverseMap.find(service);
789 if (it==fReverseMap.end())
790 return;
791
792 const HandleScope handle_scope;
793
794 Handle<Object> obj = it->second;
795 if (obj.IsEmpty())
796 return;
797
798 const Handle<String> onchange = String::New("onchange");
799 if (!obj->Has(onchange))
800 return;
801
802 const Handle<Value> val = obj->Get(onchange);
803 if (!val->IsFunction())
804 return;
805
806 // -------------------------------------------------------------------
807 // We are not in a context... we need to get into one for Array::New
808
809 Persistent<Context> context = Context::New();
810 if (context.IsEmpty())
811 return;
812
813 const Context::Scope scope(context);
814
815 // -------------------------------------------------------------------
816
817 TryCatch exception;
818
819 Handle<Value> ret = ConvertEvent(&evt, cnt, service.c_str());
820 if (ret->IsArray())
821 {
822 Handle<Array> data = Handle<Array>::Cast(ret);
823 Handle<Value> args[] = { data };
824
825 Handle<Function>::Cast(val)->Call(obj, 1, args);
826 }
827
828 if (exception.HasCaught())
829 ReportException(&exception);
830
831 if (ret->IsNativeError())
832 JsException(service+".onchange callback - "+*String::Utf8Value(ret));
833
834 context.Dispose();
835
836 if (ret->IsUndefined() || ret->IsNativeError() || exception.HasCaught())
837 V8::TerminateExecution(fThreadId);
838}
839
840Handle<Value> InterpreterV8::OnChangeSet(Local<String> prop, Local< Value > value, const AccessorInfo &info)
841{
842 const HandleScope handle_scope;
843
844 // Returns the value if the setter intercepts the request. Otherwise, returns an empty handle.
845 const string server = *String::Utf8Value(prop);
846 auto it = fStateCallbacks.find(server);
847
848 if (it!=fStateCallbacks.end())
849 {
850 it->second.Dispose();
851 fStateCallbacks.erase(it);
852 }
853
854 if (value->IsFunction())
855 fStateCallbacks[server] = Persistent<Value>::New(value);
856
857 return Handle<Value>();
858}
859
860
861void InterpreterV8::JsHandleState(const std::string &server, const State &state)
862{
863 if (fThreadId<0)
864 return;
865
866 Locker locker;
867
868 auto it = fStateCallbacks.find(server);
869 if (it==fStateCallbacks.end())
870 {
871 it = fStateCallbacks.find("*");
872 if (it==fStateCallbacks.end())
873 return;
874 }
875
876 const HandleScope handle_scope;
877
878 if (it->second.IsEmpty() || !it->second->IsFunction())
879 return;
880
881 // -------------------------------------------------------------------
882 // We are not in a context... we need to get into one for Array::New
883
884 Persistent<Context> context = Context::New();
885 if (context.IsEmpty())
886 return;
887
888 const Context::Scope scope(context);
889
890 // -------------------------------------------------------------------
891
892 TryCatch exception;
893
894 // It is important to catch the exception thrown
895 // by Date::New in case of thread termination!
896 Local<Value> date = Date::New(state.time.JavaDate());
897
898 if (!exception.HasCaught())
899 {
900 Handle<ObjectTemplate> obj = ObjectTemplate::New();
901 obj->Set(String::New("index"), state.index<=-256?Undefined():Integer::New(state.index), ReadOnly);
902 obj->Set(String::New("name"), state.index<=-256?Undefined():String::New(state.name.c_str()), ReadOnly);
903 obj->Set(String::New("comment"), state.index<=-256?Undefined():String::New(state.comment.c_str()), ReadOnly);
904 obj->Set(String::New("server"), String::New(server.c_str()), ReadOnly);
905 if (state.index>-256)
906 obj->Set(String::New("time"), date);
907
908 Handle<Value> args[] = { obj->NewInstance() };
909
910 Handle<Function> fun = Handle<Function>::Cast(it->second);
911 fun->Call(fun, 1, args);
912 }
913
914 if (exception.HasCaught())
915 ReportException(&exception);
916
917 context.Dispose();
918
919 if (exception.HasCaught())
920 V8::TerminateExecution(fThreadId);
921}
922
923/*
924void Cleanup( Persistent<Value> object, void *parameter )
925{
926 cout << "======================> RemoveMyObj()" << endl;
927}*/
928
929Handle<Value> InterpreterV8::FuncOpen(const Arguments &args)
930{
931 if (args.Length()!=1)
932 return ThrowException(String::New("Number of arguments must be exactly 1."));
933
934 if (!args[0]->IsString())
935 return ThrowException(String::New("Argument 1 must be a string."));
936
937 //if (!args.IsConstructCall())
938 // return ThrowException(String::New("Must be used as constructor."));
939
940 HandleScope handle_scope;
941
942 const String::Utf8Value str(args[0]);
943
944 void *ptr = JsSubscribe(*str);
945 if (ptr==0)
946 return ThrowException(String::New(("Subscription to '"+string(*str)+"' already exists.").c_str()));
947
948 Handle<ObjectTemplate> tem = ObjectTemplate::New();
949 tem->Set(String::New("get"), FunctionTemplate::New(WrapGetData), ReadOnly);
950 tem->Set(String::New("close"), FunctionTemplate::New(WrapClose), ReadOnly);
951 tem->Set(String::New("name"), String::New(*str), ReadOnly);
952 tem->Set(String::New("isOpen"), Boolean::New(true));
953 tem->SetInternalFieldCount(1);
954 //tem->Set(String::New("toString"), String::New(("[object Dim "+string(*str)+"]").c_str()), ReadOnly);
955
956 Handle<Object> obj = tem->NewInstance();
957 obj->SetInternalField(0, External::New(ptr));
958
959 fReverseMap[*str] = Persistent<Object>::New(obj);
960
961 return handle_scope.Close(obj);
962
963 // Persistent<Object> p = Persistent<Object>::New(obj->NewInstance());
964 // obj.MakeWeak((void*)1, Cleanup);
965 // return obj;
966}
967
968bool InterpreterV8::JsRun(const string &filename, const map<string, string> &map)
969{
970 Locker locker;
971 fThreadId = V8::GetCurrentThreadId();
972
973 JsLoad(filename);
974
975 HandleScope handle_scope;
976
977 // Create a template for the global object.
978 Handle<ObjectTemplate> dim = ObjectTemplate::New();
979 dim->Set(String::New("print"), FunctionTemplate::New(WrapPrint), ReadOnly);
980 dim->Set(String::New("alarm"), FunctionTemplate::New(WrapAlarm), ReadOnly);
981 dim->Set(String::New("out"), FunctionTemplate::New(WrapOut), ReadOnly);
982 dim->Set(String::New("wait"), FunctionTemplate::New(WrapWait), ReadOnly);
983 dim->Set(String::New("send"), FunctionTemplate::New(WrapSend), ReadOnly);
984 dim->Set(String::New("state"), FunctionTemplate::New(WrapState), ReadOnly);
985 dim->Set(String::New("sleep"), FunctionTemplate::New(WrapSleep), ReadOnly);
986 dim->Set(String::New("open"), FunctionTemplate::New(WrapOpen), ReadOnly);
987 dim->Set(String::New("database"), FunctionTemplate::New(WrapDatabase), ReadOnly);
988
989 Handle<ObjectTemplate> onchange = ObjectTemplate::New();
990 onchange->SetNamedPropertyHandler(OnChangeGet, WrapOnChangeSet);
991 dim->Set(v8::String::New("onchange"), onchange);
992
993 Handle<ObjectTemplate> global = ObjectTemplate::New();
994 global->Set(String::New("dim"), dim, ReadOnly);
995 global->Set(String::New("include"), FunctionTemplate::New(WrapInclude), ReadOnly);
996 global->Set(String::New("exit"), FunctionTemplate::New(WrapExit), ReadOnly);
997 global->Set(String::New("version"), FunctionTemplate::New(InterpreterV8::FuncVersion), ReadOnly);
998
999 // Persistent
1000 Persistent<Context> context = Context::New(NULL, global);
1001 if (context.IsEmpty())
1002 {
1003 //printf("Error creating context\n");
1004 return false;
1005 }
1006
1007 Context::Scope scope(context);
1008
1009 Handle<Array> args = Array::New(map.size());
1010 for (auto it=map.begin(); it!=map.end(); it++)
1011 args->Set(String::New(it->first.c_str()), String::New(it->second.c_str()));
1012 context->Global()->Set(String::New("$"), args, ReadOnly);
1013 context->Global()->Set(String::New("arg"), args, ReadOnly);
1014
1015 JsStart(filename);
1016
1017 //context->Enter();
1018 Locker::StartPreemption(10);
1019 const bool rc = ExecuteFile(filename);
1020
1021 // -----
1022 // This is how an exit handler could look like, but there is no way to interrupt it
1023 // -----
1024 // Handle<Object> obj = Handle<Object>::Cast(context->Global()->Get(String::New("dim")));
1025 // if (!obj.IsEmpty())
1026 // {
1027 // Handle<Value> onexit = obj->Get(String::New("onexit"));
1028 // if (!onexit->IsUndefined())
1029 // Handle<Function>::Cast(onexit)->NewInstance(0, NULL); // argc, argv
1030 // // Handle<Object> result = Handle<Function>::Cast(onexit)->NewInstance(0, NULL); // argc, argv
1031 // }
1032
1033 Locker::StopPreemption();
1034 //context->Exit();
1035
1036 for (auto it=fStateCallbacks.begin(); it!=fStateCallbacks.end(); it++)
1037 it->second.Dispose();
1038 fStateCallbacks.clear();
1039
1040 for (auto it=fReverseMap.begin(); it!=fReverseMap.end(); it++)
1041 it->second.Dispose();
1042 fReverseMap.clear();
1043
1044 context.Dispose();
1045
1046#ifdef HAVE_SQL
1047 for (auto it=fDatabases.begin(); it!=fDatabases.end(); it++)
1048 delete *it;
1049 fDatabases.clear();
1050#endif
1051
1052 JsEnd(filename);
1053
1054 return rc;
1055}
1056
1057void InterpreterV8::JsStop()
1058{
1059 Locker locker;
1060
1061 //cout << "Terminate " << fThreadId << endl;
1062 if (This->fThreadId>=0)
1063 V8::TerminateExecution(This->fThreadId);
1064 //cout << "Terminate " << fThreadId << endl;
1065
1066 //Unlocker unlocker;
1067}
1068
1069#endif
Note: See TracBrowser for help on using the repository browser.