Subversion Repositories HomeAutomation

Rev

Rev 1741 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | SVN | RSS feed

Rev Author Line No. Line
1601 runge 1
/*
2
 *
3
 *  Copyright (C) 2010  Mattias Runge
4
 *
5
 *  This program is free software; you can redistribute it and/or modify
6
 *  it under the terms of the GNU General Public License as published by
7
 *  the Free Software Foundation; either version 2 of the License, or
8
 *  (at your option) any later version.
9
 *
10
 *  This program is distributed in the hope that it will be useful,
11
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 *  GNU General Public License for more details.
14
 *
15
 *  You should have received a copy of the GNU General Public License along
16
 *  with this program; if not, write to the Free Software Foundation, Inc.,
17
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18
 *
19
 */
20
 
21
#include "Manager.h"
22
 
23
#include <fstream>
24
 
25
#include <boost/lexical_cast.hpp>
26
#include <boost/bind.hpp>
27
 
28
namespace atom {
29
namespace vm {
30
 
31
Manager::Pointer Manager::instance_;
32
 
33
Manager::Manager() : LOG("vm::Manager")
34
{
35
}
36
 
37
Manager::~Manager()
38
{
39
    this->io_service_.stop();
40
 
41
    this->plugins_.clear();
42
    this->context_.Dispose();
43
 
44
    for (ImportFunctionList::iterator it = this->functions_.begin(); it != this->functions_.end(); it++)
45
    {
46
        it->second.Dispose();
47
    }
48
}
49
 
50
void Manager::Create()
51
{
52
    Manager::instance_ = Manager::Pointer(new Manager());
53
}
54
 
55
Manager::Pointer Manager::Instance()
56
{
57
    return Manager::instance_;
58
}
59
 
60
void Manager::Delete()
61
{
62
    Manager::instance_.reset();
63
}
64
 
1619 runge 65
v8::Persistent<v8::Context>& Manager::GetContext()
66
{
67
    return this->context_;
68
}
69
 
1601 runge 70
void Manager::AddPlugin(Plugin::Pointer plugin)
71
{
1603 runge 72
    this->plugins_.push_back(plugin);
1601 runge 73
}
74
 
1656 runge 75
void Manager::Start(std::string script_path, std::string user_script_path)
1601 runge 76
{
77
    this->script_path_ = script_path;
1656 runge 78
    this->user_script_path_ = user_script_path;
1601 runge 79
    this->io_service_.post(boost::bind(&Manager::StartHandler, this));
80
}
81
 
1647 runge 82
void Manager::CallOutput(std::string output)
1601 runge 83
{
1647 runge 84
    if (this->current_plugin_name_ != "")
1608 runge 85
    {
1647 runge 86
        for (unsigned int n = 0; n < this->plugins_.size(); n++)
1608 runge 87
        {
1647 runge 88
            if (this->plugins_[n]->GetName() == this->current_plugin_name_)
89
            {
90
                this->plugins_[n]->CallOutput(this->current_request_id_, output);
91
                return;
92
            }
1608 runge 93
        }
94
    }
1647 runge 95
    else
96
    {
97
        LOG.Info(output);
98
    }
1601 runge 99
}
100
 
2107 runge 101
void Manager::CallResult(std::string output)
102
{
103
  if (this->current_plugin_name_ != "")
104
  {
105
    for (unsigned int n = 0; n < this->plugins_.size(); n++)
106
    {
107
      if (this->plugins_[n]->GetName() == this->current_plugin_name_)
108
      {
109
        this->plugins_[n]->CallResult(this->current_request_id_, output);
110
        return;
111
      }
112
    }
113
  }
114
  else
115
  {
116
    LOG.Info(output);
117
  }
118
}
119
 
1647 runge 120
Value Manager::Export_Log(const v8::Arguments& args)
121
{
1740 runge 122
    v8::Locker lock;
1647 runge 123
    v8::Context::Scope context_scope(Manager::Instance()->GetContext());
1741 runge 124
    v8::HandleScope handle_scope;
125
 
1647 runge 126
    //LOG.Debug(std::string(__FUNCTION__) + " called!");
127
 
128
    if (args.Length() < 1)
129
    {
130
        Manager::instance_->LOG.Error(std::string(__FUNCTION__) + ": To few arguments to log.");
131
        return v8::Undefined();
132
    }
133
 
134
    v8::String::AsciiValue str(args[0]);
135
 
136
    Manager::instance_->CallOutput(*str);
137
 
1741 runge 138
    return handle_scope.Close(v8::Undefined());
1647 runge 139
}
140
 
1608 runge 141
void Manager::Call(std::string plugin_name, unsigned int request_id, std::string name, ArgumentListPointer arguments)
1601 runge 142
{
1608 runge 143
    this->io_service_.post(boost::bind(&Manager::CallHandler, this, plugin_name, request_id, name, arguments));
1601 runge 144
}
145
 
1608 runge 146
void Manager::Execute(std::string plugin_name, unsigned int request_id, std::string code)
1601 runge 147
{
1608 runge 148
    this->io_service_.post(boost::bind(&Manager::ExecuteHandler, this, plugin_name, request_id, code));
149
}
150
 
1647 runge 151
bool Manager::CallHandler(std::string plugin_name, unsigned int request_id, std::string name, ArgumentListPointer arguments)
1608 runge 152
{
1740 runge 153
    v8::Locker lock;
1601 runge 154
    v8::Context::Scope context_scope(this->context_);
155
    v8::TryCatch try_catch;
156
 
1647 runge 157
    this->current_plugin_name_ = plugin_name;
158
    this->current_request_id_ = request_id;
159
 
1601 runge 160
    if (this->functions_.find(name) == this->functions_.end())
161
    {
1647 runge 162
        this->CallOutput("No such function found, " + name);
163
 
164
        this->current_plugin_name_ = "";
165
        this->current_request_id_ = 0;
166
        return false;
1601 runge 167
    }
1604 runge 168
 
1642 runge 169
    //LOG.Debug("Call: " + name);
1625 runge 170
 
1601 runge 171
    Value result = this->functions_[name]->Call(this->context_->Global(), arguments->size(), arguments->data());
172
 
173
    if (result.IsEmpty())
174
    {
1647 runge 175
        this->CallOutput(this->FormatException(try_catch));
176
 
177
        this->current_plugin_name_ = "";
178
        this->current_request_id_ = 0;
179
        return false;
1601 runge 180
    }
1608 runge 181
 
1647 runge 182
    //v8::String::AsciiValue response(result->ToString());
183
    //this->CallOutput(plugin_name, request_id, std::string(*response));
1608 runge 184
 
1647 runge 185
    this->current_plugin_name_ = "";
186
    this->current_request_id_ = 0;
187
    return true;
1601 runge 188
}
189
 
190
void Manager::StartHandler()
191
{
1741 runge 192
    v8::Locker lock;
193
    v8::HandleScope handle_scope;
1601 runge 194
    v8::Handle<v8::ObjectTemplate> raw_template = v8::ObjectTemplate::New();
195
 
1647 runge 196
    raw_template->Set(v8::String::New("Log"), v8::FunctionTemplate::New(Manager::Export_Log));
197
 
1603 runge 198
    for (unsigned int c = 0; c < this->plugins_.size(); c++)
1601 runge 199
    {
1603 runge 200
        ExportFunctionList export_functions = this->plugins_[c]->GetExportFunctions();
1601 runge 201
 
202
        for (ExportFunctionList::iterator it = export_functions.begin(); it != export_functions.end(); it++)
203
        {
204
            raw_template->Set(v8::String::New(it->first.data()), v8::FunctionTemplate::New(it->second));
205
        }
206
    }
207
 
208
    this->context_ = v8::Context::New(NULL, raw_template);
209
 
1741 runge 210
 
1601 runge 211
    v8::Context::Scope context_scope(this->context_);
212
 
1603 runge 213
    for (unsigned int c = 0; c < this->plugins_.size(); c++)
1601 runge 214
    {
1608 runge 215
        this->LoadScript("plugin/" + this->plugins_[c]->GetName() + ".js");
1601 runge 216
    }
217
 
218
    this->object_template_ = v8::Persistent<v8::ObjectTemplate>::New(raw_template);
219
 
1603 runge 220
    for (unsigned int c = 0; c < this->plugins_.size(); c++)
1601 runge 221
    {
1603 runge 222
        this->plugins_[c]->InitializeDone();
1601 runge 223
    }
224
}
225
 
1608 runge 226
bool Manager::ImportFunction(std::string functionname)
1601 runge 227
{
1740 runge 228
    v8::Locker lock;
1608 runge 229
    v8::Context::Scope context_scope(this->context_);
230
 
231
    v8::TryCatch try_catch;
232
 
233
    v8::Handle<v8::String> process_name = v8::String::New(functionname.data());
234
    v8::Handle<v8::Value> process_val = this->context_->Global()->Get(process_name);
235
 
236
    if (!process_val->IsFunction())
237
    {
238
        LOG.Error(functionname + " was not found to be a function!");
239
        return false;
240
    }
241
 
242
    v8::Handle<v8::Function> process_fun = v8::Handle<v8::Function>::Cast(process_val);
243
 
244
    this->functions_[functionname] = v8::Persistent<v8::Function>::New(process_fun);
245
 
246
    return true;
247
}
248
 
249
bool Manager::LoadScript(std::string scriptname)
250
{
1644 runge 251
    for (unsigned int n = 0; n < this->loaded_scripts_.size(); n++)
252
    {
253
        if (this->loaded_scripts_[n] == scriptname)
254
        {
1657 runge 255
            LOG.Debug(scriptname + " is already loaded.");
1644 runge 256
            return true;
257
        }
258
    }
259
 
1656 runge 260
    std::string path = this->user_script_path_ + scriptname;
1601 runge 261
    std::ifstream file(path.data());
262
 
263
    if (!file.is_open())
264
    {
1656 runge 265
        path = this->script_path_ + scriptname;
266
        file.open(path.data());
267
 
268
        if (!file.is_open())
269
        {
270
            file.close();
271
            LOG.Warning("Could not load " + scriptname + ".");
272
            return false;
273
        }
1601 runge 274
    }
275
 
276
    std::string code = "";
277
    std::string line;
278
 
279
    while (!file.eof())
280
    {
281
        std::getline(file, line);
282
 
283
        if (file.eof())
284
        {
285
            break;
286
        }
287
 
288
        code += line + "\n";
289
    }
290
 
1602 runge 291
    code += "\n";
292
 
1601 runge 293
    file.close();
294
 
1740 runge 295
    v8::Locker lock;
1601 runge 296
    v8::Context::Scope context_scope(this->context_);
297
 
298
    v8::TryCatch try_catch;
299
 
300
    v8::Handle<v8::Script> script = v8::Script::Compile(v8::String::New(code.data(), code.length()),
301
                                                        v8::String::New(scriptname.data(), scriptname.length()));
302
 
303
    if (script.IsEmpty())
304
    {
305
        LOG.Error(this->FormatException(try_catch));
1608 runge 306
        return false;
1601 runge 307
    }
308
    else
309
    {
310
        Value result = script->Run();
311
 
312
        if (result.IsEmpty())
313
        {
314
            LOG.Error(this->FormatException(try_catch));
1608 runge 315
            return false;
1601 runge 316
        }
317
    }
318
 
1644 runge 319
    this->loaded_scripts_.push_back(scriptname);
320
 
1657 runge 321
    LOG.Info("\033[32mLoaded " + scriptname + " successfully.\033[0m");
1601 runge 322
    return true;
323
}
324
 
1608 runge 325
void Manager::ExecuteHandler(std::string plugin_name, unsigned int request_id, std::string code)
326
{
327
    std::string scriptname = "execute_" + plugin_name + ".js";
328
 
1740 runge 329
    v8::Locker lock;
1608 runge 330
    v8::Context::Scope context_scope(this->context_);
331
 
332
    v8::TryCatch try_catch;
333
 
334
    v8::Handle<v8::Script> script = v8::Script::Compile(v8::String::New(code.data(), code.length()),
335
                                                        v8::String::New(scriptname.data(), scriptname.length()));
336
 
1647 runge 337
    this->current_plugin_name_ = plugin_name;
338
    this->current_request_id_ = request_id;
339
 
1608 runge 340
    if (script.IsEmpty())
341
    {
1647 runge 342
        this->CallOutput(this->FormatException(try_catch));
1608 runge 343
    }
344
    else
345
    {
346
        Value result = script->Run();
347
 
348
        if (result.IsEmpty())
349
        {
1647 runge 350
            this->CallOutput(this->FormatException(try_catch));
1608 runge 351
        }
352
        else
353
        {
2107 runge 354
            v8::String::AsciiValue response(result->ToString());
355
            this->CallResult(std::string(*response));
1608 runge 356
        }
357
    }
1647 runge 358
 
359
    this->current_plugin_name_ = "";
360
    this->current_request_id_ = 0;
1608 runge 361
}
362
 
1601 runge 363
std::string Manager::FormatException(v8::TryCatch& try_catch)
364
{
1740 runge 365
    v8::Locker lock;
1625 runge 366
    v8::Context::Scope context_scope(this->context_);
367
 
1601 runge 368
    std::string result;
369
 
370
    v8::HandleScope handle_scope;
371
    v8::String::Utf8Value exception(try_catch.Exception());
372
    v8::Handle<v8::Message> message = try_catch.Message();
373
 
374
    if (message.IsEmpty())
375
    {
376
        result = *exception;
377
    }
378
    else
379
    {
380
        v8::String::Utf8Value filename(message->GetScriptResourceName());
381
 
382
        result = std::string(*filename) + ":" + boost::lexical_cast<std::string>(message->GetLineNumber()) + ": " + std::string(*exception);
383
 
384
        /*v8::String::Utf8Value sourceline(message->GetSourceLine());
385
        string strSourceline = *sourceline;
386
 
387
        result += strSourceline + "\n";
388
 
389
        string underline = rpad("", message->GetStartColumn(), ' ');
390
        underline = rpad(underline, message->GetEndColumn(), '^');
391
 
392
        result += underline + "\n";*/
393
    }
394
 
395
    return result;
396
}
397
 
398
}; // namespace vm
399
}; // namespace atom