QFileInfoList CDspHaClusterHelper::getReport()
{
	QFileInfoList output;
	QFileInfo p("/usr/bin/vstorage-make-report");
	if (!p.exists())
		return output;
	QDir d("/etc/vstorage/clusters");
	if (!d.exists())
		return output;
	QStringList a = d.entryList(QDir::NoDotAndDotDot | QDir::Dirs);
	foreach (QString x, a)
	{
		QTemporaryFile t;
		t.setFileTemplate(QString("%1/pstorage.%2.XXXXXX.tgz")
			.arg(QDir::tempPath()).arg(x));
		if (!t.open())
		{
			WRITE_TRACE(DBG_FATAL, "QTemporaryFile::open() error: %s",
					QSTR2UTF8(t.errorString()));
			continue;
		}
		QString b, c = QString("%1 -f %2 \"%3\"").arg(p.filePath()).arg(t.fileName()).arg(x);
		if (!HostUtils::RunCmdLineUtility(c, b, -1) || t.size() == 0)
		{
			t.close();
			continue;
		}
		t.setAutoRemove(false);
		output.append(QFileInfo(t.fileName()));
		t.close();
	}
Beispiel #2
0
void
FileStore::compressRide(RideFile*ride, QByteArray &data, QString name)
{
    // compress via a temporary file
    QTemporaryFile tempfile;
    tempfile.open();
    tempfile.close();

    // write as json
    QFile jsonFile(tempfile.fileName());
    if (RideFileFactory::instance().writeRideFile(NULL, ride, jsonFile, "json") == true) {

        // create a temp zip file
        QTemporaryFile zipFile;
        zipFile.open();
        zipFile.close();

        // add files using zip writer
        QString zipname = zipFile.fileName();
        ZipWriter writer(zipname);

        // read the ride file back and add to zip file
        jsonFile.open(QFile::ReadOnly);
        writer.addFile(name, jsonFile.readAll());
        jsonFile.close();
        writer.close();

        // now read in the zipfile
        QFile zip(zipname);
        zip.open(QFile::ReadOnly);
        data = zip.readAll();
        zip.close();
    }
}
Beispiel #3
0
void FileWatchUnitTest::filewatchTest()
{
    QWARN("Unittest will take about 1 minute. Please wait.");

    QCA::FileWatch watcher;
    QCOMPARE( watcher.fileName(), QString() );

    QSignalSpy spy( &watcher, SIGNAL(changed()) );
    QVERIFY( spy.isValid() );
    QCOMPARE( spy.count(), 0 );

    QTemporaryFile *tempFile = new QTemporaryFile;

    tempFile->open();

    watcher.setFileName( tempFile->fileName() );
    QCOMPARE( watcher.fileName(), tempFile->fileName() );
    QTest::qWait(7000);
    QCOMPARE( spy.count(), 0 );
    tempFile->close();
    QTest::qWait(7000);
    QCOMPARE( spy.count(), 0 );

    tempFile->open();
    tempFile->write("foo");
    tempFile->flush();
    QTest::qWait(7000);
    QCOMPARE( spy.count(), 1 );

    tempFile->close();
    QTest::qWait(7000);

    QCOMPARE( spy.count(), 1 );

    tempFile->open();
    tempFile->write("foo");
    tempFile->flush();
    QTest::qWait(7000);
    QCOMPARE( spy.count(), 2 );

    tempFile->write("bar");
    tempFile->flush();
    QTest::qWait(7000);
    QCOMPARE( spy.count(), 3 );

    tempFile->close();
    QTest::qWait(7000);

    QCOMPARE( spy.count(), 3 );

    delete tempFile;
    QTest::qWait(7000);
    QCOMPARE( spy.count(), 4 );
    
}
QgsVectorLayer* QgsSentDataSourceBuilder::vectorLayerFromSentVDS( const QDomElement& sentVDSElem, QList<QTemporaryFile*>& filesToRemove, QList<QgsMapLayer*>& layersToRemove ) const
{
  if ( sentVDSElem.attribute( "format" ) == "GML" )
  {
    QTemporaryFile* tmpFile = new QTemporaryFile();
    if ( tmpFile->open() )
    {
      filesToRemove.push_back( tmpFile ); //make sure the temporary file gets deleted after each request
      QTextStream tempFileStream( tmpFile );
      sentVDSElem.save( tempFileStream, 4 );
      tmpFile->close();
    }
    else
    {
      return 0;
    }

    QgsVectorLayer* theVectorLayer = new QgsVectorLayer( tmpFile->fileName(), layerNameFromUri( tmpFile->fileName() ), "WFS" );
    if ( !theVectorLayer || !theVectorLayer->isValid() )
    {
      QgsMSDebugMsg( "invalid maplayer" );
      return 0;
    }
    QgsMSDebugMsg( "returning maplayer" );

    layersToRemove.push_back( theVectorLayer ); //make sure the layer gets deleted after each request

    if ( !theVectorLayer || !theVectorLayer->isValid() )
    {
      return 0;
    }
    return theVectorLayer;
  }
  return 0;
}
void AddCommandTest::testAddItem()
{
    QTemporaryFile tempFile;
    tempFile.setAutoRemove(false);
    tempFile.open();
    tempFile.write("Hello World!");

    const char *args[6] = {
        "akonadiclient",
        "add",
        "/res3",
        tempFile.fileName().toLocal8Bit().data(),
        "--base",
        QDir::tempPath().toLocal8Bit().data()
    };

    tempFile.close();
    KCmdLineArgs *parsedArgs = getParsedArgs(6, args);

    AddCommand *command = new AddCommand(this);

    int ret = command->init(parsedArgs);
    QCOMPARE(ret, 0);

    ret = runCommand(command);
    QCOMPARE(ret, 0);
}
    void downloadFile()
    {
        QTemporaryFile file;
        file.setAutoRemove(false);

        if (file.open()) {
            const QString filename = file.fileName();
            QInstaller::blockingWrite(&file, QByteArray(scLargeSize, '1'));
            file.close();

            DownloadFileTask fileTask(QLatin1String("file:///") + filename);
            QFutureWatcher<FileTaskResult> watcher;

            QSignalSpy started(&watcher, SIGNAL(started()));
            QSignalSpy finished(&watcher, SIGNAL(finished()));
            QSignalSpy progress(&watcher, SIGNAL(progressValueChanged(int)));

            watcher.setFuture(QtConcurrent::run(&DownloadFileTask::doTask, &fileTask));

            watcher.waitForFinished();
            QTest::qWait(10); // Spin the event loop to deliver queued signals.

            QCOMPARE(started.count(), 1);
            QCOMPARE(finished.count(), 1);

            FileTaskResult result = watcher.result();
            QCOMPARE(watcher.future().resultCount(), 1);

            QVERIFY(QFile(result.target()).exists());
            QCOMPARE(file.size(), QFile(result.target()).size());
            QCOMPARE(result.checkSum().toHex(), QByteArray("85304f87b8d90554a63c6f6d1e9cc974fbef8d32"));
        }
    }
        void ExiftoolImageWritingWorker::process() {
            Helpers::AsyncCoordinatorUnlocker unlocker(m_AsyncCoordinator);
            Q_UNUSED(unlocker);

            bool success = false;

            initWorker();

            QTemporaryFile jsonFile;
            if (jsonFile.open()) {
                LOG_INFO << "Serializing artworks to json" << jsonFile.fileName();
                QJsonArray objectsToSave;
                artworksToJsonArray(m_ItemsToWriteSnapshot, objectsToSave);
                QJsonDocument document(objectsToSave);
                jsonFile.write(document.toJson());
                jsonFile.flush();
                jsonFile.close();

                int numberOfItems = (int)m_ItemsToWriteSnapshot.size();

                QTemporaryFile argumentsFile;
                if (argumentsFile.open()) {
                    QStringList exiftoolArguments = createArgumentsList(jsonFile.fileName());

                    foreach (const QString &line, exiftoolArguments) {
                        argumentsFile.write(line.toUtf8());
#ifdef Q_OS_WIN
                        argumentsFile.write("\r\n");
#else
                        argumentsFile.write("\n");
#endif
                    }
Beispiel #8
0
/**
  * Create a grouping file to extract detectors in dets. Option List - one group - one detector,
  * Option Sum - one group which is a sum of the detectors
  * If fname is empty create a temporary file
  */
DetXMLFile::DetXMLFile(const QList<int>& dets, Option opt, const QString& fname)
{
    if (dets.empty())
    {
      m_fileName = "";
      return;
    }

    if (fname.isEmpty())
    {
      QTemporaryFile mapFile;
      mapFile.open();
      m_fileName = mapFile.fileName() + ".xml";
      mapFile.close();
      m_delete = true;
    }
    else
    {
      m_fileName = fname;
      m_delete = false;
    }

    switch(opt)
    {
    case Sum: makeSumFile(dets); break;
    case List: makeListFile(dets); break;
    }
}
    void testExportAsSinglePage()
    {
        // Same testcase as testVerticalScaling, for now
        fillModel(1, 40);
        Report report;
        report.setReportMode(Report::SpreadSheet);
        report.mainTable()->setAutoTableElement(AutoTableElement(&m_model));
        report.scaleTo(1, 2); // must cram 40 rows into 2 page vertically
        QFont font = QFont(QLatin1String(s_fontName));
        font.setPointSize(86); // huge :)
        report.setDefaultFont(font);
        //QCOMPARE(report.numberOfPages(), 2);

        //report.exportToFile( "testExportAsSinglePage.pdf" ); // for debugging

        QTemporaryFile tempFile;
        QVERIFY(tempFile.open());
        const QString filename = tempFile.fileName();
        tempFile.close();
        const QSize size(1000, 2000);
        bool ok = report.exportToImage( size, filename, "PNG" );
        QVERIFY(ok);
        QVERIFY(QFile::exists(filename));
        QPixmap pix;
        QVERIFY(pix.load(filename));
        QCOMPARE(pix.size(), size);

        QCOMPARE(report.mainTable()->pageRects()[0], QRect(0,0,1,40));
        QVERIFY(report.mainTable()->lastAutoFontScalingFactor() > 0.9999);
        // The only way to truly validate that it worked, though, is to open test-export.jpg and check...

        QFile::remove(filename);
    }
Result StoragePoolControlThread::getStoragePoolXMLDesc()
{
    Result result;
    QString name = task.object;
    bool read = false;
    char *Returns = NULL;
    virStoragePoolPtr storagePool = virStoragePoolLookupByName(
                *task.srcConnPtr, name.toUtf8().data());
    if ( storagePool!=NULL ) {
        Returns = (virStoragePoolGetXMLDesc(storagePool, VIR_STORAGE_XML_INACTIVE));
        if ( Returns==NULL )
            result.err = sendConnErrors();
        else read = true;
        virStoragePoolFree(storagePool);
    } else
        result.err = sendConnErrors();
    QTemporaryFile f;
    f.setAutoRemove(false);
    f.setFileTemplate(QString("%1%2XML_Desc-XXXXXX.xml")
                      .arg(QDir::tempPath()).arg(QDir::separator()));
    read = f.open();
    if (read) f.write(Returns);
    result.fileName.append(f.fileName());
    f.close();
    if ( Returns!=NULL ) free(Returns);
    result.msg.append(QString("'<b>%1</b>' StoragePool %2 XML'ed")
                  .arg(name).arg((read)?"":"don't"));
    result.name = name;
    result.result = read;
    return result;
}
Beispiel #11
0
ProcessPtr
Process::execute(QString const &command,
                 QStringList const &args,
                 bool useTempFile) {
  auto runner = [](QString const &commandToUse, QStringList const &argsToUse) {
    auto pr = std::make_shared<Process>( commandToUse, argsToUse );
    pr->run();
    return pr;
  };

  if (!useTempFile)
    return runner(command, args);

  QTemporaryFile optFile;

  if (!optFile.open())
    throw ProcessX{ to_utf8(QY("Error creating a temporary file (reason: %1).").arg(optFile.errorString())) };

  static const unsigned char utf8_bom[3] = {0xef, 0xbb, 0xbf};
  optFile.write(reinterpret_cast<char const *>(utf8_bom), 3);
  for (auto &arg : args)
    optFile.write(QString{"%1\n"}.arg(arg).toUtf8());
  optFile.close();

  QStringList argsToUse;
  argsToUse << QString{"@%1"}.arg(optFile.fileName());
  return runner(command, argsToUse);
}
bool DownloadHandler::saveToFile(const QByteArray &replyData, QString &filePath)
{
    QTemporaryFile *tmpfile = new QTemporaryFile;
    if (!tmpfile->open()) {
        delete tmpfile;
        return false;
    }

    tmpfile->setAutoRemove(false);
    filePath = tmpfile->fileName();
    qDebug("Temporary filename is: %s", qPrintable(filePath));
    if (m_reply->isOpen() || m_reply->open(QIODevice::ReadOnly)) {
        tmpfile->write(replyData);
        tmpfile->close();
        // XXX: tmpfile needs to be deleted on Windows before using the file
        // or it will complain that the file is used by another process.
        delete tmpfile;
        return true;
    }
    else {
        delete tmpfile;
        Utils::Fs::forceRemove(filePath);
    }

    return false;
}
Beispiel #13
0
bool QgsArchive::zip( const QString &filename )
{
  // create a temporary path
  QTemporaryFile tmpFile;
  tmpFile.open();
  tmpFile.close();

  // zip content
  if ( ! QgsZipUtils::zip( tmpFile.fileName(), mFiles ) )
  {
    QString err = QObject::tr( "Unable to zip content" );
    QgsMessageLog::logMessage( err, QStringLiteral( "QgsArchive" ) );
    return false;
  }

  // remove existing zip file
  if ( QFile::exists( filename ) )
    QFile::remove( filename );

  // save zip archive
  if ( ! tmpFile.rename( filename ) )
  {
    QString err = QObject::tr( "Unable to save zip file '%1'" ).arg( filename );
    QgsMessageLog::logMessage( err, QStringLiteral( "QgsArchive" ) );
    return false;
  }

  // keep the zip filename
  tmpFile.setAutoRemove( false );

  return true;
}
Beispiel #14
0
PageItem_LatexFrame::PageItem_LatexFrame(ScribusDoc *pa, double x, double y, double w, double h, double w2, QString fill, QString outline)
		: PageItem_ImageFrame(pa, x, y, w, h, w2, fill, outline)
{
	setUPixmap(Um::ILatexFrame);
	AnName = tr("Render") + QString::number(m_Doc->TotalItems);
	setUName(AnName);
	
	imgValid = false;
	m_usePreamble = true;
	err = 0;
	internalEditor = 0;
	killed = false;
	
	config = 0;
	if (PrefsManager::instance()->latexConfigs().count() > 0)
		setConfigFile(PrefsManager::instance()->latexConfigs()[0]);

	latex = new QProcess();
	connect(latex, SIGNAL(finished(int, QProcess::ExitStatus)),
		this, SLOT(updateImage(int, QProcess::ExitStatus)));
	connect(latex, SIGNAL(error(QProcess::ProcessError)),
		this, SLOT(latexError(QProcess::ProcessError)));
	latex->setProcessChannelMode(QProcess::MergedChannels);
	
	QTemporaryFile *tempfile = new QTemporaryFile(QDir::tempPath() + "/scribus_temp_render_XXXXXX");
	tempfile->open();
	tempFileBase = getLongPathName(tempfile->fileName());
	tempfile->setAutoRemove(false);
	tempfile->close();
	delete tempfile;
	Q_ASSERT(!tempFileBase.isEmpty());
	
	m_dpi = 0;
}
Beispiel #15
0
void ScrPainter::drawBitmap(const libwpg::WPGBitmap& bitmap, double hres, double vres)
{
	QImage image = QImage(bitmap.width(), bitmap.height(), QImage::Format_RGB32);
	for(int x = 0; x < bitmap.width(); x++)
	{
		for(int y = 0; y < bitmap.height(); y++)
		{
			libwpg::WPGColor color = bitmap.pixel(x, y);
			image.setPixel(x, y, qRgb(color.red, color.green, color.blue));
		}
	}
	double w = (bitmap.rect.x2 - bitmap.rect.x1) * 72.0;
	double h = (bitmap.rect.y2 - bitmap.rect.y1) * 72.0;
	int z = m_Doc->itemAdd(PageItem::ImageFrame, PageItem::Unspecified, bitmap.rect.x1 * 72 + baseX, bitmap.rect.y1 * 72 + baseY, w, h, 1, m_Doc->itemToolPrefs().imageFillColor, m_Doc->itemToolPrefs().imageStrokeColor, true);
	PageItem *ite = m_Doc->Items->at(z);
	QTemporaryFile *tempFile = new QTemporaryFile(QDir::tempPath() + "/scribus_temp_wpg_XXXXXX.png");
	tempFile->setAutoRemove(false);
	tempFile->open();
	QString fileName = getLongPathName(tempFile->fileName());
	tempFile->close();
	delete tempFile;
	ite->isTempFile = true;
	ite->isInlineImage = true;
	image.setDotsPerMeterX ((int) (hres / 0.0254));
	image.setDotsPerMeterY ((int) (vres / 0.0254));
	image.save(fileName, "PNG");
	m_Doc->loadPict(fileName, ite);
	ite->setImageScalingMode(false, false);
	ite->moveBy(m_Doc->currentPage()->xOffset(), m_Doc->currentPage()->yOffset());
	finishItem(ite);
//	qDebug() << "drawBitmap";
}
void QgsFetchedContent::taskCompleted()
{
  if ( !mFetchingTask || !mFetchingTask->reply() )
  {
    // if no reply, it has been canceled
    mStatus = QgsFetchedContent::Failed;
    mError = QNetworkReply::OperationCanceledError;
    mFilePath = QString();
  }
  else
  {
    QNetworkReply *reply = mFetchingTask->reply();
    if ( reply->error() == QNetworkReply::NoError )
    {
      QTemporaryFile *tf = new QTemporaryFile( QStringLiteral( "XXXXXX" ) );
      mFile = tf;
      tf->open();
      mFile->write( reply->readAll() );
      // Qt docs notes that on some system if fileName is not called before close, file might get deleted
      mFilePath = tf->fileName();
      tf->close();
      mStatus = QgsFetchedContent::Finished;
    }
    else
    {
      mStatus = QgsFetchedContent::Failed;
      mError = reply->error();
      mFilePath = QString();
    }
  }

  emit fetched();
}
Beispiel #17
0
QTemporaryFile* Downloader::downloadToTemporary(Job* job,
        const Downloader::Request &request)
{
    QTemporaryFile* file = new QTemporaryFile();
    Downloader::Request r2(request);
    r2.file = file;

    if (file->open()) {
        download(job, r2);
        file->close();

        if (job->isCancelled() || !job->getErrorMessage().isEmpty()) {
            delete file;
            file = 0;
        }
    } else {
        job->setErrorMessage(QString(QObject::tr("Error opening file: %1")).
                arg(file->fileName()));
        delete file;
        file = 0;
        job->complete();
    }

    return file;
}
void SqlTableModel::ouvrirCSV(QString commande)
{
    QTemporaryFile* temporaryFile = new QTemporaryFile(parent());
    if (temporaryFile->open()) {
        QxtCsvModel csv(this);
        csv.insertColumns(0, columnCount());
        csv.insertRows(0, rowCount());
        for (int column = 0; column < csv.columnCount(); column ++) {
            csv.setHeaderText(column, headerData(column, Qt::Horizontal).toString());
        }
        for (int row = 0; row < csv.rowCount(); row ++) {
            for (int column = 0; column < csv.columnCount(); column ++) {
                csv.setText(row, column, QSqlTableModel::data(index(row, column)).toString());
            }
        }
        csv.toCSV(temporaryFile->fileName(), true);
        temporaryFile->close();
        QProcess* process = new QProcess();
        process->start(commande, QStringList { temporaryFile->fileName() });
        connect(process, SIGNAL(finished(int)), temporaryFile, SLOT(deleteLater()));
    } else {
        qCritical() << temporaryFile->errorString();
    }

}
void TreeLog::onSaveLog()
{
	const QUrl url = QFileDialog::getSaveFileUrl();

	if (!url.isEmpty())
	{
		QTemporaryFile tempFile;

		if (!tempFile.open())
		{
			KMessageBox::error(this, xi18nc("@info", "Could not create temporary output file to save <filename>%1</filename>.", url.fileName()), i18nc("@title:window", "Error Saving Log File"));
			return;
		}

		QTextStream stream(&tempFile);

		for (qint32 idx = 0; idx < treeLog().topLevelItemCount(); idx++)
		{
			QTreeWidgetItem* item = treeLog().topLevelItem(idx);
			stream << item->text(1) << ": " << item->text(2) << "\n";
		}

		tempFile.close();

		KIO::CopyJob* job = KIO::move(QUrl::fromLocalFile(tempFile.fileName()), url, KIO::HideProgressInfo);
		job->exec();
		if ( job->error() )
			job->ui()->showErrorMessage();
	}
}
void SnapshotActionDialog::showSnapsotXMLDesc()
{
    if ( snapshotTree->currentIndex().isValid() ) {
        TreeItem *item = static_cast<TreeItem*>(
                snapshotTree->currentIndex().internalPointer());
        if ( NULL!=item ) {
            // flags: extra flags; not used yet, so callers should always pass 0
            virDomainSnapshotPtr snapShot =
                    virDomainSnapshotLookupByName(
                        domain, item->data(0).toByteArray().data(), 0);
            char *xmlDesc = virDomainSnapshotGetXMLDesc(snapShot, 0);
            if ( NULL!=xmlDesc ) {
                QTemporaryFile f;
                f.setAutoRemove(false);
                f.setFileTemplate(
                            QString("%1%2XML_Desc-XXXXXX.xml")
                            .arg(QDir::tempPath())
                            .arg(QDir::separator()));
                bool read = f.open();
                if (read) f.write(xmlDesc);
                QString xml = f.fileName();
                f.close();
                free(xmlDesc);
                QDesktopServices::openUrl(QUrl(xml));
            };
        };
    };
}
Beispiel #21
0
void TestQgsProject::testLayerFlags()
{
  QString dataDir( TEST_DATA_DIR ); //defined in CmakeLists.txt
  QString layerPath = dataDir + "/points.shp";
  QgsVectorLayer *layer1 = new QgsVectorLayer( layerPath, QStringLiteral( "points 1" ), QStringLiteral( "ogr" ) );
  QgsVectorLayer *layer2 = new QgsVectorLayer( layerPath, QStringLiteral( "points 2" ), QStringLiteral( "ogr" ) );

  QgsProject prj;
  prj.addMapLayer( layer1 );
  prj.addMapLayer( layer2 );

  layer2->setFlags( layer2->flags() & ~QgsMapLayer::Removable );

  QString layer2id = layer2->id();

  QTemporaryFile f;
  QVERIFY( f.open() );
  f.close();
  prj.setFileName( f.fileName() );
  prj.write();

  // test reading required layers back
  QgsProject prj2;
  prj2.setFileName( f.fileName() );
  QVERIFY( prj2.read() );
  QgsMapLayer *layer = prj.mapLayer( layer2id );
  QVERIFY( layer );
  QVERIFY( !layer->flags().testFlag( QgsMapLayer::Removable ) );
}
void QgsAuxiliaryStorage::initTmpFileName()
{
  QTemporaryFile tmpFile;
  tmpFile.open();
  tmpFile.close();
  mTmpFileName = tmpFile.fileName();
}
Beispiel #23
0
// Testing uint64_t countLines(std::istream& file)
void FileUtilsTest::FileUtilsTest2()
{
  QTemporaryFile tempFile;
  QVERIFY2( tempFile.open(), "Opens a temporary file" );
  QString tempFileName = tempFile.fileName();
  tempFile.close();
  std::fstream file;
  file.open(tempFileName.toUtf8().constData(),std::fstream::binary | std::fstream::in | std::fstream::out| std::fstream::trunc);
  
  QVERIFY2( file.good(), "Opens a temporary file" );

  uint64_t nbLines = countLines(file);
  QVERIFY2( nbLines == 0, QString(QLatin1String("Initial temp file should be empty but has %1 lines.")).arg(nbLines).toUtf8().constData() );
  
  file << "auie" << std::flush; 
  file.seekg(0, std::ios::beg);
  QVERIFY(file.good());
  nbLines = countLines(file);
  QVERIFY2( nbLines == 1, QString(QLatin1String("File is not empty but has no \\n: result should be 1 but is %1")).arg(nbLines).toUtf8().constData() );
  file.seekg(0, std::ios::end);
  file << '\n' << std::flush;
  file.seekg(0, std::ios::beg);
  nbLines = countLines(file);
  QVERIFY2( nbLines == 1, QString(QLatin1String("file has now one \\n and nothing after it: should still count one line but get %1")).arg(nbLines).toUtf8().constData() );
  file.seekg(0, std::ios::end);
  file << "bepo" << std::flush;
  file.seekg(0, std::ios::beg);
  nbLines = countLines(file);
  QVERIFY2( nbLines == 2, QString(QLatin1String("file has now two \\n and chars on second line: should count two lines but get %1")).arg(nbLines).toUtf8().constData() );
  file.close();

}
Beispiel #24
0
void Oven::cook(QString inputContents, QString scriptContents) {
  QTemporaryFile file;
  QProcess process;
  
  if (file.open()) {
    QString filename = file.fileName();
    
    file.write(scriptContents.toUtf8());
    if (!file.error()) {
      file.close();
      
      process.setProcessChannelMode(QProcess::ForwardedChannels);
      process.start("bash", QStringList() << filename);
      
      QTextStream inputStream(&process);
      inputStream << inputContents;
      inputStream.flush();
      process.closeWriteChannel();
      
      if (process.waitForStarted() && process.waitForFinished()) {
        // success!
        return;
      }
    }
  }
  
  if (file.error() != QTemporaryFile::NoError) {
    emit error(file.errorString());
  } else {
    emit error(process.errorString());
  }
  
  // error.
  return;
}
Beispiel #25
0
void KDocumentTextBuffer::checkConsistency()
{
    QString bufferContents = codec()->toUnicode( slice(0, length())->text() );
    QString documentContents = kDocument()->text();
    if ( bufferContents != documentContents ) {
        KUrl url = kDocument()->url();
        kDocument()->setModified(false);
        kDocument()->setReadWrite(false);
        m_aboutToClose = true;
        QTemporaryFile f;
        f.setAutoRemove(false);
        f.open();
        f.close();
        kDocument()->saveAs(f.fileName());
        KDialog* dialog = new KDialog;
        dialog->setButtons(KDialog::Ok | KDialog::Cancel);
        QLabel* label = new QLabel(i18n("Sorry, an internal error occurred in the text synchronization component.<br>"
                                        "You can try to reload the document or disconnect."));
        label->setWordWrap(true);
        dialog->setMainWidget(label);
        dialog->button(KDialog::Ok)->setText(i18n("Reload document"));
        dialog->button(KDialog::Cancel)->setText(i18n("Disconnect"));
        DocumentReopenHelper* helper = new DocumentReopenHelper(url, kDocument());
        connect(dialog, SIGNAL(accepted()), helper, SLOT(reopen()));
        // We must not use exec() here, since that will create a nested event loop,
        // which might handle incoming network events. This can easily get very messy.
        dialog->show();
    }
}
Beispiel #26
0
static SendCoinsRecipient handleRequest(PaymentServer* server, std::vector<unsigned char>& data)
{
    RecipientCatcher sigCatcher;
    QObject::connect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),
        &sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));

    // Write data to a temp file:
    QTemporaryFile f;
    f.open();
    f.write((const char*)data.data(), data.size());
    f.close();

    // Create a QObject, install event filter from PaymentServer
    // and send a file open event to the object
    QObject object;
    object.installEventFilter(server);
    QFileOpenEvent event(f.fileName());
    // If sending the event fails, this will cause sigCatcher to be empty,
    // which will lead to a test failure anyway.
    QCoreApplication::sendEvent(&object, &event);

    QObject::disconnect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),
        &sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));

    // Return results from sigCatcher
    return sigCatcher.recipient;
}
Beispiel #27
0
void TestCompilerProvider::testStorageBackwardsCompatible()
{
    SettingsManager settings;
    QTemporaryFile file;
    QVERIFY(file.open());
    QTextStream stream(&file);
    stream << "[Buildset]\n" <<
      "BuildItems=@Variant(\\x00\\x00\\x00\\t\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x0b\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x1a\\x00S\\x00i\\x00m\\x00p\\x00l\\x00e\\x00P\\x00r\\x00o\\x00j\\x00e\\x00c\\x00t)\n" <<
      "[CustomBuildSystem]\n" << "CurrentConfiguration=BuildConfig0\n" <<
      "[CustomDefinesAndIncludes][ProjectPath0]\n" <<
      "Defines=\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x0c\\x00_\\x00D\\x00E\\x00B\\x00U\\x00G\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00V\\x00A\\x00R\\x00I\\x00A\\x00B\\x00L\\x00E\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x00\\n\\x00V\\x00A\\x00L\\x00U\\x00E\n" <<
      "Includes=\\x00\\x00\\x00\\x01\\x00\\x00\\x00$\\x00/\\x00u\\x00s\\x00r\\x00/\\x00i\\x00n\\x00c\\x00l\\x00u\\x00d\\x00e\\x00/\\x00m\\x00y\\x00d\\x00i\\x00r\n" <<
      "Path=/\n" <<
      "[CustomDefinesAndIncludes][ProjectPath0][Compiler]\nName=GCC\nPath=gcc\nType=GCC\n";
    file.close();
    KConfig config(file.fileName());
    auto entries = settings.readPaths(&config);
    QCOMPARE(entries.size(), 1);
    auto entry = entries.first();
    Defines defines;
    defines["VARIABLE"] = "VALUE";
    defines["_DEBUG"] = QString();
    QCOMPARE(entry.defines, defines);
    QStringList includes = QStringList() << "/usr/include/mydir";
    QCOMPARE(entry.includes, includes);
    QCOMPARE(entry.path, QString("/"));
    QVERIFY(entry.compiler);

    testCompilerEntry(settings, &config);
    testAddingEntry(settings, &config);
}
Beispiel #28
0
void GitEditorWidget::applyDiffChunk(const DiffChunk& chunk, bool revert)
{
    QTemporaryFile patchFile;
    if (!patchFile.open())
        return;

    const QString baseDir = workingDirectory();
    patchFile.write(chunk.header);
    patchFile.write(chunk.chunk);
    patchFile.close();

    QStringList args = QStringList() << QLatin1String("--cached");
    if (revert)
        args << QLatin1String("--reverse");
    QString errorMessage;
    if (GitPlugin::client()->synchronousApplyPatch(baseDir, patchFile.fileName(), &errorMessage, args)) {
        if (errorMessage.isEmpty())
            VcsOutputWindow::append(tr("Chunk successfully staged"));
        else
            VcsOutputWindow::append(errorMessage);
        if (revert)
            emit diffChunkReverted(chunk);
        else
            emit diffChunkApplied(chunk);
    } else {
        VcsOutputWindow::appendError(errorMessage);
    }
}
Beispiel #29
0
PHISRequest::~PHISRequest()
{
    QTemporaryFile *tmpFile;
    foreach ( tmpFile, _tmpFiles ) {
        qDebug( "Closing %s", qPrintable( tmpFile->fileName() ) );
        tmpFile->close();
        delete tmpFile;
    }
Beispiel #30
0
static QString buildTempFile()
{
    QTemporaryFile tempFile;
    tempFile.setAutoRemove(false);
    tempFile.open();
    QString a = tempFile.fileName();
    tempFile.close();
    return a;
}