Esempio n. 1
0
FSTReader::ModelType FSTReader::predictModelType(const QVariantHash& mapping) {

    QVariantHash joints;

    if (mapping.contains("joint") && mapping["joint"].type() == QVariant::Hash) {
        joints = mapping["joint"].toHash();
    }

    // if the mapping includes the type hint... then we trust the mapping
    if (mapping.contains(TYPE_FIELD)) {
        return FSTReader::getTypeFromName(mapping[TYPE_FIELD].toString());
    }
    
    // check for blendshapes
    bool hasBlendshapes = mapping.contains(BLENDSHAPE_FIELD);

    // a Head needs to have these minimum fields...
    //joint = jointEyeLeft = EyeL = 1
    //joint = jointEyeRight = EyeR = 1
    //joint = jointNeck = Head = 1
    bool hasHeadMinimum = joints.contains("jointNeck") && joints.contains("jointEyeLeft") && joints.contains("jointEyeRight");

    // a Body needs to have these minimum fields...
    //joint = jointRoot = Hips
    //joint = jointLean = Spine
    //joint = jointNeck = Neck
    //joint = jointHead = HeadTop_End

    bool hasBodyMinimumJoints = joints.contains("jointRoot") && joints.contains("jointLean") && joints.contains("jointNeck")  
                                        && joints.contains("jointHead");
    
    bool isLikelyHead = hasBlendshapes || hasHeadMinimum;

    if (isLikelyHead && hasBodyMinimumJoints) {
        return HEAD_AND_BODY_MODEL;
    }
      
    if (isLikelyHead) {
        return HEAD_MODEL;
    }

    if (hasBodyMinimumJoints) {
        return BODY_ONLY_MODEL;
    }
    
    return ENTITY_MODEL;
}
Esempio n. 2
0
QVariant getChild(const QVariant &in, const QString &parentName, const QString &childName, bool required, bool *ok, QString *errorMessage)
{
	if(!isKeyedObject(in))
	{
		QString pn = !parentName.isEmpty() ? parentName : QString("value");
		setError(ok, errorMessage, QString("%1 is not an object").arg(pn));
		return QVariant();
	}

	QString pn = !parentName.isEmpty() ? parentName : QString("object");

	QVariant v;
	if(in.type() == QVariant::Hash)
	{
		QVariantHash h = in.toHash();

		if(!h.contains(childName))
		{
			if(required)
				setError(ok, errorMessage, QString("%1 does not contain '%2'").arg(pn, childName));
			else
				setSuccess(ok, errorMessage);

			return QVariant();
		}

		v = h[childName];
	}
	else // Map
	{
		QVariantMap m = in.toMap();

		if(!m.contains(childName))
		{
			if(required)
				setError(ok, errorMessage, QString("%1 does not contain '%2'").arg(pn, childName));
			else
				setSuccess(ok, errorMessage);

			return QVariant();
		}

		v = m[childName];
	}

	setSuccess(ok, errorMessage);
	return v;
}
Esempio n. 3
0
void RssParser::parseRssArticle(QXmlStreamReader& xml, const QString& feedUrl)
{
  QVariantHash article;

  while(!xml.atEnd()) {
    xml.readNext();

    if(xml.isEndElement() && xml.name() == "item")
      break;

    if (xml.isStartElement()) {
      if (xml.name() == "title")
        article["title"] = xml.readElementText();
      else if (xml.name() == "enclosure") {
        if (xml.attributes().value("type") == "application/x-bittorrent")
          article["torrent_url"] = xml.attributes().value("url").toString();
      }
      else if (xml.name() == "link")
        article["news_link"] = xml.readElementText();
      else if (xml.name() == "description")
        article["description"] = xml.readElementText();
      else if (xml.name() == "pubDate")
        article["date"] = parseDate(xml.readElementText());
      else if (xml.name() == "author")
        article["author"] = xml.readElementText();
      else if (xml.name() == "guid")
        article["id"] = xml.readElementText();
    }
  }

  if (!article.contains("id")) {
    // Item does not have a guid, fall back to some other identifier
    const QString link = article.value("news_link").toString();
    if (!link.isEmpty())
      article["id"] = link;
    else {
      const QString title = article.value("title").toString();
      if (!title.isEmpty())
        article["id"] = title;
      else {
        qWarning() << "Item has no guid, link or title, ignoring it...";
        return;
      }
    }
  }

  emit newArticle(feedUrl, article);
}
Esempio n. 4
0
void RegroupNode::render( OutputStream *stream, Context *c ) const
{
  Q_UNUSED( stream )
  QVariantList objList = m_target.toList( c );
  if ( objList.isEmpty() ) {
    c->insert( m_varName, QVariantHash() );
    return;
  }

  // What's going on?
  //
  // objList is a flat list of objects with a common parameter. For example, Person objects with
  // a name parameter. The list is already sorted.
  // Say the objList contains ["David Beckham", "David Blain", "Keira Nightly"] etc.
  // We want to regroup the list into separate lists of people with the same first name.
  // ie objHash should be: {"David": ["David Beckham", "David Blain"], "Keira": ["Keira Nightly"]}
  //
  // We then insert the objHash into the Context ready for rendering later in a for loop.

  QVariantList contextList;
  const QString keyName = getSafeString( m_expression.resolve( c ) );
  QListIterator<QVariant> i( objList );
  while ( i.hasNext() ) {
    const QVariant var = i.next();
    c->push();
    c->insert( QLatin1String( "var" ), var );
    const QString key = getSafeString( FilterExpression( QLatin1String( "var." ) + keyName, 0 ).resolve( c ) );
    c->pop();
    QVariantHash hash;
    if ( contextList.size() > 0 ) {
      QVariant hashVar = contextList.last();
      hash = hashVar.toHash();
    }
    if ( !hash.contains( QLatin1String( "grouper" ) ) || hash.value( QLatin1String( "grouper" ) ) != key ) {
      QVariantHash newHash;
      hash.insert( QLatin1String( "grouper" ), key );
      hash.insert( QLatin1String( "list" ), QVariantList() );
      contextList.append( newHash );
    }

    QVariantList list = hash.value( QLatin1String( "list" ) ).toList();
    list.append( var );
    hash.insert( QLatin1String( "list" ), list );
    contextList[contextList.size() - 1] = hash;
  }
  c->insert( m_varName, contextList );
}
//-----------------------------------------------------------------------------
bool qtConfirmationDialog::willAsk(const QString& key)
{
  if (key.isEmpty())
    {
    return true;
    }

  QVariantHash hash = qApp->property("ConfirmationDialogs").toHash();
  if (hash.contains(key))
    {
    return hash[key].toBool();
    }

  QSettings settings;
  settings.beginGroup("ConfirmationDialogs");
  return settings.value(key, true).toBool();
}
Esempio n. 6
0
void ModifyPrinter::save()
{
    if (m_changes) {
        QVariantHash args = m_changedValues;
        QString fileName;
        qCDebug(PM_CONFIGURE_PRINTER) << args;
        if (args.contains("ppd-name") &&
            args["ppd-name"].type() == QVariant::Bool) {

            fileName = ui->makeCB->itemData(ui->makeCB->currentIndex(), PPDFile).toString();
            args.remove("ppd-name");
        }
        qCDebug(PM_CONFIGURE_PRINTER) << fileName;

        QPointer<KCupsRequest> request = new KCupsRequest;
        if (m_isClass) {
            request->addOrModifyClass(m_destName, args);
        } else {
            request->addOrModifyPrinter(m_destName, args, fileName);
        }
        request->waitTillFinished();
        if (request) {
            if (!request->hasError()) {
                if (m_changedValues.contains("ppd-name")) {
                    emit ppdChanged();
                }
                request->getPrinterAttributes(m_destName, m_isClass, neededValues());
                request->waitTillFinished();

                if (!request->hasError() && !request->printers().isEmpty()) {
                    KCupsPrinter printer = request->printers().first();
                    setValues(printer);
                }
            } else {
                KMessageBox::detailedSorry(this,
                                           m_isClass ? i18nc("@info", "Failed to configure class") :
                                                       i18nc("@info", "Failed to configure printer"),
                                           request->errorMsg(),
                                           i18nc("@title:window", "Failed"));
            }
            request->deleteLater();
        }
    }
}
Esempio n. 7
0
ConnCheckWorker::ConnCheckWorker(ZrpcRequest *req, ZrpcManager *proxyControlClient, StatsManager *stats, QObject *parent) :
	Deferred(parent),
	req_(req)
{
	req_->setParent(this);

	QVariantHash args = req_->args();

	if(!args.contains("ids") || args["ids"].type() != QVariant::List)
	{
		respondError("bad-request");
		return;
	}

	QVariantList vids = args["ids"].toList();

	foreach(const QVariant &vid, vids)
	{
		if(vid.type() != QVariant::ByteArray)
		{
			respondError("bad-request");
			return;
		}

		cids_ += QString::fromUtf8(vid.toByteArray());
	}

	foreach(const QString &cid, cids_)
	{
		if(!stats->checkConnection(cid.toUtf8()))
			missing_ += cid;
	}

	if(!missing_.isEmpty())
	{
		// ask the proxy about any cids we don't know about
		Deferred *d = ControlRequest::connCheck(proxyControlClient, missing_, this);
		connect(d, SIGNAL(finished(const DeferredResult &)), SLOT(proxyConnCheck_finished(const DeferredResult &)));
		return;
	}

	doFinish();
}
Esempio n. 8
0
void ModelPackager::populateBasicMapping(QVariantHash& mapping, QString filename, const hfm::Model& hfmModel) {

    // mixamo files - in the event that a mixamo file was edited by some other tool, it's likely the applicationName will
    // be rewritten, so we detect the existence of several different blendshapes which indicate we're likely a mixamo file
    bool likelyMixamoFile = hfmModel.applicationName == "mixamo.com" ||
                            (hfmModel.blendshapeChannelNames.contains("BrowsDown_Right") &&
                             hfmModel.blendshapeChannelNames.contains("MouthOpen") &&
                             hfmModel.blendshapeChannelNames.contains("Blink_Left") &&
                             hfmModel.blendshapeChannelNames.contains("Blink_Right") &&
                             hfmModel.blendshapeChannelNames.contains("Squint_Right"));
    
    if (!mapping.contains(NAME_FIELD)) {
        mapping.insert(NAME_FIELD, QFileInfo(filename).baseName());
    }
    
    if (!mapping.contains(FILENAME_FIELD)) {
        QDir root(_modelFile.path());
        mapping.insert(FILENAME_FIELD, root.relativeFilePath(filename));
    }
    if (!mapping.contains(TEXDIR_FIELD)) {
        mapping.insert(TEXDIR_FIELD, ".");
    }
    if (!mapping.contains(SCRIPT_FIELD)) {
        mapping.insert(SCRIPT_FIELD, ".");
    }
    // mixamo/autodesk defaults
    if (!mapping.contains(SCALE_FIELD)) {
        mapping.insert(SCALE_FIELD, 1.0);
    }
    QVariantHash joints = mapping.value(JOINT_FIELD).toHash();
    if (!joints.contains("jointEyeLeft")) {
        joints.insert("jointEyeLeft", hfmModel.jointIndices.contains("jointEyeLeft") ? "jointEyeLeft" :
                      (hfmModel.jointIndices.contains("EyeLeft") ? "EyeLeft" : "LeftEye"));
    }
    if (!joints.contains("jointEyeRight")) {
        joints.insert("jointEyeRight", hfmModel.jointIndices.contains("jointEyeRight") ? "jointEyeRight" :
                      hfmModel.jointIndices.contains("EyeRight") ? "EyeRight" : "RightEye");
    }
    if (!joints.contains("jointNeck")) {
        joints.insert("jointNeck", hfmModel.jointIndices.contains("jointNeck") ? "jointNeck" : "Neck");
    }
    
    if (!joints.contains("jointRoot")) {
        joints.insert("jointRoot", "Hips");
    }
    if (!joints.contains("jointLean")) {
        joints.insert("jointLean", "Spine");
    }
    if (!joints.contains("jointLeftHand")) {
        joints.insert("jointLeftHand", "LeftHand");
    }
    if (!joints.contains("jointRightHand")) {
        joints.insert("jointRightHand", "RightHand");
    }
    
    if (!joints.contains("jointHead")) {
        const char* topName = likelyMixamoFile ? "HeadTop_End" : "HeadEnd";
        joints.insert("jointHead", hfmModel.jointIndices.contains(topName) ? topName : "Head");
    }

    mapping.insert(JOINT_FIELD, joints);

    if (!mapping.contains(FREE_JOINT_FIELD)) {
        mapping.insertMulti(FREE_JOINT_FIELD, "LeftArm");
        mapping.insertMulti(FREE_JOINT_FIELD, "LeftForeArm");
        mapping.insertMulti(FREE_JOINT_FIELD, "RightArm");
        mapping.insertMulti(FREE_JOINT_FIELD, "RightForeArm");
    }
    
    // If there are no blendshape mappings, and we detect that this is likely a mixamo file,
    // then we can add the default mixamo to "faceshift" mappings
    if (!mapping.contains(BLENDSHAPE_FIELD) && likelyMixamoFile) {
        QVariantHash blendshapes;
        blendshapes.insertMulti("BrowsD_L", QVariantList() << "BrowsDown_Left" << 1.0);
        blendshapes.insertMulti("BrowsD_R", QVariantList() << "BrowsDown_Right" << 1.0);
        blendshapes.insertMulti("BrowsU_C", QVariantList() << "BrowsUp_Left" << 1.0);
        blendshapes.insertMulti("BrowsU_C", QVariantList() << "BrowsUp_Right" << 1.0);
        blendshapes.insertMulti("BrowsU_L", QVariantList() << "BrowsUp_Left" << 1.0);
        blendshapes.insertMulti("BrowsU_R", QVariantList() << "BrowsUp_Right" << 1.0);
        blendshapes.insertMulti("ChinLowerRaise", QVariantList() << "Jaw_Up" << 1.0);
        blendshapes.insertMulti("ChinUpperRaise", QVariantList() << "UpperLipUp_Left" << 0.5);
        blendshapes.insertMulti("ChinUpperRaise", QVariantList() << "UpperLipUp_Right" << 0.5);
        blendshapes.insertMulti("EyeBlink_L", QVariantList() << "Blink_Left" << 1.0);
        blendshapes.insertMulti("EyeBlink_R", QVariantList() << "Blink_Right" << 1.0);
        blendshapes.insertMulti("EyeOpen_L", QVariantList() << "EyesWide_Left" << 1.0);
        blendshapes.insertMulti("EyeOpen_R", QVariantList() << "EyesWide_Right" << 1.0);
        blendshapes.insertMulti("EyeSquint_L", QVariantList() << "Squint_Left" << 1.0);
        blendshapes.insertMulti("EyeSquint_R", QVariantList() << "Squint_Right" << 1.0);
        blendshapes.insertMulti("JawFwd", QVariantList() << "JawForeward" << 1.0);
        blendshapes.insertMulti("JawLeft", QVariantList() << "JawRotateY_Left" << 0.5);
        blendshapes.insertMulti("JawOpen", QVariantList() << "MouthOpen" << 0.7);
        blendshapes.insertMulti("JawRight", QVariantList() << "Jaw_Right" << 1.0);
        blendshapes.insertMulti("LipsFunnel", QVariantList() << "JawForeward" << 0.39);
        blendshapes.insertMulti("LipsFunnel", QVariantList() << "Jaw_Down" << 0.36);
        blendshapes.insertMulti("LipsFunnel", QVariantList() << "MouthNarrow_Left" << 1.0);
        blendshapes.insertMulti("LipsFunnel", QVariantList() << "MouthNarrow_Right" << 1.0);
        blendshapes.insertMulti("LipsFunnel", QVariantList() << "MouthWhistle_NarrowAdjust_Left" << 0.5);
        blendshapes.insertMulti("LipsFunnel", QVariantList() << "MouthWhistle_NarrowAdjust_Right" << 0.5);
        blendshapes.insertMulti("LipsFunnel", QVariantList() << "TongueUp" << 1.0);
        blendshapes.insertMulti("LipsLowerClose", QVariantList() << "LowerLipIn" << 1.0);
        blendshapes.insertMulti("LipsLowerDown", QVariantList() << "LowerLipDown_Left" << 0.7);
        blendshapes.insertMulti("LipsLowerDown", QVariantList() << "LowerLipDown_Right" << 0.7);
        blendshapes.insertMulti("LipsLowerOpen", QVariantList() << "LowerLipOut" << 1.0);
        blendshapes.insertMulti("LipsPucker", QVariantList() << "MouthNarrow_Left" << 1.0);
        blendshapes.insertMulti("LipsPucker", QVariantList() << "MouthNarrow_Right" << 1.0);
        blendshapes.insertMulti("LipsUpperClose", QVariantList() << "UpperLipIn" << 1.0);
        blendshapes.insertMulti("LipsUpperOpen", QVariantList() << "UpperLipOut" << 1.0);
        blendshapes.insertMulti("LipsUpperUp", QVariantList() << "UpperLipUp_Left" << 0.7);
        blendshapes.insertMulti("LipsUpperUp", QVariantList() << "UpperLipUp_Right" << 0.7);
        blendshapes.insertMulti("MouthDimple_L", QVariantList() << "Smile_Left" << 0.25);
        blendshapes.insertMulti("MouthDimple_R", QVariantList() << "Smile_Right" << 0.25);
        blendshapes.insertMulti("MouthFrown_L", QVariantList() << "Frown_Left" << 1.0);
        blendshapes.insertMulti("MouthFrown_R", QVariantList() << "Frown_Right" << 1.0);
        blendshapes.insertMulti("MouthLeft", QVariantList() << "Midmouth_Left" << 1.0);
        blendshapes.insertMulti("MouthRight", QVariantList() << "Midmouth_Right" << 1.0);
        blendshapes.insertMulti("MouthSmile_L", QVariantList() << "Smile_Left" << 1.0);
        blendshapes.insertMulti("MouthSmile_R", QVariantList() << "Smile_Right" << 1.0);
        blendshapes.insertMulti("Puff", QVariantList() << "CheekPuff_Left" << 1.0);
        blendshapes.insertMulti("Puff", QVariantList() << "CheekPuff_Right" << 1.0);
        blendshapes.insertMulti("Sneer", QVariantList() << "NoseScrunch_Left" << 0.75);
        blendshapes.insertMulti("Sneer", QVariantList() << "NoseScrunch_Right" << 0.75);
        blendshapes.insertMulti("Sneer", QVariantList() << "Squint_Left" << 0.5);
        blendshapes.insertMulti("Sneer", QVariantList() << "Squint_Right" << 0.5);
        mapping.insert(BLENDSHAPE_FIELD, blendshapes);
    }
}
ReturnArguments KCupsConnection::request(ipp_op_e operation,
                                         const char *resource,
                                         const QVariantHash &reqValues,
                                         bool needResponse)
{
    ReturnArguments ret;

    if (!readyToStart()) {
        return ret; // This is not intended to be used in the gui thread
    }

    ipp_t *response = NULL;
    bool needDestName = false;
    int group_tag = IPP_TAG_PRINTER;
    do {
        ipp_t *request;
        bool isClass = false;
        QString filename;
        QVariantHash values = reqValues;

        ippDelete(response);

        if (values.contains(QLatin1String("printer-is-class"))) {
            isClass = values.take(QLatin1String("printer-is-class")).toBool();
        }
        if (values.contains(QLatin1String("need-dest-name"))) {
            needDestName = values.take(QLatin1String("need-dest-name")).toBool();
        }
        if (values.contains(QLatin1String("group-tag-qt"))) {
            group_tag = values.take(QLatin1String("group-tag-qt")).toInt();
        }

        if (values.contains(QLatin1String("filename"))) {
            filename = values.take(QLatin1String("filename")).toString();
        }

        // Lets create the request
        if (values.contains(QLatin1String(KCUPS_PRINTER_NAME))) {
            request = ippNewDefaultRequest(values.take(QLatin1String(KCUPS_PRINTER_NAME)).toString(),
                                           isClass,
                                           operation);
        } else {
            request = ippNewRequest(operation);
        }

        // send our user name on the request too
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
                     "requesting-user-name", NULL, cupsUser());

        // Add the requested values to the request
        requestAddValues(request, values);

        // Do the request
        // do the request deleting the response
        if (filename.isEmpty()) {
            response = cupsDoRequest(CUPS_HTTP_DEFAULT, request, resource);
        } else {
            response = cupsDoFileRequest(CUPS_HTTP_DEFAULT, request, resource, filename.toUtf8());
        }
    } while (retry(resource));

    if (response != NULL && needResponse) {
        ret = parseIPPVars(response, group_tag, needDestName);
    }
    ippDelete(response);

    return ret;
}
QScriptValue include( QScriptContext *context, QScriptEngine *engine )
{
    // Check argument count, include() call in global context?
    const QScriptContextInfo contextInfo( context->parentContext() );
    if ( context->argumentCount() < 1 ) {
        context->throwError( i18nc("@info/plain", "One argument expected for <icode>include()</icode>") );
        return engine->undefinedValue();
    } else if ( context->parentContext() && context->parentContext()->parentContext() ) {
        QScriptContext *parentContext = context->parentContext()->parentContext();
        bool error = false;
        while ( parentContext ) {
            const QScriptContextInfo parentContextInfo( parentContext );
            if ( !parentContextInfo.fileName().isEmpty() &&
                 parentContextInfo.fileName() == contextInfo.fileName() )
            {
                // Parent context is in the same file, error
                error = true;
                break;
            }
            parentContext = parentContext->parentContext();
        }

        if ( error ) {
            context->throwError( i18nc("@info/plain", "<icode>include()</icode> calls must be in global context") );
            return engine->undefinedValue();
        }
    }

    // Check if this include() call is before all other statements
    QVariantHash includeData = context->callee().data().toVariant().toHash();
    if ( includeData.contains(contextInfo.fileName()) ) {
        const quint16 maxIncludeLine = includeData[ contextInfo.fileName() ].toInt();
        if ( contextInfo.lineNumber() > maxIncludeLine ) {
            context->throwError( i18nc("@info/plain", "<icode>include()</icode> calls must be the first statements") );
            return engine->undefinedValue();
        }
    }

    // Get argument and check that it's not pointing to another directory
    const QString fileName = context->argument(0).toString();
    if ( fileName.contains('/') ) {
        context->throwError( i18nc("@info/plain", "Cannot include files from other directories") );
        return engine->undefinedValue();
    }

    // Get path of the main script
    QString path;
    QScriptContext *fileInfoContext = context;
    do {
        path = QFileInfo( QScriptContextInfo(fileInfoContext).fileName() ).path();
        fileInfoContext = fileInfoContext->parentContext();
    } while ( path.isEmpty() || path == QLatin1String(".") );

    // Construct file path to the file to be included and check if the file is already included
    const QString filePath = path + '/' + fileName;
    QStringList includedFiles =
            engine->globalObject().property( "includedFiles" ).toVariant().toStringList();
    if ( includedFiles.contains(filePath) ) {
        kWarning() << "File already included" << filePath;
        return engine->undefinedValue();
    }

    // Try to open the file to be included
    QFile scriptFile( filePath );
    if ( !scriptFile.open(QIODevice::ReadOnly) ) {
        context->throwError( i18nc("@info/plain", "Cannot find file to be included: "
                                   "<filename>%1</filename>", filePath) );
        return engine->undefinedValue();
    }

    // Read the file
    QTextStream stream( &scriptFile );
    const QString program = stream.readAll();
    scriptFile.close();

    if ( !includeData.contains(scriptFile.fileName()) ) {
        includeData[ scriptFile.fileName() ] = maxIncludeLine( program );

        QScriptValue includeFunction = engine->globalObject().property("include");
        Q_ASSERT( includeFunction.isValid() );
        includeFunction.setData( qScriptValueFromValue(engine, includeData) );
        engine->globalObject().setProperty( "include", includeFunction,
                                            QScriptValue::KeepExistingFlags );
    }

    // Set script context
    QScriptContext *parent = context->parentContext();
    if ( parent ) {
        context->setActivationObject( parent->activationObject() );
        context->setThisObject( parent->thisObject() );
    }

    // Store included files in global property "includedFiles"
    includedFiles << filePath;
    includedFiles.removeDuplicates();
    QScriptValue::PropertyFlags flags = QScriptValue::ReadOnly | QScriptValue::Undeletable;
    engine->globalObject().setProperty( "includedFiles", engine->newVariant(includedFiles), flags );

    // Evaluate script
    return engine->evaluate( program, filePath );
}
Esempio n. 11
0
void RssParser::parseAtomArticle(QXmlStreamReader& xml, const QString& feedUrl, const QString& baseUrl)
{
  QVariantHash article;
  bool double_content = false;

  while(!xml.atEnd()) {
    xml.readNext();

    if(xml.isEndElement() && xml.name() == "entry")
      break;

    if (xml.isStartElement()) {
      if (xml.name() == "title") {
        // Workaround for CDATA (QString cannot parse html escapes on it's own)
        QTextDocument doc;
        doc.setHtml(xml.readElementText());
        article["title"] = doc.toPlainText();
      }
      else if (xml.name() == "link") {
        QString theLink = ( xml.attributes().isEmpty() ?
                              xml.readElementText() :
                              xml.attributes().value("href").toString() );

        // Atom feeds can have relative links, work around this and
        // take the stress of figuring article full URI from UI

        // Assemble full URI
        article["news_link"] = ( baseUrl.isEmpty() ?
                                   theLink :
                                   baseUrl + theLink );
      }
      else if (xml.name() == "summary" || xml.name() == "content"){
        if(double_content) { // Duplicate content -> ignore
          xml.readNext();

          while(xml.name() != "summary" && xml.name() != "content")
            xml.readNext();

          continue;
        }

        // Try to also parse broken articles, which don't use html '&' escapes
        // Actually works great for non-broken content too
        QString feedText = xml.readElementText(QXmlStreamReader::IncludeChildElements);
        if (!feedText.isEmpty())
          article["description"] = feedText;

        double_content = true;
      }
      else if (xml.name() == "updated"){
        // ATOM uses standard compliant date, don't do fancy stuff
        QDateTime articleDate = QDateTime::fromString(xml.readElementText(), Qt::ISODate);
        article["date"] = ( articleDate.isValid() ?
                              articleDate :
                              QDateTime::currentDateTime() );
      }
      else if (xml.name() == "author") {
        xml.readNext();
        while(xml.name() != "author") {
          if(xml.name() == "name")
            article["author"] = xml.readElementText();
          xml.readNext();
        }
      }
      else if (xml.name() == "id")
        article["id"] = xml.readElementText();
    }
  }

  if (!article.contains("id")) {
    // Item does not have a guid, fall back to some other identifier
    const QString link = article.value("news_link").toString();
    if (!link.isEmpty())
      article["id"] = link;
    else {
      const QString title = article.value("title").toString();
      if (!title.isEmpty())
        article["id"] = title;
      else {
        qWarning() << "Item has no guid, link or title, ignoring it...";
        return;
      }
    }
  }

  emit newArticle(feedUrl, article);
}
Esempio n. 12
0
void AVDecoder::setOptions(const QVariantHash &dict)
{
    DPTR_D(AVDecoder);
    d.options = dict;
    if (d.dict) {
        av_dict_free(&d.dict);
        d.dict = 0; //aready 0 in av_free
    }
    if (dict.isEmpty())
        return;
    // TODO: use QVariantMap only
    QVariant opt;
    if (dict.contains("avcodec"))
        opt = dict.value("avcodec");
    if (opt.type() == QVariant::Hash) {
        QVariantHash avcodec_dict = opt.toHash();
        // workaround for VideoDecoderFFmpeg. now it does not call av_opt_set_xxx, so set here in dict
        // TODO: wrong if opt is empty
        //if (dict.contains("FFmpeg"))
        //    avcodec_dict.unite(dict.value("FFmpeg").toHash());
        QHashIterator<QString, QVariant> i(avcodec_dict);
        while (i.hasNext()) {
            i.next();
            const QByteArray key(i.key().toLower().toUtf8());
            switch (i.value().type()) {
            case QVariant::Hash: // for example "vaapi": {...}
                continue;
            case QVariant::Bool:
            case QVariant::Int: {
                // QVariant.toByteArray(): "true" or "false", can not recognized by avcodec
                av_dict_set(&d.dict, key.constData(), QByteArray::number(i.value().toInt()).constData(), 0);
                if (d.codec_ctx)
                    av_opt_set_int(d.codec_ctx, key.constData(), i.value().toInt(), 0);
            }
                break;
            case QVariant::ULongLong:
            case QVariant::LongLong: {
                av_dict_set(&d.dict, key.constData(), QByteArray::number(i.value().toLongLong()).constData(), 0);
                if (d.codec_ctx)
                    av_opt_set_int(d.codec_ctx, key.constData(), i.value().toLongLong(), 0);
            }
                break;
            default:
                // avcodec key and value are in lower case
                av_dict_set(&d.dict, i.key().toLower().toUtf8().constData(), i.value().toByteArray().toLower().constData(), 0);
                break;
            }
            qDebug("avcodec option: %s=>%s", i.key().toUtf8().constData(), i.value().toByteArray().constData());
        }
    } else if (opt.type() == QVariant::Map) {
        QVariantMap avcodec_dict = opt.toMap();
        // workaround for VideoDecoderFFmpeg. now it does not call av_opt_set_xxx, so set here in dict
        //if (dict.contains("FFmpeg"))
        //    avcodec_dict.unite(dict.value("FFmpeg").toMap());
        QMapIterator<QString, QVariant> i(avcodec_dict);
        while (i.hasNext()) {
            i.next();
            const QByteArray key(i.key().toLower().toUtf8());
            switch (i.value().type()) {
            case QVariant::Map: // for example "vaapi": {...}
                continue;
            case QVariant::Bool:
            case QVariant::UInt:
            case QVariant::Int: {
                // QVariant.toByteArray(): "true" or "false", can not recognized by avcodec
                av_dict_set(&d.dict, key.constData(), QByteArray::number(i.value().toInt()), 0);
                if (d.codec_ctx)
                    av_opt_set_int(d.codec_ctx, key.constData(), i.value().toInt(), 0);
            }
                break;
            case QVariant::ULongLong:
            case QVariant::LongLong: {
                av_dict_set(&d.dict, key.constData(), QByteArray::number(i.value().toLongLong()).constData(), 0);
                if (d.codec_ctx)
                    av_opt_set_int(d.codec_ctx, key.constData(), i.value().toLongLong(), 0);
            }
                break;
            default:
                // avcodec key and value are in lower case
                av_dict_set(&d.dict, i.key().toLower().toUtf8().constData(), i.value().toByteArray().toLower().constData(), 0);
                break;
            }
            qDebug("avcodec option: %s=>%s", i.key().toUtf8().constData(), i.value().toByteArray().constData());
        }
    }
    if (name() == "avcodec")
        return;
    if (dict.contains(name()))
        opt = dict.value(name());
    else if (dict.contains(name().toLower()))
        opt = dict.value(name().toLower());
    else
        return;
    if (opt.type() == QVariant::Hash) {
        QVariantHash property_dict(opt.toHash());
        if (property_dict.isEmpty())
            return;
        QHashIterator<QString, QVariant> i(property_dict);
        while (i.hasNext()) {
            i.next();
            if (i.value().type() == QVariant::Hash) // for example "vaapi": {...}
                continue;
            setProperty(i.key().toUtf8().constData(), i.value());
            qDebug("decoder property: %s=>%s", i.key().toUtf8().constData(), i.value().toByteArray().constData());
        }
    } else if (opt.type() == QVariant::Map) {
        QVariantMap property_dict(opt.toMap());
        if (property_dict.isEmpty())
            return;
        QMapIterator<QString, QVariant> i(property_dict);
        while (i.hasNext()) {
            i.next();
            if (i.value().type() == QVariant::Map) // for example "vaapi": {...}
                continue;
            setProperty(i.key().toUtf8().constData(), i.value());
            qDebug("decoder property: %s=>%s", i.key().toUtf8().constData(), i.value().toByteArray().constData());
        }
    }

}
Esempio n. 13
0
bool RetryRequestPacket::fromVariant(const QVariant &in)
{
	if(in.type() != QVariant::Hash)
		return false;

	QVariantHash obj = in.toHash();

	if(!obj.contains("requests") || obj["requests"].type() != QVariant::List)
		return false;

	requests.clear();
	foreach(const QVariant &i, obj["requests"].toList())
	{
		if(i.type() != QVariant::Hash)
			return false;

		QVariantHash vrequest = i.toHash();

		Request r;

		if(!vrequest.contains("rid") || vrequest["rid"].type() != QVariant::Hash)
			return false;

		QVariantHash vrid = vrequest["rid"].toHash();

		QByteArray sender, id;

		if(!vrid.contains("sender") || vrid["sender"].type() != QVariant::ByteArray)
			return false;

		sender = vrid["sender"].toByteArray();

		if(!vrid.contains("id") || vrid["id"].type() != QVariant::ByteArray)
			return false;

		id = vrid["id"].toByteArray();

		r.rid = Rid(sender, id);

		if(vrequest.contains("https"))
		{
			if(vrequest["https"].type() != QVariant::Bool)
				return false;

			r.https = vrequest["https"].toBool();
		}

		if(vrequest.contains("peer-address"))
		{
			if(vrequest["peer-address"].type() != QVariant::ByteArray)
				return false;

			r.peerAddress = QHostAddress(QString::fromUtf8(vrequest["peer-address"].toByteArray()));
		}

		if(vrequest.contains("auto-cross-origin"))
		{
			if(vrequest["auto-cross-origin"].type() != QVariant::Bool)
				return false;

			r.autoCrossOrigin = vrequest["auto-cross-origin"].toBool();
		}

		if(vrequest.contains("jsonp-callback"))
		{
			if(vrequest["jsonp-callback"].type() != QVariant::ByteArray)
				return false;

			r.jsonpCallback = vrequest["jsonp-callback"].toByteArray();

			if(vrequest.contains("jsonp-extended-response"))
			{
				if(vrequest["jsonp-extended-response"].type() != QVariant::Bool)
					return false;

				r.jsonpExtendedResponse = vrequest["jsonp-extended-response"].toBool();
			}
		}

		if(!vrequest.contains("in-seq") || vrequest["in-seq"].type() != QVariant::Int)
			return false;
		r.inSeq = vrequest["in-seq"].toInt();

		if(!vrequest.contains("out-seq") || vrequest["out-seq"].type() != QVariant::Int)
			return false;
		r.outSeq = vrequest["out-seq"].toInt();

		if(!vrequest.contains("out-credits") || vrequest["out-credits"].type() != QVariant::Int)
			return false;
		r.outCredits = vrequest["out-credits"].toInt();

		if(vrequest.contains("user-data"))
			r.userData = vrequest["user-data"];

		requests += r;
	}

	if(!obj.contains("request-data") || obj["request-data"].type() != QVariant::Hash)
		return false;
	QVariantHash vrequestData = obj["request-data"].toHash();

	if(!vrequestData.contains("method") || vrequestData["method"].type() != QVariant::ByteArray)
		return false;
	requestData.method = QString::fromLatin1(vrequestData["method"].toByteArray());

	if(!vrequestData.contains("uri") || vrequestData["uri"].type() != QVariant::ByteArray)
		return false;
	requestData.uri = QUrl::fromEncoded(vrequestData["uri"].toByteArray(), QUrl::StrictMode);

	requestData.headers.clear();
	if(vrequestData.contains("headers"))
	{
		if(vrequestData["headers"].type() != QVariant::List)
			return false;

		foreach(const QVariant &i, vrequestData["headers"].toList())
		{
			QVariantList list = i.toList();
			if(list.count() != 2)
				return false;

			if(list[0].type() != QVariant::ByteArray || list[1].type() != QVariant::ByteArray)
				return false;

			requestData.headers += QPair<QByteArray, QByteArray>(list[0].toByteArray(), list[1].toByteArray());
		}
	}

	if(!vrequestData.contains("body") || vrequestData["body"].type() != QVariant::ByteArray)
		return false;
	requestData.body = vrequestData["body"].toByteArray();

	if(obj.contains("inspect"))
	{
		if(obj["inspect"].type() != QVariant::Hash)
			return false;
		QVariantHash vinspect = obj["inspect"].toHash();

		if(!vinspect.contains("no-proxy") || vinspect["no-proxy"].type() != QVariant::Bool)
			return false;
		inspectInfo.noProxy = vinspect["no-proxy"].toBool();

		inspectInfo.sharingKey.clear();
		if(vinspect.contains("sharing-key"))
		{
			if(vinspect["sharing-key"].type() != QVariant::ByteArray)
				return false;

			inspectInfo.sharingKey = vinspect["sharing-key"].toByteArray();
		}

		inspectInfo.userData = vinspect["user-data"];

		haveInspectInfo = true;
	}

	return true;
}