Example #1
0
void ParameterEdit::editItem()
{
    if(_table->currentSelection() != -1) {
	bool do_update = false;
	int r = _table->currentRow();
	Q3CheckTableItem * ctItem = (Q3CheckTableItem*)_table->item(r, 0);
        if(ctItem == 0)
          return;
	bool active = ctItem->isChecked();
	QString name = _table->text(r, 1);
	QVariant var = _params[name];
	BoolEdit * be = 0;
	IntEdit * ie = 0;
	DoubleEdit * de = 0;
	StringEdit * se = 0;
	ListEdit * le = 0;
	switch(var.type()) {
	case QVariant::Bool:
	    be = new BoolEdit(this);
	    be->_name->setText(name);
	    be->_active->setChecked(active);
	    be->setValue(var.toBool());
	    if(be->exec() == QDialog::Accepted) {
		var = QVariant(be->value(), 0);
		active = be->_active->isChecked();
		do_update = TRUE;
	    }
	    delete be;
	    be = 0;
	    break;
	case QVariant::Int:
	    ie = new IntEdit(this);
	    ie->_name->setText(name);
	    ie->_active->setChecked(active);
	    ie->_value->setText(QString::number(var.toInt()));
	    if(ie->exec() == QDialog::Accepted) {
		var = QVariant(ie->_value->text().toInt());
		active = ie->_active->isChecked();
		do_update = TRUE;
	    }
	    delete ie;
	    ie = 0;
	    break;
	case QVariant::Double:
	    de = new DoubleEdit(this);
	    de->_name->setText(name);
	    de->_active->setChecked(active);
	    de->_value->setText(QString::number(var.toDouble()));
	    if(de->exec() == QDialog::Accepted) {
		var = QVariant(de->_value->text().toDouble());
		active = de->_active->isChecked();
		do_update = TRUE;
	    }
	    delete de;
	    de = 0;
	    break;
	case QVariant::String:
	    se = new StringEdit(this);
	    se->_name->setText(name);
	    se->_active->setChecked(active);
	    se->_value->setText(var.toString());
	    if(se->exec() == QDialog::Accepted) {
		var = QVariant(se->_value->text());
		active = se->_active->isChecked();
		do_update = TRUE;
	    }
	    delete se;
	    se = 0;
	    break;
	case QVariant::List:
	    le = new ListEdit(this);
	    le->_name->setText(name);
	    le->_active->setChecked(active);
	    le->setList(var.toList());
	    if(le->exec() == QDialog::Accepted) {
		var = QVariant(le->list());
		active = le->_active->isChecked();
		do_update = TRUE;
	    }
	    delete le;
	    le = 0;
	    break;
	default:
	    QMessageBox::warning(this, tr("Warning"), QString(tr("I do not know how to edit QVariant type %1.")).arg(var.typeName()));
	};
		
	if(do_update) {
	    _params[name] = var;
	    ctItem->setChecked(active);
	    _table->setText(r, 1, name);
	    _table->setText(r, 2, var.typeName());
	    _table->setText(r, 3, var.toString());
	}
    }
}
Example #2
0
    void evaluation()
    {
      QFETCH( QString, string );
      QFETCH( bool, evalError );
      QFETCH( QVariant, result );

      QgsExpression exp( string );
      QCOMPARE( exp.hasParserError(), false );
      if ( exp.hasParserError() )
        qDebug() << exp.parserErrorString();

      QVariant res = exp.evaluate();
      if ( exp.hasEvalError() )
        qDebug() << exp.evalErrorString();
      if ( res.type() != result.type() )
      {
        qDebug() << "got " << res.typeName() << " instead of " << result.typeName();
      }
      //qDebug() << res.type() << " " << result.type();
      //qDebug() << "type " << res.typeName();
      QCOMPARE( exp.hasEvalError(), evalError );

      QCOMPARE( res.type(), result.type() );
      switch ( res.type() )
      {
        case QVariant::Invalid:
          break; // nothing more to check
        case QVariant::Int:
          QCOMPARE( res.toInt(), result.toInt() );
          break;
        case QVariant::Double:
          QCOMPARE( res.toDouble(), result.toDouble() );
          break;
        case QVariant::String:
          QCOMPARE( res.toString(), result.toString() );
          break;
        case QVariant::Date:
          QCOMPARE( res.toDate(), result.toDate() );
          break;
        case QVariant::DateTime:
          QCOMPARE( res.toDateTime(), result.toDateTime() );
          break;
        case QVariant::Time:
          QCOMPARE( res.toTime(), result.toTime() );
          break;
        case QVariant::UserType:
        {
          if ( res.userType() == qMetaTypeId<QgsExpression::Interval>() )
          {
            QgsExpression::Interval inter = res.value<QgsExpression::Interval>();
            QgsExpression::Interval gotinter = result.value<QgsExpression::Interval>();
            QCOMPARE( inter.seconds(), gotinter.seconds() );
          }
          else
          {
            QFAIL( "unexpected user type" );
          }
          break;
        }
        default:
          Q_ASSERT( false ); // should never happen
      }
    }
Example #3
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 (int(mp.type()) != QMetaType::QVariant) {
        expectedSignature = QDBusMetaType::typeToSignature(where.userType());
        if (expectedSignature == 0) {
            qWarning("QDBusAbstractInterface: type %s must be registered with Qt D-Bus 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, timeout);

    if (reply.type() != QDBusMessage::ReplyMessage) {
        lastError = QDBusError(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.userType() == QMetaType::QVariant
            || (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;
}
Example #4
0
VALUE RubyType<QVariant>::toVALUE(const QVariant& v)
{
    #ifdef QROSS_RUBY_VARIANT_DEBUG
        qrossdebug( QString("RubyType<QVariant>::toVALUE variant.toString=%1 variant.typeid=%2 variant.typeName=%3").arg(v.toString()).arg(v.type()).arg(v.typeName()) );
    #endif

    switch( v.type() ) {
        case QVariant::Int:
            return RubyType<int>::toVALUE(v.toInt());
        case QVariant::UInt:
            return RubyType<uint>::toVALUE(v.toUInt());
        case QVariant::Double:
            return RubyType<double>::toVALUE(v.toDouble());
        case QVariant::ByteArray:
            return RubyType<QByteArray>::toVALUE(v.toByteArray());
        case QVariant::String:
            return RubyType<QString>::toVALUE(v.toString());
        case QVariant::Bool:
            return RubyType<bool>::toVALUE(v.toBool());
        case QVariant::StringList:
            return RubyType<QStringList>::toVALUE(v.toStringList());
        case QVariant::Map:
            return RubyType<QVariantMap>::toVALUE(v.toMap());
        case QVariant::List:
            return RubyType<QVariantList>::toVALUE(v.toList());
        case QVariant::LongLong:
            return RubyType<qlonglong>::toVALUE(v.toLongLong());
        case QVariant::ULongLong:
            return RubyType<qlonglong>::toVALUE(v.toULongLong());

        case QVariant::Size:
            return RubyType<QSize>::toVALUE(v.toSize());
        case QVariant::SizeF:
            return RubyType<QSizeF>::toVALUE(v.toSizeF());
        case QVariant::Point:
            return RubyType<QPoint>::toVALUE(v.toPoint());
        case QVariant::PointF:
            return RubyType<QPointF>::toVALUE(v.toPointF());
        case QVariant::Rect:
            return RubyType<QRect>::toVALUE(v.toRect());
        case QVariant::RectF:
            return RubyType<QRectF>::toVALUE(v.toRectF());

        case QVariant::Color:
            return RubyType<QColor>::toVALUE( v.value<QColor>() );
        case QVariant::Url:
            return RubyType<QUrl>::toVALUE(v.toUrl());

        case QVariant::Date:
            return RubyType<QDate>::toVALUE( v.value<QDate>() );
        case QVariant::Time:
            return RubyType<QTime>::toVALUE( v.value<QTime>() );
        case QVariant::DateTime:
            return RubyType<QDateTime>::toVALUE( v.value<QDateTime>() );

        case QVariant::Invalid: {
            #ifdef QROSS_RUBY_VARIANT_DEBUG
                qrossdebug( QString("RubyType<QVariant>::toVALUE variant=%1 is QVariant::Invalid. Returning Qnil.").arg(v.toString()) );
            #endif
            return Qnil;
        } // fall through

        case QVariant::UserType: {
            #ifdef QROSS_RUBY_VARIANT_DEBUG
                qrossdebug( QString("RubyType<QVariant>::toVALUE variant=%1 is QVariant::UserType. Trying to cast now.").arg(v.toString()) );
            #endif
        } // fall through

        default: {
            if( strcmp(v.typeName(),"float") == 0 ) {
                #ifdef QROSS_RUBY_VARIANT_DEBUG
                    qrossdebug( QString("RubyType<QVariant>::toVALUE Casting '%1' to double").arg(v.typeName()) );
                #endif
                return RubyType<double>::toVALUE(v.toDouble());
            }

            if( strcmp(v.typeName(),"Qross::VoidList") == 0 ) {
                VoidList list = v.value<VoidList>();
                Qross::MetaTypeHandler* handler = Qross::Manager::self().metaTypeHandler(list.typeName);
                #ifdef QROSS_RUBY_VARIANT_DEBUG
                    qrossdebug( QString("RubyType<QVariant>::toVALUE Casting '%1' to QList<%2> with %3 items, hasHandler=%4").arg(v.typeName()).arg(list.typeName.constData()).arg(list.count()).arg(handler ? "true" : "false") );
                #endif
                QVariantList l;
                foreach(void* ptr, list) {
                    if( handler ) {
                        l << handler->callHandler(ptr);
                    }
                    else {
                        QVariant v;
                        v.setValue(ptr);
                        l << v;
                    }
                }
                return RubyType<QVariantList>::toVALUE(l);
            }

            if( qVariantCanConvert< Qross::Object::Ptr >(v) ) {
                #ifdef QROSS_RUBY_VARIANT_DEBUG
                    qrossdebug( QString("RubyType<QVariant>::toPyObject Casting '%1' to Qross::Object::Ptr").arg(v.typeName()) );
                #endif
                Qross::Object::Ptr obj = v.value< Qross::Object::Ptr >();
                Qross::RubyObject* rbobj = dynamic_cast< Qross::RubyObject* >(obj.data());
                if(! obj) {
                    #ifdef QROSS_RUBY_VARIANT_DEBUG
                        qrossdebug( QString("RubyType<QVariant>::toPyObject To Qross::RubyObject* casted '%1' is NULL").arg(v.typeName()) );
                    #endif
                    return Qnil;
                }
                return rbobj->rbObject();
            }

            if( qVariantCanConvert< QWidget* >(v) ) {
                #ifdef QROSS_RUBY_VARIANT_DEBUG
                    qrossdebug( QString("RubyType<QVariant>::toVALUE Casting '%1' to QWidget").arg(v.typeName()) );
                #endif
                QWidget* widget = qvariant_cast< QWidget* >(v);
                if(! widget) {
                    #ifdef QROSS_RUBY_VARIANT_DEBUG
                        qrosswarning( QString("RubyType<QVariant>::toVALUE To QWidget casted '%1' is NULL").arg(v.typeName()) );
                    #endif
                    return Qnil;
                }
                return RubyExtension::toVALUE( new RubyExtension(widget), true /*owner*/ );
            }

            if( qVariantCanConvert< QObject* >(v) ) {
                #ifdef QROSS_RUBY_VARIANT_DEBUG
                    qrossdebug( QString("RubyType<QVariant>::toVALUE Casting '%1' to QObject*").arg(v.typeName()) );
                #endif
                QObject* obj = qvariant_cast< QObject* >(v);
                if(! obj) {
                    #ifdef QROSS_RUBY_VARIANT_DEBUG
                        qrosswarning( QString("RubyType<QVariant>::toVALUE To QObject casted '%1' is NULL").arg(v.typeName()) );
                    #endif
                    return Qnil;
                }
                return RubyExtension::toVALUE( new RubyExtension(obj), true /*owner*/ );
            }
            
            if( qVariantCanConvert< void* >(v) ) {
              return Data_Wrap_Struct( rb_cObject, 0, 0, qvariant_cast<void*>(v));
            }

            //QObject* obj = (*reinterpret_cast< QObject*(*)>( variantargs[0]->toVoidStar() ));
            //PyObject* qobjectptr = PyLong_FromVoidPtr( (void*) variantargs[0]->toVoidStar() );

            #ifdef QROSS_RUBY_VARIANT_DEBUG
                qrosswarning( QString("RubyType<QVariant>::toVALUE Not possible to convert the QVariant '%1' with type '%2' (%3) to a VALUE.").arg(v.toString()).arg(v.typeName()).arg(v.type()) );
            #endif
            //throw Py::TypeError( QString("Variant of type %1 can not be casted to a Ruby object.").arg(v.typeName()).toLatin1().constData() );
            return 0;
        }
    }
Example #5
0
bool DomConvenience::variantToElement(const QVariant& v, QDomElement& e)
{
  bool ok = true;

  clearAttributes(e);

  switch (v.type())
  {
  case QVariant::String:
    e.setTagName("string");
    e.setAttribute("value", v.toString().utf8());
    break;
  case QVariant::CString:
    e.setTagName("string");
    e.setAttribute("value", v.toCString());
    break;
  case QVariant::Int:
    e.setTagName("int");
    e.setAttribute("value", v.toInt());
    break;
  case QVariant::UInt:
    e.setTagName("uint");
    e.setAttribute("value", v.toUInt());
    break;
  case QVariant::Double:
    e.setTagName("double");
    e.setAttribute("value", v.toDouble());
    break;
  case QVariant::Bool:
    e.setTagName("bool");
    e.setAttribute("value", boolString(v.toBool()));
    break;
  case QVariant::Color:
    {
      e.setTagName("color");
      QColor color = v.toColor();
      e.setAttribute("red", color.red());
      e.setAttribute("green", color.green());
      e.setAttribute("blue", color.blue());
    }
    break;
  case QVariant::Pen:
    {
      e.setTagName("pen");
      QPen pen = v.toPen();
      e.setAttribute("red", pen.color().red());
      e.setAttribute("green", pen.color().green());
      e.setAttribute("blue", pen.color().blue());
      e.setAttribute("style", pen.style());
      e.setAttribute("cap", pen.capStyle());
      e.setAttribute("join", pen.joinStyle());
    }
    break;
  case QVariant::Brush:
    {
      e.setTagName("brush");
      QBrush brush = v.toBrush();
      e.setAttribute("red", brush.color().red());
      e.setAttribute("green", brush.color().green());
      e.setAttribute("blue", brush.color().blue());
      e.setAttribute("style", brush.style());
    }
    break;
  case QVariant::Point:
    {
      e.setTagName("point");
      QPoint point = v.toPoint();
      e.setAttribute("x", point.x());
      e.setAttribute("y", point.y());
    }
    break;
  case QVariant::Rect:
    {
      e.setTagName("rect");
      QRect rect = v.toRect();
      e.setAttribute("x", rect.x());
      e.setAttribute("y", rect.y());
      e.setAttribute("width", rect.width());
      e.setAttribute("height", rect.height());
    }
    break;
  case QVariant::Size:
    {
      e.setTagName("size");
      QSize qsize = v.toSize();
      e.setAttribute("width", qsize.width());
      e.setAttribute("height", qsize.height());
    }
    break;
  case QVariant::Font:
    {
      e.setTagName("font");
      QFont f(v.toFont());
      e.setAttribute("family", f.family());
      e.setAttribute("pointsize", f.pointSize());
      e.setAttribute("bold", boolString(f.bold()));
      e.setAttribute("italic", boolString(f.italic()));
      e.setAttribute("underline", boolString(f.underline()));
      e.setAttribute("strikeout", boolString(f.strikeOut()));
    }
    break;
  case QVariant::SizePolicy:
    {
      e.setTagName("sizepolicy");
      QSizePolicy sp(v.toSizePolicy());
      e.setAttribute("hsizetype", sp.horData());
      e.setAttribute("vsizetype", sp.verData());
#if (QT_VERSION >= 300)
      e.setAttribute("horstretch", sp.horStretch());
      e.setAttribute("verstretch", sp.verStretch());
#endif
    }
    break;
  case QVariant::Cursor:
    e.setTagName("cursor");
    e.setAttribute("shape", v.toCursor().shape());
    break;

  case QVariant::StringList:
    {
      e.setTagName("stringlist");
      uint j;
      
      QDomNode n;
      QDomNodeList stringNodeList = e.elementsByTagName("string");
      QDomElement stringElem;
      QStringList stringList = v.toStringList();
      QStringList::Iterator it = stringList.begin();

      for (j = 0; 
	   ((j < stringNodeList.length()) && (it != stringList.end()));
	   j++)
      {
	// get the current string element
	stringElem = stringNodeList.item(j).toElement();

	// set it to the current string
	variantToElement(QVariant(*it), stringElem);

	// iterate to the next string
	++it;
      }
      
      // more nodes in previous stringlist then current, remove excess nodes
      if (stringNodeList.count() > stringList.count())
      {
	while (j < stringNodeList.count())
	  e.removeChild(stringNodeList.item(j).toElement());
      }
      else if (j <stringList.count())
      {
	while (it != stringList.end())
	{
	  // create a new element
	  stringElem = m_doc.createElement("string");
	
	  // set it to the currentstring
	  variantToElement(QVariant(*it), stringElem);

	  // append it to the current element
	  e.appendChild(stringElem);

	  // iterate to the next string
	  ++it;
	}
      }
    }
    break;

#if QT_VERSION >= 300
  case QVariant::KeySequence:
    e.setTagName("key");
    e.setAttribute("sequence", (QString)v.toKeySequence());
    break;
#endif

  case QVariant::ByteArray: // this is only for [u]int64_t
    {
      e.setTagName("uint64");
      QByteArray ba = v.toByteArray();

      // make sure this only handles [u]int64_t's
      if (ba.size() != sizeof(uint64_t))
      {
	qWarning("Don't know how to persist variant of type: %s (%d) (size=%d)!",
		 v.typeName(), v.type(), ba.size());
	ok = false;
	break;
      }

      // convert the data back into a uint64_t
      uint64_t num = *(uint64_t*)ba.data();
      
      QChar buff[33];
      QChar* p = &buff[32];
      const char* digitSet = "0123456789abcdef";
      int len = 0;

      // construct the string
      do 
      {
        *--p = digitSet[((int)(num%16))];
        num = num >> 4; // divide by 16
        len++;
      } while ( num );

      // store it in a QString
      QString storage;
      storage.setUnicode(p, len);
      
      // set the value
      e.setAttribute("value", storage);
    }
    break;

#if 0
  case QVariant::List:
  case QVaraint::Map:
#endif
  default:
    qWarning("Don't know how to persist variant of type: %s (%d)!",
	     v.typeName(), v.type());
    ok = false;
    break;
  }

  return ok;
}
Example #6
0
QString QJson::encodeData(const QVariant &data, EncodeOptions options, QString *errorMessage,
	int indentation, QString currentLinePrefix)
{
	QString indentedLinePrefix = options.testFlag(Compact) ?
		QString::fromLatin1("") :
		(currentLinePrefix + QString::fromLatin1(" ").repeated(indentation));

	QString optionalNewLine = options.testFlag(Compact) ?
		QString::fromLatin1("") :
		(QString::fromLatin1("\n") + currentLinePrefix);

	QString optionalIndentedNewLine = options.testFlag(Compact) ?
		QString::fromLatin1("") :
		(QString::fromLatin1("\n") + indentedLinePrefix);

	QString encoded;

	switch (data.type())
	{
	case(QVariant::Bool) :
		encoded += QString::fromLatin1(data.toBool() ? "true" : "false");
		break;

	case(QVariant::Int) :
	case(QVariant::UInt) :
	case(QVariant::LongLong) :
	case(QVariant::ULongLong) :
							  Q_ASSERT(data.canConvert(QVariant::String));
		encoded = data.toString();
		break;

	case(QVariant::Double) :
		encoded = QString::number(data.toDouble(), 'g', 16);
		if (!encoded.contains(QString::fromLatin1(".")) && !encoded.contains(QString::fromLatin1("e")))
			encoded += ".0";
		break;

	case(QVariant::String) :
		encoded = encodeString(data.toString());
		break;

	case(QVariant::ByteArray) :
		encoded = encodeByteArray(data.toByteArray());
		break;

	case(QVariant::List) :
	{
		encoded = QString::fromLatin1("[") + optionalIndentedNewLine;
		QVariantList list = data.toList();
		for (int i = 0; i < list.count(); ++i)
		{
			if (i) encoded += QString::fromLatin1(",") + optionalIndentedNewLine;
			encoded += encodeData(list.at(i), options, errorMessage, indentation, indentedLinePrefix);
			if (errorMessage && !errorMessage->isNull())
				return QString();
		}
		encoded += optionalNewLine + QString::fromLatin1("]");
	}
						 break;

	case(QVariant::StringList) :
	{
		encoded = QString::fromLatin1("[") + optionalIndentedNewLine;
		QStringList list = data.toStringList();
		for (int i = 0; i < list.count(); ++i)
		{
			if (i) encoded += QString::fromLatin1(",") + optionalIndentedNewLine;
			encoded += encodeData(list.at(i), options, errorMessage, indentation, indentedLinePrefix);
			if (errorMessage && !errorMessage->isNull())
				return QString();
		}
		encoded += optionalNewLine + QString::fromLatin1("]");
	}
							   break;

	case(QVariant::Map) :
	{
		encoded = QString::fromLatin1("{") + optionalIndentedNewLine;
		QVariantMap map = data.toMap();
		QVariantMap::iterator i;
		bool first = true;
		for (i = map.begin(); i != map.end(); ++i)
		{
			if (!first)
				encoded += QString::fromLatin1(",") + optionalIndentedNewLine;
			first = false;
			encoded += encodeString(i.key());
			encoded += options.testFlag(Compact) ? QString::fromLatin1(":") : QString::fromLatin1(" : ");
			encoded += encodeData(i.value(), options, errorMessage, indentation, indentedLinePrefix);
			if (errorMessage && !errorMessage->isNull())
				return QString();
		}
		encoded += optionalNewLine + QString::fromLatin1("}");
	}
						break;

	case(QVariant::Hash) :
	{
		encoded = QString::fromLatin1("{") + optionalIndentedNewLine;
		QVariantHash hash = data.toHash();
		QVariantHash::iterator i;
		bool first = true;
		for (i = hash.begin(); i != hash.end(); ++i)
		{
			if (!first)
				encoded += QString::fromLatin1(",") + optionalIndentedNewLine;
			first = false;
			encoded += encodeString(i.key());
			encoded += options.testFlag(Compact) ? QString::fromLatin1(":") : QString::fromLatin1(" : ");
			encoded += encodeData(i.value(), options, errorMessage, indentation, indentedLinePrefix);
			if (errorMessage && !errorMessage->isNull())
				return QString();
		}
		encoded += optionalNewLine + QString::fromLatin1("}");
	}
						 break;

	case(QVariant::Invalid) :
		encoded = QString::fromLatin1("null");
		break;

	default:
		if (!options.testFlag(EncodeUnknownTypesAsNull))
		{
			if (errorMessage)
				*errorMessage = QString::fromLatin1("Can't encode this type of data to JSON: %1")
				.arg(data.typeName());
			return QString();
		}
		encoded = QString::fromLatin1("null");
		break;
	}

	return encoded;
}
//! [0]
QDataStream out(...);
QVariant v(123);                // The variant now contains an int
int x = v.toInt();              // x = 123
out << v;                       // Writes a type tag and an int to out
v = QVariant("hello");          // The variant now contains a QByteArray
v = QVariant(tr("hello"));      // The variant now contains a QString
int y = v.toInt();              // y = 0 since v cannot be converted to an int
QString s = v.toString();       // s = tr("hello")  (see QObject::tr())
out << v;                       // Writes a type tag and a QString to out
...
QDataStream in(...);            // (opening the previously written stream)
in >> v;                        // Reads an Int variant
int z = v.toInt();              // z = 123
qDebug("Type is %s",            // prints "Type is int"
        v.typeName());
v = v.toInt() + 100;            // The variant now hold the value 223
v = QVariant(QStringList());
//! [0]


//! [1]
QVariant x, y(QString()), z(QString(""));
x.convert(QVariant::Int);
// x.isNull() == true
// y.isNull() == true, z.isNull() == false
//! [1]


//! [2]
QVariant variant;
Example #8
0
void Settings::setting_changed(const QString& module_name, const QString& name, const QVariant& value)
{
	if (!map_.contains(module_name))
	{
		cgogn_log_debug("Settings::setting_changed") << "Trying to modify a setting of a non-existing module \"" << module_name.toStdString() << "\".";
	} else
	{
		if (!map_[module_name].contains(name))
		{
			cgogn_log_debug("Settings::setting_changed") << "Trying to modify a non-existing setting \"" << name.toStdString() << "\" of the module \"" << module_name.toStdString() << "\".";
		} else {
			QVariant& v = map_[module_name][name];
			if (v.type() != value.type())
			{
				cgogn_log_debug("Settings::setting_changed") << "Cannot replace a setting of type \"" << v.typeName() << "\" by another setting of type \"" << value.typeName() << "\".";
			} else {
				v = value;
			}
		}
	}
}
// convert the variant to the given type and return true if it worked.
// if the type is not known, guess it from the variant and set.
// return false if conversion failed.
static bool checkType(QVariant &var, QDBusType &type)
{
    if (!type.isValid()) {
        // guess it from the variant
        type = QDBusType::guessFromVariant(var);
        return type.isValid();
    }

    int id = var.userType(); 
    
    if (type.dbusType() == DBUS_TYPE_VARIANT) {
        // this is a non symmetrical operation:
        // nest a QVariant if we want variant and it isn't so
        if (id != QDBusTypeHelper<QVariant>::id()) {
            QVariant tmp = var;
            var = QDBusTypeHelper<QVariant>::toVariant(tmp);
        }
        return true;
    }

    switch (id) {
    case QVariant::Bool:
    case QMetaType::Short: 
    case QMetaType::UShort:
    case QMetaType::UChar:
    case QVariant::Int:
    case QVariant::UInt:
    case QVariant::LongLong:
    case QVariant::ULongLong:
    case QVariant::Double:
    case QVariant::String:
        if (type.isBasic())
            // QVariant can handle this on its own
            return true;

        // cannot handle this
        qWarning("Invalid conversion from %s to '%s'", var.typeName(),
                 type.dbusSignature().constData());
        var.clear();
        return false;

    case QVariant::ByteArray:
        // make sure it's an "ARRAY of BYTE"
        if (type.qvariantType() != QVariant::ByteArray) {
            qWarning("Invalid conversion from %s to '%s'", var.typeName(),
                     type.dbusSignature().constData());
            var.clear();
            return false;
        }
        return true;

    case QVariant::StringList:
        // make sure it's "ARRAY of STRING"
        if (type.qvariantType() != QVariant::StringList) {
            qWarning("Invalid conversion from %s to '%s'", var.typeName(),
                     type.dbusSignature().constData());
            var.clear();
            return false;
        }
        return true;

    case QVariant::List:
        // could be either struct or array
        if (type.dbusType() != DBUS_TYPE_ARRAY && type.dbusType() != DBUS_TYPE_STRUCT) {
            qWarning("Invalid conversion from %s to '%s'", var.typeName(),
                     type.dbusSignature().constData());
            var.clear();
            return false;
        }
        
        return true;

    case QVariant::Map:
        if (!type.isMap()) {
            qWarning("Invalid conversion from %s to '%s'", var.typeName(),
                     type.dbusSignature().constData());
            var.clear();
            return false;
        }

        return true;

    case QVariant::Invalid: {
        // create an empty variant
        void *null = 0;
        var = QVariant(type.qvariantType(), null);
        break;
    }

    default:
        if (id == QDBusTypeHelper<QVariant>::id()) {
            // if we got here, it means the match above for DBUS_TYPE_VARIANT didn't work
            qWarning("Invalid conversion from nested variant to '%s'",
                     type.dbusSignature().constData());
            return false;
        } else if (type.dbusType() == DBUS_TYPE_ARRAY) {
            int subType = type.arrayElement().dbusType();
            if ((id == QDBusTypeHelper<bool>::listId() && subType == DBUS_TYPE_BOOLEAN) ||
                (id == QDBusTypeHelper<short>::listId() && subType == DBUS_TYPE_INT16) ||
                (id == QDBusTypeHelper<ushort>::listId() && subType == DBUS_TYPE_UINT16) ||
                (id == QDBusTypeHelper<int>::listId() && subType == DBUS_TYPE_INT32) ||
                (id == QDBusTypeHelper<uint>::listId() && subType == DBUS_TYPE_UINT32) ||
                (id == QDBusTypeHelper<qlonglong>::listId() && subType == DBUS_TYPE_INT64) ||
                (id == QDBusTypeHelper<qulonglong>::listId() && subType == DBUS_TYPE_UINT64) ||
                (id == QDBusTypeHelper<double>::listId() && subType == DBUS_TYPE_DOUBLE))
                return true;
        }

        qWarning("Invalid conversion from %s to '%s'", var.typeName(),
                 type.dbusSignature().constData());
        return false;
    }

    qWarning("Found unknown QVariant type %d (%s) when converting to DBus", (int)var.type(),
             var.typeName());
    var.clear();
    return false;
}
Example #10
0
void ParameterEdit::editItem(int row)
{
    bool do_update = false;
    bool active = _table->item(row, 0)->checkState() == Qt::Checked;
    QString name = _table->item(row, 1)->text();
    QVariant var = _params[name];
    BoolEdit * be = 0;
    IntEdit * ie = 0;
    DoubleEdit * de = 0;
    StringEdit * se = 0;
    ListEdit * le = 0;
    switch(var.type()) {
      case QVariant::Bool:
        be = new BoolEdit(this);
        be->_name->setText(name);
        be->_active->setChecked(active);
        be->setValue(var.toBool());
        if(be->exec() == QDialog::Accepted) {
        var = QVariant((bool)be->value());
        active = be->_active->isChecked();
        do_update = TRUE;
        }
        delete be;
        be = 0;
        break;
      case QVariant::Int:
        ie = new IntEdit(this);
        ie->_name->setText(name);
        ie->_active->setChecked(active);
        ie->_value->setText(QString::number(var.toInt()));
        if(ie->exec() == QDialog::Accepted) {
        var = QVariant(ie->_value->text().toInt());
        active = ie->_active->isChecked();
        do_update = TRUE;
        }
        delete ie;
        ie = 0;
        break;
      case QVariant::Double:
        de = new DoubleEdit(this);
        de->_name->setText(name);
        de->_active->setChecked(active);
        de->_value->setText(QString::number(var.toDouble()));
        if(de->exec() == QDialog::Accepted) {
        var = QVariant(de->_value->text().toDouble());
        active = de->_active->isChecked();
        do_update = TRUE;
        }
        delete de;
        de = 0;
        break;
      case QVariant::String:
        se = new StringEdit(this);
        se->_name->setText(name);
        se->_active->setChecked(active);
        se->_value->setText(var.toString());
        if(se->exec() == QDialog::Accepted) {
        var = QVariant(se->_value->text());
        active = se->_active->isChecked();
        do_update = TRUE;
        }
        delete se;
        se = 0;
        break;
      case QVariant::List:
        le = new ListEdit(this);
        le->_name->setText(name);
        le->_active->setChecked(active);
        le->setList(var.toList());
        if(le->exec() == QDialog::Accepted) {
        var = QVariant(le->list());
        active = le->_active->isChecked();
        do_update = TRUE;
        }
        delete le;
        le = 0;
        break;
      default:
        QMessageBox::warning(this, tr("Warning"), QString(tr("I do not know how to edit QVariant type %1.")).arg(var.typeName()));
    };
        
    if(do_update) {
        _params[name] = var;
        _table->item(row, 0)->setCheckState((active ? Qt::Checked : Qt::Unchecked));
        _table->item(row, 1)->setText(name);
        _table->item(row, 2)->setText(var.typeName());
        _table->item(row, 3)->setText(var.toString());
    }
}
Example #11
0
void ListEdit::editItem()
{
    Q3ListBoxItem * item = _list->selectedItem();
    if(item) {
	if(item->rtti() == QListBoxVariant::RTTI) {
	    QListBoxVariant * lbvar = (QListBoxVariant*)item;
	    QVariant var = lbvar->variant();
	    BoolEdit * be = 0;
	    IntEdit * ie = 0;
	    DoubleEdit * de = 0;
	    StringEdit * se = 0;
	    ListEdit * le = 0;
	    switch(var.type()) {
	    case QVariant::Bool:
		be = new BoolEdit(this);
		be->_lblName->hide();
		be->_name->hide();
		be->_active->hide();
		be->setValue(var.toBool());
		if(be->exec() == QDialog::Accepted) {
		    lbvar->setVariant(QVariant(be->value(), 0));
		}
		delete be;
		be = 0;
		break;
	    case QVariant::Int:
		ie = new IntEdit(this);
		ie->_lblName->hide();
		ie->_name->hide();
		ie->_active->hide();
		ie->_value->setText(QString::number(var.toInt()));
		if(ie->exec() == QDialog::Accepted) {
		    lbvar->setVariant(QVariant(ie->_value->text().toInt()));
		}
		delete ie;
		ie = 0;
		break;
	    case QVariant::Double:
		de = new DoubleEdit(this);
		de->_lblName->hide();
		de->_name->hide();
		de->_active->hide();
		de->_value->setText(QString::number(var.toDouble()));
		if(de->exec() == QDialog::Accepted) {
		    lbvar->setVariant(QVariant(de->_value->text().toDouble()));
		}
		delete de;
		de = 0;
		break;
	    case QVariant::String:
		se = new StringEdit(this);
		se->_lblName->hide();
		se->_name->hide();
		se->_active->hide();
		se->_value->setText(var.toString());
		if(se->exec() == QDialog::Accepted) {
		    lbvar->setVariant(QVariant(se->_value->text()));
		}
		delete se;
		se = 0;
		break;
	    case QVariant::List:
		le = new ListEdit(this);
		le->_lblName->hide();
		le->_name->hide();
		le->_active->hide();
		le->setList(var.toList());
		if(le->exec() == QDialog::Accepted) {
		    lbvar->setVariant(QVariant(le->list()));
		}
		delete le;
		le = 0;
		break;
	    default:
		QMessageBox::warning(this, tr("Warning"), QString(tr("I do not know how to edit QVariant type %1.")).arg(var.typeName()));
	    };
	} else {
	    QMessageBox::warning(this, tr("Warning"), tr("The item you selected is not a QListBoxVariant item. I do not know what to do."));
	}   
    }
}
Example #12
0
void ParameterEdit::newItem()
{
    NewVariant newVar(this);
    if(newVar.exec() == QDialog::Accepted) {
	QString varType = newVar._type->currentText();
	QString name = newVar._name->text();
	bool active = false;
	if(_params.contains(name)) {
	    QMessageBox::warning(this, tr("Name already exists"), tr("The name for the parameter you specified already exists in the list."));
	}
	BoolEdit * be = 0;
	IntEdit * ie = 0;
	DoubleEdit * de = 0;
	StringEdit * se = 0;
	ListEdit * le = 0;
	if(varType == tr("String")) {
	    se = new StringEdit(this);
	    se->_name->setText(name);
	    if(se->exec() == QDialog::Accepted) {
		_params[name] = QVariant(se->_value->text());
		active = se->_active->isChecked();
	    }
	    delete se;
	    se = 0;
	} else if(varType == tr("Int")) {
	    ie = new IntEdit(this);
	    ie->_name->setText(name);
	    if(ie->exec() == QDialog::Accepted) {
		_params[name] = QVariant(ie->_value->text().toInt());
		active = ie->_active->isChecked();
	    }
	    delete ie;
	    ie = 0;
	} else if(varType == tr("Double")) {
	    de = new DoubleEdit(this);
	    de->_name->setText(name);
	    if(de->exec() == QDialog::Accepted) {
		_params[name] = QVariant(de->_value->text().toDouble());
		active = de->_active->isChecked();
	    }
	    delete de;
	    de = 0;
	} else if(varType == tr("Bool")) {
	    be = new BoolEdit(this);
	    be->_name->setText(name);
	    if(be->exec() == QDialog::Accepted) {
		_params[name] = QVariant((bool)be->value());
		active = be->_active->isChecked();
	    }
	    delete be;
	    be = 0;
	} else if(varType == tr("List")) {
	    le = new ListEdit(this);
	    le->_name->setText(name);
	    if(le->exec() == QDialog::Accepted) {
		_params[name] = QVariant(le->list());
		active = le->_active->isChecked();
	    }
	    delete le;
	    le = 0;
	} else {
	    QMessageBox::warning(this, tr("Unknown Type"), QString(tr("I do not understand the type %1.")).arg(varType));
	    return;
	}
	int r = _table->rowCount();
	_table->setRowCount(r+1);
        QTableWidgetItem * ctItem = 0;
        ctItem = new QTableWidgetItem();
        ctItem->setFlags(Qt::ItemIsUserCheckable);
        ctItem->setCheckState((active ? Qt::Checked : Qt::Unchecked));
        _table->setItem(r, 0, ctItem);
        _table->setItem(r, 1, new QTableWidgetItem(name));
        QVariant var = _params[name];
        _table->setItem(r, 2, new QTableWidgetItem(var.typeName()));
        _table->setItem(r, 3, new QTableWidgetItem(var.toString()));
    }
}
Example #13
0
bool LispPlugin::isa(QVariant ltok, const char* typeName) {
    return QString::compare(typeName, ltok.typeName());
}
Example #14
0
bool DomConvenience::variantToElement(const QVariant& v, QDomElement& e)
{
	bool ok = true;

	clearAttributes(e);

	switch (v.type())
	{
		case QVariant::String:
			e.setTagName("string");
			e.setAttribute("value", v.toString());
			break;
#if 0
		case QVariant::CString:
			e.setTagName("string");
			e.setAttribute("value", v.toString());
			break;
#endif
		case QVariant::Int:
			e.setTagName("int");
			e.setAttribute("value", v.toInt());
			break;
		case QVariant::UInt:
			e.setTagName("uint");
			e.setAttribute("value", v.toUInt());
			break;
		case QVariant::Double:
			e.setTagName("double");
			e.setAttribute("value", v.toDouble());
			break;
		case QVariant::Bool:
			e.setTagName("bool");
			e.setAttribute("value", boolString(v.toBool()));
			break;
		case QVariant::Color:
		{
			e.setTagName("color");
			QColor color = v.value<QColor>();
			e.setAttribute("red", color.red());
			e.setAttribute("green", color.green());
			e.setAttribute("blue", color.blue());
		}
			break;
		case QVariant::Pen:
		{
			e.setTagName("pen");
			QPen pen = v.value<QPen>();
			e.setAttribute("red", pen.color().red());
			e.setAttribute("green", pen.color().green());
			e.setAttribute("blue", pen.color().blue());
			e.setAttribute("style", pen.style());
			e.setAttribute("cap", pen.capStyle());
			e.setAttribute("join", pen.joinStyle());
		}
			break;
		case QVariant::Brush:
		{
			e.setTagName("brush");
			QBrush brush = v.value<QBrush>();
			e.setAttribute("red", brush.color().red());
			e.setAttribute("green", brush.color().green());
			e.setAttribute("blue", brush.color().blue());
			e.setAttribute("style", brush.style());
		}
			break;
		case QVariant::Point:
		{
			e.setTagName("point");
			QPoint point = v.toPoint();
			e.setAttribute("x", point.x());
			e.setAttribute("y", point.y());
		}
			break;
		case QVariant::Rect:
		{
			e.setTagName("rect");
			QRect rect = v.toRect();
			e.setAttribute("x", rect.x());
			e.setAttribute("y", rect.y());
			e.setAttribute("width", rect.width());
			e.setAttribute("height", rect.height());
		}
			break;
		case QVariant::Size:
		{
			e.setTagName("size");
			QSize qsize = v.toSize();
			e.setAttribute("width", qsize.width());
			e.setAttribute("height", qsize.height());
		}
			break;
		case QVariant::Font:
		{
			e.setTagName("font");
			QFont f(v.value<QFont>());
			e.setAttribute("family", f.family());
			e.setAttribute("pointsize", f.pointSize());
			e.setAttribute("bold", boolString(f.bold()));
			e.setAttribute("italic", boolString(f.italic()));
			e.setAttribute("underline", boolString(f.underline()));
			e.setAttribute("strikeout", boolString(f.strikeOut()));
		}
			break;
		case QVariant::SizePolicy:
		{
			e.setTagName("sizepolicy");
			QSizePolicy sp(v.value<QSizePolicy>());
			e.setAttribute("hsizetype", sp.horData());
			e.setAttribute("vsizetype", sp.verData());
			e.setAttribute("horstretch", sp.horStretch());
			e.setAttribute("verstretch", sp.verStretch());
		}
			break;
		case QVariant::Cursor:
			e.setTagName("cursor");
			e.setAttribute("shape", v.value<QCursor>().shape());
			break;

		case QVariant::StringList:
		{
			e.setTagName("stringlist");
			int32_t j;

			QDomNode n;
			QDomNodeList stringNodeList = e.elementsByTagName("string");
			QDomElement stringElem;
			QStringList stringList = v.toStringList();
			QStringList::Iterator it = stringList.begin();

			for (j = 0;
				 ((j < (int32_t)stringNodeList.length()) && (it != stringList.end()));
				 j++)
			{
				// get the current string element
				stringElem = stringNodeList.item(j).toElement();

				// set it to the current string
				variantToElement(QVariant(*it), stringElem);

				// iterate to the next string
				++it;
			}

			// more nodes in previous stringlist then current, remove excess nodes
			if (stringNodeList.count() > stringList.count())
			{
				while (j < (int32_t)stringNodeList.count())
					e.removeChild(stringNodeList.item(j).toElement());
			}
			else if (j < (int32_t)stringList.count())
			{
				while (it != stringList.end())
				{
					// create a new element
					stringElem = m_doc.createElement("string");

					// set it to the currentstring
					variantToElement(QVariant(*it), stringElem);

					// append it to the current element
					e.appendChild(stringElem);

					// iterate to the next string
					++it;
				}
			}
		}
			break;

		case QVariant::KeySequence:
			e.setTagName("key");
			e.setAttribute("sequence", (QString)v.value<QKeySequence>().toString());
			break;

		case QVariant::ByteArray: // this is only for [u]int64_t
		{
			e.setTagName("data");

			// set the value
			e.setAttribute("value", getStringFromByteArray(v.toByteArray()));
		}
			break;

		default:
			qWarning("Don't know how to persist variant of type: %s (%d)!",
					 v.typeName(), v.type());
			ok = false;
			break;
	}

	return ok;
}
Example #15
0
QT_BEGIN_NAMESPACE

/*!
    \class QDBusReply
    \inmodule QtDBus
    \since 4.2

    \brief The QDBusReply class stores the reply for a method call to a remote object.

    A QDBusReply object is a subset of the QDBusMessage object that represents a method call's
    reply. It contains only the first output argument or the error code and is used by
    QDBusInterface-derived classes to allow returning the error code as the function's return
    argument.

    It can be used in the following manner:
    \snippet doc/src/snippets/code/src_qdbus_qdbusreply.cpp 0

    If the remote method call cannot fail, you can skip the error checking:
    \snippet doc/src/snippets/code/src_qdbus_qdbusreply.cpp 1

    However, if it does fail under those conditions, the value returned by QDBusReply::value() is
    a default-constructed value. It may be indistinguishable from a valid return value.

    QDBusReply objects are used for remote calls that have no output
    arguments or return values (i.e., they have a "void" return
    type). Use the isValid() function to test if the reply succeeded.

    \sa QDBusMessage, QDBusInterface
*/

/*!
    \fn QDBusReply::QDBusReply(const QDBusMessage &reply)
    Automatically construct a QDBusReply object from the reply message \a reply, extracting the
    first return value from it if it is a success reply.
*/

/*!
    \fn QDBusReply::QDBusReply(const QDBusPendingReply<T> &reply)
    Constructs a QDBusReply object from the pending reply message, \a reply.
*/

/*!
    \fn QDBusReply::QDBusReply(const QDBusPendingCall &pcall)
    Automatically construct a QDBusReply object from the asynchronous
    pending call \a pcall. If the call isn't finished yet, QDBusReply
    will call QDBusPendingCall::waitForFinished(), which is a blocking
    operation.

    If the return types patch, QDBusReply will extract the first
    return argument from the reply.
*/

/*!
    \fn QDBusReply::QDBusReply(const QDBusError &error)
    Constructs an error reply from the D-Bus error code given by \a error.
*/

/*!
    \fn QDBusReply::operator=(const QDBusReply &other)
    Makes this object be a copy of the object \a other.
*/

/*!
    \fn QDBusReply::operator=(const QDBusError &error)
    Sets this object to contain the error code given by \a error. You
    can later access it with error().
*/

/*!
    \fn QDBusReply::operator=(const QDBusMessage &message)

    Makes this object contain the reply specified by message \a
    message. If \a message is an error message, this function will
    copy the error code and message into this object

    If \a message is a standard reply message and contains at least
    one parameter, it will be copied into this object, as long as it
    is of the correct type. If it's not of the same type as this
    QDBusError object, this function will instead set an error code
    indicating a type mismatch.
*/

/*!
    \fn QDBusReply::operator=(const QDBusPendingCall &pcall)

    Makes this object contain the reply specified by the pending
    asynchronous call \a pcall. If the call is not finished yet, this
    function will call QDBusPendingCall::waitForFinished() to block
    until the reply arrives.

    If \a pcall finishes with an error message, this function will
    copy the error code and message into this object

    If \a pcall finished with a standard reply message and contains at
    least one parameter, it will be copied into this object, as long
    as it is of the correct type. If it's not of the same type as this
    QDBusError object, this function will instead set an error code
    indicating a type mismatch.
*/

/*!
    \fn bool QDBusReply::isValid() const

    Returns true if no error occurred; otherwise, returns false.

    \sa error()
*/

/*!
    \fn QDBusReply::error()

    Returns the error code that was returned from the remote function call. If the remote call did
    not return an error (i.e., if it succeeded), then the QDBusError object that is returned will
    not be a valid error code (QDBusError::isValid() will return false).

    \sa isValid()
*/

/*!
    \fn QDBusReply::value() const
    Returns the remote function's calls return value. If the remote call returned with an error,
    the return value of this function is undefined and may be undistinguishable from a valid return
    value.

    This function is not available if the remote call returns \c void.
*/

/*!
    \fn QDBusReply::operator Type() const
    Returns the same as value().

    This function is not available if the remote call returns \c void.
*/

/*!
    \internal
    Fills in the QDBusReply data \a error and \a data from the reply message \a reply.
*/
void qDBusReplyFill(const QDBusMessage &reply, QDBusError &error, QVariant &data)
{
    error = reply;

    if (error.isValid()) {
        data = QVariant();      // clear it
        return;
    }

    if (reply.arguments().count() >= 1 && reply.arguments().at(0).userType() == data.userType()) {
        data = reply.arguments().at(0);
        return;
    }

    const char *expectedSignature = QDBusMetaType::typeToSignature(data.userType());
    const char *receivedType = 0;
    QByteArray receivedSignature;

    if (reply.arguments().count() >= 1) {
        if (reply.arguments().at(0).userType() == QDBusMetaTypeId::argument) {
            // compare signatures instead
            QDBusArgument arg = qvariant_cast<QDBusArgument>(reply.arguments().at(0));
            receivedSignature = arg.currentSignature().toLatin1();
            if (receivedSignature == expectedSignature) {
                // matched. Demarshall it
                QDBusMetaType::demarshall(arg, data.userType(), data.data());
                return;
            }
        } else {
            // not an argument and doesn't match?
            int type = reply.arguments().at(0).userType();
            receivedType = QVariant::typeToName(QVariant::Type(type));
            receivedSignature = QDBusMetaType::typeToSignature(type);
        }
    }

    // error
    if (receivedSignature.isEmpty())
        receivedSignature = "no signature";
    QString errorMsg;
    if (receivedType) {
        errorMsg = QString::fromLatin1("Unexpected reply signature: got \"%1\" (%4), "
                                         "expected \"%2\" (%3)")
                   .arg(QLatin1String(receivedSignature),
                        QLatin1String(expectedSignature),
                        QLatin1String(data.typeName()),
                        QLatin1String(receivedType));
    } else {
        errorMsg = QString::fromLatin1("Unexpected reply signature: got \"%1\", "
                                         "expected \"%2\" (%3)")
                   .arg(QLatin1String(receivedSignature),
                        QLatin1String(expectedSignature),
                        QLatin1String(data.typeName()));
    }

    error = QDBusError(QDBusError::InvalidSignature, errorMsg);
    data = QVariant();      // clear it
}
Example #16
0
bool SyncableObject::setInitValue(const QString &property, const QVariant &value) {
  QString handlername = QString("initSet") + property;
  handlername[7] = handlername[7].toUpper();
  QGenericArgument param(value.typeName(), value.constData());
  return QMetaObject::invokeMethod(this, handlername.toAscii(), param);
}
Example #17
0
QString ConversionUtil::toJsonString(const QVariant &variant, Options options) {

    switch (variant.type()) {
        case QVariant::Bool:
            return variant.toBool() ? "true" : "false";
        case QVariant::Int:
            return QString::number(variant.toInt());
        case QVariant::UInt:
            return QString::number(variant.toUInt());
        case QVariant::Double:
            return QString::number(variant.toDouble());
        case QVariant::String:
            return variant.toString().isEmpty() ? QString() : jsString(variant.toString());
        case QVariant::List: {
            QStringList stringList;
            for (const QVariant &item : variant.toList()) {
                stringList.append(ConversionUtil::toJsonString(item));
            }
            if (stringList.isEmpty()) {
                return QString();
            } else {
                return "[ " + stringList.join(", ") + " ]";
            }
        }
        case QVariant::StringList: {
            QStringList stringList;
            for (const QString &string : variant.toStringList()) {
                stringList.append(jsString(string));
            }
            if (stringList.isEmpty()) {
                return QString();
            } else {
                return "[ " + stringList.join(", ") + " ]";
            }
        }
        case QVariant::DateTime:
            return QString::number(variant.toDateTime().toMSecsSinceEpoch());
        case QVariant::Map: {
            QStringList stringList;
            QVariantMap map = variant.toMap();
            for (const QString &key : map.keys()) {
                QVariant value = map[key];
                QString jsonString = toJsonString(value, options);
                if (!jsonString.isEmpty()) {
                    if (options & IncludeTypeInfo) {
                        stringList.append(QString("%1: [ %2, %3, %4 ]")
                                          .arg(jsString(key), QString::number(value.type()),
                                               QString::number(value.userType()), jsonString));
                    } else {
                        stringList.append(QString("%1: %2").arg(jsString(key), jsonString));
                    }
                }
            }
            return stringList.isEmpty() ? QString() : "{ " + stringList.join(", ") + " }";
        }
        case QVariant::UserType: {
            MetaTypeRegistry::JsonConverters converters =
                    MetaTypeRegistry::jsonConverters(QMetaType::typeName(variant.userType()));
            if (converters.typeToJsonStringConverter) {
                return converters.typeToJsonStringConverter(variant);
            } else {
                const char *typeName = QMetaType::typeName(variant.userType());
                if (typeName) {
                    LogUtil::logError("User type not serializable: %1", typeName);
                } else {
                    LogUtil::logError("Unknown user type: %1", QString::number(variant.userType()));
                }
                return QString();
            }
        }
        default:
            LogUtil::logError("Unknown type: %1", variant.typeName());
            return QString();
    }
}
QVariant ObjectStaticPropertyModel::data(const QModelIndex &index, int role) const
{
  if (!index.isValid() || !m_obj || index.row() < 0 ||
      index.row() >= m_obj.data()->metaObject()->propertyCount()) {
    return QVariant();
  }

  const QMetaProperty prop = m_obj.data()->metaObject()->property(index.row());
  const QVariant value = prop.read(m_obj.data());
  if (role == Qt::DisplayRole) {
    if (index.column() == 0) {
      return prop.name();
    } else if (index.column() == 1) {
      // QMetaProperty::read sets QVariant::typeName to int for enums,
      // so we need to handle that separately here
      const QString enumStr = Util::enumToString(value, prop.typeName(), m_obj.data());
      if (!enumStr.isEmpty()) {
        return enumStr;
      }
      return VariantHandler::displayString(value);
    } else if (index.column() == 2) {
      return prop.typeName();
    } else if (index.column() == 3) {
      const QMetaObject *mo = m_obj.data()->metaObject();
      while (mo->propertyOffset() > index.row()) {
        mo = mo->superClass();
      }
      return mo->className();
    }
  } else if (role == Qt::DecorationRole) {
    if (index.column() == 1) {
      return VariantHandler::decoration(value);
    }
  } else if (role == Qt::EditRole) {
    if (index.column() == 1 && prop.isWritable()) {
      return value;
    }
  } else if (role == Qt::ToolTipRole) {
    return detailString(prop);
  } else if (role == PropertyModel::ActionRole) {
    return (prop.isResettable() ? PropertyModel::Reset : PropertyModel::NoAction)
         | ((MetaObjectRepository::instance()->metaObject(value.typeName()) && *reinterpret_cast<void* const*>(value.data())) || value.value<QObject*>()
            ? PropertyModel::NavigateTo
            : PropertyModel::NoAction);
  } else if (role == PropertyModel::ValueRole) {
    return value;
  } else if (role == PropertyModel::AppropriateToolRole) {
    ToolModel *toolModel = Probe::instance()->toolModel();
    ToolFactory *factory;
    if (value.canConvert<QObject*>())
      factory = toolModel->data(toolModel->toolForObject(value.value<QObject*>()), ToolModelRole::ToolFactory).value<ToolFactory*>();
    else
      factory = toolModel->data(toolModel->toolForObject(*reinterpret_cast<void* const*>(value.data()), value.typeName()), ToolModelRole::ToolFactory).value<ToolFactory*>();
    if (factory) {
      return factory->name();
    }
    return QVariant();
  }

  return QVariant();
}
glm::quat EntityActionInterface::extractQuatArgument(QString objectName, QVariantMap arguments,
                                                     QString argumentName, bool& ok, bool required) {
    if (!arguments.contains(argumentName)) {
        if (required) {
            qDebug() << objectName << "requires argument:" << argumentName;
        }
        ok = false;
        return glm::quat();
    }

    QVariant resultV = arguments[argumentName];
    if (resultV.type() != (QVariant::Type) QMetaType::QVariantMap) {
        qDebug() << objectName << "argument" << argumentName << "must be a map, not" << resultV.typeName();
        ok = false;
        return glm::quat();
    }

    QVariantMap resultVM = resultV.toMap();
    if (!resultVM.contains("x") || !resultVM.contains("y") || !resultVM.contains("z") || !resultVM.contains("w")) {
        qDebug() << objectName << "argument" << argumentName << "must be a map with keys: x, y, z, and w";
        ok = false;
        return glm::quat();
    }

    QVariant xV = resultVM["x"];
    QVariant yV = resultVM["y"];
    QVariant zV = resultVM["z"];
    QVariant wV = resultVM["w"];

    bool xOk = true;
    bool yOk = true;
    bool zOk = true;
    bool wOk = true;
    float x = xV.toFloat(&xOk);
    float y = yV.toFloat(&yOk);
    float z = zV.toFloat(&zOk);
    float w = wV.toFloat(&wOk);
    if (!xOk || !yOk || !zOk || !wOk) {
        qDebug() << objectName << "argument" << argumentName
                 << "must be a map with keys: x, y, z, and w of type float.";
        ok = false;
        return glm::quat();
    }

    if (x != x || y != y || z != z || w != w) {
        // at least one of the components is NaN!
        ok = false;
        return glm::quat();
    }

    return glm::normalize(glm::quat(w, x, y, z));
}
/**
 * Called by Qt's drag'n drop operation (QDrag) for retrieving the actual drag'n drop
 * data in case of a successful drag'n drop operation.
 *
 * @param strMIMEType           MIME type string.
 * @param vaType                Variant containing the actual data based on the the MIME type.
 *
 * @return QVariant
 */
QVariant UIDnDMIMEData::retrieveData(const QString &strMIMEType, QVariant::Type vaType) const
{
    LogFlowFunc(("state=%RU32, curAction=0x%x, defAction=0x%x, mimeType=%s, type=%d (%s)\n",
                 m_enmState, m_curAction, m_defAction, strMIMEType.toStdString().c_str(), vaType, QVariant::typeToName(vaType)));

    bool fCanDrop = true; /* Accept by default. */

#ifdef RT_OS_WINDOWS
    /* 
     * On Windows this function will be called several times by Qt's
     * OLE-specific internals to figure out which data formats we have
     * to offer. So just assume we can drop data here for a start.
     */ 
#elif defined(RT_OS_DARWIN)
    /*
     * On OS X we rely on an internal flag which gets set in the overriden 
     * hasFormat() function. That function only gets called on a successful drop 
     * so that we can tell if we have to start receiving data the next time 
     * we come by here. 
     */
    fCanDrop = m_fCanDrop;
#else
    /* 
     * On non-Windows our state gets updated via an own event filter
     * (see UIDnDMimeData::eventFilter). This filter will update the current
     * operation state for us (based on the mouse buttons). 
     */ 
    if (m_curAction == Qt::IgnoreAction)
    {
        LogFlowFunc(("Current drop action is 0x%x, so can't drop yet\n", m_curAction));
        fCanDrop = false;
    }
#endif

    if (fCanDrop)
    {
        /* Do we support the requested MIME type? */
        if (!m_lstFormats.contains(strMIMEType))
        {
            LogRel(("DnD: Unsupported MIME type '%s'\n", strMIMEType.toStdString().c_str()));
            fCanDrop = false;
        }

        /* Supported types. See below in the switch statement. */
        if (!(
              /* Plain text. */
                 vaType == QVariant::String
              /* Binary data. */
              || vaType == QVariant::ByteArray
                 /* URI list. */
              || vaType == QVariant::List))
        {
            LogRel(("DnD: Unsupported data type '%s'\n", QVariant::typeToName(vaType)));
            fCanDrop = false;
        }
    }

    LogRel3(("DnD: State=%ld, Action=0x%x, fCanDrop=%RTbool\n", m_enmState, m_curAction, fCanDrop));

    if (fCanDrop)
    {
        QVariant vaData;
        int rc = emit getData(strMIMEType, vaType, vaData);

        LogRel3(("DnD: Returning data of type=%s (requested MIME type=%s, requested type=%s), rc=%Rrc\n",
                 vaData.typeName() ? vaData.typeName() : "<Invalid>",
                 strMIMEType.toStdString().c_str(),
                 QVariant::typeToName(vaType) ? QVariant::typeToName(vaType) : "<Invalid>", rc));

        if (RT_SUCCESS(rc))
            return vaData;
    }

#ifdef RT_OS_DARWIN
    LogFlowFunc(("Returning data for Cocoa\n"));
    return QMimeData::retrieveData(strMIMEType, vaType);
#else
    LogFlowFunc(("Skipping request, state=%RU32 ...\n", m_enmState));
    return QVariant(QVariant::Invalid); /* Return a NULL variant. */
#endif
}
Example #21
0
mongo::BSONObj toBson(QVariantMap obj) {
    mongo::BSONObjBuilder b;

    QVariantMap::iterator it = obj.begin();
    while(it != obj.end()) {
        QByteArray byteName = it.key().toStdString().c_str();
        const char* name = byteName.constData();
        QVariant v = it.value();
        int type = v.type();

//        qDebug() << "toBson converting type" << v.typeName();
        if (v.canConvert<QObject*>()) {
            QMongoType* mongo = qobject_cast<QMongoType*>( v.value<QObject*>() );
            Q_ASSERT(mongo->o.nFields() == 1);
            b.appendAs(mongo->o.firstElement(), name);
            ++it;
            continue;
        }

        bool ok = true;
        switch(type) {
        case QVariant::Int:
            b.append(name, v.toInt(&ok));
            break;
        case QVariant::String:
            b.append(name, v.toString().toStdString());
            break;
        case QVariant::LongLong:
            b.append(name, v.toLongLong(&ok));
            break;
        case QVariant::UInt:
            b.append(name, v.toUInt(&ok));
            break;
        case QVariant::Map:
            b.append(name, toBson(v.toMap()));
            break;
        case QVariant::Double:
            b.append(name, v.toDouble(&ok));
            break;
        case QVariant::Bool:
            b.appendBool(name, v.toBool());
            break;            
        case QVariant::Time:
            b.appendTimeT(name, v.toDateTime().toTime_t());
            break;
        case QVariant::Invalid:
            b.appendUndefined(name);
            break;
        default:
            qCritical() << "toBson() failed to convert" << obj << "for" << name << "with type" << v.typeName();
            ok = false;
        }
        Q_ASSERT(ok);
        ++it;
    }
    return b.obj();
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DataContainerSelectionWidget::populateComboBoxes()
{
  //  std::cout << "void DataContainerSelectionWidget::populateComboBoxesWithSelection()" << std::endl;


  // Now get the DataContainerArray from the Filter instance
  // We are going to use this to get all the current DataContainers
  DataContainerArray::Pointer dca = getFilter()->getDataContainerArray();
  if(NULL == dca.get()) { return; }

  // Check to see if we have any DataContainers to actually populate drop downs with.
  if(dca->getDataContainers().size() == 0)
  {
    return;
  }
  // Cache the DataContainerArray Structure for our use during all the selections
  m_DcaProxy = DataContainerArrayProxy(dca.get());

  // Populate the DataContainerArray Combo Box with all the DataContainers
  QList<DataContainerProxy> dcList = m_DcaProxy.dataContainers.values();
  QListIterator<DataContainerProxy> iter(dcList);
  dataContainerCombo->clear();
  while(iter.hasNext() )
  {
    DataContainerProxy dc = iter.next();
    dataContainerCombo->addItem(dc.name);
//    if(dataContainerCombo->findText(dc.name) == -1 )
//    {
//      int index = dataContainerCombo->currentIndex();
//      dataContainerCombo->addItem(dc.name);
//      dataContainerCombo->setCurrentIndex(index);
//    }
  }

  //remove items in the combo that are NOT in the Data Container Array
//  int count = dataContainerCombo->count();
//  for(int i = count - 1; i >= 0; i--)
//  {
//    QString str0 = dataContainerCombo->itemText(i);
//    iter.toFront();
//    bool boo = false;
//    while(iter.hasNext() )
//    {
//      DataContainerProxy dc = iter.next();
//      if(dc.name.compare(str0) == 0)
//      {
//        boo = true; // found in the list
//      }
//    }
//    if(boo == false)
//    {
//      dataContainerCombo->removeItem(i);
//    }
//  }

  // Grab what is currently selected
  QString curDcName = dataContainerCombo->currentText();


  // Get what is in the filter
  QString filtDcName;
  QString filtAmName;

  QVariant qvSelectedPath = getFilter()->property(PROPERTY_NAME_AS_CHAR);
  if( QString("QString").compare(qvSelectedPath.typeName()) == 0 )
  {
    filtDcName = qvSelectedPath.toString();
  }
  else if( QString("DataArrayPath").compare(qvSelectedPath.typeName()) == 0 )
  {
    DataArrayPath selectedPath = qvSelectedPath.value<DataArrayPath>();
    filtDcName = selectedPath.getDataContainerName();
    filtAmName = selectedPath.getAttributeMatrixName();
  }

  // Now to figure out which one of these to use. If this is the first time through then what we picked up from the
  // gui will be empty strings because nothing is there. If there is something in the filter then we should use that.
  // If there is something in both of them and they are NOT equal then we have a problem. Use the flag m_DidCausePreflight
  // to determine if the change from the GUI should over ride the filter or vice versa. there is a potential that in future
  // versions that something else is driving DREAM3D and pushing the changes to the filter and we need to reflect those
  // changes in the GUI, like a testing script?

  QString dcName = checkStringValues(curDcName, filtDcName);
  if( !dca->doesDataContainerExist(dcName) ) { dcName = ""; }

  bool didBlock = false;

  if (!dataContainerCombo->signalsBlocked()) { didBlock = true; }
  dataContainerCombo->blockSignals(true);
  int dcIndex = dataContainerCombo->findText(dcName);
  if(dcIndex < 0 && dcName.isEmpty() == false)
  {
    dataContainerCombo->addItem(dcName);
  }
  else
  {
    dataContainerCombo->setCurrentIndex(dcIndex);
  }
  if(didBlock) { dataContainerCombo->blockSignals(false); didBlock = false; }

}
Example #23
0
QVariant PythonObject::callMethod(const QString& name, const QVariantList& args)
{
    #ifdef QROSS_PYTHON_FUNCTION_DEBUG
        qrossdebug( QString("PythonObject(%1)::call(%2) isInstance=%3").arg(d->m_pyobject.as_string().c_str()).arg(name).arg(d->m_pyobject.isInstance()) );
    #endif

    //if(d->m_pyobject.isInstance()) { // if it inherits a PyQt4 QObject/QWidget then it's not counted as instance
        try {
            Py::Callable method = d->m_pyobject.getAttr(name.toLatin1().data());
            if (!method.isCallable()) {
                qrossdebug( QString("%1 is not callable (%2).").arg(name).arg(method.str().as_string().c_str()) );
                return QVariant();
            }
            Py::Object pyresult = method.apply( PythonType<QVariantList,Py::Tuple>::toPyObject(args) );
            QVariant result = PythonType<QVariant>::toVariant(pyresult);
            #ifdef QROSS_PYTHON_FUNCTION_DEBUG
                qrossdebug( QString("PythonScript::callFunction() result=%1 variant.toString=%2 variant.typeName=%3").arg(pyresult.as_string().c_str()).arg(result.toString()).arg(result.typeName()) );
            #endif
            return result;
        }
        catch(Py::Exception& e) {
            //#ifdef QROSS_PYTHON_SCRIPT_CALLFUNC_DEBUG
                qrosswarning( QString("PythonScript::callFunction() Exception: %1").arg(Py::value(e).as_string().c_str()) );
            //#endif
            Py::Object err = Py::value(e);
            if(err.ptr() == Py_None) err = Py::type(e); // e.g. string-exceptions have there errormessage in the type-object
            QStringList trace;
            int lineno;
            PythonInterpreter::extractException(trace, lineno);
            setError(err.as_string().c_str(), trace.join("\n"), lineno);
            PyErr_Print();
        }
    //}

    return QVariant();
}
/*
taken from http://delta.affinix.com/2006/08/14/invokemethodwithvariants/
thanks to Justin Karneges once again :)
*/
bool MaiaXmlRpcServerConnection::invokeMethodWithVariants( QObject *obj,
                                                           const QByteArray &method,
                                                           const QVariantList &args,
                                                           QVariant *ret,
                                                           Qt::ConnectionType type )
{
    // QMetaObject::invokeMethod() has a 10 argument maximum
    if( args.count() > 10 ) {
        return false;
    }

    QList<QByteArray> argTypes;
    for( int n = 0; n < args.count(); ++n ) {
        argTypes += args[n].typeName();
    }

    // get return type
    int metatype = 0;
    QByteArray retTypeName = getReturnType(obj->metaObject(), method, argTypes);
    if( !retTypeName.isEmpty() && retTypeName != "QVariant" ) {
        metatype = QMetaType::type(retTypeName.data());
        if( metatype == 0 ) {
            // lookup failed
            return false;
        }
    }

    QGenericArgument arg[10];
    for( int n = 0; n < args.count(); ++n ) {
        arg[n] = QGenericArgument(args[n].typeName(), args[n].constData());
    }

    QGenericReturnArgument retarg;
    QVariant retval;
    if( metatype != 0 && retTypeName != "void" ) {
        retval = QVariant(metatype, (const void *)0);
        retarg = QGenericReturnArgument(retval.typeName(), retval.data());
    }
    else {
        /* QVariant */
        retarg = QGenericReturnArgument("QVariant", &retval);
    }

    if( retTypeName.isEmpty() || retTypeName == "void" ) {
        /* void */
        if( !QMetaObject::invokeMethod(obj, method.data(), type,
                                       arg[0], arg[1], arg[2], arg[3], arg[4],
                                       arg[5], arg[6], arg[7], arg[8], arg[9]) ) {
            return false;
        }
    }
    else {
        if( !QMetaObject::invokeMethod(obj, method.data(), type, retarg,
                                       arg[0], arg[1], arg[2], arg[3], arg[4],
                                       arg[5], arg[6], arg[7], arg[8], arg[9]) ) {
            return false;
        }
    }

    if( retval.isValid() && ret ) {
        *ret = retval;
    }
    return true;

} // bool invokeMethodWithVariants( QObject *obj, const QByteArray &method, const QVariantList &args, QVariant *ret, Qt::ConnectionType type )
 foreach (const QVariant &ar, args) {
     vargs.append(QGenericArgument(ar.typeName(), ar.data()));
 }
Example #26
0
void QDetaliiTabDialog::saveConfiguration()
{
    QString fileName
        = QFileDialog::getSaveFileName(this, tr("Save layout"),"./","*.ccf");
    if (fileName.isEmpty())
        return;

    if (fileName.right(4) != ".ccf")
        fileName += ".ccf";

    QFile file(fileName);
    if (!file.open(QFile::WriteOnly | QIODevice::Text)) {
        QString msg = tr("Failed to open %1\n%2")
                        .arg(fileName)
                        .arg(file.errorString());
        QMessageBox::warning(this, tr("Error"), msg);
        return;
    }

    bool ok = true;

    QTextStream text(&file);
    QSettings settings;
    QVariant settingsValue;

    QStringList settingsKeys = settings.allKeys();

    QList<QString>::iterator j;

    QString settingsType;
    QString stringValue;
    bool okInt;
    for (j = settingsKeys.begin(); j != settingsKeys.end(); ++j)
        {
          settingsValue = settings.value(*j);
          settingsType = settingsValue.typeName();
          if (settingsType == "QString")
            {
              stringValue = settingsValue.toString();

              stringValue.toInt(&okInt, 10);

              if (okInt)
                  {
                   text << *j << "=@Int(" << settingsValue.toString() << ")" << endl;
                  }
              else
                  {
                    if (stringValue == "true")
                      {
                       text << *j << "=@Bool(" << settingsValue.toString() << ")" << endl;
                      }
                    else if (stringValue == "false")
                      {
                       text << *j << "=@Bool(" << settingsValue.toString() << ")" << endl;
                      }
                    else
                      {
                       text << *j << "=@String(\"" << settingsValue.toString() << "\")" << endl;
                      }
                   }
            }

          if (settingsType == "QSize")
            {
              text << *j << "=@Size(" << settingsValue.toSize().width() << "," << settingsValue.toSize().height() << ")" << endl;
            }

          if (settingsType == "QPoint")
            {
              text << *j << "=@Point(" << settingsValue.toPoint().x() << "," << settingsValue.toPoint().y() << ")" << endl;
            }
        }

    text.flush();

    if (!ok) {
        QString msg = tr("Error writing to %1\n%2")
                        .arg(fileName)
                        .arg(file.errorString());
        QMessageBox::warning(this, tr("Error"), msg);
        return;
    }
}
/*!
    \internal
    Adds the variant \a var to the list of arguments, so that the variant's
    value is serialized in send() rather than the variant itself.
*/
void XQServiceRequest::addArg(const QVariant& v)
{
    XQSERVICE_DEBUG_PRINT("XQServiceRequest::addArg %s,%d", v.typeName());
    XQSERVICE_DEBUG_PRINT("v: %s", qPrintable(v.toString()));
    mData->mArguments.append(v);
}
Example #28
0
void QtCUrl::setOptions(Options& opt) {
	Options defaults;
    //defaults[CURLOPT_FAILONERROR] = true;
	defaults[CURLOPT_ERRORBUFFER].setValue(_errorBuffer);

    if(FileName.isEmpty())
    {
        defaults[CURLOPT_WRITEFUNCTION].setValue(&writer);
        defaults[CURLOPT_WRITEDATA].setValue(&_buffer);
    }else
    {
        File.setFileName(FileName);

        defaults[CURLOPT_WRITEFUNCTION].setValue(&writer_file);
        defaults[CURLOPT_WRITEDATA].setValue(&File);
    }

    defaults[CURLOPT_PROGRESSFUNCTION].setValue(&progress_callback);
    defaults[CURLOPT_PROGRESSDATA].setValue(&AutoDelete);

    defaults[CURLOPT_NOPROGRESS].setValue(0);

    defaults[CURLOPT_SSL_VERIFYPEER].setValue(false);
    defaults[CURLOPT_SSL_VERIFYHOST].setValue(false);

    if(!Filter.isEmpty())
    {
        //defaults[CURLOPT_VERBOSE].setValue(1);
        defaults[CURLOPT_HEADERFUNCTION].setValue(&writer2);
        defaults[CURLOPT_WRITEHEADER].setValue(&_buffer_and_filter);
    }
    //defaults[CURLOPT_VERBOSE].setValue(1);



#ifdef QTCURL_DEBUG
	curl_easy_setopt(_curl, CURLOPT_VERBOSE, 1);
	curl_easy_setopt(_curl, CURLOPT_DEBUGFUNCTION, trace);
#endif

	OptionsIterator i(defaults);

	while (i.hasNext()) {
		i.next();

		if (! opt.contains(i.key())) {
			opt[i.key()] = i.value();
		}
	}

    if(opt.contains(CURLOPT_POSTFIELDSIZE))
    {
        int val = opt[CURLOPT_POSTFIELDSIZE].toInt();
        curl_easy_setopt(_curl, CURLOPT_POSTFIELDSIZE, (long)val);
    }

	i = opt;

	while (i.hasNext()) {
		i.next();
		QVariant value = i.value();


        if(i.key() == CURLOPT_POSTFIELDSIZE)
        {
            continue;
        }

		switch (value.type()) {
			case QVariant::Bool:
			case QVariant::Int: {
				int val = value.toInt();
				curl_easy_setopt(_curl, i.key(), val);
				break;
			}
			case QVariant::ByteArray: {
				QByteArray ba = value.toByteArray();
				curl_easy_setopt(_curl, i.key(), ba.constData());
				break;
			}
			case QVariant::Url: {
				QByteArray ba = value.toUrl().toEncoded();
				curl_easy_setopt(_curl, i.key(), ba.constData());
				break;
			}
			case QVariant::String: {
                curl_easy_setopt(_curl, i.key(), value.toString().toUtf8().data());
				break;
			}
			case QVariant::ULongLong: {
				qulonglong val = value.toULongLong();
				curl_easy_setopt(_curl, i.key(), (void*) val);
				break;
			}
			case QVariant::StringList: {
				struct curl_slist *slist = NULL;
				foreach (const QString &tmp, value.toStringList()) {
					 slist = curl_slist_append(slist, tmp.toUtf8().data());
				}
				_slist.append(slist);
				curl_easy_setopt(_curl, i.key(), slist);
				break;
			}
			default:
				const QString typeName = value.typeName();

				if (typeName == "QtCUrl::WriterPtr") {
					curl_easy_setopt(_curl, i.key(), value.value<WriterPtr>());
                }else if (typeName == "QtCUrl::WriterFilePtr") {
                    curl_easy_setopt(_curl, i.key(), value.value<WriterFilePtr>());
                }else if (typeName == "QtCUrl::HeaderPtr") {
                    curl_easy_setopt(_curl, i.key(), value.value<HeaderPtr>());
                }else if (typeName == "QtCUrl::ProgressPtr") {
                    curl_easy_setopt(_curl, i.key(), value.value<ProgressPtr>());
                }
				else if (typeName == "std::string*") {
					curl_easy_setopt(_curl, i.key(), value.value<std::string*>());
				}
                else if (typeName == "BufferAndFilter*") {
                    curl_easy_setopt(_curl, i.key(), value.value<BufferAndFilter*>());
                }
				else if (typeName == "char*") {
					curl_easy_setopt(_curl, i.key(), value.value<char*>());
				}
                else if (typeName == "bool*") {
                    curl_easy_setopt(_curl, i.key(), value.value<bool*>());
                }
                else if (typeName == "QFile*") {
                    curl_easy_setopt(_curl, i.key(), value.value<QFile*>());
                }
				else {
                    //qDebug() << "[QtCUrl] Unsupported option type: " << typeName;
				}
		}
	}
}
Example #29
0
void packDataValue(QVariant_ *var, DataValue *value)
{
    QVariant *qvar = reinterpret_cast<QVariant *>(var);

    // Some assumptions are made below regarding the size of types.
    // There's apparently no better way to handle this since that's
    // how the types with well defined sizes (qint64) are mapped to
    // meta-types (QMetaType::LongLong).
    switch ((int)qvar->type()) {
    case QVariant::Invalid:
        value->dataType = DTInvalid;
        break;
    case QMetaType::QUrl:
        *qvar = qvar->value<QUrl>().toString();
        // fallthrough
    case QMetaType::QString:
        {
            value->dataType = DTString;
            QByteArray ba = qvar->toByteArray();
            *(char**)(value->data) = local_strdup(ba.constData());
            value->len = ba.size();
            break;
        }
    case QMetaType::Bool:
        value->dataType = DTBool;
        *(qint8*)(value->data) = (qint8)qvar->toInt();
        break;
    case QMetaType::LongLong:
        // Some of these entries will have to be fixed when handling platforms
        // where sizeof(long long) != 8 or sizeof(int) != 4.
        value->dataType = DTInt64;
        *(qint64*)(value->data) = qvar->toLongLong();
        break;
    case QMetaType::ULongLong:
        value->dataType = DTUint64;
        *(quint64*)(value->data) = qvar->toLongLong();
        break;
    case QMetaType::Int:
        value->dataType = DTInt32;
        *(qint32*)(value->data) = qvar->toInt();
        break;
    case QMetaType::UInt:
        value->dataType = DTUint32;
        *(quint32*)(value->data) = qvar->toUInt();
        break;
    case QMetaType::VoidStar:
        value->dataType = DTUintptr;
        *(uintptr_t*)(value->data) = (uintptr_t)qvar->value<void *>();
        break;
    case QMetaType::Double:
        value->dataType = DTFloat64;
        *(double*)(value->data) = qvar->toDouble();
        break;
    case QMetaType::Float:
        value->dataType = DTFloat32;
        *(float*)(value->data) = qvar->toFloat();
        break;
    case QMetaType::QColor:
        value->dataType = DTColor;
        *(unsigned int*)(value->data) = qvar->value<QColor>().rgba();
        break;
    case QMetaType::QVariantList:
        {
            QVariantList varlist = qvar->toList();
            int len = varlist.size();
            DataValue *dvlist = (DataValue *) malloc(sizeof(DataValue) * len);
            for (int i = 0; i < len; i++) {
                packDataValue((void*)&varlist.at(i), &dvlist[i]);
            }
            value->dataType = DTValueList;
            value->len = len;
            *(DataValue**)(value->data) = dvlist;
        }
        break;
    case QMetaType::QVariantMap:
        {
            QVariantMap varmap = qvar->toMap();
            int len = varmap.size() * 2;
            DataValue *dvlist = (DataValue *) malloc(sizeof(DataValue) * len);
            QMapIterator<QString, QVariant> it(varmap);
            for (int i = 0; i < len; i += 2) {
                if (!it.hasNext()) {
                    panicf("QVariantMap mutated during iteration");
                }
                it.next();
                QVariant key = it.key();
                QVariant val = it.value();
                packDataValue((void*)&key, &dvlist[i]);
                packDataValue((void*)&val, &dvlist[i+1]);
            }
            value->dataType = DTValueMap;
            value->len = len;
            *(DataValue**)(value->data) = dvlist;
        }
        break;
    default:
        if (qvar->type() == (int)QMetaType::QObjectStar || qvar->canConvert<QObject *>()) {
            QObject *qobject = qvar->value<QObject *>();
            GoValue *goValue = dynamic_cast<GoValue *>(qobject);
            if (goValue) {
                value->dataType = DTGoAddr;
                *(void **)(value->data) = goValue->addr;
                break;
            }
            GoPaintedValue *goPaintedValue = dynamic_cast<GoPaintedValue *>(qobject);
            if (goPaintedValue) {
                value->dataType = DTGoAddr;
                *(void **)(value->data) = goPaintedValue->addr;
                break;
            }
            value->dataType = DTObject;
            *(void **)(value->data) = qobject;
            break;
        }
        {
            QQmlListReference ref = qvar->value<QQmlListReference>();
            if (ref.isValid() && ref.canCount() && ref.canAt()) {
                int len = ref.count();
                DataValue *dvlist = (DataValue *) malloc(sizeof(DataValue) * len);
                QVariant elem;
                for (int i = 0; i < len; i++) {
                    elem.setValue(ref.at(i));
                    packDataValue(&elem, &dvlist[i]);
                }
                value->dataType = DTValueList;
                value->len = len;
                *(DataValue**)(value->data) = dvlist;
                break;
            }
        }
        if (qstrncmp(qvar->typeName(), "QQmlListProperty<", 17) == 0) {
            QQmlListProperty<QObject> *list = reinterpret_cast<QQmlListProperty<QObject>*>(qvar->data());
            if (list->count && list->at) {
                int len = list->count(list);
                DataValue *dvlist = (DataValue *) malloc(sizeof(DataValue) * len);
                QVariant elem;
                for (int i = 0; i < len; i++) {
                    elem.setValue(list->at(list, i));
                    packDataValue(&elem, &dvlist[i]);
                }
                value->dataType = DTValueList;
                value->len = len;
                *(DataValue**)(value->data) = dvlist;
                break;
            }
        }
        panicf("unsupported variant type: %d (%s)", qvar->type(), qvar->typeName());
        break;
    }
}
Example #30
0
void lua::store_qvariant(QVariant& destination, const lua::index& source)
{
    switch (destination.userType()) {
        case QVariant::Invalid:
            throw lua::error("A QVariant must have a valid type");
            destination.clear();
            break;
        case QVariant::Bool:
            destination.setValue(lua::get<bool>(source));
            break;
        case QVariant::Char:
            destination.setValue(lua::get<char>(source));
            break;
        case QVariant::Int:
        case QVariant::UInt:
            destination.setValue(lua::get<int>(source));
            break;
        case QVariant::Double:
            destination.setValue(lua::get<double>(source));
            break;
        case QVariant::String:
            destination.setValue(lua::get<QString>(source));
            break;
        case QVariant::StringList:
        {
            auto state = source.state();
            QStringList items;

            auto length = lua_rawlen(state, source.pos());
            for (unsigned int i = 1; i <= length; ++i) {
                lua::push(state, i);
                lua_gettable(state, source.pos());
                items << lua::get<QString>(state, -1);
                lua_pop(state, 1);
            }

            destination.setValue(items);
            break;
        }
        case QVariant::Hash:
        {
            QHash<QString, QVariant> hash;

            auto state = source.state();

            lua::push(state, lua::value::nil);
            while (lua_next(state, source.pos()) != 0) {
                auto key = lua::get<QString>(state, -2);
                auto value = lua::get<QVariant>(state, -1);

                hash[key] = value;

                lua_pop(state, 1);
            }

            destination.setValue(hash);
            break;
        }
        default:
        {
            auto converter = qvariant_store_handler.find(destination.userType());
            if (converter != qvariant_store_handler.end()) {
                converter->second(destination, source);
            } else {
                throw std::logic_error(std::string("No QVariant handler exists to store type: ") + destination.typeName());
            }
        }
    }
}