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 uint64_t val = *reinterpret_cast<const uint64_t*>(ptr);
|
---|
1161 | ptr += 8;
|
---|
1162 | if (val>UINT32_MAX)
|
---|
1163 | return Number::New(val);
|
---|
1164 | return Integer::NewFromUnsigned(val);
|
---|
1165 | }
|
---|
1166 | case 'S': { Handle<Value> v=Integer::NewFromUnsigned(*reinterpret_cast<const uint16_t*>(ptr)); ptr += 2; return v; }
|
---|
1167 | case 'C': { Handle<Value> v=Integer::NewFromUnsigned((uint16_t)*reinterpret_cast<const uint8_t*>(ptr)); ptr += 1; return v; }
|
---|
1168 | }
|
---|
1169 | return Undefined();
|
---|
1170 | }
|
---|
1171 |
|
---|
1172 | Handle<Value> InterpreterV8::FuncClose(const Arguments &args)
|
---|
1173 | {
|
---|
1174 | HandleScope handle_scope;
|
---|
1175 |
|
---|
1176 | //const void *ptr = Local<External>::Cast(args.Holder()->GetInternalField(0))->Value();
|
---|
1177 |
|
---|
1178 | const String::AsciiValue str(args.This()->Get(String::New("name")));
|
---|
1179 |
|
---|
1180 | const auto it = fReverseMap.find(*str);
|
---|
1181 | if (it!=fReverseMap.end())
|
---|
1182 | {
|
---|
1183 | it->second.Dispose();
|
---|
1184 | fReverseMap.erase(it);
|
---|
1185 | }
|
---|
1186 |
|
---|
1187 | args.This()->Set(String::New("isOpen"), Boolean::New(false), ReadOnly);
|
---|
1188 |
|
---|
1189 | return handle_scope.Close(Boolean::New(JsUnsubscribe(*str)));
|
---|
1190 | }
|
---|
1191 |
|
---|
1192 | Handle<Value> InterpreterV8::ConvertEvent(const EventImp *evt, uint64_t counter, const char *str)
|
---|
1193 | {
|
---|
1194 | const vector<Description> vec = JsDescription(str);
|
---|
1195 |
|
---|
1196 | Handle<Object> ret = fTemplateEvent->GetFunction()->NewInstance();//Object::New();
|
---|
1197 | if (ret.IsEmpty())
|
---|
1198 | return Undefined();
|
---|
1199 |
|
---|
1200 | const Local<Value> date = Date::New(evt->GetJavaDate());
|
---|
1201 | if (date.IsEmpty())
|
---|
1202 | return Undefined();
|
---|
1203 |
|
---|
1204 | ret->Set(String::New("name"), String::New(str), ReadOnly);
|
---|
1205 | ret->Set(String::New("format"), String::New(evt->GetFormat().c_str()), ReadOnly);
|
---|
1206 | ret->Set(String::New("qos"), Integer::New(evt->GetQoS()), ReadOnly);
|
---|
1207 | ret->Set(String::New("size"), Integer::New(evt->GetSize()), ReadOnly);
|
---|
1208 | ret->Set(String::New("counter"), Integer::New(counter), ReadOnly);
|
---|
1209 | if (evt->GetJavaDate()>0)
|
---|
1210 | ret->Set(String::New("time"), date, ReadOnly);
|
---|
1211 |
|
---|
1212 | // If names are available data will also be provided as an
|
---|
1213 | // object. If an empty event was received, but names are available,
|
---|
1214 | // the object will be empty. Otherwise 'obj' will be undefined.
|
---|
1215 | // obj===undefined: no data received
|
---|
1216 | // obj!==undefined, length==0: names for event available
|
---|
1217 | // obj!==undefined, obj.length>0: names available, data received
|
---|
1218 | Handle<Object> named = Object::New();
|
---|
1219 | if (vec.size()>0)
|
---|
1220 | ret->Set(String::New("obj"), named, ReadOnly);
|
---|
1221 |
|
---|
1222 | // If no event was received (usually a disconnection event in
|
---|
1223 | // the context of FACT++), no data is returned
|
---|
1224 | if (evt->IsEmpty())
|
---|
1225 | return ret;
|
---|
1226 |
|
---|
1227 | // If valid data was received, but the size was zero, then
|
---|
1228 | // null is returned as data
|
---|
1229 | // data===undefined: no data received
|
---|
1230 | // data===null: event received, but no data
|
---|
1231 | // data.length>0: event received, contains data
|
---|
1232 | if (evt->GetSize()==0 || evt->GetFormat().empty())
|
---|
1233 | {
|
---|
1234 | ret->Set(String::New("data"), Null(), ReadOnly);
|
---|
1235 | return ret;
|
---|
1236 | }
|
---|
1237 |
|
---|
1238 | typedef boost::char_separator<char> separator;
|
---|
1239 | const boost::tokenizer<separator> tokenizer(evt->GetFormat(), separator(";:"));
|
---|
1240 |
|
---|
1241 | const vector<string> tok(tokenizer.begin(), tokenizer.end());
|
---|
1242 |
|
---|
1243 | Handle<Object> arr = tok.size()>1 ? Array::New() : ret;
|
---|
1244 | if (arr.IsEmpty())
|
---|
1245 | return Undefined();
|
---|
1246 |
|
---|
1247 | const char *ptr = evt->GetText();
|
---|
1248 | const char *end = evt->GetText()+evt->GetSize();
|
---|
1249 |
|
---|
1250 | try
|
---|
1251 | {
|
---|
1252 | size_t pos = 1;
|
---|
1253 | for (auto it=tok.begin(); it<tok.end() && ptr<end; it++, pos++)
|
---|
1254 | {
|
---|
1255 | char type = (*it)[0];
|
---|
1256 | it++;
|
---|
1257 |
|
---|
1258 | string name = pos<vec.size() ? vec[pos].name : "";
|
---|
1259 | if (tok.size()==1)
|
---|
1260 | name = "data";
|
---|
1261 |
|
---|
1262 | // Get element size
|
---|
1263 | uint32_t sz = 1;
|
---|
1264 | switch (type)
|
---|
1265 | {
|
---|
1266 | case 'X':
|
---|
1267 | case 'D': sz = 8; break;
|
---|
1268 | case 'F':
|
---|
1269 | case 'I':
|
---|
1270 | case 'L': sz = 4; break;
|
---|
1271 | case 'S': sz = 2; break;
|
---|
1272 | case 'C': sz = 1; break;
|
---|
1273 | }
|
---|
1274 |
|
---|
1275 | // Check if no number is attached if the size of the
|
---|
1276 | // received data is consistent with the format string
|
---|
1277 | if (it==tok.end() && (end-ptr)%sz>0)
|
---|
1278 | return Exception::Error(String::New(("Number of received bytes ["+to_string(evt->GetSize())+"] does not match format ["+evt->GetFormat()+"]").c_str()));
|
---|
1279 |
|
---|
1280 | // Check if format has a number attached.
|
---|
1281 | // If no number is attached calculate number of elements
|
---|
1282 | const uint32_t cnt = it==tok.end() ? (end-ptr)/sz : stoi(it->c_str());
|
---|
1283 |
|
---|
1284 | // is_str: Array of type C but unknown size (String)
|
---|
1285 | // is_one: Array of known size, but size is 1 (I:1)
|
---|
1286 | const bool is_str = type=='C' && it==tok.end();
|
---|
1287 | const bool is_one = cnt==1 && it!=tok.end();
|
---|
1288 |
|
---|
1289 | Handle<Value> v;
|
---|
1290 |
|
---|
1291 | if (is_str)
|
---|
1292 | v = String::New(ptr);
|
---|
1293 | if (is_one)
|
---|
1294 | v = Convert(type, ptr);
|
---|
1295 |
|
---|
1296 | // Array of known (I:5) or unknown size (I), but no string
|
---|
1297 | if (!is_str && !is_one)
|
---|
1298 | {
|
---|
1299 | Handle<Object> a = Array::New(cnt);
|
---|
1300 | if (a.IsEmpty())
|
---|
1301 | return Undefined();
|
---|
1302 |
|
---|
1303 | for (uint32_t i=0; i<cnt; i++)
|
---|
1304 | a->Set(i, Convert(type, ptr));
|
---|
1305 |
|
---|
1306 | v = a;
|
---|
1307 | }
|
---|
1308 |
|
---|
1309 | if (tok.size()>1)
|
---|
1310 | arr->Set(pos-1, v);
|
---|
1311 | else
|
---|
1312 | ret->Set(String::New("data"), v, ReadOnly);
|
---|
1313 |
|
---|
1314 | if (!name.empty())
|
---|
1315 | {
|
---|
1316 | const Handle<String> n = String::New(name.c_str());
|
---|
1317 | named->Set(n, v);
|
---|
1318 | }
|
---|
1319 | }
|
---|
1320 |
|
---|
1321 | if (tok.size()>1)
|
---|
1322 | ret->Set(String::New("data"), arr, ReadOnly);
|
---|
1323 |
|
---|
1324 | return ret;
|
---|
1325 | }
|
---|
1326 | catch (...)
|
---|
1327 | {
|
---|
1328 | return Exception::Error(String::New(("Format string conversion '"+evt->GetFormat()+"' failed.").c_str()));
|
---|
1329 | }
|
---|
1330 | }
|
---|
1331 | /*
|
---|
1332 | Handle<Value> InterpreterV8::FuncGetData(const Arguments &args)
|
---|
1333 | {
|
---|
1334 | HandleScope handle_scope;
|
---|
1335 |
|
---|
1336 | const String::AsciiValue str(args.Holder()->Get(String::New("name")));
|
---|
1337 |
|
---|
1338 | const pair<uint64_t, EventImp *> p = JsGetEvent(*str);
|
---|
1339 |
|
---|
1340 | const EventImp *evt = p.second;
|
---|
1341 | if (!evt)
|
---|
1342 | return Undefined();
|
---|
1343 |
|
---|
1344 | //if (counter==cnt)
|
---|
1345 | // return info.Holder();//Holder()->Get(String::New("data"));
|
---|
1346 |
|
---|
1347 | Handle<Value> ret = ConvertEvent(evt, p.first, *str);
|
---|
1348 | return ret->IsNativeError() ? ThrowException(ret) : handle_scope.Close(ret);
|
---|
1349 | }
|
---|
1350 | */
|
---|
1351 | Handle<Value> InterpreterV8::FuncGetData(const Arguments &args)
|
---|
1352 | {
|
---|
1353 | if (args.Length()>2)
|
---|
1354 | return ThrowException(String::New("Number of arguments must not be greater than 2."));
|
---|
1355 |
|
---|
1356 | if (args.Length()>=1 && !args[0]->IsInt32() && !args[0]->IsNull())
|
---|
1357 | return ThrowException(String::New("Argument 1 not an uint32."));
|
---|
1358 |
|
---|
1359 | if (args.Length()==2 && !args[1]->IsBoolean())
|
---|
1360 | return ThrowException(String::New("Argument 2 not a boolean."));
|
---|
1361 |
|
---|
1362 | // Using a Javascript function has the advantage that it is fully
|
---|
1363 | // interruptable without the need of C++ code
|
---|
1364 | const bool null = args.Length()>=1 && args[0]->IsNull();
|
---|
1365 | const int32_t timeout = args.Length()>=1 ? args[0]->Int32Value() : 0;
|
---|
1366 | const bool named = args.Length()<2 || args[1]->BooleanValue();
|
---|
1367 |
|
---|
1368 | HandleScope handle_scope;
|
---|
1369 |
|
---|
1370 | const Handle<String> data = String::New("data");
|
---|
1371 | const Handle<String> object = String::New("obj");
|
---|
1372 |
|
---|
1373 | const String::AsciiValue name(args.Holder()->Get(String::New("name")));
|
---|
1374 |
|
---|
1375 | TryCatch exception;
|
---|
1376 |
|
---|
1377 | Time t;
|
---|
1378 | while (!exception.HasCaught())
|
---|
1379 | {
|
---|
1380 | const pair<uint64_t, EventImp *> p = JsGetEvent(*name);
|
---|
1381 |
|
---|
1382 | const EventImp *evt = p.second;
|
---|
1383 | if (evt)
|
---|
1384 | {
|
---|
1385 | const Handle<Value> val = ConvertEvent(evt, p.first, *name);
|
---|
1386 | if (val->IsNativeError())
|
---|
1387 | return ThrowException(val);
|
---|
1388 |
|
---|
1389 | // Protect against the return of an exception
|
---|
1390 | if (val->IsObject())
|
---|
1391 | {
|
---|
1392 | const Handle<Object> event = val->ToObject();
|
---|
1393 | const Handle<Value> obj = event->Get(named?object:data);
|
---|
1394 | if (!obj.IsEmpty())
|
---|
1395 | {
|
---|
1396 | if (!named)
|
---|
1397 | {
|
---|
1398 | // No names (no 'obj'), but 'data'
|
---|
1399 | if (!obj->IsUndefined())
|
---|
1400 | return handle_scope.Close(val);
|
---|
1401 | }
|
---|
1402 | else
|
---|
1403 | {
|
---|
1404 | // Has names and data was received?
|
---|
1405 | if (obj->IsObject() && obj->ToObject()->GetOwnPropertyNames()->Length()>0)
|
---|
1406 | return handle_scope.Close(val);
|
---|
1407 | }
|
---|
1408 | }
|
---|
1409 | }
|
---|
1410 | }
|
---|
1411 |
|
---|
1412 | if (args.Length()==0)
|
---|
1413 | break;
|
---|
1414 |
|
---|
1415 | if (!null && Time()-t>=boost::posix_time::milliseconds(abs(timeout)))
|
---|
1416 | break;
|
---|
1417 |
|
---|
1418 | // Theoretically, the CPU usage can be reduced by maybe a factor
|
---|
1419 | // of four using a larger value, but this also means that the
|
---|
1420 | // JavaScript is locked for a longer time.
|
---|
1421 | const Unlocker unlock;
|
---|
1422 | usleep(1000);
|
---|
1423 | }
|
---|
1424 |
|
---|
1425 | // This hides the location of the exception, which is wanted.
|
---|
1426 | if (exception.HasCaught())
|
---|
1427 | return exception.ReThrow();
|
---|
1428 |
|
---|
1429 | if (timeout<0)
|
---|
1430 | return Undefined();
|
---|
1431 |
|
---|
1432 | const string str = "Waiting for a valid event of "+string(*name)+" timed out.";
|
---|
1433 | return ThrowException(String::New(str.c_str()));
|
---|
1434 | }
|
---|
1435 |
|
---|
1436 |
|
---|
1437 | // This is a callback from the RemoteControl piping event handling
|
---|
1438 | // to the java script ---> in test phase!
|
---|
1439 | void InterpreterV8::JsHandleEvent(const EventImp &evt, uint64_t cnt, const string &service)
|
---|
1440 | {
|
---|
1441 | const Locker locker;
|
---|
1442 |
|
---|
1443 | if (fThreadId<0)
|
---|
1444 | return;
|
---|
1445 |
|
---|
1446 | const auto it = fReverseMap.find(service);
|
---|
1447 | if (it==fReverseMap.end())
|
---|
1448 | return;
|
---|
1449 |
|
---|
1450 | const HandleScope handle_scope;
|
---|
1451 |
|
---|
1452 | Handle<Object> obj = it->second;
|
---|
1453 |
|
---|
1454 | obj->CreationContext()->Enter();
|
---|
1455 |
|
---|
1456 | const Handle<String> onchange = String::New("onchange");
|
---|
1457 | if (!obj->Has(onchange))
|
---|
1458 | return;
|
---|
1459 |
|
---|
1460 | const Handle<Value> val = obj->Get(onchange);
|
---|
1461 | if (!val->IsFunction())
|
---|
1462 | return;
|
---|
1463 |
|
---|
1464 | // -------------------------------------------------------------------
|
---|
1465 |
|
---|
1466 | TryCatch exception;
|
---|
1467 |
|
---|
1468 | const int id = V8::GetCurrentThreadId();
|
---|
1469 | fThreadIds.insert(id);
|
---|
1470 |
|
---|
1471 | Handle<Value> ret = ConvertEvent(&evt, cnt, service.c_str());
|
---|
1472 | if (ret->IsObject())
|
---|
1473 | Handle<Function>::Cast(val)->Call(obj, 1, &ret);
|
---|
1474 |
|
---|
1475 | fThreadIds.erase(id);
|
---|
1476 |
|
---|
1477 | if (!HandleException(exception, "Service.onchange"))
|
---|
1478 | V8::TerminateExecution(fThreadId);
|
---|
1479 |
|
---|
1480 | if (ret->IsNativeError())
|
---|
1481 | {
|
---|
1482 | JsException(service+".onchange callback - "+*String::AsciiValue(ret));
|
---|
1483 | V8::TerminateExecution(fThreadId);
|
---|
1484 | }
|
---|
1485 | }
|
---|
1486 |
|
---|
1487 | Handle<Value> InterpreterV8::OnChangeSet(Local<String> prop, Local<Value> value, const AccessorInfo &)
|
---|
1488 | {
|
---|
1489 | // Returns the value if the setter intercepts the request. Otherwise, returns an empty handle.
|
---|
1490 | const string server = *String::AsciiValue(prop);
|
---|
1491 | auto it = fStateCallbacks.find(server);
|
---|
1492 |
|
---|
1493 | if (it!=fStateCallbacks.end())
|
---|
1494 | {
|
---|
1495 | it->second.Dispose();
|
---|
1496 | fStateCallbacks.erase(it);
|
---|
1497 | }
|
---|
1498 |
|
---|
1499 | if (value->IsFunction())
|
---|
1500 | fStateCallbacks[server] = Persistent<Object>::New(value->ToObject());
|
---|
1501 |
|
---|
1502 | return Handle<Value>();
|
---|
1503 | }
|
---|
1504 |
|
---|
1505 | void InterpreterV8::JsHandleState(const std::string &server, const State &state)
|
---|
1506 | {
|
---|
1507 | const Locker locker;
|
---|
1508 |
|
---|
1509 | if (fThreadId<0)
|
---|
1510 | return;
|
---|
1511 |
|
---|
1512 | auto it = fStateCallbacks.find(server);
|
---|
1513 | if (it==fStateCallbacks.end())
|
---|
1514 | {
|
---|
1515 | it = fStateCallbacks.find("*");
|
---|
1516 | if (it==fStateCallbacks.end())
|
---|
1517 | return;
|
---|
1518 | }
|
---|
1519 |
|
---|
1520 | const HandleScope handle_scope;
|
---|
1521 |
|
---|
1522 | it->second->CreationContext()->Enter();
|
---|
1523 |
|
---|
1524 | // -------------------------------------------------------------------
|
---|
1525 |
|
---|
1526 | Handle<ObjectTemplate> obj = ObjectTemplate::New();
|
---|
1527 | obj->Set(String::New("server"), String::New(server.c_str()), ReadOnly);
|
---|
1528 |
|
---|
1529 | if (state.index>-256)
|
---|
1530 | {
|
---|
1531 | obj->Set(String::New("index"), Integer::New(state.index), ReadOnly);
|
---|
1532 | obj->Set(String::New("name"), String::New(state.name.c_str()), ReadOnly);
|
---|
1533 | obj->Set(String::New("comment"), String::New(state.comment.c_str()), ReadOnly);
|
---|
1534 | const Local<Value> date = Date::New(state.time.JavaDate());
|
---|
1535 | if (!date.IsEmpty())
|
---|
1536 | obj->Set(String::New("time"), date);
|
---|
1537 | }
|
---|
1538 |
|
---|
1539 | // -------------------------------------------------------------------
|
---|
1540 |
|
---|
1541 | TryCatch exception;
|
---|
1542 |
|
---|
1543 | const int id = V8::GetCurrentThreadId();
|
---|
1544 | fThreadIds.insert(id);
|
---|
1545 |
|
---|
1546 | Handle<Value> args[] = { obj->NewInstance() };
|
---|
1547 | Handle<Function> fun = Handle<Function>(Function::Cast(*it->second));
|
---|
1548 | fun->Call(fun, 1, args);
|
---|
1549 |
|
---|
1550 | fThreadIds.erase(id);
|
---|
1551 |
|
---|
1552 | if (!HandleException(exception, "dim.onchange"))
|
---|
1553 | V8::TerminateExecution(fThreadId);
|
---|
1554 | }
|
---|
1555 |
|
---|
1556 | Handle<Value> InterpreterV8::FuncSetInterrupt(const Arguments &args)
|
---|
1557 | {
|
---|
1558 | if (args.Length()!=1)
|
---|
1559 | return ThrowException(String::New("Number of arguments must be 1."));
|
---|
1560 |
|
---|
1561 | if (!args[0]->IsNull() && !args[0]->IsUndefined() && !args[0]->IsFunction())
|
---|
1562 | return ThrowException(String::New("Argument not a function, null or undefined."));
|
---|
1563 |
|
---|
1564 | if (args[0]->IsNull() || args[0]->IsUndefined())
|
---|
1565 | {
|
---|
1566 | fInterruptCallback.Dispose();
|
---|
1567 | return Undefined();
|
---|
1568 | }
|
---|
1569 |
|
---|
1570 | // Returns the value if the setter intercepts the request. Otherwise, returns an empty handle.
|
---|
1571 | fInterruptCallback = Persistent<Object>::New(args[0]->ToObject());
|
---|
1572 | return Undefined();
|
---|
1573 | }
|
---|
1574 |
|
---|
1575 | int InterpreterV8::JsHandleInterrupt(const EventImp &evt)
|
---|
1576 | {
|
---|
1577 | const Locker locker;
|
---|
1578 |
|
---|
1579 | if (fThreadId<0)
|
---|
1580 | return -42;
|
---|
1581 |
|
---|
1582 | if (fInterruptCallback.IsEmpty())
|
---|
1583 | return -42;
|
---|
1584 |
|
---|
1585 | const HandleScope handle_scope;
|
---|
1586 |
|
---|
1587 | fInterruptCallback->CreationContext()->Enter();
|
---|
1588 |
|
---|
1589 | // -------------------------------------------------------------------
|
---|
1590 |
|
---|
1591 | TryCatch exception;
|
---|
1592 |
|
---|
1593 | const string str = evt.GetString();
|
---|
1594 |
|
---|
1595 | const size_t p = str.find_last_of('\n');
|
---|
1596 |
|
---|
1597 | const string irq = p==string::npos?str:str.substr(0, p);
|
---|
1598 | const string usr = p==string::npos?"nobody":str.substr(p+1);
|
---|
1599 |
|
---|
1600 | Local<Value> irq_str = String::New(irq.c_str());
|
---|
1601 | Local<Value> usr_str = String::New(usr.c_str());
|
---|
1602 | Local<Value> date = Date::New(evt.GetJavaDate());
|
---|
1603 |
|
---|
1604 | int32_t rc = -42;
|
---|
1605 | if (!date.IsEmpty())
|
---|
1606 | {
|
---|
1607 | const int id = V8::GetCurrentThreadId();
|
---|
1608 | fThreadIds.insert(id);
|
---|
1609 |
|
---|
1610 | Handle<Value> args[] = { irq_str, date, usr_str };
|
---|
1611 | Handle<Function> fun = Handle<Function>(Function::Cast(*fInterruptCallback));
|
---|
1612 |
|
---|
1613 | const Handle<Value> val = fun->Call(fun, 3, args);
|
---|
1614 |
|
---|
1615 | rc = !val.IsEmpty() && val->IsInt32() ? val->Int32Value() : 0;
|
---|
1616 |
|
---|
1617 | fThreadIds.erase(id);
|
---|
1618 | }
|
---|
1619 |
|
---|
1620 | if (!HandleException(exception, "interrupt"))
|
---|
1621 | V8::TerminateExecution(fThreadId);
|
---|
1622 |
|
---|
1623 | return rc<10 || rc>255 ? -42 : rc;
|
---|
1624 | }
|
---|
1625 |
|
---|
1626 | /*
|
---|
1627 | void Cleanup( Persistent<Value> object, void *parameter )
|
---|
1628 | {
|
---|
1629 | cout << "======================> RemoveMyObj()" << endl;
|
---|
1630 | }*/
|
---|
1631 |
|
---|
1632 | Handle<Value> InterpreterV8::FuncSubscription(const Arguments &args)
|
---|
1633 | {
|
---|
1634 | if (args.Length()!=1 && args.Length()!=2)
|
---|
1635 | return ThrowException(String::New("Number of arguments must be one or two."));
|
---|
1636 |
|
---|
1637 | if (!args[0]->IsString())
|
---|
1638 | return ThrowException(String::New("Argument 1 must be a string."));
|
---|
1639 |
|
---|
1640 | if (args.Length()==2 && !args[1]->IsFunction())
|
---|
1641 | return ThrowException(String::New("Argument 2 must be a function."));
|
---|
1642 |
|
---|
1643 | const String::AsciiValue str(args[0]);
|
---|
1644 |
|
---|
1645 | if (!args.IsConstructCall())
|
---|
1646 | {
|
---|
1647 | const auto it = fReverseMap.find(*str);
|
---|
1648 | if (it!=fReverseMap.end())
|
---|
1649 | return it->second;
|
---|
1650 |
|
---|
1651 | return Undefined();
|
---|
1652 | }
|
---|
1653 |
|
---|
1654 | const HandleScope handle_scope;
|
---|
1655 |
|
---|
1656 | Handle<Object> self = args.This();
|
---|
1657 | self->Set(String::New("get"), FunctionTemplate::New(WrapGetData)->GetFunction(), ReadOnly);
|
---|
1658 | self->Set(String::New("close"), FunctionTemplate::New(WrapClose)->GetFunction(), ReadOnly);
|
---|
1659 | self->Set(String::New("name"), String::New(*str), ReadOnly);
|
---|
1660 | self->Set(String::New("isOpen"), Boolean::New(true));
|
---|
1661 |
|
---|
1662 | if (args.Length()==2)
|
---|
1663 | self->Set(String::New("onchange"), args[1]);
|
---|
1664 |
|
---|
1665 | fReverseMap[*str] = Persistent<Object>::New(self);
|
---|
1666 |
|
---|
1667 | void *ptr = JsSubscribe(*str);
|
---|
1668 | if (ptr==0)
|
---|
1669 | return ThrowException(String::New(("Subscription to '"+string(*str)+"' already exists.").c_str()));
|
---|
1670 |
|
---|
1671 | self->SetInternalField(0, External::New(ptr));
|
---|
1672 |
|
---|
1673 | return Undefined();
|
---|
1674 |
|
---|
1675 | // Persistent<Object> p = Persistent<Object>::New(obj->NewInstance());
|
---|
1676 | // obj.MakeWeak((void*)1, Cleanup);
|
---|
1677 | // return obj;
|
---|
1678 | }
|
---|
1679 |
|
---|
1680 | // ==========================================================================
|
---|
1681 | // Astrometry
|
---|
1682 | // ==========================================================================
|
---|
1683 | #ifdef HAVE_NOVA
|
---|
1684 |
|
---|
1685 | double InterpreterV8::GetDataMember(const Arguments &args, const char *name)
|
---|
1686 | {
|
---|
1687 | return args.This()->Get(String::New(name))->NumberValue();
|
---|
1688 | }
|
---|
1689 |
|
---|
1690 | Handle<Value> InterpreterV8::CalcDist(const Arguments &args, const bool local)
|
---|
1691 | {
|
---|
1692 | if (args.Length()!=2)
|
---|
1693 | return ThrowException(String::New("dist must not be called with two arguments."));
|
---|
1694 |
|
---|
1695 | if (!args[0]->IsObject() || !args[1]->IsObject())
|
---|
1696 | return ThrowException(String::New("at least one argument not an object."));
|
---|
1697 |
|
---|
1698 | HandleScope handle_scope;
|
---|
1699 |
|
---|
1700 | Handle<Object> obj[2] =
|
---|
1701 | {
|
---|
1702 | Handle<Object>::Cast(args[0]),
|
---|
1703 | Handle<Object>::Cast(args[1])
|
---|
1704 | };
|
---|
1705 |
|
---|
1706 | const Handle<String> s_theta = String::New(local?"zd":"dec"); // was: zd
|
---|
1707 | const Handle<String> s_phi = String::New(local?"az":"ra"); // was: az
|
---|
1708 |
|
---|
1709 | const double conv_t = M_PI/180;
|
---|
1710 | const double conv_p = local ? -M_PI/180 : M_PI/12;
|
---|
1711 | const double offset = local ? 0 : M_PI;
|
---|
1712 |
|
---|
1713 | const double theta0 = offset - obj[0]->Get(s_theta)->NumberValue() * conv_t;
|
---|
1714 | const double phi0 = obj[0]->Get(s_phi )->NumberValue() * conv_p;
|
---|
1715 | const double theta1 = offset - obj[1]->Get(s_theta)->NumberValue() * conv_t;
|
---|
1716 | const double phi1 = obj[1]->Get(s_phi )->NumberValue() * conv_p;
|
---|
1717 |
|
---|
1718 | if (!finite(theta0) || !finite(theta1) || !finite(phi0) || !finite(phi1))
|
---|
1719 | return ThrowException(String::New("some values not valid or not finite."));
|
---|
1720 |
|
---|
1721 | /*
|
---|
1722 | const double x0 = sin(zd0) * cos(az0); // az0 -= az0
|
---|
1723 | const double y0 = sin(zd0) * sin(az0); // az0 -= az0
|
---|
1724 | const double z0 = cos(zd0);
|
---|
1725 |
|
---|
1726 | const double x1 = sin(zd1) * cos(az1); // az1 -= az0
|
---|
1727 | const double y1 = sin(zd1) * sin(az1); // az1 -= az0
|
---|
1728 | const double z1 = cos(zd1);
|
---|
1729 |
|
---|
1730 | const double res = acos(x0*x1 + y0*y1 + z0*z1) * 180/M_PI;
|
---|
1731 | */
|
---|
1732 |
|
---|
1733 | // cos(az1-az0) = cos(az1)*cos(az0) + sin(az1)*sin(az0)
|
---|
1734 |
|
---|
1735 | const double x = sin(theta0) * sin(theta1) * cos(phi1-phi0);
|
---|
1736 | const double y = cos(theta0) * cos(theta1);
|
---|
1737 |
|
---|
1738 | const double res = acos(x + y) * 180/M_PI;
|
---|
1739 |
|
---|
1740 | return handle_scope.Close(Number::New(res));
|
---|
1741 | }
|
---|
1742 |
|
---|
1743 | Handle<Value> InterpreterV8::LocalDist(const Arguments &args)
|
---|
1744 | {
|
---|
1745 | return CalcDist(args, true);
|
---|
1746 | }
|
---|
1747 |
|
---|
1748 | Handle<Value> InterpreterV8::SkyDist(const Arguments &args)
|
---|
1749 | {
|
---|
1750 | return CalcDist(args, false);
|
---|
1751 | }
|
---|
1752 |
|
---|
1753 | Handle<Value> InterpreterV8::MoonDisk(const Arguments &args)
|
---|
1754 | {
|
---|
1755 | if (args.Length()>1)
|
---|
1756 | return ThrowException(String::New("disk must not be called with more than one argument."));
|
---|
1757 |
|
---|
1758 | const uint64_t v = uint64_t(args[0]->NumberValue());
|
---|
1759 | const Time utc = args.Length()==0 ? Time() : Time(v/1000, v%1000);
|
---|
1760 |
|
---|
1761 | return Number::New(Nova::GetLunarDisk(utc.JD()));
|
---|
1762 | }
|
---|
1763 |
|
---|
1764 | Handle<Value> InterpreterV8::LocalToSky(const Arguments &args)
|
---|
1765 | {
|
---|
1766 | if (args.Length()>1)
|
---|
1767 | return ThrowException(String::New("toSky must not be called with more than one argument."));
|
---|
1768 |
|
---|
1769 | if (args.Length()==1 && !args[0]->IsDate())
|
---|
1770 | return ThrowException(String::New("Argument must be a Date"));
|
---|
1771 |
|
---|
1772 | Nova::ZdAzPosn hrz;
|
---|
1773 | hrz.zd = GetDataMember(args, "zd");
|
---|
1774 | hrz.az = GetDataMember(args, "az");
|
---|
1775 |
|
---|
1776 | if (!finite(hrz.zd) || !finite(hrz.az))
|
---|
1777 | return ThrowException(String::New("zd and az must be finite."));
|
---|
1778 |
|
---|
1779 | HandleScope handle_scope;
|
---|
1780 |
|
---|
1781 | const Local<Value> date =
|
---|
1782 | args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
|
---|
1783 | if (date.IsEmpty())
|
---|
1784 | return Undefined();
|
---|
1785 |
|
---|
1786 | const uint64_t v = uint64_t(date->NumberValue());
|
---|
1787 | const Time utc(v/1000, v%1000);
|
---|
1788 |
|
---|
1789 | const Nova::EquPosn equ = Nova::GetEquFromHrz(hrz, utc.JD());
|
---|
1790 |
|
---|
1791 | // -----------------------------
|
---|
1792 |
|
---|
1793 | Handle<Value> arg[] = { Number::New(equ.ra/15), Number::New(equ.dec), date };
|
---|
1794 | return handle_scope.Close(fTemplateSky->GetFunction()->NewInstance(3, arg));
|
---|
1795 | }
|
---|
1796 |
|
---|
1797 | Handle<Value> InterpreterV8::SkyToLocal(const Arguments &args)
|
---|
1798 | {
|
---|
1799 | if (args.Length()>1)
|
---|
1800 | return ThrowException(String::New("toLocal must not be called with more than one argument."));
|
---|
1801 |
|
---|
1802 | if (args.Length()==1 && !args[0]->IsDate())
|
---|
1803 | return ThrowException(String::New("Argument must be a Date"));
|
---|
1804 |
|
---|
1805 | Nova::EquPosn equ;
|
---|
1806 | equ.ra = GetDataMember(args, "ra")*15;
|
---|
1807 | equ.dec = GetDataMember(args, "dec");
|
---|
1808 |
|
---|
1809 | if (!finite(equ.ra) || !finite(equ.dec))
|
---|
1810 | return ThrowException(String::New("Ra and dec must be finite."));
|
---|
1811 |
|
---|
1812 | HandleScope handle_scope;
|
---|
1813 |
|
---|
1814 | const Local<Value> date =
|
---|
1815 | args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
|
---|
1816 | if (date.IsEmpty())
|
---|
1817 | return Undefined();
|
---|
1818 |
|
---|
1819 | const uint64_t v = uint64_t(date->NumberValue());
|
---|
1820 | const Time utc(v/1000, v%1000);
|
---|
1821 |
|
---|
1822 | const Nova::ZdAzPosn hrz = Nova::GetHrzFromEqu(equ, utc.JD());
|
---|
1823 |
|
---|
1824 | Handle<Value> arg[] = { Number::New(hrz.zd), Number::New(hrz.az), date };
|
---|
1825 | return handle_scope.Close(fTemplateLocal->GetFunction()->NewInstance(3, arg));
|
---|
1826 | }
|
---|
1827 |
|
---|
1828 | Handle<Value> InterpreterV8::MoonToLocal(const Arguments &args)
|
---|
1829 | {
|
---|
1830 | if (args.Length()>0)
|
---|
1831 | return ThrowException(String::New("toLocal must not be called with arguments."));
|
---|
1832 |
|
---|
1833 | Nova::EquPosn equ;
|
---|
1834 | equ.ra = GetDataMember(args, "ra")*15;
|
---|
1835 | equ.dec = GetDataMember(args, "dec");
|
---|
1836 |
|
---|
1837 | if (!finite(equ.ra) || !finite(equ.dec))
|
---|
1838 | return ThrowException(String::New("ra and dec must be finite."));
|
---|
1839 |
|
---|
1840 | HandleScope handle_scope;
|
---|
1841 |
|
---|
1842 | const Local<Value> date = args.This()->Get(String::New("time"));
|
---|
1843 | if (date.IsEmpty() || date->IsUndefined() )
|
---|
1844 | return Undefined();
|
---|
1845 |
|
---|
1846 | const uint64_t v = uint64_t(date->NumberValue());
|
---|
1847 | const Time utc(v/1000, v%1000);
|
---|
1848 |
|
---|
1849 | const Nova::ZdAzPosn hrz = Nova::GetHrzFromEqu(equ, utc.JD());
|
---|
1850 |
|
---|
1851 | Handle<Value> arg[] = { Number::New(hrz.zd), Number::New(hrz.az), date };
|
---|
1852 | return handle_scope.Close(fTemplateLocal->GetFunction()->NewInstance(3, arg));
|
---|
1853 | }
|
---|
1854 |
|
---|
1855 | Handle<Value> InterpreterV8::ConstructorMoon(const Arguments &args)
|
---|
1856 | {
|
---|
1857 | if (args.Length()>1)
|
---|
1858 | return ThrowException(String::New("Moon constructor must not be called with more than one argument."));
|
---|
1859 |
|
---|
1860 | if (args.Length()==1 && !args[0]->IsDate())
|
---|
1861 | return ThrowException(String::New("Argument must be a Date"));
|
---|
1862 |
|
---|
1863 | HandleScope handle_scope;
|
---|
1864 |
|
---|
1865 | const Local<Value> date =
|
---|
1866 | args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
|
---|
1867 | if (date.IsEmpty())
|
---|
1868 | return Undefined();
|
---|
1869 |
|
---|
1870 | const uint64_t v = uint64_t(date->NumberValue());
|
---|
1871 | const Time utc(v/1000, v%1000);
|
---|
1872 |
|
---|
1873 | const Nova::EquPosn equ = Nova::GetLunarEquCoords(utc.JD(), 0.01);
|
---|
1874 |
|
---|
1875 | // ----------------------------
|
---|
1876 |
|
---|
1877 | if (!args.IsConstructCall())
|
---|
1878 | return handle_scope.Close(Constructor(args));
|
---|
1879 |
|
---|
1880 | Handle<Function> function =
|
---|
1881 | FunctionTemplate::New(MoonToLocal)->GetFunction();
|
---|
1882 | if (function.IsEmpty())
|
---|
1883 | return Undefined();
|
---|
1884 |
|
---|
1885 | Handle<Object> self = args.This();
|
---|
1886 | self->Set(String::New("ra"), Number::New(equ.ra/15), ReadOnly);
|
---|
1887 | self->Set(String::New("dec"), Number::New(equ.dec), ReadOnly);
|
---|
1888 | self->Set(String::New("toLocal"), function, ReadOnly);
|
---|
1889 | self->Set(String::New("time"), date, ReadOnly);
|
---|
1890 |
|
---|
1891 | return handle_scope.Close(self);
|
---|
1892 | }
|
---|
1893 |
|
---|
1894 | Handle<Value> InterpreterV8::ConstructorSky(const Arguments &args)
|
---|
1895 | {
|
---|
1896 | if (args.Length()<2 || args.Length()>3)
|
---|
1897 | return ThrowException(String::New("Sky constructor takes two or three arguments."));
|
---|
1898 |
|
---|
1899 | if (args.Length()==3 && !args[2]->IsDate())
|
---|
1900 | return ThrowException(String::New("Third argument must be a Date."));
|
---|
1901 |
|
---|
1902 | const double ra = args[0]->NumberValue();
|
---|
1903 | const double dec = args[1]->NumberValue();
|
---|
1904 |
|
---|
1905 | if (!finite(ra) || !finite(dec))
|
---|
1906 | return ThrowException(String::New("Both arguments to Sky must be valid numbers."));
|
---|
1907 |
|
---|
1908 | // ----------------------------
|
---|
1909 |
|
---|
1910 | HandleScope handle_scope;
|
---|
1911 |
|
---|
1912 | if (!args.IsConstructCall())
|
---|
1913 | return handle_scope.Close(Constructor(args));
|
---|
1914 |
|
---|
1915 | Handle<Function> function =
|
---|
1916 | FunctionTemplate::New(SkyToLocal)->GetFunction();
|
---|
1917 | if (function.IsEmpty())
|
---|
1918 | return Undefined();
|
---|
1919 |
|
---|
1920 | Handle<Object> self = args.This();
|
---|
1921 | self->Set(String::New("ra"), Number::New(ra), ReadOnly);
|
---|
1922 | self->Set(String::New("dec"), Number::New(dec), ReadOnly);
|
---|
1923 | self->Set(String::New("toLocal"), function, ReadOnly);
|
---|
1924 | if (args.Length()==3)
|
---|
1925 | self->Set(String::New("time"), args[2], ReadOnly);
|
---|
1926 |
|
---|
1927 | return handle_scope.Close(self);
|
---|
1928 | }
|
---|
1929 |
|
---|
1930 | Handle<Value> InterpreterV8::ConstructorLocal(const Arguments &args)
|
---|
1931 | {
|
---|
1932 | if (args.Length()<2 || args.Length()>3)
|
---|
1933 | return ThrowException(String::New("Local constructor takes two or three arguments."));
|
---|
1934 |
|
---|
1935 | if (args.Length()==3 && !args[2]->IsDate())
|
---|
1936 | return ThrowException(String::New("Third argument must be a Date."));
|
---|
1937 |
|
---|
1938 | const double zd = args[0]->NumberValue();
|
---|
1939 | const double az = args[1]->NumberValue();
|
---|
1940 |
|
---|
1941 | if (!finite(zd) || !finite(az))
|
---|
1942 | return ThrowException(String::New("Both arguments to Local must be valid numbers."));
|
---|
1943 |
|
---|
1944 | // --------------------
|
---|
1945 |
|
---|
1946 | HandleScope handle_scope;
|
---|
1947 |
|
---|
1948 | if (!args.IsConstructCall())
|
---|
1949 | return handle_scope.Close(Constructor(args));
|
---|
1950 |
|
---|
1951 | Handle<Function> function =
|
---|
1952 | FunctionTemplate::New(LocalToSky)->GetFunction();
|
---|
1953 | if (function.IsEmpty())
|
---|
1954 | return Undefined();
|
---|
1955 |
|
---|
1956 | Handle<Object> self = args.This();
|
---|
1957 | self->Set(String::New("zd"), Number::New(zd), ReadOnly);
|
---|
1958 | self->Set(String::New("az"), Number::New(az), ReadOnly);
|
---|
1959 | self->Set(String::New("toSky"), function, ReadOnly);
|
---|
1960 | if (args.Length()==3)
|
---|
1961 | self->Set(String::New("time"), args[2], ReadOnly);
|
---|
1962 |
|
---|
1963 | return handle_scope.Close(self);
|
---|
1964 | }
|
---|
1965 |
|
---|
1966 | Handle<Object> InterpreterV8::ConstructRiseSet(const Handle<Value> time, const Nova::RstTime &rst, const bool &rc)
|
---|
1967 | {
|
---|
1968 | Handle<Object> obj = Object::New();
|
---|
1969 | obj->Set(String::New("time"), time, ReadOnly);
|
---|
1970 |
|
---|
1971 | const uint64_t v = uint64_t(time->NumberValue());
|
---|
1972 | const double jd = Time(v/1000, v%1000).JD();
|
---|
1973 |
|
---|
1974 | const bool isUp = rc>0 ||
|
---|
1975 | (rst.rise<rst.set && (jd>rst.rise && jd<rst.set)) ||
|
---|
1976 | (rst.rise>rst.set && (jd<rst.set || jd>rst.rise));
|
---|
1977 |
|
---|
1978 | obj->Set(String::New("isUp"), Boolean::New(rc>=0 && isUp), ReadOnly);
|
---|
1979 |
|
---|
1980 | if (rc!=0)
|
---|
1981 | return obj;
|
---|
1982 |
|
---|
1983 | Handle<Value> rise = Date::New(Time(rst.rise).JavaDate());
|
---|
1984 | Handle<Value> set = Date::New(Time(rst.set).JavaDate());
|
---|
1985 | Handle<Value> trans = Date::New(Time(rst.transit).JavaDate());
|
---|
1986 | if (rise.IsEmpty() || set.IsEmpty() || trans.IsEmpty())
|
---|
1987 | return Handle<Object>();
|
---|
1988 |
|
---|
1989 | obj->Set(String::New("rise"), rise, ReadOnly);
|
---|
1990 | obj->Set(String::New("set"), set, ReadOnly);
|
---|
1991 | obj->Set(String::New("transit"), trans, ReadOnly);
|
---|
1992 |
|
---|
1993 | return obj;
|
---|
1994 | }
|
---|
1995 |
|
---|
1996 | Handle<Value> InterpreterV8::SunHorizon(const Arguments &args)
|
---|
1997 | {
|
---|
1998 | if (args.Length()>2)
|
---|
1999 | return ThrowException(String::New("Sun.horizon must not be called with one or two arguments."));
|
---|
2000 |
|
---|
2001 | if (args.Length()==2 && !args[1]->IsDate())
|
---|
2002 | return ThrowException(String::New("Second argument must be a Date"));
|
---|
2003 |
|
---|
2004 | HandleScope handle_scope;
|
---|
2005 |
|
---|
2006 | double hrz = NAN;
|
---|
2007 | if (args.Length()==0 || args[0]->IsNull())
|
---|
2008 | hrz = LN_SOLAR_STANDART_HORIZON;
|
---|
2009 | if (args.Length()>0 && args[0]->IsNumber())
|
---|
2010 | hrz = args[0]->NumberValue();
|
---|
2011 | if (args.Length()>0 && args[0]->IsString())
|
---|
2012 | {
|
---|
2013 | string arg(Tools::Trim(*String::AsciiValue(args[0])));
|
---|
2014 | transform(arg.begin(), arg.end(), arg.begin(), ::tolower);
|
---|
2015 |
|
---|
2016 | if (arg==string("horizon").substr(0, arg.length()))
|
---|
2017 | hrz = LN_SOLAR_STANDART_HORIZON;
|
---|
2018 | if (arg==string("civil").substr(0, arg.length()))
|
---|
2019 | hrz = LN_SOLAR_CIVIL_HORIZON;
|
---|
2020 | if (arg==string("nautical").substr(0, arg.length()))
|
---|
2021 | hrz = LN_SOLAR_NAUTIC_HORIZON;
|
---|
2022 | if (arg==string("fact").substr(0, arg.length()))
|
---|
2023 | hrz = -13;
|
---|
2024 | if (arg==string("astronomical").substr(0, arg.length()))
|
---|
2025 | hrz = LN_SOLAR_ASTRONOMICAL_HORIZON;
|
---|
2026 | }
|
---|
2027 |
|
---|
2028 | if (!finite(hrz))
|
---|
2029 | return ThrowException(String::New("Second argument did not yield a valid number."));
|
---|
2030 |
|
---|
2031 | const Local<Value> date =
|
---|
2032 | args.Length()<2 ? Date::New(Time().JavaDate()) : args[1];
|
---|
2033 | if (date.IsEmpty())
|
---|
2034 | return Undefined();
|
---|
2035 |
|
---|
2036 | const uint64_t v = uint64_t(date->NumberValue());
|
---|
2037 | const Time utc(v/1000, v%1000);
|
---|
2038 |
|
---|
2039 | Nova::LnLatPosn obs = Nova::ORM();
|
---|
2040 |
|
---|
2041 | ln_rst_time sun;
|
---|
2042 | const int rc = ln_get_solar_rst_horizon(utc.JD()-0.5, &obs, hrz, &sun);
|
---|
2043 | Handle<Object> rst = ConstructRiseSet(date, sun, rc);
|
---|
2044 | rst->Set(String::New("horizon"), Number::New(hrz));
|
---|
2045 | return handle_scope.Close(rst);
|
---|
2046 | };
|
---|
2047 |
|
---|
2048 | Handle<Value> InterpreterV8::MoonHorizon(const Arguments &args)
|
---|
2049 | {
|
---|
2050 | if (args.Length()>1)
|
---|
2051 | return ThrowException(String::New("Moon.horizon must not be called with one argument."));
|
---|
2052 |
|
---|
2053 | if (args.Length()==1 && !args[0]->IsDate())
|
---|
2054 | return ThrowException(String::New("Argument must be a Date"));
|
---|
2055 |
|
---|
2056 | HandleScope handle_scope;
|
---|
2057 |
|
---|
2058 | const Local<Value> date =
|
---|
2059 | args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
|
---|
2060 | if (date.IsEmpty())
|
---|
2061 | return Undefined();
|
---|
2062 |
|
---|
2063 | const uint64_t v = uint64_t(date->NumberValue());
|
---|
2064 | const Time utc(v/1000, v%1000);
|
---|
2065 |
|
---|
2066 | Nova::LnLatPosn obs = Nova::ORM();
|
---|
2067 |
|
---|
2068 | ln_rst_time moon;
|
---|
2069 | const int rc = ln_get_lunar_rst(utc.JD()-0.5, &obs, &moon);
|
---|
2070 | Handle<Object> rst = ConstructRiseSet(date, moon, rc);
|
---|
2071 | return handle_scope.Close(rst);
|
---|
2072 | };
|
---|
2073 | #endif
|
---|
2074 |
|
---|
2075 | // ==========================================================================
|
---|
2076 | // Process control
|
---|
2077 | // ==========================================================================
|
---|
2078 |
|
---|
2079 | bool InterpreterV8::HandleException(TryCatch& try_catch, const char *where)
|
---|
2080 | {
|
---|
2081 | if (!try_catch.HasCaught() || !try_catch.CanContinue())
|
---|
2082 | return true;
|
---|
2083 |
|
---|
2084 | const HandleScope handle_scope;
|
---|
2085 |
|
---|
2086 | Handle<Value> except = try_catch.Exception();
|
---|
2087 | if (except.IsEmpty() || except->IsNull())
|
---|
2088 | return true;
|
---|
2089 |
|
---|
2090 | const String::AsciiValue exception(except);
|
---|
2091 |
|
---|
2092 | const Handle<Message> message = try_catch.Message();
|
---|
2093 | if (message.IsEmpty())
|
---|
2094 | return false;
|
---|
2095 |
|
---|
2096 | ostringstream out;
|
---|
2097 |
|
---|
2098 | if (!message->GetScriptResourceName()->IsUndefined())
|
---|
2099 | {
|
---|
2100 | // Print (filename):(line number): (message).
|
---|
2101 | const String::AsciiValue filename(message->GetScriptResourceName());
|
---|
2102 | if (filename.length()>0)
|
---|
2103 | {
|
---|
2104 | out << *filename;
|
---|
2105 | if (message->GetLineNumber()>0)
|
---|
2106 | out << ": l." << message->GetLineNumber();
|
---|
2107 | if (*exception)
|
---|
2108 | out << ": ";
|
---|
2109 | }
|
---|
2110 | }
|
---|
2111 |
|
---|
2112 | if (*exception)
|
---|
2113 | out << *exception;
|
---|
2114 |
|
---|
2115 | out << " [" << where << "]";
|
---|
2116 |
|
---|
2117 | JsException(out.str());
|
---|
2118 |
|
---|
2119 | // Print line of source code.
|
---|
2120 | const String::AsciiValue sourceline(message->GetSourceLine());
|
---|
2121 | if (*sourceline)
|
---|
2122 | JsException(*sourceline);
|
---|
2123 |
|
---|
2124 | // Print wavy underline (GetUnderline is deprecated).
|
---|
2125 | const int start = message->GetStartColumn();
|
---|
2126 | const int end = message->GetEndColumn();
|
---|
2127 |
|
---|
2128 | out.str("");
|
---|
2129 | if (start>0)
|
---|
2130 | out << setfill(' ') << setw(start) << ' ';
|
---|
2131 | out << setfill('^') << setw(end-start) << '^';
|
---|
2132 |
|
---|
2133 | JsException(out.str());
|
---|
2134 |
|
---|
2135 | const String::AsciiValue stack_trace(try_catch.StackTrace());
|
---|
2136 | if (stack_trace.length()<=0)
|
---|
2137 | return false;
|
---|
2138 |
|
---|
2139 | if (!*stack_trace)
|
---|
2140 | return false;
|
---|
2141 |
|
---|
2142 | const string trace(*stack_trace);
|
---|
2143 |
|
---|
2144 | typedef boost::char_separator<char> separator;
|
---|
2145 | const boost::tokenizer<separator> tokenizer(trace, separator("\n"));
|
---|
2146 |
|
---|
2147 | // maybe skip: " at internal:"
|
---|
2148 | // maybe skip: " at unknown source:"
|
---|
2149 |
|
---|
2150 | auto it = tokenizer.begin();
|
---|
2151 | JsException("");
|
---|
2152 | while (it!=tokenizer.end())
|
---|
2153 | JsException(*it++);
|
---|
2154 |
|
---|
2155 | return false;
|
---|
2156 | }
|
---|
2157 |
|
---|
2158 | Handle<Value> InterpreterV8::ExecuteInternal(const string &code)
|
---|
2159 | {
|
---|
2160 | // Try/catch and re-throw hides our internal code from
|
---|
2161 | // the displayed exception showing the origin and shows
|
---|
2162 | // the user function instead.
|
---|
2163 | TryCatch exception;
|
---|
2164 |
|
---|
2165 | const Handle<Value> result = ExecuteCode(code);
|
---|
2166 |
|
---|
2167 | // This hides the location of the exception in the internal code,
|
---|
2168 | // which is wanted.
|
---|
2169 | if (exception.HasCaught())
|
---|
2170 | exception.ReThrow();
|
---|
2171 |
|
---|
2172 | return result;
|
---|
2173 | }
|
---|
2174 |
|
---|
2175 | Handle<Value> InterpreterV8::ExecuteCode(const string &code, const string &file)
|
---|
2176 | {
|
---|
2177 | HandleScope handle_scope;
|
---|
2178 |
|
---|
2179 | const Handle<String> source = String::New(code.c_str(), code.size());
|
---|
2180 | const Handle<String> origin = String::New(file.c_str());
|
---|
2181 | if (source.IsEmpty())
|
---|
2182 | return Undefined();
|
---|
2183 |
|
---|
2184 | const Handle<Script> script = Script::Compile(source, origin);
|
---|
2185 | if (script.IsEmpty())
|
---|
2186 | return Undefined();
|
---|
2187 |
|
---|
2188 | const Handle<String> __date__ = String::New("__DATE__");
|
---|
2189 | const Handle<String> __file__ = String::New("__FILE__");
|
---|
2190 |
|
---|
2191 | Handle<Value> save_date;
|
---|
2192 | Handle<Value> save_file;
|
---|
2193 |
|
---|
2194 | Handle<Object> global = Context::GetCurrent()->Global();
|
---|
2195 | if (!global.IsEmpty())
|
---|
2196 | {
|
---|
2197 | struct stat attrib;
|
---|
2198 | if (stat(file.c_str(), &attrib)==0)
|
---|
2199 | {
|
---|
2200 | save_date = global->Get(__date__);
|
---|
2201 | save_file = global->Get(__file__);
|
---|
2202 |
|
---|
2203 | global->Set(__file__, String::New(file.c_str()));
|
---|
2204 |
|
---|
2205 | const Local<Value> date = Date::New(attrib.st_mtime*1000);
|
---|
2206 | if (!date.IsEmpty())
|
---|
2207 | global->Set(__date__, date);
|
---|
2208 | }
|
---|
2209 | }
|
---|
2210 |
|
---|
2211 | const Handle<Value> rc = script->Run();
|
---|
2212 | if (rc.IsEmpty())
|
---|
2213 | return Undefined();
|
---|
2214 |
|
---|
2215 | // If all went well and the result wasn't undefined then print
|
---|
2216 | // the returned value.
|
---|
2217 | if (!rc->IsUndefined() && file!="internal")
|
---|
2218 | JsResult(*String::AsciiValue(rc));
|
---|
2219 |
|
---|
2220 | if (!global.IsEmpty() && !save_date.IsEmpty())
|
---|
2221 | {
|
---|
2222 | global->ForceSet(__date__, save_date);
|
---|
2223 | global->ForceSet(__file__, save_file);
|
---|
2224 | }
|
---|
2225 |
|
---|
2226 | return handle_scope.Close(rc);
|
---|
2227 | }
|
---|
2228 |
|
---|
2229 | void InterpreterV8::ExecuteConsole()
|
---|
2230 | {
|
---|
2231 | JsSetState(3);
|
---|
2232 |
|
---|
2233 | WindowLog lout;
|
---|
2234 | lout << "\n " << kUnderline << " JavaScript interpreter " << kReset << " (enter '.q' to quit)\n" << endl;
|
---|
2235 |
|
---|
2236 | Readline::StaticPushHistory("java.his");
|
---|
2237 |
|
---|
2238 | string command;
|
---|
2239 | while (1)
|
---|
2240 | {
|
---|
2241 | // Create a local handle scope so that left-overs from single
|
---|
2242 | // console inputs will not fill up the memory
|
---|
2243 | const HandleScope handle_scope;
|
---|
2244 |
|
---|
2245 | // Unlocking is necessary for the preemption to work
|
---|
2246 | const Unlocker global_unlock;
|
---|
2247 |
|
---|
2248 | const string buffer = Tools::Trim(Readline::StaticPrompt(command.empty() ? "JS> " : " \\> "));
|
---|
2249 | if (buffer==".q")
|
---|
2250 | break;
|
---|
2251 |
|
---|
2252 | // buffer empty, do nothing
|
---|
2253 | if (buffer.empty())
|
---|
2254 | continue;
|
---|
2255 |
|
---|
2256 | // Compose command
|
---|
2257 | if (!command.empty())
|
---|
2258 | command += ' ';
|
---|
2259 | command += buffer;
|
---|
2260 |
|
---|
2261 | // If line ends with a backslash, allow addition of next line
|
---|
2262 | auto back = command.rbegin();
|
---|
2263 | if (*back=='\\')
|
---|
2264 | {
|
---|
2265 | *back = ' ';
|
---|
2266 | command = Tools::Trim(command);
|
---|
2267 | continue;
|
---|
2268 | }
|
---|
2269 |
|
---|
2270 | // Locking is necessary to be able to execute java script code
|
---|
2271 | const Locker lock;
|
---|
2272 |
|
---|
2273 | // Catch exceptions during code compilation
|
---|
2274 | TryCatch exception;
|
---|
2275 |
|
---|
2276 | // Execute code which was entered
|
---|
2277 | ExecuteCode(command, "console");
|
---|
2278 | if (!HandleException(exception, "console"))
|
---|
2279 | lout << endl;
|
---|
2280 |
|
---|
2281 | // Stop all other threads
|
---|
2282 | for (auto it=fThreadIds.begin(); it!=fThreadIds.end(); it++)
|
---|
2283 | V8::TerminateExecution(*it);
|
---|
2284 |
|
---|
2285 | // Allow the java scripts (threads) to run and hence to terminate
|
---|
2286 | const Unlocker unlock;
|
---|
2287 |
|
---|
2288 | // Wait until all threads are terminated
|
---|
2289 | while (!fThreadIds.empty())
|
---|
2290 | usleep(1000);
|
---|
2291 |
|
---|
2292 | // command has been executed, collect new command
|
---|
2293 | command = "";
|
---|
2294 | }
|
---|
2295 |
|
---|
2296 | lout << endl;
|
---|
2297 |
|
---|
2298 | Readline::StaticPopHistory("java.his");
|
---|
2299 | }
|
---|
2300 |
|
---|
2301 | // ==========================================================================
|
---|
2302 | // CORE
|
---|
2303 | // ==========================================================================
|
---|
2304 |
|
---|
2305 | InterpreterV8::InterpreterV8() : fThreadId(-1)
|
---|
2306 | {
|
---|
2307 | const string ver(V8::GetVersion());
|
---|
2308 |
|
---|
2309 | typedef boost::char_separator<char> separator;
|
---|
2310 | const boost::tokenizer<separator> tokenizer(ver, separator("."));
|
---|
2311 |
|
---|
2312 | const vector<string> tok(tokenizer.begin(), tokenizer.end());
|
---|
2313 |
|
---|
2314 | const int major = tok.size()>0 ? stol(tok[0]) : -1;
|
---|
2315 | const int minor = tok.size()>1 ? stol(tok[1]) : -1;
|
---|
2316 | const int build = tok.size()>2 ? stol(tok[2]) : -1;
|
---|
2317 |
|
---|
2318 | if (major>3 || (major==3 && minor>9) || (major==3 && minor==9 && build>10))
|
---|
2319 | {
|
---|
2320 | const string argv = "--use_strict";
|
---|
2321 | V8::SetFlagsFromString(argv.c_str(), argv.size());
|
---|
2322 | }
|
---|
2323 |
|
---|
2324 | This = this;
|
---|
2325 | }
|
---|
2326 |
|
---|
2327 | Handle<Value> InterpreterV8::Constructor(/*Handle<FunctionTemplate> T,*/ const Arguments &args)
|
---|
2328 | {
|
---|
2329 | Handle<Value> argv[args.Length()];
|
---|
2330 |
|
---|
2331 | for (int i=0; i<args.Length(); i++)
|
---|
2332 | argv[i] = args[i];
|
---|
2333 |
|
---|
2334 | return args.Callee()->NewInstance(args.Length(), argv);
|
---|
2335 | }
|
---|
2336 |
|
---|
2337 |
|
---|
2338 | void InterpreterV8::AddFormatToGlobal()// const
|
---|
2339 | {
|
---|
2340 | const string code =
|
---|
2341 | "String.form = function(str, arr)"
|
---|
2342 | "{"
|
---|
2343 | "var i = -1;"
|
---|
2344 | "function callback(exp, p0, p1, p2, p3, p4/*, pos, str*/)"
|
---|
2345 | "{"
|
---|
2346 | "if (exp=='%%')"
|
---|
2347 | "return '%';"
|
---|
2348 | ""
|
---|
2349 | "if (arr[++i]===undefined)"
|
---|
2350 | "return undefined;"
|
---|
2351 | ""
|
---|
2352 | "var exp = p2 ? parseInt(p2.substr(1)) : undefined;"
|
---|
2353 | "var base = p3 ? parseInt(p3.substr(1)) : undefined;"
|
---|
2354 | ""
|
---|
2355 | "var val;"
|
---|
2356 | "switch (p4)"
|
---|
2357 | "{"
|
---|
2358 | "case 's': val = arr[i]; break;"
|
---|
2359 | "case 'c': val = arr[i][0]; break;"
|
---|
2360 | "case 'f': val = parseFloat(arr[i]).toFixed(exp); break;"
|
---|
2361 | "case 'p': val = parseFloat(arr[i]).toPrecision(exp); break;"
|
---|
2362 | "case 'e': val = parseFloat(arr[i]).toExponential(exp); break;"
|
---|
2363 | "case 'x': val = parseInt(arr[i]).toString(base?base:16); break;"
|
---|
2364 | "case 'd': val = parseFloat(parseInt(arr[i], base?base:10).toPrecision(exp)).toFixed(0); break;"
|
---|
2365 | //"default:\n"
|
---|
2366 | //" throw new SyntaxError('Conversion specifier '+p4+' unknown.');\n"
|
---|
2367 | "}"
|
---|
2368 | ""
|
---|
2369 | "val = typeof(val)=='object' ? JSON.stringify(val) : val.toString(base);"
|
---|
2370 | ""
|
---|
2371 | "var sz = parseInt(p1); /* padding size */"
|
---|
2372 | "var ch = p1 && p1[0]=='0' ? '0' : ' '; /* isnull? */"
|
---|
2373 | "while (val.length<sz)"
|
---|
2374 | "val = p0 !== undefined ? val+ch : ch+val; /* isminus? */"
|
---|
2375 | ""
|
---|
2376 | "return val;"
|
---|
2377 | "}"
|
---|
2378 | ""
|
---|
2379 | "var regex = /%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd])/g;"
|
---|
2380 | "return str.replace(regex, callback);"
|
---|
2381 | "}"
|
---|
2382 | "\n"
|
---|
2383 | "String.prototype.$ = function()"
|
---|
2384 | "{"
|
---|
2385 | "return String.form(this, Array.prototype.slice.call(arguments));"
|
---|
2386 | "}"
|
---|
2387 | "\n"
|
---|
2388 | "String.prototype.count = function(c,i)"
|
---|
2389 | "{"
|
---|
2390 | "return (this.match(new RegExp(c,i?'gi':'g'))||[]).length;"
|
---|
2391 | "}"/*
|
---|
2392 | "\n"
|
---|
2393 | "var format = function()"
|
---|
2394 | "{"
|
---|
2395 | "return dim.format(arguments[0], Array.prototype.slice.call(arguments,1));"
|
---|
2396 | "}"*/;
|
---|
2397 |
|
---|
2398 | // ExcuteInternal does not work properly here...
|
---|
2399 | // If suring compilation an exception is thrown, it will not work
|
---|
2400 | Handle<Script> script = Script::New(String::New(code.c_str()), String::New("internal"));
|
---|
2401 | if (!script.IsEmpty())
|
---|
2402 | script->Run();
|
---|
2403 | }
|
---|
2404 |
|
---|
2405 | void InterpreterV8::JsLoad(const std::string &)
|
---|
2406 | {
|
---|
2407 | Readline::SetScriptDepth(1);
|
---|
2408 | }
|
---|
2409 |
|
---|
2410 | void InterpreterV8::JsEnd(const std::string &)
|
---|
2411 | {
|
---|
2412 | Readline::SetScriptDepth(0);
|
---|
2413 | }
|
---|
2414 |
|
---|
2415 | bool InterpreterV8::JsRun(const string &filename, const map<string, string> &map)
|
---|
2416 | {
|
---|
2417 | const Locker locker;
|
---|
2418 | fThreadId = V8::GetCurrentThreadId();
|
---|
2419 |
|
---|
2420 | JsPrint(string("JavaScript Engine V8 ")+V8::GetVersion());
|
---|
2421 |
|
---|
2422 | JsLoad(filename);
|
---|
2423 |
|
---|
2424 | const HandleScope handle_scope;
|
---|
2425 |
|
---|
2426 | // Create a template for the global object.
|
---|
2427 | Handle<ObjectTemplate> dim = ObjectTemplate::New();
|
---|
2428 | dim->Set(String::New("log"), FunctionTemplate::New(WrapLog), ReadOnly);
|
---|
2429 | dim->Set(String::New("alarm"), FunctionTemplate::New(WrapAlarm), ReadOnly);
|
---|
2430 | dim->Set(String::New("wait"), FunctionTemplate::New(WrapWait), ReadOnly);
|
---|
2431 | dim->Set(String::New("send"), FunctionTemplate::New(WrapSend), ReadOnly);
|
---|
2432 | dim->Set(String::New("state"), FunctionTemplate::New(WrapState), ReadOnly);
|
---|
2433 | dim->Set(String::New("version"), Integer::New(DIM_VERSION_NUMBER), ReadOnly);
|
---|
2434 | dim->Set(String::New("getStates"), FunctionTemplate::New(WrapGetStates), ReadOnly);
|
---|
2435 | dim->Set(String::New("getDescription"), FunctionTemplate::New(WrapGetDescription), ReadOnly);
|
---|
2436 | dim->Set(String::New("getServices"), FunctionTemplate::New(WrapGetServices), ReadOnly);
|
---|
2437 |
|
---|
2438 | Handle<ObjectTemplate> dimctrl = ObjectTemplate::New();
|
---|
2439 | dimctrl->Set(String::New("defineState"), FunctionTemplate::New(WrapNewState), ReadOnly);
|
---|
2440 | dimctrl->Set(String::New("setState"), FunctionTemplate::New(WrapSetState), ReadOnly);
|
---|
2441 | dimctrl->Set(String::New("getState"), FunctionTemplate::New(WrapGetState), ReadOnly);
|
---|
2442 | dimctrl->Set(String::New("setInterruptHandler"), FunctionTemplate::New(WrapSetInterrupt), ReadOnly);
|
---|
2443 |
|
---|
2444 | Handle<ObjectTemplate> v8 = ObjectTemplate::New();
|
---|
2445 | v8->Set(String::New("sleep"), FunctionTemplate::New(WrapSleep), ReadOnly);
|
---|
2446 | v8->Set(String::New("timeout"), FunctionTemplate::New(WrapTimeout), ReadOnly);
|
---|
2447 | v8->Set(String::New("version"), String::New(V8::GetVersion()), ReadOnly);
|
---|
2448 |
|
---|
2449 | Handle<ObjectTemplate> console = ObjectTemplate::New();
|
---|
2450 | console->Set(String::New("out"), FunctionTemplate::New(WrapOut), ReadOnly);
|
---|
2451 | console->Set(String::New("warn"), FunctionTemplate::New(WrapWarn), ReadOnly);
|
---|
2452 |
|
---|
2453 | Handle<ObjectTemplate> onchange = ObjectTemplate::New();
|
---|
2454 | onchange->SetNamedPropertyHandler(OnChangeGet, WrapOnChangeSet);
|
---|
2455 | dim->Set(String::New("onchange"), onchange);
|
---|
2456 |
|
---|
2457 | Handle<ObjectTemplate> global = ObjectTemplate::New();
|
---|
2458 | global->Set(String::New("v8"), v8, ReadOnly);
|
---|
2459 | global->Set(String::New("dim"), dim, ReadOnly);
|
---|
2460 | global->Set(String::New("dimctrl"), dimctrl, ReadOnly);
|
---|
2461 | global->Set(String::New("console"), console, ReadOnly);
|
---|
2462 | global->Set(String::New("include"), FunctionTemplate::New(WrapInclude), ReadOnly);
|
---|
2463 | global->Set(String::New("exit"), FunctionTemplate::New(WrapExit), ReadOnly);
|
---|
2464 |
|
---|
2465 | Handle<FunctionTemplate> sub = FunctionTemplate::New(WrapSubscription);
|
---|
2466 | sub->SetClassName(String::New("Subscription"));
|
---|
2467 | sub->InstanceTemplate()->SetInternalFieldCount(1);
|
---|
2468 | global->Set(String::New("Subscription"), sub, ReadOnly);
|
---|
2469 |
|
---|
2470 | #ifdef HAVE_SQL
|
---|
2471 | Handle<FunctionTemplate> db = FunctionTemplate::New(WrapDatabase);
|
---|
2472 | db->SetClassName(String::New("Database"));
|
---|
2473 | db->InstanceTemplate()->SetInternalFieldCount(1);
|
---|
2474 | global->Set(String::New("Database"), db, ReadOnly);
|
---|
2475 | #endif
|
---|
2476 |
|
---|
2477 | Handle<FunctionTemplate> thread = FunctionTemplate::New(WrapThread);
|
---|
2478 | thread->SetClassName(String::New("Thread"));
|
---|
2479 | global->Set(String::New("Thread"), thread, ReadOnly);
|
---|
2480 |
|
---|
2481 | Handle<FunctionTemplate> file = FunctionTemplate::New(WrapFile);
|
---|
2482 | file->SetClassName(String::New("File"));
|
---|
2483 | global->Set(String::New("File"), file, ReadOnly);
|
---|
2484 |
|
---|
2485 | Handle<FunctionTemplate> evt = FunctionTemplate::New();
|
---|
2486 | evt->SetClassName(String::New("Event"));
|
---|
2487 | global->Set(String::New("Event"), evt, ReadOnly);
|
---|
2488 |
|
---|
2489 | Handle<FunctionTemplate> desc = FunctionTemplate::New();
|
---|
2490 | desc->SetClassName(String::New("Description"));
|
---|
2491 | global->Set(String::New("Description"), desc, ReadOnly);
|
---|
2492 |
|
---|
2493 | fTemplateEvent = evt;
|
---|
2494 | fTemplateDescription = desc;
|
---|
2495 |
|
---|
2496 | #ifdef HAVE_MAILX
|
---|
2497 | Handle<FunctionTemplate> mail = FunctionTemplate::New(ConstructorMail);
|
---|
2498 | mail->SetClassName(String::New("Mail"));
|
---|
2499 | global->Set(String::New("Mail"), mail, ReadOnly);
|
---|
2500 | #endif
|
---|
2501 |
|
---|
2502 | #ifdef HAVE_NOVA
|
---|
2503 | Handle<FunctionTemplate> sky = FunctionTemplate::New(ConstructorSky);
|
---|
2504 | sky->SetClassName(String::New("Sky"));
|
---|
2505 | sky->Set(String::New("dist"), FunctionTemplate::New(SkyDist), ReadOnly);
|
---|
2506 | global->Set(String::New("Sky"), sky, ReadOnly);
|
---|
2507 |
|
---|
2508 | Handle<FunctionTemplate> loc = FunctionTemplate::New(ConstructorLocal);
|
---|
2509 | loc->SetClassName(String::New("Local"));
|
---|
2510 | loc->Set(String::New("dist"), FunctionTemplate::New(LocalDist), ReadOnly);
|
---|
2511 | global->Set(String::New("Local"), loc, ReadOnly);
|
---|
2512 |
|
---|
2513 | Handle<FunctionTemplate> moon = FunctionTemplate::New(ConstructorMoon);
|
---|
2514 | moon->SetClassName(String::New("Moon"));
|
---|
2515 | moon->Set(String::New("disk"), FunctionTemplate::New(MoonDisk), ReadOnly);
|
---|
2516 | moon->Set(String::New("horizon"), FunctionTemplate::New(MoonHorizon), ReadOnly);
|
---|
2517 | global->Set(String::New("Moon"), moon, ReadOnly);
|
---|
2518 |
|
---|
2519 | Handle<FunctionTemplate> sun = FunctionTemplate::New();
|
---|
2520 | sun->SetClassName(String::New("Sun"));
|
---|
2521 | sun->Set(String::New("horizon"), FunctionTemplate::New(SunHorizon), ReadOnly);
|
---|
2522 | global->Set(String::New("Sun"), sun, ReadOnly);
|
---|
2523 |
|
---|
2524 | fTemplateLocal = loc;
|
---|
2525 | fTemplateSky = sky;
|
---|
2526 | #endif
|
---|
2527 |
|
---|
2528 | // Persistent
|
---|
2529 | Persistent<Context> context = Context::New(NULL, global);
|
---|
2530 | if (context.IsEmpty())
|
---|
2531 | {
|
---|
2532 | JsException("Creation of global context failed...");
|
---|
2533 | JsEnd(filename);
|
---|
2534 | return false;
|
---|
2535 | }
|
---|
2536 |
|
---|
2537 | // Switch off eval(). It is not possible to track it's exceptions.
|
---|
2538 | context->AllowCodeGenerationFromStrings(false);
|
---|
2539 |
|
---|
2540 | Context::Scope scope(context);
|
---|
2541 |
|
---|
2542 | Handle<Array> args = Array::New(map.size());
|
---|
2543 | for (auto it=map.begin(); it!=map.end(); it++)
|
---|
2544 | args->Set(String::New(it->first.c_str()), String::New(it->second.c_str()));
|
---|
2545 | context->Global()->Set(String::New("$"), args, ReadOnly);
|
---|
2546 | context->Global()->Set(String::New("arg"), args, ReadOnly);
|
---|
2547 |
|
---|
2548 | const Local<Value> starttime = Date::New(Time().JavaDate());
|
---|
2549 | if (!starttime.IsEmpty())
|
---|
2550 | context->Global()->Set(String::New("__START__"), starttime, ReadOnly);
|
---|
2551 |
|
---|
2552 | //V8::ResumeProfiler();
|
---|
2553 |
|
---|
2554 | TryCatch exception;
|
---|
2555 |
|
---|
2556 | AddFormatToGlobal();
|
---|
2557 |
|
---|
2558 | if (!exception.HasCaught())
|
---|
2559 | {
|
---|
2560 | JsStart(filename);
|
---|
2561 |
|
---|
2562 | Locker::StartPreemption(10);
|
---|
2563 |
|
---|
2564 | if (filename.empty())
|
---|
2565 | ExecuteConsole();
|
---|
2566 | else
|
---|
2567 | {
|
---|
2568 | // We call script->Run because it is the only way to
|
---|
2569 | // catch exceptions.
|
---|
2570 | const Handle<String> source = String::New(("include('"+filename+"');").c_str());
|
---|
2571 | const Handle<String> origin = String::New("main");
|
---|
2572 | const Handle<Script> script = Script::Compile(source, origin);
|
---|
2573 | if (!script.IsEmpty())
|
---|
2574 | {
|
---|
2575 | JsSetState(3);
|
---|
2576 | script->Run();
|
---|
2577 | }
|
---|
2578 | }
|
---|
2579 |
|
---|
2580 | Locker::StopPreemption();
|
---|
2581 |
|
---|
2582 | // Stop all other threads
|
---|
2583 | for (auto it=fThreadIds.begin(); it!=fThreadIds.end(); it++)
|
---|
2584 | V8::TerminateExecution(*it);
|
---|
2585 | fThreadIds.clear();
|
---|
2586 | }
|
---|
2587 |
|
---|
2588 | // Handle an exception
|
---|
2589 | /*const bool rc =*/ HandleException(exception, "main");
|
---|
2590 |
|
---|
2591 | // IsProfilerPaused()
|
---|
2592 | // V8::PauseProfiler();
|
---|
2593 |
|
---|
2594 | // -----
|
---|
2595 | // This is how an exit handler could look like, but there is no way to interrupt it
|
---|
2596 | // -----
|
---|
2597 | // Handle<Object> obj = Handle<Object>::Cast(context->Global()->Get(String::New("dim")));
|
---|
2598 | // if (!obj.IsEmpty())
|
---|
2599 | // {
|
---|
2600 | // Handle<Value> onexit = obj->Get(String::New("onexit"));
|
---|
2601 | // if (!onexit->IsUndefined())
|
---|
2602 | // Handle<Function>::Cast(onexit)->NewInstance(0, NULL); // argc, argv
|
---|
2603 | // // Handle<Object> result = Handle<Function>::Cast(onexit)->NewInstance(0, NULL); // argc, argv
|
---|
2604 | // }
|
---|
2605 |
|
---|
2606 | //context->Exit();
|
---|
2607 |
|
---|
2608 | // The threads are started already and wait to get the lock
|
---|
2609 | // So we have to unlock (manual preemtion) so that they get
|
---|
2610 | // the signal to terminate.
|
---|
2611 | {
|
---|
2612 | const Unlocker unlock;
|
---|
2613 |
|
---|
2614 | for (auto it=fThreads.begin(); it!=fThreads.end(); it++)
|
---|
2615 | it->join();
|
---|
2616 | fThreads.clear();
|
---|
2617 | }
|
---|
2618 |
|
---|
2619 | // Now we can dispose all persistent handles from state callbacks
|
---|
2620 | for (auto it=fStateCallbacks.begin(); it!=fStateCallbacks.end(); it++)
|
---|
2621 | it->second.Dispose();
|
---|
2622 | fStateCallbacks.clear();
|
---|
2623 |
|
---|
2624 | // Now we can dispose the persistent interrupt handler
|
---|
2625 | fInterruptCallback.Dispose();
|
---|
2626 |
|
---|
2627 | // Now we can dispose all persistent handles from reverse maps
|
---|
2628 | for (auto it=fReverseMap.begin(); it!=fReverseMap.end(); it++)
|
---|
2629 | it->second.Dispose();
|
---|
2630 | fReverseMap.clear();
|
---|
2631 |
|
---|
2632 | #ifdef HAVE_SQL
|
---|
2633 | // ...and close all database handles
|
---|
2634 | for (auto it=fDatabases.begin(); it!=fDatabases.end(); it++)
|
---|
2635 | delete *it;
|
---|
2636 | fDatabases.clear();
|
---|
2637 | #endif
|
---|
2638 |
|
---|
2639 | fStates.clear();
|
---|
2640 |
|
---|
2641 | context.Dispose();
|
---|
2642 |
|
---|
2643 | JsEnd(filename);
|
---|
2644 |
|
---|
2645 | return true;
|
---|
2646 | }
|
---|
2647 |
|
---|
2648 | void InterpreterV8::JsStop()
|
---|
2649 | {
|
---|
2650 | Locker locker;
|
---|
2651 | V8::TerminateExecution(This->fThreadId);
|
---|
2652 | }
|
---|
2653 |
|
---|
2654 | #endif
|
---|
2655 |
|
---|
2656 | InterpreterV8 *InterpreterV8::This = 0;
|
---|