void AbstractEmoticonsLayer::setEmoticonPath(const QString &path)
{
	m_emoticon_list.clear();
	m_emoticons.clear();
	QFile file(path);
	QString dirPath = QFileInfo( path ).absolutePath();
	m_dir_path = dirPath;
	QDir dir ( dirPath );
	QStringList fileList = dir.entryList(QDir::Files);
	if (file.exists() && file.open(QIODevice::ReadOnly) )
	{
		QDomDocument doc;
		if ( doc.setContent(&file) )
		{
			QDomElement rootElement = doc.documentElement();
			int emoticonCount = rootElement.childNodes().count();
			QDomElement emoticon = rootElement.firstChild().toElement();
			for ( int i = 0; i < emoticonCount ; i++ )
			{
				if ( emoticon.tagName() == "emoticon")
				{
					QString regexp = "(^";
					regexp += QRegExp::escape(emoticon.attribute("file"));
					regexp += "\\.\\w+$)|(^";
					regexp += QRegExp::escape(emoticon.attribute("file"));
					regexp += "$)";
					QStringList fileName = fileList.filter(QRegExp(regexp));
					if ( !fileName.isEmpty())
					{
						QStringList strings;
						QPixmap tmp;
						int stringCount = emoticon.childNodes().count();
						QDomElement emoticonString = emoticon.firstChild().toElement();
						for(int j = 0; j < stringCount; j++)
						{
							if ( emoticonString.tagName() == "string")
							{
								if(tmp.isNull())
									tmp = QPixmap(dirPath + "/" + fileName.at(0));
								QString text = Qt::escape(emoticonString.text());
								m_urls.insert(Qt::escape(emoticonString.text()),
								QString("<img src=\"%1\" width=\"%2\" height=\"%3\" alt=\"%4\" title=\"%4\"/>")
								.arg(dirPath + "/" + fileName.at(0)).arg(tmp.size().width())
								.arg(tmp.size().height())
								//.arg(text.replace("\"", "&quot;"))
								);

								strings.append(emoticonString.text());
							}

							emoticonString = emoticonString.nextSibling().toElement();
						}
						m_emoticon_list.insert(QString::number(i+1)+"|"+dirPath + "/" + fileName.at(0),strings);
					}
				}
				emoticon = emoticon.nextSibling().toElement();
			}
			QStringList emoticon_keys = m_urls.keys();
			qSort(emoticon_keys.begin(), emoticon_keys.end(), lengthLessThan);
			m_emoticons.clear();
			foreach( const QString &emoticon, emoticon_keys )
			{
				m_emoticons << qMakePair( emoticon.toLower(), m_urls.value(emoticon) );
			}
Пример #2
0
			PackageInfo ParsePackage (const QByteArray& data,
					const QUrl& baseUrl,
					const QString& packageName,
					const QStringList& packageVersions)
			{
				QDomDocument doc;
				QString msg;
				int line = 0;
				int column = 0;
				if (!doc.setContent (data, &msg, &line, &column))
				{
					qWarning () << Q_FUNC_INFO
							<< "erroneous document with msg"
							<< msg
							<< line
							<< column
							<< data;
					throw std::runtime_error ("Unagle to parse package description.");
				}

				PackageInfo packageInfo;

				QDomElement package = doc.documentElement ();

				QString type = package.attribute ("type");
				if (type == "iconset")
					packageInfo.Type_ = PackageInfo::TIconset;
				else if (type == "translation")
					packageInfo.Type_ = PackageInfo::TTranslation;
				else if (type == "plugin")
					packageInfo.Type_ = PackageInfo::TPlugin;
				else if (type == "theme")
					packageInfo.Type_ = PackageInfo::TTheme;
				else
					packageInfo.Type_ = PackageInfo::TData;

				packageInfo.Language_ = package.attribute ("language");
				packageInfo.Name_ = packageName;
				packageInfo.Versions_ = packageVersions;
				packageInfo.Description_ = package.firstChildElement ("description").text ();
				packageInfo.LongDescription_ = package.firstChildElement ("long").text ();

				QDomElement images = package.firstChildElement ("images");
				QDomElement imageNode = images.firstChildElement ("thumbnail");
				while (!imageNode.isNull ())
				{
					Image image =
					{
						Image::TThumbnail,
						MakeProperURL (imageNode.attribute ("url"), baseUrl)
					};
					packageInfo.Images_ << image;
					imageNode = imageNode.nextSiblingElement ("thumbnail");
				}
				imageNode = images.firstChildElement ("screenshot");
				while (!imageNode.isNull ())
				{
					Image image =
					{
						Image::TScreenshot,
						MakeProperURL (imageNode.attribute ("url"), baseUrl)
					};
					packageInfo.Images_ << image;
					imageNode = imageNode.nextSiblingElement ("screenshot");
				}
				packageInfo.IconURL_ = images.firstChildElement ("icon").attribute ("url");

				QDomElement tags = package.firstChildElement ("tags");
				QDomElement tagNode = tags.firstChildElement ("tag");
				while (!tagNode.isNull ())
				{
					packageInfo.Tags_ << tagNode.text ();
					tagNode = tagNode.nextSiblingElement ("tag");
				}
				
				QDomElement verNode = package.firstChildElement ("versions")
						.firstChildElement ("version");
				while (!verNode.isNull ())
				{
					if (verNode.hasAttribute ("size"))
					{
						bool ok = false;
						qint64 size = verNode.attribute ("size").toLong (&ok);
						if (ok)
							packageInfo.PackageSizes_ [verNode.text ()] = size;
					}
					verNode = verNode.nextSiblingElement ("version");
				}

				QDomElement maintNode = package.firstChildElement ("maintainer");
				packageInfo.MaintName_ = maintNode.firstChildElement ("name").text ();
				packageInfo.MaintEmail_ = maintNode.firstChildElement ("email").text ();

				QDomElement depends = package.firstChildElement ("depends");
				QDomElement dependNode = depends.firstChildElement ("depend");
				while (!dependNode.isNull ())
				{
					Dependency dep;
					if (dependNode.attribute ("type") == "depends" ||
							!dependNode.hasAttribute ("type"))
						dep.Type_ = Dependency::TRequires;
					else
						dep.Type_ = Dependency::TProvides;
					dep.Name_ = dependNode.attribute ("name");
					dep.Version_ = dependNode.attribute ("version");

					packageInfo.Deps_ [dependNode.attribute ("thisVersion")] << dep;

					dependNode = dependNode.nextSiblingElement ("depend");
				}

				return packageInfo;
			}
Пример #3
0
  /*
   * \author Anders Fernström
   * \date 2005-10-26
   *
   * \brief Parse the FONT tag
   */
  void Stylesheet::parseFontTag( QDomElement element,
    CellStyle *item ) const
  {
    QDomNode fontNode = element.firstChild();
    while( !fontNode.isNull() )
    {
      QDomElement fontElement = fontNode.toElement();
      if( !fontElement.isNull() )
      {
        // FAMILY
        if( fontElement.tagName() == "family" )
        {
          item->textCharFormat()->setFontFamily( fontElement.text() );
        }
        // SIZE
        else if( fontElement.tagName() == "size" )
        {
          bool ok;
          int size = fontElement.text().toInt(&ok);

          if(ok)
            item->textCharFormat()->setFontPointSize( size );
          else
            item->textCharFormat()->setFontPointSize( 12 );
        }
        // WEIGHT
        else if( fontElement.tagName() == "weight" )
        {
          QString weight = fontElement.text();

          if( weight == "light" )
            item->textCharFormat()->setFontWeight( QFont::Light );
          else if( weight == "normal" )
            item->textCharFormat()->setFontWeight( QFont::Normal );
          else if( weight == "demibold" )
            item->textCharFormat()->setFontWeight( QFont::DemiBold );
          else if( weight == "bold" )
            item->textCharFormat()->setFontWeight( QFont::Bold );
          else if( weight == "black" )
            item->textCharFormat()->setFontWeight( QFont::Black );
          else
          {
            bool ok;
            int size = weight.toInt(&ok);

            if(ok)
              item->textCharFormat()->setFontWeight( size );
            else
              item->textCharFormat()->setFontWeight( QFont::Normal );
          }
        }
        // STRETCH
        else if( fontElement.tagName() == "stretch" )
        {
          QString stretch = fontElement.text();

          if( stretch == "ultracondensed" )
            item->textCharFormat()->font().setStretch( QFont::UltraCondensed );
          else if( stretch == "extracondensed" )
            item->textCharFormat()->font().setStretch( QFont::ExtraCondensed );
          else if( stretch == "condensed" )
            item->textCharFormat()->font().setStretch( QFont::Condensed );
          else if( stretch == "semicondensed" )
            item->textCharFormat()->font().setStretch( QFont::SemiCondensed );
          else if( stretch == "unstretched" )
            item->textCharFormat()->font().setStretch( QFont::Unstretched );
          else if( stretch == "semiexpanded" )
            item->textCharFormat()->font().setStretch( QFont::SemiExpanded );
          else if( stretch == "expanded" )
            item->textCharFormat()->font().setStretch( QFont::Expanded );
          else if( stretch == "extraexpanded" )
            item->textCharFormat()->font().setStretch( QFont::ExtraExpanded );
          else if( stretch == "ultraexpanded" )
            item->textCharFormat()->font().setStretch( QFont::UltraExpanded );
          else
          {
            cout << "Stretch value not correct: " << stretch.toStdString();
            item->textCharFormat()->font().setStretch( QFont::Unstretched );
          }
        }
        // ITALIC
        else if( fontElement.tagName() == "italic" )
        {
          //This only occur when italic tag is present.
          //delete italic tag to disable.
          item->textCharFormat()->setFontItalic( true );
        }
        // STRIKEOUT
        else if( fontElement.tagName() == "strikeout" )
        {
          //This only occur when strikeout tag is present.
          //delete strikeout tag to disable.
          item->textCharFormat()->setFontStrikeOut( true );
        }
        // UNDERLINE
        else if( fontElement.tagName() == "underline" )
        {
          //This only occur when underline tag is present.
          //delete underline tag to disable.
          item->textCharFormat()->setFontUnderline( true );
        }
        // OVERLINE
        else if( fontElement.tagName() == "overline" )
        {
          //This only occur when overline tag is present.
          //delete overline tag to disable.
          item->textCharFormat()->setFontOverline( true );
        }
        // COLOR
        else if( fontElement.tagName() == "color" )
        {
          bool okRed;
          bool okGreen;
          bool okBlue;

          int red = fontElement.attribute( "red", "0" ).toInt(&okRed);
          int green = fontElement.attribute( "green", "0" ).toInt(&okGreen);
          int blue = fontElement.attribute( "blue", "0" ).toInt(&okBlue);

          if( okRed && okGreen && okBlue )
            item->textCharFormat()->setForeground( QBrush( QColor(red, green, blue) ));
          else
            item->textCharFormat()->setForeground( QBrush( QColor(0, 0, 0) ));
        }
        else
        {
          cout << "font tag not specified: " <<
            fontElement.tagName().toStdString();
        }
      }

      fontNode = fontNode.nextSibling();
    }
  }
Пример #4
0
/**
	\brief Reads the error from XML

	This function finds and reads the error element \a e.

	You need to provide the base namespace of the stream which this stanza belongs to
	(probably by using stream.baseNS() function).
*/
bool Stanza::Error::fromXml(const QDomElement &e, const QString &baseNS)
{
	if(e.tagName() != "error" && e.namespaceURI() != baseNS)
		return false;

	// type
	type = Private::stringToErrorType(e.attribute("type"));

	// condition
	QDomNodeList nl = e.childNodes();
	QDomElement t;
	condition = -1;
	int n;
	for(n = 0; n < nl.count(); ++n) {
		QDomNode i = nl.item(n);
		t = i.toElement();
		if(!t.isNull()) {
			// FIX-ME: this shouldn't be needed
			if(t.namespaceURI() == NS_STANZAS || t.attribute("xmlns") == NS_STANZAS) {
				condition = Private::stringToErrorCond(t.tagName());
				if (condition != -1)
					break;
			}
		}
	}

	// code
	originalCode = e.attribute("code").toInt();

	// try to guess type/condition
	if(type == -1 || condition == -1) {
		QPair<int, int> guess(-1, -1);
		if (originalCode)
			guess = Private::errorCodeToTypeCond(originalCode);

		if (type == -1)
			type = guess.first != -1 ? guess.first : Cancel;
		if (condition == -1)
			condition = guess.second != -1 ? guess.second : UndefinedCondition;
	}

	// text
	t = e.elementsByTagNameNS(NS_STANZAS, "text").item(0).toElement();
	if(!t.isNull())
		text = t.text().trimmed();
	else
		text = e.text().trimmed();

	// appspec: find first non-standard namespaced element
	appSpec = QDomElement();
	nl = e.childNodes();
	for(n = 0; n < nl.count(); ++n) {
		QDomNode i = nl.item(n);
		if(i.isElement() && i.namespaceURI() != NS_STANZAS) {
			appSpec = i.toElement();
			break;
		}
	}

	return true;
}
Пример #5
0
bool Bookmarks::updateBookmarkState(const QString &type, const QVariant &data, bool state)
{
    if (type == "Verses" || type == tr("Verses")) {
        QDomElement verseNode = findChildNode("folder", "Verses");
        if (verseNode.isNull()) {
            QDomElement root = m_domDocument.createElement("folder");
            QDomElement child = m_domDocument.createElement("title");
            QDomText newTitleText = m_domDocument.createTextNode(tr("Verses"));
            root.setAttribute("folded", "no");
            child.appendChild(newTitleText);
            root.appendChild(child);
            m_domDocument.documentElement().appendChild(root);
            verseNode = root;
            parseFolderElement(root);
        }

        QTreeWidgetItem* parentItem = m_domElementForItem.key(verseNode);
        //REMOVE OPERATION
        if (!state) {
            int countOfChildren = parentItem->childCount();
            int numOfDel = 0;
            bool allMatchedRemoved = true;
            for (int i = 0; i < countOfChildren; ++i) {
                QTreeWidgetItem* childItem = parentItem->child(i);
                if (!childItem) {
                    continue;
                }

                if (childItem->data(0, Qt::UserRole).toString() == data.toStringList().at(0) + "|" + data.toStringList().at(1)) {
                    ++numOfDel;

                    if (unBookmarkItem(childItem)) {
                        --i; //because one of children was deleted
                        --countOfChildren;
                    }
                    else {
                        allMatchedRemoved = false;
                    }
                }
            }

            //allMatchedRemoved is false when at least one of
            // matched items are not deleted!!
            return allMatchedRemoved;
        }

        QDomElement bookmark = m_domDocument.createElement("bookmark");
        QDomElement bookmarkTitle = m_domDocument.createElement("title");
        QDomElement bookmarkDescription = m_domDocument.createElement("desc");
        QDomElement bookmarkInfo = m_domDocument.createElement("info");
        QDomElement infoMetaData = m_domDocument.createElement("metadata");

        infoMetaData.setAttribute("owner", "http://saaghar.pozh.org");
        QDomText bookmarkSaagharMetadata = m_domDocument.createTextNode(data.toStringList().at(0) + "|" + data.toStringList().at(1));
        infoMetaData.appendChild(bookmarkSaagharMetadata);
        bookmarkInfo.appendChild(infoMetaData);
        bookmark.appendChild(bookmarkTitle);
        bookmark.appendChild(bookmarkDescription);
        bookmark.appendChild(bookmarkInfo);
        verseNode.appendChild(bookmark);

        qDebug() << data << state;
        QDomElement firstChild = m_domDocument.documentElement().firstChildElement("folder");
        firstChild.text();
        QTreeWidgetItem* item = createItem(bookmark, parentItem);
        item->setIcon(0, m_bookmarkIcon);

        QString title = data.toStringList().at(2);
        item->setText(0, title);
        item->setToolTip(0, title);
        item->setData(0, Qt::UserRole, data.toStringList().at(0) + "|" + data.toStringList().at(1));
        item->setData(1, Qt::UserRole, data.toStringList().at(3));
        if (data.toStringList().size() == 5) {
            item->setText(1, data.toStringList().at(4));
            item->setToolTip(1, data.toStringList().at(4));
        }

        if (parentItem->childCount() == 1) {
            resizeColumnToContents(0);
            resizeColumnToContents(1);
        }

        return true;
    }

    //an unknown type!!
    return false;
}
Пример #6
0
CGraphicsScene* CDecodeFlowGraphicsList::readGraphicsScene ( const QDomElement& diagram )
{
  CGraphicsScene* scene = NULL;
  QDomElement title = diagram.firstChildElement("title");
  QDomElement type = diagram.firstChildElement("type");
  QDomElement item = diagram.firstChildElement("item");
  QDomElement isDisplayed = diagram.firstChildElement("displayed");
  QDomElement rectScene = diagram.firstChildElement("scene");
  
  
  if (!title.isNull() && !type.isNull() && !item.isNull() && !rectScene.isNull())
  {
    scene = new CGraphicsScene();
    scene->setTitle(title.text());
    scene->setType(type.text().toInt());
    
    QRectF sceneRect;
    int typeOfItem;
    int IdOfItem;
    bool bOk;
    typeOfItem = item.attribute("type").toInt();
    IdOfItem = item.attribute("id").toInt();  
    
    sceneRect = CXmlBasicItem::decodeQRectF(rectScene, &bOk);
    if (bOk)
      scene->setSceneRect(sceneRect);
    else
    {
      qDebug("scene Rect unable to decode");
      delete scene;
      scene = NULL;
    }
    
    CItem* gitem;
    gitem = m_itemFactory->search(typeOfItem, IdOfItem);
    if ((gitem != NULL) && (scene != NULL))
    {
      scene->setItem(gitem);
    }
    else
    {
      qDebug("scene not found");
      delete scene;
      scene = NULL;
    }
    getApp()->getDocument()->buildAuthorizationList(scene);
    
    if (!isDisplayed.isNull() && (scene != NULL))
    {
      bool displayed;
      displayed = CXmlBasicItem::decodeInt(isDisplayed);
      scene->setDisplayState(displayed);
    }
    
    if (scene != NULL)
    {
      bool bCorrectlyDecoded;
      
      bCorrectlyDecoded = lookIntoDiagramElement(diagram, scene, dynamic_cast<CItemContainer*>(gitem), FIRST_PASS);
      if (bCorrectlyDecoded == true)
      {
        bCorrectlyDecoded = lookIntoDiagramElement(diagram, scene, dynamic_cast<CItemContainer*>(gitem), SECOND_PASS);
      }
      
      if (bCorrectlyDecoded == false)
      {
        delete scene;
        scene = NULL;
      }
    }
  }
  else
  {
    qDebug("unable to read scene");
  }

  return scene;
}
Пример #7
0
void Bookmarks::parseFolderElement(const QDomElement &element,
                                   QTreeWidgetItem* parentItem, const QString &/*elementID*/)
{
    QDomElement parentElement(element);
    QString id = "";
    if (parentElement.tagName() == "folder") {
        //old files that their 'folder' tag don't use 'id' attribute
        // just contain 'folder' tag of type 'Verses'!
        id = parentElement.attribute("id", "Verses");
        parentElement.setAttribute("id", id);
    }

    QTreeWidgetItem* item = createItem(parentElement, parentItem, id);

    QString title;
    if (id == "Verses") {
        title = tr("Verses");
    }
    else {
        title = element.firstChildElement("title").text();
    }
    if (title.isEmpty()) {
        title = QObject::tr("Folder");
    }

    item->setIcon(0, m_folderIcon);
    item->setText(0, title);
    item->setToolTip(0, title);

    bool folded = (parentElement.attribute("folded") != "no");
    setItemExpanded(item, !folded);

    QDomElement child = parentElement.firstChildElement();
    while (!child.isNull()) {
        if (child.tagName() == "folder") {
//TODO: we can save labguage within a 'metadata' tag of this 'folder'
//          //update node title by new loaded translation
            QString id = child.attribute("id");
            QString title = child.firstChildElement("title").text();

            if (id.isEmpty()) {
                //old files that their 'folder' tags don't use 'id' attribute just contain 'folder' tags of type 'Verses'!
                id = "Verses";
                title = tr(title.toLocal8Bit().data());
                QDomElement oldTitleElement = child.firstChildElement("title");
                QDomElement newTitleElement = m_domDocument.createElement("title");
                QDomText newTitleText = m_domDocument.createTextNode(tr("Verses"));
                newTitleElement.appendChild(newTitleText);

                child.replaceChild(newTitleElement, oldTitleElement);
                child.setAttribute("id", "Verses");
            }
            parseFolderElement(child, item, id);
        }
        else if (child.tagName() == "bookmark") {
            QTreeWidgetItem* childItem = createItem(child, item);

            QString title = child.firstChildElement("title").text();
            if (title.isEmpty()) {
                title = QObject::tr("Folder");
            }

            QDomElement infoChild = child.firstChildElement("info");
            QDomElement metaData = infoChild.firstChildElement("metadata");
            while (!metaData.isNull()) {
                QString owner = metaData.attribute("owner");
                if (owner == "http://saaghar.pozh.org") {
                    break;
                }
                metaData = metaData.nextSiblingElement("metadata");
            }
            if (!metaData.isNull() && metaData.attribute("owner") == "http://saaghar.pozh.org") {
                childItem->setData(0, Qt::UserRole, metaData.text());
            }
            else {
                qDebug() << "This DOM-NODE SHOULD deleted--->" << title;
            }
            //href data URL data
            childItem->setData(1, Qt::UserRole, child.attribute("href", "http://saaghar.pozh.org"));
            childItem->setIcon(0, m_bookmarkIcon);
            childItem->setText(0, title);
            childItem->setToolTip(0, title);
            childItem->setText(1, child.firstChildElement("desc").text());
            childItem->setToolTip(1, child.firstChildElement("desc").text());
        }
        else if (child.tagName() == "separator") {
            QTreeWidgetItem* childItem = createItem(child, item);
            childItem->setFlags(item->flags() & ~(Qt::ItemIsSelectable | Qt::ItemIsEditable));
            childItem->setText(0, QString(30, 0xB7));
        }
        child = child.nextSiblingElement();
    }
}
Пример #8
0
void Browser::load(void)
{
  std::cout << qPrintable(tr("Loading data")) << std::endl;

  QFile file( CFG_FILE );
  QDir::setCurrent( CFG_DIR );

  if( !file.open( QIODevice::ReadOnly ) )
    {
      QString strErr = QObject::tr("Error: Can't open config file !\n"
                                   "This is probably the first time\n"
                                   "you run this application.\n"
                                   "So just click ok.\n"
                                   "Next time, this message shouldn't appear.\n"
                                  );
      std::cerr << " " << qPrintable(strErr) << std::endl;
      QMessageBox::warning(0,
                           QObject::tr("Loading config file"),
                           strErr
                          );
      file.close();

      /* Default values */
      default_interval = 5000;
      url_list.append(QUrl("http://www.google.fr/search?hl=fr&q=test%200"));
      url_list.append(QUrl("http://www.google.fr/search?hl=fr&q=test%201"));
      url_list.append(QUrl("http://www.google.fr/search?hl=fr&q=test%202"));
      url_list.append(QUrl("http://www.google.fr/search?hl=fr&q=test%203"));
      url_list.append(QUrl("http://www.google.fr/search?hl=fr&q=test%204"));
      url_list.append(QUrl("http://www.google.fr/search?hl=fr&q=test%205"));
/*

<!DOCTYPE BrowserML PUBLIC '-//CELLES//DTD Browser 0.1 //EN' 'http://www.celles.net/dtd/browser/browser_data-0_1.dtd'>
<!--This file describe data for a very light browser for dynamic display-->
<!--http://www.celles.net/wiki/Browser-->
<browser timer="5000">
 <url>http://127.0.0.1/test/0.html</url>
 <url>http://127.0.0.1/test/1.html</url>
 <url>http://127.0.0.1/test/2.html</url>
 <url>http://127.0.0.1/test/3.html</url>
 <url>http://127.0.0.1/test/4.html</url>
 <url>http://127.0.0.1/test/5.html</url>
</browser>

http://www.google.fr/search?hl=fr&q=test
http://www.google.fr/search?hl=fr&amp;q=test

*/

      //save(); // save default values
      return;
    }

  std::cout << " " << qPrintable(tr("Loading...")) << std::endl;
  //std::cout << " ToDo" << std::endl;

  /* validating document using dtd : not possible easily using Qt4 */

  /* En test */
  QDomDocument doc;
  QString errorStr;
  int errorLine;
  int errorColumn;

  /* looking for malformed xml file */
  if( !doc.setContent( &file, true, &errorStr, &errorLine, &errorColumn ) )
    {
      QString strErr = QObject::tr("Parse error at line %1, "
                                   "column %2:\n%3")
                       .arg(errorLine)
                       .arg(errorColumn)
                       .arg(errorStr);
      std::cerr << " " << qPrintable(strErr) << std::endl;
      QMessageBox::warning(0,
                           QObject::tr("DOM Parser"),
                           strErr
                          );
      file.close();
      return;
    }

  QDomElement root = doc.documentElement();

  /* looking for the root name 'ocdata' */
  //std::cout << "root = " << qPrintable(root.tagName()) << std::endl;
  if (root.tagName() != QLatin1String("browser"))
    {
      QString strErr = QObject::tr("Document should begin with <browser> and stop with </browser>");
      std::cerr << " " << qPrintable(strErr) << std::endl;
      QMessageBox::warning(0,
                           QObject::tr("DOM Parser"),
                           strErr
                          );

      file.close();
      return;
    }

  /* parsing file */

  QDomNode node = root.firstChild();
  while ( !node.isNull() )
    {
      default_interval = root.attribute(QLatin1String("timer")).toInt();

      QDomElement element = node.toElement();

      if (element.tagName() == QLatin1String("url"))
        {
          std::cout << qPrintable(tr(" ")) << qPrintable(tr("Parsing"))  << qPrintable(tr(" ")) << qPrintable(element.tagName()) << std::endl;
          std::cout << "  " << qPrintable(element.text()) << std::endl;
         // QString
          QUrl url = QUrl(element.text());
          //QUrl url = QUrl(element.text(),QUrl::TolerantMode);
          //QString str = QString("http://www.google.fr/search?hl=fr&q=test");
          //QUrl url = QUrl(str);
          //url.ParsingMode=QUrl::TolerantMode;
          url_list.append(url);
          //url_list.append(element.text());
          //url_list.append(QUrl::fromEncoded(element.text().toStdString()));
        }
      else
        {
          QString strErr = QObject::tr("Error: Undefined element tagName");
          std::cerr << qPrintable(tr(" ")) << qPrintable(strErr) << std::endl;
          QMessageBox::warning(0,
                               QObject::tr("DOM Parser"),
                               strErr
                              );
        }

      node = node.nextSibling();
    }

  file.close();

  std::cout << qPrintable(tr(" ")) << qPrintable(tr("Data loaded")) << std::endl;

  if (url_list.count()==0) {
    //url_list.append(QUrl("about:blank"));
    url_list.append(QUrl("http://www.google.fr"));
  }

}
Пример #9
0
void DistroMesas::importXML(const QString val) {
  QFile file ( g_confpr->value( CONF_DIR_USER ) + "distromesas_" + mainCompany()->dbName() + ".cfn" );

    if (file.exists()) {
        if ( !file.open ( QIODevice::ReadOnly ) ) {
            
            return;
        } // end if
        QString result (file.readAll());
        file.close(); 


    QDomDocument doc ( "mydocument" );

    if ( !doc.setContent ( result ) ) {
	
        return;
    } // end if

    QDomElement docElem = doc.documentElement();
    QDomElement principal = docElem.firstChildElement ( "BACKGROUND" );
    m_background = principal.text();

    principal = docElem.firstChildElement ( "ESCALA" );
    g_escala = principal.text().toInt();


    QDomNodeList nodos = docElem.elementsByTagName ( "MESA" );
    int i = 0;
    while (i < nodos.count() ) {
        QDomNode ventana = nodos.item ( i++ );
        QDomElement e1 = ventana.toElement(); /// try to convert the node to an element.
        if ( !e1.isNull() ) { /// the node was really an element.
            QString nodoText = e1.text();
            /// Pasamos el XML a texto para poder procesarlo como tal.
            QString result;
            QTextStream stream ( &result );
            ventana.save(stream,5);

            Mesa *mesa = new Mesa((BtCompany *) mainCompany(), mui_widget);
            mesa->importXML(result);
	    
	    if (! m_listapantallas.contains(mesa->m_pantalla)) {
	        if (m_pantallaactual == "") {
		    m_pantallaactual = mesa->m_pantalla;
		} // end if
		m_listapantallas.append(mesa->m_pantalla);
		QToolButton *but = new QToolButton(this);
		but->setObjectName("p_"+mesa->m_pantalla);
		but->setText(mesa->m_pantalla);
		but->setMinimumHeight(42);
		but->setMinimumWidth(42);
		but->setCheckable(TRUE);
		mui_espaciopantallas->addWidget(but);
		connect(but, SIGNAL(clicked()), this, SLOT(cambiarPantalla()));
	    } // end if
	    if (mesa->m_pantalla == m_pantallaactual) 
		mesa->show();

        } // end if
    } // end while

} // end if

}
Пример #10
0
bool UPNPSubscription::ProcessRequest(HttpWorkerThread *pThread,
                                      HTTPRequest *pRequest)
{
    (void)pThread;
    if (!pRequest)
        return false;

    if (pRequest->m_sBaseUrl != "/Subscriptions")
        return false;
    if (pRequest->m_sMethod != "event")
        return false;

    LOG(VB_UPNP, LOG_DEBUG, QString("%1\n%2")
        .arg(pRequest->m_sRawRequest).arg(pRequest->m_sPayload));

    if (pRequest->m_sPayload.isEmpty())
        return true;

    pRequest->m_eResponseType = ResponseTypeHTML;

    QString nt  = pRequest->m_mapHeaders["nt"];
    QString nts = pRequest->m_mapHeaders["nts"];
    bool    no  = pRequest->m_sRawRequest.startsWith("NOTIFY");

    if (nt.isEmpty() || nts.isEmpty() || !no)
    {
        pRequest->m_nResponseStatus = 400;
        return true;
    }

    pRequest->m_nResponseStatus = 412;
    if (nt != "upnp:event" || nts != "upnp:propchange")
        return true;

    QString usn = pRequest->m_mapParams["usn"];
    QString sid = pRequest->m_mapHeaders["sid"];
    if (usn.isEmpty() || sid.isEmpty())
        return true;

    // N.B. Validating the usn and uuid here might mean blocking for some time
    // while waiting for a subscription to complete. While this operates in a
    // worker thread, worker threads are a limited resource which we could
    // rapidly overload if a number of events arrive. Instead let the
    // subscribing objects validate the usn - the uuid should be superfluous.

    QString seq = pRequest->m_mapHeaders["seq"];

    // mediatomb sends some extra character(s) at the end of the payload
    // which throw Qt, so try and trim them off
    int loc = pRequest->m_sPayload.lastIndexOf("propertyset>");
    QString payload = (loc > -1) ? pRequest->m_sPayload.left(loc + 12) :
                                   pRequest->m_sPayload;

    LOG(VB_UPNP, LOG_DEBUG, QString("Payload:\n%1").arg(payload));

    pRequest->m_nResponseStatus = 400;
    QDomDocument body;
    QString error;
    int errorCol = 0;
    int errorLine = 0;
    if (!body.setContent(payload, true, &error, &errorLine, &errorCol))
    {
        LOG(VB_GENERAL, LOG_ERR,
            QString("Failed to parse event: Line: %1 Col: %2 Error: '%3'")
            .arg(errorLine).arg(errorCol).arg(error));
        return true;
    }

    VERBOSE(VB_UPNP|VB_EXTRA, "/n/n" + body.toString(4) + "/n/n");

    QDomNodeList properties = body.elementsByTagName("property");
    QHash<QString,QString> results;

    // this deals with both one argument per property (compliant) and mutliple
    // arguments per property as sent by mediatomb
    for (int i = 0; i < properties.size(); i++)
    {
        QDomNodeList arguments = properties.at(i).childNodes();
        for (int j = 0; j < arguments.size(); j++)
        {
            QDomElement e = arguments.at(j).toElement();
            if (!e.isNull() && !e.text().isEmpty() && !e.tagName().isEmpty())
                results.insert(e.tagName(), e.text());
        }
    }

    // using MythObservable allows multiple objects to subscribe to the same
    // service but is less efficient from an eventing perspective, especially
    // if multiple objects are subscribing
    if (!results.isEmpty())
    {
        pRequest->m_nResponseStatus = 200;
        results.insert("usn", usn);
        results.insert("seq", seq);
        MythInfoMapEvent me("UPNP_EVENT", results);
        dispatch(me);
    }

    return true;
}
Пример #11
0
/// \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;
        }
    }
    const QString show = element.firstChildElement("show").text();
    for (int i = Online; i <= Invisible; i++) {
        if (show == presence_shows[i]) {
            d->availableStatusType = static_cast<AvailableStatusType>(i);
            break;
        }
    }
    d->statusText = element.firstChildElement("status").text();
    d->priority = element.firstChildElement("priority").text().toInt();

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