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