コード例 #1
0
void QgsProjectFileTransform::transform0110to1000()
{
  if ( ! mDom.isNull() )
  {
    QDomNodeList layerList = mDom.elementsByTagName( QStringLiteral( "maplayer" ) );
    for ( int i = 0; i < layerList.size(); ++i )
    {
      QDomElement layerElem = layerList.at( i ).toElement();
      QString typeString = layerElem.attribute( QStringLiteral( "type" ) );
      if ( typeString != QLatin1String( "vector" ) )
      {
        continue;
      }

      //datasource
      QDomNode dataSourceNode = layerElem.namedItem( QStringLiteral( "datasource" ) );
      if ( dataSourceNode.isNull() )
      {
        return;
      }
      QString dataSource = dataSourceNode.toElement().text();

      //provider key
      QDomNode providerNode = layerElem.namedItem( QStringLiteral( "provider" ) );
      if ( providerNode.isNull() )
      {
        return;
      }
      QString providerKey = providerNode.toElement().text();

      //create the layer to get the provider for int->fieldName conversion
      QgsVectorLayer* theLayer = new QgsVectorLayer( dataSource, QLatin1String( "" ), providerKey, false );
      if ( !theLayer->isValid() )
      {
        delete theLayer;
        return;
      }

      QgsVectorDataProvider* theProvider = theLayer->dataProvider();
      if ( !theProvider )
      {
        return;
      }
      QgsFields theFields = theProvider->fields();

      //read classificationfield
      QDomNodeList classificationFieldList = layerElem.elementsByTagName( QStringLiteral( "classificationfield" ) );
      for ( int j = 0; j < classificationFieldList.size(); ++j )
      {
        QDomElement classificationFieldElem = classificationFieldList.at( j ).toElement();
        int fieldNumber = classificationFieldElem.text().toInt();
        if ( fieldNumber >= 0 && fieldNumber < theFields.count() )
        {
          QDomText fieldName = mDom.createTextNode( theFields.at( fieldNumber ).name() );
          QDomNode nameNode = classificationFieldElem.firstChild();
          classificationFieldElem.replaceChild( fieldName, nameNode );
        }
      }

    }
  }
}
コード例 #2
0
ファイル: GraphMLImporter.cpp プロジェクト: kapecp/3dsoftviz
bool GraphMLImporter::processGraph_Edges(
	QDomElement& graphElement
)
{
	bool ok = true;

	iColor_ = 0;

	// default direction
	bool defaultDirection;
	if ( graphElement.attribute( "edgedefault" ) == "directed" ) {
		defaultDirection = true;
	}
	else {
		defaultDirection = false;
	}

	// edges
	for ( QDomElement edgeElement = graphElement.firstChildElement( "edge" ); ok && !edgeElement.isNull(); edgeElement = edgeElement.nextSiblingElement( "edge" ) ) {
		QString sourceId = edgeElement.attribute( "source" );
		QString targetId = edgeElement.attribute( "target" );

		QString direction = NULL;
		bool directed = false;
		direction = edgeElement.attribute( "directed" );
		if ( direction == NULL ) {
			directed = defaultDirection;
			if ( directed ) {
				direction = "_directed";
			}
			else {
				direction = "";
			}
		}
		else {
			if ( direction == "true" ) {
				direction = "_directed";
				directed = true;
			}
			else {
				direction = "";
				directed = false;
			}
		}

		// pozerame sa na data ktore hrana nesie
		Data::Type* newEdgeType;
		newEdgeType = NULL;
		QDomNodeList edgeDataList = edgeElement.elementsByTagName( "data" );
		for ( unsigned int j = 0; j < edgeDataList.length(); j++ ) {
			QDomNode edgeData = edgeDataList.item( static_cast<int>( j ) );
			if ( !edgeData.isNull() && edgeData.isElement() ) {
				QDomElement edgeDataElement = edgeData.toElement();
				QString dataName = edgeDataElement.attribute( "key" );
				QString dataValue = edgeDataElement.text();
				// rozpoznavame typy deklarovane atributom relation
				if ( dataName == edgeTypeAttribute_ ) {
					// overime ci uz dany typ existuje v grafe
					QList<Data::Type*> types = context_->getGraph().getTypesByName( dataValue+direction );
					if ( types.isEmpty() ) {
						QMap<QString, QString>* settings = new QMap<QString, QString>;

						// FIXME spravit tak, aby to rotovalo po tom poli - palo az to budes prerabat tak pre hrany pouzi ine pole, take co ma alfu na 0.5.. a to sa tyka aj uzlov s defaultnym typom
						settings->insert( "color.R", QString::number( colors_[iColor_][0] ) );
						settings->insert( "color.G", QString::number( colors_[iColor_][1] ) );
						settings->insert( "color.B", QString::number( colors_[iColor_][2] ) );
						settings->insert( "color.A", QString::number( colors_[iColor_][3] ) );
						settings->insert( "scale",		Util::ApplicationConfig::get()->getValue( "Viewer.Textures.DefaultNodeScale" ) );

						if ( !directed ) {
							settings->insert( "textureFile", Util::ApplicationConfig::get()->getValue( "Viewer.Textures.Edge" ) );
						}
						else {
							settings->insert( "textureFile", Util::ApplicationConfig::get()->getValue( "Viewer.Textures.OrientedEdgePrefix" ) );
							settings->insert( "textureFile", Util::ApplicationConfig::get()->getValue( "Viewer.Textures.OrientedEdgeSuffix" ) );
						}

						newEdgeType = context_->getGraph().addType( dataValue+direction, settings );

						iColor_++;
						if ( iColor_ == colors_.size() ) {
							iColor_ = 0;
						}
					}
					else {
						newEdgeType = types.first();
					}

				}
				else {
					// kazde dalsie data nacitame do nosica dat - Edge.name
					// FIXME potom prerobit cez Adamove Node.settings
				}
			}
		}

		// ak nebol najdeny typ, tak pouzijeme defaulty
		if ( newEdgeType == NULL ) {
			newEdgeType = edgeType_;
		}

		context_->getGraph().addEdge( sourceId+targetId, readNodes_->get( sourceId ), readNodes_->get( targetId ), newEdgeType, directed );

		// vnorene grafy
		for ( QDomElement subgraphElement = edgeElement.firstChildElement( "graph" ); ok && !subgraphElement.isNull(); subgraphElement = subgraphElement.nextSiblingElement( "graph" ) ) {
			if ( ok ) {
				// TODO: begin subgraph in edge
			}

			if ( ok ) {
				ok = processGraph( subgraphElement );
			}

			if ( ok ) {
				// TODO: end subgraph in edge
			}
		}

		entitiesProcessed_++;
		context_->getInfoHandler().setProgress( static_cast<unsigned int>( entitiesProcessed_ * 100 / entitiesCount_ ) );
	}

	return ok;
}
コード例 #3
0
ファイル: GraphMLImporter.cpp プロジェクト: kapecp/3dsoftviz
bool GraphMLImporter::processGraph_Nodes(
	QDomElement& graphElement
)
{
	bool ok = true;

	iColor_ = 0;

	// nodes
	for ( QDomElement nodeElement = graphElement.firstChildElement( "node" ); ok && !nodeElement.isNull(); nodeElement = nodeElement.nextSiblingElement( "node" ) ) {
		QString nameId = nodeElement.attribute( "id" );
		QString name = NULL;
		// pozerame sa na data ktore nesie
		Data::Type* newNodeType;
		newNodeType = NULL;
		QDomNodeList nodeDataList = nodeElement.elementsByTagName( "data" );
		for ( unsigned int j = 0; j < nodeDataList.length(); j++ ) {
			QDomNode nodeData = nodeDataList.item( static_cast<int>( j ) );
			if ( !nodeData.isNull() && nodeData.isElement() ) {
				QDomElement nodeDataElement = nodeData.toElement();
				QString dataName = nodeDataElement.attribute( "key" );
				QString dataValue = nodeDataElement.text();
				// rozpoznavame typy
				if ( dataName == nodeTypeAttribute_ ) {
					// overime ci uz dany typ existuje v grafe
					QList<Data::Type*> types = context_->getGraph().getTypesByName( dataValue );
					if ( types.isEmpty() ) {
						QMap<QString, QString>* settings = new QMap<QString, QString>;

						settings->insert( "color.R", QString::number( colors_[iColor_][0] ) );
						settings->insert( "color.G", QString::number( colors_[iColor_][1] ) );
						settings->insert( "color.B", QString::number( colors_[iColor_][2] ) );
						settings->insert( "color.A", QString::number( colors_[iColor_][3] ) );
						settings->insert( "scale",		Util::ApplicationConfig::get()->getValue( "Viewer.Textures.DefaultNodeScale" ) );
						settings->insert( "textureFile", Util::ApplicationConfig::get()->getValue( "Viewer.Textures.Node" ) );

						newNodeType = context_->getGraph().addType( dataValue, settings );

						iColor_++;
						if ( iColor_ == colors_.size() ) {
							iColor_ = 0;
						}
					}
					else {
						newNodeType = types.first();
					}

				}
				else {
					// kazde dalsie data nacitame do nosica dat - Node.name
					// FIXME potom prerobit cez Adamove Node.settings
					if ( name == NULL ) {
						name = dataName+":"+dataValue;
					}
					else {
						name += " | "+dataName+":"+dataValue;
					}
				}
			}
		}

		// ak sme nenasli name, tak ako name pouzijeme aspon ID
		if ( name == NULL ) {
			name = nameId;
		}

		// ak nebol najdeny ziaden typ, tak pouzijeme defaultny typ
		osg::ref_ptr<Data::Node> node;
		if ( newNodeType == NULL ) {
			node = context_->getGraph().addNode( name, nodeType_ );
		}
		else {
			node = context_->getGraph().addNode( name, newNodeType );
		}
		readNodes_->addNode( nameId, node );

		// subgraphs
		for ( QDomElement subgraphElement = nodeElement.firstChildElement( "graph" ); ok && !subgraphElement.isNull(); subgraphElement = subgraphElement.nextSiblingElement( "graph" ) ) {
			if ( ok ) {
				context_->getGraph().createNestedGraph( node );
			}

			if ( ok ) {
				ok = processGraph( subgraphElement );
			}

			if ( ok ) {
				context_->getGraph().closeNestedGraph();
			}
		}

		entitiesProcessed_++;
		context_->getInfoHandler().setProgress( static_cast<unsigned int>( entitiesProcessed_ * 100 / entitiesCount_ ) );
	}

	return ok;
}
コード例 #4
0
ファイル: upnpdevice.cpp プロジェクト: microe/mythtv
void UPnpDeviceDesc::_InternalLoad( QDomNode oNode, UPnpDevice *pCurDevice )
{
    QString pin = GetMythDB()->GetSetting( "SecurityPin", "");
    pCurDevice->m_securityPin = (pin.isEmpty() || pin == "0000") ?
                                false : true;

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

        if (!e.isNull())
        {
            if ( e.tagName() == "deviceType"       )
            { SetStrValue( e, pCurDevice->m_sDeviceType      ); continue; }
            if ( e.tagName() == "friendlyName"     )
            { SetStrValue( e, pCurDevice->m_sFriendlyName    ); continue; }
            if ( e.tagName() == "manufacturer"     )
            { SetStrValue( e, pCurDevice->m_sManufacturer    ); continue; }
            if ( e.tagName() == "manufacturerURL"  )
            { SetStrValue( e, pCurDevice->m_sManufacturerURL ); continue; }
            if ( e.tagName() == "modelDescription" )
            { SetStrValue( e, pCurDevice->m_sModelDescription); continue; }
            if ( e.tagName() == "modelName"        )
            { SetStrValue( e, pCurDevice->m_sModelName       ); continue; }
            if ( e.tagName() == "modelNumber"      )
            { SetStrValue( e, pCurDevice->m_sModelNumber     ); continue; }
            if ( e.tagName() == "modelURL"         )
            { SetStrValue( e, pCurDevice->m_sModelURL        ); continue; }
            if ( e.tagName() == "serialNumber"     )
            { SetStrValue( e, pCurDevice->m_sSerialNumber    ); continue; }
            if ( e.tagName() == "UPC"              )
            { SetStrValue( e, pCurDevice->m_sUPC             ); continue; }
            if ( e.tagName() == "presentationURL"  )
            { SetStrValue( e, pCurDevice->m_sPresentationURL ); continue; }
            if ( e.tagName() == "UDN"              )
            { SetStrValue( e, pCurDevice->m_sUDN             ); continue; }

            if ( e.tagName() == "iconList"         )
            { ProcessIconList   ( oNode, pCurDevice ); continue; }
            if ( e.tagName() == "serviceList"      )
            { ProcessServiceList( oNode, pCurDevice ); continue; }
            if ( e.tagName() == "deviceList"       )
            { ProcessDeviceList ( oNode, pCurDevice ); continue; }

            if ( e.tagName() == "mythtv:X_secure"  )
            { SetBoolValue( e, pCurDevice->m_securityPin ); continue; }
            if ( e.tagName() == "mythtv:X_protocol"  )
            { SetStrValue( e, pCurDevice->m_protocolVersion ); continue; }

            // 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));
        }
    }
}
コード例 #5
0
ファイル: kdupdaterupdatesinfo.cpp プロジェクト: KDAB/KDTools
void UpdatesInfo::Private::parseFile(const QString& updateXmlFile)
{
    QFile file( updateXmlFile );
    if( !file.open(QFile::ReadOnly) )
    {
        error = UpdatesInfo::CouldNotReadUpdateInfoFileError;
        errorMessage = tr("Could not read \"%1\"").arg(updateXmlFile);
        return;
    }

    QDomDocument doc;
    QString parseErrorMessage;
    int parseErrorLine;
    int parseErrorColumn;
    if( !doc.setContent( &file, &parseErrorMessage, &parseErrorLine, &parseErrorColumn ) )
    {
        error = UpdatesInfo::InvalidXmlError;
        errorMessage = tr("Parse error in %1 at %2, %3: %4")
                      .arg( updateXmlFile, 
                            QString::number( parseErrorLine ),
                            QString::number( parseErrorColumn ),
                            parseErrorMessage );
        return;
    }

    const QDomElement rootE = doc.documentElement();
    if( rootE.tagName() != QLatin1String( "Updates" ) )
    {
        setInvalidContentError(tr("root element %1 unexpected, should be \"Updates\"").arg(rootE.tagName()));
        return;
    }

    const QDomNodeList childNodes = rootE.childNodes();
    for(int i=0; i<childNodes.count(); i++)
    {
        const QDomNode childNode = childNodes.at(i);
        const QDomElement childE = childNode.toElement();
        if( childE.isNull() )
            continue;

        if ( childE.tagName() == QLatin1String( "TargetName" ) ||
             childE.tagName() == QLatin1String( "ApplicationName" ) ) // backwards compat
            targetName = childE.text();
        else if ( childE.tagName() == QLatin1String( "TargetVersion" ) ||
                  childE.tagName() == QLatin1String( "ApplicationVersion" ) ) // backwards compat
            targetVersion = childE.text();
        else if( childE.tagName() == QLatin1String( "RequiredCompatLevel" ) )
            compatLevel = childE.text().toInt();
        else if( childE.tagName() == QLatin1String( "PackageUpdate" ) ) {
            const bool res = parsePackageUpdateElement( childE );
            if (!res) {
                //error handled in subroutine
                return;
            }
        } else if( childE.tagName() == QLatin1String( "CompatUpdate" ) ) {
            const bool res = parseCompatUpdateElement( childE );
            if (!res) {
                //error handled in subroutine
                return;
            }
        }
    }

    if ( targetName.isEmpty() )
    {
        setInvalidContentError( tr("TargetName element is missing") );
        return;
    }
    
    if ( targetVersion.isEmpty() )
    {
        setInvalidContentError(tr("TargetVersion element is missing"));
        return;
    }
    
    error = UpdatesInfo::NoError;
    errorMessage.clear();
}
コード例 #6
0
QBrush XMLParseBase::parseGradient(const QDomElement &element)
{
    QLinearGradient gradient;
    QString gradientStart = element.attribute("start", "");
    QString gradientEnd = element.attribute("end", "");
    int gradientAlpha = element.attribute("alpha", "255").toInt();
    QString direction = element.attribute("direction", "vertical");

    float x1, y1, x2, y2 = 0.0;
    if (direction == "vertical")
    {
        x1 = 0.5;
        x2 = 0.5;
        y1 = 0.0;
        y2 = 1.0;
    }
    else if (direction == "diagonal")
    {
        x1 = 0.0;
        x2 = 1.0;
        y1 = 0.0;
        y2 = 1.0;
    }
    else
    {
        x1 = 0.0;
        x2 = 1.0;
        y1 = 0.5;
        y2 = 0.5;
    }

    gradient.setCoordinateMode(QGradient::ObjectBoundingMode);
    gradient.setStart(x1, y1);
    gradient.setFinalStop(x2, y2);

    QGradientStops stops;

    if (!gradientStart.isEmpty())
    {
        QColor startColor = QColor(gradientStart);
        startColor.setAlpha(gradientAlpha);
        QGradientStop stop(0.0, startColor);
        stops.append(stop);
    }

    if (!gradientEnd.isEmpty())
    {
        QColor endColor = QColor(gradientEnd);
        endColor.setAlpha(gradientAlpha);
        QGradientStop stop(1.0, endColor);
        stops.append(stop);
    }

    for (QDomNode child = element.firstChild(); !child.isNull();
        child = child.nextSibling())
    {
        QDomElement childElem = child.toElement();
        if (childElem.tagName() == "stop")
        {
            float position = childElem.attribute("position", "0").toFloat();
            QString color = childElem.attribute("color", "");
            int alpha = childElem.attribute("alpha", "-1").toInt();
            if (alpha < 0)
                alpha = gradientAlpha;
            QColor stopColor = QColor(color);
            stopColor.setAlpha(alpha);
            QGradientStop stop((position / 100), stopColor);
            stops.append(stop);
        }
    }

    gradient.setStops(stops);

    return QBrush(gradient);
}
コード例 #7
0
MythUIType *XMLParseBase::ParseUIType(
    const QString &filename,
    QDomElement &element, const QString &type,
    MythUIType *parent,
    MythScreenType *screen,
    bool showWarnings)
{
    QString name = element.attribute("name", "");
    if (name.isEmpty())
    {
        VERBOSE_XML(VB_IMPORTANT, filename, element,
                    LOC_ERR + "This element requires a name");
        return NULL;
    }

    MythUIType *olduitype = NULL;

    // check for name in immediate parent as siblings cannot share names
    if (parent && parent->GetChild(name))
    {
        // if we're the global object store, assume it's just a theme overriding
        // the defaults..
        if (parent == GetGlobalObjectStore())
            return NULL;

        // Reuse the existing child and reparse
        olduitype = parent->GetChild(name);
    }

    MythUIType *uitype = NULL;
    MythUIType *base = NULL;

    QString inherits = element.attribute("from", "");
    if (!inherits.isEmpty())
    {
        if (parent)
            base = parent->GetChild(inherits);

        // might remove this
        if (screen && !base)
            base = screen->GetChild(inherits);

        if (!base)
            base = GetGlobalObjectStore()->GetChild(inherits);

        if (!base)
        {
            VERBOSE_XML(VB_IMPORTANT, filename, element,
                        LOC_ERR + QString(
                            "Couldn't find object '%1' to inherit '%2' from")
                        .arg(inherits).arg(name));
            return NULL;
        }
    }

    if (type == "imagetype")
        uitype = new MythUIImage(parent, name);
    else if (type == "textarea")
        uitype = new MythUIText(parent, name);
    else if (type == "group")
        uitype = new MythUIGroup(parent, name);
    else if (type == "textedit")
        uitype = new MythUITextEdit(parent, name);
    else if (type == "button")
        uitype = new MythUIButton(parent, name);
    else if (type == "buttonlist2" || type == "buttonlist")
        uitype = new MythUIButtonList(parent, name);
    else if (type == "buttontree")
        uitype = new MythUIButtonTree(parent, name);
    else if (type == "spinbox")
        uitype = new MythUISpinBox(parent, name);
    else if (type == "checkbox")
        uitype = new MythUICheckBox(parent, name);
    else if (type == "statetype")
        uitype = new MythUIStateType(parent, name);
    else if (type == "clock")
        uitype = new MythUIClock(parent, name);
    else if (type == "progressbar")
        uitype = new MythUIProgressBar(parent, name);
    else if (type == "webbrowser")
        uitype = new MythUIWebBrowser(parent, name);
    else if (type == "guidegrid")
        uitype = new MythUIGuideGrid(parent, name);
    else if (type == "shape")
        uitype = new MythUIShape(parent, name);
    else if (type == "editbar")
        uitype = new MythUIEditBar(parent, name);
    else if (type == "window" && parent == GetGlobalObjectStore())
        uitype = new MythScreenType(parent, name);
    else
    {
        VERBOSE_XML(VB_IMPORTANT, filename, element,
                    LOC_ERR + "Unknown widget type.");
        return NULL;
    }

    if (!uitype)
    {
        VERBOSE_XML(VB_IMPORTANT, filename, element,
                    LOC_ERR + "Failed to instantiate widget type.");
        return NULL;
    }

    if (olduitype)
    {
        if (typeid(*olduitype) != typeid(*uitype))
        {
            VERBOSE_XML(VB_IMPORTANT, filename, element, LOC_ERR +
                        QString("Duplicate name: '%1' in parent '%2'")
                        .arg(name).arg(parent->objectName()));
            parent->DeleteChild(olduitype);
        }
        else
        {
            parent->DeleteChild(uitype);
            uitype = olduitype;
        }
    }

    if (base)
    {
        if (typeid(*base) != typeid(*uitype))
        {
            VERBOSE_XML(VB_IMPORTANT, filename, element, LOC_ERR +
                        QString("Type of new widget '%1' doesn't "
                                "match old '%2'")
                        .arg(name).arg(inherits));
            parent->DeleteChild(uitype);
            return NULL;
        }
        else
            uitype->CopyFrom(base);
    }

    for (QDomNode child = element.firstChild(); !child.isNull();
         child = child.nextSibling())
    {
        QDomElement info = child.toElement();
        if (!info.isNull())
        {
            if (uitype->ParseElement(filename, info, showWarnings))
            {
            }
            else if (info.tagName() == "font" || info.tagName() == "fontdef")
            {
                bool global = (GetGlobalObjectStore() == parent);
                MythFontProperties *font = MythFontProperties::ParseFromXml(
                    filename, info, parent, global, showWarnings);

                if (!global && font)
                {
                    QString name = info.attribute("name");
                    uitype->AddFont(name, font);
                }

                delete font;
            }
            else if (info.tagName() == "imagetype" ||
                     info.tagName() == "textarea" ||
                     info.tagName() == "group" ||
                     info.tagName() == "textedit" ||
                     info.tagName() == "button" ||
                     info.tagName() == "buttonlist" ||
                     info.tagName() == "buttonlist2" ||
                     info.tagName() == "buttontree" ||
                     info.tagName() == "spinbox" ||
                     info.tagName() == "checkbox" ||
                     info.tagName() == "statetype" ||
                     info.tagName() == "clock" ||
                     info.tagName() == "progressbar" ||
                     info.tagName() == "webbrowser" ||
                     info.tagName() == "guidegrid" ||
                     info.tagName() == "shape" ||
                     info.tagName() == "editbar")
            {
                ParseUIType(filename, info, info.tagName(),
                            uitype, screen, showWarnings);
            }
            else
            {
                VERBOSE_XML(VB_IMPORTANT, filename, info,
                            LOC_ERR + "Unknown widget type.");
            }
        }
    }

    uitype->Finalize();
    return uitype;
}
コード例 #8
0
MythFontProperties *MythFontProperties::ParseFromXml(
    const QString &filename,
    const QDomElement &element,
    MythUIType *parent,
    bool addToGlobal,
    bool showWarnings)
{
    // Crappy, but cached.  Move to GlobalFontMap?

    bool fromBase = false;
    MythFontProperties *newFont = new MythFontProperties();
    newFont->Freeze();

    if (element.tagName() == "font")
        LOG(VB_GENERAL, LOG_WARNING, LOC +
            QString("File %1: Use of 'font' is deprecated in favour of "
                    "'fontdef'") .arg(filename));

    QString name = element.attribute("name", "");
    if (name.isEmpty())
    {
        VERBOSE_XML(VB_GENERAL, LOG_ERR,
                    filename, element, "Font requires a name");
        delete newFont;
        return NULL;
    }

    QString base = element.attribute("from", "");

    if (!base.isEmpty())
    {
        MythFontProperties *tmp = NULL;

        if (parent)
            tmp = parent->GetFont(base);

        if (!tmp)
            tmp = GetGlobalFontMap()->GetFont(base);

        if (!tmp)
        {
            VERBOSE_XML(VB_GENERAL, LOG_ERR, filename, element,
                QString("Specified base font '%1' does not exist.").arg(base));

            delete newFont;
            return NULL;
        }

        *newFont = *tmp;
        fromBase = true;
    }

    int size, pixelsize;
    size = pixelsize = -1;

    QString face = element.attribute("face", "");
    if (face.isEmpty())
    {
        if (!fromBase)
        {
            VERBOSE_XML(VB_GENERAL, LOG_ERR, filename, element,
                        "Font needs a face");
            delete newFont;
            return NULL;
        }
    }
    else
    {
        newFont->m_face.setFamily(face);
    }

    if (addToGlobal && GetGlobalFontMap()->Contains(name))
    {
        MythFontProperties *tmp = GetGlobalFontMap()->GetFont(name);
        if (showWarnings)
        {
            VERBOSE_XML(VB_GENERAL, LOG_WARNING, filename, element,
                QString("Attempting to define '%1'\n\t\t\t"
                        "with face '%2', but it already "
                        "exists with face '%3'")
                .arg(name).arg(QFontInfo(newFont->m_face).family())
                .arg((tmp) ? QFontInfo(tmp->m_face).family() : "ERROR"));
        }
        delete newFont;
        return NULL;
    }

    QString hint = element.attribute("stylehint", "");
    if (!hint.isEmpty())
    {
        newFont->m_face.setStyleHint((QFont::StyleHint)hint.toInt());
    }

    for (QDomNode child = element.firstChild(); !child.isNull();
         child = child.nextSibling())
    {
        QDomElement info = child.toElement();
        if (!info.isNull())
        {
            if (info.tagName() == "size")
            {
                size = getFirstText(info).toInt();
            }
            else if (info.tagName() == "pixelsize")
            {
                pixelsize = getFirstText(info).toInt();
            }
            else if (info.tagName() == "color")
            {
                newFont->m_brush = QBrush(QColor(getFirstText(info)));
            }
            else if (info.tagName() == "gradient")
            {
                newFont->m_brush = parseGradient(info);
            }
            else if (info.tagName() == "shadowcolor")
            {
                newFont->m_shadowColor = QColor(getFirstText(info));
            }
            else if (info.tagName() == "shadowoffset")
            {
                newFont->m_hasShadow = true;
                newFont->m_shadowOffset = parsePoint(info);
            }
            else if (info.tagName() == "shadowalpha")
            {
                newFont->m_shadowAlpha = getFirstText(info).toInt();
            }
            else if (info.tagName() == "outlinecolor")
            {
                newFont->m_outlineColor = QColor(getFirstText(info));
            }
            else if (info.tagName() == "outlinesize")
            {
                newFont->m_hasOutline = true;
                newFont->m_outlineSize = getFirstText(info).toInt();
            }
            else if (info.tagName() == "outlinealpha")
            {
                newFont->m_outlineAlpha = getFirstText(info).toInt();
            }
            else if (info.tagName() == "italics")
            {
                newFont->m_face.setItalic(parseBool(info));
            }
            else if (info.tagName() == "letterspacing")
            {
                newFont->m_face.setLetterSpacing(QFont::AbsoluteSpacing,
                                              getFirstText(info).toInt());
            }
            else if (info.tagName() == "wordspacing")
            {
                newFont->m_face.setWordSpacing(getFirstText(info).toInt());
            }
            else if (info.tagName() == "decoration")
            {
                QString dec = getFirstText(info).toLower();
                QStringList values = dec.split(',');

                QStringList::Iterator it;
                for ( it = values.begin(); it != values.end(); ++it )
                {
                    if (*it == "underline")
                        newFont->m_face.setUnderline(true);
                    else if (*it == "overline")
                        newFont->m_face.setOverline(true);
                    else if (*it == "strikeout")
                        newFont->m_face.setStrikeOut(true);
                }
            }
            else if (info.tagName() == "weight")
            {
                QString weight = getFirstText(info).toLower();

                if (weight == "ultralight" ||
                    weight == "1")
                    newFont->m_face.setWeight(1);
                else if (weight == "light" ||
                         weight == "2")
                    newFont->m_face.setWeight(QFont::Light);
                else if (weight == "normal" ||
                         weight == "3")
                    newFont->m_face.setWeight(QFont::Normal);
                else if (weight == "demibold" ||
                         weight == "4")
                    newFont->m_face.setWeight(QFont::DemiBold);
                else if (weight == "bold" ||
                         weight == "5")
                    newFont->m_face.setWeight(QFont::Bold);
                else if (weight == "black" ||
                         weight == "6")
                    newFont->m_face.setWeight(QFont::Black);
                else if (weight == "ultrablack" ||
                         weight == "7")
                    newFont->m_face.setWeight(99);
                else
                    newFont->m_face.setWeight(QFont::Normal);
            }
            else if (info.tagName() == "stretch")
            {
                QString stretch = getFirstText(info).toLower();

                if (stretch == "ultracondensed" ||
                    stretch == "1")
                    newFont->m_stretch = QFont::UltraCondensed;
                else if (stretch == "extracondensed" ||
                         stretch == "2")
                    newFont->m_stretch = QFont::ExtraCondensed;
                else if (stretch == "condensed" ||
                         stretch == "3")
                    newFont->m_stretch = QFont::Condensed;
                else if (stretch == "semicondensed" ||
                         stretch == "4")
                    newFont->m_stretch = QFont::SemiCondensed;
                else if (stretch == "unstretched" ||
                         stretch == "5")
                    newFont->m_stretch = QFont::Unstretched;
                else if (stretch == "semiexpanded" ||
                         stretch == "6")
                    newFont->m_stretch = QFont::SemiExpanded;
                else if (stretch == "expanded" ||
                         stretch == "7")
                    newFont->m_stretch = QFont::Expanded;
                else if (stretch == "extraexpanded" ||
                         stretch == "8")
                    newFont->m_stretch = QFont::ExtraExpanded;
                else if (stretch == "ultraexpanded" ||
                         stretch == "9")
                    newFont->m_stretch = QFont::UltraExpanded;
                else
                    newFont->m_stretch = QFont::Unstretched;

                newFont->m_face.setStretch(newFont->m_stretch);
            }
            else
            {
                VERBOSE_XML(VB_GENERAL, LOG_ERR, filename, info,
                            QString("Unknown tag in font '%1'").arg(name));
                delete newFont;
                return NULL;
            }
        }
    }

    if (size <= 0 && pixelsize <= 0 && !fromBase)
    {
        VERBOSE_XML(VB_GENERAL, LOG_ERR, filename, element,
                    "Font size must be greater than 0.");
        delete newFont;
        return NULL;
    }
    else if (pixelsize > 0)
    {
        newFont->SetPixelSize(pixelsize);
    }
    else if (size > 0)
    {
        newFont->SetPointSize(size);
    }

    newFont->Unfreeze();

    QFontInfo fi(newFont->m_face);
    if (newFont->m_face.family() != fi.family())
    {
        VERBOSE_XML(VB_GENERAL, LOG_ERR, filename, element,
                    QString("Failed to load '%1', got '%2' instead")
            .arg(newFont->m_face.family()).arg(fi.family()));
    }
    else
    {
        VERBOSE_XML(VB_GUI, LOG_DEBUG, filename, element,
                    QString("loaded '%1'").arg(fi.family()));
    }

    if (addToGlobal)
        GetGlobalFontMap()->AddFont(name, newFont);

    return newFont;
}
コード例 #9
0
QDomElement SmartPlaylistEditor::result() {
    QDomDocument doc;
    QDomNode node = doc.namedItem( "smartplaylists" );
    QDomElement nodeE;
    nodeE = node.toElement();

    QDomElement smartplaylist = doc.createElement( "smartplaylist" );

    smartplaylist.setAttribute( "name", name() );

    // Limit
    if ( m_limitCheck->isChecked() )
        smartplaylist.setAttribute( "maxresults", m_limitSpin->value() );

    nodeE.appendChild( smartplaylist );
    // Matches
    if( m_matchAnyCheck->isChecked() ) {
        QDomElement matches = doc.createElement("matches");
        smartplaylist.appendChild( matches );
        // Iterate through all criteria list
        CriteriaEditor *criteriaeditor = m_criteriaEditorAnyList.first();
        for( int i=0; criteriaeditor; criteriaeditor = m_criteriaEditorAnyList.next(), ++i ) {
            matches.appendChild( doc.importNode( criteriaeditor->getDomSearchCriteria( doc ), true ) );
        }
        matches.setAttribute( "glue",  "OR" );
        smartplaylist.appendChild( matches );
    }

    if( m_matchAllCheck->isChecked() ) {
        QDomElement matches = doc.createElement("matches");
        smartplaylist.appendChild( matches );
        // Iterate through all criteria list
        CriteriaEditor *criteriaeditor = m_criteriaEditorAllList.first();
        for( int i=0; criteriaeditor; criteriaeditor = m_criteriaEditorAllList.next(), ++i ) {
            matches.appendChild( doc.importNode( criteriaeditor->getDomSearchCriteria( doc ), true ) );
        }
        matches.setAttribute( "glue",  "AND" );
        smartplaylist.appendChild( matches );
    }

    // Order By
    if( m_orderCheck->isChecked() ) {
        QDomElement orderby = doc.createElement("orderby");
        if (m_orderCombo->currentItem() != m_orderCombo->count()-1) {
            orderby.setAttribute( "field", m_dbFields[ m_orderCombo->currentItem() ] );
            orderby.setAttribute( "order", m_orderTypeCombo->currentItem() == 1 ? "DESC" : "ASC" );
        } else {
            orderby.setAttribute( "field", "random" );
            orderby.setAttribute( "order", m_orderTypeCombo->currentItem() == 1 ? "weighted" : "random" );
        }

        smartplaylist.appendChild( orderby );
    }
    QDomElement Sql = doc.createElement("sqlquery");
    buildQuery();
    Sql.appendChild( doc.createTextNode( m_query ) );
    smartplaylist.appendChild( Sql );

    if( m_expandCheck->isChecked() ) {
        QDomElement expandBy = doc.createElement("expandby");
        expandBy.setAttribute( "field", m_expandableFields[ m_expandCombo->currentItem() ] );
        QDomText t = doc.createTextNode( m_expandQuery );
        expandBy.appendChild( t );
        smartplaylist.appendChild( expandBy );
    }
    return (smartplaylist);
}
コード例 #10
0
ファイル: importshape.cpp プロジェクト: QuLogic/ScribusCTL
void ShapePlug::parseGroup(QDomNode &DOC)
{
	QString tmp = "";
	QString FillCol = "White";
	QString StrokeCol = "Black";
	QString defFillCol = "White";
	QString defStrokeCol = "Black";
	QColor stroke = Qt::black;
	QColor fill = Qt::white;
//	Qt::PenStyle Dash = Qt::SolidLine;
	Qt::PenCapStyle LineEnd = Qt::FlatCap;
	Qt::PenJoinStyle LineJoin = Qt::MiterJoin;
//	int fillStyle = 1;
	double strokewidth = 0.1;
//	bool poly = false;
	while(!DOC.isNull())
	{
		double x1, y1, x2, y2;
		StrokeCol = defStrokeCol;
		FillCol = defFillCol;
		stroke = Qt::black;
		fill = Qt::white;
	//	fillStyle = 1;
		strokewidth = 1.0;
	//	Dash = Qt::SolidLine;
		LineEnd = Qt::FlatCap;
		LineJoin = Qt::MiterJoin;
		FPointArray PoLine;
		PoLine.resize(0);
		QDomElement pg = DOC.toElement();
		QString STag = pg.tagName();
		QString style = pg.attribute( "style", "" ).simplified();
		if (style.isEmpty())
			style = pg.attribute( "svg:style", "" ).simplified();
		QStringList substyles = style.split(';', QString::SkipEmptyParts);
		for( QStringList::Iterator it = substyles.begin(); it != substyles.end(); ++it )
		{
			QStringList substyle = (*it).split(':', QString::SkipEmptyParts);
			QString command(substyle[0].trimmed());
			QString params(substyle[1].trimmed());
			if (command == "fill")
			{
				if (!((params == "foreground") || (params == "background") || (params == "fg") || (params == "bg") || (params == "none") || (params == "default") || (params == "inverse")))
				{
					if (params == "nofill")
						FillCol = CommonStrings::None;
					else
					{
						fill.setNamedColor( params );
						FillCol = "FromDia"+fill.name();
						ScColor tmp;
						tmp.fromQColor(fill);
						tmp.setSpotColor(false);
						tmp.setRegistrationColor(false);
						QString fNam = m_Doc->PageColors.tryAddColor(FillCol, tmp);
						if (fNam == FillCol)
							importedColors.append(FillCol);
						FillCol = fNam;
					}
				}
			}
			else if (command == "stroke")
			{
				if (!((params == "foreground") || (params == "background") || (params == "fg") || (params == "bg") || (params == "none") || (params == "default")) || (params == "inverse"))
				{
					stroke.setNamedColor( params );
					StrokeCol = "FromDia"+stroke.name();
					ScColor tmp;
					tmp.fromQColor(stroke);
					tmp.setSpotColor(false);
					tmp.setRegistrationColor(false);
					QString fNam = m_Doc->PageColors.tryAddColor(StrokeCol, tmp);
					if (fNam == StrokeCol)
						importedColors.append(StrokeCol);
					StrokeCol = fNam;
				}
			}
			else if (command == "stroke-width")
				strokewidth = ScCLocale::toDoubleC(params);
			else if( command == "stroke-linejoin" )
			{
				if( params == "miter" )
					LineJoin = Qt::MiterJoin;
				else if( params == "round" )
					LineJoin = Qt::RoundJoin;
				else if( params == "bevel" )
					LineJoin = Qt::BevelJoin;
			}
			else if( command == "stroke-linecap" )
			{
				if( params == "butt" )
					LineEnd = Qt::FlatCap;
				else if( params == "round" )
					LineEnd = Qt::RoundCap;
				else if( params == "square" )
					LineEnd = Qt::SquareCap;
			}
		}
		if (STag == "svg:line")
		{
			x1 = ScCLocale::toDoubleC(pg.attribute("x1")) * Conversion;
			y1 = ScCLocale::toDoubleC(pg.attribute("y1")) * Conversion;
			x2 = ScCLocale::toDoubleC(pg.attribute("x2")) * Conversion;
			y2 = ScCLocale::toDoubleC(pg.attribute("y2")) * Conversion;
			PoLine.addPoint(x1, y1);
			PoLine.addPoint(x1, y1);
			PoLine.addPoint(x2, y2);
			PoLine.addPoint(x2, y2);
			int z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, strokewidth, CommonStrings::None, StrokeCol, true);
			m_Doc->Items->at(z)->PoLine = PoLine.copy();
			finishItem(m_Doc->Items->at(z));
		}
		else if (STag == "svg:rect")
		{
			x1 = ScCLocale::toDoubleC(pg.attribute("x")) * Conversion;
			y1 = ScCLocale::toDoubleC(pg.attribute("y")) * Conversion;
			x2 = ScCLocale::toDoubleC(pg.attribute("width")) * Conversion;
			y2 = ScCLocale::toDoubleC(pg.attribute("height")) * Conversion;
			int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Rectangle, baseX + x1, baseY + y1, x2, y2, strokewidth, FillCol, StrokeCol, true);
			m_Doc->Items->at(z)->setLineJoin(LineJoin);
			m_Doc->Items->at(z)->setLineEnd(LineEnd);
			finishItem(m_Doc->Items->at(z));
		}
		else if ((STag == "svg:polygon") || (STag == "svg:polyline"))
		{
			bool bFirst = true;
			double x = 0.0;
			double y = 0.0;
			QString points = pg.attribute( "points" ).simplified().replace(',', " ");
			QStringList pointList = points.split(' ', QString::SkipEmptyParts);
			FirstM = true;
			for( QStringList::Iterator it = pointList.begin(); it != pointList.end(); it++ )
			{
				x = ScCLocale::toDoubleC(*(it++));
				y = ScCLocale::toDoubleC(*it);
				if( bFirst )
				{
					svgMoveTo(x * Conversion, y * Conversion);
					bFirst = false;
					WasM = true;
				}
				else
				{
					svgLineTo(&PoLine, x * Conversion, y * Conversion);
				}
			}
			if (STag == "svg:polygon")
				svgClosePath(&PoLine);
			if (PoLine.size() < 4)
			{
				DOC = DOC.nextSibling();
				continue;
			}
			int z;
			if (STag == "svg:polygon")
				z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, strokewidth, FillCol, StrokeCol, true);
			else
				z = m_Doc->itemAdd(PageItem::PolyLine, PageItem::Unspecified, baseX, baseY, 10, 10, strokewidth, CommonStrings::None, StrokeCol, true);
			m_Doc->Items->at(z)->PoLine = PoLine.copy();
			finishItem(m_Doc->Items->at(z));
		}
		else if ((STag == "svg:circle") || (STag == "svg:ellipse"))
		{
			x1 = ScCLocale::toDoubleC(pg.attribute("r")) * Conversion;
			y1 = ScCLocale::toDoubleC(pg.attribute("r")) * Conversion;
			x2 = ScCLocale::toDoubleC(pg.attribute("cx")) * Conversion - x1;
			y2 = ScCLocale::toDoubleC(pg.attribute("cy")) * Conversion - y1;
			x1 *= 2.0;
			y1 *= 2.0;
			int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Ellipse, baseX + x1, baseY + y1, x2, y2, strokewidth, FillCol, StrokeCol, true);
			m_Doc->Items->at(z)->setLineJoin(LineJoin);
			m_Doc->Items->at(z)->setLineEnd(LineEnd);
			finishItem(m_Doc->Items->at(z));
		}
		else if (STag == "svg:path")
		{
		//	poly =
			parseSVG( pg.attribute( "d" ), &PoLine );
			if (PoLine.size() < 4)
			{
				DOC = DOC.nextSibling();
				continue;
			}
			int z = m_Doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, baseX, baseY, 10, 10, strokewidth, FillCol, StrokeCol, true);
			m_Doc->Items->at(z)->PoLine = PoLine.copy();
			finishItem(m_Doc->Items->at(z));
		}
		else if (STag == "svg:g")
		{
			int z = m_Doc->itemAdd(PageItem::Group, PageItem::Rectangle, baseX, baseX, 1, 1, 0, CommonStrings::None, CommonStrings::None, true);
			PageItem *neu = m_Doc->Items->at(z);
			Elements.append(neu);
			if (groupStack.count() > 0)
				groupStack.top().append(neu);
			QList<PageItem*> gElements;
			groupStack.push(gElements);
			QDomNode child = DOC.firstChild();
			parseGroup(child);
			if (gElements.count() == 0)
			{
				groupStack.pop();
				Elements.removeAll(neu);
				groupStack.top().removeAll(neu);
				Selection tmpSelection(m_Doc, false);
				tmpSelection.addItem(neu);
				m_Doc->itemSelection_DeleteItem(&tmpSelection);
			}
			else
			{
				QList<PageItem*> gElem = groupStack.pop();
				double minx =  std::numeric_limits<double>::max();
				double miny =  std::numeric_limits<double>::max();
				double maxx = -std::numeric_limits<double>::max();
				double maxy = -std::numeric_limits<double>::max();
				for (int gr = 0; gr < gElements.count(); ++gr)
				{
					PageItem* currItem = gElem.at(gr);
					double x1, x2, y1, y2;
					currItem->getVisualBoundingRect(&x1, &y1, &x2, &y2);
					minx = qMin(minx, x1);
					miny = qMin(miny, y1);
					maxx = qMax(maxx, x2);
					maxy = qMax(maxy, y2);
				}
				double gx = minx;
				double gy = miny;
				double gw = maxx - minx;
				double gh = maxy - miny;
				neu->setXYPos(gx, gy, true);
				neu->setWidthHeight(gw, gh, true);
				neu->SetRectFrame();
				neu->Clip = FlattenPath(neu->PoLine, neu->Segments);
				neu->setItemName( tr("Group%1").arg(m_Doc->GroupCounter));
				neu->AutoName = false;
				neu->gXpos = neu->xPos() - gx;
				neu->gYpos = neu->yPos() - gy;
				neu->groupWidth = gw;
				neu->groupHeight = gh;
				for (int gr = 0; gr < gElem.count(); ++gr)
				{
					PageItem* currItem = gElem.at(gr);
					currItem->gXpos = currItem->xPos() - gx;
					currItem->gYpos = currItem->yPos() - gy;
					currItem->gWidth = gw;
					currItem->gHeight = gh;
					currItem->Parent = neu;
					neu->groupItemList.append(currItem);
					m_Doc->Items->removeAll(currItem);
					Elements.removeAll(currItem);
				}
				neu->setRedrawBounding();
				neu->setTextFlowMode(PageItem::TextFlowDisabled);
				m_Doc->GroupCounter++;
			}
		}
		DOC = DOC.nextSibling();
	}
}
コード例 #11
0
ファイル: importshape.cpp プロジェクト: QuLogic/ScribusCTL
void ShapePlug::parseGroupProperties(QDomNode &DOC, double &minXCoor, double &minYCoor, double &maxXCoor, double &maxYCoor, bool &firstCheck)
{
	QString FillCol = "White";
	QString StrokeCol = "Black";
	while(!DOC.isNull())
	{
		double x1, y1, x2, y2;
		FPointArray PoLine;
		PoLine.resize(0);
		QDomElement pg = DOC.toElement();
		QString STag = pg.tagName();
		if (STag == "svg:line")
		{
			x1 = ScCLocale::toDoubleC(pg.attribute("x1")) * Conversion;
			y1 = ScCLocale::toDoubleC(pg.attribute("y1")) * Conversion;
			x2 = ScCLocale::toDoubleC(pg.attribute("x2")) * Conversion;
			y2 = ScCLocale::toDoubleC(pg.attribute("y2")) * Conversion;
			PoLine.addPoint(x1, y1);
			PoLine.addPoint(x1, y1);
			PoLine.addPoint(x2, y2);
			PoLine.addPoint(x2, y2);
		}
		else if (STag == "svg:rect")
		{
			x1 = ScCLocale::toDoubleC(pg.attribute("x")) * Conversion;
			y1 = ScCLocale::toDoubleC(pg.attribute("y")) * Conversion;
			x2 = ScCLocale::toDoubleC(pg.attribute("width")) * Conversion;
			y2 = ScCLocale::toDoubleC(pg.attribute("height")) * Conversion;
			static double rect[] = {0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0,
									1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0,
									0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0};
			for (int a = 0; a < 29; a += 4)
			{
				double xa = x2 * rect[a];
				double ya = y2 * rect[a+1];
				double xb = x2 * rect[a+2];
				double yb = y2 * rect[a+3];
				PoLine.addPoint(x1+xa, y1+ya);
				PoLine.addPoint(x1+xb, y1+yb);
			}
		}
		else if ((STag == "svg:polygon") || (STag == "svg:polyline"))
		{
			bool bFirst = true;
			double x = 0.0;
			double y = 0.0;
			QString points = pg.attribute( "points" ).simplified().replace(',', " ");
			QStringList pointList = points.split(' ', QString::SkipEmptyParts);
			FirstM = true;
			for( QStringList::Iterator it1 = pointList.begin(); it1 != pointList.end(); it1++ )
			{
				x = ScCLocale::toDoubleC(*(it1++));
				y = ScCLocale::toDoubleC(*it1);
				if( bFirst )
				{
					svgMoveTo(x * Conversion, y * Conversion);
					bFirst = false;
					WasM = true;
				}
				else
				{
					svgLineTo(&PoLine, x * Conversion, y * Conversion);
				}
			}
			if (STag == "svg:polygon")
				svgClosePath(&PoLine);
			if (PoLine.size() < 4)
			{
				DOC = DOC.nextSibling();
				continue;
			}
		}
		else if (STag == "svg:circle")
		{
			x1 = ScCLocale::toDoubleC(pg.attribute("r")) * Conversion;
			y1 = ScCLocale::toDoubleC(pg.attribute("r")) * Conversion;
			x2 = ScCLocale::toDoubleC(pg.attribute("cx")) * Conversion - x1;
			y2 = ScCLocale::toDoubleC(pg.attribute("cy")) * Conversion - y1;
			x1 *= 2.0;
			y1 *= 2.0;
			static double rect[] = {1.0, 0.5, 1.0, 0.77615235,0.5, 1.0, 0.77615235, 1.0,
									0.5, 1.0, 0.22385765, 1.0, 0.0, 0.5, 0.0, 0.77615235,
									0.0, 0.5, 0.0, 0.22385765, 0.5, 0.0, 0.22385765, 0.0,
									0.5, 0.0, 0.77615235, 0.0, 1.0, 0.5, 1.0, 0.22385765};
			for (int a = 0; a < 29; a += 4)
			{
				double xa = x1 * rect[a];
				double ya = y1 * rect[a+1];
				double xb = x1 * rect[a+2];
				double yb = y1 * rect[a+3];
				PoLine.addPoint(x2+xa, y2+ya);
				PoLine.addPoint(x2+xb, y2+yb);
			}
		}
		else if (STag == "svg:ellipse")
		{
			x1 = ScCLocale::toDoubleC(pg.attribute("rx")) * Conversion;
			y1 = ScCLocale::toDoubleC(pg.attribute("ry")) * Conversion;
			x2 = ScCLocale::toDoubleC(pg.attribute("cx")) * Conversion - x1;
			y2 = ScCLocale::toDoubleC(pg.attribute("cy")) * Conversion - y1;
			x1 *= 2.0;
			y1 *= 2.0;
			static double rect[] = {1.0, 0.5, 1.0, 0.77615235,0.5, 1.0, 0.77615235, 1.0,
									0.5, 1.0, 0.22385765, 1.0, 0.0, 0.5, 0.0, 0.77615235,
									0.0, 0.5, 0.0, 0.22385765, 0.5, 0.0, 0.22385765, 0.0,
									0.5, 0.0, 0.77615235, 0.0, 1.0, 0.5, 1.0, 0.22385765};
			for (int a = 0; a < 29; a += 4)
			{
				double xa = x1 * rect[a];
				double ya = y1 * rect[a+1];
				double xb = x1 * rect[a+2];
				double yb = y1 * rect[a+3];
				PoLine.addPoint(x2+xa, y2+ya);
				PoLine.addPoint(x2+xb, y2+yb);
			}
		}
		else if (STag == "svg:path")
		{
			parseSVG( pg.attribute( "d" ), &PoLine );
			if (PoLine.size() < 4)
			{
				DOC = DOC.nextSibling();
				continue;
			}
		}
		else if (STag == "svg:g")
		{
			QDomNode child = DOC.firstChild();
			parseGroupProperties(child, minXCoor, minYCoor, maxXCoor, maxYCoor, firstCheck);
		}
		if (PoLine.size() < 4)
		{
			DOC = DOC.nextSibling();
			continue;
		}
		FPoint tp2(getMinClipF(&PoLine));
		PoLine.translate(-tp2.x(), -tp2.y());
		FPoint wh(getMaxClipF(&PoLine));
		if (firstCheck)
		{
			minXCoor = tp2.x();
			minYCoor = tp2.y();
			maxXCoor = tp2.x() + wh.x();
			maxYCoor = tp2.y() + wh.y();
			firstCheck = false;
		}
		else
		{
			minXCoor = qMin(minXCoor, tp2.x());
			minYCoor = qMin(minYCoor, tp2.y());
			maxXCoor = qMax(maxXCoor, tp2.x() + wh.x());
			maxYCoor = qMax(maxYCoor, tp2.y() + wh.y());
		}
		DOC = DOC.nextSibling();
	}
}
コード例 #12
0
void QgsProjectFileTransform::convertRasterProperties( QDomDocument& doc, QDomNode& parentNode,
    QDomElement& rasterPropertiesElem, QgsRasterLayer* rlayer )
{
  //no data
  //TODO: We would need to set no data on all bands, but we don't know number of bands here
  QDomNode noDataNode = rasterPropertiesElem.namedItem( QStringLiteral( "mNoDataValue" ) );
  QDomElement noDataElement = noDataNode.toElement();
  if ( !noDataElement.text().isEmpty() )
  {
    QgsDebugMsg( "mNoDataValue = " + noDataElement.text() );
    QDomElement noDataElem = doc.createElement( QStringLiteral( "noData" ) );

    QDomElement noDataRangeList = doc.createElement( QStringLiteral( "noDataRangeList" ) );
    noDataRangeList.setAttribute( QStringLiteral( "bandNo" ), 1 );

    QDomElement noDataRange =  doc.createElement( QStringLiteral( "noDataRange" ) );
    noDataRange.setAttribute( QStringLiteral( "min" ), noDataElement.text() );
    noDataRange.setAttribute( QStringLiteral( "max" ), noDataElement.text() );
    noDataRangeList.appendChild( noDataRange );

    noDataElem.appendChild( noDataRangeList );

    parentNode.appendChild( noDataElem );
  }

  QDomElement rasterRendererElem = doc.createElement( QStringLiteral( "rasterrenderer" ) );
  //convert general properties

  //invert color
  rasterRendererElem.setAttribute( QStringLiteral( "invertColor" ), QStringLiteral( "0" ) );
  QDomElement  invertColorElem = rasterPropertiesElem.firstChildElement( QStringLiteral( "mInvertColor" ) );
  if ( !invertColorElem.isNull() )
  {
    if ( invertColorElem.text() == QLatin1String( "true" ) )
    {
      rasterRendererElem.setAttribute( QStringLiteral( "invertColor" ), QStringLiteral( "1" ) );
    }
  }

  //opacity
  rasterRendererElem.setAttribute( QStringLiteral( "opacity" ), QStringLiteral( "1" ) );
  QDomElement transparencyElem = parentNode.firstChildElement( QStringLiteral( "transparencyLevelInt" ) );
  if ( !transparencyElem.isNull() )
  {
    double transparency = transparencyElem.text().toInt();
    rasterRendererElem.setAttribute( QStringLiteral( "opacity" ), QString::number( transparency / 255.0 ) );
  }

  //alphaBand was not saved until now (bug)
  rasterRendererElem.setAttribute( QStringLiteral( "alphaBand" ), -1 );

  //gray band is used for several renderers
  int grayBand = rasterBandNumber( rasterPropertiesElem, QStringLiteral( "mGrayBandName" ), rlayer );

  //convert renderer specific properties
  QString drawingStyle = rasterPropertiesElem.firstChildElement( QStringLiteral( "mDrawingStyle" ) ).text();

  // While PalettedColor should normaly contain only integer values, usually
  // color palette 0-255, it may happen (Tim, issue #7023) that it contains
  // colormap classification with double values and text labels
  // (which should normaly only appear in SingleBandPseudoColor drawingStyle)
  // => we have to check first the values and change drawingStyle if necessary
  if ( drawingStyle == QLatin1String( "PalettedColor" ) )
  {
    QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( QStringLiteral( "customColorRamp" ) );
    QDomNodeList colorRampEntryList = customColorRampElem.elementsByTagName( QStringLiteral( "colorRampEntry" ) );

    for ( int i = 0; i < colorRampEntryList.size(); ++i )
    {
      QDomElement colorRampEntryElem = colorRampEntryList.at( i ).toElement();
      QString strValue = colorRampEntryElem.attribute( QStringLiteral( "value" ) );
      double value = strValue.toDouble();
      if ( value < 0 || value > 10000 || !qgsDoubleNear( value, static_cast< int >( value ) ) )
      {
        QgsDebugMsg( QString( "forcing SingleBandPseudoColor value = %1" ).arg( value ) );
        drawingStyle = QStringLiteral( "SingleBandPseudoColor" );
        break;
      }
    }
  }

  if ( drawingStyle == QLatin1String( "SingleBandGray" ) )
  {
    rasterRendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "singlebandgray" ) );
    rasterRendererElem.setAttribute( QStringLiteral( "grayBand" ), grayBand );
    transformContrastEnhancement( doc, rasterPropertiesElem, rasterRendererElem );
  }
  else if ( drawingStyle == QLatin1String( "SingleBandPseudoColor" ) )
  {
    rasterRendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "singlebandpseudocolor" ) );
    rasterRendererElem.setAttribute( QStringLiteral( "band" ), grayBand );
    QDomElement newRasterShaderElem = doc.createElement( QStringLiteral( "rastershader" ) );
    QDomElement newColorRampShaderElem = doc.createElement( QStringLiteral( "colorrampshader" ) );
    newRasterShaderElem.appendChild( newColorRampShaderElem );
    rasterRendererElem.appendChild( newRasterShaderElem );

    //switch depending on mColorShadingAlgorithm
    QString colorShadingAlgorithm = rasterPropertiesElem.firstChildElement( QStringLiteral( "mColorShadingAlgorithm" ) ).text();
    if ( colorShadingAlgorithm == QLatin1String( "PseudoColorShader" ) || colorShadingAlgorithm == QLatin1String( "FreakOutShader" ) )
    {
      newColorRampShaderElem.setAttribute( QStringLiteral( "colorRampType" ), QStringLiteral( "INTERPOLATED" ) );

      //get minmax from rasterlayer
      QgsRasterBandStats rasterBandStats = rlayer->dataProvider()->bandStatistics( grayBand );
      double minValue = rasterBandStats.minimumValue;
      double maxValue = rasterBandStats.maximumValue;
      double breakSize = ( maxValue - minValue ) / 3;

      QStringList colorList;
      if ( colorShadingAlgorithm == QLatin1String( "FreakOutShader" ) )
      {
        colorList << QStringLiteral( "#ff00ff" ) << QStringLiteral( "#00ffff" ) << QStringLiteral( "#ff0000" ) << QStringLiteral( "#00ff00" );
      }
      else //pseudocolor
      {
        colorList << QStringLiteral( "#0000ff" ) << QStringLiteral( "#00ffff" ) << QStringLiteral( "#ffff00" ) << QStringLiteral( "#ff0000" );
      }
      QStringList::const_iterator colorIt = colorList.constBegin();
      double boundValue = minValue;
      for ( ; colorIt != colorList.constEnd(); ++colorIt )
      {
        QDomElement newItemElem = doc.createElement( QStringLiteral( "item" ) );
        newItemElem.setAttribute( QStringLiteral( "value" ), QString::number( boundValue ) );
        newItemElem.setAttribute( QStringLiteral( "label" ), QString::number( boundValue ) );
        newItemElem.setAttribute( QStringLiteral( "color" ), *colorIt );
        newColorRampShaderElem.appendChild( newItemElem );
        boundValue += breakSize;
      }
    }
    else if ( colorShadingAlgorithm == QLatin1String( "ColorRampShader" ) )
    {
      QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( QStringLiteral( "customColorRamp" ) );
      QString type = customColorRampElem.firstChildElement( QStringLiteral( "colorRampType" ) ).text();
      newColorRampShaderElem.setAttribute( QStringLiteral( "colorRampType" ), type );
      QDomNodeList colorNodeList = customColorRampElem.elementsByTagName( QStringLiteral( "colorRampEntry" ) );

      QString value, label;
      QColor newColor;
      int red, green, blue;
      QDomElement currentItemElem;
      for ( int i = 0; i < colorNodeList.size(); ++i )
      {
        currentItemElem = colorNodeList.at( i ).toElement();
        value = currentItemElem.attribute( QStringLiteral( "value" ) );
        label = currentItemElem.attribute( QStringLiteral( "label" ) );
        red = currentItemElem.attribute( QStringLiteral( "red" ) ).toInt();
        green = currentItemElem.attribute( QStringLiteral( "green" ) ).toInt();
        blue = currentItemElem.attribute( QStringLiteral( "blue" ) ).toInt();
        newColor = QColor( red, green, blue );
        QDomElement newItemElem = doc.createElement( QStringLiteral( "item" ) );
        newItemElem.setAttribute( QStringLiteral( "value" ), value );
        newItemElem.setAttribute( QStringLiteral( "label" ), label );
        newItemElem.setAttribute( QStringLiteral( "color" ), newColor.name() );
        newColorRampShaderElem.appendChild( newItemElem );
      }
    }
  }
  else if ( drawingStyle == QLatin1String( "PalettedColor" ) )
  {
    rasterRendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "paletted" ) );
    rasterRendererElem.setAttribute( QStringLiteral( "band" ), grayBand );
    QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( QStringLiteral( "customColorRamp" ) );
    QDomNodeList colorRampEntryList = customColorRampElem.elementsByTagName( QStringLiteral( "colorRampEntry" ) );
    QDomElement newColorPaletteElem = doc.createElement( QStringLiteral( "colorPalette" ) );

    int red = 0;
    int green = 0;
    int blue = 0;
    int value = 0;
    QDomElement colorRampEntryElem;
    for ( int i = 0; i < colorRampEntryList.size(); ++i )
    {
      colorRampEntryElem = colorRampEntryList.at( i ).toElement();
      QDomElement newPaletteElem = doc.createElement( QStringLiteral( "paletteEntry" ) );
      value = static_cast< int >( colorRampEntryElem.attribute( QStringLiteral( "value" ) ).toDouble() );
      newPaletteElem.setAttribute( QStringLiteral( "value" ), value );
      red = colorRampEntryElem.attribute( QStringLiteral( "red" ) ).toInt();
      green = colorRampEntryElem.attribute( QStringLiteral( "green" ) ).toInt();
      blue = colorRampEntryElem.attribute( QStringLiteral( "blue" ) ).toInt();
      newPaletteElem.setAttribute( QStringLiteral( "color" ), QColor( red, green, blue ).name() );
      QString label = colorRampEntryElem.attribute( QStringLiteral( "label" ) );
      if ( !label.isEmpty() )
      {
        newPaletteElem.setAttribute( QStringLiteral( "label" ), label );
      }
      newColorPaletteElem.appendChild( newPaletteElem );
    }
    rasterRendererElem.appendChild( newColorPaletteElem );
  }
  else if ( drawingStyle == QLatin1String( "MultiBandColor" ) )
  {
    rasterRendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "multibandcolor" ) );

    //red band, green band, blue band
    int redBand = rasterBandNumber( rasterPropertiesElem, QStringLiteral( "mRedBandName" ), rlayer );
    int greenBand = rasterBandNumber( rasterPropertiesElem, QStringLiteral( "mGreenBandName" ), rlayer );
    int blueBand = rasterBandNumber( rasterPropertiesElem, QStringLiteral( "mBlueBandName" ), rlayer );
    rasterRendererElem.setAttribute( QStringLiteral( "redBand" ), redBand );
    rasterRendererElem.setAttribute( QStringLiteral( "greenBand" ), greenBand );
    rasterRendererElem.setAttribute( QStringLiteral( "blueBand" ), blueBand );

    transformContrastEnhancement( doc, rasterPropertiesElem, rasterRendererElem );
  }
  else
  {
    return;
  }

  //replace rasterproperties element with rasterrenderer element
  if ( !parentNode.isNull() )
  {
    parentNode.replaceChild( rasterRendererElem, rasterPropertiesElem );
  }
}
コード例 #13
0
void QgsProjectFileTransform::transform2990()
{
  QDomNodeList mapLayers = mDom.elementsByTagName( QStringLiteral( "maplayer" ) );

  for ( int mapLayerIndex = 0; mapLayerIndex < mapLayers.count(); ++mapLayerIndex )
  {
    QDomElement layerElem = mapLayers.at( mapLayerIndex ).toElement();

    // The newly added fieldConfiguration element
    QDomElement fieldConfigurationElement = mDom.createElement( QStringLiteral( "fieldConfiguration" ) );
    layerElem.appendChild( fieldConfigurationElement );

    QDomNodeList editTypeNodes = layerElem.namedItem( QStringLiteral( "edittypes" ) ).childNodes();
    QDomElement constraintExpressionsElem = mDom.createElement( QStringLiteral( "constraintExpressions" ) );
    layerElem.appendChild( constraintExpressionsElem );

    for ( int i = 0; i < editTypeNodes.size(); ++i )
    {
      QDomNode editTypeNode = editTypeNodes.at( i );
      QDomElement editTypeElement = editTypeNode.toElement();

      QDomElement fieldElement = mDom.createElement( QStringLiteral( "field" ) );
      fieldConfigurationElement.appendChild( fieldElement );

      QString name = editTypeElement.attribute( QStringLiteral( "name" ) );
      fieldElement.setAttribute( QStringLiteral( "name" ), name );
      QDomElement constraintExpressionElem = mDom.createElement( QStringLiteral( "constraint" ) );
      constraintExpressionElem.setAttribute( "field", name );
      constraintExpressionsElem.appendChild( constraintExpressionElem );

      QDomElement editWidgetElement = mDom.createElement( QStringLiteral( "editWidget" ) );
      fieldElement.appendChild( editWidgetElement );

      QString ewv2Type = editTypeElement.attribute( QStringLiteral( "widgetv2type" ) );
      editWidgetElement.setAttribute( "type", ewv2Type );

      QDomElement ewv2CfgElem = editTypeElement.namedItem( QStringLiteral( "widgetv2config" ) ).toElement();

      if ( !ewv2CfgElem.isNull() )
      {
        QDomElement editWidgetConfigElement = mDom.createElement( QStringLiteral( "config" ) );
        editWidgetElement.appendChild( editWidgetConfigElement );

        QVariantMap editWidgetConfiguration;

        QDomNamedNodeMap configAttrs = ewv2CfgElem.attributes();
        for ( int configIndex = 0; configIndex < configAttrs.count(); ++configIndex )
        {
          QDomAttr configAttr = configAttrs.item( configIndex ).toAttr();
          if ( configAttr.name() == QStringLiteral( "fieldEditable" ) )
          {
            editWidgetConfigElement.setAttribute( QStringLiteral( "fieldEditable" ), configAttr.value() );
          }
          else if ( configAttr.name() == QStringLiteral( "labelOnTop" ) )
          {
            editWidgetConfigElement.setAttribute( QStringLiteral( "labelOnTop" ), configAttr.value() );
          }
          else if ( configAttr.name() == QStringLiteral( "notNull" ) )
          {
            editWidgetConfigElement.setAttribute( QStringLiteral( "notNull" ), configAttr.value() );
          }
          else if ( configAttr.name() == QStringLiteral( "constraint" ) )
          {
            constraintExpressionElem.setAttribute( "exp", configAttr.value() );
          }
          else if ( configAttr.name() == QStringLiteral( "constraintDescription" ) )
          {
            constraintExpressionElem.setAttribute( "desc", configAttr.value() );
          }
          else
          {
            editWidgetConfiguration.insert( configAttr.name(), configAttr.value() );
          }
        }

        if ( ewv2Type == QStringLiteral( "ValueMap" ) )
        {
          QDomNodeList configElements = ewv2CfgElem.childNodes();
          QVariantMap map;
          for ( int configIndex = 0; configIndex < configElements.count(); ++configIndex )
          {
            QDomElement configElem = configElements.at( configIndex ).toElement();
            map.insert( configElem.attribute( QStringLiteral( "key" ) ), configElem.attribute( QStringLiteral( "value" ) ) );
          }
          editWidgetConfiguration.insert( QStringLiteral( "map" ), map );
        }

        editWidgetConfigElement.appendChild( QgsXmlUtils::writeVariant( editWidgetConfiguration, mDom ) );
      }
    }
  }
}
コード例 #14
0
void QgsProjectFileTransform::transform1800to1900()
{
  if ( mDom.isNull() )
  {
    return;
  }

  QDomNodeList layerItemList = mDom.elementsByTagName( QStringLiteral( "rasterproperties" ) );
  for ( int i = 0; i < layerItemList.size(); ++i )
  {
    QDomElement rasterPropertiesElem = layerItemList.at( i ).toElement();
    QDomNode layerNode = rasterPropertiesElem.parentNode();
    QDomElement dataSourceElem = layerNode.firstChildElement( QStringLiteral( "datasource" ) );
    QDomElement layerNameElem = layerNode.firstChildElement( QStringLiteral( "layername" ) );
    QgsRasterLayer rasterLayer;
    // TODO: We have to use more data from project file to read the layer it correctly,
    // OTOH, we should not read it until it was converted
    rasterLayer.readLayerXml( layerNode.toElement() );
    convertRasterProperties( mDom, layerNode, rasterPropertiesElem, &rasterLayer );
  }

  //composer: replace mGridAnnotationPosition with mLeftGridAnnotationPosition & co.
  // and mGridAnnotationDirection with mLeftGridAnnotationDirection & co.
  QDomNodeList composerMapList = mDom.elementsByTagName( QStringLiteral( "ComposerMap" ) );
  for ( int i = 0; i < composerMapList.size(); ++i )
  {
    QDomNodeList gridList = composerMapList.at( i ).toElement().elementsByTagName( QStringLiteral( "Grid" ) );
    for ( int j = 0; j < gridList.size(); ++j )
    {
      QDomNodeList annotationList = gridList.at( j ).toElement().elementsByTagName( QStringLiteral( "Annotation" ) );
      for ( int k = 0; k < annotationList.size(); ++k )
      {
        QDomElement annotationElem = annotationList.at( k ).toElement();

        //position
        if ( annotationElem.hasAttribute( QStringLiteral( "position" ) ) )
        {
          int pos = annotationElem.attribute( QStringLiteral( "position" ) ).toInt();
          annotationElem.setAttribute( QStringLiteral( "leftPosition" ), pos );
          annotationElem.setAttribute( QStringLiteral( "rightPosition" ), pos );
          annotationElem.setAttribute( QStringLiteral( "topPosition" ), pos );
          annotationElem.setAttribute( QStringLiteral( "bottomPosition" ), pos );
          annotationElem.removeAttribute( QStringLiteral( "position" ) );
        }

        //direction
        if ( annotationElem.hasAttribute( QStringLiteral( "direction" ) ) )
        {
          int dir = annotationElem.attribute( QStringLiteral( "direction" ) ).toInt();
          if ( dir == 2 )
          {
            annotationElem.setAttribute( QStringLiteral( "leftDirection" ), 0 );
            annotationElem.setAttribute( QStringLiteral( "rightDirection" ), 0 );
            annotationElem.setAttribute( QStringLiteral( "topDirection" ), 1 );
            annotationElem.setAttribute( QStringLiteral( "bottomDirection" ), 1 );
          }
          else if ( dir == 3 )
          {
            annotationElem.setAttribute( QStringLiteral( "leftDirection" ), 1 );
            annotationElem.setAttribute( QStringLiteral( "rightDirection" ), 1 );
            annotationElem.setAttribute( QStringLiteral( "topDirection" ), 0 );
            annotationElem.setAttribute( QStringLiteral( "bottomDirection" ), 0 );
          }
          else
          {
            annotationElem.setAttribute( QStringLiteral( "leftDirection" ), dir );
            annotationElem.setAttribute( QStringLiteral( "rightDirection" ), dir );
            annotationElem.setAttribute( QStringLiteral( "topDirection" ), dir );
            annotationElem.setAttribute( QStringLiteral( "bottomDirection" ), dir );
          }
          annotationElem.removeAttribute( QStringLiteral( "direction" ) );
        }
      }
    }
  }

  //Composer: move all items under Composition element
  QDomNodeList composerList = mDom.elementsByTagName( QStringLiteral( "Composer" ) );
  for ( int i = 0; i < composerList.size(); ++i )
  {
    QDomElement composerElem = composerList.at( i ).toElement();

    //find <QgsComposition element
    QDomElement compositionElem = composerElem.firstChildElement( QStringLiteral( "Composition" ) );
    if ( compositionElem.isNull() )
    {
      continue;
    }

    QDomNodeList composerChildren = composerElem.childNodes();

    if ( composerChildren.size() < 1 )
    {
      continue;
    }

    for ( int j = composerChildren.size() - 1; j >= 0; --j )
    {
      QDomElement childElem = composerChildren.at( j ).toElement();
      if ( childElem.tagName() == QLatin1String( "Composition" ) )
      {
        continue;
      }

      composerElem.removeChild( childElem );
      compositionElem.appendChild( childElem );

    }
  }

  // SimpleFill symbol layer v2: avoid double transparency
  // replacing alpha value of symbol layer's color with 255 (the
  // transparency value is already stored as symbol transparency).
  QDomNodeList rendererList = mDom.elementsByTagName( QStringLiteral( "renderer-v2" ) );
  for ( int i = 0; i < rendererList.size(); ++i )
  {
    QDomNodeList layerList = rendererList.at( i ).toElement().elementsByTagName( QStringLiteral( "layer" ) );
    for ( int j = 0; j < layerList.size(); ++j )
    {
      QDomElement layerElem = layerList.at( j ).toElement();
      if ( layerElem.attribute( QStringLiteral( "class" ) ) == QLatin1String( "SimpleFill" ) )
      {
        QDomNodeList propList = layerElem.elementsByTagName( QStringLiteral( "prop" ) );
        for ( int k = 0; k < propList.size(); ++k )
        {
          QDomElement propElem = propList.at( k ).toElement();
          if ( propElem.attribute( QStringLiteral( "k" ) ) == QLatin1String( "color" ) || propElem.attribute( QStringLiteral( "k" ) ) == QLatin1String( "color_border" ) )
          {
            propElem.setAttribute( QStringLiteral( "v" ), propElem.attribute( QStringLiteral( "v" ) ).section( ',', 0, 2 ) + ",255" );
          }
        }
      }
    }
  }

  QgsDebugMsg( mDom.toString() );
}
コード例 #15
0
ファイル: renderwindow.cpp プロジェクト: Wushaowei001/xtuple
void RenderWindow::setDocument(const QDomDocument & doc)
{
  // Clear out the param list for this new document
  _params.clear();
  _lists.clear();
  _table->clear();
  _table->setRowCount(0);

  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;
  }

  _doc = doc;
  _reportInfo->setEnabled(true);

  _reportName->setText(QString::null);
  _reportTitle->setText(QString::null);
  _reportDescription->setText(QString::null);
  for(QDomNode n = root.firstChild(); !n.isNull(); n = n.nextSibling())
  {
    if(n.nodeName() == "name")
      _reportName->setText(n.firstChild().nodeValue());
    else if(n.nodeName() == "title")
      _reportTitle->setText(n.firstChild().nodeValue());
    else if(n.nodeName() == "description")
      _reportDescription->setText(n.firstChild().nodeValue());
    else 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",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);
    }
  }
}
コード例 #16
0
bool QgsMapLayer::readLayerXML( const QDomElement& layerElement )
{
  QgsCoordinateReferenceSystem savedCRS;
  CUSTOM_CRS_VALIDATION savedValidation;
  bool layerError;

  QDomNode mnl;
  QDomElement mne;

  // read provider
  QString provider;
  mnl = layerElement.namedItem( "provider" );
  mne = mnl.toElement();
  provider = mne.text();

  // set data source
  mnl = layerElement.namedItem( "datasource" );
  mne = mnl.toElement();
  mDataSource = mne.text();

  // TODO: this should go to providers
  if ( provider == "spatialite" )
  {
    QgsDataSourceURI uri( mDataSource );
    uri.setDatabase( QgsProject::instance()->readPath( uri.database() ) );
    mDataSource = uri.uri();
  }
  else if ( provider == "ogr" )
  {
    QStringList theURIParts = mDataSource.split( "|" );
    theURIParts[0] = QgsProject::instance()->readPath( theURIParts[0] );
    mDataSource = theURIParts.join( "|" );
  }
  else if ( provider == "delimitedtext" )
  {
    QUrl urlSource = QUrl::fromEncoded( mDataSource.toAscii() );

    if ( !mDataSource.startsWith( "file:" ) )
    {
      QUrl file = QUrl::fromLocalFile( mDataSource.left( mDataSource.indexOf( "?" ) ) );
      urlSource.setScheme( "file" );
      urlSource.setPath( file.path() );
    }

    QUrl urlDest = QUrl::fromLocalFile( QgsProject::instance()->readPath( urlSource.toLocalFile() ) );
    urlDest.setQueryItems( urlSource.queryItems() );
    mDataSource = QString::fromAscii( urlDest.toEncoded() );
  }
  else if ( provider == "wms" )
  {
    // >>> BACKWARD COMPATIBILITY < 1.9
    // For project file backward compatibility we must support old format:
    // 1. mode: <url>
    //    example: http://example.org/wms?
    // 2. mode: tiled=<width>;<height>;<resolution>;<resolution>...,ignoreUrl=GetMap;GetFeatureInfo,featureCount=<count>,username=<name>,password=<password>,url=<url>
    //    example: tiled=256;256;0.703;0.351,url=http://example.org/tilecache?
    //    example: featureCount=10,http://example.org/wms?
    //    example: ignoreUrl=GetMap;GetFeatureInfo,username=cimrman,password=jara,url=http://example.org/wms?
    // This is modified version of old QgsWmsProvider::parseUri
    // The new format has always params crs,format,layers,styles and that params
    // should not appear in old format url -> use them to identify version
    if ( !mDataSource.contains( "crs=" ) && !mDataSource.contains( "format=" ) )
    {
      QgsDebugMsg( "Old WMS URI format detected -> converting to new format" );
      QgsDataSourceURI uri;
      if ( !mDataSource.startsWith( "http:" ) )
      {
        QStringList parts = mDataSource.split( "," );
        QStringListIterator iter( parts );
        while ( iter.hasNext() )
        {
          QString item = iter.next();
          if ( item.startsWith( "username="******"username", item.mid( 9 ) );
          }
          else if ( item.startsWith( "password="******"password", item.mid( 9 ) );
          }
          else if ( item.startsWith( "tiled=" ) )
          {
            // in < 1.9 tiled= may apper in to variants:
            // tiled=width;height - non tiled mode, specifies max width and max height
            // tiled=width;height;resolutions-1;resolution2;... - tile mode

            QStringList params = item.mid( 6 ).split( ";" );

            if ( params.size() == 2 ) // non tiled mode
            {
              uri.setParam( "maxWidth", params.takeFirst() );
              uri.setParam( "maxHeight", params.takeFirst() );
            }
            else if ( params.size() > 2 ) // tiled mode
            {
              // resolutions are no more needed and size limit is not used for tiles
              // we have to tell to the provider however that it is tiled
              uri.setParam( "tileMatrixSet", "" );
            }
          }
          else if ( item.startsWith( "featureCount=" ) )
          {
            uri.setParam( "featureCount", item.mid( 13 ) );
          }
          else if ( item.startsWith( "url=" ) )
          {
            uri.setParam( "url", item.mid( 4 ) );
          }
          else if ( item.startsWith( "ignoreUrl=" ) )
          {
            uri.setParam( "ignoreUrl", item.mid( 10 ).split( ";" ) );
          }
        }
      }
      else
      {
        uri.setParam( "url", mDataSource );
      }
      mDataSource = uri.encodedUri();
      // At this point, the URI is obviously incomplete, we add additional params
      // in QgsRasterLayer::readXml
    }
    // <<< BACKWARD COMPATIBILITY < 1.9
  }
  else
  {
    mDataSource = QgsProject::instance()->readPath( mDataSource );
  }

  // Set the CRS from project file, asking the user if necessary.
  // Make it the saved CRS to have WMS layer projected correctly.
  // We will still overwrite whatever GDAL etc picks up anyway
  // further down this function.
  mnl = layerElement.namedItem( "layername" );
  mne = mnl.toElement();

  QDomNode srsNode = layerElement.namedItem( "srs" );
  mCRS->readXML( srsNode );
  mCRS->setValidationHint( tr( "Specify CRS for layer %1" ).arg( mne.text() ) );
  mCRS->validate();
  savedCRS = *mCRS;

  // Do not validate any projections in children, they will be overwritten anyway.
  // No need to ask the user for a projections when it is overwritten, is there?
  savedValidation = QgsCoordinateReferenceSystem::customSrsValidation();
  QgsCoordinateReferenceSystem::setCustomSrsValidation( NULL );

  // now let the children grab what they need from the Dom node.
  layerError = !readXml( layerElement );

  // overwrite CRS with what we read from project file before the raster/vector
  // file readnig functions changed it. They will if projections is specfied in the file.
  // FIXME: is this necessary?
  QgsCoordinateReferenceSystem::setCustomSrsValidation( savedValidation );
  *mCRS = savedCRS;

  // Abort if any error in layer, such as not found.
  if ( layerError )
  {
    return false;
  }

  // the internal name is just the data source basename
  //QFileInfo dataSourceFileInfo( mDataSource );
  //internalName = dataSourceFileInfo.baseName();

  // set ID
  mnl = layerElement.namedItem( "id" );
  if ( ! mnl.isNull() )
  {
    mne = mnl.toElement();
    if ( ! mne.isNull() && mne.text().length() > 10 ) // should be at least 17 (yyyyMMddhhmmsszzz)
    {
      mID = mne.text();
    }
  }

  // use scale dependent visibility flag
  toggleScaleBasedVisibility( layerElement.attribute( "hasScaleBasedVisibilityFlag" ).toInt() == 1 );
  setMinimumScale( layerElement.attribute( "minimumScale" ).toFloat() );
  setMaximumScale( layerElement.attribute( "maximumScale" ).toFloat() );

  // set name
  mnl = layerElement.namedItem( "layername" );
  mne = mnl.toElement();
  setLayerName( mne.text() );

  //title
  QDomElement titleElem = layerElement.firstChildElement( "title" );
  if ( !titleElem.isNull() )
  {
    mTitle = titleElem.text();
  }

  //abstract
  QDomElement abstractElem = layerElement.firstChildElement( "abstract" );
  if ( !abstractElem.isNull() )
  {
    mAbstract = abstractElem.text();
  }

  //keywordList
  QDomElement keywordListElem = layerElement.firstChildElement( "keywordList" );
  if ( !keywordListElem.isNull() )
  {
    QStringList kwdList;
    for ( QDomNode n = keywordListElem.firstChild(); !n.isNull(); n = n.nextSibling() )
    {
      kwdList << n.toElement().text();
    }
    mKeywordList = kwdList.join( ", " );
  }

  //metadataUrl
  QDomElement dataUrlElem = layerElement.firstChildElement( "dataUrl" );
  if ( !dataUrlElem.isNull() )
  {
    mDataUrl = dataUrlElem.text();
    mDataUrlFormat = dataUrlElem.attribute( "format", "" );
  }

  //attribution
  QDomElement attribElem = layerElement.firstChildElement( "attribution" );
  if ( !attribElem.isNull() )
  {
    mAttribution = attribElem.text();
    mAttributionUrl = attribElem.attribute( "href", "" );
  }

  //metadataUrl
  QDomElement metaUrlElem = layerElement.firstChildElement( "metadataUrl" );
  if ( !metaUrlElem.isNull() )
  {
    mMetadataUrl = metaUrlElem.text();
    mMetadataUrlType = metaUrlElem.attribute( "type", "" );
    mMetadataUrlFormat = metaUrlElem.attribute( "format", "" );
  }

#if 0
  //read transparency level
  QDomNode transparencyNode = layer_node.namedItem( "transparencyLevelInt" );
  if ( ! transparencyNode.isNull() )
  {
    // set transparency level only if it's in project
    // (otherwise it sets the layer transparent)
    QDomElement myElement = transparencyNode.toElement();
    setTransparency( myElement.text().toInt() );
  }
#endif

  readCustomProperties( layerElement );

  return true;
} // bool QgsMapLayer::readLayerXML
コード例 #17
0
ファイル: ofxpartner.cpp プロジェクト: KDE/kmymoney
static void ParseFile(QMap<QString, QString>& result, const QString& fileName, const QString& bankName)
{
  QFile f(fileName);
  if (f.open(QIODevice::ReadOnly)) {
    QTextStream stream(&f);
#if OFXHOME
    stream.setCodec("UTF-8");
    QString msg;
    int errl, errc;
    QDomDocument doc;
    if (doc.setContent(stream.readAll(), &msg, &errl, &errc)) {
      QDomNodeList olist = doc.elementsByTagName("institutionid");
      for (int i = 0; i < olist.count(); ++i) {
        QDomNode onode = olist.item(i);
        if (onode.isElement()) {
          QDomElement elo = onode.toElement();
          QString name = elo.attribute("name");

          if (bankName.isEmpty())
            result[name].clear();

          else if (name == bankName) {
            result[elo.attribute("id")].clear();
          }
        }
      }
    }
#endif

#if MSN
    stream.setCodec("UTF-16");
    QString msg;
    int errl, errc;
    QDomDocument doc;
    if (doc.setContent(stream.readAll(), &msg, &errl, &errc)) {
      QDomNodeList olist = doc.elementsByTagName("prov");
      for (int i = 0; i < olist.count(); ++i) {
        QDomNode onode = olist.item(i);
        if (onode.isElement()) {
          bool collectGuid = false;
          QDomElement elo = onode.toElement();
          QDomNodeList ilist = onode.childNodes();
          for (int j = 0; j < ilist.count(); ++j) {
            QDomNode inode = ilist.item(j);
            QDomElement el = inode.toElement();
            if (el.tagName() == "name") {
              if (bankName.isEmpty())
                result[el.text()].clear();
              else if (el.text() == bankName) {
                collectGuid = true;
              }
            }
            if (el.tagName() == "guid" && collectGuid) {
              result[el.text()].clear();
            }
          }
        }
      }
    }
#endif
    f.close();
  }
}
コード例 #18
0
QString QgsMapLayer::loadNamedStyle( const QString theURI, bool &theResultFlag )
{
  QgsDebugMsg( QString( "uri = %1 myURI = %2" ).arg( theURI ).arg( publicSource() ) );

  theResultFlag = false;

  QDomDocument myDocument( "qgis" );

  // location of problem associated with errorMsg
  int line, column;
  QString myErrorMessage;

  QFile myFile( theURI );
  if ( myFile.open( QFile::ReadOnly ) )
  {
    // read file
    theResultFlag = myDocument.setContent( &myFile, &myErrorMessage, &line, &column );
    if ( !theResultFlag )
      myErrorMessage = tr( "%1 at line %2 column %3" ).arg( myErrorMessage ).arg( line ).arg( column );
    myFile.close();
  }
  else
  {
    QFileInfo project( QgsProject::instance()->fileName() );
    QgsDebugMsg( QString( "project fileName: %1" ).arg( project.absoluteFilePath() ) );

    QString qml;
    if ( loadNamedStyleFromDb( QDir( QgsApplication::qgisSettingsDirPath() ).absoluteFilePath( "qgis.qmldb" ), theURI, qml ) ||
         ( project.exists() && loadNamedStyleFromDb( project.absoluteDir().absoluteFilePath( project.baseName() + ".qmldb" ), theURI, qml ) ) ||
         loadNamedStyleFromDb( QDir( QgsApplication::pkgDataPath() ).absoluteFilePath( "resources/qgis.qmldb" ), theURI, qml ) )
    {
      theResultFlag = myDocument.setContent( qml, &myErrorMessage, &line, &column );
      if ( !theResultFlag )
      {
        myErrorMessage = tr( "%1 at line %2 column %3" ).arg( myErrorMessage ).arg( line ).arg( column );
      }
    }
    else
    {
      myErrorMessage = tr( "style not found in database" );
    }
  }

  if ( !theResultFlag )
  {
    return myErrorMessage;
  }

  // get style file version string, if any
  QgsProjectVersion fileVersion( myDocument.firstChildElement( "qgis" ).attribute( "version" ) );
  QgsProjectVersion thisVersion( QGis::QGIS_VERSION );

  if ( thisVersion > fileVersion )
  {
    QgsLogger::warning( "Loading a style file that was saved with an older "
                        "version of qgis (saved in " + fileVersion.text() +
                        ", loaded in " + QGis::QGIS_VERSION +
                        "). Problems may occur." );

    QgsProjectFileTransform styleFile( myDocument, fileVersion );
    // styleFile.dump();
    styleFile.updateRevision( thisVersion );
    // styleFile.dump();
  }

  // now get the layer node out and pass it over to the layer
  // to deserialise...
  QDomElement myRoot = myDocument.firstChildElement( "qgis" );
  if ( myRoot.isNull() )
  {
    myErrorMessage = tr( "Error: qgis element could not be found in %1" ).arg( theURI );
    theResultFlag = false;
    return myErrorMessage;
  }

  // use scale dependent visibility flag
  toggleScaleBasedVisibility( myRoot.attribute( "hasScaleBasedVisibilityFlag" ).toInt() == 1 );
  setMinimumScale( myRoot.attribute( "minimumScale" ).toFloat() );
  setMaximumScale( myRoot.attribute( "maximumScale" ).toFloat() );

#if 0
  //read transparency level
  QDomNode transparencyNode = myRoot.namedItem( "transparencyLevelInt" );
  if ( ! transparencyNode.isNull() )
  {
    // set transparency level only if it's in project
    // (otherwise it sets the layer transparent)
    QDomElement myElement = transparencyNode.toElement();
    setTransparency( myElement.text().toInt() );
  }
#endif

  QString errorMsg;
  theResultFlag = readSymbology( myRoot, errorMsg );
  if ( !theResultFlag )
  {
    myErrorMessage = tr( "Loading style file %1 failed because:\n%2" ).arg( theURI ).arg( errorMsg );
    return myErrorMessage;
  }

  return "";
}
コード例 #19
0
void XMLParseBase::ParseChildren(const QString &filename,
                                 QDomElement &element,
                                 MythUIType *parent,
                                 bool showWarnings)
{
    if (!parent)
    {
        VERBOSE(VB_IMPORTANT, "Parent is NULL");
        return;
    }

    for (QDomNode child = element.firstChild(); !child.isNull();
         child = child.nextSibling())
    {
        QDomElement info = child.toElement();
        if (!info.isNull())
        {
            QString type = info.tagName();
            if (parent->ParseElement(filename, info, showWarnings))
            {
            }
            else if (type == "font" || type == "fontdef")
            {
                bool global = (GetGlobalObjectStore() == parent);
                MythFontProperties *font = MythFontProperties::ParseFromXml(
                    filename, info, parent, global, showWarnings);

                if (!global && font)
                {
                    QString name = info.attribute("name");
                    parent->AddFont(name, font);
                }

                delete font;
            }
            else if (type == "imagetype" ||
                     type == "textarea" ||
                     type == "group" ||
                     type == "textedit" ||
                     type == "button" ||
                     type == "buttonlist" ||
                     type == "buttonlist2" ||
                     type == "buttontree" ||
                     type == "spinbox" ||
                     type == "checkbox" ||
                     type == "statetype" ||
                     type == "clock" ||
                     type == "progressbar" ||
                     type == "webbrowser" ||
                     type == "guidegrid" ||
                     type == "shape" ||
                     type == "editbar")
            {
                ParseUIType(filename, info, type, parent, NULL, showWarnings);
            }
            else
            {
                VERBOSE_XML(VB_IMPORTANT, filename, info,
                            LOC_ERR + "Unknown widget type");
            }
        }
    }
}
コード例 #20
0
SResourcePackage::SResourcePackage() : QDomDocument()
{
	QDomElement root = createElement("Resources");
	appendChild(root);
	
	// Leemos los datos desde un archivo de indices
	QFile rscIndex(HOME+"/data/index.rsc");
	
	if( rscIndex.open( QIODevice::ReadOnly | QIODevice::Text))
	{
		QDomDocument doc;
		if ( doc.setContent( &rscIndex ) )
		{
			QDomElement docElem = doc.documentElement();
			
			QDomNode n = docElem.firstChild();
			
			QDomElement resource;
			
			while(!n.isNull())
			{
				QDomElement e = n.toElement();
				if(!e.isNull())
				{
					dDebug() << e.tagName();
					
					QString path = e.attribute("path");
						
					QString name = e.attribute("name");
						
					if( name.isEmpty() )
					{
						QFileInfo finfo(path);
						name = finfo.fileName();
					}
					
					if ( e.tagName() == "Image" )
					{
						resource = createElement("Image");
						resource.setAttribute("filename", name);
						
						addResource( resource, path );
						
						documentElement().appendChild(resource);
					}
					else if ( e.tagName() == "Svg" )
					{
						resource = createElement("Svg");
						resource.setAttribute("filename", name);
						
						addResource( resource, path );
						
						documentElement().appendChild(resource);
					}
					else if ( e.tagName() == "Sourd" )
					{
						resource = createElement("Sourd");
						resource.setAttribute("filename", name);
						
						addResource( resource, path );
						
						documentElement().appendChild(resource);
					}
					
					
				}
				n = n.nextSibling();
			}

		}
		else
		{
			dError() << "Invalid resource index file: " << rscIndex.fileName();
		}
		
		rscIndex.close();
	}
}
コード例 #21
0
bool XMLParseBase::doLoad(const QString &windowname,
                          MythUIType *parent,
                          const QString &filename,
                          bool onlywindows,
                          bool showWarnings)
{
    QDomDocument doc;
    QFile f(filename);

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

    QString errorMsg;
    int errorLine = 0;
    int errorColumn = 0;

    if (!doc.setContent(&f, false, &errorMsg, &errorLine, &errorColumn))
    {
        VERBOSE(VB_IMPORTANT, LOC_ERR +
                QString("Location: '%1' @ %2 column: %3"
                        "\n\t\t\tError: %4")
                .arg(qPrintable(filename)).arg(errorLine).arg(errorColumn)
                .arg(qPrintable(errorMsg)));
        f.close();
        return false;
    }

    f.close();

    QDomElement docElem = doc.documentElement();
    QDomNode n = docElem.firstChild();
    while (!n.isNull())
    {
        QDomElement e = n.toElement();
        if (!e.isNull())
        {
            if (onlywindows && e.tagName() == "window")
            {
                QString name = e.attribute("name", "");
                if (name.isEmpty())
                {
                    VERBOSE_XML(VB_IMPORTANT, filename, e,
                                LOC_ERR + "Window needs a name");
                    return false;
                }

                if (name == windowname)
                {
                    ParseChildren(filename, e, parent, showWarnings);
                    return true;
                }
            }

            if (!onlywindows)
            {
                QString type = e.tagName();
                if (type == "font" || type == "fontdef")
                {
                    bool global = (GetGlobalObjectStore() == parent);
                    MythFontProperties *font = MythFontProperties::ParseFromXml(
                        filename, e, parent, global, showWarnings);

                    if (!global && font)
                    {
                        QString name = e.attribute("name");
                        parent->AddFont(name, font);
                    }
                    delete font;
                }
                else if (type == "imagetype" ||
                         type == "textarea" ||
                         type == "group" ||
                         type == "textedit" ||
                         type == "button" ||
                         type == "buttonlist" ||
                         type == "buttonlist2" ||
                         type == "buttontree" ||
                         type == "spinbox" ||
                         type == "checkbox" ||
                         type == "statetype" ||
                         type == "window" ||
                         type == "clock" ||
                         type == "progressbar" ||
                         type == "webbrowser" ||
                         type == "guidegrid" ||
                         type == "shape" ||
                         type == "editbar")
                {
                    ParseUIType(filename, e, type, parent, NULL, showWarnings);
                }
                else
                {
                    VERBOSE_XML(VB_IMPORTANT, filename, e,
                                LOC_ERR + "Unknown widget type");
                }
            }
        }
        n = n.nextSibling();
    }

    if (onlywindows)
        return false;
    return true;
}
コード例 #22
0
LayoutItemConfig LayoutManager::parseItemConfig( const QDomElement &elem )
{
	const bool showMetaContactIcon = ( elem.attribute( "show_metacontact_icon", "false" ).compare( "true", Qt::CaseInsensitive ) == 0 );

	LayoutItemConfig config;
	config.setShowIcon( showMetaContactIcon );

	QDomNodeList rows = elem.elementsByTagName("row");

	int index = 0;
	while ( index < rows.size() )
	{
		QDomNode rowNode = rows.item( index );
		index++;

		LayoutItemConfigRow row;

		QDomNodeList elements = rowNode.toElement().elementsByTagName("element");

		int index2 = 0;
		while ( index2 < elements.size() )
		{
			QDomNode elementNode = elements.item( index2 );
			index2++;

			int value = 0; // Placeholder as default
			QString configName = elementNode.toElement().attribute( "value" );
			if ( !configName.isEmpty() )
			{
				for ( int i = 0; i < m_tokens.size(); i++)
				{
					if ( m_tokens.at(i).mConfigName == configName )
					{
						value = i;
						break;
					}
				}
			}


			QString prefix = elementNode.toElement().attribute( "prefix", QString() );
			QString sufix = elementNode.toElement().attribute( "suffix", QString() );
			qreal size = elementNode.toElement().attribute( "size", "0.0" ).toDouble();
			bool bold = ( elementNode.toElement().attribute( "bold", "false" ).compare( "true", Qt::CaseInsensitive ) == 0 );
			bool italic = ( elementNode.toElement().attribute( "italic", "false" ).compare( "true", Qt::CaseInsensitive ) == 0 );
			bool small = ( elementNode.toElement().attribute( "small", "false" ).compare( "true", Qt::CaseInsensitive ) == 0 );
			bool optimalSize = ( elementNode.toElement().attribute( "optimalSize", "false" ).compare( "true", Qt::CaseInsensitive ) == 0 );
			QString alignmentString = elementNode.toElement().attribute( "alignment", "left" );
			Qt::Alignment alignment;


			if ( alignmentString.compare( "left", Qt::CaseInsensitive ) == 0 )
				alignment = Qt::AlignLeft | Qt::AlignVCenter;
			else if ( alignmentString.compare( "right", Qt::CaseInsensitive ) == 0 )
				alignment = Qt::AlignRight| Qt::AlignVCenter;
			else
				alignment = Qt::AlignCenter| Qt::AlignVCenter;

			row.addElement( LayoutItemConfigRowElement( value, size, bold, italic, small, optimalSize, alignment, prefix, sufix ) );
		}

		config.addRow( row );
	}

	return config;
}
コード例 #23
0
ファイル: messagevalidator.cpp プロジェクト: senu/psi
QString MessageValidator::validateMessage(QString message, bool* illformed, HTMLTextFormatter* formatter) {

    //    qDebug() << "IMG val0" << message;
    QDomDocument doc("document");
    *illformed = false;

    QString errorMessage;
    int line, column;
    QDomDocument tmpDoc; //used by textformatter

    xmlSource.setData(message);

    if (!doc.setContent(&xmlSource, &xmlReader, &errorMessage, &line, &column)) {
        qDebug() << errorMessage << " " << line << " " << column << message;
        *illformed = true;
        qDebug() << "WARNING: MessageValidator::validateMessage() - illformed message";
        return "illformed message!!!";
    }

    //now DOM tree will be traversed in preorder. 
    QStack<QDomElement> stack; //current element, QStack is used to avoid possible stack overflow in ordinary recursion
    stack.push(doc.documentElement());

    while (!stack.empty()) {
        QDomElement cur = stack.top();
        stack.pop();

        // Traverse through DOM Tree(cur), cut off bad elements/attributes 
        // and format text nodes using textFormatter

        //    qDebug() << QString(4, ' ') << cur.tagName();

        QString parentName = cur.tagName();
        NodeInfo curNI = allowed[parentName];

        //delete disallowed attributes
        for (int i = 0; i < cur.attributes().count(); i++) {
            QString attrName = cur.attributes().item(i).toAttr().name();

            if (!curNI.allowedAttributes.contains(attrName)) {
                //     qDebug() << "VALIDATIN ERR" << "TA" << attrName  << " in " << parentName;
                //   qDebug() << "note allowed attributes are:" << curNI.allowedAttributes;

                cur.attributes().removeNamedItem(attrName);
                i--;
            }
        }

        QDomNodeList children = cur.childNodes();

        for (int i = children.size() - 1; i >= 0; i--) {
            QDomNode node = children.at(i);

            if (node.isElement()) {
                QString childName = node.toElement().tagName();

                if (childName == "a") { // always show hyperlink destination
                    QString href = node.toElement().attribute("href");
                    node.appendChild(doc.createTextNode(" [ " + href + " ]"));
                }

                if (childName == "style") { //NOTE: this action is not XHTML-IM compliant! (css rules should be displayed, but it's stupid)
                    cur.removeChild(node);
                }
                else if (childName == "img") { //disabling images until they are whitelisted

                    QString href = node.toElement().attribute("src");

                    QDomElement newElement = doc.createElement("a");
                    newElement.setAttribute("class", "psi_disabled_image");
                    newElement.setAttribute("href", "javascript:psi_addToWhiteList('" + href + "')");
                    newElement.appendChild(doc.createTextNode("[ click here to display: " + href + " ]"));

                    cur.replaceChild(newElement, node);
                }
                else if (!curNI.allowedTags.contains(childName)) {//is subElement valid here?

                    qDebug() << "VALIDATIN ERR" << "TS" << childName << " in " << parentName;
                    qDebug() << "note allowed subElements are:" << curNI.allowedTags;

                    //append bad node's children (they will be validated in next loop iteration)
                    int j = 0;
                    while (node.hasChildNodes()) {
                        cur.insertBefore(node.firstChild(), node);
                        j++;
                    }

                    i = i + j; //j nodes were inserted

                    //delete bad node
                    cur.removeChild(node);
                }
                else {
                    stack.push(node.toElement());
                }
            }
            else if (node.isText() && !node.isCDATASection()) {
                if (!curNI.canHaveText) {
                    cur.removeChild(node);
                }
                else { //format text
                    QString formattedText = "<tmp>" + formatter->format(Qt::escape(node.toText().data()), cur) + "</tmp>";
                    //NOTE: we don't need to escape quotes, and we want this code be more reusable/decoupled, 
                    //NOTE: so we use Qt::escape() instead of TextUtil::escape()
                   
                    xmlSource.setData(formattedText);
                    tmpDoc.setContent(&xmlSource, &xmlReader);
                   
                    QDomNode tmpElement = tmpDoc.firstChild();
                    while (tmpElement.hasChildNodes()) { //append <tmp>'s children. They won't be validated
                        cur.insertBefore(tmpElement.firstChild(), node);
                    }
                    
                    cur.removeChild(node);
                }
            }
        }//foreach child
    } //stack/dfs

//    qDebug() << "IMG MV:" << doc.toString(0);
    return doc.toString(0);
}
コード例 #24
0
void QgsGrassTools::addModules( QTreeWidgetItem *parent, QDomElement &element )
{
  QDomNode n = element.firstChild();

  QTreeWidgetItem *item;
  QTreeWidgetItem *lastItem = 0;
  while ( !n.isNull() )
  {
    QDomElement e = n.toElement();
    if ( !e.isNull() )
    {
// QgsDebugMsg(QString("tag = %1").arg(e.tagName()));

      if ( e.tagName() == "section" && e.tagName() == "grass" )
      {
        QgsDebugMsg( QString( "Unknown tag: %1" ).arg( e.tagName() ) );
        continue;
      }

      if ( parent )
      {
        item = new QTreeWidgetItem( parent, lastItem );
      }
      else
      {
        item = new QTreeWidgetItem( mModulesTree, lastItem );
      }

      if ( e.tagName() == "section" )
      {
        QString label = QApplication::translate( "grasslabel", e.attribute( "label" ).toUtf8() );
        QgsDebugMsg( QString( "label = %1" ).arg( label ) );
        item->setText( 0, label );
        item->setExpanded( false );

        addModules( item, e );

        lastItem = item;
      }
      else if ( e.tagName() == "grass" )
      { // GRASS module
        QString name = e.attribute( "name" );
        QgsDebugMsg( QString( "name = %1" ).arg( name ) );

        QString path = QgsApplication::pkgDataPath() + "/grass/modules/" + name;
        QString label = QgsGrassModule::label( path );
        QPixmap pixmap = QgsGrassModule::pixmap( path, 32 );

        item->setText( 0, name + " - " + label );
        item->setIcon( 0, QIcon( pixmap ) );
        item->setText( 1, name );
        lastItem = item;


        //
        // Experimental work by Tim - add this item to our list model
        //
        QStandardItem * mypDetailItem = new QStandardItem( name + "\n" + label );
        mypDetailItem->setData( name, Qt::UserRole + 1 ); //for calling runModule later
        QString mySearchText = name + " - " + label;
        mypDetailItem->setData( mySearchText, Qt::UserRole + 2 ); //for filtering later
        mypDetailItem->setData( pixmap, Qt::DecorationRole );
        mypDetailItem->setCheckable( false );
        mypDetailItem->setEditable( false );
        // setData in the delegate with a variantised QgsDetailedItemData
        QgsDetailedItemData myData;
        myData.setTitle( name );
        myData.setDetail( label );
        myData.setIcon( pixmap );
        myData.setCheckable( false );
        myData.setRenderAsWidget( false );
        QVariant myVariant = qVariantFromValue( myData );
        mypDetailItem->setData( myVariant, Qt::UserRole );
        mModelTools->appendRow( mypDetailItem );
        //
        // End of experimental work by Tim
        //
      }
    }
    n = n.nextSibling();
  }
}
コード例 #25
0
int YourPayProcessor::handleResponse(const QString &presponse, const int pccardid, const QString &ptype, const double pamount, const int pcurrid, QString &pneworder, QString &preforder, int &pccpayid, ParameterList &pparams)
{
  if (DEBUG)
    qDebug("YP::handleResponse(%s, %d, %s, %f, %d, %s, %d, pparams)",
	   presponse.toAscii().data(), pccardid,
	   ptype.toAscii().data(), pamount, pcurrid,
	   preforder.toAscii().data(), pccpayid);

  QDomDocument response;
  // YP doesn't even send back a valid XML doc!
  response.setContent("<yp_wrapper>" + presponse + "</yp_wrapper>");

  QDomNode node;
  QDomElement root = response.documentElement();

  QString r_approved;
  QString r_avs;
  QString r_code;
  QString r_error;
  QString r_message;
  QString r_ordernum;
  QString r_ref;
  QString r_score;
  QString r_shipping;
  QString r_tax;
  QString r_tdate;
  QString r_time;

  QString status;

  node = root.firstChild();
  while ( !node.isNull() )
  {
    if (node.isElement())
    {
      if (node.nodeName() == "r_approved" )
	r_approved = node.toElement().text();

      else if (node.nodeName() == "r_avs" )
	r_avs = node.toElement().text();

      else if (node.nodeName() == "r_code" )
	r_code = node.toElement().text();

      else if (node.nodeName() == "r_error" )
	r_error = node.toElement().text();

      else if (node.nodeName() == "r_message" )
	r_message = node.toElement().text();

      else if (node.nodeName() == "r_ordernum" )
	r_ordernum = node.toElement().text();

      else if (node.nodeName() == "r_ref" )
	r_ref = node.toElement().text();

      else if (node.nodeName() == "r_score" )
	r_score = node.toElement().text();

      else if (node.nodeName() == "r_shipping" )
	r_shipping = node.toElement().text();

      else if (node.nodeName() == "r_tax" )
	r_tax = node.toElement().text();

      else if (node.nodeName() == "r_tdate" )
	r_tdate = node.toElement().text();

      else if (node.nodeName() == "r_time" )
	r_time = node.toElement().text();
    }

    node = node.nextSibling();
  }

  if (isTest())
  {
    // in test mode YP doesn't send an approval code
    if (r_approved == "APPROVED" && r_code.isEmpty())
    r_code = "12345";

    // inject failures to test AVS and CVV checking but ONLY IN TEST MODE
    if (r_avs.isEmpty() && _metrics->value("CCTestResult") == "S")
    {
      switch (qrand() % 50)
      {
	case 0: r_avs = "NN";
		break;
	case 1: r_avs = "XN";
		break;
	case 2: r_avs = "YN";
		break;
	case 3: r_avs = "NX";
		break;
	case 4: r_avs = "XX";
		break;
	case 5: r_avs = "YX";
		break;
	default:
		r_avs = "YY";
		break;
      }
      switch (qrand() % 50)
      {
	case 0: r_avs += "N";
		break;
	case 1: r_avs += "P";
		break;
	case 2: r_avs += "S";
		break;
	case 3: r_avs += "U";
		break;
	default:
		r_avs += "M";
		break;
      }
    }
  }

  int returnValue = 0;
  if (r_approved == "APPROVED")
  {
    _errorMsg = errorMsg(0).arg(r_ref);
    if (ptype == "A")
      status = "A";	// Authorized
    else if (ptype == "V")
      status = "V";	// Voided
    else
      status = "C";	// Completed/Charged
  }

  else if (r_approved == "DENIED")
  {
    _errorMsg = errorMsg(10).arg(r_message);
    returnValue = 10;
    status = "D";
  }

  else if (r_approved == "DUPLICATE")
  {
    _errorMsg = errorMsg(11).arg(r_message);
    returnValue = 11;
    status = "D";
  }

  else if (r_approved == "DECLINED")
  {
    _errorMsg = errorMsg(12).arg(r_error);
    returnValue = 12;
    status = "D";
  }

  else if (r_approved == "FRAUD")
  {
    _errorMsg = errorMsg(13).arg(r_error);
    returnValue = 13;
    status = "D";
  }

  else if (r_approved.isEmpty())
  {
    _errorMsg = errorMsg(-100)
		     .arg(r_error).arg(r_message).arg(presponse);
    returnValue = -100;
    status = "X";
  }

  // YP encodes AVS and CVV checking in the r_avs response field
  QRegExp avsRegExp("^[" + _metrics->value("CCAvsAddr") +
		    "][" + _metrics->value("CCAvsZIP") + "]");

  _passedAvs = _metrics->value("CCAvsCheck") == "X" ||
	       ! r_avs.contains(avsRegExp); // avsregexp matches failures

  _passedCvv = _metrics->value("CCCVVCheck") == "X" ||
	       ! r_avs.contains(QRegExp("[" + _metrics->value("CCCVVErrors") +
					"]$"));

  _passedLinkShield = (! _metrics->boolean("CCYPLinkShield")) ||
	      (! r_score.isEmpty() &&
	       r_score.toInt() <= _metrics->value("CCYPLinkShieldMax").toInt());

  if (DEBUG)
    qDebug("YP:%s\t_passedAvs %d\t_passedCvv %d\t_passedLinkShield %d",
	    r_avs.toAscii().data(), _passedAvs, _passedCvv, _passedLinkShield);

  pparams.append("ccard_id",    pccardid);
  pparams.append("auth_charge", ptype);
  pparams.append("type",        ptype);
  pparams.append("reforder",    preforder.isEmpty() ? pneworder : preforder);
  pparams.append("status",      status);
  pparams.append("avs",         r_avs);
  pparams.append("ordernum",    pneworder);
  pparams.append("xactionid",   r_ordernum.isEmpty() ? pneworder : r_ordernum);
  pparams.append("error",       r_error);
  pparams.append("approved",    r_approved);
  pparams.append("code",        r_code);
  pparams.append("score",       r_score.toInt());
  pparams.append("shipping",    r_shipping);
  pparams.append("tax",         r_tax);
  pparams.append("tdate",       r_tdate);
  pparams.append("ref",         r_ref);
  pparams.append("message",     r_message);

  if (pcurrid != _ypcurrid)
  {
    pparams.append("fromcurr",  pcurrid);
    pparams.append("tocurr",    _ypcurrid);
  }
  else
    pparams.append("currid",    pcurrid);

  if (ptype == "A")
    pparams.append("auth", QVariant(true, 0));
  else
    pparams.append("auth", QVariant(false, 1));

  if (! r_time.isEmpty())
    pparams.append("time",     r_time);

  if (DEBUG)
    qDebug("YP:r_error.isEmpty() = %d", r_error.isEmpty());

  if (! r_error.isEmpty())
  {
    _errorMsg = errorMsg(-12).arg(r_error);
    returnValue = -12;
  }

  if (returnValue == 0)
    pparams.append("amount",   pamount);
  else
    pparams.append("amount",   0);	// no money changed hands this attempt

  return returnValue;
}
コード例 #26
0
ファイル: samplerbank.cpp プロジェクト: Alppasa/mixxx
void SamplerBank::slotLoadSamplerBank(double v) {
    if (v == 0.0 || m_pPlayerManager == NULL) {
        return;
    }

    QString samplerBankPath = QFileDialog::getOpenFileName(
            NULL,
            tr("Load Sampler Bank"),
            QString(),
            tr("Mixxx Sampler Banks (*.xml)"));
    if (samplerBankPath.isEmpty()) {
        return;
    }

    // The user has picked a new directory via a file dialog. This means the
    // system sandboxer (if we are sandboxed) has granted us permission to this
    // folder. We don't need access to this file on a regular basis so we do not
    // register a security bookmark.

    QFile file(samplerBankPath);
    if (!file.open(QIODevice::ReadOnly)) {
        QMessageBox::warning(NULL,
                             tr("Error Reading Sampler Bank"),
                             tr("Could not open the sampler bank file '%1'.")
                             .arg(samplerBankPath));
        return;
    }

    QDomDocument doc;

    if (!doc.setContent(file.readAll())) {
        QMessageBox::warning(NULL,
                             tr("Error Reading Sampler Bank"),
                             tr("Could not read the sampler bank file '%1'.")
                             .arg(samplerBankPath));
        return;
    }

    QDomElement root = doc.documentElement();
    if(root.tagName() != "samplerbank") {
        QMessageBox::warning(NULL,
                             tr("Error Reading Sampler Bank"),
                             tr("Could not read the sampler bank file '%1'.")
                             .arg(samplerBankPath));
        return;
    }

    QDomNode n = root.firstChild();

    while (!n.isNull()) {
        QDomElement e = n.toElement();

        if (!e.isNull()) {
            if (e.tagName() == "sampler") {
                QString group = e.attribute("group", "");
                QString location = e.attribute("location", "");

                if (!group.isEmpty()) {
                    if (location.isEmpty()) {
                        m_pPlayerManager->slotLoadTrackToPlayer(TrackPointer(), group);
                    } else {
                        m_pPlayerManager->slotLoadToPlayer(location, group);
                    }
                }

            }
        }
        n = n.nextSibling();
    }

    file.close();
}
コード例 #27
0
ファイル: GraphMLImporter.cpp プロジェクト: kapecp/3dsoftviz
bool GraphMLImporter::import(
	ImporterContext& context
)
{
	// context
	context_ = &context;
	// helpers
	graphOp_.reset( new GraphOperations( context_->getGraph() ) );
	readNodes_.reset( new ReadNodesStore() );

	// default types
	edgeType_ = NULL;
	nodeType_ = NULL;
	( void )graphOp_->addDefaultTypes( edgeType_, nodeType_ );

	// ziskame pristup ku nastaveniam
	Util::ApplicationConfig* appConf = Util::ApplicationConfig::get();
	edgeTypeAttribute_ = appConf->getValue( "GraphMLParser.edgeTypeAttribute" );
	nodeTypeAttribute_ = appConf->getValue( "GraphMLParser.nodeTypeAttribute" );

	// pole farieb FIXME oddelit farby hran od farieb uzlov
	colors_.push_back( ColorType( 0, 1, 0, 1 ) );
	colors_.push_back( ColorType( 0, 1, 1, 1 ) );
	colors_.push_back( ColorType( 1, 0, 0, 1 ) );
	colors_.push_back( ColorType( 1, 0, 1, 1 ) );
	colors_.push_back( ColorType( 1, 1, 0, 1 ) );
	colors_.push_back( ColorType( 1, 1, 1, 1 ) );

	iColor_ = 0;

	bool ok = true;

	// ziskame graph element
	QDomElement graphElement;
	if ( ok ) {
		QDomNode graphNode;

		QDomDocument doc( "graphMLDocument" );
		if ( doc.setContent( &( context_->getStream() ) ) ) {
			QDomElement docElem = doc.documentElement();
			if ( !docElem.isNull() && docElem.nodeName() == "graphml" ) {
				QDomNodeList graphNodes = docElem.elementsByTagName( "graph" );
				if ( graphNodes.length() > 0 ) {
					graphNode = graphNodes.item( 0 );
					if ( !graphNode.isNull() && graphNode.parentNode() == docElem && graphNode.isElement() ) {
						graphElement = graphNode.toElement();
					}
				}
			}
		}

		ok = !graphElement.isNull();

		context_->getInfoHandler().reportError( ok, "Zvoleny subor nie je validny GraphML subor." );
	}

	if ( ok ) {
		// for progress reporting
		entitiesProcessed_ = 0;
		entitiesCount_ = graphElement.elementsByTagName( "node" ).size() + graphElement.elementsByTagName( "edge" ).count();
	}

	if ( ok ) {
		ok = processGraph( graphElement );
	}

	return ok;
}
コード例 #28
0
void QgsWFSCapabilities::capabilitiesReplyFinished()
{
  QNetworkReply *reply = mCapabilitiesReply;
  reply->deleteLater();
  mCapabilitiesReply = 0;

  // handle network errors
  if ( reply->error() != QNetworkReply::NoError )
  {
    mErrorCode = QgsWFSCapabilities::NetworkError;
    mErrorMessage = reply->errorString();
    emit gotCapabilities();
    return;
  }

  // handle HTTP redirects
  QVariant redirect = reply->attribute( QNetworkRequest::RedirectionTargetAttribute );
  if ( !redirect.isNull() )
  {
    QgsDebugMsg( "redirecting to " + redirect.toUrl().toString() );
    QNetworkRequest request( redirect.toUrl() );
    request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork );
    request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true );

    mCapabilitiesReply = QgsNetworkAccessManager::instance()->get( request );

    connect( mCapabilitiesReply, SIGNAL( finished() ), this, SLOT( capabilitiesReplyFinished() ) );
    return;
  }

  QByteArray buffer = reply->readAll();

  QgsDebugMsg( "parsing capabilities: " + buffer );

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

  QDomElement doc = capabilitiesDocument.documentElement();

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

  mCaps.clear();

  //test wfs version
  QString version = capabilitiesDocument.documentElement().attribute( "version" );
  if ( version != "1.0.0" && version != "1.0" )
  {
    mErrorCode = WFSVersionNotSupported;
    mErrorMessage = tr( "Either the WFS server does not support WFS version 1.0.0 or the WFS url is wrong" );
    emit gotCapabilities();
    return;
  }

  // get the <FeatureType> elements
  QDomNodeList featureTypeList = capabilitiesDocument.elementsByTagNameNS( WFS_NAMESPACE, "FeatureType" );
  for ( unsigned int i = 0; i < featureTypeList.length(); ++i )
  {
    FeatureType featureType;
    QDomElement featureTypeElem = featureTypeList.at( i ).toElement();

    //Name
    QDomNodeList nameList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "Name" );
    if ( nameList.length() > 0 )
    {
      featureType.name = nameList.at( 0 ).toElement().text();
    }
    //Title
    QDomNodeList titleList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "Title" );
    if ( titleList.length() > 0 )
    {
      featureType.title = titleList.at( 0 ).toElement().text();
    }
    //Abstract
    QDomNodeList abstractList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "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.elementsByTagNameNS( WFS_NAMESPACE, "DefaultSRS" );
    if ( defaultCRSList.length() > 0 )
    {
      featureType.crslist.append( defaultCRSList.at( 0 ).toElement().text() );
    }

    //OtherSRS
    QDomNodeList otherCRSList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "OtherSRS" );
    for ( unsigned int i = 0; i < otherCRSList.length(); ++i )
    {
      featureType.crslist.append( otherCRSList.at( i ).toElement().text() );
    }

    //Support <SRS> for compatibility with older versions
    QDomNodeList srsList = featureTypeElem.elementsByTagNameNS( WFS_NAMESPACE, "SRS" );
    for ( unsigned int i = 0; i < srsList.length(); ++i )
    {
      featureType.crslist.append( srsList.at( i ).toElement().text() );
    }

    mCaps.featureTypes.append( featureType );
  }

  emit gotCapabilities();
}
コード例 #29
0
bool ChartElemNavaids::loadFromDomElement(QDomElement& dom_element, 
                                          QDomDocument& dom_doc,
                                          QString& err_msg)
{
    MYASSERT(!dom_element.isNull());
    TreeBaseXML::loadFromDomElement(dom_element, dom_doc, err_msg);

    if (m_dom_element.tagName() != CHART_NODE_NAME_NAVAIDS)
    {
        err_msg = QString("Wrong node name (%s), expected (%s)").
                  arg(m_dom_element.tagName()).arg(CHART_NODE_NAME_NAVAIDS);
        return false;
    }

    // loop through all navaids

    QDomNode node = m_dom_element.firstChild();
    for(; !node.isNull(); node = node.nextSibling())
    {
        QDomElement element = node.toElement();
        if (element.isNull()) continue;

        // extract info from node

        QString id = element.attribute(CHART_ATTR_ID);
        QString ctry = element.attribute(CHART_ATTR_CTRY);
        QString name = element.attribute(CHART_ATTR_NAME);
        double lat = element.attribute(CHART_ATTR_LAT).toDouble();
        double lon = element.attribute(CHART_ATTR_LON).toDouble();
        int freq = element.attribute(CHART_ATTR_FREQ).toUInt();
        bool has_dme = element.attribute(CHART_ATTR_DME).toInt();
        int elevation = element.attribute(CHART_ATTR_ELEV).toInt();

        // check info

        if (id.isEmpty())
        {
            err_msg = QString("Navaids: Missing ID at tag named (%1)").arg(element.tagName());
            return false;
        }

        // process element

        if (element.tagName() == CHART_NODE_NAME_NAVAIDS_VOR)
        {
            Vor* vor = 0;

            if (!name.isEmpty() && lat != 0.0 && lon != 0.0 && freq != 0)
                vor = new Vor(id, name, lat, lon, freq, has_dme, 0, 0, ctry);
            else
                vor = (Vor*)m_chart_model->getNavdata()->getElementsWithSignal(
                    id, ctry, Waypoint::VOR);

            if (!vor)
            {
                err_msg = QString("Navaids:VOR: unknown VOR with ID (%1)").arg(id);
                return false;
            }

            if (!addVor(*vor, element, dom_doc, err_msg))
            {
                node = node.previousSibling();
                m_dom_element.removeChild(element);
            }
            
            delete vor;
        }
        else if (element.tagName() == CHART_NODE_NAME_NAVAIDS_NDB)
        {
            Ndb* ndb = 0;

            if (!name.isEmpty() && lat != 0.0 && lon != 0.0 && freq != 0)
                ndb = new Ndb(id, name, lat, lon, freq, 0, 0, ctry);
            else
                ndb = (Ndb*)m_chart_model->getNavdata()->getElementsWithSignal(
                    id, ctry, Waypoint::NDB);

            if (!ndb)
            {
                err_msg = QString("Navaids:NDB: unknown NDB with ID (%1)").arg(id);
                return false;
            }

            if (!addNdb(*ndb, element, dom_doc, err_msg))
            {
                node = node.previousSibling();
                m_dom_element.removeChild(element);
            }
            
            delete ndb;
        }
        else if (element.tagName() == CHART_NODE_NAME_NAVAIDS_AIRPORT)
        {
            Airport* airport = 0;

            if (!name.isEmpty() && lat != 0.0 && lon != 0.0 && 
                element.hasAttribute(CHART_ATTR_ELEV))
                airport = new Airport(id, name, lat, lon, elevation);
            else
                airport = (Airport*)m_chart_model->getNavdata()->getElementsWithSignal(
                    id, ctry, Waypoint::AIRPORT);

            if (!airport)
            {
                err_msg = QString("Navaids:AIRPORT: unknown AIRPORT with ID (%1)").arg(id);
                return false;
            }

            if (!addAirport(*airport, element, dom_doc, err_msg))
            {
                node = node.previousSibling();
                m_dom_element.removeChild(element);
            }

            delete airport;
        }
        else if (element.tagName() == CHART_NODE_NAME_NAVAIDS_INTERSECTION)
        {
            Intersection* intersection = 0;
            
            if (lat != 0.0 && lon != 0.0)
                intersection = new Intersection(id, lat, lon, ctry);
            else
                intersection = (Intersection*)m_chart_model->getNavdata()->getElementsWithSignal(
                    id, ctry, Waypoint::INTERSECTION);

            if (!intersection)
            {
                err_msg = 
                    QString("Navaids:INTERSECTION: unknown INTERSECTION with ID (%1)").arg(id);
                return false;
            }

            if (!addIntersection(*intersection, element, dom_doc, err_msg))
            {
                node = node.previousSibling();
                m_dom_element.removeChild(element);
            }

            delete intersection;
        }
    }
    
    return true;
}
コード例 #30
0
void QgsProjectFileTransform::transform081to090()
{
  QgsDebugMsg( "Entering..." );
  if ( ! mDom.isNull() )
  {
    // Start with inserting a mapcanvas element and populate it

    QDomElement mapCanvas; // A null element.

    // there should only be one <qgis>
    QDomNode qgis = mDom.firstChildElement( QStringLiteral( "qgis" ) );
    if ( ! qgis.isNull() )
    {
      QgsDebugMsg( "Populating new mapcanvas" );

      // Create a mapcanvas
      mapCanvas = mDom.createElement( QStringLiteral( "mapcanvas" ) );
      // Append mapcanvas to parent 'qgis'.
      qgis.appendChild( mapCanvas );
      // Re-parent units
      mapCanvas.appendChild( qgis.namedItem( QStringLiteral( "units" ) ) );
      // Re-parent extent
      mapCanvas.appendChild( qgis.namedItem( QStringLiteral( "extent" ) ) );

      // See if we can find if projection is on.

      QDomElement properties = qgis.firstChildElement( QStringLiteral( "properties" ) );
      QDomElement spatial = properties.firstChildElement( QStringLiteral( "SpatialRefSys" ) );
      QDomElement hasCrsTransformEnabled = spatial.firstChildElement( QStringLiteral( "ProjectionsEnabled" ) );
      // Type is 'int', and '1' if on.
      // Create an element
      QDomElement projection = mDom.createElement( QStringLiteral( "projections" ) );
      QgsDebugMsg( QString( "Projection flag: " ) + hasCrsTransformEnabled.text() );
      // Set flag from ProjectionsEnabled
      projection.appendChild( mDom.createTextNode( hasCrsTransformEnabled.text() ) );
      // Set new element as child of <mapcanvas>
      mapCanvas.appendChild( projection );

    }


    // Transforming coordinate-transforms
    // Create a list of all map layers
    QDomNodeList mapLayers = mDom.elementsByTagName( QStringLiteral( "maplayer" ) );
    bool doneDestination = false;
    for ( int i = 0; i < mapLayers.count(); i++ )
    {
      QDomNode mapLayer = mapLayers.item( i );
      // Find the coordinatetransform
      QDomNode coordinateTransform = mapLayer.namedItem( QStringLiteral( "coordinatetransform" ) );
      // Find the sourcesrs
      QDomNode sourceCrs = coordinateTransform.namedItem( QStringLiteral( "sourcesrs" ) );
      // Rename to srs
      sourceCrs.toElement().setTagName( QStringLiteral( "srs" ) );
      // Re-parent to maplayer
      mapLayer.appendChild( sourceCrs );
      // Re-move coordinatetransform
      // Take the destination CRS of the first layer and use for mapcanvas projection
      if ( ! doneDestination )
      {
        // Use destination CRS from the last layer
        QDomNode destinationCRS = coordinateTransform.namedItem( QStringLiteral( "destinationsrs" ) );
        // Re-parent the destination CRS to the mapcanvas
        // If mapcanvas wasn't set, nothing will happen.
        mapCanvas.appendChild( destinationCRS );
        // Only do this once
        doneDestination = true;
      }
      mapLayer.removeChild( coordinateTransform );
      //QDomNode id = mapLayer.namedItem("id");
      //QgsDebugMsg(QString("Found maplayer ") + id.toElement().text());

    }

    // Set the flag 'visible' to match the status of 'checked'
    QDomNodeList legendLayerFiles = mDom.elementsByTagName( QStringLiteral( "legendlayerfile" ) );
    QgsDebugMsg( QString( "Legend layer file entries: " ) + QString::number( legendLayerFiles.count() ) );
    for ( int i = 0; i < mapLayers.count(); i++ )
    {
      // Get one maplayer element from list
      QDomElement mapLayer = mapLayers.item( i ).toElement();
      // Find it's id.
      QString id = mapLayer.firstChildElement( QStringLiteral( "id" ) ).text();
      QgsDebugMsg( QString( "Handling layer " + id ) );
      // Now, look it up in legend
      for ( int j = 0; j < legendLayerFiles.count(); j++ )
      {
        QDomElement legendLayerFile = legendLayerFiles.item( j ).toElement();
        if ( id == legendLayerFile.attribute( QStringLiteral( "layerid" ) ) )
        {
          // Found a the legend layer that matches the maplayer
          QgsDebugMsg( "Found matching id" );

          // Set visible flag from maplayer to legendlayer
          legendLayerFile.setAttribute( QStringLiteral( "visible" ), mapLayer.attribute( QStringLiteral( "visible" ) ) );

          // Set overview flag from maplayer to legendlayer
          legendLayerFile.setAttribute( QStringLiteral( "isInOverview" ), mapLayer.attribute( QStringLiteral( "showInOverviewFlag" ) ) );
        }
      }
    }
  }
  return;

}