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