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