4c75f9e
/*
4c75f9e
    Copyright (c) 2017, Lukas Holecek <hluk@email.cz>
4c75f9e
4c75f9e
    This file is part of CopyQ.
4c75f9e
4c75f9e
    CopyQ is free software: you can redistribute it and/or modify
4c75f9e
    it under the terms of the GNU General Public License as published by
4c75f9e
    the Free Software Foundation, either version 3 of the License, or
4c75f9e
    (at your option) any later version.
4c75f9e
4c75f9e
    CopyQ is distributed in the hope that it will be useful,
4c75f9e
    but WITHOUT ANY WARRANTY; without even the implied warranty of
4c75f9e
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
4c75f9e
    GNU General Public License for more details.
4c75f9e
4c75f9e
    You should have received a copy of the GNU General Public License
4c75f9e
    along with CopyQ.  If not, see <http://www.gnu.org/licenses/>.
4c75f9e
*/
4c75f9e
4c75f9e
#include "scriptableclass.h"
4c75f9e
4c75f9e
#include <QScriptContext>
4c75f9e
4c75f9e
Q_DECLARE_METATYPE(ScriptableClassBase*)
4c75f9e
4c75f9e
namespace {
4c75f9e
4c75f9e
QScriptValue construct(QScriptContext *context, QScriptEngine *)
4c75f9e
{
4c75f9e
    ScriptableClassBase *cls = qscriptvalue_cast<ScriptableClassBase*>(context->callee().data());
4c75f9e
    return cls ? cls->createInstance(*context) : QScriptValue();
4c75f9e
}
4c75f9e
4c75f9e
} // namespace
4c75f9e
4c75f9e
ScriptableClassBase::ScriptableClassBase(QScriptEngine *engine)
4c75f9e
    : QObject(engine)
4c75f9e
    , QScriptClass(engine)
4c75f9e
{
4c75f9e
}
4c75f9e
4c75f9e
QScriptValue ScriptableClassBase::constructor()
4c75f9e
{
4c75f9e
    return ctor;
4c75f9e
}
4c75f9e
4c75f9e
QScriptValue ScriptableClassBase::prototype() const
4c75f9e
{
4c75f9e
    return proto;
4c75f9e
}
4c75f9e
4c75f9e
QScriptValue ScriptableClassBase::newInstance(QObject *instance)
4c75f9e
{
4c75f9e
    instance->setParent(engine());
4c75f9e
    QScriptValue data = engine()->newQObject(instance, QScriptEngine::ScriptOwnership);
4c75f9e
    return engine()->newObject(this, data);
4c75f9e
}
4c75f9e
4c75f9e
void ScriptableClassBase::init(QObject *prototype)
4c75f9e
{
4c75f9e
    proto = engine()->newQObject(
4c75f9e
                prototype,
4c75f9e
                QScriptEngine::QtOwnership,
4c75f9e
                QScriptEngine::SkipMethodsInEnumeration);
4c75f9e
    QScriptValue global = engine()->globalObject();
4c75f9e
    proto.setPrototype(global.property("Object").property("prototype"));
4c75f9e
4c75f9e
    ctor = engine()->newFunction(construct, proto);
4c75f9e
    ctor.setData(engine()->toScriptValue(this));
4c75f9e
}
4c75f9e
4c75f9e
QScriptValue ScriptableClassBase::toScriptValue(QScriptEngine *eng, QObject * const &instance)
4c75f9e
{
4c75f9e
    return eng->newQObject(instance, QScriptEngine::QtOwnership, QScriptEngine::PreferExistingWrapperObject);
4c75f9e
}