Subversion Repositories HomeAutomation

Rev

Rev 1656 | 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
 
1647 runge 101
Value Manager::Export_Log(const v8::Arguments& args)
102
{
103
    v8::Context::Scope context_scope(Manager::Instance()->GetContext());
104
 
105
    //LOG.Debug(std::string(__FUNCTION__) + " called!");
106
 
107
    if (args.Length() < 1)
108
    {
109
        Manager::instance_->LOG.Error(std::string(__FUNCTION__) + ": To few arguments to log.");
110
        return v8::Undefined();
111
    }
112
 
113
    v8::String::AsciiValue str(args[0]);
114
 
115
    Manager::instance_->CallOutput(*str);
116
 
117
    return v8::Undefined();
118
}
119
 
1608 runge 120
void Manager::Call(std::string plugin_name, unsigned int request_id, std::string name, ArgumentListPointer arguments)
1601 runge 121
{
1608 runge 122
    this->io_service_.post(boost::bind(&Manager::CallHandler, this, plugin_name, request_id, name, arguments));
1601 runge 123
}
124
 
1608 runge 125
void Manager::Execute(std::string plugin_name, unsigned int request_id, std::string code)
1601 runge 126
{
1608 runge 127
    this->io_service_.post(boost::bind(&Manager::ExecuteHandler, this, plugin_name, request_id, code));
128
}
129
 
1647 runge 130
bool Manager::CallHandler(std::string plugin_name, unsigned int request_id, std::string name, ArgumentListPointer arguments)
1608 runge 131
{
1601 runge 132
    v8::Context::Scope context_scope(this->context_);
133
    v8::TryCatch try_catch;
134
 
1647 runge 135
    this->current_plugin_name_ = plugin_name;
136
    this->current_request_id_ = request_id;
137
 
1601 runge 138
    if (this->functions_.find(name) == this->functions_.end())
139
    {
1647 runge 140
        this->CallOutput("No such function found, " + name);
141
 
142
        this->current_plugin_name_ = "";
143
        this->current_request_id_ = 0;
144
        return false;
1601 runge 145
    }
1604 runge 146
 
1642 runge 147
    //LOG.Debug("Call: " + name);
1625 runge 148
 
1601 runge 149
    Value result = this->functions_[name]->Call(this->context_->Global(), arguments->size(), arguments->data());
150
 
151
    if (result.IsEmpty())
152
    {
1647 runge 153
        this->CallOutput(this->FormatException(try_catch));
154
 
155
        this->current_plugin_name_ = "";
156
        this->current_request_id_ = 0;
157
        return false;
1601 runge 158
    }
1608 runge 159
 
1647 runge 160
    //v8::String::AsciiValue response(result->ToString());
161
    //this->CallOutput(plugin_name, request_id, std::string(*response));
1608 runge 162
 
1647 runge 163
    this->current_plugin_name_ = "";
164
    this->current_request_id_ = 0;
165
    return true;
1601 runge 166
}
167
 
168
void Manager::StartHandler()
169
{
170
    v8::Handle<v8::ObjectTemplate> raw_template = v8::ObjectTemplate::New();
171
 
1647 runge 172
    raw_template->Set(v8::String::New("Log"), v8::FunctionTemplate::New(Manager::Export_Log));
173
 
1603 runge 174
    for (unsigned int c = 0; c < this->plugins_.size(); c++)
1601 runge 175
    {
1603 runge 176
        ExportFunctionList export_functions = this->plugins_[c]->GetExportFunctions();
1601 runge 177
 
178
        for (ExportFunctionList::iterator it = export_functions.begin(); it != export_functions.end(); it++)
179
        {
180
            raw_template->Set(v8::String::New(it->first.data()), v8::FunctionTemplate::New(it->second));
181
        }
182
    }
183
 
184
    this->context_ = v8::Context::New(NULL, raw_template);
185
 
186
    v8::Context::Scope context_scope(this->context_);
187
 
1603 runge 188
    for (unsigned int c = 0; c < this->plugins_.size(); c++)
1601 runge 189
    {
1608 runge 190
        this->LoadScript("plugin/" + this->plugins_[c]->GetName() + ".js");
1601 runge 191
    }
192
 
193
    this->object_template_ = v8::Persistent<v8::ObjectTemplate>::New(raw_template);
194
 
1603 runge 195
    for (unsigned int c = 0; c < this->plugins_.size(); c++)
1601 runge 196
    {
1603 runge 197
        this->plugins_[c]->InitializeDone();
1601 runge 198
    }
199
}
200
 
1608 runge 201
bool Manager::ImportFunction(std::string functionname)
1601 runge 202
{
1608 runge 203
    v8::Context::Scope context_scope(this->context_);
204
 
205
    v8::TryCatch try_catch;
206
 
207
    v8::Handle<v8::String> process_name = v8::String::New(functionname.data());
208
    v8::Handle<v8::Value> process_val = this->context_->Global()->Get(process_name);
209
 
210
    if (!process_val->IsFunction())
211
    {
212
        LOG.Error(functionname + " was not found to be a function!");
213
        return false;
214
    }
215
 
216
    v8::Handle<v8::Function> process_fun = v8::Handle<v8::Function>::Cast(process_val);
217
 
218
    this->functions_[functionname] = v8::Persistent<v8::Function>::New(process_fun);
219
 
220
    return true;
221
}
222
 
223
bool Manager::LoadScript(std::string scriptname)
224
{
1644 runge 225
    for (unsigned int n = 0; n < this->loaded_scripts_.size(); n++)
226
    {
227
        if (this->loaded_scripts_[n] == scriptname)
228
        {
1657 runge 229
            LOG.Debug(scriptname + " is already loaded.");
1644 runge 230
            return true;
231
        }
232
    }
233
 
1656 runge 234
    std::string path = this->user_script_path_ + scriptname;
1601 runge 235
    std::ifstream file(path.data());
236
 
237
    if (!file.is_open())
238
    {
1656 runge 239
        path = this->script_path_ + scriptname;
240
        file.open(path.data());
241
 
242
        if (!file.is_open())
243
        {
244
            file.close();
245
            LOG.Warning("Could not load " + scriptname + ".");
246
            return false;
247
        }
1601 runge 248
    }
249
 
250
    std::string code = "";
251
    std::string line;
252
 
253
    while (!file.eof())
254
    {
255
        std::getline(file, line);
256
 
257
        if (file.eof())
258
        {
259
            break;
260
        }
261
 
262
        code += line + "\n";
263
    }
264
 
1602 runge 265
    code += "\n";
266
 
1601 runge 267
    file.close();
268
 
269
    v8::Context::Scope context_scope(this->context_);
270
 
271
    v8::TryCatch try_catch;
272
 
273
    v8::Handle<v8::Script> script = v8::Script::Compile(v8::String::New(code.data(), code.length()),
274
                                                        v8::String::New(scriptname.data(), scriptname.length()));
275
 
276
    if (script.IsEmpty())
277
    {
278
        LOG.Error(this->FormatException(try_catch));
1608 runge 279
        return false;
1601 runge 280
    }
281
    else
282
    {
283
        Value result = script->Run();
284
 
285
        if (result.IsEmpty())
286
        {
287
            LOG.Error(this->FormatException(try_catch));
1608 runge 288
            return false;
1601 runge 289
        }
290
    }
291
 
1644 runge 292
    this->loaded_scripts_.push_back(scriptname);
293
 
1657 runge 294
    LOG.Info("\033[32mLoaded " + scriptname + " successfully.\033[0m");
1601 runge 295
    return true;
296
}
297
 
1608 runge 298
void Manager::ExecuteHandler(std::string plugin_name, unsigned int request_id, std::string code)
299
{
300
    std::string scriptname = "execute_" + plugin_name + ".js";
301
 
302
    v8::Context::Scope context_scope(this->context_);
303
 
304
    v8::TryCatch try_catch;
305
 
306
    v8::Handle<v8::Script> script = v8::Script::Compile(v8::String::New(code.data(), code.length()),
307
                                                        v8::String::New(scriptname.data(), scriptname.length()));
308
 
1647 runge 309
    this->current_plugin_name_ = plugin_name;
310
    this->current_request_id_ = request_id;
311
 
1608 runge 312
    if (script.IsEmpty())
313
    {
1647 runge 314
        this->CallOutput(this->FormatException(try_catch));
1608 runge 315
    }
316
    else
317
    {
318
        Value result = script->Run();
319
 
320
        if (result.IsEmpty())
321
        {
1647 runge 322
            this->CallOutput(this->FormatException(try_catch));
1608 runge 323
        }
324
        else
325
        {
1647 runge 326
            //v8::String::AsciiValue response(result->ToString());
327
            //this->CallOutput(std::string(*response));
1608 runge 328
        }
329
    }
1647 runge 330
 
331
    this->current_plugin_name_ = "";
332
    this->current_request_id_ = 0;
1608 runge 333
}
334
 
1601 runge 335
std::string Manager::FormatException(v8::TryCatch& try_catch)
336
{
1625 runge 337
    v8::Context::Scope context_scope(this->context_);
338
 
1601 runge 339
    std::string result;
340
 
341
    v8::HandleScope handle_scope;
342
    v8::String::Utf8Value exception(try_catch.Exception());
343
    v8::Handle<v8::Message> message = try_catch.Message();
344
 
345
    if (message.IsEmpty())
346
    {
347
        result = *exception;
348
    }
349
    else
350
    {
351
        v8::String::Utf8Value filename(message->GetScriptResourceName());
352
 
353
        result = std::string(*filename) + ":" + boost::lexical_cast<std::string>(message->GetLineNumber()) + ": " + std::string(*exception);
354
 
355
        /*v8::String::Utf8Value sourceline(message->GetSourceLine());
356
        string strSourceline = *sourceline;
357
 
358
        result += strSourceline + "\n";
359
 
360
        string underline = rpad("", message->GetStartColumn(), ' ');
361
        underline = rpad(underline, message->GetEndColumn(), '^');
362
 
363
        result += underline + "\n";*/
364
    }
365
 
366
    return result;
367
}
368
 
369
}; // namespace vm
370
}; // namespace atom