diff --git a/src/cpp.cpp b/src/cpp.cpp index bca595b..cf4f8c1 100644 --- a/src/cpp.cpp +++ b/src/cpp.cpp @@ -1,937 +1,991 @@ /* * Copyright 2017 Jos van den Oever * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License or (at your option) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "structs.h" #include "cpp.h" #include "helper.h" #include template QString cppSetType(const T& p) { if (p.optional) { return "option_" + p.type.cppSetType; } return p.type.cppSetType; } QString upperInitial(const QString& name) { return name.left(1).toUpper() + name.mid(1); } QString lowerInitial(const QString& name) { return name.left(1).toLower() + name.mid(1); } QString writeProperty(const QString& name) { return "WRITE set" + upperInitial(name) + " "; } QString baseType(const Object& o) { if (o.type != ObjectType::Object) { return "QAbstractItemModel"; } return "QObject"; } QString cGetType(const BindingTypeProperties& type) { return type.name + "*, " + type.name.toLower() + "_set"; } bool modelIsWritable(const Object& o) { bool write = false; for (auto ip: o.itemProperties) { write |= ip.write; } return write; } void writeHeaderItemModel(QTextStream& h, const Object& o) { h << QString(R"( int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; QModelIndex parent(const QModelIndex &index) const override; bool hasChildren(const QModelIndex &parent = QModelIndex()) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; bool canFetchMore(const QModelIndex &parent) const override; void fetchMore(const QModelIndex &parent) override; Qt::ItemFlags flags(const QModelIndex &index) const override; void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override; QHash roleNames() const override; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role = Qt::EditRole) override; Q_INVOKABLE bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; Q_INVOKABLE bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; )"); if (modelIsWritable(o)) { h << " bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;\n"; } for (auto ip: o.itemProperties) { if (o.type == ObjectType::List) { h << QString(" Q_INVOKABLE QVariant %1(int row) const;\n").arg(ip.name); if (ip.write) { h << QString(" Q_INVOKABLE bool set%1(int row, const QVariant& value);\n").arg(upperInitial(ip.name)); } } else { h << QString(" Q_INVOKABLE QVariant %1(const QModelIndex& index) const;\n").arg(ip.name); if (ip.write) { h << QString(" Q_INVOKABLE bool set%1(const QModelIndex& index, const QVariant& value);\n").arg(upperInitial(ip.name)); } } } h << R"( signals: // new data is ready to be made available to the model with fetchMore() void newDataReady(const QModelIndex &parent) const; private: QHash, QVariant> m_headerData; void initHeaderData(); )"; } bool isColumnWrite(const Object& o, int col) { for (auto ip: o.itemProperties) { if (ip.write && ip.roles.size() > col && ip.roles[col].size() > 0) { return true; } } return false; } void writeModelGetterSetter(QTextStream& cpp, const QString& index, const ItemProperty& ip, const Object& o) { const QString lcname(snakeCase(o.name)); QString idx = index; // getter if (o.type == ObjectType::List) { idx = ", row"; cpp << QString("QVariant %1::%2(int row) const\n{\n") .arg(o.name, ip.name); } else { cpp << QString("QVariant %1::%2(const QModelIndex& index) const\n{\n") .arg(o.name, ip.name); } cpp << " QVariant v;\n"; if (ip.type.name == "QString") { cpp << " QString s;\n"; cpp << QString(" %1_data_%2(m_d%4, &s, set_%3);\n") .arg(lcname, snakeCase(ip.name), ip.type.name.toLower(), idx); cpp << " if (!s.isNull()) v.setValue(s);\n"; } else if (ip.type.name == "QByteArray") { cpp << " QByteArray b;\n"; cpp << QString(" %1_data_%2(m_d%4, &b, set_%3);\n") .arg(lcname, snakeCase(ip.name), ip.type.name.toLower(), idx); cpp << " if (!b.isNull()) v.setValue(b);\n"; } else { cpp << QString(" v = %1_data_%2(m_d%3);\n") .arg(lcname, snakeCase(ip.name), idx); } cpp << " return v;\n"; cpp << "}\n\n"; if (!ip.write) { return; } // setter if (o.type == ObjectType::List) { idx = ", row"; cpp << QString("bool %1::set%2(int row, const QVariant& value)\n{\n") .arg(o.name, upperInitial(ip.name)); } else { cpp << QString("bool %1::set%2(const QModelIndex& index, const QVariant& value)\n{\n") .arg(o.name, upperInitial(ip.name)); } cpp << " bool set = false;\n"; if (ip.optional) { QString test = "!value.isValid()"; if (ip.type.isComplex()) { test += " || value.isNull()"; } cpp << " if (" << test << ") {\n"; cpp << QString(" set = %1_set_data_%2_none(m_d%3);") .arg(lcname, snakeCase(ip.name), idx) << endl; cpp << " } else\n"; } QString val = QString("value.value<%1>()").arg(ip.type.name); cpp << QString(" set = %1_set_data_%2(m_d%3, %4);") .arg(lcname, snakeCase(ip.name), idx, val) << endl; if (o.type == ObjectType::List) { cpp << R"( if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } )"; } else { cpp << R"( if (set) { emit dataChanged(index, index); } return set; } )"; } } void writeCppModel(QTextStream& cpp, const Object& o) { const QString lcname(snakeCase(o.name)); QString indexDecl = ", int"; QString index = ", index.row()"; if (o.type == ObjectType::Tree) { indexDecl = ", quintptr"; index = ", index.internalId()"; } cpp << "extern \"C\" {\n"; for (auto ip: o.itemProperties) { if (ip.type.isComplex()) { cpp << QString(" void %2_data_%3(const %1::Private*%5, %4);\n") .arg(o.name, lcname, snakeCase(ip.name), cGetType(ip.type), indexDecl); } else { cpp << QString(" %4 %2_data_%3(const %1::Private*%5);\n") .arg(o.name, lcname, snakeCase(ip.name), cppSetType(ip), indexDecl); } if (ip.write) { cpp << QString(" bool %2_set_data_%3(%1::Private*%5, %4);") .arg(o.name, lcname, snakeCase(ip.name), ip.type.cSetType, indexDecl) << endl; if (ip.optional) { cpp << QString(" bool %2_set_data_%3_none(%1::Private*%4);") .arg(o.name, lcname, snakeCase(ip.name), indexDecl) << endl; } } } cpp << QString(" void %2_sort(%1::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder);\n").arg(o.name, lcname); if (o.type == ObjectType::List) { cpp << QString(R"( int %2_row_count(const %1::Private*); bool %2_insert_rows(%1::Private*, int, int); bool %2_remove_rows(%1::Private*, int, int); bool %2_can_fetch_more(const %1::Private*); void %2_fetch_more(%1::Private*); } int %1::columnCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : %3; } bool %1::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int %1::rowCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : %2_row_count(m_d); } bool %1::insertRows(int row, int count, const QModelIndex &parent) { return %2_insert_rows(m_d, row, count); } bool %1::removeRows(int row, int count, const QModelIndex &parent) { return %2_remove_rows(m_d, row, count); } QModelIndex %1::index(int row, int column, const QModelIndex &parent) const { if (!parent.isValid() && row >= 0 && row < rowCount(parent) && column >= 0 && column < %3) { return createIndex(row, column, (quintptr)row); } return QModelIndex(); } QModelIndex %1::parent(const QModelIndex &) const { return QModelIndex(); } bool %1::canFetchMore(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : %2_can_fetch_more(m_d); } void %1::fetchMore(const QModelIndex &parent) { if (!parent.isValid()) { %2_fetch_more(m_d); } } )").arg(o.name, lcname, QString::number(o.columnCount)); } else { cpp << QString(R"( int %2_row_count(const %1::Private*, quintptr, bool); bool %2_can_fetch_more(const %1::Private*, quintptr, bool); void %2_fetch_more(%1::Private*, quintptr, bool); quintptr %2_index(const %1::Private*, quintptr, bool, int); qmodelindex_t %2_parent(const %1::Private*, quintptr); int %2_row(const %1::Private*, quintptr); } int %1::columnCount(const QModelIndex &) const { return %3; } bool %1::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int %1::rowCount(const QModelIndex &parent) const { if (parent.isValid() && parent.column() != 0) { return 0; } return %2_row_count(m_d, parent.internalId(), parent.isValid()); } bool %1::insertRows(int, int, const QModelIndex &) { return false; // not supported yet } bool %1::removeRows(int, int, const QModelIndex &) { return false; // not supported yet } QModelIndex %1::index(int row, int column, const QModelIndex &parent) const { if (row < 0 || column < 0 || column >= %3) { return QModelIndex(); } if (parent.isValid() && parent.column() != 0) { return QModelIndex(); } if (row >= rowCount(parent)) { return QModelIndex(); } const quintptr id = %2_index(m_d, parent.internalId(), parent.isValid(), row); return createIndex(row, column, id); } QModelIndex %1::parent(const QModelIndex &index) const { if (!index.isValid()) { return QModelIndex(); } const qmodelindex_t parent = %2_parent(m_d, index.internalId()); return parent.row >= 0 ?createIndex(parent.row, 0, parent.id) :QModelIndex(); } bool %1::canFetchMore(const QModelIndex &parent) const { if (parent.isValid() && parent.column() != 0) { return false; } return %2_can_fetch_more(m_d, parent.internalId(), parent.isValid()); } void %1::fetchMore(const QModelIndex &parent) { %2_fetch_more(m_d, parent.internalId(), parent.isValid()); } )").arg(o.name, lcname, QString::number(o.columnCount)); } cpp << QString(R"( void %1::sort(int column, Qt::SortOrder order) { %2_sort(m_d, column, order); } Qt::ItemFlags %1::flags(const QModelIndex &i) const { auto flags = QAbstractItemModel::flags(i); )").arg(o.name, lcname); for (int col = 0; col < o.columnCount; ++col) { if (isColumnWrite(o, col)) { cpp << " if (i.column() == " << col << ") {\n"; cpp << " flags |= Qt::ItemIsEditable;\n }\n"; } } cpp << " return flags;\n}\n\n"; for (auto ip: o.itemProperties) { writeModelGetterSetter(cpp, index, ip, o); } cpp << QString(R"(QVariant %1::data(const QModelIndex &index, int role) const { Q_ASSERT(rowCount(index.parent()) > index.row()); switch (index.column()) { )").arg(o.name); auto metaRoles = QMetaEnum::fromType(); for (int col = 0; col < o.columnCount; ++col) { cpp << QString(" case %1:\n").arg(col); cpp << QString(" switch (role) {\n"); for (int i = 0; i < o.itemProperties.size(); ++i) { auto ip = o.itemProperties[i]; auto roles = ip.roles.value(col); if (col > 0 && roles.size() == 0) { continue; } for (auto role: roles) { cpp << QString(" case Qt::%1:\n").arg(metaRoles.valueToKey(role)); } cpp << QString(" case Qt::UserRole + %1:\n").arg(i); if (o.type == ObjectType::List) { cpp << QString(" return %1(index.row());\n").arg(ip.name); } else { cpp << QString(" return %1(index);\n").arg(ip.name); } } cpp << " }\n"; } cpp << " }\n return QVariant();\n}\n\n"; cpp << "QHash " << o.name << "::roleNames() const {\n"; cpp << " QHash names = QAbstractItemModel::roleNames();\n"; for (int i = 0; i < o.itemProperties.size(); ++i) { auto ip = o.itemProperties[i]; cpp << " names.insert(Qt::UserRole + " << i << ", \"" << ip.name << "\");\n"; } cpp << " return names;\n"; cpp << QString(R"(} QVariant %1::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation != Qt::Horizontal) { return QVariant(); } return m_headerData.value(qMakePair(section, (Qt::ItemDataRole)role), role == Qt::DisplayRole ?QString::number(section + 1) :QVariant()); } bool %1::setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role) { if (orientation != Qt::Horizontal) { return false; } m_headerData.insert(qMakePair(section, (Qt::ItemDataRole)role), value); return true; } )").arg(o.name); if (modelIsWritable(o)) { cpp << QString("bool %1::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n").arg(o.name); for (int col = 0; col < o.columnCount; ++col) { if (!isColumnWrite(o, col)) { continue; } cpp << " if (index.column() == " << col << ") {\n"; for (int i = 0; i < o.itemProperties.size(); ++i) { auto ip = o.itemProperties[i]; if (!ip.write) { continue; } auto roles = ip.roles.value(col); if (col > 0 && roles.size() == 0) { continue; } cpp << " if ("; for (auto role: roles) { cpp << QString("role == Qt::%1 || ").arg(metaRoles.valueToKey(role)); } cpp << "role == Qt::UserRole + " << i << ") {\n"; if (o.type == ObjectType::List) { cpp << QString(" return set%1(index.row(), value);\n") .arg(upperInitial(ip.name)); } else { cpp << QString(" return set%1(index, value);\n") .arg(upperInitial(ip.name)); } cpp << " }\n"; } cpp << " }\n"; } cpp << " return false;\n}\n\n"; } } void writeHeaderObject(QTextStream& h, const Object& o, const Configuration& conf) { h << QString(R"( class %1 : public %3 { Q_OBJEC%2 )").arg(o.name, "T", baseType(o)); for (auto object: conf.objects) { if (object.containsObject() && o.name != object.name) { h << " friend class " << object.name << ";\n"; } } h << R"(public: class Private; private: )"; for (auto p: o.properties) { if (p.type.type == BindingType::Object) { h << " " << p.type.name << "* const m_" << p.name << ";\n"; } } h << R"( Private * m_d; bool m_ownsPrivate; )"; for (auto p: o.properties) { bool obj = p.type.type == BindingType::Object; h << QString(" Q_PROPERTY(%1 %2 READ %2 %3NOTIFY %2Changed FINAL)") .arg(p.type.name + (obj ?"*" :""), p.name, p.write ? writeProperty(p.name) :"") << endl; } h << QString(R"( explicit %1(bool owned, QObject *parent); public: explicit %1(QObject *parent = nullptr); ~%1(); )").arg(o.name); for (auto p: o.properties) { if (p.type.type == BindingType::Object) { h << " const " << p.type.name << "* " << p.name << "() const;" << endl; h << " " << p.type.name << "* " << p.name << "();" << endl; } else { h << " " << p.type.name << " " << p.name << "() const;" << endl; if (p.write) { h << " void set" << upperInitial(p.name) << "(" << p.type.cppSetType << " v);" << endl; } } } + for (auto f: o.functions) { + h << " Q_INVOKABLE " << f.type.name << " " << f.name << "("; + for (auto a = f.args.begin(); a < f.args.end(); a++) { + h << QString("%1 %2%3").arg(a->type.cppSetType, a->name, a + 1 < f.args.end() ? ", " : ""); + } + h << QString(")%1;") + .arg(f.mut ? "" : " const"); + h << endl; + } if (baseType(o) == "QAbstractItemModel") { writeHeaderItemModel(h, o); } h << "signals:" << endl; for (auto p: o.properties) { h << " void " << p.name << "Changed();" << endl; } h << "};" << endl; } void constructorArgsDecl(QTextStream& cpp, const Object& o, const Configuration& conf) { cpp << o.name << "*"; for (auto p: o.properties) { if (p.type.type == BindingType::Object) { cpp << QString(", "); constructorArgsDecl(cpp, conf.findObject(p.type.name), conf); } else { cpp << QString(", void (*)(%1*)").arg(o.name); } } if (o.type == ObjectType::List) { cpp << QString(R"(, void (*)(const %1*), void (*)(%1*, quintptr, quintptr), void (*)(%1*), void (*)(%1*), void (*)(%1*, int, int), void (*)(%1*), void (*)(%1*, int, int), void (*)(%1*))").arg(o.name); } if (o.type == ObjectType::Tree) { cpp << QString(R"(, void (*)(const %1*, quintptr, bool), void (*)(%1*, quintptr, quintptr), void (*)(%1*), void (*)(%1*), void (*)(%1*, option_quintptr, int, int), void (*)(%1*), void (*)(%1*, option_quintptr, int, int), void (*)(%1*))").arg(o.name); } } QString changedF(const Object& o, const Property& p) { return lowerInitial(o.name) + upperInitial(p.name) + "Changed"; } void constructorArgs(QTextStream& cpp, const QString& prefix, const Object& o, const Configuration& conf) { const QString lcname(snakeCase(o.name)); for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { cpp << ", " << prefix << "m_" << p.name; constructorArgs(cpp, "m_" + p.name + "->", conf.findObject(p.type.name), conf); } else { cpp << ",\n " << changedF(o, p); } } if (o.type == ObjectType::List) { cpp << QString(R"(, [](const %1* o) { emit o->newDataReady(QModelIndex()); }, [](%1* o, quintptr first, quintptr last) { o->dataChanged(o->createIndex(first, 0, first), o->createIndex(last, %2, last)); }, [](%1* o) { o->beginResetModel(); }, [](%1* o) { o->endResetModel(); }, [](%1* o, int first, int last) { o->beginInsertRows(QModelIndex(), first, last); }, [](%1* o) { o->endInsertRows(); }, [](%1* o, int first, int last) { o->beginRemoveRows(QModelIndex(), first, last); }, [](%1* o) { o->endRemoveRows(); } )").arg(o.name, QString::number(o.columnCount - 1)); } if (o.type == ObjectType::Tree) { cpp << QString(R"(, [](const %1* o, quintptr id, bool valid) { if (valid) { int row = %2_row(o->m_d, id); emit o->newDataReady(o->createIndex(row, 0, id)); } else { emit o->newDataReady(QModelIndex()); } }, [](%1* o, quintptr first, quintptr last) { quintptr frow = %2_row(o->m_d, first); quintptr lrow = %2_row(o->m_d, first); o->dataChanged(o->createIndex(frow, 0, first), o->createIndex(lrow, %3, last)); }, [](%1* o) { o->beginResetModel(); }, [](%1* o) { o->endResetModel(); }, [](%1* o, option_quintptr id, int first, int last) { if (id.some) { int row = %2_row(o->m_d, id.value); o->beginInsertRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginInsertRows(QModelIndex(), first, last); } }, [](%1* o) { o->endInsertRows(); }, [](%1* o, option_quintptr id, int first, int last) { if (id.some) { int row = %2_row(o->m_d, id.value); o->beginRemoveRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginRemoveRows(QModelIndex(), first, last); } }, [](%1* o) { o->endRemoveRows(); } )").arg(o.name, lcname, QString::number(o.columnCount - 1)); } } void writeObjectCDecl(QTextStream& cpp, const Object& o, const Configuration& conf) { const QString lcname(snakeCase(o.name)); cpp << QString(" %1::Private* %2_new(").arg(o.name, lcname); constructorArgsDecl(cpp, o, conf); cpp << ");" << endl; cpp << QString(" void %2_free(%1::Private*);").arg(o.name, lcname) << endl; for (const Property& p: o.properties) { const QString base = QString("%1_%2").arg(lcname, snakeCase(p.name)); if (p.type.type == BindingType::Object) { cpp << QString(" %3::Private* %2_get(const %1::Private*);") .arg(o.name, base, p.type.name) << endl; } else if (p.type.isComplex()) { cpp << QString(" void %2_get(const %1::Private*, %3);") .arg(o.name, base, cGetType(p.type)) << endl; } else { cpp << QString(" %3 %2_get(const %1::Private*);") .arg(o.name, base, p.type.name) << endl; } if (p.write) { cpp << QString(" void %2_set(%1::Private*, %3);") .arg(o.name, base, p.type.cSetType) << endl; if (p.optional) { cpp << QString(" void %2_set_none(%1::Private*);") .arg(o.name, base) << endl; } } } + + for (const Function& f: o.functions) { + const QString name = QString("%1_%2").arg(lcname, f.name); + cpp << QString(" %1 %2(%4%3::Private*") + .arg(f.type.cSetType, name, o.name, f.mut ? "" : "const "); + if (f.args.size() > 0) { + cpp << ", "; + for (auto a = f.args.begin(); a < f.args.end(); a++) { + cpp << QString("%2%3").arg(a->type.cSetType, a + 1 < f.args.end() ? ", " : ""); + } + } + if (f.type.name == "QString") { + cpp << ", QString*, qstring_set"; + } + cpp << ");" << endl; + } } void initializeMembersEmpty(QTextStream& cpp, const Object& o, const Configuration& conf) { for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { initializeMembersEmpty(cpp, conf.findObject(p.type.name), conf); cpp << QString(" %1m_%2(new %3(false, this)),\n") .arg(p.name, p.type.name); } } } void initializeMembersZero(QTextStream& cpp, const Object& o) { for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { cpp << QString(" m_%1(new %2(false, this)),\n") .arg(p.name, p.type.name); } } } void initializeMembers(QTextStream& cpp, const QString& prefix, const Object& o, const Configuration& conf) { for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { cpp << QString(" %1m_%2->m_d = %3_%4_get(%1m_d);\n") .arg(prefix, p.name, snakeCase(o.name), snakeCase(p.name)); initializeMembers(cpp, "m_" + p.name + "->", conf.findObject(p.type.name), conf); } } } void connect(QTextStream& cpp, const QString& d, const Object& o, const Configuration& conf) { for (auto p: o.properties) { if (p.type.type == BindingType::Object) { connect(cpp, d + "->m_" + p.name, conf.findObject(p.type.name), conf); } } if (o.type != ObjectType::Object) { cpp << QString(R"( connect(%2, &%1::newDataReady, %2, [this](const QModelIndex& i) { %2->fetchMore(i); }, Qt::QueuedConnection); )").arg(o.name, d); } } void writeCppObject(QTextStream& cpp, const Object& o, const Configuration& conf) { const QString lcname(snakeCase(o.name)); cpp << QString("%1::%1(bool /*owned*/, QObject *parent):\n %2(parent),") .arg(o.name, baseType(o)) << endl; for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { cpp << QString(" m_%1(new %2(false, this)),\n") .arg(p.name, p.type.name); } } cpp << " m_d(0),\n m_ownsPrivate(false)\n{\n"; if (o.type != ObjectType::Object) { cpp << " initHeaderData();\n"; } cpp << QString("}\n\n%1::%1(QObject *parent):\n %2(parent),") .arg(o.name, baseType(o)) << endl; initializeMembersZero(cpp, o); cpp << QString(" m_d(%1_new(this").arg(lcname); constructorArgs(cpp, "", o, conf); cpp << ")),\n m_ownsPrivate(true)\n{\n"; initializeMembers(cpp, "", o, conf); connect(cpp, "this", o, conf); if (o.type != ObjectType::Object) { cpp << " initHeaderData();\n"; } cpp << QString(R"(} %1::~%1() { if (m_ownsPrivate) { %2_free(m_d); } } )").arg(o.name, lcname); if (o.type != ObjectType::Object) { cpp << QString("void %1::initHeaderData() {\n").arg(o.name); for (int col = 0; col < o.columnCount; ++col) { for (auto ip: o.itemProperties) { auto roles = ip.roles.value(col); if (roles.contains(Qt::DisplayRole)) { cpp << QString(" m_headerData.insert(qMakePair(%1, Qt::DisplayRole), QVariant(\"%2\"));\n").arg(QString::number(col), ip.name); } } } cpp << "}\n"; } for (const Property& p: o.properties) { const QString base = QString("%1_%2").arg(lcname, snakeCase(p.name)); if (p.type.type == BindingType::Object) { cpp << QString(R"(const %3* %1::%2() const { return m_%2; } %3* %1::%2() { return m_%2; } )").arg(o.name, p.name, p.type.name); } else if (p.type.isComplex()) { cpp << QString("%3 %1::%2() const\n{\n").arg(o.name, p.name, p.type.name); cpp << " " << p.type.name << " v;\n"; cpp << " " << base << "_get(m_d, &v, set_" << p.type.name.toLower() << ");\n"; cpp << " return v;\n}\n"; } else { cpp << QString("%3 %1::%2() const\n{\n").arg(o.name, p.name, p.type.name); cpp << QString(" return %1_get(m_d);\n}\n").arg(base); } if (p.write) { cpp << "void " << o.name << "::set" << upperInitial(p.name) << "(" << p.type.cppSetType << " v) {" << endl; if (p.optional) { cpp << QString(" if (v.isNull()) {") << endl; cpp << QString(" %1_set_none(m_d);").arg(base) << endl; cpp << QString(" } else {") << endl; cpp << QString(" %1_set(m_d, v);").arg(base) << endl; cpp << QString(" }") << endl; } else { cpp << QString(" %1_set(m_d, v);").arg(base) << endl; } cpp << "}" << endl; } } + + for (const Function& f: o.functions) { + const QString base = QString("%1_%2") + .arg(lcname, snakeCase(f.name)); + cpp << QString("%1 %2::%3(") + .arg(f.type.name, o.name, f.name); + for (auto a = f.args.begin(); a < f.args.end(); a++) { + cpp << QString("%1 %2%3").arg(a->type.cppSetType, a->name, a + 1 < f.args.end() ? ", " : ""); + } + cpp << QString(") %4\n{\n") + .arg(f.mut ? "" : "const"); + QString argList; + if (f.args.size() > 0) { + argList.append(", "); + for (auto a = f.args.begin(); a < f.args.end(); a++) { + argList.append(QString("%2%3").arg(a->name, a + 1 < f.args.end() ? ", " : "")); + } + } + if (f.type.name == "QString") { + cpp << QString(" %1 s;").arg(f.type.name) << endl; + cpp << QString(" %1(m_d%2, &s, set_qstring);") + .arg(base, argList) << endl; + cpp << " return s;" << endl; + } else { + cpp << QString(" return %1(m_d%2);") + .arg(base, argList) << endl; + } + cpp << "}" << endl; + } } void writeHeader(const Configuration& conf) { DifferentFileWriter w(conf.hFile.absoluteFilePath()); QTextStream h(&w.buffer); const QString guard(conf.hFile.fileName().replace('.', '_').toUpper()); h << QString(R"(/* generated by rust_qt_binding_generator */ #ifndef %1 #define %1 #include #include )").arg(guard); for (auto object: conf.objects) { h << "class " << object.name << ";\n"; } for (auto object: conf.objects) { writeHeaderObject(h, object, conf); } h << QString("#endif // %1\n").arg(guard); } void writeCpp(const Configuration& conf) { DifferentFileWriter w(conf.cppFile.absoluteFilePath()); QTextStream cpp(&w.buffer); cpp << QString(R"(/* generated by rust_qt_binding_generator */ #include "%1" namespace { )").arg(conf.hFile.fileName()); for (auto option: conf.optionalTypes()) { cpp << QString(R"( struct option_%1 { public: %1 value; bool some; operator QVariant() const { if (some) { return QVariant(value); } return QVariant(); } }; )").arg(option); } if (conf.types().contains("QString")) { cpp << R"( struct qstring_t { private: const void* data; int len; public: qstring_t(const QString& v): data(static_cast(v.utf16())), len(v.size()) { } operator QString() const { return QString::fromUtf8(static_cast(data), len); } }; typedef void (*qstring_set)(QString*, qstring_t*); void set_qstring(QString* v, qstring_t* val) { *v = *val; } )"; } if (conf.types().contains("QByteArray")) { cpp << R"( struct qbytearray_t { private: const char* data; int len; public: qbytearray_t(const QByteArray& v): data(v.data()), len(v.size()) { } operator QByteArray() const { return QByteArray(data, len); } }; typedef void (*qbytearray_set)(QByteArray*, qbytearray_t*); void set_qbytearray(QByteArray* v, qbytearray_t* val) { *v = *val; } )"; } if (conf.hasListOrTree()) { cpp << R"( struct qmodelindex_t { int row; quintptr id; }; )"; } for (auto o: conf.objects) { for (auto p: o.properties) { if (p.type.type == BindingType::Object) { continue; } cpp << " inline void " << changedF(o, p) << "(" << o.name << "* o)\n"; cpp << " {\n emit o->" << p.name << "Changed();\n }\n"; } } cpp << "}\n"; for (auto object: conf.objects) { if (object.type != ObjectType::Object) { writeCppModel(cpp, object); } cpp << "extern \"C\" {\n"; writeObjectCDecl(cpp, object, conf); cpp << "};\n" << endl; } for (auto object: conf.objects) { writeCppObject(cpp, object, conf); } } diff --git a/src/parseJson.cpp b/src/parseJson.cpp index 09af681..a5cbade 100644 --- a/src/parseJson.cpp +++ b/src/parseJson.cpp @@ -1,251 +1,306 @@ /* * Copyright 2017 Jos van den Oever * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License or (at your option) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "parseJson.h" #include "helper.h" #include #include #include #include BindingTypeProperties simpleType(BindingType type, const char* name, const char* init) { return { .type = type, .name = name, .cppSetType = name, .cSetType = name, .rustType = name, .rustTypeInit = init }; } QList& bindingTypeProperties() { static QList p; if (p.empty()) { QList f; f.append(simpleType(BindingType::Bool, "bool", "true")); f.append({ .type = BindingType::UChar, .name = "quint8", .cppSetType = "quint8", .cSetType = "quint8", .rustType = "u8", .rustTypeInit = "0", }); f.append({ .type = BindingType::Int, .name = "qint32", .cppSetType = "qint32", .cSetType = "qint32", .rustType = "i32", .rustTypeInit = "0", }); f.append({ .type = BindingType::UInt, .name = "quint32", .cppSetType = "uint", .cSetType = "uint", .rustType = "u32", .rustTypeInit = "0" }); f.append({ .type = BindingType::ULongLong, .name = "quint64", .cppSetType = "quint64", .cSetType = "quint64", .rustType = "u64", .rustTypeInit = "0" }); f.append({ .type = BindingType::Float, .name = "float", .cppSetType = "float", .cSetType = "float", .rustType = "f32", .rustTypeInit = "0.0" }); f.append({ .type = BindingType::QString, .name = "QString", .cppSetType = "const QString&", .cSetType = "qstring_t", .rustType = "String", .rustTypeInit = "String::new()" }); f.append({ .type = BindingType::QByteArray, .name = "QByteArray", .cppSetType = "const QByteArray&", .cSetType = "qbytearray_t", .rustType = "Vec", .rustTypeInit = "Vec::new()" }); + f.append({ + .type = BindingType::Void, + .name = "void", + .cppSetType = "void", + .cSetType = "void", + .rustType = "()", + .rustTypeInit = "()", + }); p = f; } return p; } BindingTypeProperties parseBindingType(const QString& value) { for (auto type: bindingTypeProperties()) { if (value == type.name) { return type; } } QTextStream err(stderr); err << QCoreApplication::translate("main", "'%1' is not a supported type. Use one of\n").arg(value); for (auto i: bindingTypeProperties()) { if (i.name == i.rustType) { err << " " << i.rustType << "\n"; } else { err << " " << i.name << " (" << i.rustType << ")\n"; } } err.flush(); exit(1); } Property parseProperty(const QString& name, const QJsonObject& json) { Property p; p.name = name; p.type = parseBindingType(json.value("type").toString()); p.write = json.value("write").toBool(); p.optional = json.value("optional").toBool(); p.rustByValue = json.value("rustByValue").toBool(); return p; } +Argument +parseArgument(const QJsonObject& json) { + Argument arg; + arg.name = json.value("name").toString(); + arg.type = parseBindingType(json.value("type").toString()); + QTextStream out(stdout); + out.flush(); + if (arg.type.type == BindingType::Object) { + QTextStream err(stderr); + err << QCoreApplication::translate("main", + "'%1' is not a supported type in argument \"%2\". Only use the basic QT types for now\n").arg(arg.type.name, arg.name); + err.flush(); + exit(1); + } + return arg; +} + +QList +parseArguments(const QJsonArray& json) { + QList args; + for(const auto& a: json) { + args.push_back(parseArgument(a.toObject())); + } + return args; +} + +Function +parseFunction(const QString& name, const QJsonObject& json) { + Function f; + f.name = name; + f.mut = json.value("mut").toBool(); + f.type = parseBindingType(json.value("return").toString()); + if (f.type.type == BindingType::Object) { + QTextStream err(stderr); + err << QCoreApplication::translate("main", + "'%1' is not a supported return type in function \"%2\". Only use the basic QT types for now\n").arg(f.type.name, f.name); + err.flush(); + exit(1); + } + f.args = parseArguments(json.value("arguments").toArray()); + return f; +} + Qt::ItemDataRole parseItemDataRole(const QString& s) { const QString name = s.left(1).toUpper() + s.mid(1) + "Role"; int v = QMetaEnum::fromType() .keyToValue(name.toUtf8()); if (v >= 0) { return (Qt::ItemDataRole)v; } QTextStream err(stderr); err << QCoreApplication::translate("main", "%1 is not a valid role name.\n").arg(s); err.flush(); exit(1); } ItemProperty parseItemProperty(const QString& name, const QJsonObject& json) { ItemProperty ip; ip.name = name; ip.type = parseBindingType(json.value("type").toString()); ip.write = json.value("write").toBool(); ip.optional = json.value("optional").toBool(); ip.rustByValue = json.value("rustByValue").toBool(); QJsonArray roles = json.value("roles").toArray(); for (auto r: roles) { QList l; for (auto v: r.toArray()) { l.append(parseItemDataRole(v.toString())); } ip.roles.append(l); } return ip; } Object parseObject(const QString& name, const QJsonObject& json) { Object o; o.name = name; QString type = json.value("type").toString(); if (type == "List") { o.type = ObjectType::List; } else if (type == "Tree") { o.type = ObjectType::Tree; } else { o.type = ObjectType::Object; } const QJsonObject& properties = json.value("properties").toObject(); for (const QString& key: properties.keys()) { o.properties.append(parseProperty(key, properties[key].toObject())); } + const QJsonObject& functions = json.value("functions").toObject(); + for (const QString& key: functions.keys()) { + o.functions.append(parseFunction(key, functions[key].toObject())); + } QTextStream err(stderr); const QJsonObject& itemProperties = json.value("itemProperties").toObject(); if (o.type != ObjectType::Object && itemProperties.size() == 0) { err << QCoreApplication::translate("main", "No item properties are defined for %1.\n").arg(o.name); err.flush(); exit(1); } else if (o.type == ObjectType::Object && itemProperties.size() > 0) { err << QCoreApplication::translate("main", "%1 is an Object and should not have itemProperties.").arg(o.name); err.flush(); exit(1); } o.columnCount = 0; for (const QString& key: itemProperties.keys()) { ItemProperty p = parseItemProperty(key, itemProperties[key].toObject()); o.columnCount = qMax(o.columnCount, p.roles.size()); o.itemProperties.append(p); } return o; } Configuration parseConfiguration(const QString& path) { QFile configurationFile(path); const QDir base = QFileInfo(configurationFile).dir(); QTextStream err(stderr); if (!configurationFile.open(QIODevice::ReadOnly)) { err << QCoreApplication::translate("main", "Cannot read %1.\n").arg(configurationFile.fileName()); err.flush(); exit(1); } const QByteArray data(configurationFile.readAll()); QJsonParseError error; const QJsonDocument doc(QJsonDocument::fromJson(data, &error)); if (error.error != QJsonParseError::NoError) { err << error.errorString(); err.flush(); exit(1); } const QJsonObject o = doc.object(); Configuration c; c.cppFile = QFileInfo(base, o.value("cppFile").toString()); QDir(c.cppFile.dir()).mkpath("."); c.hFile = QFileInfo(c.cppFile.dir(), c.cppFile.completeBaseName() + ".h"); const QJsonObject& object = o.value("objects").toObject(); for (const QString& key: object.keys()) { bindingTypeProperties().append({ .type = BindingType::Object, .name = key, .cppSetType = key, .cSetType = key, .rustType = key, .rustTypeInit = "", }); } for (const QString& key: object.keys()) { Object o = parseObject(key, object[key].toObject()); c.objects.append(o); } const QJsonObject rust = o.value("rust").toObject(); c.rustdir = QDir(base.filePath(rust.value("dir").toString())); c.interfaceModule = rust.value("interfaceModule").toString(); c.implementationModule = rust.value("implementationModule").toString(); return c; } diff --git a/src/rust.cpp b/src/rust.cpp index 308f32a..c9b0748 100644 --- a/src/rust.cpp +++ b/src/rust.cpp @@ -1,915 +1,960 @@ /* * Copyright 2017 Jos van den Oever * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License or (at your option) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "structs.h" #include "helper.h" template QString rustType(const T& p) { if (p.optional) { return "Option<" + p.type.rustType + ">"; } return p.type.rustType; } template QString rustReturnType(const T& p) { QString type = p.type.rustType; if (type == "String" && !p.rustByValue) { type = "str"; } if (type == "Vec" && !p.rustByValue) { type = "[u8]"; } if (p.type.isComplex() && !p.rustByValue) { type = "&" + type; } if (p.optional) { return "Option<" + type + ">"; } return type; } template QString rustCType(const T& p) { if (p.optional) { return "COption<" + p.type.rustType + ">"; } return p.type.rustType; } template QString rustTypeInit(const T& p) { if (p.optional) { return "None"; } return p.type.rustTypeInit; } void rConstructorArgsDecl(QTextStream& r, const QString& name, const Object& o, const Configuration& conf) { r << QString(" %2: *mut %1QObject").arg(o.name, snakeCase(name)); for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { r << QString(",\n"); rConstructorArgsDecl(r, p.name, conf.findObject(p.type.name), conf); } else { r << QString(",\n %2_changed: fn(*const %1QObject)") .arg(o.name, snakeCase(p.name)); } } if (o.type == ObjectType::List) { r << QString(",\n %2_new_data_ready: fn(*const %1QObject)") .arg(o.name, snakeCase(o.name)); } else if (o.type == ObjectType::Tree) { r << QString(",\n %2_new_data_ready: fn(*const %1QObject, item: usize, valid: bool)") .arg(o.name, snakeCase(o.name)); } if (o.type != ObjectType::Object) { QString indexDecl; if (o.type == ObjectType::Tree) { indexDecl = " item: usize, valid: bool,"; } r << QString(R"(, %3_data_changed: fn(*const %1QObject, usize, usize), %3_begin_reset_model: fn(*const %1QObject), %3_end_reset_model: fn(*const %1QObject), %3_begin_insert_rows: fn(*const %1QObject,%2 usize, usize), %3_end_insert_rows: fn(*const %1QObject), %3_begin_remove_rows: fn(*const %1QObject,%2 usize, usize), %3_end_remove_rows: fn(*const %1QObject))").arg(o.name, indexDecl, snakeCase(o.name)); } } void rConstructorArgs(QTextStream& r, const QString& name, const Object& o, const Configuration& conf) { const QString lcname(snakeCase(o.name)); for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { rConstructorArgs(r, p.name, conf.findObject(p.type.name), conf); } } r << QString(R"( let %2_emit = %1Emitter { qobject: Arc::new(Mutex::new(%2)), )").arg(o.name, snakeCase(name)); for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) continue; r << QString(" %1_changed: %1_changed,\n").arg(snakeCase(p.name)); } if (o.type != ObjectType::Object) { r << QString(" new_data_ready: %1_new_data_ready,\n") .arg(snakeCase(o.name)); } QString model = ""; if (o.type != ObjectType::Object) { const QString type = o.type == ObjectType::List ? "List" : "Tree"; model = ", model"; r << QString(R"( }; let model = %1%2 { qobject: %3, data_changed: %4_data_changed, begin_reset_model: %4_begin_reset_model, end_reset_model: %4_end_reset_model, begin_insert_rows: %4_begin_insert_rows, end_insert_rows: %4_end_insert_rows, begin_remove_rows: %4_begin_remove_rows, end_remove_rows: %4_end_remove_rows, )").arg(o.name, type, snakeCase(name), snakeCase(o.name)); } r << QString(" };\n let d_%3 = %1::new(%3_emit%2") .arg(o.name, model, snakeCase(name)); for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { r << ",\n d_" << snakeCase(p.name); } } r << ");\n"; } void writeRustInterfaceObject(QTextStream& r, const Object& o, const Configuration& conf) { const QString lcname(snakeCase(o.name)); r << QString(R"( pub struct %1QObject {} #[derive(Clone)] pub struct %1Emitter { qobject: Arc>, )").arg(o.name); for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { continue; } r << QString(" %2_changed: fn(*const %1QObject),\n") .arg(o.name, snakeCase(p.name)); } if (o.type == ObjectType::List) { r << QString(" new_data_ready: fn(*const %1QObject),\n") .arg(o.name); } else if (o.type == ObjectType::Tree) { r << QString(" new_data_ready: fn(*const %1QObject, item: usize, valid: bool),\n") .arg(o.name); } r << QString(R"(} unsafe impl Send for %1Emitter {} impl %1Emitter { fn clear(&self) { *self.qobject.lock().unwrap() = null(); } )").arg(o.name); for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { continue; } r << QString(R"( pub fn %1_changed(&self) { let ptr = *self.qobject.lock().unwrap(); if !ptr.is_null() { (self.%1_changed)(ptr); } } )").arg(snakeCase(p.name)); } if (o.type == ObjectType::List) { r << R"( pub fn new_data_ready(&self) { let ptr = *self.qobject.lock().unwrap(); if !ptr.is_null() { (self.new_data_ready)(ptr); } } )"; } else if (o.type == ObjectType::Tree) { r << R"( pub fn new_data_ready(&self, item: Option) { let ptr = *self.qobject.lock().unwrap(); if !ptr.is_null() { (self.new_data_ready)(ptr, item.unwrap_or(13), item.is_some()); } } )"; } QString modelStruct = ""; if (o.type != ObjectType::Object) { QString type = o.type == ObjectType::List ? "List" : "Tree"; modelStruct = ", model: " + o.name + type; QString index; QString indexDecl; QString indexCDecl; if (o.type == ObjectType::Tree) { indexDecl = " item: Option,"; indexCDecl = " item: usize, valid: bool,"; index = " item.unwrap_or(13), item.is_some(),"; } r << QString(R"(} pub struct %1%2 { qobject: *const %1QObject, data_changed: fn(*const %1QObject, usize, usize), begin_reset_model: fn(*const %1QObject), end_reset_model: fn(*const %1QObject), begin_insert_rows: fn(*const %1QObject,%5 usize, usize), end_insert_rows: fn(*const %1QObject), begin_remove_rows: fn(*const %1QObject,%5 usize, usize), end_remove_rows: fn(*const %1QObject), } impl %1%2 { pub fn data_changed(&self, first: usize, last: usize) { (self.data_changed)(self.qobject, first, last); } pub fn begin_reset_model(&self) { (self.begin_reset_model)(self.qobject); } pub fn end_reset_model(&self) { (self.end_reset_model)(self.qobject); } pub fn begin_insert_rows(&self,%3 first: usize, last: usize) { (self.begin_insert_rows)(self.qobject,%4 first, last); } pub fn end_insert_rows(&self) { (self.end_insert_rows)(self.qobject); } pub fn begin_remove_rows(&self,%3 first: usize, last: usize) { (self.begin_remove_rows)(self.qobject,%4 first, last); } pub fn end_remove_rows(&self) { (self.end_remove_rows)(self.qobject); } )").arg(o.name, type, indexDecl, index, indexCDecl); } r << QString(R"(} pub trait %1Trait { fn new(emit: %1Emitter%2)").arg(o.name, modelStruct); for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { r << ",\n " << snakeCase(p.name) << ": " << p.type.name; } } r << QString(R"() -> Self; fn emit(&self) -> &%1Emitter; )").arg(o.name); for (const Property& p: o.properties) { const QString lc(snakeCase(p.name)); if (p.type.type == BindingType::Object) { r << QString(" fn %1(&self) -> &%2;\n").arg(lc, rustType(p)); r << QString(" fn %1_mut(&mut self) -> &mut %2;\n").arg(lc, rustType(p)); } else { r << QString(" fn %1(&self) -> %2;\n").arg(lc, rustReturnType(p)); if (p.write) { r << QString(" fn set_%1(&mut self, value: %2);\n").arg(lc, rustType(p)); } } } + for (const Function& f: o.functions) { + const QString lc(snakeCase(f.name)); + QString argList; + if (f.args.size() > 0) { + argList.append(", "); + for (auto a = f.args.begin(); a < f.args.end(); a++) { + argList.append( + QString("%1: %2%3") + .arg(a->name, a->type.rustType, a + 1 < f.args.end() ? ", " : "") + ); + } + } + r << QString(" fn %1(&%2self%4) -> %3;\n") + .arg(lc, f.mut ? "mut " : "", f.type.rustType, argList); + } if (o.type == ObjectType::List) { r << R"( fn row_count(&self) -> usize; fn insert_rows(&mut self, row: usize, count: usize) -> bool { false } fn remove_rows(&mut self, row: usize, count: usize) -> bool { false } fn can_fetch_more(&self) -> bool { false } fn fetch_more(&mut self) {} fn sort(&mut self, u8, SortOrder) {} )"; } else if (o.type == ObjectType::Tree) { r << R"( fn row_count(&self, Option) -> usize; fn can_fetch_more(&self, Option) -> bool { false } fn fetch_more(&mut self, Option) {} fn sort(&mut self, u8, SortOrder) {} fn index(&self, item: Option, row: usize) -> usize; fn parent(&self, item: usize) -> Option; fn row(&self, item: usize) -> usize; )"; } if (o.type != ObjectType::Object) { for (auto ip: o.itemProperties) { r << QString(" fn %1(&self, item: usize) -> %2;\n") .arg(snakeCase(ip.name), rustReturnType(ip)); if (ip.write) { r << QString(" fn set_%1(&mut self, item: usize, %2) -> bool;\n") .arg(snakeCase(ip.name), rustType(ip)); } } } r << QString(R"(} #[no_mangle] pub extern "C" fn %1_new( )").arg(lcname); rConstructorArgsDecl(r, lcname, o, conf); r << QString(",\n) -> *mut %1 {\n").arg(o.name); rConstructorArgs(r, lcname, o, conf); r << QString(R"( Box::into_raw(Box::new(d_%2)) } #[no_mangle] pub unsafe extern "C" fn %2_free(ptr: *mut %1) { Box::from_raw(ptr).emit().clear(); } )").arg(o.name, lcname); for (const Property& p: o.properties) { const QString base = QString("%1_%2").arg(lcname, snakeCase(p.name)); QString ret = ") -> " + rustType(p); if (p.type.type == BindingType::Object) { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_get(ptr: *mut %1) -> *mut %4 { (&mut *ptr).%3_mut() } )").arg(o.name, base, snakeCase(p.name), rustType(p)); } else if (p.type.isComplex() && !p.optional) { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_get( ptr: *const %1, p: *mut c_void, set: fn(*mut c_void, %4), ) { let data = (&*ptr).%3(); set(p, %5data.into()); } )").arg(o.name, base, snakeCase(p.name), p.type.name, p.rustByValue ?"&" :""); if (p.write) { const QString type = p.type.name == "QString" ? "QStringIn" : p.type.name; r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_set(ptr: *mut %1, v: %4) { (&mut *ptr).set_%3(v.convert()); } )").arg(o.name, base, snakeCase(p.name), type); } } else if (p.type.isComplex()) { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_get( ptr: *const %1, p: *mut c_void, set: fn(*mut c_void, %4), ) { let data = (&*ptr).%3(); if let Some(data) = data { set(p, %5data.into()); } } )").arg(o.name, base, snakeCase(p.name), p.type.name, p.rustByValue ?"&" :""); if (p.write) { const QString type = p.type.name == "QString" ? "QStringIn" : p.type.name; r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_set(ptr: *mut %1, v: %4) { (&mut *ptr).set_%3(Some(v.convert())); } #[no_mangle] pub unsafe extern "C" fn %2_set_none(ptr: *mut %1) { (&mut *ptr).set_%3(None); } )").arg(o.name, base, snakeCase(p.name), type); } } else { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_get(ptr: *const %1) -> %4 { (&*ptr).%3() } )").arg(o.name, base, snakeCase(p.name), rustType(p)); if (p.write) { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_set(ptr: *mut %1, v: %4) { (&mut *ptr).set_%3(v); } )").arg(o.name, base, snakeCase(p.name), rustType(p)); } } } + for (const Function& f: o.functions) { + QString argList; + QString noTypeArgs; + if (f.args.size() > 0) { + argList.append(", "); + for (auto a = f.args.begin(); a < f.args.end(); a++) { + const QString type = a->type.name == "QString" ? "QStringIn" : a->type.rustType; + const QString passAlong = a->type.name == "QString" ? QString("%1.convert()").arg(a->name) : a->name; + argList.append(QString("%1: %2%3").arg(a->name, type, a + 1 < f.args.end() ? ", " : "")); + noTypeArgs.append(QString("%1%3").arg(passAlong, a + 1 < f.args.end() ? ", " : "")); + } + } + if (f.type.isComplex()) { + r << QString(R"( +#[no_mangle] +pub unsafe extern "C" fn %1_%2(ptr: *%3 %4%7, d: *mut c_void, set: fn(*mut c_void, %5)) { + let data = (&%6*ptr).%2(%8); + set(d, (&data).into()); +} +)").arg(lcname, f.name, f.mut ? "mut" : "const", o.name, f.type.name, f.mut ? "mut " : "", argList, noTypeArgs); + + } else { + r << QString(R"( +#[no_mangle] +pub unsafe extern "C" fn %1_%2(ptr: *%3 %4%7) -> %5 { + (&%6*ptr).%2(%8) +} +)").arg(lcname, f.name, f.mut ? "mut" : "const", o.name, f.type.rustType, f.mut ? "mut " : "", argList, noTypeArgs); + } + } if (o.type == ObjectType::List) { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_row_count(ptr: *const %1) -> c_int { (&*ptr).row_count() as c_int } #[no_mangle] pub unsafe extern "C" fn %2_insert_rows(ptr: *mut %1, row: c_int, count: c_int) -> bool { (&mut *ptr).insert_rows(row as usize, count as usize) } #[no_mangle] pub unsafe extern "C" fn %2_remove_rows(ptr: *mut %1, row: c_int, count: c_int) -> bool { (&mut *ptr).remove_rows(row as usize, count as usize) } #[no_mangle] pub unsafe extern "C" fn %2_can_fetch_more(ptr: *const %1) -> bool { (&*ptr).can_fetch_more() } #[no_mangle] pub unsafe extern "C" fn %2_fetch_more(ptr: *mut %1) { (&mut *ptr).fetch_more() } #[no_mangle] pub unsafe extern "C" fn %2_sort( ptr: *mut %1, column: u8, order: SortOrder, ) { (&mut *ptr).sort(column, order) } )").arg(o.name, lcname); } else if (o.type == ObjectType::Tree) { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_row_count( ptr: *const %1, item: usize, valid: bool, ) -> c_int { if valid { (&*ptr).row_count(Some(item)) as c_int } else { (&*ptr).row_count(None) as c_int } } #[no_mangle] pub unsafe extern "C" fn %2_can_fetch_more( ptr: *const %1, item: usize, valid: bool, ) -> bool { if valid { (&*ptr).can_fetch_more(Some(item)) } else { (&*ptr).can_fetch_more(None) } } #[no_mangle] pub unsafe extern "C" fn %2_fetch_more(ptr: *mut %1, item: usize, valid: bool) { if valid { (&mut *ptr).fetch_more(Some(item)) } else { (&mut *ptr).fetch_more(None) } } #[no_mangle] pub unsafe extern "C" fn %2_sort( ptr: *mut %1, column: u8, order: SortOrder ) { (&mut *ptr).sort(column, order) } #[no_mangle] pub unsafe extern "C" fn %2_index( ptr: *const %1, item: usize, valid: bool, row: c_int, ) -> usize { if !valid { (&*ptr).index(None, row as usize) } else { (&*ptr).index(Some(item), row as usize) } } #[no_mangle] pub unsafe extern "C" fn %2_parent(ptr: *const %1, index: usize) -> QModelIndex { if let Some(parent) = (&*ptr).parent(index) { QModelIndex { row: (&*ptr).row(parent) as c_int, internal_id: parent, } } else { QModelIndex { row: -1, internal_id: 0, } } } #[no_mangle] pub unsafe extern "C" fn %2_row(ptr: *const %1, item: usize) -> c_int { (&*ptr).row(item) as c_int } )").arg(o.name, lcname); } if (o.type != ObjectType::Object) { QString indexDecl = ", row: c_int"; QString index = "row as usize"; if (o.type == ObjectType::Tree) { indexDecl = ", item: usize"; index = "item"; } for (auto ip: o.itemProperties) { if (ip.type.isComplex() && !ip.optional) { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_data_%3( ptr: *const %1%5, d: *mut c_void, set: fn(*mut c_void, %4), ) { let data = (&*ptr).%3(%6); set(d, (%7data).into()); } )").arg(o.name, lcname, snakeCase(ip.name), ip.type.name, indexDecl, index, ip.rustByValue ?"&" :""); } else if (ip.type.isComplex()) { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_data_%3( ptr: *const %1%5, d: *mut c_void, set: fn(*mut c_void, %4), ) { let data = (&*ptr).%3(%6); if let Some(data) = data { set(d, %4::from(&data)); } } )").arg(o.name, lcname, snakeCase(ip.name), ip.type.name, indexDecl, index); } else { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_data_%3(ptr: *const %1%5) -> %4 { (&*ptr).%3(%6).into() } )").arg(o.name, lcname, snakeCase(ip.name), rustCType(ip), indexDecl, index); } if (ip.write) { QString val = "v"; QString type = ip.type.rustType; if (ip.type.isComplex()) { val = val + ".convert()"; type = ip.type.name == "QString" ? "QStringIn" : ip.type.name; } if (ip.optional) { val = "Some(" + val + ")"; } r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_set_data_%3( ptr: *mut %1%4, v: %6, ) -> bool { (&mut *ptr).set_%3(%5, %7) } )").arg(o.name, lcname, snakeCase(ip.name), indexDecl, index, type, val); } if (ip.write && ip.optional) { r << QString(R"( #[no_mangle] pub unsafe extern "C" fn %2_set_data_%3_none(ptr: *mut %1, row: c_int%4) -> bool { (&mut *ptr).set_%3(%5row as usize, None) } )").arg(o.name, lcname, snakeCase(ip.name), indexDecl, index); } } } } QString rustFile(const QDir rustdir, const QString& module) { QDir src(rustdir.absoluteFilePath("src")); QString modulePath = src.absoluteFilePath(module + "/mod.rs"); if (QFile::exists(modulePath)) { return modulePath; } return src.absoluteFilePath(module + ".rs"); } void writeRustTypes(const Configuration& conf, QTextStream& r) { bool hasOption = false; bool hasString = false; bool hasStringWrite = false; bool hasByteArray = false; bool hasListOrTree = false; for (auto o: conf.objects) { hasListOrTree |= o.type != ObjectType::Object; for (auto p: o.properties) { hasOption |= p.optional; hasString |= p.type.type == BindingType::QString; hasStringWrite |= p.type.type == BindingType::QString && p.write; hasByteArray |= p.type.type == BindingType::QByteArray; } for (auto p: o.itemProperties) { hasOption |= p.optional; hasString |= p.type.type == BindingType::QString; hasByteArray |= p.type.type == BindingType::QByteArray; } } if (hasOption || hasListOrTree) { r << R"( #[repr(C)] pub struct COption { data: T, some: bool, } impl From> for COption where T: Default, { fn from(t: Option) -> COption { if let Some(v) = t { COption { data: v, some: true, } } else { COption { data: T::default(), some: false, } } } } )"; } if (hasString) { r << R"( #[repr(C)] pub struct QString { data: *const uint8_t, len: c_int, } #[repr(C)] pub struct QStringIn { data: *const uint16_t, len: c_int, } impl QStringIn { fn convert(&self) -> String { let data = unsafe { slice::from_raw_parts(self.data, self.len as usize) }; String::from_utf16_lossy(data) } } impl<'a> From<&'a str> for QString { fn from(string: &'a str) -> QString { QString { len: string.len() as c_int, data: string.as_ptr(), } } } impl<'a> From<&'a String> for QString { fn from(string: &'a String) -> QString { QString { len: string.len() as c_int, data: string.as_ptr(), } } } )"; } if (hasByteArray) { r << R"( #[repr(C)] pub struct QByteArray { data: *const uint8_t, len: c_int, } impl QByteArray { fn convert(&self) -> Vec { let data = unsafe { slice::from_raw_parts(self.data, self.len as usize) }; Vec::from(data) } } impl<'a> From<&'a [u8]> for QByteArray { fn from(value: &'a [u8]) -> QByteArray { QByteArray { len: value.len() as c_int, data: value.as_ptr(), } } } )"; } if (hasListOrTree) { r << R"( #[repr(C)] pub enum SortOrder { Ascending = 0, Descending = 1, } #[repr(C)] pub struct QModelIndex { row: c_int, internal_id: usize, } )"; } } void writeRustInterface(const Configuration& conf) { DifferentFileWriter w(rustFile(conf.rustdir, conf.interfaceModule)); QTextStream r(&w.buffer); r << QString(R"(/* generated by rust_qt_binding_generator */ #![allow(unknown_lints)] #![allow(mutex_atomic, needless_pass_by_value)] use libc::{c_int, c_void, uint8_t, uint16_t}; use std::slice; use std::sync::{Arc, Mutex}; use std::ptr::null; use %1::*; )").arg(conf.implementationModule); writeRustTypes(conf, r); for (auto object: conf.objects) { writeRustInterfaceObject(r, object, conf); } } void writeRustImplementationObject(QTextStream& r, const Object& o) { const QString lcname(snakeCase(o.name)); if (o.type != ObjectType::Object) { r << "#[derive(Default, Clone)]\n"; r << QString("struct %1Item {\n").arg(o.name); for (auto ip: o.itemProperties) { const QString lc(snakeCase(ip.name)); r << QString(" %1: %2,\n").arg(lc, ip.type.rustType); } r << "}\n\n"; } QString modelStruct = ""; r << QString("pub struct %1 {\n emit: %1Emitter,\n").arg((o.name)); if (o.type == ObjectType::List) { modelStruct = ", model: " + o.name + "List"; r << QString(" model: %1List,\n").arg(o.name); } else if (o.type == ObjectType::Tree) { modelStruct = ", model: " + o.name + "Tree"; r << QString(" model: %1Tree,\n").arg(o.name); } for (const Property& p: o.properties) { const QString lc(snakeCase(p.name)); r << QString(" %1: %2,\n").arg(lc, rustType(p)); } if (o.type != ObjectType::Object) { r << QString(" list: Vec<%1Item>,\n").arg(o.name); } r << "}\n\n"; for (const Property& p: o.properties) { if (p.type.type == BindingType::Object) { modelStruct += ", " + p.name + ": " + p.type.name; } } r << QString(R"(impl %1Trait for %1 { fn new(emit: %1Emitter%2) -> %1 { %1 { emit: emit, )").arg(o.name, modelStruct); if (o.type != ObjectType::Object) { r << QString(" model: model,\n"); } for (const Property& p: o.properties) { const QString lc(snakeCase(p.name)); if (p.type.type == BindingType::Object) { r << QString(" %1: %1,\n").arg(lc); } else { r << QString(" %1: %2,\n").arg(lc, rustTypeInit(p)); } } if (o.type != ObjectType::Object) { r << QString(" list: vec![%1Item::default(); 10],\n") .arg(o.name); } r << QString(R"( } } fn emit(&self) -> &%1Emitter { &self.emit } )").arg(o.name); for (const Property& p: o.properties) { const QString lc(snakeCase(p.name)); if (p.type.type == BindingType::Object) { r << QString(R"( fn %1(&self) -> &%2 { &self.%1 } fn %1_mut(&mut self) -> &mut %2 { &mut self.%1 } )").arg(lc, rustReturnType(p)); } else { r << QString(" fn %1(&self) -> %2 {\n").arg(lc, rustReturnType(p)); if (p.type.isComplex()) { if (p.optional) { /* if (rustType(p) == "Option") { r << QString(" self.%1.as_ref().map(|p|p.as_str())\n").arg(lc); } else { } */ r << QString(" self.%1.as_ref().map(|p|&p[..])\n").arg(lc); } else { r << QString(" &self.%1\n").arg(lc); } } else { r << QString(" self.%1\n").arg(lc); } r << " }\n"; if (p.write) { r << QString(R"( fn set_%1(&mut self, value: %2) { self.%1 = value; self.emit.%1_changed(); } )").arg(lc, rustType(p)); } } } if (o.type == ObjectType::List) { r << " fn row_count(&self) -> usize {\n self.list.len()\n }\n"; } else if (o.type == ObjectType::Tree) { r << R"( fn row_count(&self, item: Option) -> usize { self.list.len() } fn index(&self, item: Option, row: usize) -> usize { 0 } fn parent(&self, item: usize) -> Option { None } fn row(&self, item: usize) -> usize { item } )"; } if (o.type != ObjectType::Object) { QString index; if (o.type == ObjectType::Tree) { index = ", item: usize"; } for (auto ip: o.itemProperties) { const QString lc(snakeCase(ip.name)); r << QString(" fn %1(&self, item: usize) -> %2 {\n") .arg(lc, rustReturnType(ip)); if (ip.type.isComplex()) { r << " &self.list[item]." << lc << "\n"; } else { r << " self.list[item]." << lc << "\n"; } r << " }\n"; if (ip.write) { r << QString(" fn set_%1(&mut self, item: usize, v: %2) -> bool {\n") .arg(snakeCase(ip.name), rustType(ip)); r << " self.list[item]." << lc << " = v;\n"; r << " true\n"; r << " }\n"; } } } r << "}\n\n"; } void writeRustImplementation(const Configuration& conf) { DifferentFileWriter w(rustFile(conf.rustdir, conf.implementationModule), conf.overwriteImplementation); QTextStream r(&w.buffer); r << QString(R"(#![allow(unused_imports)] #![allow(unused_variables)] #![allow(dead_code)] use %1::*; )").arg(conf.interfaceModule); for (auto object: conf.objects) { writeRustImplementationObject(r, object); } } diff --git a/src/structs.h b/src/structs.h index 58c5fb9..69e105b 100644 --- a/src/structs.h +++ b/src/structs.h @@ -1,159 +1,173 @@ /* * Copyright 2017 Jos van den Oever * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License or (at your option) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #include #include #include enum class ObjectType { Object, List, Tree }; enum class BindingType { Bool, UChar, Int, UInt, ULongLong, Float, QString, QByteArray, Object, + Void, }; struct BindingTypeProperties { BindingType type; QString name; QString cppSetType; QString cSetType; QString rustType; QString rustTypeInit; bool isComplex() const { return name.startsWith("Q"); } bool operator==(const BindingTypeProperties& other) { return type == other.type && name == other.name && cppSetType == other.cppSetType && cSetType == other.cSetType && rustType == other.rustType && rustTypeInit == other.rustTypeInit; } }; struct Property { QString name; BindingTypeProperties type; bool write; bool optional; bool rustByValue; }; +struct Argument { + QString name; + BindingTypeProperties type; +}; + +struct Function { + QString name; + BindingTypeProperties type; + QList args; + bool mut; +}; + struct ItemProperty { QString name; BindingTypeProperties type; bool write; bool optional; bool rustByValue; QList> roles; }; struct Object { QString name; ObjectType type; QList properties; QList itemProperties; + QList functions; int columnCount; bool containsObject() { for (auto p: properties) { if (p.type.type == BindingType::Object) { return true; } } return false; } }; struct Configuration { QFileInfo hFile; QFileInfo cppFile; QDir rustdir; QString interfaceModule; QString implementationModule; QList objects; bool overwriteImplementation; const Object& findObject(const QString& name) const { for (auto& o: objects) { if (o.name == name) { return o; } } QTextStream err(stderr); err << QCoreApplication::translate("main", "Cannot find type %1.\n").arg(name); err.flush(); exit(1); } QList types() const { QList ops; for (auto o: objects) { for (auto ip: o.properties) { if (!ops.contains(ip.type.name)) { ops.append(ip.type.name); } } for (auto ip: o.itemProperties) { if (!ops.contains(ip.type.name)) { ops.append(ip.type.name); } } } return ops; } QList optionalTypes() const { QList ops; for (auto o: objects) { for (auto ip: o.itemProperties) { if (ip.optional && !ops.contains(ip.type.name)) { ops.append(ip.type.name); } } if (o.type != ObjectType::Object && !ops.contains("quintptr")) { ops.append("quintptr"); } } return ops; } bool hasListOrTree() const { for (auto o: objects) { if (o.type == ObjectType::List || o.type == ObjectType::Tree) { return true; } } return false; } }; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 72881fd..3d2c88f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,69 +1,70 @@ SET(GENERATOR "${CMAKE_BINARY_DIR}/src/rust_qt_binding_generator") include_directories("${CMAKE_CURRENT_BINARY_DIR}") add_custom_target("clean-rust") function(rust_test NAME DIRECTORY) set(SRC "${CMAKE_CURRENT_SOURCE_DIR}") set(DIR "${SRC}/${DIRECTORY}") add_custom_command( OUTPUT "${DIR}/src/interface.rs" "${DIR}/src/implementation.rs" "${SRC}/${NAME}_rust.h" # if the cpp file is marked GENERATED, CMake will not check it for moc # "${SRC}/${NAME}_rust.cpp" COMMAND "${GENERATOR}" --overwrite-implementation "${SRC}/${NAME}.json" MAIN_DEPENDENCY "${NAME}.json" DEPENDS rust_qt_binding_generator ) add_custom_command( OUTPUT "${DIR}/${RUST_TARGET_DIR}/librust.a" COMMAND ${Cargo_EXECUTABLE} build ${RUST_BUILD_FLAG} DEPENDS "${DIR}/src/lib.rs" "${DIR}/src/implementation.rs" "${DIR}/src/interface.rs" WORKING_DIRECTORY "${DIR}" ) add_custom_target("test_${DIRECTORY}" DEPENDS "${DIR}/${RUST_TARGET_DIR}/librust.a") add_executable("${NAME}" "${NAME}.cpp" "${NAME}_rust.cpp" "${NAME}_rust.h") set_target_properties("${NAME}" PROPERTIES CXX_STANDARD 11 CXX_STANDARD_REQUIRED ON ) add_dependencies("${NAME}" "test_${DIRECTORY}") target_link_libraries("${NAME}" Qt5::Core Qt5::Test "${DIR}/${RUST_TARGET_DIR}/librust.a" Threads::Threads ${DL_LIBRARY} ) set_property(TARGET ${NAME} APPEND PROPERTY AUTOGEN_TARGET_DEPENDS "${SRC}/${NAME}_rust.h" APPEND PROPERTY AUTOGEN_TARGET_DEPENDS "${SRC}/${NAME}_rust.cpp") add_test("build_${NAME}" "${CMAKE_COMMAND}" --build ${CMAKE_BINARY_DIR} --target "${NAME}") add_test("${NAME}" "${NAME}") set_tests_properties("${NAME}" PROPERTIES DEPENDS "build_${NAME}") add_custom_command( OUTPUT "clean_${NAME}" COMMAND ${Cargo_EXECUTABLE} clean WORKING_DIRECTORY "${DIR}" ) add_custom_target("clean-${NAME}" DEPENDS "clean_${NAME}") add_dependencies("clean-rust" "clean-${NAME}") endfunction(rust_test) rust_test(test_object rust_object) rust_test(test_object_types rust_object_types) rust_test(test_list rust_list) rust_test(test_tree rust_tree) rust_test(test_objects rust_objects) +rust_test(test_functions rust_functions) diff --git a/tests/rust_functions/Cargo.toml b/tests/rust_functions/Cargo.toml new file mode 100644 index 0000000..c65758c --- /dev/null +++ b/tests/rust_functions/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "rust_functions" +version = "1.0.0" + +[dependencies] +libc = "*" + +[lib] +name = "rust" +crate-type = ["staticlib"] diff --git a/tests/rust_functions/src/implementation.rs b/tests/rust_functions/src/implementation.rs new file mode 100644 index 0000000..cb1cfcc --- /dev/null +++ b/tests/rust_functions/src/implementation.rs @@ -0,0 +1,44 @@ +#![allow(unused_imports)] +#![allow(unused_variables)] +#![allow(dead_code)] +use interface::*; + +pub struct Person { + emit: PersonEmitter, + user_name: String, +} + +impl PersonTrait for Person { + fn new(emit: PersonEmitter) -> Person { + Person { + emit: emit, + user_name: String::new(), + } + } + fn emit(&self) -> &PersonEmitter { + &self.emit + } + fn user_name(&self) -> &str { + &self.user_name + } + fn set_user_name(&mut self, value: String) { + self.user_name = value; + self.emit.user_name_changed(); + } + + fn double_name(&mut self) { + self.user_name = format!("{}{}", self.user_name, self.user_name); + } + + fn greet(&self, name: String) -> String { + format!("Hello {}, my name is {}, how is it going?", name, self.user_name) + } + + fn vowels_in_name(&self) -> u8 { + self.user_name.chars().fold(0, |count, ch| match ch { + 'a'|'e'|'i'|'o'|'u' => count + 1, + _ => count + }) + } +} + diff --git a/tests/rust_functions/src/interface.rs b/tests/rust_functions/src/interface.rs new file mode 100644 index 0000000..1a07de5 --- /dev/null +++ b/tests/rust_functions/src/interface.rs @@ -0,0 +1,129 @@ +/* generated by rust_qt_binding_generator */ +#![allow(unknown_lints)] +#![allow(mutex_atomic, needless_pass_by_value)] +use libc::{c_int, c_void, uint8_t, uint16_t}; +use std::slice; + +use std::sync::{Arc, Mutex}; +use std::ptr::null; + +use implementation::*; + + +#[repr(C)] +pub struct QString { + data: *const uint8_t, + len: c_int, +} + +#[repr(C)] +pub struct QStringIn { + data: *const uint16_t, + len: c_int, +} + +impl QStringIn { + fn convert(&self) -> String { + let data = unsafe { slice::from_raw_parts(self.data, self.len as usize) }; + String::from_utf16_lossy(data) + } +} + +impl<'a> From<&'a str> for QString { + fn from(string: &'a str) -> QString { + QString { + len: string.len() as c_int, + data: string.as_ptr(), + } + } +} + +impl<'a> From<&'a String> for QString { + fn from(string: &'a String) -> QString { + QString { + len: string.len() as c_int, + data: string.as_ptr(), + } + } +} + +pub struct PersonQObject {} + +#[derive(Clone)] +pub struct PersonEmitter { + qobject: Arc>, + user_name_changed: fn(*const PersonQObject), +} + +unsafe impl Send for PersonEmitter {} + +impl PersonEmitter { + fn clear(&self) { + *self.qobject.lock().unwrap() = null(); + } + pub fn user_name_changed(&self) { + let ptr = *self.qobject.lock().unwrap(); + if !ptr.is_null() { + (self.user_name_changed)(ptr); + } + } +} + +pub trait PersonTrait { + fn new(emit: PersonEmitter) -> Self; + fn emit(&self) -> &PersonEmitter; + fn user_name(&self) -> &str; + fn set_user_name(&mut self, value: String); + fn double_name(&mut self) -> (); + fn greet(&self, Name: String) -> String; + fn vowels_in_name(&self) -> u8; +} + +#[no_mangle] +pub extern "C" fn person_new( + person: *mut PersonQObject, + user_name_changed: fn(*const PersonQObject), +) -> *mut Person { + let person_emit = PersonEmitter { + qobject: Arc::new(Mutex::new(person)), + user_name_changed: user_name_changed, + }; + let d_person = Person::new(person_emit); + Box::into_raw(Box::new(d_person)) +} + +#[no_mangle] +pub unsafe extern "C" fn person_free(ptr: *mut Person) { + Box::from_raw(ptr).emit().clear(); +} + +#[no_mangle] +pub unsafe extern "C" fn person_user_name_get( + ptr: *const Person, + p: *mut c_void, + set: fn(*mut c_void, QString), +) { + let data = (&*ptr).user_name(); + set(p, data.into()); +} + +#[no_mangle] +pub unsafe extern "C" fn person_user_name_set(ptr: *mut Person, v: QStringIn) { + (&mut *ptr).set_user_name(v.convert()); +} + +#[no_mangle] +pub unsafe extern "C" fn person_double_name(ptr: *mut Person) -> () { + (&mut *ptr).double_name() +} + +#[no_mangle] +pub unsafe extern "C" fn person_greet(ptr: *const Person, Name: QStringIn, d: *mut c_void, set: fn(*mut c_void, QString)) { + let data = (&*ptr).greet(Name.convert()); + set(d, (&data).into()); +} + +#[no_mangle] +pub unsafe extern "C" fn person_vowels_in_name(ptr: *const Person) -> u8 { + (&*ptr).vowels_in_name() +} diff --git a/tests/rust_functions/src/lib.rs b/tests/rust_functions/src/lib.rs new file mode 100644 index 0000000..d7eb847 --- /dev/null +++ b/tests/rust_functions/src/lib.rs @@ -0,0 +1,4 @@ +extern crate libc; + +pub mod interface; +mod implementation; diff --git a/tests/test_functions.cpp b/tests/test_functions.cpp new file mode 100644 index 0000000..373f6fc --- /dev/null +++ b/tests/test_functions.cpp @@ -0,0 +1,72 @@ +/* + * Copyright 2017 Jos van den Oever + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License or (at your option) version 3 or any later version + * accepted by the membership of KDE e.V. (or its successor approved + * by the membership of KDE e.V.), which shall act as a proxy + * defined in Section 14 of version 3 of the license. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "test_functions_rust.h" +#include +#include + +class TestRustObject : public QObject +{ + Q_OBJECT +private slots: + void testConstructor(); + void testStringFunction(); + void testSimpleFunction(); + void testVoidFunction(); +}; + +void TestRustObject::testConstructor() +{ + Person person; +} + +void TestRustObject::testSimpleFunction() +{ + // GIVEN + Person person; + person.setUserName("Konqi"); + + // THEN + QCOMPARE((int)person.vowels_in_name(), 2); +} + +void TestRustObject::testVoidFunction() +{ + // GIVEN + Person person; + person.setUserName("Konqi"); + + // THEN + person.double_name(); + QCOMPARE(person.userName(), QString("KonqiKonqi")); +} + +void TestRustObject::testStringFunction() +{ + // GIVEN + Person person; + person.setUserName("Konqi"); + + // THEN + QCOMPARE(person.greet("John"), QString("Hello John, my name is Konqi, how is it going?")); +} + +QTEST_MAIN(TestRustObject) +#include "test_functions.moc" diff --git a/tests/test_functions.json b/tests/test_functions.json new file mode 100644 index 0000000..b92cfae --- /dev/null +++ b/tests/test_functions.json @@ -0,0 +1,40 @@ +{ + "cppFile": "test_functions_rust.cpp", + "rust": { + "dir": "rust_functions", + "interfaceModule": "interface", + "implementationModule": "implementation" + }, + "objects": { + "Person": { + "type": "Object", + "properties": { + "userName": { + "type": "QString", + "write": true + } + }, + "functions": { + "greet": { + "return": "QString", + "mut": false, + "arguments": [ + { + "name": "Name", + "type": "QString" + } + ] + }, + "double_name": { + "return": "void", + "mut": true, + "arguments": [] + }, + "vowels_in_name": { + "return": "quint8", + "arguments": [] + } + } + } + } +} diff --git a/tests/test_functions_rust.cpp b/tests/test_functions_rust.cpp new file mode 100644 index 0000000..b07d8b8 --- /dev/null +++ b/tests/test_functions_rust.cpp @@ -0,0 +1,80 @@ +/* generated by rust_qt_binding_generator */ +#include "test_functions_rust.h" + +namespace { + + struct qstring_t { + private: + const void* data; + int len; + public: + qstring_t(const QString& v): + data(static_cast(v.utf16())), + len(v.size()) { + } + operator QString() const { + return QString::fromUtf8(static_cast(data), len); + } + }; + typedef void (*qstring_set)(QString*, qstring_t*); + void set_qstring(QString* v, qstring_t* val) { + *v = *val; + } + inline void personUserNameChanged(Person* o) + { + emit o->userNameChanged(); + } +} +extern "C" { + Person::Private* person_new(Person*, void (*)(Person*)); + void person_free(Person::Private*); + void person_user_name_get(const Person::Private*, QString*, qstring_set); + void person_user_name_set(Person::Private*, qstring_t); + void person_double_name(Person::Private*); + qstring_t person_greet(const Person::Private*, qstring_t, QString*, qstring_set); + quint8 person_vowels_in_name(const Person::Private*); +}; + +Person::Person(bool /*owned*/, QObject *parent): + QObject(parent), + m_d(0), + m_ownsPrivate(false) +{ +} + +Person::Person(QObject *parent): + QObject(parent), + m_d(person_new(this, + personUserNameChanged)), + m_ownsPrivate(true) +{ +} + +Person::~Person() { + if (m_ownsPrivate) { + person_free(m_d); + } +} +QString Person::userName() const +{ + QString v; + person_user_name_get(m_d, &v, set_qstring); + return v; +} +void Person::setUserName(const QString& v) { + person_user_name_set(m_d, v); +} +void Person::double_name() +{ + return person_double_name(m_d); +} +QString Person::greet(const QString& Name) const +{ + QString s; + person_greet(m_d, Name, &s, set_qstring); + return s; +} +quint8 Person::vowels_in_name() const +{ + return person_vowels_in_name(m_d); +} diff --git a/tests/test_functions_rust.h b/tests/test_functions_rust.h new file mode 100644 index 0000000..9096f19 --- /dev/null +++ b/tests/test_functions_rust.h @@ -0,0 +1,31 @@ +/* generated by rust_qt_binding_generator */ +#ifndef TEST_FUNCTIONS_RUST_H +#define TEST_FUNCTIONS_RUST_H + +#include +#include + +class Person; + +class Person : public QObject +{ + Q_OBJECT +public: + class Private; +private: + Private * m_d; + bool m_ownsPrivate; + Q_PROPERTY(QString userName READ userName WRITE setUserName NOTIFY userNameChanged FINAL) + explicit Person(bool owned, QObject *parent); +public: + explicit Person(QObject *parent = nullptr); + ~Person(); + QString userName() const; + void setUserName(const QString& v); + Q_INVOKABLE void double_name(); + Q_INVOKABLE QString greet(const QString& Name) const; + Q_INVOKABLE quint8 vowels_in_name() const; +signals: + void userNameChanged(); +}; +#endif // TEST_FUNCTIONS_RUST_H