diff --git a/demo/src/Bindings.cpp b/demo/src/Bindings.cpp index 4585441..10ee4f8 100644 --- a/demo/src/Bindings.cpp +++ b/demo/src/Bindings.cpp @@ -1,1494 +1,1498 @@ /* generated by rust_qt_binding_generator */ #include "Bindings.h" namespace { struct option_quintptr { public: quintptr value; bool some; operator QVariant() const { if (some) { return QVariant::fromValue(value); } return QVariant(); } }; static_assert(std::is_pod::value, "option_quintptr must be a POD type."); struct option_quint64 { public: quint64 value; bool some; operator QVariant() const { if (some) { return QVariant::fromValue(value); } return QVariant(); } }; static_assert(std::is_pod::value, "option_quint64 must be a POD type."); typedef void (*qstring_set)(QString* val, const char* utf8, int nbytes); void set_qstring(QString* val, const char* utf8, int nbytes) { *val = QString::fromUtf8(utf8, nbytes); } typedef void (*qbytearray_set)(QByteArray* val, const char* bytes, int nbytes); void set_qbytearray(QByteArray* v, const char* bytes, int nbytes) { - v->truncate(0); - v->append(bytes, nbytes); + if (v->isNull() && nbytes == 0) { + *v = QByteArray(bytes, nbytes); + } else { + v->truncate(0); + v->append(bytes, nbytes); + } } struct qmodelindex_t { int row; quintptr id; }; inline void fibonacciInputChanged(Fibonacci* o) { emit o->inputChanged(); } inline void fibonacciResultChanged(Fibonacci* o) { emit o->resultChanged(); } inline void fileSystemTreePathChanged(FileSystemTree* o) { emit o->pathChanged(); } inline void processesActiveChanged(Processes* o) { emit o->activeChanged(); } } extern "C" { Demo::Private* demo_new(Demo*, Fibonacci*, void (*)(Fibonacci*), void (*)(Fibonacci*), FibonacciList*, void (*)(const FibonacciList*), void (*)(FibonacciList*, quintptr, quintptr), void (*)(FibonacciList*), void (*)(FibonacciList*), void (*)(FibonacciList*, int, int), void (*)(FibonacciList*), void (*)(FibonacciList*, int, int), void (*)(FibonacciList*), FileSystemTree*, void (*)(FileSystemTree*), void (*)(const FileSystemTree*, quintptr, bool), void (*)(FileSystemTree*, quintptr, quintptr), void (*)(FileSystemTree*), void (*)(FileSystemTree*), void (*)(FileSystemTree*, option_quintptr, int, int), void (*)(FileSystemTree*), void (*)(FileSystemTree*, option_quintptr, int, int), void (*)(FileSystemTree*), Processes*, void (*)(Processes*), void (*)(const Processes*, quintptr, bool), void (*)(Processes*, quintptr, quintptr), void (*)(Processes*), void (*)(Processes*), void (*)(Processes*, option_quintptr, int, int), void (*)(Processes*), void (*)(Processes*, option_quintptr, int, int), void (*)(Processes*), TimeSeries*, void (*)(const TimeSeries*), void (*)(TimeSeries*, quintptr, quintptr), void (*)(TimeSeries*), void (*)(TimeSeries*), void (*)(TimeSeries*, int, int), void (*)(TimeSeries*), void (*)(TimeSeries*, int, int), void (*)(TimeSeries*)); void demo_free(Demo::Private*); Fibonacci::Private* demo_fibonacci_get(const Demo::Private*); FibonacciList::Private* demo_fibonacci_list_get(const Demo::Private*); FileSystemTree::Private* demo_file_system_tree_get(const Demo::Private*); Processes::Private* demo_processes_get(const Demo::Private*); TimeSeries::Private* demo_time_series_get(const Demo::Private*); }; extern "C" { Fibonacci::Private* fibonacci_new(Fibonacci*, void (*)(Fibonacci*), void (*)(Fibonacci*)); void fibonacci_free(Fibonacci::Private*); quint32 fibonacci_input_get(const Fibonacci::Private*); void fibonacci_input_set(Fibonacci::Private*, uint); quint64 fibonacci_result_get(const Fibonacci::Private*); }; extern "C" { quint64 fibonacci_list_data_fibonacci_number(const FibonacciList::Private*, int); quint64 fibonacci_list_data_row(const FibonacciList::Private*, int); void fibonacci_list_sort(FibonacciList::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder); int fibonacci_list_row_count(const FibonacciList::Private*); bool fibonacci_list_insert_rows(FibonacciList::Private*, int, int); bool fibonacci_list_remove_rows(FibonacciList::Private*, int, int); bool fibonacci_list_can_fetch_more(const FibonacciList::Private*); void fibonacci_list_fetch_more(FibonacciList::Private*); } int FibonacciList::columnCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : 2; } bool FibonacciList::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int FibonacciList::rowCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : fibonacci_list_row_count(m_d); } bool FibonacciList::insertRows(int row, int count, const QModelIndex &parent) { return fibonacci_list_insert_rows(m_d, row, count); } bool FibonacciList::removeRows(int row, int count, const QModelIndex &parent) { return fibonacci_list_remove_rows(m_d, row, count); } QModelIndex FibonacciList::index(int row, int column, const QModelIndex &parent) const { if (!parent.isValid() && row >= 0 && row < rowCount(parent) && column >= 0 && column < 2) { return createIndex(row, column, (quintptr)row); } return QModelIndex(); } QModelIndex FibonacciList::parent(const QModelIndex &) const { return QModelIndex(); } bool FibonacciList::canFetchMore(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : fibonacci_list_can_fetch_more(m_d); } void FibonacciList::fetchMore(const QModelIndex &parent) { if (!parent.isValid()) { fibonacci_list_fetch_more(m_d); } } void FibonacciList::sort(int column, Qt::SortOrder order) { fibonacci_list_sort(m_d, column, order); } Qt::ItemFlags FibonacciList::flags(const QModelIndex &i) const { auto flags = QAbstractItemModel::flags(i); return flags; } QVariant FibonacciList::fibonacciNumber(int row) const { QVariant v; v.setValue(fibonacci_list_data_fibonacci_number(m_d, row)); return v; } QVariant FibonacciList::row(int row) const { QVariant v; v.setValue(fibonacci_list_data_row(m_d, row)); return v; } QVariant FibonacciList::data(const QModelIndex &index, int role) const { Q_ASSERT(rowCount(index.parent()) > index.row()); switch (index.column()) { case 0: switch (role) { case Qt::UserRole + 0: return fibonacciNumber(index.row()); case Qt::DisplayRole: case Qt::UserRole + 1: return row(index.row()); } case 1: switch (role) { case Qt::DisplayRole: case Qt::UserRole + 0: return fibonacciNumber(index.row()); } } return QVariant(); } QHash FibonacciList::roleNames() const { QHash names = QAbstractItemModel::roleNames(); names.insert(Qt::UserRole + 0, "fibonacciNumber"); names.insert(Qt::UserRole + 1, "row"); return names; } QVariant FibonacciList::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 FibonacciList::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; } extern "C" { FibonacciList::Private* fibonacci_list_new(FibonacciList*, void (*)(const FibonacciList*), void (*)(FibonacciList*, quintptr, quintptr), void (*)(FibonacciList*), void (*)(FibonacciList*), void (*)(FibonacciList*, int, int), void (*)(FibonacciList*), void (*)(FibonacciList*, int, int), void (*)(FibonacciList*)); void fibonacci_list_free(FibonacciList::Private*); }; extern "C" { void file_system_tree_data_file_icon(const FileSystemTree::Private*, quintptr, QByteArray*, qbytearray_set); void file_system_tree_data_file_name(const FileSystemTree::Private*, quintptr, QString*, qstring_set); void file_system_tree_data_file_path(const FileSystemTree::Private*, quintptr, QString*, qstring_set); qint32 file_system_tree_data_file_permissions(const FileSystemTree::Private*, quintptr); option_quint64 file_system_tree_data_file_size(const FileSystemTree::Private*, quintptr); qint32 file_system_tree_data_file_type(const FileSystemTree::Private*, quintptr); void file_system_tree_sort(FileSystemTree::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder); int file_system_tree_row_count(const FileSystemTree::Private*, quintptr, bool); bool file_system_tree_can_fetch_more(const FileSystemTree::Private*, quintptr, bool); void file_system_tree_fetch_more(FileSystemTree::Private*, quintptr, bool); quintptr file_system_tree_index(const FileSystemTree::Private*, quintptr, bool, int); qmodelindex_t file_system_tree_parent(const FileSystemTree::Private*, quintptr); int file_system_tree_row(const FileSystemTree::Private*, quintptr); } int FileSystemTree::columnCount(const QModelIndex &) const { return 5; } bool FileSystemTree::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int FileSystemTree::rowCount(const QModelIndex &parent) const { if (parent.isValid() && parent.column() != 0) { return 0; } return file_system_tree_row_count(m_d, parent.internalId(), parent.isValid()); } bool FileSystemTree::insertRows(int, int, const QModelIndex &) { return false; // not supported yet } bool FileSystemTree::removeRows(int, int, const QModelIndex &) { return false; // not supported yet } QModelIndex FileSystemTree::index(int row, int column, const QModelIndex &parent) const { if (row < 0 || column < 0 || column >= 5) { return QModelIndex(); } if (parent.isValid() && parent.column() != 0) { return QModelIndex(); } if (row >= rowCount(parent)) { return QModelIndex(); } const quintptr id = file_system_tree_index(m_d, parent.internalId(), parent.isValid(), row); return createIndex(row, column, id); } QModelIndex FileSystemTree::parent(const QModelIndex &index) const { if (!index.isValid()) { return QModelIndex(); } const qmodelindex_t parent = file_system_tree_parent(m_d, index.internalId()); return parent.row >= 0 ?createIndex(parent.row, 0, parent.id) :QModelIndex(); } bool FileSystemTree::canFetchMore(const QModelIndex &parent) const { if (parent.isValid() && parent.column() != 0) { return false; } return file_system_tree_can_fetch_more(m_d, parent.internalId(), parent.isValid()); } void FileSystemTree::fetchMore(const QModelIndex &parent) { file_system_tree_fetch_more(m_d, parent.internalId(), parent.isValid()); } void FileSystemTree::sort(int column, Qt::SortOrder order) { file_system_tree_sort(m_d, column, order); } Qt::ItemFlags FileSystemTree::flags(const QModelIndex &i) const { auto flags = QAbstractItemModel::flags(i); return flags; } QVariant FileSystemTree::fileIcon(const QModelIndex& index) const { QVariant v; QByteArray b; file_system_tree_data_file_icon(m_d, index.internalId(), &b, set_qbytearray); if (!b.isNull()) v.setValue(b); return v; } QVariant FileSystemTree::fileName(const QModelIndex& index) const { QVariant v; QString s; file_system_tree_data_file_name(m_d, index.internalId(), &s, set_qstring); if (!s.isNull()) v.setValue(s); return v; } QVariant FileSystemTree::filePath(const QModelIndex& index) const { QVariant v; QString s; file_system_tree_data_file_path(m_d, index.internalId(), &s, set_qstring); if (!s.isNull()) v.setValue(s); return v; } QVariant FileSystemTree::filePermissions(const QModelIndex& index) const { QVariant v; v.setValue(file_system_tree_data_file_permissions(m_d, index.internalId())); return v; } QVariant FileSystemTree::fileSize(const QModelIndex& index) const { QVariant v; v = file_system_tree_data_file_size(m_d, index.internalId()); return v; } QVariant FileSystemTree::fileType(const QModelIndex& index) const { QVariant v; v.setValue(file_system_tree_data_file_type(m_d, index.internalId())); return v; } QVariant FileSystemTree::data(const QModelIndex &index, int role) const { Q_ASSERT(rowCount(index.parent()) > index.row()); switch (index.column()) { case 0: switch (role) { case Qt::DecorationRole: case Qt::UserRole + 0: return fileIcon(index); case Qt::DisplayRole: case Qt::UserRole + 1: return fileName(index); case Qt::UserRole + 2: return filePath(index); case Qt::UserRole + 3: return filePermissions(index); case Qt::UserRole + 4: return fileSize(index); case Qt::UserRole + 5: return fileType(index); } case 1: switch (role) { case Qt::DisplayRole: case Qt::UserRole + 4: return fileSize(index); } case 2: switch (role) { case Qt::DisplayRole: case Qt::UserRole + 2: return filePath(index); } case 3: switch (role) { case Qt::DisplayRole: case Qt::UserRole + 3: return filePermissions(index); } case 4: switch (role) { case Qt::DisplayRole: case Qt::UserRole + 5: return fileType(index); } } return QVariant(); } QHash FileSystemTree::roleNames() const { QHash names = QAbstractItemModel::roleNames(); names.insert(Qt::UserRole + 0, "fileIcon"); names.insert(Qt::UserRole + 1, "fileName"); names.insert(Qt::UserRole + 2, "filePath"); names.insert(Qt::UserRole + 3, "filePermissions"); names.insert(Qt::UserRole + 4, "fileSize"); names.insert(Qt::UserRole + 5, "fileType"); return names; } QVariant FileSystemTree::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 FileSystemTree::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; } extern "C" { FileSystemTree::Private* file_system_tree_new(FileSystemTree*, void (*)(FileSystemTree*), void (*)(const FileSystemTree*, quintptr, bool), void (*)(FileSystemTree*, quintptr, quintptr), void (*)(FileSystemTree*), void (*)(FileSystemTree*), void (*)(FileSystemTree*, option_quintptr, int, int), void (*)(FileSystemTree*), void (*)(FileSystemTree*, option_quintptr, int, int), void (*)(FileSystemTree*)); void file_system_tree_free(FileSystemTree::Private*); void file_system_tree_path_get(const FileSystemTree::Private*, QString*, qstring_set); void file_system_tree_path_set(FileSystemTree::Private*, const ushort *str, int len); void file_system_tree_path_set_none(FileSystemTree::Private*); }; extern "C" { void processes_data_cmd(const Processes::Private*, quintptr, QString*, qstring_set); quint8 processes_data_cpu_percentage(const Processes::Private*, quintptr); float processes_data_cpu_usage(const Processes::Private*, quintptr); quint64 processes_data_memory(const Processes::Private*, quintptr); void processes_data_name(const Processes::Private*, quintptr, QString*, qstring_set); uint processes_data_pid(const Processes::Private*, quintptr); uint processes_data_uid(const Processes::Private*, quintptr); void processes_sort(Processes::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder); int processes_row_count(const Processes::Private*, quintptr, bool); bool processes_can_fetch_more(const Processes::Private*, quintptr, bool); void processes_fetch_more(Processes::Private*, quintptr, bool); quintptr processes_index(const Processes::Private*, quintptr, bool, int); qmodelindex_t processes_parent(const Processes::Private*, quintptr); int processes_row(const Processes::Private*, quintptr); } int Processes::columnCount(const QModelIndex &) const { return 3; } bool Processes::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int Processes::rowCount(const QModelIndex &parent) const { if (parent.isValid() && parent.column() != 0) { return 0; } return processes_row_count(m_d, parent.internalId(), parent.isValid()); } bool Processes::insertRows(int, int, const QModelIndex &) { return false; // not supported yet } bool Processes::removeRows(int, int, const QModelIndex &) { return false; // not supported yet } QModelIndex Processes::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 = processes_index(m_d, parent.internalId(), parent.isValid(), row); return createIndex(row, column, id); } QModelIndex Processes::parent(const QModelIndex &index) const { if (!index.isValid()) { return QModelIndex(); } const qmodelindex_t parent = processes_parent(m_d, index.internalId()); return parent.row >= 0 ?createIndex(parent.row, 0, parent.id) :QModelIndex(); } bool Processes::canFetchMore(const QModelIndex &parent) const { if (parent.isValid() && parent.column() != 0) { return false; } return processes_can_fetch_more(m_d, parent.internalId(), parent.isValid()); } void Processes::fetchMore(const QModelIndex &parent) { processes_fetch_more(m_d, parent.internalId(), parent.isValid()); } void Processes::sort(int column, Qt::SortOrder order) { processes_sort(m_d, column, order); } Qt::ItemFlags Processes::flags(const QModelIndex &i) const { auto flags = QAbstractItemModel::flags(i); return flags; } QVariant Processes::cmd(const QModelIndex& index) const { QVariant v; QString s; processes_data_cmd(m_d, index.internalId(), &s, set_qstring); if (!s.isNull()) v.setValue(s); return v; } QVariant Processes::cpuPercentage(const QModelIndex& index) const { QVariant v; v.setValue(processes_data_cpu_percentage(m_d, index.internalId())); return v; } QVariant Processes::cpuUsage(const QModelIndex& index) const { QVariant v; v.setValue(processes_data_cpu_usage(m_d, index.internalId())); return v; } QVariant Processes::memory(const QModelIndex& index) const { QVariant v; v.setValue(processes_data_memory(m_d, index.internalId())); return v; } QVariant Processes::name(const QModelIndex& index) const { QVariant v; QString s; processes_data_name(m_d, index.internalId(), &s, set_qstring); if (!s.isNull()) v.setValue(s); return v; } QVariant Processes::pid(const QModelIndex& index) const { QVariant v; v.setValue(processes_data_pid(m_d, index.internalId())); return v; } QVariant Processes::uid(const QModelIndex& index) const { QVariant v; v.setValue(processes_data_uid(m_d, index.internalId())); return v; } QVariant Processes::data(const QModelIndex &index, int role) const { Q_ASSERT(rowCount(index.parent()) > index.row()); switch (index.column()) { case 0: switch (role) { case Qt::UserRole + 0: return cmd(index); case Qt::UserRole + 1: return cpuPercentage(index); case Qt::UserRole + 2: return cpuUsage(index); case Qt::UserRole + 3: return memory(index); case Qt::DisplayRole: case Qt::UserRole + 4: return name(index); case Qt::ToolTipRole: case Qt::UserRole + 5: return pid(index); case Qt::UserRole + 6: return uid(index); } case 1: switch (role) { case Qt::DisplayRole: case Qt::UserRole + 2: return cpuUsage(index); } case 2: switch (role) { case Qt::DisplayRole: case Qt::UserRole + 3: return memory(index); } } return QVariant(); } QHash Processes::roleNames() const { QHash names = QAbstractItemModel::roleNames(); names.insert(Qt::UserRole + 0, "cmd"); names.insert(Qt::UserRole + 1, "cpuPercentage"); names.insert(Qt::UserRole + 2, "cpuUsage"); names.insert(Qt::UserRole + 3, "memory"); names.insert(Qt::UserRole + 4, "name"); names.insert(Qt::UserRole + 5, "pid"); names.insert(Qt::UserRole + 6, "uid"); return names; } QVariant Processes::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 Processes::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; } extern "C" { Processes::Private* processes_new(Processes*, void (*)(Processes*), void (*)(const Processes*, quintptr, bool), void (*)(Processes*, quintptr, quintptr), void (*)(Processes*), void (*)(Processes*), void (*)(Processes*, option_quintptr, int, int), void (*)(Processes*), void (*)(Processes*, option_quintptr, int, int), void (*)(Processes*)); void processes_free(Processes::Private*); bool processes_active_get(const Processes::Private*); void processes_active_set(Processes::Private*, bool); }; extern "C" { float time_series_data_cos(const TimeSeries::Private*, int); bool time_series_set_data_cos(TimeSeries::Private*, int, float); float time_series_data_sin(const TimeSeries::Private*, int); bool time_series_set_data_sin(TimeSeries::Private*, int, float); float time_series_data_time(const TimeSeries::Private*, int); bool time_series_set_data_time(TimeSeries::Private*, int, float); void time_series_sort(TimeSeries::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder); int time_series_row_count(const TimeSeries::Private*); bool time_series_insert_rows(TimeSeries::Private*, int, int); bool time_series_remove_rows(TimeSeries::Private*, int, int); bool time_series_can_fetch_more(const TimeSeries::Private*); void time_series_fetch_more(TimeSeries::Private*); } int TimeSeries::columnCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : 3; } bool TimeSeries::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int TimeSeries::rowCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : time_series_row_count(m_d); } bool TimeSeries::insertRows(int row, int count, const QModelIndex &parent) { return time_series_insert_rows(m_d, row, count); } bool TimeSeries::removeRows(int row, int count, const QModelIndex &parent) { return time_series_remove_rows(m_d, row, count); } QModelIndex TimeSeries::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 TimeSeries::parent(const QModelIndex &) const { return QModelIndex(); } bool TimeSeries::canFetchMore(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : time_series_can_fetch_more(m_d); } void TimeSeries::fetchMore(const QModelIndex &parent) { if (!parent.isValid()) { time_series_fetch_more(m_d); } } void TimeSeries::sort(int column, Qt::SortOrder order) { time_series_sort(m_d, column, order); } Qt::ItemFlags TimeSeries::flags(const QModelIndex &i) const { auto flags = QAbstractItemModel::flags(i); if (i.column() == 0) { flags |= Qt::ItemIsEditable; } if (i.column() == 1) { flags |= Qt::ItemIsEditable; } if (i.column() == 2) { flags |= Qt::ItemIsEditable; } return flags; } QVariant TimeSeries::cos(int row) const { QVariant v; v.setValue(time_series_data_cos(m_d, row)); return v; } bool TimeSeries::setCos(int row, const QVariant& value) { + bool set = false; if (!value.canConvert(qMetaTypeId())) { return false; } - bool set = false; set = time_series_set_data_cos(m_d, row, value.value()); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } QVariant TimeSeries::sin(int row) const { QVariant v; v.setValue(time_series_data_sin(m_d, row)); return v; } bool TimeSeries::setSin(int row, const QVariant& value) { + bool set = false; if (!value.canConvert(qMetaTypeId())) { return false; } - bool set = false; set = time_series_set_data_sin(m_d, row, value.value()); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } QVariant TimeSeries::time(int row) const { QVariant v; v.setValue(time_series_data_time(m_d, row)); return v; } bool TimeSeries::setTime(int row, const QVariant& value) { + bool set = false; if (!value.canConvert(qMetaTypeId())) { return false; } - bool set = false; set = time_series_set_data_time(m_d, row, value.value()); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } QVariant TimeSeries::data(const QModelIndex &index, int role) const { Q_ASSERT(rowCount(index.parent()) > index.row()); switch (index.column()) { case 0: switch (role) { case Qt::UserRole + 0: return cos(index.row()); case Qt::UserRole + 1: return sin(index.row()); case Qt::DisplayRole: case Qt::EditRole: case Qt::UserRole + 2: return time(index.row()); } case 1: switch (role) { case Qt::DisplayRole: case Qt::EditRole: case Qt::UserRole + 1: return sin(index.row()); } case 2: switch (role) { case Qt::DisplayRole: case Qt::EditRole: case Qt::UserRole + 0: return cos(index.row()); } } return QVariant(); } QHash TimeSeries::roleNames() const { QHash names = QAbstractItemModel::roleNames(); names.insert(Qt::UserRole + 0, "cos"); names.insert(Qt::UserRole + 1, "sin"); names.insert(Qt::UserRole + 2, "time"); return names; } QVariant TimeSeries::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 TimeSeries::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; } bool TimeSeries::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.column() == 0) { if (role == Qt::UserRole + 0) { return setCos(index.row(), value); } if (role == Qt::UserRole + 1) { return setSin(index.row(), value); } if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::UserRole + 2) { return setTime(index.row(), value); } } if (index.column() == 1) { if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::UserRole + 1) { return setSin(index.row(), value); } } if (index.column() == 2) { if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::UserRole + 0) { return setCos(index.row(), value); } } return false; } extern "C" { TimeSeries::Private* time_series_new(TimeSeries*, void (*)(const TimeSeries*), void (*)(TimeSeries*, quintptr, quintptr), void (*)(TimeSeries*), void (*)(TimeSeries*), void (*)(TimeSeries*, int, int), void (*)(TimeSeries*), void (*)(TimeSeries*, int, int), void (*)(TimeSeries*)); void time_series_free(TimeSeries::Private*); }; Demo::Demo(bool /*owned*/, QObject *parent): QObject(parent), m_fibonacci(new Fibonacci(false, this)), m_fibonacciList(new FibonacciList(false, this)), m_fileSystemTree(new FileSystemTree(false, this)), m_processes(new Processes(false, this)), m_timeSeries(new TimeSeries(false, this)), m_d(0), m_ownsPrivate(false) { } Demo::Demo(QObject *parent): QObject(parent), m_fibonacci(new Fibonacci(false, this)), m_fibonacciList(new FibonacciList(false, this)), m_fileSystemTree(new FileSystemTree(false, this)), m_processes(new Processes(false, this)), m_timeSeries(new TimeSeries(false, this)), m_d(demo_new(this, m_fibonacci, fibonacciInputChanged, fibonacciResultChanged, m_fibonacciList, [](const FibonacciList* o) { emit o->newDataReady(QModelIndex()); }, [](FibonacciList* o, quintptr first, quintptr last) { o->dataChanged(o->createIndex(first, 0, first), o->createIndex(last, 1, last)); }, [](FibonacciList* o) { o->beginResetModel(); }, [](FibonacciList* o) { o->endResetModel(); }, [](FibonacciList* o, int first, int last) { o->beginInsertRows(QModelIndex(), first, last); }, [](FibonacciList* o) { o->endInsertRows(); }, [](FibonacciList* o, int first, int last) { o->beginRemoveRows(QModelIndex(), first, last); }, [](FibonacciList* o) { o->endRemoveRows(); } , m_fileSystemTree, fileSystemTreePathChanged, [](const FileSystemTree* o, quintptr id, bool valid) { if (valid) { int row = file_system_tree_row(o->m_d, id); emit o->newDataReady(o->createIndex(row, 0, id)); } else { emit o->newDataReady(QModelIndex()); } }, [](FileSystemTree* o, quintptr first, quintptr last) { quintptr frow = file_system_tree_row(o->m_d, first); quintptr lrow = file_system_tree_row(o->m_d, first); o->dataChanged(o->createIndex(frow, 0, first), o->createIndex(lrow, 4, last)); }, [](FileSystemTree* o) { o->beginResetModel(); }, [](FileSystemTree* o) { o->endResetModel(); }, [](FileSystemTree* o, option_quintptr id, int first, int last) { if (id.some) { int row = file_system_tree_row(o->m_d, id.value); o->beginInsertRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginInsertRows(QModelIndex(), first, last); } }, [](FileSystemTree* o) { o->endInsertRows(); }, [](FileSystemTree* o, option_quintptr id, int first, int last) { if (id.some) { int row = file_system_tree_row(o->m_d, id.value); o->beginRemoveRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginRemoveRows(QModelIndex(), first, last); } }, [](FileSystemTree* o) { o->endRemoveRows(); } , m_processes, processesActiveChanged, [](const Processes* o, quintptr id, bool valid) { if (valid) { int row = processes_row(o->m_d, id); emit o->newDataReady(o->createIndex(row, 0, id)); } else { emit o->newDataReady(QModelIndex()); } }, [](Processes* o, quintptr first, quintptr last) { quintptr frow = processes_row(o->m_d, first); quintptr lrow = processes_row(o->m_d, first); o->dataChanged(o->createIndex(frow, 0, first), o->createIndex(lrow, 2, last)); }, [](Processes* o) { o->beginResetModel(); }, [](Processes* o) { o->endResetModel(); }, [](Processes* o, option_quintptr id, int first, int last) { if (id.some) { int row = processes_row(o->m_d, id.value); o->beginInsertRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginInsertRows(QModelIndex(), first, last); } }, [](Processes* o) { o->endInsertRows(); }, [](Processes* o, option_quintptr id, int first, int last) { if (id.some) { int row = processes_row(o->m_d, id.value); o->beginRemoveRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginRemoveRows(QModelIndex(), first, last); } }, [](Processes* o) { o->endRemoveRows(); } , m_timeSeries, [](const TimeSeries* o) { emit o->newDataReady(QModelIndex()); }, [](TimeSeries* o, quintptr first, quintptr last) { o->dataChanged(o->createIndex(first, 0, first), o->createIndex(last, 2, last)); }, [](TimeSeries* o) { o->beginResetModel(); }, [](TimeSeries* o) { o->endResetModel(); }, [](TimeSeries* o, int first, int last) { o->beginInsertRows(QModelIndex(), first, last); }, [](TimeSeries* o) { o->endInsertRows(); }, [](TimeSeries* o, int first, int last) { o->beginRemoveRows(QModelIndex(), first, last); }, [](TimeSeries* o) { o->endRemoveRows(); } )), m_ownsPrivate(true) { m_fibonacci->m_d = demo_fibonacci_get(m_d); m_fibonacciList->m_d = demo_fibonacci_list_get(m_d); m_fileSystemTree->m_d = demo_file_system_tree_get(m_d); m_processes->m_d = demo_processes_get(m_d); m_timeSeries->m_d = demo_time_series_get(m_d); connect(this->m_fibonacciList, &FibonacciList::newDataReady, this->m_fibonacciList, [this](const QModelIndex& i) { this->m_fibonacciList->fetchMore(i); }, Qt::QueuedConnection); connect(this->m_fileSystemTree, &FileSystemTree::newDataReady, this->m_fileSystemTree, [this](const QModelIndex& i) { this->m_fileSystemTree->fetchMore(i); }, Qt::QueuedConnection); connect(this->m_processes, &Processes::newDataReady, this->m_processes, [this](const QModelIndex& i) { this->m_processes->fetchMore(i); }, Qt::QueuedConnection); connect(this->m_timeSeries, &TimeSeries::newDataReady, this->m_timeSeries, [this](const QModelIndex& i) { this->m_timeSeries->fetchMore(i); }, Qt::QueuedConnection); } Demo::~Demo() { if (m_ownsPrivate) { demo_free(m_d); } } const Fibonacci* Demo::fibonacci() const { return m_fibonacci; } Fibonacci* Demo::fibonacci() { return m_fibonacci; } const FibonacciList* Demo::fibonacciList() const { return m_fibonacciList; } FibonacciList* Demo::fibonacciList() { return m_fibonacciList; } const FileSystemTree* Demo::fileSystemTree() const { return m_fileSystemTree; } FileSystemTree* Demo::fileSystemTree() { return m_fileSystemTree; } const Processes* Demo::processes() const { return m_processes; } Processes* Demo::processes() { return m_processes; } const TimeSeries* Demo::timeSeries() const { return m_timeSeries; } TimeSeries* Demo::timeSeries() { return m_timeSeries; } Fibonacci::Fibonacci(bool /*owned*/, QObject *parent): QObject(parent), m_d(0), m_ownsPrivate(false) { } Fibonacci::Fibonacci(QObject *parent): QObject(parent), m_d(fibonacci_new(this, fibonacciInputChanged, fibonacciResultChanged)), m_ownsPrivate(true) { } Fibonacci::~Fibonacci() { if (m_ownsPrivate) { fibonacci_free(m_d); } } quint32 Fibonacci::input() const { return fibonacci_input_get(m_d); } void Fibonacci::setInput(uint v) { fibonacci_input_set(m_d, v); } quint64 Fibonacci::result() const { return fibonacci_result_get(m_d); } FibonacciList::FibonacciList(bool /*owned*/, QObject *parent): QAbstractItemModel(parent), m_d(0), m_ownsPrivate(false) { initHeaderData(); } FibonacciList::FibonacciList(QObject *parent): QAbstractItemModel(parent), m_d(fibonacci_list_new(this, [](const FibonacciList* o) { emit o->newDataReady(QModelIndex()); }, [](FibonacciList* o, quintptr first, quintptr last) { o->dataChanged(o->createIndex(first, 0, first), o->createIndex(last, 1, last)); }, [](FibonacciList* o) { o->beginResetModel(); }, [](FibonacciList* o) { o->endResetModel(); }, [](FibonacciList* o, int first, int last) { o->beginInsertRows(QModelIndex(), first, last); }, [](FibonacciList* o) { o->endInsertRows(); }, [](FibonacciList* o, int first, int last) { o->beginRemoveRows(QModelIndex(), first, last); }, [](FibonacciList* o) { o->endRemoveRows(); } )), m_ownsPrivate(true) { connect(this, &FibonacciList::newDataReady, this, [this](const QModelIndex& i) { this->fetchMore(i); }, Qt::QueuedConnection); initHeaderData(); } FibonacciList::~FibonacciList() { if (m_ownsPrivate) { fibonacci_list_free(m_d); } } void FibonacciList::initHeaderData() { m_headerData.insert(qMakePair(0, Qt::DisplayRole), QVariant("row")); m_headerData.insert(qMakePair(1, Qt::DisplayRole), QVariant("fibonacciNumber")); } FileSystemTree::FileSystemTree(bool /*owned*/, QObject *parent): QAbstractItemModel(parent), m_d(0), m_ownsPrivate(false) { initHeaderData(); } FileSystemTree::FileSystemTree(QObject *parent): QAbstractItemModel(parent), m_d(file_system_tree_new(this, fileSystemTreePathChanged, [](const FileSystemTree* o, quintptr id, bool valid) { if (valid) { int row = file_system_tree_row(o->m_d, id); emit o->newDataReady(o->createIndex(row, 0, id)); } else { emit o->newDataReady(QModelIndex()); } }, [](FileSystemTree* o, quintptr first, quintptr last) { quintptr frow = file_system_tree_row(o->m_d, first); quintptr lrow = file_system_tree_row(o->m_d, first); o->dataChanged(o->createIndex(frow, 0, first), o->createIndex(lrow, 4, last)); }, [](FileSystemTree* o) { o->beginResetModel(); }, [](FileSystemTree* o) { o->endResetModel(); }, [](FileSystemTree* o, option_quintptr id, int first, int last) { if (id.some) { int row = file_system_tree_row(o->m_d, id.value); o->beginInsertRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginInsertRows(QModelIndex(), first, last); } }, [](FileSystemTree* o) { o->endInsertRows(); }, [](FileSystemTree* o, option_quintptr id, int first, int last) { if (id.some) { int row = file_system_tree_row(o->m_d, id.value); o->beginRemoveRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginRemoveRows(QModelIndex(), first, last); } }, [](FileSystemTree* o) { o->endRemoveRows(); } )), m_ownsPrivate(true) { connect(this, &FileSystemTree::newDataReady, this, [this](const QModelIndex& i) { this->fetchMore(i); }, Qt::QueuedConnection); initHeaderData(); } FileSystemTree::~FileSystemTree() { if (m_ownsPrivate) { file_system_tree_free(m_d); } } void FileSystemTree::initHeaderData() { m_headerData.insert(qMakePair(0, Qt::DisplayRole), QVariant("fileName")); m_headerData.insert(qMakePair(1, Qt::DisplayRole), QVariant("fileSize")); m_headerData.insert(qMakePair(2, Qt::DisplayRole), QVariant("filePath")); m_headerData.insert(qMakePair(3, Qt::DisplayRole), QVariant("filePermissions")); m_headerData.insert(qMakePair(4, Qt::DisplayRole), QVariant("fileType")); } QString FileSystemTree::path() const { QString v; file_system_tree_path_get(m_d, &v, set_qstring); return v; } void FileSystemTree::setPath(const QString& v) { if (v.isNull()) { file_system_tree_path_set_none(m_d); } else { file_system_tree_path_set(m_d, reinterpret_cast(v.data()), v.size()); } } Processes::Processes(bool /*owned*/, QObject *parent): QAbstractItemModel(parent), m_d(0), m_ownsPrivate(false) { initHeaderData(); } Processes::Processes(QObject *parent): QAbstractItemModel(parent), m_d(processes_new(this, processesActiveChanged, [](const Processes* o, quintptr id, bool valid) { if (valid) { int row = processes_row(o->m_d, id); emit o->newDataReady(o->createIndex(row, 0, id)); } else { emit o->newDataReady(QModelIndex()); } }, [](Processes* o, quintptr first, quintptr last) { quintptr frow = processes_row(o->m_d, first); quintptr lrow = processes_row(o->m_d, first); o->dataChanged(o->createIndex(frow, 0, first), o->createIndex(lrow, 2, last)); }, [](Processes* o) { o->beginResetModel(); }, [](Processes* o) { o->endResetModel(); }, [](Processes* o, option_quintptr id, int first, int last) { if (id.some) { int row = processes_row(o->m_d, id.value); o->beginInsertRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginInsertRows(QModelIndex(), first, last); } }, [](Processes* o) { o->endInsertRows(); }, [](Processes* o, option_quintptr id, int first, int last) { if (id.some) { int row = processes_row(o->m_d, id.value); o->beginRemoveRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginRemoveRows(QModelIndex(), first, last); } }, [](Processes* o) { o->endRemoveRows(); } )), m_ownsPrivate(true) { connect(this, &Processes::newDataReady, this, [this](const QModelIndex& i) { this->fetchMore(i); }, Qt::QueuedConnection); initHeaderData(); } Processes::~Processes() { if (m_ownsPrivate) { processes_free(m_d); } } void Processes::initHeaderData() { m_headerData.insert(qMakePair(0, Qt::DisplayRole), QVariant("name")); m_headerData.insert(qMakePair(1, Qt::DisplayRole), QVariant("cpuUsage")); m_headerData.insert(qMakePair(2, Qt::DisplayRole), QVariant("memory")); } bool Processes::active() const { return processes_active_get(m_d); } void Processes::setActive(bool v) { processes_active_set(m_d, v); } TimeSeries::TimeSeries(bool /*owned*/, QObject *parent): QAbstractItemModel(parent), m_d(0), m_ownsPrivate(false) { initHeaderData(); } TimeSeries::TimeSeries(QObject *parent): QAbstractItemModel(parent), m_d(time_series_new(this, [](const TimeSeries* o) { emit o->newDataReady(QModelIndex()); }, [](TimeSeries* o, quintptr first, quintptr last) { o->dataChanged(o->createIndex(first, 0, first), o->createIndex(last, 2, last)); }, [](TimeSeries* o) { o->beginResetModel(); }, [](TimeSeries* o) { o->endResetModel(); }, [](TimeSeries* o, int first, int last) { o->beginInsertRows(QModelIndex(), first, last); }, [](TimeSeries* o) { o->endInsertRows(); }, [](TimeSeries* o, int first, int last) { o->beginRemoveRows(QModelIndex(), first, last); }, [](TimeSeries* o) { o->endRemoveRows(); } )), m_ownsPrivate(true) { connect(this, &TimeSeries::newDataReady, this, [this](const QModelIndex& i) { this->fetchMore(i); }, Qt::QueuedConnection); initHeaderData(); } TimeSeries::~TimeSeries() { if (m_ownsPrivate) { time_series_free(m_d); } } void TimeSeries::initHeaderData() { m_headerData.insert(qMakePair(0, Qt::DisplayRole), QVariant("time")); m_headerData.insert(qMakePair(1, Qt::DisplayRole), QVariant("sin")); m_headerData.insert(qMakePair(2, Qt::DisplayRole), QVariant("cos")); } diff --git a/src/cpp.cpp b/src/cpp.cpp index 841e4e1..7091886 100644 --- a/src/cpp.cpp +++ b/src/cpp.cpp @@ -1,1028 +1,1035 @@ /* * 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 #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 if (!ip.optional) { cpp << QString(" v.setValue(%1_data_%2(m_d%3));\n") .arg(lcname, snakeCase(ip.name), idx); } 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 << QString(" if (!value.canConvert(qMetaTypeId<%1>())) {\n return false;\n }\n").arg(ip.type.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"; + cpp << " } else {\n"; } + cpp << QString(" if (!value.canConvert(qMetaTypeId<%1>())) {\n return false;\n }\n").arg(ip.type.name); QString val = QString("value.value<%1>()").arg(ip.type.name); if (ip.type.isComplex()) { cpp << QString(" const %1 s = %2;\n").arg(ip.type.name, val); if (ip.type.name == "QString") { val = "s.utf16(), s.length()"; } else { val = "s.data(), s.length()"; } } cpp << QString(" set = %1_set_data_%2(m_d%3, %4);") .arg(lcname, snakeCase(ip.name), idx, val) << endl; + if (ip.optional) { + cpp << " }\n"; + } 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) { if (ip.type.name == "QString") { cpp << QString(" bool %2_set_data_%3(%1::Private*%4, const ushort* s, int len);") .arg(o.name, lcname, snakeCase(ip.name), indexDecl) << endl; } else if (ip.type.name == "QByteArray") { cpp << QString(" bool %2_set_data_%3(%1::Private*%4, const char* s, int len);") .arg(o.name, lcname, snakeCase(ip.name), indexDecl) << endl; } else { 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 writeFunctionCDecl(QTextStream& cpp, const Function& f, const QString& lcname, const Object& o) { const QString lc(snakeCase(f.name)); cpp << " "; if (f.type.isComplex()) { cpp << "void"; } else { cpp << f.type.name; } const QString name = QString("%1_%2").arg(lcname, lc); cpp << QString(" %1(%3%2::Private*").arg(name, o.name, f.mut ? "" : "const "); // write all the input arguments, for QString and QByteArray, write // pointers to their content and the length for (auto a = f.args.begin(); a < f.args.end(); a++) { if (a->type.name == "QString") { cpp << ", const ushort*, int"; } else if (a->type.name == "QByteArray") { cpp << ", const char*, int"; } else { cpp << ", " << a->type.rustType; } } // If the return type is QString or QByteArray, append a pointer to the // variable that will be set to the argument list. Also add a setter // function. if (f.type.name == "QString") { cpp << ", QString*, qstring_set"; } else if (f.type.name == "QByteArray") { cpp << ", QByteArray*, qbytearray_set"; } cpp << ");\n"; } 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) { QString t = p.type.cSetType; if (t == "qstring_t") { t = "const ushort *str, int len"; } else if (t == "qbytearray_t") { t = "const char* bytes, int len"; } cpp << QString(" void %2_set(%1::Private*, %3);") .arg(o.name, base, t) << endl; if (p.optional) { cpp << QString(" void %2_set_none(%1::Private*);") .arg(o.name, base) << endl; } } } for (const Function& f: o.functions) { writeFunctionCDecl(cpp, f, lcname, o); } } 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; if (p.type.name == "QString") { cpp << QString(" %1_set(m_d, reinterpret_cast(v.data()), v.size());").arg(base) << endl; } else if (p.type.name == "QByteArray") { cpp << QString(" %1_set(m_d, v.data(), v.size());").arg(base) << endl; } else { cpp << QString(" %1_set(m_d, v);").arg(base) << endl; } cpp << QString(" }") << endl; } else if (p.type.name == "QString") { cpp << QString(" %1_set(m_d, reinterpret_cast(v.data()), v.size());").arg(base) << endl; } else if (p.type.name == "QByteArray") { cpp << QString(" %1_set(m_d, v.data(), v.size());").arg(base) << endl; } else { qWarning() << p.type.cppSetType; 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(")%1\n{\n") .arg(f.mut ? "" : " const"); QString argList; for (auto a = f.args.begin(); a < f.args.end(); a++) { if (a->type.name == "QString") { argList.append(QString(", %2%3.utf16(), %2%3.size()").arg(a->name, a + 1 < f.args.end() ? ", " : "")); } else { 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()) { - if (option != "QString") { + if (option != "QString" && option != "QByteArray") { cpp << QString(R"( struct option_%1 { public: %1 value; bool some; operator QVariant() const { if (some) { return QVariant::fromValue(value); } return QVariant(); } }; static_assert(std::is_pod::value, "option_%1 must be a POD type."); )").arg(option); } } if (conf.types().contains("QString")) { cpp << R"( typedef void (*qstring_set)(QString* val, const char* utf8, int nbytes); void set_qstring(QString* val, const char* utf8, int nbytes) { *val = QString::fromUtf8(utf8, nbytes); } )"; } if (conf.types().contains("QByteArray")) { cpp << R"( typedef void (*qbytearray_set)(QByteArray* val, const char* bytes, int nbytes); void set_qbytearray(QByteArray* v, const char* bytes, int nbytes) { - v->truncate(0); - v->append(bytes, nbytes); + if (v->isNull() && nbytes == 0) { + *v = QByteArray(bytes, nbytes); + } else { + v->truncate(0); + v->append(bytes, nbytes); + } } )"; } 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/rust.cpp b/src/rust.cpp index 05fb27b..e0b0ad8 100644 --- a/src/rust.cpp +++ b/src/rust.cpp @@ -1,997 +1,998 @@ /* * 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 writeFunction(QTextStream& r, const Function& f, const QString& lcname, const Object& o) { const QString lc(snakeCase(f.name)); r << QString(R"( #[no_mangle] pub extern "C" fn %1_%2(ptr: *%3 %4)").arg(lcname, lc, f.mut ? "mut" : "const", o.name); // write all the input arguments, for QString and QByteArray, write // pointers to their content and the length which is int in Qt for (auto a = f.args.begin(); a < f.args.end(); a++) { r << ", "; if (a->type.name == "QString") { r << QString("%1_str: *const c_ushort, %1_len: c_int").arg(a->name); } else { r << a->name << ": " << a->type.rustType; } } // If the return type is QString or QByteArray, append a pointer to the // variable that will be set to the argument list. Also add a setter // function. if (f.type.name == "QString") { r << ", d: *mut QString, set: fn(*mut QString, str: *const c_char, len: c_int)) {\n"; } else if (f.type.name == "QByteArray") { r << ", d: *mut QByteArray, set: fn(*mut QString, str: *const c_char, len: c_int)) {\n"; } else { r << ") -> " << f.type.rustType << " {\n"; } for (auto a = f.args.begin(); a < f.args.end(); a++) { if (a->type.name == "QString") { r << " let mut " << a->name << " = String::new();\n"; r << QString(" set_string_from_utf16(&mut %1, %1_str, %1_len);\n").arg(a->name); } else if (a->type.name == "QByteArray") { } } if (f.mut) { r << " let o = unsafe { &mut *ptr };\n"; } else { r << " let o = unsafe { &*ptr };\n"; } r << " let r = o." << lc << "("; for (auto a = f.args.begin(); a < f.args.end(); a++) { if (a != f.args.begin()) { r << ", "; } r << a->name; } r << ");\n"; if (f.type.isComplex()) { r << " let s: *const c_char = r.as_ptr() as (*const c_char);\n"; r << " set(d, s, r.len() as i32);\n"; } else if (f.type.rustType != "()") { r << " r\n"; } 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 extern "C" fn %2_get( ptr: *const %1, p: *mut c_void, set: fn(*mut c_void, *const c_char, c_int), ) { let o = unsafe { &*ptr }; let v = o.%3(); let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, v.len() as c_int); } )").arg(o.name, base, snakeCase(p.name)); if (p.write && p.type.name == "QString") { r << QString(R"( #[no_mangle] pub extern "C" fn %2_set(ptr: *mut %1, v: *const c_ushort, len: c_int) { let o = unsafe { &mut *ptr }; let mut s = String::new(); set_string_from_utf16(&mut s, v, len); o.set_%3(s); } )").arg(o.name, base, snakeCase(p.name)); } else if (p.write) { r << QString(R"( #[no_mangle] pub extern "C" fn %2_set(ptr: *mut %1, v: *const c_char, len: c_int) { let o = unsafe { &mut *ptr }; let v = unsafe { slice::from_raw_parts(v as *const u8, len as usize) }; o.set_%3(v.into()); } )").arg(o.name, base, snakeCase(p.name)); } } else if (p.type.isComplex()) { r << QString(R"( #[no_mangle] pub extern "C" fn %2_get( ptr: *const %1, p: *mut c_void, set: fn(*mut c_void, *const c_char, c_int), ) { let o = unsafe { &*ptr }; let v = o.%3(); if let Some(v) = v { let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, v.len() as c_int); } } )").arg(o.name, base, snakeCase(p.name)); if (p.write && p.type.name == "QString") { r << QString(R"( #[no_mangle] pub extern "C" fn %2_set(ptr: *mut %1, v: *const c_ushort, len: c_int) { let o = unsafe { &mut *ptr }; let mut s = String::new(); set_string_from_utf16(&mut s, v, len); o.set_%3(Some(s)); } #[no_mangle] pub extern "C" fn %2_set_none(ptr: *mut %1) { let o = unsafe { &mut *ptr }; o.set_%3(None); } )").arg(o.name, base, snakeCase(p.name)); } else if (p.write) { r << QString(R"( #[no_mangle] pub extern "C" fn %2_set(ptr: *mut %1, v: *const c_char, len: c_int) { let o = unsafe { &mut *ptr }; let v = unsafe { slice::from_raw_parts(v as *const u8, len as usize) }; o.set_%3(Some(v.into())); } #[no_mangle] pub extern "C" fn %2_set_none(ptr: *mut %1) { let o = unsafe { &mut *ptr }; o.set_%3(None); } )").arg(o.name, base, snakeCase(p.name)); } } 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) { writeFunction(r, f, lcname, o); } 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 extern "C" fn %2_data_%3( ptr: *const %1%5, d: *mut QString, set: fn(*mut QString, *const c_char, len: c_int), ) { let o = unsafe { &*ptr }; let data = o.%3(%6); let s: *const c_char = data.as_ptr() as (*const c_char); set(d, s, data.len() as c_int); } )").arg(o.name, lcname, snakeCase(ip.name), indexDecl, index); - } else if (ip.type.name == "QString") { + } else if (ip.type.isComplex()) { r << QString(R"( #[no_mangle] pub extern "C" fn %2_data_%3( ptr: *const %1%4, d: *mut QString, set: fn(*mut QString, *const c_char, len: c_int), ) { let o = unsafe { &*ptr }; let data = o.%3(%5); if let Some(data) = data { let s: *const c_char = data.as_ptr() as (*const c_char); set(d, s, data.len() as c_int); } } )").arg(o.name, lcname, snakeCase(ip.name), indexDecl, index); } else { r << QString(R"( #[no_mangle] pub extern "C" fn %2_data_%3(ptr: *const %1%5) -> %4 { let o = unsafe { &*ptr }; o.%3(%6).into() } )").arg(o.name, lcname, snakeCase(ip.name), rustCType(ip), indexDecl, index); } if (ip.write) { QString val = "v"; if (ip.optional) { val = "Some(" + val + ")"; } if (ip.type.name == "QString") { r << QString(R"( #[no_mangle] pub extern "C" fn %2_set_data_%3( ptr: *mut %1%4, s: *const c_ushort, len: c_int, ) -> bool { let o = unsafe { &mut *ptr }; let mut v = String::new(); set_string_from_utf16(&mut v, s, len); o.set_%3(%5, %6) } )").arg(o.name, lcname, snakeCase(ip.name), indexDecl, index, val); } else if (ip.type.name == "QByteArray") { r << QString(R"( #[no_mangle] pub extern "C" fn %2_set_data_%3( ptr: *mut %1%4, s: *const c_char, len: c_int, ) -> bool { let o = unsafe { &mut *ptr }; let mut v = Vec::new(); - set_string_from_utf16(&mut v, s, len); + let slice = unsafe { ::std::slice::from_raw_parts(s as *const u8, len as usize) }; + v.extend_from_slice(slice); o.set_%3(%5, %6) } )").arg(o.name, lcname, snakeCase(ip.name), indexDecl, index, val); } else { const QString type = ip.type.rustType; 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) +pub unsafe extern "C" fn %2_set_data_%3_none(ptr: *mut %1%4) -> bool { + (&mut *ptr).set_%3(%5, 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"( pub enum QString {} fn set_string_from_utf16(s: &mut String, str: *const c_ushort, len: c_int) { let utf16 = unsafe { slice::from_raw_parts(str, len as usize) }; let characters = decode_utf16(utf16.iter().cloned()) .into_iter() .map(|r| r.unwrap()); s.clear(); s.extend(characters); } )"; } if (hasByteArray) { r << R"( pub enum QByteArray {} )"; } 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_char, c_ushort, c_int, c_void, uint8_t, uint16_t}; use std::slice; use std::char::decode_utf16; 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)); } } 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/tests/CMakeLists.txt b/tests/CMakeLists.txt index da0454f..14f44e8 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" "${SRC}/${NAME}_rust.h" # if the cpp file is marked GENERATED, CMake will not check it for moc # "${SRC}/${NAME}_rust.cpp" COMMAND "${GENERATOR}" "${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_list_types rust_list_types) rust_test(test_tree rust_tree) rust_test(test_objects rust_objects) rust_test(test_functions rust_functions) diff --git a/tests/rust_list_types/Cargo.toml b/tests/rust_list_types/Cargo.toml new file mode 100644 index 0000000..2e8f02c --- /dev/null +++ b/tests/rust_list_types/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "rust_list" +version = "1.0.0" + +[dependencies] +libc = "*" + +[lib] +name = "rust" +crate-type = ["staticlib"] + +[profile.release] +debug = true diff --git a/tests/rust_list_types/src/implementation.rs b/tests/rust_list_types/src/implementation.rs new file mode 100644 index 0000000..f591a85 --- /dev/null +++ b/tests/rust_list_types/src/implementation.rs @@ -0,0 +1,151 @@ +#![allow(unused_imports)] +#![allow(unused_variables)] +#![allow(dead_code)] +use interface::*; + +#[derive(Default, Clone)] +struct ListItem { + boolean: bool, + i8: i8, + u8: u8, + i16: i16, + u16: u16, + i32: i32, + u32: u32, + i64: i64, + u64: u64, + f32: f32, + f64: f64, + bytearray: Vec, + optional_bytearray: Option>, + string: String, + optional_string: Option, +} + +pub struct List { + emit: ListEmitter, + model: ListList, + list: Vec, +} + +impl ListTrait for List { + fn new(emit: ListEmitter, model: ListList) -> List { + List { + emit: emit, + model: model, + list: vec![ListItem::default(); 10], + } + } + fn emit(&self) -> &ListEmitter { + &self.emit + } + fn row_count(&self) -> usize { + self.list.len() + } + fn boolean(&self, item: usize) -> bool { + self.list[item].boolean + } + fn set_boolean(&mut self, item: usize, v: bool) -> bool { + self.list[item].boolean = v; + true + } + fn i8(&self, item: usize) -> i8 { + self.list[item].i8 + } + fn set_i8(&mut self, item: usize, v: i8) -> bool { + self.list[item].i8 = v; + true + } + fn u8(&self, item: usize) -> u8 { + self.list[item].u8 + } + fn set_u8(&mut self, item: usize, v: u8) -> bool { + self.list[item].u8 = v; + true + } + fn i16(&self, item: usize) -> i16 { + self.list[item].i16 + } + fn set_i16(&mut self, item: usize, v: i16) -> bool { + self.list[item].i16 = v; + true + } + fn u16(&self, item: usize) -> u16 { + self.list[item].u16 + } + fn set_u16(&mut self, item: usize, v: u16) -> bool { + self.list[item].u16 = v; + true + } + fn i32(&self, item: usize) -> i32 { + self.list[item].i32 + } + fn set_i32(&mut self, item: usize, v: i32) -> bool { + self.list[item].i32 = v; + true + } + fn u32(&self, item: usize) -> u32 { + self.list[item].u32 + } + fn set_u32(&mut self, item: usize, v: u32) -> bool { + self.list[item].u32 = v; + true + } + fn i64(&self, item: usize) -> i64 { + self.list[item].i64 + } + fn set_i64(&mut self, item: usize, v: i64) -> bool { + self.list[item].i64 = v; + true + } + fn u64(&self, item: usize) -> u64 { + self.list[item].u64 + } + fn set_u64(&mut self, item: usize, v: u64) -> bool { + self.list[item].u64 = v; + true + } + fn f32(&self, item: usize) -> f32 { + self.list[item].f32 + } + fn set_f32(&mut self, item: usize, v: f32) -> bool { + self.list[item].f32 = v; + true + } + fn f64(&self, item: usize) -> f64 { + self.list[item].f64 + } + fn set_f64(&mut self, item: usize, v: f64) -> bool { + self.list[item].f64 = v; + true + } + fn string(&self, item: usize) -> &str { + &self.list[item].string + } + fn set_string(&mut self, item: usize, v: String) -> bool { + self.list[item].string = v; + true + } + fn optional_string(&self, item: usize) -> Option<&str> { + self.list[item].optional_string.as_ref().map(|p|&p[..]) + } + fn set_optional_string(&mut self, item: usize, v: Option) -> bool { + self.list[item].optional_string = v; + true + } + fn bytearray(&self, item: usize) -> &[u8] { + &self.list[item].bytearray + } + fn set_bytearray(&mut self, item: usize, v: Vec) -> bool { + self.list[item].bytearray = v; + true + } + fn optional_bytearray(&self, item: usize) -> Option<&[u8]> { + self.list[item].optional_bytearray.as_ref().map(|p|&p[..]) + } + fn set_optional_bytearray(&mut self, item: usize, v: Option>) -> bool { + self.list[item].optional_bytearray = v; + true + } +} + diff --git a/tests/rust_list_types/src/interface.rs b/tests/rust_list_types/src/interface.rs new file mode 100644 index 0000000..63e8ea9 --- /dev/null +++ b/tests/rust_list_types/src/interface.rs @@ -0,0 +1,492 @@ +/* generated by rust_qt_binding_generator */ +#![allow(unknown_lints)] +#![allow(mutex_atomic, needless_pass_by_value)] +use libc::{c_char, c_ushort, c_int, c_void, uint8_t, uint16_t}; +use std::slice; +use std::char::decode_utf16; + +use std::sync::{Arc, Mutex}; +use std::ptr::null; + +use implementation::*; + + +#[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, + } + } + } +} + + +pub enum QString {} + +fn set_string_from_utf16(s: &mut String, str: *const c_ushort, len: c_int) { + let utf16 = unsafe { slice::from_raw_parts(str, len as usize) }; + let characters = decode_utf16(utf16.iter().cloned()) + .into_iter() + .map(|r| r.unwrap()); + s.clear(); + s.extend(characters); +} + + + +pub enum QByteArray {} + + +#[repr(C)] +pub enum SortOrder { + Ascending = 0, + Descending = 1, +} + +#[repr(C)] +pub struct QModelIndex { + row: c_int, + internal_id: usize, +} + +pub struct ListQObject {} + +#[derive(Clone)] +pub struct ListEmitter { + qobject: Arc>, + new_data_ready: fn(*const ListQObject), +} + +unsafe impl Send for ListEmitter {} + +impl ListEmitter { + fn clear(&self) { + *self.qobject.lock().unwrap() = null(); + } + pub fn new_data_ready(&self) { + let ptr = *self.qobject.lock().unwrap(); + if !ptr.is_null() { + (self.new_data_ready)(ptr); + } + } +} + +pub struct ListList { + qobject: *const ListQObject, + data_changed: fn(*const ListQObject, usize, usize), + begin_reset_model: fn(*const ListQObject), + end_reset_model: fn(*const ListQObject), + begin_insert_rows: fn(*const ListQObject, usize, usize), + end_insert_rows: fn(*const ListQObject), + begin_remove_rows: fn(*const ListQObject, usize, usize), + end_remove_rows: fn(*const ListQObject), +} + +impl ListList { + 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, first: usize, last: usize) { + (self.begin_insert_rows)(self.qobject, first, last); + } + pub fn end_insert_rows(&self) { + (self.end_insert_rows)(self.qobject); + } + pub fn begin_remove_rows(&self, first: usize, last: usize) { + (self.begin_remove_rows)(self.qobject, first, last); + } + pub fn end_remove_rows(&self) { + (self.end_remove_rows)(self.qobject); + } +} + +pub trait ListTrait { + fn new(emit: ListEmitter, model: ListList) -> Self; + fn emit(&self) -> &ListEmitter; + 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) {} + fn boolean(&self, item: usize) -> bool; + fn set_boolean(&mut self, item: usize, bool) -> bool; + fn bytearray(&self, item: usize) -> &[u8]; + fn set_bytearray(&mut self, item: usize, Vec) -> bool; + fn f32(&self, item: usize) -> f32; + fn set_f32(&mut self, item: usize, f32) -> bool; + fn f64(&self, item: usize) -> f64; + fn set_f64(&mut self, item: usize, f64) -> bool; + fn i16(&self, item: usize) -> i16; + fn set_i16(&mut self, item: usize, i16) -> bool; + fn i32(&self, item: usize) -> i32; + fn set_i32(&mut self, item: usize, i32) -> bool; + fn i64(&self, item: usize) -> i64; + fn set_i64(&mut self, item: usize, i64) -> bool; + fn i8(&self, item: usize) -> i8; + fn set_i8(&mut self, item: usize, i8) -> bool; + fn optional_bytearray(&self, item: usize) -> Option<&[u8]>; + fn set_optional_bytearray(&mut self, item: usize, Option>) -> bool; + fn optional_string(&self, item: usize) -> Option<&str>; + fn set_optional_string(&mut self, item: usize, Option) -> bool; + fn string(&self, item: usize) -> &str; + fn set_string(&mut self, item: usize, String) -> bool; + fn u16(&self, item: usize) -> u16; + fn set_u16(&mut self, item: usize, u16) -> bool; + fn u32(&self, item: usize) -> u32; + fn set_u32(&mut self, item: usize, u32) -> bool; + fn u64(&self, item: usize) -> u64; + fn set_u64(&mut self, item: usize, u64) -> bool; + fn u8(&self, item: usize) -> u8; + fn set_u8(&mut self, item: usize, u8) -> bool; +} + +#[no_mangle] +pub extern "C" fn list_new( + list: *mut ListQObject, + list_new_data_ready: fn(*const ListQObject), + list_data_changed: fn(*const ListQObject, usize, usize), + list_begin_reset_model: fn(*const ListQObject), + list_end_reset_model: fn(*const ListQObject), + list_begin_insert_rows: fn(*const ListQObject, usize, usize), + list_end_insert_rows: fn(*const ListQObject), + list_begin_remove_rows: fn(*const ListQObject, usize, usize), + list_end_remove_rows: fn(*const ListQObject), +) -> *mut List { + let list_emit = ListEmitter { + qobject: Arc::new(Mutex::new(list)), + new_data_ready: list_new_data_ready, + }; + let model = ListList { + qobject: list, + data_changed: list_data_changed, + begin_reset_model: list_begin_reset_model, + end_reset_model: list_end_reset_model, + begin_insert_rows: list_begin_insert_rows, + end_insert_rows: list_end_insert_rows, + begin_remove_rows: list_begin_remove_rows, + end_remove_rows: list_end_remove_rows, + }; + let d_list = List::new(list_emit, model); + Box::into_raw(Box::new(d_list)) +} + +#[no_mangle] +pub unsafe extern "C" fn list_free(ptr: *mut List) { + Box::from_raw(ptr).emit().clear(); +} + +#[no_mangle] +pub unsafe extern "C" fn list_row_count(ptr: *const List) -> c_int { + (&*ptr).row_count() as c_int +} +#[no_mangle] +pub unsafe extern "C" fn list_insert_rows(ptr: *mut List, row: c_int, count: c_int) -> bool { + (&mut *ptr).insert_rows(row as usize, count as usize) +} +#[no_mangle] +pub unsafe extern "C" fn list_remove_rows(ptr: *mut List, row: c_int, count: c_int) -> bool { + (&mut *ptr).remove_rows(row as usize, count as usize) +} +#[no_mangle] +pub unsafe extern "C" fn list_can_fetch_more(ptr: *const List) -> bool { + (&*ptr).can_fetch_more() +} +#[no_mangle] +pub unsafe extern "C" fn list_fetch_more(ptr: *mut List) { + (&mut *ptr).fetch_more() +} +#[no_mangle] +pub unsafe extern "C" fn list_sort( + ptr: *mut List, + column: u8, + order: SortOrder, +) { + (&mut *ptr).sort(column, order) +} + +#[no_mangle] +pub extern "C" fn list_data_boolean(ptr: *const List, row: c_int) -> bool { + let o = unsafe { &*ptr }; + o.boolean(row as usize).into() +} + +#[no_mangle] +pub unsafe extern "C" fn list_set_data_boolean( + ptr: *mut List, row: c_int, + v: bool, +) -> bool { + (&mut *ptr).set_boolean(row as usize, v) +} + +#[no_mangle] +pub extern "C" fn list_data_bytearray( + ptr: *const List, row: c_int, + d: *mut QString, + set: fn(*mut QString, *const c_char, len: c_int), +) { + let o = unsafe { &*ptr }; + let data = o.bytearray(row as usize); + let s: *const c_char = data.as_ptr() as (*const c_char); + set(d, s, data.len() as c_int); +} + +#[no_mangle] +pub extern "C" fn list_set_data_bytearray( + ptr: *mut List, row: c_int, + s: *const c_char, len: c_int, +) -> bool { + let o = unsafe { &mut *ptr }; + let mut v = Vec::new(); + let slice = unsafe { ::std::slice::from_raw_parts(s as *const u8, len as usize) }; + v.extend_from_slice(slice); + o.set_bytearray(row as usize, v) +} + +#[no_mangle] +pub extern "C" fn list_data_f32(ptr: *const List, row: c_int) -> f32 { + let o = unsafe { &*ptr }; + o.f32(row as usize).into() +} + +#[no_mangle] +pub unsafe extern "C" fn list_set_data_f32( + ptr: *mut List, row: c_int, + v: f32, +) -> bool { + (&mut *ptr).set_f32(row as usize, v) +} + +#[no_mangle] +pub extern "C" fn list_data_f64(ptr: *const List, row: c_int) -> f64 { + let o = unsafe { &*ptr }; + o.f64(row as usize).into() +} + +#[no_mangle] +pub unsafe extern "C" fn list_set_data_f64( + ptr: *mut List, row: c_int, + v: f64, +) -> bool { + (&mut *ptr).set_f64(row as usize, v) +} + +#[no_mangle] +pub extern "C" fn list_data_i16(ptr: *const List, row: c_int) -> i16 { + let o = unsafe { &*ptr }; + o.i16(row as usize).into() +} + +#[no_mangle] +pub unsafe extern "C" fn list_set_data_i16( + ptr: *mut List, row: c_int, + v: i16, +) -> bool { + (&mut *ptr).set_i16(row as usize, v) +} + +#[no_mangle] +pub extern "C" fn list_data_i32(ptr: *const List, row: c_int) -> i32 { + let o = unsafe { &*ptr }; + o.i32(row as usize).into() +} + +#[no_mangle] +pub unsafe extern "C" fn list_set_data_i32( + ptr: *mut List, row: c_int, + v: i32, +) -> bool { + (&mut *ptr).set_i32(row as usize, v) +} + +#[no_mangle] +pub extern "C" fn list_data_i64(ptr: *const List, row: c_int) -> i64 { + let o = unsafe { &*ptr }; + o.i64(row as usize).into() +} + +#[no_mangle] +pub unsafe extern "C" fn list_set_data_i64( + ptr: *mut List, row: c_int, + v: i64, +) -> bool { + (&mut *ptr).set_i64(row as usize, v) +} + +#[no_mangle] +pub extern "C" fn list_data_i8(ptr: *const List, row: c_int) -> i8 { + let o = unsafe { &*ptr }; + o.i8(row as usize).into() +} + +#[no_mangle] +pub unsafe extern "C" fn list_set_data_i8( + ptr: *mut List, row: c_int, + v: i8, +) -> bool { + (&mut *ptr).set_i8(row as usize, v) +} + +#[no_mangle] +pub extern "C" fn list_data_optional_bytearray( + ptr: *const List, row: c_int, + d: *mut QString, + set: fn(*mut QString, *const c_char, len: c_int), +) { + let o = unsafe { &*ptr }; + let data = o.optional_bytearray(row as usize); + if let Some(data) = data { + let s: *const c_char = data.as_ptr() as (*const c_char); + set(d, s, data.len() as c_int); + } +} + +#[no_mangle] +pub extern "C" fn list_set_data_optional_bytearray( + ptr: *mut List, row: c_int, + s: *const c_char, len: c_int, +) -> bool { + let o = unsafe { &mut *ptr }; + let mut v = Vec::new(); + let slice = unsafe { ::std::slice::from_raw_parts(s as *const u8, len as usize) }; + v.extend_from_slice(slice); + o.set_optional_bytearray(row as usize, Some(v)) +} + +#[no_mangle] +pub unsafe extern "C" fn list_set_data_optional_bytearray_none(ptr: *mut List, row: c_int) -> bool { + (&mut *ptr).set_optional_bytearray(row as usize, None) +} + +#[no_mangle] +pub extern "C" fn list_data_optional_string( + ptr: *const List, row: c_int, + d: *mut QString, + set: fn(*mut QString, *const c_char, len: c_int), +) { + let o = unsafe { &*ptr }; + let data = o.optional_string(row as usize); + if let Some(data) = data { + let s: *const c_char = data.as_ptr() as (*const c_char); + set(d, s, data.len() as c_int); + } +} + +#[no_mangle] +pub extern "C" fn list_set_data_optional_string( + ptr: *mut List, row: c_int, + s: *const c_ushort, len: c_int, +) -> bool { + let o = unsafe { &mut *ptr }; + let mut v = String::new(); + set_string_from_utf16(&mut v, s, len); + o.set_optional_string(row as usize, Some(v)) +} + +#[no_mangle] +pub unsafe extern "C" fn list_set_data_optional_string_none(ptr: *mut List, row: c_int) -> bool { + (&mut *ptr).set_optional_string(row as usize, None) +} + +#[no_mangle] +pub extern "C" fn list_data_string( + ptr: *const List, row: c_int, + d: *mut QString, + set: fn(*mut QString, *const c_char, len: c_int), +) { + let o = unsafe { &*ptr }; + let data = o.string(row as usize); + let s: *const c_char = data.as_ptr() as (*const c_char); + set(d, s, data.len() as c_int); +} + +#[no_mangle] +pub extern "C" fn list_set_data_string( + ptr: *mut List, row: c_int, + s: *const c_ushort, len: c_int, +) -> bool { + let o = unsafe { &mut *ptr }; + let mut v = String::new(); + set_string_from_utf16(&mut v, s, len); + o.set_string(row as usize, v) +} + +#[no_mangle] +pub extern "C" fn list_data_u16(ptr: *const List, row: c_int) -> u16 { + let o = unsafe { &*ptr }; + o.u16(row as usize).into() +} + +#[no_mangle] +pub unsafe extern "C" fn list_set_data_u16( + ptr: *mut List, row: c_int, + v: u16, +) -> bool { + (&mut *ptr).set_u16(row as usize, v) +} + +#[no_mangle] +pub extern "C" fn list_data_u32(ptr: *const List, row: c_int) -> u32 { + let o = unsafe { &*ptr }; + o.u32(row as usize).into() +} + +#[no_mangle] +pub unsafe extern "C" fn list_set_data_u32( + ptr: *mut List, row: c_int, + v: u32, +) -> bool { + (&mut *ptr).set_u32(row as usize, v) +} + +#[no_mangle] +pub extern "C" fn list_data_u64(ptr: *const List, row: c_int) -> u64 { + let o = unsafe { &*ptr }; + o.u64(row as usize).into() +} + +#[no_mangle] +pub unsafe extern "C" fn list_set_data_u64( + ptr: *mut List, row: c_int, + v: u64, +) -> bool { + (&mut *ptr).set_u64(row as usize, v) +} + +#[no_mangle] +pub extern "C" fn list_data_u8(ptr: *const List, row: c_int) -> u8 { + let o = unsafe { &*ptr }; + o.u8(row as usize).into() +} + +#[no_mangle] +pub unsafe extern "C" fn list_set_data_u8( + ptr: *mut List, row: c_int, + v: u8, +) -> bool { + (&mut *ptr).set_u8(row as usize, v) +} diff --git a/tests/rust_list_types/src/lib.rs b/tests/rust_list_types/src/lib.rs new file mode 100644 index 0000000..d7eb847 --- /dev/null +++ b/tests/rust_list_types/src/lib.rs @@ -0,0 +1,4 @@ +extern crate libc; + +pub mod interface; +mod implementation; diff --git a/tests/rust_object_types/src/implementation.rs b/tests/rust_object_types/src/implementation.rs index 96ba22d..b70c0d9 100644 --- a/tests/rust_object_types/src/implementation.rs +++ b/tests/rust_object_types/src/implementation.rs @@ -1,92 +1,163 @@ #![allow(unused_imports)] #![allow(unused_variables)] #![allow(dead_code)] use interface::*; pub struct Object { emit: ObjectEmitter, boolean: bool, + i8: i8, + u8: u8, + i16: i16, + u16: u16, + i32: i32, + u32: u32, + i64: i64, + u64: u64, + f32: f32, + f64: f64, bytearray: Vec, - integer: i32, optional_bytearray: Option>, - optional_string: Option, string: String, - u64: u64, - uinteger: u32, + optional_string: Option, } impl ObjectTrait for Object { fn new(emit: ObjectEmitter) -> Object { Object { - emit: emit, - boolean: true, + emit, + boolean: false, + i8: 0, + u8: 0, + i16: 0, + u16: 0, + i32: 0, + u32: 0, + i64: 0, + u64: 0, + f32: 0., + f64: 0., bytearray: Vec::new(), - integer: 0, optional_bytearray: None, - optional_string: None, string: String::new(), - u64: 0, - uinteger: 0, + optional_string: None } } fn emit(&self) -> &ObjectEmitter { &self.emit } fn boolean(&self) -> bool { self.boolean } fn set_boolean(&mut self, value: bool) { self.boolean = value; self.emit.boolean_changed(); } + fn i8(&self) -> i8 { + self.i8 + } + fn set_i8(&mut self, value: i8) { + self.i8 = value; + self.emit.i8_changed(); + } + fn u8(&self) -> u8 { + self.u8 + } + fn set_u8(&mut self, value: u8) { + self.u8 = value; + self.emit.u8_changed(); + } + fn i16(&self) -> i16 { + self.i16 + } + fn set_i16(&mut self, value: i16) { + self.i16 = value; + self.emit.i16_changed(); + } + fn u16(&self) -> u16 { + self.u16 + } + fn set_u16(&mut self, value: u16) { + self.u16 = value; + self.emit.u16_changed(); + } + fn i32(&self) -> i32 { + self.i32 + } + fn set_i32(&mut self, value: i32) { + self.i32 = value; + self.emit.i32_changed(); + } + fn u32(&self) -> u32 { + self.u32 + } + fn set_u32(&mut self, value: u32) { + self.u32 = value; + self.emit.u32_changed(); + } + fn i64(&self) -> i64 { + self.i64 + } + fn set_i64(&mut self, value: i64) { + self.i64 = value; + self.emit.i64_changed(); + } + fn u64(&self) -> u64 { + self.u64 + } + fn set_u64(&mut self, value: u64) { + self.u64 = value; + self.emit.u64_changed(); + } + fn f32(&self) -> f32 { + self.f32 + } + fn set_f32(&mut self, value: f32) { + self.f32 = value; + self.emit.f32_changed(); + } + fn f64(&self) -> f64 { + self.f64 + } + fn set_f64(&mut self, value: f64) { + self.f64 = value; + self.emit.f64_changed(); + } + /* + fn optional_boolean(&self) -> Option { + self.optional_boolean + } + fn set_optional_boolean(&mut self, b: Option) { + self.optional_boolean = b; + } + */ fn bytearray(&self) -> &[u8] { &self.bytearray } fn set_bytearray(&mut self, value: Vec) { self.bytearray = value; self.emit.bytearray_changed(); } - fn integer(&self) -> i32 { - self.integer - } - fn set_integer(&mut self, value: i32) { - self.integer = value; - self.emit.integer_changed(); - } fn optional_bytearray(&self) -> Option<&[u8]> { self.optional_bytearray.as_ref().map(|p|&p[..]) } fn set_optional_bytearray(&mut self, value: Option>) { self.optional_bytearray = value; self.emit.optional_bytearray_changed(); } fn optional_string(&self) -> Option<&str> { self.optional_string.as_ref().map(|p|&p[..]) } fn set_optional_string(&mut self, value: Option) { self.optional_string = value; self.emit.optional_string_changed(); } fn string(&self) -> &str { &self.string } fn set_string(&mut self, value: String) { self.string = value; self.emit.string_changed(); } - fn u64(&self) -> u64 { - self.u64 - } - fn set_u64(&mut self, value: u64) { - self.u64 = value; - self.emit.u64_changed(); - } - fn uinteger(&self) -> u32 { - self.uinteger - } - fn set_uinteger(&mut self, value: u32) { - self.uinteger = value; - self.emit.uinteger_changed(); - } } diff --git a/tests/rust_object_types/src/interface.rs b/tests/rust_object_types/src/interface.rs index abc7f5f..ab06e6a 100644 --- a/tests/rust_object_types/src/interface.rs +++ b/tests/rust_object_types/src/interface.rs @@ -1,309 +1,456 @@ /* generated by rust_qt_binding_generator */ #![allow(unknown_lints)] #![allow(mutex_atomic, needless_pass_by_value)] use libc::{c_char, c_ushort, c_int, c_void, uint8_t, uint16_t}; use std::slice; use std::char::decode_utf16; use std::sync::{Arc, Mutex}; use std::ptr::null; use implementation::*; #[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, } } } } pub enum QString {} fn set_string_from_utf16(s: &mut String, str: *const c_ushort, len: c_int) { let utf16 = unsafe { slice::from_raw_parts(str, len as usize) }; let characters = decode_utf16(utf16.iter().cloned()) .into_iter() .map(|r| r.unwrap()); s.clear(); s.extend(characters); } pub enum QByteArray {} pub struct ObjectQObject {} #[derive(Clone)] pub struct ObjectEmitter { qobject: Arc>, boolean_changed: fn(*const ObjectQObject), bytearray_changed: fn(*const ObjectQObject), - integer_changed: fn(*const ObjectQObject), + f32_changed: fn(*const ObjectQObject), + f64_changed: fn(*const ObjectQObject), + i16_changed: fn(*const ObjectQObject), + i32_changed: fn(*const ObjectQObject), + i64_changed: fn(*const ObjectQObject), + i8_changed: fn(*const ObjectQObject), optional_bytearray_changed: fn(*const ObjectQObject), optional_string_changed: fn(*const ObjectQObject), string_changed: fn(*const ObjectQObject), + u16_changed: fn(*const ObjectQObject), + u32_changed: fn(*const ObjectQObject), u64_changed: fn(*const ObjectQObject), - uinteger_changed: fn(*const ObjectQObject), + u8_changed: fn(*const ObjectQObject), } unsafe impl Send for ObjectEmitter {} impl ObjectEmitter { fn clear(&self) { *self.qobject.lock().unwrap() = null(); } pub fn boolean_changed(&self) { let ptr = *self.qobject.lock().unwrap(); if !ptr.is_null() { (self.boolean_changed)(ptr); } } pub fn bytearray_changed(&self) { let ptr = *self.qobject.lock().unwrap(); if !ptr.is_null() { (self.bytearray_changed)(ptr); } } - pub fn integer_changed(&self) { + pub fn f32_changed(&self) { let ptr = *self.qobject.lock().unwrap(); if !ptr.is_null() { - (self.integer_changed)(ptr); + (self.f32_changed)(ptr); + } + } + pub fn f64_changed(&self) { + let ptr = *self.qobject.lock().unwrap(); + if !ptr.is_null() { + (self.f64_changed)(ptr); + } + } + pub fn i16_changed(&self) { + let ptr = *self.qobject.lock().unwrap(); + if !ptr.is_null() { + (self.i16_changed)(ptr); + } + } + pub fn i32_changed(&self) { + let ptr = *self.qobject.lock().unwrap(); + if !ptr.is_null() { + (self.i32_changed)(ptr); + } + } + pub fn i64_changed(&self) { + let ptr = *self.qobject.lock().unwrap(); + if !ptr.is_null() { + (self.i64_changed)(ptr); + } + } + pub fn i8_changed(&self) { + let ptr = *self.qobject.lock().unwrap(); + if !ptr.is_null() { + (self.i8_changed)(ptr); } } pub fn optional_bytearray_changed(&self) { let ptr = *self.qobject.lock().unwrap(); if !ptr.is_null() { (self.optional_bytearray_changed)(ptr); } } pub fn optional_string_changed(&self) { let ptr = *self.qobject.lock().unwrap(); if !ptr.is_null() { (self.optional_string_changed)(ptr); } } pub fn string_changed(&self) { let ptr = *self.qobject.lock().unwrap(); if !ptr.is_null() { (self.string_changed)(ptr); } } + pub fn u16_changed(&self) { + let ptr = *self.qobject.lock().unwrap(); + if !ptr.is_null() { + (self.u16_changed)(ptr); + } + } + pub fn u32_changed(&self) { + let ptr = *self.qobject.lock().unwrap(); + if !ptr.is_null() { + (self.u32_changed)(ptr); + } + } pub fn u64_changed(&self) { let ptr = *self.qobject.lock().unwrap(); if !ptr.is_null() { (self.u64_changed)(ptr); } } - pub fn uinteger_changed(&self) { + pub fn u8_changed(&self) { let ptr = *self.qobject.lock().unwrap(); if !ptr.is_null() { - (self.uinteger_changed)(ptr); + (self.u8_changed)(ptr); } } } pub trait ObjectTrait { fn new(emit: ObjectEmitter) -> Self; fn emit(&self) -> &ObjectEmitter; fn boolean(&self) -> bool; fn set_boolean(&mut self, value: bool); fn bytearray(&self) -> &[u8]; fn set_bytearray(&mut self, value: Vec); - fn integer(&self) -> i32; - fn set_integer(&mut self, value: i32); + fn f32(&self) -> f32; + fn set_f32(&mut self, value: f32); + fn f64(&self) -> f64; + fn set_f64(&mut self, value: f64); + fn i16(&self) -> i16; + fn set_i16(&mut self, value: i16); + fn i32(&self) -> i32; + fn set_i32(&mut self, value: i32); + fn i64(&self) -> i64; + fn set_i64(&mut self, value: i64); + fn i8(&self) -> i8; + fn set_i8(&mut self, value: i8); fn optional_bytearray(&self) -> Option<&[u8]>; fn set_optional_bytearray(&mut self, value: Option>); fn optional_string(&self) -> Option<&str>; fn set_optional_string(&mut self, value: Option); fn string(&self) -> &str; fn set_string(&mut self, value: String); + fn u16(&self) -> u16; + fn set_u16(&mut self, value: u16); + fn u32(&self) -> u32; + fn set_u32(&mut self, value: u32); fn u64(&self) -> u64; fn set_u64(&mut self, value: u64); - fn uinteger(&self) -> u32; - fn set_uinteger(&mut self, value: u32); + fn u8(&self) -> u8; + fn set_u8(&mut self, value: u8); } #[no_mangle] pub extern "C" fn object_new( object: *mut ObjectQObject, boolean_changed: fn(*const ObjectQObject), bytearray_changed: fn(*const ObjectQObject), - integer_changed: fn(*const ObjectQObject), + f32_changed: fn(*const ObjectQObject), + f64_changed: fn(*const ObjectQObject), + i16_changed: fn(*const ObjectQObject), + i32_changed: fn(*const ObjectQObject), + i64_changed: fn(*const ObjectQObject), + i8_changed: fn(*const ObjectQObject), optional_bytearray_changed: fn(*const ObjectQObject), optional_string_changed: fn(*const ObjectQObject), string_changed: fn(*const ObjectQObject), + u16_changed: fn(*const ObjectQObject), + u32_changed: fn(*const ObjectQObject), u64_changed: fn(*const ObjectQObject), - uinteger_changed: fn(*const ObjectQObject), + u8_changed: fn(*const ObjectQObject), ) -> *mut Object { let object_emit = ObjectEmitter { qobject: Arc::new(Mutex::new(object)), boolean_changed: boolean_changed, bytearray_changed: bytearray_changed, - integer_changed: integer_changed, + f32_changed: f32_changed, + f64_changed: f64_changed, + i16_changed: i16_changed, + i32_changed: i32_changed, + i64_changed: i64_changed, + i8_changed: i8_changed, optional_bytearray_changed: optional_bytearray_changed, optional_string_changed: optional_string_changed, string_changed: string_changed, + u16_changed: u16_changed, + u32_changed: u32_changed, u64_changed: u64_changed, - uinteger_changed: uinteger_changed, + u8_changed: u8_changed, }; let d_object = Object::new(object_emit); Box::into_raw(Box::new(d_object)) } #[no_mangle] pub unsafe extern "C" fn object_free(ptr: *mut Object) { Box::from_raw(ptr).emit().clear(); } #[no_mangle] pub unsafe extern "C" fn object_boolean_get(ptr: *const Object) -> bool { (&*ptr).boolean() } #[no_mangle] pub unsafe extern "C" fn object_boolean_set(ptr: *mut Object, v: bool) { (&mut *ptr).set_boolean(v); } #[no_mangle] pub extern "C" fn object_bytearray_get( ptr: *const Object, p: *mut c_void, set: fn(*mut c_void, *const c_char, c_int), ) { let o = unsafe { &*ptr }; let v = o.bytearray(); let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, v.len() as c_int); } #[no_mangle] pub extern "C" fn object_bytearray_set(ptr: *mut Object, v: *const c_char, len: c_int) { let o = unsafe { &mut *ptr }; let v = unsafe { slice::from_raw_parts(v as *const u8, len as usize) }; o.set_bytearray(v.into()); } #[no_mangle] -pub unsafe extern "C" fn object_integer_get(ptr: *const Object) -> i32 { - (&*ptr).integer() +pub unsafe extern "C" fn object_f32_get(ptr: *const Object) -> f32 { + (&*ptr).f32() +} + +#[no_mangle] +pub unsafe extern "C" fn object_f32_set(ptr: *mut Object, v: f32) { + (&mut *ptr).set_f32(v); +} + +#[no_mangle] +pub unsafe extern "C" fn object_f64_get(ptr: *const Object) -> f64 { + (&*ptr).f64() +} + +#[no_mangle] +pub unsafe extern "C" fn object_f64_set(ptr: *mut Object, v: f64) { + (&mut *ptr).set_f64(v); +} + +#[no_mangle] +pub unsafe extern "C" fn object_i16_get(ptr: *const Object) -> i16 { + (&*ptr).i16() +} + +#[no_mangle] +pub unsafe extern "C" fn object_i16_set(ptr: *mut Object, v: i16) { + (&mut *ptr).set_i16(v); +} + +#[no_mangle] +pub unsafe extern "C" fn object_i32_get(ptr: *const Object) -> i32 { + (&*ptr).i32() +} + +#[no_mangle] +pub unsafe extern "C" fn object_i32_set(ptr: *mut Object, v: i32) { + (&mut *ptr).set_i32(v); } #[no_mangle] -pub unsafe extern "C" fn object_integer_set(ptr: *mut Object, v: i32) { - (&mut *ptr).set_integer(v); +pub unsafe extern "C" fn object_i64_get(ptr: *const Object) -> i64 { + (&*ptr).i64() +} + +#[no_mangle] +pub unsafe extern "C" fn object_i64_set(ptr: *mut Object, v: i64) { + (&mut *ptr).set_i64(v); +} + +#[no_mangle] +pub unsafe extern "C" fn object_i8_get(ptr: *const Object) -> i8 { + (&*ptr).i8() +} + +#[no_mangle] +pub unsafe extern "C" fn object_i8_set(ptr: *mut Object, v: i8) { + (&mut *ptr).set_i8(v); } #[no_mangle] pub extern "C" fn object_optional_bytearray_get( ptr: *const Object, p: *mut c_void, set: fn(*mut c_void, *const c_char, c_int), ) { let o = unsafe { &*ptr }; let v = o.optional_bytearray(); if let Some(v) = v { let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, v.len() as c_int); } } #[no_mangle] pub extern "C" fn object_optional_bytearray_set(ptr: *mut Object, v: *const c_char, len: c_int) { let o = unsafe { &mut *ptr }; let v = unsafe { slice::from_raw_parts(v as *const u8, len as usize) }; o.set_optional_bytearray(Some(v.into())); } #[no_mangle] pub extern "C" fn object_optional_bytearray_set_none(ptr: *mut Object) { let o = unsafe { &mut *ptr }; o.set_optional_bytearray(None); } #[no_mangle] pub extern "C" fn object_optional_string_get( ptr: *const Object, p: *mut c_void, set: fn(*mut c_void, *const c_char, c_int), ) { let o = unsafe { &*ptr }; let v = o.optional_string(); if let Some(v) = v { let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, v.len() as c_int); } } #[no_mangle] pub extern "C" fn object_optional_string_set(ptr: *mut Object, v: *const c_ushort, len: c_int) { let o = unsafe { &mut *ptr }; let mut s = String::new(); set_string_from_utf16(&mut s, v, len); o.set_optional_string(Some(s)); } #[no_mangle] pub extern "C" fn object_optional_string_set_none(ptr: *mut Object) { let o = unsafe { &mut *ptr }; o.set_optional_string(None); } #[no_mangle] pub extern "C" fn object_string_get( ptr: *const Object, p: *mut c_void, set: fn(*mut c_void, *const c_char, c_int), ) { let o = unsafe { &*ptr }; let v = o.string(); let s: *const c_char = v.as_ptr() as (*const c_char); set(p, s, v.len() as c_int); } #[no_mangle] pub extern "C" fn object_string_set(ptr: *mut Object, v: *const c_ushort, len: c_int) { let o = unsafe { &mut *ptr }; let mut s = String::new(); set_string_from_utf16(&mut s, v, len); o.set_string(s); } +#[no_mangle] +pub unsafe extern "C" fn object_u16_get(ptr: *const Object) -> u16 { + (&*ptr).u16() +} + +#[no_mangle] +pub unsafe extern "C" fn object_u16_set(ptr: *mut Object, v: u16) { + (&mut *ptr).set_u16(v); +} + +#[no_mangle] +pub unsafe extern "C" fn object_u32_get(ptr: *const Object) -> u32 { + (&*ptr).u32() +} + +#[no_mangle] +pub unsafe extern "C" fn object_u32_set(ptr: *mut Object, v: u32) { + (&mut *ptr).set_u32(v); +} + #[no_mangle] pub unsafe extern "C" fn object_u64_get(ptr: *const Object) -> u64 { (&*ptr).u64() } #[no_mangle] pub unsafe extern "C" fn object_u64_set(ptr: *mut Object, v: u64) { (&mut *ptr).set_u64(v); } #[no_mangle] -pub unsafe extern "C" fn object_uinteger_get(ptr: *const Object) -> u32 { - (&*ptr).uinteger() +pub unsafe extern "C" fn object_u8_get(ptr: *const Object) -> u8 { + (&*ptr).u8() } #[no_mangle] -pub unsafe extern "C" fn object_uinteger_set(ptr: *mut Object, v: u32) { - (&mut *ptr).set_uinteger(v); +pub unsafe extern "C" fn object_u8_set(ptr: *mut Object, v: u8) { + (&mut *ptr).set_u8(v); } diff --git a/tests/test_list_rust.cpp b/tests/test_list_rust.cpp index 65181fb..e4a54f1 100644 --- a/tests/test_list_rust.cpp +++ b/tests/test_list_rust.cpp @@ -1,239 +1,239 @@ /* generated by rust_qt_binding_generator */ #include "test_list_rust.h" namespace { struct option_quintptr { public: quintptr value; bool some; operator QVariant() const { if (some) { return QVariant::fromValue(value); } return QVariant(); } }; static_assert(std::is_pod::value, "option_quintptr must be a POD type."); typedef void (*qstring_set)(QString* val, const char* utf8, int nbytes); void set_qstring(QString* val, const char* utf8, int nbytes) { *val = QString::fromUtf8(utf8, nbytes); } struct qmodelindex_t { int row; quintptr id; }; } extern "C" { void persons_data_user_name(const Persons::Private*, int, QString*, qstring_set); bool persons_set_data_user_name(Persons::Private*, int, const ushort* s, int len); void persons_sort(Persons::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder); int persons_row_count(const Persons::Private*); bool persons_insert_rows(Persons::Private*, int, int); bool persons_remove_rows(Persons::Private*, int, int); bool persons_can_fetch_more(const Persons::Private*); void persons_fetch_more(Persons::Private*); } int Persons::columnCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : 1; } bool Persons::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int Persons::rowCount(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : persons_row_count(m_d); } bool Persons::insertRows(int row, int count, const QModelIndex &parent) { return persons_insert_rows(m_d, row, count); } bool Persons::removeRows(int row, int count, const QModelIndex &parent) { return persons_remove_rows(m_d, row, count); } QModelIndex Persons::index(int row, int column, const QModelIndex &parent) const { if (!parent.isValid() && row >= 0 && row < rowCount(parent) && column >= 0 && column < 1) { return createIndex(row, column, (quintptr)row); } return QModelIndex(); } QModelIndex Persons::parent(const QModelIndex &) const { return QModelIndex(); } bool Persons::canFetchMore(const QModelIndex &parent) const { return (parent.isValid()) ? 0 : persons_can_fetch_more(m_d); } void Persons::fetchMore(const QModelIndex &parent) { if (!parent.isValid()) { persons_fetch_more(m_d); } } void Persons::sort(int column, Qt::SortOrder order) { persons_sort(m_d, column, order); } Qt::ItemFlags Persons::flags(const QModelIndex &i) const { auto flags = QAbstractItemModel::flags(i); if (i.column() == 0) { flags |= Qt::ItemIsEditable; } return flags; } QVariant Persons::userName(int row) const { QVariant v; QString s; persons_data_user_name(m_d, row, &s, set_qstring); if (!s.isNull()) v.setValue(s); return v; } bool Persons::setUserName(int row, const QVariant& value) { + bool set = false; if (!value.canConvert(qMetaTypeId())) { return false; } - bool set = false; const QString s = value.value(); set = persons_set_data_user_name(m_d, row, s.utf16(), s.length()); if (set) { QModelIndex index = createIndex(row, 0, row); emit dataChanged(index, index); } return set; } QVariant Persons::data(const QModelIndex &index, int role) const { Q_ASSERT(rowCount(index.parent()) > index.row()); switch (index.column()) { case 0: switch (role) { case Qt::DisplayRole: case Qt::EditRole: case Qt::UserRole + 0: return userName(index.row()); } } return QVariant(); } QHash Persons::roleNames() const { QHash names = QAbstractItemModel::roleNames(); names.insert(Qt::UserRole + 0, "userName"); return names; } QVariant Persons::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 Persons::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; } bool Persons::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.column() == 0) { if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::UserRole + 0) { return setUserName(index.row(), value); } } return false; } extern "C" { Persons::Private* persons_new(Persons*, void (*)(const Persons*), void (*)(Persons*, quintptr, quintptr), void (*)(Persons*), void (*)(Persons*), void (*)(Persons*, int, int), void (*)(Persons*), void (*)(Persons*, int, int), void (*)(Persons*)); void persons_free(Persons::Private*); }; Persons::Persons(bool /*owned*/, QObject *parent): QAbstractItemModel(parent), m_d(0), m_ownsPrivate(false) { initHeaderData(); } Persons::Persons(QObject *parent): QAbstractItemModel(parent), m_d(persons_new(this, [](const Persons* o) { emit o->newDataReady(QModelIndex()); }, [](Persons* o, quintptr first, quintptr last) { o->dataChanged(o->createIndex(first, 0, first), o->createIndex(last, 0, last)); }, [](Persons* o) { o->beginResetModel(); }, [](Persons* o) { o->endResetModel(); }, [](Persons* o, int first, int last) { o->beginInsertRows(QModelIndex(), first, last); }, [](Persons* o) { o->endInsertRows(); }, [](Persons* o, int first, int last) { o->beginRemoveRows(QModelIndex(), first, last); }, [](Persons* o) { o->endRemoveRows(); } )), m_ownsPrivate(true) { connect(this, &Persons::newDataReady, this, [this](const QModelIndex& i) { this->fetchMore(i); }, Qt::QueuedConnection); initHeaderData(); } Persons::~Persons() { if (m_ownsPrivate) { persons_free(m_d); } } void Persons::initHeaderData() { m_headerData.insert(qMakePair(0, Qt::DisplayRole), QVariant("userName")); } diff --git a/tests/test_list_types.cpp b/tests/test_list_types.cpp new file mode 100644 index 0000000..451a4ac --- /dev/null +++ b/tests/test_list_types.cpp @@ -0,0 +1,274 @@ +/* + * Copyright 2018 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_list_types_rust.h" +#include +#include + +class TestRustListTypes : public QObject +{ + Q_OBJECT +private slots: + void testConstructor(); + void testStringGetter(); + void testStringSetter(); + void testBool(); + void testInt8(); + void testUint8(); + void testInt16(); + void testUint16(); + void testInt32(); + void testUint32(); + void testInt64(); + void testUint64(); + void testFloat(); + void testDouble(); + void testString(); + void testOptionalString(); + void testByteArray(); + void testOptionalByteArray(); +}; + +template +void testSetter(const V v, Set set, Get get) +{ + // GIVEN + List list; + QSignalSpy spy(&list, &List::dataChanged); + + // WHEN + QVariant vv = QVariant::fromValue(v); + if (vv.isNull()) { + vv = QVariant(); + } + bool ok = (list.*set)(0, vv); + QVERIFY(ok); + + // THEN + QVERIFY(spy.isValid()); + QCOMPARE(spy.count(), 1); + QCOMPARE((list.*get)(0), vv); +} + +int getRoleFromName(const QAbstractItemModel& model, const char* name) +{ + auto names = model.roleNames(); + auto i = names.constBegin(); + while (i != names.constEnd()) { + if (i.value() == name) { + return i.key(); + } + ++i; + } + return -1; +} + +template +void testDataSetter(const char* roleName, const V v) +{ + // GIVEN + List list; + QSignalSpy spy(&list, &List::dataChanged); + + // WHEN + int role = getRoleFromName(list, roleName); + auto index = list.index(1, 0); + QVariant vv = QVariant::fromValue(v); + if (vv.isNull()) { + vv = QVariant(); + } + bool ok = list.setData(index, vv, role); + QVERIFY(ok); + + // THEN + QVERIFY(spy.isValid()); + QCOMPARE(spy.count(), 1); + QCOMPARE(list.data(index, role), vv); +} + +template +void test(const V v, Set set, Get get, const char* roleName) +{ + testSetter(v, set, get); + //testDataSetter(roleName, v); +} + +void TestRustListTypes::testConstructor() +{ + List list; +} + +void TestRustListTypes::testBool() +{ + test(true, &List::setBoolean, &List::boolean, "boolean"); + test(false, &List::setBoolean, &List::boolean, "boolean"); +} + +void TestRustListTypes::testInt8() +{ + test(0, &List::setI8, &List::i8, "i8"); + test(1, &List::setI8, &List::i8, "i8"); + test(std::numeric_limits::min(), &List::setI8, &List::i8, "i8"); + test(std::numeric_limits::max(), &List::setI8, &List::i8, "i8"); +} + +void TestRustListTypes::testUint8() +{ + test(0, &List::setU8, &List::u8, "u8"); + test(1, &List::setU8, &List::u8, "u8"); + test(std::numeric_limits::min(), &List::setU8, &List::u8, "u8"); + test(std::numeric_limits::max(), &List::setU8, &List::u8, "u8"); +} + +void TestRustListTypes::testInt16() +{ + test(0, &List::setI16, &List::i16, "i16"); + test(1, &List::setI16, &List::i16, "i16"); + test(std::numeric_limits::min(), &List::setI16, &List::i16, "i16"); + test(std::numeric_limits::max(), &List::setI16, &List::i16, "i16"); +} + +void TestRustListTypes::testUint16() +{ + test(0, &List::setU16, &List::u16, "u16"); + test(1, &List::setU16, &List::u16, "u16"); + test(std::numeric_limits::min(), &List::setU16, &List::u16, "u16"); + test(std::numeric_limits::max(), &List::setU16, &List::u16, "u16"); +} + +void TestRustListTypes::testInt32() +{ + test(0, &List::setI32, &List::i32, "i32"); + test(1, &List::setI32, &List::i32, "i32"); + test(std::numeric_limits::min(), &List::setI32, &List::i32, "i32"); + test(std::numeric_limits::max(), &List::setI32, &List::i32, "i32"); +} + +void TestRustListTypes::testUint32() +{ + test(0, &List::setU32, &List::u32, "u32"); + test(1, &List::setU32, &List::u32, "u32"); + test(std::numeric_limits::min(), &List::setU32, &List::u32, "u32"); + test(std::numeric_limits::max(), &List::setU32, &List::u32, "u32"); +} + +void TestRustListTypes::testInt64() +{ + test(0, &List::setI64, &List::i64, "i64"); + test(1, &List::setI64, &List::i64, "i64"); + test(std::numeric_limits::min(), &List::setI64, &List::i64, "i64"); + test(std::numeric_limits::max(), &List::setI64, &List::i64, "i64"); +} + +void TestRustListTypes::testUint64() +{ + test(0, &List::setU64, &List::u64, "u64"); + test(1, &List::setU64, &List::u64, "u64"); + test(std::numeric_limits::min(), &List::setU64, &List::u64, "u64"); + test(std::numeric_limits::max(), &List::setU64, &List::u64, "u64"); +} + +void TestRustListTypes::testFloat() +{ + test(0, &List::setF32, &List::f32, "f32"); + test(1, &List::setF32, &List::f32, "f32"); + test(std::numeric_limits::min(), &List::setF32, &List::f32, "f32"); + test(std::numeric_limits::max(), &List::setF32, &List::f32, "f32"); +} + +void TestRustListTypes::testDouble() +{ + test(0, &List::setF64, &List::f64, "f64"); + test(1, &List::setF64, &List::f64, "f64"); + test(std::numeric_limits::min(), &List::setF64, &List::f64, "f64"); + test(std::numeric_limits::max(), &List::setF64, &List::f64, "f64"); +} + +void TestRustListTypes::testString() +{ + test(QString(""), &List::setString, &List::string, "string"); + test(QString("Konqi"), &List::setString, &List::string, "string"); + test(QString("$𐐷𤭢"), &List::setString, &List::string, "string"); +} + +void TestRustListTypes::testOptionalString() +{ + test(QString(), &List::setOptionalString, &List::optionalString, + "optionalString"); + test(QString(""), &List::setOptionalString, &List::optionalString, + "optionalString"); + test(QString("Konqi"), &List::setOptionalString, &List::optionalString, + "optionalString"); + test(QString("$𐐷𤭢"), &List::setOptionalString, &List::optionalString, + "optionalString"); +} + +void TestRustListTypes::testByteArray() +{ + const char data[10] = {0x0,0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9}; + test(QByteArray(data, 0), &List::setBytearray, + &List::bytearray, "bytearray"); + test(QByteArray(data, 10), &List::setBytearray, + &List::bytearray, "bytearray"); +} + +void TestRustListTypes::testOptionalByteArray() +{ + test(QByteArray(), &List::setOptionalBytearray, &List::optionalBytearray, + "optionalBytearray"); + const char data[10] = {0x0,0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9}; + test(QByteArray(data, 0), &List::setOptionalBytearray, + &List::optionalBytearray, "optionalBytearray"); + test(QByteArray(data, 10), &List::setOptionalBytearray, + &List::optionalBytearray, "optionalBytearray"); +} + + +void TestRustListTypes::testStringGetter() +{ + List list; + QCOMPARE(list.rowCount(), 10); + QVariant value = list.data(list.index(0,0)); + // value should be empty string in default implementation + QVERIFY(value.isValid()); + QCOMPARE(value.type(), QVariant::String); + QCOMPARE(value.toString(), QString()); +} + +void TestRustListTypes::testStringSetter() +{ + // GIVEN + List list; + QSignalSpy spy(&list, &List::dataChanged); + + // WHEN + const QModelIndex index(list.index(0,0)); + const bool set = list.setData(index, "Konqi"); + + // THEN + QVERIFY(set); + QVERIFY(spy.isValid()); + QCOMPARE(spy.count(), 1); + QVariant value = list.data(list.index(0,0)); + QCOMPARE(value.toString(), QString("Konqi")); +} + +QTEST_MAIN(TestRustListTypes) +#include "test_list_types.moc" diff --git a/tests/test_object_types.json b/tests/test_list_types.json similarity index 52% copy from tests/test_object_types.json copy to tests/test_list_types.json index 5fdb62f..6f4b2a5 100644 --- a/tests/test_object_types.json +++ b/tests/test_list_types.json @@ -1,49 +1,78 @@ { - "cppFile": "test_object_types_rust.cpp", + "cppFile": "test_list_types_rust.cpp", "rust": { - "dir": "rust_object_types", + "dir": "rust_list_types", "interfaceModule": "interface", "implementationModule": "implementation" }, "objects": { - "Object": { - "type": "Object", - "properties": { + "List": { + "type": "List", + "itemProperties": { "boolean": { "type": "bool", "write": true }, - "integer": { + "i8": { + "type": "qint8", + "write": true + }, + "u8": { + "type": "quint8", + "write": true + }, + "i16": { + "type": "qint16", + "write": true + }, + "u16": { + "type": "quint16", + "write": true + }, + "i32": { "type": "qint32", "write": true }, - "uinteger": { + "u32": { "type": "quint32", "write": true }, + "i64": { + "type": "qint64", + "write": true + }, "u64": { "type": "quint64", "write": true }, + "f32": { + "type": "float", + "write": true + }, + "f64": { + "type": "double", + "write": true + }, "string": { "type": "QString", - "write": true + "write": true, + "roles": [ [ "display", "edit" ] ] }, "optionalString": { "type": "QString", "write": true, "optional": true }, "bytearray": { "type": "QByteArray", "write": true }, "optionalBytearray": { "type": "QByteArray", "write": true, "optional": true } } } } } diff --git a/tests/test_list_types_rust.cpp b/tests/test_list_types_rust.cpp new file mode 100644 index 0000000..50b79a6 --- /dev/null +++ b/tests/test_list_types_rust.cpp @@ -0,0 +1,674 @@ +/* generated by rust_qt_binding_generator */ +#include "test_list_types_rust.h" + +namespace { + + struct option_quintptr { + public: + quintptr value; + bool some; + operator QVariant() const { + if (some) { + return QVariant::fromValue(value); + } + return QVariant(); + } + }; + static_assert(std::is_pod::value, "option_quintptr must be a POD type."); + + typedef void (*qstring_set)(QString* val, const char* utf8, int nbytes); + void set_qstring(QString* val, const char* utf8, int nbytes) { + *val = QString::fromUtf8(utf8, nbytes); + } + + typedef void (*qbytearray_set)(QByteArray* val, const char* bytes, int nbytes); + void set_qbytearray(QByteArray* v, const char* bytes, int nbytes) { + if (v->isNull() && nbytes == 0) { + *v = QByteArray(bytes, nbytes); + } else { + v->truncate(0); + v->append(bytes, nbytes); + } + } + + struct qmodelindex_t { + int row; + quintptr id; + }; +} +extern "C" { + bool list_data_boolean(const List::Private*, int); + bool list_set_data_boolean(List::Private*, int, bool); + void list_data_bytearray(const List::Private*, int, QByteArray*, qbytearray_set); + bool list_set_data_bytearray(List::Private*, int, const char* s, int len); + float list_data_f32(const List::Private*, int); + bool list_set_data_f32(List::Private*, int, float); + double list_data_f64(const List::Private*, int); + bool list_set_data_f64(List::Private*, int, double); + qint16 list_data_i16(const List::Private*, int); + bool list_set_data_i16(List::Private*, int, qint16); + qint32 list_data_i32(const List::Private*, int); + bool list_set_data_i32(List::Private*, int, qint32); + qint64 list_data_i64(const List::Private*, int); + bool list_set_data_i64(List::Private*, int, qint64); + qint8 list_data_i8(const List::Private*, int); + bool list_set_data_i8(List::Private*, int, qint8); + void list_data_optional_bytearray(const List::Private*, int, QByteArray*, qbytearray_set); + bool list_set_data_optional_bytearray(List::Private*, int, const char* s, int len); + bool list_set_data_optional_bytearray_none(List::Private*, int); + void list_data_optional_string(const List::Private*, int, QString*, qstring_set); + bool list_set_data_optional_string(List::Private*, int, const ushort* s, int len); + bool list_set_data_optional_string_none(List::Private*, int); + void list_data_string(const List::Private*, int, QString*, qstring_set); + bool list_set_data_string(List::Private*, int, const ushort* s, int len); + uint list_data_u16(const List::Private*, int); + bool list_set_data_u16(List::Private*, int, uint); + uint list_data_u32(const List::Private*, int); + bool list_set_data_u32(List::Private*, int, uint); + quint64 list_data_u64(const List::Private*, int); + bool list_set_data_u64(List::Private*, int, quint64); + quint8 list_data_u8(const List::Private*, int); + bool list_set_data_u8(List::Private*, int, quint8); + void list_sort(List::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder); + + int list_row_count(const List::Private*); + bool list_insert_rows(List::Private*, int, int); + bool list_remove_rows(List::Private*, int, int); + bool list_can_fetch_more(const List::Private*); + void list_fetch_more(List::Private*); +} +int List::columnCount(const QModelIndex &parent) const +{ + return (parent.isValid()) ? 0 : 1; +} + +bool List::hasChildren(const QModelIndex &parent) const +{ + return rowCount(parent) > 0; +} + +int List::rowCount(const QModelIndex &parent) const +{ + return (parent.isValid()) ? 0 : list_row_count(m_d); +} + +bool List::insertRows(int row, int count, const QModelIndex &parent) +{ + return list_insert_rows(m_d, row, count); +} + +bool List::removeRows(int row, int count, const QModelIndex &parent) +{ + return list_remove_rows(m_d, row, count); +} + +QModelIndex List::index(int row, int column, const QModelIndex &parent) const +{ + if (!parent.isValid() && row >= 0 && row < rowCount(parent) && column >= 0 && column < 1) { + return createIndex(row, column, (quintptr)row); + } + return QModelIndex(); +} + +QModelIndex List::parent(const QModelIndex &) const +{ + return QModelIndex(); +} + +bool List::canFetchMore(const QModelIndex &parent) const +{ + return (parent.isValid()) ? 0 : list_can_fetch_more(m_d); +} + +void List::fetchMore(const QModelIndex &parent) +{ + if (!parent.isValid()) { + list_fetch_more(m_d); + } +} + +void List::sort(int column, Qt::SortOrder order) +{ + list_sort(m_d, column, order); +} +Qt::ItemFlags List::flags(const QModelIndex &i) const +{ + auto flags = QAbstractItemModel::flags(i); + if (i.column() == 0) { + flags |= Qt::ItemIsEditable; + } + return flags; +} + +QVariant List::boolean(int row) const +{ + QVariant v; + v.setValue(list_data_boolean(m_d, row)); + return v; +} + +bool List::setBoolean(int row, const QVariant& value) +{ + bool set = false; + if (!value.canConvert(qMetaTypeId())) { + return false; + } + set = list_set_data_boolean(m_d, row, value.value()); + if (set) { + QModelIndex index = createIndex(row, 0, row); + emit dataChanged(index, index); + } + return set; +} + +QVariant List::bytearray(int row) const +{ + QVariant v; + QByteArray b; + list_data_bytearray(m_d, row, &b, set_qbytearray); + if (!b.isNull()) v.setValue(b); + return v; +} + +bool List::setBytearray(int row, const QVariant& value) +{ + bool set = false; + if (!value.canConvert(qMetaTypeId())) { + return false; + } + const QByteArray s = value.value(); + set = list_set_data_bytearray(m_d, row, s.data(), s.length()); + if (set) { + QModelIndex index = createIndex(row, 0, row); + emit dataChanged(index, index); + } + return set; +} + +QVariant List::f32(int row) const +{ + QVariant v; + v.setValue(list_data_f32(m_d, row)); + return v; +} + +bool List::setF32(int row, const QVariant& value) +{ + bool set = false; + if (!value.canConvert(qMetaTypeId())) { + return false; + } + set = list_set_data_f32(m_d, row, value.value()); + if (set) { + QModelIndex index = createIndex(row, 0, row); + emit dataChanged(index, index); + } + return set; +} + +QVariant List::f64(int row) const +{ + QVariant v; + v.setValue(list_data_f64(m_d, row)); + return v; +} + +bool List::setF64(int row, const QVariant& value) +{ + bool set = false; + if (!value.canConvert(qMetaTypeId())) { + return false; + } + set = list_set_data_f64(m_d, row, value.value()); + if (set) { + QModelIndex index = createIndex(row, 0, row); + emit dataChanged(index, index); + } + return set; +} + +QVariant List::i16(int row) const +{ + QVariant v; + v.setValue(list_data_i16(m_d, row)); + return v; +} + +bool List::setI16(int row, const QVariant& value) +{ + bool set = false; + if (!value.canConvert(qMetaTypeId())) { + return false; + } + set = list_set_data_i16(m_d, row, value.value()); + if (set) { + QModelIndex index = createIndex(row, 0, row); + emit dataChanged(index, index); + } + return set; +} + +QVariant List::i32(int row) const +{ + QVariant v; + v.setValue(list_data_i32(m_d, row)); + return v; +} + +bool List::setI32(int row, const QVariant& value) +{ + bool set = false; + if (!value.canConvert(qMetaTypeId())) { + return false; + } + set = list_set_data_i32(m_d, row, value.value()); + if (set) { + QModelIndex index = createIndex(row, 0, row); + emit dataChanged(index, index); + } + return set; +} + +QVariant List::i64(int row) const +{ + QVariant v; + v.setValue(list_data_i64(m_d, row)); + return v; +} + +bool List::setI64(int row, const QVariant& value) +{ + bool set = false; + if (!value.canConvert(qMetaTypeId())) { + return false; + } + set = list_set_data_i64(m_d, row, value.value()); + if (set) { + QModelIndex index = createIndex(row, 0, row); + emit dataChanged(index, index); + } + return set; +} + +QVariant List::i8(int row) const +{ + QVariant v; + v.setValue(list_data_i8(m_d, row)); + return v; +} + +bool List::setI8(int row, const QVariant& value) +{ + bool set = false; + if (!value.canConvert(qMetaTypeId())) { + return false; + } + set = list_set_data_i8(m_d, row, value.value()); + if (set) { + QModelIndex index = createIndex(row, 0, row); + emit dataChanged(index, index); + } + return set; +} + +QVariant List::optionalBytearray(int row) const +{ + QVariant v; + QByteArray b; + list_data_optional_bytearray(m_d, row, &b, set_qbytearray); + if (!b.isNull()) v.setValue(b); + return v; +} + +bool List::setOptionalBytearray(int row, const QVariant& value) +{ + bool set = false; + if (!value.isValid() || value.isNull()) { + set = list_set_data_optional_bytearray_none(m_d, row); + } else { + if (!value.canConvert(qMetaTypeId())) { + return false; + } + const QByteArray s = value.value(); + set = list_set_data_optional_bytearray(m_d, row, s.data(), s.length()); + } + if (set) { + QModelIndex index = createIndex(row, 0, row); + emit dataChanged(index, index); + } + return set; +} + +QVariant List::optionalString(int row) const +{ + QVariant v; + QString s; + list_data_optional_string(m_d, row, &s, set_qstring); + if (!s.isNull()) v.setValue(s); + return v; +} + +bool List::setOptionalString(int row, const QVariant& value) +{ + bool set = false; + if (!value.isValid() || value.isNull()) { + set = list_set_data_optional_string_none(m_d, row); + } else { + if (!value.canConvert(qMetaTypeId())) { + return false; + } + const QString s = value.value(); + set = list_set_data_optional_string(m_d, row, s.utf16(), s.length()); + } + if (set) { + QModelIndex index = createIndex(row, 0, row); + emit dataChanged(index, index); + } + return set; +} + +QVariant List::string(int row) const +{ + QVariant v; + QString s; + list_data_string(m_d, row, &s, set_qstring); + if (!s.isNull()) v.setValue(s); + return v; +} + +bool List::setString(int row, const QVariant& value) +{ + bool set = false; + if (!value.canConvert(qMetaTypeId())) { + return false; + } + const QString s = value.value(); + set = list_set_data_string(m_d, row, s.utf16(), s.length()); + if (set) { + QModelIndex index = createIndex(row, 0, row); + emit dataChanged(index, index); + } + return set; +} + +QVariant List::u16(int row) const +{ + QVariant v; + v.setValue(list_data_u16(m_d, row)); + return v; +} + +bool List::setU16(int row, const QVariant& value) +{ + bool set = false; + if (!value.canConvert(qMetaTypeId())) { + return false; + } + set = list_set_data_u16(m_d, row, value.value()); + if (set) { + QModelIndex index = createIndex(row, 0, row); + emit dataChanged(index, index); + } + return set; +} + +QVariant List::u32(int row) const +{ + QVariant v; + v.setValue(list_data_u32(m_d, row)); + return v; +} + +bool List::setU32(int row, const QVariant& value) +{ + bool set = false; + if (!value.canConvert(qMetaTypeId())) { + return false; + } + set = list_set_data_u32(m_d, row, value.value()); + if (set) { + QModelIndex index = createIndex(row, 0, row); + emit dataChanged(index, index); + } + return set; +} + +QVariant List::u64(int row) const +{ + QVariant v; + v.setValue(list_data_u64(m_d, row)); + return v; +} + +bool List::setU64(int row, const QVariant& value) +{ + bool set = false; + if (!value.canConvert(qMetaTypeId())) { + return false; + } + set = list_set_data_u64(m_d, row, value.value()); + if (set) { + QModelIndex index = createIndex(row, 0, row); + emit dataChanged(index, index); + } + return set; +} + +QVariant List::u8(int row) const +{ + QVariant v; + v.setValue(list_data_u8(m_d, row)); + return v; +} + +bool List::setU8(int row, const QVariant& value) +{ + bool set = false; + if (!value.canConvert(qMetaTypeId())) { + return false; + } + set = list_set_data_u8(m_d, row, value.value()); + if (set) { + QModelIndex index = createIndex(row, 0, row); + emit dataChanged(index, index); + } + return set; +} + +QVariant List::data(const QModelIndex &index, int role) const +{ + Q_ASSERT(rowCount(index.parent()) > index.row()); + switch (index.column()) { + case 0: + switch (role) { + case Qt::UserRole + 0: + return boolean(index.row()); + case Qt::UserRole + 1: + return bytearray(index.row()); + case Qt::UserRole + 2: + return f32(index.row()); + case Qt::UserRole + 3: + return f64(index.row()); + case Qt::UserRole + 4: + return i16(index.row()); + case Qt::UserRole + 5: + return i32(index.row()); + case Qt::UserRole + 6: + return i64(index.row()); + case Qt::UserRole + 7: + return i8(index.row()); + case Qt::UserRole + 8: + return optionalBytearray(index.row()); + case Qt::UserRole + 9: + return optionalString(index.row()); + case Qt::DisplayRole: + case Qt::EditRole: + case Qt::UserRole + 10: + return string(index.row()); + case Qt::UserRole + 11: + return u16(index.row()); + case Qt::UserRole + 12: + return u32(index.row()); + case Qt::UserRole + 13: + return u64(index.row()); + case Qt::UserRole + 14: + return u8(index.row()); + } + } + return QVariant(); +} + +QHash List::roleNames() const { + QHash names = QAbstractItemModel::roleNames(); + names.insert(Qt::UserRole + 0, "boolean"); + names.insert(Qt::UserRole + 1, "bytearray"); + names.insert(Qt::UserRole + 2, "f32"); + names.insert(Qt::UserRole + 3, "f64"); + names.insert(Qt::UserRole + 4, "i16"); + names.insert(Qt::UserRole + 5, "i32"); + names.insert(Qt::UserRole + 6, "i64"); + names.insert(Qt::UserRole + 7, "i8"); + names.insert(Qt::UserRole + 8, "optionalBytearray"); + names.insert(Qt::UserRole + 9, "optionalString"); + names.insert(Qt::UserRole + 10, "string"); + names.insert(Qt::UserRole + 11, "u16"); + names.insert(Qt::UserRole + 12, "u32"); + names.insert(Qt::UserRole + 13, "u64"); + names.insert(Qt::UserRole + 14, "u8"); + return names; +} +QVariant List::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 List::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; +} + +bool List::setData(const QModelIndex &index, const QVariant &value, int role) +{ + if (index.column() == 0) { + if (role == Qt::UserRole + 0) { + return setBoolean(index.row(), value); + } + if (role == Qt::UserRole + 1) { + return setBytearray(index.row(), value); + } + if (role == Qt::UserRole + 2) { + return setF32(index.row(), value); + } + if (role == Qt::UserRole + 3) { + return setF64(index.row(), value); + } + if (role == Qt::UserRole + 4) { + return setI16(index.row(), value); + } + if (role == Qt::UserRole + 5) { + return setI32(index.row(), value); + } + if (role == Qt::UserRole + 6) { + return setI64(index.row(), value); + } + if (role == Qt::UserRole + 7) { + return setI8(index.row(), value); + } + if (role == Qt::UserRole + 8) { + return setOptionalBytearray(index.row(), value); + } + if (role == Qt::UserRole + 9) { + return setOptionalString(index.row(), value); + } + if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::UserRole + 10) { + return setString(index.row(), value); + } + if (role == Qt::UserRole + 11) { + return setU16(index.row(), value); + } + if (role == Qt::UserRole + 12) { + return setU32(index.row(), value); + } + if (role == Qt::UserRole + 13) { + return setU64(index.row(), value); + } + if (role == Qt::UserRole + 14) { + return setU8(index.row(), value); + } + } + return false; +} + +extern "C" { + List::Private* list_new(List*, + void (*)(const List*), + void (*)(List*, quintptr, quintptr), + void (*)(List*), + void (*)(List*), + void (*)(List*, int, int), + void (*)(List*), + void (*)(List*, int, int), + void (*)(List*)); + void list_free(List::Private*); +}; + +List::List(bool /*owned*/, QObject *parent): + QAbstractItemModel(parent), + m_d(0), + m_ownsPrivate(false) +{ + initHeaderData(); +} + +List::List(QObject *parent): + QAbstractItemModel(parent), + m_d(list_new(this, + [](const List* o) { + emit o->newDataReady(QModelIndex()); + }, + [](List* o, quintptr first, quintptr last) { + o->dataChanged(o->createIndex(first, 0, first), + o->createIndex(last, 0, last)); + }, + [](List* o) { + o->beginResetModel(); + }, + [](List* o) { + o->endResetModel(); + }, + [](List* o, int first, int last) { + o->beginInsertRows(QModelIndex(), first, last); + }, + [](List* o) { + o->endInsertRows(); + }, + [](List* o, int first, int last) { + o->beginRemoveRows(QModelIndex(), first, last); + }, + [](List* o) { + o->endRemoveRows(); + } +)), + m_ownsPrivate(true) +{ + connect(this, &List::newDataReady, this, [this](const QModelIndex& i) { + this->fetchMore(i); + }, Qt::QueuedConnection); + initHeaderData(); +} + +List::~List() { + if (m_ownsPrivate) { + list_free(m_d); + } +} +void List::initHeaderData() { + m_headerData.insert(qMakePair(0, Qt::DisplayRole), QVariant("string")); +} diff --git a/tests/test_list_types_rust.h b/tests/test_list_types_rust.h new file mode 100644 index 0000000..1c84341 --- /dev/null +++ b/tests/test_list_types_rust.h @@ -0,0 +1,78 @@ +/* generated by rust_qt_binding_generator */ +#ifndef TEST_LIST_TYPES_RUST_H +#define TEST_LIST_TYPES_RUST_H + +#include +#include + +class List; + +class List : public QAbstractItemModel +{ + Q_OBJECT +public: + class Private; +private: + Private * m_d; + bool m_ownsPrivate; + explicit List(bool owned, QObject *parent); +public: + explicit List(QObject *parent = nullptr); + ~List(); + + 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; + bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; + Q_INVOKABLE QVariant boolean(int row) const; + Q_INVOKABLE bool setBoolean(int row, const QVariant& value); + Q_INVOKABLE QVariant bytearray(int row) const; + Q_INVOKABLE bool setBytearray(int row, const QVariant& value); + Q_INVOKABLE QVariant f32(int row) const; + Q_INVOKABLE bool setF32(int row, const QVariant& value); + Q_INVOKABLE QVariant f64(int row) const; + Q_INVOKABLE bool setF64(int row, const QVariant& value); + Q_INVOKABLE QVariant i16(int row) const; + Q_INVOKABLE bool setI16(int row, const QVariant& value); + Q_INVOKABLE QVariant i32(int row) const; + Q_INVOKABLE bool setI32(int row, const QVariant& value); + Q_INVOKABLE QVariant i64(int row) const; + Q_INVOKABLE bool setI64(int row, const QVariant& value); + Q_INVOKABLE QVariant i8(int row) const; + Q_INVOKABLE bool setI8(int row, const QVariant& value); + Q_INVOKABLE QVariant optionalBytearray(int row) const; + Q_INVOKABLE bool setOptionalBytearray(int row, const QVariant& value); + Q_INVOKABLE QVariant optionalString(int row) const; + Q_INVOKABLE bool setOptionalString(int row, const QVariant& value); + Q_INVOKABLE QVariant string(int row) const; + Q_INVOKABLE bool setString(int row, const QVariant& value); + Q_INVOKABLE QVariant u16(int row) const; + Q_INVOKABLE bool setU16(int row, const QVariant& value); + Q_INVOKABLE QVariant u32(int row) const; + Q_INVOKABLE bool setU32(int row, const QVariant& value); + Q_INVOKABLE QVariant u64(int row) const; + Q_INVOKABLE bool setU64(int row, const QVariant& value); + Q_INVOKABLE QVariant u8(int row) const; + Q_INVOKABLE bool setU8(int row, const QVariant& value); + +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(); +signals: +}; +#endif // TEST_LIST_TYPES_RUST_H diff --git a/tests/test_object_types.cpp b/tests/test_object_types.cpp index d194b47..682a6bb 100644 --- a/tests/test_object_types.cpp +++ b/tests/test_object_types.cpp @@ -1,127 +1,218 @@ #include "test_object_types_rust.h" #include #include #include class TestRustObjectTypes : public QObject { Q_OBJECT private slots: void testBool(); - void testInteger(); - void testUinteger(); + void testInt8(); + void testUint8(); + void testInt16(); + void testUint16(); + void testInt32(); + void testUint32(); + void testInt64(); void testUint64(); + void testFloat(); + void testDouble(); void testString(); void testOptionalString(); void testByteArray(); void testOptionalByteArray(); }; template void testSetter(const V v, Set set, Get get, Changed changed) { // GIVEN Object object; QSignalSpy spy(&object, changed); // WHEN (object.*set)((V)v); // THEN QVERIFY(spy.isValid()); QCOMPARE(spy.count(), 1); QCOMPARE((V)(object.*get)(), (V)v); } void TestRustObjectTypes::testBool() { testSetter(true, &Object::setBoolean, &Object::boolean, &Object::booleanChanged); testSetter(false, &Object::setBoolean, &Object::boolean, &Object::booleanChanged); } -void TestRustObjectTypes::testInteger() +void TestRustObjectTypes::testInt8() { - testSetter(0, &Object::setInteger, - &Object::integer, &Object::integerChanged); - testSetter(1, &Object::setInteger, - &Object::integer, &Object::integerChanged); - testSetter(std::numeric_limits::min(), &Object::setInteger, - &Object::integer, &Object::integerChanged); - testSetter(std::numeric_limits::max(), &Object::setInteger, - &Object::integer, &Object::integerChanged); + testSetter(0, &Object::setI8, + &Object::i8, &Object::i8Changed); + testSetter(1, &Object::setI8, + &Object::i8, &Object::i8Changed); + testSetter(std::numeric_limits::min(), &Object::setI8, + &Object::i8, &Object::i8Changed); + testSetter(std::numeric_limits::max(), &Object::setI8, + &Object::i8, &Object::i8Changed); } -void TestRustObjectTypes::testUinteger() +void TestRustObjectTypes::testUint8() { - testSetter(0, &Object::setUinteger, - &Object::uinteger, &Object::uintegerChanged); - testSetter(1, &Object::setUinteger, - &Object::uinteger, &Object::uintegerChanged); - testSetter(std::numeric_limits::min(), &Object::setUinteger, - &Object::uinteger, &Object::uintegerChanged); - testSetter(std::numeric_limits::max(), &Object::setUinteger, - &Object::uinteger, &Object::uintegerChanged); + testSetter(0, &Object::setU8, + &Object::u8, &Object::u8Changed); + testSetter(1, &Object::setU8, + &Object::u8, &Object::u8Changed); + testSetter(std::numeric_limits::min(), &Object::setU8, + &Object::u8, &Object::u8Changed); + testSetter(std::numeric_limits::max(), &Object::setU8, + &Object::u8, &Object::u8Changed); +} + +void TestRustObjectTypes::testInt16() +{ + testSetter(0, &Object::setI16, + &Object::i16, &Object::i16Changed); + testSetter(1, &Object::setI16, + &Object::i16, &Object::i16Changed); + testSetter(std::numeric_limits::min(), &Object::setI16, + &Object::i16, &Object::i16Changed); + testSetter(std::numeric_limits::max(), &Object::setI16, + &Object::i16, &Object::i16Changed); +} + +void TestRustObjectTypes::testUint16() +{ + testSetter(0, &Object::setU16, + &Object::u16, &Object::u16Changed); + testSetter(1, &Object::setU16, + &Object::u16, &Object::u16Changed); + testSetter(std::numeric_limits::min(), &Object::setU16, + &Object::u16, &Object::u16Changed); + testSetter(std::numeric_limits::max(), &Object::setU16, + &Object::u16, &Object::u16Changed); +} + +void TestRustObjectTypes::testInt32() +{ + testSetter(0, &Object::setI32, + &Object::i32, &Object::i32Changed); + testSetter(1, &Object::setI32, + &Object::i32, &Object::i32Changed); + testSetter(std::numeric_limits::min(), &Object::setI32, + &Object::i32, &Object::i32Changed); + testSetter(std::numeric_limits::max(), &Object::setI32, + &Object::i32, &Object::i32Changed); +} + +void TestRustObjectTypes::testUint32() +{ + testSetter(0, &Object::setU32, + &Object::u32, &Object::u32Changed); + testSetter(1, &Object::setU32, + &Object::u32, &Object::u32Changed); + testSetter(std::numeric_limits::min(), &Object::setU32, + &Object::u32, &Object::u32Changed); + testSetter(std::numeric_limits::max(), &Object::setU32, + &Object::u32, &Object::u32Changed); +} + +void TestRustObjectTypes::testInt64() +{ + testSetter(0, &Object::setI64, + &Object::i64, &Object::i64Changed); + testSetter(1, &Object::setI64, + &Object::i64, &Object::i64Changed); + testSetter(std::numeric_limits::min(), &Object::setI64, + &Object::i64, &Object::i64Changed); + testSetter(std::numeric_limits::max(), &Object::setI64, + &Object::i64, &Object::i64Changed); } void TestRustObjectTypes::testUint64() { testSetter(0, &Object::setU64, &Object::u64, &Object::u64Changed); testSetter(1, &Object::setU64, &Object::u64, &Object::u64Changed); - testSetter(std::numeric_limits::min(), &Object::setU64, + testSetter(std::numeric_limits::min(), &Object::setU64, &Object::u64, &Object::u64Changed); - testSetter(std::numeric_limits::max(), &Object::setU64, + testSetter(std::numeric_limits::max(), &Object::setU64, &Object::u64, &Object::u64Changed); } +void TestRustObjectTypes::testFloat() +{ + testSetter(0, &Object::setF32, + &Object::f32, &Object::f32Changed); + testSetter(1, &Object::setF32, + &Object::f32, &Object::f32Changed); + testSetter(std::numeric_limits::min(), &Object::setF32, + &Object::f32, &Object::f32Changed); + testSetter(std::numeric_limits::max(), &Object::setF32, + &Object::f32, &Object::f32Changed); +} + +void TestRustObjectTypes::testDouble() +{ + testSetter(0, &Object::setF64, + &Object::f64, &Object::f64Changed); + testSetter(1, &Object::setF64, + &Object::f64, &Object::f64Changed); + testSetter(std::numeric_limits::min(), &Object::setF64, + &Object::f64, &Object::f64Changed); + testSetter(std::numeric_limits::max(), &Object::setF64, + &Object::f64, &Object::f64Changed); +} + void TestRustObjectTypes::testString() { testSetter(QString(), &Object::setString, &Object::string, &Object::stringChanged); testSetter(QString(""), &Object::setString, &Object::string, &Object::stringChanged); testSetter(QString("Konqi"), &Object::setString, &Object::string, &Object::stringChanged); testSetter(QString("$𐐷𤭢"), &Object::setString, &Object::string, &Object::stringChanged); } void TestRustObjectTypes::testOptionalString() { testSetter(QString(), &Object::setOptionalString, &Object::optionalString, &Object::optionalStringChanged); testSetter(QString(""), &Object::setOptionalString, &Object::optionalString, &Object::optionalStringChanged); testSetter(QString("Konqi"), &Object::setOptionalString, &Object::optionalString, &Object::optionalStringChanged); testSetter(QString("$𐐷𤭢"), &Object::setOptionalString, &Object::optionalString, &Object::optionalStringChanged); } void TestRustObjectTypes::testByteArray() { testSetter(QByteArray(), &Object::setBytearray, &Object::bytearray, &Object::bytearrayChanged); const char data[10] = {0x0,0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9}; testSetter(QByteArray(data, 0), &Object::setBytearray, &Object::bytearray, &Object::bytearrayChanged); testSetter(QByteArray(data, 10), &Object::setBytearray, &Object::bytearray, &Object::bytearrayChanged); } void TestRustObjectTypes::testOptionalByteArray() { testSetter(QByteArray(), &Object::setOptionalBytearray, &Object::optionalBytearray, &Object::optionalBytearrayChanged); const char data[10] = {0x0,0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9}; testSetter(QByteArray(data, 0), &Object::setOptionalBytearray, &Object::optionalBytearray, &Object::optionalBytearrayChanged); testSetter(QByteArray(data, 10), &Object::setOptionalBytearray, &Object::optionalBytearray, &Object::optionalBytearrayChanged); } QTEST_MAIN(TestRustObjectTypes) #include "test_object_types.moc" diff --git a/tests/test_object_types.json b/tests/test_object_types.json index 5fdb62f..656d149 100644 --- a/tests/test_object_types.json +++ b/tests/test_object_types.json @@ -1,49 +1,77 @@ { "cppFile": "test_object_types_rust.cpp", "rust": { "dir": "rust_object_types", "interfaceModule": "interface", "implementationModule": "implementation" }, "objects": { "Object": { "type": "Object", "properties": { "boolean": { "type": "bool", "write": true }, - "integer": { + "i8": { + "type": "qint8", + "write": true + }, + "u8": { + "type": "quint8", + "write": true + }, + "i16": { + "type": "qint16", + "write": true + }, + "u16": { + "type": "quint16", + "write": true + }, + "i32": { "type": "qint32", "write": true }, - "uinteger": { + "u32": { "type": "quint32", "write": true }, + "i64": { + "type": "qint64", + "write": true + }, "u64": { "type": "quint64", "write": true }, + "f32": { + "type": "float", + "write": true + }, + "f64": { + "type": "double", + "write": true + }, "string": { "type": "QString", "write": true }, "optionalString": { "type": "QString", "write": true, "optional": true }, "bytearray": { "type": "QByteArray", "write": true }, "optionalBytearray": { "type": "QByteArray", "write": true, "optional": true } } } } } diff --git a/tests/test_object_types_rust.cpp b/tests/test_object_types_rust.cpp index b095f23..4544677 100644 --- a/tests/test_object_types_rust.cpp +++ b/tests/test_object_types_rust.cpp @@ -1,170 +1,272 @@ /* generated by rust_qt_binding_generator */ #include "test_object_types_rust.h" namespace { typedef void (*qstring_set)(QString* val, const char* utf8, int nbytes); void set_qstring(QString* val, const char* utf8, int nbytes) { *val = QString::fromUtf8(utf8, nbytes); } typedef void (*qbytearray_set)(QByteArray* val, const char* bytes, int nbytes); void set_qbytearray(QByteArray* v, const char* bytes, int nbytes) { - v->truncate(0); - v->append(bytes, nbytes); + if (v->isNull() && nbytes == 0) { + *v = QByteArray(bytes, nbytes); + } else { + v->truncate(0); + v->append(bytes, nbytes); + } } inline void objectBooleanChanged(Object* o) { emit o->booleanChanged(); } inline void objectBytearrayChanged(Object* o) { emit o->bytearrayChanged(); } - inline void objectIntegerChanged(Object* o) + inline void objectF32Changed(Object* o) { - emit o->integerChanged(); + emit o->f32Changed(); + } + inline void objectF64Changed(Object* o) + { + emit o->f64Changed(); + } + inline void objectI16Changed(Object* o) + { + emit o->i16Changed(); + } + inline void objectI32Changed(Object* o) + { + emit o->i32Changed(); + } + inline void objectI64Changed(Object* o) + { + emit o->i64Changed(); + } + inline void objectI8Changed(Object* o) + { + emit o->i8Changed(); } inline void objectOptionalBytearrayChanged(Object* o) { emit o->optionalBytearrayChanged(); } inline void objectOptionalStringChanged(Object* o) { emit o->optionalStringChanged(); } inline void objectStringChanged(Object* o) { emit o->stringChanged(); } + inline void objectU16Changed(Object* o) + { + emit o->u16Changed(); + } + inline void objectU32Changed(Object* o) + { + emit o->u32Changed(); + } inline void objectU64Changed(Object* o) { emit o->u64Changed(); } - inline void objectUintegerChanged(Object* o) + inline void objectU8Changed(Object* o) { - emit o->uintegerChanged(); + emit o->u8Changed(); } } extern "C" { - Object::Private* object_new(Object*, void (*)(Object*), void (*)(Object*), void (*)(Object*), void (*)(Object*), void (*)(Object*), void (*)(Object*), void (*)(Object*), void (*)(Object*)); + Object::Private* object_new(Object*, void (*)(Object*), void (*)(Object*), void (*)(Object*), void (*)(Object*), void (*)(Object*), void (*)(Object*), void (*)(Object*), void (*)(Object*), void (*)(Object*), void (*)(Object*), void (*)(Object*), void (*)(Object*), void (*)(Object*), void (*)(Object*), void (*)(Object*)); void object_free(Object::Private*); bool object_boolean_get(const Object::Private*); void object_boolean_set(Object::Private*, bool); void object_bytearray_get(const Object::Private*, QByteArray*, qbytearray_set); void object_bytearray_set(Object::Private*, const char* bytes, int len); - qint32 object_integer_get(const Object::Private*); - void object_integer_set(Object::Private*, qint32); + float object_f32_get(const Object::Private*); + void object_f32_set(Object::Private*, float); + double object_f64_get(const Object::Private*); + void object_f64_set(Object::Private*, double); + qint16 object_i16_get(const Object::Private*); + void object_i16_set(Object::Private*, qint16); + qint32 object_i32_get(const Object::Private*); + void object_i32_set(Object::Private*, qint32); + qint64 object_i64_get(const Object::Private*); + void object_i64_set(Object::Private*, qint64); + qint8 object_i8_get(const Object::Private*); + void object_i8_set(Object::Private*, qint8); void object_optional_bytearray_get(const Object::Private*, QByteArray*, qbytearray_set); void object_optional_bytearray_set(Object::Private*, const char* bytes, int len); void object_optional_bytearray_set_none(Object::Private*); void object_optional_string_get(const Object::Private*, QString*, qstring_set); void object_optional_string_set(Object::Private*, const ushort *str, int len); void object_optional_string_set_none(Object::Private*); void object_string_get(const Object::Private*, QString*, qstring_set); void object_string_set(Object::Private*, const ushort *str, int len); + quint16 object_u16_get(const Object::Private*); + void object_u16_set(Object::Private*, uint); + quint32 object_u32_get(const Object::Private*); + void object_u32_set(Object::Private*, uint); quint64 object_u64_get(const Object::Private*); void object_u64_set(Object::Private*, quint64); - quint32 object_uinteger_get(const Object::Private*); - void object_uinteger_set(Object::Private*, uint); + quint8 object_u8_get(const Object::Private*); + void object_u8_set(Object::Private*, quint8); }; Object::Object(bool /*owned*/, QObject *parent): QObject(parent), m_d(0), m_ownsPrivate(false) { } Object::Object(QObject *parent): QObject(parent), m_d(object_new(this, objectBooleanChanged, objectBytearrayChanged, - objectIntegerChanged, + objectF32Changed, + objectF64Changed, + objectI16Changed, + objectI32Changed, + objectI64Changed, + objectI8Changed, objectOptionalBytearrayChanged, objectOptionalStringChanged, objectStringChanged, + objectU16Changed, + objectU32Changed, objectU64Changed, - objectUintegerChanged)), + objectU8Changed)), m_ownsPrivate(true) { } Object::~Object() { if (m_ownsPrivate) { object_free(m_d); } } bool Object::boolean() const { return object_boolean_get(m_d); } void Object::setBoolean(bool v) { object_boolean_set(m_d, v); } QByteArray Object::bytearray() const { QByteArray v; object_bytearray_get(m_d, &v, set_qbytearray); return v; } void Object::setBytearray(const QByteArray& v) { object_bytearray_set(m_d, v.data(), v.size()); } -qint32 Object::integer() const +float Object::f32() const { - return object_integer_get(m_d); + return object_f32_get(m_d); } -void Object::setInteger(qint32 v) { - object_integer_set(m_d, v); +void Object::setF32(float v) { + object_f32_set(m_d, v); +} +double Object::f64() const +{ + return object_f64_get(m_d); +} +void Object::setF64(double v) { + object_f64_set(m_d, v); +} +qint16 Object::i16() const +{ + return object_i16_get(m_d); +} +void Object::setI16(qint16 v) { + object_i16_set(m_d, v); +} +qint32 Object::i32() const +{ + return object_i32_get(m_d); +} +void Object::setI32(qint32 v) { + object_i32_set(m_d, v); +} +qint64 Object::i64() const +{ + return object_i64_get(m_d); +} +void Object::setI64(qint64 v) { + object_i64_set(m_d, v); +} +qint8 Object::i8() const +{ + return object_i8_get(m_d); +} +void Object::setI8(qint8 v) { + object_i8_set(m_d, v); } QByteArray Object::optionalBytearray() const { QByteArray v; object_optional_bytearray_get(m_d, &v, set_qbytearray); return v; } void Object::setOptionalBytearray(const QByteArray& v) { if (v.isNull()) { object_optional_bytearray_set_none(m_d); } else { object_optional_bytearray_set(m_d, v.data(), v.size()); } } QString Object::optionalString() const { QString v; object_optional_string_get(m_d, &v, set_qstring); return v; } void Object::setOptionalString(const QString& v) { if (v.isNull()) { object_optional_string_set_none(m_d); } else { object_optional_string_set(m_d, reinterpret_cast(v.data()), v.size()); } } QString Object::string() const { QString v; object_string_get(m_d, &v, set_qstring); return v; } void Object::setString(const QString& v) { object_string_set(m_d, reinterpret_cast(v.data()), v.size()); } +quint16 Object::u16() const +{ + return object_u16_get(m_d); +} +void Object::setU16(uint v) { + object_u16_set(m_d, v); +} +quint32 Object::u32() const +{ + return object_u32_get(m_d); +} +void Object::setU32(uint v) { + object_u32_set(m_d, v); +} quint64 Object::u64() const { return object_u64_get(m_d); } void Object::setU64(quint64 v) { object_u64_set(m_d, v); } -quint32 Object::uinteger() const +quint8 Object::u8() const { - return object_uinteger_get(m_d); + return object_u8_get(m_d); } -void Object::setUinteger(uint v) { - object_uinteger_set(m_d, v); +void Object::setU8(quint8 v) { + object_u8_set(m_d, v); } diff --git a/tests/test_object_types_rust.h b/tests/test_object_types_rust.h index 95aeb59..18bf7c0 100644 --- a/tests/test_object_types_rust.h +++ b/tests/test_object_types_rust.h @@ -1,56 +1,84 @@ /* generated by rust_qt_binding_generator */ #ifndef TEST_OBJECT_TYPES_RUST_H #define TEST_OBJECT_TYPES_RUST_H #include #include class Object; class Object : public QObject { Q_OBJECT public: class Private; private: Private * m_d; bool m_ownsPrivate; Q_PROPERTY(bool boolean READ boolean WRITE setBoolean NOTIFY booleanChanged FINAL) Q_PROPERTY(QByteArray bytearray READ bytearray WRITE setBytearray NOTIFY bytearrayChanged FINAL) - Q_PROPERTY(qint32 integer READ integer WRITE setInteger NOTIFY integerChanged FINAL) + Q_PROPERTY(float f32 READ f32 WRITE setF32 NOTIFY f32Changed FINAL) + Q_PROPERTY(double f64 READ f64 WRITE setF64 NOTIFY f64Changed FINAL) + Q_PROPERTY(qint16 i16 READ i16 WRITE setI16 NOTIFY i16Changed FINAL) + Q_PROPERTY(qint32 i32 READ i32 WRITE setI32 NOTIFY i32Changed FINAL) + Q_PROPERTY(qint64 i64 READ i64 WRITE setI64 NOTIFY i64Changed FINAL) + Q_PROPERTY(qint8 i8 READ i8 WRITE setI8 NOTIFY i8Changed FINAL) Q_PROPERTY(QByteArray optionalBytearray READ optionalBytearray WRITE setOptionalBytearray NOTIFY optionalBytearrayChanged FINAL) Q_PROPERTY(QString optionalString READ optionalString WRITE setOptionalString NOTIFY optionalStringChanged FINAL) Q_PROPERTY(QString string READ string WRITE setString NOTIFY stringChanged FINAL) + Q_PROPERTY(quint16 u16 READ u16 WRITE setU16 NOTIFY u16Changed FINAL) + Q_PROPERTY(quint32 u32 READ u32 WRITE setU32 NOTIFY u32Changed FINAL) Q_PROPERTY(quint64 u64 READ u64 WRITE setU64 NOTIFY u64Changed FINAL) - Q_PROPERTY(quint32 uinteger READ uinteger WRITE setUinteger NOTIFY uintegerChanged FINAL) + Q_PROPERTY(quint8 u8 READ u8 WRITE setU8 NOTIFY u8Changed FINAL) explicit Object(bool owned, QObject *parent); public: explicit Object(QObject *parent = nullptr); ~Object(); bool boolean() const; void setBoolean(bool v); QByteArray bytearray() const; void setBytearray(const QByteArray& v); - qint32 integer() const; - void setInteger(qint32 v); + float f32() const; + void setF32(float v); + double f64() const; + void setF64(double v); + qint16 i16() const; + void setI16(qint16 v); + qint32 i32() const; + void setI32(qint32 v); + qint64 i64() const; + void setI64(qint64 v); + qint8 i8() const; + void setI8(qint8 v); QByteArray optionalBytearray() const; void setOptionalBytearray(const QByteArray& v); QString optionalString() const; void setOptionalString(const QString& v); QString string() const; void setString(const QString& v); + quint16 u16() const; + void setU16(uint v); + quint32 u32() const; + void setU32(uint v); quint64 u64() const; void setU64(quint64 v); - quint32 uinteger() const; - void setUinteger(uint v); + quint8 u8() const; + void setU8(quint8 v); signals: void booleanChanged(); void bytearrayChanged(); - void integerChanged(); + void f32Changed(); + void f64Changed(); + void i16Changed(); + void i32Changed(); + void i64Changed(); + void i8Changed(); void optionalBytearrayChanged(); void optionalStringChanged(); void stringChanged(); + void u16Changed(); + void u32Changed(); void u64Changed(); - void uintegerChanged(); + void u8Changed(); }; #endif // TEST_OBJECT_TYPES_RUST_H diff --git a/tests/test_tree_rust.cpp b/tests/test_tree_rust.cpp index a823173..8731b95 100644 --- a/tests/test_tree_rust.cpp +++ b/tests/test_tree_rust.cpp @@ -1,271 +1,271 @@ /* generated by rust_qt_binding_generator */ #include "test_tree_rust.h" namespace { struct option_quintptr { public: quintptr value; bool some; operator QVariant() const { if (some) { return QVariant::fromValue(value); } return QVariant(); } }; static_assert(std::is_pod::value, "option_quintptr must be a POD type."); typedef void (*qstring_set)(QString* val, const char* utf8, int nbytes); void set_qstring(QString* val, const char* utf8, int nbytes) { *val = QString::fromUtf8(utf8, nbytes); } struct qmodelindex_t { int row; quintptr id; }; } extern "C" { void persons_data_user_name(const Persons::Private*, quintptr, QString*, qstring_set); bool persons_set_data_user_name(Persons::Private*, quintptr, const ushort* s, int len); void persons_sort(Persons::Private*, unsigned char column, Qt::SortOrder order = Qt::AscendingOrder); int persons_row_count(const Persons::Private*, quintptr, bool); bool persons_can_fetch_more(const Persons::Private*, quintptr, bool); void persons_fetch_more(Persons::Private*, quintptr, bool); quintptr persons_index(const Persons::Private*, quintptr, bool, int); qmodelindex_t persons_parent(const Persons::Private*, quintptr); int persons_row(const Persons::Private*, quintptr); } int Persons::columnCount(const QModelIndex &) const { return 1; } bool Persons::hasChildren(const QModelIndex &parent) const { return rowCount(parent) > 0; } int Persons::rowCount(const QModelIndex &parent) const { if (parent.isValid() && parent.column() != 0) { return 0; } return persons_row_count(m_d, parent.internalId(), parent.isValid()); } bool Persons::insertRows(int, int, const QModelIndex &) { return false; // not supported yet } bool Persons::removeRows(int, int, const QModelIndex &) { return false; // not supported yet } QModelIndex Persons::index(int row, int column, const QModelIndex &parent) const { if (row < 0 || column < 0 || column >= 1) { return QModelIndex(); } if (parent.isValid() && parent.column() != 0) { return QModelIndex(); } if (row >= rowCount(parent)) { return QModelIndex(); } const quintptr id = persons_index(m_d, parent.internalId(), parent.isValid(), row); return createIndex(row, column, id); } QModelIndex Persons::parent(const QModelIndex &index) const { if (!index.isValid()) { return QModelIndex(); } const qmodelindex_t parent = persons_parent(m_d, index.internalId()); return parent.row >= 0 ?createIndex(parent.row, 0, parent.id) :QModelIndex(); } bool Persons::canFetchMore(const QModelIndex &parent) const { if (parent.isValid() && parent.column() != 0) { return false; } return persons_can_fetch_more(m_d, parent.internalId(), parent.isValid()); } void Persons::fetchMore(const QModelIndex &parent) { persons_fetch_more(m_d, parent.internalId(), parent.isValid()); } void Persons::sort(int column, Qt::SortOrder order) { persons_sort(m_d, column, order); } Qt::ItemFlags Persons::flags(const QModelIndex &i) const { auto flags = QAbstractItemModel::flags(i); if (i.column() == 0) { flags |= Qt::ItemIsEditable; } return flags; } QVariant Persons::userName(const QModelIndex& index) const { QVariant v; QString s; persons_data_user_name(m_d, index.internalId(), &s, set_qstring); if (!s.isNull()) v.setValue(s); return v; } bool Persons::setUserName(const QModelIndex& index, const QVariant& value) { + bool set = false; if (!value.canConvert(qMetaTypeId())) { return false; } - bool set = false; const QString s = value.value(); set = persons_set_data_user_name(m_d, index.internalId(), s.utf16(), s.length()); if (set) { emit dataChanged(index, index); } return set; } QVariant Persons::data(const QModelIndex &index, int role) const { Q_ASSERT(rowCount(index.parent()) > index.row()); switch (index.column()) { case 0: switch (role) { case Qt::DisplayRole: case Qt::EditRole: case Qt::UserRole + 0: return userName(index); } } return QVariant(); } QHash Persons::roleNames() const { QHash names = QAbstractItemModel::roleNames(); names.insert(Qt::UserRole + 0, "userName"); return names; } QVariant Persons::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 Persons::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; } bool Persons::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.column() == 0) { if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::UserRole + 0) { return setUserName(index, value); } } return false; } extern "C" { Persons::Private* persons_new(Persons*, void (*)(const Persons*, quintptr, bool), void (*)(Persons*, quintptr, quintptr), void (*)(Persons*), void (*)(Persons*), void (*)(Persons*, option_quintptr, int, int), void (*)(Persons*), void (*)(Persons*, option_quintptr, int, int), void (*)(Persons*)); void persons_free(Persons::Private*); }; Persons::Persons(bool /*owned*/, QObject *parent): QAbstractItemModel(parent), m_d(0), m_ownsPrivate(false) { initHeaderData(); } Persons::Persons(QObject *parent): QAbstractItemModel(parent), m_d(persons_new(this, [](const Persons* o, quintptr id, bool valid) { if (valid) { int row = persons_row(o->m_d, id); emit o->newDataReady(o->createIndex(row, 0, id)); } else { emit o->newDataReady(QModelIndex()); } }, [](Persons* o, quintptr first, quintptr last) { quintptr frow = persons_row(o->m_d, first); quintptr lrow = persons_row(o->m_d, first); o->dataChanged(o->createIndex(frow, 0, first), o->createIndex(lrow, 0, last)); }, [](Persons* o) { o->beginResetModel(); }, [](Persons* o) { o->endResetModel(); }, [](Persons* o, option_quintptr id, int first, int last) { if (id.some) { int row = persons_row(o->m_d, id.value); o->beginInsertRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginInsertRows(QModelIndex(), first, last); } }, [](Persons* o) { o->endInsertRows(); }, [](Persons* o, option_quintptr id, int first, int last) { if (id.some) { int row = persons_row(o->m_d, id.value); o->beginRemoveRows(o->createIndex(row, 0, id.value), first, last); } else { o->beginRemoveRows(QModelIndex(), first, last); } }, [](Persons* o) { o->endRemoveRows(); } )), m_ownsPrivate(true) { connect(this, &Persons::newDataReady, this, [this](const QModelIndex& i) { this->fetchMore(i); }, Qt::QueuedConnection); initHeaderData(); } Persons::~Persons() { if (m_ownsPrivate) { persons_free(m_d); } } void Persons::initHeaderData() { m_headerData.insert(qMakePair(0, Qt::DisplayRole), QVariant("userName")); }