Exemplo n.º 1
0
void FileSender::bytesWritten(qint64 bytes) {
    Q_UNUSED(bytes);

	if(!active)
		return;

	qint64 unsentBytes = fileSize - file->pos();

	if(unsentBytes == 0) {
		active = false;
		file->close();
		socket->close();
        QString data;
		emit progressUpdated(FM_Send, FO_Complete, type, &id, &peerId, &data);
		return;
	}

	qint64 bytesToSend = (bufferSize < unsentBytes) ? bufferSize : unsentBytes;
	qint64 bytesRead = file->read(buffer, bytesToSend);
	socket->write(buffer, bytesRead);

	if(file->pos() > milestone) {
		QString transferred = QString::number(file->pos());
		emit progressUpdated(FM_Send, FO_Progress, type, &id, &peerId, &transferred);
		milestone += mile;
	}
}
Exemplo n.º 2
0
NewsList::NewsList() : m_curAccount(0)
{
    m_ui.setupUi(this);
    m_ui.tableGroups->setModel(&m_model);
    m_ui.tableGroups->setColumnWidth(0, 150);
    m_ui.progressBar->setMaximum(0);
    m_ui.progressBar->setMinimum(0);
    m_ui.progressBar->setValue(0);
    m_ui.progressBar->setVisible(false);
    m_ui.actionRefresh->setShortcut(QKeySequence::Refresh);
    m_ui.actionRefresh->setEnabled(false);    
    m_ui.actionFavorite->setEnabled(false);
    m_ui.actionStop->setEnabled(false);    
    m_ui.chkShowEmpty->setChecked(false);

    const auto nameWidth = m_ui.tableGroups->columnWidth((int)app::NewsList::Columns::Name);
    m_ui.tableGroups->setColumnWidth((int)app::NewsList::Columns::Name, nameWidth * 3);
    m_ui.tableGroups->setColumnWidth((int)app::NewsList::Columns::Subscribed, 32);

    QObject::connect(app::g_accounts, SIGNAL(accountsUpdated()),
        this, SLOT(accountsUpdated()));

    QObject::connect(&m_model, SIGNAL(progressUpdated(quint32, quint32, quint32)),
        this, SLOT(progressUpdated(quint32, quint32, quint32)));
    QObject::connect(&m_model, SIGNAL(loadComplete(quint32)),
        this, SLOT(loadComplete(quint32)));
    QObject::connect(&m_model, SIGNAL(makeComplete(quint32)),
        this, SLOT(makeComplete(quint32)));
}
/*!
    Sets the \a status for the media transfer. Note that this method also
    sets the progress if status changes to MediaTransferInterface::TransferFinished.
    If status changes to MediaTransferInterface::TransferCanceled or
    MediaTransferInterface::TransferInterrupted, the progress is set to 0.

    This method emits statusChanged() and progressUpdated() signals automatically based
    on status changes and if this method marks progress to 1 or to 0.
*/
void MediaTransferInterface::setStatus(TransferStatus status)
{
    Q_D(MediaTransferInterface);

    // Make sure that progress is 1 if we are really finished
    if (status == MediaTransferInterface::TransferFinished &&
        d->m_prevProgress < 1 ) {
        d->m_progress = 1;
        d->m_prevProgress = 1;
        emit progressUpdated(1);
    }

    // Make sure that progress is set to 0 if transfer is canceled or
    // interrupted
    if (status == MediaTransferInterface::TransferCanceled ||
        status == MediaTransferInterface::TransferInterrupted) {
        d->m_progress = 0;
        d->m_prevProgress = 0;
        emit progressUpdated(0);
    }

    // And update the status
    if (d->m_status != status) {
        d->m_status = status;
        emit statusChanged(d->m_status);
    }

}
Exemplo n.º 4
0
void FileReceiver::timer_timeout(void) {
	if(!active)
		return;

	QString transferred = QString::number(file->pos());
	emit progressUpdated(FM_Receive, FO_Progress, type, &id, &peerId, &transferred);
}
Exemplo n.º 5
0
bool FileManager::loadObjectOldWay( Object* object, const QDomElement& root )
{
	return object->loadXML( root, [this]( float f )
	{
		emit progressUpdated( f );
	} );
}
Exemplo n.º 6
0
void PartialArchive::emitStatusEvents()
{
    updatePeerInfo();
    updateDownloadRate(downloadRate);
    emit progressUpdated(torrentClient != 0 ? torrentClient->progress() : -1);
    emit statusTextUpdated(torrentClient != 0 ? getStateText(torrentClient->state()) : "");
}
Exemplo n.º 7
0
void MeltJob::onReadyRead()
{
    QString msg;
    do {
        msg = readLine();
        int index = msg.indexOf("Frame:");
        if (index > -1) {
            index += 6;
            int comma = msg.indexOf(',', index);
            m_currentFrame = msg.mid(index, comma - index).toInt();
        }
        index = msg.indexOf("percentage:");
        if (index > -1) {
            int percent = msg.mid(index + 11).toInt();
            if (percent != m_previousPercent) {
                emit progressUpdated(m_item, percent);
                QCoreApplication::processEvents();
                m_previousPercent = percent;
            }
        }
        else {
            appendToLog(msg);
        }
    } while (!msg.isEmpty());
}
Exemplo n.º 8
0
QString TemplateLayout::generate()
{
	int progress = 0;
	int totalWork = getTotalWork(PrintOptions);
	QString templateName;

	QString htmlContent;
	m_engine = new Grantlee::Engine(this);

	QSharedPointer<Grantlee::FileSystemTemplateLoader> m_templateLoader =
		QSharedPointer<Grantlee::FileSystemTemplateLoader>(new Grantlee::FileSystemTemplateLoader());
	m_templateLoader->setTemplateDirs(QStringList() << getSubsurfaceDataPath("printing_templates"));
	m_engine->addTemplateLoader(m_templateLoader);

	Grantlee::registerMetaType<Dive>();
	Grantlee::registerMetaType<template_options>();
	Grantlee::registerMetaType<print_options>();

	QVariantHash mapping;
	QVariantList diveList;

	struct dive *dive;
	int i;
	for_each_dive (i, dive) {
		//TODO check for exporting selected dives only
		if (!dive->selected && PrintOptions->print_selected)
			continue;
		Dive d(dive);
		diveList.append(QVariant::fromValue(d));
		progress++;
		emit progressUpdated(progress * 100.0 / totalWork);
	}
	mapping.insert("dives", diveList);
	mapping.insert("template_options", QVariant::fromValue(*templateOptions));
	mapping.insert("print_options", QVariant::fromValue(*PrintOptions));

	Grantlee::Context c(mapping);

	if (PrintOptions->p_template == print_options::ONE_DIVE) {
		templateName = "one_dive.html";
	} else if (PrintOptions->p_template == print_options::TWO_DIVE) {
		templateName = "two_dives.html";
	} else if (PrintOptions->p_template == print_options::CUSTOM) {
		templateName = "custom.html";
	}
	Grantlee::Template t = m_engine->loadByName(templateName);
	if (!t || t->error()) {
		qDebug() << "Can't load template";
		return htmlContent;
	}

	htmlContent = t->render(&c);

	if (t->error()) {
		qDebug() << "Can't render template";
		return htmlContent;
	}
	return htmlContent;
}
Exemplo n.º 9
0
void MeltJob::onReadyRead()
{
    QString msg = readLine();
    if (msg.contains("percentage:")) {
        uint percent = msg.mid(msg.indexOf("percentage:") + 11).toUInt();
        emit progressUpdated(m_index, percent);
    }
    else {
        appendToLog(msg);
    }
}
Exemplo n.º 10
0
void FileReceiver::readyRead(void) {
	if(!active)
		return;

	qint64 bytesReceived = socket->read(buffer, bufferSize);
	file->write(buffer, bytesReceived);

	qint64 unreceivedBytes = fileSize - file->pos();
	if(unreceivedBytes == 0) {
		active = false;
		file->close();
		socket->close();
		emit progressUpdated(FM_Receive, FO_Complete, type, &id, &peerId, &filePath);
		return;
	}

	if(file->pos() > milestone) {
		QString transferred = QString::number(file->pos());
		emit progressUpdated(FM_Receive, FO_Progress, type, &id, &peerId, &transferred);
		milestone += mile;
	}
}
Exemplo n.º 11
0
void LatticeFitter::findBestLattice(const std::vector<cv::Point2f>& points)
{
  emit latticeFittingStarted();
  emit progressUpdated(0);

  std::vector<Lattice> bestLattices;

  double progress = 0.0;
  double progress_delta = 100.0 / points.size();

  for (const auto& p : points) {
    bestLattices.emplace_back(bestLatticeForOrigin(p, points));
    progress += progress_delta;
    emit progressUpdated(static_cast<int>(std::round(progress)));
  }

  best_lattice = *std::min_element(bestLattices.cbegin(), bestLattices.cend(),
  [](const Lattice& l1, const Lattice& l2) {
    return l1.total_error < l2.total_error;
  });

  emit foundBestLattice(best_lattice);
}
Exemplo n.º 12
0
void QgsOfflineEditing::applyGeometryChanges( QgsVectorLayer* remoteLayer, sqlite3* db, int layerId, int commitNo )
{
  QString sql = QString( "SELECT \"fid\", \"geom_wkt\" FROM 'log_geometry_updates' WHERE \"layer_id\" = %1 AND \"commit_no\" = %2" ).arg( layerId ).arg( commitNo );
  GeometryChanges values = sqlQueryGeometryChanges( db, sql );

  emit progressModeSet( QgsOfflineEditing::UpdateGeometries, values.size() );

  for ( int i = 0; i < values.size(); i++ )
  {
    QgsFeatureId fid = remoteFid( db, layerId, values.at( i ).fid );
    remoteLayer->changeGeometry( fid, QgsGeometry::fromWkt( values.at( i ).geom_wkt ) );

    emit progressUpdated( i + 1 );
  }
}
Exemplo n.º 13
0
QString TemplateLayout::generate()
{
	int progress = 0;
	int totalWork = getTotalWork(PrintOptions);

	QString htmlContent;
	delete m_engine;
	m_engine = new Grantlee::Engine(this);

	QSharedPointer<Grantlee::FileSystemTemplateLoader> m_templateLoader =
		QSharedPointer<Grantlee::FileSystemTemplateLoader>(new Grantlee::FileSystemTemplateLoader());
	m_templateLoader->setTemplateDirs(QStringList() << getPrintingTemplatePathUser());
	m_engine->addTemplateLoader(m_templateLoader);

	Grantlee::registerMetaType<template_options>();
	Grantlee::registerMetaType<print_options>();

	QVariantList diveList;

	struct dive *dive;
	int i;
	for_each_dive (i, dive) {
		//TODO check for exporting selected dives only
		if (!dive->selected && PrintOptions->print_selected)
			continue;
		DiveObjectHelper *d = new DiveObjectHelper(dive);
		diveList.append(QVariant::fromValue(d));
		progress++;
		emit progressUpdated(progress * 100.0 / totalWork);
	}
	Grantlee::Context c;
	c.insert("dives", diveList);
	c.insert("template_options", QVariant::fromValue(*templateOptions));
	c.insert("print_options", QVariant::fromValue(*PrintOptions));

	Grantlee::Template t = m_engine->loadByName(PrintOptions->p_template);
	if (!t || t->error()) {
		qDebug() << "Can't load template";
		return htmlContent;
	}

	htmlContent = t->render(&c);

	if (t->error()) {
		qDebug() << "Can't render template";
	}
	return htmlContent;
}
Exemplo n.º 14
0
void QgsOfflineEditing::applyFeaturesRemoved( QgsVectorLayer* remoteLayer, sqlite3* db, int layerId )
{
  QString sql = QString( "SELECT \"fid\" FROM 'log_removed_features' WHERE \"layer_id\" = %1" ).arg( layerId );
  QgsFeatureIds values = sqlQueryFeaturesRemoved( db, sql );

  emit progressModeSet( QgsOfflineEditing::RemoveFeatures, values.size() );

  int i = 1;
  for ( QgsFeatureIds::const_iterator it = values.begin(); it != values.end(); ++it )
  {
    QgsFeatureId fid = remoteFid( db, layerId, *it );
    remoteLayer->deleteFeature( fid );

    emit progressUpdated( i++ );
  }
}
Exemplo n.º 15
0
QString TemplateLayout::generate()
{
	int progress = 0;
	int totalWork = getTotalWork(PrintOptions);

	QString htmlContent;
	delete m_engine;
	m_engine = new Grantlee::Engine(this);
	Grantlee::registerMetaType<template_options>();
	Grantlee::registerMetaType<print_options>();

	QVariantList diveList;

	struct dive *dive;
	int i;
	for_each_dive (i, dive) {
		//TODO check for exporting selected dives only
		if (!dive->selected && PrintOptions->print_selected)
			continue;
		DiveObjectHelper *d = new DiveObjectHelper(dive);
		diveList.append(QVariant::fromValue(d));
		progress++;
		emit progressUpdated(lrint(progress * 100.0 / totalWork));
	}
	Grantlee::Context c;
	c.insert("dives", diveList);
	c.insert("template_options", QVariant::fromValue(*templateOptions));
	c.insert("print_options", QVariant::fromValue(*PrintOptions));

	/* don't use the Grantlee loader API */
	QString templateContents = readTemplate(PrintOptions->p_template);
	QString preprocessed = preprocessTemplate(templateContents);

	/* create the template from QString; is this thing allocating memory? */
	Grantlee::Template t = m_engine->newTemplate(preprocessed, PrintOptions->p_template);
	if (!t || t->error()) {
		qDebug() << "Can't load template";
		return htmlContent;
	}

	htmlContent = t->render(&c);

	if (t->error()) {
		qDebug() << "Can't render template";
	}
	return htmlContent;
}
Exemplo n.º 16
0
QString TemplateLayout::generateStatistics()
{
	QString htmlContent;
	delete m_engine;
	m_engine = new Grantlee::Engine(this);

	QSharedPointer<Grantlee::FileSystemTemplateLoader> m_templateLoader =
		QSharedPointer<Grantlee::FileSystemTemplateLoader>(new Grantlee::FileSystemTemplateLoader());
	m_templateLoader->setTemplateDirs(QStringList() << getPrintingTemplatePathUser() + QDir::separator() + QString("statistics"));
	m_engine->addTemplateLoader(m_templateLoader);

	Grantlee::registerMetaType<YearInfo>();
	Grantlee::registerMetaType<template_options>();
	Grantlee::registerMetaType<print_options>();

	QVariantList years;

	int i = 0;
	while (stats_yearly != NULL && stats_yearly[i].period) {
		YearInfo year(stats_yearly[i]);
		years.append(QVariant::fromValue(year));
		i++;
	}

	Grantlee::Context c;
	c.insert("years", years);
	c.insert("template_options", QVariant::fromValue(*templateOptions));
	c.insert("print_options", QVariant::fromValue(*PrintOptions));

	Grantlee::Template t = m_engine->loadByName(PrintOptions->p_template);
	if (!t || t->error()) {
		qDebug() << "Can't load template";
		return htmlContent;
	}

	htmlContent = t->render(&c);

	if (t->error()) {
		qDebug() << "Can't render template";
		return htmlContent;
	}

	emit progressUpdated(100);
	return htmlContent;
}
Exemplo n.º 17
0
void QgsOfflineEditing::updateFidLookup( QgsVectorLayer* remoteLayer, sqlite3* db, int layerId )
{
  // update fid lookup for added features

  // get remote added fids
  // NOTE: use QMap for sorted fids
  QMap < QgsFeatureId, bool /*dummy*/ > newRemoteFids;
  QgsFeature f;

  QgsFeatureIterator fit = remoteLayer->getFeatures( QgsFeatureRequest().setFlags( QgsFeatureRequest::NoGeometry ).setSubsetOfAttributes( QgsAttributeList() ) );

  emit progressModeSet( QgsOfflineEditing::ProcessFeatures, remoteLayer->featureCount() );

  int i = 1;
  while ( fit.nextFeature( f ) )
  {
    if ( offlineFid( db, layerId, f.id() ) == -1 )
    {
      newRemoteFids[ f.id()] = true;
    }

    emit progressUpdated( i++ );
  }

  // get local added fids
  // NOTE: fids are sorted
  QString sql = QString( "SELECT \"fid\" FROM 'log_added_features' WHERE \"layer_id\" = %1" ).arg( layerId );
  QList<int> newOfflineFids = sqlQueryInts( db, sql );

  if ( newRemoteFids.size() != newOfflineFids.size() )
  {
    //showWarning( QString( "Different number of new features on offline layer (%1) and remote layer (%2)" ).arg(newOfflineFids.size()).arg(newRemoteFids.size()) );
  }
  else
  {
    // add new fid lookups
    i = 0;
    sqlExec( db, "BEGIN" );
    for ( QMap<QgsFeatureId, bool>::const_iterator it = newRemoteFids.begin(); it != newRemoteFids.end(); ++it )
    {
      addFidLookup( db, layerId, newOfflineFids.at( i++ ), it.key() );
    }
    sqlExec( db, "COMMIT" );
  }
}
Exemplo n.º 18
0
void QgsOfflineEditing::applyAttributeValueChanges( QgsVectorLayer* offlineLayer, QgsVectorLayer* remoteLayer, sqlite3* db, int layerId, int commitNo )
{
  QString sql = QString( "SELECT \"fid\", \"attr\", \"value\" FROM 'log_feature_updates' WHERE \"layer_id\" = %1 AND \"commit_no\" = %2 " ).arg( layerId ).arg( commitNo );
  AttributeValueChanges values = sqlQueryAttributeValueChanges( db, sql );

  emit progressModeSet( QgsOfflineEditing::UpdateFeatures, values.size() );

  QMap<int, int> attrLookup = attributeLookup( offlineLayer, remoteLayer );

  for ( int i = 0; i < values.size(); i++ )
  {
    QgsFeatureId fid = remoteFid( db, layerId, values.at( i ).fid );

    remoteLayer->changeAttributeValue( fid, attrLookup[ values.at( i ).attr ], values.at( i ).value, false );

    emit progressUpdated( i + 1 );
  }
}
Exemplo n.º 19
0
QStringList Pipeline::RunTaskList(const QList<Task*>& taskList)
{
	errors.clear();

	emit progressUpdated(0);

	for(Task* task : taskList)
	{
		QString error = CheckTask(task);

		if(error.isNull()) RunTask(task);
		else errors.push_back(ERROR_MASK.arg(task->name).arg(error));
	}

	curStages = 0;

	return errors;
}
Exemplo n.º 20
0
void FileReceiver::receiveFile(void) {
	QDir dir = QFileInfo(filePath).dir();
	if(!dir.exists())
		dir.mkpath(dir.absolutePath());

	file = new QFile(filePath);

	if(file->open(QIODevice::WriteOnly)) {
		buffer = new char[bufferSize];
		active = true;

		timer = new QTimer(this);
		connect(timer, SIGNAL(timeout()), this, SLOT(timer_timeout()));
		timer->start(timeout);
	} else {
		socket->close();
		emit progressUpdated(FM_Receive, FO_Error, type, &id, &peerId, &filePath);
	}
}
Exemplo n.º 21
0
void QgsOfflineEditing::applyFeaturesAdded( QgsVectorLayer* offlineLayer, QgsVectorLayer* remoteLayer, sqlite3* db, int layerId )
{
  QString sql = QString( "SELECT \"fid\" FROM 'log_added_features' WHERE \"layer_id\" = %1" ).arg( layerId );
  QList<int> newFeatureIds = sqlQueryInts( db, sql );

  // get new features from offline layer
  QgsFeatureList features;
  for ( int i = 0; i < newFeatureIds.size(); i++ )
  {
    QgsFeature feature;
    if ( offlineLayer->getFeatures( QgsFeatureRequest().setFilterFid( newFeatureIds.at( i ) ) ).nextFeature( feature ) )
    {
      features << feature;
    }
  }

  // copy features to remote layer
  emit progressModeSet( QgsOfflineEditing::AddFeatures, features.size() );

  int i = 1;
  int newAttrsCount = remoteLayer->pendingFields().count();
  for ( QgsFeatureList::iterator it = features.begin(); it != features.end(); ++it )
  {
    QgsFeature f = *it;

    // NOTE: Spatialite provider ignores position of geometry column
    // restore gap in QgsAttributeMap if geometry column is not last (WORKAROUND)
    QMap<int, int> attrLookup = attributeLookup( offlineLayer, remoteLayer );
    QgsAttributes newAttrs( newAttrsCount );
    QgsAttributes attrs = f.attributes();
    for ( int it = 0; it < attrs.count(); ++it )
    {
      newAttrs[ attrLookup[ it ] ] = attrs[ it ];
    }
    f.setAttributes( newAttrs );

    remoteLayer->addFeature( f, false );

    emit progressUpdated( i++ );
  }
}
/*!
    Set the \a progress for the on going media transfer.

    Note that progressUpdated() signal might not be emitted in every call of this method
    because it might pollute dbus if progress changes too many times.
 */
void MediaTransferInterface::setProgress(qreal progress)
{
    Q_D(MediaTransferInterface);
    if (progress < 0 || 1 < progress) {
        qWarning() << "MediaTransferInterface::setProgress: progress must be in between 0 and 1";
        // Just show the warning and let the progress update. Sometimes there might be some
        // decimals which may not match exactly with 1, like 1.0001
    }

    if (d->m_progress == progress) {
        return;
    }

    d->m_progress = progress;

    // To avoid dbus overload let's not emit this signal in every progress change
    if (qAbs(d->m_progress - d->m_prevProgress) >= PROGRESS_THRESHOLD) {
        emit progressUpdated(progress);
        d->m_prevProgress = progress;
    }
}
Exemplo n.º 23
0
void FileSender::sendFile(void) {
	file = new QFile(filePath);

	if(file->open(QIODevice::ReadOnly)) {
		buffer = new char[bufferSize];
		active = true;

		timer = new QTimer(this);
		connect(timer, SIGNAL(timeout()), this, SLOT(timer_timeout()));
		timer->start(timeout);

		qint64 unsentBytes = fileSize - file->pos();
		qint64 bytesToSend = (bufferSize < unsentBytes) ? bufferSize : unsentBytes;
		qint64 bytesRead = file->read(buffer, bytesToSend);
		socket->write(buffer, bytesRead);
	} else {
		socket->close();
        QString data;
		emit progressUpdated(FM_Send, FO_Error, type, &id, &peerId, &data);
	}
}
Exemplo n.º 24
0
bool FileManager::loadObject( Object* object, const QDomElement& root )
{
    QDomElement e = root.firstChildElement( "object" );
    if ( e.isNull() )
    {
        return false;
    }
    
    bool isOK = true;
    for ( QDomNode node = root.firstChild(); !node.isNull(); node = node.nextSibling() )
    {
        QDomElement element = node.toElement(); // try to convert the node to an element.
        if ( element.isNull() )
        { 
            continue;
        }

        if ( element.tagName() == "object" )
        {
            qCDebug( mLog ) << "Load object";
			isOK = object->loadXML( element, [this] ( float f )
			{
				emit progressUpdated( f );
			} );
        }
        else if ( element.tagName() == "editor" )
        {
            ObjectData* editorData = loadEditorState( element );
            object->setData( editorData );
        }
        else
        {
            Q_ASSERT( false );
        }
        //progress = std::min( progress + 10, 100 );
        //emit progressValueChanged( progress );
    }

    return isOK;
}
Exemplo n.º 25
0
void QgsOfflineEditing::applyAttributesAdded( QgsVectorLayer* remoteLayer, sqlite3* db, int layerId, int commitNo )
{
  QString sql = QString( "SELECT \"name\", \"type\", \"length\", \"precision\", \"comment\" FROM 'log_added_attrs' WHERE \"layer_id\" = %1 AND \"commit_no\" = %2" ).arg( layerId ).arg( commitNo );
  QList<QgsField> fields = sqlQueryAttributesAdded( db, sql );

  const QgsVectorDataProvider* provider = remoteLayer->dataProvider();
  QList<QgsVectorDataProvider::NativeType> nativeTypes = provider->nativeTypes();

  // NOTE: uses last matching QVariant::Type of nativeTypes
  QMap < QVariant::Type, QString /*typeName*/ > typeNameLookup;
  for ( int i = 0; i < nativeTypes.size(); i++ )
  {
    QgsVectorDataProvider::NativeType nativeType = nativeTypes.at( i );
    typeNameLookup[ nativeType.mType ] = nativeType.mTypeName;
  }

  emit progressModeSet( QgsOfflineEditing::AddFields, fields.size() );

  for ( int i = 0; i < fields.size(); i++ )
  {
    // lookup typename from layer provider
    QgsField field = fields[i];
    if ( typeNameLookup.contains( field.type() ) )
    {
      QString typeName = typeNameLookup[ field.type()];
      field.setTypeName( typeName );
      remoteLayer->addAttribute( field );
    }
    else
    {
      showWarning( QString( "Could not add attribute '%1' of type %2" ).arg( field.name() ).arg( field.type() ) );
    }

    emit progressUpdated( i + 1 );
  }
}
Exemplo n.º 26
0
/*!
 * This slot handles the current progress of a job being updated by emitting an
 * appropriate signal.
 *
 * \param p The new current progress of the current job.
 */
void CSCollectionTypeResolver::doProgressUpdated(int p)
{ /* SLOT */

	Q_EMIT progressUpdated(p);

}
Exemplo n.º 27
0
void Pipeline::UpdateProgress()
{
	curStages++;
	emit progressUpdated(curStages / (float)totalStages);
}
Exemplo n.º 28
0
void FileReceiver::disconnected(void) {
	if(active) {
		QString data;
		emit progressUpdated(FM_Receive, FO_Error, type, &id, &peerId, &data);
	}
}
Exemplo n.º 29
0
void QgsOfflineEditing::copyVectorLayer( QgsVectorLayer* layer, sqlite3* db, const QString& offlineDbPath )
{
  if ( layer == NULL )
  {
    return;
  }

  QString tableName = layer->name();

  // create table
  QString sql = QString( "CREATE TABLE '%1' (" ).arg( tableName );
  QString delim = "";
  const QgsFields& fields = layer->dataProvider()->fields();
  for ( int idx = 0; idx < fields.count(); ++idx )
  {
    QString dataType = "";
    QVariant::Type type = fields[idx].type();
    if ( type == QVariant::Int )
    {
      dataType = "INTEGER";
    }
    else if ( type == QVariant::Double )
    {
      dataType = "REAL";
    }
    else if ( type == QVariant::String )
    {
      dataType = "TEXT";
    }
    else
    {
      showWarning( tr( "Unknown data type %1" ).arg( type ) );
    }

    sql += delim + QString( "'%1' %2" ).arg( fields[idx].name() ).arg( dataType );
    delim = ",";
  }
  sql += ")";

  // add geometry column
  QString geomType = "";
  switch ( layer->wkbType() )
  {
    case QGis::WKBPoint:
      geomType = "POINT";
      break;
    case QGis::WKBMultiPoint:
      geomType = "MULTIPOINT";
      break;
    case QGis::WKBLineString:
      geomType = "LINESTRING";
      break;
    case QGis::WKBMultiLineString:
      geomType = "MULTILINESTRING";
      break;
    case QGis::WKBPolygon:
      geomType = "POLYGON";
      break;
    case QGis::WKBMultiPolygon:
      geomType = "MULTIPOLYGON";
      break;
    default:
      showWarning( tr( "QGIS wkbType %1 not supported" ).arg( layer->wkbType() ) );
      break;
  };
  QString sqlAddGeom = QString( "SELECT AddGeometryColumn('%1', 'Geometry', %2, '%3', 2)" )
                       .arg( tableName )
                       .arg( layer->crs().authid().startsWith( "EPSG:", Qt::CaseInsensitive ) ? layer->crs().authid().mid( 5 ).toLong() : 0 )
                       .arg( geomType );

  // create spatial index
  QString sqlCreateIndex = QString( "SELECT CreateSpatialIndex('%1', 'Geometry')" ).arg( tableName );

  int rc = sqlExec( db, sql );
  if ( rc == SQLITE_OK )
  {
    rc = sqlExec( db, sqlAddGeom );
    if ( rc == SQLITE_OK )
    {
      rc = sqlExec( db, sqlCreateIndex );
    }
  }

  if ( rc == SQLITE_OK )
  {
    // add new layer
    QgsVectorLayer* newLayer = new QgsVectorLayer( QString( "dbname='%1' table='%2'(Geometry) sql=" )
        .arg( offlineDbPath ).arg( tableName ), tableName + " (offline)", "spatialite" );
    if ( newLayer->isValid() )
    {
      // mark as offline layer
      newLayer->setCustomProperty( CUSTOM_PROPERTY_IS_OFFLINE_EDITABLE, true );

      // store original layer source
      newLayer->setCustomProperty( CUSTOM_PROPERTY_REMOTE_SOURCE, layer->source() );
      newLayer->setCustomProperty( CUSTOM_PROPERTY_REMOTE_PROVIDER, layer->providerType() );

      // copy style
      bool hasLabels = layer->hasLabelsEnabled();
      if ( !hasLabels )
      {
        // NOTE: copy symbology before adding the layer so it is displayed correctly
        copySymbology( layer, newLayer );
      }

      // register this layer with the central layers registry
      QgsMapLayerRegistry::instance()->addMapLayers(
        QList<QgsMapLayer *>() << newLayer );

      if ( hasLabels )
      {
        // NOTE: copy symbology of layers with labels enabled after adding to project, as it will crash otherwise (WORKAROUND)
        copySymbology( layer, newLayer );
      }

      // TODO: layer order

      // copy features
      newLayer->startEditing();
      QgsFeature f;

      // NOTE: force feature recount for PostGIS layer, else only visible features are counted, before iterating over all features (WORKAROUND)
      layer->setSubsetString( "" );

      QgsFeatureIterator fit = layer->getFeatures();

      emit progressModeSet( QgsOfflineEditing::CopyFeatures, layer->featureCount() );
      int featureCount = 1;

      QList<QgsFeatureId> remoteFeatureIds;
      while ( fit.nextFeature( f ) )
      {
        remoteFeatureIds << f.id();

        // NOTE: Spatialite provider ignores position of geometry column
        // fill gap in QgsAttributeMap if geometry column is not last (WORKAROUND)
        int column = 0;
        QgsAttributes attrs = f.attributes();
        QgsAttributes newAttrs( attrs.count() );
        for ( int it = 0; it < attrs.count(); ++it )
        {
          newAttrs[column++] = attrs[it];
        }
        f.setAttributes( newAttrs );

        newLayer->addFeature( f, false );

        emit progressUpdated( featureCount++ );
      }
      if ( newLayer->commitChanges() )
      {
        emit progressModeSet( QgsOfflineEditing::ProcessFeatures, layer->featureCount() );
        featureCount = 1;

        // update feature id lookup
        int layerId = getOrCreateLayerId( db, newLayer->id() );
        QList<QgsFeatureId> offlineFeatureIds;

        QgsFeatureIterator fit = newLayer->getFeatures( QgsFeatureRequest().setFlags( QgsFeatureRequest::NoGeometry ).setSubsetOfAttributes( QgsAttributeList() ) );
        while ( fit.nextFeature( f ) )
        {
          offlineFeatureIds << f.id();
        }

        // NOTE: insert fids in this loop, as the db is locked during newLayer->nextFeature()
        sqlExec( db, "BEGIN" );
        int remoteCount = remoteFeatureIds.size();
        for ( int i = 0; i < remoteCount; i++ )
        {
          addFidLookup( db, layerId, offlineFeatureIds.at( i ), remoteFeatureIds.at( remoteCount - ( i + 1 ) ) );
          emit progressUpdated( featureCount++ );
        }
        sqlExec( db, "COMMIT" );
      }
      else
      {
        showWarning( newLayer->commitErrors().join( "\n" ) );
      }

      // remove remote layer
      QgsMapLayerRegistry::instance()->removeMapLayers(
        QStringList() << layer->id() );
    }
  }
}
Exemplo n.º 30
0
Object* FileManager::load( QString strFileName )
{
    if ( !QFile::exists( strFileName ) )
    {
        qCDebug( mLog ) << "ERROR - File doesn't exist.";
        return cleanUpWithErrorCode( Status::FILE_NOT_FOUND );
    }

    emit progressUpdated( 0.f );

    Object* obj = new Object;
    obj->setFilePath( strFileName );
    obj->createWorkingDir();

    QString strMainXMLFile;	
    QString strDataFolder;

    // Test file format: new zipped .pclx or old .pcl?
    bool oldFormat = isOldForamt( strFileName );

    if ( oldFormat )
    {
        qCDebug( mLog ) << "Recognized Old Pencil File Format (*.pcl) !";

        strMainXMLFile = strFileName;
        strDataFolder  = strMainXMLFile + "." + PFF_OLD_DATA_DIR;
    }
    else
    {
        qCDebug( mLog ) << "Recognized New zipped Pencil File Format (*.pclx) !";

        unzip( strFileName, obj->workingDir() );

        strMainXMLFile = QDir( obj->workingDir() ).filePath( PFF_XML_FILE_NAME );
        strDataFolder  = QDir( obj->workingDir() ).filePath( PFF_DATA_DIR );
    }

    qDebug() << "XML=" << strMainXMLFile;
    qDebug() << "Data Folder=" << strDataFolder;
    qDebug() << "Working Folder=" << obj->workingDir();

    obj->setDataDir( strDataFolder );
    obj->setMainXMLFile( strMainXMLFile );

    QFile file( strMainXMLFile );
    if ( !file.open( QFile::ReadOnly ) )
    {
        return cleanUpWithErrorCode( Status::ERROR_FILE_CANNOT_OPEN );
    }

    qCDebug( mLog ) << "Checking main XML file...";
    QDomDocument xmlDoc;
    if ( !xmlDoc.setContent( &file ) )
    {
        return cleanUpWithErrorCode( Status::ERROR_INVALID_XML_FILE );
    }

    QDomDocumentType type = xmlDoc.doctype();
    if ( !( type.name() == "PencilDocument" || type.name() == "MyObject" ) )
    {
        return cleanUpWithErrorCode( Status::ERROR_INVALID_PENCIL_FILE );
    }

    QDomElement root = xmlDoc.documentElement();
    if ( root.isNull() )
    {
        return cleanUpWithErrorCode( Status::ERROR_INVALID_PENCIL_FILE );
    }
    
    // Create object.
    qCDebug( mLog ) << "Start to load object..";

    loadPalette( obj );

    bool ok = true;
    
    if ( root.tagName() == "document" )
    {
        ok = loadObject( obj, root );
    }
    else if ( root.tagName() == "object" || root.tagName() == "MyOject" ) // old Pencil format (<=0.4.3)
    {
        ok = loadObjectOldWay( obj, root );
    }

    if ( !ok )
    {
        delete obj;
        return cleanUpWithErrorCode( Status::ERROR_INVALID_PENCIL_FILE );
    }
    
    verifyObject( obj );
    
    return obj;
}