示例#1
0
文件: qtrpt.cpp 项目: ant32/QtRPT
void QtRPT::drawField(QDomNode n, int bandTop) {
    //В качестве параметра подается нод бэнда
    QDomNode c = n.firstChild();
    while(!c.isNull()) {
        QDomElement e = c.toElement(); // try to convert the node to an element.
        if ((!e.isNull()) && (e.tagName() == "TContainerField")) {
            if (isFieldVisible(e)) {
                QFont font(e.attribute("fontFamily"),e.attribute("fontSize").toInt());
                font.setBold(processHighligthing(e, FontBold).toInt());
                font.setItalic(processHighligthing(e, FontItalic).toInt());
                font.setUnderline(processHighligthing(e, FontUnderline).toInt());

                painter.setFont(font);
                painter.setPen(Qt::black);

                int left_ = e.attribute("left").toInt()*koefRes_w;
                int top_ = (bandTop+e.attribute("top").toInt())*koefRes_h;
                int width_ = (e.attribute("width").toInt()-1)*koefRes_w;;
                int height_ = e.attribute("height").toInt()*koefRes_h;

                int cor = QFontMetrics(font).height() * koefRes_h;
                QRect textRect(left_, top_-height_, width_, height_);
                textRect.translate(0, cor );

                QPen pen = painter.pen();

                Qt::Alignment al;
                Qt::Alignment alH, alV;
                if (e.attribute("aligmentH") == "hRight")   alH = Qt::AlignRight;
                if (e.attribute("aligmentH") == "hLeft")    alH = Qt::AlignLeft;
                if (e.attribute("aligmentH") == "hCenter")  alH = Qt::AlignHCenter;
                if (e.attribute("aligmentH") == "hJustify") alH = Qt::AlignJustify;
                if (e.attribute("aligmentV") == "vTop")     alV = Qt::AlignTop;
                if (e.attribute("aligmentV") == "vBottom")  alV = Qt::AlignBottom;
                if (e.attribute("aligmentV") == "vCenter")  alV = Qt::AlignVCenter;
                al = alH | alV;

                if ( colorFromString(processHighligthing(e, BgColor).toString() )  != QColor(255,255,255,0))
                    painter.fillRect(left_+1,top_+1,width_-2,height_-2,colorFromString(processHighligthing(e, BgColor).toString()));

                /*if ( colorFromString(e.attribute("backgroundColor")) != QColor(255,255,255,0))
                    painter.fillRect(left_+1,top_+1,width_-2,height_-2,colorFromString(e.attribute("backgroundColor")));*/

                //Set border width
                pen.setWidth(e.attribute("borderWidth","1").replace("px","").toInt()*5);
                //Set border style
                QString borderStyle = e.attribute("borderStyle","solid");
                if (borderStyle == "dashed")
                    pen.setStyle(Qt::DashLine);
                else if (borderStyle == "dotted")
                    pen.setStyle(Qt::DotLine);
                else if (borderStyle == "dot-dash")
                    pen.setStyle(Qt::DashDotLine);
                else if (borderStyle == "dot-dot-dash")
                    pen.setStyle(Qt::DashDotDotLine);
                else
                    pen.setStyle(Qt::SolidLine);

                if ( colorFromString(e.attribute("borderTop")) != QColor(255,255,255,0) ) {
                    pen.setColor(colorFromString(e.attribute("borderTop")));
                    painter.setPen(pen);
                    painter.drawLine(left_, top_, left_ + width_, top_);
                }
                if ( colorFromString(e.attribute("borderBottom")) != QColor(255,255,255,0) ) {
                    pen.setColor(colorFromString(e.attribute("borderBottom")));
                    painter.setPen(pen);
                    painter.drawLine(left_, top_ + height_, left_ + width_, top_ + height_);
                }
                if ( colorFromString(e.attribute("borderLeft")) != QColor(255,255,255,0) ) {
                    pen.setColor(colorFromString(e.attribute("borderLeft")));
                    painter.setPen(pen);
                    painter.drawLine(left_, top_, left_, top_ + height_);
                }
                if ( colorFromString(e.attribute("borderRight")) != QColor(255,255,255,0) ) {
                    pen.setColor(colorFromString(e.attribute("borderRight")));
                    painter.setPen(pen);
                    painter.drawLine(left_ + width_, top_, left_ + width_, top_ + height_);
                }
                if (e.attribute("type","label") == "label") { //NOT Proccess if field set as ImageField
                    QString txt = sectionField(e.attribute("value"),false);
                    //pen.setColor(colorFromString(e.attribute("fontColor")));
                    pen.setColor(colorFromString(processHighligthing(e, FontColor).toString()));

                    painter.setPen(pen);
                    painter.drawText(left_+10,top_,width_-10,height_, al | Qt::TextDontClip | Qt::TextWordWrap, txt);
                }
                if (e.attribute("type","label") == "labelImage") { //Proccess field as ImageField
                    QImage image = sectionFieldImage(e.attribute("value"));
                    if (!image.isNull()) {
                        QRectF target(left_, top_, width_, height_);
                        painter.drawImage(target,image);
                    }
                }
                if (e.attribute("type","label") == "image") {  //Proccess as static ImageField
                    QByteArray byteArray;
                    byteArray = QByteArray::fromBase64(e.attribute("picture","text").toLatin1());
                    QPixmap pixmap = QPixmap::fromImage(QImage::fromData(byteArray, "PNG"));
                    painter.drawPixmap(left_,top_,width_,height_,pixmap);
                }
            }
        }
        c = c.nextSibling();
    }
}
示例#2
0
void XMLPreferences::savePreferences(const QString& filename, 
				     PrefSectionDict& dict)
{
  // open the existing preference file
  QDomDocument doc;
  QFile f(filename);
  bool loaded = false;
  if (f.open(IO_ReadOnly))
  {
    QString errorMsg;
    int errorLine = 0;
    int errorColumn = 0;
    if (doc.setContent(&f, false, &errorMsg, &errorLine, &errorColumn))
      loaded = true;
    else
    {
      qWarning("Error processing file: %s!\n\t %s on line %d in column %d!", 
	       (const char*)filename, 
	       (const char*)errorMsg, errorLine, errorColumn);

    }

    // close the file
    f.close();
  }

  // if no file was loaded, use the template document
  if (!loaded)
  {
    QString errorMsg;
    int errorLine = 0;
    int errorColumn = 0;
    if (doc.setContent(m_templateDoc, false, &errorMsg, &errorLine, &errorColumn))
      loaded = true;
  }

  // if there was an existing file, rename it
  QFileInfo fileInfo(filename);
  if (fileInfo.exists())
  {
    QDir dir(fileInfo.dirPath(true));

    dir.rename(filename, filename + QString(".bak"));
  }

  // do more processing here
  QDomElement docElem = doc.documentElement();
  DomConvenience conv(doc);
  QDomNodeList sectionList, propertyList;
  PreferenceDict* sectionDict;
  QString sectionName;
  QString propertyName;
  QVariant* propertyValue;
  QDomElement e;
  QDomNode n;

  sectionList = docElem.elementsByTagName("section");

  QDictIterator<PreferenceDict> sdit(dict);
  for (; sdit.current(); ++sdit)
  {
    QDomElement section;
    sectionName = sdit.currentKey();
    sectionDict = sdit.current();

    // iterate over all the sections in the document
    for (uint i = 0; i < sectionList.length(); i++)
    {
      e = sectionList.item(i).toElement();
      if (!e.hasAttribute("name"))
      {
	qWarning("section without name!");
	continue;
      }

      //      printf("found section: %s\n", (const char*)section.attribute("name"));

      // is this the section?
      if (sectionName == e.attribute("name"))
      {
	// yes, done
	section = e;
	break;
      }
    }

    // if no section was found, create a new one
    if (section.isNull())
    {
      // create the section element
      section = doc.createElement("section");

      // set the name attribute of the section element
      section.setAttribute("name", sectionName);

      // append the new section to the document
      docElem.appendChild(section);
    }

    // iterate over all the properties in the section
    QDictIterator<QVariant> pdit(*sectionDict);
    for (; pdit.current(); ++pdit)
    {
      QDomElement property;
      propertyName = pdit.currentKey();
      propertyValue = pdit.current();

      // get all the property elements in the section
      propertyList = section.elementsByTagName("property");

      // iterate over all the property elements until a match is found
      for (uint j = 0; j < propertyList.length(); j++)
      {
	e = propertyList.item(j).toElement();
	if (!e.hasAttribute("name"))
	{
	  qWarning("property in section '%s' without name! Ignoring!",
		   (const char*)sectionName);
	  continue;
	}

	// is this the property being searched for?
	if (propertyName == e.attribute("name"))
	{
	  // yes, done
	  property = e;
	  break;
	}
      }

      // if no property was found, create a new one
      if (property.isNull())
      {
	// create the property element
	property = doc.createElement("property");

	// set the name attribute of the property element
	property.setAttribute("name", propertyName);

	// append the new property to the section
	section.appendChild(property);
      }

      QDomElement value;

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

	// don't replace comments
	if (n.toElement().tagName() == "comment")
	  continue;

	// convert it to an element
	value = n.toElement();
	break;
      }

      // if no value element was found, create a new one
      if (value.isNull())
      {
	// create the value element, bogus type, will be filled in later
	value = doc.createElement("bogus");
	
	// append the new value to the property
	property.appendChild(value);
      }

      if (!conv.variantToElement(*propertyValue, value))
      {
	qWarning("Unable to set value element in section '%s' property '%s'!",
		 (const char*)propertyName, (const char*)propertyName);
      }
    }
  }

  // write the modified DOM to disk
  if (!f.open(IO_WriteOnly))
  {
    qWarning("Unable to open file for writing: %s!", 
	     (const char*)filename);
  }

  // open a Text Stream on the file
  QTextStream out(&f);

  // make sure stream is UTF8 encoded
  out.setEncoding(QTextStream::UnicodeUTF8);

  // save the document to the text stream
  QString docText;
  QTextStream docTextStream(&docText, IO_WriteOnly);
  doc.save(docTextStream, 4);

  // put newlines after comments (which unfortunately Qt's DOM doesn't track)
  QRegExp commentEnd("-->");
  docText.replace(commentEnd, "-->\n");

  // write the fixed document out to the file
  out << docText;

  // close the file
  f.close();

  printf("Finished saving preferences to file: %s\n",
	 (const char*)filename);
}
示例#3
0
void ColorSetManager::initialiseDefaultPrefs(struct ApplicationPrefs& appPrefs)
{
	QString pfadC = ScPaths::instance().libDir()+"swatches/";
	QString pfadC2 = pfadC + "Scribus_Basic.xml";
	QFile fiC(pfadC2);
	if (!fiC.exists())
	{
		appPrefs.colorPrefs.DColors.insert("White", ScColor(0, 0, 0, 0));
		appPrefs.colorPrefs.DColors.insert("Black", ScColor(0, 0, 0, 255));
		ScColor cc = ScColor(255, 255, 255, 255);
		cc.setRegistrationColor(true);
		appPrefs.colorPrefs.DColors.insert("Registration", cc);
		appPrefs.colorPrefs.DColors.insert("Blue", ScColor(255, 255, 0, 0));
		appPrefs.colorPrefs.DColors.insert("Cyan", ScColor(255, 0, 0, 0));
		appPrefs.colorPrefs.DColors.insert("Green", ScColor(255, 0, 255, 0));
		appPrefs.colorPrefs.DColors.insert("Red", ScColor(0, 255, 255, 0));
		appPrefs.colorPrefs.DColors.insert("Yellow", ScColor(0, 0, 255, 0));
		appPrefs.colorPrefs.DColors.insert("Magenta", ScColor(0, 255, 0, 0));
		appPrefs.colorPrefs.DColorSet = "Scribus-Small";
	}
	else
	{
		if (fiC.open(QIODevice::ReadOnly))
		{
			QString ColorEn, Cname;
			int Rval, Gval, Bval;
			QTextStream tsC(&fiC);
			ColorEn = tsC.readLine();
			if (ColorEn.startsWith("<?xml version="))
			{
				QByteArray docBytes("");
				loadRawText(pfadC2, docBytes);
				QString docText("");
				docText = QString::fromUtf8(docBytes);
				QDomDocument docu("scridoc");
				docu.setContent(docText);
				ScColor lf = ScColor();
				QDomElement elem = docu.documentElement();
				QDomNode PAGE = elem.firstChild();
				while(!PAGE.isNull())
				{
					QDomElement pg = PAGE.toElement();
					if(pg.tagName()=="COLOR" && pg.attribute("NAME")!=CommonStrings::None)
					{
						if (pg.hasAttribute("CMYK"))
							lf.setNamedColor(pg.attribute("CMYK"));
						else
							lf.fromQColor(QColor(pg.attribute("RGB")));
						if (pg.hasAttribute("Spot"))
							lf.setSpotColor(static_cast<bool>(pg.attribute("Spot").toInt()));
						else
							lf.setSpotColor(false);
						if (pg.hasAttribute("Register"))
							lf.setRegistrationColor(static_cast<bool>(pg.attribute("Register").toInt()));
						else
							lf.setRegistrationColor(false);
						appPrefs.colorPrefs.DColors.insert(pg.attribute("NAME"), lf);
					}
					PAGE=PAGE.nextSibling();
				}
			}
			else
			{
				while (!tsC.atEnd())
				{
					ColorEn = tsC.readLine();
					QTextStream CoE(&ColorEn, QIODevice::ReadOnly);
					CoE >> Rval;
					CoE >> Gval;
					CoE >> Bval;
					CoE >> Cname;
					ScColor tmp;
					tmp.setColorRGB(Rval, Gval, Bval);
					appPrefs.colorPrefs.DColors.insert(Cname, tmp);
				}
			}
			fiC.close();
		}
		appPrefs.colorPrefs.DColorSet = "Scribus Basic";
	}
void QgsManageConnectionsDialog::loadWFSConnections( const QDomDocument &doc, const QStringList &items )
{
  QDomElement root = doc.documentElement();
  if ( root.tagName() != "qgsWFSConnections" )
  {
    QMessageBox::information( this, tr( "Loading connections" ),
                              tr( "The file is not an WFS connections exchange file." ) );
    return;
  }

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

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

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

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

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

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

    if ( !child.attribute( "username" ).isEmpty() )
    {
      settings.beginGroup( "/Qgis/WFS/" + connectionName );
      settings.setValue( "/username", child.attribute( "username" ) );
      settings.setValue( "/password", child.attribute( "password" ) );
      settings.endGroup();
    }
    child = child.nextSiblingElement();
  }
}
示例#5
0
void QXmppDataForm::parse(const QDomElement &element)
{
    if (element.isNull())
        return;

    /* form type */
    const QString typeStr = element.attribute("type");
    if (typeStr == "form")
        m_type = QXmppDataForm::Form;
    else if (typeStr == "submit")
        m_type = QXmppDataForm::Submit;
    else if (typeStr == "cancel")
        m_type = QXmppDataForm::Cancel;
    else if (typeStr == "result")
        m_type = QXmppDataForm::Result;
    else
    {
        qWarning() << "Unknown form type" << typeStr;
        return;
    }

    /* form properties */
    m_title = element.firstChildElement("title").text();
    m_instructions = element.firstChildElement("instructions").text();

    QDomElement fieldElement = element.firstChildElement("field");
    while (!fieldElement.isNull())
    {
        QXmppDataForm::Field field;

        /* field type */
        QXmppDataForm::Field::Type type = QXmppDataForm::Field::TextSingleField;
        const QString typeStr = fieldElement.attribute("type");
        struct field_type *ptr;
        for (ptr = field_types; ptr->str; ptr++)
        {
            if (typeStr == ptr->str)
            {
                type = ptr->type;
                break;
            }
        }
        field.setType(type);

        /* field attributes */
        field.setLabel(fieldElement.attribute("label"));
        field.setKey(fieldElement.attribute("var"));

        /* field value(s) */
        if (type == QXmppDataForm::Field::BooleanField)
        {
            const QString valueStr = fieldElement.firstChildElement("value").text();
            field.setValue(valueStr == "1" || valueStr == "true");
        }
        else if (type == QXmppDataForm::Field::ListMultiField ||
            type == QXmppDataForm::Field::JidMultiField || 
            type == QXmppDataForm::Field::TextMultiField) 
        {
            QStringList values;
            QDomElement valueElement = fieldElement.firstChildElement("value");
            while (!valueElement.isNull())
            {
                values.append(valueElement.text());
                valueElement = valueElement.nextSiblingElement("value");
            }
            field.setValue(values);
        }
        else
        {
            field.setValue(fieldElement.firstChildElement("value").text());
        }

        /* field options */
        if (type == QXmppDataForm::Field::ListMultiField ||
            type == QXmppDataForm::Field::ListSingleField)
        { 
            QList<QPair<QString, QString> > options;
            QDomElement optionElement = fieldElement.firstChildElement("option");
            while (!optionElement.isNull())
            {
                options.append(QPair<QString, QString>(optionElement.attribute("label"),
                    optionElement.firstChildElement("value").text()));
                optionElement = optionElement.nextSiblingElement("option"); 
            }
            field.setOptions(options);
        }

        /* other properties */
        field.setDescription(fieldElement.firstChildElement("description").text());
        field.setRequired(!fieldElement.firstChildElement("required").isNull());

        m_fields.append(field);

        fieldElement = fieldElement.nextSiblingElement("field");
    }
}
示例#6
0
void VCButton_Test::save()
{
    QWidget w;

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

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

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

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

        node = node.nextSibling();
    }

    QCOMPARE(function, 1);
    QCOMPARE(action, 1);
    QCOMPARE(key, 1);
    QCOMPARE(intensity, 1);
    QCOMPARE(wstate, 1);
    QCOMPARE(appearance, 1);
}
示例#7
0
bool QgsComposerTable::tableReadXML( const QDomElement& itemElem, const QDomDocument& doc )
{
  if ( itemElem.isNull() )
  {
    return false;
  }

  if ( !QgsFontUtils::setFromXmlChildNode( mHeaderFont, itemElem, "headerFontProperties" ) )
  {
    mHeaderFont.fromString( itemElem.attribute( "headerFont", "" ) );
  }
  mHeaderFontColor = QgsSymbolLayerV2Utils::decodeColor( itemElem.attribute( "headerFontColor", "0,0,0,255" ) );
  mHeaderHAlignment = QgsComposerTable::HeaderHAlignment( itemElem.attribute( "headerHAlignment", "0" ).toInt() );
  if ( !QgsFontUtils::setFromXmlChildNode( mContentFont, itemElem, "contentFontProperties" ) )
  {
    mContentFont.fromString( itemElem.attribute( "contentFont", "" ) );
  }
  mContentFontColor = QgsSymbolLayerV2Utils::decodeColor( itemElem.attribute( "contentFontColor", "0,0,0,255" ) );
  mLineTextDistance = itemElem.attribute( "lineTextDist", "1.0" ).toDouble();
  mGridStrokeWidth = itemElem.attribute( "gridStrokeWidth", "0.5" ).toDouble();
  mShowGrid = itemElem.attribute( "showGrid", "1" ).toInt();

  //grid color
  if ( itemElem.hasAttribute( "gridColor" ) )
  {
    mGridColor = QgsSymbolLayerV2Utils::decodeColor( itemElem.attribute( "gridColor", "0,0,0,255" ) );
  }
  else
  {
    //old style grid color
    int gridRed = itemElem.attribute( "gridColorRed", "0" ).toInt();
    int gridGreen = itemElem.attribute( "gridColorGreen", "0" ).toInt();
    int gridBlue = itemElem.attribute( "gridColorBlue", "0" ).toInt();
    int gridAlpha = itemElem.attribute( "gridColorAlpha", "255" ).toInt();
    mGridColor = QColor( gridRed, gridGreen, gridBlue, gridAlpha );
  }

  //restore column specifications
  qDeleteAll( mColumns );
  mColumns.clear();
  QDomNodeList columnsList = itemElem.elementsByTagName( "displayColumns" );
  if ( columnsList.size() > 0 )
  {
    QDomElement columnsElem =  columnsList.at( 0 ).toElement();
    QDomNodeList columnEntryList = columnsElem.elementsByTagName( "column" );
    for ( int i = 0; i < columnEntryList.size(); ++i )
    {
      QDomElement columnElem = columnEntryList.at( i ).toElement();
      QgsComposerTableColumn* column = new QgsComposerTableColumn;
      column->readXML( columnElem );
      mColumns.append( column );
    }
  }

  //restore general composer item properties
  QDomNodeList composerItemList = itemElem.elementsByTagName( "ComposerItem" );
  if ( composerItemList.size() > 0 )
  {
    QDomElement composerItemElem = composerItemList.at( 0 ).toElement();
    _readXML( composerItemElem, doc );
  }
  return true;
}
示例#8
0
bool Profile::load(const QString &fileName) {
    QDomDocument doc("renamah_profile");
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly)) {
        qCritical("Cannot open the profile file");
        return false;
    }
    if (!doc.setContent(&file)) {
        qCritical("Error in the XML scheme");
        file.close();
        return false;
    }
    file.close();

    QDomElement rootElem = doc.firstChildElement("profile");
    if (rootElem.isNull()) {
        qCritical("Error in format of the profile file");
        return false;
    }

    FilterModel::instance().clear();

    QDomElement extensionPolicyElem = rootElem.firstChildElement("extension_policy");
    if (!extensionPolicyElem.isNull())
        FilterModel::instance().setExtensionPolicy(loadExtensionPolicy(extensionPolicyElem));

    // Filters
    QDomElement filtersElem = rootElem.firstChildElement("filters");
    if (!filtersElem.isNull()) {
        QDomElement filterElem = filtersElem.firstChildElement("modifier");
        while (!filterElem.isNull()) {
            QString factoryName = filterElem.attribute("factory");
            core::ModifierFactory *factory = FilterManager::instance().factoryByName(factoryName);
            if (factory) {
                core::Modifier *modifier = factory->makeModifier();
                FilterModel::instance().addModifier(modifier);
                FilterModel::instance().setModifierState(modifier, !filterElem.hasAttribute("state") || filterElem.attribute("state").toInt());
                bool exclusive = filterElem.attribute("exclusive").toInt();
                if (exclusive)
                    FilterModel::instance().setExclusiveModifier(modifier);

                // Properties
                QDomElement propElem = filterElem.firstChildElement("properties").firstChildElement("property");
                QMap<QString,QPair<QString,QVariant> > properties;
                while (!propElem.isNull()) {
                    QString name = propElem.attribute("name");
                    QString type = propElem.attribute("type");
                    QVariant value(propElem.attribute("value"));

                    properties.insert(name, QPair<QString,QVariant>(type, value));

                    // To the next prop
                    propElem = propElem.nextSiblingElement("property");
                }
                modifier->deserializeProperties(properties);

                // Extension policy
                QDomElement extensionPolicyElem = filterElem.firstChildElement("extension_policy");
                if (!extensionPolicyElem.isNull()) {
                    FilterModel::instance().setLocalExtensionPolicyEnabled(static_cast<core::Filter*>(modifier), true);
                    FilterModel::instance().setLocalExtensionPolicy(static_cast<core::Filter*>(modifier), loadExtensionPolicy(extensionPolicyElem));
                }
            }

            // To the next modifier
            filterElem = filterElem.nextSiblingElement("modifier");
        }
    }
    return true;
}
示例#9
0
// Sigh. NOT optimal. The only reason that we need to have this
// is so we can create the XMLNodes, if needed.
// would be better if we could create a handler interface that each
// codeblock used so all we have to do here is add the handler
void JavaANTCodeDocument::loadChildTextBlocksFromNode (QDomElement & root)
{
    QDomNode tnode = root.firstChild();
    QDomElement telement = tnode.toElement();
    bool loadCheckForChildrenOK = false;
    while (!telement.isNull()) {
        QString nodeName = telement.tagName();

        if (nodeName == QLatin1String("textblocks")) {

            QDomNode node = telement.firstChild();
            QDomElement element = node.toElement();

            // if there is nothing to begin with, then we don't worry about it
            loadCheckForChildrenOK = element.isNull() ? true : false;

            while (!element.isNull()) {
                QString name = element.tagName();

                if (name == QLatin1String("codecomment")) {
                    CodeComment * block = new XMLCodeComment(this);
                    block->loadFromXMI(element);
                    if (!addTextBlock(block))
                    {
                        uError()<<"Unable to add codeComment to :"<<this;
                        delete block;
                    } else
                        loadCheckForChildrenOK= true;
                } else if (name == QLatin1String("codeaccessormethod") ||
                           name == QLatin1String("ccfdeclarationcodeblock")) {
                    QString acctag = element.attribute(QLatin1String("tag"));
                    // search for our method in the
                    TextBlock * tb = findCodeClassFieldTextBlockByTag(acctag);
                    if (!tb || !addTextBlock(tb)) {
                        uError()<<"Unable to add codeclassfield child method to:"<<this;
                        // DON'T delete
                    } else {
                        loadCheckForChildrenOK= true;
                    }
                } else if (name == QLatin1String("codeblock")) {
                    CodeBlock * block = newCodeBlock();
                    block->loadFromXMI(element);
                    if (!addTextBlock(block)) {
                        uError()<<"Unable to add codeBlock to :"<<this;
                        delete block;
                    } else {
                        loadCheckForChildrenOK= true;
                    }
                } else if (name == QLatin1String("codeblockwithcomments")) {
                    CodeBlockWithComments * block = newCodeBlockWithComments();
                    block->loadFromXMI(element);
                    if (!addTextBlock(block)) {
                        uError()<<"Unable to add codeBlockwithcomments to:"<<this;
                        delete block;
                    } else {
                        loadCheckForChildrenOK= true;
                    }
                } else if (name == QLatin1String("header")) {
                    // do nothing.. this is treated elsewhere
                } else if (name == QLatin1String("hierarchicalcodeblock")) {
                    HierarchicalCodeBlock * block = newHierarchicalCodeBlock();
                    block->loadFromXMI(element);
                    if (!addTextBlock(block)) {
                        uError()<<"Unable to add hierarchicalcodeBlock to:"<<this;
                        delete block;
                    } else {
                        loadCheckForChildrenOK= true;
                    }
                } else if (name == QLatin1String("codeoperation")) {
                    // find the code operation by id
                    QString id = element.attribute(QLatin1String("parent_id"),QLatin1String("-1"));
                    UMLObject * obj = UMLApp::app()->document()->findObjectById(Uml::ID::fromString(id));
                    UMLOperation * op = obj->asUMLOperation();
                    if (op) {
                        CodeOperation * block = 0;
                        uError() << "TODO: implement CodeGenFactory::newCodeOperation() for JavaANTCodeDocument";
                        break;  // remove when above is implemented
                        block->loadFromXMI(element);
                        if (addTextBlock(block)) {
                            loadCheckForChildrenOK= true;
                        } else {
                            uError()<<"Unable to add codeoperation to:"<<this;
                            block->deleteLater();
                        }
                    } else {
                        uError()<<"Unable to find operation create codeoperation for:"<<this;
                    }
                } else if (name == QLatin1String("xmlelementblock")) {
                    QString xmltag = element.attribute(QLatin1String("nodeName"),QLatin1String("UNKNOWN"));
                    XMLElementCodeBlock * block = new XMLElementCodeBlock(this, xmltag);
                    block->loadFromXMI(element);
                    if (!addTextBlock(block)) {
                        uError()<<"Unable to add XMLelement to Java ANT document:"<<this;
                        delete block;
                    } else {
                        loadCheckForChildrenOK= true;
                    }
                } else {
                    uDebug()<<" LoadFromXMI: Got strange tag in text block stack:"<<name<<", ignoring";
                }

                node = element.nextSibling();
                element = node.toElement();
            }
            break;
        }

        tnode = telement.nextSibling();
        telement = tnode.toElement();
    }

    if (!loadCheckForChildrenOK)
    {
        uWarning() << " loadChildBlocks : unable to initialize any child blocks in doc: " << getFileName() << " " << this;
    }

}
示例#10
0
ProgInfo *XMLTVParser::parseProgram(QDomElement &element)
{
    QString uniqueid, season, episode, totalepisodes;
    int dd_progid_done = 0;
    ProgInfo *pginfo = new ProgInfo();

    QString text = element.attribute("start", "");
    fromXMLTVDate(text, pginfo->starttime);
    pginfo->startts = text;

    text = element.attribute("stop", "");
    fromXMLTVDate(text, pginfo->endtime);
    pginfo->endts = text;

    text = element.attribute("channel", "");
    QStringList split = text.split(" ");

    pginfo->channel = split[0];

    text = element.attribute("clumpidx", "");
    if (!text.isEmpty())
    {
        split = text.split('/');
        pginfo->clumpidx = split[0];
        pginfo->clumpmax = split[1];
    }

    for (QDomNode child = element.firstChild(); !child.isNull();
         child = child.nextSibling())
    {
        QDomElement info = child.toElement();
        if (!info.isNull())
        {
            if (info.tagName() == "title")
            {
                if (info.attribute("lang") == "ja_JP")
                {
                    pginfo->title = getFirstText(info);
                }
                else if (info.attribute("lang") == "ja_JP@kana")
                {
                    pginfo->title_pronounce = getFirstText(info);
                }
                else if (pginfo->title.isEmpty())
                {
                    pginfo->title = getFirstText(info);
                }
            }
            else if (info.tagName() == "sub-title" &&
                     pginfo->subtitle.isEmpty())
            {
                pginfo->subtitle = getFirstText(info);
            }
            else if (info.tagName() == "desc" && pginfo->description.isEmpty())
            {
                pginfo->description = getFirstText(info);
            }
            else if (info.tagName() == "category")
            {
                const QString cat = getFirstText(info).toLower();

                if (ProgramInfo::kCategoryNone == pginfo->categoryType &&
                    string_to_myth_category_type(cat) != ProgramInfo::kCategoryNone)
                {
                    pginfo->categoryType = string_to_myth_category_type(cat);
                }
                else if (pginfo->category.isEmpty())
                {
                    pginfo->category = cat;
                }

                if (cat == QObject::tr("movie") || cat == QObject::tr("film"))
                {
                    // Hack for tv_grab_uk_rt
                    pginfo->categoryType = ProgramInfo::kCategoryMovie;
                }
            }
            else if (info.tagName() == "date" && !pginfo->airdate)
            {
                // Movie production year
                QString date = getFirstText(info);
                pginfo->airdate = date.left(4).toUInt();
            }
            else if (info.tagName() == "star-rating" && pginfo->stars.isEmpty())
            {
                QDomNodeList values = info.elementsByTagName("value");
                QDomElement item;
                QString stars, num, den;
                float rating = 0.0;

                // Use the first rating to appear in the xml, this should be
                // the most important one.
                //
                // Averaging is not a good idea here, any subsequent ratings
                // are likely to represent that days recommended programmes
                // which on a bad night could given to an average programme.
                // In the case of uk_rt it's not unknown for a recommendation
                // to be given to programmes which are 'so bad, you have to
                // watch!'
                item = values.item(0).toElement();
                if (!item.isNull())
                {
                    stars = getFirstText(item);
                    num = stars.section('/', 0, 0);
                    den = stars.section('/', 1, 1);
                    if (0.0 < den.toFloat())
                        rating = num.toFloat()/den.toFloat();
                }

                pginfo->stars.setNum(rating);
            }
            else if (info.tagName() == "rating")
            {
                // again, the structure of ratings seems poorly represented
                // in the XML.  no idea what we'd do with multiple values.
                QDomNodeList values = info.elementsByTagName("value");
                QDomElement item = values.item(0).toElement();
                if (item.isNull())
                    continue;
                EventRating rating;
                rating.system = info.attribute("system", "");
                rating.rating = getFirstText(item);
                pginfo->ratings.append(rating);
            }
            else if (info.tagName() == "previously-shown")
            {
                pginfo->previouslyshown = true;

                QString prevdate = info.attribute("start");
                if (!prevdate.isEmpty())
                {
                    QDateTime date;
                    fromXMLTVDate(prevdate, date);
                    pginfo->originalairdate = date.date();
                }
            }
            else if (info.tagName() == "credits")
            {
                parseCredits(info, pginfo);
            }
            else if (info.tagName() == "subtitles")
            {
                if (info.attribute("type") == "teletext")
                    pginfo->subtitleType |= SUB_NORMAL;
                else if (info.attribute("type") == "onscreen")
                    pginfo->subtitleType |= SUB_ONSCREEN;
                else if (info.attribute("type") == "deaf-signed")
                    pginfo->subtitleType |= SUB_SIGNED;
            }
            else if (info.tagName() == "audio")
            {
                parseAudio(info, pginfo);
            }
            else if (info.tagName() == "video")
            {
                parseVideo(info, pginfo);
            }
            else if (info.tagName() == "episode-num")
            {
                if (info.attribute("system") == "dd_progid")
                {
                    QString episodenum(getFirstText(info));
                    // if this field includes a dot, strip it out
                    int idx = episodenum.indexOf('.');
                    if (idx != -1)
                        episodenum.remove(idx, 1);
                    pginfo->programId = episodenum;
                    dd_progid_done = 1;
                }
                else if (info.attribute("system") == "xmltv_ns")
                {
                    int tmp;
                    QString episodenum(getFirstText(info));
                    episode = episodenum.section('.',1,1);
                    totalepisodes = episode.section('/',1,1).trimmed();
                    episode = episode.section('/',0,0).trimmed();
                    season = episodenum.section('.',0,0).trimmed();
                    QString part(episodenum.section('.',2,2));
                    QString partnumber(part.section('/',0,0).trimmed());
                    QString parttotal(part.section('/',1,1).trimmed());

                    pginfo->categoryType = ProgramInfo::kCategorySeries;

                    if (!season.isEmpty())
                    {
                        tmp = season.toUInt() + 1;
                        pginfo->season = tmp;
                        season = QString::number(tmp);
                        pginfo->syndicatedepisodenumber = QString('S' + season);
                    }

                    if (!episode.isEmpty())
                    {
                        tmp = episode.toUInt() + 1;
                        pginfo->episode = tmp;
                        episode = QString::number(tmp);
                        pginfo->syndicatedepisodenumber.append(QString('E' + episode));
                    }

                    if (!totalepisodes.isEmpty())
                    {
                        pginfo->totalepisodes = totalepisodes.toUInt();
                    }

                    uint partno = 0;
                    if (!partnumber.isEmpty())
                    {
                        bool ok;
                        partno = partnumber.toUInt(&ok) + 1;
                        partno = (ok) ? partno : 0;
                    }

                    if (!parttotal.isEmpty() && partno > 0)
                    {
                        bool ok;
                        uint partto = parttotal.toUInt(&ok);
                        if (ok && partnumber <= parttotal)
                        {
                            pginfo->parttotal  = partto;
                            pginfo->partnumber = partno;
                        }
                    }
                }
                else if (info.attribute("system") == "onscreen")
                {
                    pginfo->categoryType = ProgramInfo::kCategorySeries;
                    if (pginfo->subtitle.isEmpty())
                    {
                        pginfo->subtitle = getFirstText(info);
                    }
                }
                else if ((info.attribute("system") == "themoviedb.org") &&
                    (MetadataDownload::GetMovieGrabber().endsWith(QString("/tmdb3.py"))))
                {
                    /* text is movie/<inetref> */
                    QString inetrefRaw(getFirstText(info));
                    if (inetrefRaw.startsWith(QString("movie/"))) {
                        QString inetref(QString ("tmdb3.py_") + inetrefRaw.section('/',1,1).trimmed());
                        pginfo->inetref = inetref;
                    }
                }
                else if ((info.attribute("system") == "thetvdb.com") &&
                    (MetadataDownload::GetTelevisionGrabber().endsWith(QString("/ttvdb.py"))))
                {
                    /* text is series/<inetref> */
                    QString inetrefRaw(getFirstText(info));
                    if (inetrefRaw.startsWith(QString("series/"))) {
                        QString inetref(QString ("ttvdb.py_") + inetrefRaw.section('/',1,1).trimmed());
                        pginfo->inetref = inetref;
                        /* ProgInfo does not have a collectionref, so we don't set any */
                    }
                }
            }
        }
    }

    if (pginfo->category.isEmpty() &&
        pginfo->categoryType != ProgramInfo::kCategoryNone)
        pginfo->category = myth_category_type_to_string(pginfo->categoryType);

    if (!pginfo->airdate)
        pginfo->airdate = current_year;

    /* Let's build ourself a programid */
    QString programid;

    if (ProgramInfo::kCategoryMovie == pginfo->categoryType)
        programid = "MV";
    else if (ProgramInfo::kCategorySeries == pginfo->categoryType)
        programid = "EP";
    else if (ProgramInfo::kCategorySports == pginfo->categoryType)
        programid = "SP";
    else
        programid = "SH";

    if (!uniqueid.isEmpty()) // we already have a unique id ready for use
        programid.append(uniqueid);
    else
    {
        QString seriesid = QString::number(ELFHash(pginfo->title.toUtf8()));
        pginfo->seriesId = seriesid;
        programid.append(seriesid);

        if (!episode.isEmpty() && !season.isEmpty())
        {
            /* Append unpadded episode and season number to the seriesid (to
               maintain consistency with historical encoding), but limit the
               season number representation to a single base-36 character to
               ensure unique programid generation. */
            int season_int = season.toInt();
            if (season_int > 35)
            {
                // Cannot represent season as a single base-36 character, so
                // remove the programid and fall back to normal dup matching.
                if (ProgramInfo::kCategoryMovie != pginfo->categoryType)
                    programid.clear();
            }
            else
            {
                programid.append(episode);
                programid.append(QString::number(season_int, 36));
                if (pginfo->partnumber && pginfo->parttotal)
                {
                    programid += QString::number(pginfo->partnumber);
                    programid += QString::number(pginfo->parttotal);
                }
            }
        }
        else
        {
            /* No ep/season info? Well then remove the programid and rely on
               normal dupchecking methods instead. */
            if (ProgramInfo::kCategoryMovie != pginfo->categoryType)
                programid.clear();
        }
    }
    if (dd_progid_done == 0)
        pginfo->programId = programid;

    return pginfo;
}
示例#11
0
bool XMLTVParser::parseFile(
    QString filename, ChannelInfoList *chanlist,
    QMap<QString, QList<ProgInfo> > *proglist)
{
    QDomDocument doc;
    QFile f;

    if (!dash_open(f, filename, QIODevice::ReadOnly))
    {
        LOG(VB_GENERAL, LOG_ERR,
            QString("Error unable to open '%1' for reading.") .arg(filename));
        return false;
    }

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

    if (!doc.setContent(&f, &errorMsg, &errorLine, &errorColumn))
    {
        LOG(VB_GENERAL, LOG_ERR, QString("Error in %1:%2: %3")
            .arg(errorLine).arg(errorColumn).arg(errorMsg));

        f.close();
        return true;
    }

    f.close();

    QDomElement docElem = doc.documentElement();

    QUrl baseUrl(docElem.attribute("source-data-url", ""));
    //QUrl sourceUrl(docElem.attribute("source-info-url", ""));

    QString aggregatedTitle;
    QString aggregatedDesc;

    QDomNode n = docElem.firstChild();
    while (!n.isNull())
    {
        QDomElement e = n.toElement();
        if (!e.isNull())
        {
            if (e.tagName() == "channel")
            {
                ChannelInfo *chinfo = parseChannel(e, baseUrl);
                if (!chinfo->xmltvid.isEmpty())
                    chanlist->push_back(*chinfo);
                delete chinfo;
            }
            else if (e.tagName() == "programme")
            {
                ProgInfo *pginfo = parseProgram(e);

                if (pginfo->startts == pginfo->endts)
                {
                    LOG(VB_GENERAL, LOG_WARNING, QString("Invalid programme (%1), "
                                                        "identical start and end "
                                                        "times, skipping")
                                                        .arg(pginfo->title));
                }
                else
                {
                    if (pginfo->clumpidx.isEmpty())
                        (*proglist)[pginfo->channel].push_back(*pginfo);
                    else
                    {
                        /* append all titles/descriptions from one clump */
                        if (pginfo->clumpidx.toInt() == 0)
                        {
                            aggregatedTitle.clear();
                            aggregatedDesc.clear();
                        }

                        if (!pginfo->title.isEmpty())
                        {
                            if (!aggregatedTitle.isEmpty())
                                aggregatedTitle.append(" | ");
                            aggregatedTitle.append(pginfo->title);
                        }

                        if (!pginfo->description.isEmpty())
                        {
                            if (!aggregatedDesc.isEmpty())
                                aggregatedDesc.append(" | ");
                            aggregatedDesc.append(pginfo->description);
                        }
                        if (pginfo->clumpidx.toInt() ==
                            pginfo->clumpmax.toInt() - 1)
                        {
                            pginfo->title = aggregatedTitle;
                            pginfo->description = aggregatedDesc;
                            (*proglist)[pginfo->channel].push_back(*pginfo);
                        }
                    }
                }
                delete pginfo;
            }
        }
        n = n.nextSibling();
    }

    return true;
}
void QgsConfigureShortcutsDialog::loadShortcuts()
{
  QString fileName = QFileDialog::getOpenFileName( this, tr( "Load shortcuts" ), ".", tr( "XML file (*.xml);; All files (*)" ) );

  if ( fileName.isEmpty() )
  {
    return;
  }

  QFile file( fileName );
  if ( !file.open( QIODevice::ReadOnly | QIODevice::Text ) )
  {
    QMessageBox::warning( this, tr( "Loading shortcuts" ),
                          tr( "Cannot read file %1:\n%2." )
                          .arg( fileName )
                          .arg( file.errorString() ) );
    return;
  }

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

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

  QDomElement root = doc.documentElement();
  if ( root.tagName() != "qgsshortcuts" )
  {
    QMessageBox::information( this, tr( "Loading shortcuts" ),
                              tr( "The file is not an shortcuts exchange file." ) );
    return;
  }

  QSettings settings;
  QString currentLocale;

  bool localeOverrideFlag = settings.value( "locale/overrideFlag", false ).toBool();
  if ( localeOverrideFlag )
  {
    currentLocale = settings.value( "locale/userLocale", "en_US" ).toString();
  }
  else // use QGIS locale
  {
    currentLocale = QLocale::system().name();
  }

  if ( root.attribute( "locale" ) != currentLocale )
  {
    QMessageBox::information( this, tr( "Loading shortcuts" ),
                              tr( "The file contains shortcuts created with different locale, so you can't use it." ) );
    return;
  }

  QAction* action;
  QString actionName;
  QString actionShortcut;

  QDomElement child = root.firstChildElement();
  while ( !child.isNull() )
  {
    actionName = child.attribute( "name" );
    actionShortcut = child.attribute( "shortcut" );
    action = QgsShortcutsManager::instance()->actionByName( actionName );
    QgsShortcutsManager::instance()->setActionShortcut( action, actionShortcut );
    child = child.nextSiblingElement();
  }

  treeActions->clear();
  populateActions();
}
示例#13
0
void MessageTreeWidget::importSms()
{
	QString filename = QFileDialog::getOpenFileName(NULL, "Open File",".","Sms (*.xml)");
	if(!filename.isEmpty())
	{
		QFile file1(strMessagePathOpen);
		QFile file2(filename);
		QFile file3(strMessagePathOpen);
		if (!file1.open(QIODevice::ReadOnly)) return ;
		if (!file2.open(QIODevice::ReadOnly)) return ;
		QDomDocument doc1;//文档1
		QDomDocument doc2;//文档2
		if (!doc1.setContent(&file1))
		{
			file1.close();
			return;
		}
		if (!doc2.setContent(&file2))
		{
			file2.close();
			return ;
		}
		QDomElement docElem1 = doc1.documentElement();
		QDomElement docElem2 = doc2.documentElement();
		
		QDomNodeList list1 = doc1.elementsByTagName("SmsSum");
		//以标签名进行查找
		QDomElement firstElement;
		for(int i=0; i<list1.count(); i++)
		{
			QDomElement e = list1.at(i).toElement();
			
			QString str= e.attribute("term");
			if(str.compare("信息")==0)
			{  
				firstElement = e;
				break;
			}
		}
		
		QDomNodeList list = doc2.elementsByTagName("Sms");
		//以标签名进行查找
		for(int j=0; j< list.count(); j++)
		{
			QDomElement e = list.at(j).toElement();
			QDomElement tmp = e.cloneNode(true).toElement();
			QString strContent = tmp.text();
			bool key = keydetect(strContent);
			if(!key)
				firstElement.appendChild(tmp);//加入以后list 内已经删除了
		}		
		if(!file3.open(QIODevice::WriteOnly | QIODevice::Truncate)) return ;
			QTextStream out(&file3);
		doc1.save(out,4);   //将文档保存到文件,4为子元素缩进字符数
		file3.close();
		emit updateTreeAllItem();
		QMessageBox *message=new QMessageBox(QMessageBox::NoIcon, "导入短信", "导入成功"); 
		message->show();
		
	}
}
示例#14
0
/**
 * This method loads the generic parts of the XMI common to most model
 * classes.  It is not usually reimplemented by child classes.
 * Instead, it invokes the load() method which implements the loading
 * of the specifics of each child class.
 *
 * @param element   The QDomElement from which to load.
 */
bool UMLObject::loadFromXMI(QDomElement & element)
{
    UMLDoc* umldoc = UMLApp::app()->document();
    if (umldoc == 0) {
        uError() << "umldoc is NULL";
        return false;
    }
    // Read the name first so that if we encounter a problem, the error
    // message can say the name.
    m_name = element.attribute("name", "");
    QString id = element.attribute("xmi.id", "");
    if (id.isEmpty() || id == "-1") {
        if (m_BaseType == ot_Role) {
            // Before version 1.4, Umbrello did not save the xmi.id
            // of UMLRole objects.
            m_nId = UniqueID::gen();
        } else {
            uError() << m_name << ": nonexistent or illegal xmi.id";
            return false;
        }
    } else {
        Uml::IDType nId = STR2ID(id);
        if (m_BaseType == ot_Role) {
            // Some older Umbrello versions had a problem with xmi.id's
            // of other objects being reused for the UMLRole, see e.g.
            // attachment 21179 at http://bugs.kde.org/147988 .
            // If the xmi.id is already being used then we generate a new one.
            UMLObject *o = umldoc->findObjectById(nId);
            if (o) {
                uError() << "loadFromXMI(UMLRole): id " << id
                         << " is already in use!!! Please fix your XMI file.";
            }
        }
        m_nId = nId;
    }

    if (element.hasAttribute("documentation"))  // for bkwd compat.
        m_Doc = element.attribute("documentation", "");
    else
        m_Doc = element.attribute("comment", "");    //CHECK: need a UML:Comment?

    m_Vis = Uml::Visibility::Public;
    if (element.hasAttribute("scope")) {        // for bkwd compat.
        QString scope = element.attribute("scope", "");
        if (scope == "instance_level")         // nsuml compat.
            m_bStatic = false;
        else if (scope == "classifier_level")  // nsuml compat.
            m_bStatic = true;
        else {
            int nScope = scope.toInt();
            switch (nScope) {
            case 200:
                m_Vis = Uml::Visibility::Public;
                break;
            case 201:
                m_Vis = Uml::Visibility::Private;
                break;
            case 202:
                m_Vis = Uml::Visibility::Protected;
                break;
            default:
                uError() << m_name << ": illegal scope " << nScope;
            }
        }
    } else {
        QString visibility = element.attribute("visibility", "public");
        if (visibility == "private"
                || visibility == "private_vis")    // for compatibility with other programs
            m_Vis = Uml::Visibility::Private;
        else if (visibility == "protected"
                 || visibility == "protected_vis")  // for compatibility with other programs
            m_Vis = Uml::Visibility::Protected;
        else if (visibility == "implementation")
            m_Vis = Uml::Visibility::Implementation;
    }

    QString stereo = element.attribute("stereotype", "");
    if (!stereo.isEmpty()) {
        Uml::IDType stereoID = STR2ID(stereo);
        m_pStereotype = umldoc->findStereotypeById(stereoID);
        if (m_pStereotype) {
            m_pStereotype->incrRefCount();
        } else {
            uDebug() << m_name << ": UMLStereotype " << ID2STR(stereoID)
                     << " not found, creating now.";
            setStereotype(stereo);
        }
    }

    if (element.hasAttribute("abstract")) {      // for bkwd compat.
        QString abstract = element.attribute("abstract", "0");
        m_bAbstract = (bool)abstract.toInt();
    } else {
        QString isAbstract = element.attribute("isAbstract", "false");
        m_bAbstract = (isAbstract == "true");
    }

    if (element.hasAttribute("static")) {        // for bkwd compat.
        QString staticScope = element.attribute("static", "0");
        m_bStatic = (bool)staticScope.toInt();
    } else {
        QString ownerScope = element.attribute("ownerScope", "instance");
        m_bStatic = (ownerScope == "classifier");
    }

    // If the node has child nodes, check whether attributes can be
    // extracted from them.
    if (element.hasChildNodes()) {
        QDomNode node = element.firstChild();
        if (node.isComment())
            node = node.nextSibling();
        QDomElement elem = node.toElement();
        while (!elem.isNull()) {
            QString tag = elem.tagName();
            if (UMLDoc::tagEq(tag, "name")) {
                m_name = elem.attribute("xmi.value", "");
                if (m_name.isEmpty())
                    m_name = elem.text();
            } else if (UMLDoc::tagEq(tag, "visibility")) {
                QString vis = elem.attribute("xmi.value", "");
                if (vis.isEmpty())
                    vis = elem.text();
                if (vis == "private" || vis == "private_vis")
                    m_Vis = Uml::Visibility::Private;
                else if (vis == "protected" || vis == "protected_vis")
                    m_Vis = Uml::Visibility::Protected;
                else if (vis == "implementation")
                    m_Vis = Uml::Visibility::Implementation;
            } else if (UMLDoc::tagEq(tag, "isAbstract")) {
                QString isAbstract = elem.attribute("xmi.value", "");
                if (isAbstract.isEmpty())
                    isAbstract = elem.text();
                m_bAbstract = (isAbstract == "true");
            } else if (UMLDoc::tagEq(tag, "ownerScope")) {
                QString ownerScope = elem.attribute("xmi.value", "");
                if (ownerScope.isEmpty())
                    ownerScope = elem.text();
                m_bStatic = (ownerScope == "classifier");
            } else {
                loadStereotype(elem);
            }
            node = node.nextSibling();
            if (node.isComment())
                node = node.nextSibling();
            elem = node.toElement();
        }
    }

    // Operations, attributes, enum literals, templates, stereotypes,
    // and association role objects get added and signaled elsewhere.
    if (m_BaseType != ot_Operation && m_BaseType != ot_Attribute &&
        m_BaseType != ot_EnumLiteral && m_BaseType != ot_EntityAttribute &&
        m_BaseType != ot_Template && m_BaseType != ot_Stereotype &&
        m_BaseType != ot_Role && m_BaseType != ot_UniqueConstraint &&
        m_BaseType != ot_ForeignKeyConstraint) {
        if (m_bInPaste) {
            m_pUMLPackage = Model_Utils::treeViewGetPackageFromCurrent();
        }
        if (m_pUMLPackage) {
            m_pUMLPackage->addObject(this);
        } else if (umldoc->rootFolderType(this) == Uml::ModelType::N_MODELTYPES) {
            // m_pUMLPackage is not set on the root folders.
            uDebug() << m_name << ": m_pUMLPackage is not set";
        }
    }
    return load(element);
}
示例#15
0
ViewGeometry::ViewGeometry(QDomElement & geometry) {
	m_wireFlags = (WireFlags) geometry.attribute("wireFlags").toInt();
	m_z = geometry.attribute("z").toDouble();
	m_loc.setX(geometry.attribute("x").toDouble());
	m_loc.setY(geometry.attribute("y").toDouble());
	QString x1 = geometry.attribute("x1");
	if (!x1.isEmpty()) {
		m_line.setLine( geometry.attribute("x1").toDouble(),
						geometry.attribute("y1").toDouble(),
						geometry.attribute("x2").toDouble(),
						geometry.attribute("y2").toDouble() );
	}
	QString w = geometry.attribute("width");
	if (!w.isEmpty()) {
		m_rect.setX(geometry.attribute("x").toDouble());
		m_rect.setY(geometry.attribute("y").toDouble());
		m_rect.setWidth(geometry.attribute("width").toDouble());
		m_rect.setHeight(geometry.attribute("height").toDouble());
	}

	GraphicsUtils::loadTransform(geometry.firstChildElement("transform"), m_transform);
}
示例#16
0
	void ThymioVisualProgramming::loadFromDom(const QDomDocument& document, bool fromFile) 
	{
		scene->clear();

		QDomNode domNode = document.documentElement().firstChild();

		while (!domNode.isNull())
		{
			if (domNode.isElement())
			{
				QDomElement element = domNode.toElement();
				if (element.tagName() == "settings") 
				{
					if( element.attribute("advanced-mode") == "true" )
						advancedMode();
					else
					{
						advancedButton->setEnabled(true);
						actionButtons.last()->hide(); // state button
						scene->setAdvanced(false);
					}
					
					colorComboButton->setCurrentIndex(element.attribute("color-scheme").toInt());
				}
				else if(element.tagName() == "buttonset")
				{
					QString buttonName;
					ThymioButton *eventButton = 0;
					ThymioButton *actionButton = 0;
					
					if( !(buttonName = element.attribute("event-name")).isEmpty() )
					{
						
						if ( buttonName == "button" )
							eventButton = new ThymioButtonsEvent(0,scene->getAdvanced());
						else if ( buttonName == "prox" )
							eventButton = new ThymioProxEvent(0,scene->getAdvanced());
						else if ( buttonName == "proxground" )
							eventButton = new ThymioProxGroundEvent(0,scene->getAdvanced());
						else if ( buttonName == "tap" )
						{					
							eventButton = new ThymioTapEvent(0,scene->getAdvanced());
							eventButton->setSharedRenderer(tapSvg);
						}
						else if ( buttonName == "clap" )
						{
							eventButton = new ThymioClapEvent(0,scene->getAdvanced());
							eventButton->setSharedRenderer(clapSvg);
						}
						else
						{
							QMessageBox::warning(this,tr("Loading"),
												 tr("Error in XML source file: %0 unknown event type").arg(buttonName));
							return;
						}

						for(int i=0; i<eventButton->getNumButtons(); ++i)
							eventButton->setClicked(i,element.attribute(QString("eb%0").arg(i)).toInt());

						eventButton->setState(element.attribute("state").toInt());
					}
					
					if( !(buttonName = element.attribute("action-name")).isEmpty() )
					{
						if ( buttonName == "move" )
							actionButton = new ThymioMoveAction();
						else if ( buttonName == "color" )
							actionButton = new ThymioColorAction();
						else if ( buttonName == "circle" )
							actionButton = new ThymioCircleAction();
						else if ( buttonName == "sound" )
							actionButton = new ThymioSoundAction();
						else if ( buttonName == "memory" )
							actionButton = new ThymioMemoryAction();
						else
						{
							QMessageBox::warning(this,tr("Loading"),
												 tr("Error in XML source file: %0 unknown event type").arg(buttonName));
							return;
						}

						for(int i=0; i<actionButton->getNumButtons(); ++i)
							actionButton->setClicked(i,element.attribute(QString("ab%0").arg(i)).toInt());
					}

					scene->addButtonSet(eventButton, actionButton);
				}
			}
			domNode = domNode.nextSibling();
		}
		
		scene->setModified(!fromFile);
		
		if (!scene->isEmpty())
			QTimer::singleShot(0, this, SLOT(exec()));
	}
示例#17
0
bool Function::loader(const QDomElement& root, Doc* doc)
{
    if (root.tagName() != KXMLQLCFunction)
    {
        qWarning("Function node not found!");
        return false;
    }

    /* Get common information from the tag's attributes */
    quint32 id = root.attribute(KXMLQLCFunctionID).toUInt();
    QString name = root.attribute(KXMLQLCFunctionName);
    Type type = Function::stringToType(root.attribute(KXMLQLCFunctionType));
    QString path;
    if (root.hasAttribute(KXMLQLCFunctionPath))
        path = root.attribute(KXMLQLCFunctionPath);

    /* Check for ID validity before creating the function */
    if (id == Function::invalidId())
    {
        qWarning() << Q_FUNC_INFO << "Function ID" << id << "is not allowed.";
        return false;
    }

    /* Create a new function according to the type */
    Function* function = NULL;
    if (type == Function::Scene)
        function = new class Scene(doc);
    else if (type == Function::Chaser)
        function = new class Chaser(doc);
    else if (type == Function::Collection)
        function = new class Collection(doc);
    else if (type == Function::EFX)
        function = new class EFX(doc);
    else if (type == Function::Script)
        function = new class Script(doc);
    else if (type == Function::RGBMatrix)
        function = new class RGBMatrix(doc);
    else if (type == Function::Show)
        function = new class Show(doc);
    else if (type == Function::Audio)
        function = new class Audio(doc);
    else
        return false;

    function->setName(name);
    function->setPath(path);
    if (function->loadXML(root) == true)
    {
        if (doc->addFunction(function, id) == true)
        {
            /* Success */
            return true;
        }
        else
        {
            qWarning() << "Function" << name << "cannot be created.";
            delete function;
            return false;
        }
    }
    else
    {
        qWarning() << "Function" << name << "cannot be loaded.";
        delete function;
        return false;
    }
}
示例#18
0
void QgsLabel::readXML( const QDomNode& node )
{
  QgsDebugMsg( " called for layer label properties, got node " + node.nodeName() );

  QDomNode scratchNode;       // Dom node re-used to get current QgsLabel attribute
  QDomElement el;

  int red, green, blue;
  int type;

  /* Text */
  scratchNode = node.namedItem( "label" );

  if ( scratchNode.isNull() )
  {
    QgsDebugMsg( "couldn't find QgsLabel ``label'' attribute" );
  }
  else
  {
    el = scratchNode.toElement();
    mLabelAttributes->setText( el.attribute( "text", "" ) );
    readLabelField( el, Text );
  }

  /* Family */
  scratchNode = node.namedItem( "family" );

  if ( scratchNode.isNull() )
  {
    QgsDebugMsg( "couldn't find QgsLabel ``family'' attribute" );
  }
  else
  {
    el = scratchNode.toElement();
    mLabelAttributes->setFamily( el.attribute( "name", "" ) );
    readLabelField( el, Family );
  }

  /* Size */
  scratchNode = node.namedItem( "size" );

  if ( scratchNode.isNull() )
  {
    QgsDebugMsg( "couldn't find QgsLabel ``size'' attribute" );
  }
  else
  {
    el = scratchNode.toElement();
    if ( !el.hasAttribute( "unitfield" ) && !el.hasAttribute( "unitfieldname" ) )
    {
      type = QgsLabelAttributes::unitsCode( el.attribute( "units", "" ) );
      mLabelAttributes->setSize( el.attribute( "value", "0.0" ).toDouble(), type );
    }
    else
    {
      readLabelField( el, SizeType, "unitfield" );
    }
    readLabelField( el, Size );
  }

  /* Bold */
  scratchNode = node.namedItem( "bold" );

  if ( scratchNode.isNull() )
  {
    QgsDebugMsg( "couldn't find QgsLabel ``bold'' attribute" );
  }
  else
  {
    el = scratchNode.toElement();
    mLabelAttributes->setBold(( bool )el.attribute( "on", "0" ).toInt() );
    readLabelField( el, Bold );
  }

  /* Italic */
  scratchNode = node.namedItem( "italic" );

  if ( scratchNode.isNull() )
  {
    QgsDebugMsg( "couldn't find QgsLabel ``italic'' attribute" );
  }
  else
  {
    el = scratchNode.toElement();
    mLabelAttributes->setItalic(( bool )el.attribute( "on", "0" ).toInt() );
    readLabelField( el, Italic );
  }

  /* Underline */
  scratchNode = node.namedItem( "underline" );

  if ( scratchNode.isNull() )
  {
    QgsDebugMsg( "couldn't find QgsLabel ``underline'' attribute" );
  }
  else
  {
    el = scratchNode.toElement();
    mLabelAttributes->setUnderline(( bool )el.attribute( "on", "0" ).toInt() );
    readLabelField( el, Underline );
  }

  /* Strikeout */
  scratchNode = node.namedItem( "strikeout" );

  if ( scratchNode.isNull() )
  {
    QgsDebugMsg( "couldn't find QgsLabel ``strikeout'' attribute" );
  }
  else
  {
    el = scratchNode.toElement();
    mLabelAttributes->setStrikeOut(( bool )el.attribute( "on", "0" ).toInt() );
    readLabelField( el, StrikeOut );
  }

  /* Color */
  scratchNode = node.namedItem( "color" );

  if ( scratchNode.isNull() )
  {
    QgsDebugMsg( "couldn't find QgsLabel ``color'' attribute" );
  }
  else
  {
    el = scratchNode.toElement();

    red = el.attribute( "red", "0" ).toInt();
    green = el.attribute( "green", "0" ).toInt();
    blue = el.attribute( "blue", "0" ).toInt();

    mLabelAttributes->setColor( QColor( red, green, blue ) );

    readLabelField( el, Color );
  }

  /* X */
  scratchNode = node.namedItem( "x" );

  if ( scratchNode.isNull() )
  {
    QgsDebugMsg( "couldn't find QgsLabel ``x'' attribute" );
  }
  else
  {
    el = scratchNode.toElement();
    readLabelField( el, XCoordinate );
  }

  /* Y */
  scratchNode = node.namedItem( "y" );

  if ( scratchNode.isNull() )
  {
    QgsDebugMsg( "couldn't find QgsLabel ``y'' attribute" );
  }
  else
  {
    el = scratchNode.toElement();
    readLabelField( el, YCoordinate );
  }


  /* X,Y offset */
  scratchNode = node.namedItem( "offset" );

  if ( scratchNode.isNull() )
  {
    QgsDebugMsg( "couldn't find QgsLabel ``offset'' attribute" );
  }
  else
  {
    double xoffset, yoffset;

    el = scratchNode.toElement();

    type = QgsLabelAttributes::unitsCode( el.attribute( "units", "" ) );
    xoffset = el.attribute( "x", "0.0" ).toDouble();
    yoffset = el.attribute( "y", "0.0" ).toDouble();

    mLabelAttributes->setOffset( xoffset, yoffset, type );
    readLabelField( el, XOffset, "xfield" );
    readLabelField( el, YOffset, "yfield" );
  }

  /* Angle */
  scratchNode = node.namedItem( "angle" );

  if ( scratchNode.isNull() )
  {
    QgsDebugMsg( "couldn't find QgsLabel ``angle'' attribute" );
  }
  else
  {
    el = scratchNode.toElement();
    mLabelAttributes->setAngle( el.attribute( "value", "0.0" ).toDouble() );
    readLabelField( el, Angle );
    mLabelAttributes->setAutoAngle( el.attribute( "auto", "0" ) == "1" );
  }

  /* Alignment */
  scratchNode = node.namedItem( "alignment" );

  if ( scratchNode.isNull() )
  {
    QgsDebugMsg( "couldn't find QgsLabel ``alignment'' attribute" );
  }
  else
  {
    el = scratchNode.toElement();
    mLabelAttributes->setAlignment( QgsLabelAttributes::alignmentCode( el.attribute( "value", "" ) ) );
    readLabelField( el, Alignment );
  }


  // Buffer
  scratchNode = node.namedItem( "buffercolor" );

  if ( scratchNode.isNull() )
  {
    QgsDebugMsg( "couldn't find QgsLabel ``buffercolor'' attribute" );
  }
  else
  {
    el = scratchNode.toElement();

    red = el.attribute( "red", "0" ).toInt();
    green = el.attribute( "green", "0" ).toInt();
    blue = el.attribute( "blue", "0" ).toInt();

    mLabelAttributes->setBufferColor( QColor( red, green, blue ) );
    readLabelField( el, BufferColor );
  }

  scratchNode = node.namedItem( "buffersize" );

  if ( scratchNode.isNull() )
  {
    QgsDebugMsg( "couldn't find QgsLabel ``bffersize'' attribute" );
  }
  else
  {
    el = scratchNode.toElement();

    type = QgsLabelAttributes::unitsCode( el.attribute( "units", "" ) );
    mLabelAttributes->setBufferSize( el.attribute( "value", "0.0" ).toDouble(), type );
    readLabelField( el, BufferSize );
  }

  scratchNode = node.namedItem( "bufferenabled" );

  if ( scratchNode.isNull() )
  {
    QgsDebugMsg( "couldn't find QgsLabel ``bufferenabled'' attribute" );
  }
  else
  {
    el = scratchNode.toElement();

    mLabelAttributes->setBufferEnabled(( bool )el.attribute( "on", "0" ).toInt() );
    readLabelField( el, BufferEnabled );
  }

  scratchNode = node.namedItem( "multilineenabled" );

  if ( scratchNode.isNull() )
  {
    QgsDebugMsg( "couldn't find QgsLabel ``multilineenabled'' attribute" );
  }
  else
  {
    el = scratchNode.toElement();

    mLabelAttributes->setMultilineEnabled(( bool )el.attribute( "on", "0" ).toInt() );
    readLabelField( el, MultilineEnabled );
  }

  scratchNode = node.namedItem( "selectedonly" );

  if ( scratchNode.isNull() )
  {
    QgsDebugMsg( "couldn't find QgsLabel ``selectedonly'' attribute" );
  }
  else
  {
    el = scratchNode.toElement();
    mLabelAttributes->setSelectedOnly(( bool )el.attribute( "on", "0" ).toInt() );
  }

} // QgsLabel::readXML()
示例#19
0
void AProProject::parseFile()
{
    if(fileName.isEmpty())
    {
        QMessageBox::warning(0,"Erreur","Le projet spécifié n'existe pas !");
        return;
    }
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::warning(0,"Erreur","Le projet spécifié n'existe pas !");
        return;
    }
    QDomDocument doc("projet");
    if (!doc.setContent(&file))
        return;

    file.close();

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

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

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

                if (e.attribute("type","") == "header")
                {
                    QDomNode n2 = e.firstChild();
                    while (!n2.isNull())
                    {
                        QDomElement e2 = n2.toElement();
                        if (!e2.isNull())
                        {
                            QString h = e2.attribute("src","");
                            Headers.append(h);
                        }
                        n2 = n2.nextSibling();
                    }
                }
            }
        }
        n = n.nextSibling();
    }
}
示例#20
0
void Scene::read(const char *filename)
{
    QString path;
    if(!filename)
        path = QString("./data/scenes/open/");
    else
        path = QString("./data/scenes/")+QString(filename)+QString("/");

    //Parsing XML document.
    QDomDocument dom("config");
    QFile xml_doc(path+"config.xml");
    if(!xml_doc.open(QIODevice::ReadOnly))
    {
        QMessageBox::warning(NULL, QString("Read ")+filename+QString(" config"), QString("Can't open the file config.xml of ")+filename);
        return;
    }
    if (!dom.setContent(&xml_doc))
    {
        xml_doc.close();
        QMessageBox::warning(NULL, QString("Read ")+filename+QString(" config"), "Le document XML n'a pas pu être attribué à l'objet QDomDocument.");
        return;
    }

    //Count layers
    QDomNode node = dom.documentElement().firstChild();
    while(!node.isNull())
    {
        QDomElement element = node.toElement();
        if(element.tagName() == "layer")
            m_nbLayer++;
        node = node.nextSibling();
    }

    //Init new layers
    m_layer = new Layer[m_nbLayer];
    for(int i=0; i<m_nbLayer; i++)
    {
        m_layer[i].shader = NULL;
        m_layer[i].buffer = NULL;
        m_layer[i].backBuffer = NULL;
        m_layer[i].tmpBuffer = NULL;
        m_layer[i].mode = DEFAULT;
        for(int j=0; j<4; j++)
        {
            m_layer[i].channel[j] = NULL;
        }
    }

    //Read the xml file
    node = dom.documentElement().firstChild();
    int textureID=0;
    while(!node.isNull())
    {
        QDomElement element = node.toElement();
        if(element.tagName() == "layer")
        {
            //Get infos ..
            int id = element.attribute("id", "0").toInt();
            QString format = element.attribute("format", "rgba");

            QString blend = element.attribute("mode", "default");
            m_layer[id].width = element.attribute("width", "-1").toInt();
            m_layer[id].height = element.attribute("height", "-1").toInt();

            if(m_layer[id].width == -1)
                m_layer[id].width = Core::instance()->getResX();
            if(m_layer[id].height == -1)
                m_layer[id].height = Core::instance()->getResY();

            if(blend != "default")
            {
                m_layer[id].tmpBuffer = new FBO();
                m_layer[id].tmpBuffer->setSize(m_layer[id].width, m_layer[id].height);
                m_layer[id].width = Core::instance()->getResX();
                m_layer[id].height = Core::instance()->getResY();
            }

            //Select format
            GLint bufferFormat = GL_RGBA;
            if(format == "rgb")
                bufferFormat = GL_RGB;
            else if(format == "rgba")
                bufferFormat = GL_RGBA;
            else if(format == "rgba32")
                bufferFormat = GL_RGBA32F_ARB; //TODOOOOOOO
            else if(format == "luminance")
                bufferFormat = GL_LUMINANCE;
            else
                QMessageBox::warning(NULL, QString("Scene ")+filename, QString("This layer format doesn't exist : ")+format);

            //Select mode
            if(blend == "default")
                m_layer[id].mode = DEFAULT;
            else if(blend == "alpha")
                m_layer[id].mode = BLEND_ALPHA;
            else if(blend == "add")
                m_layer[id].mode = BLEND_ADD;
            else
                QMessageBox::warning(NULL, QString("Scene ")+filename, QString("This layer mode doesn't exist : ")+blend);

            //Compute shader
            QString filePath = element.attribute("value", "none");
            int ok;
            if(filePath != "none")
            {
                QFile file(path+filePath);
                QString strings;
                if (file.open(QIODevice::ReadOnly | QIODevice::Text))
                {
                    QTextStream in(&file);
                    while (!in.atEnd()) {
                        strings += in.readLine()+"\n";
                    }
                }
                m_layer[id].shader = new Shader();
                ok = m_layer[id].shader->compil(Core::instance()->getVertexShader(),strings.toStdString().c_str());
            }


            //Generate buffers !
            if(ok == SHADER_SUCCESS)
            {
                m_layer[id].buffer = new FBO();
                m_layer[id].buffer->setSize(m_layer[id].width, m_layer[id].height);
                m_layer[id].buffer->setFormat(bufferFormat);
                if(element.attribute("backbuffer", "false") == "true")
                {
                    m_layer[id].backBuffer = new FBO();
                    m_layer[id].backBuffer->setSize(m_layer[id].width, m_layer[id].height);
                    m_layer[id].backBuffer->setFormat(bufferFormat);
                }
            }
            else
            {
                return;
                delete m_layer[id].shader;
            }

            //Load channel
            textureID=0;
            QDomNode n = element.firstChild();
            while(!n.isNull())
            {
                QDomElement e = n.toElement();
                if(e.tagName() == "channel")
                {
                    if(textureID<4)
                    {
                        m_layer[id].channelName[textureID] = e.attribute("id", "tex");
                        if( e.attribute("type", "") == "image" )
                        {
                            m_layer[id].channel[textureID] = new Texture();
                            m_layer[id].channel[textureID]->load("./data/textures/"+e.attribute("value", "none").toStdString());
                        }
                        else if( e.attribute("type", "") == "layer" )
                        {
                            m_layer[id].channel[textureID] = m_layer[e.attribute("value", "0").toInt()].buffer;
                            m_layer[e.attribute("value", "0").toInt()].buffer->bind();
                        }
                        textureID++;
                    }
                    else
                        QMessageBox::warning(NULL, QString("Read ")+filename+QString(" config"), QString("Too many textures (max is 4)"));
                }
                n = n.nextSibling();
            }
        }
        else if(element.tagName() == "param")
        {
            m_param[element.attribute("id", "0").toInt()] = element.attribute("value","none");
        }
        node = node.nextSibling();
    }
}
bool QgsManageConnectionsDialog::populateConnections()
{
  // Export mode. Populate connections list from settings
  if ( mDialogMode == Export )
  {
    QSettings settings;
    switch ( mConnectionType )
    {
      case WMS:
        settings.beginGroup( "/Qgis/connections-wms" );
        break;
      case WFS:
        settings.beginGroup( "/Qgis/connections-wfs" );
        break;
      case WCS:
        settings.beginGroup( "/Qgis/connections-wcs" );
        break;
      case PostGIS:
        settings.beginGroup( "/PostgreSQL/connections" );
        break;
      case MSSQL:
        settings.beginGroup( "/MSSQL/connections" );
        break;
      case Oracle:
        settings.beginGroup( "/Oracle/connections" );
        break;
    }
    QStringList keys = settings.childGroups();
    QStringList::Iterator it = keys.begin();
    while ( it != keys.end() )
    {
      QListWidgetItem *item = new QListWidgetItem();
      item->setText( *it );
      listConnections->addItem( item );
      ++it;
    }
    settings.endGroup();
  }
  // Import mode. Populate connections list from file
  else
  {
    QFile file( mFileName );
    if ( !file.open( QIODevice::ReadOnly | QIODevice::Text ) )
    {
      QMessageBox::warning( this, tr( "Loading connections" ),
                            tr( "Cannot read file %1:\n%2." )
                            .arg( mFileName )
                            .arg( file.errorString() ) );
      return false;
    }

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

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

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

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

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

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

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

    QDomElement child = root.firstChildElement();
    while ( !child.isNull() )
    {
      QListWidgetItem *item = new QListWidgetItem();
      item->setText( child.attribute( "name" ) );
      listConnections->addItem( item );
      child = child.nextSiblingElement();
    }
  }
  return true;
}
/// \cond
void QXmppPresence::parse(const QDomElement &element)
{
    QXmppStanza::parse(element);

    const QString type = element.attribute("type");
    for (int i = Error; i <= Probe; i++) {
        if (type == presence_types[i]) {
            d->type = static_cast<Type>(i);
            break;
        }
    }
    d->status.parse(element);

    QXmppElementList extensions;
    QDomElement xElement = element.firstChildElement();
    d->vCardUpdateType = VCardUpdateNone;
    while(!xElement.isNull())
    {
        // XEP-0045: Multi-User Chat
        if(xElement.namespaceURI() == ns_muc) {
            d->mucSupported = true;
            d->mucPassword = xElement.firstChildElement("password").text();
        }
        else if(xElement.namespaceURI() == ns_muc_user)
        {
            QDomElement itemElement = xElement.firstChildElement("item");
            d->mucItem.parse(itemElement);
            QDomElement statusElement = xElement.firstChildElement("status");
            d->mucStatusCodes.clear();
            while (!statusElement.isNull()) {
                d->mucStatusCodes << statusElement.attribute("code").toInt();
                statusElement = statusElement.nextSiblingElement("status");
            }
        }
        // XEP-0153: vCard-Based Avatars
        else if(xElement.namespaceURI() == ns_vcard_update)
        {
            QDomElement photoElement = xElement.firstChildElement("photo");
            if(!photoElement.isNull())
            {
                d->photoHash = QByteArray::fromHex(photoElement.text().toLatin1());
                if(d->photoHash.isEmpty())
                    d->vCardUpdateType = VCardUpdateNoPhoto;
                else
                    d->vCardUpdateType = VCardUpdateValidPhoto;
            }
            else
            {
                d->photoHash = QByteArray();
                d->vCardUpdateType = VCardUpdateNotReady;
            }
        }
        // XEP-0115: Entity Capabilities
        else if(xElement.tagName() == "c" && xElement.namespaceURI() == ns_capabilities)
        {
            d->capabilityNode = xElement.attribute("node");
            d->capabilityVer = QByteArray::fromBase64(xElement.attribute("ver").toLatin1());
            d->capabilityHash = xElement.attribute("hash");
            d->capabilityExt = xElement.attribute("ext").split(" ", QString::SkipEmptyParts);
        }
        else if (xElement.tagName() == "addresses")
        {
        }
        else if (xElement.tagName() == "error")
        {
        }
        else if (xElement.tagName() == "show")
        {
        }
        else if (xElement.tagName() == "status")
        {
        }
        else if (xElement.tagName() == "priority")
        {
        }
        else
        {
            // other extensions
            extensions << QXmppElement(xElement);
        }
        xElement = xElement.nextSiblingElement();
    }
    setExtensions(extensions);
}
void QgsManageConnectionsDialog::loadOracleConnections( const QDomDocument &doc, const QStringList &items )
{
  QDomElement root = doc.documentElement();
  if ( root.tagName() != "qgsOracleConnections" )
  {
    QMessageBox::information( this,
                              tr( "Loading connections" ),
                              tr( "The file is not an Oracle connections exchange file." ) );
    return;
  }

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

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

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

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

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

    settings.setValue( "/host", child.attribute( "host" ) );
    settings.setValue( "/port", child.attribute( "port" ) );
    settings.setValue( "/database", child.attribute( "database" ) );
    settings.setValue( "/estimatedMetadata", child.attribute( "estimatedMetadata" ) );
    settings.setValue( "/userTablesOnly", child.attribute( "userTablesOnly" ) );
    settings.setValue( "/geometryColumnsOnly", child.attribute( "geometryColumnsOnly" ) );
    settings.setValue( "/allowGeometrylessTables", child.attribute( "allowGeometrylessTables" ) );
    settings.setValue( "/saveUsername", child.attribute( "saveUsername" ) );
    settings.setValue( "/username", child.attribute( "username" ) );
    settings.setValue( "/savePassword", child.attribute( "savePassword" ) );
    settings.setValue( "/password", child.attribute( "password" ) );
    settings.endGroup();

    child = child.nextSiblingElement();
  }
}
示例#24
0
static XMPP::Ice176::Candidate elementToCandidate(const QDomElement &e)
{
	if(e.tagName() != "candidate")
		return XMPP::Ice176::Candidate();

	XMPP::Ice176::Candidate c;
	c.component = e.attribute("component").toInt();
	c.foundation = e.attribute("foundation");
	c.generation = e.attribute("generation").toInt();
	c.id = e.attribute("id");
	c.ip = QHostAddress(e.attribute("ip"));
	c.network = e.attribute("network").toInt();
	c.port = e.attribute("port").toInt();
	c.priority = e.attribute("priority").toInt();
	c.protocol = e.attribute("protocol");
	c.rel_addr = QHostAddress(e.attribute("rel-addr"));
	c.rel_port = e.attribute("rel-port").toInt();
	c.rem_addr = QHostAddress(e.attribute("rem-addr"));
	c.rem_port = e.attribute("rem-port").toInt();
	c.type = e.attribute("type");
	return c;
}
示例#25
0
void XMLPreferences::loadPreferences(const QString& filename, 
				     PrefSectionDict& dict)
{
  QDomDocument doc(seqPrefName);
  QFile f(filename);
  if (!f.open(IO_ReadOnly))
  {
    qWarning("Unable to open file: %s!", 
	     (const char*)filename);
    return;
  }

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

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

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

   sectionName = section.attribute("name");

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

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

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

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

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

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

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

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

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

     propertyName = property.attribute("name");

     foundValue = false;

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

       valueElement = n.toElement();

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

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

	 continue;
       }

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

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

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

  // close the file
  f.close();

#if 1 // ZBTEMP
  printf("Loaded preferences file: %s!\n", (const char*)filename);
#endif
}
示例#26
0
bool QgsComposerShape::readXml( const QDomElement& itemElem, const QDomDocument& doc )
{
    mShape = QgsComposerShape::Shape( itemElem.attribute( "shapeType", "0" ).toInt() );
    mCornerRadius = itemElem.attribute( "cornerRadius", "0" ).toDouble();

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

        //rotation
        if ( !qgsDoubleNear( composerItemElem.attribute( "rotation", "0" ).toDouble(), 0.0 ) )
        {
            //check for old (pre 2.1) rotation attribute
            setItemRotation( composerItemElem.attribute( "rotation", "0" ).toDouble() );
        }

        _readXml( composerItemElem, doc );
    }

    QDomElement shapeStyleSymbolElem = itemElem.firstChildElement( "symbol" );
    if ( !shapeStyleSymbolElem.isNull() )
    {
        delete mShapeStyleSymbol;
        mShapeStyleSymbol = QgsSymbolLayerUtils::loadSymbol<QgsFillSymbol>( shapeStyleSymbolElem );
    }
    else
    {
        //upgrade project file from 2.0 to use symbol styling
        delete mShapeStyleSymbol;
        QgsStringMap properties;
        properties.insert( "color", QgsSymbolLayerUtils::encodeColor( brush().color() ) );
        if ( hasBackground() )
        {
            properties.insert( "style", "solid" );
        }
        else
        {
            properties.insert( "style", "no" );
        }
        if ( hasFrame() )
        {
            properties.insert( "style_border", "solid" );
        }
        else
        {
            properties.insert( "style_border", "no" );
        }
        properties.insert( "color_border", QgsSymbolLayerUtils::encodeColor( pen().color() ) );
        properties.insert( "width_border", QString::number( pen().widthF() ) );

        //for pre 2.0 projects, shape color and outline were specified in a different element...
        QDomNodeList outlineColorList = itemElem.elementsByTagName( "OutlineColor" );
        if ( !outlineColorList.isEmpty() )
        {
            QDomElement frameColorElem = outlineColorList.at( 0 ).toElement();
            bool redOk, greenOk, blueOk, alphaOk, widthOk;
            int penRed, penGreen, penBlue, penAlpha;
            double penWidth;

            penWidth = itemElem.attribute( "outlineWidth" ).toDouble( &widthOk );
            penRed = frameColorElem.attribute( "red" ).toDouble( &redOk );
            penGreen = frameColorElem.attribute( "green" ).toDouble( &greenOk );
            penBlue = frameColorElem.attribute( "blue" ).toDouble( &blueOk );
            penAlpha = frameColorElem.attribute( "alpha" ).toDouble( &alphaOk );

            if ( redOk && greenOk && blueOk && alphaOk && widthOk )
            {
                properties.insert( "color_border", QgsSymbolLayerUtils::encodeColor( QColor( penRed, penGreen, penBlue, penAlpha ) ) );
                properties.insert( "width_border", QString::number( penWidth ) );
            }
        }
        QDomNodeList fillColorList = itemElem.elementsByTagName( "FillColor" );
        if ( !fillColorList.isEmpty() )
        {
            QDomElement fillColorElem = fillColorList.at( 0 ).toElement();
            bool redOk, greenOk, blueOk, alphaOk;
            int fillRed, fillGreen, fillBlue, fillAlpha;

            fillRed = fillColorElem.attribute( "red" ).toDouble( &redOk );
            fillGreen = fillColorElem.attribute( "green" ).toDouble( &greenOk );
            fillBlue = fillColorElem.attribute( "blue" ).toDouble( &blueOk );
            fillAlpha = fillColorElem.attribute( "alpha" ).toDouble( &alphaOk );

            if ( redOk && greenOk && blueOk && alphaOk )
            {
                properties.insert( "color", QgsSymbolLayerUtils::encodeColor( QColor( fillRed, fillGreen, fillBlue, fillAlpha ) ) );
                properties.insert( "style", "solid" );
            }
        }
        if ( itemElem.hasAttribute( "transparentFill" ) )
        {
            //old style (pre 2.0) of specifying that shapes had no fill
            bool hasOldTransparentFill = itemElem.attribute( "transparentFill", "0" ).toInt();
            if ( hasOldTransparentFill )
            {
                properties.insert( "style", "no" );
            }
        }

        mShapeStyleSymbol = QgsFillSymbol::createSimple( properties );
    }
    emit itemChanged();
    return true;
}
示例#27
0
  QgsFeatureRequest parseFilterElement( const QString &typeName, QDomElement &filterElem, const QgsProject *project )
  {
    QgsFeatureRequest request;

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

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

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

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

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

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

        if ( filter->needsGeometry() )
        {
          request.setFlags( QgsFeatureRequest::NoFlags );
        }
        request.setFilterExpression( filter->expression() );
        return request;
      }
    }
    return request;
  }
示例#28
0
void EffectStackEdit::transferParamDesc(const QDomElement& d, int in, int out)
{
    kDebug() << "in";
    m_params = d;
    m_in = in;
    m_out = out;
    clearAllItems();
    if (m_params.isNull()) return;

    QDomDocument doc;
    doc.appendChild(doc.importNode(m_params, true));
    //kDebug() << "IMPORTED TRANS: " << doc.toString();
    QDomNodeList namenode = m_params.elementsByTagName("parameter");
    QDomElement e = m_params.toElement();
    const int minFrame = e.attribute("start").toInt();
    const int maxFrame = e.attribute("end").toInt();


    for (int i = 0;i < namenode.count() ;i++) {
        kDebug() << "in form";
        QDomElement pa = namenode.item(i).toElement();
        QDomNode na = pa.firstChildElement("name");
        QString type = pa.attribute("type");
        QString paramName = i18n(na.toElement().text().toUtf8().data());
        QWidget * toFillin = new QWidget;
        QString value = pa.attribute("value").isNull() ?
                        pa.attribute("default") : pa.attribute("value");
        if (type == "geometry") {
            /*pa.setAttribute("namedesc", "X;Y;Width;Height;Transparency");
            pa.setAttribute("format", "%d%,%d%:%d%x%d%:%d");
            pa.setAttribute("min", "-500;-500;0;0;0");
            pa.setAttribute("max", "500;500;200;200;100");*/
        } else if (type == "complex") {
            //pa.setAttribute("namedesc",pa.attribute("name"));

        }


        //TODO constant, list, bool, complex , color, geometry, position
        if (type == "double" || type == "constant") {
            createSliderItem(paramName, value.toInt(), pa.attribute("min").toInt(), pa.attribute("max").toInt());
            delete toFillin;
            toFillin = NULL;
        } else if (type == "list") {
            Listval *lsval = new Listval;
            lsval->setupUi(toFillin);
            QStringList listitems = pa.attribute("paramlist").split(',');
            QStringList listitemsdisplay = pa.attribute("paramlistdisplay").split(',');
            if (listitemsdisplay.count() != listitems.count()) listitemsdisplay = listitems;
            //lsval->list->addItems(listitems);
            lsval->list->setIconSize(QSize(30, 30));
            for (int i = 0;i < listitems.count();i++) {
                lsval->list->addItem(listitemsdisplay.at(i), listitems.at(i));
                QString entry = listitems.at(i);
                if (!entry.isEmpty() && (entry.endsWith(".png") || entry.endsWith(".pgm"))) {
                    if (!EffectStackEdit::iconCache.contains(entry)) {
                        QImage pix(entry);
                        EffectStackEdit::iconCache[entry] = pix.scaled(30, 30);
                    }
                    lsval->list->setItemIcon(i, QPixmap::fromImage(iconCache[entry]));
                }
            }
            if (!value.isEmpty()) lsval->list->setCurrentIndex(listitems.indexOf(value));

            connect(lsval->list, SIGNAL(currentIndexChanged(int)) , this, SLOT(collectAllParameters()));
            lsval->title->setTitle(paramName);
            m_valueItems[paramName] = lsval;
            m_uiItems.append(lsval);
        } else if (type == "bool") {
示例#29
0
// Index any resources
void NoteIndexer::indexRecognition(qint32 reslid, Resource &r) {

    QLOG_TRACE_IN();
    if (!r.noteGuid.isSet() || !r.guid.isSet())
        return;

    if (reslid <= 0)
        return;

    NSqlQuery sql(db);

    // Make sure we have something to look through.
    Data recognition;
    if (r.recognition.isSet())
        recognition = r.recognition;
    if (!recognition.body.isSet())
        return;

    QDomDocument doc;
    QString emsg;
    doc.setContent(recognition.body, &emsg);

    // look for text tags
    QDomNodeList anchors = doc.documentElement().elementsByTagName("t");

    QLOG_TRACE() << "Beginning insertion of recognition:";
    QLOG_TRACE() << "Anchors found: " << anchors.length();
    sql.exec("begin;");
#if QT_VERSION < 0x050000
    for (unsigned int i=0;  i<anchors.length(); i++) {
#else
    for (int i=0; i<anchors.length(); i++) {
#endif
        QLOG_TRACE() << "Anchor: " << i;
        QApplication::processEvents();
        QDomElement enmedia = anchors.at(i).toElement();
        QString weight = enmedia.attribute("w");
        QString text = enmedia.text();
        if (text != "") {
            // Add the new content.  it is basically a text version of the note with a weight of 100.
            sql.prepare("Insert into SearchIndex (lid, weight, source, content) values (:lid, :weight, :source, :content)");
            sql.bindValue(":lid", reslid);
            sql.bindValue(":weight", weight);
            sql.bindValue(":source", "recognition");


            text = global.normalizeTermForSearchAndIndex(text);
            sql.bindValue(":content", text);

            sql.exec();
        }
    }
    QLOG_TRACE() << "Committing";
    sql.exec("commit");
    QLOG_TRACE_OUT();
}



// Index any PDFs that are attached.  Basically it turns the PDF into text and adds it the same
// way as a note's body
void NoteIndexer::indexPdf(qint32 reslid) {

    QLOG_TRACE_IN();
    if (!global.indexPDFLocally)
        return;

    NSqlQuery sql(db);
    if (reslid <= 0)
        return;

    QString file = global.fileManager.getDbaDirPath() + QString::number(reslid) +".pdf";

    QString text = "";
    Poppler::Document *doc = Poppler::Document::load(file);
    if (doc == nullptr || doc->isEncrypted() || doc->isLocked())
        return;

    for (int i=0; i<doc->numPages(); i++) {
        QRectF rect;
        text = text + doc->page(i)->text(rect) + QString(" ");
    }

    QLOG_TRACE() << "Adding PDF";
    // Add the new content.  it is basically a text version of the note with a weight of 100.
    sql.prepare("Insert into SearchIndex (lid, weight, source, content) values (:lid, :weight, :source, :content)");
    sql.bindValue(":lid", reslid);
    sql.bindValue(":weight", 100);
    sql.bindValue(":source", "recognition");

    text = global.normalizeTermForSearchAndIndex(text);
    sql.bindValue(":content", text);

    sql.exec();
    QLOG_TRACE_OUT();
}
示例#30
0
文件: qtrpt.cpp 项目: ant32/QtRPT
QVariant QtRPT::processHighligthing(QDomElement e, HiType type) {
    QString tmpStr = e.attribute("highlighting","");
    if (tmpStr.isEmpty() || tmpStr.isNull()) {
        switch (type) {
            case FontBold: {
                return e.attribute("fontBold").toInt();
                break;
            }
            case FontItalic: {
                return e.attribute("fontItalic").toInt();
                break;
            }
            case FontUnderline: {
                return e.attribute("fontUnderline").toInt();
                break;
            }
            case FontColor: {
                return e.attribute("fontColor");
                break;
            }
            case BgColor: {
                return e.attribute("backgroundColor");
                break;
            }
        }
    } else {
        QStringList list = tmpStr.split(";");
        const QString cond = list.at(0);
        for (int i = 1; i < list.size(); i++) {
            if (list.at(i).isEmpty()) continue;
            QString exp = list.at(i);
            if (list.at(i).contains("bold") && type == FontBold) {
                exp.remove("bold=");
                QString formulaStr = exp.insert(0,cond);
                formulaStr = sectionField(formulaStr,true);
                QScriptEngine myEngine;
                return myEngine.evaluate(formulaStr).toInteger();
            }
            if (list.at(i).contains("italic") && type == FontItalic) {
                exp.remove("italic=");
                QString formulaStr = exp.insert(0,cond);
                formulaStr = sectionField(formulaStr,true);
                QScriptEngine myEngine;
                return myEngine.evaluate(formulaStr).toInteger();
            }
            if (list.at(i).contains("underline") && type == FontUnderline) {
                exp.remove("underline=");
                QString formulaStr = exp.insert(0,cond);
                formulaStr = sectionField(formulaStr,true);
                QScriptEngine myEngine;
                return myEngine.evaluate(formulaStr).toInteger();
            }
            if (list.at(i).contains("fontColor") && type == FontColor) {
                exp.remove("fontColor=");
                QString formulaStr = exp.insert(1,"'");
                formulaStr = exp.insert(0,cond);
                formulaStr = sectionField(formulaStr,true)+"':'"+e.attribute("fontColor")+"'";
                QScriptEngine myEngine;
                return myEngine.evaluate(formulaStr).toString();
            }
            if (list.at(i).contains("backgroundColor") && type == BgColor) {
                exp.remove("backgroundColor=");
                QString formulaStr = exp.insert(1,"'");
                formulaStr = exp.insert(0,cond);
                formulaStr = sectionField(formulaStr,true)+"':'"+e.attribute("backgroundColor")+"'";
                QScriptEngine myEngine;
                return myEngine.evaluate(formulaStr).toString();
            }
        }
    }
    return QVariant();
}