-
Notifications
You must be signed in to change notification settings - Fork 4
/
julia_api.cpp
94 lines (76 loc) · 2.09 KB
/
julia_api.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <sstream>
#include <QDebug>
#include <QString>
#include <QVariant>
#include <QVariantList>
#include "julia_api.hpp"
#include "jlqml.hpp"
namespace qmlwrap
{
void JuliaAPI::setJuliaSignals(JuliaSignals* julia_signals)
{
m_julia_signals = julia_signals;
}
void JuliaAPI::set_js_engine(QJSEngine* e)
{
m_engine = e;
if(m_engine != nullptr)
{
for(JuliaFunction* f : m_registered_functions)
{
register_function_internal(f);
}
m_registered_functions.clear();
}
}
void JuliaAPI::register_function(const QString& name, jl_function_t* f)
{
JuliaFunction* jf = new JuliaFunction(name, f, this);
if(m_engine == nullptr)
{
m_registered_functions.push_back(jf);
}
else
{
register_function_internal(jf);
}
}
JuliaAPI::~JuliaAPI()
{
}
void JuliaAPI::register_function_internal(JuliaFunction* jf)
{
if(m_engine == nullptr)
{
throw std::runtime_error("No JS engine, can't register function");
}
QJSValue f = m_engine->evaluate("(function() { return this." + jf->name() + ".julia_function.call(arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments)); })");
if(f.isError() || !f.isCallable())
{
throw std::runtime_error(("Error setting function" + jf->name()).toStdString());
}
f.setProperty("julia_function", m_engine->newQObject(jf));
(*this)[jf->name()] = f.toVariant(QJSValue::RetainJSObjects);
}
JuliaAPI* JuliaSingleton::create(QQmlEngine* qmlEngine, QJSEngine* scriptEngine)
{
Q_ASSERT(s_singletonInstance);
Q_ASSERT(scriptEngine->thread() == s_singletonInstance->thread());
if (s_engine != nullptr)
{
if(s_engine != scriptEngine)
{
throw std::runtime_error("Only one scriptEngine may access the singleton");
}
}
s_engine = scriptEngine;
QObject::connect(s_engine, &QObject::destroyed, [&]()
{
s_engine = nullptr;
});
s_singletonInstance->set_js_engine(qmlEngine);
QJSEngine::setObjectOwnership(s_singletonInstance, QJSEngine::CppOwnership);
QQmlEngine::setObjectOwnership(s_singletonInstance, QQmlEngine::CppOwnership);
return s_singletonInstance;
}
} // namespace qmlwrap