void BackGroundPropertyGridWidget::UpdateComboBoxWidgetWithPropertyValue(QComboBox* comboBoxWidget, const QMetaProperty& curProperty)
{
    if (!this->activeMetadata)
    {
        return;
    }

    bool isPropertyValueDiffers = false;
    const QString& propertyName = curProperty.name();
    int propertyValue = PropertiesHelper::GetPropertyValue<int>(this->activeMetadata, propertyName, isPropertyValueDiffers);

    // Firstly check the custom comboboxes.
    if (comboBoxWidget == ui->drawTypeComboBox)
    {
        UpdateWidgetPalette(comboBoxWidget, propertyName);
        return SetComboboxSelectedItem(comboBoxWidget,
                                       BackgroundGridWidgetHelper::GetDrawTypeDescByType((UIControlBackground::eDrawType)propertyValue));
    }
    else if (comboBoxWidget == ui->colorInheritComboBox)
    {
        UpdateWidgetPalette(comboBoxWidget, propertyName);
        return SetComboboxSelectedItem(comboBoxWidget,
                                       BackgroundGridWidgetHelper::GetColorInheritTypeDescByType((UIControlBackground::eColorInheritType)
                                       propertyValue));
    }
    else if (comboBoxWidget == ui->alignComboBox)
    {
        UpdateWidgetPalette(comboBoxWidget, propertyName);
        return SetComboboxSelectedItem(comboBoxWidget,
                                       BackgroundGridWidgetHelper::GetAlignTypeDescByType(propertyValue));
    }
	else if (comboBoxWidget == ui->modificationComboBox)
    {
        UpdateWidgetPalette(comboBoxWidget, propertyName);
        return SetComboboxSelectedItem(comboBoxWidget,
                                       BackgroundGridWidgetHelper::GetModificationTypeDescByType(propertyValue));
    }

    // Not related to the custom combobox - call the generic one.
    BasePropertyGridWidget::UpdateComboBoxWidgetWithPropertyValue(comboBoxWidget, curProperty);
}
BorderDrawerInterface * BorderDrawersLoader::getDrawerByName(const QString & name, const QMap<QString,QString> & properties)
{
    BorderDrawerFactoryInterface * factory = getFactoryByName(name);
    if (factory)
    {
        BorderDrawerInterface * drawer = factory->getDrawerInstance(factory);
        if (!drawer)
            return 0;
        const QMetaObject * meta = drawer->metaObject();
        for (int i = meta->propertyCount()-1; i >= 0; --i)
        {
            QMetaProperty prop = meta->property(i);
            QString value = properties.value(QString(prop.name()));
            if (value.isEmpty())
                continue;
            prop.write(drawer, QVariant(value.toAscii()));
        }
        return drawer;
    }
    return 0;
}
QDebug  operator<<( QDebug dbg, const Properties& p )
{
    QDebugStateSaver saver( dbg ); Q_UNUSED( saver );  // Automatically save dbg settings, and restore them at destruction
    if ( p.getTarget() == nullptr )
        return dbg;
    int pCount = p.getTarget()->metaObject( )->propertyCount( );
    for ( int i = 0; i < pCount; ++i ) {
        QMetaProperty metaProperty = p.getTarget()->metaObject( )->property( i );
        const char* propertyName = metaProperty.name( );
        QVariant propertyValue = p.getTarget()->property( propertyName );
        dbg.nospace( ) << "( static " << propertyName << "=" << propertyValue.toString( ) << ") ";
    }
    QList< QByteArray > dynamicProperties = p.getTarget()->dynamicPropertyNames( );
    for ( int d = 0; d < dynamicProperties.size( ); d++ ) {
        QString propertyName = dynamicProperties.at( d );
        QVariant propertyValue = p.getTarget()->property( propertyName.toLatin1( ) );
        dbg.nospace( ) << "( dynamic " << propertyName << "=" << propertyValue.toString( ) << ")";
    }
    dbg.nospace() << "\n";
    return dbg;
}
void    Properties::serializeOut( QXmlStreamWriter& stream )
{
    stream.writeStartElement( "properties" );   // <properties>

    // Serialize static properties
    int pCount = metaObject( )->propertyCount( );
    for ( int i = 0; i < pCount; ++i )
    {
        QMetaProperty metaProperty = metaObject( )->property( i );
        QString propertyName = QString( metaProperty.name( ) );
        QVariant v = property( propertyName.toLatin1( ) );

        stream.writeStartElement( "property" );     // <property>
        stream.writeAttribute( "name", propertyName );
        serializeValueOut( v, stream );
        serializeTimeValuesOut( propertyName, stream );

        stream.writeEndElement( );                  // </property>
    }

    // Serialize dynamic properties
    QList< QByteArray > dynamicProperties = dynamicPropertyNames( );
    for ( int d = 0; d < dynamicProperties.size( ); d++ )
    {
        QString propertyName = dynamicProperties.at( d );
        QVariant v = property( propertyName.toLatin1( ) );

        stream.writeStartElement( "property" );     // <property>
        stream.writeAttribute( "name", propertyName );
        serializeValueOut( v, stream );

        if ( isEnum( propertyName ) )
            stream.writeAttribute( "isEnum", getEnumValueLabels( propertyName ).join( ',') );
        serializeTimeValuesOut( propertyName, stream );

        stream.writeEndElement( );                  // </property>
    }

    stream.writeEndElement( );                  // </properties>
}
/*! \internal
    \reimp

    \a n is in the signal index range (see QObjectPrivate::signalIndex()).
*/
void QQmlJavaScriptExpression::GuardCapture::captureProperty(QObject *o, int c, int n)
{
    if (expression) {
        if (n == -1) {
            if (!errorString) {
                errorString = new QStringList;
                QString preamble = QLatin1String("QQmlExpression: Expression ") +
                                   expression->m_vtable->expressionIdentifier(expression) +
                                   QLatin1String(" depends on non-NOTIFYable properties:");
                errorString->append(preamble);
            }

            const QMetaObject *metaObj = o->metaObject();
            QMetaProperty metaProp = metaObj->property(c);

            QString error = QLatin1String("    ") +
                            QString::fromUtf8(metaObj->className()) +
                            QLatin1String("::") +
                            QString::fromUtf8(metaProp.name());
            errorString->append(error);
        } else {

            // Try and find a matching guard
            while (!guards.isEmpty() && !guards.first()->isConnected(o, n))
                guards.takeFirst()->Delete();

            Guard *g = 0;
            if (!guards.isEmpty()) {
                g = guards.takeFirst();
                g->cancelNotify();
                Q_ASSERT(g->isConnected(o, n));
            } else {
                g = Guard::New(expression, engine);
                g->connect(o, n, engine);
            }

            expression->activeGuards.prepend(g);
        }
    }
}
Beispiel #6
0
QSqlRecord QsoEntry::getRecord() const
{
    QSqlRecord record;

    // create a field for each property
    const QMetaObject* obj = metaObject();
    for (int i = 0; i < obj->propertyCount(); i++) {
        QMetaProperty metaProperty = obj->property(i);

        const char* name = metaProperty.name();

        // create field
        QSqlField field;
        field.setName(QLatin1String(name));
        field.setValue(property(name));

        // insert field into record
        record.insert(i, field);
    }

    return record;
}
PropertyWatcher::PropertyWatcher(QObject *subject, QString annotation, QWidget *parent)
    : QWidget(parent), m_subject(subject), m_layout(new QFormLayout)
{
    setWindowTitle(QString("Properties of %1 %2 %3")
        .arg(subject->metaObject()->className()).arg(subject->objectName()).arg(annotation));
    setMinimumSize(450, 300);
    const QMetaObject* meta = m_subject->metaObject();

    for (int i = 0; i < meta->propertyCount(); ++i) {
        QMetaProperty prop = meta->property(i);
        if (prop.isReadable()) {
            PropertyField* field = new PropertyField(m_subject, prop);
            m_layout->addRow(prop.name(), field);
        }
    }
    QPushButton *updateButton = new QPushButton("update");
    connect(updateButton, &QPushButton::clicked, this, &PropertyWatcher::updateAllFields);
    m_layout->addRow("", updateButton);
    m_layout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
    setLayout(m_layout);
    connect(subject, &QObject::destroyed, this, &PropertyWatcher::subjectDestroyed);
}
QList<ObjectProxy::Property> DirectObjectProxy::properties() const
{
	QList<Property> properties;
	if (!m_object)
	{
		return properties;
	}

	const QMetaObject* metaObject = m_object.data()->metaObject();
	for (int i=0; i < metaObject->propertyCount(); i++)
	{
		QMetaProperty metaProperty = metaObject->property(i);

		Property property;
		property.name = metaProperty.name();
		property.value = metaProperty.read(m_object.data());
		property.isWritable = metaProperty.isWritable();
		properties << property;
	}

	return properties;
}
QStringList propertyNameForWritableProperties(QObject *object, const QString &baseName = QString())
{
    QStringList propertyNameList;

    const QMetaObject *metaObject = object->metaObject();
    for (int index = 0; index < metaObject->propertyCount(); ++index) {
        QMetaProperty metaProperty = metaObject->property(index);
        if (metaProperty.isReadable() && !metaProperty.isWritable()) {
            QObject *childObject = QDeclarativeMetaType::toQObject(metaProperty.read(object));
            if (childObject)
                propertyNameList.append(propertyNameForWritableProperties(childObject, baseName +  QString::fromUtf8(metaProperty.name()) + '.'));
        } else if (QDeclarativeValueTypeFactory::valueType(metaProperty.userType())) {
            QDeclarativeValueType *valueType = QDeclarativeValueTypeFactory::valueType(metaProperty.userType());
            valueType->setValue(metaProperty.read(object));
            propertyNameList.append(propertyNameForWritableProperties(valueType, baseName +  QString::fromUtf8(metaProperty.name()) + '.'));
        } else if (metaProperty.isReadable() && metaProperty.isWritable()) {
            propertyNameList.append(baseName + QString::fromUtf8(metaProperty.name()));
        }
    }

    return propertyNameList;
}
Beispiel #10
0
void PropertyWidget::setData(Kore::data::Block* block, kint propertyIndex)
{
	_block = block;
	_propertyIndex = propertyIndex;

	QMetaProperty property = _block->metaObject()->property(_propertyIndex);
	if(property.hasNotifySignal())
	{
		static const int slotIndex = staticMetaObject.indexOfMethod(QMetaObject::normalizedSignature("update()"));
		Q_ASSERT(slotIndex != -1);
		connect(_block, property.notifySignal(), this, staticMetaObject.method(slotIndex));
	}
	else
	{
		qWarning(
				"%s / Block %s's property %s has no notify signal, it won't be updated!",
				__FUNCTION__,
				qPrintable(block->objectClassName()),
				property.name()
			);
	}
}
Beispiel #11
0
bool Serialization::SerializeToXML(const QObject &obj, QString name)
{
    try
    {
        //?????
        QFile::remove(name);
        //?????

        QDomDocument doc;
        QDomElement root = doc.createElement(obj.metaObject()->className());
        doc.appendChild(root);

        for(int i = 0; i < obj.metaObject()->propertyCount(); i++)
        {
            const QMetaProperty prop = obj.metaObject()->property(i);
            QString propName = prop.name();
            if(propName == "objectName")
                continue;
            QDomElement el = doc.createElement(propName);
            QVariant value = obj.property(propName.toLocal8Bit().data());
            QDomText txt = doc.createTextNode( value.toString() );
            el.appendChild(txt);
            root.appendChild(el);
        }
        QFile output(name);
        if (output.open(QFile::ReadWrite))
        {
            QTextStream stream(&output);
            doc.save(stream, 2);
            return true;
        }
        return false;
    }
    catch(...)
    {
        return false;
    }
}
Beispiel #12
0
QVariantMap SyncableObject::toVariantMap() {
  QVariantMap properties;

  const QMetaObject* meta = metaObject();

  // we collect data from properties
  QMetaProperty prop;
  QString propName;
  for(int i = 0; i < meta->propertyCount(); i++) {
    prop = meta->property(i);
    propName = QString(prop.name());
    if(propName == "objectName")
      continue;
    properties[propName] = prop.read(this);
  }

  // ...as well as methods, which have names starting with "init"
  for(int i = 0; i < meta->methodCount(); i++) {
    QMetaMethod method = meta->method(i);
    QString methodname(SignalProxy::ExtendedMetaObject::methodName(method));
    if(!methodname.startsWith("init") || methodname.startsWith("initSet") || methodname.startsWith("initDone"))
      continue;

    QVariant::Type variantType = QVariant::nameToType(method.typeName());
    if(variantType == QVariant::Invalid && !QByteArray(method.typeName()).isEmpty()) {
      qWarning() << "SyncableObject::toVariantMap(): cannot fetch init data for:" << this << method.signature() << "- Returntype is unknown to Qt's MetaSystem:" << QByteArray(method.typeName());
      continue;
    }
    QVariant value = QVariant(variantType);
    QGenericReturnArgument genericvalue = QGenericReturnArgument(method.typeName(), &value);
    QMetaObject::invokeMethod(this, methodname.toAscii(), genericvalue);

    properties[SignalProxy::ExtendedMetaObject::methodBaseName(method)] = value;
  }
  // properties["Payload"] = QByteArray(10000000, 'a');  // for testing purposes
  return properties;

}
Beispiel #13
0
QStringList REPL::_enumerateCompletions(QObject* obj) const
{
    const QMetaObject* meta = obj->metaObject();
    QMap<QString, bool> completions;

    // List up slots, signals, and invokable methods
    const int methodOffset = meta->methodOffset();
    const int methodCount = meta->methodCount();
    for (int i = methodOffset; i < methodCount; i++) {
        const QString name = QString::fromLatin1(meta->method(i).methodSignature());
        // Ignore methods starting with underscores
        if (name.startsWith('_')) {
            continue;
        }
        // Keep only up to, but not including, first paren
        const int cutoff = name.indexOf('(');
        completions.insert((0 < cutoff ? name.left(cutoff) : name), true);
    }

    // List up properties
    const int propertyOffset = meta->propertyOffset();
    const int propertyCount = meta->propertyCount();
    for (int i = propertyOffset; i < propertyCount; i++) {
        const QMetaProperty prop = meta->property(i);
        // Ignore non-scriptable properties
        if (!prop.isScriptable()) {
            continue;
        }
        const QString name = QString::fromLatin1(prop.name());
        // Ignore properties starting with underscores
        if (name.startsWith('_')) {
            continue;
        }
        completions.insert(name, true);
    }

    return completions.uniqueKeys();
}
Beispiel #14
0
void XmlPListSerializer::SerializePListObjectProperties(const QString &sName,
                                                        const QObject *pObject,
                                                        bool          needKey )
{
    if (!pObject)
        return;

    if (needKey)
    {
        QString sItemName = GetItemName(sName);
        m_pXmlWriter->writeTextElement("key", sItemName);
    }
    m_pXmlWriter->writeStartElement("dict");

    const QMetaObject *pMetaObject = pObject->metaObject();

    int nCount = pMetaObject->propertyCount();

    for (int nIdx=0; nIdx < nCount; ++nIdx)
    {
        QMetaProperty metaProperty = pMetaObject->property(nIdx);

        if (metaProperty.isDesignable(pObject))
        {
            const char *pszPropName = metaProperty.name();
            QString     sPropName(pszPropName);

            if (sPropName.compare("objectName") == 0)
                continue;

            QVariant value(pObject->property(pszPropName));

            AddProperty(sPropName, value, pMetaObject, &metaProperty);
        }
    }

    m_pXmlWriter->writeEndElement();
}
Beispiel #15
0
bool Serializer::_deserialize(QDomElement root, QObject** object)
{
    if (int id = QMetaType::type(root.nodeName().toAscii().data()))
        *object = (QObject*)QMetaType::construct(id);
    else
        return false;

    for(int i = 0; i < (*object)->metaObject()->propertyCount(); i++)
    {
        QMetaProperty prop = (*object)->metaObject()->property(i);
        QString propName = prop.name();
        if(propName == "objectName")
            continue;
        QDomNodeList nodeList = root.elementsByTagName(propName);
        if(nodeList.length() < 1)
            continue;
        QDomNode node = nodeList.at(0);
        QString v = node.toElement().text();
        (*object)->setProperty(propName.toAscii().data(), QVariant(v));
        qDebug() << propName << " = " << v;
    }
    return true;
}
Beispiel #16
0
void QtInstance::getPropertyNames(ExecState* exec, PropertyNameArray& array)
{
    // This is the enumerable properties, so put:
    // properties
    // dynamic properties
    // slots
    QObject* obj = getObject();
    if (obj) {
        const QMetaObject* meta = obj->metaObject();

        int i;
        for (i = 0; i < meta->propertyCount(); i++) {
            QMetaProperty prop = meta->property(i);
            if (prop.isScriptable())
                array.add(Identifier(exec, prop.name()));
        }

#ifndef QT_NO_PROPERTIES
        QList<QByteArray> dynProps = obj->dynamicPropertyNames();
        foreach (const QByteArray& ba, dynProps)
            array.add(Identifier(exec, ba.constData()));
#endif

        const int methodCount = meta->methodCount();
        for (i = 0; i < methodCount; i++) {
            QMetaMethod method = meta->method(i);
            if (method.access() != QMetaMethod::Private) {
#if HAVE(QT5)
                QByteArray sig = method.methodSignature();
                array.add(Identifier(exec, UString(sig.constData(), sig.length())));
#else
                array.add(Identifier(exec, method.signature()));
#endif
            }
        }
    }
}
Beispiel #17
0
bool Serialization::DeserializeFromXML(QObject* object, const QString& input)//QObject* object)
{
    try
    {
        QDomDocument doc("credentials");
        QFile file(input);
        if (!file.open(QIODevice::ReadOnly))
            return false;
        if (!doc.setContent(&file))
        {
            file.close();
            return false;
        }
        file.close();

        QDomElement root = doc.documentElement();
        for(int i = 0; i < object->metaObject()->propertyCount(); i++)
        {
            QMetaProperty prop = object->metaObject()->property(i);
            QString propName = prop.name();
            if(propName == "objectName")
                continue;
            QDomNodeList nodeList = root.elementsByTagName(propName);
            if(nodeList.length() < 1)
                continue;
            QDomNode node = nodeList.at(0);
            //QVariant value = object->property(propName.toLocal8Bit().data());
            QString v = node.toElement().text();
            object->setProperty(propName.toLocal8Bit().data(), QVariant(v));
        }
        return true;
    }
    catch(...)
    {
        return false;
    }
}
Beispiel #18
0
QObject* GenericDAO::readModel(QSqlQuery& query)
{
    QObject* obj = getModelInstance();
    Q_ASSERT(obj);

    const QMetaObject* metaobject = obj->metaObject();
    int count = metaobject->propertyCount();
    for (int i = 1; i < count; i++)
    {
        QMetaProperty metaproperty = metaobject->property(i);
        const char* name = metaproperty.name();
        int fieldNo = query.record().indexOf(name);
        if (fieldNo > -1)
        {
            QVariant value = query.value(fieldNo);
//            if (strcmp(name, "id") == 0)
//                metaproperty.write(obj, Database::variantToUuid(value));
  //          else
                metaproperty.write(obj, value);
        }
    }

    return obj;
}
void TextPropertyGridWidget::UpdateComboBoxWidgetWithPropertyValue(QComboBox* comboBoxWidget, const QMetaProperty& curProperty)
{
	if (!this->activeMetadata)
    {
        return;
    }
    
    bool isPropertyValueDiffers = false;
    const QString& propertyName = curProperty.name();
    
    // Firstly check the custom comboboxes.
    if (comboBoxWidget == ui->alignComboBox)
    {
        int propertyValue = PropertiesHelper::GetPropertyValue<int>(this->activeMetadata, propertyName, isPropertyValueDiffers);
        
        UpdateWidgetPalette(comboBoxWidget, propertyName);
        return SetComboboxSelectedItem(comboBoxWidget,
                                       BackgroundGridWidgetHelper::GetAlignTypeDescByType(propertyValue));
    }
	else if(comboBoxWidget == ui->fontPresetComboBox)
    {
        Font* propertyValue = PropertiesHelper::GetPropertyValue<Font*>(this->activeMetadata, propertyName, isPropertyValueDiffers);
        
        QString fontPresetName = QString::fromStdString(EditorFontManager::Instance()->GetLocalizedFontName(propertyValue));
        
        UpdateWidgetPalette(comboBoxWidget, propertyName); // what is it for? - needed for controls like UIButton
        
//        int index = comboBoxWidget->findText(fontPresetName); //TODO: remove debug log
//        Logger::Debug("TextPropertyGridWidget::UpdateComboBoxWidgetWithPropertyValue %s index=%d", fontPresetName.toStdString().c_str(), index);
        
        return SetComboboxSelectedItem(ui->fontPresetComboBox, fontPresetName );
    }
    
    // Not related to the custom combobox - call the generic one.
    BasePropertyGridWidget::UpdateComboBoxWidgetWithPropertyValue(comboBoxWidget, curProperty);
}
void ControlInfo::setControl(QWidget *activex)
{
    listInfo->clear();

    const QMetaObject *mo = activex->metaObject();
    QTreeWidgetItem *group = new QTreeWidgetItem(listInfo);
    group->setText(0, tr("Class Info"));
    group->setText(1, QString::number(mo->classInfoCount()));

    QTreeWidgetItem *item = 0;
    int i;
    int count;
    for (i = mo->classInfoOffset(); i < mo->classInfoCount(); ++i) {
	const QMetaClassInfo info = mo->classInfo(i);
	item = new QTreeWidgetItem(group);
        item->setText(0, QString::fromLatin1(info.name()));
        item->setText(1, QString::fromLatin1(info.value()));
    }
    group = new QTreeWidgetItem(listInfo);
    group->setText(0, tr("Signals"));

    count = 0;
    for (i = mo->methodOffset(); i < mo->methodCount(); ++i) {
	const QMetaMethod method = mo->method(i);
        if (method.methodType() == QMetaMethod::Signal) {
            ++count;
	    item = new QTreeWidgetItem(group);
            item->setText(0, QString::fromLatin1(method.signature()));
        }
    }
    group->setText(1, QString::number(count));

    group = new QTreeWidgetItem(listInfo);
    group->setText(0, tr("Slots"));

    count = 0;
    for (i = mo->methodOffset(); i < mo->methodCount(); ++i) {
	const QMetaMethod method = mo->method(i);
        if (method.methodType() == QMetaMethod::Slot) {
            ++count;
	    item = new QTreeWidgetItem(group);
            item->setText(0, QString::fromLatin1(method.signature()));
        }
    }
    group->setText(1, QString::number(count));

    group = new QTreeWidgetItem(listInfo);
    group->setText(0, tr("Properties"));

    count = 0;
    for (i = mo->propertyOffset(); i < mo->propertyCount(); ++i) {
        ++count;
	const QMetaProperty property = mo->property(i);
	item = new QTreeWidgetItem(group);
        item->setText(0, QString::fromLatin1(property.name()));
        item->setText(1, QString::fromLatin1(property.typeName()));
        if (!property.isDesignable()) {
            item->setTextColor(0, Qt::gray);
            item->setTextColor(1, Qt::gray);
        }
    }
    group->setText(1, QString::number(count));
}
int Dialog::showDialog(const QString& view, QObject* viewModel, int type)
{
    QDialog* dialog = NULL;
    QMainWindow* mainWindow = NULL;
    QWidget* windowWidget = NULL;
    QWidget* layoutWidget = NULL;

    switch (type)
    {
    case Dialog::MainWindow:
        mainWindow = new QMainWindow();
        windowWidget = mainWindow;
        layoutWidget = new QWidget(windowWidget);
        mainWindow->setCentralWidget(layoutWidget);
        break;

    case Dialog::ModalDialog:
        dialog = new QDialog(QApplication::activeWindow());
        windowWidget = dialog;
        layoutWidget = dialog;
        break;

    default:
        dialog = new QDialog();
        windowWidget = dialog;
        layoutWidget = dialog;
        break;
    }

    QGridLayout* layout = new QGridLayout(layoutWidget);

    // Create view

    QDeclarativeView* v = new QDeclarativeView(layoutWidget);

    if (viewModel)
    {
        int count = viewModel->metaObject()->propertyCount();
        for (int i = 0; i < count; ++i)
        {
            QMetaProperty p = viewModel->metaObject()->property(i);
            if (p.isReadable() && p.typeName() == QString("QDeclarativeImageProvider*"))
            {
                QString name = p.name();
                QDeclarativeImageProvider* value = p.read(viewModel).value<QDeclarativeImageProvider*>();

                v->engine()->addImageProvider(name.toLatin1(), new ProxyImageProvider(value));
            }
        }

        v->rootContext()->setContextProperty("dataContext", viewModel);
    }

    QString path;
    foreach (path, importPaths)
        v->engine()->addImportPath(path);
    foreach (path, pluginPaths)
        v->engine()->addPluginPath(path);

    v->setSource(QUrl(view));
    v->setResizeMode(QDeclarativeView::SizeRootObjectToView);

    // Initialize dialog

    QGraphicsObject* root = v->rootObject();

    QVariant property = root->property("dialogTitle");
    if (property.isValid())
        windowWidget->setWindowTitle(property.toString());

    property = root->property("dialogMinWidth");
    if (property.isValid())
        layoutWidget->setMinimumWidth(property.toInt());

    property = root->property("dialogMinHeight");
    if (property.isValid())
        layoutWidget->setMinimumHeight(property.toInt());

    property = root->property("dialogMaxWidth");
    if (property.isValid())
        layoutWidget->setMaximumWidth(property.toInt());

    property = root->property("dialogMaxHeight");
    if (property.isValid())
        layoutWidget->setMaximumHeight(property.toInt());

    property = root->property("dialogResizable");
    if (property.isValid() && !property.toBool())
        layout->setSizeConstraint(QLayout::SetFixedSize);

    Qt::WindowStates states = windowWidget->windowState();
    Qt::WindowFlags flags = windowWidget->windowFlags();

    property = root->property("dialogMinimizeButton");
    if (property.isValid())
        flags = property.toBool() ? flags | Qt::WindowMinimizeButtonHint : flags & ~Qt::WindowMinimizeButtonHint;

    property = root->property("dialogMaximizeButton");
    if (property.isValid())
        flags = property.toBool() ? flags | Qt::WindowMaximizeButtonHint : flags & ~Qt::WindowMaximizeButtonHint;

    property = root->property("dialogCloseButton");
    if (property.isValid())
        flags = property.toBool() ? flags | Qt::WindowCloseButtonHint : flags & ~Qt::WindowCloseButtonHint;

    property = root->property("dialogFullScreen");
    if (property.isValid())
        states = property.toBool() ? states | Qt::WindowFullScreen : states & ~Qt::WindowFullScreen;

    flags = flags & ~Qt::WindowContextHelpButtonHint;

    windowWidget->setWindowFlags(flags);
    windowWidget->setWindowState(states);

    property = root->property("dialogToolBar");
    if (type == Dialog::MainWindow && property.isValid() && property.typeName() == QString("QDeclarativeListProperty<QDeclarativeItem>"))
    {
        QToolBar* toolbar = new QToolBar(mainWindow);
        toolbar->setMovable(false);
        toolbar->setFloatable(false);
        toolbar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        toolbar->setAllowedAreas(Qt::TopToolBarArea);

        QDeclarativeListProperty<QDeclarativeItem> btnList = property.value< QDeclarativeListProperty<QDeclarativeItem> >();
        int btnCount = btnList.count(&btnList);

        for (int i = 0; i < btnCount; ++i)
        {
            QDeclarativeItem* item = btnList.at(&btnList, i);

            if (!item->property("text").isValid())
                continue;

            QString itemText = item->property("text").toString();
            QString itemTooltip = item->property("tooltip").isValid() ? item->property("tooltip").toString() : "";
            QString itemIconSource = item->property("iconSource").isValid() ? item->property("iconSource").toString() : "";
            int itemIconSize = item->property("iconSize").isValid() ? item->property("iconSize").toInt() : -1;

            if (itemText == "|")
            {
                toolbar->addSeparator();
            }
            else if (itemText == "-")
            {
                QWidget* spacer = new QWidget();
                spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
                toolbar->addWidget(spacer);
            }
            else
            {
                QAction* action = new QAction(mainWindow);
                action->setText(itemText);
                action->setToolTip(itemTooltip);
                action->setIcon(QIcon(itemIconSource));
                QObject::connect(action, SIGNAL(triggered()), item, SLOT(trigger()));

                if (item->property("enabled").isValid())
                    new PropertyBinding(action, "enabled", item, "enabled", PropertyBinding::OneWay, NULL, this);

                if (item->property("visible").isValid())
                    new PropertyBinding(action, "visible", item, "visible", PropertyBinding::OneWay, NULL, this);

                toolbar->addAction(action);
            }

            if (itemIconSize != -1)
                toolbar->setIconSize(QSize(itemIconSize, itemIconSize));
        }

        mainWindow->setUnifiedTitleAndToolBarOnMac(true);
        mainWindow->addToolBar(toolbar);
    }

    property = root->property("dialogMenu");
    if (type == Dialog::MainWindow && property.isValid() && property.typeName() == QString("QDeclarativeListProperty<QDeclarativeItem>"))
    {
        QDeclarativeListProperty<QDeclarativeItem> list = property.value< QDeclarativeListProperty<QDeclarativeItem> >();
        int count = list.count(&list);

        for (int i = 0; i < count; ++i)
        {
            QDeclarativeItem* item = list.at(&list, i);

            if (!item->property("text").isValid())
                continue;

            QString itemText = item->property("text").toString();
            QMenu * menuItem = mainWindow->menuBar()->addMenu(itemText);

            if (!item->property("submenu").isValid() || item->property("submenu").typeName() != QString("QDeclarativeListProperty<QDeclarativeItem>"))
                continue;

            QDeclarativeListProperty<QDeclarativeItem> innerList = item->property("submenu").value< QDeclarativeListProperty<QDeclarativeItem> >();
            int innerCount = innerList.count(&innerList);

            for (int j = 0; j < innerCount; ++j)
            {
                QDeclarativeItem* innerItem = innerList.at(&innerList, j);

                if (!innerItem->property("text").isValid())
                    continue;

                QString innerItemText = innerItem->property("text").toString();
                QString innerItemShortcut = innerItem->property("shortcut").isValid() ? innerItem->property("shortcut").toString() : "";
                QString innerItemIconSource = innerItem->property("iconSource").isValid() ? innerItem->property("iconSource").toString() : "";

                if (innerItemText == "-")
                {
                    menuItem->addSeparator();
                }
                else
                {
                    QAction * action = menuItem->addAction(QIcon(innerItemIconSource), innerItemText);
                    action->setShortcut(QKeySequence(innerItemShortcut));

                    QObject::connect(action, SIGNAL(triggered()), innerItem, SLOT(trigger()));

                    if (innerItem->property("enabled").isValid())
                        new PropertyBinding(action, "enabled", innerItem, "enabled", PropertyBinding::OneWay, NULL, this);

                    if (innerItem->property("visible").isValid())
                        new PropertyBinding(action, "visible", innerItem, "visible", PropertyBinding::OneWay, NULL, this);
                }
            }
        }
    }

    new DialogCallbacks(windowWidget, v, root);

    // Initialize layout

    layout->setMargin(0);
    layout->addWidget(v, 0, 0);

    // Execute

    switch (type)
    {
    case Dialog::ModalDialog:
        dialog->exec();
        break;

    case Dialog::MainWindow:
    {
        if (mainWindowGeometry.isEmpty())
        {
            mainWindow->adjustSize();
            mainWindow->move(QApplication::desktop()->screen()->rect().center() - mainWindow->rect().center());
        }
        else
            mainWindow->restoreGeometry(mainWindowGeometry);
    }

    default:
        windowWidget->setAttribute(Qt::WA_DeleteOnClose);
        windowWidget->show();
        break;
    }

    int result = 0;

    property = root->property("dialogResult");
    if (property.isValid())
        result = property.toInt();

    if (type == Dialog::ModalDialog)
        delete dialog;

    return result;
}
	bool operator==(const PropertyPair& other) const {return QString(other.Property.name()) == QString(Property.name());}
Beispiel #23
0
void QDBusAbstractInterfacePrivate::property(const QMetaProperty &mp, QVariant &where) const
{
    if (!isValid || !canMakeCalls()) {   // can't make calls
        where.clear();
        return;
    }

    // is this metatype registered?
    const char *expectedSignature = "";
    if (mp.type() != 0xff) {
        expectedSignature = QDBusMetaType::typeToSignature(where.userType());
        if (expectedSignature == 0) {
            qWarning("QDBusAbstractInterface: type %s must be registered with QtDBus before it can be "
                     "used to read property %s.%s",
                     mp.typeName(), qPrintable(interface), mp.name());
            lastError = QDBusError(QDBusError::Failed,
                                   QString::fromLatin1("Unregistered type %1 cannot be handled")
                                   .arg(QLatin1String(mp.typeName())));
            where.clear();
            return;
        }
    }

    // try to read this property
    QDBusMessage msg = QDBusMessage::createMethodCall(service, path,
                                                      QLatin1String(DBUS_INTERFACE_PROPERTIES),
                                                      QLatin1String("Get"));
    QDBusMessagePrivate::setParametersValidated(msg, true);
    msg << interface << QString::fromUtf8(mp.name());
    QDBusMessage reply = connection.call(msg, QDBus::Block);

    if (reply.type() != QDBusMessage::ReplyMessage) {
        lastError = reply;
        where.clear();
        return;
    }
    if (reply.signature() != QLatin1String("v")) {
        QString errmsg = QLatin1String("Invalid signature `%1' in return from call to "
                                       DBUS_INTERFACE_PROPERTIES);
        lastError = QDBusError(QDBusError::InvalidSignature, errmsg.arg(reply.signature()));
        where.clear();
        return;
    }

    QByteArray foundSignature;
    const char *foundType = 0;
    QVariant value = qvariant_cast<QDBusVariant>(reply.arguments().at(0)).variant();

    if (value.userType() == where.userType() || mp.type() == 0xff
        || (expectedSignature[0] == 'v' && expectedSignature[1] == '\0')) {
        // simple match
        where = value;
        return;
    }

    if (value.userType() == qMetaTypeId<QDBusArgument>()) {
        QDBusArgument arg = qvariant_cast<QDBusArgument>(value);

        foundType = "user type";
        foundSignature = arg.currentSignature().toLatin1();
        if (foundSignature == expectedSignature) {
            // signatures match, we can demarshall
            QDBusMetaType::demarshall(arg, where.userType(), where.data());
            return;
        }
    } else {
        foundType = value.typeName();
        foundSignature = QDBusMetaType::typeToSignature(value.userType());
    }

    // there was an error...
    QString errmsg = QLatin1String("Unexpected `%1' (%2) when retrieving property `%3.%4' "
                                   "(expected type `%5' (%6))");
    lastError = QDBusError(QDBusError::InvalidSignature,
                           errmsg.arg(QString::fromLatin1(foundType),
                                      QString::fromLatin1(foundSignature),
                                      interface,
                                      QString::fromUtf8(mp.name()),
                                      QString::fromLatin1(mp.typeName()),
                                      QString::fromLatin1(expectedSignature)));
    where.clear();
    return;
}
Beispiel #24
0
QObject *QDeclarativeVME::run(QDeclarativeVMEObjectStack &stack, 
                              QDeclarativeContextData *ctxt, 
                              QDeclarativeCompiledData *comp, 
                              int start, int count, 
                              const QBitField &bindingSkipList)
{
    Q_ASSERT(comp);
    Q_ASSERT(ctxt);
    const QList<QDeclarativeCompiledData::TypeReference> &types = comp->types;
    const QList<QString> &primitives = comp->primitives;
    const QList<QByteArray> &datas = comp->datas;
    const QList<QDeclarativeCompiledData::CustomTypeData> &customTypeData = comp->customTypeData;
    const QList<int> &intData = comp->intData;
    const QList<float> &floatData = comp->floatData;
    const QList<QDeclarativePropertyCache *> &propertyCaches = comp->propertyCaches;
    const QList<QDeclarativeParser::Object::ScriptBlock> &scripts = comp->scripts;
    const QList<QUrl> &urls = comp->urls;

    QDeclarativeEnginePrivate::SimpleList<QDeclarativeAbstractBinding> bindValues;
    QDeclarativeEnginePrivate::SimpleList<QDeclarativeParserStatus> parserStatus;

    QDeclarativeVMEStack<ListInstance> qliststack;

    vmeErrors.clear();
    QDeclarativeEnginePrivate *ep = QDeclarativeEnginePrivate::get(ctxt->engine);

    int status = -1;    //for dbus
    QDeclarativePropertyPrivate::WriteFlags flags = QDeclarativePropertyPrivate::BypassInterceptor |
                                                    QDeclarativePropertyPrivate::RemoveBindingOnAliasWrite;

    for (int ii = start; !isError() && ii < (start + count); ++ii) {
        const QDeclarativeInstruction &instr = comp->bytecode.at(ii);

        switch(instr.type) {
        case QDeclarativeInstruction::Init:
            {
                if (instr.init.bindingsSize) 
                    bindValues = QDeclarativeEnginePrivate::SimpleList<QDeclarativeAbstractBinding>(instr.init.bindingsSize);
                if (instr.init.parserStatusSize)
                    parserStatus = QDeclarativeEnginePrivate::SimpleList<QDeclarativeParserStatus>(instr.init.parserStatusSize);
                if (instr.init.contextCache != -1) 
                    ctxt->setIdPropertyData(comp->contextCaches.at(instr.init.contextCache));
                if (instr.init.compiledBinding != -1) 
                    ctxt->optimizedBindings = new QDeclarativeCompiledBindings(datas.at(instr.init.compiledBinding).constData(), ctxt, comp);
            }
            break;

        case QDeclarativeInstruction::CreateObject:
            {
                QBitField bindings;
                if (instr.create.bindingBits != -1) {
                    const QByteArray &bits = datas.at(instr.create.bindingBits);
                    bindings = QBitField((const quint32*)bits.constData(),
                                         bits.size() * 8);
                }
                if (stack.isEmpty())
                    bindings = bindings.united(bindingSkipList);

                QObject *o = 
                    types.at(instr.create.type).createInstance(ctxt, bindings, &vmeErrors);

                if (!o) {
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Unable to create object of type %1").arg(QString::fromLatin1(types.at(instr.create.type).className)));
                }

                QDeclarativeData *ddata = QDeclarativeData::get(o);
                Q_ASSERT(ddata);

                if (stack.isEmpty()) {
                    if (ddata->context) {
                        Q_ASSERT(ddata->context != ctxt);
                        Q_ASSERT(ddata->outerContext);
                        Q_ASSERT(ddata->outerContext != ctxt);
                        QDeclarativeContextData *c = ddata->context;
                        while (c->linkedContext) c = c->linkedContext;
                        c->linkedContext = ctxt;
                    } else {
                        ctxt->addObject(o);
                    }

                    ddata->ownContext = true;
                } else if (!ddata->context) {
                    ctxt->addObject(o);
                }

                ddata->setImplicitDestructible();
                ddata->outerContext = ctxt;
                ddata->lineNumber = instr.line;
                ddata->columnNumber = instr.create.column;

                if (instr.create.data != -1) {
                    QDeclarativeCustomParser *customParser =
                        types.at(instr.create.type).type->customParser();
                    customParser->setCustomData(o, datas.at(instr.create.data));
                }
                if (!stack.isEmpty()) {
                    QObject *parent = stack.top();
                    if (o->isWidgetType()) { 
                        QWidget *widget = static_cast<QWidget*>(o); 
                        if (parent->isWidgetType()) { 
                            QWidget *parentWidget = static_cast<QWidget*>(parent); 
                            widget->setParent(parentWidget); 
                        } else { 
                            // TODO: parent might be a layout 
                        } 
                    } else { 
			    QDeclarative_setParent_noEvent(o, parent);
                    } 
                }
                stack.push(o);
            }
            break;

        case QDeclarativeInstruction::CreateSimpleObject:
            {
                QObject *o = (QObject *)operator new(instr.createSimple.typeSize + 
                                                     sizeof(QDeclarativeData));   
                ::memset(static_cast<void *>(o), 0, instr.createSimple.typeSize + sizeof(QDeclarativeData));
                instr.createSimple.create(o);

                QDeclarativeData *ddata = (QDeclarativeData *)(((const char *)o) + instr.createSimple.typeSize);
                const QDeclarativeCompiledData::TypeReference &ref = types.at(instr.createSimple.type);
                if (!ddata->propertyCache && ref.typePropertyCache) {
                    ddata->propertyCache = ref.typePropertyCache;
                    ddata->propertyCache->addref();
                }
                ddata->lineNumber = instr.line;
                ddata->columnNumber = instr.createSimple.column;

                QObjectPrivate::get(o)->declarativeData = ddata;                                                      
                ddata->context = ddata->outerContext = ctxt;
                ddata->nextContextObject = ctxt->contextObjects; 
                if (ddata->nextContextObject) 
                    ddata->nextContextObject->prevContextObject = &ddata->nextContextObject; 
                ddata->prevContextObject = &ctxt->contextObjects; 
                ctxt->contextObjects = ddata; 

                QObject *parent = stack.top();                                                                    
                QDeclarative_setParent_noEvent(o, parent);                                                        

                stack.push(o);
            }
            break;

        case QDeclarativeInstruction::SetId:
            {
                QObject *target = stack.top();
                ctxt->setIdProperty(instr.setId.index, target);
            }
            break;


        case QDeclarativeInstruction::SetDefault:
            {
                ctxt->contextObject = stack.top();
            }
            break;

        case QDeclarativeInstruction::CreateComponent:
            {
                QDeclarativeComponent *qcomp = 
                    new QDeclarativeComponent(ctxt->engine, comp, ii + 1, instr.createComponent.count,
                                              stack.isEmpty() ? 0 : stack.top());

                QDeclarativeData *ddata = QDeclarativeData::get(qcomp, true);
                Q_ASSERT(ddata);

                ctxt->addObject(qcomp);

                if (stack.isEmpty()) 
                    ddata->ownContext = true;

                ddata->setImplicitDestructible();
                ddata->outerContext = ctxt;
                ddata->lineNumber = instr.line;
                ddata->columnNumber = instr.create.column;

                QDeclarativeComponentPrivate::get(qcomp)->creationContext = ctxt;

                stack.push(qcomp);
                ii += instr.createComponent.count;
            }
            break;

        case QDeclarativeInstruction::StoreMetaObject:
            {
                QObject *target = stack.top();

                QMetaObject mo;
                const QByteArray &metadata = datas.at(instr.storeMeta.data);
                QMetaObjectBuilder::fromRelocatableData(&mo, 0, metadata);

                const QDeclarativeVMEMetaData *data = 
                    (const QDeclarativeVMEMetaData *)datas.at(instr.storeMeta.aliasData).constData();

                (void)new QDeclarativeVMEMetaObject(target, &mo, data, comp);

                if (instr.storeMeta.propertyCache != -1) {
                    QDeclarativeData *ddata = QDeclarativeData::get(target, true);
                    if (ddata->propertyCache) ddata->propertyCache->release();
                    ddata->propertyCache = propertyCaches.at(instr.storeMeta.propertyCache);
                    ddata->propertyCache->addref();
                }
            }
            break;

        case QDeclarativeInstruction::StoreVariant:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeString.propertyIndex);

                // XXX - can be more efficient
                QVariant v = QDeclarativeStringConverters::variantFromString(primitives.at(instr.storeString.value));
                void *a[] = { &v, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeString.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreVariantInteger:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeString.propertyIndex);

                QVariant v(instr.storeInteger.value);
                void *a[] = { &v, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeString.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreVariantDouble:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeString.propertyIndex);

                QVariant v(instr.storeDouble.value);
                void *a[] = { &v, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeString.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreVariantBool:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeString.propertyIndex);

                QVariant v(instr.storeBool.value);
                void *a[] = { &v, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeString.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreString:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeString.propertyIndex);

                void *a[] = { (void *)&primitives.at(instr.storeString.value), 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeString.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreUrl:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeUrl.propertyIndex);

                void *a[] = { (void *)&urls.at(instr.storeUrl.value), 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeUrl.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreFloat:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeFloat.propertyIndex);

                float f = instr.storeFloat.value;
                void *a[] = { &f, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                      instr.storeFloat.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreDouble:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeDouble.propertyIndex);

                double d = instr.storeDouble.value;
                void *a[] = { &d, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                      instr.storeDouble.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreBool:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeBool.propertyIndex);

                void *a[] = { (void *)&instr.storeBool.value, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeBool.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreInteger:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeInteger.propertyIndex);

                void *a[] = { (void *)&instr.storeInteger.value, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeInteger.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreColor:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeColor.propertyIndex);

                QColor c = QColor::fromRgba(instr.storeColor.value);
                void *a[] = { &c, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeColor.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreDate:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeDate.propertyIndex);

                QDate d = QDate::fromJulianDay(instr.storeDate.value);
                void *a[] = { &d, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeDate.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreTime:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeTime.propertyIndex);

                QTime t;
                t.setHMS(intData.at(instr.storeTime.valueIndex),
                         intData.at(instr.storeTime.valueIndex+1),
                         intData.at(instr.storeTime.valueIndex+2),
                         intData.at(instr.storeTime.valueIndex+3));
                void *a[] = { &t, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeTime.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreDateTime:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeDateTime.propertyIndex);

                QTime t;
                t.setHMS(intData.at(instr.storeDateTime.valueIndex+1),
                         intData.at(instr.storeDateTime.valueIndex+2),
                         intData.at(instr.storeDateTime.valueIndex+3),
                         intData.at(instr.storeDateTime.valueIndex+4));
                QDateTime dt(QDate::fromJulianDay(intData.at(instr.storeDateTime.valueIndex)), t);
                void *a[] = { &dt, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                      instr.storeDateTime.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StorePoint:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeRealPair.propertyIndex);

                QPoint p = QPointF(floatData.at(instr.storeRealPair.valueIndex),
                                   floatData.at(instr.storeRealPair.valueIndex+1)).toPoint();
                void *a[] = { &p, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeRealPair.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StorePointF:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeRealPair.propertyIndex);

                QPointF p(floatData.at(instr.storeRealPair.valueIndex),
                          floatData.at(instr.storeRealPair.valueIndex+1));
                void *a[] = { &p, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeRealPair.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreSize:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeRealPair.propertyIndex);

                QSize p = QSizeF(floatData.at(instr.storeRealPair.valueIndex),
                                 floatData.at(instr.storeRealPair.valueIndex+1)).toSize();
                void *a[] = { &p, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeRealPair.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreSizeF:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeRealPair.propertyIndex);

                QSizeF s(floatData.at(instr.storeRealPair.valueIndex),
                         floatData.at(instr.storeRealPair.valueIndex+1));
                void *a[] = { &s, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeRealPair.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreRect:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeRect.propertyIndex);

                QRect r = QRectF(floatData.at(instr.storeRect.valueIndex),
                                 floatData.at(instr.storeRect.valueIndex+1),
                                 floatData.at(instr.storeRect.valueIndex+2),
                                 floatData.at(instr.storeRect.valueIndex+3)).toRect();
                void *a[] = { &r, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeRect.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreRectF:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeRect.propertyIndex);

                QRectF r(floatData.at(instr.storeRect.valueIndex),
                         floatData.at(instr.storeRect.valueIndex+1),
                         floatData.at(instr.storeRect.valueIndex+2),
                         floatData.at(instr.storeRect.valueIndex+3));
                void *a[] = { &r, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeRect.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreVector3D:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeVector3D.propertyIndex);

                QVector3D p(floatData.at(instr.storeVector3D.valueIndex),
                            floatData.at(instr.storeVector3D.valueIndex+1),
                            floatData.at(instr.storeVector3D.valueIndex+2));
                void *a[] = { &p, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeVector3D.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreObject:
            {
                QObject *assignObj = stack.pop();
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeObject.propertyIndex);

                void *a[] = { (void *)&assignObj, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeObject.propertyIndex, a);
            }
            break;


        case QDeclarativeInstruction::AssignCustomType:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.assignCustomType.propertyIndex);

                QDeclarativeCompiledData::CustomTypeData data = customTypeData.at(instr.assignCustomType.valueIndex);
                const QString &primitive = primitives.at(data.index);
                QDeclarativeMetaType::StringConverter converter = 
                    QDeclarativeMetaType::customStringConverter(data.type);
                QVariant v = (*converter)(primitive);

                QMetaProperty prop = 
                        target->metaObject()->property(instr.assignCustomType.propertyIndex);
                if (v.isNull() || ((int)prop.type() != data.type && prop.userType() != data.type)) 
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign value %1 to property %2").arg(primitive).arg(QString::fromUtf8(prop.name())));

                void *a[] = { (void *)v.data(), 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.assignCustomType.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::AssignSignalObject:
            {
                // XXX optimize

                QObject *assign = stack.pop();
                QObject *target = stack.top();
                int sigIdx = instr.assignSignalObject.signal;
                const QByteArray &pr = datas.at(sigIdx);

                QDeclarativeProperty prop(target, QString::fromUtf8(pr));
                if (prop.type() & QDeclarativeProperty::SignalProperty) {

                    QMetaMethod method = QDeclarativeMetaType::defaultMethod(assign);
                    if (method.signature() == 0)
                        VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign object type %1 with no default method").arg(QString::fromLatin1(assign->metaObject()->className())));

                    if (!QMetaObject::checkConnectArgs(prop.method().signature(), method.signature()))
                        VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot connect mismatched signal/slot %1 %vs. %2").arg(QString::fromLatin1(method.signature())).arg(QString::fromLatin1(prop.method().signature())));

                    QDeclarativePropertyPrivate::connect(target, prop.index(), assign, method.methodIndex());

                } else {
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign an object to signal property %1").arg(QString::fromUtf8(pr)));
                }


            }
            break;

        case QDeclarativeInstruction::StoreSignal:
            {
                QObject *target = stack.top();
                QObject *context = stack.at(stack.count() - 1 - instr.storeSignal.context);

                QMetaMethod signal = target->metaObject()->method(instr.storeSignal.signalIndex);

                QDeclarativeBoundSignal *bs = new QDeclarativeBoundSignal(target, signal, target);
                QDeclarativeExpression *expr = 
                    new QDeclarativeExpression(ctxt, context, primitives.at(instr.storeSignal.value));
                expr->setSourceLocation(comp->name, instr.line);
                static_cast<QDeclarativeExpressionPrivate *>(QObjectPrivate::get(expr))->name = datas.at(instr.storeSignal.name);
                bs->setExpression(expr);
            }
            break;

        case QDeclarativeInstruction::StoreImportedScript:
            {
                ctxt->addImportedScript(scripts.at(instr.storeScript.value));
            }
            break;

        case QDeclarativeInstruction::StoreScriptString:
            {
                QObject *target = stack.top();
                QObject *scope = stack.at(stack.count() - 1 - instr.storeScriptString.scope);
                QDeclarativeScriptString ss;
                ss.setContext(ctxt->asQDeclarativeContext());
                ss.setScopeObject(scope);
                ss.setScript(primitives.at(instr.storeScriptString.value));

                void *a[] = { &ss, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeScriptString.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::BeginObject:
            {
                QObject *target = stack.top();
                QDeclarativeParserStatus *status = reinterpret_cast<QDeclarativeParserStatus *>(reinterpret_cast<char *>(target) + instr.begin.castValue);
                parserStatus.append(status);
                status->d = &parserStatus.values[parserStatus.count - 1];

                status->classBegin();
            }
            break;

        case QDeclarativeInstruction::StoreBinding:
        case QDeclarativeInstruction::StoreBindingOnAlias:
            {
                QObject *target = 
                    stack.at(stack.count() - 1 - instr.assignBinding.owner);
                QObject *context = 
                    stack.at(stack.count() - 1 - instr.assignBinding.context);

                QDeclarativeProperty mp = 
                    QDeclarativePropertyPrivate::restore(datas.at(instr.assignBinding.property), target, ctxt);

                int coreIndex = mp.index();

                if ((stack.count() - instr.assignBinding.owner) == 1 && bindingSkipList.testBit(coreIndex)) 
                    break;

                QDeclarativeBinding *bind = new QDeclarativeBinding((void *)datas.at(instr.assignBinding.value).constData(), comp, context, ctxt, comp->name, instr.line, 0);
                bindValues.append(bind);
                bind->m_mePtr = &bindValues.values[bindValues.count - 1];
                bind->setTarget(mp);

                if (instr.type == QDeclarativeInstruction::StoreBindingOnAlias) {
                    QDeclarativeAbstractBinding *old = QDeclarativePropertyPrivate::setBindingNoEnable(target, coreIndex, QDeclarativePropertyPrivate::valueTypeCoreIndex(mp), bind);
                    if (old) { old->destroy(); }
                } else {
                    bind->addToObject(target, QDeclarativePropertyPrivate::bindingIndex(mp));
                }
            }
            break;

        case QDeclarativeInstruction::StoreCompiledBinding:
            {
                QObject *target = 
                    stack.at(stack.count() - 1 - instr.assignBinding.owner);
                QObject *scope = 
                    stack.at(stack.count() - 1 - instr.assignBinding.context);

                int property = instr.assignBinding.property;
                if (stack.count() == 1 && bindingSkipList.testBit(property & 0xFFFF))  
                    break;

                QDeclarativeAbstractBinding *binding = 
                    ctxt->optimizedBindings->configBinding(instr.assignBinding.value, target, scope, property);
                bindValues.append(binding);
                binding->m_mePtr = &bindValues.values[bindValues.count - 1];
                binding->addToObject(target, property);
            }
            break;

        case QDeclarativeInstruction::StoreValueSource:
            {
                QObject *obj = stack.pop();
                QDeclarativePropertyValueSource *vs = reinterpret_cast<QDeclarativePropertyValueSource *>(reinterpret_cast<char *>(obj) + instr.assignValueSource.castValue);
                QObject *target = stack.at(stack.count() - 1 - instr.assignValueSource.owner);

                QDeclarativeProperty prop = 
                    QDeclarativePropertyPrivate::restore(datas.at(instr.assignValueSource.property), target, ctxt);
                obj->setParent(target);
                vs->setTarget(prop);
            }
            break;

        case QDeclarativeInstruction::StoreValueInterceptor:
            {
                QObject *obj = stack.pop();
                QDeclarativePropertyValueInterceptor *vi = reinterpret_cast<QDeclarativePropertyValueInterceptor *>(reinterpret_cast<char *>(obj) + instr.assignValueInterceptor.castValue);
                QObject *target = stack.at(stack.count() - 1 - instr.assignValueInterceptor.owner);
                QDeclarativeProperty prop = 
                    QDeclarativePropertyPrivate::restore(datas.at(instr.assignValueInterceptor.property), target, ctxt);
                obj->setParent(target);
                vi->setTarget(prop);
                QDeclarativeVMEMetaObject *mo = static_cast<QDeclarativeVMEMetaObject *>((QMetaObject*)target->metaObject());
                mo->registerInterceptor(prop.index(), QDeclarativePropertyPrivate::valueTypeCoreIndex(prop), vi);
            }
            break;

        case QDeclarativeInstruction::StoreObjectQList:
            {
                QObject *assign = stack.pop();

                const ListInstance &list = qliststack.top();
                list.qListProperty.append((QDeclarativeListProperty<void>*)&list.qListProperty, assign);
            }
            break;

        case QDeclarativeInstruction::AssignObjectList:
            {
                // This is only used for assigning interfaces
                QObject *assign = stack.pop();
                const ListInstance &list = qliststack.top();

                int type = list.type;

                void *ptr = 0;

                const char *iid = QDeclarativeMetaType::interfaceIId(type);
                if (iid) 
                    ptr = assign->qt_metacast(iid);
                if (!ptr) 
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign object to list"));


                list.qListProperty.append((QDeclarativeListProperty<void>*)&list.qListProperty, ptr);
            }
            break;

        case QDeclarativeInstruction::StoreVariantObject:
            {
                QObject *assign = stack.pop();
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeObject.propertyIndex);

                QVariant v = QVariant::fromValue(assign);
                void *a[] = { &v, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeObject.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreInterface:
            {
                QObject *assign = stack.pop();
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeObject.propertyIndex);

                int coreIdx = instr.storeObject.propertyIndex;
                QMetaProperty prop = target->metaObject()->property(coreIdx);
                int t = prop.userType();
                const char *iid = QDeclarativeMetaType::interfaceIId(t);
                bool ok = false;
                if (iid) {
                    void *ptr = assign->qt_metacast(iid);
                    if (ptr) {
                        void *a[] = { &ptr, 0, &status, &flags };
                        QMetaObject::metacall(target, 
                                              QMetaObject::WriteProperty,
                                              coreIdx, a);
                        ok = true;
                    }
                } 

                if (!ok) 
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign object to interface property"));
            }
            break;
            
        case QDeclarativeInstruction::FetchAttached:
            {
                QObject *target = stack.top();

                QObject *qmlObject = qmlAttachedPropertiesObjectById(instr.fetchAttached.id, target);

                if (!qmlObject)
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Unable to create attached object"));

                stack.push(qmlObject);
            }
            break;

        case QDeclarativeInstruction::FetchQList:
            {
                QObject *target = stack.top();

                qliststack.push(ListInstance(instr.fetchQmlList.type));

                void *a[1];
                a[0] = (void *)&(qliststack.top().qListProperty);
                QMetaObject::metacall(target, QMetaObject::ReadProperty, 
                                      instr.fetchQmlList.property, a);
            }
            break;

        case QDeclarativeInstruction::FetchObject:
            {
                QObject *target = stack.top();

                QObject *obj = 0;
                // NOTE: This assumes a cast to QObject does not alter the 
                // object pointer
                void *a[1];
                a[0] = &obj;
                QMetaObject::metacall(target, QMetaObject::ReadProperty, 
                                      instr.fetch.property, a);

                if (!obj)
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot set properties on %1 as it is null").arg(QString::fromUtf8(target->metaObject()->property(instr.fetch.property).name())));

                stack.push(obj);
            }
            break;

        case QDeclarativeInstruction::PopQList:
            {
                qliststack.pop();
            }
            break;

        case QDeclarativeInstruction::Defer:
            {
                if (instr.defer.deferCount) {
                    QObject *target = stack.top();
                    QDeclarativeData *data = 
                        QDeclarativeData::get(target, true);
                    comp->addref();
                    data->deferredComponent = comp;
                    data->deferredIdx = ii;
                    ii += instr.defer.deferCount;
                }
            }
            break;

        case QDeclarativeInstruction::PopFetchedObject:
            {
                stack.pop();
            }
            break;

        case QDeclarativeInstruction::FetchValueType:
            {
                QObject *target = stack.top();

                if (instr.fetchValue.bindingSkipList != 0) {
                    // Possibly need to clear bindings
                    QDeclarativeData *targetData = QDeclarativeData::get(target);
                    if (targetData) {
                        QDeclarativeAbstractBinding *binding = 
                            QDeclarativePropertyPrivate::binding(target, instr.fetchValue.property, -1);

                        if (binding && binding->bindingType() != QDeclarativeAbstractBinding::ValueTypeProxy) {
                            QDeclarativePropertyPrivate::setBinding(target, instr.fetchValue.property, -1, 0);
                            binding->destroy();
                        } else if (binding) {
                            QDeclarativeValueTypeProxyBinding *proxy = 
                                static_cast<QDeclarativeValueTypeProxyBinding *>(binding);
                            proxy->removeBindings(instr.fetchValue.bindingSkipList);
                        }
                    }
                }

                QDeclarativeValueType *valueHandler = ep->valueTypes[instr.fetchValue.type];
                valueHandler->read(target, instr.fetchValue.property);
                stack.push(valueHandler);
            }
            break;

        case QDeclarativeInstruction::PopValueType:
            {
                QDeclarativeValueType *valueHandler = 
                    static_cast<QDeclarativeValueType *>(stack.pop());
                QObject *target = stack.top();
                valueHandler->write(target, instr.fetchValue.property, 
                                    QDeclarativePropertyPrivate::BypassInterceptor);
            }
            break;

        default:
            qFatal("QDeclarativeCompiledData: Internal error - unknown instruction %d", instr.type);
            break;
        }
    }

    if (isError()) {
        if (!stack.isEmpty()) {
            delete stack.at(0); // ### What about failures in deferred creation?
        } else {
            ctxt->destroy();
        }

        QDeclarativeEnginePrivate::clear(bindValues);
        QDeclarativeEnginePrivate::clear(parserStatus);
        return 0;
    }

    if (bindValues.count)
        ep->bindValues << bindValues;
    else if (bindValues.values)
        bindValues.clear();

    if (parserStatus.count)
        ep->parserStatus << parserStatus;
    else if (parserStatus.values)
        parserStatus.clear();

    Q_ASSERT(stack.count() == 1);
    return stack.top();
}
Beispiel #25
0
void QDeclarativePropertyCache::append(QDeclarativeEngine *engine, const QMetaObject *metaObject, 
                                       int revision, 
                                       Data::Flag propertyFlags, Data::Flag methodFlags, Data::Flag signalFlags)
{
    Q_UNUSED(revision);

    allowedRevisionCache.append(0);

    QDeclarativeEnginePrivate *enginePriv = QDeclarativeEnginePrivate::get(engine);
    int methodCount = metaObject->methodCount();
    // 3 to block the destroyed signal and the deleteLater() slot
    int methodOffset = qMax(3, metaObject->methodOffset()); 

    methodIndexCache.resize(methodCount);
    for (int ii = methodOffset; ii < methodCount; ++ii) {
        QMetaMethod m = metaObject->method(ii);
        if (m.access() == QMetaMethod::Private) 
            continue;
        QString methodName = QString::fromUtf8(m.signature());

        int parenIdx = methodName.indexOf(QLatin1Char('('));
        Q_ASSERT(parenIdx != -1);
        methodName = methodName.left(parenIdx);

        RData *data = new RData;
        data->identifier = enginePriv->objectClass->createPersistentIdentifier(methodName);
        methodIndexCache[ii] = data;  

        data->load(m);
        if (m.methodType() == QMetaMethod::Slot || m.methodType() == QMetaMethod::Method) 
            data->flags |= methodFlags;
        else if (m.methodType() == QMetaMethod::Signal)
            data->flags |= signalFlags;

        data->metaObjectOffset = allowedRevisionCache.count() - 1;

        if (stringCache.contains(methodName)) {
            RData *old = stringCache[methodName];
            // We only overload methods in the same class, exactly like C++
            if (old->flags & Data::IsFunction && old->coreIndex >= methodOffset)
                data->relatedIndex = old->coreIndex;
            data->overrideIndexIsProperty = !bool(old->flags & Data::IsFunction);
            data->overrideIndex = old->coreIndex;
            stringCache[methodName]->release();
            identifierCache[data->identifier.identifier]->release();
        }

        stringCache.insert(methodName, data);
        identifierCache.insert(data->identifier.identifier, data);
        data->addref();
        data->addref();
    }

    int propCount = metaObject->propertyCount();
    int propOffset = metaObject->propertyOffset();

    indexCache.resize(propCount);
    for (int ii = propOffset; ii < propCount; ++ii) {
        QMetaProperty p = metaObject->property(ii);
        if (!p.isScriptable())
            continue;

        QString propName = QString::fromUtf8(p.name());

        RData *data = new RData;
        data->identifier = enginePriv->objectClass->createPersistentIdentifier(propName);
        indexCache[ii] = data;

        data->load(p, engine);
        data->flags |= propertyFlags;

        data->metaObjectOffset = allowedRevisionCache.count() - 1;

        if (stringCache.contains(propName)) {
            RData *old = stringCache[propName];
            data->overrideIndexIsProperty = !bool(old->flags & Data::IsFunction);
            data->overrideIndex = old->coreIndex;
            stringCache[propName]->release();
            identifierCache[data->identifier.identifier]->release();
        }

        stringCache.insert(propName, data);
        identifierCache.insert(data->identifier.identifier, data);
        data->addref();
        data->addref();
    }
}
Beispiel #26
0
/* We catch all qt_metacall invocations */
extern "C" SEXP qt_qmetacall(SEXP x, SEXP s_call, SEXP s_id, SEXP s_args)
{
  SmokeObject *so = SmokeObject::fromSexp(x);
  QMetaObject::Call call =
    enum_from_sexp<QMetaObject::Call>(s_call, SmokeType());
  int id = from_sexp<int>(s_id);
  void **args = reinterpret_cast<void **>(from_sexp<void *>(s_args));
  
  // Assume the target slot is a C++ one
  Smoke::StackItem i[4];
  i[1].s_enum = call;
  i[2].s_int = id;
  i[3].s_voidp = args;
  so->invokeMethod("qt_metacall$$?", i);
  int ret = i[0].s_int;
  if (ret < 0) {
    return ScalarInteger(ret);
  }

  QObject * qobj = reinterpret_cast<QObject *>(so->castPtr("QObject"));
  // get obj metaobject with a virtual call
  const QMetaObject *metaobject = qobj->metaObject();
  
  if (call == QMetaObject::ReadProperty || call == QMetaObject::WriteProperty) {
    MocStack mocStack = MocStack(args, 1);
    QMetaProperty metaProp = metaobject->property(id);
    Property *prop = so->klass()->property(metaProp.name());
    SmokeType type(so->smoke(), metaProp.typeName(), metaobject->className());
    if (call == QMetaObject::ReadProperty) {
      Smoke::StackItem item = prop->read(so);
      mocStack.returnFromSmoke(SmokeStack(&item, 1), type);
    } else if (call == QMetaObject::WriteProperty) {
      QVector<SmokeType> types;
      types += type;
      prop->write(so, mocStack.toSmoke(types).ret());
    }
  }

  if (call != QMetaObject::InvokeMetaMethod)
    return ScalarInteger(id);
  
  // get method count
  int count = metaobject->methodCount();
  
  QMetaMethod method = metaobject->method(id);
  if (method.methodType() == QMetaMethod::Signal) {
    // FIXME: this overload of 'activate' is obsolete
    metaobject->activate(qobj, id, (void**) args);
    return ScalarInteger(id - count);
  }
  
  MocDynamicBinding binding(MocMethod(so->smoke(), metaobject, id));
  binding.invoke(qobj, args);
  /*
    DynamicBinding binding(MocMethod(so->smoke(), metaobject, id));
    QVector<SmokeType> stackTypes = binding.types();
    MocStack mocStack = MocStack(args, stackTypes.size());
    SmokeStack smokeStack = mocStack.toSmoke(stackTypes);
    binding.invoke(so, smokeStack.items());
    mocStack.returnFromSmoke(smokeStack, stackTypes[0]);
  */
  if (binding.lastError() == Method::NoError)
    warning("Slot invocation failed for %s::%s", so->klass()->name(),
            binding.name());
  
  return ScalarInteger(id - count);
}
Beispiel #27
0
void QDeclarativeExpressionPrivate::updateGuards(const QPODVector<QDeclarativeEnginePrivate::CapturedProperty> &properties)
{
    Q_Q(QDeclarativeExpression);

    static int notifyIdx = -1;
    if (notifyIdx == -1) 
        notifyIdx = QDeclarativeExpression::staticMetaObject.indexOfMethod("__q_notify()");

    if (properties.count() != data->guardListLength) {
        QDeclarativeNotifierEndpoint *newGuardList = 
            new QDeclarativeNotifierEndpoint[properties.count()];

        for (int ii = 0; ii < qMin(data->guardListLength, properties.count()); ++ii) 
           data->guardList[ii].copyAndClear(newGuardList[ii]);

        delete [] data->guardList;
        data->guardList = newGuardList;
        data->guardListLength = properties.count();
    }

    bool outputWarningHeader = false;
    bool noChanges = true;
    for (int ii = 0; ii < properties.count(); ++ii) {
        QDeclarativeNotifierEndpoint &guard = data->guardList[ii];
        const QDeclarativeEnginePrivate::CapturedProperty &property = properties.at(ii);

        guard.target = q;
        guard.targetMethod = notifyIdx;

        if (property.notifier != 0) {

            if (!noChanges && guard.isConnected(property.notifier)) {
                // Nothing to do

            } else {
                noChanges = false;

                bool existing = false;
                for (int jj = 0; !existing && jj < ii; ++jj) 
                    if (data->guardList[jj].isConnected(property.notifier)) 
                        existing = true;

                if (existing) {
                    // duplicate
                    guard.disconnect();
                } else {
                    guard.connect(property.notifier);
                }
            }


        } else if (property.notifyIndex != -1) {

            if (!noChanges && guard.isConnected(property.object, property.notifyIndex)) {
                // Nothing to do

            } else {
                noChanges = false;

                bool existing = false;
                for (int jj = 0; !existing && jj < ii; ++jj) 
                    if (data->guardList[jj].isConnected(property.object, property.notifyIndex)) 
                        existing = true;

                if (existing) {
                    // duplicate
                    guard.disconnect();
                } else {
                    guard.connect(property.object, property.notifyIndex);
                }
            }

        } else {
            if (!outputWarningHeader) {
                outputWarningHeader = true;
                qWarning() << "QDeclarativeExpression: Expression" << q->expression()
                    << "depends on non-NOTIFYable properties:";
            }

            const QMetaObject *metaObj = property.object->metaObject();
            QMetaProperty metaProp = metaObj->property(property.coreIndex);

            qWarning().nospace() << "    " << metaObj->className()
                                 << "::" << metaProp.name();
        }
    }
}
Beispiel #28
0
void QSAEditor::completeQMetaObject( const QMetaObject *meta,
					 const QString &,
					 QVector<CompletionEntry> &res,
					 int flags,
					 QSObject &obj )
{
    QMap<QString, bool> propMap;
    bool includeSuperClass = (flags & IncludeSuperClass) == IncludeSuperClass;

    // properties
    const QMetaObject *m = meta;
    int num = m->propertyCount();

    for ( int j = 0; j < num; ++j ) {
        const QMetaProperty mp = m->property( j );
        if ( propMap.find( QString::fromLatin1(mp.name()) ) != propMap.end() )
            continue;
        CompletionEntry c;
        propMap[QLatin1String(mp.name())] = false;
        c.type = QLatin1String("property");
        c.text = mp.name();
        c.prefix = QString();
        c.postfix2 = mp.typeName();
        QuickInterpreter::cleanType( c.postfix2 );
        if ( !c.postfix2.isEmpty() )
            c.postfix2.prepend( QLatin1String(" : ") );
        res.append( c );
    }

    if ( includeSuperClass && obj.isValid() && !obj.isUndefined() ) {
        QStringList vars = interpreter()->variablesOf( obj, true );
        QStringList::iterator it;
        for ( it = vars.begin(); it != vars.end(); ++it ) {
            CompletionEntry c;
            c.type = QLatin1String("variable");
            c.text = *it;
            c.prefix = QString();
            c.postfix2 = QString();
            res << c;
        }
    }

    // functions
    QList<Property> lst;
    QList<Property>::Iterator pit;
    getSlots( meta, lst, includeSuperClass, false, false );
    for ( pit  = lst.begin(); pit != lst.end(); ++pit ) {
        CompletionEntry c;
        c.type = QLatin1String("function");
        c.text = (*pit).name;
        c.postfix = QLatin1String("()");
        c.postfix2 = (*pit).type;
        if ( !c.postfix2.isEmpty() )
            c.postfix2.prepend( QString::fromLatin1(" : ") );
        res << c;
    }
    if ( includeSuperClass && obj.isValid() && !obj.isUndefined() ) {
        QStringList funcs = interpreter()->functionsOf( obj, true, true, true );
        QStringList::Iterator it;
        for ( it = funcs.begin(); it != funcs.end(); ++it ) {
            CompletionEntry c;
            c.type = QLatin1String("function");
            c.text = *it;
            c.prefix = QString();
            c.postfix2 = QString();
            res << c;
        }
    }

    // enum values

    m = meta;
    for (int k=0; k<m->enumeratorCount(); ++k) {
        QMetaEnum me = m->enumerator(k);
        for (int l=0; l<me.keyCount(); ++l) {
            CompletionEntry c;
            c.type = QLatin1String("enum");
            c.text = QLatin1String(me.key(l));
            c.prefix = QString();
            c.postfix2 = QLatin1String(me.name());

            if (!c.postfix2.isEmpty())
                c.postfix2.prepend( QString::fromLatin1(" : ") );
            res << c;
        }
    }

    if ( includeSuperClass && obj.isValid() && !obj.isUndefined() ) {
        QStringList classes = interpreter()->classesOf( obj );
        QStringList::Iterator it;
        for ( it = classes.begin(); it != classes.end(); ++it ) {
            CompletionEntry c;
            c.type = QLatin1String("class");
            c.text = *it;
            c.prefix = QString();
            c.postfix2 = QString();
            res << c;
        }
    }
}
QVariant QDBusAbstractInterfacePrivate::property(const QMetaProperty &mp) const
{
    if (!connection.isConnected())    // not connected
        return QVariant();

    // is this metatype registered?
    int mid;
    const char *expectedSignature;
    if (mp.type() == QVariant::LastType) {
        // We're asking to read a QVariant
        mid = qMetaTypeId<QDBusVariant>();
        expectedSignature = "v";
    } else {
        mid = QMetaType::type(mp.typeName());
        expectedSignature = QDBusMetaType::typeToSignature(mid);
        if (expectedSignature == 0) {
            qWarning("QDBusAbstractInterface: type %s must be registered with QtDBus before it can be "
                     "used to read property %s.%s",
                     mp.typeName(), qPrintable(interface), mp.name());
            return QVariant();
        }
    }

    // try to read this property
    QDBusMessage msg = QDBusMessage::createMethodCall(service, path,
                                                      QLatin1String(DBUS_INTERFACE_PROPERTIES),
                                                      QLatin1String("Get"));
    msg << interface << QString::fromUtf8(mp.name());
    QDBusMessage reply = connection.call(msg, QDBus::Block);

    if (reply.type() != QDBusMessage::ReplyMessage) {
        lastError = reply;
        return QVariant();
    }
    if (reply.signature() != QLatin1String("v")) {
        QString errmsg = QLatin1String("Invalid signature `%1' in return from call to "
                                       DBUS_INTERFACE_PROPERTIES);
        lastError = QDBusError(QDBusError::InvalidSignature, errmsg.arg(reply.signature()));
        return QVariant();
    }

    QByteArray foundSignature;
    const char *foundType = 0;
    QVariant value = qvariant_cast<QDBusVariant>(reply.arguments().at(0)).variant();

    if (value.userType() == mid)
        return value;       // simple match

    if (value.userType() == qMetaTypeId<QDBusArgument>()) {
        QDBusArgument arg = qvariant_cast<QDBusArgument>(value);

        foundType = "user type";
        foundSignature = arg.currentSignature().toLatin1();
        if (foundSignature == expectedSignature) {
            void *null = 0;
            QVariant result(mid, null);
            QDBusMetaType::demarshall(arg, mid, result.data());

            if (mp.type() == QVariant::LastType)
                // special case: QVariant
                return qvariant_cast<QDBusVariant>(result).variant();
            return result;
        }
    } else {
        foundType = value.typeName();
        foundSignature = QDBusMetaType::typeToSignature(value.userType());
    }

    // there was an error...
    QString errmsg = QLatin1String("Unexpected `%1' (%2) when retrieving property `%3.%4' "
                                   "(expected type `%5' (%6))");
    lastError = QDBusError(QDBusError::InvalidSignature,
                           errmsg.arg(QString::fromLatin1(foundType),
                                      QString::fromLatin1(foundSignature),
                                      interface,
                                      QString::fromUtf8(mp.name()),
                                      QString::fromLatin1(mp.typeName()),
                                      QString::fromLatin1(expectedSignature)));
    return QVariant();
}
Beispiel #30
0
int GoValueMetaObject::metaCall(QMetaObject::Call c, int idx, void **a)
{
    //qWarning() << "GoValueMetaObject::metaCall" << c << idx;
    switch (c) {
    case QMetaObject::ReadProperty:
    case QMetaObject::WriteProperty:
        {
            // TODO Cache propertyOffset, methodOffset (and maybe qmlEngine)
            int propOffset = propertyOffset();
            if (idx < propOffset) {
                return value->qt_metacall(c, idx, a);
            }
            GoMemberInfo *memberInfo = typeInfo->fields;
            for (int i = 0; i < typeInfo->fieldsLen; i++) {
                if (memberInfo->metaIndex == idx) {
                    if (c == QMetaObject::ReadProperty) {
                        DataValue result;
                        hookGoValueReadField(qmlEngine(value), ref, memberInfo->reflectIndex, memberInfo->reflectGetIndex, memberInfo->reflectSetIndex, &result);
                        if (memberInfo->memberType == DTListProperty) {
                            if (result.dataType != DTListProperty) {
                                panicf("reading DTListProperty field returned non-DTListProperty result");
                            }
                            QQmlListProperty<QObject> *in = *reinterpret_cast<QQmlListProperty<QObject> **>(result.data);
                            QQmlListProperty<QObject> *out = reinterpret_cast<QQmlListProperty<QObject> *>(a[0]);
                            *out = *in;
                            // TODO Could provide a single variable in the stack to ReadField instead.
                            delete in;
                        } else {
                            QVariant *out = reinterpret_cast<QVariant *>(a[0]);
                            unpackDataValue(&result, out);
                        }
                    } else {
                        DataValue assign;
                        QVariant *in = reinterpret_cast<QVariant *>(a[0]);
                        packDataValue(in, &assign);
                        hookGoValueWriteField(qmlEngine(value), ref, memberInfo->reflectIndex, memberInfo->reflectSetIndex, &assign);
                        activate(value, methodOffset() + (idx - propOffset), 0);
                    }
                    return -1;
                }
                memberInfo++;
            }
            QMetaProperty prop = property(idx);
            qWarning() << "Property" << prop.name() << "not found!?";
            break;
        }
    case QMetaObject::InvokeMetaMethod:
        {
            if (idx < methodOffset()) {
                return value->qt_metacall(c, idx, a);
            }
            GoMemberInfo *memberInfo = typeInfo->methods;
            for (int i = 0; i < typeInfo->methodsLen; i++) {
                if (memberInfo->metaIndex == idx) {
                    // args[0] is the result if any.
                    DataValue args[1 + MaxParams];
                    for (int i = 1; i < memberInfo->numIn+1; i++) {
                        packDataValue(reinterpret_cast<QVariant *>(a[i]), &args[i]);
                    }
                    hookGoValueCallMethod(qmlEngine(value), ref, memberInfo->reflectIndex, args);
                    if (memberInfo->numOut > 0) {
                        unpackDataValue(&args[0], reinterpret_cast<QVariant *>(a[0]));
                    }
                    return -1;
                }
                memberInfo++;
            }
            QMetaMethod m = method(idx);
            qWarning() << "Method" << m.name() << "not found!?";
            break;
        }
    default:
        break; // Unhandled.
    }
    return -1;
}