bool AMCDFv1FileLoaderPlugin::load(AMScan *scan, const QString &userDataFolder, AMErrorMon *errorMonitor){

	if(!scan)
		return false;

	QFileInfo sourceFileInfo(scan->filePath());
	if(sourceFileInfo.isRelative()){
		sourceFileInfo.setFile(userDataFolder + "/" + scan->filePath());
	}

	// for now, we create a new AMCDFDataStore by opening this CDF file in read-only mode.  If read-only is a problem in the future (ex: data sources writing to the data store for caching values) we'll need to adjust this strategy.
	AMCDFDataStore* ds = new AMCDFDataStore(sourceFileInfo.filePath(), false, true);
	if(!ds->isValid()) {
		delete ds;
		errorMonitor->exteriorReport(AMErrorReport(0, AMErrorReport::Serious, AMCDFV1FILELOADERPLUGIN_CANNOT_OPEN_FILE, QString("Could not open the CDF file at '%1'. It's possible that the file has been moved, or is corrupted.").arg(sourceFileInfo.filePath())));
		return false;
	}

	if(!scan->replaceRawDataStore(ds)) {
		delete ds;
		errorMonitor->exteriorReport(AMErrorReport(0, AMErrorReport::Serious, AMCDFV1FILELOADERPLUGIN_CANNOT_USE_FILE, QString("Could not use the CDF file at '%1' for the scan '%2': it does not contain the correct measurements for the data sources that should exist in this scan.").arg(sourceFileInfo.filePath()).arg(scan->fullName())));
		return false;
	}

	return true;
}
void QgsComposerPicture::setPictureFile( const QString& path )
{
  mSourceFile.setFileName( path );
  if ( !mSourceFile.exists() )
  {
    mMode = Unknown;
  }

  //mImage = QImage(mImage.width(), mImage.height(), QImage::Format_ARGB32 );
  //setSceneRect

  QFileInfo sourceFileInfo( mSourceFile );
  QString sourceFileSuffix = sourceFileInfo.suffix();
  if ( sourceFileSuffix.compare( "svg", Qt::CaseInsensitive ) == 0 )
  {
    //try to open svg
    QSvgRenderer validTestRenderer( mSourceFile.fileName() );
    if ( validTestRenderer.isValid() )
    {
      mMode = SVG;
      QRect viewBox = validTestRenderer.viewBox(); //take width/height ratio from view box instead of default size
      mDefaultSvgSize.setWidth( viewBox.width() );
      mDefaultSvgSize.setHeight( viewBox.height() );
      mSvgCacheUpToDate = false;
    }
    else
    {
      mMode = Unknown;
    }
  }
  else
  {
    //try to open raster with QImageReader
    QImageReader imageReader( mSourceFile.fileName() );
    if ( imageReader.read( &mImage ) )
    {
      mMode = RASTER;
    }
    else
    {
      mMode = Unknown;
    }
  }

  if ( mMode != Unknown ) //make sure we start with a new QImage
  {
    setSceneRect( QRectF( transform().dx(), transform().dy(), rect().width(), rect().height() ) );
  }
  emit settingsChanged();
}
void UIWizardCloneVDPageExpert::sltHandleSourceDiskChange()
{
    /* Get source virtual-disk file-information: */
    QFileInfo sourceFileInfo(sourceVirtualDisk().GetLocation());
    /* Get default path for virtual-disk copy: */
    m_strDefaultPath = sourceFileInfo.absolutePath();
    /* Compose name for virtual-disk copy: */
    QString strMediumName = UIWizardCloneVD::tr("%1_copy", "copied virtual hard drive name").arg(sourceFileInfo.baseName());
    /* Set text to location editor: */
    m_pDestinationDiskEditor->setText(strMediumName);

    /* Broadcast complete-change: */
    emit completeChanged();
}
Beispiel #4
0
void QgsLayoutItemPicture::loadLocalPicture( const QString &path )
{
  QFile pic;
  pic.setFileName( path );

  if ( !pic.exists() )
  {
    mMode = FormatUnknown;
  }
  else
  {
    QFileInfo sourceFileInfo( pic );
    QString sourceFileSuffix = sourceFileInfo.suffix();
    if ( sourceFileSuffix.compare( QLatin1String( "svg" ), Qt::CaseInsensitive ) == 0 )
    {
      //try to open svg
      QgsExpressionContext context = createExpressionContext();
      QColor fillColor = mDataDefinedProperties.valueAsColor( QgsLayoutObject::PictureSvgBackgroundColor, context, mSvgFillColor );
      QColor strokeColor = mDataDefinedProperties.valueAsColor( QgsLayoutObject::PictureSvgStrokeColor, context, mSvgStrokeColor );
      double strokeWidth = mDataDefinedProperties.valueAsDouble( QgsLayoutObject::PictureSvgStrokeWidth, context, mSvgStrokeWidth );
      const QByteArray &svgContent = QgsApplication::svgCache()->svgContent( path, rect().width(), fillColor, strokeColor, strokeWidth,
                                     1.0 );
      mSVG.load( svgContent );
      if ( mSVG.isValid() )
      {
        mMode = FormatSVG;
        QRect viewBox = mSVG.viewBox(); //take width/height ratio from view box instead of default size
        mDefaultSvgSize.setWidth( viewBox.width() );
        mDefaultSvgSize.setHeight( viewBox.height() );
      }
      else
      {
        mMode = FormatUnknown;
      }
    }
    else
    {
      //try to open raster with QImageReader
      QImageReader imageReader( pic.fileName() );
      if ( imageReader.read( &mImage ) )
      {
        mMode = FormatRaster;
      }
      else
      {
        mMode = FormatUnknown;
      }
    }
  }
}
Beispiel #5
0
void UIWizardCloneVDPageBasic4::initializePage()
{
    /* Translate page: */
    retranslateUi();

    /* Get source virtual-disk file-information: */
    QFileInfo sourceFileInfo(field("sourceVirtualDisk").value<CMedium>().GetLocation());
    /* Get default path for virtual-disk copy: */
    m_strDefaultPath = sourceFileInfo.absolutePath();
    /* Get default extension for virtual-disk copy: */
    m_strDefaultExtension = defaultExtension(field("mediumFormat").value<CMediumFormat>());
    /* Compose default-name for virtual-disk copy: */
    QString strMediumName = UIWizardCloneVD::tr("%1_copy", "copied virtual hard drive name").arg(sourceFileInfo.baseName());
    /* Set default-name as text for location editor: */
    m_pDestinationDiskEditor->setText(strMediumName);
}
Beispiel #6
0
void QgsComposerPicture::loadLocalPicture( const QString &path )
{
  QFile pic;
  pic.setFileName( path );

  if ( !pic.exists() )
  {
    mMode = Unknown;
  }
  else
  {
    QFileInfo sourceFileInfo( pic );
    QString sourceFileSuffix = sourceFileInfo.suffix();
    if ( sourceFileSuffix.compare( "svg", Qt::CaseInsensitive ) == 0 )
    {
      //try to open svg
      const QByteArray &svgContent = QgsSvgCache::instance()->svgContent( pic.fileName(), rect().width(), mSvgFillColor, mSvgBorderColor, mSvgBorderWidth,
                                     1.0, 1.0 );
      mSVG.load( svgContent );
      if ( mSVG.isValid() )
      {
        mMode = SVG;
        QRect viewBox = mSVG.viewBox(); //take width/height ratio from view box instead of default size
        mDefaultSvgSize.setWidth( viewBox.width() );
        mDefaultSvgSize.setHeight( viewBox.height() );
      }
      else
      {
        mMode = Unknown;
      }
    }
    else
    {
      //try to open raster with QImageReader
      QImageReader imageReader( pic.fileName() );
      if ( imageReader.read( &mImage ) )
      {
        mMode = RASTER;
      }
      else
      {
        mMode = Unknown;
      }
    }
  }

}
Beispiel #7
0
void QgsComposerPicture::setPictureFile( const QString& path )
{
  mSourceFile.setFileName( path );
  if ( !mSourceFile.exists() )
  {
    mMode = Unknown;
  }

  QFileInfo sourceFileInfo( mSourceFile );
  QString sourceFileSuffix = sourceFileInfo.suffix();
  if ( sourceFileSuffix.compare( "svg", Qt::CaseInsensitive ) == 0 )
  {
    //try to open svg
    mSVG.load( mSourceFile.fileName() );
    if ( mSVG.isValid() )
    {
      mMode = SVG;
      QRect viewBox = mSVG.viewBox(); //take width/height ratio from view box instead of default size
      mDefaultSvgSize.setWidth( viewBox.width() );
      mDefaultSvgSize.setHeight( viewBox.height() );
    }
    else
    {
      mMode = Unknown;
    }
  }
  else
  {
    //try to open raster with QImageReader
    QImageReader imageReader( mSourceFile.fileName() );
    if ( imageReader.read( &mImage ) )
    {
      mMode = RASTER;
    }
    else
    {
      mMode = Unknown;
    }
  }

  if ( mMode != Unknown ) //make sure we start with a new QImage
  {
    setSceneRect( QRectF( pos().x(), pos().y(), rect().width(), rect().height() ) );
  }
  emit itemChanged();
}
void UIWizardCloneVDPageExpert::setTargetLocation()
{
    UIWizardCloneVD *pWizard = qobject_cast<UIWizardCloneVD*>(wizard());
    if (!pWizard)
        return;
    /* Get source virtual-disk file-information: */
    QFileInfo sourceFileInfo(pWizard->sourceVirtualDisk().GetLocation());
    /* Get default path for virtual-disk copy: */
    m_strDefaultPath = sourceFileInfo.absolutePath();
    /* Compose name for virtual-disk copy: */
    QString strMediumName = UIWizardCloneVD::tr("%1_copy", "copied virtual disk image name").arg(sourceFileInfo.baseName());
    /* Set text to location editor: */
    m_pDestinationDiskEditor->setText(strMediumName);

    /* Broadcast complete-change: */
    emit completeChanged();
}
void MyFileSystemView::dropEvent(QDropEvent *event)
{
	QTreeView::dropEvent(event);
	if (!m_boolIsWatched)
	{
		return;
	}
	auto mypos = event->pos();
	auto mysrc = event->source();
	if (qobject_cast<MyFileSystemView*>(mysrc))
	{
		QModelIndex index = this->indexAt(mypos); // show only the target folder
		if (index.isValid())
		{
			QFileInfo destFileInfo = qobject_cast<QFileSystemModel*>(this->model())->fileInfo(index);
			QString strAbsoluteDestinationDir;
			if (destFileInfo.isFile())
			{
				strAbsoluteDestinationDir = destFileInfo.absolutePath();
			}
			else
			{
				strAbsoluteDestinationDir = destFileInfo.absoluteFilePath();
			}
			QFileInfo sourceFileInfo(m_strRelativeSourceFilePath);
			QString strAbsoluteDestinationFilePath = strAbsoluteDestinationDir + "/" + sourceFileInfo.fileName();
			// construct relative destination path
			QDir myDir("./");
			m_strRelativeDestinationFilePath = myDir.relativeFilePath(strAbsoluteDestinationFilePath);
			// send signal
			if (m_strRelativeSourceFilePath.compare(m_strRelativeDestinationFilePath) != 0 && QFileInfo(m_strRelativeDestinationFilePath).exists())
			{
				Q_EMIT trackedFileWasMoved(m_strRelativeSourceFilePath, m_strRelativeDestinationFilePath);
			}
			// clean
			m_strRelativeSourceFilePath.clear();
			m_strRelativeDestinationFilePath.clear();
			m_boolIsWatched = false;
		}
	}
}
Beispiel #10
0
QgsUserColorScheme::QgsUserColorScheme( const QString &filename )
  : mFilename( filename )
{
  QFile sourceFile( gplFilePath() );

  //read in name
  if ( sourceFile.open( QIODevice::ReadOnly ) )
  {
    QTextStream in( &sourceFile );

    //find name line
    QString line;
    while ( !in.atEnd() && !line.startsWith( QLatin1String( "Name:" ) ) )
    {
      line = in.readLine();
    }
    if ( !in.atEnd() )
    {
      QRegExp rx( "Name:\\s*(\\S.*)$" );
      if ( rx.indexIn( line ) != -1 )
      {
        mName = rx.cap( 1 );
      }
    }
  }
  if ( mName.isEmpty() )
  {
    mName = mFilename;
  }

  // we consider this scheme writable if the user has permission, OR
  // if it DOESN'T already exist (since new schemes are only created when
  // first written to)
  QFileInfo sourceFileInfo( gplFilePath() );
  mEditable = !sourceFileInfo.exists() || sourceFileInfo.isWritable();
}
bool ALSBL8XASFileLoaderPlugin::load(AMScan *scan, const QString &userDataFolder, AMErrorMon *errorMonitor){

	if(columns2fileFormatHeaders_.count() == 0) {
		columns2fileFormatHeaders_.set("eV", "Mono Energy");
		columns2fileFormatHeaders_.set("ringCurrent", "Beam Current");
		columns2fileFormatHeaders_.set("I0", "Counter 0");
		columns2fileFormatHeaders_.set("TEY", "Counter 1");
		columns2fileFormatHeaders_.set("TFY", "Counter 2");
	}

	if(!scan)
		return false;

	// Clear the old scan axes to ensure we don't have any extras.
	scan->clearRawDataCompletely();
	scan->rawData()->addScanAxis( AMAxisInfo("eV", 0, "Incident Energy", "eV") );

	QFileInfo sourceFileInfo(scan->filePath());
	if(sourceFileInfo.isRelative()){
		sourceFileInfo.setFile(userDataFolder + "/" + scan->filePath());
	}

	// used in parsing the data file
	QString line;
	QStringList lp;

	// names of the columns, taken from headers in the data file.
	QStringList colNames1;

	// open the file:
	QFile f(sourceFileInfo.filePath());
	if(!f.open(QIODevice::ReadOnly)) {
		errorMonitor->exteriorReport(AMErrorReport(0, AMErrorReport::Serious, ALSBL8XASFileLoaderPLUGIN_CANNOT_OPEN_FILE, "ALSBL8XASFileLoader parse error while loading scan data from file. Missing file."));
		return false;
	}
	QTextStream fs(&f);

	// find out what columns exist. Looking for line starting with 'Time (s)'
	while(!fs.atEnd() && !line.startsWith("Time (s)"))
		line = fs.readLine();
	if(fs.atEnd()) {
		errorMonitor->exteriorReport(AMErrorReport(0, AMErrorReport::Serious, ALSBL8XASFileLoaderPLUGIN_BAD_FORMAT_NO_EVENT1_HEADER, "ALSBL8XASFileLoader parse error while loading scan data from file. Missing the Column Header line."));
		return false;	// bad format. Missing the column header
	}
	colNames1 = line.split(QChar('\t'));

	// translate header names into meaningful column names (ex: "Counter 0" ---> "I0".... "Counter1"--->"tey")
	for(int i=0; i<colNames1.count(); i++)
		header2columnName(colNames1[i]);

	// ensure that we have the basic "eV" column
	int eVIndex = colNames1.indexOf("eV");
	if(eVIndex < 0) {
		errorMonitor->exteriorReport(AMErrorReport(0, AMErrorReport::Serious, ALSBL8XASFileLoaderPLUGIN_BAD_FORMAT_NO_ENERGY_COLUMN, "ALSBL8XASFileLoader parse error while loading scan data from file. I couldn't find the energy (eV) column."));
		return false;	// bad format. No primary column

	}

	scan->clearRawDataPointsAndMeasurements();

	// There is a rawData scan axis called "eV" created in the constructor.  AMAxisInfo("eV", 0, "Incident Energy", "eV")
	/// \todo What if there isn't? Should we check, and create the axis if none exist? What if there's more than one scan axis? Can't remove from AMDataStore... [The rest of this code assumes a single scan axis]

	// add scalar (0D) measurements to the raw data store, for each data column.  Also add raw data sources to the scan, which expose this data.
	foreach(QString colName, colNames1) {
		if(colName != "eV" && colName != "Event-ID") {
			scan->rawData()->addMeasurement(AMMeasurementInfo(colName, colName));	/// \todo nice descriptions for the common column names. Not just 'tey' or 'tfy'.
		}
	}

	int eVAxisIndex = 0;	// counter for each datapoint along the scan axis.

	// read all the data. Add to data columns or scan properties depending on the event-ID.
	while(!fs.atEnd()) {

		line = fs.readLine();

		// Data line. If there are the correct number of columns:
		if( (lp = line.split('\t', QString::SkipEmptyParts)).count() == colNames1.count() ) {

			// append a new datapoint to the data tree (supply primary eV value here)
			scan->rawData()->beginInsertRows(1, -1);
			scan->rawData()->setAxisValue(0, eVAxisIndex, lp.at(eVIndex).toDouble());	// insert eV

			// add all columns (but ignore the eV column)
			int measurementId = 0;
			for(int i=1; i<colNames1.count(); i++) {
				if(i!=eVIndex)
					scan->rawData()->setValue(eVAxisIndex, measurementId++, AMnDIndex(), lp.at(i).toDouble());
			}
			eVAxisIndex++;
			scan->rawData()->endInsertRows();
		}
	}

	/// Not supposed to create the raw data sources.  Do an integrity check on the pre-existing data sources instead... If there's a raw data source, but it's pointing to a non-existent measurement in the data store, that's a problem. Remove it.  \todo Is there any way to incorporate this at a higher level, so that import-writers don't need to bother?

	for(int i=0; i<scan->rawDataSources()->count(); i++) {
		if(scan->rawDataSources()->at(i)->measurementId() >= scan->rawData()->measurementCount()) {
			errorMonitor->exteriorReport(AMErrorReport(scan, AMErrorReport::Debug, ALSBL8XASFileLoaderPLUGIN_DATA_COLUMN_MISMATCH, QString("The data in the file didn't match the raw data columns we were expecting. Removing the raw data column '%1')").arg(scan->rawDataSources()->at(i)->name())));
			scan->deleteRawDataSource(i);
		}
	}

	return true;
}
void FileSignAndEncryption::on_okButton2_clicked()
{
    ui->warningLabel2->setText("");
    if (ui->sourceFileEdit2->text().startsWith("~/") || ui->destinationFileEdit2->text().startsWith("~/")) {
        ui->warningLabel2->setText("Seul les chemins absolus sont autorisés.");
        return;
    }

    if (ui->sourceFileEdit2->text() == ui->destinationFileEdit2->text()) {
        ui->warningLabel2->setText("Vous ne pouvez pas utiliser le même fichier source et destination.");
        return;
    }

    QFile sourcefile(ui->sourceFileEdit2->text());
    if (!sourcefile.exists()) {
        ui->warningLabel2->setText("Le fichier source n'existe pas.");
        return;
    }

    QFileInfo sourceFileInfo(sourcefile);
    if (!sourceFileInfo.isReadable()) {
        ui->warningLabel2->setText("Vous n'avez pas les droits de lecture sur le fichier source.");
        return;
    }

    QFile destinationfile(ui->destinationFileEdit2->text());
    if (destinationfile.exists()) {
        if (!destinationfile.remove()) {
            ui->warningLabel2->setText("Impossible d'écraser le fichier existant. Veuillez modifier la destination.");
            return;
        }
    }

    QFileInfo destinationFileInfo(destinationfile);
    QFileInfo destinationDirInfo(destinationFileInfo.absoluteDir().path());
    if (!destinationDirInfo.isWritable()) {
        ui->warningLabel2->setText("Vous n'avez pas les droits d'écriture sur le dossier destination.");
        return;
    }

    // On récupère l'indice des lignes selectionnées
    QModelIndexList selectedIndex = ui->tableWidgetRecipient2->selectionModel()->selectedIndexes();
    QList<int> rowIndexes;
    for (QModelIndex index : selectedIndex) {
        if (!rowIndexes.contains(index.row())) {
            rowIndexes.append(index.row());
        }
    }

    // On récupère l'indice des lignes selectionnées pour le signataire
    QModelIndexList selectedIndexSign = ui->tableWidgetSign->selectionModel()->selectedIndexes();
    QList<int> rowIndexesSign;
    for (QModelIndex index : selectedIndexSign) {
        if (!rowIndexesSign.contains(index.row())) {
            rowIndexesSign.append(index.row());
        }
    }

    if (rowIndexes.count() == 0) {
        ui->warningLabel2->setText("Vous devez sélectionner au moins un destinaire.");
        return;
    }

    if (rowIndexesSign.count() == 0) {
        ui->warningLabel2->setText("Vous devez sélectionner un signataire.");
        return;
    }

    /* Utilisé pour paramétré les intéractions car gpg est tellement
     * intelligent qu'il les demandes dans l'ordre inverse pour le cas anonyme
     */
    QList<int> reverseRowIndexes;
    reverseRowIndexes.reserve(rowIndexes.size());
    std::reverse_copy(rowIndexes.begin(), rowIndexes.end(), std::back_inserter(reverseRowIndexes));

    QStringList opt;
    opt << "--command-fd=0"
        << "--status-fd=1"
        << "-a"
        << "--sign"
        << "--default-key " + ui->tableWidgetSign->item(rowIndexesSign[0], 0)->text()
        << "--output" << ui->destinationFileEdit2->text();
    QString cmd = "-e";
    QStringList arg;
    arg << ui->sourceFileEdit2->text();
    QStringList interactions;

    if (ui->anonymousCheckBox->isChecked()) {
        for (int i : rowIndexes) {
            opt << "-R \""
                   + ui->tableWidgetRecipient2->item(i, 0)->text()
                   + " <"
                   + ui->tableWidgetRecipient2->item(i, 1)->text()
                   + ">\"";
        }

        for (int i : reverseRowIndexes) {
            if (ui->tableWidgetRecipient2->item(i, 3)->text() == GpgObject::validityToStr(VALIDITY_NO_VALUE) ||
                    ui->tableWidgetRecipient2->item(i, 3)->text() == GpgObject::validityToStr(VALIDITY_UNDEFINED)) {
                interactions << "y";
            }
        }
    } else {
        for (int i : rowIndexes) {
            interactions << ui->tableWidgetRecipient2->item(i, 0)->text()
                           + " <"
                           + ui->tableWidgetRecipient2->item(i, 1)->text()
                           + ">";
            if (ui->tableWidgetRecipient2->item(i, 3)->text() == GpgObject::validityToStr(VALIDITY_NO_VALUE) ||
                    ui->tableWidgetRecipient2->item(i, 3)->text() == GpgObject::validityToStr(VALIDITY_UNDEFINED)) {
                interactions << "y";
            }
        }
        interactions << "";
    }


    Action action(cmd, arg, opt, interactions);
    m_manager->setAction(action);
    connect(m_manager, &GPGManager::finished, this, &FileSignAndEncryption::onEncryptionCompleted);
    m_manager->execute();
}
bool VESPERS2011XASFileLoaderPlugin::load(AMScan *scan, const QString &userDataFolder, AMErrorMon *errorMonitor)
{
	// Check for null scan reference.
	if (!scan)
		return false;

	QFileInfo sourceFileInfo(scan->filePath());
	if(sourceFileInfo.isRelative())
		sourceFileInfo.setFile(userDataFolder + "/" + scan->filePath());

	QFile file(sourceFileInfo.filePath());
	if(!file.open(QIODevice::ReadOnly)) {
		errorMonitor->exteriorReport(AMErrorReport(0, AMErrorReport::Serious, VESPERS2011XASFILELOADERPLUGIN_CANNOT_OPEN_FILE, "XASFileLoader parse error while loading scan data from file."));
		return false;
	}

	QString temp = sourceFileInfo.filePath();
	temp.replace(".dat", ".cdf");
	AMCDFDataStore *cdfData = new AMCDFDataStore(temp, false);
	cdfData->addScanAxis( AMAxisInfo("eV", 0, "Incident Energy", "eV") );

	QTextStream in(&file);
	QString line;
	QStringList lineTokenized;

	// Need to determine if the single element or four element vortex detector was used.  Also need to determine which ion chambers were used for I0 and It.
	// First two lines are useless.
	line = in.readLine();
	line = in.readLine();

	line = in.readLine();

	if (line.contains("#(2)"))
		line = in.readLine();

	bool usingSingleElement = line.contains("IOC1607-004");
	bool usingFourElement = line.contains("dxp1607-B21-04");

	while ((line = in.readLine()).contains("#")){
		//Do nothing
	}

	// Clear any old data so we can start fresh.
	scan->clearRawDataPointsAndMeasurements();

	// Some setup variables.
	int axisValueIndex = 0;
	int count = scan->rawDataSourceCount();
	// Note!  Not general!
	QList<AMAxisInfo> axisInfo;
	AMAxisInfo ai("Energy", 2048, "Energy", "eV");
	ai.increment = 10;
	ai.start = AMNumber(0);
	ai.isUniform = true;
	axisInfo << ai;

	if (usingSingleElement && usingFourElement){

		// The last 6 raw data sources are spectra.
		for (int i = 0; i < count-6; i++)
			cdfData->addMeasurement(AMMeasurementInfo(scan->rawDataSources()->at(i)->name(), scan->rawDataSources()->at(i)->description()));

		for (int i = count-6; i < count; i++)
			cdfData->addMeasurement(AMMeasurementInfo(scan->rawDataSources()->at(i)->name(), scan->rawDataSources()->at(i)->description(), "eV", axisInfo));
	}

	else if (usingSingleElement){

		// The last raw data source is a spectrum.
		for (int i = 0; i < count-1; i++)
			cdfData->addMeasurement(AMMeasurementInfo(scan->rawDataSources()->at(i)->name(), scan->rawDataSources()->at(i)->description()));

		cdfData->addMeasurement(AMMeasurementInfo(scan->rawDataSources()->at(scan->rawDataSourceCount()-1)->name(), scan->rawDataSources()->at(scan->rawDataSourceCount()-1)->description(), "eV", axisInfo));
	}

	else if (usingFourElement){

		// The last 5 raw data sources are spectra.
		for (int i = 0; i < count-5; i++)
			cdfData->addMeasurement(AMMeasurementInfo(scan->rawDataSources()->at(i)->name(), scan->rawDataSources()->at(i)->description()));

		for (int i = count-5; i < count; i++)
			cdfData->addMeasurement(AMMeasurementInfo(scan->rawDataSources()->at(i)->name(), scan->rawDataSources()->at(i)->description(), "eV", axisInfo));
	}

	else{

		for (int i = 0; i < count; i++)
			cdfData->addMeasurement(AMMeasurementInfo(scan->rawDataSources()->at(i)->name(), scan->rawDataSources()->at(i)->description()));
	}

	QStringList fileLines;
	fileLines << line;

	while(!in.atEnd())
		fileLines << in.readLine();

	file.close();

	// Add in the data at the right spot.
	cdfData->beginInsertRows(fileLines.size(), -1);

	foreach(QString currentLine, fileLines){

		lineTokenized = currentLine.split(", ");

		cdfData->setAxisValue(0, axisValueIndex, lineTokenized.at(1).toDouble());

		// This isn't the most efficient way of putting the spectra data in, but it will do for the time being.
		if (usingSingleElement && usingFourElement){

			// Only going to rawDataSourceCount-6 because the last 6 raw data sources are the 2D spectra scan and requires its own method of entering the data.
			for (int i = 0; i < count-6; i++)
				cdfData->setValue(axisValueIndex, i, AMnDIndex(), lineTokenized.at(i+2).toDouble());
		}

		else if (usingSingleElement){

			// Only going to rawDataSourceCount-1 because the last raw data source is the 2D spectra scan and requires its own method of entering the data.
			for (int i = 0; i < count-1; i++)
				cdfData->setValue(axisValueIndex, i, AMnDIndex(), lineTokenized.at(i+2).toDouble());
		}

		else if (usingFourElement){

			// Only going to rawDataSourceCount-5 because the last 5 raw data sources are the 2D spectra scan and requires its own method of entering the data.
			for (int i = 0; i < count-5; i++)
				cdfData->setValue(axisValueIndex, i, AMnDIndex(), lineTokenized.at(i+2).toDouble());
		}

		else{

			// In transmission, there is no 2D spectra.  Go through all the data sources.
			for (int i = 0; i < count; i++)
				cdfData->setValue(axisValueIndex, i, AMnDIndex(), lineTokenized.at(i+2).toDouble());
		}

		axisValueIndex++;
	}
Beispiel #14
0
void QgsComposerPicture::loadPicture( const QFile& file )
{
  if ( !file.exists()
       || ( mUseSourceExpression && mPictureExpr->hasEvalError() ) )
  {
    mMode = Unknown;
  }
  else
  {
    QFileInfo sourceFileInfo( file );
    QString sourceFileSuffix = sourceFileInfo.suffix();
    if ( sourceFileSuffix.compare( "svg", Qt::CaseInsensitive ) == 0 )
    {
      //try to open svg
      mSVG.load( file.fileName() );
      if ( mSVG.isValid() )
      {
        mMode = SVG;
        QRect viewBox = mSVG.viewBox(); //take width/height ratio from view box instead of default size
        mDefaultSvgSize.setWidth( viewBox.width() );
        mDefaultSvgSize.setHeight( viewBox.height() );
      }
      else
      {
        mMode = Unknown;
      }
    }
    else
    {
      //try to open raster with QImageReader
      QImageReader imageReader( file.fileName() );
      if ( imageReader.read( &mImage ) )
      {
        mMode = RASTER;
      }
      else
      {
        mMode = Unknown;
      }
    }
  }

  if ( mMode != Unknown ) //make sure we start with a new QImage
  {
    recalculateSize();
  }
  else if ( !( file.fileName().isEmpty() ) || ( mUseSourceExpression && mPictureExpr && mPictureExpr->hasEvalError() ) )
  {
    //trying to load an invalid file or bad expression, show cross picture
    mMode = SVG;
    QString badFile = QString( ":/images/composer/missing_image.svg" );
    mSVG.load( badFile );
    if ( mSVG.isValid() )
    {
      mMode = SVG;
      QRect viewBox = mSVG.viewBox(); //take width/height ratio from view box instead of default size
      mDefaultSvgSize.setWidth( viewBox.width() );
      mDefaultSvgSize.setHeight( viewBox.height() );
      recalculateSize();
    }
  }

  emit itemChanged();
}
bool SGM2013FastFileLoaderPlugin::load(AMScan *scan, const QString &userDataFolder, AMErrorMon *errorMonitor){
	if(!scan)
		return false;

	// Clear the old scan axes to ensure we don't have any extras.
	scan->clearRawDataCompletely();
	scan->rawData()->addScanAxis( AMAxisInfo("eV", 0, "Incident Energy", "eV") );

	QFileInfo sourceFileInfo(scan->filePath());
	if(sourceFileInfo.isRelative())
		sourceFileInfo.setFile(userDataFolder + "/" + scan->filePath());

	// open the file:
	QFile f(sourceFileInfo.filePath());
	if(!f.open(QIODevice::ReadOnly)) {
		errorMonitor->exteriorReport(AMErrorReport(0, AMErrorReport::Serious, SGM2013FASTFILELOADERPLUGIN_CANNOT_OPEN_FILE, "SGM2013FastFileLoader parse error while loading scan data from file. Missing file."));
		return false;
	}
	QTextStream fs(&f);

	QMap<int, QList<int> > measurementOrderByRank;

	// used in parsing the data file
	QString line;
	QStringList lp;
	QString versionString;
	int index;
	double dataValue;
	int insertionIndex = 0;
	bool informationSection = false;
	bool finishedHeader = false;
	while(!fs.atEnd()){
		if(!finishedHeader)
			line = fs.readLine();
		if(line == "Start Info")
			informationSection = true;
		else if(line.contains("Version: "))
			versionString = line.remove("Version: ");
		else if(line == "End Info"){
			informationSection = false;
			finishedHeader = true;
			line = "";
		}
		else if(informationSection){
			if(versionString == "SGM Generic Fast 0.1"){
				if(!line.contains("Encoder Start Value:") && !line.contains("SpacingParam:") && !line.contains("C1Param:") && !line.contains("C2Param:") && !line.contains("SParam:") && !line.contains("ThetaParam:")){
					lp = line.split("|!|!|");
					index = lp.at(0).toInt();
					if(index >= 0){
						QString oneString = lp.at(1);
						AMTextStream measurementInfoStreamOut(&oneString);
						AMMeasurementInfo oneMeasurementInfo = AMMeasurementInfo(QString(), QString());
						measurementInfoStreamOut.read(oneMeasurementInfo);

						if(measurementOrderByRank.contains(oneMeasurementInfo.rank())){
							QList<int> thisRankList = measurementOrderByRank.value(oneMeasurementInfo.rank());
							thisRankList.append(index);
							measurementOrderByRank.insert(oneMeasurementInfo.rank(), thisRankList);
						}
						else{
							QList<int> newRankList;
							newRankList.append(index);
							measurementOrderByRank.insert(oneMeasurementInfo.rank(), newRankList);
						}

						scan->rawData()->addMeasurement(oneMeasurementInfo);
					}
				}
			}
		}
		else{
			if(!fs.atEnd()){
				fs >> dataValue;
				if(!fs.atEnd()){
					scan->rawData()->beginInsertRows(1, -1);
					scan->rawData()->setAxisValue(0, insertionIndex, dataValue); // insert eV
					QList<int> rank0Measurements = measurementOrderByRank.value(0);
					for(int x = 0; x < rank0Measurements.count(); x++){
						fs >> dataValue;
						scan->rawData()->setValue(AMnDIndex(insertionIndex), rank0Measurements.at(x), AMnDIndex(), dataValue);
					}
					scan->rawData()->endInsertRows();
					insertionIndex++;
				}
			}
		}
bool VESPERS2012SpatialLineScanFileLoaderPlugin::load(AMScan *scan, const QString &userDataFolder, AMErrorMon *errorMonitor)
{
	// Check for null scan reference.
	if (!scan)
		return false;

	QFileInfo sourceFileInfo(scan->filePath());
	if(sourceFileInfo.isRelative())
		sourceFileInfo.setFile(userDataFolder + "/" + scan->filePath());

	QFile file(sourceFileInfo.filePath());
	if(!file.open(QIODevice::ReadOnly)) {
		errorMonitor->exteriorReport(AMErrorReport(0, AMErrorReport::Serious, VESPERS201SPATIALLINESCANFILELOADERPLUGIN_CANNOT_OPEN_FILE, "Line Scan File Loader parse error while loading scan data from file."));
		return false;
	}

	QTextStream in(&file);
	QString line;
	QStringList lineTokenized;

	bool usingSingleElement = false;
	bool usingFourElement = false;

	if (scan->fileFormat() == "vespers2012LineScanXRF1El" || scan->fileFormat() == "vespers2012LineScanXRF1ElXRD")
		usingSingleElement = true;
	else if (scan->fileFormat() == "vespers2012LineScanXRF4El" || scan->fileFormat() == "vespers2012LineScanXRF4ElXRD")
		usingFourElement = true;
	else if (scan->fileFormat() == "vespers2012LineScan1Eln4El" || scan->fileFormat() == "vespers2012LineScan1Eln4ElXRD"){

		usingSingleElement = true;
		usingFourElement = true;
	}

	in.readLine();
	in.readLine();
	in.readLine();

	// Grab the first PV, it tells us what the axis was.
	line = in.readLine();
	lineTokenized = line.split(" ");
	line = lineTokenized.at(2);

	QString temp = sourceFileInfo.filePath();
	temp.replace(".dat", ".cdf");
	AMCDFDataStore *cdfData = new AMCDFDataStore(temp, false);

	if (line == "TS1607-2-B21-01:H:user:mm")
		cdfData->addScanAxis(AMAxisInfo("H", 0, "Horizontal Position", "mm"));
	else if (line == "TS1607-2-B21-01:V:user:mm")
		cdfData->addScanAxis(AMAxisInfo("V", 0, "Vertical Position", "mm"));
	else if (line == "SVM1607-2-B21-02:mm")
		cdfData->addScanAxis(AMAxisInfo("X", 0, "Horizontal Position", "mm"));
	else if (line == "SVM1607-2-B21-01:mm")
		cdfData->addScanAxis(AMAxisInfo("Z", 0, "Vertical Position", "mm"));
	else if (line == "07B2_Mono_SineB_Egec:eV")
		cdfData->addScanAxis(AMAxisInfo("eV", 0, "Incident Energy", "eV"));

	in.readLine();
	in.readLine();
	in.readLine();

	// Clear any old data so we can start fresh.
	scan->clearRawDataPointsAndMeasurements();
	int axisValueIndex = 0;
	int count = scan->rawDataSourceCount();

	// Note!  Not general!
	QList<AMAxisInfo> axisInfo;
	AMAxisInfo ai("Energy", 2048, "Energy", "eV");
	ai.increment = 10;
	ai.start = AMNumber(0);
	ai.isUniform = true;
	axisInfo << ai;

	if (usingSingleElement && usingFourElement){

		// The last 6 raw data sources are spectra.
		for (int i = 0; i < count-6; i++)
			cdfData->addMeasurement(AMMeasurementInfo(scan->rawDataSources()->at(i)->name(), scan->rawDataSources()->at(i)->description()));

		for (int i = count-6; i < count; i++)
			cdfData->addMeasurement(AMMeasurementInfo(scan->rawDataSources()->at(i)->name(), scan->rawDataSources()->at(i)->description(), "eV", axisInfo));
	}

	else if (usingSingleElement){

		// The last raw data source is a spectrum.
		for (int i = 0; i < count-1; i++)
			cdfData->addMeasurement(AMMeasurementInfo(scan->rawDataSources()->at(i)->name(), scan->rawDataSources()->at(i)->description()));

		cdfData->addMeasurement(AMMeasurementInfo(scan->rawDataSources()->at(scan->rawDataSourceCount()-1)->name(), scan->rawDataSources()->at(scan->rawDataSourceCount()-1)->description(), "eV", axisInfo));
	}

	else if (usingFourElement){

		// The last 5 raw data sources are spectra.
		for (int i = 0; i < count-5; i++)
			cdfData->addMeasurement(AMMeasurementInfo(scan->rawDataSources()->at(i)->name(), scan->rawDataSources()->at(i)->description()));

		for (int i = count-5; i < count; i++)
			cdfData->addMeasurement(AMMeasurementInfo(scan->rawDataSources()->at(i)->name(), scan->rawDataSources()->at(i)->description(), "eV", axisInfo));
	}

	else{

		for (int i = 0; i < count; i++)
			cdfData->addMeasurement(AMMeasurementInfo(scan->rawDataSources()->at(i)->name(), scan->rawDataSources()->at(i)->description()));

	}

	lineTokenized.clear();

	QStringList fileLines;
	while(!in.atEnd())
		fileLines << in.readLine();

	file.close();

	// Add in the data at the right spot.
	cdfData->beginInsertRows(fileLines.size(), -1);

	foreach(QString currentLine, fileLines){

		lineTokenized = currentLine.split(", ");

		cdfData->setAxisValue(0, axisValueIndex, lineTokenized.at(1).toDouble());

		// This isn't the most efficient way of putting the spectra data in, but it will do for the time being.
		if (usingSingleElement && usingFourElement){

			// Only going to rawDataSourceCount-6 because the last 6 raw data sources are the 2D spectra scan and requires its own method of entering the data.
			for (int i = 0; i < count-6; i++)
				cdfData->setValue(axisValueIndex, i, AMnDIndex(), lineTokenized.at(i+2).toDouble());
		}

		else if (usingSingleElement){

			// Only going to rawDataSourceCount-1 because the last raw data source is the 2D spectra scan and requires its own method of entering the data.
			for (int i = 0; i < count-1; i++)
				cdfData->setValue(axisValueIndex, i, AMnDIndex(), lineTokenized.at(i+2).toDouble());
		}

		else if (usingFourElement){

			// Only going to rawDataSourceCount-5 because the last 5 raw data sources are the 2D spectra scan and requires its own method of entering the data.
			for (int i = 0; i < count-5; i++)
				cdfData->setValue(axisValueIndex, i, AMnDIndex(), lineTokenized.at(i+2).toDouble());
		}

		else{

			for (int i = 0; i < count; i++)
				cdfData->setValue(axisValueIndex, i, AMnDIndex(), lineTokenized.at(i+2).toDouble());
		}

		// Advance to the next spot.
		axisValueIndex++;
	}