Пример #1
1
QgsFeatureRenderer* QgsFeatureRenderer::loadSld( const QDomNode &node, QgsWkbTypes::GeometryType geomType, QString &errorMessage )
{
  QDomElement element = node.toElement();
  if ( element.isNull() )
    return nullptr;

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

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

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

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

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

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

      ruleChildElem = ruleChildElem.nextSiblingElement();
    }

    if ( needRuleRenderer )
    {
      break;
    }

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

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

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

  QgsFeatureRenderer* r = m->createRendererFromSld( featTypeStyleElem, geomType );
  return r;
}
Пример #2
1
Font::Font(QString image_path, QString xml_path)
{
    QFile f(xml_path);
    QString errorStr("");
    int errorLine(0);
    int errorColumn(0);
    QDomDocument doc;
    QDomElement root;
    
    if (!f.open(QFile::ReadOnly | QFile::Text)) {
        qCritical("ERROR: Failed to open config file \"%s\": %s",
                  xml_path.toUtf8().constData(),
                  f.errorString().toUtf8().constData()
                  );
        return;
    }
    
    if (!doc.setContent(&f, false, &errorStr, &errorLine, &errorColumn)) {
        qCritical("ERROR: Failed to parse config file \"%s\" at line %d, column %d:\n%s",
                  xml_path.toUtf8().constData(),
                  errorLine,
                  errorColumn,
                  errorStr.toUtf8().constData()
                  );
        return;
    }
    
    root = doc.documentElement();
    if (root.tagName() != "Font") {
        qCritical("ERROR: Unexpected root element \"%s\" at line %d, column %d",
                  root.tagName().toUtf8().constData(),
                  root.lineNumber(),
                  root.columnNumber());
        return;
    }
    
    this->size = root.attribute("size").toInt();
    this->family = root.attribute("family");
    this->height = root.attribute("height").toInt();
    this->style = root.attribute("style");
    
//    qDebug("Font: %d, %s, %d, %s", this->size, this->family.toUtf8().constData(), this->height, this->style.toUtf8().constData());
    
    _minChar = 127;
    _maxChar = 0;
    QDomElement childElement = root.firstChildElement();
    while (!childElement.isNull()) {
        QString tagName = childElement.tagName();
        if (tagName == "Char") {
            Char *c = new Char(childElement);
            this->_chars[c->code] = c;
            if (c->code > _maxChar)
                _maxChar = c->code;
            if (c->code < _minChar)
                _minChar = c->code;
        }
        childElement = childElement.nextSiblingElement();
    }
    
    QImageReader image_reader(image_path);
    this->_image = image_reader.read();
}
Пример #3
1
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( "mNoDataValue" );
  QDomElement noDataElement = noDataNode.toElement();
  if ( !noDataElement.text().isEmpty() )
  {
    QgsDebugMsg( "mNoDataValue = " + noDataElement.text() );
    QDomElement noDataElem = doc.createElement( "noData" );

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

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

    noDataElem.appendChild( noDataRangeList );

    parentNode.appendChild( noDataElem );
  }

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

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

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

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

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

  //convert renderer specific properties
  QString drawingStyle = rasterPropertiesElem.firstChildElement( "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 == "PalettedColor" )
  {
    QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( "customColorRamp" );
    QDomNodeList colorRampEntryList = customColorRampElem.elementsByTagName( "colorRampEntry" );

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

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

    //switch depending on mColorShadingAlgorithm
    QString colorShadingAlgorithm = rasterPropertiesElem.firstChildElement( "mColorShadingAlgorithm" ).text();
    if ( colorShadingAlgorithm == "PseudoColorShader" || colorShadingAlgorithm == "FreakOutShader" )
    {
      newColorRampShaderElem.setAttribute( "colorRampType", "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 == "FreakOutShader" )
      {
        colorList << "#ff00ff" << "#00ffff" << "#ff0000" << "#00ff00";
      }
      else //pseudocolor
      {
        colorList << "#0000ff" << "#00ffff" << "#ffff00" << "#ff0000";
      }
      QStringList::const_iterator colorIt = colorList.constBegin();
      double boundValue = minValue;
      for ( ; colorIt != colorList.constEnd(); ++colorIt )
      {
        QDomElement newItemElem = doc.createElement( "item" );
        newItemElem.setAttribute( "value", QString::number( boundValue ) );
        newItemElem.setAttribute( "label", QString::number( boundValue ) );
        newItemElem.setAttribute( "color", *colorIt );
        newColorRampShaderElem.appendChild( newItemElem );
        boundValue += breakSize;
      }
    }
    else if ( colorShadingAlgorithm == "ColorRampShader" )
    {
      QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( "customColorRamp" );
      QString type = customColorRampElem.firstChildElement( "colorRampType" ).text();
      newColorRampShaderElem.setAttribute( "colorRampType", type );
      QDomNodeList colorNodeList = customColorRampElem.elementsByTagName( "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( "value" );
        label = currentItemElem.attribute( "label" );
        red = currentItemElem.attribute( "red" ).toInt();
        green = currentItemElem.attribute( "green" ).toInt();
        blue = currentItemElem.attribute( "blue" ).toInt();
        newColor = QColor( red, green, blue );
        QDomElement newItemElem = doc.createElement( "item" );
        newItemElem.setAttribute( "value", value );
        newItemElem.setAttribute( "label", label );
        newItemElem.setAttribute( "color", newColor.name() );
        newColorRampShaderElem.appendChild( newItemElem );
      }
    }
  }
  else if ( drawingStyle == "PalettedColor" )
  {
    rasterRendererElem.setAttribute( "type", "paletted" );
    rasterRendererElem.setAttribute( "band", grayBand );
    QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( "customColorRamp" );
    QDomNodeList colorRampEntryList = customColorRampElem.elementsByTagName( "colorRampEntry" );
    QDomElement newColorPaletteElem = doc.createElement( "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( "paletteEntry" );
      value = ( int )( colorRampEntryElem.attribute( "value" ).toDouble() );
      newPaletteElem.setAttribute( "value", value );
      red = colorRampEntryElem.attribute( "red" ).toInt();
      green = colorRampEntryElem.attribute( "green" ).toInt();
      blue = colorRampEntryElem.attribute( "blue" ).toInt();
      newPaletteElem.setAttribute( "color", QColor( red, green, blue ).name() );
      QString label = colorRampEntryElem.attribute( "label" );
      if ( !label.isEmpty() )
      {
        newPaletteElem.setAttribute( "label", label );
      }
      newColorPaletteElem.appendChild( newPaletteElem );
    }
    rasterRendererElem.appendChild( newColorPaletteElem );
  }
  else if ( drawingStyle == "MultiBandColor" )
  {
    rasterRendererElem.setAttribute( "type", "multibandcolor" );

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

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

  //replace rasterproperties element with rasterrenderer element
  if ( !parentNode.isNull() )
  {
    parentNode.replaceChild( rasterRendererElem, rasterPropertiesElem );
  }
}
QgsSymbolLayerV2* QgsLinePatternFillSymbolLayer::createFromSld( QDomElement &element )
{
  QgsDebugMsg( "Entered." );

  QString name;
  QColor fillColor, lineColor;
  double size, lineWidth;

  QDomElement fillElem = element.firstChildElement( "Fill" );
  if ( fillElem.isNull() )
    return NULL;

  QDomElement graphicFillElem = fillElem.firstChildElement( "GraphicFill" );
  if ( graphicFillElem.isNull() )
    return NULL;

  QDomElement graphicElem = graphicFillElem.firstChildElement( "Graphic" );
  if ( graphicElem.isNull() )
    return NULL;

  if ( !QgsSymbolLayerV2Utils::wellKnownMarkerFromSld( graphicElem, name, fillColor, lineColor, lineWidth, size ) )
    return NULL;

  if ( name != "horline" )
    return NULL;

  double angle = 0.0;
  QString angleFunc;
  if ( QgsSymbolLayerV2Utils::rotationFromSldElement( graphicElem, angleFunc ) )
  {
    bool ok;
    double d = angleFunc.toDouble( &ok );
    if ( ok )
      angle = d;
  }

  double offset = 0.0;
  QPointF vectOffset;
  if ( QgsSymbolLayerV2Utils::displacementFromSldElement( graphicElem, vectOffset ) )
  {
    offset = sqrt( pow( vectOffset.x(), 2 ) + pow( vectOffset.y(), 2 ) );
  }

  QgsLinePatternFillSymbolLayer* sl = new QgsLinePatternFillSymbolLayer();
  sl->setColor( lineColor );
  sl->setLineWidth( lineWidth );
  sl->setLineAngle( angle );
  sl->setOffset( offset );
  sl->setDistance( size );

  // try to get the outline
  QDomElement strokeElem = element.firstChildElement( "Stroke" );
  if ( !strokeElem.isNull() )
  {
    QgsSymbolLayerV2 *l = QgsSymbolLayerV2Utils::createLineLayerFromSld( strokeElem );
    if ( l )
    {
      QgsSymbolLayerV2List layers;
      layers.append( l );
      sl->setSubSymbol( new QgsLineSymbolV2( layers ) );
    }
  }

  return sl;
}
Пример #5
1
void ReportViewWidget::on_actionRunQryFromFile_triggered()
{
	QString path = m_dirModel->data(ui.dirView->currentIndex(), QDirModel::FilePathRole).toString();
	if (!QFileInfo(path).isFile() || !QFile(path).exists())
		return;

    QString errorStr;
    int errorLine;
    int errorColumn;

    QFile file(path);
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, "CuteFarm",
                             tr("Can not read file  %1\nError: %2")
                             .arg(QFile(path).fileName())
                             .arg(file.errorString()));
        return;
    }

    if (!m_domDocument.setContent(&file, true, &errorStr, &errorLine,
                                &errorColumn)) {
        QMessageBox::information(this, "CuteFarm",
                                 tr("Error in line %1, column %2\nError: %3")
                                 .arg(errorLine)
                                 .arg(errorColumn)
                                 .arg(errorStr));
        return;
    }

    QDomElement root = m_domDocument.documentElement();
    if (root.tagName() != "qry") {
        QMessageBox::information(this, "CuteFarm",
                                 tr("This file is not a query file."));
        return;
    } else if (root.hasAttribute("version")
               && root.attribute("version") != "1.0") {
        QMessageBox::information(this, "CuteFarm",
                                 tr("The file is not an query version 1.0 "
                                    "file."));
        return;
    }

    QString sql = root.firstChildElement("sql").text();
    file.close();

	if (sql.contains("INSERT", Qt::CaseInsensitive) ||
			sql.contains("UPDATE", Qt::CaseInsensitive) ||
			sql.contains("CREATE", Qt::CaseInsensitive) ||
			sql.contains("DELETE", Qt::CaseInsensitive))
		return;

	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
	m_qryModel->setQuery(sql);
	ui.resultView->resizeColumnsToContents();
	ui.resultView->horizontalHeader()->setStretchLastSection(true);
	QApplication::restoreOverrideCursor();

	if (m_qryModel->lastError().type() != QSqlError::NoError)
		emit statusMsg(tr("Error"), 2500);
	else
		emit statusMsg("Ok", 2500);

	ui.textEditError->setText(m_qryModel->lastError().text());
}
Пример #6
1
void LineSegment::read(const QDomElement& e)
      {
      for (QDomElement ee = e.firstChildElement(); !ee.isNull(); ee = ee.nextSiblingElement())
            readProperties(ee);
      }
Пример #7
1
void Dossier::charger(const FormationManager& forman, const PeriodeManager& periodeman, const UVManager& uvman, const NoteManager& notman)
{
    QDomDocument doc = this->chargerXml(chemin_fichier + "/" + fichier);
    QDomElement racine = doc.documentElement();

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

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

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

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

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

    QDomDocument document;
    document.setContent(&file);

    QDomElement docElem = document.documentElement();

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

    Script* script = new Script();

    script->m_name = name;

    QDomElement elem = docElem.firstChildElement();

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

        elem = elem.nextSiblingElement();
    }

    file.close();

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

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

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

      if (score()->mscVersion() < 117 && (type() == HBOX || type() == VBOX) && !keepMargins)  {
            _leftMargin = _rightMargin = _topMargin = _bottomMargin = 0.0;
            }
      }
Пример #10
0
bool QgsProject::createEmbeddedLayer( const QString& layerId, const QString& projectFilePath, QList<QDomNode>& brokenNodes,
                                      QList< QPair< QgsVectorLayer*, QDomElement > >& vectorLayerList, bool saveFlag )
{
  QFile projectFile( projectFilePath );
  if ( !projectFile.open( QIODevice::ReadOnly ) )
  {
    return false;
  }

  QDomDocument projectDocument;
  if ( !projectDocument.setContent( &projectFile ) )
  {
    return false;
  }

  //does project store pathes absolute or relative?
  bool useAbsolutePathes = true;
  QDomElement propertiesElem = projectDocument.documentElement().firstChildElement( "properties" );
  if ( !propertiesElem.isNull() )
  {
    QDomElement absElem = propertiesElem.firstChildElement( "Paths" ).firstChildElement( "Absolute" );
    if ( !absElem.isNull() )
    {
      useAbsolutePathes = absElem.text().compare( "true", Qt::CaseInsensitive ) == 0;
    }
  }

  QDomElement projectLayersElem = projectDocument.documentElement().firstChildElement( "projectlayers" );
  if ( projectLayersElem.isNull() )
  {
    return false;
  }

  QDomNodeList mapLayerNodes = projectLayersElem.elementsByTagName( "maplayer" );
  for ( int i = 0; i < mapLayerNodes.size(); ++i )
  {
    //get layer id
    QDomElement mapLayerElem = mapLayerNodes.at( i ).toElement();
    QString id = mapLayerElem.firstChildElement( "id" ).text();
    if ( id == layerId )
    {
      //layer can be embedded only once
      if ( mapLayerElem.attribute( "embedded" ) == "1" )
      {
        return false;
      }

      mEmbeddedLayers.insert( layerId, qMakePair( projectFilePath, saveFlag ) );

      //change datasource path from relative to absolute if necessary
      if ( !useAbsolutePathes )
      {
        QDomElement provider = mapLayerElem.firstChildElement( "provider" );
        if ( provider.text() == "spatialite" )
        {
          QDomElement dsElem = mapLayerElem.firstChildElement( "datasource" );

          QgsDataSourceURI uri( dsElem.text() );

          QFileInfo absoluteDs( QFileInfo( projectFilePath ).absolutePath() + "/" + uri.database() );
          if ( absoluteDs.exists() )
          {
            uri.setDatabase( absoluteDs.absoluteFilePath() );
            dsElem.removeChild( dsElem.childNodes().at( 0 ) );
            dsElem.appendChild( projectDocument.createTextNode( uri.uri() ) );
          }
        }
        else
        {
          QDomElement dsElem = mapLayerElem.firstChildElement( "datasource" );
          QString debug( QFileInfo( projectFilePath ).absolutePath() + "/" + dsElem.text() );
          QFileInfo absoluteDs( QFileInfo( projectFilePath ).absolutePath() + "/" + dsElem.text() );
          if ( absoluteDs.exists() )
          {
            dsElem.removeChild( dsElem.childNodes().at( 0 ) );
            dsElem.appendChild( projectDocument.createTextNode( absoluteDs.absoluteFilePath() ) );
          }
        }
      }

      if ( addLayer( mapLayerElem, brokenNodes, vectorLayerList ) )
      {
        return true;
      }
      else
      {
        mEmbeddedLayers.remove( layerId );
        return false;
      }
    }
  }

  return false;
}
Пример #11
0
bool Scene::load(const QString& fn) {
    QFile file(fn);
    if (!file.open(QIODevice::ReadOnly)) {
        return false;
    }

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

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

    QDomElement root = doc.documentElement();
    m_worldSize.setWidth(root.attribute("width").toInt());
    m_worldSize.setHeight(root.attribute("height").toInt());
    QDomElement node = root.firstChildElement("body");
    while (node.isElement()) {
        QString type = node.attribute("type");
        Body* b = 0;
        if (type=="StaticBody") {
            b = new StaticBody(this,"body",this);
            ReadAttributes(b,node);
            if (!m_static_body)
                m_static_body = b;
            else {
                m_bodys.push_back( b );
            }
        } else if (type=="DynamicBody") {
            b = new DynamicBody(this,"body",this);
            ReadAttributes(b,node);
            m_bodys.push_back( b );
        }
        if (b) {
            QDomElement primNode = node.firstChildElement("primitive");
            while (primNode.isElement()) {
                Primitive* p = 0;
                QString type = primNode.attribute("type");
                p = Primitive::create(type,b,this);
                if (p) {
                    ReadAttributes(p,primNode);
                    b->addPrimitive(p);
                }
                primNode = primNode.nextSiblingElement("primitive");
            }
            connect( b,SIGNAL(changed()),this,SLOT(bodyChanged()));
        }
        node = node.nextSiblingElement("body");
    }
    endResetModel();
    m_filename = fn;
    emit changed();
    return true;
}
Пример #12
0
ProcessViewItem::ProcessViewItem(QDomElement _graph, const QColor &_color, QGraphicsItem *parent)
        : QGraphicsItem(parent)
        , graph(_graph)
        , color(_color)
        , box_topleft(-140, -140)
        , box_bottomright(140, 140)
        , old_box_topleft(box_topleft)
        , old_box_bottomright(box_bottomright)
        , min_box(120, 80){
    setPos(GetGraphToplevelPosition(graph));
    resizer_topleft     = new ResizeViewItem(this);
    resizer_bottomright = new ResizeViewItem(this);
    resizer_topleft->setPos(box_topleft);
    resizer_bottomright->setPos(box_bottomright);
    connect(resizer_topleft, SIGNAL(positionChanged(ResizeViewItem*)),
            this, SLOT(sizeChanged(ResizeViewItem*)));
    connect(resizer_bottomright, SIGNAL(positionChanged(ResizeViewItem*)),
            this, SLOT(sizeChanged(ResizeViewItem*)));
    connect(resizer_topleft, SIGNAL(mouseRelease(ResizeViewItem*)),
            this, SLOT(mouseRelease(ResizeViewItem*)));
    connect(resizer_bottomright, SIGNAL(mouseRelease(ResizeViewItem*)),
            this, SLOT(mouseRelease(ResizeViewItem*)));
    setFlag(ItemIsMovable, true);
    QDomElement nodes = graph.firstChildElement("nodes");
    for (QDomElement n=nodes.firstChildElement(); !n.isNull(); n=n.nextSiblingElement()){
        NodeViewItem *item;
        QString nodename = n.attribute("name");
        if (nodename.startsWith("input_proxy_")){
            item = new InputProxyViewItem(n, this);
        } else if (nodename.startsWith("output_proxy_")){
            item = new OutputProxyViewItem(n, this);
        } else {
            item = new NodeViewItem(n, this);
        }
        item->setPos(-item->width/2, -item->height/2);
        nodeviewitemlist.push_back(item);
        connect(item, SIGNAL(positionChanged(const NodeViewItem*)),
                this, SLOT(positionChanged(const NodeViewItem*)));
    }
    QDomElement edges = graph.firstChildElement("connections");
    for (QDomElement edge=edges.firstChildElement(); !edge.isNull(); edge=edge.nextSiblingElement()){
        const NodeViewItem *from = 0, *to = 0;
        for (list<NodeViewItem*>::const_iterator j=nodeviewitemlist.begin(); j!=nodeviewitemlist.end(); ++j){
            if ((*j)->node.attribute("name") == edge.attribute("from")){
                from = *j;
            }
            if ((*j)->node.attribute("name") == edge.attribute("to")){
                to = *j;
            }
        }
        if ((from != 0) && (to != 0)){
            int from_index = GetOutportIndex(from->node, edge.attribute("from-port"));
            int to_index   = GetInportIndex(to->node, edge.attribute("to-port"));
            //cout << ", index: " << from_index << ", " << to_index << ", elem: " << hex << (void*)node->elem2 << ", " << (void*)node->elem3 << dec << endl;
            EdgeViewItem *item = new EdgeViewItem(from, to, from_index, to_index, this);
            for (list<NodeViewItem*>::const_iterator nvi=nodeviewitemlist.begin(); nvi!=nodeviewitemlist.end(); ++nvi){
                if (   ((*nvi)->node.attribute("name") == edge.attribute("from"))
                    || ((*nvi)->node.attribute("name") == edge.attribute("to"))){
                    connect((*nvi), SIGNAL(positionChanged(const NodeViewItem*)),
                            item, SLOT(redrawEdge(const NodeViewItem*)));
                }
            }
        }
Пример #13
0
	channels_container_t RSS10Parser::Parse (const QDomDocument& doc,
			const IDType_t& feedId) const
	{
		channels_container_t result;
	
		QMap<QString, Channel_ptr> item2Channel;
		QDomElement root = doc.documentElement ();
		QDomElement channelDescr = root.firstChildElement ("channel");
		while (!channelDescr.isNull ())
		{
			Channel_ptr channel (new Channel (feedId));
			channel->Title_ = channelDescr.firstChildElement ("title").text ().trimmed ();
			channel->Link_ = channelDescr.firstChildElement ("link").text ();
			channel->Description_ =
				channelDescr.firstChildElement ("description").text ();
			channel->PixmapURL_ =
				channelDescr.firstChildElement ("image")
				.firstChildElement ("url").text ();
			channel->LastBuild_ = GetDCDateTime (channelDescr);
	
			QDomElement itemsRoot = channelDescr.firstChildElement ("items");
			QDomNodeList seqs = itemsRoot.elementsByTagNameNS (RDF_, "Seq");
	
			channelDescr = channelDescr.nextSiblingElement ("channel");
	
			if (!seqs.size ())
				continue;
	
			QDomElement seqElem = seqs.at (0).toElement ();
			QDomNodeList lis = seqElem.elementsByTagNameNS (RDF_, "li");
			for (int i = 0; i < lis.size (); ++i)
				item2Channel [lis.at (i).toElement ().attribute ("resource")] = channel;
	
			result.push_back (channel);
		}
	
		QDomElement itemDescr = root.firstChildElement ("item");
		while (!itemDescr.isNull ())
		{
			QString about = itemDescr.attributeNS (RDF_, "about");
			if (item2Channel.contains (about))
			{
				Item_ptr item (new Item (item2Channel [about]->ChannelID_));
				item->Title_ = itemDescr.firstChildElement ("title").text ();
				item->Link_ = itemDescr.firstChildElement ("link").text ();
				item->Description_ = itemDescr.firstChildElement ("description").text ();
				GetDescription (itemDescr, item->Description_);
	
				item->Categories_ = GetAllCategories (itemDescr);
				item->Author_ = GetAuthor (itemDescr);
				item->PubDate_ = GetDCDateTime (itemDescr);
				item->Unread_ = true;
				item->NumComments_ = GetNumComments (itemDescr);
				item->CommentsLink_ = GetCommentsRSS (itemDescr);
				item->CommentsPageLink_ = GetCommentsLink (itemDescr);
				item->Enclosures_ = GetEncEnclosures (itemDescr, item->ItemID_);
				QPair<double, double> point = GetGeoPoint (itemDescr);
				item->Latitude_ = point.first;
				item->Longitude_ = point.second;
				if (item->Guid_.isEmpty ())
					item->Guid_ = "empty";
	
				item2Channel [about]->Items_.push_back (item);
			}
			itemDescr = itemDescr.nextSiblingElement ("item");
		}
	
		return result;
	}
Пример #14
0
/**
\return
**/
void BfCompany::cargaConf()
{
    BL_FUNC_DEBUG
    QFile file ( g_confpr->value( CONF_DIR_USER ) + "bulmafact_" + dbName() + ".cfn" );
    QDomDocument doc ( "mydocument" );
    if ( !file.open ( QIODevice::ReadOnly ) )
        return;
    if ( !doc.setContent ( &file ) ) {
        file.close();
        return;
    }
    file.close();

    // print out the element names of all elements that are direct children
    // of the outermost element.
    QDomElement docElem = doc.documentElement();
    QDomElement principal = docElem.firstChildElement ( "PRINCIPAL" );
    /// Cogemos la coordenada X
    QString nx = principal.firstChildElement ( "X" ).toElement().text();

    /// Cogemos la coordenada Y
    QString ny = principal.firstChildElement ( "Y" ).toElement().text();

    /// Cogemos el ancho
    QString nwidth = principal.firstChildElement ( "WIDTH" ).toElement().text();

    /// Cogemos el alto
    QString nheight = principal.firstChildElement ( "HEIGHT" ).toElement().text();

    /// Si est&aacute; maximizada, ignoramos las otras dimensiones
    if (principal.firstChildElement ( "MAXIMIZED" ).toElement().text() == "true")
	 m_bulmafact->setWindowState(Qt::WindowMaximized);
    else /// Establecemos la geometria de la ventana principal.
	 m_bulmafact->setGeometry ( nx.toInt(), ny.toInt(), nwidth.toInt(), nheight.toInt() );

    /// Cogemos el indexador
    QString indexador = principal.firstChildElement ( "INDEXADOR" ).toElement().text();
    if ( indexador == "true" ) {
        s_indexadorCambiaEstado ( true );
        m_bulmafact->actionIndexador->setChecked ( true );
    } else {
        s_indexadorCambiaEstado ( false );
        m_bulmafact->actionIndexador->setChecked ( false );
    } // end if

    /// Cogemos el ancho del indexador
    m_bulmafact->restoreState ( QByteArray::fromBase64 ( QByteArray ( principal.firstChildElement ( "TOOLBARSDOCKWIDGETS" ).toElement().text().toLatin1() ) ) );

    /// Tratamos cada ventana
    QWidget *activewindow = NULL;
    QDomNodeList nodos = docElem.elementsByTagName ( "VENTANA" );
    for ( int i = 0; i < nodos.count(); i++ ) {
        QDomNode ventana = nodos.item ( i );
        QDomElement e1 = ventana.toElement(); /// try to convert the node to an element.
        if ( !e1.isNull() ) { /// the node was really an element.
            QString vname = e1.firstChildElement ( "VNAME" ).toElement().text();
            for ( int j = 0; j < m_windowListDock->numVentanas(); j++ ) {
                QObject *obj = m_windowListDock->ventana ( j );
                QWidget *wid = ( QWidget * ) obj;
                if ( obj->objectName() == vname ) {
                    QString vx = e1.firstChildElement ( "VX" ).toElement().text();
                    QString vy = e1.firstChildElement ( "VY" ).toElement().text();
                    QString vwidth = e1.firstChildElement ( "VWIDTH" ).toElement().text();
                    QString vheight = e1.firstChildElement ( "VHEIGHT" ).toElement().text();
                    QString vvisible = e1.firstChildElement ( "VVISIBLE" ).toElement().text();
                    QString vmaximized = e1.firstChildElement ( "VMAXIMIZED" ).toElement().text();
                    QString vactivewindow = e1.firstChildElement ( "VACTIVEWINDOW" ).toElement().text();
                    /// Establecemos la geometria de la ventana principal.
                    wid->resize ( vwidth.toInt(), vheight.toInt() );
                    wid->parentWidget() ->move ( vx.toInt(), vy.toInt() );
                    if ( vvisible == "true" ) {
                        wid->showNormal();
                    } // end if
                    if ( vmaximized == "true" ) {
                        wid->showMaximized();
                    }
                    if ( vactivewindow == "true" ) {
                        activewindow = wid;
                    }
                } // end if
            } // end for
        } // end if
    } // end for
    /// Si hay una ventana activa se pone como activa.
    if ( activewindow )
	activewindow->activateWindow();
    
}
Пример #15
0
bool ActionCollection::deSerialize(const QDomElement& actionCollectionElem)
{
  if (actionCollectionElem.isNull())
    return false;

  qDeleteAll(listInterfaceCommands);
  listInterfaceCommands.clear();

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

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

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

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

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

      commandElem = commandElem.nextSiblingElement("voiceInterfaceCommand");

      if (!com) continue;

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

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

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

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

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

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

  return true;
}
Пример #16
0
bool QgsComposerLegend::readXml( const QDomElement& itemElem, const QDomDocument& doc )
{
  if ( itemElem.isNull() )
  {
    return false;
  }

  //read general properties
  mSettings.setTitle( itemElem.attribute( QStringLiteral( "title" ) ) );
  if ( !itemElem.attribute( QStringLiteral( "titleAlignment" ) ).isEmpty() )
  {
    mSettings.setTitleAlignment( static_cast< Qt::AlignmentFlag >( itemElem.attribute( QStringLiteral( "titleAlignment" ) ).toInt() ) );
  }
  int colCount = itemElem.attribute( QStringLiteral( "columnCount" ), QStringLiteral( "1" ) ).toInt();
  if ( colCount < 1 ) colCount = 1;
  mSettings.setColumnCount( colCount );
  mSettings.setSplitLayer( itemElem.attribute( QStringLiteral( "splitLayer" ), QStringLiteral( "0" ) ).toInt() == 1 );
  mSettings.setEqualColumnWidth( itemElem.attribute( QStringLiteral( "equalColumnWidth" ), QStringLiteral( "0" ) ).toInt() == 1 );

  QDomNodeList stylesNodeList = itemElem.elementsByTagName( QStringLiteral( "styles" ) );
  if ( !stylesNodeList.isEmpty() )
  {
    QDomNode stylesNode = stylesNodeList.at( 0 );
    for ( int i = 0; i < stylesNode.childNodes().size(); i++ )
    {
      QDomElement styleElem = stylesNode.childNodes().at( i ).toElement();
      QgsLegendStyle style;
      style.readXml( styleElem, doc );
      QString name = styleElem.attribute( QStringLiteral( "name" ) );
      QgsLegendStyle::Style s;
      if ( name == QLatin1String( "title" ) ) s = QgsLegendStyle::Title;
      else if ( name == QLatin1String( "group" ) ) s = QgsLegendStyle::Group;
      else if ( name == QLatin1String( "subgroup" ) ) s = QgsLegendStyle::Subgroup;
      else if ( name == QLatin1String( "symbol" ) ) s = QgsLegendStyle::Symbol;
      else if ( name == QLatin1String( "symbolLabel" ) ) s = QgsLegendStyle::SymbolLabel;
      else continue;
      setStyle( s, style );
    }
  }

  //font color
  QColor fontClr;
  fontClr.setNamedColor( itemElem.attribute( QStringLiteral( "fontColor" ), QStringLiteral( "#000000" ) ) );
  mSettings.setFontColor( fontClr );

  //spaces
  mSettings.setBoxSpace( itemElem.attribute( QStringLiteral( "boxSpace" ), QStringLiteral( "2.0" ) ).toDouble() );
  mSettings.setColumnSpace( itemElem.attribute( QStringLiteral( "columnSpace" ), QStringLiteral( "2.0" ) ).toDouble() );

  mSettings.setSymbolSize( QSizeF( itemElem.attribute( QStringLiteral( "symbolWidth" ), QStringLiteral( "7.0" ) ).toDouble(), itemElem.attribute( QStringLiteral( "symbolHeight" ), QStringLiteral( "14.0" ) ).toDouble() ) );
  mSettings.setWmsLegendSize( QSizeF( itemElem.attribute( QStringLiteral( "wmsLegendWidth" ), QStringLiteral( "50" ) ).toDouble(), itemElem.attribute( QStringLiteral( "wmsLegendHeight" ), QStringLiteral( "25" ) ).toDouble() ) );
  mSettings.setLineSpacing( itemElem.attribute( QStringLiteral( "lineSpacing" ), "1.0" ).toDouble() );

  mSettings.setDrawRasterBorder( itemElem.attribute( QStringLiteral( "rasterBorder" ), QStringLiteral( "1" ) ) != QLatin1String( "0" ) );
  mSettings.setRasterBorderColor( QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "rasterBorderColor" ), QStringLiteral( "0,0,0" ) ) ) );
  mSettings.setRasterBorderWidth( itemElem.attribute( QStringLiteral( "rasterBorderWidth" ), QStringLiteral( "0" ) ).toDouble() );

  mSettings.setWrapChar( itemElem.attribute( QStringLiteral( "wrapChar" ) ) );

  mSizeToContents = itemElem.attribute( QStringLiteral( "resizeToContents" ), QStringLiteral( "1" ) ) != QLatin1String( "0" );

  //composer map
  mLegendFilterByMap = itemElem.attribute( QStringLiteral( "legendFilterByMap" ), QStringLiteral( "0" ) ).toInt();
  if ( !itemElem.attribute( QStringLiteral( "map" ) ).isEmpty() )
  {
    setComposerMap( mComposition->getComposerMapById( itemElem.attribute( QStringLiteral( "map" ) ).toInt() ) );
  }

  QDomElement oldLegendModelElem = itemElem.firstChildElement( QStringLiteral( "Model" ) );
  if ( !oldLegendModelElem.isNull() )
  {
    // QGIS <= 2.4
    QgsLayerTreeGroup* nodeRoot = new QgsLayerTreeGroup();
    _readOldLegendGroup( oldLegendModelElem, nodeRoot, mComposition->project() );
    setCustomLayerTree( nodeRoot );
  }
  else
  {
    // QGIS >= 2.6
    QDomElement layerTreeElem = itemElem.firstChildElement( QStringLiteral( "layer-tree-group" ) );
    setCustomLayerTree( QgsLayerTreeGroup::readXml( layerTreeElem ) );
  }

  //restore general composer item properties
  QDomNodeList composerItemList = itemElem.elementsByTagName( QStringLiteral( "ComposerItem" ) );
  if ( !composerItemList.isEmpty() )
  {
    QDomElement composerItemElem = composerItemList.at( 0 ).toElement();
    _readXml( composerItemElem, doc );
  }

  // < 2.0 projects backward compatibility >>>>>
  //title font
  QString titleFontString = itemElem.attribute( QStringLiteral( "titleFont" ) );
  if ( !titleFontString.isEmpty() )
  {
    rstyle( QgsLegendStyle::Title ).rfont().fromString( titleFontString );
  }
  //group font
  QString groupFontString = itemElem.attribute( QStringLiteral( "groupFont" ) );
  if ( !groupFontString.isEmpty() )
  {
    rstyle( QgsLegendStyle::Group ).rfont().fromString( groupFontString );
  }

  //layer font
  QString layerFontString = itemElem.attribute( QStringLiteral( "layerFont" ) );
  if ( !layerFontString.isEmpty() )
  {
    rstyle( QgsLegendStyle::Subgroup ).rfont().fromString( layerFontString );
  }
  //item font
  QString itemFontString = itemElem.attribute( QStringLiteral( "itemFont" ) );
  if ( !itemFontString.isEmpty() )
  {
    rstyle( QgsLegendStyle::SymbolLabel ).rfont().fromString( itemFontString );
  }

  if ( !itemElem.attribute( QStringLiteral( "groupSpace" ) ).isEmpty() )
  {
    rstyle( QgsLegendStyle::Group ).setMargin( QgsLegendStyle::Top, itemElem.attribute( QStringLiteral( "groupSpace" ), QStringLiteral( "3.0" ) ).toDouble() );
  }
  if ( !itemElem.attribute( QStringLiteral( "layerSpace" ) ).isEmpty() )
  {
    rstyle( QgsLegendStyle::Subgroup ).setMargin( QgsLegendStyle::Top, itemElem.attribute( QStringLiteral( "layerSpace" ), QStringLiteral( "3.0" ) ).toDouble() );
  }
  if ( !itemElem.attribute( QStringLiteral( "symbolSpace" ) ).isEmpty() )
  {
    rstyle( QgsLegendStyle::Symbol ).setMargin( QgsLegendStyle::Top, itemElem.attribute( QStringLiteral( "symbolSpace" ), QStringLiteral( "2.0" ) ).toDouble() );
    rstyle( QgsLegendStyle::SymbolLabel ).setMargin( QgsLegendStyle::Top, itemElem.attribute( QStringLiteral( "symbolSpace" ), QStringLiteral( "2.0" ) ).toDouble() );
  }
  // <<<<<<< < 2.0 projects backward compatibility

  emit itemChanged();
  return true;
}
Пример #17
0
void ReportViewWidget::on_actionSaveQry_triggered()
{
	if (m_currentQry.isEmpty()) {

		ReportFileDialog fD(m_dirModel, this);
		start:
	    if (fD.exec() != QDialog::Accepted)
	         return;

		if (fD.fileName().isEmpty())
			return;

		m_currentQry = fD.path() + "/" + fD.fileName();

		if (QFile(m_currentQry).exists()) {
	        if (QMessageBox::question(this, "CuteFarm",
	                             tr("File %1 exists.\nReplace?")
	                             .arg(m_currentQry), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No)
	        	goto start;
		}

		QFile file(m_currentQry);
	    if (!file.open(QFile::WriteOnly | QFile::Text)) {
	        QMessageBox::warning(this, "CuteFarm",
	                             tr("Can not save file %1\n%2.")
	                             .arg(file.fileName())
	                             .arg(file.errorString()));
	        return;
	    }

	    QTextStream out(&file);
	    out << "<?xml version='1.0' encoding='UTF-8'?>\n"
	    	   "<!DOCTYPE qry>\n"
	    	   "<qry version=\"1.0\">\n"
	    	   "	<description>"+ Qt::escape(ui.textEditComt->toPlainText()) +"</description>\n"
	    	   "	<sql>"+ Qt::escape(ui.textEditSql->toPlainText()) +"</sql>\n"
	    	   "</qry>\n";

	    QModelIndex parent = ui.dirView->currentIndex().parent();
	    m_dirModel->refresh(parent);
	    file.close();
	    m_actnQryButton->setText(QFileInfo(file.fileName()).fileName());

	    return;
	}

    QFile file(m_currentQry);
    if (!file.open(QFile::WriteOnly | QFile::Text)) {
        QMessageBox::warning(this, "CuteFarm",
                             tr("Can not save file %1\n%2.")
                             .arg(QFile(m_currentQry).fileName())
                             .arg(file.errorString()));
        return;
    }

    QDomElement root = m_domDocument.documentElement();
    QDomElement oldDesc = root.firstChildElement("description");
    QDomElement newDesc = m_domDocument.createElement("description");
    QDomText newDescText = m_domDocument.createTextNode(ui.textEditComt->toPlainText());
    newDesc.appendChild(newDescText);
    root.replaceChild(newDesc, oldDesc);
    QDomElement oldSql = root.firstChildElement("sql");
    QDomElement newSql = m_domDocument.createElement("sql");
    QDomText newSqlText = m_domDocument.createTextNode(ui.textEditSql->toPlainText());
    newSql.appendChild(newSqlText);
    root.replaceChild(newSql, oldSql);

    const int IndentSize = 4;

    QTextStream out(&file);
    m_domDocument.save(out, IndentSize);
    file.close();
    QModelIndex parent = ui.dirView->currentIndex().parent();
    m_dirModel->refresh(parent);

    emit statusMsg(tr("Saved: %1").arg(m_currentQry), 5000);
}
Пример #18
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", "" );
  }

  //legendUrl
  QDomElement legendUrlElem = layerElement.firstChildElement( "legendUrl" );
  if ( !legendUrlElem.isNull() )
  {
    mLegendUrl = legendUrlElem.text();
    mLegendUrlFormat = legendUrlElem.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
Пример #19
0
LADSPAPresetSlot::LADSPAPresetSlot(QWidget *parent, QDomElement element, int slot, LADSPAPresetManager *presetManager, QPalette palette) : QWidget(parent)
{
    m_pPresetManager = presetManager;
    m_qPalette = palette;
    m_iSlotNumber = slot;

    setAcceptDrops(true);

    m_pScrollArea = new QScrollArea(this);
    m_pScrollWidget = new QWidget(m_pScrollArea);
    m_pScrollArea->setWidget(m_pScrollWidget);
    //m_pScrollArea->setWidgetResizable(true);
    m_pScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    QDomElement posElement = element.firstChildElement("Pos");
    QString pos = posElement.text();
    int x = pos.left(pos.indexOf(",")).toInt();
    int y = pos.mid(pos.indexOf(",") + 1).toInt();
    if (x < 0)
    {
        x = parent->width() + x;
    }
    if (y < 0)
    {
	    y = parent->height() + y;
    }
    QDomElement spacingElement = element.firstChildElement("Spacing");
    QString spacing = spacingElement.text();
    int spacingWidth = spacing.left(spacing.indexOf(",")).toInt();
    int spacingHeight = spacing.mid(spacing.indexOf(",") + 1).toInt();    

    QDomElement sizeElement = element.firstChildElement("Size");
    QString size = sizeElement.text();
    int width = size.left(size.indexOf(",")).toInt();
    int height = size.mid(size.indexOf(",") + 1).toInt();
    if (width <= 0)
    {
	width = parent->width() + width;
    }
    if (height <= 0)
    {
	height = parent->height() + height;
    }
    move(x + slot * spacingWidth, y + slot * (height + spacingHeight));
    resize(width, height);
    m_pScrollArea->resize(width, height);
    m_pScrollWidget->resize(width - 5, height - 5);
    m_iBaseWidth = width;

    QString slotString;
    slotString.setNum(slot);
    
    QDomNodeList buttonNodeList = element.elementsByTagName("PushButton");
    for (int i = 0; i < buttonNodeList.count(); i++)
    {
	QDomElement buttonElement = buttonNodeList.item(i).toElement();
	QString configKey = buttonElement.firstChildElement("Connection").firstChildElement("ConfigKey").text();
	if (configKey.startsWith("[LADSPA],RemoveEffect"))
	{
	    QString keyString = QString("RemoveEffect") + slotString;
	    ConfigKey *key = new ConfigKey("[LADSPA]", keyString);
	    ControlPushButton *control = new ControlPushButton(*key, false);
	    m_pRemoveButton = new WPushButton(m_pScrollWidget);
	    buttonElement.firstChildElement("Connection").firstChildElement("ConfigKey").firstChild().setNodeValue("[LADSPA]," + keyString);
	    m_pRemoveButton->setup(buttonElement);
	    m_pRemoveButton->setVisible(false);
	}
	else if (configKey.startsWith("[LADSPA],EnableEffect"))
	{
        qDebug() << "Setting up LADSPA EnableEffect" << slotString;
	    QString keyString = QString("EnableEffect") + slotString;
	    ConfigKey *key = new ConfigKey("[LADSPA]", keyString);
        qDebug() << "Key string:" << keyString;
	    ControlObject *control = new ControlPushButton(*key, false);
        control->set(1.0f);
	    m_pEnableButton = new WPushButton(m_pScrollWidget);
	    buttonElement.firstChildElement("Connection").firstChildElement("ConfigKey").firstChild().setNodeValue("[LADSPA]," + keyString);
	    m_pEnableButton->setup(buttonElement);
	}
	else
	{
	    qDebug() << "LADSPA: Invalid skin (unknown button: " << configKey << ")";
	}
    }

    QDomElement labelElement = element.firstChildElement("Label");
    m_pLabel = new QLabel(m_pScrollWidget);
    m_pLabel->setText(tr("Drag a preset from the list & drop it here"));

    posElement = labelElement.firstChildElement("Pos");
    pos = posElement.text();
    x = pos.left(pos.indexOf(",")).toInt();
    y = pos.mid(pos.indexOf(",") + 1).toInt();
    if (x < 0)
    {
        x = this->width() + x;
    }
    if (y < 0)
    {
	    y = this->height() + y;
    }
    m_pLabel->move(x, y);

    QDomElement widthElement = labelElement.firstChildElement("Width");
    if (!(widthElement.isNull()))
    {
	    width = widthElement.text().toInt();
	    m_pLabel->setMaximumWidth(width);
    }

    m_pLabel->setPalette(palette);

    m_qKnobElement = element.firstChildElement("Knob");
    m_pPresetInstance = NULL;

    
    ConfigKey *key = new ConfigKey("[LADSPA]", "DryWet" + slotString);
    ControlPotmeter *control = new ControlPotmeter(*key, 0.0, 1.0);
    m_pDryWetKnob = new WKnob(m_pScrollWidget);
    QString keyString = QString("[LADSPA],DryWet") + slotString;
    m_qKnobElement.firstChildElement(QString("Connection")).firstChildElement(QString("ConfigKey")).firstChild().setNodeValue(keyString);
    m_qKnobElement.firstChildElement(QString("Tooltip")).firstChild().setNodeValue("Dry/wet");
    m_pDryWetKnob->setup(m_qKnobElement);
    m_pDryWetKnob->show();

    posElement = m_qKnobElement.firstChildElement("Pos");
    pos = posElement.text();
    x = pos.left(pos.indexOf(",")).toInt();
    y = pos.mid(pos.indexOf(",") + 1).toInt();
    if (x < 0)
    {
        x = this->width() + x;
    }
    if (y < 0)
    {
	y = this->height() + y;
    }
    m_pDryWetKnob->move(x, y);

    spacingElement = m_qKnobElement.firstChildElement("Spacing");
    spacing = spacingElement.text();
    spacingWidth = spacing.left(spacing.indexOf(",")).toInt();

    m_pDryWetLabel = new QLabel("Dry/wet", m_pScrollWidget);
    m_pDryWetLabel->setMaximumWidth(spacingWidth + m_pDryWetKnob->width() - 4);
    m_pDryWetLabel->show();
    x += m_pDryWetKnob->width() / 2 - m_pDryWetLabel->width() / 2;
    m_pDryWetLabel->move(x, y + m_pDryWetKnob->height() + 1);
    m_pDryWetLabel->setPalette(m_qPalette);

    connect(m_pRemoveButton, SIGNAL(valueChangedLeftUp(double)), this, SLOT(slotRemove()));
}
Пример #20
0
QgsSymbolLayerV2* QgsMarkerLineSymbolLayerV2::createFromSld( QDomElement &element )
{
  QgsDebugMsg( "Entered." );

  QDomElement strokeElem = element.firstChildElement( "Stroke" );
  if ( strokeElem.isNull() )
    return NULL;

  QDomElement graphicStrokeElem = strokeElem.firstChildElement( "GraphicStroke" );
  if ( graphicStrokeElem.isNull() )
    return NULL;

  // retrieve vendor options
  bool rotateMarker = true;
  Placement placement = Interval;

  QgsStringMap vendorOptions = QgsSymbolLayerV2Utils::getVendorOptionList( element );
  for ( QgsStringMap::iterator it = vendorOptions.begin(); it != vendorOptions.end(); ++it )
  {
    if ( it.key() == "placement" )
    {
      if ( it.value() == "points" ) placement = Vertex;
      else if ( it.value() == "firstPoint" ) placement = FirstVertex;
      else if ( it.value() == "lastPoint" ) placement = LastVertex;
      else if ( it.value() == "centralPoint" ) placement = CentralPoint;
    }
    else if ( it.value() == "rotateMarker" )
    {
      rotateMarker = it.value() == "0";
    }
  }

  QgsMarkerSymbolV2 *marker = 0;

  QgsSymbolLayerV2 *l = QgsSymbolLayerV2Utils::createMarkerLayerFromSld( graphicStrokeElem );
  if ( l )
  {
    QgsSymbolLayerV2List layers;
    layers.append( l );
    marker = new QgsMarkerSymbolV2( layers );
  }

  if ( !marker )
    return NULL;

  double interval = 0.0;
  QDomElement gapElem = graphicStrokeElem.firstChildElement( "Gap" );
  if ( !gapElem.isNull() )
  {
    bool ok;
    double d = gapElem.firstChild().nodeValue().toDouble( &ok );
    if ( ok )
      interval = d;
  }

  double offset = 0.0;
  QDomElement perpOffsetElem = graphicStrokeElem.firstChildElement( "PerpendicularOffset" );
  if ( !perpOffsetElem.isNull() )
  {
    bool ok;
    double d = perpOffsetElem.firstChild().nodeValue().toDouble( &ok );
    if ( ok )
      offset = d;
  }

  QgsMarkerLineSymbolLayerV2* x = new QgsMarkerLineSymbolLayerV2( rotateMarker );
  x->setPlacement( placement );
  x->setInterval( interval );
  x->setSubSymbol( marker );
  x->setOffset( offset );
  return x;
}
Пример #21
0
CClass* CDecodeFlowType::readClassType ( const QDomElement& element)
{
  bool bOk = false;
  CClass* cl = NULL;
  
  QDomElement id = element.firstChildElement("id");
  QDomElement name = element.firstChildElement("name");
  QDomElement definition = element.firstChildElement("definition");
  QDomElement readOnly = element.firstChildElement("read-only");
  QDomElement values = element.firstChildElement("values");
  QDomElement type = element.firstChildElement("type");

  switch (type.text().toInt())
  {
    case CClass::VOID:
    {
      CVoid* v = new CVoid(name.text(), definition.text());
      v->setId(id.text().toInt(&bOk));
      v->setReadOnly((readOnly.text().toInt(&bOk)));
      cl = v;
      bOk = true;
    }
      break;
      
    case CClass::ENUMERATION:
    {
      CEnumeration* e = new CEnumeration(name.text(), definition.text());
      e->setId(id.text().toInt(&bOk));
      e->setReadOnly((readOnly.text().toInt(&bOk)));
      QDomElement data = values.firstChildElement("string");
      while (!data.isNull())
      {
        e->append(data.text());
        data = data.nextSiblingElement("string");
      }
      bOk = true;
      cl = e;
    }
      break;
    
    case CClass::NUMBER:
    {
      CNumber* n = new CNumber(name.text(), definition.text());
      n->setId(id.text().toInt(&bOk));
      n->setReadOnly((readOnly.text().toInt(&bOk)));
      QDomElement range = values.firstChildElement("range");
      if (!range.isNull())
      {
        Range r;
        r.begin = range.attribute("begin").toLongLong(&bOk);
        if (!bOk)
        {
          // try with uLongLong
          r.begin = range.attribute("begin").toULongLong(&bOk);
        }
        r.end = range.attribute("end").toLongLong(&bOk);
        if (!bOk)
        {
          // try with uLongLong
          r.end = range.attribute("end").toULongLong(&bOk);
        }
        r.beginName = range.attribute("begin-name");
        r.endName = range.attribute("end-name");
        n->insertRange(r);
        bOk = true;
      }
      else 
        bOk = false;
      
      cl = n;
    }
      break;
    
    case CClass::FLOAT:
    {
      CFloat* f = new CFloat(name.text(), definition.text());
      f->setId(id.text().toInt(&bOk));
      f->setReadOnly((readOnly.text().toInt(&bOk)));
      QDomElement range = values.firstChildElement("range");
      if (!range.isNull())
      {
        Range r;
        r.begin = range.attribute("begin").toDouble(&bOk);
        r.end = range.attribute("end").toDouble(&bOk);
        r.beginName = range.attribute("begin-name");
        r.endName = range.attribute("end-name");
        f->insertRange(r);
        bOk = true;
      }
      else 
        bOk = false;
      
      cl = f;
    }
      break;
      
    case CClass::CHAR:
    {
      CChar* c = new CChar(name.text(), definition.text());
      c->setId(id.text().toInt(&bOk));
      c->setReadOnly((readOnly.text().toInt(&bOk)));
      QDomElement range = values.firstChildElement("range");
      if (!range.isNull())
      {
        Range r;
        r.begin = range.attribute("begin").toInt(&bOk);
        r.end = range.attribute("end").toInt(&bOk);
        r.beginName = range.attribute("begin-name");
        r.endName = range.attribute("end-name");
        c->insertRange(r);
        bOk = true;
      }
      else 
        bOk = false;
      
      cl = c;
    }
      break;
      
    case CClass::STRING:
    {
      CString* s = new CString(name.text(), definition.text());
      s->setId(id.text().toInt(&bOk));
      s->setReadOnly((readOnly.text().toInt(&bOk)));
      QDomElement size = values.firstChildElement("size");
      if (!size.isNull())
      {
        s->setSize(size.text().toInt(&bOk));
        bOk = true;
      }
      else 
        bOk = false;
      
      cl = s;
    }
      break;
      
    case CClass::AGGREGATION:
    {
      CStructure* s = new CStructure(name.text(), definition.text());
      s->setId(id.text().toInt(&bOk));
      s->setReadOnly((readOnly.text().toInt(&bOk)));
      QDomElement structure = values.firstChildElement("structure");
      while (!structure.isNull() && !bOk)
      {
        Structure st;
        st.name = structure.attribute("name");
        st.classId = structure.attribute("type").toInt(&bOk);
        st.pClass = NULL;
        if (bOk == true)
        {
          s->insertField(st);
        }
        structure = structure.nextSiblingElement("structure");
      }      
      cl = s;
    }
      break;
      
    default:
      bOk = false;
      break;
  }
  
  if ((bOk == false) & (cl != NULL))
  {
    delete cl;
    cl = NULL;
  }
  
  return cl;
}
Пример #22
0
QgsFeatureRendererV2* QgsGraduatedSymbolRendererV2::create( QDomElement& element )
{
  QDomElement symbolsElem = element.firstChildElement( "symbols" );
  if ( symbolsElem.isNull() )
    return NULL;

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

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

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

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

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

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


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

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

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

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

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

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

  QDomElement labelFormatElem = element.firstChildElement( "labelformat" );
  if ( ! labelFormatElem.isNull() )
  {
    QgsRendererRangeV2LabelFormat labelFormat;
    labelFormat.setFromDomElement( labelFormatElem );
    r->setLabelFormat( labelFormat );
  }
  // TODO: symbol levels
  return r;
}
// Slot called by the menu manager on user action
void UAVSettingsImportExportFactory::importUAVSettings()
{
    // ask for file name
    QString fileName;
    QString filters = tr("UAVObjects XML files (*.uav);; XML files (*.xml)");
    fileName = QFileDialog::getOpenFileName(0, tr("Import UAV Settings"), "", filters);
    if (fileName.isEmpty()) {
        return;
    }

    // Now open the file
    QFile file(fileName);
    QDomDocument doc("UAVObjects");
    file.open(QFile::ReadOnly|QFile::Text);
    if (!doc.setContent(file.readAll())) {
        QMessageBox msgBox;
        msgBox.setText(tr("File Parsing Failed."));
        msgBox.setInformativeText(tr("This file is not a correct XML file"));
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.exec();
        return;
    }
    file.close();

    // find the root of settings subtree
    emit importAboutToBegin();
    qDebug()<<"Import about to begin";

    QDomElement root = doc.documentElement();
    if (root.tagName() == "uavobjects") {
        root = root.firstChildElement("settings");
    }
    if (root.isNull() || (root.tagName() != "settings")) {
        QMessageBox msgBox;
        msgBox.setText(tr("Wrong file contents"));
        msgBox.setInformativeText(tr("This file does not contain correct UAVSettings"));
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.exec();
        return;
    }

    // We are now ok: setup the import summary dialog & update it as we
    // go along.
    ImportSummaryDialog swui((QWidget*)Core::ICore::instance()->mainWindow());

    ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
    UAVObjectManager *objManager = pm->getObject<UAVObjectManager>();
    swui.show();

    QDomNode node = root.firstChild();
    while (!node.isNull()) {
        QDomElement e = node.toElement();
        if (e.tagName() == "object") {

            //  - Read each object
            QString uavObjectName  = e.attribute("name");
            uint uavObjectID = e.attribute("id").toUInt(NULL,16);

            // Sanity Check:
            UAVObject *obj = objManager->getObject(uavObjectName);
            UAVDataObject *dobj = dynamic_cast<UAVDataObject*>(obj);
            if (obj == NULL) {
                // This object is unknown!
                qDebug() << "Object unknown:" << uavObjectName << uavObjectID;
                swui.addLine(uavObjectName, "Error (Object unknown)", false);
            } else if(dobj && !dobj->getIsPresentOnHardware()) {
                swui.addLine(uavObjectName, "Error (Object not present on hw)", false);
            } else {
                //  - Update each field
                //  - Issue and "updated" command
                bool error = false;
                bool setError = false;
                QDomNode field = node.firstChild();
                while(!field.isNull()) {
                    QDomElement f = field.toElement();
                    if (f.tagName() == "field") {
                        UAVObjectField *uavfield = obj->getField(f.attribute("name"));
                        if (uavfield) {
                            QStringList list = f.attribute("values").split(",");
                            if (list.length() == 1) {
                                if (false == uavfield->checkValue(f.attribute("values"))) {
                                    qDebug() << "checkValue returned false on: " << uavObjectName << f.attribute("values");
                                    setError = true;
                                } else {
                                    uavfield->setValue(f.attribute("values"));
                                }
                            } else {
                                // This is an enum:
                                int i = 0;
                                QStringList list = f.attribute("values").split(",");
                                foreach (QString element, list) {
                                    if (false == uavfield->checkValue(element, i)) {
                                        qDebug() << "checkValue(list) returned false on: " << uavObjectName << list;
                                        setError = true;
                                    } else {
                                        uavfield->setValue(element,i);
                                    }
                                    i++;
                                }
                            }
                        } else {
                            error = true;
                        }
                    }
                    field = field.nextSibling();
                }
                obj->updated();

                if (error) {
                    swui.addLine(uavObjectName, "Warning (Object field unknown)", true);
                } else if (uavObjectID != obj->getObjID()) {
                    qDebug() << "Mismatch for Object " << uavObjectName << uavObjectID << " - " << obj->getObjID();
                    swui.addLine(uavObjectName, "Warning (ObjectID mismatch)", true);
                } else if (setError) {
                    swui.addLine(uavObjectName, "Warning (Objects field value(s) invalid)", false);
                } else {
                    swui.addLine(uavObjectName, "OK", true);
                }
            }
Пример #24
0
void Variable::handleProperty(const QDomElement &xml)
{
    Q_ASSERT(!xml.isNull());
    Q_ASSERT(xml.nodeName() == "property");

    setInScope(true);

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

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

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

        v->handleProperty(el);

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

    for (int i = 0; i < childCount() - (hasMore() ? 1 : 0); ++i) {
        Q_ASSERT(dynamic_cast<KDevelop::Variable*>(child(i)));
        KDevelop::Variable* v = static_cast<KDevelop::Variable*>(child(i));
        if (!current.contains(v->expression())) {
            removeChild(i);
            --i;
            delete v;
        }
    }
    if (!childCount() && xml.attribute("children") == "1") {
        kDebug() << "has more" << this;
        setHasMore(true);
        if (isExpanded()) {
            fetchMoreChildren();
        }
    }
}
GraphicsMidiInputItem::GraphicsMidiInputItem(QDomElement controlNode, const PixmapMap& pixmapMap)
{
	// map a midi message to a
	m_inputMidiMessages.append(MidiMessage(controlNode));

	m_name = controlNode.attribute(CONTROL_NAME, "");
	m_groupName = controlNode.attribute(CONTROL_GROUP, "");
	QString debugColor = controlNode.attribute("debug");

	GraphicsMidiArea area = parseAreaElement(controlNode);
	if (area.isNull())
		return;

	QString mask = parsePixmapMask(controlNode);

	setSceneRect(area.rect);
	bool hasRanged = false;

	// get states
	QDomElement stateNode = controlNode.firstChildElement("state");
	int rangeMarker;
	QPixmap backgroundPixmap = pixmapFromMap(GuiUtils::background, m_sceneRect, pixmapMap, mask);
	ushort minRangeId, maxRangeId;
	while (!stateNode.isNull())
	{
		QString state = stateNode.text();
		QString stateValue = stateNode.attribute("value").trimmed();

		// map range to m_state2Pixmap
		rangeMarker = stateValue.indexOf(INPUT_STATE_RANGEMARKER);
		if (rangeMarker > 0)
		{
			hasRanged = true;
			bool ok = false;
			//qDebug() << state << stateValue  << rangeMarker << stateValue.left(rangeMarker) << stateValue.mid(rangeMarker + 1);
			minRangeId = stateValue.left(rangeMarker).toUShort(&ok, 0);
			if (ok)
				maxRangeId = stateValue.mid(rangeMarker + 1).toUShort(&ok, 0);
			if (!ok)
			{
				qCritical() << "error parsing:" << stateValue << "; line:" << stateNode.lineNumber();
				return;
			}

			QPixmap pixmap = pixmapFromState(stateNode, backgroundPixmap, m_sceneRect, pixmapMap, mask);
			if (!pixmap.isNull())
			{
				checkDebug(debugColor, pixmap, area);
				// map range to m_state2Pixmap
				m_state2Pixmap.insert(maxRangeId, pixmap);
				m_range2State.insert(minRangeId, maxRangeId); // add ranged value
			}
		}
		else
		{
			bool ok = false;
			ushort stateId = stateValue.toUShort(&ok, 0);
			if (pixmapMap.contains(state) && ok)
			{
//				QPixmap pixmap = pixmapMap.value(state).copy(rect);
				QPixmap pixmap = pixmapFromState(stateNode, backgroundPixmap, m_sceneRect, pixmapMap, mask);
				checkDebug(debugColor, pixmap, area);

				m_state2Pixmap.insert(stateId, pixmap);
				m_range2State.insert(stateId, stateId); // support for ranged values
				if (GuiUtils::isBackground(state))
				{
					m_offState = stateId;
					setPixmap(pixmap);
				}
			}
		}
		stateNode = stateNode.nextSiblingElement("state");
	}

	if (!hasRanged)
		m_range2State.clear(); // no ranged values after all...

/*	QPixmap pixmap = pixmapMap[GuiUtils::background];

if (0) {
	setPixmap(pixmap.copy(rect));
} else {
QPixmap tmp = pixmap.copy(rect);
QPainter dc(&tmp);
dc.setPen(Qt::green);
dc.drawRect(0,0,rect.width()-1, rect.height()-1);
setPixmap(tmp);
}
*/
	setPos(m_sceneRect.topLeft());
	setZValue(2);

	m_hasInput = true;
}
Пример #26
0
bool GwfObjectInfoReader::read(const QDomDocument& document)
{
    if (mIsOwner)
        del();
    mLastError.clear();

    QDomElement root = document.documentElement();

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

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

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

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

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

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

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

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

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

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

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

        element = element.nextSiblingElement("contour");
    }
    return true;
}
Пример #27
0
void QgsProjectFileTransform::transform1800to1900()
{
  if ( mDom.isNull() )
  {
    return;
  }

  QDomNodeList layerItemList = mDom.elementsByTagName( "rasterproperties" );
  for ( int i = 0; i < layerItemList.size(); ++i )
  {
    QDomElement rasterPropertiesElem = layerItemList.at( i ).toElement();
    QDomNode layerNode = rasterPropertiesElem.parentNode();
    QDomElement dataSourceElem = layerNode.firstChildElement( "datasource" );
    QDomElement layerNameElem = layerNode.firstChildElement( "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( "ComposerMap" );
  for ( int i = 0; i < composerMapList.size(); ++i )
  {
    QDomNodeList gridList = composerMapList.at( i ).toElement().elementsByTagName( "Grid" );
    for ( int j = 0; j < gridList.size(); ++j )
    {
      QDomNodeList annotationList = gridList.at( j ).toElement().elementsByTagName( "Annotation" );
      for ( int k = 0; k < annotationList.size(); ++k )
      {
        QDomElement annotationElem = annotationList.at( k ).toElement();

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

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

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

    //find <QgsComposition element
    QDomElement compositionElem = composerElem.firstChildElement( "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() == "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( "renderer-v2" );
  for ( int i = 0; i < rendererList.size(); ++i )
  {
    QDomNodeList layerList = rendererList.at( i ).toElement().elementsByTagName( "layer" );
    for ( int j = 0; j < layerList.size(); ++j )
    {
      QDomElement layerElem = layerList.at( j ).toElement();
      if ( layerElem.attribute( "class" ) == "SimpleFill" )
      {
        QDomNodeList propList = layerElem.elementsByTagName( "prop" );
        for ( int k = 0; k < propList.size(); ++k )
        {
          QDomElement propElem = propList.at( k ).toElement();
          if ( propElem.attribute( "k" ) == "color" || propElem.attribute( "k" ) == "color_border" )
          {
            propElem.setAttribute( "v", propElem.attribute( "v" ).section( ",", 0, 2 ) + ",255" );
          }
        }
      }
    }
  }

  QgsDebugMsg( mDom.toString() );
}
Пример #28
0
bool GwfObjectInfoReader::parseNode(const QDomElement &element)
{
    std::auto_ptr<SCgNodeInfo> nodeInfo(new SCgNodeInfo());

    if(!parseObject(element,nodeInfo.get()))
        return false;

    qreal& x = nodeInfo->posRef().rx();
    qreal& y = nodeInfo->posRef().ry();
    if (!getAttributeDouble(element, "x", x) || !getAttributeDouble(element, "y", y))
        return false;


    // get identifier position
    int& idtfPos = nodeInfo->idtfPosRef();
    if (!getAttributeInt(element, "idtf_pos", idtfPos))
        idtfPos = 0;

    // get content element
    QDomElement contEl = element.firstChildElement("content");
    if (contEl.isNull())
    {
        errorHaventContent(element.tagName());
        return false;
    }

    // get content type
    int& cType = nodeInfo->contentTypeRef();
    if (!getAttributeInt(contEl, "type", cType))
        return false;

    // get mime type
    if (!getAttributeString(contEl, "mime_type", nodeInfo->contentMimeTypeRef()))
        return false;

    // in old versions format, there wasn't content_visibility attribute, so we need to check if it exists
    if (contEl.hasAttribute("content_visibility") && !getAttributeBool(contEl, "content_visibility", nodeInfo->contentVisibleRef()))
        return false;

    // set content to nodeInfo
    if (cType > 0 && cType < 5)
    {
        if (cType == 1 || cType == 2 || cType == 3)
            nodeInfo->contentDataRef() = QVariant(contEl.firstChild().nodeValue());
        else if (cType == 4)
        {
            // get file name
            getAttributeString(contEl, "file_name", nodeInfo->contentFilenameRef());
            QString cData = contEl.firstChild().nodeValue();
            QByteArray arr = QByteArray::fromBase64(cData.toLocal8Bit());
            nodeInfo->contentDataRef() = QVariant(arr);
        }else
        {
            mLastError = QObject::tr("Content type '%1' doesn't supported for now").arg(cType);
            return false;
        }
    }else if (cType != 0)
    {
        mLastError = QObject::tr("Unknown content type '%1'").arg(cType);
        return false;
    }

    mObjectsInfo[SCgNode::Type].append(nodeInfo.release());
    return true;
}
Пример #29
0
void QgsProjectFileTransform::transformContrastEnhancement( QDomDocument& doc, const QDomElement& rasterproperties, QDomElement& rendererElem )
{
  if ( rasterproperties.isNull() || rendererElem.isNull() )
  {
    return;
  }

  double minimumValue = 0;
  double maximumValue = 0;
  QDomElement contrastMinMaxElem = rasterproperties.firstChildElement( "contrastEnhancementMinMaxValues" );
  if ( contrastMinMaxElem.isNull() )
  {
    return;
  }

  QDomElement contrastEnhancementAlgorithmElem = rasterproperties.firstChildElement( "mContrastEnhancementAlgorithm" );
  if ( contrastEnhancementAlgorithmElem.isNull() )
  {
    return;
  }

  //convert enhancement name to enumeration
  int algorithmEnum = 0;
  QString algorithmString = contrastEnhancementAlgorithmElem.text();
  if ( algorithmString == "StretchToMinimumMaximum" )
  {
    algorithmEnum = 1;
  }
  else if ( algorithmString == "StretchAndClipToMinimumMaximum" )
  {
    algorithmEnum = 2;
  }
  else if ( algorithmString == "ClipToMinimumMaximum" )
  {
    algorithmEnum = 3;
  }
  else if ( algorithmString == "UserDefinedEnhancement" )
  {
    algorithmEnum = 4;
  }

  QDomNodeList minMaxEntryList = contrastMinMaxElem.elementsByTagName( "minMaxEntry" );
  QStringList enhancementNameList;
  if ( minMaxEntryList.size() == 1 )
  {
    enhancementNameList << "contrastEnhancement";
  }
  if ( minMaxEntryList.size() ==  3 )
  {
    enhancementNameList << "redContrastEnhancement" << "greenContrastEnhancement" << "blueContrastEnhancement";
  }
  if ( minMaxEntryList.size() > enhancementNameList.size() )
  {
    return;
  }

  QDomElement minMaxEntryElem;
  for ( int i = 0; i < minMaxEntryList.size(); ++i )
  {
    minMaxEntryElem = minMaxEntryList.at( i ).toElement();
    QDomElement minElem = minMaxEntryElem.firstChildElement( "min" );
    if ( minElem.isNull() )
    {
      return;
    }
    minimumValue = minElem.text().toDouble();

    QDomElement maxElem = minMaxEntryElem.firstChildElement( "max" );
    if ( maxElem.isNull() )
    {
      return;
    }
    maximumValue = maxElem.text().toDouble();

    QDomElement newContrastEnhancementElem = doc.createElement( enhancementNameList.at( i ) );
    QDomElement newMinValElem = doc.createElement( "minValue" );
    QDomText minText = doc.createTextNode( QString::number( minimumValue ) );
    newMinValElem.appendChild( minText );
    newContrastEnhancementElem.appendChild( newMinValElem );
    QDomElement newMaxValElem = doc.createElement( "maxValue" );
    QDomText maxText = doc.createTextNode( QString::number( maximumValue ) );
    newMaxValElem.appendChild( maxText );
    newContrastEnhancementElem.appendChild( newMaxValElem );

    QDomElement newAlgorithmElem = doc.createElement( "algorithm" );
    QDomText newAlgorithmText = doc.createTextNode( QString::number( algorithmEnum ) );
    newAlgorithmElem.appendChild( newAlgorithmText );
    newContrastEnhancementElem.appendChild( newAlgorithmElem );

    rendererElem.appendChild( newContrastEnhancementElem );
  }
}
Пример #30
0
void ServerLight::processTicketDataXML(QString data)
{
    BtCompany *emp = (BtCompany *) mainCompany();
    BlDbRecord *rec;
    BtTicket *ticket;
    BtTicket *ticketActual;
    
    fprintf(stdout, "\n==========MENSAJE COMPLETO ===============\n");
    fprintf(stdout, data.toAscii());
    fprintf(stdout, "\n=========================\n");
    
    ticketActual = emp->ticketActual();
  
  
    QString *er = new QString("");
    int *erline;
    int num = 0;
    erline = &num;
  
    QDomDocument doc ( "mydocument" );
    if ( !doc.setContent ( data, true, er, erline ) ) {
      
	//fprintf(stderr, er->toAscii());
	//fprintf(stderr, QString::number(*erline).toAscii());
      
	fprintf(stderr, "Error en documento XML.\n");
        return;
    } // end if


    QDomElement docElem = doc.documentElement();
    QDomElement principal = docElem.firstChildElement ( "TICKET" );
    
    /// Cogemos la coordenada X
    QDomNodeList nodos = principal.elementsByTagName ( "LINEATICKET" );
    
    
    /// Crea un ticket.
    ticket = emp->newBtTicket();
    
    ticket->setDbValue("nomticket", principal.firstChildElement("NOMTICKET").text() );
    ticket->setDbValue("idtrabajador", "1");

	    
    int i = 0;
    while (i < nodos.count() ) {

        QDomNode ventana = nodos.item ( i++ );
		
        QDomElement e1 = ventana.toElement(); /// try to convert the node to an element.
        if ( !e1.isNull() ) { /// the node was really an element.

	    QString idarticulo = e1.firstChildElement("IDARTICULO").text();
	    QString cantarticulo = e1.firstChildElement("CANTARTICULO").text();
	    QString imagen = "";
	    QDomElement modificadores = e1.firstChildElement("MODIFICADORES");
	    if (!modificadores.isNull()) 
	      imagen = modificadores.firstChildElement("IMAGEN").text();
	    
	    
	    /// Inserta lineas.
	    BlDbRecord *linea = ticket->agregarLinea();
	    linea->setDbValue("idarticulo", idarticulo);
	    linea->setDbValue("cantlalbaran", cantarticulo);	    
	    
	    if (imagen != "") {
	      QByteArray bytes1 = QByteArray::fromBase64(imagen.toAscii());
	      QByteArray bytes;
	      QBuffer buffer(&bytes);
	      QImage img;
	      buffer.open(QIODevice::WriteOnly);
	      img.loadFromData(bytes1, "BMP");
	      img.save("/tmp/imagen.bmp","BMP");
	      img.save(&buffer, "PNG");
	      QString text = bytes.toBase64();
	      linea->setDbValue ( "imglalbaran", text );
	    } else {
	      linea->setDbValue ( "imglalbaran", "" );
	    } // end if
	    


	    
	    /// El plugin de IVA incluido tiene que estar instalado.
	    
	    /// Buscamos los parametros en la base de datos.
	    QString query = "SELECT pvparticulo, pvpivaincarticulo, codigocompletoarticulo, nomarticulo, porcentasa_iva FROM articulo LEFT JOIN (SELECT idtipo_iva, porcentasa_iva, fechatasa_iva FROM tasa_iva ) AS t1 ON articulo.idtipo_iva = t1.idtipo_iva WHERE idarticulo = " + idarticulo + " ORDER BY t1.fechatasa_iva LIMIT 1";
  	    
	    BlDbRecordSet *cur = mainCompany() ->loadQuery ( query );

	    if ( !cur->eof() ) {
		linea->setDbValue ( "pvplalbaran", cur->value( "pvparticulo" ) );
		linea->setDbValue ( "pvpivainclalbaran", cur->value( "pvpivaincarticulo" ) );		
		linea->setDbValue ( "codigocompletoarticulo", cur->value( "codigocompletoarticulo" ) );
		linea->setDbValue ( "nomarticulo", cur->value( "nomarticulo" ) );
		linea->setDbValue ( "desclalbaran", cur->value( "nomarticulo" ) );
		linea->setDbValue ( "ivalalbaran", cur->value( "porcentasa_iva") );

	    } // end if
	    delete cur;

        } // end if
    } // end while


    /// Aparca el ticket.
    emp->listaTickets()->prepend(ticket);
    
    /// Hacemos una llamada a plugins para indicar que hay un ticket nuevo y que deben recoger los otros plugins.
    /// En este caso es una llamada extraña pq no se pasa la clase llamante sino que se pasa el ticket generado.
    g_plugins->run("ticket_aparcado_remotamente", ticket);
    
}