예제 #1
1
파일: line.cpp 프로젝트: briff/MuseScore
void LineSegment::read(const QDomElement& e)
      {
      for (QDomElement ee = e.firstChildElement(); !ee.isNull(); ee = ee.nextSiblingElement())
            readProperties(ee);
      }
예제 #2
1
QgsFeatureRenderer* QgsFeatureRenderer::loadSld( const QDomNode &node, QgsWkbTypes::GeometryType geomType, QString &errorMessage )
{
  QDomElement element = node.toElement();
  if ( element.isNull() )
    return nullptr;

  // get the UserStyle element
  QDomElement userStyleElem = element.firstChildElement( "UserStyle" );
  if ( userStyleElem.isNull() )
  {
    // UserStyle element not found, nothing will be rendered
    errorMessage = "Info: UserStyle element not found.";
    return nullptr;
  }

  // get the FeatureTypeStyle element
  QDomElement featTypeStyleElem = userStyleElem.firstChildElement( "FeatureTypeStyle" );
  if ( featTypeStyleElem.isNull() )
  {
    errorMessage = "Info: FeatureTypeStyle element not found.";
    return nullptr;
  }

  // use the RuleRenderer when more rules are present or the rule
  // has filters or min/max scale denominators set,
  // otherwise use the SingleSymbol renderer
  bool needRuleRenderer = false;
  int ruleCount = 0;

  QDomElement ruleElem = featTypeStyleElem.firstChildElement( "Rule" );
  while ( !ruleElem.isNull() )
  {
    ruleCount++;

    // more rules present, use the RuleRenderer
    if ( ruleCount > 1 )
    {
      QgsDebugMsg( "more Rule elements found: need a RuleRenderer" );
      needRuleRenderer = true;
      break;
    }

    QDomElement ruleChildElem = ruleElem.firstChildElement();
    while ( !ruleChildElem.isNull() )
    {
      // rule has filter or min/max scale denominator, use the RuleRenderer
      if ( ruleChildElem.localName() == "Filter" ||
           ruleChildElem.localName() == "MinScaleDenominator" ||
           ruleChildElem.localName() == "MaxScaleDenominator" )
      {
        QgsDebugMsg( "Filter or Min/MaxScaleDenominator element found: need a RuleRenderer" );
        needRuleRenderer = true;
        break;
      }

      ruleChildElem = ruleChildElem.nextSiblingElement();
    }

    if ( needRuleRenderer )
    {
      break;
    }

    ruleElem = ruleElem.nextSiblingElement( "Rule" );
  }

  QString rendererType;
  if ( needRuleRenderer )
  {
    rendererType = "RuleRenderer";
  }
  else
  {
    rendererType = "singleSymbol";
  }
  QgsDebugMsg( QString( "Instantiating a '%1' renderer..." ).arg( rendererType ) );

  // create the renderer and return it
  QgsRendererAbstractMetadata* m = QgsRendererRegistry::instance()->rendererMetadata( rendererType );
  if ( !m )
  {
    errorMessage = QString( "Error: Unable to get metadata for '%1' renderer." ).arg( rendererType );
    return nullptr;
  }

  QgsFeatureRenderer* r = m->createRendererFromSld( featTypeStyleElem, geomType );
  return r;
}
예제 #3
1
void Dossier::charger(const FormationManager& forman, const PeriodeManager& periodeman, const UVManager& uvman, const NoteManager& notman)
{
    QDomDocument doc = this->chargerXml(chemin_fichier + "/" + fichier);
    QDomElement racine = doc.documentElement();

    std::vector<const Formation*> tempformations;
    std::vector<Inscription> tempinscriptions;
    Factory<UV> tempuvs;
    std::map<QString,Note> tempnotes;
    QString tempForma = "NULL", tempInscri = "NULL";

    if(racine.tagName() == "dossier")
    {
        QString tempNom, tempPrenom, tempFormation, tempUv, tempNote, code;
        QDomElement unElement = racine.firstChildElement();

        while(!unElement.isNull())
        {
            if(unElement.tagName() == "nom")
            {
                tempNom = unElement.text();
            }
            else if(unElement.tagName() == "prenom")
            {
                tempPrenom = unElement.text();
            }
            else if(unElement.tagName() == "formations")
            {
                tempForma = unElement.text();
                tempformations.push_back(&forman.getFormation(tempForma));
            }
            else if(unElement.tagName() == "inscription")
            {
                QDomElement filsElement = unElement.firstChildElement();
                while(!filsElement.isNull())
                {
                    if(filsElement.tagName()=="code"){
                        code = filsElement.text();
                    }
                    else if(filsElement.tagName()=="semestre"){
                        tempInscri = filsElement.text();
                    }
                    else if(filsElement.tagName() =="formation"){
                        tempFormation = filsElement.text();
                    }
                    else if(filsElement.tagName() == "uv")
                    {
                        QDomElement filsUV = filsElement.firstChildElement();
                        while(!filsUV.isNull())
                        {
                            if(filsUV.tagName() == "codeUV"){
                                tempUv = filsUV.text();
                                tempuvs.ajouter(tempUv,uvman.getUV(tempUv));
                            }
                            if(filsUV.tagName() == "note"){
                                tempNote = filsUV.text();
                                tempnotes[tempUv] = notman.getNote(tempNote);
                            }
                            filsUV = filsUV.nextSiblingElement();
                        }

                    }
                filsElement = filsElement.nextSiblingElement();
                }
                Inscription temp(code,periodeman.getPeriode(tempInscri),forman.getFormation(tempFormation));
                for (map<QString,UV>::iterator it = tempuvs.begin(); it != tempuvs.end(); it++)
                {
                    temp.ajouterUV(it->second);
                    temp.modifierNote(it->second.getCode(),tempnotes.find(it->second.getCode())->second.getNote());
                }
                tempuvs.vider();
                tempinscriptions.push_back(temp);
            }
            unElement = unElement.nextSiblingElement();
        }
        this->setLogin();
        this->setNom(tempNom);
        this->setPrenom(tempPrenom);
        this->setLogin();
        if (tempForma != "NULL")
        {
            for (unsigned int i = 0; i < tempformations.size(); i++)
            {
               ajouterFormation(*tempformations[i]);
            }
            tempformations.clear();
            tempForma = "NULL";
        }
        if (tempInscri!="NULL")
        {
            for(unsigned int i=0; i < tempinscriptions.size(); i++)
            {
                ajouterInscription(tempinscriptions[i].getCode(),tempinscriptions[i].getPeriode(),tempinscriptions[i].getFormation());
                tempuvs=tempinscriptions[i].getUVs();
                for (map<QString,UV>::iterator it = tempuvs.begin(); it != tempuvs.end(); it++)
                {
                    getInscription(tempinscriptions[i].getCode()).ajouterUV(uvman.getUV(it->second.getCode()));
                    getInscription(tempinscriptions[i].getCode()).
                            modifierNote(it->second.getCode(),tempnotes.find(it->second.getCode())->second.getNote());
                }
            }
            tempuvs.vider();
            tempinscriptions.clear();
            tempInscri="NULL";
         }
    }
}
예제 #4
1
파일: Script.cpp 프로젝트: appl/RASP
Script* Script::load(std::string name)
{
    std::string filename = "scripts/";
    filename.append(name);
    filename.append(".xml");

    QFile file(filename.c_str());
    if(!file.open(QIODevice::ReadOnly))
    {
        pi_warn("Could not open file");
        return NULL;
    }

    QDomDocument document;
    document.setContent(&file);

    QDomElement docElem = document.documentElement();

    // check if this is a valid script file
    if(docElem.tagName().toLower().compare("script") != 0)
    {
        pi_warn("Invalid configuration file: tag \"script\" is missing");
        return NULL;
    }

    Script* script = new Script();

    script->m_name = name;

    QDomElement elem = docElem.firstChildElement();

    while(!elem.isNull())
    {
        if(elem.tagName().toLower().compare("rule") == 0)
        {
            Rule* rule = Rule::load(&elem);
            if(rule != NULL)
            {
                script->addRule(rule);
            }
        }
        else if(elem.tagName().toLower().compare("variable") == 0)
        {
            Variable* variable = Variable::load(&elem);
            if(variable != NULL)
            {
                script->addVariable(variable);
            }
        }
        else if(elem.tagName().toLower().compare("description") == 0)
        {
            script->m_desc = elem.text().toStdString();
        }

        elem = elem.nextSiblingElement();
    }

    file.close();

    return script;
}
예제 #5
1
void Box::read(const QDomElement& de)
      {
      _leftMargin = _rightMargin = _topMargin = _bottomMargin = 0.0;
      bool keepMargins = false;        // whether original margins have to be kept when reading old file

      for (QDomElement e = de.firstChildElement(); !e.isNull(); e = e.nextSiblingElement()) {
            const QString& tag(e.tagName());
            const QString& text(e.text());
            if (tag == "height")
                  _boxHeight = Spatium(text.toDouble());
            else if (tag == "width")
                  _boxWidth = Spatium(text.toDouble());
            else if (tag == "topGap")
                  _topGap = text.toDouble();
            else if (tag == "bottomGap")
                  _bottomGap = text.toDouble();
            else if (tag == "leftMargin")
                  _leftMargin = text.toDouble();
            else if (tag == "rightMargin")
                  _rightMargin = text.toDouble();
            else if (tag == "topMargin")
                  _topMargin = text.toDouble();
            else if (tag == "bottomMargin")
                  _bottomMargin = text.toDouble();
            else if (tag == "Text") {
                  Text* t;
                  if (type() == TBOX) {
                        t = static_cast<TBox*>(this)->getText();
                        t->read(e);
                        }
                  else {
                        t = new Text(score());
                        t->read(e);
                        add(t);
                        if (score()->mscVersion() <= 114)
                              t->setLayoutToParentWidth(true);
                        }
                  }
            else if (tag == "Symbol") {
                  Symbol* s = new Symbol(score());
                  s->read(e);
                  add(s);
                  }
            else if (tag == "Image") {
                  // look ahead for image type
                  QString path;
                  QDomElement ee = e.firstChildElement("path");
                  if (!ee.isNull())
                        path = ee.text();
                  Image* image = 0;
                  QString s(path.toLower());
                  if (s.endsWith(".svg"))
                        image = new SvgImage(score());
                  else
                        if (s.endsWith(".jpg")
                     || s.endsWith(".png")
                     || s.endsWith(".gif")
                     || s.endsWith(".xpm")
                        ) {
                        image = new RasterImage(score());
                        }
                  else {
                        qDebug("unknown image format <%s>\n", path.toLatin1().data());
                        }
                  if (image) {
                        image->setTrack(score()->curTrack);
                        image->read(e);
                        add(image);
                        }
                  }
            else if (tag == "FretDiagram") {
                  FretDiagram* f = new FretDiagram(score());
                  f->read(e);
                  add(f);
                  }
            else if (tag == "LayoutBreak") {
                  LayoutBreak* lb = new LayoutBreak(score());
                  lb->read(e);
                  add(lb);
                  }
            else if (tag == "HBox") {
                  HBox* hb = new HBox(score());
                  hb->read(e);
                  add(hb);
                  keepMargins = true;     // in old file, box nesting used outer box margins
                  }
            else if (tag == "VBox") {
                  VBox* vb = new VBox(score());
                  vb->read(e);
                  add(vb);
                  keepMargins = true;     // in old file, box nesting used outer box margins
                  }
            else
                  domError(e);
            }

      // with .msc versions prior to 1.17, box margins were only used when nesting another box inside this box:
      // for backward compatibility set them to 0 in all other cases

      if (score()->mscVersion() < 117 && (type() == HBOX || type() == VBOX) && !keepMargins)  {
            _leftMargin = _rightMargin = _topMargin = _bottomMargin = 0.0;
            }
      }
예제 #6
0
    QSharedPointer<FormatDefinition>
    FormatReader::_parseFormat(const QDomElement &formatNode)
    {
        QString id;                             // Unique; required
        QDateTime releaseDate;                  // As attribute of id; required
        QString name;                           // Localised; required
        QString description;                    // Localised; optional
        QString completeness;                   // From enum; required
        bool isText;                            // True or false; required
        // Prioritised when outputting; required to specify at least one:
        QStringList mimeTypes;

        // <id releaseDate="xsd:dateTime">xsd:NMTOKEN</id>
        QDomElement e = formatNode.firstChildElement();
        if (ElementParser::expect(e, "id", ElementParser::Required))
        {
            releaseDate = ElementParser::dateTime(e.attribute("releaseDate"));
            id = ElementParser::nmtoken(e.text());
            e = e.nextSiblingElement();
        }
        else
            return QSharedPointer<FormatDefinition>();

        // <name xml:lang="xsd:language">xsd:token</name>
        // (one or more, with unique xml:lang attributes)
        if (ElementParser::expect(e, "name", ElementParser::Required))
        {
            name = ElementParser::localisedString(e);
            e = e.nextSiblingElement();
        }
        else
            return QSharedPointer<FormatDefinition>();

        // <description xml:lang="xsd:language">xsd:token</description>
        // (zero or more, with unique xml:lang attributes)
        if (ElementParser::expect(e, "description", ElementParser::Optional))
        {
            description = ElementParser::localisedString(e);
            e = e.nextSiblingElement();
        }
        else if (e.isNull())
            return QSharedPointer<FormatDefinition>();

        // <completeness>(notEmpty|metaOnly|dataOnly|complete)</completeness>
        if (ElementParser::expect(e, "completeness", ElementParser::Required))
        {
            completeness = e.text();
            e = e.nextSiblingElement();
        }
        else
            return QSharedPointer<FormatDefinition>();

        // <isText> ( true | false ) </isText>
        if (ElementParser::expect(e, "isText", ElementParser::Required))
        {
            isText = ElementParser::boolean(e.text());
            e = e.nextSiblingElement();
        }
        else
            return QSharedPointer<FormatDefinition>();

        // <mimeTypes>
        //     <mimeType>xxx/yyy</mimeType>
        //     ...
        // <mimeTypes>
        if (ElementParser::expect(e, "mimeTypes", ElementParser::Required))
            mimeTypes = ElementParser::tokenList(e, "mimeType");
        e = e.nextSiblingElement();

        // alloc: QSharedPointer
        QSharedPointer<FormatDefinition> format(
            new FormatDefinition(id,
                                 name,
                                 description,
                                 releaseDate,
                                 completeness,
                                 isText,
                                 mimeTypes,
                                 0));
        if (format->isValid())
            return format;

        qDebug() << "FormatReader::parseFormat() discarded invalid format"
                 << " definition.";
        return QSharedPointer<FormatDefinition>();
    }
예제 #7
0
bool Scene::load(const QString& fn) {
    QFile file(fn);
    if (!file.open(QIODevice::ReadOnly)) {
        return false;
    }

    QByteArray data = file.readAll();
    QDomDocument doc;
    if (!doc.setContent(data)) {
        return false;
    }

    clearSelection();
    beginResetModel();
    m_history->clear();
    if (m_static_body)
        delete m_static_body;
    m_static_body = 0;
    foreach( Body* b, m_bodys ) {
        delete b;
    }
    m_bodys.clear();

    QDomElement root = doc.documentElement();
    m_worldSize.setWidth(root.attribute("width").toInt());
    m_worldSize.setHeight(root.attribute("height").toInt());
    QDomElement node = root.firstChildElement("body");
    while (node.isElement()) {
        QString type = node.attribute("type");
        Body* b = 0;
        if (type=="StaticBody") {
            b = new StaticBody(this,"body",this);
            ReadAttributes(b,node);
            if (!m_static_body)
                m_static_body = b;
            else {
                m_bodys.push_back( b );
            }
        } else if (type=="DynamicBody") {
            b = new DynamicBody(this,"body",this);
            ReadAttributes(b,node);
            m_bodys.push_back( b );
        }
        if (b) {
            QDomElement primNode = node.firstChildElement("primitive");
            while (primNode.isElement()) {
                Primitive* p = 0;
                QString type = primNode.attribute("type");
                p = Primitive::create(type,b,this);
                if (p) {
                    ReadAttributes(p,primNode);
                    b->addPrimitive(p);
                }
                primNode = primNode.nextSiblingElement("primitive");
            }
            connect( b,SIGNAL(changed()),this,SLOT(bodyChanged()));
        }
        node = node.nextSiblingElement("body");
    }
    endResetModel();
    m_filename = fn;
    emit changed();
    return true;
}
예제 #8
0
QTextDocument* Converter::convert(const QString &fileName)
{
    firstTime = true;
    Document oooDocument(fileName);
    if (!oooDocument.open())
    {
        return 0;
    }
    m_TextDocument = new QTextDocument;
    m_Cursor = new QTextCursor(m_TextDocument);

    /**
     * Create the dom of the content
     */
    QXmlSimpleReader reader;

    QXmlInputSource source;
    source.setData(oooDocument.content());
    QString errorMsg;
    QDomDocument document;
    if (!document.setContent(&source, &reader, &errorMsg))
    {
        setError(QString("Invalid XML document: %1").arg(errorMsg), -1);
        delete m_Cursor;
        return m_TextDocument;
    }

    /**
     * Read the style properties, so the are available when
     * parsing the content.
     */

    m_StyleInformation = new StyleInformation();

    if (oooDocument.content().size() == 0)
    {
        setError("Empty document", -1);
    }

    StyleParser styleParser(&oooDocument, document, m_StyleInformation);
    if (!styleParser.parse())
    {
        setError("Unable to read style information", -1);
        delete m_Cursor;
        return 0;
    }

    /**
    * Add all images of the document to resource framework
    */

    QMap<QString, QByteArray> imageLIST = oooDocument.images();
    QMapIterator<QString, QByteArray> it(imageLIST);
    while (it.hasNext())
    {
        it.next();
        m_TextDocument->addResource(QTextDocument::ImageResource, QUrl(it.key()), QImage::fromData(it.value()));
    }

    /**
     * Set the correct page size
     */

    const QString masterLayout = m_StyleInformation->masterPageName();

    if (m_StyleInformation->pagePropertyExists(masterLayout))
    {
        const int DPX = 231; /// im.logicalDpiX(); // 231
        const int DPY = 231; // im.logicalDpiY(); // 231
        const int A4Width = MM_TO_POINT(210); /// A4 210 x297 mm
        const int A4Height = MM_TO_POINT(297);

        const PageFormatProperty property = m_StyleInformation->pageProperty(masterLayout);
        int pageWidth = qRound(property.width() / 72.0 * DPX);
        if (pageWidth < 1) {
            pageWidth = A4Width;
        }
        int pageHeight = qRound(property.height() / 72.0 * DPY);
        if (pageHeight < 1) {
            pageHeight = A4Height;
        }
        m_TextDocument->setPageSize(QSize(pageWidth, pageHeight));

        QTextFrameFormat frameFormat;
        frameFormat.setMargin(qRound(property.margin()));

        QTextFrame *rootFrame = m_TextDocument->rootFrame();
        rootFrame->setFrameFormat(frameFormat);
    }

    /**
     * Parse the content of the document
     */
    const QDomElement documentElement = document.documentElement();

    QDomElement element = documentElement.firstChildElement();
    while (!element.isNull())
    {
        if (element.tagName() == QLatin1String("body"))
        {
            if (!convertBody(element))
            {
                setError("Unable to convert document content", -1);
                delete m_Cursor;
                return 0;
            }
        }

        element = element.nextSiblingElement();
    }

    return m_TextDocument;
}
예제 #9
0
	channels_container_t RSS10Parser::Parse (const QDomDocument& doc,
			const IDType_t& feedId) const
	{
		channels_container_t result;
	
		QMap<QString, Channel_ptr> item2Channel;
		QDomElement root = doc.documentElement ();
		QDomElement channelDescr = root.firstChildElement ("channel");
		while (!channelDescr.isNull ())
		{
			Channel_ptr channel (new Channel (feedId));
			channel->Title_ = channelDescr.firstChildElement ("title").text ().trimmed ();
			channel->Link_ = channelDescr.firstChildElement ("link").text ();
			channel->Description_ =
				channelDescr.firstChildElement ("description").text ();
			channel->PixmapURL_ =
				channelDescr.firstChildElement ("image")
				.firstChildElement ("url").text ();
			channel->LastBuild_ = GetDCDateTime (channelDescr);
	
			QDomElement itemsRoot = channelDescr.firstChildElement ("items");
			QDomNodeList seqs = itemsRoot.elementsByTagNameNS (RDF_, "Seq");
	
			channelDescr = channelDescr.nextSiblingElement ("channel");
	
			if (!seqs.size ())
				continue;
	
			QDomElement seqElem = seqs.at (0).toElement ();
			QDomNodeList lis = seqElem.elementsByTagNameNS (RDF_, "li");
			for (int i = 0; i < lis.size (); ++i)
				item2Channel [lis.at (i).toElement ().attribute ("resource")] = channel;
	
			result.push_back (channel);
		}
	
		QDomElement itemDescr = root.firstChildElement ("item");
		while (!itemDescr.isNull ())
		{
			QString about = itemDescr.attributeNS (RDF_, "about");
			if (item2Channel.contains (about))
			{
				Item_ptr item (new Item (item2Channel [about]->ChannelID_));
				item->Title_ = itemDescr.firstChildElement ("title").text ();
				item->Link_ = itemDescr.firstChildElement ("link").text ();
				item->Description_ = itemDescr.firstChildElement ("description").text ();
				GetDescription (itemDescr, item->Description_);
	
				item->Categories_ = GetAllCategories (itemDescr);
				item->Author_ = GetAuthor (itemDescr);
				item->PubDate_ = GetDCDateTime (itemDescr);
				item->Unread_ = true;
				item->NumComments_ = GetNumComments (itemDescr);
				item->CommentsLink_ = GetCommentsRSS (itemDescr);
				item->CommentsPageLink_ = GetCommentsLink (itemDescr);
				item->Enclosures_ = GetEncEnclosures (itemDescr, item->ItemID_);
				QPair<double, double> point = GetGeoPoint (itemDescr);
				item->Latitude_ = point.first;
				item->Longitude_ = point.second;
				if (item->Guid_.isEmpty ())
					item->Guid_ = "empty";
	
				item2Channel [about]->Items_.push_back (item);
			}
			itemDescr = itemDescr.nextSiblingElement ("item");
		}
	
		return result;
	}
예제 #10
0
void Variable::handleProperty(const QDomElement &xml)
{
    Q_ASSERT(!xml.isNull());
    Q_ASSERT(xml.nodeName() == "property");

    setInScope(true);

    m_fullName = xml.attribute("fullname");
    //kDebug() << m_fullName;
    if (xml.firstChild().isText()) {
        QString v  = xml.firstChild().toText().data();
        if (xml.attribute("encoding") == "base64") {
            //TODO: use Connection::m_codec->toUnicode
            v = QString::fromUtf8(QByteArray::fromBase64(xml.text().toAscii()));
        }
        //kDebug() << "value" << v;
        setValue(v);
    }

    QMap<QString, Variable*> existing;
    for (int i = 0; i < childCount() - (hasMore() ? 1 : 0) ; i++) {
        Q_ASSERT(dynamic_cast<Variable*>(child(i)));
        Variable* v = static_cast<Variable*>(child(i));
        existing[v->expression()] = v;
    }

    QSet<QString> current;
    QDomElement el = xml.firstChildElement("property");
    while (!el.isNull()) {
        QString name = el.attribute("name");
        //kDebug() << name;
        current << name;
        Variable* v = 0;
        if( !existing.contains(name) ) {
            v = new Variable(model(), this, name);
            appendChild( v, false );
        } else {
            v = existing[name];
        }

        v->handleProperty(el);

        el = el.nextSiblingElement("property");
    }

    for (int i = 0; i < childCount() - (hasMore() ? 1 : 0); ++i) {
        Q_ASSERT(dynamic_cast<KDevelop::Variable*>(child(i)));
        KDevelop::Variable* v = static_cast<KDevelop::Variable*>(child(i));
        if (!current.contains(v->expression())) {
            removeChild(i);
            --i;
            delete v;
        }
    }
    if (!childCount() && xml.attribute("children") == "1") {
        kDebug() << "has more" << this;
        setHasMore(true);
        if (isExpanded()) {
            fetchMoreChildren();
        }
    }
}
예제 #11
0
bool ActionCollection::deSerialize(const QDomElement& actionCollectionElem)
{
  if (actionCollectionElem.isNull())
    return false;

  qDeleteAll(listInterfaceCommands);
  listInterfaceCommands.clear();

  QDomElement listsElement = actionCollectionElem.firstChildElement("lists");

  if (listsElement.isNull()) {
    QHash<CommandListElements::Element, VoiceInterfaceCommand*> baseConfig = ScenarioManager::getInstance()->
      getListBaseConfiguration();

    QHashIterator<CommandListElements::Element, VoiceInterfaceCommand*> i(baseConfig);
    while (i.hasNext()) {
      i.next();
      // i.value() is not a valid command
      listInterfaceCommands.insertMulti(i.key(), new VoiceInterfaceCommand(*(i.value())));
    }
  }
  else {
    QDomElement commandElem = listsElement.firstChildElement();

    while (!commandElem.isNull()) {
      VoiceInterfaceCommand *com = VoiceInterfaceCommand::createInstance(commandElem);

      int elementId = commandElem.attribute("element").toInt();

      commandElem = commandElem.nextSiblingElement("voiceInterfaceCommand");

      if (!com) continue;

      listInterfaceCommands.insert((CommandListElements::Element) elementId, com);
    }
  }

  QDomElement autorunElem = actionCollectionElem.firstChildElement("autorun");
  m_autorunActive = autorunElem.attribute("active") == "1";
  m_autorunCommand = autorunElem.firstChildElement("trigger").text();
  m_autorunType = autorunElem.firstChildElement("category").text();

  //clean member
  qDeleteAll(m_actions);
  m_actions.clear();

  QDomElement pluginElem = actionCollectionElem.firstChildElement("plugin");
  while (!pluginElem.isNull()) {
    Action *a = Action::createAction(parentScenario, pluginElem, this);
    if (!a) {
      kDebug() << "Could not load action";
    }
    else {
      //m_actions << a;
      appendAction(a, true /*silent*/);
    }

    pluginElem = pluginElem.nextSiblingElement("plugin");
  }
  proxy->update();
  reset();

  if (m_autorunActive)
  {
    bool succ = triggerCommand(m_autorunType, m_autorunCommand, true /* silent */);
    kDebug() << "Executed autorun command; Success: " << succ;
  }

  return true;
}
예제 #12
0
void ePageView::_onOperatorPaste()
{
    eGuiOpPage *guiPage = (eGuiOpPage *)scene();
    eASSERT(guiPage != eNULL);

    // Check if clipboard format is correct.
    const QMimeData *md = QApplication::clipboard()->mimeData();
    eASSERT(md != eNULL);

    if (!md->hasFormat("operator/xml"))
    {
        return;
    }

    // Get operator with smallest (x, y) position,
    // needed to calculate new positions for
    // pasted operators.
    QDomDocument xml;
    xml.setContent(md->data("operator/xml"));
    QDomElement xmlOp = xml.firstChild().firstChildElement("operator");

    ePoint minPos(eS32_MAX, eS32_MAX);

    while (!xmlOp.isNull())
    {
        const eInt x = xmlOp.attribute("xpos").toInt();
        const eInt y = xmlOp.attribute("ypos").toInt();

        if (x < minPos.x)
        {
            minPos.x = x;
        }

        if (y < minPos.y)
        {
            minPos.y = y;
        }

        xmlOp = xmlOp.nextSiblingElement("operator");
    }

    // Iterate the second time through operators. This
    // time the operators are added to the page using
    // the previously calculated minimum relative
    // position.
    xmlOp = xml.firstChild().firstChildElement("operator");

    while (!xmlOp.isNull())
    {
        const QString opType = xmlOp.attribute("type");
        const eU32 xpos = xmlOp.attribute("xpos").toInt();
        const eU32 ypos = xmlOp.attribute("ypos").toInt();
        const eU32 width = xmlOp.attribute("width").toInt();
        const eID opId = xmlOp.attribute("id").toInt();

        const ePoint newPos = guiPage->getInsertAt()+(ePoint(xpos, ypos)-minPos);
        eASSERT(newPos.x >= 0 && newPos.y >= 0);

        // Only add operator, if its position
        // lies on operator page.
        if (newPos.y < eOperatorPage::HEIGHT &&
            newPos.x+width <= eOperatorPage::WIDTH)
        {
            eGuiOperator *guiOp = new eGuiOperator(opType.toAscii().constData(), newPos, guiPage, width, eFALSE, opId);
            eASSERT(guiOp != eNULL);

            // Was adding of operator successful?
            if (guiOp->getOperator())
            {
                guiOp->loadFromXml(xmlOp);
                scene()->addItem(guiOp);
            }
            else
            {
                eSAFE_DELETE(guiOp);
            }
        }

        xmlOp = xmlOp.nextSiblingElement("operator");
    }

    // Finally, after adding all operators,
    // update links on page.
    guiPage->getPage()->updateLinks();
    scene()->invalidate();
}
예제 #13
0
QgsFeatureRendererV2* QgsGraduatedSymbolRendererV2::create( QDomElement& element )
{
  QDomElement symbolsElem = element.firstChildElement( "symbols" );
  if ( symbolsElem.isNull() )
    return NULL;

  QDomElement rangesElem = element.firstChildElement( "ranges" );
  if ( rangesElem.isNull() )
    return NULL;

  QgsSymbolV2Map symbolMap = QgsSymbolLayerV2Utils::loadSymbols( symbolsElem );
  QgsRangeList ranges;

  QDomElement rangeElem = rangesElem.firstChildElement();
  while ( !rangeElem.isNull() )
  {
    if ( rangeElem.tagName() == "range" )
    {
      double lowerValue = rangeElem.attribute( "lower" ).toDouble();
      double upperValue = rangeElem.attribute( "upper" ).toDouble();
      QString symbolName = rangeElem.attribute( "symbol" );
      QString label = rangeElem.attribute( "label" );
      bool render = rangeElem.attribute( "render", "true" ) != "false";
      if ( symbolMap.contains( symbolName ) )
      {
        QgsSymbolV2* symbol = symbolMap.take( symbolName );
        ranges.append( QgsRendererRangeV2( lowerValue, upperValue, symbol, label, render ) );
      }
    }
    rangeElem = rangeElem.nextSiblingElement();
  }

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

  QgsGraduatedSymbolRendererV2* r = new QgsGraduatedSymbolRendererV2( attrName, ranges );

  QString attrMethod = element.attribute( "graduatedMethod" );
  if ( attrMethod.length() )
  {
    if ( attrMethod == graduatedMethodStr( GraduatedColor ) )
      r->setGraduatedMethod( GraduatedColor );
    else if ( attrMethod == graduatedMethodStr( GraduatedSize ) )
      r->setGraduatedMethod( GraduatedSize );
  }


  // 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" );
  }

  // try to load mode
  QDomElement modeElem = element.firstChildElement( "mode" );
  if ( !modeElem.isNull() )
  {
    QString modeString = modeElem.attribute( "name" );
    if ( modeString == "equal" )
      r->setMode( EqualInterval );
    else if ( modeString == "quantile" )
      r->setMode( Quantile );
    else if ( modeString == "jenks" )
      r->setMode( Jenks );
    else if ( modeString == "stddev" )
      r->setMode( StdDev );
    else if ( modeString == "pretty" )
      r->setMode( Pretty );
  }

  QDomElement rotationElem = element.firstChildElement( "rotation" );
  if ( !rotationElem.isNull() && !rotationElem.attribute( "field" ).isEmpty() )
  {
    for ( QgsRangeList::iterator it = r->mRanges.begin(); it != r->mRanges.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() )
  {
    for ( QgsRangeList::iterator it = r->mRanges.begin(); it != r->mRanges.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" ) );
    }
  }

  QDomElement labelFormatElem = element.firstChildElement( "labelformat" );
  if ( ! labelFormatElem.isNull() )
  {
    QgsRendererRangeV2LabelFormat labelFormat;
    labelFormat.setFromDomElement( labelFormatElem );
    r->setLabelFormat( labelFormat );
  }
  // TODO: symbol levels
  return r;
}
예제 #14
0
void XmlSettingsDialog::RegisterObject (QObject* obj, const QString& basename)
{
	Basename_ = QFileInfo (basename).baseName ();
	WorkingObject_ = obj;
	QString filename;
	if (QFile::exists (basename))
		filename = basename;
	else if (QFile::exists (QString (":/") + basename))
		filename = QString (":/") + basename;
#ifdef Q_WS_WIN
	else if (QFile::exists (QString ("settings/") + basename))
		filename = QString ("settings/") + basename;
#elif defined (Q_WS_MAC)
	else if (QFile::exists (QApplication::applicationDirPath () +
			"/../Resources/settings/" + basename))
		filename = QApplication::applicationDirPath () +
				"/../Resources/settings/" + basename;
#else
	else if (QFile::exists (QString ("/usr/local/share/leechcraft/settings/") + basename))
		filename = QString ("/usr/local/share/leechcraft/settings/") + basename;
	else if (QFile::exists (QString ("/usr/share/leechcraft/settings/") + basename))
		filename = QString ("/usr/share/leechcraft/settings/") + basename;
#endif
	QFile file (filename);
	if (!file.open (QIODevice::ReadOnly))
	{
		qWarning () << "cannot open file"
			<< filename
			<< basename;
		return;
	}
	QByteArray data = file.readAll ();
	file.close ();

	QString emsg;
	int eline;
	int ecol;
	if (!Document_->setContent (data, &emsg, &eline, &ecol))
	{
		qWarning () << "Could not parse file, line"
			<< eline
			<< "; column"
			<< ecol
			<< emsg;
		return;
	}
	QDomElement root = Document_->documentElement ();
	if (root.tagName () != "settings")
	{
		qWarning () << "Bad settings file";
		return;
	}

	QDomElement declaration = root.firstChildElement ("declare");
	while (!declaration.isNull ())
	{
		HandleDeclaration (declaration);
		declaration = declaration.nextSiblingElement ("declare");
	}

	QDomElement pageChild = root.firstChildElement ("page");
	while (!pageChild.isNull ())
	{
		ParsePage (pageChild);
		pageChild = pageChild.nextSiblingElement ("page");
	}

	obj->installEventFilter (this);

	UpdateXml (true);
}
예제 #15
0
bool ResourceFile::load()
{
    m_error_message.clear();

    if (m_file_name.isEmpty()) {
        m_error_message = tr("The file name is empty.");
        return false;
    }

    QFile file(m_file_name);
    if (!file.open(QIODevice::ReadOnly)) {
        m_error_message = file.errorString();
        return false;
    }

    clearPrefixList();

    QDomDocument doc;

    QString error_msg;
    int error_line, error_col;
    if (!doc.setContent(&file, &error_msg, &error_line, &error_col)) {
        m_error_message = tr("XML error on line %1, col %2: %3")
                    .arg(error_line).arg(error_col).arg(error_msg);
        return false;
    }

    QDomElement root = doc.firstChildElement(QLatin1String("RCC"));
    if (root.isNull()) {
        m_error_message = tr("The <RCC> root element is missing.");
        return false;
    }

    QDomElement relt = root.firstChildElement(QLatin1String("qresource"));
    for (; !relt.isNull(); relt = relt.nextSiblingElement(QLatin1String("qresource"))) {

        QString prefix = fixPrefix(relt.attribute(QLatin1String("prefix")));
        if (prefix.isEmpty())
            prefix = QString(QLatin1Char('/'));
        const QString language = relt.attribute(QLatin1String("lang"));

        const int idx = indexOfPrefix(prefix, language);
        Prefix * p = 0;
        if (idx == -1) {
            p = new Prefix(prefix, language);
            m_prefix_list.append(p);
        } else {
            p = m_prefix_list[idx];
        }
        Q_ASSERT(p);

        QDomElement felt = relt.firstChildElement(QLatin1String("file"));
        for (; !felt.isNull(); felt = felt.nextSiblingElement(QLatin1String("file"))) {
            const QString fileName = absolutePath(felt.text());
            const QString alias = felt.attribute(QLatin1String("alias"));
            File * const file = new File(p, fileName, alias);
            file->compress = felt.attribute(QLatin1String("compress"));
            file->threshold = felt.attribute(QLatin1String("threshold"));
            p->file_list.append(file);
        }
    }

    return true;
}
예제 #16
0
void XmlSettingsDialog::ParseEntity (const QDomElement& entity, QWidget *baseWidget)
{
	QDomElement item = entity.firstChildElement ("item");
	while (!item.isNull ())
	{
		ParseItem (item, baseWidget);
		item = item.nextSiblingElement ("item");
	}

	QDomElement gbox = entity.firstChildElement ("groupbox");
	while (!gbox.isNull ())
	{
		QGroupBox *box = new QGroupBox (GetLabel (gbox));
		QGridLayout *groupLayout = new QGridLayout ();
		groupLayout->setContentsMargins (2, 2, 2, 2);
		box->setLayout (groupLayout);
		box->setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Expanding);
		ParseEntity (gbox, box);

		QGridLayout *lay = qobject_cast<QGridLayout*> (baseWidget->layout ());
		lay->addWidget (box, lay->rowCount (), 0);

		gbox = gbox.nextSiblingElement ("groupbox");

		QSpacerItem *verticalSpacer = new QSpacerItem (10, 20, QSizePolicy::Minimum, QSizePolicy::Expanding);
		groupLayout->addItem (verticalSpacer, groupLayout->rowCount (), 0);
	}

	QDomElement scroll = entity.firstChildElement ("scrollarea");
	while (!scroll.isNull ())
	{
		QScrollArea *area = new QScrollArea ();
		if (scroll.hasAttribute ("horizontalScroll"))
		{
			QString attr = scroll.attribute ("horizontalScroll");
			if (attr == "on")
				area->setHorizontalScrollBarPolicy (Qt::ScrollBarAlwaysOn);
			else if (attr == "off")
				area->setHorizontalScrollBarPolicy (Qt::ScrollBarAlwaysOff);
		}
		if (scroll.hasAttribute ("verticalScroll"))
		{
			QString attr = scroll.attribute ("verticalScroll");
			if (attr == "on")
				area->setVerticalScrollBarPolicy (Qt::ScrollBarAlwaysOn);
			else if (attr == "off")
				area->setVerticalScrollBarPolicy (Qt::ScrollBarAlwaysOff);
		}

		QFrame *areaWidget = new QFrame;
		QGridLayout *areaLayout = new QGridLayout;
		areaWidget->setLayout (areaLayout);
		ParseEntity (scroll, areaWidget);
		area->setWidget (areaWidget);
		areaWidget->show ();

		QGridLayout *lay = qobject_cast<QGridLayout*> (baseWidget->layout ());
		lay->addWidget (area, lay->rowCount (), 0, 1, 2);

		scroll = scroll.nextSiblingElement ("scrollarea");
		QSpacerItem *verticalSpacer = new QSpacerItem (10, 20, QSizePolicy::Minimum, QSizePolicy::Expanding);
		lay->addItem (verticalSpacer, lay->rowCount (), 0, 1, 1);
	}

	QDomElement tab = entity.firstChildElement ("tab");
	if (!tab.isNull ())
	{
		QTabWidget *tabs = new QTabWidget;
		QGridLayout *lay = qobject_cast<QGridLayout*> (baseWidget->layout ());
		lay->addWidget (tabs, lay->rowCount (), 0, 1, 2);
		while (!tab.isNull ())
		{
			QWidget *page = new QWidget;
			QGridLayout *widgetLay = new QGridLayout;
			widgetLay->setContentsMargins (0, 0, 0, 0);
			page->setLayout (widgetLay);
			page->setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Expanding);
			tabs->addTab (page, GetLabel (tab));
			ParseEntity (tab, page);
			tab = tab.nextSiblingElement ("tab");
			QSpacerItem *verticalSpacer = new QSpacerItem (10, 20, QSizePolicy::Minimum, QSizePolicy::Expanding);
			widgetLay->addItem (verticalSpacer, widgetLay->rowCount (), 0, 1, 1);
		}
	}
}
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" );
      if ( symbolMap.contains( symbolName ) )
      {
        QgsSymbolV2* symbol = symbolMap.take( symbolName );
        cats.append( QgsRendererCategoryV2( value, symbol, label ) );
      }
    }
    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 rotationElem = element.firstChildElement( "rotation" );
  if ( !rotationElem.isNull() )
    r->setRotationField( rotationElem.attribute( "field" ) );

  QDomElement sizeScaleElem = element.firstChildElement( "sizescale" );
  if ( !sizeScaleElem.isNull() )
    r->setSizeScaleField( sizeScaleElem.attribute( "field" ) );

  // TODO: symbol levels
  return r;
}
예제 #18
0
void JabberSearch::stanzaRequestResult(const Jid &AStreamJid, const Stanza &AStanza)
{
    Q_UNUSED(AStreamJid);
    if (FRequests.contains(AStanza.id()))
    {
        if (AStanza.type() == "result")
        {
            LOG_STRM_INFO(AStreamJid,QString("Search request result received, id=%1").arg(AStanza.id()));
            QDomElement query = AStanza.firstElement("query",NS_JABBER_SEARCH);

            ISearchFields fields;
            fields.serviceJid = AStanza.from();
            fields.fieldMask = 0;
            fields.instructions = query.firstChildElement("instructions").text();
            if (!query.firstChildElement("first").isNull())
            {
                fields.fieldMask += ISearchFields::First;
                fields.item.firstName = query.firstChildElement("first").text();
            }
            if (!query.firstChildElement("last").isNull())
            {
                fields.fieldMask += ISearchFields::Last;
                fields.item.lastName = query.firstChildElement("last").text();
            }
            if (!query.firstChildElement("nick").isNull())
            {
                fields.fieldMask += ISearchFields::Nick;
                fields.item.nick = query.firstChildElement("nick").text();
            }
            if (!query.firstChildElement("email").isNull())
            {
                fields.fieldMask += ISearchFields::Email;
                fields.item.email = query.firstChildElement("email").text();
            }

            if (FDataForms)
            {
                QDomElement formElem = query.firstChildElement("x");
                while (!formElem.isNull() && formElem.namespaceURI()!=NS_JABBER_DATA)
                    formElem = formElem.nextSiblingElement("x");
                if (!formElem.isNull())
                    fields.form = FDataForms->dataForm(formElem);
            }

            emit searchFields(AStanza.id(),fields);
        }
        else
        {
            XmppStanzaError err(AStanza);
            LOG_STRM_WARNING(AStreamJid,QString("Failed to receive search request result, id=%1: %2").arg(AStanza.id(),err.condition()));
            emit searchError(AStanza.id(),err);
        }
        FRequests.removeAll(AStanza.id());
    }
    else if (FSubmits.contains(AStanza.id()))
    {
        if (AStanza.type() == "result")
        {
            LOG_STRM_INFO(AStreamJid,QString("Search submit result received, id=%1").arg(AStanza.id()));
            QDomElement query = AStanza.firstElement("query",NS_JABBER_SEARCH);

            ISearchResult result;
            result.serviceJid = AStanza.from();
            QDomElement itemElem = query.firstChildElement("item");
            while (!itemElem.isNull())
            {
                ISearchItem item;
                item.itemJid = itemElem.attribute("jid");
                item.firstName = itemElem.firstChildElement("first").text();
                item.lastName = itemElem.firstChildElement("last").text();
                item.nick = itemElem.firstChildElement("nick").text();
                item.email = itemElem.firstChildElement("email").text();
                result.items.append(item);
            }

            if (FDataForms)
            {
                QDomElement formElem = query.firstChildElement("x");
                while (!formElem.isNull() && formElem.namespaceURI()!=NS_JABBER_DATA)
                    formElem = formElem.nextSiblingElement("x");
                if (!formElem.isNull())
                    result.form = FDataForms->dataForm(formElem);
            }

            emit searchResult(AStanza.id(),result);
        }
        else
        {
            XmppStanzaError err(AStanza);
            LOG_STRM_WARNING(AStreamJid,QString("Failed to receive search submit result, id=%1: %2").arg(AStanza.id(),err.condition()));
            emit searchError(AStanza.id(),err);
        }
        FSubmits.removeAll(AStanza.id());
    }
}
예제 #19
0
  // Downloaded component from component.xml
  BCLComponent::BCLComponent(const std::string& dir):
    m_directory(dir)
  {
    QDomDocument component("component.xml");
    component.setContent(openstudio::filesystem::read_as_QByteArray(openstudio::toPath(m_directory) / "component.xml"));

    QDomElement comp = component.firstChildElement("component");
    m_name = comp.firstChildElement("name").firstChild().nodeValue().replace("_", " ")
      .toStdString();
    m_uid = comp.firstChildElement("uid").firstChild().nodeValue().toStdString();
    m_versionId = comp.firstChildElement("version_id").firstChild().nodeValue().toStdString();
    m_description = comp.firstChildElement("description").firstChild().nodeValue().toStdString();
    QDomElement componentElement = comp.firstChildElement("files").firstChildElement("file");

    while (!componentElement.isNull())
    {
      if (componentElement.hasChildNodes())
      {
        m_files.push_back(componentElement.firstChildElement("filename").firstChild()
          .nodeValue().toStdString());
        m_filetypes.push_back(componentElement.firstChildElement("filetype").firstChild()
          .nodeValue().toStdString());
      }
      else
      {
        break;
      }
      componentElement = componentElement.nextSiblingElement("file");
    }
    componentElement = comp.firstChildElement("attributes").firstChildElement("attribute");
    while (!componentElement.isNull())
    {
      if (componentElement.hasChildNodes())
      {
        std::string name = componentElement.firstChildElement("name").firstChild()
          .nodeValue().toStdString();
        std::string value = componentElement.firstChildElement("value").firstChild()
          .nodeValue().toStdString();
        std::string datatype = componentElement.firstChildElement("datatype").firstChild()
          .nodeValue().toStdString();

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

        if (datatype == "float"){
          if (units.empty()){
            Attribute attr(name, boost::lexical_cast<double>(value));
            m_attributes.push_back(attr);
          }else{
            Attribute attr(name, boost::lexical_cast<double>(value), units);
            m_attributes.push_back(attr);
          }
        }else if (datatype == "int"){
          if (units.empty()){
            Attribute attr(name, boost::lexical_cast<int>(value));
            m_attributes.push_back(attr);
          }else{
            Attribute attr(name, boost::lexical_cast<int>(value), units);
            m_attributes.push_back(attr);
          }
        }else if (datatype == "boolean"){
          bool temp;
          if (value == "true"){
            temp = true;
          }else{
            temp = false;
          }
          if (units.empty()){
            Attribute attr(name, temp);
            m_attributes.push_back(attr);
          }else{
            Attribute attr(name, temp, units);
            m_attributes.push_back(attr);
          }
        }else{
          // Assume string
          if (units.empty()){
            Attribute attr(name, value);
            m_attributes.push_back(attr);
          }else{
            Attribute attr(name, value, units);
            m_attributes.push_back(attr);
          }
        }
      }
      else
      {
        break;
      }
      componentElement = componentElement.nextSiblingElement("attribute");
    }
  }
예제 #20
0
void
XSPFLoader::gotBody()
{
    QDomDocument xmldoc;
    bool namespaceProcessing = true;
    xmldoc.setContent( m_body, namespaceProcessing );
    QDomElement docElement( xmldoc.documentElement() );

    QString origTitle;
    QDomNodeList tracklist;
    QDomElement n = docElement.firstChildElement();
    for ( ; !n.isNull(); n = n.nextSiblingElement() )
    {
        if ( n.namespaceURI() == m_NS && n.localName() == "title" )
        {
            origTitle = n.text();
        }
        else if ( n.namespaceURI() == m_NS && n.localName() == "creator" )
        {
            m_creator = n.text();
        }
        else if ( n.namespaceURI() == m_NS && n.localName() == "info" )
        {
            m_info = n.text();
        }
        else if ( n.namespaceURI() == m_NS && n.localName() == "trackList" )
        {
            tracklist = n.childNodes();
        }
    }

    m_title = origTitle;
    if ( m_title.isEmpty() )
        m_title = tr( "New Playlist" );
    if ( !m_overrideTitle.isEmpty() )
        m_title = m_overrideTitle;

    bool shownError = false;
    for ( int i = 0; i < tracklist.length(); i++ )
    {
        QDomNode e = tracklist.at( i );

        QString artist, album, track, duration, annotation, url;
        QDomElement n = e.firstChildElement();
        for ( ; !n.isNull(); n = n.nextSiblingElement() )
        {
            if ( n.namespaceURI() == m_NS && n.localName() == "duration" )
            {
                duration = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "annotation" )
            {
                annotation = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "creator" )
            {
                artist = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "album" )
            {
                album = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "title" )
            {
                track = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "url" )
            {
                if ( !n.text().startsWith( "http" ) || TomahawkUtils::whitelistedHttpResultHint( n.text() ) )
                    url = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "location" )
            {
                if ( !n.text().startsWith( "http" ) || TomahawkUtils::whitelistedHttpResultHint( n.text() ) )
                    url = n.text();
            }
        }

        if ( artist.isEmpty() || track.isEmpty() )
        {
            if ( !shownError )
            {
                emit error( InvalidTrackError );
                shownError = true;
            }
            continue;
        }

        track_ptr t = Tomahawk::Track::get( artist, track, album, duration.toInt() / 1000 );
        query_ptr q = Tomahawk::Query::get( t );
        if ( q.isNull() )
            continue;

        if ( !url.isEmpty() )
        {
            q->setResultHint( url );
            q->setSaveHTTPResultHint( true );
        }

        m_entries << q;
    }

    if ( m_autoResolve )
    {
        for ( int i = m_entries.size() - 1; i >= 0; i-- )
            Pipeline::instance()->resolve( m_entries[ i ] );
    }

    if ( origTitle.isEmpty() && m_entries.isEmpty() )
    {
        emit error( ParseError );
        if ( m_autoCreate )
            deleteLater();
        return;
    }

    if ( m_autoCreate )
    {
        emit ok( getPlaylistForRecentUrl() );
    }
    else
    {
        if ( !m_entries.isEmpty() )
            emit tracks( m_entries );
    }

    if ( m_autoDelete )
        deleteLater();
}
예제 #21
0
void XmlCndInterface::readConditions( const QDomNode &listRoot,
                                   std::vector<FEMCondition*> &conditions,
                                   FEMCondition::CondType type)
{
	QDomElement cond = listRoot.firstChildElement();
	while (!cond.isNull())
	{
		std::string geometry_name ( cond.attribute("geometry").toStdString() );
		if (this->_project->getGEOObjects()->exists(geometry_name) >= 0 ||
			this->_project->meshExists(geometry_name))
		{

			FEMCondition* c ( new FEMCondition(geometry_name, type) );

			QDomNodeList condProperties = cond.childNodes();
			for (int i = 0; i < condProperties.count(); i++)
			{
				const QDomNode prop_node (condProperties.at(i));
				if (condProperties.at(i).nodeName().compare("Process") == 0)
				{
					QDomNodeList processProps = prop_node.childNodes();
					for (int j = 0; j < processProps.count(); j++)
					{
						const QString prop_name(processProps.at(j).nodeName());
						if (prop_name.compare("Type") == 0)
							c->setProcessType(FiniteElement::convertProcessType(processProps.at(j).toElement().text().toStdString()));
						else if (prop_name.compare("Variable") == 0)
							c->setProcessPrimaryVariable(FiniteElement::convertPrimaryVariable(processProps.at(j).toElement().text().toStdString()));
					}
				}
				else if (prop_node.nodeName().compare("Geometry") == 0)
				{
					QDomNodeList geoProps = prop_node.childNodes();
					for (int j = 0; j < geoProps.count(); j++)
					{
						const QString prop_name(geoProps.at(j).nodeName());
						if (prop_name.compare("Type") == 0)
							c->setGeoType(GeoLib::convertGeoType(geoProps.at(j).toElement().text().toStdString()));
						else if (prop_name.compare("Name") == 0)
							c->setGeoName(geoProps.at(j).toElement().text().toStdString());
					}
				}
				else if (prop_node.nodeName().compare("Distribution") == 0)
				{
					QDomNodeList distProps = prop_node.childNodes();
					for (int j = 0; j < distProps.count(); j++)
					{
						const QString prop_name(distProps.at(j).nodeName());
						if (prop_name.compare("Type") == 0)
							c->setProcessDistributionType(FiniteElement::convertDisType(distProps.at(j).toElement().text().toStdString()));
						else if (prop_name.compare("Value") == 0)
						{
							std::vector<size_t> disNodes;
							std::vector<double> disValues;
							if (c->getProcessDistributionType()==FiniteElement::CONSTANT ||
								c->getProcessDistributionType()==FiniteElement::CONSTANT_NEUMANN)
								disValues.push_back( strtod(distProps.at(j).toElement().text().toStdString().c_str(), 0) );
							else if (c->getProcessDistributionType()==FiniteElement::LINEAR ||
								     c->getProcessDistributionType()==FiniteElement::LINEAR_NEUMANN ||
									 c->getProcessDistributionType()==FiniteElement::DIRECT)
							{
								QString text = distProps.at(j).toElement().text();
								QStringList list = text.split(QRegExp("\\t"));
								size_t count(0);
								for (QStringList::iterator it=list.begin(); it!=list.end(); ++it)
								{
									std::string val (it->trimmed().toStdString());
									if (!val.empty())
									{
										if (count%2==0)
											disNodes.push_back(atoi(val.c_str()));
										else
											disValues.push_back(strtod(val.c_str(), 0));
										count++;
									}
								}
							}
							else
								std::cout << "Error in XmlCndInterface::readConditions() - Distribution type not supported." << std::endl;
							c->setDisValues(disNodes, disValues);
						}
					}
				}
			}
			conditions.push_back(c);
		}
		else
		{
			std::cout << "Error loading FEM Conditions: No geometry \"" << geometry_name << "\" found." << std::endl;
		}
		cond = cond.nextSiblingElement();
	}
}
예제 #22
0
QVariant QXmppRpcMarshaller::demarshall(const QDomElement &elem, QStringList &errors)
{
    if ( elem.tagName().toLower() != "value" )
    {
        errors << "Bad param value";
        return QVariant();
    }

    if ( !elem.firstChild().isElement() )
    {
        return QVariant( elem.text() );
    }

    const QDomElement typeData = elem.firstChild().toElement();
    const QString typeName = typeData.tagName().toLower();

    if (typeName == "nil")
    {
        return QVariant();
    }
    if ( typeName == "string" )
    {
        return QVariant( typeData.text() );
    }
    else if (typeName == "int" || typeName == "i4" )
    {
        bool ok = false;
        QVariant val( typeData.text().toInt( &ok ) );
        if (ok)
            return val;
        errors << "I was looking for an integer but data was courupt";
        return QVariant();
    }
    else if( typeName == "double" )
    {
        bool ok = false;
        QVariant val( typeData.text().toDouble( &ok ) );
        if (ok)
            return val;
        errors <<  "I was looking for an double but data was corrupt";
    }
    else if( typeName == "boolean" )
        return QVariant( typeData.text() == "1" || typeData.text().toLower() == "true" );
    else if( typeName == "datetime" || typeName == "datetime.iso8601" )
        return QVariant( QDateTime::fromString( typeData.text(), Qt::ISODate ) );
    else if( typeName == "array" )
    {
        QVariantList arr;
        QDomElement valueNode = typeData.firstChildElement("data").firstChildElement();
        while (!valueNode.isNull() && errors.isEmpty())
        {
            arr.append(demarshall(valueNode, errors));
            valueNode = valueNode.nextSiblingElement();
        }
        return QVariant( arr );
    }
    else if( typeName == "struct" )
    {
        QMap<QString,QVariant> stct;
        QDomNode valueNode = typeData.firstChild();
        while(!valueNode.isNull() && errors.isEmpty())
        {
            const QDomElement memberNode = valueNode.toElement().elementsByTagName("name").item(0).toElement();
            const QDomElement dataNode = valueNode.toElement().elementsByTagName("value").item(0).toElement();
            stct[ memberNode.text() ] = demarshall(dataNode, errors);
            valueNode = valueNode.nextSibling();
        }
        return QVariant(stct);
    }
    else if( typeName == "base64" )
    {
        QVariant returnVariant;
        QByteArray dest;
        QByteArray src = typeData.text().toLatin1();
        return QVariant(QByteArray::fromBase64(src));
    }

    errors << QString( "Cannot handle type %1").arg(typeName);
    return QVariant();
}
예제 #23
0
void DataManagerImpl::parseXml(QDomNode& dataManagerNode, QString rootPath)
{
	// look in the toolmanager, for backwards compatibility (2014-02-21)
	QDomNode toolManagerNode = dataManagerNode.parentNode().namedItem("toolManager");

	QDomNode registrationHistory = dataManagerNode.namedItem("registrationHistory");
	if (registrationHistory.isNull())
		registrationHistory = toolManagerNode.namedItem("registrationHistory");
	m_rMpr_History->parseXml(registrationHistory);

	QDomNode landmarksNode = dataManagerNode.namedItem("landmarkprops");
	QDomElement landmarkNode = landmarksNode.firstChildElement("landmarkprop");
	for (; !landmarkNode.isNull(); landmarkNode = landmarkNode.nextSiblingElement("landmarkprop"))
	{
		LandmarkProperty landmarkProp;
		landmarkProp.parseXml(landmarkNode);
		mLandmarkProperties[landmarkProp.getUid()] = landmarkProp;
		//std::cout << "Loaded landmarkprop with name: " << landmarkProp.getName() << std::endl;
		emit landmarkPropertiesChanged();
	}

	QDomNode patientLandmarksNode = dataManagerNode.namedItem("landmarks");
	if (patientLandmarksNode.isNull())
		patientLandmarksNode = toolManagerNode.namedItem("landmarks");
	mPatientLandmarks->parseXml(patientLandmarksNode);

	// All images must be created from the DataManager, so the image nodes are parsed here
	std::map<DataPtr, QDomNode> datanodes;

	QDomNode child = dataManagerNode.firstChild();
	for (; !child.isNull(); child = child.nextSibling())
	{
		if (child.nodeName() == "data")
		{
			DataPtr data = this->loadData(child.toElement(), rootPath);
			if (data)
				datanodes[data] = child.toElement();
		}
	}

	// parse xml data separately: we want to first load all data
	// because there might be interdependencies (cx::DistanceMetric)
	for (std::map<DataPtr, QDomNode>::iterator iter = datanodes.begin(); iter != datanodes.end(); ++iter)
	{
		iter->first->parseXml(iter->second);
	}

	emit dataAddedOrRemoved();

	//we need to make sure all images are loaded before we try to set an active image
	child = dataManagerNode.firstChild();
	while (!child.isNull())
	{
		if (child.toElement().tagName() == "center")
		{
			const QString centerString = child.toElement().text();
			if (!centerString.isEmpty())
			{
				Vector3D center = Vector3D::fromString(centerString);
				this->setCenter(center);
			}
		}
		child = child.nextSibling();
	}
}
bool DrugDrugInteraction::updateDomElement(QDomElement *element, QDomDocument *doc) const
{
    if (element->tagName()!="DDI")
        return false;
    element->setAttribute("i1", m_Data.value(FirstInteractorName).toString());
    element->setAttribute("i2", m_Data.value(SecondInteractorName).toString());
    element->setAttribute("i1ra", m_Data.value(FirstInteractorRouteOfAdministrationIds).toStringList().join(";"));
    element->setAttribute("i2ra", m_Data.value(SecondInteractorRouteOfAdministrationIds).toStringList().join(";"));
    element->setAttribute("l", m_Data.value(LevelCode).toString());
    element->setAttribute("a", m_Data.value(DateCreation).toString());
    element->setAttribute("lu", m_Data.value(DateLastUpdate).toString());
    element->setAttribute("v", m_Data.value(IsValid).toInt());
    element->setAttribute("rv", m_Data.value(IsReviewed).toInt());
    element->setAttribute("p", m_Data.value(PMIDsStringList).toStringList().join(";"));

    // Update risk
    QDomElement riskNode = element->firstChildElement("R");
    if (riskNode.isNull()) {
        // create risk
        QDomElement rFr = doc->createElement("R");
        rFr.setAttribute("l", "fr");
        rFr.setAttribute("t", risk("fr"));
        element->appendChild(rFr);
        QDomElement rEn = doc->createElement("R");
        rEn.setAttribute("l", "en");
        rEn.setAttribute("t", risk("en"));
        element->appendChild(rEn);
    } else {
        if (riskNode.attribute("l").compare("fr",Qt::CaseInsensitive)==0) {
            riskNode.setAttribute("t", risk("fr"));
            QDomElement rEn = riskNode.nextSiblingElement("R");
            if (rEn.isNull()) {
                rEn = doc->createElement("R");
                rEn.setAttribute("l", "en");
                element->appendChild(rEn);
            }
            rEn.setAttribute("t", risk("en"));
        } else if (riskNode.attribute("l").compare("en",Qt::CaseInsensitive)==0) {
            riskNode.setAttribute("t", risk("en"));
            QDomElement rFr = riskNode.nextSiblingElement("R");
            if (rFr.isNull()) {
                rFr = doc->createElement("R");
                rFr.setAttribute("l", "fr");
                element->appendChild(rFr);
            }
            rFr.setAttribute("t", risk("fr"));
        }
    }

    // Update management
    QDomElement manNode = element->firstChildElement("M");
    if (manNode.isNull()) {
        // create management
        QDomElement rFr = doc->createElement("M");
        rFr.setAttribute("l", "fr");
        rFr.setAttribute("t", management("fr"));
        element->appendChild(rFr);
        QDomElement rEn = doc->createElement("M");
        rEn.setAttribute("l", "en");
        rEn.setAttribute("t", management("en"));
        element->appendChild(rEn);
    } else {
        if (manNode.attribute("l").compare("fr",Qt::CaseInsensitive)==0) {
            manNode.setAttribute("t", management("fr"));
            QDomElement rEn = manNode.nextSiblingElement("M");
            if (rEn.isNull()) {
                rEn = doc->createElement("R");
                rEn.setAttribute("l", "en");
                element->appendChild(rEn);
            }
            rEn.setAttribute("t", management("en"));
        } else if (manNode.attribute("l").compare("en",Qt::CaseInsensitive)==0) {
            manNode.setAttribute("t", risk("en"));
            QDomElement rFr = manNode.nextSiblingElement("M");
            if (rFr.isNull()) {
                rFr = doc->createElement("R");
                rFr.setAttribute("l", "fr");
                element->appendChild(rFr);
            }
            rFr.setAttribute("t", management("fr"));
        }
    }

    // Update doses
//    QDomElement dose = element.firstChildElement("D");
//    while (!dose.isNull()) {
//        DrugDrugInteractionDose *ddidose = 0;
//        if (dose.attribute("i") == "1") {
//            ddidose = &m_FirstDose;
//        } else {
//            ddidose = &m_SecondDose;
//        }
//        if (dose.attribute("uf").toInt()==1) {
//            ddidose->setData(DrugDrugInteractionDose::UsesFrom, true);
//            ddidose->setData(DrugDrugInteractionDose::FromValue , dose.attribute("fv"));
//            ddidose->setData(DrugDrugInteractionDose::FromUnits, dose.attribute("fu"));
//            ddidose->setData(DrugDrugInteractionDose::FromRepartition , dose.attribute("fr"));
//        } else if (dose.attribute("ut").toInt()==1) {
//            ddidose->setData(DrugDrugInteractionDose::UsesTo, true);
//            ddidose->setData(DrugDrugInteractionDose::ToValue , dose.attribute("tv"));
//            ddidose->setData(DrugDrugInteractionDose::ToUnits, dose.attribute("tu"));
//            ddidose->setData(DrugDrugInteractionDose::ToRepartition , dose.attribute("tr"));
//        }
//        dose = dose.nextSiblingElement("D");
//    }

    // Update formalized risk
    QDomElement formNode = element->firstChildElement("F");
    if (!formNode.isNull()) {
        QDomNamedNodeMap attributeMap = formNode.attributes();
        for(int i=0; i < attributeMap.size(); ++i) {
            formNode.removeAttribute(attributeMap.item(i).nodeName());
        }
    }
    if (m_Formalized.count() > 0) {
        QHashIterator<QString,QString> i(m_Formalized);
        while (i.hasNext()) {
            i.next();
            formNode.setAttribute(i.key(), i.value());
        }
    }
    return true;
}
예제 #25
0
bool GwfObjectInfoReader::read(const QDomDocument& document)
{
    if (mIsOwner)
        del();
    mLastError.clear();

    QDomElement root = document.documentElement();

    if (root.tagName() != "GWF")
    {
        mLastError = QString(QObject::tr("Given document has unsupported format %1").arg(root.tagName()));
        return false;
    }
    else
    {
        QStringList v_list = root.attribute("version").split(".");
        mVersion.first = v_list.first().toInt();
        mVersion.second = v_list.last().toInt();
        if (mVersion != qMakePair(1, 6) && mVersion != qMakePair(2, 0))
        {
            mLastError = QString(QObject::tr("Version %1 of GWF files not supported.\n"
                                        "Just 1.6 and 2.0 versions supported.")).arg(root.attribute("version"));
            return false;
        }
    }

    // get static sector
    QDomElement staticSector = root.firstChildElement("staticSector");

    // parse nodes
    QDomElement element = staticSector.firstChildElement("node");
    while (!element.isNull())
    {
        if (!parseNode(element))
            return false;

        element = element.nextSiblingElement("node");
    }

    // parse arcs
    element = staticSector.firstChildElement("arc");
    while (!element.isNull())
    {
        if (!parsePair(element))
            return false;

        element = element.nextSiblingElement("arc");
    }

    // parse pairs
    element = staticSector.firstChildElement("pair");
    while (!element.isNull())
    {
        if (!parsePair(element))
            return false;

        element = element.nextSiblingElement("pair");
    }

    // parse bus
    element = staticSector.firstChildElement("bus");
    while (!element.isNull())
    {
        if (!parseBus(element))
            return false;

        element = element.nextSiblingElement("bus");
    }

    // parse contour
    element = staticSector.firstChildElement("contour");
    while (!element.isNull())
    {
        if (!parseContour(element))
            return false;

        element = element.nextSiblingElement("contour");
    }
    return true;
}
QgsFeatureRendererV2* QgsSingleSymbolRendererV2::createFromSld( QDomElement& element, QGis::GeometryType geomType )
{
  // XXX this renderer can handle only one Rule!

  // get the first Rule element
  QDomElement ruleElem = element.firstChildElement( "Rule" );
  if ( ruleElem.isNull() )
  {
    QgsDebugMsg( "no Rule elements found!" );
    return NULL;
  }

  QString label, description;
  QgsSymbolLayerV2List layers;

  // retrieve the Rule element child nodes
  QDomElement childElem = ruleElem.firstChildElement();
  while ( !childElem.isNull() )
  {
    if ( childElem.localName() == "Name" )
    {
      // <se:Name> tag contains the rule identifier,
      // so prefer title tag for the label property value
      if ( label.isEmpty() )
        label = childElem.firstChild().nodeValue();
    }
    else if ( childElem.localName() == "Description" )
    {
      // <se:Description> can contains a title and an abstract
      QDomElement titleElem = childElem.firstChildElement( "Title" );
      if ( !titleElem.isNull() )
      {
        label = titleElem.firstChild().nodeValue();
      }

      QDomElement abstractElem = childElem.firstChildElement( "Abstract" );
      if ( !abstractElem.isNull() )
      {
        description = abstractElem.firstChild().nodeValue();
      }
    }
    else if ( childElem.localName() == "Abstract" )
    {
      // <sld:Abstract> (v1.0)
      description = childElem.firstChild().nodeValue();
    }
    else if ( childElem.localName() == "Title" )
    {
      // <sld:Title> (v1.0)
      label = childElem.firstChild().nodeValue();
    }
    else if ( childElem.localName().endsWith( "Symbolizer" ) )
    {
      // create symbol layers for this symbolizer
      QgsSymbolLayerV2Utils::createSymbolLayerV2ListFromSld( childElem, geomType, layers );
    }

    childElem = childElem.nextSiblingElement();
  }

  if ( layers.size() == 0 )
    return NULL;

  // now create the symbol
  QgsSymbolV2 *symbol;
  switch ( geomType )
  {
    case QGis::Line:
      symbol = new QgsLineSymbolV2( layers );
      break;

    case QGis::Polygon:
      symbol = new QgsFillSymbolV2( layers );
      break;

    case QGis::Point:
      symbol = new QgsMarkerSymbolV2( layers );
      break;

    default:
      QgsDebugMsg( QString( "invalid geometry type: found %1" ).arg( geomType ) );
      return NULL;
  }

  // and finally return the new renderer
  return new QgsSingleSymbolRendererV2( symbol );
}
예제 #27
0
파일: parser.cpp 프로젝트: mbahar94/KDSoap
bool Parser::parseSchemaTag( ParserContext *context, const QDomElement &root )
{
  QName name(root.tagName());
  if ( name.localName() != QLatin1String("schema") ) {
    qDebug() << "ERROR localName=" << name.localName();
    return false;
  }

  // Already done by caller when coming from type.cpp, but doesn't hurt to do twice
  context->namespaceManager()->enterChild(root);

  // This method can call itself recursively, so save/restore the member attribute.
  QString oldNamespace = d->mNameSpace;
  if ( root.hasAttribute( QLatin1String("targetNamespace") ) )
    d->mNameSpace = root.attribute( QLatin1String("targetNamespace") );

  if (root.attribute( QLatin1String("elementFormDefault") ) == QLatin1String("qualified"))
      d->mDefaultQualifiedElements = true;

  if (root.attribute( QLatin1String("attributeFormDefault") ) == QLatin1String("qualified"))
      d->mDefaultQualifiedAttributes = true;

 // mTypesTable.setTargetNamespace( mNameSpace );

  QDomElement element = root.firstChildElement();
  while ( !element.isNull() ) {
    NSManager namespaceManager( context, element );
    const QName name( element.tagName() );
    if (debugParsing())
        qDebug() << "Schema: parsing" << name.localName();
    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 );
      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, d->mNameSpace ) );
    } else if ( name.localName() == QLatin1String("attributeGroup") ) {
      d->mAttributeGroups.append( parseAttributeGroup( context, element, d->mNameSpace ) );
    } else if ( name.localName() == QLatin1String("group") ) {
      d->mGroups.append( parseGroup( context, element, d->mNameSpace ) );
    } else if ( name.localName() == QLatin1String("annotation") ) {
      d->mAnnotations = parseAnnotation( context, element );
    } else if ( name.localName() == QLatin1String("include") ) {
      parseInclude( context, element );
    } else {
        qWarning() << "Unsupported schema element" << name.localName();
    }

    element = element.nextSiblingElement();
  }

  if (!resolveForwardDeclarations())
      return false;

  d->mNameSpace = oldNamespace;

  return true;
}
예제 #28
0
bool Converter::convertTable(const QDomElement &element)
{
    /**
     * Find out dimension of the table
     */

    int rowCounter = 0;
    int columnCounter = 0;

    QQueue<QDomNode> nodeQueue;
    enqueueNodeList(nodeQueue, element.childNodes());
    while (!nodeQueue.isEmpty())
    {
        QDomElement el = nodeQueue.dequeue().toElement();
        if (el.isNull())
            continue;

        if (el.tagName() == QLatin1String("table-row"))
        {
            rowCounter++;

            int counter = 0;
            QDomElement columnElement = el.firstChildElement();
            while (!columnElement.isNull())
            {
                if (columnElement.tagName() == QLatin1String("table-cell"))
                {
                    counter++;
                }
                columnElement = columnElement.nextSiblingElement();
            }

            columnCounter = qMax(columnCounter, counter);
        }
        else if (el.tagName() == QLatin1String("table-header-rows"))
        {
            enqueueNodeList(nodeQueue, el.childNodes());
        }
    }

    /**
     * Create table
     */
    QTextTable *table = m_Cursor->insertTable(rowCounter, columnCounter);
    firstTime=false;
    m_Cursor->movePosition(QTextCursor::End);

    /**
     * Fill table
     */
    nodeQueue.clear();
    enqueueNodeList(nodeQueue, element.childNodes());

    QTextTableFormat tableFormat;

    rowCounter = 0;
    while (!nodeQueue.isEmpty())
    {
        QDomElement el = nodeQueue.dequeue().toElement();
        if (el.isNull())
            continue;

        if (el.tagName() == QLatin1String("table-row"))
        {
            int columnCounter = 0;
            QDomElement columnElement = el.firstChildElement();
            while (!columnElement.isNull())
            {
                if (columnElement.tagName() == QLatin1String("table-cell"))
                {
                    const StyleFormatProperty property = m_StyleInformation->styleProperty(columnElement.attribute("style-name"));

                    QTextBlockFormat format;
                    property.applyTableCell(&format);

                    QDomElement paragraphElement = columnElement.firstChildElement();
                    while (!paragraphElement.isNull())
                    {
                        if (paragraphElement.tagName() == QLatin1String("p"))
                        {
                            QTextTableCell cell = table->cellAt(rowCounter, columnCounter);
                            // Insert a frame into the cell and work on that, so we can handle
                            // different parts of the cell having different block formatting
                            QTextCursor cellCursor = cell.lastCursorPosition();
                            QTextFrameFormat frameFormat;
                            //frameFormat.setMargin(1); // TODO: this shouldn't be hard coded
                            //todo: too much is created here - why?
                            QTextFrame *frame = cellCursor.insertFrame(frameFormat);
                            QTextCursor frameCursor = frame->firstCursorPosition();
                            frameCursor.setBlockFormat(format);

                            if (!convertParagraph(&frameCursor, paragraphElement, format))
                                return false;
                        }
                        else if (paragraphElement.tagName() == QLatin1String("list"))
                        {
                            QTextTableCell cell = table->cellAt(rowCounter, columnCounter);
                            // insert a list into the cell
                            QTextCursor cellCursor = cell.lastCursorPosition();
                            if (!convertList(&cellCursor, paragraphElement))
                            {
                                return false;
                            }
                        }

                        paragraphElement = paragraphElement.nextSiblingElement();
                    }
                    columnCounter++;
                }
                columnElement = columnElement.nextSiblingElement();
            }

            rowCounter++;
        }
        else if (el.tagName() == QLatin1String("table-column"))
        {
            const StyleFormatProperty property = m_StyleInformation->styleProperty(el.attribute("style-name"));
            const QString tableColumnNumColumnsRepeated = el.attribute("number-columns-repeated", "1");
            int numColumnsToApplyTo = tableColumnNumColumnsRepeated.toInt();
            for (int i = 0; i < numColumnsToApplyTo; ++i)
            {
                property.applyTableColumn(&tableFormat);
            }
        }
    }

    table->setFormat(tableFormat);

    return true;
}
예제 #29
0
CClass* CDecodeFlowType::readClassType ( const QDomElement& element)
{
  bool bOk = false;
  CClass* cl = NULL;
  
  QDomElement id = element.firstChildElement("id");
  QDomElement name = element.firstChildElement("name");
  QDomElement definition = element.firstChildElement("definition");
  QDomElement readOnly = element.firstChildElement("read-only");
  QDomElement values = element.firstChildElement("values");
  QDomElement type = element.firstChildElement("type");

  switch (type.text().toInt())
  {
    case CClass::VOID:
    {
      CVoid* v = new CVoid(name.text(), definition.text());
      v->setId(id.text().toInt(&bOk));
      v->setReadOnly((readOnly.text().toInt(&bOk)));
      cl = v;
      bOk = true;
    }
      break;
      
    case CClass::ENUMERATION:
    {
      CEnumeration* e = new CEnumeration(name.text(), definition.text());
      e->setId(id.text().toInt(&bOk));
      e->setReadOnly((readOnly.text().toInt(&bOk)));
      QDomElement data = values.firstChildElement("string");
      while (!data.isNull())
      {
        e->append(data.text());
        data = data.nextSiblingElement("string");
      }
      bOk = true;
      cl = e;
    }
      break;
    
    case CClass::NUMBER:
    {
      CNumber* n = new CNumber(name.text(), definition.text());
      n->setId(id.text().toInt(&bOk));
      n->setReadOnly((readOnly.text().toInt(&bOk)));
      QDomElement range = values.firstChildElement("range");
      if (!range.isNull())
      {
        Range r;
        r.begin = range.attribute("begin").toLongLong(&bOk);
        if (!bOk)
        {
          // try with uLongLong
          r.begin = range.attribute("begin").toULongLong(&bOk);
        }
        r.end = range.attribute("end").toLongLong(&bOk);
        if (!bOk)
        {
          // try with uLongLong
          r.end = range.attribute("end").toULongLong(&bOk);
        }
        r.beginName = range.attribute("begin-name");
        r.endName = range.attribute("end-name");
        n->insertRange(r);
        bOk = true;
      }
      else 
        bOk = false;
      
      cl = n;
    }
      break;
    
    case CClass::FLOAT:
    {
      CFloat* f = new CFloat(name.text(), definition.text());
      f->setId(id.text().toInt(&bOk));
      f->setReadOnly((readOnly.text().toInt(&bOk)));
      QDomElement range = values.firstChildElement("range");
      if (!range.isNull())
      {
        Range r;
        r.begin = range.attribute("begin").toDouble(&bOk);
        r.end = range.attribute("end").toDouble(&bOk);
        r.beginName = range.attribute("begin-name");
        r.endName = range.attribute("end-name");
        f->insertRange(r);
        bOk = true;
      }
      else 
        bOk = false;
      
      cl = f;
    }
      break;
      
    case CClass::CHAR:
    {
      CChar* c = new CChar(name.text(), definition.text());
      c->setId(id.text().toInt(&bOk));
      c->setReadOnly((readOnly.text().toInt(&bOk)));
      QDomElement range = values.firstChildElement("range");
      if (!range.isNull())
      {
        Range r;
        r.begin = range.attribute("begin").toInt(&bOk);
        r.end = range.attribute("end").toInt(&bOk);
        r.beginName = range.attribute("begin-name");
        r.endName = range.attribute("end-name");
        c->insertRange(r);
        bOk = true;
      }
      else 
        bOk = false;
      
      cl = c;
    }
      break;
      
    case CClass::STRING:
    {
      CString* s = new CString(name.text(), definition.text());
      s->setId(id.text().toInt(&bOk));
      s->setReadOnly((readOnly.text().toInt(&bOk)));
      QDomElement size = values.firstChildElement("size");
      if (!size.isNull())
      {
        s->setSize(size.text().toInt(&bOk));
        bOk = true;
      }
      else 
        bOk = false;
      
      cl = s;
    }
      break;
      
    case CClass::AGGREGATION:
    {
      CStructure* s = new CStructure(name.text(), definition.text());
      s->setId(id.text().toInt(&bOk));
      s->setReadOnly((readOnly.text().toInt(&bOk)));
      QDomElement structure = values.firstChildElement("structure");
      while (!structure.isNull() && !bOk)
      {
        Structure st;
        st.name = structure.attribute("name");
        st.classId = structure.attribute("type").toInt(&bOk);
        st.pClass = NULL;
        if (bOk == true)
        {
          s->insertField(st);
        }
        structure = structure.nextSiblingElement("structure");
      }      
      cl = s;
    }
      break;
      
    default:
      bOk = false;
      break;
  }
  
  if ((bOk == false) & (cl != NULL))
  {
    delete cl;
    cl = NULL;
  }
  
  return cl;
}
void PokeTeam::loadFromXml(const QDomElement &poke, int version)
{
    if (poke.hasAttribute("Gen")) {
        setGen(poke.attribute("Gen").toInt());
    }

    reset();

    /* Code to import old teams which had different formes registered as different pokemon numbers */
    int num = poke.attribute("Num").toInt();
    int forme = poke.attribute("Forme").toInt();

    if (gen() == 4 && num > 493 && forme == 0 && !PokemonInfo::Exists(Pokemon::uniqueId(num, 0), 4)) {
        //Old way
        int indexes[] = {
            479,479,479,479,479,386,386,386,413,413,492,487
        };
        int formes[] = {
            1,2,3,4,5,1,2,3,1,2,1,1
        };

        int i = num - 494;

        setNum(Pokemon::uniqueId(indexes[i], formes[i]));
    } else {
        setNum(Pokemon::uniqueId(num, forme));
    }

    bool outdated = gen() < 5 && version < 1;

    load();
    nickname() = poke.attribute("Nickname");
    item() = poke.attribute("Item").toInt();
    ability() = poke.attribute("Ability").toInt();
    if (outdated) {
        ability() = AbilityInfo::ConvertFromOldAbility(ability());
    }
    nature() = poke.attribute("Nature").toInt();
    gender() = poke.attribute("Gender").toInt();
    shiny() = QVariant(poke.attribute("Shiny")).toBool();
    happiness() = poke.attribute("Happiness").toInt();
    level() = poke.attribute("Lvl").toInt();

    int cptMove=0;

    QDomElement moveElement = poke.firstChildElement("Move");
    while(!moveElement.isNull())
    {
        int movenum = moveElement.text().toInt();
        if (outdated) {
            movenum = MoveInfo::ConvertFromOldMove(movenum);
        }
        setMove(movenum,cptMove,false);
        cptMove++;
        moveElement = moveElement.nextSiblingElement("Move");
    }
    int cptDV=0;
    QDomElement DVElement = poke.firstChildElement("DV");
    while(!DVElement.isNull())
    {
        setDV(outdated ? NatureInfo::ConvertToStat(cptDV) : cptDV,DVElement.text().toInt());
        cptDV++;
        DVElement = DVElement.nextSiblingElement("DV");
    }
    int cptEV=0;
    QDomElement EVElement = poke.firstChildElement("EV");
    while(!EVElement.isNull())
    {
        setEV(outdated ? NatureInfo::ConvertToStat(cptEV) : cptEV,EVElement.text().toInt());
        cptEV++;
        EVElement = EVElement.nextSiblingElement("EV");
    }
}