static int writeProperty(QObject *obj, const QByteArray &property_name, QVariant value,
                         int propFlags = QDBusConnection::ExportAllProperties)
{
    const QMetaObject *mo = obj->metaObject();
    int pidx = mo->indexOfProperty(property_name);
    if (pidx == -1) {
        // this object has no property by that name
        return PropertyNotFound;
    }

    QMetaProperty mp = mo->property(pidx);

    // check if this property is exported
    bool isScriptable = mp.isScriptable();
    if (!(propFlags & QDBusConnection::ExportScriptableProperties) && isScriptable)
        return PropertyNotFound;
    if (!(propFlags & QDBusConnection::ExportNonScriptableProperties) && !isScriptable)
        return PropertyNotFound;

    // we found our property
    // do we have the right type?
    int id = mp.type();
    if (id == QVariant::UserType) {
        // dynamic type
        id = qDBusNameToTypeId(mp.typeName());
        if (id == -1) {
            // type not registered?
            qWarning("QDBusConnection: Unable to handle unregistered datatype '%s' for property '%s::%s'",
                     mp.typeName(), mo->className(), property_name.constData());
            return PropertyWriteFailed;
        }
    }

    if (id != 0xff && value.userType() == QDBusMetaTypeId::argument) {
        // we have to demarshall before writing
        void *null = 0;
        QVariant other(id, null);
        if (!QDBusMetaType::demarshall(qvariant_cast<QDBusArgument>(value), id, other.data())) {
            qWarning("QDBusConnection: type `%s' (%d) is not registered with QtDBus. "
                     "Use qDBusRegisterMetaType to register it",
                     mp.typeName(), id);
            return PropertyWriteFailed;
        }

        value = other;
    }

    // the property type here should match
    return mp.write(obj, value) ? PropertyWriteSuccess : PropertyWriteFailed;
}
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;
}
Exemplo n.º 3
0
void MashListModel::mashChanged(QMetaProperty prop, QVariant val)
{   
   Mash* mSend = qobject_cast<Mash*>(sender());
   
   // NOTE: how to get around the issue that the sender might live in
   // a different thread and therefore always cause sSend == 0?
   if( mSend == 0 )
      return;
   
   QString propName(prop.name());
   if( propName == "name" )
   {
      int ndx = mashes.indexOf(mSend);
      if( ndx >= 0 )
         emit dataChanged( createIndex(ndx,0), createIndex(ndx,0) );
   }
}
void listInterface(const QString &service, const QString &path, const QString &interface)
{
    QDBusInterfacePtr iface(*connection, service, path, interface);
    if (!iface->isValid()) {
        QDBusError err(iface->lastError());
        fprintf(stderr, "Interface '%s' not available in object %s at %s:\n%s (%s)\n",
                qPrintable(interface), qPrintable(path), qPrintable(service),
                qPrintable(err.name()), qPrintable(err.message()));
        exit(1);
    }
    const QMetaObject *mo = iface->metaObject();

    // properties
    for (int i = mo->propertyOffset(); i < mo->propertyCount(); ++i) {
        QMetaProperty mp = mo->property(i);
        printf("property ");

        if (mp.isReadable() && mp.isWritable())
            printf("readwrite");
        else if (mp.isReadable())
            printf("read");
        else
            printf("write");

        printf(" %s %s.%s\n", mp.typeName(), qPrintable(interface), mp.name());
    }

    // methods (signals and slots)
    for (int i = mo->methodOffset(); i < mo->methodCount(); ++i) {
        QMetaMethod mm = mo->method(i);

        QByteArray signature = mm.signature();
        signature.truncate(signature.indexOf('('));
        printf("%s %s%s%s %s.%s(",
               mm.methodType() == QMetaMethod::Signal ? "signal" : "method",
               mm.tag(), *mm.tag() ? " " : "",
               *mm.typeName() ? mm.typeName() : "void",
               qPrintable(interface), signature.constData());

        QList<QByteArray> types = mm.parameterTypes();
        QList<QByteArray> names = mm.parameterNames();
        bool first = true;
        for (int i = 0; i < types.count(); ++i) {
            printf("%s%s",
                   first ? "" : ", ",
                   types.at(i).constData());
            if (!names.at(i).isEmpty())
                printf(" %s", names.at(i).constData());
            first = false;
        }
        printf(")\n");
    }
}
void QDeclarativeValueTypeScriptClass::setProperty(Object *obj, const Identifier &,
                                                   const QScriptValue &value)
{
    QDeclarativeValueTypeObject *o = static_cast<QDeclarativeValueTypeObject *>(obj);

    QVariant v = QDeclarativeEnginePrivate::get(engine)->scriptValueToVariant(value);

    if (o->objectType == QDeclarativeValueTypeObject::Reference) {
        QDeclarativeValueTypeReference *ref = static_cast<QDeclarativeValueTypeReference *>(obj);

        ref->type->read(ref->object, ref->property);
        QMetaProperty p = ref->type->metaObject()->property(m_lastIndex);

        QDeclarativeBinding *newBinding = 0;
        if (value.isFunction() && !value.isRegExp()) {
            QDeclarativeContextData *ctxt = QDeclarativeEnginePrivate::get(engine)->getContext(context());

            QDeclarativePropertyCache::Data cacheData;
            cacheData.flags = QDeclarativePropertyCache::Data::IsWritable;
            cacheData.propType = ref->object->metaObject()->property(ref->property).userType();
            cacheData.coreIndex = ref->property;

            QDeclarativePropertyCache::ValueTypeData valueTypeData;
            valueTypeData.valueTypeCoreIdx = m_lastIndex;
            valueTypeData.valueTypePropType = p.userType();

            newBinding = new QDeclarativeBinding(value, ref->object, ctxt);
            QScriptContextInfo ctxtInfo(context());
            newBinding->setSourceLocation(ctxtInfo.fileName(), ctxtInfo.functionStartLineNumber());
            QDeclarativeProperty prop = QDeclarativePropertyPrivate::restore(cacheData, valueTypeData, ref->object, ctxt);
            newBinding->setTarget(prop);
            if (newBinding->expression().contains(QLatin1String("this")))
                newBinding->setEvaluateFlags(newBinding->evaluateFlags() | QDeclarativeBinding::RequiresThisObject);
        }

        QDeclarativeAbstractBinding *delBinding =
            QDeclarativePropertyPrivate::setBinding(ref->object, ref->property, m_lastIndex, newBinding);
        if (delBinding)
            delBinding->destroy();

        if (p.isEnumType() && (QMetaType::Type)v.type() == QMetaType::Double)
            v = v.toInt();
        p.write(ref->type, v);
        ref->type->write(ref->object, ref->property, 0);

    } else {
        QDeclarativeValueTypeCopy *copy = static_cast<QDeclarativeValueTypeCopy *>(obj);
        copy->type->setValue(copy->value);
        QMetaProperty p = copy->type->metaObject()->property(m_lastIndex);
        p.write(copy->type, v);
        copy->value = copy->type->value();
    }
}
Exemplo n.º 6
0
void ObjectControllerPrivate::slotValueChanged(QtProperty *property, const QVariant &value)
{
    if (!m_propertyToIndex.contains(property))
        return;

    int idx = m_propertyToIndex.value(property);

    const QMetaObject *metaObject = m_object->metaObject();
    QMetaProperty metaProperty = metaObject->property(idx);
    if (metaProperty.isEnumType()) {
        if (metaProperty.isFlagType())
            metaProperty.write(m_object, intToFlag(metaProperty.enumerator(), value.toInt()));
        else
            metaProperty.write(m_object, intToEnum(metaProperty.enumerator(), value.toInt()));
    } else {
        metaProperty.write(m_object, value);
    }

    updateClassProperties(metaObject, true);
}
Exemplo n.º 7
0
bool QDBusAbstractInterfacePrivate::setProperty(const QMetaProperty &mp, const QVariant &value)
{
    if (!isValid || !canMakeCalls())    // can't make calls
        return false;

    // send the value
    QDBusMessage msg = QDBusMessage::createMethodCall(service, path,
                                                QLatin1String(DBUS_INTERFACE_PROPERTIES),
                                                QLatin1String("Set"));
    QDBusMessagePrivate::setParametersValidated(msg, true);
    msg << interface << QString::fromUtf8(mp.name()) << qVariantFromValue(QDBusVariant(value));
    QDBusMessage reply = connection.call(msg, QDBus::Block);

    if (reply.type() != QDBusMessage::ReplyMessage) {
        lastError = reply;
        return false;
    }
    return true;
}
ObjectMapperForwarder::ObjectMapperForwarder(ObjectMapper *m, QObject *o) :
    QObject(m),
    m_mapper(m),
    m_source(o)
{
    for (int i = 0; i < o->metaObject()->propertyCount(); ++i) {
            
        QMetaProperty property = o->metaObject()->property(i);
            
        if (!property.isStored() ||
            !property.isReadable() ||
            !property.isWritable()) {
            continue;
        }
            
        if (!property.hasNotifySignal()) {
            DEBUG << "ObjectMapperForwarder: No notify signal for property " << property.name() << endl;
            continue;
        }
        
        // Signals can be connected to slots with fewer arguments, so
        // long as the arguments they do have match.  So we connect
        // the property notify signal to our universal
        // property-changed slot, and use the sender() of that to
        // discover which object's property has changed.
        // Unfortunately, we don't then know which property it was
        // that changed, as the identity of the signal that activated
        // the slot is not available to us.  The annoying part of this
        // is that Qt does actually store the identity of the signal
        // in the same structure as used for the sender() object data;
        // it just doesn't (at least as of Qt 4.5) make it available
        // through the public API.

        QString sig = QString("%1%2").arg(QSIGNAL_CODE)
            .arg(property.notifySignal().methodSignature().data());
        QByteArray ba = sig.toLocal8Bit();
        
        if (!connect(o, ba.data(), this, SLOT(objectModified()))) {
            std::cerr << "ObjectMapperForwarder: Failed to connect notify signal" << std::endl;
        }
    }
    
    connect(o, SIGNAL(destroyed(QObject *)), this, SLOT(objectDestroyed()));
}
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);
}
Exemplo n.º 10
0
void tst_QMetaProperty::gadget()
{
    const QMetaObject *mo = &MyGadget::staticMetaObject;
    QMetaProperty valueProp = mo->property(mo->indexOfProperty("value"));
    QVERIFY(valueProp.isValid());
    {
        MyGadget g;
        QString hello = QLatin1Literal("hello");
        QVERIFY(valueProp.writeOnGadget(&g, hello));
        QCOMPARE(g.m_value, QLatin1String("hello"));
        QCOMPARE(valueProp.readOnGadget(&g), QVariant(hello));
        QVERIFY(valueProp.resetOnGadget(&g));
        QCOMPARE(valueProp.readOnGadget(&g), QVariant(QLatin1String("reset")));
    }
}
Exemplo n.º 11
0
void ObjectEndPoint::propertyCall(const QServicePackage& p)
{
    if(p.d->responseType == QServicePackage::NotAResponse) {
        //service side
        Q_ASSERT(d->endPointType == ObjectEndPoint::Service);

        QByteArray data = p.d->payload.toByteArray();
        QDataStream stream(&data, QIODevice::ReadOnly);
        int metaIndex = -1;
        QVariant arg;
        int callType;
        stream >> metaIndex;
        stream >> arg;
        stream >> callType;
        const QMetaObject::Call c = (QMetaObject::Call) callType;

        QVariant result;
        QMetaProperty property = service->metaObject()->property(metaIndex);
        if (property.isValid()) {
            switch(c) {
                case QMetaObject::ReadProperty:
                    result = property.read(service);
                    break;
                case QMetaObject::WriteProperty:
                    property.write(service, arg);
                    break;
                case QMetaObject::ResetProperty:
                    property.reset(service);
                    break;
                default:
                    break;

            }
        } 

        if (c == QMetaObject::ReadProperty) {
            QServicePackage response = p.createResponse();
            if (property.isValid()) {
                response.d->responseType = QServicePackage::Success;
                response.d->payload = result;
            } else {
                response.d->responseType = QServicePackage::Failed;
            }
            dispatch->writePackage(response);
        }
    } else {
Exemplo n.º 12
0
const char *SettingsWidget::lookForWidgetState(QWidget *widget, const char *property, const char *signal)
{
	const QMetaObject *meta = widget->metaObject();
	WidgetInfo info = { widget, NULL, QVariant(), false };
	bool free_signal = false;
	// Firstly try to search this widget in predefined classes
	if (!signal && !property) {
		for (int i = 0, size = sizeof(widget_infos) / sizeof(AbstractWidgetInfo*); i < size; i++) {
			if (widget_infos[i]->handle(widget)) {
				info.property = widget_infos[i]->property;
				signal = widget_infos[i]->signal;
				break;
			}
		}
	}
	// Then try to find "User" property with signal or signal by property
	if (!signal) {
		for (int i = 0, size = meta->propertyCount(); i < size; i++) {
			QMetaProperty prop = meta->property(i);
			if (prop.hasNotifySignal()
				&& ((property && !qstrcmp(prop.name(), property))
					|| (!property && prop.isUser()))) {
				info.property = prop.name();
				const char *sig = prop.notifySignal().signature();
				int len = strlen(sig);
				char *str = (char *)qMalloc(sizeof(char) * (len + 2));
				str[0] = QSIGNAL_CODE;
				qstrcpy(str + 1, sig);
				signal = str;
				free_signal = true;
				break;
			}
		}
	}
	bool result(signal);
	if (result) {
		p->mapper->setMapping(widget, p->infos.size());
		connect(widget, signal, p->mapper, SLOT(map()));
		p->infos << info;
	}
	if (free_signal)
		qFree((void *)signal);
	return result ? info.property : 0;
}
Exemplo n.º 13
0
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);
}
Exemplo n.º 14
0
void PropertyEditor::getProperties(QObject *obj)
{
    mMetaProperties.clear();
    mProperties.clear();
    mPropertyDetails.clear();
    if (!obj)
        return;
    const QMetaObject *mo = obj->metaObject();
    for (int i = 0; i < mo->propertyCount(); ++i) {
        QMetaProperty mp = mo->property(mo->propertyOffset()+i);
        mMetaProperties.append(mp);
        QVariant v(mp.read(obj));
        if (mp.isEnumType()) {
            mProperties.insert(QString::fromLatin1(mp.name()), v.toInt());//mp.enumerator().valueToKey(v.toInt())); //always use string
        } else {
            mProperties.insert(QString::fromLatin1(mp.name()), v);
        }
        const QVariant detail = obj->property(QByteArray("detail_").append(mp.name()).constData());
        if (!detail.isNull())
            mPropertyDetails.insert(QString::fromLatin1(mp.name()), detail.toString());
    }
    mProperties.remove(QString::fromLatin1("objectName"));
}
Exemplo n.º 15
0
bool parseObject(const QVariant &source, QObject *target)
{
    if (!source.isValid() || !source.canConvert(QVariant::Map)) {
        qDebug() << "[ObjectParser] Error: Invalid object... " << source.toByteArray();
        return false;
    }
    const QVariantMap &map = source.toMap();
    const QMetaObject *metaobject = target->metaObject();

    QVariantMap::const_iterator it;
    QVariantMap::const_iterator end = map.constEnd();
    for (it = map.constBegin(); it != end; ++it) {
        const int index = metaobject->indexOfProperty(it.key().toLatin1());
        if (index < 0) {
            continue;
        }

        const QMetaProperty metaproperty = metaobject->property(index);
        const QVariant::Type type = metaproperty.type();
        QVariant v = it.value();

        if (v.canConvert(type)) {
            v.convert(type);
            metaproperty.write(target, v);
        } else if (QString(QLatin1String("QVariant"))
                       .compare(QLatin1String(metaproperty.typeName())) == 0) {
            metaproperty.write(target, v);
        } else {
            qDebug() << "[ObjectParser] Warning: unable to map variable" << it.key() << "of type"
                     << v.type() << "to type" << metaproperty.type() << "!";
            metaproperty.write(target, QVariant());
        }
    }

    return true;
}
Exemplo n.º 16
0
void tst_QMetaProperty::conversion()
{
    if (qVersion() < QByteArray("5.6.0"))
        QSKIP("this is a test for a bug in 5.5");


    QMetaType::registerConverter<QString, CustomType>();
    QMetaType::registerConverter<CustomType, QString>();

    QString hello = QStringLiteral("Hello");

    // Write to a QString property using a CustomType in a QVariant
    QMetaProperty value7P = metaObject()->property(metaObject()->indexOfProperty("value7"));
    QVERIFY(value7P.isValid());
    QVERIFY(value7P.write(this, QVariant::fromValue(CustomType(hello))));
    QCOMPARE(value7, hello);

    // Write to a CustomType property using a QString in a QVariant
    QMetaProperty customP = metaObject()->property(metaObject()->indexOfProperty("custom"));
    QVERIFY(customP.isValid());
    QVERIFY(customP.write(this, hello));
    QCOMPARE(custom.str, hello);

    // Something that cannot be converted should fail
    QVERIFY(!customP.write(this, 45));
    QVERIFY(!customP.write(this, QVariant::fromValue(this)));
    QVERIFY(!value7P.write(this, QVariant::fromValue(this)));
    QVERIFY(!value7P.write(this, QVariant::fromValue<QObject*>(this)));

    // none of this should have changed the values
    QCOMPARE(value7, hello);
    QCOMPARE(custom.str, hello);

    // Empty variant should be converted to default object
    QVERIFY(customP.write(this, QVariant()));
    QCOMPARE(custom.str, QString());
    // or reset resetable
    QVERIFY(value7P.write(this, QVariant()));
    QCOMPARE(value7, QLatin1Literal("reset"));
}
Exemplo n.º 17
0
	void JsonToProperties::parse(const QString& json, QObject* object)
		throw(ParseException)
	{
		QVariantMap dataMap = JsonToVariant::parse(json).toMap();

		const QMetaObject* meta = object->metaObject();
		for(
			int i = 0;
			i < meta->propertyCount();
			++i
		)
		{
			QMetaProperty property = meta->property(i);
			if(dataMap.contains(property.name()))
			{
				QVariant data = dataMap[property.name()];
				if(data.canConvert(property.type()))
					property.write(object, data);
				else
					qDebug() << QObject::tr("Found property %1 with incompatible data type.").arg(property.name());
			}
		}
	}
Exemplo n.º 18
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;
}
Exemplo n.º 19
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();
}
Exemplo n.º 20
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();
    }
}
Exemplo n.º 21
0
void AcceleratorManagerPrivate::manageWidget(QWidget *w, Item *item)
{
  // first treat the special cases

  QTabBar *tabBar = qobject_cast<QTabBar*>(w);
  if (tabBar)
  {
      manageTabBar(tabBar, item);
      return;
  }

  QStackedWidget *wds = qobject_cast<QStackedWidget*>( w );
  if ( wds )
  {
      QWidgetStackAccelManager::manage( wds );
      // return;
  }

  QDockWidget *dock = qobject_cast<QDockWidget*>( w );
  if ( dock )
  {
      //QWidgetStackAccelManager::manage( wds );
      manageDockWidget(dock, item);
  }


  QMenu *popupMenu = qobject_cast<QMenu*>(w);
  if (popupMenu)
  {
      // create a popup accel manager that can deal with dynamic menus
      PopupAccelManager::manage(popupMenu);
      return;
  }

  QStackedWidget *wdst = qobject_cast<QStackedWidget*>( w );
  if ( wdst )
  {
      QWidgetStackAccelManager::manage( wdst );
      // return;
  }

  QMenuBar *menuBar = qobject_cast<QMenuBar*>(w);
  if (menuBar)
  {
      manageMenuBar(menuBar, item);
      return;
  }

  if (qobject_cast<QComboBox*>(w) || qobject_cast<QLineEdit*>(w) ||
      w->inherits("Q3TextEdit") ||
      qobject_cast<QTextEdit*>(w) ||
      qobject_cast<QAbstractSpinBox*>(w) || w->inherits( "KMultiTabBar" ) )
      return;

  if ( w->inherits("KUrlRequester") ) {
    traverseChildren(w, item);
    return;
  }

  if ( qobject_cast<PathRequester*>(w) ) {
    traverseChildren(w, item);
    return;
  }

  // now treat 'ordinary' widgets
  QLabel *label =  qobject_cast<QLabel*>(w);
  if ( label  ) {
      if ( !label->buddy() )
          return;
      else {
          if ( label->textFormat() == Qt::RichText ||
               ( label->textFormat() == Qt::AutoText &&
                 Qt::mightBeRichText( label->text() ) ) )
              return;
      }
  }

  if (w->focusPolicy() != Qt::NoFocus || label || qobject_cast<QGroupBox*>(w) || qobject_cast<QRadioButton*>( w ))
  {
    QString content;
    QVariant variant;
    int tprop = w->metaObject()->indexOfProperty("text");
    if (tprop != -1)  {
        QMetaProperty p = w->metaObject()->property( tprop );
        if ( p.isValid() && p.isWritable() )
            variant = p.read (w);
        else
            tprop = -1;
    }

    if (tprop == -1)  {
        tprop = w->metaObject()->indexOfProperty("title");
        if (tprop != -1)  {
            QMetaProperty p = w->metaObject()->property( tprop );
            if ( p.isValid() && p.isWritable() )
                variant = p.read (w);
        }
    }

    if (variant.isValid())
        content = variant.toString();

    if (!content.isEmpty())
    {
        Item *i = new Item;
        i->m_widget = w;

        // put some more weight on the usual action elements
        int weight = AccelManagerAlgorithm::DEFAULT_WEIGHT;
        if (qobject_cast<QPushButton*>(w) || qobject_cast<QCheckBox*>(w) || qobject_cast<QRadioButton*>(w) || qobject_cast<QLabel*>(w))
            weight = AccelManagerAlgorithm::ACTION_ELEMENT_WEIGHT;

        // don't put weight on non-checkable group boxes,
        // as usually the contents are more important
        QGroupBox *groupBox = qobject_cast<QGroupBox*>(w);
        if (groupBox)
        {
            if (groupBox->isCheckable())
                weight = AccelManagerAlgorithm::CHECKABLE_GROUP_BOX_WEIGHT;
            else
                weight = AccelManagerAlgorithm::GROUP_BOX_WEIGHT;
        }

        i->m_content = AccelString(content, weight);
        item->addChild(i);
    }
  }
  traverseChildren(w, item);
}
Exemplo n.º 22
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);
}
Exemplo n.º 23
0
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;
}
Exemplo n.º 24
0
void QDeclarativePropertyPrivate::initProperty(QObject *obj, const QString &name)
{
    if (!obj) return;

    QDeclarativeTypeNameCache *typeNameCache = context?context->imports:0;

    QStringList path = name.split(QLatin1Char('.'));
    if (path.isEmpty()) return;

    QObject *currentObject = obj;

    // Everything up to the last property must be an "object type" property
    for (int ii = 0; ii < path.count() - 1; ++ii) {
        const QString &pathName = path.at(ii);

        if (QDeclarativeTypeNameCache::Data *data = typeNameCache?typeNameCache->data(pathName):0) {
            if (data->type) {
                QDeclarativeAttachedPropertiesFunc func = data->type->attachedPropertiesFunction();
                if (!func) return; // Not an attachable type

                currentObject = qmlAttachedPropertiesObjectById(data->type->index(), currentObject);
                if (!currentObject) return; // Something is broken with the attachable type
            } else {
                Q_ASSERT(data->typeNamespace);
                if ((ii + 1) == path.count()) return; // No type following the namespace
                
                ++ii; data = data->typeNamespace->data(path.at(ii));
                if (!data || !data->type) return; // Invalid type in namespace 

                QDeclarativeAttachedPropertiesFunc func = data->type->attachedPropertiesFunction();
                if (!func) return; // Not an attachable type

                currentObject = qmlAttachedPropertiesObjectById(data->type->index(), currentObject);
                if (!currentObject) return; // Something is broken with the attachable type
            }
        } else {

            QDeclarativePropertyCache::Data local;
            QDeclarativePropertyCache::Data *property = 
                QDeclarativePropertyCache::property(engine, obj, pathName, local);

            if (!property) return; // Not a property
            if (property->flags & QDeclarativePropertyCache::Data::IsFunction) 
                return; // Not an object property 

            if (ii == (path.count() - 2) && QDeclarativeValueTypeFactory::isValueType(property->propType)) {
                // We're now at a value type property.  We can use a global valuetypes array as we 
                // never actually use the objects, just look up their properties.
                QObject *typeObject = (*qmlValueTypes())[property->propType];
                if (!typeObject) return; // Not a value type

                int idx = typeObject->metaObject()->indexOfProperty(path.last().toUtf8().constData());
                if (idx == -1) return; // Value type property does not exist

                QMetaProperty vtProp = typeObject->metaObject()->property(idx);

                object = currentObject;
                core = *property;
                valueType.flags = QDeclarativePropertyCache::Data::flagsForProperty(vtProp);
                valueType.valueTypeCoreIdx = idx;
                valueType.valueTypePropType = vtProp.userType();

                return; 
            } else {
                if (!(property->flags & QDeclarativePropertyCache::Data::IsQObjectDerived)) 
                    return; // Not an object property

                void *args[] = { &currentObject, 0 };
                QMetaObject::metacall(currentObject, QMetaObject::ReadProperty, property->coreIndex, args);
                if (!currentObject) return; // No value

            }
        }

    }

    const QString &terminal = path.last();

    if (terminal.count() >= 3 &&
        terminal.at(0) == QLatin1Char('o') &&
        terminal.at(1) == QLatin1Char('n') &&
        terminal.at(2).isUpper()) {

        QString signalName = terminal.mid(2);
        signalName[0] = signalName.at(0).toLower();

        QMetaMethod method = QDeclarativeCompiler::findSignalByName(currentObject->metaObject(), signalName.toLatin1().constData());
        if (method.signature()) {
            object = currentObject;
            core.load(method);
            return;
        }
    }

    // Property
    QDeclarativePropertyCache::Data local;
    QDeclarativePropertyCache::Data *property = 
        QDeclarativePropertyCache::property(engine, currentObject, terminal, local);
    if (property && !(property->flags & QDeclarativePropertyCache::Data::IsFunction)) {
        object = currentObject;
        core = *property;
    }
}
Exemplo n.º 25
0
int QDeclarativeVMEMetaObject::metaCall(QMetaObject::Call c, int _id, void **a)
{
    int id = _id;
    if(c == QMetaObject::WriteProperty) {
        int flags = *reinterpret_cast<int*>(a[3]);
        if (!(flags & QDeclarativePropertyPrivate::BypassInterceptor)
            && !aInterceptors.isEmpty()
            && aInterceptors.testBit(id)) {
            QPair<int, QDeclarativePropertyValueInterceptor*> pair = interceptors.value(id);
            int valueIndex = pair.first;
            QDeclarativePropertyValueInterceptor *vi = pair.second;
            int type = property(id).userType();

            if (type != QVariant::Invalid) {
                if (valueIndex != -1) {
                    QDeclarativeEnginePrivate *ep = ctxt?QDeclarativeEnginePrivate::get(ctxt->engine):0;
                    QDeclarativeValueType *valueType = 0;
                    if (ep) valueType = ep->valueTypes[type];
                    else valueType = QDeclarativeValueTypeFactory::valueType(type);
                    Q_ASSERT(valueType);

                    valueType->setValue(QVariant(type, a[0]));
                    QMetaProperty valueProp = valueType->metaObject()->property(valueIndex);
                    vi->write(valueProp.read(valueType));

                    if (!ep) delete valueType;
                    return -1;
                } else {
                    vi->write(QVariant(type, a[0]));
                    return -1;
                }
            }
        }
    }
    if(c == QMetaObject::ReadProperty || c == QMetaObject::WriteProperty) {
        if (id >= propOffset) {
            id -= propOffset;

            if (id < metaData->propertyCount) {
               int t = (metaData->propertyData() + id)->propertyType;
                bool needActivate = false;

                if (t == -1) {

                    if (c == QMetaObject::ReadProperty) {
                        *reinterpret_cast<QVariant *>(a[0]) = readVarPropertyAsVariant(id);
                    } else if (c == QMetaObject::WriteProperty) {
                        writeVarProperty(id, *reinterpret_cast<QVariant *>(a[0]));
                    }

                } else {

                    if (c == QMetaObject::ReadProperty) {
                        switch(t) {
                        case QVariant::Int:
                            *reinterpret_cast<int *>(a[0]) = data[id].asInt();
                            break;
                        case QVariant::Bool:
                            *reinterpret_cast<bool *>(a[0]) = data[id].asBool();
                            break;
                        case QVariant::Double:
                            *reinterpret_cast<double *>(a[0]) = data[id].asDouble();
                            break;
                        case QVariant::String:
                            *reinterpret_cast<QString *>(a[0]) = data[id].asQString();
                            break;
                        case QVariant::Url:
                            *reinterpret_cast<QUrl *>(a[0]) = data[id].asQUrl();
                            break;
                        case QVariant::Color:
                            *reinterpret_cast<QColor *>(a[0]) = data[id].asQColor();
                            break;
                        case QVariant::Date:
                            *reinterpret_cast<QDate *>(a[0]) = data[id].asQDate();
                            break;
                        case QVariant::DateTime:
                            *reinterpret_cast<QDateTime *>(a[0]) = data[id].asQDateTime();
                            break;
                        case QMetaType::QObjectStar:
                            *reinterpret_cast<QObject **>(a[0]) = data[id].asQObject();
                            break;
                        default:
                            break;
                        }
                        if (t == qMetaTypeId<QDeclarativeListProperty<QObject> >()) {
                            int listIndex = data[id].asInt();
                            const List *list = &listProperties.at(listIndex);
                            *reinterpret_cast<QDeclarativeListProperty<QObject> *>(a[0]) = 
                                QDeclarativeListProperty<QObject>(object, (void *)list,
                                                                  list_append, list_count, list_at, 
                                                                  list_clear);
                        }

                    } else if (c == QMetaObject::WriteProperty) {

                        switch(t) {
                        case QVariant::Int:
                            needActivate = *reinterpret_cast<int *>(a[0]) != data[id].asInt();
                            data[id].setValue(*reinterpret_cast<int *>(a[0]));
                            break;
                        case QVariant::Bool:
                            needActivate = *reinterpret_cast<bool *>(a[0]) != data[id].asBool();
                            data[id].setValue(*reinterpret_cast<bool *>(a[0]));
                            break;
                        case QVariant::Double:
                            needActivate = *reinterpret_cast<double *>(a[0]) != data[id].asDouble();
                            data[id].setValue(*reinterpret_cast<double *>(a[0]));
                            break;
                        case QVariant::String:
                            needActivate = *reinterpret_cast<QString *>(a[0]) != data[id].asQString();
                            data[id].setValue(*reinterpret_cast<QString *>(a[0]));
                            break;
                        case QVariant::Url:
                            needActivate = *reinterpret_cast<QUrl *>(a[0]) != data[id].asQUrl();
                            data[id].setValue(*reinterpret_cast<QUrl *>(a[0]));
                            break;
                        case QVariant::Color:
                            needActivate = *reinterpret_cast<QColor *>(a[0]) != data[id].asQColor();
                            data[id].setValue(*reinterpret_cast<QColor *>(a[0]));
                            break;
                        case QVariant::Date:
                            needActivate = *reinterpret_cast<QDate *>(a[0]) != data[id].asQDate();
                            data[id].setValue(*reinterpret_cast<QDate *>(a[0]));
                            break;
                        case QVariant::DateTime:
                            needActivate = *reinterpret_cast<QDateTime *>(a[0]) != data[id].asQDateTime();
                            data[id].setValue(*reinterpret_cast<QDateTime *>(a[0]));
                            break;
                        case QMetaType::QObjectStar:
                            needActivate = *reinterpret_cast<QObject **>(a[0]) != data[id].asQObject();
                            data[id].setValue(*reinterpret_cast<QObject **>(a[0]));
                            break;
                        default:
                            break;
                        }
                    }

                }

                if (c == QMetaObject::WriteProperty && needActivate) {
                    activate(object, methodOffset + id, 0);
                }

                return -1;
            }

            id -= metaData->propertyCount;

            if (id < metaData->aliasCount) {

                QDeclarativeVMEMetaData::AliasData *d = metaData->aliasData() + id;

                if (d->flags & QML_ALIAS_FLAG_PTR && c == QMetaObject::ReadProperty) 
                        *reinterpret_cast<void **>(a[0]) = 0;

                if (!ctxt) return -1;

                QDeclarativeContext *context = ctxt->asQDeclarativeContext();
                QDeclarativeContextPrivate *ctxtPriv = QDeclarativeContextPrivate::get(context);

                QObject *target = ctxtPriv->data->idValues[d->contextIdx].data();
                if (!target) 
                    return -1;

                connectAlias(id);

                if (d->isObjectAlias()) {
                    *reinterpret_cast<QObject **>(a[0]) = target;
                    return -1;
                } 
                
                // Remove binding (if any) on write
                if(c == QMetaObject::WriteProperty) {
                    int flags = *reinterpret_cast<int*>(a[3]);
                    if (flags & QDeclarativePropertyPrivate::RemoveBindingOnAliasWrite) {
                        QDeclarativeData *targetData = QDeclarativeData::get(target);
                        if (targetData && targetData->hasBindingBit(d->propertyIndex())) {
                            QDeclarativeAbstractBinding *binding = QDeclarativePropertyPrivate::setBinding(target, d->propertyIndex(), d->isValueTypeAlias()?d->valueTypeIndex():-1, 0);
                            if (binding) binding->destroy();
                        }
                    }
                }
                
                if (d->isValueTypeAlias()) {
                    // Value type property
                    QDeclarativeEnginePrivate *ep = QDeclarativeEnginePrivate::get(ctxt->engine);

                    QDeclarativeValueType *valueType = ep->valueTypes[d->valueType()];
                    Q_ASSERT(valueType);

                    valueType->read(target, d->propertyIndex());
                    int rv = QMetaObject::metacall(valueType, c, d->valueTypeIndex(), a);
                    
                    if (c == QMetaObject::WriteProperty)
                        valueType->write(target, d->propertyIndex(), 0x00);

                    return rv;

                } else {
                    return QMetaObject::metacall(target, c, d->propertyIndex(), a);
                }

            }
            return -1;

        }

    } else if(c == QMetaObject::InvokeMetaMethod) {

        if (id >= methodOffset) {

            id -= methodOffset;
            int plainSignals = metaData->signalCount + metaData->propertyCount +
                               metaData->aliasCount;
            if (id < plainSignals) {
                QMetaObject::activate(object, _id, a);
                return -1;
            }

            id -= plainSignals;

            if (id < metaData->methodCount) {
                if (!ctxt->engine)
                    return -1; // We can't run the method

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

                QScriptValue function = method(id);

                QScriptValueList args;
                QDeclarativeVMEMetaData::MethodData *data = metaData->methodData() + id;
                if (data->parameterCount) {
                    for (int ii = 0; ii < data->parameterCount; ++ii) {
                        args << ep->scriptValueFromVariant(*(QVariant *)a[ii + 1]);
                    }
                }
                QScriptValue rv = function.call(ep->objectClass->newQObject(object), args);

                if (a[0]) *reinterpret_cast<QVariant *>(a[0]) = ep->scriptValueToVariant(rv);

                return -1;
            }
            return -1;
        }
    }

    if (parent)
        return parent->metaCall(c, _id, a);
    else
        return object->qt_metacall(c, _id, a);
}
Exemplo n.º 26
0
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();
}
Exemplo n.º 27
0
	bool operator==(const PropertyPair& other) const {return QString(other.Property.name()) == QString(Property.name());}
Exemplo n.º 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;
        }
    }
}
Exemplo n.º 29
0
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));
}
Exemplo n.º 30
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();
        }
    }
}