Ejemplo n.º 1
0
void AProProject::parseFile()
{
    if(fileName.isEmpty())
    {
        QMessageBox::warning(0,"Erreur","Le projet spécifié n'existe pas !");
        return;
    }
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::warning(0,"Erreur","Le projet spécifié n'existe pas !");
        return;
    }
    QDomDocument doc("projet");
    if (!doc.setContent(&file))
        return;

    file.close();

    QDomElement root = doc.documentElement();
    if (root.tagName()!="aproject")
        return;

    version = root.attribute("version","");
    if (version != APROJECT_CURRENT_VERSION)
        return;

    QDomNode n = root.firstChild();
    while(!n.isNull())
    {
        QDomElement e = n.toElement();
        if (!e.isNull())
        {
            if (e.tagName()=="config")
            {
                name = e.attribute("name","");
            }
            else if (e.tagName()=="files")
            {
                if (e.attribute("type","") == "src")
                {
                    QDomNode n2 = e.firstChild();
                    while (!n2.isNull())
                    {
                        QDomElement e2 = n2.toElement();
                        if (!e2.isNull())
                        {
                            QString src = e2.attribute("src","");
                            Sources.append(src);
                        }
                        n2 = n2.nextSibling();
                    }
                }

                if (e.attribute("type","") == "header")
                {
                    QDomNode n2 = e.firstChild();
                    while (!n2.isNull())
                    {
                        QDomElement e2 = n2.toElement();
                        if (!e2.isNull())
                        {
                            QString h = e2.attribute("src","");
                            Headers.append(h);
                        }
                        n2 = n2.nextSibling();
                    }
                }
            }
        }
        n = n.nextSibling();
    }
}
Ejemplo n.º 2
0
void EvolutionCalendar::extractCalendarInfo(const QString &info)
{
    //qCDebug(IMPORTWIZARD_LOG)<<" info "<<info;
    //Read QDomElement
    QDomDocument cal;
    if (!EvolutionUtil::loadInDomDocument(info, cal)) {
        return;
    }
    QDomElement domElement = cal.documentElement();

    if (domElement.isNull()) {
        qCDebug(IMPORTWIZARD_LOG) << "Account not found";
        return;
    }
    QString base_uri;
    if (domElement.hasAttribute(QStringLiteral("base_uri"))) {
        base_uri = domElement.attribute(QStringLiteral("base_uri"));
    }
    if (base_uri == QLatin1String("local:")) {
        for (QDomElement e = domElement.firstChildElement(); !e.isNull(); e = e.nextSiblingElement()) {
            const QString tag = e.tagName();
            if (tag == QLatin1String("source")) {
                QString name;
                QMap<QString, QVariant> settings;
                if (e.hasAttribute(QStringLiteral("uid"))) {
                }
                if (e.hasAttribute(QStringLiteral("name"))) {
                    name = e.attribute(QStringLiteral("name"));
                    settings.insert(QStringLiteral("DisplayName"), name);
                }
                if (e.hasAttribute(QStringLiteral("relative_uri"))) {
                    const QString path = mCalendarPath + e.attribute(QStringLiteral("relative_uri")) + QLatin1String("/calendar.ics");
                    settings.insert(QStringLiteral("Path"), path);
                }
                if (e.hasAttribute(QStringLiteral("color_spec"))) {
                    //const QString color = e.attribute(QStringLiteral("color_spec"));
                    //Need id.
                    //TODO: Need to get id for collection to add color.
                }
                QDomElement propertiesElement = e.firstChildElement();
                if (!propertiesElement.isNull()) {
                    for (QDomElement property = propertiesElement.firstChildElement(); !property.isNull(); property = property.nextSiblingElement()) {
                        const QString propertyTag = property.tagName();
                        if (propertyTag == QLatin1String("property")) {
                            if (property.hasAttribute(QStringLiteral("name"))) {
                                const QString propertyName = property.attribute(QStringLiteral("name"));
                                if (propertyName == QLatin1String("custom-file-readonly")) {
                                    if (property.hasAttribute(QStringLiteral("value"))) {
                                        if (property.attribute(QStringLiteral("value")) == QLatin1String("1")) {
                                            settings.insert(QStringLiteral("ReadOnly"), true);
                                        }
                                    }
                                } else if (propertyName == QLatin1String("alarm")) {
                                    qCDebug(IMPORTWIZARD_LOG) << " need to implement alarm property";
                                } else {
                                    qCDebug(IMPORTWIZARD_LOG) << " property unknown :" << propertyName;
                                }
                            }
                        } else {
                            qCDebug(IMPORTWIZARD_LOG) << " tag unknown :" << propertyTag;
                        }
                    }
                }
                AbstractBase::createResource(QStringLiteral("akonadi_ical_resource"), name, settings);
            } else {
                qCDebug(IMPORTWIZARD_LOG) << " tag unknown :" << tag;
            }
        }
    } else if (base_uri == QLatin1String("webcal://")) {
        qCDebug(IMPORTWIZARD_LOG) << " need to implement webcal protocol";
    } else if (base_uri == QLatin1String("google://")) {
        qCDebug(IMPORTWIZARD_LOG) << " need to implement google protocol";
    } else if (base_uri == QLatin1String("caldav://")) {
        qCDebug(IMPORTWIZARD_LOG) << " need to implement caldav protocol";
    } else {
        qCDebug(IMPORTWIZARD_LOG) << " base_uri unknown" << base_uri;
    }
}
void QgsManageConnectionsDialog::loadWFSConnections( const QDomDocument &doc, const QStringList &items )
{
  QDomElement root = doc.documentElement();
  if ( root.tagName() != "qgsWFSConnections" )
  {
    QMessageBox::information( this, tr( "Loading connections" ),
                              tr( "The file is not an WFS connections exchange file." ) );
    return;
  }

  QString connectionName;
  QSettings settings;
  settings.beginGroup( "/Qgis/connections-wfs" );
  QStringList keys = settings.childGroups();
  settings.endGroup();
  QDomElement child = root.firstChildElement();
  bool prompt = true;
  bool overwrite = true;

  while ( !child.isNull() )
  {
    connectionName = child.attribute( "name" );
    if ( !items.contains( connectionName ) )
    {
      child = child.nextSiblingElement();
      continue;
    }

    // check for duplicates
    if ( keys.contains( connectionName ) && prompt )
    {
      int res = QMessageBox::warning( this, tr( "Loading connections" ),
                                      tr( "Connection with name '%1' already exists. Overwrite?" )
                                      .arg( connectionName ),
                                      QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No | QMessageBox::NoToAll | QMessageBox::Cancel );

      switch ( res )
      {
        case QMessageBox::Cancel:   return;
        case QMessageBox::No:       child = child.nextSiblingElement();
          continue;
        case QMessageBox::Yes:      overwrite = true;
          break;
        case QMessageBox::YesToAll: prompt = false;
          overwrite = true;
          break;
        case QMessageBox::NoToAll:  prompt = false;
          overwrite = false;
          break;
      }
    }

    if ( keys.contains( connectionName ) && !overwrite )
    {
      child = child.nextSiblingElement();
      continue;
    }

    // no dups detected or overwrite is allowed
    settings.beginGroup( "/Qgis/connections-wfs" );
    settings.setValue( QString( "/" + connectionName + "/url" ) , child.attribute( "url" ) );
    settings.endGroup();

    if ( !child.attribute( "username" ).isEmpty() )
    {
      settings.beginGroup( "/Qgis/WFS/" + connectionName );
      settings.setValue( "/username", child.attribute( "username" ) );
      settings.setValue( "/password", child.attribute( "password" ) );
      settings.endGroup();
    }
    child = child.nextSiblingElement();
  }
}
Ejemplo n.º 4
0
KstCSD::KstCSD(const QDomElement &e)
: KstDataObject(e) {
  
    QString in_tag;
    QString vecName;
    QString in_vectorUnits, in_rateUnits;
    KstVectorPtr in_V;
    double in_freq = 60.0;
    bool in_average = true;
    int in_length = 8;
    bool in_removeMean = true;
    bool in_apodize = true;
    int in_apodizeFxn = 0;
    int in_windowSize = 5000;
    double in_gaussianSigma = 3.0;
    
    QDomNode n = e.firstChild();
    while (!n.isNull()) {
      QDomElement e = n.toElement(); // try to convert the node to an element.
      if (!e.isNull()) { // the node was really an element.
        if (e.tagName() == "tag") {
          in_tag = e.text();
        } else if (e.tagName() == "vectag") {
          vecName = e.text();
        } else if (e.tagName() == "sampRate") {
          in_freq = e.text().toDouble();
        } else if (e.tagName() == "average") {
          in_average = (e.text() != "0");
        } else if (e.tagName() == "fftLen") {
          in_length = e.text().toInt();
        } else if (e.tagName() == "apodize") {
          in_apodize = (e.text() != "0");
        } else if (e.tagName() == "apodizefxn") {
          in_apodizeFxn = e.text().toInt();
        } else if (e.tagName() == "gaussiansigma") {
          in_gaussianSigma = e.text().toDouble();
        } else if (e.tagName() == "removeMean") {
          in_removeMean = (e.text() != "0");
        } else if (e.tagName() == "windowsize") {
          in_windowSize = e.text().toInt();
        } else if (e.tagName() == "vectorunits") {
          in_vectorUnits = e.text();
        } else if (e.tagName() == "rateunits") {
          in_rateUnits = e.text();
        }
      }
      n = n.nextSibling();
    }
    
    _inputVectorLoadQueue.append(qMakePair(INVECTOR, vecName));
    
    commonConstructor(in_tag, in_V, in_freq, in_average, in_removeMean,
                      in_apodize, in_apodizeFxn, in_windowSize, in_length, in_gaussianSigma,
                      in_vectorUnits, in_rateUnits, vecName);
}
Ejemplo n.º 5
0
void QTestLibPlugin::processExited(int exitCode)
{
    m_projectExplorer->applicationOutputWindow()->processExited(exitCode);

    QFile f(m_outputFile);
    if (!f.open(QIODevice::ReadOnly))
        return;

    QDomDocument doc;
    if (!doc.setContent(&f))
        return;

    f.close();
    f.remove();

    m_outputPane->clearContents();

    const QString testFunctionTag = QLatin1String("TestFunction");
    const QString nameAttr = QLatin1String("name");
    const QString typeAttr = QLatin1String("type");
    const QString incidentTag = QLatin1String("Incident");
    const QString fileAttr = QLatin1String("file");
    const QString lineAttr = QLatin1String("line");
    const QString messageTag = QLatin1String("Message");
    const QString descriptionItem = QLatin1String("Description");

    for (QDomElement testElement = doc.documentElement().firstChildElement();
         !testElement.isNull(); testElement = testElement.nextSiblingElement()) {

         if (testElement.tagName() != testFunctionTag)
             continue;

         QTestFunction *function = new QTestFunction(testElement.attribute(nameAttr));

         for (QDomElement e = testElement.firstChildElement();
              !e.isNull(); e = e.nextSiblingElement()) {

             const QString type = e.attribute(typeAttr);

              if (e.tagName() == incidentTag) {
                 QString file = e.attribute(fileAttr);

                 if (!file.isEmpty()
                     && QFileInfo(file).isRelative()
                     && !m_projectDirectory.isEmpty()) {

                     QFileInfo fi(m_projectDirectory, file);
                     if (fi.exists())
                         file = fi.absoluteFilePath();
                 }

                 const QString line = e.attribute(lineAttr);
                 const QString details = e.text();

                 QTestFunction::IncidentType itype = stringToIncident(type);
                 function->addIncident(itype, file, line, details);
             } else if (e.tagName() ==  messageTag ) {
                 QTestFunction::MessageType msgType = stringToMessageType(type);
                 function->addMessage(msgType, e.namedItem(descriptionItem).toElement().text());
             }
         }

         m_outputPane->addFunction(function);
     }

     m_outputPane->show();
}
Ejemplo n.º 6
0
void xmlParser::parseElement(const QDomElement &element)
{
    QDomNode nodeL2;
    Station tmpS;
    Edge tmpE;
    if( element.tagName() == "stations_list" )
    {        
        nodeL2 = element.firstChild();
        while( !nodeL2.isNull() )
        {
            tmpS.id = nodeL2.toElement().attribute("id").toInt();
            tmpS.fullName = nodeL2.toElement().attribute("fullname");
            tmpS.name = nodeL2.toElement().attribute("name");
            tmpS.x = nodeL2.toElement().attribute("x").toInt();
            tmpS.y = nodeL2.toElement().attribute("y").toInt();
            tmpS.width = nodeL2.toElement().attribute("width").toInt();
            tmpS.height = nodeL2.toElement().attribute("height").toInt();
            tmpS.HAlign = nodeL2.toElement().attribute("halign").toInt();
            tmpS.VAlign = nodeL2.toElement().attribute("valign").toInt();
            tmpS.color = nodeL2.toElement().attribute("stationcolor").toUtf8();
            tmpS.line = nodeL2.toElement().attribute("line").toUShort();
            tmpS.latitude = nodeL2.toElement().attribute("latitude").toDouble();
            tmpS.longitude = nodeL2.toElement().attribute("longitude").toDouble();
            tmpS.xCenter = nodeL2.toElement().attribute("xcenter",QString("-1")).toInt();
            tmpS.yCenter = nodeL2.toElement().attribute("ycenter",QString("-1")).toInt();
            /*
            tmpS.id = nodeL2.toElement().attribute("id").toUShort();
            tmpS.name = nodeL2.toElement().attribute("name");
            tmpS.x = nodeL2.toElement().attribute("x").toUShort();
            tmpS.y = nodeL2.toElement().attribute("y").toUShort();
            */

            StLst->append( tmpS );
            nodeL2 = nodeL2.nextSibling();
        }
    }
    if( element.tagName() == "edges_list" )
    {
        nodeL2 = element.firstChild();
        while( !nodeL2.isNull() )
        {
            tmpE.id = nodeL2.toElement().attribute("id").toUShort();
            tmpE.value = nodeL2.toElement().attribute("value").toUShort();
            tmpE.idFrom = nodeL2.toElement().attribute("idFrom").toUShort();
            tmpE.idTo = nodeL2.toElement().attribute("idTo").toUShort();
            tmpE.byLegs = nodeL2.toElement().attribute("byLegs").toUShort() ? true : false;
//            tmpE.location = nodeL2.toElement().attribute("location");
//            tmpE.x1 = nodeL2.toElement().attribute("x1").toInt() + 15;
//            tmpE.y1 = nodeL2.toElement().attribute("y1").toInt() + 20;
//            tmpE.x2 = nodeL2.toElement().attribute("x2").toInt() + 15;
//            tmpE.y2 = nodeL2.toElement().attribute("y2").toInt() + 20;
            tmpE.x1 = nodeL2.toElement().attribute("x1").toInt();
            tmpE.y1 = nodeL2.toElement().attribute("y1").toInt();
            tmpE.x2 = nodeL2.toElement().attribute("x2").toInt();
            tmpE.y2 = nodeL2.toElement().attribute("y2").toInt();
            tmpE.x3 = nodeL2.toElement().attribute("x3",QString("-1")).toInt();
            tmpE.y3 = nodeL2.toElement().attribute("y3",QString("-1")).toInt();
            tmpE.x4 = nodeL2.toElement().attribute("x4",QString("-1")).toInt();
            tmpE.y4 = nodeL2.toElement().attribute("y4",QString("-1")).toInt();

            EdLst->append( tmpE );
            nodeL2 = nodeL2.nextSibling();
        }
    }
}
Ejemplo n.º 7
0
bool Parser::parseSchemaTag( ParserContext *context, const QDomElement &root )
{
  QName name = root.tagName();
  if ( name.localName() != QLatin1String("schema") )
    return false;

  NSManager *parentManager = context->namespaceManager();
  NSManager namespaceManager;

  // copy namespaces from wsdl
  if ( parentManager )
    namespaceManager = *parentManager;

  context->setNamespaceManager( &namespaceManager );

  QDomNamedNodeMap attributes = root.attributes();
  for ( int i = 0; i < attributes.count(); ++i ) {
    QDomAttr attribute = attributes.item( i ).toAttr();
    if ( attribute.name().startsWith( QLatin1String("xmlns:") ) ) {
      QString prefix = attribute.name().mid( 6 );
      context->namespaceManager()->setPrefix( prefix, attribute.value() );
    }
  }

  if ( root.hasAttribute( QLatin1String("targetNamespace") ) )
    d->mNameSpace = root.attribute( QLatin1String("targetNamespace") );

 // mTypesTable.setTargetNamespace( mNameSpace );

  QDomElement element = root.firstChildElement();
  while ( !element.isNull() ) {
    QName name = element.tagName();
    if ( name.localName() == QLatin1String("import") ) {
      parseImport( context, element );
    } else if ( name.localName() == QLatin1String("element") ) {
      addGlobalElement( parseElement( context, element, d->mNameSpace, element ) );
    } else if ( name.localName() == QLatin1String("complexType") ) {
      ComplexType ct = parseComplexType( context, element, element.attribute("name") );
      d->mComplexTypes.append( ct );
    } else if ( name.localName() == QLatin1String("simpleType") ) {
      SimpleType st = parseSimpleType( context, element );
      d->mSimpleTypes.append( st );
    } else if ( name.localName() == QLatin1String("attribute") ) {
      addGlobalAttribute( parseAttribute( context, element ) );
    } else if ( name.localName() == QLatin1String("attributeGroup") ) {
      d->mAttributeGroups.append( parseAttributeGroup( context, element ) );
    } else if ( name.localName() == QLatin1String("annotation") ) {
      d->mAnnotations = parseAnnotation( context, element );
    } else if ( name.localName() == QLatin1String("include") ) {
      parseInclude( context, element );
    }

    element = element.nextSiblingElement();
  }

  context->setNamespaceManager( parentManager );
  d->mNamespaces = joinNamespaces( d->mNamespaces, namespaceManager.uris() );
  d->mNamespaces = joinNamespaces( d->mNamespaces, QStringList( d->mNameSpace ) );

  resolveForwardDeclarations();

  return true;
}
Ejemplo n.º 8
0
static bool loadDetailsFromXML(const QString &filename, FileDetails *details)
{
    QDomDocument doc("mydocument");
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly))
        return false;

    if (!doc.setContent(&file))
    {
        file.close();
        return false;
    }
    file.close();

    QString docType = doc.doctype().name();

    if (docType == "MYTHARCHIVEITEM")
    {
        QDomNodeList itemNodeList = doc.elementsByTagName("item");
        QString type, dbVersion;

        if (itemNodeList.count() < 1)
        {
            LOG(VB_GENERAL, LOG_ERR,
                "Couldn't find an 'item' element in XML file");
            return false;
        }

        QDomNode n = itemNodeList.item(0);
        QDomElement e = n.toElement();
        type = e.attribute("type");
        dbVersion = e.attribute("databaseversion");
        if (type == "recording")
        {
            QDomNodeList nodeList = e.elementsByTagName("recorded");
            if (nodeList.count() < 1)
            {
                LOG(VB_GENERAL, LOG_ERR,
                    "Couldn't find a 'recorded' element in XML file");
                return false;
            }

            n = nodeList.item(0);
            e = n.toElement();
            n = e.firstChild();
            while (!n.isNull())
            {
                e = n.toElement();
                if (!e.isNull())
                {
                    if (e.tagName() == "title")
                        details->title = e.text();

                    if (e.tagName() == "subtitle")
                        details->subtitle = e.text();

                    if (e.tagName() == "starttime")
                        details->startTime = MythDate::fromString(e.text());

                    if (e.tagName() == "description")
                        details->description = e.text();
                }
                n = n.nextSibling();
            }

            // get channel info
            n = itemNodeList.item(0);
            e = n.toElement();
            nodeList = e.elementsByTagName("channel");
            if (nodeList.count() < 1)
            {
                LOG(VB_GENERAL, LOG_ERR,
                    "Couldn't find a 'channel' element in XML file");
                details->chanID = "";
                details->chanNo = "";
                details->chanName = "";
                details->callsign =  "";
                return false;
            }

            n = nodeList.item(0);
            e = n.toElement();
            details->chanID = e.attribute("chanid");
            details->chanNo = e.attribute("channum");
            details->chanName = e.attribute("name");
            details->callsign =  e.attribute("callsign");
            return true;
        }
        else if (type == "video")
        {
            QDomNodeList nodeList = e.elementsByTagName("videometadata");
            if (nodeList.count() < 1)
            {
                LOG(VB_GENERAL, LOG_ERR,
                    "Couldn't find a 'videometadata' element in XML file");
                return false;
            }

            n = nodeList.item(0);
            e = n.toElement();
            n = e.firstChild();
            while (!n.isNull())
            {
                e = n.toElement();
                if (!e.isNull())
                {
                    if (e.tagName() == "title")
                    {
                        details->title = e.text();
                        details->subtitle = "";
                        details->startTime = QDateTime();
                    }

                    if (e.tagName() == "plot")
                    {
                        details->description = e.text();
                    }
                }
                n = n.nextSibling();
            }

            details->chanID = "N/A";
            details->chanNo = "N/A";
            details->chanName = "N/A";
            details->callsign = "N/A";

            return true;
        }
    }

    return false;
}
Ejemplo n.º 9
0
bool ParameterEdit::setDocument(const QDomDocument & doc)
{
  QDomElement root = doc.documentElement();
  if(root.tagName() != "report")
  {
    QMessageBox::critical(this, tr("Not a Valid Report"),
      tr("The report definition does not appear to be a valid report."
         "\n\nThe root node is not 'report'."));
    return false;
  }

  _list->show();	
  _new->hide();	
  _delete->hide();	

  for(QDomNode n = root.firstChild(); !n.isNull(); n = n.nextSibling())
  {
    if(n.nodeName() == "parameter")
    {
      QDomElement elemSource = n.toElement();
      ORParameter param;

      param.name = elemSource.attribute("name");
      if(param.name.isEmpty())
        continue;
    
      param.type = elemSource.attribute("type");
      param.defaultValue  = elemSource.attribute("default");
      param.active = (elemSource.attribute("active") == "true");
      param.listtype = elemSource.attribute("listtype");
      
      QList<QPair<QString,QString> > pairs;
      if(param.listtype.isEmpty())
        param.description = elemSource.text();
      else
      {
        QDomNodeList section = elemSource.childNodes();
        for(int nodeCounter = 0; nodeCounter < section.count(); nodeCounter++)
        {
          QDomElement elemThis = section.item(nodeCounter).toElement();
          if(elemThis.tagName() == "description")
            param.description = elemThis.text();
          else if(elemThis.tagName() == "query")
            param.query = elemThis.text();
          else if(elemThis.tagName() == "item")
            param.values.append(qMakePair(elemThis.attribute("value"), elemThis.text()));
          else
            qDebug("While parsing parameter encountered an unknown element: %s",(const char*)elemThis.tagName().toLatin1().data());
        }
      }
      QVariant defaultVar;
      if(!param.defaultValue.isEmpty())
        defaultVar = QVariant(param.defaultValue);
      if("integer" == param.type)
        defaultVar = defaultVar.toInt();
      else if("double" == param.type)
        defaultVar = defaultVar.toDouble();
      else if("bool" == param.type)
        defaultVar = QVariant(defaultVar.toBool());
      else
        defaultVar = defaultVar.toString();
      updateParam(param.name, defaultVar, param.active);
      QList<QPair<QString, QString> > list;
      if("static" == param.listtype)
        list = param.values;
      else if("dynamic" == param.listtype && !param.query.isEmpty())
      {
        QSqlQuery qry(param.query);
        while(qry.next())
          list.append(qMakePair(qry.value(0).toString(), qry.value(1).toString()));
      }
      if(!list.isEmpty())
        _lists.insert(param.name, list);
    }
  }

  if(_lists.isEmpty())
    return false; // no defined parameters
  else 
    return true;
}
Ejemplo n.º 10
0
void UPnpDeviceDesc::_InternalLoad( QDomNode oNode, UPnpDevice *pCurDevice )
{
    QString pin = GetMythDB()->GetSetting( "SecurityPin", "");
    pCurDevice->m_securityPin = !(pin.isEmpty() || pin == "0000");

    for ( oNode = oNode.firstChild();
          !oNode.isNull();
          oNode = oNode.nextSibling() )
    {
        QDomElement e = oNode.toElement();

        if (e.isNull())
            continue;

        // TODO: make this table driven (using offset within structure)
        if ( e.tagName() == "deviceType" )
            SetStrValue( e, pCurDevice->m_sDeviceType);
        else if ( e.tagName() == "friendlyName" )
            SetStrValue( e, pCurDevice->m_sFriendlyName );
        else if ( e.tagName() == "manufacturer" )
            SetStrValue( e, pCurDevice->m_sManufacturer );
        else if ( e.tagName() == "manufacturerURL" )
            SetStrValue( e, pCurDevice->m_sManufacturerURL );
        else if ( e.tagName() == "modelDescription" )
            SetStrValue( e, pCurDevice->m_sModelDescription);
        else if ( e.tagName() == "modelName" )
            SetStrValue( e, pCurDevice->m_sModelName );
        else if ( e.tagName() == "modelNumber" )
            SetStrValue( e, pCurDevice->m_sModelNumber );
        else if ( e.tagName() == "modelURL" )
            SetStrValue( e, pCurDevice->m_sModelURL );
        else if ( e.tagName() == "serialNumber" )
            SetStrValue( e, pCurDevice->m_sSerialNumber );
        else if ( e.tagName() == "UPC" )
            SetStrValue( e, pCurDevice->m_sUPC );
        else if ( e.tagName() == "presentationURL" )
            SetStrValue( e, pCurDevice->m_sPresentationURL );
        else if ( e.tagName() == "UDN" )
            SetStrValue( e, pCurDevice->m_sUDN );
        else if ( e.tagName() == "iconList" )
            ProcessIconList( oNode, pCurDevice );
        else if ( e.tagName() == "serviceList" )
            ProcessServiceList( oNode, pCurDevice );
        else if ( e.tagName() == "deviceList" )
            ProcessDeviceList ( oNode, pCurDevice );
        else if ( e.tagName() == "mythtv:X_secure" )
            SetBoolValue( e, pCurDevice->m_securityPin );
        else if ( e.tagName() == "mythtv:X_protocol" )
            SetStrValue( e, pCurDevice->m_protocolVersion );
        else
        {
            // Not one of the expected element names... add to extra list.
            QString sValue = "";
            SetStrValue( e, sValue );
            pCurDevice->m_lstExtra.push_back(NameValue(e.tagName(), sValue));
        }
    }
}
Ejemplo n.º 11
0
  BCLSearchResult::BCLSearchResult(const QDomElement& componentElement)
  {
    m_componentType = componentElement.tagName().toStdString();

    QDomElement uidElement = componentElement.firstChildElement("uuid");
    QDomElement versionIdElement = componentElement.firstChildElement("vuuid");
    QDomElement nameElement = componentElement.firstChildElement("name");
    QDomElement descriptionElement = componentElement.firstChildElement("description");
    QDomElement modelerDescriptionElement = componentElement.firstChildElement("modeler_description");
    QDomElement fidelityLevelElement = componentElement.firstChildElement("fidelity_level");
    QDomElement provenancesElement = componentElement.firstChildElement("provenances");
    QDomElement tagsElement = componentElement.firstChildElement("tags");
    QDomElement attributesElement = componentElement.firstChildElement("attributes");
    QDomElement filesElement = componentElement.firstChildElement("files");
    QDomElement costsElement = componentElement.firstChildElement("costs");

    OS_ASSERT(!nameElement.isNull());
    OS_ASSERT(!uidElement.isNull());
    OS_ASSERT(!versionIdElement.isNull());
    
    QString name = nameElement.firstChild().nodeValue().replace('_', ' ');
    while (name.indexOf("  ") != -1) {
      name = name.replace("  ", " ");
    }
    name[0] = name[0].toUpper();
    m_name = name.toStdString();

    if (!uidElement.isNull() && uidElement.firstChild().nodeValue().length() == 36)
    {
      m_uid = uidElement.firstChild().nodeValue().toStdString();
    }

    if (!versionIdElement.isNull() && versionIdElement.firstChild().nodeValue().length() == 36)
    {
      m_versionId = versionIdElement.firstChild().nodeValue().toStdString();
    }

    if (!descriptionElement.isNull())
    {
      m_description = descriptionElement.firstChild().nodeValue().toStdString();
    }

    if (!modelerDescriptionElement.isNull())
    {
      m_modelerDescription = modelerDescriptionElement.firstChild().nodeValue().toStdString();
    }

    if (!fidelityLevelElement.isNull())
    {
      m_fidelityLevel= fidelityLevelElement.firstChild().nodeValue().toStdString();
    }

    QDomElement provenanceElement = provenancesElement.firstChildElement("provenance");
    while (!provenanceElement.isNull())
    {
      if (provenanceElement.hasChildNodes())
      {
        m_provenances.push_back(BCLProvenance(provenanceElement));
      }
      else
      {
        break;
      }
      provenanceElement = provenanceElement.nextSiblingElement("provenance");
    }
    QDomElement provenanceRequiredElement = provenancesElement.firstChildElement("provenance_required");
    if (!provenanceRequiredElement.isNull())
    {
      std::string required = provenanceRequiredElement.firstChild().nodeValue().toStdString();
      m_provenanceRequired = (required == "true") ? true : false;
    }

    QDomElement tagElement = tagsElement.firstChildElement("tag");
    while (!tagElement.isNull())
    {
      m_tags.push_back(tagElement.firstChild().nodeValue().toStdString());
      tagElement = tagElement.nextSiblingElement("tag");
    }

    QDomElement attributeElement = attributesElement.firstChildElement("attribute");
    while (!attributeElement.isNull())
    {
      if (attributeElement.hasChildNodes())
      {
        std::string name = attributeElement.firstChildElement("name").firstChild()
          .nodeValue().toStdString();
        std::string value = attributeElement.firstChildElement("value").firstChild()
          .nodeValue().toStdString();
        std::string datatype = attributeElement.firstChildElement("datatype").firstChild()
          .nodeValue().toStdString();

        // Units are optional
        std::string units = attributeElement.firstChildElement("units").firstChild()
          .nodeValue().toStdString();

        bool doubleOk;
        double doubleValue = toQString(value).toDouble(&doubleOk);

        bool intOk;
        int intValue = toQString(value).toInt(&intOk);
        
        if (datatype == "float" && doubleOk)
        {
          if (units.empty())
          {
            Attribute attr(name, doubleValue);
            m_attributes.push_back(attr);
          }
          else
          {
            Attribute attr(name, doubleValue, units);
            m_attributes.push_back(attr);
          }
        }
        else if (datatype == "int" && intOk)
        {
          if (units.empty())
          {
            Attribute attr(name, intValue);
            m_attributes.push_back(attr);
          }
          else
          {
            Attribute attr(name, intValue, units);
            m_attributes.push_back(attr);
          }
        }
        // Assume string
        else
        {
          if (units.empty())
          {
            Attribute attr(name, value);
            m_attributes.push_back(attr);
          }
          else
          {
            Attribute attr(name, value, units);
            m_attributes.push_back(attr);
          }
          //LOG(Error, "Error: Unrecognized attribute datatype \"" << datatype << "\"");
        }
      }
      else
      {
        break;
      }
      attributeElement = attributeElement.nextSiblingElement("attribute");
    }

    QDomElement fileElement = filesElement.firstChildElement("file");
    while (!fileElement.isNull())
    {
      if (fileElement.hasChildNodes())
      {
        m_files.push_back(BCLFile(fileElement));
      }
      else
      {
        break;
      }
      fileElement = fileElement.nextSiblingElement("file");
    }

    if (m_componentType == "component")
    {
      QDomElement costElement = costsElement.firstChildElement("cost");
      while (!costElement.isNull())
      {
        if (costElement.hasChildNodes())
        {
          m_costs.push_back(BCLCost(costElement));
        }
        else
        {
          break;
        }
        costElement = costElement.nextSiblingElement("cost");
      }
    }
  }
Ejemplo n.º 12
0
void ColorSetManager::initialiseDefaultPrefs(struct ApplicationPrefs& appPrefs)
{
	QString pfadC = ScPaths::instance().libDir()+"swatches/";
	QString pfadC2 = pfadC + "Scribus_Basic.xml";
	QFile fiC(pfadC2);
	if (!fiC.exists())
	{
		appPrefs.colorPrefs.DColors.insert("White", ScColor(0, 0, 0, 0));
		appPrefs.colorPrefs.DColors.insert("Black", ScColor(0, 0, 0, 255));
		ScColor cc = ScColor(255, 255, 255, 255);
		cc.setRegistrationColor(true);
		appPrefs.colorPrefs.DColors.insert("Registration", cc);
		appPrefs.colorPrefs.DColors.insert("Blue", ScColor(255, 255, 0, 0));
		appPrefs.colorPrefs.DColors.insert("Cyan", ScColor(255, 0, 0, 0));
		appPrefs.colorPrefs.DColors.insert("Green", ScColor(255, 0, 255, 0));
		appPrefs.colorPrefs.DColors.insert("Red", ScColor(0, 255, 255, 0));
		appPrefs.colorPrefs.DColors.insert("Yellow", ScColor(0, 0, 255, 0));
		appPrefs.colorPrefs.DColors.insert("Magenta", ScColor(0, 255, 0, 0));
		appPrefs.colorPrefs.DColorSet = "Scribus-Small";
	}
	else
	{
		if (fiC.open(QIODevice::ReadOnly))
		{
			QString ColorEn, Cname;
			int Rval, Gval, Bval;
			QTextStream tsC(&fiC);
			ColorEn = tsC.readLine();
			if (ColorEn.startsWith("<?xml version="))
			{
				QByteArray docBytes("");
				loadRawText(pfadC2, docBytes);
				QString docText("");
				docText = QString::fromUtf8(docBytes);
				QDomDocument docu("scridoc");
				docu.setContent(docText);
				ScColor lf = ScColor();
				QDomElement elem = docu.documentElement();
				QDomNode PAGE = elem.firstChild();
				while(!PAGE.isNull())
				{
					QDomElement pg = PAGE.toElement();
					if(pg.tagName()=="COLOR" && pg.attribute("NAME")!=CommonStrings::None)
					{
						if (pg.hasAttribute("CMYK"))
							lf.setNamedColor(pg.attribute("CMYK"));
						else
							lf.fromQColor(QColor(pg.attribute("RGB")));
						if (pg.hasAttribute("Spot"))
							lf.setSpotColor(static_cast<bool>(pg.attribute("Spot").toInt()));
						else
							lf.setSpotColor(false);
						if (pg.hasAttribute("Register"))
							lf.setRegistrationColor(static_cast<bool>(pg.attribute("Register").toInt()));
						else
							lf.setRegistrationColor(false);
						appPrefs.colorPrefs.DColors.insert(pg.attribute("NAME"), lf);
					}
					PAGE=PAGE.nextSibling();
				}
			}
			else
			{
				while (!tsC.atEnd())
				{
					ColorEn = tsC.readLine();
					QTextStream CoE(&ColorEn, QIODevice::ReadOnly);
					CoE >> Rval;
					CoE >> Gval;
					CoE >> Bval;
					CoE >> Cname;
					ScColor tmp;
					tmp.setColorRGB(Rval, Gval, Bval);
					appPrefs.colorPrefs.DColors.insert(Cname, tmp);
				}
			}
			fiC.close();
		}
		appPrefs.colorPrefs.DColorSet = "Scribus Basic";
	}
Ejemplo n.º 13
0
  QgsFeatureRequest parseFilterElement( const QString &typeName, QDomElement &filterElem, const QgsProject *project )
  {
    QgsFeatureRequest request;

    QDomNodeList fidNodes = filterElem.elementsByTagName( QStringLiteral( "FeatureId" ) );
    QDomNodeList goidNodes = filterElem.elementsByTagName( QStringLiteral( "GmlObjectId" ) );
    if ( !fidNodes.isEmpty() )
    {
      QgsFeatureIds fids;
      QDomElement fidElem;
      for ( int f = 0; f < fidNodes.size(); f++ )
      {
        fidElem = fidNodes.at( f ).toElement();
        if ( !fidElem.hasAttribute( QStringLiteral( "fid" ) ) )
        {
          throw QgsRequestNotWellFormedException( "FeatureId element without fid attribute" );
        }

        QString fid = fidElem.attribute( QStringLiteral( "fid" ) );
        if ( fid.contains( QLatin1String( "." ) ) )
        {
          if ( fid.section( QStringLiteral( "." ), 0, 0 ) != typeName )
            continue;
          fid = fid.section( QStringLiteral( "." ), 1, 1 );
        }
        fids.insert( fid.toInt() );
      }

      if ( !fids.isEmpty() )
      {
        request.setFilterFids( fids );
      }
      else
      {
        throw QgsRequestNotWellFormedException( QStringLiteral( "No FeatureId element correctly parse against typeName '%1'" ).arg( typeName ) );
      }
      request.setFlags( QgsFeatureRequest::NoFlags );
      return request;
    }
    else if ( !goidNodes.isEmpty() )
    {
      QgsFeatureIds fids;
      QDomElement goidElem;
      for ( int f = 0; f < goidNodes.size(); f++ )
      {
        goidElem = goidNodes.at( f ).toElement();
        if ( !goidElem.hasAttribute( QStringLiteral( "id" ) ) && !goidElem.hasAttribute( QStringLiteral( "gml:id" ) ) )
        {
          throw QgsRequestNotWellFormedException( "GmlObjectId element without gml:id attribute" );
        }

        QString fid = goidElem.attribute( QStringLiteral( "id" ) );
        if ( fid.isEmpty() )
          fid = goidElem.attribute( QStringLiteral( "gml:id" ) );
        if ( fid.contains( QLatin1String( "." ) ) )
        {
          if ( fid.section( QStringLiteral( "." ), 0, 0 ) != typeName )
            continue;
          fid = fid.section( QStringLiteral( "." ), 1, 1 );
        }
        fids.insert( fid.toInt() );
      }

      if ( !fids.isEmpty() )
      {
        request.setFilterFids( fids );
      }
      else
      {
        throw QgsRequestNotWellFormedException( QStringLiteral( "No GmlObjectId element correctly parse against typeName '%1'" ).arg( typeName ) );
      }
      request.setFlags( QgsFeatureRequest::NoFlags );
      return request;
    }
    else if ( filterElem.firstChildElement().tagName() == QLatin1String( "BBOX" ) )
    {
      QDomElement bboxElem = filterElem.firstChildElement();
      QDomElement childElem = bboxElem.firstChildElement();

      while ( !childElem.isNull() )
      {
        if ( childElem.tagName() == QLatin1String( "Box" ) )
        {
          request.setFilterRect( QgsOgcUtils::rectangleFromGMLBox( childElem ) );
        }
        else if ( childElem.tagName() != QLatin1String( "PropertyName" ) )
        {
          QgsGeometry geom = QgsOgcUtils::geometryFromGML( childElem );
          request.setFilterRect( geom.boundingBox() );
        }
        childElem = childElem.nextSiblingElement();
      }
      request.setFlags( QgsFeatureRequest::ExactIntersect | QgsFeatureRequest::NoFlags );
      return request;
    }
    // Apply BBOX through filterRect even inside an And to use spatial index
    else if ( filterElem.firstChildElement().tagName() == QLatin1String( "And" ) &&
              !filterElem.firstChildElement().firstChildElement( QLatin1String( "BBOX" ) ).isNull() )
    {
      QDomElement childElem = filterElem.firstChildElement().firstChildElement();
      while ( !childElem.isNull() )
      {
        QDomElement childFilterElement = filterElem.ownerDocument().createElement( QLatin1String( "Filter" ) );
        childFilterElement.appendChild( childElem.cloneNode( true ) );
        QgsFeatureRequest childRequest = parseFilterElement( typeName, childFilterElement );
        if ( childElem.tagName() == QLatin1String( "BBOX" ) )
        {
          if ( request.filterRect().isEmpty() )
          {
            request.setFilterRect( childRequest.filterRect() );
          }
          else
          {
            request.setFilterRect( request.filterRect().intersect( childRequest.filterRect() ) );
          }
        }
        else
        {
          if ( !request.filterExpression() )
          {
            request.setFilterExpression( childRequest.filterExpression()->expression() );
          }
          else
          {
            QgsExpressionNode *opLeft = request.filterExpression()->rootNode()->clone();
            QgsExpressionNode *opRight = childRequest.filterExpression()->rootNode()->clone();
            std::unique_ptr<QgsExpressionNodeBinaryOperator> node = qgis::make_unique<QgsExpressionNodeBinaryOperator>( QgsExpressionNodeBinaryOperator::boAnd, opLeft, opRight );
            QgsExpression expr( node->dump() );
            request.setFilterExpression( expr );
          }
        }
        childElem = childElem.nextSiblingElement();
      }
      request.setFlags( QgsFeatureRequest::ExactIntersect | QgsFeatureRequest::NoFlags );
      return request;
    }
    else
    {
      QgsVectorLayer *layer = nullptr;
      if ( project != nullptr )
      {
        layer = layerByTypeName( project, typeName );
      }
      std::shared_ptr<QgsExpression> filter( QgsOgcUtils::expressionFromOgcFilter( filterElem, layer ) );
      if ( filter )
      {
        if ( filter->hasParserError() )
        {
          throw QgsRequestNotWellFormedException( filter->parserErrorString() );
        }

        if ( filter->needsGeometry() )
        {
          request.setFlags( QgsFeatureRequest::NoFlags );
        }
        request.setFilterExpression( filter->expression() );
        return request;
      }
    }
    return request;
  }
Ejemplo n.º 14
0
void XMLPreferences::loadPreferences(const QString& filename, 
				     PrefSectionDict& dict)
{
  QDomDocument doc(seqPrefName);
  QFile f(filename);
  if (!f.open(IO_ReadOnly))
  {
    qWarning("Unable to open file: %s!", 
	     (const char*)filename);
    return;
  }

  QString errorMsg;
  int errorLine = 0;
  int errorColumn = 0;
  if (!doc.setContent(&f, false, &errorMsg, &errorLine, &errorColumn))
  {
    qWarning("Error processing file: %s!\n\t %s on line %d in column %d!", 
	     (const char*)filename, 
	     (const char*)errorMsg, errorLine, errorColumn);
    f.close();
    return;
  }

  // do more processing here
 QDomElement docElem = doc.documentElement();
 DomConvenience conv(doc);
 QDomNodeList sectionList, propertyList;
 PreferenceDict* sectionDict;
 CommentDict* commentSectionDict;
 QString comment;
 QString* commentVal;
 QDomElement section;
 QDomElement property;
 QString sectionName;
 QString propertyName;
 QDomNode n;
 QDomElement valueElement;
 bool foundValue;

 sectionList = doc.elementsByTagName("section");
 for (uint i = 0; i < sectionList.length(); i++)
 {
   section = sectionList.item(i).toElement();
   if (!section.hasAttribute("name"))
   {
     qWarning("section without name!");
     continue;
   }

   sectionName = section.attribute("name");

   // see if the section exists in the dictionary
   sectionDict = dict.find(sectionName);

   // if not, then create it
   if (sectionDict == NULL)
   {
     // create the new preference dictionary
     sectionDict = new PreferenceDict(preferenceHashSize);

     // make sure the dictionary deletes removed properties
     sectionDict->setAutoDelete(true);

     // insert the preference dictionary into the section
     dict.insert(sectionName, sectionDict);
   }

   // see if comment section exists in the dictionary
   commentSectionDict = m_commentSections.find(sectionName);

   // if not, then create it
   if (commentSectionDict == NULL)
   {
     // create the new preference dictionary
     commentSectionDict = new CommentDict(preferenceHashSize);

     // make sure the dictionary deletes removed properties
     commentSectionDict->setAutoDelete(true);

     // insert the preference dictionary into the section
     m_commentSections.insert(sectionName, commentSectionDict);
   }

   propertyList = section.elementsByTagName("property");
   
   for (uint j = 0; j < propertyList.length(); j++)
   {
     property = propertyList.item(j).toElement();
     if (!property.hasAttribute("name"))
     {
       qWarning("property in section '%s' without name! Ignoring!",
		(const char*)sectionName);
       continue;
     }

     propertyName = property.attribute("name");

     foundValue = false;

     QVariant value;
     // iterate over the nodes under the property
     for (n = property.firstChild(); !n.isNull(); n = n.nextSibling())
     {
       if (!n.isElement())
	 continue;

       valueElement = n.toElement();

       if (valueElement.tagName() == "comment")
       {
	 // get comment if any
	 comment = valueElement.text();

	 // if there is a comment, cache it
         if (!comment.isEmpty())
         {
	   commentVal = commentSectionDict->find(propertyName);
	   
	   if (commentVal != NULL)
	     *commentVal = comment;
	   else
	     commentSectionDict->insert(propertyName, 
					new QString(comment));
	 }

	 continue;
       }

       if (!conv.elementToVariant(valueElement, value))
       {
	 qWarning("property '%s' in section '%s' with bogus value in tag '%s'!"
		  " Ignoring!",
		  (const char*)propertyName, (const char*)sectionName,
		  (const char*)valueElement.tagName());
	 
	 continue;
       }

       // found the value
       foundValue = true;
       
       // insert value into the section dictionary
       sectionDict->insert(propertyName, new QVariant(value));
       
       break;
     }

#if 0 // ZBTEMP : Support properties without values to get comments?
     if (!foundValue)
     {
       qWarning("property '%s' in section '%s' without value! Ignoring!",
		(const char*)propertyName, (const char*)sectionName);
       continue;
     }
#endif
   }
 }

  // close the file
  f.close();

#if 1 // ZBTEMP
  printf("Loaded preferences file: %s!\n", (const char*)filename);
#endif
}
Ejemplo n.º 15
0
void SdfRenderer::render(QPainter *painter, const QRectF &bounds)
{
	current_size_x = static_cast<int>(bounds.width());
	current_size_y = static_cast<int>(bounds.height());
	mStartX = static_cast<int>(bounds.x());
	mStartY = static_cast<int>(bounds.y());
	this->painter = painter;
	QDomElement docElem = doc.documentElement();
	QDomNode node = docElem.firstChild();
	while(!node.isNull())
	{
		QDomElement elem = node.toElement();
		if(!elem.isNull())
		{
			if (elem.tagName()=="line")
			{
				line(elem);
			}
			else if(elem.tagName()=="ellipse")
			{
				ellipse(elem);
			}
			else if (elem.tagName() == "arc") {
				arc(elem);
			}
			else if(elem.tagName()=="background")
			{
				background(elem);
			}
			else if(elem.tagName()=="text")
			{
				draw_text(elem);
			}
			else if (elem.tagName()=="rectangle")
			{
				rectangle(elem);
			}
			else if (elem.tagName()=="polygon")
			{
				polygon(elem);
			}
			else if (elem.tagName()=="point")
			{
				point(elem);
			}
			else if(elem.tagName()=="path")
			{
				path_draw(elem);
			}
			else if(elem.tagName()=="stylus")
			{
				stylus_draw(elem);
			}
			else if(elem.tagName()=="curve")
			{
				curve_draw(elem);
			}
			else if(elem.tagName()=="image")
			{
				image_draw(elem);
			}
		}
		node = node.nextSibling();
	}
	this->painter = 0;
}
Ejemplo n.º 16
0
bool importColorsFromFile(QString fileName, ColorList &EditColors, QHash<QString, VGradient> *dialogGradients, bool merge)
{
	if (fileName.isEmpty())
		return false;
	int oldCount = EditColors.count();

	QFileInfo fi = QFileInfo(fileName);
	QString ext = fi.suffix().toLower();
	if (extensionIndicatesEPSorPS(ext))
	{
		PaletteLoader_PS psPalLoader;
		psPalLoader.setupTargets(&EditColors, dialogGradients);
		return psPalLoader.importFile(fileName, merge);
	}
	else
	{
		QStringList allFormatsV = LoadSavePlugin::getExtensionsForColors();
		if (allFormatsV.contains(ext))
		{
			FileLoader fl(fileName);
			int testResult = fl.testFile();
			if (testResult != -1)
			{
				ColorList LColors;
				if (fl.readColors(LColors))
				{
					ColorList::Iterator it;
					for (it = LColors.begin(); it != LColors.end(); ++it)
					{
						EditColors.tryAddColor(it.key(), it.value());
					}
					return (EditColors.count() != oldCount);
				}
			}
		}
		if (ext == "acb")			// Adobe color book format
		{
			PaletteLoader_Adobe_acb adobePalLoader;
			if (adobePalLoader.isFileSupported(fileName))
			{
				adobePalLoader.setupTargets(&EditColors, dialogGradients);
				return adobePalLoader.importFile(fileName, merge);
			}

			PaletteLoader_Autocad_acb autocadPalLoder;
			if (autocadPalLoder.isFileSupported(fileName))
			{
				autocadPalLoder.setupTargets(&EditColors, dialogGradients);
				return autocadPalLoder.importFile(fileName, merge);
			}
			return false;
		}
		else if (ext == "aco")			// Adobe color swatch format
		{
			PaletteLoader_Adobe_aco adobePalLoader;
			if (adobePalLoader.isFileSupported(fileName))
			{
				adobePalLoader.setupTargets(&EditColors, dialogGradients);
				return adobePalLoader.importFile(fileName, merge);
			}
			return false;
		}
		else if (ext == "ase")			// Adobe swatch exchange format
		{
			PaletteLoader_Adobe_ase adobePalLoader;
			if (adobePalLoader.isFileSupported(fileName))
			{
				adobePalLoader.setupTargets(&EditColors, dialogGradients);
				return adobePalLoader.importFile(fileName, merge);
			}
			return false;
		}
		else if (ext == "cxf")			// Adobe swatch exchange format
		{
			PaletteLoader_CxF cxfLoader;
			if (cxfLoader.isFileSupported(fileName))
			{
				cxfLoader.setupTargets(&EditColors, dialogGradients);
				return cxfLoader.importFile(fileName, merge);
			}
			return false;
		}
		else if (ext == "skp")			// Sk1 palette
		{
			PaletteLoader_sK1 sk1PalLoader;
			if (sk1PalLoader.isFileSupported(fileName))
			{
				sk1PalLoader.setupTargets(&EditColors, dialogGradients);
				return sk1PalLoader.importFile(fileName, merge);
			}
			return false;
		}
		else if (ext == "sbz")
		{
			PaletteLoader_Swatchbook swatchbookLoader;
			if (swatchbookLoader.isFileSupported(fileName))
			{
				swatchbookLoader.setupTargets(&EditColors, dialogGradients);
				return swatchbookLoader.importFile(fileName, merge);
			}
			return false;
		}
		else							// try for OpenOffice, Viva and our own format
		{
			QFile fiC(fileName);
			if (fiC.open(QIODevice::ReadOnly))
			{
				QString ColorEn, Cname;
				int Rval, Gval, Bval, Kval;
				ScTextStream tsC(&fiC);
				ColorEn = tsC.readLine();
				bool cus = false;
				if (ColorEn.contains("OpenOffice"))
					cus = true;
				if ((ColorEn.startsWith("<?xml version=")) || (ColorEn.contains("VivaColors")))
				{
					QByteArray docBytes("");
					loadRawText(fileName, docBytes);
					QString docText("");
					docText = QString::fromUtf8(docBytes);
					QDomDocument docu("scridoc");
					docu.setContent(docText);
					ScColor lf = ScColor();
					QDomElement elem = docu.documentElement();
					QString dTag = "";
					dTag = elem.tagName();
					QString nameMask = "%1";
					nameMask = elem.attribute("mask", "%1");
					QDomNode PAGE = elem.firstChild();
					while (!PAGE.isNull())
					{
						QDomElement pg = PAGE.toElement();
						if (pg.tagName()=="COLOR" && pg.attribute("NAME")!=CommonStrings::None)
						{
							if (pg.hasAttribute("SPACE"))
							{
								QString space = pg.attribute("SPACE");
								if (space == "CMYK")
								{
									double c = pg.attribute("C", "0").toDouble() / 100.0;
									double m = pg.attribute("M", "0").toDouble() / 100.0;
									double y = pg.attribute("Y", "0").toDouble() / 100.0;
									double k = pg.attribute("K", "0").toDouble() / 100.0;
									lf.setCmykColorF(c, m, y, k);
								}
								else if (space == "RGB")
								{
									double r = pg.attribute("R", "0").toDouble() / 255.0;
									double g = pg.attribute("G", "0").toDouble() / 255.0;
									double b = pg.attribute("B", "0").toDouble() / 255.0;
									lf.setRgbColorF(r, g, b);
								}
								else if (space == "Lab")
								{
									double L = pg.attribute("L", "0").toDouble();
									double a = pg.attribute("A", "0").toDouble();
									double b = pg.attribute("B", "0").toDouble();
									lf.setLabColor(L, a, b);
								}
							}
							else if (pg.hasAttribute("CMYK"))
								lf.setNamedColor(pg.attribute("CMYK"));
							else if (pg.hasAttribute("RGB"))
								lf.fromQColor(QColor(pg.attribute("RGB")));
							else
							{
								double L = pg.attribute("L", "0").toDouble();
								double a = pg.attribute("A", "0").toDouble();
								double b = pg.attribute("B", "0").toDouble();
								lf.setLabColor(L, a, b);
							}
							if (pg.hasAttribute("Spot"))
								lf.setSpotColor(static_cast<bool>(pg.attribute("Spot").toInt()));
							else
								lf.setSpotColor(false);
							if (pg.hasAttribute("Register"))
								lf.setRegistrationColor(static_cast<bool>(pg.attribute("Register").toInt()));
							else
								lf.setRegistrationColor(false);
							EditColors.tryAddColor(pg.attribute("NAME"), lf);
						}
						else if (pg.tagName() == "Gradient")
						{
							if (dialogGradients != NULL)
							{
								VGradient gra = VGradient(VGradient::linear);
								gra.clearStops();
								QDomNode grad = pg.firstChild();
								while (!grad.isNull())
								{
									QDomElement stop = grad.toElement();
									QString name = stop.attribute("NAME");
									double ramp  = ScCLocale::toDoubleC(stop.attribute("RAMP"), 0.0);
									int shade    = stop.attribute("SHADE", "100").toInt();
									double opa   = ScCLocale::toDoubleC(stop.attribute("TRANS"), 1.0);
									QColor color;
									if (name == CommonStrings::None)
										color = QColor(255, 255, 255, 0);
									else
									{
										const ScColor& col = EditColors[name];
										color = ScColorEngine::getShadeColorProof(col, NULL, shade);
									}
									gra.addStop(color, ramp, 0.5, opa, name, shade);
									grad = grad.nextSibling();
								}
								if ((!dialogGradients->contains(pg.attribute("Name"))) || (merge))
									dialogGradients->insert(pg.attribute("Name"), gra);
								else
								{
									QString tmp;
									QString name = pg.attribute("Name");
									name += "("+tmp.setNum(dialogGradients->count())+")";
									dialogGradients->insert(name, gra);
								}
							}
						}
						else if (pg.tagName()=="draw:color" && pg.attribute("draw:name")!=CommonStrings::None)
						{
							if (pg.hasAttribute("draw:color"))
								lf.setNamedColor(pg.attribute("draw:color"));
							lf.setSpotColor(false);
							lf.setRegistrationColor(false);
							QString nam = pg.attribute("draw:name");
							if (!nam.isEmpty())
								EditColors.tryAddColor(nam, lf);
						}
						else if (dTag == "VivaColors")
						{
							int cVal = 0;
							int mVal = 0;
							int yVal = 0;
							int kVal = 0;
							QString nam = nameMask.arg(pg.attribute("name"));
							if (pg.attribute("type") == "cmyk")
							{
								QDomNode colNode = pg.firstChild();
								while (!colNode.isNull())
								{
									QDomElement colVal = colNode.toElement();
									if (colVal.tagName() == "cyan")
										cVal = colVal.text().toInt();
									if (colVal.tagName() == "magenta")
										mVal = colVal.text().toInt();
									if (colVal.tagName() == "yellow")
										yVal = colVal.text().toInt();
									if (colVal.tagName() == "key")
										kVal = colVal.text().toInt();
									colNode = colNode.nextSibling();
								}
								lf.setColorF(cVal / 100.0, mVal / 100.0, yVal / 100.0, kVal / 100.0);
								lf.setSpotColor(false);
								lf.setRegistrationColor(false);
								if (!nam.isEmpty())
									EditColors.tryAddColor(nam, lf);
							}
							else if (pg.attribute("type") == "rgb")
							{
								QDomNode colNode = pg.firstChild();
								while (!colNode.isNull())
								{
									QDomElement colVal = colNode.toElement();
									if (colVal.tagName() == "red")
										cVal = colVal.text().toInt();
									if (colVal.tagName() == "green")
										mVal = colVal.text().toInt();
									if (colVal.tagName() == "blue")
										yVal = colVal.text().toInt();
									colNode = colNode.nextSibling();
								}
								lf.setRgbColor(cVal, mVal, yVal);
								lf.setSpotColor(false);
								lf.setRegistrationColor(false);
								if (!nam.isEmpty())
									EditColors.tryAddColor(nam, lf);
							}
						}
						PAGE=PAGE.nextSibling();
					}
				}
				else
				{
					QString paletteName = "";
					QString dummy;
					if (ColorEn.startsWith("GIMP Palette"))
					{
						ColorEn = tsC.readLine();
						ScTextStream CoE(&ColorEn, QIODevice::ReadOnly);
						CoE >> dummy >> paletteName;
					}
					while (!tsC.atEnd())
					{
						ScColor tmp;
						ColorEn = tsC.readLine();
						if (ColorEn.length()>0 && ColorEn[0]==QChar('#'))
							continue;
						ScTextStream CoE(&ColorEn, QIODevice::ReadOnly);
						CoE >> Rval;
						CoE >> Gval;
						CoE >> Bval;
						if (cus)
						{
							CoE >> Kval;
							Cname = CoE.readAll().trimmed();
							tmp.setColor(Rval, Gval, Bval, Kval);
						}
						else
						{
							Cname = CoE.readAll().trimmed();
							tmp.setRgbColor(Rval, Gval, Bval);
						}
						if (Cname == "Untitled")
							Cname = "";
						if (Cname.length() == 0)
						{
							if (!cus)
								Cname = paletteName + QString("#%1%2%3").arg(Rval,2,16).arg(Gval,2,16).arg(Bval,2,16).toUpper();
							else
								Cname = paletteName + QString("#%1%2%3%4").arg(Rval,2,16).arg(Gval,2,16).arg(Bval,2,16).arg(Kval,2,16).toUpper();
							Cname.replace(" ","0");
						}
						EditColors.tryAddColor(Cname, tmp);
					}
				}
				fiC.close();
			}
QgsFeatureRendererV2* QgsCategorizedSymbolRendererV2::create( QDomElement& element )
{
  QDomElement symbolsElem = element.firstChildElement( "symbols" );
  if ( symbolsElem.isNull() )
    return NULL;

  QDomElement catsElem = element.firstChildElement( "categories" );
  if ( catsElem.isNull() )
    return NULL;

  QgsSymbolV2Map symbolMap = QgsSymbolLayerV2Utils::loadSymbols( symbolsElem );
  QgsCategoryList cats;

  QDomElement catElem = catsElem.firstChildElement();
  while ( !catElem.isNull() )
  {
    if ( catElem.tagName() == "category" )
    {
      QVariant value = QVariant( catElem.attribute( "value" ) );
      QString symbolName = catElem.attribute( "symbol" );
      QString label = catElem.attribute( "label" );
      bool render = catElem.attribute( "render" ) != "false";
      if ( symbolMap.contains( symbolName ) )
      {
        QgsSymbolV2* symbol = symbolMap.take( symbolName );
        cats.append( QgsRendererCategoryV2( value, symbol, label, render ) );
      }
    }
    catElem = catElem.nextSiblingElement();
  }

  QString attrName = element.attribute( "attr" );

  QgsCategorizedSymbolRendererV2* r = new QgsCategorizedSymbolRendererV2( attrName, cats );

  // delete symbols if there are any more
  QgsSymbolLayerV2Utils::clearSymbolMap( symbolMap );

  // try to load source symbol (optional)
  QDomElement sourceSymbolElem = element.firstChildElement( "source-symbol" );
  if ( !sourceSymbolElem.isNull() )
  {
    QgsSymbolV2Map sourceSymbolMap = QgsSymbolLayerV2Utils::loadSymbols( sourceSymbolElem );
    if ( sourceSymbolMap.contains( "0" ) )
    {
      r->setSourceSymbol( sourceSymbolMap.take( "0" ) );
    }
    QgsSymbolLayerV2Utils::clearSymbolMap( sourceSymbolMap );
  }

  // try to load color ramp (optional)
  QDomElement sourceColorRampElem = element.firstChildElement( "colorramp" );
  if ( !sourceColorRampElem.isNull() && sourceColorRampElem.attribute( "name" ) == "[source]" )
  {
    r->setSourceColorRamp( QgsSymbolLayerV2Utils::loadColorRamp( sourceColorRampElem ) );
    QDomElement invertedColorRampElem = element.firstChildElement( "invertedcolorramp" );
    if ( !invertedColorRampElem.isNull() )
      r->setInvertedColorRamp( invertedColorRampElem.attribute( "value" ) == "1" );
  }

  QDomElement rotationElem = element.firstChildElement( "rotation" );
  if ( !rotationElem.isNull() && !rotationElem.attribute( "field" ).isEmpty() )
  {
    QgsCategoryList::iterator it = r->mCategories.begin();
    for ( ; it != r->mCategories.end(); ++it )
    {
      convertSymbolRotation( it->symbol(), rotationElem.attribute( "field" ) );
    }
    if ( r->mSourceSymbol.data() )
    {
      convertSymbolRotation( r->mSourceSymbol.data(), rotationElem.attribute( "field" ) );
    }
  }

  QDomElement sizeScaleElem = element.firstChildElement( "sizescale" );
  if ( !sizeScaleElem.isNull() && !sizeScaleElem.attribute( "field" ).isEmpty() )
  {
    QgsCategoryList::iterator it = r->mCategories.begin();
    for ( ; it != r->mCategories.end(); ++it )
    {
      convertSymbolSizeScale( it->symbol(),
                              QgsSymbolLayerV2Utils::decodeScaleMethod( sizeScaleElem.attribute( "scalemethod" ) ),
                              sizeScaleElem.attribute( "field" ) );
    }
    if ( r->mSourceSymbol.data() && r->mSourceSymbol->type() == QgsSymbolV2::Marker )
    {
      convertSymbolSizeScale( r->mSourceSymbol.data(),
                              QgsSymbolLayerV2Utils::decodeScaleMethod( sizeScaleElem.attribute( "scalemethod" ) ),
                              sizeScaleElem.attribute( "field" ) );
    }
  }

  // TODO: symbol levels
  return r;
}
Ejemplo n.º 18
0
bool QgsWcsCapabilities::parseCapabilitiesDom( QByteArray const &xml, QgsWcsCapabilitiesProperty &capabilities )
{
  QgsDebugMsg( "Entered." );
#ifdef QGISDEBUG
  QFile file( QDir::tempPath() + "/qgis-wcs-capabilities.xml" );
  if ( file.open( QIODevice::WriteOnly ) )
  {
    file.write( xml );
    file.close();
  }
#endif

  if ( ! convertToDom( xml ) ) return false;

  QDomElement docElem = mCapabilitiesDom.documentElement();

  // Assert that the DTD is what we expected (i.e. a WCS Capabilities document)
  QgsDebugMsg( "testing tagName " + docElem.tagName() );

  QString tagName = stripNS( docElem.tagName() );
  if (
    // We don't support 1.0, but try WCS_Capabilities tag to get version
    tagName != "WCS_Capabilities" && // 1.0
    tagName != "Capabilities"  // 1.1, tags seen: Capabilities, wcs:Capabilities
  )
  {
    if ( tagName == "ExceptionReport" )
    {
      mErrorTitle = tr( "Exception" );
      mErrorFormat = "text/plain";
      mError = tr( "Could not get WCS capabilities: %1" ).arg( domElementText( docElem, "Exception.ExceptionText" ) );
    }
    else
    {
      mErrorTitle = tr( "Dom Exception" );
      mErrorFormat = "text/plain";
      mError = tr( "Could not get WCS capabilities in the expected format (DTD): no %1 found.\nThis might be due to an incorrect WCS Server URL.\nTag:%3\nResponse was:\n%4" )
               .arg( "Capabilities" )
               .arg( docElem.tagName() )
               .arg( QString( xml ) );
    }

    QgsLogger::debug( "Dom Exception: " + mError );

    return false;
  }

  capabilities.version = docElem.attribute( "version" );
  mVersion = capabilities.version;

  if ( !mVersion.startsWith( "1.0" ) && !mVersion.startsWith( "1.1" ) )
  {
    mErrorTitle = tr( "Version not supported" );
    mErrorFormat = "text/plain";
    mError = tr( "WCS server version %1 is not supported by QGIS (supported versions: 1.0.0, 1.1.0, 1.1.2)" )
             .arg( mVersion );

    QgsLogger::debug( "WCS version: " + mError );

    return false;
  }

  if ( mVersion.startsWith( "1.0" ) )
  {
    capabilities.title = domElementText( docElem, "Service.name" );
    capabilities.abstract = domElementText( docElem, "Service.description" );
    // There is also "label" in 1.0

    capabilities.getCoverageGetUrl = domElement( docElem, "Capability.Request.GetCoverage.DCPType.HTTP.Get.OnlineResource" ).attribute( "xlink:href" );

    parseContentMetadata( domElement( docElem, "ContentMetadata" ), capabilities.contents );
  }
  else if ( mVersion.startsWith( "1.1" ) )
  {
    capabilities.title = domElementText( docElem, "ServiceIdentification.Title" );
    capabilities.abstract = domElementText( docElem, "ServiceIdentification.Abstract" );

    QList<QDomElement> operationElements = domElements( docElem, "OperationsMetadata.Operation" );
    Q_FOREACH ( const QDomElement& el, operationElements )
    {
      if ( el.attribute( "name" ) == "GetCoverage" )
      {
        capabilities.getCoverageGetUrl = domElement( el, "DCP.HTTP.Get" ).attribute( "xlink:href" );
      }
    }

    parseCoverageSummary( domElement( docElem, "Contents" ), capabilities.contents );
  }
Ejemplo n.º 19
0
void QgsWfsCapabilities::capabilitiesReplyFinished()
{
  const QByteArray &buffer = mResponse;

  QgsDebugMsg( "parsing capabilities: " + buffer );

  // parse XML
  QString capabilitiesDocError;
  QDomDocument capabilitiesDocument;
  if ( !capabilitiesDocument.setContent( buffer, true, &capabilitiesDocError ) )
  {
    mErrorCode = QgsWfsRequest::XmlError;
    mErrorMessage = capabilitiesDocError;
    emit gotCapabilities();
    return;
  }

  QDomElement doc = capabilitiesDocument.documentElement();

  // handle exceptions
  if ( doc.tagName() == QLatin1String( "ExceptionReport" ) )
  {
    QDomNode ex = doc.firstChild();
    QString exc = ex.toElement().attribute( QStringLiteral( "exceptionCode" ), QStringLiteral( "Exception" ) );
    QDomElement ext = ex.firstChild().toElement();
    mErrorCode = QgsWfsRequest::ServerExceptionError;
    mErrorMessage = exc + ": " + ext.firstChild().nodeValue();
    emit gotCapabilities();
    return;
  }

  mCaps.clear();

  //test wfs version
  mCaps.version = doc.attribute( QStringLiteral( "version" ) );
  if ( !mCaps.version.startsWith( QLatin1String( "1.0" ) ) &&
       !mCaps.version.startsWith( QLatin1String( "1.1" ) ) &&
       !mCaps.version.startsWith( QLatin1String( "2.0" ) ) )
  {
    mErrorCode = WFSVersionNotSupported;
    mErrorMessage = tr( "WFS version %1 not supported" ).arg( mCaps.version );
    emit gotCapabilities();
    return;
  }

  // WFS 2.0 implementation are supposed to implement resultType=hits, and some
  // implementations (GeoServer) might advertize it, whereas others (MapServer) do not.
  // WFS 1.1 implementation too I think, but in the examples of the GetCapabilities
  // response of the WFS 1.1 standard (and in common implementations), this is
  // explicitly advertized
  if ( mCaps.version.startsWith( QLatin1String( "2.0" ) ) )
    mCaps.supportsHits = true;

  // Note: for conveniency, we do not use the elementsByTagNameNS() method as
  // the WFS and OWS namespaces URI are not the same in all versions

  if ( mCaps.version.startsWith( QLatin1String( "1.0" ) ) )
  {
    QDomElement capabilityElem = doc.firstChildElement( QStringLiteral( "Capability" ) );
    if ( !capabilityElem.isNull() )
    {
      QDomElement requestElem = capabilityElem.firstChildElement( QStringLiteral( "Request" ) );
      if ( !requestElem.isNull() )
      {
        QDomElement getFeatureElem = requestElem.firstChildElement( QStringLiteral( "GetFeature" ) );
        if ( !getFeatureElem.isNull() )
        {
          QDomElement resultFormatElem = getFeatureElem.firstChildElement( QStringLiteral( "ResultFormat" ) );
          if ( !resultFormatElem.isNull() )
          {
            QDomElement child = resultFormatElem.firstChildElement();
            while ( !child.isNull() )
            {
              mCaps.outputFormats << child.tagName();
              child = child.nextSiblingElement();
            }
          }
        }
      }
    }
  }

  // find <ows:OperationsMetadata>
  QDomElement operationsMetadataElem = doc.firstChildElement( QStringLiteral( "OperationsMetadata" ) );
  if ( !operationsMetadataElem.isNull() )
  {
    QDomNodeList contraintList = operationsMetadataElem.elementsByTagName( QStringLiteral( "Constraint" ) );
    for ( int i = 0; i < contraintList.size(); ++i )
    {
      QDomElement contraint = contraintList.at( i ).toElement();
      if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "DefaultMaxFeatures" ) /* WFS 1.1 */ )
      {
        QDomElement value = contraint.firstChildElement( QStringLiteral( "Value" ) );
        if ( !value.isNull() )
        {
          mCaps.maxFeatures = value.text().toInt();
          QgsDebugMsg( QString( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) );
        }
      }
      else if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "CountDefault" ) /* WFS 2.0 (e.g. MapServer) */ )
      {
        QDomElement value = contraint.firstChildElement( QStringLiteral( "DefaultValue" ) );
        if ( !value.isNull() )
        {
          mCaps.maxFeatures = value.text().toInt();
          QgsDebugMsg( QString( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) );
        }
      }
      else if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "ImplementsResultPaging" ) /* WFS 2.0 */ )
      {
        QDomElement value = contraint.firstChildElement( QStringLiteral( "DefaultValue" ) );
        if ( !value.isNull() && value.text() == QLatin1String( "TRUE" ) )
        {
          mCaps.supportsPaging = true;
          QgsDebugMsg( "Supports paging" );
        }
      }
      else if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "ImplementsStandardJoins" ) ||
                contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "ImplementsSpatialJoins" ) /* WFS 2.0 */ )
      {
        QDomElement value = contraint.firstChildElement( QStringLiteral( "DefaultValue" ) );
        if ( !value.isNull() && value.text() == QLatin1String( "TRUE" ) )
        {
          mCaps.supportsJoins = true;
          QgsDebugMsg( "Supports joins" );
        }
      }
    }

    // In WFS 2.0, max features can also be set in Operation.GetFeature (e.g. GeoServer)
    // and we are also interested by resultType=hits for WFS 1.1
    QDomNodeList operationList = operationsMetadataElem.elementsByTagName( QStringLiteral( "Operation" ) );
    for ( int i = 0; i < operationList.size(); ++i )
    {
      QDomElement operation = operationList.at( i ).toElement();
      if ( operation.attribute( QStringLiteral( "name" ) ) == QLatin1String( "GetFeature" ) )
      {
        QDomNodeList operationContraintList = operation.elementsByTagName( QStringLiteral( "Constraint" ) );
        for ( int j = 0; j < operationContraintList.size(); ++j )
        {
          QDomElement contraint = operationContraintList.at( j ).toElement();
          if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "CountDefault" ) )
          {
            QDomElement value = contraint.firstChildElement( QStringLiteral( "DefaultValue" ) );
            if ( !value.isNull() )
            {
              mCaps.maxFeatures = value.text().toInt();
              QgsDebugMsg( QString( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) );
            }
            break;
          }
        }

        QDomNodeList parameterList = operation.elementsByTagName( QStringLiteral( "Parameter" ) );
        for ( int j = 0; j < parameterList.size(); ++j )
        {
          QDomElement parameter = parameterList.at( j ).toElement();
          if ( parameter.attribute( QStringLiteral( "name" ) ) == QLatin1String( "resultType" ) )
          {
            QDomNodeList valueList = parameter.elementsByTagName( QStringLiteral( "Value" ) );
            for ( int k = 0; k < valueList.size(); ++k )
            {
              QDomElement value = valueList.at( k ).toElement();
              if ( value.text() == QLatin1String( "hits" ) )
              {
                mCaps.supportsHits = true;
                QgsDebugMsg( "Support hits" );
                break;
              }
            }
          }
          else if ( parameter.attribute( QStringLiteral( "name" ) ) == QLatin1String( "outputFormat" ) )
          {
            QDomNodeList valueList = parameter.elementsByTagName( QStringLiteral( "Value" ) );
            for ( int k = 0; k < valueList.size(); ++k )
            {
              QDomElement value = valueList.at( k ).toElement();
              mCaps.outputFormats << value.text();
            }
          }
        }

        break;
      }
    }
  }

  //go to <FeatureTypeList>
  QDomElement featureTypeListElem = doc.firstChildElement( QStringLiteral( "FeatureTypeList" ) );
  if ( featureTypeListElem.isNull() )
  {
    emit gotCapabilities();
    return;
  }

  // Parse operations supported for all feature types
  bool insertCap = false;
  bool updateCap = false;
  bool deleteCap = false;
  // WFS < 2
  if ( mCaps.version.startsWith( QLatin1String( "1" ) ) )
  {
    parseSupportedOperations( featureTypeListElem.firstChildElement( QStringLiteral( "Operations" ) ),
                              insertCap,
                              updateCap,
                              deleteCap );
  }
  else // WFS 2.0.0 tested on GeoServer
  {
    QDomNodeList operationNodes = doc.elementsByTagName( "Operation" );
    for ( int i = 0; i < operationNodes.count(); i++ )
    {
      QDomElement operationElement = operationNodes.at( i ).toElement( );
      if ( operationElement.isElement( ) && "Transaction" == operationElement.attribute( "name" ) )
      {
        insertCap = true;
        updateCap = true;
        deleteCap = true;
      }
    }
  }

  // get the <FeatureType> elements
  QDomNodeList featureTypeList = featureTypeListElem.elementsByTagName( QStringLiteral( "FeatureType" ) );
  for ( int i = 0; i < featureTypeList.size(); ++i )
  {
    FeatureType featureType;
    QDomElement featureTypeElem = featureTypeList.at( i ).toElement();

    //Name
    QDomNodeList nameList = featureTypeElem.elementsByTagName( QStringLiteral( "Name" ) );
    if ( nameList.length() > 0 )
    {
      featureType.name = nameList.at( 0 ).toElement().text();
    }
    //Title
    QDomNodeList titleList = featureTypeElem.elementsByTagName( QStringLiteral( "Title" ) );
    if ( titleList.length() > 0 )
    {
      featureType.title = titleList.at( 0 ).toElement().text();
    }
    //Abstract
    QDomNodeList abstractList = featureTypeElem.elementsByTagName( QStringLiteral( "Abstract" ) );
    if ( abstractList.length() > 0 )
    {
      featureType.abstract = abstractList.at( 0 ).toElement().text();
    }

    //DefaultSRS is always the first entry in the feature srs list
    QDomNodeList defaultCRSList = featureTypeElem.elementsByTagName( QStringLiteral( "DefaultSRS" ) );
    if ( defaultCRSList.length() == 0 )
      // In WFS 2.0, this is spelled DefaultCRS...
      defaultCRSList = featureTypeElem.elementsByTagName( QStringLiteral( "DefaultCRS" ) );
    if ( defaultCRSList.length() > 0 )
    {
      QString srsname( defaultCRSList.at( 0 ).toElement().text() );
      // Some servers like Geomedia advertize EPSG:XXXX even in WFS 1.1 or 2.0
      if ( srsname.startsWith( QLatin1String( "EPSG:" ) ) )
        mCaps.useEPSGColumnFormat = true;
      featureType.crslist.append( NormalizeSRSName( srsname ) );
    }

    //OtherSRS
    QDomNodeList otherCRSList = featureTypeElem.elementsByTagName( QStringLiteral( "OtherSRS" ) );
    if ( otherCRSList.length() == 0 )
      // In WFS 2.0, this is spelled OtherCRS...
      otherCRSList = featureTypeElem.elementsByTagName( QStringLiteral( "OtherCRS" ) );
    for ( int i = 0; i < otherCRSList.size(); ++i )
    {
      featureType.crslist.append( NormalizeSRSName( otherCRSList.at( i ).toElement().text() ) );
    }

    //Support <SRS> for compatibility with older versions
    QDomNodeList srsList = featureTypeElem.elementsByTagName( QStringLiteral( "SRS" ) );
    for ( int i = 0; i < srsList.size(); ++i )
    {
      featureType.crslist.append( NormalizeSRSName( srsList.at( i ).toElement().text() ) );
    }

    // Get BBox WFS 1.0 way
    QDomElement latLongBB = featureTypeElem.firstChildElement( QStringLiteral( "LatLongBoundingBox" ) );
    if ( latLongBB.hasAttributes() )
    {
      // Despite the name LatLongBoundingBox, the coordinates are supposed to
      // be expressed in <SRS>. From the WFS schema;
      // <!-- The LatLongBoundingBox element is used to indicate the edges of
      // an enclosing rectangle in the SRS of the associated feature type.
      featureType.bbox = QgsRectangle(
                           latLongBB.attribute( QStringLiteral( "minx" ) ).toDouble(),
                           latLongBB.attribute( QStringLiteral( "miny" ) ).toDouble(),
                           latLongBB.attribute( QStringLiteral( "maxx" ) ).toDouble(),
                           latLongBB.attribute( QStringLiteral( "maxy" ) ).toDouble() );
      featureType.bboxSRSIsWGS84 = false;

      // But some servers do not honour this and systematically reproject to WGS84
      // such as GeoServer. See http://osgeo-org.1560.x6.nabble.com/WFS-LatLongBoundingBox-td3813810.html
      // This is also true of TinyOWS
      if ( !featureType.crslist.isEmpty() &&
           featureType.bbox.xMinimum() >= -180 && featureType.bbox.yMinimum() >= -90 &&
           featureType.bbox.xMaximum() <= 180 && featureType.bbox.yMaximum() < 90 )
      {
        QgsCoordinateReferenceSystem crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( featureType.crslist[0] );
        if ( !crs.isGeographic() )
        {
          // If the CRS is projected then check that projecting the corner of the bbox, assumed to be in WGS84,
          // into the CRS, and then back to WGS84, works (check that we are in the validity area)
          QgsCoordinateReferenceSystem crsWGS84 = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "CRS:84" ) );
          QgsCoordinateTransform ct( crsWGS84, crs );

          QgsPointXY ptMin( featureType.bbox.xMinimum(), featureType.bbox.yMinimum() );
          QgsPointXY ptMinBack( ct.transform( ct.transform( ptMin, QgsCoordinateTransform::ForwardTransform ), QgsCoordinateTransform::ReverseTransform ) );
          QgsPointXY ptMax( featureType.bbox.xMaximum(), featureType.bbox.yMaximum() );
          QgsPointXY ptMaxBack( ct.transform( ct.transform( ptMax, QgsCoordinateTransform::ForwardTransform ), QgsCoordinateTransform::ReverseTransform ) );

          QgsDebugMsg( featureType.bbox.toString() );
          QgsDebugMsg( ptMinBack.toString() );
          QgsDebugMsg( ptMaxBack.toString() );

          if ( fabs( featureType.bbox.xMinimum() - ptMinBack.x() ) < 1e-5 &&
               fabs( featureType.bbox.yMinimum() - ptMinBack.y() ) < 1e-5 &&
               fabs( featureType.bbox.xMaximum() - ptMaxBack.x() ) < 1e-5 &&
               fabs( featureType.bbox.yMaximum() - ptMaxBack.y() ) < 1e-5 )
          {
            QgsDebugMsg( "Values of LatLongBoundingBox are consistent with WGS84 long/lat bounds, so as the CRS is projected, assume they are indeed in WGS84 and not in the CRS units" );
            featureType.bboxSRSIsWGS84 = true;
          }
        }
      }
    }
    else
    {
      // WFS 1.1 way
      QDomElement WGS84BoundingBox = featureTypeElem.firstChildElement( QStringLiteral( "WGS84BoundingBox" ) );
      if ( !WGS84BoundingBox.isNull() )
      {
        QDomElement lowerCorner = WGS84BoundingBox.firstChildElement( QStringLiteral( "LowerCorner" ) );
        QDomElement upperCorner = WGS84BoundingBox.firstChildElement( QStringLiteral( "UpperCorner" ) );
        if ( !lowerCorner.isNull() && !upperCorner.isNull() )
        {
          QStringList lowerCornerList = lowerCorner.text().split( QStringLiteral( " " ), QString::SkipEmptyParts );
          QStringList upperCornerList = upperCorner.text().split( QStringLiteral( " " ), QString::SkipEmptyParts );
          if ( lowerCornerList.size() == 2 && upperCornerList.size() == 2 )
          {
            featureType.bbox = QgsRectangle(
                                 lowerCornerList[0].toDouble(),
                                 lowerCornerList[1].toDouble(),
                                 upperCornerList[0].toDouble(),
                                 upperCornerList[1].toDouble() );
            featureType.bboxSRSIsWGS84 = true;
          }
        }
      }
    }

    // Parse Operations specific to the type name
    parseSupportedOperations( featureTypeElem.firstChildElement( QStringLiteral( "Operations" ) ),
                              featureType.insertCap,
                              featureType.updateCap,
                              featureType.deleteCap );
    featureType.insertCap |= insertCap;
    featureType.updateCap |= updateCap;
    featureType.deleteCap |= deleteCap;

    mCaps.featureTypes.push_back( featureType );
  }

  Q_FOREACH ( const FeatureType &f, mCaps.featureTypes )
  {
    mCaps.setAllTypenames.insert( f.name );
    QString unprefixed( QgsWFSUtils::removeNamespacePrefix( f.name ) );
    if ( !mCaps.setAmbiguousUnprefixedTypename.contains( unprefixed ) )
    {
      if ( mCaps.mapUnprefixedTypenameToPrefixedTypename.contains( unprefixed ) )
      {
        mCaps.setAmbiguousUnprefixedTypename.insert( unprefixed );
        mCaps.mapUnprefixedTypenameToPrefixedTypename.remove( unprefixed );
      }
      else
      {
        mCaps.mapUnprefixedTypenameToPrefixedTypename[unprefixed] = f.name;
      }
    }
  }

  //go to <Filter_Capabilities>
  QDomElement filterCapabilitiesElem = doc.firstChildElement( QStringLiteral( "Filter_Capabilities" ) );
  if ( !filterCapabilitiesElem.isNull() )
    parseFilterCapabilities( filterCapabilitiesElem );

  // Hard-coded functions
  Function f_ST_GeometryFromText( QStringLiteral( "ST_GeometryFromText" ), 1, 2 );
  f_ST_GeometryFromText.returnType = QStringLiteral( "gml:AbstractGeometryType" );
  f_ST_GeometryFromText.argumentList << Argument( QStringLiteral( "wkt" ), QStringLiteral( "xs:string" ) );
  f_ST_GeometryFromText.argumentList << Argument( QStringLiteral( "srsname" ), QStringLiteral( "xs:string" ) );
  mCaps.functionList << f_ST_GeometryFromText;

  Function f_ST_GeomFromGML( QStringLiteral( "ST_GeomFromGML" ), 1 );
  f_ST_GeomFromGML.returnType = QStringLiteral( "gml:AbstractGeometryType" );
  f_ST_GeomFromGML.argumentList << Argument( QStringLiteral( "gml" ), QStringLiteral( "xs:string" ) );
  mCaps.functionList << f_ST_GeomFromGML;

  Function f_ST_MakeEnvelope( QStringLiteral( "ST_MakeEnvelope" ), 4, 5 );
  f_ST_MakeEnvelope.returnType = QStringLiteral( "gml:AbstractGeometryType" );
  f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "minx" ), QStringLiteral( "xs:double" ) );
  f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "miny" ), QStringLiteral( "xs:double" ) );
  f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "maxx" ), QStringLiteral( "xs:double" ) );
  f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "maxy" ), QStringLiteral( "xs:double" ) );
  f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "srsname" ), QStringLiteral( "xs:string" ) );
  mCaps.functionList << f_ST_MakeEnvelope;

  emit gotCapabilities();
}
Ejemplo n.º 20
0
bool Configuration::load() {
    QFile f(m_filePath);
    if (!f.exists()) {
        return false;
    }
    if (!f.open(QIODevice::ReadOnly)) {
        cerr << "Unable to open '" << m_filePath.toStdString() << "'" << endl;
        return false;
    }
    QDomDocument doc;
    if (!doc.setContent(&f)) {
        cerr << "Unable to load '" << m_filePath.toStdString() << "'" << endl;
        f.close();
        return false;
    }

    QDomElement e = doc.documentElement();
    if (e.tagName() == ROOT_TAG_NAME) {
        QDomElement profiles = e.firstChildElement(PROFILES_TAG_NAME);
        QDomElement pe = profiles.firstChildElement(PROFILE_TAG_NAME);
        while (!pe.isNull()) {
            bool ok = false;
            unsigned id = pe.attribute(ID_ATTR_NAME).toUInt(&ok);
            if (ok) {
                QString name = pe.attribute(NAME_ATTR_NAME);
                QDomNode n = pe.firstChild();
                Profile* p = new Profile(id, name);
                while (!n.isNull()) {
                    if (n.isElement()) {
                        QDomElement ae = n.toElement();
                        if (ae.tagName() == EXEC_TAG_NAME) {
                            p->setGPGExecutable(ae.text());
                        } else if (ae.tagName() == PATH_TAG_NAME) {
                            p->setConfigurationPath(ae.text());
                        } else if (ae.tagName() == VALIDITY_COLOR_TAG_NAME) {
                            QColor c(
                                        ae.attribute(RED_ATTRIBUTE).toInt(),
                                        ae.attribute(GREEN_ATTRIBUTE).toInt(),
                                        ae.attribute(BLUE_ATTRIBUTE).toInt()
                            );
                            p->setValidityColor((QString) ae.attribute(VALUE_ATTRIBUTE).toInt(), c);
                        } else if (ae.tagName() == SIG_COLOR_TAG_NAME) {
                            QColor c(
                                        ae.attribute(RED_ATTRIBUTE).toInt(),
                                        ae.attribute(GREEN_ATTRIBUTE).toInt(),
                                        ae.attribute(BLUE_ATTRIBUTE).toInt()
                            );
                            p->setSignatureColor(c);
                        }
                    }
                    n = n.nextSibling();
                }
                m_profiles.append(p);
            }
            pe = pe.nextSiblingElement(PROFILE_TAG_NAME);
        }
        bool ok = false;
        unsigned defaultProfileId = profiles.attribute(DEFAULT_PROFILE_ATTR_NAME).toUInt(&ok);
        if (ok) {
            setDefaultProfileId(defaultProfileId);
        }
    }
    f.close();
    return true;
}
Ejemplo n.º 21
0
bool MainWindow2::openObject( QString strFilePath )
{
    QProgressDialog progress( tr("Opening document..."), tr("Abort"), 0, 100, this );
    progress.setWindowModality( Qt::WindowModal );
    progress.show();

    editor->setCurrentLayer( 0 );
    editor->layerManager()->setCurrentFrameIndex( 1 );
    editor->fps = 12;
    m_pTimeLine->setFps( editor->fps );
    m_pScribbleArea->setMyView( QMatrix() );

    ObjectSaveLoader objectLoader( this );
    Object* pObject = objectLoader.loadFromFile( strFilePath );

    if ( pObject != NULL && objectLoader.error().code() == PCL_OK )
    {
        SafeDelete( m_object );
        m_object = pObject;

        pObject->setFilePath( strFilePath );
        QSettings settings( "Pencil", "Pencil" );
        settings.setValue( "lastFilePath", QVariant( pObject->filePath() ) );

        editor->setObject( pObject );
        editor->updateObject();

        m_recentFileMenu->addRecentFile( pObject->filePath() );
        m_recentFileMenu->saveToDisk();

        qDebug() << "Current File Path=" << pObject->filePath();
        setWindowTitle( pObject->filePath() );
    }
    else
    {
        return false;
    }
    return true;

    //-------------------
    QString filePath = strFilePath;

    bool openingTheOLDWAY = true;
    QString realXMLFilePath = filePath;
    QString tmpFilePath;

    // ---- test before opening ----
    QStringList zippedFileList = JlCompress::getFileList( filePath );
    if ( !zippedFileList.empty() )
    {
        qDebug() << "Recognized New zipped Pencil File Format !";
        openingTheOLDWAY = false;

        // ---- now decompress PFF -----
        QFileInfo fileInfo( filePath );
        QDir dir( QDir::tempPath() );
        tmpFilePath = QDir::tempPath() + "/" + fileInfo.completeBaseName() + PFF_TMP_DECOMPRESS_EXT;
        if ( fileInfo.exists() ) {
            dir.rmpath( tmpFilePath ); // --removes an old decompression directory
            removePFFTmpDirectory( tmpFilePath ); // --removes an old decompression directory - better approach
        }
        dir.mkpath( tmpFilePath ); // --creates a new decompression directory

        JlCompress::extractDir( filePath, tmpFilePath );

        realXMLFilePath = tmpFilePath + "/" + PFF_XML_FILE_NAME;
    }
    else
    {
        qDebug() << "Recognized Old Pencil File Format !";
    }

    QScopedPointer<QFile> file( new QFile( realXMLFilePath ) );

    //QFile* file = new QFile(filePath);
    if ( !file->open( QFile::ReadOnly ) )
    {
        if ( !openingTheOLDWAY )
        {
            removePFFTmpDirectory( tmpFilePath ); // --removes temporary decompression directory
        }
        return false;
    }

    QDomDocument doc;
    if ( !doc.setContent( file.data() ) )
    {
        if ( !openingTheOLDWAY )
        {
            removePFFTmpDirectory( tmpFilePath ); // --removes temporary decompression directory
        }
        return false; // this is not a XML file
    }
    QDomDocumentType type = doc.doctype();
    if ( type.name() != "PencilDocument" && type.name() != "MyObject" )
    {
        if ( !openingTheOLDWAY )
        {
            removePFFTmpDirectory( tmpFilePath ); // --removes temporary decompression directory
        }
        return false; // this is not a Pencil document
    }

    // delete old object @sent foreward -> if (ok)
    /*if (m_object != NULL)
    {
    m_object->deleteLater();
    }*/

    // -----------------------------


    //QSettings settings("Pencil","Pencil");
    //settings.setValue("lastFilePath", QVariant(object->strCurrentFilePath) );

    QString dataLayersDir;
    if ( openingTheOLDWAY )
    {
        dataLayersDir = filePath + "." + PFF_LAYERS_DIR;
    }
    else
    {
        dataLayersDir = tmpFilePath + "/" + PFF_LAYERS_DIR;
    }

    Object* newObject = new Object();
    if ( !newObject->loadPalette( dataLayersDir ) )
    {
        newObject->loadDefaultPalette();
    }
    editor->setObject( newObject );

    newObject->setFilePath( filePath );

    // ------- reads the XML file -------
    bool ok = true;
    int progVal = 0;
    QDomElement docElem = doc.documentElement();
    if ( docElem.isNull() )
    {
        return false;
    }

    if ( docElem.tagName() == "document" )
    {
        qDebug( "Object Loader: start." );

        qreal rProgressValue = 0;
        qreal rProgressDelta = 100 / docElem.childNodes().count();

        QDomNode tag = docElem.firstChild();

        while ( !tag.isNull() )
        {
            QDomElement element = tag.toElement(); // try to convert the node to an element.
            if ( !element.isNull() )
            {
                progVal = qMin( (int)rProgressValue, 100 );
                progress.setValue( progVal );
                rProgressValue += rProgressDelta;

                if ( element.tagName() == "editor" )
                {
                    qDebug( "  Load editor" );
                    loadDomElement( element, filePath );
                }
                else if ( element.tagName() == "object" )
                {
                    qDebug( "  Load object" );
                    ok = newObject->loadDomElement( element, dataLayersDir );
                    qDebug() << "    dataDir:" << dataLayersDir;
                }
            }
            tag = tag.nextSibling();
        }
    }
    else
    {
        if ( docElem.tagName() == "object" || docElem.tagName() == "MyOject" )   // old Pencil format (<=0.4.3)
        {
            ok = newObject->loadDomElement( docElem, filePath );
        }
    }

    // ------------------------------
    if ( ok )
    {
        editor->updateObject();

        if ( !openingTheOLDWAY )
        {
            removePFFTmpDirectory( tmpFilePath ); // --removes temporary decompression directory
        }

        m_recentFileMenu->addRecentFile( filePath );
        m_recentFileMenu->saveToDisk();

        //qDebug() << "Current File Path=" << newObject->strCurrentFilePath;
        setWindowTitle( newObject->filePath() );

        // FIXME: need to free the old object. but delete object will crash app, don't know why.
        // fixed by shoshon... don't know if it's right
        Object* objectToDelete = m_object;
        m_object = newObject;
        if ( objectToDelete != NULL )
        {
            delete objectToDelete;
        }
    }

    progress.setValue( 100 );
    return true;
}
  /**
   * Init the action pattern from the XML description of the policy.
   *
   * @param _node Node within the XML-Tree containing the behaviour.
   * @param _apMap Map of the other existing action patterns of the policy,
   * for transition links.
   */
  void
  ActionPattern::xmlInit(const QDomNode& _node, const ActionPatternMap& _apMap) 
  {
    ArbiterRepository * ar = ArbiterRepository::instance();
    BehaviourRepository * br = BehaviourRepository::instance();

    // first pass
    // retrieve arbiter

    // we need it to register the behaviours there

    QDomNode n = _node.firstChild();
    while( !n.isNull() ) {
      QDomElement e = n.toElement(); // try to convert the node to an element.
      if( !e.isNull() ) {            // the node was really an element.

	QDomAttr attribute = e.attributeNode("name");

	// retrieve arbiter
	if (e.tagName()=="arbiter") {
	  if (arbiter_ == NULL) {
	    if (!attribute.isNull() && !attribute.value().isEmpty()) {
	      std::string name(attribute.value().latin1());
	      Arbiter* a;
	      if ((a = ar->getArbiter(name)) != 0) {
		ArbiterParameters * params = a->getParametersInstance();
		arbiter(a, params);
		
	      } 
	      else {
		std::string error("Arbiter not registered: " + name);
		throw BehaviourEngine:: EMalformedPolicy(CORBA::string_dup(error.c_str()));
	      }
	    } 
	    else {
	      throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup("Arbiter without name."));
	    }
	  }
	  else {
	   throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup("Multiple arbiters specified."));
	  }
	}
	// syntax checking 
	else if (e.tagName() != "behaviour" && e.tagName() != "transition") {
	  std::string error("Unknown tag name: " + 
		            std::string(e.tagName().latin1()));
	  throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup(error.c_str()));
	}
      }
      n = n.nextSibling();
    }

    // There has to be exact one arbiter
    if (arbiter_ == NULL) {
      std::string error("ActionPattern without an arbiter: " + actionPatternName_);
      throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup(error.c_str()));
    }
    
    // second pass 
    // retrieve behaviours and transitions
    
    n = _node.firstChild();
    while( !n.isNull() ) {
      QDomElement e = n.toElement(); // try to convert the node to an element.
      if( !e.isNull() ) {            // the node was really an element.

	QDomAttr attribute = e.attributeNode("name");

	// retrieve behaviours
	if (e.tagName() == "behaviour") {
	  if (!attribute.isNull() && !attribute.value().isEmpty()) {
	    std::string name(attribute.value().latin1());

	    Behaviour * behaviour;
	    BehaviourParameters * parameters;
	    if ((behaviour = br->getBehaviour(name)) != NULL) {
	      parameters = behaviour->getParametersInstance();

	      *parameters <<= n;
	      addBehaviour(behaviour, parameters);
	    } 
	    else {
	      std::string error("Behaviour not registered: " + name);
	      throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup(error.c_str()));
	    }
	  } 
	  else {
	    throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup("Behaviour without name."));		
	  }
	}

	// retrieve transitions
	else if (e.tagName() == "transition") {
	  QDomAttr attrMessage = e.attributeNode("message");
	  std::string message;

	  if (!attrMessage.isNull() && !attrMessage.value().isEmpty()) {
	    message = std::string(attrMessage.value().latin1());
	  } 
	  else {
	    throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup("Transition without message."));
	  }
	  
	  QDomAttr attrPattern = e.attributeNode("target");
	  if (!attrPattern.isNull() && !attrPattern.value().isEmpty()) {
	    std::string patternname(attrPattern.value().latin1());
	    ActionPatternMap::const_iterator iter = _apMap.find(patternname);

	    if (iter != _apMap.end())
	      addTransition(message, iter->second);
	    else {
	      std::string error("ActionPattern for transition not registered: " + 
				message + " --> " + patternname + ".");
	      throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup(error.c_str()));
	    }
	  }
	  else
	    throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup("Transition without target."));
	}
      }
      n = n.nextSibling();
    }
  }
Ejemplo n.º 23
0
bool LH_MonitoringSource_Aida64::doUpdate()
{
#ifdef Q_OS_WIN
    bool resultVal = true;

    const char* mapnameAida64  = "AIDA64_SensorValues";
    const char* mapnameEverest  = "EVEREST_SensorValues";

    // Create file mapping
    HANDLE filemap = (HANDLE)OpenFileMappingA(FILE_MAP_READ,0,mapnameAida64);
    if(filemap == NULL)
        filemap = (HANDLE)OpenFileMappingA(FILE_MAP_READ,0,mapnameEverest);

    setDataAvailable(filemap != NULL);
    if(dataAvailable())
    {
        char* aidaData = (char*)MapViewOfFile(filemap, FILE_MAP_READ, 0, 0, 0);
        if (aidaData) {
            aidaXml_.setContent(QString("<data>%1</data>").arg(QString(aidaData)));

            QRegExp rx = QRegExp("([^0-9]*)([0-9]+#?\\s?)(.*)");
            rx.setPatternSyntax(QRegExp::RegExp2);

            QDomNode n = aidaXml_.documentElement().firstChild();
            while(!n.isNull()) {
                QDomElement e = n.toElement(); // try to convert the node to an element.
                if(!e.isNull()) {
                    QDomNodeList labelNodes = e.elementsByTagName("label");
                    QDomNodeList valueNodes = e.elementsByTagName("value");

                    if(labelNodes.count()==1 && valueNodes.count()==1)
                    {

                        QString typeName = e.tagName();
                        QString itemName = labelNodes.at(0).toElement().text();
                        QString groupName = (rx.indexIn(reverse(itemName))==-1 ? itemName : reverse(rx.cap(3)) + reverse(rx.cap(1)) );
                        QString valueString = valueNodes.at(0).toElement().text();
                        QString units="";

                        if(typeName=="sys")
                        {
                            typeName = "System";
                            if (itemName.endsWith("FSB")) units="mhz";
                            if (itemName.endsWith("Clock")) units="mhz";
                            if (itemName.endsWith("Utilization")) units="%";
                            if (itemName.endsWith("Memory")) units="MB";
                        }
                        if(typeName=="temp")
                        {
                            typeName = "Temperatures";
                            units=QLatin1Literal("\260C");
                        }
                        if(typeName=="fan")
                        {
                            typeName = "Cooling Fans";
                            units="rpm";
                        }
                        if(typeName=="duty")
                        {
                            typeName = "Fan Speeds";
                        }
                        if(typeName=="volt")
                        {
                            typeName = "Voltage Values";
                            units="V";
                        }

                        bool ok;
                        double valueDouble = valueString.toDouble(&ok);
                        if(ok)
                            updateValue(typeName,groupName,itemName, valueDouble, SensorDefinition(units));
                        else
                            updateValue(typeName,groupName,itemName, valueString, SensorDefinition(units));
                    }
                }
                n = n.nextSibling();
            }


            UnmapViewOfFile(aidaData);
        }
        else
            resultVal = false;
        CloseHandle(filemap);
    }
    else
        resultVal = false;

    return resultVal;
#else
    return false;
#endif
}
Ejemplo n.º 24
0
void FilterChoice::initUI()
{
  QDialogButtonBox *buttonBox;
  QLabel *label;
  QLabel *label_2;

  this->setWindowTitle("FilterChoice");
  this->setMinimumSize(623, 374);
  buttonBox = new QDialogButtonBox(this);
  buttonBox->setGeometry(QRect(260, 310, 341, 32));
  buttonBox->setOrientation(Qt::Horizontal);
  buttonBox->setStandardButtons(QDialogButtonBox::Cancel);
  QPushButton* applyButton = buttonBox->addButton(QString::fromStdString("Apply"), QDialogButtonBox::ApplyRole);
  _deleteButton = buttonBox->addButton(QString::fromStdString("Delete"), QDialogButtonBox::ActionRole);
  _deleteButton->setGeometry(QRect(310, 310, 98, 27));
  _deleteButton->setEnabled(false);
  
  QObject::connect(applyButton, SIGNAL(clicked()), this, SLOT(validate()));
  QObject::connect(buttonBox, SIGNAL(rejected()), this, SLOT(cancel()));
  QObject::connect(_deleteButton, SIGNAL(clicked()), this, SLOT(deleteFilter()));
  
  label = new QLabel(this);
  label->setText("Blur:");
  label->setGeometry(QRect(70, 80, 66, 17));
  label_2 = new QLabel(this);
  label_2->setText("Policy");
  label_2->setGeometry(QRect(60, 150, 66, 17));
  _labelNumber = new QLabel(this);
  _labelNumber->setText("Number of pixels:");
  _labelNumber->setGeometry(QRect(30, 220, 241, 17));
  _number = new QSpinBox(this);
  _number->setValue(3);
  _number->setMinimum(1);
  _number->setGeometry(QRect(170, 210, 60, 27));
  
  QObject::connect(_number, SIGNAL(valueChanged(const QString&)), this, SLOT(dataChanged(const QString&)));
  
  /* INIT FILTER */
  _filterView = new QTableWidget(3, 3, this);
  _filterView->setGeometry(QRect(300, 20, 311, 281));
  _filterView->verticalHeader()->hide();
  _filterView->horizontalHeader()->hide();
  _filterView->setDragEnabled(false);
  _filterView->setCornerButtonEnabled(false);
  
  int numPixels = _number->value();
  for(int i = 0; i < numPixels; i++)
  {
    _filterView->setColumnWidth(i, _filterView->rowHeight(0));
    for(int j = 0; j < numPixels; j++)
    {
      QTableWidgetItem* item = new QTableWidgetItem("1");
      item->setTextAlignment(Qt::AlignHCenter);
      item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
      _filterView->setItem(i, j, item);
    }
  }
  
  /* BLUR CHOICE */
  _blurChoices = new QComboBox(this);
  _blurChoices->setGeometry(QRect(140, 80, 141, 27));
  
  QStringList blurs = QStringList();
  blurs.push_back("Uniform");
  blurs.push_back("Gaussian");
  blurs.push_back("Prewitt");
  blurs.push_back("Roberts");
  blurs.push_back("Sobel");
  blurs.push_back("SquareLaplacien");
  
  _filters.push_back(Filter::uniform(3));
  _filters.push_back(Filter::gaussian(1));
  _filters.push_back(Filter::prewitt(3));
  _filters.push_back(Filter::roberts());
  _filters.push_back(Filter::sobel());
  _filters.push_back(Filter::squareLaplacien());
  
  //Personal filters
  QFile file("filters.xml");
  if(file.exists())
  {
    QDomDocument doc("");
    file.open(QIODevice::ReadOnly);
	  doc.setContent(&file);
	  file.close();
    
    QDomElement root = doc.documentElement();
    QDomNode child = root.firstChild();
	  while(!child.isNull())
	  {
      QDomElement e = child.toElement();
	    // We know how to treat appearance and geometry
      blurs.push_back(e.attribute("name"));
      
      int nbFilters = e.attribute("nbFilters").toInt();
      
      std::vector<Filter*> temp;
      QDomNode grandChild = e.firstChild();
      for(int i = 0; i < nbFilters && !grandChild.isNull(); i++)
      {
        QDomElement grandChildElement = grandChild.toElement();
        if(!grandChildElement.isNull())
        {
          Filter* f = new Filter(grandChildElement.attribute("width").toInt(), grandChildElement.attribute("height").toInt());
          // We know how to treat color
          if (grandChildElement.tagName() == "values")
          {
            std::string str = grandChildElement.text().toStdString();
            std::string word;
            std::stringstream stream(str);
            int w = 0, h = 0;
            while(getline(stream, word, ' '))
            {
              (*f)[w][h] = QString::fromStdString(word).toInt();
                            
              if(h == f->height() - 1)
              {
                h = 0;
                w++;
              }
              else
                h++;
            }
          }
          temp.push_back(f);
        }
        grandChild = grandChild.nextSibling();
      }
      _filters.push_back(temp);
      
      child = child.nextSibling();
	  }
  }
  _blurChoices->addItems(blurs);
  QObject::connect(_blurChoices, SIGNAL(currentIndexChanged(int)), this, SLOT(currentBlurChanged(int)));
  
  /* POLICIES CHOICE */
  _policyChoices = new QComboBox(this);
  _policyChoices->setGeometry(QRect(140, 150, 141, 27));
  
  QStringList policies = QStringList();
  policies.push_back("Black");
  policies.push_back("Mirror");
  policies.push_back("Nearest");
  policies.push_back("Spherical");
  _policyChoices->addItems(policies);
}
Ejemplo n.º 25
0
bool VCXYPad::loadXML(const QDomElement* root)
{
	bool visible = false;
	int x = 0;
	int y = 0;
	int w = 0;
	int h = 0;

	int xpos = 0;
	int ypos = 0;

	QDomNode node;
	QDomElement tag;
	QString str;

	Q_ASSERT(root != NULL);

	if (root->tagName() != KXMLQLCVCXYPad)
	{
		qDebug() << "XY Pad node not found!";
		return false;
	}

	/* Caption */
	setCaption(root->attribute(KXMLQLCVCCaption));

	/* Children */
	node = root->firstChild();
	while (node.isNull() == false)
	{
		tag = node.toElement();
		if (tag.tagName() == KXMLQLCWindowState)
		{
			QLCFile::loadXMLWindowState(&tag, &x, &y, &w, &h,
						    &visible);
		}
		else if (tag.tagName() == KXMLQLCVCAppearance)
		{
			loadXMLAppearance(&tag);
		}
		else if (tag.tagName() == KXMLQLCVCXYPadPosition)
		{
			str = tag.attribute(KXMLQLCVCXYPadPositionX);
			xpos = str.toInt();

			str = tag.attribute(KXMLQLCVCXYPadPositionY);
			ypos = str.toInt();
		}
		else if (tag.tagName() == KXMLQLCVCXYPadFixture)
		{
			VCXYPadFixture fxi;
			if (fxi.loadXML(&tag) == true)
				appendFixture(fxi);
		}
		else
		{
			qDebug() << "Unknown XY Pad tag:" << tag.tagName();
		}

		node = node.nextSibling();
	}

	/* First set window dimensions and AFTER that set the
	   pointer's XY position */
	setGeometry(x, y, w, h);
	setCurrentXYPosition(QPoint(xpos, ypos));

	return true;
}
Ejemplo n.º 26
0
bool Fixture::loadXML(const QDomElement& root,
                      const QLCFixtureDefCache* fixtureDefCache)
{
    const QLCFixtureDef* fixtureDef = NULL;
    const QLCFixtureMode* fixtureMode = NULL;
    QString manufacturer;
    QString model;
    QString modeName;
    QString name;
    quint32 id = Fixture::invalidId();
    quint32 universe = 0;
    quint32 address = 0;
    quint32 channels = 0;

    if (root.tagName() != KXMLFixture)
    {
        qWarning() << Q_FUNC_INFO << "Fixture node not found";
        return false;
    }

    QDomNode node = root.firstChild();
    while (node.isNull() == false)
    {
        QDomElement tag = node.toElement();

        if (tag.tagName() == KXMLQLCFixtureDefManufacturer)
        {
            manufacturer = tag.text();
        }
        else if (tag.tagName() == KXMLQLCFixtureDefModel)
        {
            model = tag.text();
        }
        else if (tag.tagName() == KXMLQLCFixtureMode)
        {
            modeName = tag.text();
        }
        else if (tag.tagName() == KXMLFixtureID)
        {
            id = tag.text().toUInt();
        }
        else if (tag.tagName() == KXMLFixtureName)
        {
            name = tag.text();
        }
        else if (tag.tagName() == KXMLFixtureUniverse)
        {
            universe = tag.text().toInt();
        }
        else if (tag.tagName() == KXMLFixtureAddress)
        {
            address = tag.text().toInt();
        }
        else if (tag.tagName() == KXMLFixtureChannels)
        {
            channels = tag.text().toInt();
        }
        else
        {
            qWarning() << Q_FUNC_INFO << "Unknown fixture tag:" << tag.tagName();
        }

        node = node.nextSibling();
    }

    /* Find the given fixture definition, unless its a generic dimmer */
    if (manufacturer != KXMLFixtureGeneric && model != KXMLFixtureGeneric)
    {
        fixtureDef = fixtureDefCache->fixtureDef(manufacturer, model);
        if (fixtureDef == NULL)
        {
            qWarning() << Q_FUNC_INFO << "No fixture definition for"
                       << manufacturer << model;
        }
        else
        {
            /* Find the given fixture mode */
            fixtureMode = fixtureDef->mode(modeName);
            if (fixtureMode == NULL)
            {
                qWarning() << Q_FUNC_INFO << "Fixture mode" << modeName
                           << "for" << manufacturer << model << "not found";

                /* Set this also NULL so that a generic dimmer will be
                   created instead as a backup. */
                fixtureDef = NULL;
            }
        }
    }

    /* Number of channels */
    if (channels <= 0)
    {
        qWarning() << Q_FUNC_INFO << "Fixture" << name << "channels"
                   << channels << "out of bounds";
        channels = 1;
    }

    /* Make sure that address is something sensible */
    if (address > 511 || address + (channels - 1) > 511)
    {
        qWarning() << Q_FUNC_INFO << "Fixture address range" << address << "-"
                   << address + channels - 1 << "out of DMX bounds";
        address = 0;
    }

    /* Check that the invalid ID is not used */
    if (id == Fixture::invalidId())
    {
        qWarning() << Q_FUNC_INFO << "Fixture ID" << id << "is not allowed.";
        return false;
    }

    if (fixtureDef != NULL && fixtureMode != NULL)
    {
        /* Assign fixtureDef & mode only if BOTH are not NULL */
        setFixtureDefinition(fixtureDef, fixtureMode);
    }
    else
    {
        /* Otherwise set just the channel count */
        setChannels(channels);
    }

    setAddress(address);
    setUniverse(universe);
    setName(name);
    setID(id);

    return true;
}
bool QgsManageConnectionsDialog::populateConnections()
{
  // Export mode. Populate connections list from settings
  if ( mDialogMode == Export )
  {
    QSettings settings;
    switch ( mConnectionType )
    {
      case WMS:
        settings.beginGroup( "/Qgis/connections-wms" );
        break;
      case WFS:
        settings.beginGroup( "/Qgis/connections-wfs" );
        break;
      case PostGIS:
        settings.beginGroup( "/PostgreSQL/connections" );
        break;
    }
    QStringList keys = settings.childGroups();
    QStringList::Iterator it = keys.begin();
    while ( it != keys.end() )
    {
      QListWidgetItem *item = new QListWidgetItem();
      item->setText( *it );
      listConnections->addItem( item );
      ++it;
    }
    settings.endGroup();
  }
  // Import mode. Populate connections list from file
  else
  {
    QFile file( mFileName );
    if ( !file.open( QIODevice::ReadOnly | QIODevice::Text ) )
    {
      QMessageBox::warning( this, tr( "Loading connections" ),
                            tr( "Cannot read file %1:\n%2." )
                            .arg( mFileName )
                            .arg( file.errorString() ) );
      return false;
    }

    QDomDocument doc;
    QString errorStr;
    int errorLine;
    int errorColumn;

    if ( !doc.setContent( &file, true, &errorStr, &errorLine, &errorColumn ) )
    {
      QMessageBox::warning( this, tr( "Loading connections" ),
                            tr( "Parse error at line %1, column %2:\n%3" )
                            .arg( errorLine )
                            .arg( errorColumn )
                            .arg( errorStr ) );
      return false;
    }

    QDomElement root = doc.documentElement();
    switch ( mConnectionType )
    {
      case WMS:
        if ( root.tagName() != "qgsWMSConnections" )
        {
          QMessageBox::information( this, tr( "Loading connections" ),
                                    tr( "The file is not an WMS connections exchange file." ) );
          return false;
        }
        break;

      case WFS:
        if ( root.tagName() != "qgsWFSConnections" )
        {
          QMessageBox::information( this, tr( "Loading connections" ),
                                    tr( "The file is not an WFS connections exchange file." ) );
          return false;
        }
        break;

      case PostGIS:
        if ( root.tagName() != "qgsPgConnections" )
        {
          QMessageBox::information( this, tr( "Loading connections" ),
                                    tr( "The file is not an PostGIS connections exchange file." ) );
          return false;
        }
        break;
    }

    QDomElement child = root.firstChildElement();
    while ( !child.isNull() )
    {
      QListWidgetItem *item = new QListWidgetItem();
      item->setText( child.attribute( "name" ) );
      listConnections->addItem( item );
      child = child.nextSiblingElement();
    }
  }
  return true;
}
Ejemplo n.º 28
0
int main(int argc, char *argv[])
{
  QCoreApplication application(argc, argv);
  application.addLibraryPath(".");

  QTextStream out(stdout, QIODevice::WriteOnly);

  if (application.argc() > 1)
  {
    QString databaseURL;
    QString username;
    QString passwd;
    QString arguments;

    QString xml_file = QString::null;
    int     report_grade = 0;

    for (int counter = 1; counter < application.argc(); counter++)
    {
      QString arguments(application.argv()[counter]);

      if (arguments.startsWith("-databaseURL=", Qt::CaseInsensitive))
        databaseURL = arguments.right(arguments.length() - 13);
      else if (arguments.startsWith("-username="******"-passwd=", Qt::CaseInsensitive))
        passwd = arguments.right(arguments.length() - 8);
      else if (arguments.startsWith("-f=", Qt::CaseInsensitive))
        xml_file = arguments.right(arguments.length() - 3);
      else if (arguments.startsWith("-grade=", Qt::CaseInsensitive))
        report_grade = (arguments.right(arguments.length() - 7)).toInt();
      else if(!arguments.startsWith("-"))
        xml_file = arguments;
    }

    QString report_name = QString::null;
    QString report_desc = QString::null;
    QString report_src  = QString::null;

    if(xml_file != "") {
        QFile file(xml_file);
        if(file.open( QIODevice::ReadOnly )) {
            QDomDocument doc;
            QString errMsg;
            int errLine, errCol;
            if(doc.setContent(&file, &errMsg, &errLine, &errCol)) {
                QDomElement root = doc.documentElement();
                if(root.tagName() == "report") {
                    for(QDomNode n = root.firstChild();
                            !n.isNull(); n = n.nextSibling() ) {
                        if(n.nodeName() == "name") {
                            report_name = n.firstChild().nodeValue();
                        } else if(n.nodeName() == "description") {
                            report_desc = n.firstChild().nodeValue();
                        }
                    }
                    report_src  = doc.toString();

                    if(report_name == "") {
                        out << "The document " << xml_file << " does not have a report name defined." << endl;
                    }
                } else {
                    out << "XML Document " << xml_file << " does not have root node of report." << endl;
                }
            } else {
                out << "Error parsing file " << xml_file << ": " << errMsg << " on line " << errLine << " column " << errCol << endl;
            }
        } else {
            out << "Could not open the specified file: " << xml_file << endl;
        }
    } else {
        out << "You must specify an XML file to load by using the -f= parameter." << endl;
    }

    if(report_name == "" || report_src == "") {
        // an error message already should have been displayed to the user
        exit(-1);
    }

    if (  (databaseURL != "") &&
          (username != "")    &&
          (passwd != "")          ) {
      QSqlDatabase db;

// Open the Database Driver
      db = databaseFromURL( databaseURL );
      if (!db.isValid())
      {
        out << "Could not load the specified database driver." << endl;
        exit(-1);
      }

//  Try to connect to the Database
      db.setUserName(username);
      db.setPassword(passwd);
      if (!db.open())
      {
        out << "Host=" << db.hostName() << ", Database=" << db.databaseName() << ", port=" << db.port() << endl;
        out << "Could not log into database.  System Error: "
            << db.lastError().text() << endl;
        exit(-1);
      }

      QSqlQuery().exec(getSqlFromTag("fmt05", db.driverName()));		// MANU

      // first we need to determine if there is already a report in the database of the same
      // name and if so then we will perform an update instead of an insert
      QSqlQuery qry;
      qry.prepare(getSqlFromTag("fmt09", db.driverName()));		// MANU
      qry.bindValue(":report_name", report_name);
      qry.bindValue(":report_grade", report_grade);
      qry.exec();
      QSqlQuery query;
      if(qry.first()) {
          // update
          query.prepare(getSqlFromTag("fmt10", db.driverName()));		// MANU
          query.bindValue(":report_desc", report_desc);
          query.bindValue(":report_src", report_src);
          query.bindValue(":report_id", qry.value(0));
          query.bindValue(":report_name", report_name);
      } else {
          // insert
          query.prepare(getSqlFromTag("fmt11", db.driverName()));		// MANU
          query.bindValue(":report_name", report_name);
          query.bindValue(":report_desc", report_desc);
          query.bindValue(":report_src", report_src);
          query.bindValue(":report_grade", report_grade);
      }
      
      if(!query.exec()) {
          QSqlError err = query.lastError();
          out << "Error: " << err.driverText() << endl
              << "\t" << err.databaseText() << endl;
          exit(-1);
      }
      
    }
    else if (databaseURL == "")
      out << "You must specify a Database URL by using the -databaseURL= parameter." << endl;
    else if (username == "")
      out << "You must specify a Database Username by using the -username= parameter." << endl;
    else if (passwd == "")
      out << "You must specify a Database Password by using the -passwd= parameter." << endl;
  }
  else
    out << "Usage: import -databaseURL='$' -username='******' -passwd='$' -grade=# -f='$'" << endl;
  return 0;
}
void QgsManageConnectionsDialog::loadPgConnections( const QDomDocument &doc, const QStringList &items )
{
  QDomElement root = doc.documentElement();
  if ( root.tagName() != "qgsPgConnections" )
  {
    QMessageBox::information( this,
                              tr( "Loading connections" ),
                              tr( "The file is not an PostGIS connections exchange file." ) );
    return;
  }

  QString connectionName;
  QSettings settings;
  settings.beginGroup( "/PostgreSQL/connections" );
  QStringList keys = settings.childGroups();
  settings.endGroup();
  QDomElement child = root.firstChildElement();
  bool prompt = true;
  bool overwrite = true;

  while ( !child.isNull() )
  {
    connectionName = child.attribute( "name" );
    if ( !items.contains( connectionName ) )
    {
      child = child.nextSiblingElement();
      continue;
    }

    // check for duplicates
    if ( keys.contains( connectionName ) && prompt )
    {
      int res = QMessageBox::warning( this,
                                      tr( "Loading connections" ),
                                      tr( "Connection with name '%1' already exists. Overwrite?" )
                                      .arg( connectionName ),
                                      QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No | QMessageBox::NoToAll | QMessageBox::Cancel );
      switch ( res )
      {
        case QMessageBox::Cancel:   return;
        case QMessageBox::No:       child = child.nextSiblingElement();
          continue;
        case QMessageBox::Yes:      overwrite = true;
          break;
        case QMessageBox::YesToAll: prompt = false;
          overwrite = true;
          break;
        case QMessageBox::NoToAll:  prompt = false;
          overwrite = false;
          break;
      }
    }

    if ( keys.contains( connectionName ) && !overwrite )
    {
      child = child.nextSiblingElement();
      continue;
    }

    //no dups detected or overwrite is allowed
    settings.beginGroup( "/PostgreSQL/connections/" + connectionName );

    settings.setValue( "/host", child.attribute( "host" ) );
    settings.setValue( "/port", child.attribute( "port" ) );
    settings.setValue( "/database", child.attribute( "database" ) );
    if ( child.hasAttribute( "service" ) )
    {
      settings.setValue( "/service", child.attribute( "service" ) );
    }
    else
    {
      settings.setValue( "/service", "" );
    }
    settings.setValue( "/sslmode", child.attribute( "sslmode" ) );
    settings.setValue( "/estimatedMetadata", child.attribute( "estimatedMetadata" ) );
    settings.setValue( "/saveUsername", child.attribute( "saveUsername" ) );
    settings.setValue( "/username", child.attribute( "username" ) );
    settings.setValue( "/savePassword", child.attribute( "savePassword" ) );
    settings.setValue( "/password", child.attribute( "password" ) );
    settings.endGroup();

    child = child.nextSiblingElement();
  }
}
Ejemplo n.º 30
0
void VCButton_Test::save()
{
    QWidget w;

    Scene* sc = new Scene(m_doc);
    m_doc->addFunction(sc);

    VCButton btn(&w, m_doc);
    btn.setCaption("Foobar");
    btn.setIcon("../../../gfx/qlc.png");
    btn.setFunction(sc->id());
    btn.setAction(VCButton::Flash);
    btn.setKeySequence(QKeySequence(keySequenceB));
    btn.setAdjustIntensity(true);
    btn.setIntensityAdjustment(0.2);

    QDomDocument xmldoc;
    QDomElement root = xmldoc.createElement("Root");
    xmldoc.appendChild(root);

    int function = 0, action = 0, key = 0, intensity = 0, wstate = 0, appearance = 0;
    QCOMPARE(btn.saveXML(&xmldoc, &root), true);
    QDomElement tag = root.firstChild().toElement();
    QCOMPARE(tag.tagName(), QString("Button"));
    QCOMPARE(tag.attribute("Icon"), QString("../../../gfx/qlc.png"));
    QCOMPARE(tag.attribute("Caption"), QString("Foobar"));
    QDomNode node = tag.firstChild();
    while (node.isNull() == false)
    {
        QDomElement tag = node.toElement();
        if (tag.tagName() == "Function")
        {
            function++;
            QCOMPARE(tag.attribute("ID"), QString::number(sc->id()));
        }
        else if (tag.tagName() == "Action")
        {
            action++;
            QCOMPARE(tag.text(), QString("Flash"));
        }
        else if (tag.tagName() == "Key")
        {
            key++;
            QCOMPARE(tag.text(), QKeySequence(keySequenceB).toString());
        }
        else if (tag.tagName() == "Intensity")
        {
            intensity++;
            QCOMPARE(tag.attribute("Adjust"), QString("True"));
            QCOMPARE(tag.text(), QString("20"));
        }
        else if (tag.tagName() == "WindowState")
        {
            wstate++;
        }
        else if (tag.tagName() == "Appearance")
        {
            appearance++;
        }
        else
        {
            QFAIL(QString("Unexpected tag: %1").arg(tag.tagName()).toUtf8().constData());
        }

        node = node.nextSibling();
    }

    QCOMPARE(function, 1);
    QCOMPARE(action, 1);
    QCOMPARE(key, 1);
    QCOMPARE(intensity, 1);
    QCOMPARE(wstate, 1);
    QCOMPARE(appearance, 1);
}