void SharesNavigatorTreeModel::setupModelData(const QStringList& lines, SharesNavigatorTreeItem* parent)
{
		QList<SharesNavigatorTreeItem*> parents;
		QList<int> indentations;
		parents << parent;
		indentations << 0;

		int number = 0;

		while(number < lines.count())
		{
				int position = 0;
				while(position < lines[number].length())
				{
						if(lines[number].mid(position, 1) != " ")
						{
								break;
						}
						position++;
				}

				QString lineData = lines[number].mid(position).trimmed();

				if(!lineData.isEmpty())
				{
						// Read the column data from the rest of the line.
						QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts);
						QList<QVariant> columnData;
						for(int column = 0; column < columnStrings.count(); ++column)
						{
								columnData << columnStrings[column];
						}

						if(position > indentations.last())
						{
								// The last child of the current parent is now the new parent
								// unless the current parent has no children.

								if(parents.last()->childCount() > 0)
								{
										parents << parents.last()->child(parents.last()->childCount() - 1);
										indentations << position;
								}
						}
						else
						{
								while(position < indentations.last() && parents.count() > 0)
								{
										parents.pop_back();
										indentations.pop_back();
								}
						}

						// Append a new item to the current parent's list of children.
						parents.last()->appendChild(new SharesNavigatorTreeItem(columnData, parents.last()));
				}

				number++;
		}
}
void TreeModel::setupModelData(const QStringList &lines, TreeItem *parent)
{
    QList<TreeItem*> parents;
    QList<int> indentations;
    parents << parent;
    indentations << 0;

    int number = 0;

    while (number < lines.count()) {
        int position = 0;
        while (position < lines[number].length()) {
            if (lines[number].mid(position, 1) != " ")
                break;
            position++;
        }

        QString lineData = lines[number].mid(position).trimmed();

        if (!lineData.isEmpty()) {
            // Read the column data from the rest of the line.
            QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts);
            QVector<QVariant> columnData;
            for (int column = 0; column < columnStrings.count(); ++column)
                columnData << columnStrings[column];

            if (position > indentations.last()) {
                // The last child of the current parent is now the new parent
                // unless the current parent has no children.

                if (parents.last()->childCount() > 0) {
                    parents << parents.last()->child(parents.last()->childCount()-1);
                    indentations << position;
                }
            } else {
                while (position < indentations.last() && parents.count() > 0) {
                    parents.pop_back();
                    indentations.pop_back();
                }
            }

            // Append a new item to the current parent's list of children.
            TreeItem *parent = parents.last();
            parent->insertChildren(parent->childCount(), 1, rootItem->columnCount());
            for (int column = 0; column < columnData.size(); ++column)
                parent->child(parent->childCount() - 1)->setData(column, columnData[column]);
        }

        number++;
    }
}
Example #3
0
QString huffdecoditication::TreeHuffmanDecodificationLeft(QString huff)
{
    QList<char> test;
    QString TreeHuffmanDecodificationLeft;
    if(huff.at(0).toLatin1()=='(')
    {
        test.push_back('(');
        for(int i=1;i<huff.size();i++)
        {
            if(huff.at(i).toLatin1()=='(' && huff.at(i-1).toLatin1()!='-')
            {
                test.push_back('(');
            }
            if(huff.at(i).toLatin1()==')' && huff.at(i-1).toLatin1()!='-')
            {
                test.pop_back();
            }
            if(test.isEmpty())
            {
                break;
            }
            TreeHuffmanDecodificationLeft.append(huff.at(i));
        }
    }
    else
    {
        TreeHuffmanDecodificationLeft=huff.at(0);
        if(huff.at(0).toLatin1()=='-')
        {
            TreeHuffmanDecodificationLeft=huff.at(1);
        }
    }

    return TreeHuffmanDecodificationLeft;
}
Example #4
0
bool ConnectionManager2::applyConfig(QVariant const & config)
{
    if (config.type() != QVariant::List)
        return false;

    QList<Connection *> newConns;
    struct cleanup
    {
        QList<Connection *> & conns;
        cleanup(QList<Connection *> & conns) : conns(conns) {}
        ~cleanup() { for (int i = 0; i < conns.size(); ++i) conns[i]->releaseAll(); }
    } cleanupGuard(newConns);

    QList<QVariant> const & connConfigs = config.toList();

    for (int i = 0; i < connConfigs.size(); ++i)
    {
        if (connConfigs[i].type() != QVariant::Hash)
            return false;
        QHash<QString, QVariant> const & connConfig = connConfigs[i].toHash();

        QVariant typev = connConfig.value("type");
        if (typev.type() != QVariant::String)
            return false;

        QString const & type = typev.toString();

        ConnectionPointer<Connection> conn;
        if (type == "serial_port")
            conn.reset(new SerialPort());
        else if (type == "tcp_client")
            conn.reset(new TcpSocket());
        else if (type == "udp_socket")
            conn.reset(new UdpSocket());
#ifdef HAVE_LIBYB
        else if (type == "usb_yb_acm")
            conn.reset(new UsbAcmConnection2(m_yb_runner));
#endif

        if (!conn)
            return false;

        QVariant settings = connConfig.value("settings");
        if (settings.type() != QVariant::Hash || !conn->applyConfig(settings.toHash()))
            return false;

        newConns.push_back(conn.data());
        conn.take();
    }

    this->clearUserOwnedConns();
    while (!newConns.empty())
    {
        this->addUserOwnedConn(newConns.back());
        newConns.pop_back();
    }

    return true;
}
static void cleanupEffectList(QList<QGLColladaFxEffect*> &effects)
{
    while(effects.count())
    {
        delete effects.back();
        effects.pop_back();
    }
}
Example #6
0
bool JsonParser::read( QIODevice* device )
{
    // Assert previous document got released.
    delete m_document;
    m_document = new GeoDataDocument;
    Q_ASSERT( m_document );

    // Read file data
    QJsonParseError error;
    const QJsonDocument jsonDoc = QJsonDocument::fromJson(device->readAll(), &error);

    if (jsonDoc.isNull()) {
        qDebug() << "Error parsing GeoJSON : " << error.errorString();
        return false;
    }

    // Start parsing
    const QJsonValue featuresValue = jsonDoc.object().value(QStringLiteral("features"));

    // In GeoJSON format, geometries are stored in features, so we iterate on features
    if (featuresValue.isArray()) {
        const QJsonArray featureArray = featuresValue.toArray();

        // Parse each feature
        for (int featureIndex = 0; featureIndex < featureArray.size(); ++featureIndex) {
            const QJsonObject featureObject = featureArray[featureIndex].toObject();

            // Check if the feature contains a geometry
            const QJsonValue geometryValue = featureObject.value(QStringLiteral("geometry"));
            if (geometryValue.isObject()) {
                const QJsonObject geometryObject = geometryValue.toObject();

                // Variables for creating the geometry
                QList<GeoDataGeometry*> geometryList;
                QList<GeoDataPlacemark*> placemarkList;

                // Create the different geometry types
                const QString geometryType = geometryObject.value(QStringLiteral("type")).toString().toUpper();

                if (geometryType == QLatin1String("POLYGON")) {
                    // Check first that there are coordinates
                    const QJsonValue coordinatesValue = geometryObject.value(QStringLiteral("coordinates"));
                    if (coordinatesValue.isArray()) {
                        const QJsonArray coordinateArray = coordinatesValue.toArray();

                        GeoDataPolygon * geom = new GeoDataPolygon( RespectLatitudeCircle | Tessellate );

                        // Coordinates first array will be the outer boundary, if there are more
                        // positions those will be inner holes
                        for (int ringIndex = 0 ; ringIndex < coordinateArray.size(); ++ringIndex) {
                            const QJsonArray ringArray = coordinateArray[ringIndex].toArray();

                            GeoDataLinearRing linearRing;

                            for (int coordinatePairIndex = 0; coordinatePairIndex < ringArray.size(); ++coordinatePairIndex) {
                                const QJsonArray coordinatePairArray = ringArray[coordinatePairIndex].toArray();

                                const qreal longitude = coordinatePairArray.at(0).toDouble();
                                const qreal latitude = coordinatePairArray.at(1).toDouble();

                                linearRing.append( GeoDataCoordinates( longitude , latitude , 0 , GeoDataCoordinates::Degree ) );
                            }

                            // Outer ring
                            if (ringIndex == 0) {
                                geom->setOuterBoundary( linearRing );
                            }
                            // Inner holes
                            else {
                                geom->appendInnerBoundary( linearRing );
                            }
                        }
                        geometryList.append( geom );
                    }

                } else if (geometryType == QLatin1String("MULTIPOLYGON")) {
                    // Check first that there are coordinates
                    const QJsonValue coordinatesValue = geometryObject.value(QStringLiteral("coordinates"));
                    if (coordinatesValue.isArray()) {
                        const QJsonArray coordinateArray = coordinatesValue.toArray();

                        for (int polygonIndex = 0; polygonIndex < coordinateArray.size(); ++polygonIndex) {
                            const QJsonArray polygonArray = coordinateArray[polygonIndex].toArray();

                            GeoDataPolygon * geom = new GeoDataPolygon( RespectLatitudeCircle | Tessellate );

                            // Coordinates first array will be the outer boundary, if there are more
                            // positions those will be inner holes
                            for (int ringIndex = 0 ; ringIndex < polygonArray.size(); ++ringIndex) {
                                const QJsonArray ringArray = polygonArray[ringIndex].toArray();

                                GeoDataLinearRing linearRing;

                                for (int coordinatePairIndex = 0; coordinatePairIndex < ringArray.size(); ++coordinatePairIndex) {
                                    const QJsonArray coordinatePairArray = ringArray[coordinatePairIndex].toArray();

                                    const qreal longitude = coordinatePairArray.at(0).toDouble();
                                    const qreal latitude = coordinatePairArray.at(1).toDouble();

                                    linearRing.append( GeoDataCoordinates( longitude , latitude , 0 , GeoDataCoordinates::Degree ) );
                                }

                                // Outer ring
                                if (ringIndex == 0) {
                                    geom->setOuterBoundary( linearRing );
                                }
                                // Inner holes
                                else {
                                    geom->appendInnerBoundary( linearRing );
                                }
                            }
                            geometryList.append( geom );
                        }
                    }

                } else if (geometryType == QLatin1String("LINESTRING")) {

                    // Check first that there are coordinates
                    const QJsonValue coordinatesValue = geometryObject.value(QStringLiteral("coordinates"));
                    if (coordinatesValue.isArray()) {
                        const QJsonArray coordinateArray = coordinatesValue.toArray();

                        GeoDataLineString * geom = new GeoDataLineString( RespectLatitudeCircle | Tessellate );

                        for (int coordinatePairIndex = 0; coordinatePairIndex < coordinateArray.size(); ++coordinatePairIndex) {
                            const QJsonArray coordinatePairArray = coordinateArray[coordinatePairIndex].toArray();

                            const qreal longitude = coordinatePairArray.at(0).toDouble();
                            const qreal latitude = coordinatePairArray.at(1).toDouble();

                            geom->append( GeoDataCoordinates( longitude , latitude , 0 , GeoDataCoordinates::Degree ) );
                        }
                        geometryList.append( geom );
                    }

                } else if (geometryType == QLatin1String("MULTILINESTRING")) {

                    // Check first that there are coordinates
                    const QJsonValue coordinatesValue = geometryObject.value(QStringLiteral("coordinates"));
                    if (coordinatesValue.isArray()) {
                        const QJsonArray coordinateArray = coordinatesValue.toArray();

                        for (int lineStringIndex = 0; lineStringIndex < coordinateArray.size(); ++lineStringIndex) {
                            const QJsonArray lineStringArray = coordinateArray[lineStringIndex].toArray();

                            GeoDataLineString * geom = new GeoDataLineString( RespectLatitudeCircle | Tessellate );

                            for (int coordinatePairIndex = 0; coordinatePairIndex < lineStringArray.size(); ++coordinatePairIndex) {
                                const QJsonArray coordinatePairArray = lineStringArray[coordinatePairIndex].toArray();

                                const qreal longitude = coordinatePairArray.at(0).toDouble();
                                const qreal latitude = coordinatePairArray.at(1).toDouble();

                                geom->append( GeoDataCoordinates( longitude , latitude , 0 , GeoDataCoordinates::Degree ) );
                            }
                            geometryList.append( geom );
                        }
                    }

                } else if (geometryType == QLatin1String("POINT")) {

                    // Check first that there are coordinates
                    const QJsonValue coordinatesValue = geometryObject.value(QStringLiteral("coordinates"));
                    if (coordinatesValue.isArray()) {
                        const QJsonArray coordinatePairArray = coordinatesValue.toArray();

                        GeoDataPoint * geom = new GeoDataPoint();

                        const qreal longitude = coordinatePairArray.at(0).toDouble();
                        const qreal latitude = coordinatePairArray.at(1).toDouble();

                        geom->setCoordinates( GeoDataCoordinates( longitude , latitude , 0 , GeoDataCoordinates::Degree ) );

                        geometryList.append( geom );
                    }
                } else if (geometryType == QLatin1String("MULTIPOINT")) {

                    // Check first that there are coordinates
                    const QJsonValue coordinatesValue = geometryObject.value(QStringLiteral("coordinates"));
                    if (coordinatesValue.isArray()) {
                        const QJsonArray coordinateArray = coordinatesValue.toArray();

                        for (int pointIndex = 0; pointIndex < coordinateArray.size(); ++pointIndex) {
                            const QJsonArray coordinatePairArray = coordinateArray[pointIndex].toArray();

                            GeoDataPoint * geom = new GeoDataPoint();

                            const qreal longitude = coordinatePairArray.at(0).toDouble();
                            const qreal latitude = coordinatePairArray.at(1).toDouble();

                            geom->setCoordinates( GeoDataCoordinates( longitude , latitude , 0 , GeoDataCoordinates::Degree ) );

                            geometryList.append( geom );
                        }
                    }
                }


                // Parse the features properties
                const QJsonValue propertiesValue = featureObject.value(QStringLiteral("properties"));
                if (!geometryList.isEmpty() && propertiesValue.isObject()) {
                    const QJsonObject propertiesObject = propertiesValue.toObject();

                    // First create a placemark for each geometry, there could be multi geometries
                    // that are translated into more than one geometry/placemark
                    for ( int numberGeometries = 0 ; numberGeometries < geometryList.length() ; numberGeometries++ ) {
                        GeoDataPlacemark * placemark = new GeoDataPlacemark();
                        placemarkList.append( placemark );
                    }

                    OsmPlacemarkData osmData;

                    QJsonObject::ConstIterator it = propertiesObject.begin();
                    const QJsonObject::ConstIterator end = propertiesObject.end();
                    for ( ; it != end; ++it) {
                        if (it.value().isObject() || it.value().isArray()) {
                            qDebug() << "Skipping property, values of type arrays and objects not supported:" << it.key();
                            continue;
                        }

                        // pass value through QVariant to also get bool & numbers
                        osmData.addTag(it.key(), it.value().toVariant().toString());
                    }

                    // If the property read, is the features name
                    const auto tagIter = osmData.findTag(QStringLiteral("name"));
                    if (tagIter != osmData.tagsEnd()) {
                        const QString& name = tagIter.value();
                        for (int pl = 0 ; pl < placemarkList.length(); ++pl) {
                            placemarkList.at(pl)->setName(name);
                        }
                    }

                    const GeoDataPlacemark::GeoDataVisualCategory category = StyleBuilder::determineVisualCategory(osmData);
                    if (category != GeoDataPlacemark::None) {
                        // Add the visual category to all the placemarks
                        for (int pl = 0 ; pl < placemarkList.length(); ++pl) {
                            placemarkList.at(pl)->setVisualCategory(category);
                            placemarkList.at(pl)->setOsmData(osmData);
                        }
                    }
                }

                // Add the geometry to the document
                if ( geometryList.length() == placemarkList.length() ) {

                    while( placemarkList.length() > 0 ) {

                        GeoDataPlacemark * placemark = placemarkList.last();
                        placemarkList.pop_back();

                        GeoDataGeometry * geom = geometryList.last();
                        geometryList.pop_back();

                        placemark->setGeometry( geom );
                        placemark->setVisible( true );
                        m_document->append( placemark );
                    }
                }

                // If geometries or placemarks missing inside the lists, delete them
                qDeleteAll( geometryList.begin(), geometryList.end() );
                geometryList.clear();
                qDeleteAll( placemarkList.begin(), placemarkList.end() );
                placemarkList.clear();
            }
        }
    }
    return true;
}
Example #7
0
File: gwc.cpp Project: c3c/quazaa
void CGWC::requestCompleted(QNetworkReply* pReply)
{
	QWriteLocker oGWCLock( &m_oRWLock );

	if ( !pReply || !isRunning() || !m_pRequest ) // we got cancelled while waiting for the lock
	{
		postLog( LogSeverity::Warning, QString( "The request got probably cancelled while " ) +
		         QString( "requestCompleted() was waiting for a lock on the service." ), true );

		resetRunning();

		if ( pReply )
			pReply->deleteLater();

		if ( m_pRequest )
		{
			delete m_pRequest;
			m_pRequest = NULL;
		}

		m_pNAMgr.clear();

		postLog( LogSeverity::Warning,
		         QString( "Finished cleanup after unusual termination." ),
		         true );

		return;
	}

	if ( pReply->request() != *m_pRequest )
	{
		return; // reply was meant for sb else
	}

	postLog( LogSeverity::Debug, tr( "Recieved answer from GWC." ) );

	// used for statistics update at a later time
	quint16 nHosts = 0;
	quint16 nURLs  = 0;

	bool bUpdateOK = false;     // in case we did update, was it successful?
	QList<QString>   lURLList;  // alternate services returned by the GWC
	QList<CEndPoint> lHostList; // hosts returned by the GWC

	if ( pReply->error() == QNetworkReply::NoError )
	{
		postLog( LogSeverity::Debug, tr( "Parsing GWC response:" ) );

		// get first piece of data from reply
		QString ln = pReply->readLine( 2048 );
		QString sWarning; // used for error messages/warnings the GWC might return

		// parse data
		while ( !ln.isEmpty() )
		{
			postLog( LogSeverity::Debug, QString( "Line: %1" ).arg( ln.replace( '\n', "" ) ) );

			QStringList lp = ln.split( "|" );
			if ( lp.size() > 1 )
			{
				if ( lp[0] == "I" || lp[0] == "i" )
				{
					if ( lp.size() > 2 )
					{
						if ( lp[1].toLower() == "pong" )
						{
							m_sPong = lp[2];
							if ( lp.size() > 3 )
							{
								QStringList lNetworks = lp[3].split( "-" );

								m_bGnutella = false;
								m_bG2       = false;

								for ( int i = 0; i < lNetworks.size(); ++i )
								{
									if ( !lNetworks[i].toLower().compare( "gnutella" ) )
									{
										m_bGnutella = true;
									}

									if ( !lNetworks[i].toLower().compare( "gnutella2" ) )
									{
										m_bG2       = true;
									}
								}
							}
							else
							{
								postLog( LogSeverity::Warning, "Skipped line.", true );
							}
						}
						else if ( lp[1].toLower() == "update" )
						{
							if ( lp[2].toLower() == "ok" )
							{
								bUpdateOK = true;
								if ( lp.size() > 4 && lp[3].toLower() == "warning" )
								{
									sWarning = lp[4];
								}
							}
							else if ( lp[2].toLower() == "warning" )
							{
								if ( lp.size() > 3 )
								{
									sWarning = lp[3];
								}
							}
							else
							{
								postLog( LogSeverity::Warning, "Skipped line.", true );
							}
						}
						else
						{
							postLog( LogSeverity::Warning, "Skipped line.", true );
						}
					}
					else
					{
						postLog( LogSeverity::Warning, "Skipped line.", true );
					}
				}
				else if ( lp[0] == "H" || lp[0] == "h" )
				{
					// found host
					lHostList.push_back( CEndPoint( lp[1] ) );
					++nHosts;
				}
				else if ( lp[0] == "U" || lp[0] == "u" )
				{
					// found URL
					lURLList.push_back( lp[1] );
					++nURLs;
				}
			}
			else
			{
				postLog( LogSeverity::Debug, tr( "Parsing error!" ) );
			}

			if ( !sWarning.isEmpty() )
			{
				if ( bUpdateOK )
				{
					postLog( LogSeverity::Warning, sWarning );
				}
				else
				{
					postLog( LogSeverity::Error, sWarning );
				}
			}

			// get next piece of data
			ln = pReply->readLine( 2048 );
		}
	}
	else
	{
		postLog( LogSeverity::Error,
		         tr( "Network error while querying GWC: " ) + pReply->errorString() );
	}

	// make sure all statistics and failure counters are updated
	updateStatistics( nHosts, nURLs, bUpdateOK );

	// clean up
	pReply->deleteLater();
	delete m_pRequest;
	m_pRequest = NULL;
	m_pNAMgr.clear();

	// make sure the service is not reported as running anymore
	resetRunning();

	TServiceType oServiceType = m_nServiceType;

	// finished accessing GWC variables
	oGWCLock.unlock();

	// add new services to manager
	while ( lURLList.size() )
	{
		discoveryManager.add( lURLList.back(), oServiceType, CNetworkType( dpG2 ) );
		lURLList.pop_back();
	}

	const quint32 tNow = common::getTNowUTC();

	// prepare for adding new hosts
	QMutexLocker l( &hostCache.m_pSection );

	while ( lHostList.size() )
	{
		hostCache.add( lHostList.back(), tNow );
		lHostList.pop_back();
	}

	postLog( LogSeverity::Debug,
	         QString( "Host Cache count after querying GWC: " ) +
	         QString::number( hostCache.count() ), true );
}
Example #8
0
QString Tools::htmlToText(const QString &html)
{
    QString text = htmlToParagraph(html);
    text.remove("\n");
    text.replace("</h1>", "\n");
    text.replace("</h2>", "\n");
    text.replace("</h3>", "\n");
    text.replace("</h4>", "\n");
    text.replace("</h5>", "\n");
    text.replace("</h6>", "\n");
    text.replace("</li>", "\n");
    text.replace("</dt>", "\n");
    text.replace("</dd>", "\n");
    text.replace("<dd>",  "   ");
    text.replace("</div>", "\n");
    text.replace("</blockquote>", "\n");
    text.replace("</caption>", "\n");
    text.replace("</tr>", "\n");
    text.replace("</th>", "  ");
    text.replace("</td>", "  ");
    text.replace("<br>",  "\n");
    text.replace("<br />", "\n");
    text.replace("</p>", "\n");
    // FIXME: Format <table> tags better, if possible
    // TODO: Replace &eacute; and co. by theire equivalent!

    // To manage tags:
    int pos = 0;
    int pos2;
    QString tag, tag3;
    // To manage lists:
    int deep = 0;            // The deep of the current line in imbriqued lists
    QList<bool> ul;    // true if current list is a <ul> one, false if it's an <ol> one
    QList<int>  lines; // The line number if it is an <ol> list
    // We're removing every other tags, or replace them in the case of li:
    while ((pos = text.indexOf("<"), pos) != -1) {
        // What is the current tag?
        tag  = text.mid(pos + 1, 2);
        tag3 = text.mid(pos + 1, 3);
        // Lists work:
        if (tag == "ul") {
            deep++;
            ul.push_back(true);
            lines.push_back(-1);
        } else if (tag == "ol") {
            deep++;
            ul.push_back(false);
            lines.push_back(0);
        } else if (tag3 == "/ul" || tag3 == "/ol") {
            deep--;
            ul.pop_back();
            lines.pop_back();
        }
        // Where the tag closes?
        pos2 = text.indexOf(">");
        if (pos2 != -1) {
            // Remove the tag:
            text.remove(pos, pos2 - pos + 1);
            // And replace li with "* ", "x. "... without forbidding to indent that:
            if (tag == "li") {
                // How many spaces before the line (indentation):
                QString spaces = "";
                for (int i = 1; i < deep; i++)
                    spaces += "  ";
                // The bullet or number of the line:
                QString bullet = "* ";
                if (ul.back() == false) {
                    lines.push_back(lines.back() + 1);
                    lines.pop_back();
                    bullet = QString::number(lines.back()) + ". ";
                }
                // Insertion:
                text.insert(pos, spaces + bullet);
            }
            if ((tag3 == "/ul" || tag3 == "/ol") && deep == 0)
                text.insert(pos, "\n"); // Empty line before and after a set of lists
        }
        ++pos;
    }

    text.replace("&gt;",   ">");
    text.replace("&lt;",   "<");
    text.replace("&quot;", "\"");
    text.replace("&nbsp;", " ");
    text.replace("&amp;",  "&"); // CONVERT IN LAST!!

    // HtmlContent produces "\n" for empty note
    if (text == "\n")
        text = "";

    return text;
}