void MythCCExtractorPlayer::IngestSubtitle(
    QList<OneSubtitle> &list, const QStringList &content)
{
    bool update_last =
        !list.isEmpty() &&
        (int64_t)m_curTime == list.back().start_time &&
        !content.isEmpty();

    if (update_last)
    {
        //update text only (need for cc608)
        list.back().text = content;
        return;
    }

    OneSubtitle last_one = list.isEmpty() ? OneSubtitle() : list.back();
    if (content != last_one.text || last_one.length >= 0)
    {
        // Finish previous subtitle.
        if (!last_one.text.isEmpty() && last_one.length < 0)
        {
            list.back().length = (int64_t)m_curTime - last_one.start_time;
        }

        // Put new one if it isn't empty.
        if (!content.isEmpty())
        {
            OneSubtitle new_one;
            new_one.start_time = (int64_t)m_curTime;
            new_one.text = content;

            list.push_back(new_one);
        }
    }
}
/**
 * Adds new subtitle, finishes last if needed.
 * This is a version for DVB graphical subtitles only.
 * @param list Queue of subtitles we modify.
 * @param content Content of the new subtitle (may be empty).
 * We're going to use it's img & start_time fields.
 */
void MythCCExtractorPlayer::IngestSubtitle(
    QList<OneSubtitle> &list, const OneSubtitle &content)
{
    bool update_last =
        !list.isEmpty() &&
        content.start_time == list.back().start_time &&
        !content.img.isNull();

    if (update_last)
    {
        list.back().img = content.img; // update image only
        return;
    }

    OneSubtitle last_one = list.isEmpty() ? OneSubtitle() : list.back();
    if (content.img != last_one.img || last_one.length >= 0)
    {
        // Finish previous subtitle.
        if (!last_one.img.isNull() && last_one.length < 0)
        {
            list.back().length = content.start_time - last_one.start_time;
        }

        // Put new one if it isn't empty.
        if (!content.img.isNull())
        {
            OneSubtitle new_one;
            new_one.start_time = content.start_time;
            new_one.img = content.img;

            list.push_back(new_one);
        }
    }
}
Example #3
0
static void create_segments()
{
    segment.append(MidiSegment());

    segment[0].start = firstbeat; // Always start a segment at the very beginning of the piece (the first beat)
    for (int b = 0; b < num_sbeats; b++) {
        if (b == 0 && (sbeat[0].time - firstbeat) < ((sbeat[1].time-firstbeat) - (sbeat[0].time-firstbeat))/2)
            continue;
        /* If it's the first beat of the piece, and the upbeat is
           less than half of the first beat interval, don't start a segment
        */
        else {
            MidiSegment seg;
            seg.start          = sbeat[b].time;
            segment.back().end = sbeat[b].time;
            segment.append(seg);
        }
    }
    int s = segment.size() - 1;

    /* If final segment starts at or after final timepoint of piece, ignore it,
       decrementing number of segments by 1; if not, set that segment's ending
       to final timepoint of piece
       */
    if (segment[s].start >= final_timepoint) {
        s--;
    }
    else {
        segment[s].end = final_timepoint;
        /* qDebug("Final segment ends at %d", segment[s].end); */
    }
    segtotal = s; // index of final segment
}
Example #4
0
int
Splitter::getRightChildrenSize() const
{
    QList<int> list = sizes();
    assert(list.size() == 2);
    return list.back();
}
Example #5
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 #7
0
void make_branch( BillonTpl< arma::u8 > *initialSkel, const BillonTpl< arma::u8 > *reducedSkel, 
                  const BillonTpl< tlabel > *reducedLabeledSkel, QList< uint * > &touching ) {
	BillonTpl< arma::u8 >::iterator iterInitial = initialSkel->begin(),
	                                iterInitialEnd = initialSkel->end();
	                                
	BillonTpl< arma::u8 >::const_iterator iterReduced = reducedSkel->begin();
	
	/// step 1 : remove voxels that are activated in both images
	while( iterInitial != iterInitialEnd ) {
		if ( ( (*iterInitial) > 0 ) && ( (*iterReduced) > 0 ) ) {
			*iterInitial = 0 ;
		}
		iterInitial++ ;
		iterReduced++ ;
	}
	
	/// step 2 : identify voxels of the reduced label skeleton being adjacent to a voxel of a branch
	uint x,y,z,neighbor;
	for ( z = 0 ; z < reducedLabeledSkel->n_slices ; z++ )
		for ( y = 0 ; y < reducedLabeledSkel->n_rows ; y++ )
			for ( x = 0 ; x < reducedLabeledSkel->n_cols ; x++ ) {
				if ( (*reducedLabeledSkel)( y, x, z ) == 0 ) continue ;
				for ( neighbor = 0 ; neighbor < 27 ; neighbor++ )
					if ( ( y + (neighbor/9-1)) >= 0 		&& ( y + (neighbor/9-1)) < reducedSkel->n_rows &&
						 ( x + ( (neighbor%9)/3 -1 )) >= 0 	&& ( x + ( (neighbor%9)/3 -1 ))<reducedSkel->n_cols &&
						 ( z + ( neighbor % 3 -1 )) >= 0 	&& ( z + ( neighbor % 3 -1 ))<reducedSkel->n_slices ) {
						if ( (*initialSkel)( y + (neighbor/9-1), x + ( (neighbor%9)/3 -1 ), z + ( neighbor % 3 -1 ) ) ) {
							/// \note we do not update now initialSkel as we may get a side effect on the processing of the next voxels
							touching.append( new uint[3] ) ;
							touching.back()[ 0 ] = x ;
							touching.back()[ 1 ] = y ;
							touching.back()[ 2 ] = z ;
							assert( (*reducedLabeledSkel)( y + (neighbor/9-1), x + ( (neighbor%9)/3 -1 ), z + ( neighbor % 3 -1 ) ) == 0 ) ;
							break ;
						}
					}
			}
	/// step 3 : set active anew voxels being identified during the step 2
	QList< uint * >::ConstIterator voxelIter = touching.begin(),
	                               voxelEnd = touching.end() ;
	while ( voxelIter != voxelEnd ) {
		(*initialSkel)( (*voxelIter)[1], (*voxelIter)[0], (*voxelIter)[2] ) = 1 ;
		voxelIter++ ;
	}
}
Example #8
0
void SchematicScene::clearAllItems() {
  clearSelection();
  m_highlightedLinks.clear();
  QList<SchematicWindowEditor *> editors;
  QList<SchematicNode *> nodes;
  QList<SchematicLink *> links;
  int i;
  QList<QGraphicsItem *> sceneItems = items();
  int size                          = sceneItems.size();
  // create nodes and links list
  for (i = 0; i < size; i++) {
    QGraphicsItem *item           = sceneItems.at(i);
    SchematicWindowEditor *editor = dynamic_cast<SchematicWindowEditor *>(item);
    SchematicNode *node           = dynamic_cast<SchematicNode *>(item);
    SchematicLink *link           = dynamic_cast<SchematicLink *>(item);
    if (editor) editors.append(editor);
    if (node) nodes.append(node);
    if (link) links.append(link);
  }
  while (links.size() > 0) {
    SchematicLink *link = links.back();
    removeItem(link);
    links.removeLast();
    SchematicPort *startPort = link->getStartPort();
    SchematicPort *endPort   = link->getEndPort();
    if (startPort) startPort->removeLink(link);
    if (endPort) endPort->removeLink(link);
    delete link;
  }
  while (editors.size() > 0) {
    SchematicWindowEditor *editor = editors.back();
    removeItem(editor);
    editors.removeLast();
    delete editor;
  }
  while (nodes.size() > 0) {
    SchematicNode *node = nodes.back();
    removeItem(node);
    nodes.removeLast();
    delete node;
  }
  assert(items().size() == 0);
}
Example #9
0
/*! \brief Retrieves the episode data for a given series
    \param showDetail A ShowDetail object for which to retrieve an episode listing
    \return A QList of EpisodeDetail for the show requested
    \sa ShowDetail EpisodeDetail

    Using QNetworkAccessManager and QNetworkReply, a blocking connection is made
    to an XML service provider (in this case TVRage), for the episode listing of
    the show.
    Once the XML data is retrived, it is parsed with QXmlStreamReader and
    necessary EpisodeDetial objects are contructed and returned.
*/
QList< EpisodeDetail > ShowHolder::Fetch( ShowDetail const& showDetail )
{
    QEventLoop waitLoop;
    QNetworkAccessManager netManager;
    QNetworkReply* netReply = netManager.get( QNetworkRequest( QUrl( "http://services.tvrage.com/feeds/episode_list.php?sid=" + QString::number( showDetail.id ) ) ) );
    QObject::connect( netReply, SIGNAL( finished() ), &waitLoop, SLOT( quit() ) );
    waitLoop.exec();

    int currentSeason = 0;
    QList< EpisodeDetail > episodes;
    QXmlStreamReader xmlData;
    xmlData.addData( netReply->readAll() );

    while( !xmlData.atEnd() )
    {
        if( xmlData.readNextStartElement() )
        {
            if( xmlData.name() == "Special" )
                xmlData.skipCurrentElement();
            else if( xmlData.name() == "Season" )
                currentSeason = xmlData.attributes().value( "no" ).toString().toInt();
            else if( xmlData.name() == "episode" )
            {
                episodes.append( EpisodeDetail() );
                episodes.back().show = showDetail.name;
                episodes.back().season = currentSeason;
            }
            else if( xmlData.name() == "epnum" )
                episodes.back().show_episode = xmlData.readElementText().toInt();
            else if( xmlData.name() == "seasonnum" )
                episodes.back().episode = xmlData.readElementText().toInt();
            else if( xmlData.name() == "title" )
                episodes.back().title = xmlData.readElementText();
        }
    }

    netReply->deleteLater();

    qSort( episodes );

    return episodes;
}
Example #10
0
Highlight::Highlight(QString stringCode) {
	QList<QString> tokens = stringCode.split(" ");

	upperLeft[0] = tokens[0].toDouble();
	upperLeft[1] = tokens[1].toDouble();
	lowerRight[0] = tokens[2].toDouble();
	lowerRight[1] = tokens[3].toDouble();
	for (int i = 4; i < tokens.size() - 1; ++i)
		phoneIds.push_back(tokens[i]);
	value_ = tokens.back().toFloat();
}
Example #11
0
void WorkTabMgr::loadData(DataFileParser *file, bool closeOther)
{
    if(!file->seekToNextBlock("windowsInfo", 0))
        return;

    m_disable_window_close = true;

    startBatchOperation();

    int count = file->readVal<int>();

    if(!closeOther)
    {
        // use current window, if it is empty
        MainWindow *activeWin = dynamic_cast<MainWindow*>(qApp->activeWindow());
        if(activeWin && activeWin->onlyHomeTab())
        {
            activeWin->loadData(file);
            --count;
        }

        // create new windows
        for(int i = 0; i < count; ++i)
        {
            MainWindow *win = newWindow();
            win->loadData(file);
        }
    }
    else
    {
        QList<quint32> keys = m_windows.keys();
        while(count != m_windows.size())
        {
            if(count < m_windows.size())
            {
                m_windows[keys.back()]->close();
                m_windows.remove(keys.takeLast());
            }
            else
                newWindow();
        }

        for(WindowMap::iterator itr = m_windows.begin(); itr != m_windows.end(); ++itr)
            (*itr)->loadData(file);
    }

    m_disable_window_close = false;

    endBatchOperation();
}
Example #12
0
QList<QPainterPath> Path_Builder::build()
{
    if ( strokes.empty() )
        return QList<QPainterPath>();

    QList<QPainterPath> paths;

    foreach ( const container::value_type& ll, strokes )
    {
        if ( ll.empty() )
            continue;

        paths.push_back(QPainterPath());

        QPointF nextpoint = ll[0]->begin;

        paths.back().moveTo(nextpoint);

        foreach ( path_item::Line* stroke, ll )
        {
            stroke->add_to(true,paths.back());
            nextpoint = stroke->end;
        }
    }
Example #13
0
/*! \brief Searches for a given show name
    \param showName The show name to search for
    \return A QList of ShowDetail containing the show information of search results
    \sa ShowDetail

    Using QNetworkAccessManager and QNetworkReply, a blocking connection is made
    to an XML service provider (in this case TVRage), for the results of the user
    submitted search.
    Once the XML data is retrived, it is parsed with QXmlStreamReader and
    necessary ShowDetial objects are contructed and returned.
*/
QList< ShowDetail > ShowHolder::Search( QString const& showName )
{
    QEventLoop waitLoop;
    QNetworkAccessManager netManager;
    QNetworkReply* netReply = netManager.get( QNetworkRequest( QUrl( "http://services.tvrage.com/feeds/search.php?show=" + showName ) ) );
    QObject::connect( netReply, SIGNAL( finished() ), &waitLoop, SLOT( quit() ) );
    waitLoop.exec();

    QList< ShowDetail > results;
    QXmlStreamReader xmlData;
    xmlData.addData( netReply->readAll() );

    while( !xmlData.atEnd() )
    {
        if( xmlData.readNextStartElement() )
        {
            if( xmlData.name() == "show" )
                results.append( ShowDetail() );
            else if( xmlData.name() == "showid" )
                results.back().id = xmlData.readElementText().toInt();
            else if( xmlData.name() == "name" )
                results.back().name = xmlData.readElementText();
            else if( xmlData.name() == "started" )
                results.back().start = xmlData.readElementText();
            else if( xmlData.name() == "ended" )
                results.back().end = xmlData.readElementText();
            else if( xmlData.name() == "status" )
                results.back().status = xmlData.readElementText();
            else if( xmlData.name() == "genre" )
            {
                if( !results.back().genre.isEmpty() )
                    results.back().genre += "; ";
                results.back().genre += xmlData.readElementText();
            }
        }
    }

    netReply->deleteLater();

    return results;
}
Example #14
0
QList<Clip> Database::getClips(const QString &path)
{
    QSqlQuery q;
    int resource = getResource(path);
    if (resource < 0) {
        q.prepare(Q["insertResource"]);
        resource = _db->addResource(q, path).toInt();
    }
    q.prepare("SELECT c.id, c.type, c.data, c.clipdata, n.raw_text FROM clips AS c"
              " LEFT JOIN notes AS n ON c.id = n.id WHERE c.resource_id = ?");
    q.addBindValue(resource);
    q.exec();

    QList<Clip> clips;
    while (q.next()) {
        clips.push_back(Clip(q.value(0).toInt(), q.value(1).toString(),
                             q.value(2).toString(), q.value(3).toJsonObject()));
        clips.back().setRawText(q.value(4).toString());
    }
    return clips;
}
Example #15
0
int main(int argc, char *argv[])
{
	Q_INIT_RESOURCE(asebaqtabout);
	QApplication app(argc, argv);
	QCoreApplication::setOrganizationName(ASEBA_ORGANIZATION_NAME);
	QCoreApplication::setOrganizationDomain(ASEBA_ORGANIZATION_DOMAIN);
	app.setApplicationName("Playground");
	
	QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
	
	// Translation support
	QTranslator qtTranslator;
	qtTranslator.load("qt_" + QLocale::system().name());
	app.installTranslator(&qtTranslator);
	
	QTranslator translator;
	translator.load(QString(":/asebaplayground_") + QLocale::system().name());
	app.installTranslator(&translator);
	
	QTranslator aboutTranslator;
	aboutTranslator.load(QString(":/qtabout_") + QLocale::system().name());
	app.installTranslator(&aboutTranslator);
	
	// create document
	QDomDocument domDocument("aseba-playground");
	QString sceneFileName;
	
	// Get cmd line arguments
	bool ask = true;
	if (argc > 1)
	{
		sceneFileName = argv[1];
		ask = false;
	}
	
	// Try to load xml config file
	do
	{
		if (ask)
		{
			QString lastFileName = QSettings("EPFL-LSRO-Mobots", "Aseba Playground").value("last file").toString();
			sceneFileName = QFileDialog::getOpenFileName(0, app.tr("Open Scenario"), lastFileName, app.tr("playground scenario (*.playground)"));
		}
		ask = true;
		
		if (sceneFileName.isEmpty())
		{
			std::cerr << "You must specify a valid setup scenario on the command line or choose one in the file dialog." << std::endl;
			exit(1);
		}
		
		QFile file(sceneFileName);
		if (file.open(QIODevice::ReadOnly))
		{
			QString errorStr;
			int errorLine, errorColumn;
			if (!domDocument.setContent(&file, false, &errorStr, &errorLine, &errorColumn))
			{
				QMessageBox::information(0, "Aseba Playground",
										app.tr("Parse error at file %1, line %2, column %3:\n%4")
										.arg(sceneFileName)
										.arg(errorLine)
										.arg(errorColumn)
										.arg(errorStr));
			}
			else
			{
				QSettings("EPFL-LSRO-Mobots", "Aseba Playground").setValue("last file", sceneFileName);
				break;
			}
		}
	}
	while (true);
	
	// Scan for colors
	typedef QMap<QString, Enki::Color> ColorsMap;
	ColorsMap colorsMap;
	QDomElement colorE = domDocument.documentElement().firstChildElement("color");
	while (!colorE.isNull())
	{
		colorsMap[colorE.attribute("name")] = Enki::Color(
			colorE.attribute("r").toDouble(),
			colorE.attribute("g").toDouble(),
			colorE.attribute("b").toDouble()
		);
		
		colorE = colorE.nextSiblingElement ("color");
	}
	
	// Scan for areas
	typedef QMap<QString, Enki::Polygon> AreasMap;
	AreasMap areasMap;
	QDomElement areaE = domDocument.documentElement().firstChildElement("area");
	while (!areaE.isNull())
	{
		Enki::Polygon p;
		QDomElement pointE = areaE.firstChildElement("point");
		while (!pointE.isNull())
		{
			p.push_back(Enki::Point(
				pointE.attribute("x").toDouble(),
				pointE.attribute("y").toDouble()
			));
			pointE = pointE.nextSiblingElement ("point");
		}
		areasMap[areaE.attribute("name")] = p;
		areaE = areaE.nextSiblingElement ("area");
	}
	
	// Create the world
	QDomElement worldE = domDocument.documentElement().firstChildElement("world");
	Enki::Color worldColor(Enki::Color::gray);
	if (!colorsMap.contains(worldE.attribute("color")))
		std::cerr << "Warning, world walls color " << worldE.attribute("color").toStdString() << " undefined\n";
	else
		worldColor = colorsMap[worldE.attribute("color")];
	Enki::World::GroundTexture groundTexture;
	if (worldE.hasAttribute("groundTexture"))
	{
		const QString groundTextureFileName(QFileInfo(sceneFileName).absolutePath() + QDir::separator() + worldE.attribute("groundTexture"));
		QImage image(groundTextureFileName);
		if (!image.isNull())
		{
			// flip vertically as y-coordinate is inverted in an image
			image = image.mirrored();
			// convert to a specific format and copy the underlying data to Enki
			image = image.convertToFormat(QImage::Format_ARGB32);
			groundTexture.width = image.width();
			groundTexture.height = image.height();
			const uint32_t* imageData(reinterpret_cast<const uint32_t*>(image.constBits()));
			std::copy(imageData, imageData+image.width()*image.height(), std::back_inserter(groundTexture.data));
			// Note: this works in little endian, in big endian data should be swapped
		}
		else
		{
			qDebug() << "Could not load ground texture file named" << groundTextureFileName;
		}
	}
	Enki::World world(
		worldE.attribute("w").toDouble(),
		worldE.attribute("h").toDouble(),
		worldColor,
		groundTexture
	);
	
	// Create viewer
	Enki::PlaygroundViewer viewer(&world, worldE.attribute("energyScoringSystemEnabled", "false").toLower() == "true");
	if (Enki::simulatorEnvironment)
		qDebug() << "A simulator environment already exists, replacing";
	Enki::simulatorEnvironment.reset(new Enki::PlaygroundSimulatorEnvironment(sceneFileName, viewer));
	
	// Zeroconf support to advertise targets
#ifdef ZEROCONF_SUPPORT
	Aseba::QtZeroconf zeroconf;
#endif // ZEROCONF_SUPPORT
	
	// Scan for camera
	QDomElement cameraE = domDocument.documentElement().firstChildElement("camera");
	if (!cameraE.isNull())
	{
		const double largestDim(qMax(world.h, world.w));
		viewer.setCamera(
			QPointF(
				cameraE.attribute("x", QString::number(world.w / 2)).toDouble(),
				cameraE.attribute("y", QString::number(0)).toDouble()
			),
			cameraE.attribute("altitude", QString::number(0.85 * largestDim)).toDouble(),
			cameraE.attribute("yaw", QString::number(-M_PI/2)).toDouble(),
			cameraE.attribute("pitch", QString::number((3*M_PI)/8)).toDouble()
		);
	}
	
	// Scan for walls
	QDomElement wallE = domDocument.documentElement().firstChildElement("wall");
	while (!wallE.isNull())
	{
		Enki::PhysicalObject* wall = new Enki::PhysicalObject();
		if (!colorsMap.contains(wallE.attribute("color")))
			std::cerr << "Warning, color " << wallE.attribute("color").toStdString() << " undefined\n";
		else
			wall->setColor(colorsMap[wallE.attribute("color")]);
		wall->pos.x = wallE.attribute("x").toDouble();
		wall->pos.y = wallE.attribute("y").toDouble();
		wall->setRectangular(
			wallE.attribute("l1").toDouble(),
			wallE.attribute("l2").toDouble(),
			wallE.attribute("h").toDouble(),
			!wallE.attribute("mass").isNull() ? wallE.attribute("mass").toDouble() : -1 // normally -1 because immobile
		);
		if (! wallE.attribute("angle").isNull())
			wall->angle = wallE.attribute("angle").toDouble(); // radians
		world.addObject(wall);
		
		wallE  = wallE.nextSiblingElement ("wall");
	}
	
	// Scan for cylinders
	QDomElement cylinderE = domDocument.documentElement().firstChildElement("cylinder");
	while (!cylinderE.isNull())
	{
		Enki::PhysicalObject* cylinder = new Enki::PhysicalObject();
		if (!colorsMap.contains(cylinderE.attribute("color")))
			std::cerr << "Warning, color " << cylinderE.attribute("color").toStdString() << " undefined\n";
		else
			cylinder->setColor(colorsMap[cylinderE.attribute("color")]);
		cylinder->pos.x = cylinderE.attribute("x").toDouble();
		cylinder->pos.y = cylinderE.attribute("y").toDouble();
		cylinder->setCylindric(
			cylinderE.attribute("r").toDouble(), 
			cylinderE.attribute("h").toDouble(),
			!cylinderE.attribute("mass").isNull() ? cylinderE.attribute("mass").toDouble() : -1 // normally -1 because immobile
		);
		world.addObject(cylinder);
		
		cylinderE = cylinderE.nextSiblingElement("cylinder");
	}
	
	// Scan for feeders
	QDomElement feederE = domDocument.documentElement().firstChildElement("feeder");
	while (!feederE.isNull())
	{
		Enki::EPuckFeeder* feeder = new Enki::EPuckFeeder;
		feeder->pos.x = feederE.attribute("x").toDouble();
		feeder->pos.y = feederE.attribute("y").toDouble();
		world.addObject(feeder);
	
		feederE = feederE.nextSiblingElement ("feeder");
	}
	// TODO: if needed, custom color to feeder
	
	// Scan for doors
	typedef QMap<QString, Enki::SlidingDoor*> DoorsMap;
	DoorsMap doorsMap;
	QDomElement doorE = domDocument.documentElement().firstChildElement("door");
	while (!doorE.isNull())
	{
		Enki::SlidingDoor *door = new Enki::SlidingDoor(
			Enki::Point(
				doorE.attribute("closedX").toDouble(),
				doorE.attribute("closedY").toDouble()
			),
			Enki::Point(
				doorE.attribute("openedX").toDouble(),
				doorE.attribute("openedY").toDouble()
			),
			Enki::Point(
				doorE.attribute("l1").toDouble(),
				doorE.attribute("l2").toDouble()
			),
			doorE.attribute("h").toDouble(),
			doorE.attribute("moveDuration").toDouble()
		);
		if (!colorsMap.contains(doorE.attribute("color")))
			std::cerr << "Warning, door color " << doorE.attribute("color").toStdString() << " undefined\n";
		else
			door->setColor(colorsMap[doorE.attribute("color")]);
		doorsMap[doorE.attribute("name")] = door;
		world.addObject(door);
		
		doorE = doorE.nextSiblingElement ("door");
	}
	
	// Scan for activation, and link them with areas and doors
	QDomElement activationE = domDocument.documentElement().firstChildElement("activation");
	while (!activationE.isNull())
	{
		if (areasMap.find(activationE.attribute("area")) == areasMap.end())
		{
			std::cerr << "Warning, area " << activationE.attribute("area").toStdString() << " undefined\n";
			activationE = activationE.nextSiblingElement ("activation");
			continue;
		}
		
		if (doorsMap.find(activationE.attribute("door")) == doorsMap.end())
		{
			std::cerr << "Warning, door " << activationE.attribute("door").toStdString() << " undefined\n";
			activationE = activationE.nextSiblingElement ("activation");
			continue;
		}
		
		const Enki::Polygon& area = *areasMap.find(activationE.attribute("area"));
		Enki::Door* door = *doorsMap.find(activationE.attribute("door"));
		
		Enki::DoorButton* activation = new Enki::DoorButton(
			Enki::Point(
				activationE.attribute("x").toDouble(),
				activationE.attribute("y").toDouble()
			),
			Enki::Point(
				activationE.attribute("l1").toDouble(),
				activationE.attribute("l2").toDouble()
			),
			area,
			door
		);
		
		world.addObject(activation);
		
		activationE = activationE.nextSiblingElement ("activation");
	}
	
	// load all robots in one loop
	std::map<std::string, RobotType> robotTypes {
		{ "thymio2", { "Thymio II", createRobotSingleVMNode<Enki::DashelAsebaThymio2> } },
		{ "e-puck", { "E-Puck", createRobotSingleVMNode<Enki::DashelAsebaFeedableEPuck> } },
	};
	QDomElement robotE = domDocument.documentElement().firstChildElement("robot");
	unsigned asebaServerCount(0);
	while (!robotE.isNull())
	{
		const auto type(robotE.attribute("type", "thymio2"));
		auto typeIt(robotTypes.find(type.toStdString()));
		if (typeIt != robotTypes.end())
		{
			// retrieve informations
			const auto& cppTypeName(typeIt->second.prettyName);
			const auto qTypeName(QString::fromStdString(cppTypeName));
			auto& countOfThisType(typeIt->second.number);
			const auto qRobotNameRaw(robotE.attribute("name", QString("%1 %2").arg(qTypeName).arg(countOfThisType)));
			const auto qRobotNameFull(QObject::tr("%2 on %3").arg(qRobotNameRaw).arg(QHostInfo::localHostName()));
			const auto cppRobotName(qRobotNameFull.toStdString());
			const unsigned port(robotE.attribute("port", QString("%1").arg(ASEBA_DEFAULT_PORT+asebaServerCount)).toUInt());
			const int16_t nodeId(robotE.attribute("nodeId", "1").toInt());
			
			// create
			const auto& creator(typeIt->second.factory);
#ifdef ZEROCONF_SUPPORT
			auto robot(creator(zeroconf, port, cppRobotName, cppTypeName, nodeId));
#else // ZEROCONF_SUPPORT
			auto robot(creator(port, cppRobotName, cppTypeName, nodeId));
#endif // ZEROCONF_SUPPORT
			asebaServerCount++;
			countOfThisType++;
			
			// setup in the world
			robot->pos.x = robotE.attribute("x").toDouble();
			robot->pos.y = robotE.attribute("y").toDouble();
			robot->angle = robotE.attribute("angle").toDouble();
			world.addObject(robot);
			
			// log
			viewer.log(app.tr("New robot %0 of type %1 on port %2").arg(qRobotNameRaw).arg(qTypeName).arg(port), Qt::white);
		}
		else
			viewer.log("Error, unknown robot type " + type, Qt::red);
		
		robotE = robotE.nextSiblingElement ("robot");
	}
	
	// Scan for external processes
	QList<QProcess*> processes;
	QDomElement procssE(domDocument.documentElement().firstChildElement("process"));
	while (!procssE.isNull())
	{
		QString command(procssE.attribute("command"));
		// create process
		processes.push_back(new QProcess());
		processes.back()->setProcessChannelMode(QProcess::MergedChannels);
		// make sure it is killed when we close the window
		QObject::connect(processes.back(), SIGNAL(started()), &viewer, SLOT(processStarted()));
		QObject::connect(processes.back(), SIGNAL(error(QProcess::ProcessError)), &viewer, SLOT(processError(QProcess::ProcessError)));
		QObject::connect(processes.back(), SIGNAL(readyReadStandardOutput()), &viewer, SLOT(processReadyRead()));
		QObject::connect(processes.back(), SIGNAL(finished(int, QProcess::ExitStatus)), &viewer, SLOT(processFinished(int, QProcess::ExitStatus)));
		// check whether it is a relative command
		bool isRelative(false);
		if (!command.isEmpty() && command[0] == ':')
		{
			isRelative = true;
			command = command.mid(1);
		}
		// process the command into its components
		QStringList args(command.split(" ", QString::SkipEmptyParts));
		if (args.size() == 0)
		{
			viewer.log(app.tr("Missing program in command"), Qt::red);
		}
		else
		{
			const QString program(QDir::toNativeSeparators(args[0]));
			args.pop_front();
			if (isRelative)
				processes.back()->start(QCoreApplication::applicationDirPath() + QDir::separator() + program, args, QIODevice::ReadOnly);
			else
				processes.back()->start(program, args, QIODevice::ReadOnly);
		}
		procssE = procssE.nextSiblingElement("process");
	}
	
	// Show and run
	viewer.setWindowTitle(app.tr("Aseba Playground - Simulate your robots!"));
	viewer.show();
	
	// If D-Bus is used, register the viewer object
	#ifdef HAVE_DBUS
	new Enki::EnkiWorldInterface(&viewer);
	QDBusConnection::sessionBus().registerObject("/world", &viewer);
	QDBusConnection::sessionBus().registerService("ch.epfl.mobots.AsebaPlayground");
	#endif // HAVE_DBUS
	
	// Run the application
	const int exitValue(app.exec());
	
	// Stop and delete ongoing processes
	foreach(QProcess*process,processes)
	{
		process->terminate();
		if (!process->waitForFinished(1000))
			process->kill();
		delete process;
	}
Example #16
0
void FriendWidget::contextMenuEvent(QContextMenuEvent * event)
{
    if (!active)
        setBackgroundRole(QPalette::Highlight);

    installEventFilter(this); // Disable leave event.

    QPoint pos = event->globalPos();
    ToxId id = FriendList::findFriend(friendId)->getToxId();
    QString dir = Settings::getInstance().getAutoAcceptDir(id);
    QMenu menu;
    QAction* openChatWindow = nullptr;
    QAction* removeChatWindow = nullptr;

    ContentDialog* contentDialog = ContentDialog::getFriendDialog(friendId);
    bool notAlone = contentDialog != nullptr && contentDialog->chatroomWidgetCount() > 1;

    if (contentDialog == nullptr || notAlone)
        openChatWindow = menu.addAction(tr("Open chat in new window"));

    if (contentDialog != nullptr && contentDialog->hasFriendWidget(friendId, this))
        removeChatWindow = menu.addAction(tr("Remove chat from this window"));

    menu.addSeparator();
    QMenu* inviteMenu = menu.addMenu(tr("Invite to group","Menu to invite a friend to a groupchat"));
    QAction* newGroupAction = inviteMenu->addAction(tr("To new group"));
    inviteMenu->addSeparator();
    QMap<QAction*, Group*> groupActions;

    for (Group* group : GroupList::getAllGroups())
    {
        int maxNameLen = 30;
        QString name = group->getGroupWidget()->getName();
        if ( name.length() > maxNameLen )
        {
            name = name.left(maxNameLen).trimmed() + "..";
        }
        QAction* groupAction = inviteMenu->addAction(tr("Invite to group '%1'").arg(name));
        groupActions[groupAction] =  group;
    }

    int circleId = Settings::getInstance().getFriendCircleID(FriendList::findFriend(friendId)->getToxId());
    CircleWidget *circleWidget = CircleWidget::getFromID(circleId);

    QMenu* circleMenu = nullptr;
    QAction* newCircleAction = nullptr;
    QAction *removeCircleAction = nullptr;
    QMap<QAction*, int> circleActions;

    FriendListWidget *friendList;

    if (circleWidget == nullptr)
        friendList = qobject_cast<FriendListWidget*>(FriendList::findFriend(friendId)->getFriendWidget()->parentWidget());
    else
        friendList = qobject_cast<FriendListWidget*>(circleWidget->parentWidget());

    circleMenu = menu.addMenu(tr("Move to circle...", "Menu to move a friend into a different circle"));

    newCircleAction = circleMenu->addAction(tr("To new circle"));

    if (circleId != -1)
        removeCircleAction = circleMenu->addAction(tr("Remove from circle '%1'").arg(Settings::getInstance().getCircleName(circleId)));

    circleMenu->addSeparator();

    QList<QAction*> circleActionList;

    for (int i = 0; i < Settings::getInstance().getCircleCount(); ++i)
    {
        if (i != circleId)
        {
            circleActionList.push_back(new QAction(tr("Move  to circle \"%1\"").arg(Settings::getInstance().getCircleName(i)), circleMenu));
            circleActions[circleActionList.back()] = i;
        }
    }

    std::sort(circleActionList.begin(), circleActionList.end(), [](const QAction* lhs, const QAction* rhs) -> bool
    {
        QCollator collator;
        collator.setNumericMode(true);
        return collator.compare(lhs->text(), rhs->text()) < 0;
    });

    circleMenu->addActions(circleActionList);

    QAction* setAlias = menu.addAction(tr("Set alias..."));

    menu.addSeparator();
    QAction* autoAccept = menu.addAction(tr("Auto accept files from this friend", "context menu entry"));
    autoAccept->setCheckable(true);
    autoAccept->setChecked(!dir.isEmpty());
    menu.addSeparator();

    QAction* removeFriendAction = nullptr;

    if (contentDialog == nullptr || !contentDialog->hasFriendWidget(friendId, this))
        removeFriendAction = menu.addAction(tr("Remove friend", "Menu to remove the friend from our friendlist"));

    menu.addSeparator();
    QAction* aboutWindow = menu.addAction(tr("Show details"));

    QAction* selectedItem = menu.exec(pos);

    removeEventFilter(this);

    if (!active)
        setBackgroundRole(QPalette::Window);

    if (selectedItem)
    {
        if (selectedItem == setAlias)
        {
            nameLabel->editBegin();
        }
        else if (selectedItem == removeFriendAction)
        {
            emit removeFriend(friendId);
            return;
        }
        else if (selectedItem == openChatWindow)
        {
            emit chatroomWidgetClicked(this, true);
            return;
        }
        else if (selectedItem == removeChatWindow)
        {
            ContentDialog* contentDialog = ContentDialog::getFriendDialog(friendId);
            contentDialog->removeFriend(friendId);
            return;
        }
        else if (selectedItem == autoAccept)
        {
            if (!autoAccept->isChecked())
            {
                qDebug() << "not checked";
                dir = QDir::homePath();
                autoAccept->setChecked(false);
                Settings::getInstance().setAutoAcceptDir(id, "");
            }
            else if (autoAccept->isChecked())
            {
                dir = QFileDialog::getExistingDirectory(0,
                                                        tr("Choose an auto accept directory","popup title"),
                                                        dir,
                                                        QFileDialog::DontUseNativeDialog);
                autoAccept->setChecked(true);
                qDebug() << "setting auto accept dir for" << friendId << "to" << dir;
                Settings::getInstance().setAutoAcceptDir(id, dir);
            }
        }
        else if (selectedItem == aboutWindow)
        {
            AboutUser *aboutUser = new AboutUser(id, Widget::getInstance());
            aboutUser->setFriend(FriendList::findFriend(friendId));
            aboutUser->show();
        }
        else if (selectedItem == newGroupAction)
        {
            int groupId = Core::getInstance()->createGroup();
            Core::getInstance()->groupInviteFriend(friendId, groupId);
        }
        else if (selectedItem == newCircleAction)
        {
            if (circleWidget != nullptr)
                circleWidget->updateStatus();

            if (friendList != nullptr)
                friendList->addCircleWidget(FriendList::findFriend(friendId)->getFriendWidget());
            else
                Settings::getInstance().setFriendCircleID(id, Settings::getInstance().addCircle());
        }
        else if (groupActions.contains(selectedItem))
        {
            Group* group = groupActions[selectedItem];
            Core::getInstance()->groupInviteFriend(friendId, group->getGroupId());
        }
        else if (removeCircleAction != nullptr && selectedItem == removeCircleAction)
        {
            if (friendList != nullptr)
                friendList->moveWidget(FriendList::findFriend(friendId)->getFriendWidget(), FriendList::findFriend(friendId)->getStatus(), true);
            else
                Settings::getInstance().setFriendCircleID(id, -1);

            if (circleWidget)
            {
                circleWidget->updateStatus();
                Widget::getInstance()->searchCircle(circleWidget);
            }
        }
        else if (circleActions.contains(selectedItem))
        {
            CircleWidget* circle = CircleWidget::getFromID(circleActions[selectedItem]);

            if (circle != nullptr)
            {
                circle->addFriendWidget(FriendList::findFriend(friendId)->getFriendWidget(), FriendList::findFriend(friendId)->getStatus());
                circle->setExpanded(true);
                Widget::getInstance()->searchCircle(circle);
                Settings::getInstance().savePersonal();
            }
            else
                Settings::getInstance().setFriendCircleID(id, circleActions[selectedItem]);

            if (circleWidget != nullptr)
            {
                circleWidget->updateStatus();
                Widget::getInstance()->searchCircle(circleWidget);
            }
        }
    }
}
bool StartApplicationDialog::run(QWidget *parent, DebuggerStartParameters *sp)
{
    const bool attachRemote = sp->startMode == AttachToRemoteServer;
    const QString settingsGroup = QLatin1String("DebugMode");
    const QString arrayName = QLatin1String("StartApplication");

    QList<StartApplicationParameters> history;
    QSettings *settings = ICore::settings();
    settings->beginGroup(settingsGroup);
    if (const int arraySize = settings->beginReadArray(arrayName)) {
        for (int i = 0; i < arraySize; ++i) {
            settings->setArrayIndex(i);
            StartApplicationParameters p;
            p.fromSettings(settings);
            history.append(p);
        }
    } else {
        history.append(StartApplicationParameters());
    }
    settings->endArray();
    settings->endGroup();

    StartApplicationDialog dialog(parent);
    dialog.setHistory(history);
    dialog.setParameters(history.back());
    if (!attachRemote) {
        dialog.d->serverStartScriptPathChooser->setVisible(false);
        dialog.d->serverStartScriptLabel->setVisible(false);
        dialog.d->serverPortSpinBox->setVisible(false);
        dialog.d->serverPortLabel->setVisible(false);
        dialog.d->serverAddressLabel->setVisible(false);
        dialog.d->serverAddressEdit->setVisible(false);
    }
    if (dialog.exec() != QDialog::Accepted)
        return false;

    const StartApplicationParameters newParameters = dialog.parameters();
    if (newParameters != history.back()) {
        history.append(newParameters);
        while (history.size() > 10)
            history.takeFirst();
        settings->beginGroup(settingsGroup);
        settings->beginWriteArray(arrayName);
        for (int i = 0; i < history.size(); ++i) {
            settings->setArrayIndex(i);
            history.at(i).toSettings(settings);
        }
        settings->endArray();
        settings->endGroup();
    }

    Kit *kit = dialog.d->kitChooser->currentKit();
    QTC_ASSERT(kit, return false);
    bool res = DebuggerRunControlFactory::fillParametersFromKit(sp, kit);
    QTC_ASSERT(res, return false);

    sp->executable = newParameters.localExecutable;
    const QString inputAddress = dialog.d->serverAddressEdit->text();
    if (!inputAddress.isEmpty())
        sp->remoteChannel = inputAddress;
    else
        sp->remoteChannel = sp->connParams.host;
    sp->remoteChannel += QLatin1Char(':') + QString::number(newParameters.serverPort);
    sp->displayName = newParameters.displayName();
    sp->workingDirectory = newParameters.workingDirectory;
    sp->useTerminal = newParameters.runInTerminal;
    if (!newParameters.processArgs.isEmpty())
        sp->processArgs = newParameters.processArgs;
    sp->breakOnMain = newParameters.breakAtMain;
    sp->serverStartScript = newParameters.serverStartScript;
    sp->debugInfoLocation = newParameters.debugInfoLocation;

    IDevice::ConstPtr dev = DeviceKitInformation::device(kit);
    bool isLocal = !dev || (dev->type() == ProjectExplorer::Constants::DESKTOP_DEVICE_TYPE);
    if (!attachRemote)
        sp->startMode = isLocal ? StartExternal : StartRemoteProcess;
    return true;
}
Example #18
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;
}
Example #19
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 );
}